網頁

2018年11月8日 星期四

tail corrections

在rc到無限遠的空間內散佈著i和j粒子,所以只是在算i和j粒子密度分佈。如果把這裡的密度思考成質量就會發現右項單位和utail單位不合。從講義上也可以確認rho的定義是"average number density"。

參考
http://www.iitg.ac.in/physics/fac/padmakumarp/Courses/PH442/PH442_Slides.pdf

根據Cameron F. Abrams的code會發現少一個N
但其實只是自己眼殘

參考
https://github.com/cameronabrams/codes/blob/master/src/mclj_npt.c

unit converter

Conventional units:
  • distance = Angstroms
  • time = femtoseconds
  • mass = grams/mole
  • temperature = degrees K
  • pressure = atmospheres
  • energy = Kcal/mole
  • velocity = Angstroms/femtosecond
  • force = grams/mole * Angstroms/femtosecond^2
  • charge = +/- 1.0 is proton/electron
LJ reduced units:
  • distance = sigmas
  • time = reduced LJ tau
  • mass = ratio to unitless 1.0
  • temperature = reduced LJ temp
  • pressure = reduced LJ pressure
  • energy = epsilons
  • velocity = sigmas/tau
  • force = reduced LJ force (sigmas/tau^2)
  • charge = ratio to unitless 1.0
This listing of variables assumes conventional units; to convert to LJ reduced units, simply substitute the appropriate term from the list above. E.g. x is in sigmas in LJ units. Per-mole in any of the units simply means for 6.023 x 10^23 atoms.


Meaning        Variable        Units

positions      x               Angstroms
velocities     v               Angstroms / click (see below)
forces         f               Kcal / (mole - Angstrom)                
masses         mass            gram / mole
charges        q               electron units (-1 for an electron)
                                 (1 e.u. = 1.602 x 10^-19 coul)

time            ---             clicks (1 click = 48.88821 fmsec)
timestep        dt              clicks
input timestep  dt_in           fmsec
time convert    dtfactor        48.88821 fmsec / click

temperature     t_current       degrees K
                t_start
                t_stop
input damping   t_freq_in       inverse fmsec
internal temp   t_freq          inverse clicks
  damping

dielec const    dielectric      1.0 (unitless)
Boltmann const  boltz           0.001987191 Kcal / (mole - degree K)

virial          virial[xyz]     Kcal/mole = r dot F
pressure factor pfactor         68589.796 (convert internal to atmospheres)
internal        p_current       Kcal / (mole - Angs^3)
  pressure      p_start
                p_stop
input press     p_start_in      atmospheres
                p_stop_in
output press    log file        atmospheres
input damping   p_freq_in       inverse time
internal press  p_freq          inverse clicks
  damping

pot eng         e_potential     Kcal/mole
kin eng         e_kinetic       Kcal/mole
eng convert     efactor         332.0636 (Kcal - Ang) / (q^2 - mole)
                                (convert Coulomb eng to Kcal/mole)

LJ coeffs       lja,ljb         Kcal-Angs^(6,12)/mole

bond            various         see force_fields file
  parameters    2,3,4-body
                terms

參考
https://lammps.sandia.gov/doc/99/units.html

https://www.unitconverters.net/

Time
1 fs = 10^-15 s
1 ps = 10^-12 s

Pressure
1 pascal (Pa) = 1 newton/square meter (N/m2)
1 bar = 0.98692 atmosphere (atm) = 10^5 pascals (Pa)
1 atm = 101325 pascals (Pa)
1 pascals (Pa) = 0.0000098692 atm
1 GPa =10^9 Pa
1 MPa =10^6 Pa

Energy
1 joule (J) = 1 newton meter (Nm)
1 calorie (cal) = 4.184 joule (J)

Gas constant
pV = nRT
R is related to the Boltzmann constant, k, by

R = k NA
where k = 1.3806 x 10^-23 J K^-1, and NA = 6.022 x 10^23 mol^-1

R with different units 
8.31451 J K^-1 mol^-1 
8.20578 x 10^-2 L atm K^-1 mol^-1 
8.31451 x 10^-2 L bar K^-1 mol^-1 
8.31451 Pa m^3 K^-1 mol^-1 
1.98722 cal K^-1 mol^-1

1 Pa = 10^-3/4.184 kcal/m^3 = 10^-33/4.184 kcal/A^3 = 6.02*10^23/4.184/10^33 kcal/mol/A^3
1 GPa = 10^6 Pa = 6.02*10^29/4.184/10^33 kcal/mol/A^3 = 10^-4*6.02/4.184 kcal/mol/A^3

1 kcal/mol/A^3 = 4184*10^30/6/10^23 j/m^3 (Pa) * 0.0000098692 (atm/Pa) = 412927.328 atm

timestep (fs轉無因次)
t* = t * (epsilon / m / sigma^2)^1/2
t* = t([fs]) * [ sqrt( Kcal/mol * mol/g * Angstrom^-2 ) ] (1 Kcal = 4184J)
    = t([fs]) * [ sqrt( 4184*Kg*meter^2/(second^2) * 1/g *  1/(10^-20 meter^2) ) ] (1 Angstrom = 10^-10 meter)
    = t([fs]) * [ sqrt( 4184*1000 g*meter/(10^30 fs^2) * 1/g *  1/(10^-20 meter^2) ) ] (1 second = 10^15 femtosecond)
    = t * 0.020455

pressure (atm轉無因次)
P* = P([atm]) sigma^3 / epsilon (1 atm = 101325 Pa = 101325 Kg/m/s^2)
     = P([101325 Kg/meter/s^2]) * [ Angstrom^-3 * mol/Kcal ] (1 Kcal = 4184J)
     = P([101325 Kg/meter/s^2]) * [10^-30 meter * mol*s^2/4184/Kg/meter] (1 mol = 6*10^23)
     = P([101325 Kg/meter/s^2]) * [10^-30 meter * 6*10^23*s^2/4184/Kg/meter]
     = P * 0.00001453

temperature (K轉無因次)
T* = T Kb / epsilon
     = T([K]) * [ 1.38064852*10^-23 J/K * mol/Kcal ] (1 mol = 6*10^23)
     = T([K]) * [ 1.38064852*10^-23 J/K * 6*10^23/4184 J ]
     = T * 0.0019798975

2018年11月4日 星期日

GNU Scientific Library (gsl) on Mac

GNU Scientific Library是一種數值計算的C語言函式庫
https://www.gnu.org/software/gsl/doc/html/index.html
由於分子模擬的平衡速度為Maxwell-Boltzmann distribution,為了讓初始結構在平衡過程中不受到local minimum影響,可以利用gsl_ran_exponential設定系統初速度。

2018年11月3日 星期六

pybind11 for Mac

1. 三種方式安裝pybind11
$ brew install pybind11
$ pip3 install pybind11
$ conda install -c conda-forge pybind11

2. 寫example.cpp




參考
https://pybind11.readthedocs.io/en/stable/basics.html#header-and-namespace-conventions

3. 執行Mac的編譯指令產生example.cpython-36m-darwin.so
$ g++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`

-undefined dynamic_lookup: Python gets linked dynamically without having all symbols resolved at link timepython3 -m pybind11 --includes: import pybind11 module
python3-config: output build options for python C/C++ extension
--extension-suffix: print the extension suffix used for binary extensions (產生example.cpython-36m-darwin.so)

參考
https://pybind11.readthedocs.io/en/stable/compiling.html#building-manually
https://osmocom.org/issues/1678
https://blog.csdn.net/IAlexanderI/article/details/81003225
https://helpmanual.io/man1/python3-config/

4. 利用python call c++ function

















$ python3 example.py


2018年10月18日 星期四

ubuntu 16.04 install Pulse Secure

1. 下載
$ wget http://ccnet.ntu.edu.tw/vpn/Download/ps-pulse-linux-9.0r2.1-b819-ubuntu-debian-64-bit-installer.deb

2. 安裝
$ sudo dpkg --install ps-pulse-linux-9.0r2.1-b819-ubuntu-debian-64-bit-installer.deb

3. 安裝missing dependency packages
$ sudo apt-get install libc6-i386 
$ sudo apt-get install lib32z1

4. 啟動Pulse client
$ /usr/local/pulse/PulseClient_x86_64.sh -h sslvpn2.ntu.edu.tw -u <username> -p <password> -U https://sslvpn2.ntu.edu.tw/  -r "NTU EMail Account"

5. 建立VPN連線
$ /usr/local/pulse/pulsesvc -h sslvpn2.ntu.edu.tw -u <username> -p <password> -r "NTU EMail Account" -U https://sslvpn2.ntu.edu.tw/

6. 確認連線狀態

ubuntu 16.04 不能用jupyter notebook

The Jupyter HTML Notebook.

這將啟動一個基於tornado的HTML筆記本服務器,它提供一個html5/
javascript筆記本客戶端。

2018年10月17日 星期三

Install CUDA with apt


ubuntu 16.04 install tensorflow

$ sudo apt update
$ sudo apt install python3-dev python3-pip
$ sudo pip3 install -U virtualenv
$ virtualenv --system-site-packages -p python3 ./venv
$ source ./venv/bin/activate
$ pip install --upgrade pip
$ pip list
$ pip install --upgrade tensorflow
$ python -c "import tensorflow as tf; print(tf.__version__)"
有顯示版本代表安裝完成
$ pip install tensorflow-gpu (要先安裝cuDNN,驗證版本cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2)
$ deactivate

TensorFlow from source in Ubuntu 18
https://medium.com/@isaaclascasas/tensorflow-from-source-in-ubuntu-18-4b5dcca910b9?fbclid=IwAR1-E-n7KStl8gPjriDEe4QZtXKZSJfQUK86q6DZRQLhp3Vj9_0qbwYA0MI

如果有顯示Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA,在跑CPU版本的tensorflow時要加入下面兩行API

$ import os
$ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

由於tensorflow默認分佈是在沒有CPU擴展的情況下構建的,例如SSE4.1,SSE4.2,AVX,AVX2,FMA等。默認版本(來自pip install tensorflow的版本)旨在與儘可能多的CPU兼容。若是用GPU版本的話,就不必在乎這個問題發生。

如果有顯示ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory
$ ~/~/.zshrc
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64/
$ source ~/.zshrc

如果出現Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'enable_eager_execution'
$ pip install tf-nightly  
$ pip install tf-nightly-gpu

ubuntu 16.04 install cuDNN

1. https://developer.nvidia.com/cudnn 下載

cuDNN v7.3.1 Library for Linux
cuDNN v7.3.1 Runtime Library for Ubuntu16.04 (Deb)
cuDNN v7.3.1 Developer Library for Ubuntu16.04 (Deb)
cuDNN v7.3.1 Code Samples and User Guide for Ubuntu16.04 (Deb)


$ tar -xzvf cudnn-9.0-linux-x64-v7.tgz
$ sudo cp cuda/include/cudnn.h /usr/local/cuda/include
(sudo cp cuda/targets/ppc64le-linux/include/cudnn.h /usr/local/cuda/include)
$ sudo cp cuda/lib64/libcudnn* /usr/local/cuda/lib64
(sudo cp cuda/targets/ppc64le-linux/lib/libcudnn* /usr/local/cuda/lib64)
$ sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*
$ sudo dpkg -i libcudnn7_7.3.1.20-1+cuda10.0_amd64.deb
$ sudo dpkg -i libcudnn7-dev_7.3.1.20-1+cuda10.0_amd64.deb
$ sudo dpkg -i libcudnn7-doc_7.3.1.20-1+cuda10.0_amd64.deb
$ cp -r /usr/src/cudnn_samples_v7/ $HOME
$ cd  $HOME/cudnn_samples_v7/mnistCUDNN
$ make clean && make
$ ./mnistCUDNN
有出現Test passed!代表完成

ubuntu 16.04 install CUDA


ubuntu install for keras

在安裝keras之前,要先安裝其他套件:
1. 安裝numpy和scipy,並確保安裝了基本的線性代數函式庫(BLAS),以便模型在CPU上快速運行。
2. 安裝兩個額外的包,在使用Keras時非常方便:HDF5(用於保存大型神經網絡文件)和Graphviz(用於可視化神經網絡架構)。
3. 通過安裝CUDA驅動程序和cuDNN,確保GPU能夠運行深度學習代碼。
4. 安裝Keras的後端:TensorFlow、CNTK或Theano。


2018年9月14日 星期五

ubuntu lammps install easily

1. 安裝前所需套件
$ sudo apt update
$ sudo apt-get install gcc
$ sudo apt-get install g++
$ sudo apt-get install gfortran
$ sudo apt-get install make
$ sudo apt-get install mpi-default-*
$ sudo apt-get install libfftw3-dev
$ sudo apt-get install libjpeg-dev
$ sudo apt-get install libpng16-dev
$ sudo apt-get install libpng-dev

2. 下載Lammps
https://lammps.sandia.gov/download.html
下載到家目錄

3. 安裝meam
$ cd /home/chiustin/lammps-12Dec18/lib/meam
$ sudo make -f Makefile.gfortran clean
$ sudo make -f Makefile.gfortran

參考
https://github.com/lammps/lammps/tree/master/lib/meam

4. 安裝reax
$ cd /home/chiustin/lammps-12Dec18/lib/reax
$ sudo make -f Makefile.gfortran

參考
https://lammps.sandia.gov/threads/msg66213.html
https://lammps.sandia.gov/threads/msg62170.html

5. 安裝voronoi
$ cd /home/chiustin/lammps-12Dec18/lib/voronoi
$ wget http://math.lbl.gov/voro++/download/dir/voro++-0.4.6.tar.gz
$ tar -xvf voro++-0.4.6.tar.gz
$ cd voro++-0.4.6
$ make clean
$ sudo make
$ sudo make install
$ cd /home/chiustin/lammps-12Dec18/lib/voronoi
$ gedit Makefile.lammps
$ voronoi_SYSINC = -I/usr/local/include/voro++
$ voronoi_SYSLIB = -lvoro++
$ voronoi_SYSPATH = -L/usr/local/lib

參考
https://github.com/lammps/lammps/tree/master/lib/voronoi

6. 安裝fftw
$ cd
http://www.fftw.org/download.html or
$ wget http://www.fftw.org/fftw-3.3.8.tar.gz
$ tar -xvf fftw-3.3.8.tar.gz
$ cd fftw-3.3.8/
$ sudo ./configure --prefix=/usr/local --enable-float
(for Mac ./configure --prefix=/usr/local --enable-float --enable-threads
參考 http://www.fftw.org/install/mac.html)
$ sudo make -j4
$ sudo make install
$ cd /home/chiustin/lammps-12Dec18/src/MAKE/OPTIONS/
$ vi Makefile.fftw
確認
FFT_INC = -DFFT_FFTW3 -I/usr/local/include
FFT_PATH = -L/usr/local/lib
FFT_LIB = -lfftw3

參考
https://zhuanlan.zhihu.com/p/36457551

7. 安裝mpich
$ cd
$ wget http://www.mpich.org/static/downloads/3.3/mpich-3.3.tar.gz
$ tar -xvf mpich-3.3.tar.gz
$ cd mpich-3.3/
$ sudo ./configure --prefix=/usr/local
$ sudo make -j4
$ sudo make install
$ cd /home/chiustin/lammps-12Dec18/src/MAKE/OPTIONS
$ vi Makefile.g++_mpich_link
確認
MPI_INC = -DMPICH_SKIP_MPICXX -DOMPI_SKIP_MPICXX=1 -I/usr/local/include
MPI_PATH = -L/usr/local/lib
MPI_LIB = -lmpi -lmpl -lpthread

參考
https://zhuanlan.zhihu.com/p/36457551

8. 選擇套件
$ cd /home/chiustin/lammps-12Dec18/src
$ make yes-meam
$ make yes-voronoi
$ make yes-class2
$ make yes-manybody
$ make yes-molecule
$ make yes-dipole
$ make yes-USER-DRUDE
$ make yes-RIGID
$ make yes-reax
$ make yes-user-reaxc

$ make package-status 可以看哪些package沒安裝

9. 編譯binary
$ cd /home/chiustin/lammps-12Dec18/src/MAKE/MACHINES
$ cp Makefile.ubuntu ../
$ cd /home/chiustin/lammps-12Dec18/src
$ sudo make ubuntu
$ sudo make mpi -j4
$ sudo make serial -j4

for Mac
$ cd /home/chiustin/lammps-12Dec18/src/MAKE/MACHINES
$ cp Makefile.mac ../
$ cp Makefile.mac_mpi ../
$ vi Makefile. mac_mpi

CC =        /usr/local/bin/mpic++
CCFLAGS =   -O3
SHFLAGS =   -fPIC
DEPFLAGS =  -M

LINK =      /usr/local/bin/mpic++
LINKFLAGS = -O3
LIB =
SIZE =      size

$ cd /home/chiustin/lammps-12Dec18/src
$ sudo make mac
$ sudo make mac_mpi

10. 環境變數
$ sudo cp lmp_ubuntu /usr/local/bin
$ sudo cp lmp_mpi /usr/local/bin
$ sudo cp lmp_serial /usr/local/bin
$ sudo vim /etc/profile
$ export PATH=/usr/local/bin:$PATH
$ source /etc/profile
$ which lmp_ubuntu
$ which lmp_mpi
$ which lmp_serial

10. 測試
$ cd /home/chiustin/lammps-12Dec18/examples/shear
$ mpirun -np 3 lmp_ubuntu < in.shear
$ lmp_ubuntu < in.shear
$ mpirun -np 3 lmp_mpi < in.shear
$ lmp_serial < in.shear

參考
http://i.youku.com/simuly#opennewwindow

ubuntu install


2018年8月1日 星期三

zsh: command not found: jupyter

問題:
安裝完Anaconda要使用jupyter notebook時
iterm2終端機輸入jupyter notebook出現
zsh: command not found: jupyter

解決:
vi ~/.zshrc
加入
source ~/.bash_profile

2017年11月2日 星期四

20171102 資結程設

hw3
DBTable::sort(constant struct)
::sort()(_table.begin(), _table.end(),s);

function object
DBSort::operator() (const DBRow& r1, const DBRow& r2)

for (n=0;  n=_sortOder.size(); n++) {
    size_t c = _sortOder[I]
......
}

struct DBSort
{

}

2017年10月31日 星期二

20171031 GPU

1. Atomics
處理變數在每個thread進行read-modify-write的操作時會有dependency,例如x++。
利用shared memory處理atomicAdd可以減少對global memory重複讀取,增加效能。

2. Stream
cudaHostAlloc()和malloc()不一樣在於malloc()是page host memory,而cudaHostAlloc()是 page-locked (有時稱之為pinned memory)。在run time時,page-locked會讓buffer不會被swapped out到硬碟,會加速記憶體的讀取。最重要是如果今天有兩個stream。假設今天stream0進行kernel運算時,stream1利用cudaHostAlloc()可以讀取非現在kernel運算的陣列不會影響kernel的運算,否則用malloc()可能在kernel會無法使用原本的陣列來運算。

















這種方式會造成copy engine跟kernel engine會有較大空閒時間。














這種方式雖然也會造成copy engine跟kernel engine有空閒時間,但kernel engine比上一種快一格進行,而且stream0和stream1的kernel之間也縮短兩格。












這種方式是最佳的。

所以結論是利用breath-first或round-robin的assignment工作方式到stream是最好的。

2017年10月29日 星期日

20171019

static在C++的種類有五種使用方式

1. Static variable in a file
2. Static variable in a function
3. Static function
4. Static data member of a class 5. Static member function of a class
static在三種scope下有不同功能
1. global
global variable宣告static會讓global scope變file scope,意思是說當兩份cpp檔如果都有相同變數名稱時,他們各自屬於他們file內的變數,彼此之間沒有關係。
2. function
在function裡,local variable宣告static時,不會因為function被回收讓變數也被回收。
3. class
static data member
(i)不管產生多少個相同class的物件,static的members只會複製一份,而且共享給每一個物件。
(ii)不必在class scope內初始化。利用::在class外部初始化,如果沒有,系統會自動初始化為0。
static member function
只能用::access,即使沒有產生物件。
只能access “static” data member,enum, or nested types。
不能access到this pointer

2017年10月26日 星期四

20171026 資結程設

begin是管理記憶體空間的開頭
end是管理記憶體空間的尾
new size_t的倍數
假設A是200 bits
P1=new A
P2=new A[5]
P3=new A[5]
delete []P2

MemMgr的_activeBlock
new一個P2假設產生208 bits
_ptr指向8個bits前面
P2指向200前面

recycle list(RL)
recycle會先找記憶體容量相同的
first要先用型態A的pointer P2強迫轉型成size_t 把前面8 bits減掉還要把值設成0
first指向8個bits後面的位置
delete []P2
delete []P3
前面8 bits用P2指
first=P3指向下一個後面要刪除的200 bits

假設delete []P5 (261 bits)
空間只有255 >end
再要一個_activeBlock

vector<MemTestObj*> _objList;
vector<MemTestObj*> _arrList;deleteObj

delete _objList[ix];
...

_objList[i]? 'o' : 'x' (如果是NULL會印o)

#define toSizeT(t)
假設38 bits會把size變40 (8的倍數)

2017年10月25日 星期三

20171025 計結

EDA playground
https://www.edaplayground.com/

t_Full_Adder.v (testbench)放左邊
Full_Adder.v (module)放右邊
檔案用貼上別upload

Tools & Simulators
Icarus Verilog

Full_Adder FA_1(.a(a), .b(b), .ci(ci), .sum(sum), .cout(cout));
input reg 
output wire

$dumpfile("Full_Adder.vcd");
$dumpvars;
輸出file可以看waveform

initial #1000 $stop;
經過一千個單位時間會停下來

verilog-ex
// Code your design here
timescale 1 ns/ 1 ns

module alu (src_a, src_b, c, data_out);

input [7:0] src_a, src_b;
input [2:0] c;
output [7:0] data_out;

/* implement here */
reg [32:0] temp;
assign data_out = temp[32];

initial begin
if(c == 1) begin
  temp = src_a + src_b;
end
else if(c == 2) begin
  temp = src_a - src_b;
end
else if(c == 3) begin
  temp = src_a & src_b;
end
else if(c == 4) begin
  temp = src_a | src_b;
end
else if(c == 5) begin
  temp = src_a ^ src_b;
end

end


endmodule

20171018 計結

sign extension

rising edge or falling edge

clock cycle

MUX

數位系統

資結程設hw2

1. using C++ implements the terminal state without echo input, like login when asking for the password

參考資料
https://www.svbug.com/documentation/comp.unix.programmer-FAQ/faq_4.html

1. CmdParser cmd
    初始化_readBufPtr(_readBuf), _readBufEnd(_readBuf),_historyIdx(0), _tempCmdStored(false)
2. cmd.readCmd()
    呼叫另一個成員函式readCmdInt(cin) {
        (1) 呼叫另一個成員函式resetBufAndPrintPrompt() {
            初始化_readBufPtr = _readBufEnd = _readBuf;*_readBufPtr = 0;
            呼叫另一個成員函式printPrompt()印出cmd> (初始化和cout可以寫在.h)
        }
        (2) while (1) {
            (a) ParseChar pch = getChar(istr)
                (i) getChar(istream& istr)是一個global function回傳型態是enum
                (ii) 呼叫mygetc(istr)是一個global function回傳型態是ch
                () char mygetc(istream& istr)
                (ii) enum回傳LINE_BEGIN_KEY等字串
            (b) pch == INPUT_END_KEY 離開
            (c) switch (pch)
        }
    }

20171024 GPU

1. Texture memory
    texture memory被cash on chip,比off-chip DRAM更可以減少使用記憶體需求,提供更有效bandwidth。在二維晶格,因為CPU處理周遭晶格時在記憶體無法連續情況下無法被cash together。因此,texture memory非常適合處理"between a cell and neighbors"這種需要讀取周圍記憶體位置的情況,也比前一張使用shared memory的方式來的好。
    以課本例子因為有固定熱流點dev_constSrc,所以在anim_gpu function裡先把常數的部分先copy_const_kernel寫進dev_insrc,然後再呼叫blend_kernel把dev_inSrc覆寫後算出dev_outSrc。利用一維texture<float>或二維texture<float,2>的不同處理方式下,差別在二維會自動處理邊界問題,但兩者效能其實是差不多的。

2. Graphics interoperability
    和之前章節差別在這邊使用多張顯卡讓CUDA結合OpenGL和GLUT calls,不必像前幾章利用CPU執行CPUBitmap,減少使用CPU系統。特別的是,把圖片長寬跟datablock寫到GPUAnimBitmap function引數,會透過initialize讓cudaCHooseDevice自動搜尋適合這張圖的顯卡。

2017年10月18日 星期三

2017年10月10日 星期二

前置處理器 指示詞

Preprocessor directives
前置處理器 指示詞(Preprocessor directives)用#(hash sign)來表示。在編譯開始前,前置處理器會先檢視指示詞。因為前置處理器 指示詞沒有用;(semicolon)做結尾,所以前置處理器只能解析一行code為基準,若超過一行要在末行加上\(backslash)。

macro definitions (#define, #undef)
#define identifier replacement
當前置處理器看到這個指示詞,會將code裡任一個identifier用replacement取代,可以是expression, statement,block或者simply anything。

ex
1
2
3
#define TABLE_SIZE 100
int table1[TABLE_SIZE];
int table2[TABLE_SIZE];

 
#define getmax(a,b) a>b?a:b

1
2
3
4
5
#define TABLE_SIZE 100
int table1[TABLE_SIZE];
#undef TABLE_SIZE
#define TABLE_SIZE 200
int table2[TABLE_SIZE];

function macro definitions兩種特別運算元#和##在replacement。#後面的參數名字會被字串字母的引數取代 (就像是被雙引號框住)。
1
2
#define str(x) #x
cout << str(test);

##連接兩個引數使他們之間沒有空白
1
2
#define glue(a,b) a ## b
glue(c,out) << "test";
參考文獻

2017年10月9日 星期一

linux centos終端機顏色

修改ls顯示資料夾名稱顏色
cp /etc/DIR_COLORS ~/.dir_colors
vim ~/.dir_colors

第59行:DIR 01;34(01:粗體,34:藍色)
修改為:DIR 01;33(01:粗體,33:黃色)

參考資料

改txt亮顯、行號
vi ~/.vimrc

hi Comment ctermfg =blue
set nu

2017年10月6日 星期五

20171005資結程設

map是一種associated container。insert pair(key跟value)後可以利用find輸入key搜尋到相對應value。搜尋法為紅黑樹概念,complexity為log(n)。此外,也可以將key和value進行刪除或清空。
因為map的key不能重複,所以可以使用multimap來允許duplicate key的操作。

參考連結:
http://www.yolinux.com/TUTORIALS/CppStlMultiMap.html

strtok()是將一連串string藉由設定delimiters來分割出個別字串

example
/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

使用方法:
在程式裡面會有兩次function call。第一次function call引數(argument)為string,為了擷取這些string,每個string的第一個character(不包含delimiter)被用來當作scan的起始位置。當scan到delimiter時,會分割string而且包含delimiter,然後scan到null character終結function。因為第一個function call有static pointer指向string,所以第二個function call當string被scan到delimiter時,會回傳NULL pointer。

前置處理器運算子(Preprocessor)
運算子動作
字串化運算子 (#)以雙引號將實際對應的引數括住
字元化運算子 (#@)以單引號造成對應的引數會將和視為字元 (Microsoft 專用)
語彙基元帶入的運算子 (##)允許做為實際引數的語彙基元會串連形成其他語彙基元
DEFINED 運算子簡化的語式是否正確文字在某些巨集的指示詞
前置處理器指示詞(Preprocessor Directive)

2017年9月29日 星期五

MAC OSX vim設定

Mac OSX 的vimrc存放位置在
/usr/local/share/vim/.vimrc
為全域設定 會影響每個使用者
但是我們無法直接在裡面進行設定
因此直接cd到家目錄創一個.vimrc
local設定只會影響目前的使用者
$ cd 
$ vi .vimrc

以下是設定參數
1. set ruler 
會顯示行列數
2. set hls
    set nohls
搜尋時會高涼反白/取消高亮反白
3. set incsearch
搜尋為完畢前就會開始搜尋
4. syntax on
開啟突顯
5. set tabstop=4
按tab會跳四個字元
6. set showmatch
括號配對
7. set nocompatible
vi不會影響vim功能
8. set shiftwidth=4
自動縮進字元數 (先用V選取要縮進的行然後再按=)
9. set backspace=2
按BACKSPACE會縮進任何東西包含在行首時會刪除前一行行末
10. set number
左邊顯示行數

2017年9月25日 星期一

VS Code Mac設定

1. 開啟資料夾
2. 檢視 -> 擴充功能 -> C/C++
3. command+shift+P -> C/Cpp: Edit Configuration (標頭檔路徑產生在c_cpp_properties.json)
4. command+shift+P -> Tasks: Configure Task Runner -> Others (選編譯器跟寫編譯script)

4. command+shift+B (compile產生a.out)
5. command+shift+P -> Debug Open launch.json -> C++ (GDB/LLDB)
6. "program": "enter program name, for example ${workspaceRoot}/a.out",
修改成"program": "${workspaceRoot}/a.out",
7. Debug

參考資料:
https://code.visualstudio.com/docs/languages/cpp

ps.
如果在main function有char** argv
要在launch.json文件裡"args": []的中括號裡輸入值

2017年9月22日 星期五

20170922資結程設



1. VS code

2. chmod 777 修改檔可讀寫屬性的方法

3. 1 >> 8 (1 shift 8)

4. char(8) ASCII8 退格

2017年7月29日 星期六

重灌Mac


1. 安裝HomeBrew
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

2. 安裝iterm2
http://iterm2.com

設定
Preference -> Keys -> Show/hide iTerm2 with a system-wide hotkey
Preferences -> Profiles -> Window -> Top of Screen

Mac已經有內建zsh (zsh --version 查版本)
$ sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

設置主題powerLine
$ git clone git://github.com/jeremyFreeAgent/oh-my-zsh-powerline-theme ~/.ohmyzsh-powerline
$ cd .ohmyzsh-powerline/
$ ./install_in_omz.sh
$ cd ~
$ vim .zshrc
將ZSH_THEME=”robbyrussell”修改成ZSH_THEME=”powerline”

安裝Powerline專屬字型
$ git clone git://github.com/powerline/fonts ~/.powerline_fonts
$ cd ~/.powerline_fonts
$ ./install.sh

設定iterm2字型(原始是Monaco)
iTerm -> Preferences -> Profile -> Text
Font -> Change Font


設定提示字元

Powerline主題預設會顯示username、hostname與日期,並且只顯示目前路徑。

若不想顯示這些資訊,且想顯示完整路徑的話,請依照以下方式設定。

取消hostname與日期
$ vim ~/.zshrc
在第一行加上
POWERLINE_HIDE_HOST_NAME="true"
POWERLINE_DISABLE_RPOMPT="true"
POWERLINE_FULL_CURRENT_PATH="true"

取消username
$ vim ~/.ohmyzsh-powerline/powerline.zsh-theme
將此行改成
PROMPT="%k%f%F{white}%K{blue}"$POWERLINE_CURRENT_PATH"%F{blue}"$POWERLINE_GIT_INFO_LEFT" %k"$'\ue0b0'"%f "








4. 安裝fira code font
download 
到ttf資料夾選擇要安裝的形式

5. 安裝終端機自動命令提示
$ brew install zsh-autosuggestions

確認是否有zsh-autosuggestions.zsh (路徑要確認是否為0.4.0版本)
$ cd /usr/local/Cellar/zsh-autosuggestions/0.4.0/share/zsh-autosuggestions

zsh-autosuggestions.zsh放入~/.zshrc文件中
$ source /usr/local/Cellar/zsh-autosuggestions/0.4.0/share/zsh-autosuggestions/zsh-autosuggestions.zsh
$ source ~/.zshrc

6. 安裝OpenMP和MPI
Installing OpenMP
如果還沒安裝gcc
$ brew install gcc --without-multilib
如果已經安裝gcc
$ brew reinstall gcc --without-multilib
compile指令
$ gcc-7 -fopenmp
Installing MPI (https://shawnliu.me/post/configuring-openmp-and-mpi-on-mac/)
$ brew install openmpi --build-from-source --cc=gcc-7
compile指令
$ mpicc <your source code>

7. 安裝 Homebrew Cask
$ brew install brew-cask-completion
$ brew cask install google-chrome

8. 更新
$ brew update && brew upgrade brew-cask && brew cleanup

9. 安裝Anaconda
https://www.continuum.io/downloads

啟動 Jupyter Notebook
$ jupyter notebook

10.安裝FileZilla
$ brew cask install filezilla

11. 安裝The Unarchiver
https://itunes.apple.com/app/the-unarchiver/id425424353

12. Sublime Text 3
https://www.sublimetext.com/3

2017年6月18日 星期日

GPU on OSX

Q: zsh: command not found: nvcc

A:



export PATH=/Developer/NVIDIA/CUDA-8.0/bin${PATH:+:${PATH}}

export DYLD_LIBRARY_PATH=/Developer/NVIDIA/CUDA-8.0/lib\

${DYLD_LIBRARY_PATH:+:${DYLD_LIBRARY_PATH}}

Q: nvcc warning : The 'compute_20', 'sm_20', and 'sm_21' architectures are deprecated, and may be removed in a future release (Use -Wno-deprecated-gpu-targets to suppress warning).

A:













nvcc -gencode arch=compute_30,code=sm_30 hello.cu -o hello

Q: nvcc fatal : The version ('80100') of the host compiler ('Apple clang') is not supported

A:












1. 下載Xcode 8.3.3 (https://developer.apple.com/download/more/)
2. Unzip "Xcode8.3.3.xip" and movie it to "Application folder" as /Applications/Xcode.app3. $ sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
4. $ /usr/bin/cc --version
移除xcode
sudo rm -rf /Applications/Xcode.app
sudo rm -rf /Library/Preferences/com.apple.dt.Xcode.plist
rm -rf ~/Library/Preferences/com.apple.dt.Xcode.plist rm -rf ~/Library/Caches/com.apple.dt.Xcode rm -rf ~/Library/Application\ Support/Xcode
rm -rf ~/Library/Developer/Xcode rm -rf ~/Library/Developer/CoreSimulator rm -rf ~/Library/Developer/XCPGDevices

2017年2月25日 星期六

nvcc warning

nvcc無法compile

解決方法:到 https://developer.apple.com/download/more/ 
下載新的Command_Line_Tools



出現警告

nvcc warning : The 'compute_20', 'sm_20', and 'sm_21' architectures are deprecated, and may be removed in a future release (Use -Wno-deprecated-gpu-targets to suppress warning).

$ nvcc -arch=sm_60 -std=c++11 vectorAdd.cu

ps. SMS ?=  30 35 37 50 52 60都可以