2015년 7월 8일 수요일

Python: *args and **kargs 임의의 개수의 변수를 가지는 함수 그리고, argument를 하나의 container로 넘겨주는 방법

*args 는 unlimited number of positional argument values 에 사용한다. (즉 keyword argument 가 아닌 경우)

**kargs 는 unlimited number of keyword argument values 에 사용한다.

예:

def func(x, *args, **kargs):
   print('first argument : '+x)
   for i in args:
     print('next argument :, i)
   for key,value  in kargs.iteritems() :
     print( '%s == %s'%(key,value))

여러개의 argument를 한번에 넘겨주고 싶을 때 다음과 같이
container를 이용하는 방법을 사용할 수 있다.
예를 들어서 다음과 같은 함수에 대해서

def avg3(a,b,c):
...     return (a+b+c)/3.0

(1) positional arguments as tuple:
     avg3( *(4,5,7) )

이 경우 하나의 3-tuple을 분해해서 3개의 argument로 받아들이게 된다.

(2) keyword arguments as dictionary
>>> d={ 'a':5, 'b':6, 'c':9 }
>>> avg3( **d )
6.666666666666667
이 경우 dictionary를 분해해서 3개의 keyword argument로 받아들인다.

(3) mix both
>>> avg3( 2, b=3, **{'c':4} )
3.0


한편, 일반적인 함수를 이용하여 계산하는 subroutine을 만들때, 기본적인 변수 이외의 extra argument를 사용할 수 있도록 하려면 어떻게 할까? 예를 들어 일반적인 f(x)꼴의 함수를 (-1,1)사이에서 적분하는 subroutine을 만들었는데, 함수에 다른 변수 f(x, a=1,b=2) 의 a,b를 바꾸고 
싶을 때는 어떻게 할까?
처음에 적분함수를 정의 할 때, def integration(func,args=()): 로 정의하고
함수 func을  func(x,*args)로 사용하면 된다. 이때, extra arguments는 tuple로 passing.



 

2015년 6월 10일 수요일

Extract even or odd line of text files 텍스트 파일에서 홀수나 짝수 줄만 뽑아내기

먼저 ouput file에서 특정 이름을 찾아서 line number, column3 column4 를 출력하는 예

grep 'EHn3lo(Q^4)' out_file | awk '{print NR" "$3"  "$4}'


출력 결과에서 짝수번째 결과만 뽑고 싶은 경우 

awk 'NR%2==0 {print $1}' infile


예를 들어 out_He6_idx02 라는 file에서 binding energy (MeV) 가 나오는
줄을 모두 찾은 뒤 그 중 짝수번재 라인에서 4번재와 5번째 Column 의
내용만 보고 싶을 때,

grep 'binding energy (MeV)' out_He6_idx02 | awk 'NR%2==0 {print NR" "$4"  "$5}'

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만원 할인이 가장 할인을 많이 받는 셈이다.