2015년 6월 8일 월요일

Sun Grid Engine (SGE) 에서 여러개의 job을 하나로 submit 하기

예를 들어 32 개의 process를 사용하는 mpi 프로그램이 100개 있을 경우,
한번에 job을 submit 하는 방법을 생각해 보자.

(1) 무식하게 100번 submit하기 : qsub 를 100번 하기

(2) array job 이용하기(-t 옵션) : 100 개의 sub job을 하나의 jobid 로 submit하기.
        편하고 Job id는 하나이지만,
        실제로는 TASK_ID가 1-100까지 붙는 100개의 job을 submit 하는 셈이다.
        만약 한번에 실행 가능한 job의 갯수에 제한이 있는 경우, 순차적으로 실행되게 된다.

    #$ -pe mpi_fu 32
    #$ -t 1-100
    mpirun -np $NSLOTS ./program${SGE_TASK_ID}
 

(3) machine file splitting : SGE가 확보한 자원을 직접 100 개의 program에 나누어 할당한다.  먼저 다음과 같이 job script를 준비한다.

    #$ -pe mpi_fu 3200   <---32*100
    cat $PE_HOSTFILE | awk '{print $1 " slots=" $2}' > "myhost_ompi"
    ./my_wrapper_script    

    여기서 $PE_HOSTFILE은 SGE가 확보한 자원의 machine file 이다.
    (형식은 "node0904 8 normal@node0904 UNDEFINED" 꼴.)
    이것을 openmpi 용 machine file로 바꾼다.
    (형식은 "node0904 slots=8" 꼴.)
    mvapich의 경우에는 다음과 같이 바꾸어 주면 된다.

for host in `cat $PE_HOSTFILE | awk '{print $1}'`; do
   num=`grep $host $PE_HOSTFILE | awk '{print $2}'`
   for i in `seq 1 $num`; do
       echo $host >> "myhost_mpich"
   done
done

  wrapper script에서는 machine hostfile  을 필요한 만큼 잘라서 여러개의 hostfile
 ( host_$num ) 으로 만들고
"mpirun -np 32 -hostfile host_$num ./program_$num > out_$num &"  을 프로그램 수 만큼 실행 시켜주면 된다.

 sed -n 1,4p myhost > host_1  

and so on... -> extract lines 1-4 "p" is a printout command.




2015년 5월 26일 화요일

(퍼옴) 안구 근력 운동

무항생제 안약을 두 통 받아든 채 K씨는 눈 운동 관련 정보를 찾았다.

(1) 상하좌우로 움직이기 - 3세트

위아래로 움직인다: 눈을 위로 향하고 이마를 본다는 감각으로 그 상태를 3초간 유지한다. 이어서 자신의 코끝을 본다는 감각으로 시선을 아래로 향하고 그 상태를 3초간 유지한다(1세트).

눈을 좌우로 움직인다: 눈을 왼쪽으로 향하고 3초간 유지한 다음, 이어서 오른쪽으로 향해 3초간 유지한다(1세트).

* 포인트: 눈을 깜빡이지 않는다. / 시선이 향하는 곳보다 2밀리미터 정도 멀리 보는 듯한 감각으로 실시한다.

눈을 모로 움직인다: 머리는 고정한 채 눈만 움직여 모로 왼쪽 위, 오른쪽 위, 오른쪽 아래, 왼쪽 아래 위치로 향하는데, 각각 3초간 유지한다(1세트).

* 포인트: 시선을 움직일 때 얼굴도 같이 움직인다면 주먹을 쥐고 턱에 대 고정한다.

(2) 빙그르 회전시키기 - 3세트

눈을 시계방향으로 가급적 크게, 천천히 1바퀴 회전시킨다. 이어서 시계반대방향으로 1바퀴 회전시킨다.

* 포인트:얼굴은 움직이지 않는다. / 실시하는 중에 시선이 정면을 향하지 않는다.

(3) ∞ 모양으로 움직이기 - 3세트

눈을 누워 있는 ∞ 모양으로 그리듯이 움직인다. 3세트 실시하고, 반대방향으로도 동일한 방법으로 실시한다.

* 포인트: 장시간 컴퓨터 작업하는 틈틈이 실시하면 안구건조를 예방할 수 있다.

(4) 앞뒤로 움직이기 - 3세트

눈을 앞으로 내밀었다가 뒤로 집어넣는다: 안구를 앞으로 내밀듯 부릅뜨고 3초간 유지한 뒤에, 안구를 뒤통수 쪽으로 집어넣듯 눈을 꾹 감고 3초간 유지한다(1세트).

* 포인트: 눈을 앞으로 내밀 때는 마치 연극하듯 과장스럽게 실시한다. / 눈을 뒤로 집어넣을 때는 아주 신 레몬을 먹은 것 같은 기분으로 실시한다.

2015년 5월 20일 수요일

Intel Math Kernel Library (MKL) and FFTW3 링크하기

먼저 MKL library의 위치를 찾을 것. 
MKL library에 FFTW가 포함되어 있다고 하지만 FFTW의 위치도 알아둘 것.

MKL libary를 사용하는 방법은 두가지가 있다.

(1) -mkl 옵션을 사용하는 방법
(2) 모든 옵션을 일일이 지정해 주는 방법
-mkl 옵션의 경우 default 설정이 무엇인가에  따라 달라지게 된다.일반적인 경우라면,

ifort test.f90 -mkl -o test_f
icc test.c -mkl -o test_c

만으로 충분하고 FFTW를 사용하는 경우에는 

icc test.c -w -DMKL_DOUBLE -I/opt/intel/Compiler/11.1/069/mkl/include/fftw -mkl -o test_c

ifort -I/opt/intel/Compiler/11.1/069/mkl/include/fftw test.f90 -mkl -o test_f

icc test.c -I/opt/intel/Compiler/11.1/069/mkl/include/fftw -mkl -o test_c

ifort test.f90 -I/opt/intel/Compiler/11.1/069/mkl/include/fftw -mkl -o test_f

와 같이 include path를 지정해 주는 것이 좋다고 한다. 

-mkl 옵션을 쓰지 않으면 아래와 같이 일일이 써 주어야한다. 

icc test.c -I/opt/intel/Compiler/11.1/069/mkl/include -I/opt/intel/Compiler/11.1/069/mkl/include/fftw
-lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread -lm 
-L/opt/intel/Compiler/11.1/069/mkl/lib/em64t -o c_test 

ifort test.f90 -I/opt/intel/Compiler/11.1/069/mkl/include -I/opt/intel/Compiler/11.1/069/mkl/include/fftw 
-lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread -lm 
-L/opt/intel/Compiler/11.1/069/mkl/lib/em64t -o f_test


(주의1) -lmkl_intel_lp64 는 64bit cpu 용 libary를 사용한다는 뜻이고,  
-lmkl_intel_ilp64 는 64bit cpu 용 libary를 사용하되 
정수도 64bit인 libary를 사용한다는 뜻으로 compile 할 때 -i8 option을 추가해 주어야 한다.   
ilp64를 사용할 경우 FFTW와 integer type이 다를 수 있으므로 주의해야 한다.

(주의2) FFTW2 를 사용할 경우는 option을 다르게 주어야한다.
icc test2.c -o test2_c -I/opt/intel/Compiler/11.1/069/mkl/include/fftw 
-L/opt/intel/Compiler/11.1/069/mkl/lib/em64t -lfftw2xc_intel -mkl 

ifort test2.f -o test2_f -I/opt/intel/Compiler/11.1/069/mkl/include/fftw 
-L/opt/intel/Compiler/11.1/069/mkl/lib/em64t -lfftw2xf_intel -mkl

만약 외부 FFTW library를 사용하는 경우에는 아래와 같이 사용한다.
ifort -O3 -o fftw_example.exe fftw_example.f -I/u/username/fftw/include -L/u/username/fftw/lib -lfftw3

참고:

http://geco.mines.edu/software/mkl/fftw/

http://www.nas.nasa.gov/hecc/support/kb/MKL-FFTW-Interface_204.html



(Details on the -mkl option )


-mkl[=]
          link to the Intel(R) Math Kernel Library (Intel(R) MKL) and
          bring in the associated headers
            parallel   - link using the threaded Intel(R) MKL libraries.
                         This is the default when -mkl is specified
            sequential - link using the non-threaded Intel(R) MKL libraries
            cluster    - link using the Intel(R) MKL Cluster libraries plus
                         the sequential Intel(R) MKL libraries
The libraries that are linked in for:
    * -mkl=parallel

          --start-group \
          -lmkl_solver_lp64 \
          -lmkl_intel_lp64 \
          -lmkl_intel_thread \
          -lmkl_core \
          -liomp5 \
          --end-group \

    * -mkl=sequential

          --start-group \
          -lmkl_solver_lp64_sequential \
          -lmkl_intel_lp64 \
          -lmkl_sequential \
          -lmkl_core \
          --end-group \

    * -mkl=cluster

          --start-group \
          -lmkl_solver_lp64 \
          -lmkl_intel_lp64 \
          -lmkl_cdft_core \
          -lmkl_scalapack_lp64 \
          -lmkl_blacs_lp64 \
          -lmkl_sequential \
          -lmkl_core \
          -liomp5 \
          --end-group \

2015년 4월 24일 금요일

Python curve fitting for a function with input vectors(변수가 여러개인 함수의 fitting)

변수가 여러개인 함수 예를 들어 f(d,t; c_0,c_1...) 인 경우에는
어떻게 fitting을 할까? 여기서, d,t는 변수이고, c_0,c_1..등은
fitting parameter 이다.

Suppose we have data which corresponds to

y=f[d,t]

Something like (d,t)=(0,0) gives y=0, (0,1) gives y=1....

We want to fit these data with certain fitting function
with parameters c1,c2,c3...

fit[d,t; c1,c2,c3]

Even in this case, we can use curve_fit
(Following example copied from http://stackoverflow.com/a/27096056/2775514

from scipy.optimize import curve_fit
import scipy

def fn(x, a, b, c):
    return a + b*x[0] + c*x[1]

# y(x0,x1) data:
#    x0=0 1 2
# ___________
# x1=0 |0 1 2
# x1=1 |1 2 3
# x1=2 |2 3 4

x = scipy.array([[0,1,2,0,1,2,0,1,2,],[0,0,0,1,1,1,2,2,2]])
y = scipy.array([0,1,2,1,2,3,2,3,4])
popt, pcov = curve_fit(fn, x, y)
print popt
In this example,
x[:, i-th], y[i-th] corresponds to  i-th data set.

result returns popt -> [0,1,1].

One can use different form : 

x = np.array([ [1.0, 1.0 ],[1.0,1.5],[2.0,0.5],[2.1,1.6],[0.5,0.5],[0.8,1.2] ]  )
y = 0.5*x[:,0] + 2.0 *x[:,1]**2

def fitf(x,*paras):
    return paras[0]*x[:,0]+paras[1]*x[:,1]**2

xx = np.array( [x[:,0],x[:,1]])
def testf(x,*para):
    return para[0]*x[0]+x[1]**2*para[1]

print( curve_fit(fitf,x,y,p0=[1,1]) )
print( curve_fit(testf,xx,y,p0=[1,1]) )

Note that curve_fit calls the function as 

ydata = f(xdata, *params) +eps 

In other words, when xdata is an (k,M) array with M-data, 
the function should return array ydata with M-data. 
if function only works work for a scalar f(x), it cannot be used directly with curve_fit. 

On the other hand, leastsq(cost, p0) assumes the 
cost function  returns a number or array of length of p0
#--------------------------------------------------------------------------------------------

scipy.optimize.curve_fit(fxdataydatap0=Nonesigma=Noneabsolute_sigma=Falsecheck_finite=True**kw)[source]
Use non-linear least squares to fit a function, f, to data.
Assumes ydata = f(xdata, *params) + eps
Parameters:
f : callable
The model function, f(x, ...). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.
xdata : An M-length sequence or an (k,M)-shaped array
for functions with k predictors. The independent variable where the data is measured.
ydata : M-length sequence
The dependent data — nominally f(xdata, ...)
p0 : None, scalar, or N-length sequence
Initial guess for the parameters. If None, then the initial values will all be 1 (if the number of parameters for the function can be determined using introspection, otherwise a ValueError is raised).
sigma : None or M-length sequence, optional
If not None, the uncertainties in the ydata array. These are used as weights in the least-squares problem i.e. minimising np.sum( ((f(xdata, *popt) -ydata) / sigma)**2 ) If None, the uncertainties are assumed to be 1.
absolute_sigma : bool, optional
If False, sigma denotes relative weights of the data points. The returned covariance matrix pcov is based on estimated errors in the data, and is not affected by the overall magnitude of the values in sigma. Only the relative magnitudes of the sigma values matter.
If True, sigma describes one standard deviation errors of the input data points. The estimated covariance in pcov is based on these values.
check_finite : bool, optional
If True, check that the input arrays do not contain nans of infs, and raise a ValueError if they do. Setting this parameter to False may silently produce nonsensical results if the input arrays do contain nans. Default is True.
Returns:
popt : array
Optimal values for the parameters so that the sum of the squared error of f(xdata, *popt) - ydata is minimized
pcov : 2d array
The estimated covariance of popt. The diagonals provide the variance of the parameter estimate. To compute one standard deviation errors on the parameters use perr = np.sqrt(np.diag(pcov)).
How the sigma parameter affects the estimated covariance depends on absolute_sigma argument, as described above.
Raises:
OptimizeWarning
if covariance of the parameters can not be estimated.
ValueError
if ydata and xdata contain NaNs.

2015년 4월 13일 월요일

피자헛 할인 비교

그동안 어떤 방법으로 주문하는 것이 가장 할인이 많이 되는지 궁금했는데 이번 기회에 비교해 보기로 했다.

기준은 라지 사이즈 치즈크러스트 베이컨 포테이토 피자.

기본가격: 32,900원

(1) 방문 할인:    22,900원  (   10000원 할인 )
(2) 무료사이즈업:  26,900원 (6000원 할인)
(3) 올레 할인 : 15% 27,965원 (4935원 할인)
                   50% 16,450원 (16,450원 할인)
(4) 이벤트: 그때그가격 이벤트 23,900원(7000원 할인)

결국, 제휴 할인을 통해서 30% 이상 할인 받지 않는 이상
방문 포장 1만원 할인이 가장 할인을 많이 받는 셈이다.


2015년 3월 26일 목요일

[퍼즐] 잘못된 주소 또는 엉뚱한 모자 문제

여기에 5개의 목적지가 다른 편지와 각각의 주소가 적힌 편지 봉투 5개가 있다.
실수로 모든 편지를 잘못된 주소로 보낼 경우의 수는 몇인가?

변형된 다른 문제는 7개의 모자와 7명의 모자 주인이 있는데, 모든 모자 주인들이
엉뚱한 모자를 가져갈 경우의 수는 몇인가?

이 문제를 처음 접한 지는 꽤 되었는데,
이것에 교란순열(derangement)이라는 수학용어가 있었다.
(예를 들어 n개가 모두 잘못된 위치로 놓이는 방법은 !n 으로  쓴다.)

이 문제의 답을 스스로 생각해 내는 것은 항상 헷갈린다.


2015년 3월 17일 화요일

[퍼즐] 이상한 학교 인사

먼저 내가 접한 퍼즐 문제는 다음과 같다.

" 어떤 학교에는 이상한 인사방법이 있다. 모든 남학생들은 남학생끼리 서로에게 인사를 한 뒤, 선생님에게 인사를 한다. 한편, 모든 여학생들도 여학생들 끼리  서로에게 인사를 한 뒤,
선생님에게 인사를 한다. 마지막으로 모든 남학생들이 여학생들에게 인사하고, 여학생들도 남학생에게 인사를 한다. 이렇게 모두 900번의 인사를 한 뒤에야 수업이 시작된다. 이 학교의 여학생 수는 남학생의 2배라고 하고, 선생님은 답례를 하지 않는다고 할 때, 이 학교의 남학생 수는 얼마인가? "

원래 문제에서는 선생님이 답례를 한다는 것인지가 명확히 써 있지 않아서 헷갈렸다.

다음은 내가 변형 시켜 본 문제이다.

"다음해에 신입생들은 전통에 따라 같은 방식으로 인사를 하지만,
담임 선생님은 학생에 따라 내키는 대로 인사를 하기도 하고, 안하기도 한다.
모든 인사 수의 합이 정확히 얼마인지 모르지만, 대략 400 보다는 많고,
440 보다는 적다고 할 때, 올 해의 신입생 수는 얼마인가?"

풀이는 아래 클릭..