stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/computer_programming... ·...

160
1 이인호 Computer programming KRISS Stay hungry, stay foolish. http://ihlee.kriss.re.kr/compphys/f90module.htm http://ihlee.kriss.re.kr/compphys/pfphysics.htm FORTRAN 90 and Python

Upload: others

Post on 05-Apr-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

1

이인호

Computer programming

KRISS

Stay hungry, stay foolish.

http://ihlee.kriss.re.kr/compphys/f90module.htmhttp://ihlee.kriss.re.kr/compphys/pfphysics.htm

FORTRAN 90 and Python

Page 2: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

2

Language is the house of the truth of Being. -Martin Heidegger

본아티클에서는포트란과파이썬을중심으로컴퓨팅프로그램의기본사항들을설명한다.

Page 3: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

3

Computer programming?

Computer programming (often shortened to programming or coding) is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs.

A programming language is an artificial language that can be used to control the behavior of a machine,particularly a computer.A prominent purpose of programming languages is to provide instructions to a computer.

Efficiency, reliability, robustness, portability, readability

오성식: 미국에는영어못하는사람이없다!왜냐하면, 매일사용하니까.

Fortran 90 and Python

1. 읽을수있어야함.2. 바꿀수있어야함.3. 새로만들수있어야함. debugging Science

문법을완전히이해하고있을때에만진정한디버깅작업이시작된다.늘프로그램을테스트할수있는상황들을만들수있어야한다.

언어는존재의집이다.-Martin Heidegger

Page 4: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

4

Debugging Debugging is a very important task for every programmer, because an erroneous program is often useless.

1945년 9월 9일최초의컴퓨터 bug; `debugging`이란개념이출현하게된다. 버그의어원은프로그래머인그레이스호퍼에의해비롯되었다.

Bugs - Compile-time ErrorsBugs - Run-time Errors

Page 5: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

5

Why FORTRAN 90?

과학기술용, 전통적 (간결한수치처리기능지원 )많은사용자들컴파일러우수

고급언어

FORTRAN 90의특징

1. 문법이매우간단하여배우기가쉽다. (고수준언어이다; 본질적으로기계보다사람에게더가깝게설계되어있다.)2. 과학기술계산용전문언어이다. (미리정의된함수들다수보유, 113, 다양한수치계산프로그래밍모듈지원)3. 수식과여러종류의계산등을간단히공식화할수있다. (감각적인간결성, 묵시적상황판단, 추상적자료형지원)4. 대상중심적이다. (동적인메모리관리, 모듈화의장점을살릴수있다, 확실한데이터처리와보완성확보)5. 기종간의호환성이있다. (이미검증된많은포트란 77 프로그램과쉽게연동된다.)

객체지향(대상중심)이란 ?: 특정한응용을위한객체 (object)를기술하는높은수준의데이터형, 데이터형처리방법들을정의함으로써프로그램을단독으로작성하는것 (개발후에있게되는수정/보완시에도단독으로...). 프로그램전체에서다른부분사이가독립되어있기때문에이해하기쉽고확장과변경이용이한코드를얻을수있는장점이있다. 객체는데이터와함수의모음으로표현된다. 아래에나타낸것이포트란 90과관련된객체지향성이다. 이들은모듈의작성과깊이연관되어있다. 객체지향이라는말보다는대상중심이라는말이더적합하다고생각합니다.특정대상을전문으로취급하는데이터와부프로그램들을설계하고필요에따라서개발기간동안쉽게계속추가하는것을목표로한다.

1. data abstraction -- user-defined types2. data hiding -- private and public attributes 3. encapsulation -- modules and data hiding facilities4. inheritance and extensibility -- generic procedures5. polymorphism -- generic overloading6. reusability -- modules

John Backus

Page 6: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

6

Hello World!

! Comment F90에서는첫칼럼아니라도사용할수있습니다.! 기호뒤부터 comment로처리됩니다.

ihlee@cetus0:~/lecture_programming$ a.outHello World!ihlee@cetus0:~/lecture_programming$

포트란 77에서는항상첫칼럼에서코멘트를표시했다.Cc*

!234567890program HWimplicit none

write(6,*) 'Hello World!'

end program hw

포트란 90 기본 : http://incredible.egloos.com/3044862

Page 7: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

7

포트란의구성요소

포트란은 6가지의 수형(type)을 가지고 있다. 포트란 77 중심의 경우 아래와 같이 분류 가능하다. 포트란 90과 비교하면 아주 편협 된 개념을 사용하고 있다. 물론, 이들만 가지고도 거의 모든 일들을 프로그램 할 수 있다. 문제는 프로그램의 효율적인 작성이다. ① 자료형 : 일반적으로 REAL(실수), INTEGER(정수), DOUBLE PRECISION(배정밀도 실수), COMPLEX(복소수),

BOOLEAN(참, 거짓), CHARACTER(문자) 등의 6가지를 지원한다. ② 변수(variable) : 변수는 첫 글자가 I 와 N 사이의 글자로 시작하면 정수형을 의미하며

나머지 영문자로 시작하는 변수는 실수형이 된다. 하지만 별도로 수형을 선언하면 원래 의미가 무시된다.변수는 영문자와 숫자를 이용하여 6자리까지 가능하지만 첫 글자는 반드시 영문자여야 한다. 특수문자는 변수명에 사용할 수 없다.

③ 배열(array) : 배열이란 여러 개의 변수가 하나로 묶인 것을 의미하는데 배열의 첨자는 상수나 정수형 변수또는 상수와 정수형 변수의 조합 수식이 가능하다.

④ COMMON(공용) : 단위가 다른 프로그램에 있는 변수나 배열명 등이 같은 기억장소를 사용할 수 있는 선언문이다. COMMON /named_common1/ A,B,CCOMMON /abc_name/ AREA(5), AVRGCOMMON B(10), YY, XX

⑤ EQUIVALENCE(동등) : 하나의 단위 프로그램 내에서 변수나 배열 등이 같은 기억장소를 공유할 수 있게 하는 선언문이다. 사용하는 변수의 이름은 달라도 같은 곳에 저장됨을 의미한다. common block의 경우와 마찬가지이다. 포트란 90을 배우는데 필요 없는 것을 논할 필요가 있을까? 하지만, 옛날 소스를 분석할 때를 위해서 알아둘 필요가 있다.

⑥ DATA문 : 초기값을 부여할 수 있다. 아래의 예를 보면, 배열 A와 변수 PI, X가 나타나 있다. PI에는 초기값 3.14가 배정되며 X에는 1.0이 배정된다. 배열 A는 3개 모두에 1.0이 배정된다.

과거에작성된루틴들을읽을수있어야한다.

가변배열모듈오퍼레이터오버로딩

FORTRNA 90에서부각되는기능들실제프로그래밍에서매우중요한항목이된다.

Page 8: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

8

수와계산

abc=1.0d0 라는표현은 abc라는변수에숫자 1.d0을할당한다는개념이다.

1.e0 (single precision) vs 1.d0 (double precision)

선언(정수, 실수, 복소수, 정수배열, 실수배열, 복소수배열, 문자배열….)표현(연산)Implicit TypingUndeclared variables have an implicit type, if first letter is I, J, K, L, M or N then type is INTEGER; any other letter then type is REAL s.

Operator precedence

pi*radius**2 = pi*(radius**2)

x*y/z+a= (x*y/z)+a

파이썬에서는 1.d0를사용하지않는다.

Page 9: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

9

반복, 선택

Intrinsic Logical OperationsA LOGICAL or boolean expression returns a .TRUE. / .FALSE. result.The following are valid with LOGICAL operands, .NOT. -- .TRUE. if operand is .FALSE.. .AND. -- .TRUE. if both operands are .TRUE.; .OR. -- .TRUE. if at least one operand is .TRUE.; .EQV. -- .TRUE. if both operands are the same; .NEQV. -- .TRUE. if both operands are different. For example, if T is .TRUE. and F is .FALSE.

FORTRAN 77에서는 do while이없었다. 아래와같이만들어서사용했다.

integer n n = 1

10 if (n .le. 100) then n = 2*n write (*,*) n goto 10

endif

while (logical expr) do statementsenddo

do while (logical expr)statementsenddo

Page 10: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

10

IF (I > 17) THENPrint*, "I > 17" ELSE Print*, "I <= 17" END IF

[name:] IF (expression) THEN block

ENDIF [name]

[name:] IF (expression) THEN block1

ELSE [name] block2

ENDIF [name]

IF (I > 17) THENPrint*, "I > 17" ELSEIF (I == 17) THENPrint*, "I == 17" ELSEPrint*, "I < 17" END IF

elseif의수는여러개가가능하다.없을수도있다.

outa: IF (a .NE. 0) THENPRINT*, "a /= 0" IF (c .NE. 0) THEN

PRINT*, "a /= 0 AND c /= 0" ELSE

PRINT*, "a /= 0 BUT c == 0" ENDIF

ELSEIF (a .GT. 0) THEN outaPRINT*, "a > 0"

ELSE outaPRINT*, "a must be < 0"

ENDIF outa

IF ( n == 1 ) THEN discount = 0.0d0 ELSEIF ( n <=5 ) THEN discount = 0.1d0 ELSEIF ( n>5 .AND. n <=10) THEN discount = 0.15d0ELSE discount = 0.25d0 ENDIF

Page 11: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

11

INTEGER :: month season: SELECT CASE( month ) CASE(4,5)WRITE(*,*) `Spring' CASE(6,7)WRITE(*,*) `Summer' CASE(8:10)WRITE(*,*) `Autumn' CASE(11,1:3,12)WRITE(*,*) `Winter' CASE DEFAULTWRITE(*,*) `not a month' END SELCET season

Conditional statementsIF statementIF constructCASE constructRepetitionDO constructsGOTO

outer: DO ... inner: DO k=1,5 IF ( a(k)==0 ) CYCLE IF ( a(k)<0 ) EXIT outer ... END DO inner END DO outer

INTEGER :: x ...

IF ( x.LT.1 ) GOTO 10...

10 x = 1

Exit from loop with EXIT. Begin another iteration with CYCLE. By default EXIT and CYCLE apply to the inner-most loop containing the statement, but can refer to a specific, named loop.

Page 12: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

12

고정배열, 가변배열

integer i,j,k,nninteger mmreal*8 abcreal*8 cde(100),vec(3),xaa(3,3)real*8, allocatable :: dd(:,:), ee(:)integer, allocatable :: kkx(:)

가변배열: FORTRAN 90에서사용가능

FORTRAN 77에서는컴파일할때미리사용가능한최대배열의크기를정해두게된다. 결국, 실제프로그램실행할때사용한도이내에서실질적인메모리사용이이루어진다.

이러한이유로, FORTRAN 77에서는컴파일을다시해야할필요성이있을수있다.

allocate( dd(-10:10,3) )allocate( ee(mm) )

…….

deallocate(dd) ; deallocate(ee)

특정, 주함수, 부함수내에서만사용되고없어질수있다.모듈에서만사용되고없어질수있다. 물론, 하나의함수에서인수로또다른함수로전달될수있다.생성된상태에서의가변배열은고정배열과동등하다.

Page 13: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

13

C vs FORTRAN F: 소문자, 대문자를구별하지못한다.

short int x; INTEGER*2 X

long int x; INTEGER*4 X

int x; INTEGER*4 X

char x; BYTE X or LOGICAL*1 X

char *x; CHARACTER*n X

char x[7]; CHARACTER*7 X

float x; REAL X

double x; DOUBLE PRECISION X

다차원배열을일차원배열로전달(매핑)할때, 배열인수가변하는순서가 C와 FORTRAN에서서로반대이다.

포트란에서는앞에있는인자들이먼저바뀌고난후에뒤쪽의인수들이바뀌게된다.a(3,3)인경우, a(1,1), a(2,1), a(3,1), a(1,2), a(2,2), a(3,2), a(1,3),a(2,3),a(3,3) 순서대로일차원배열에대응될수있다.이때, 일차원배열, 예를들면, b(9)처럼사용할수있는배열의길이는같아야한다.

기본배열, aaa(100)은배열인수가 1,2,3,,,100까지가능하다. C에서는 0,1,2,3….99파이썬에서도마찬가지이다.

FORTRAN에서는 bbb(0:99)처럼정의해서사용할수있다. 다시말해서, FORTRAN에서, bbb(1:100)과 bbb(100)은같은것을의미한다. 필요에따라서, ccc(-100:100)처럼사용할수도있을것이다.

Page 14: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

14

Slices, sectionA(:) ! the whole array A(3:9) ! A(m) to A(n) in steps of 1 A(3:9:1) ! as above A(m:n) ! A(m) to A(n) A(m:n:k) ! A(m) to A(n) in steps of k A(8:3:-1) ! A(8) to A(3) in steps of -1 A(8:3) ! A(8) to A(3) step 1 => Zero size A(m:) ! from A(m) to default UPB A(:n) ! from default LWB to A(n) A(::2) ! from default LWB to UPB step 2 A(m:m) ! 1 element section A(m) ! scalar element - not a section

aaa(:,3)=bb(:)abc=maxval(aaa(:,2))abc=minval(abs(aaa(:,:))이런식으로사용할수있다.부분단체행동(?)

FORTRAN 90에서기본적으로지원하는함수들과잘어울리는간결한표현들이가능해지다.

Page 15: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

15

프로그램의단위

다른모듈들에서가져와야할것들

고정된값

Page 16: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

16

implicit nonereal*8 a,b,creal*8 d

read(5,*) a,b,cd=b**2-4.d0*a*cif(d < 0.0d0)thenwrite(6,*) 'NO REAL ROOTS'end if

if(d == 0.0d0)thenwrite(6,*) 'two identical roots'write(6,*) -b/(2.d0*a)

endif

if(d> 0.0d0)thenwrite(6,*) 'two distinct roots'write(6,*) (-b+sqrt(d))/(2.0d0*a)write(6,*) (-b-sqrt(d))/(2.0d0*a)

endif

stopend

program areaimplicit nonereal*8 a,b,creal*8 s,p,aaa

read(5,*) a,b,cp=a+b+cs=p/2.0d0aaa=sqrt(s*(s-a)*(s-b)*(s-c))write(6,*) aaastopend program area

선언문실행문

기본입력(5 번), read(5,*)기본출력(6 번), write(6,*)a.out < input > output

주요한계산결과물은다른파일에적는것이일반적이다.자료특성에따라서나누어적는것이좋다.

Page 17: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

17

1+2+3+4+5+…=?

!234567890program sumimplicit nonereal*8 aaainteger nn

integer i

write(6,*) ' Enter nn'read(5,*) nnwrite(6,*) 'nn ',nn

aaa=0.0d0do i=1,nnaaa=aaa+float(i)end do

write(6,*) aaa,' aaa'

end program sum

ihlee@cetus0:~/lecture_programming$ a.outEnter nn

10nn 10

55.00000000000000 aaaihlee@cetus0:~/lecture_programming$

a.out < input > output형식이일반적이다.

간단한프로그램의경우, interactive 형식으로프로그램을만들수도있다.

물론, 추가적인입력파일들을이용할수있다.

Page 18: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

18

subroutine!234567890

program i_sumimplicit noneinteger mmreal*8 bbb

write(6,*) ' Enter nn'read(5,*) mmwrite(6,*) 'nn ',mm

call int_sum(mm,bbb)

write(6,*) bbb,' aaa'

end program i_sum

subroutine int_sum(nn,aaa)implicit noneinteger nnreal*8 aaa

integer i

! write(6,*) ' Enter nn'! read(5,*) nn! write(6,*) 'nn ',nn

aaa=0.0d0do i=1,nnaaa=aaa+float(i)end do

! write(6,*) aaa,' aaa'

end subroutine int_sum

ihlee@cetus0:~/lecture_programming$ a.outEnter nn

10nn 10

55.00000000000000 aaaihlee@cetus0:~/lecture_programming$

입력, 출력이정해져있다. 특별한일을수행하는단위로생각할수있다.

인수들을활용하여특정한일들을수행한다.

입력: 인수, 배열, 다양한인수가가능하다.출력: 바뀔수도있고, 안바뀔수도있다.

Subroutine의경우와함수의경우가다르다.함수의경우, 단하나의반환값이있다.함수의경우도, 인수가반환될때바뀔수있다.

Subroutine 별로테스트가진행될수있다.

Page 19: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

19

Main program and subroutine

!234567890program i_sumimplicit noneinteger mmreal*8 bbb

write(6,*) ' Enter nn'read(5,*) mmwrite(6,*) 'nn ',mmcall int_sum(mm,bbb)write(6,*) bbb,' aaa'end program i_sum

subroutine int_sum(nn,aaa)implicit noneinteger nnreal*8 aaainteger i

! write(6,*) ' Enter nn'! read(5,*) nn! write(6,*) 'nn ',nn

aaa=0.0d0do i=1,nnaaa=aaa+float(i)end do

! write(6,*) aaa,' aaa'end subroutine int_sum

ihlee@cetus0:~/lecture_programming$ pgf90 a.f90 sub1.f90

ihlee@cetus0:~/lecture_programming$ a.outEnter nn

100nn 100

5050.000000000000 aaaihlee@cetus0:~/lecture_programming$

Page 20: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

20

Main program and subroutines

!234567890implicit noneinteger mmreal*8 bbb

write(6,*) ' Enter nn'read(5,*) mmwrite(6,*) 'nn ',mm

call int_sum(mm,bbb)write(6,*) bbb,' aaa'

!call inv_sum(mm,bbb)

write(6,*) bbb,' aaa'

end

subroutine int_sum(nn,aaa)implicit noneinteger nnreal*8 aaainteger i

! write(6,*) ' Enter nn'! read(5,*) nn! write(6,*) 'nn ',nn

aaa=0.0d0do i=1,nnaaa=aaa+float(i)end do

! write(6,*) aaa,' aaa'end subroutine int_sum

subroutine inv_sum(nn,aaa)

implicit noneinteger nnreal*8 aaainteger iaaa=0.0d0do i=1,nnaaa=aaa+1.d0/float(i)end doend

1/1+1/2+1/3+1/4+1/5+…=?

1+2+3+4+5+…=?

ihlee@cetus0:~/lecture_programming$ pgf90 a.f90 sub1.f90 sub2.f90

ihlee@cetus0:~/lecture_programming$ a.outEnter nn

10nn 10

55.00000000000000 aaa2.928968253968254 aaa

단하나의메인프로그램과많은부함수(subroutine, function)들로프로그램이구성되기마련이다.

Page 21: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

21

특별한목적의일을수행하는단위

ihlee@cetus0:~/lecture_programming$ a.outa,b,n0.d0 1.d0 55

0.0000000000000000 1.000000000000000 0.3333884297520662 FORTRAN STOPihlee@cetus0:~/lecture_programming$

implicit noneinteger n,nnreal*8 a,breal(8) x,f,area,h,sinteger kf(x)=x*x!write(6,*) 'a,b,n'read(5,*) a,b,nh=(b-a)/float(n)nn=n-1s=f(a)+f(b)do k=1,nns=s+2.0d0*f(a+float(k)*h)enddoarea=h*s/2.0d0write(6,*) a,b,areastopend

ihlee@cetus0:~/lecture_programming$ a.outa,b,n0.d0 1.d0 100

0.0000000000000000 1.000000000000000 0.3333500000000000 FORTRAN STOPihlee@cetus0:~/lecture_programming$

Page 22: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

22

Program Source File

Fortran 90Compiler

Fortran 90Compiler

Linker

Module Source File

Program Object File

Module Object File

Program Executable File

Program Source File

Fortran 90Compiler

Fortran 90Compiler

Linker

Module Source File

Program Object File

Module Object File

Program Executable File

pgf90 *.f90 pgf90 a.f90 b.f90 c.f90 d.f e.fpgf90 a.f90 b.o c.o d.o e.o

makefile

Page 23: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

23

IMPLICIT NONE?

IMPLICIT NONE에관해서: 어떠한것도묵시적이지않다고선언하는것이다. 즉, 모든변수들이구체적인형을선언해주어야한다는것이다. 이렇게선언한이상. REAL*8, INTEGER, CHARACTER*3, LOGICAL, COMPLEX*16 과같이모든변수에그해당변수형을선언해야한다. 이러한것은프로그램작성시발생한 TYPO들을잡아주는기능을한다. 조금귀찮지만안전한코드생성에일조한다. 더욱이, 모듈개념을사용할때는꼭있어야한다는생각이든다. 왜냐하면, USE를사용하는경우, 사용하는모듈속에변수들이존재하는지를컴파일하는단계에서강제로확인시켜준다.

이전에많이사용했던 IMPLICIT REAL*8 (A-H,O-Z) 즉, 시작하는변수들이 A-H 또는 O-Z로시작하면실수형임을선언하는어찌보면너무나도광범위한선언은프로그램작성과관리차원에서그렇게좋은선택은아니다. 복잡한프로그램을만들다보면, 항상사용하는변수들이선언되게하는 implicit none의힘을느낀다. 뻔한내용의실수들을줄일수있도록도와주는힘. 뻔한실수들을잡아내기가더욱어려울때가종종있다. 전혀예측하지않은형태의착오이기때문이다.

변수선언은

INTEGER, DIMENSION(:), ALLOCATABLE, SAVE, PRIVATE :: ivari_name 처럼사용될수있다. 너무길어지는면이있지만, 변수하나의특성을표현하기위해선어쩔수없다. 실제로는이와같이하지않는경우가많다. INTEGER, ALLOCATABLE :: ivari_name(:) 정도로해두고 private와 save는보통, 상당히앞쪽에서미리따로선언하는경우가많다. 또한재선언을통해서 public 또는 private를확인해줄수있다.

implicit noneprivatesaveinteger .....real*8 .......real*8, allocatable ::integer, allocatable ::logical ..........public :: ..........(부)함수이름, 변수이름, 바로위에서선언된 (가변)배열이름들이포함되는경우가많이있다.

어처구니없는실수를예방하고효율적인프로그래밍을도와준다. Implicit none사용을강력-추천합니다.

Page 24: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

24

!234567890 PROGRAM xxx_1IMPLICIT NONEINTEGER, PARAMETER :: idp=KIND(0.d0)

! CHARACTER*8 fnnd ; CHARACTER*10 fnntCHARACTER(8) fnnd ; CHARACTER(10) fnntLOGICAL ll1,ll2INTEGER ii,jj,i,nnINTEGER :: kk,npt

!REAL*8 aa,piREAL(8) bb,dx,xxREAL(idp) ccREAL(KIND=idp) ddREAL(KIND=idp) :: eeREAL(8) ff

!COMPLEX(idp) zz1,zz2,zz3COMPLEX(idp) :: zz4

!REAL(8), ALLOCATABLE :: xvector(:),xmatrix(:,:)REAL(8), ALLOCATABLE :: yvector(:)REAL(8), ALLOCATABLE :: ymatrix(:,:)REAL(8), ALLOCATABLE :: qvector(:)

!REAL(8) :: sma(3)REAL(8) smb(3)

!CALL DATE_AND_TIME(DATE=fnnd,TIME=fnnt)WRITE(6,*) '____________ ',' date ',fnnd,' time ',fnnt,'____________'

!INQUIRE(FILE='input_file',EXIST=ll1)

!pi=4.0d0*atan(1.0d0)WRITE(6,*) 'pi ',pipi=acos(-1.0d0)WRITE(6,*) 'pi ',pi

IF(ll1)THENWRITE(6,*) 'file is present'ELSEWRITE(6,*) 'file is absent'ENDIF

WRITE(6,*) idp,' idp'll1=.TRUE.ll2=.FALSE.WRITE(6,*) ll1,' ll1'WRITE(6,*) ll2,' ll2'ii=0jj=1kk=-1ll1= (1 == 2)ll2= (1 /= 2)IF(ii >= jj) ll1=.TRUE.IF(ii == jj) ll2=.FALSE.WRITE(6,*) ii,' ii'WRITE(6,*) jj,' jj'aa=0.0_idp ! notebb=0.0d0cc=0.0d0dd=0.0d0zz1=0.0_idpzz2=CMPLX(1.0_idp,2.0_idp) ! notezz3=zz1+zz2zz3=zz1-zz2zz3=zz1*zz2zz3=zz1/zz2zz3=zz1**2aa=REAL(zz3)bb=IMAG(zz3)cc=ABS(zz3)zz4=CONJG(zz3)

WRITE(6,*) aa,' aa'WRITE(6,*) bb,' bb'WRITE(6,*) cc,' cc'WRITE(6,*) dd,' dd'WRITE(6,*) zz1,' zz1'WRITE(6,*) zz2,' zz2'

OPEN(1,FILE='output1',FORM='FORMATTED')WRITE(1,'(i8)') iiWRITE(1,'(2i8)') ii,jjWRITE(1,'(i8,2x,i8)') ii,jjWRITE(1,'(i8,2x,i8,3x,a5)') ii,jj,'ii,jj'WRITE(1,*) aa,' aa'WRITE(1,*) bb,' bb'WRITE(1,*) cc,' cc'WRITE(1,*) dd,' dd'WRITE(1,*) zz1,' zz1'WRITE(1,*) zz2,' zz2'CLOSE(1)

키워드익히기

Page 25: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

25

OPEN(2,FILE='output2',FORM='FORMATTED')WRITE(2,'(i8)') iiWRITE(2,'(2i8)') ii,jjCLOSE(2)

sma=0.0d0smb=1.0d0ii=10jj=10nn=iiALLOCATE(xvector(nn)) ; ALLOCATE(yvector(nn))ALLOCATE(xmatrix(nn,nn))ALLOCATE(ymatrix(nn,nn))ALLOCATE(qvector(0:nn))

IF(ALLOCATED(xvector))THENWRITE(6,*) 'xvector is allocated'WRITE(6,*) 'size ', SIZE(xvector)DO i=1,nnxvector(i)=FLOAT(i)ENDDOyvector=-xvectorENDIFWRITE(6,*) 'sum ', SUM(xvector)WRITE(6,*) 'sum ', SUM(yvector)yvector=SQRT(ABS(xvector))

IF(ALLOCATED(xmatrix))THENWRITE(6,*) 'xmatrix is allocated'WRITE(6,*) 'size ', SIZE(xmatrix)ENDIF

xvector=0.0d0yvector=0.0d0xmatrix=0.0d0ymatrix=TRANSPOSE(xmatrix)ymatrix(:,1)=yvector(:)

yvector=MATMUL(xmatrix,xvector)dd=DOT_PRODUCT(xvector,yvector)

dd=MAXVAL(xvector)ee=MINVAL(yvector)dd=MAXVAL(ABS(xvector))dd=MAXVAL(ABS(xvector-yvector))/(MAXVAL(ABS(xvector))+MAXVAL(ABS(yvector))+1.0d-8)aa=SUM(xvector)/FLOAT(SIZE(xvector))bb=PRODUCT(yvector)

DEALLOCATE(xvector) ; DEALLOCATE(yvector)DEALLOCATE(xmatrix)DEALLOCATE(ymatrix)DEALLOCATE(qvector)

INQUIRE(FILE='del',EXIST=ll1)IF(LL1)THENWRITE(6,*) 'del is present'OPEN(11,FILE='del')CLOSE(31,STATUS='DELETE')

ENDIF

aa=0.0d0bb=1.0d0npt=100000000dx=(bb-aa)/float(npt-1)cc=0.0d0DO i=1,nptxx=aa+float(i-1)*dxcc=cc+ff(xx)ENDDOcc=cc*dxwrite(6,*) cc,' cc'

STOPEND PROGRAM xxx_1

FUNCTION ff(x)REAL(8) ffREAL(8) xff=x*xRETURNEND FUNCTION ff

Page 26: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

26

키워드익히기 프로그램출력물

ihlee@cetus0:~/lecture_programming$ a.out____________ date 20080109 time 152244.148____________pi 3.141592653589793 pi 3.141592653589793 file is absent

8 idpT ll1F ll2

0 ii1 jj

0.0000000000000000 aa0.0000000000000000 bb0.0000000000000000 cc0.0000000000000000 dd

(0.0000000000000000,0.0000000000000000) zz1(1.000000000000000,2.000000000000000) zz2xvector is allocatedsize 10sum 55.00000000000000 sum -55.00000000000000 xmatrix is allocatedsize 1000.3333333283332683 cc

FORTRAN STOPihlee@cetus0:~/lecture_programming$

Page 27: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

27

기존의 프로그램들

현대적 의미로서의 포트란은 새로 만들어지는 코드는 포트란 90으로 작성하며, 기존의 포트란 77로 작성된 코드들은 철저히 재 활용 (recycling)한다는 의미이다. 즉, 검정이 완전히 끝난 코드들 (www.netlib.org, gams.nist.gov)을 다시 포트란 90으로 재작성할 필요는 없으며 그러한 일들은 많은 경우 무의미할 뿐만 아니라 오히려 위험할 수 있다. (물론, 새로운 연구를 위해서는 재 작성되어야 마땅하다.) 프로그램의 테스트와 안정성을 유지하는 것이 그만큼 어려운 것이라는 것을 의미한다. 현대의 컴퓨터 언어를 기술할 때 다음의 사항들이 중점적으로 거론된다. reusability, maintainability, readability, reliability, testability.

http://incredible.egloos.com/321647420세기 TOP 10 알고리듬

모듈개념을활용하면프로그램을이해가쉽다. 확장, 변경용이하다.특정한일들과관계된변수들, 함수들을통합적으로관리할수있다. 함수, 함수통신에서인수들의숫자를줄일수있다. 개발 재사용 재사용

http://docs.sun.com/app/docs/doc/801-5492/6hvudcqa4?l=ko&a=viewC Calls Fortran

Fortran Calls Chttp://docs.sun.com/app/docs/doc/801-5492/6hvudcqa3?l=ko&a=view

Page 28: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

28

Fortran Calls C

void simref_ ( b4, i4, r4, d8 )/* Simple types, passed by reference, from f90 (f90 calls C)*/

int * b4 ;int * i4 ;float * r4 ;double * d8 ;

{*b4 = 1 ;*i4 = 9 ;*r4 = 9.9f ;*d8 = 9.9F ;

}

PROGRAM SimpleRef! Pass some simple types, by reference, to C (f90 calls C)

LOGICAL b4 ! Default kind is 4-byteINTEGER i4 ! Default kind is 4-byteREAL r4 ! Default kind is 4-byteDOUBLE PRECISION d8! This is 8-byteCALL SimRef ( b4, i4, r4, d8 )WRITE( *, '(L4,I4,F6.1,F6.1)') b4, i4, r4, d8

END PROGRAM SimpleRef

ihlee@cetus0:~/lecture_programming$ vi simref.cihlee@cetus0:~/lecture_programming$ vi simplref.f90ihlee@cetus0:~/lecture_programming$ cc -c simref.cihlee@cetus0:~/lecture_programming$ pgf90 simplref.f90 simref.o ihlee@cetus0:~/lecture_programming$ a.out

T 9 9.9 9.9

http://docs.sun.com/app/docs/doc/801-5492/6hvudcqa3?l=ko&a=view

Page 29: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

29

단한번에거대한집을설계하는것이다, 그다음, 그설계도에맞추어서충실히집의구석구석을열심히만들어나가는것이다. 물론, 이러한아이디어자체가나쁘다는것이결코아니다. 아주이성적인선택이며분명히좋은방법임에틀림없다. 하지만, 객체지향적프로그래밍이훨씬프로그래밍효율면에서우위를점한다는것이경험적으로알려지기시작했다.

객체?클래스? 파이썬강좌에서좀더자세히설명하기로합니다.

축구선수: 클래스 (class)호날두 : 객체 (object, instance)

Page 30: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

30

-C 배열에서허용된인덱스의범위를벗어날때프로그램이중단되도록하는옵션 (컴파일할때사용하는옵션)

real*8 a(3,2),yone(6) 은 3*2=6 개의실수를가리키는이차원배열을정의한다. 처음숫자는열(row)를가리키는숫자로두번째는행(column)을가리키는숫자이다. 이를굳이 1차원형태의자료로생각할경우포트란에서는아래의경우처럼취급한다.a(1,1) a(2,1) a(3,1) a(1,2) a(2,2) a(3,2)ij=3*(j-1)+i a(i,j)로표시할때일차원인덱싱(yone이라는일차원배열, 물론, 이배열의크기는 6이다.)은결국위와같이될수있습니다. do i=1,3do j=1,2ij=3*(j-1)+iyone(ij)=a(i,j)enddoenddoakvector(natom,3,nk)와같은배열을특정한형식의 1차원배열로바꾸는(사용자정한형식) 예를아래에표시했다.do iatom=1,natomkp=3*nk*(iatom-1)do k=1,nkxone(kp+3*(k-1)+1)=akvector(iatom,1,k)xone(kp+3*(k-1)+2)=akvector(iatom,2,k)xone(kp+3*(k-1)+3)=akvector(iatom,3,k)enddoenddo

이러한배열의차원변경은실제응용프로그램작성에서중요한의미를가진다. 일반으로물리량은다차원배열일때이해하기가쉽다. 하지만, 전산물리학에서는이양들이단순한변수일뿐이라면, 전산학에서제시하는루틴들은동등하게취급하는특정 1차원배열일가능성이농후하다. 이때결국위와같은조작이유용하다.

-c 옵션은 object파일만만든다는뜻이다.

Page 31: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

31

Subroutine, function(부함수)의인수는통신될때, 정확히같은수형을유지해야한다.예를들어 double precision으로불렀으면, 해당부함수에서반드시 double precision에해당하는변수로받아야한다. 부함수에사용된인수들은계속해서지속적으로사용된다. (값이바뀔수있다.)

메인함수에서 A(3,2)로선언되어사용되다가서브루틴으로전송될때.subroutine abc1(a)implicit nonereal*8 a(3,1)

subroutine abc2(a)implicit nonereal*8 a(3,2)

위의둘다정당한선언이된다. 물론, 두번째가더정확한선언이다. 하지만, 첫번째선언도정당하다. 하지만, 아래의경우는거의에러를포함한코드일것이다. (데이터의구조를파괴하고있기때문이다.)subroutine abc3(a)implicit nonereal*8 a(1,2)

가장많이사용될수있는형태 (포트란 77에서)subroutine abc4(a,lda)implicit noneinteger ldareal*8 a(lda,1)

포트란에서는앞에있는인자들이먼저바뀌고난후에뒤쪽의인수들이바뀌게된다.a(3,3)인경우, a(1,1), a(2,1), a(3,1), a(1,2), a(2,2), a(3,2), a(1,3),a(2,3),a(3,3) 순서대로일차원배열에대응될수있다.이때, 일차원배열, 예를들면, b(9)처럼사용할수있는배열의길이는같아야한다.

Page 32: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

32

implicit noneinteger minteger j

!read(5,*) mdo j=2,mcall test_prime(j)end dostopendsubroutine test_prime(n)implicit noneinteger ninteger kif( n <=1 ) returnif( n == 2) write(6,*) n,' is a prime'if( n == 2) returnk=2

30 if (n/k*k == n) goto 70k=k+1if(k <= n/2) go to 30write(6,*) n,' is a prime'return

70 continuewrite(6,*) n, ' is not a prime'returnend

ihlee@cetus0:~/lecture_programming$ a.out20

2 is a prime3 is a prime4 is not a prime5 is a prime6 is not a prime7 is a prime8 is not a prime9 is not a prime10 is not a prime11 is a prime12 is not a prime13 is a prime14 is not a prime15 is not a prime16 is not a prime17 is a prime18 is not a prime19 is a prime20 is not a prime

FORTRAN STOPihlee@cetus0:~/lecture_programming$

Page 33: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

33

!234567890implicit noneinteger nm,n,matz,ierrreal*8, allocatable :: ar(:,:),ai(:,:),w(:),zr(:,:),zi(:,:),fv1(:),fv2(:),fm1(:,:)real*8 tmpinteger i,j,kmatz=0matz=1nm=3n=nmopen(1,file='input',form='formatted')read(1,*) nclose(1)write(6,*) n,' n'allocate(ar(nm,n),ai(nm,n),w(n),zr(nm,n),zi(nm,n),fv1(n),fv2(n),fm1(2,n))do i=1,ndo j=1,i ! 소위 lower-triangular-form으로저장하고있습니다.

!------[ set up the hermitian matrix : lower triangular formar(i,j)=dfloat(i+j)**2ai(i,j)=1.d0/dfloat(i-j)if(i == j) ai(i,j)=0.0d0 hermitian 이기때문에반드시만족해야함enddoenddodo i=1,ndo j=1,iar(j,i)=ar(i,j)ai(j,i)=-ai(i,j)enddoenddocall ch(nm,n,ar,ai,w,matz,zr,zi,fv1,fv2,fm1,ierr)write(6,*) 'eigenvalues'do i=1,nwrite(6,*) w(i)enddowrite(6,*) 'eigenvectors'do j=1,nwrite(6,*) (dcmplx(zr(k,j),zi(k,j)),k=1,n)enddodo i=1,ndo j=1,ntmp=0.0d0do k=1,ntmp=tmp+dcmplx(zr(k,i),-zi(k,i))*dcmplx(zr(k,j),zi(k,j))enddowrite(6,*) i,j,tmpenddoendddeallocate(ar,ai,w,zr,zi,fv1,fv2,fm1) ! 더이상필요하지않은배열들의메모리할당을풀어줍니다.stopend

입력3

출력

3 neigenvalues

-3.295706627065439 0.2569711761519913 59.03873545091345

eigenvectors(0.7426815277007046,0.2134499083118499) (0.3321344158486125,-0.1647469485075425) (-0.5151780835984430,0.000000000000000)(-0.4017627191549581,-0.3764084131040000) (0.7336179945919501,0.2195919189859811) (-0.3323965270105607,0.000000000000000)(0.3152758193792096,-1.9179854283106629E-002) (0.5252646650262870,-1.5040996247447431E-002) (0.7900025892433221,0.000000000000000)

1 1 0.9999999999999998 1 2 -2.6099456797157305E-0161 3 -2.2218013019659200E-0162 1 -2.6099456797157305E-0162 2 0.9999999999999998 2 3 -2.0545631168600309E-0163 1 -2.2218013019659200E-0163 2 -2.0545631168600309E-016

3 3 0.9999999999999996

Page 34: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

34

program conjugate_gradientimplicit noneinteger iters, its, nlogical :: convergedreal*8 :: tol, up, alpha, betareal*8, allocatable :: a(:,:), b(:), x(:), r(:), u(:), p(:), xnew(:)

read(5,*) n, tol, itsallocate( a(n,n), b(n), x(n), r(n), u(n), p(n), xnew(n) ) 적절한메모리확보open(10, file='data')read(10,*) aread(10,*) bclose(10)

x=1.d0 ! 모든컴포넌트가 1.d0로초기화됩니다.r=b-matmul(a,x) ! 군더더기가하나도없군요. 당연히매트릭스곱하기벡터죠.p=r ! 벡터가복사됩니다.iters=0do ! do loop 형식입니다.

iters=iters+1u=matmul(a,p)up=dot_product(r,r) !당연히내적(inner product)이죠. alpha=up/dot_product(p,u)xnew=x+p*alphar=r-u*alpha ! 여기서알파는숫자입니다.beta=dot_product(r,r)/upp=r+p*beta ! beta는숫자입니다.converged=(maxval(abs(xnew-x))/maxval(abs(x)) < tol) ! 컴포넌트들다조사하면서가장큰컴포넌트를찾습니다.x=xnew !당연히벡터의복사이지요.if( converged .or. iters == its) exit ! do 루프의탈출신호입니다.

enddo

write(6,*) iterswrite(6,*) xdeallocate( a,b,x,r,u,p,xnew ) ! 이제는필요없어요. 토사구팽end program conjugate_gradient

Page 35: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

35

module common_dataimplicit noneprivate ! 일단이렇게 ‘사적인형식을기본으로’ 시작하겠습니다. 아래에나오는모두는 ‘사적’이다. (선언을통해서 default를바꾸었다고볼수도있다.)saveinteger iii1,jjj1real*, allocatable :: aa1(:,:),bb1(:)logical first_call! 첫번째로모듈이사용되는경우가중요한경우가있다. ! 이를위해서전역변수로선언해둘수있다. 초기화를 .true.로해두고, 나중에 .false.로바꿀수있다.character*2, allocatable :: ccc1(:)

.........

public :: aa1,bb1,iii1 ! 앞서 ‘사적’이라고했지만, 다시한번더확실하게부탁의말씀을드리는꼴이다. (이 ‘선언’이채택이된다.)

end module common_data

module common_data2implicit noneprivatesave.........public :: ..........

end module common_data2

포트란모듈설명참조: http://incredible.egloos.com/2950367

다른곳에서사용될함수, 서브루틴, 변수, 가변배열, 배열등은 public 속성을가진다고선언해야한다.선언하지않으면 public이다. 즉, 선언할때, default는 public이다.

모듈: 변수들만으로구성될수도있다.모듈: 부함수들만으로구성될수도있다. Interface문들만으로도구성될수있다.통상, 모듈은특정변수들, 이변수들에연관된부함수들로구성되기마련이다.

모듈

특정한변수들의모임, 이에집중적으로연관이있는연산들을통틀어서한모듈에저장할수있다.

Page 36: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

36

모듈모듈((호스트호스트))의의 CONTAINSCONTAINS문문다음에다음에부함수들부함수들((서브루틴들서브루틴들, , 함수들함수들))이이위치할위치할수수있다있다..ENDEND문문다음에다음에 FUNCTION FUNCTION 또는또는 SUBROUTINESUBROUTINE을을반드시반드시넣어야넣어야한다한다..End function End function fnamefname, end subroutine , end subroutine snamesname등의등의형식으로형식으로끝나야끝나야한다한다..호스트에서호스트에서선언된선언된변수변수또는또는가변배열들은가변배열들은내부내부부함수들에서부함수들에서사용사용가능하다가능하다. . 변경변경가능하다가능하다..

http://www.liv.ac.uk/HPC/HTMLHPFCourse/HTMLHPFCourseSlidesnode142.html

Page 37: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

37

MODULE globy1implicit nonereal*8, save :: xglobal_variable1,xglobal_variable2 ! 이러한 경우 default를 따라서 모두 다 public하다.integer, save :: jglobal1,jglobal2END MODULE globy1 ! 하나의 데이터 저장 창고이다. 가장 간단한 예이다.! 필요에 따라서 아래의 예에서와 같이 각종형태의 가변배열도 선언할 수 있다. integer, allocatable :: ijk(:)---------------------------------MODULE globy2implicit nonePUBLICSAVEreal*8 global_variable1,global_variable2 integer iglobal1,iglobal2END MODULE globy2

PROGRAM main1USE globy1 ! implicit none보다 위에 위치한다. ! 컴파일할 때도 마찬가지이다. "globy1"를 가지고 있는 상황에서 컴파일이 진행될 수 있다. USE globy2, ONLY : iglobal1IMPLICIT NONEREAL*8 a1,a2,a3INTEGER ia1,ia2,ia3

READ(5,*) igloval1READ(5,*) global_variable1,global_variable2

!................중략.........................

END PROGRAM main1

Page 38: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

38

하나의창고라고생각할수있다. 창고를속의내용물을원하면사용할수있다.!234567890

MODULE wf_wrIMPLICIT NONEsavepublicinteger nsimreal*8 temperreal*8, allocatable :: wf(:),wr(:)END MODULE wf_wr

! 메인프로그램바로시작해도된다. 아래와같이USE wf_wrIMPLICIT NONEreal*8 tol,sol,sol1,sol2real*8 tmpinteger ireal*8 bennetteq,zerointemper=1.d0 ; nsim=10allocate(wf(nsim),wr(nsim))wf=1. ; wr=-1.do i=1,nsimcall random_number(tmp)wf(i)=wf(i)+0.2*(tmp-0.5)call random_number(tmp)wr(i)=wr(i)+0.2*(tmp-0.5)enddosol1=maxval(wf) ; sol2=minval(wf)write(6,*) sol1,bennetteq(sol1)write(6,*) sol2,bennetteq(sol2)tol=1.d-16sol=zeroin(sol1,sol2,bennetteq,tol) ! 이함수는 netlib에서다운로드받은함수이다. root finding 프로그램이다. 유저가공급할함수명: 이경우 bennetteq이다.write(6,*) sol,bennetteq(sol)deallocate(wf,wr)stopend

function bennetteq(sol) ! 유저가 사용할 함수

USE wf_wrIMPLICIT NONEreal*8 solreal*8 bennetteqinteger ibennetteq=0.0d0do i=1,nsimbennetteq=bennetteq+1.0d0/(1.d0+exp((wf(i)-sol)/temper))-1.0d0/(1.d0+exp((wr(i)+sol)/temper))enddoreturnend

Page 39: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

39

USE 모듈명, ONLY : 모듈속변수이름들, 함수이름들

당연히 public한속성을가지는함수들, 변수들만이다른곳에서사용가능하다.“USE”보다는 “USE ONLY”를사용하는것이더유용한방식이다.예상하지못한 “충돌”도현명하게피할수있다.

모듈을작성할때는 save, public (또는 private)기능들을확실히사용하고, 모듈을이용할때는이들을꼭확인한다. 각각의루틴을작성할때 implicit none을항상사용한다. 남이만든모듈과내가만든프로그램상에서우연히서로다른변수를의미함에도불구하고변수이름이동등할수있다. 이경우그숫자가너무많지않고오해의소지가없다면간단히변수이름을재명명함으로써슬기롭게문제를피해갈수있다. 이것또한포트란 90의장점이다. 위에서지적한 implicit none은모든변수들의속성이반드시선언되어야한다는의미이다. 즉, 뒤따르는줄에서실수형, 문자형, 배열형, 정수형, 논리형등이구체적으로정의되어야만한다는의미이다. 그렇지않은변수들의리스트를컴파일시보여주고더이상의컴파일을진행하지않는다. 포트란에서는컴파일할때보통 -C 옵션을이용하면배열의한도를넘는배열참조에관련된에러발생위치를실행할때보여주고실행이중단된다. 프로그램개발단계에서필요한옵션이다.

USE stack, local_use_pop => poppop가특정함수에서국소적으로사용될때, stack 모듈속의 pop는 local_pop로재명명되었다.

USE stack, ONLY: pos, local_pop=> pop모듈 stack속의 pos와 pop만이사용가능하다. 다만, 이경우모듈속 pop의경우 local_pop로이름이다시만들어졌다.

모든모듈들은그것을사용하는프로그램단위보다먼저컴파일되어야한다. 이렇게되기위해서는 makefile에서아래와같은프로그램들간의의존성이필요하기도하다. 즉, 프로그램 ximage_lbfgs.f90은모듈 timpose.f90를사용하게되어있다. 이때이모듈은다른파일속에있는것이며이전에만들어진것이다.

USE aaaUSE bbb ! 모듈 bbb에서 public한모든변수, 배열, 또는부프로그램(function, subroutine)들은모두사용할수있다.USE cccUSE ddd, ONLY: qqq,ppp ! 모듈 ddd에서사용하고자하는변수, 배열, 또는부프로그램 (subroutine, function) 이름들을적어둔다.

Page 40: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

40

implicit none 다음라인에는각종변수, 함수값, (가변) 배열들이선언될수있다. 상당히짧은프로그램의경우위와같은형식으로해결될수있다. 일반으로, 사용되는모듈들의숫자가많아질수록대부분의경우여러개의파일들을사용한다. 보통한파일속에모듈하나를넣어두는경우가많다. 위의경우에는모듈들은데이터저장창고로사용된예이다. 하지만, 모듈은특정데이터들을보관할뿐만아니라관련된데이터처리를할수있도록설계되었다. 즉, 모듈= {데이터들}+{데이터처리부함수들}이기때문이다. 모듈이변수들없이함수들만포함(contain)할수도있다. 반대로변수들만가질수도있다.

모듈속의서브루틴에서이모듈속에속하지않는외부의서브루틴, 함수들도당연히사용할수있다. 독립적으로선언된모듈속의내용(변수들, 부함수들)이라면당연히 USE를사용해야한다. 예전에만들어진포트란 77 프로그램과함께연동될경우, 특히, common문이있는경우에도 common문을그냥사용해도된다. 왜냐하면포트란 90은포트란 77을다이해하기때문이다.

현모듈내에서만사용되는부함수가일반으로많이있을수있다. 인수가있을수도없을수도있다. 물론, 목적과설계에따라서달라질수있다. 모듈속에서선언된전역변수들만집중적으로취급하는경우는모듈속서브루틴, 함수들은인수의숫자가적어질수밖에없다. 물론, 모듈외부와통하는경우에는일반으로인수들의숫자가증가할가능성이많을것이다.

다른곳에서사용될함수, 서브루틴, 변수, 가변배열, 배열등은 public 속성을가진다고선언해야한다.선언하지않으면 public이다. 즉, 선언할때, default는 public이다.

Page 41: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

41

cmpl=pgf90segl=pgf90Ocft= -c -fastcft= -c#LINK=-L/usr/lib/xmm -L/usr/lib/xmm/atlasLINK= -L/usr/lib/sse2LIBS = -llapack -lf77blas -latlas -lf2cAMD= amd.o predictor_corrector_nose.o energy_force.o tight_binding_lapack_c.o \

mini_driver.o minimization.o lbfgs.o bond_boost.o erf.o maxwell_boltzmann.o \check_transition.o rmarin.o angle_boost.o dihedral.o dihedral_boost.o

amd.x: $(AMD)$(segl) -o amd.x $(AMD) $(LINK) $(LIBS)

amd.o:amd.f90 predictor_corrector_nose.o bond_boost.o angle_boost.o dihedral_boost.o$(cmpl) $(Ocft) amd.f90

energy_force.o:energy_force.f90 tight_binding_lapack_c.o$(cmpl) $(Ocft) energy_force.f90

tight_binding_lapack_c.o:tight_binding_lapack_c.f90$(cmpl) $(Ocft) tight_binding_lapack_c.f90

predictor_corrector_nose.o:predictor_corrector_nose.f90$(cmpl) $(Ocft) predictor_corrector_nose.f90

mini_driver.o:mini_driver.f90$(cmpl) $(Ocft) mini_driver.f90

minimization.o:minimization.f90$(cmpl) $(Ocft) minimization.f90

bond_boost.o:bond_boost.f90$(cmpl) $(Ocft) bond_boost.f90

angle_boost.o:angle_boost.f90$(cmpl) $(Ocft) angle_boost.f90

dihedral_boost.o:dihedral_boost.f90 dihedral.o$(cmpl) $(Ocft) dihedral_boost.f90

dihedral.o:dihedral.f90erf.o:erf.f

$(cmpl) $(Ocft) erf.f

clean:rm -f *.x *.o *.mod *.M core*

touch:touch *.f90 *.i makefile ; chmod 600 *.f90 *.i makefile ; ls -l *.f90 *.i makefile

rmo:rm -f *.o *.mod *.M core*

lsl:ls -l *.f90 makefile *.i

Program Source File

Fortran 90Compiler

Fortran 90Compiler

Linker

Module Source File

Program Object File

Module Object File

Program Executable File

Program Source File

Fortran 90Compiler

Fortran 90Compiler

Linker

Module Source File

Program Object File

Module Object File

Program Executable File

프로그램을체계적으로컴파일할때, makefile을사용한다.실제컴파일은명령어 make를사용한다.

ls -ltra 는변화된파일들의시간순서상으로파일들을보여줍니다.ls -Fs는디렉토리표시와파일사이즈크기표시

make cleanmake

Page 42: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

module metricimplicit nonereal*8 aa,bb,cc,ddend module metric

program abcUSE metricimplicit nonereal*8 sol1,sol2,tolreal*8 sol,xreal*8, external :: func,zeroininteger iaa=0.d0bb=-2.d0cc= 1.d0dd=2.d0

!sol1=-1.0d0sol2= 0.1d0write(6,*) sol1,func(sol1)write(6,*) sol2,func(sol2)tol=1.d-16 ; sol=zeroin(sol1,sol2,func,tol)write(6,*) sol,func(sol),' sol, f(sol)'sol1=-3.0d0sol2=-1.9d0write(6,*) sol1,func(sol1)write(6,*) sol2,func(sol2)tol=1.d-16 ; sol=zeroin(sol1,sol2,func,tol)write(6,*) sol,func(sol),' sol, f(sol)'sol1= 0.9d0sol2= 1.1d0write(6,*) sol1,func(sol1)write(6,*) sol2,func(sol2)tol=1.d-16 ; sol=zeroin(sol1,sol2,func,tol)write(6,*) sol,func(sol),' sol, f(sol)'sol1= 1.9d0sol2= 2.1d0write(6,*) sol1,func(sol1)write(6,*) sol2,func(sol2)tol=1.d-16 ; sol=zeroin(sol1,sol2,func,tol)write(6,*) sol,func(sol),' sol, f(sol)'stopend program abc

real*8 function func(x)USE metricimplicit nonereal*8 xfunc=(x-dd)*(x-aa)*(x-bb)*(x-cc)returnend

-1.000000000000000 -6.0000000000000000.1000000000000000 0.35910000000000002.7076140240079107E-019 1.0830456096031642E-018 sol, f(sol)-3.000000000000000 60.00000000000000-1.900000000000000 -2.148900000000002-2.000000000000000 0.0000000000000000 sol, f(sol)0.9000000000000000 0.28709999999999991.100000000000000 -0.30690000000000031.000000000000000 0.0000000000000000 sol, f(sol)1.900000000000000 -0.66690000000000052.100000000000000 0.94710000000000092.000000000000000 0.0000000000000000 sol, f(sol)

FORTRAN STOP

많은함수들이인수하나만가지는형식으로지원된다.

하지만, 유저입장에서, 현재응용문제는인수하나만으로사용자정의함수가정의되지않기마련이다. 이때, 소위, ‘기타’ 입력들은하나의모듈(이경우변수창고수준이다.)을통하여접근할수있다.

Cf.포트란 77에서 common문을사용하는이유와사실상같은양식이다.

42설명참조: http://incredible.egloos.com/3040113

Page 43: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

43

module dihedral_angle! Written by In-Ho Lee, KRISS, October 4 (2003).

implicit noneprivatesavereal*8 diangle,dadi(3),dadj(3),dadk(3),dadl(3)public :: mk_diangle,diangle,dadi,dadj,dadk,dadlcontainssubroutine mk_diangle(ri,rj,rk,rl)implicit nonereal*8 ri(3),rj(3),rk(3),rl(3)real*8 rij(3),rkj(3),rkl(3),xnorm_ij_kj,xnorm_kj_klreal*8 rij_kj(3),rkj_kl(3),rtmp(3),xnorm_kj,xnorm_mj,xnorm_nkreal*8 rmj(3),rnk(3),xxr,xxireal*8 argu,qsignrij=ri-rj ; rkj=rk-rj ; rkl=rk-rlcall cross(rij,rkj,rij_kj)call cross(rkj,rkl,rkj_kl)call cross(rij_kj,rkj_kl,rtmp)xnorm_ij_kj=sqrt(dot_product(rij_kj,rij_kj))xnorm_kj_kl=sqrt(dot_product(rkj_kl,rkj_kl))argu=dot_product(rij_kj,rkj_kl)/(xnorm_ij_kj*xnorm_kj_kl) ; argu=min(1.0d0,max(-1.0d0,argu))qsign=1.0d0 ; if(dot_product(rkj,rtmp) < 0.0d0) qsign=-1.0d0diangle=qsign*acos(argu)call cross(rij,rkj,rmj)call cross(rkj,rkl,rnk)xnorm_kj=sqrt(dot_product(rkj,rkj))xnorm_mj=sqrt(dot_product(rmj,rmj))xnorm_nk=sqrt(dot_product(rnk,rnk))dadi(:)=rmj(:)*xnorm_kj/xnorm_mj**2dadl(:)=-rnk(:)*xnorm_kj/xnorm_nk**2xxr=dot_product(rij,rkj)/xnorm_kj**2-1.0d0xxi=dot_product(rkl,rkj)/xnorm_kj**2dadj(:)=xxr*dadi(:)-xxi*dadl(:)xxr=dot_product(rkl,rkj)/xnorm_kj**2-1.0d0xxi=dot_product(rij,rkj)/xnorm_kj**2dadk(:)=xxr*dadl(:)-xxi*dadi(:)dadi=dadi*qsigndadj=dadj*qsigndadk=dadk*qsigndadl=dadl*qsignend subroutine mk_dianglesubroutine cross(r1,r2,r3)implicit nonereal*8 r1(3),r2(3),r3(3)r3(1) = r1(2)*r2(3)-r1(3)*r2(2)r3(2) = r1(3)*r2(1)-r1(1)*r2(3)r3(3) = r1(1)*r2(2)-r1(2)*r2(1)end subroutine crossend module dihedral_angle

Dihedral angle

Page 44: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

44

!234567890implicit nonereal*8, external :: funcreal*8 rslt,aa,bbinteger nn=100aa=0.0d0bb=1.0d0

call simpson(func,n,aa,bb,rslt)write(6,*) rslt,' rslt'

stopend

subroutine simpson(func,n,aa,bb,rslt)implicit nonereal*8 funcinteger nreal*8 rslt,aa,bbreal*8 h,xxinteger jlogical loddh=(bb-aa)/float(n)rslt=(func(aa)+func(bb))lodd=.true.do j=1,n-1xx=aa+h*float(j)

if(lodd)thenrslt=rslt+4.0d0*func(xx)else

rslt=rslt+2.0d0*func(xx)endiflodd=(.not. lodd)enddorslt=rslt*h/3.0d0returnendreal*8 function func(x)implicit nonereal*8 xfunc=x*x

returnend

----------------------------------------------0.3333333333333334 rsltFORTRAN STOP

설명참조: http://incredible.egloos.com/3021478

Composite Simpson's rule적분구간: [a,b]step length: h=(b-a)/nx_i=a+i hi=0,1,2,3,....,n-1,n여기서 n은짝수이다.x_0=ax_n=b

여기서 n은 even number 이다.

Page 45: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

45

수치미분, Fornberg 공식 (포트란)

Uniform grid상에함수값이존재하지않아도된다. (nonuniform grid지원)좌측, 우측의유한한개수의함수값들을활용한다. (임의로줄수있다.)미분, 인터폴레이션둘다수행할수있다. 0회미분=인터폴레이션(k=0)k=1 (일차미분)k차미분이수행되는점은 grid상의점이아니라도가능하다.

f(x)

설명참조: http://incredible.egloos.com/3032905

Page 46: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

46

subroutine weights(xi,x,n,m,c)! purpose: computes weights for the mth derivative on arbitrarily! spaced points! Jan 04, 1996 declare all variables! date: Nov 15, 1995 (copied from Fornberg)! written by In-Ho Lee, Beckman Inst., UIUC, April 13 1997.! +real_constant=double option in HP f90! +--------------------------------------------------------------------+! | INPUT PARAMETERS: |! | xi point at which the approximations are to be accurate |! | x x-coordinates for the grid points, array dimensioned x(0:n) |! | n the grid points are at x(0),x(1),...x(n) (i.e. n+1 in all) |! | m highest order of derivative to be approximated |! | |! | OUTPUT PARAMETERS |! | c weights, array dimensioned c(0:n,0:n,0:m) |! | on return, the element c(j,k,i) contains the weight to be |! | applied at x(k) when the i:th derivative is approximated |! | by a stencil extending over x(0),x(1),...,x(j). |! +--------------------------------------------------------------------+!

implicit real*8 (a-h,o-z)dimension x(0:n),c(0:n,0:n,0:m)c(0,0,0)= 1.0d0c1 = 1.0d0c4 = x(0)-xido 40 j=1,n

mn = min(j,m)c2 = 1.0d0c5 = c4c4 = x(j)-xido 20 k=0,j-1

c3=x(j)-x(k)c2=c2*c3if (j.le.m) c(k,j-1,j)=0.0d0c(k,j,0) =c4*c(k,j-1,0)/c3do 10 i=1,mn

10 c(k,j,i)=(c4*c(k,j-1,i)-i*c(k,j-1,i-1))/c320 continue

c(j,j,0)=-c1*c5*c(j-1,j-1,0)/c2do 30 i=1,mn

30 c(j,j,i)=c1*(i*c(j-1,j-1,i-1)-c5*c(j-1,j-1,i))/c240 c1=c2

returnend

수치미분, Fornberg 공식 (포트란)

Fornberg 교수가개발한 Finite difference 와관련된공식이다. 특히, high-order 미분을가능하게하는공식이다. 물론수치계산용프로그램이다.Finite-difference 분야에서상당히유용한공식이다.관련프로그램을들여다보니거의 10년이되었다. 당시에도그렇게생각했지만, 지금보아도놀라운공식이다. 저렇게짧은코드로도정말많은것들(인터폴레이션, 미분: 다양한정밀도와환경에서)을계산할수있는공식이다. 주어진그리드에서, 원하는위치에서, 원하는정밀도로 m 차미분을계산할수있다.좌측, 우측, 또는한쪽방향에서만정의된함수로부터도계산이가능하다. 얼마나많은정보를사용할것인지도입력으로조절가능하다. 균일간격이아니라도상관없다.

Finite difference:http://en.wikipedia.org/wiki/Finite_differencehttp://mathworld.wolfram.com/FiniteDifference.htmlhttp://en.wikipedia.org/wiki/Numerical_differentiation

Page 47: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

47

!234567890module rk_dfimplicit nonepublicsaveinteger neq,info(15),idid,lrw,liwreal*8 t, toutinteger, allocatable :: iwork(:),ipar(:)real*8, allocatable :: y(:), rwork(:), rtol(:), atol(:), rpar(:) containssubroutine initialimplicit nonet=0.0d0tout=0.1d0neq=3allocate(y(neq))y(1)=0.d0y(2)=1.d0y(3)=1.d0info(1)=0lrw= 33+7*neq ; liw= 34allocate(iwork(liw)) ; allocate(rwork(lrw))allocate(atol(neq),rtol(neq))rtol=1.d-10 ; atol=1.d-10allocate(rpar(neq)) ; allocate(ipar(neq))end subroutine initialsubroutine finalimplicit nonedeallocate(y) ; deallocate(rwork) ; deallocate(iwork)deallocate(atol,rtol) ; deallocate(rpar) ; deallocate(ipar)end subroutine final

! DF(X,U,UPRIME,RPAR,IPAR) x, u가이서브루틴에서바뀌면안된다.! uprime()만계산해주세요.

subroutine df(x,u,uprime,rpar_z,ipar_z)implicit nonereal*8 x,u(1)real*8 rpar_z(1)integer ipar_z(1)real*8 uprime(1)uprime(1)=u(2)*u(3)uprime(2)=-u(1)*u(3)uprime(3)=-0.522d0*u(1)*u(2)end subroutine dfend module rk_df

!

program rk_testUSE rk_df, ONLY : neq, t, y, tout, info, rtol, atol, idid, rwork, lrw, iwork, liw, rpar, iparUSE rk_df, ONLY : df,initial,finalimplicit nonecall initial

call dderkf(df, neq, t, y, tout, info, rtol, atol, idid, rwork, lrw, iwork, liw, rpar, ipar)! write(6,*) t,' t'

write(6,*) tout,' tout'write(6,*) y,' y'write(6,'(i5,1x,a4)') idid,'idid'write(6,'(15i5,1x,a4)') info,'info'tout=tout+0.1d0call dderkf(df, neq, t, y, tout, info, rtol, atol, idid, rwork, lrw, iwork, liw, rpar, ipar)

! write(6,*) t,' t'write(6,*) tout,' tout'write(6,*) y,' y'write(6,'(i5,1x,a4)') idid,'idid'write(6,'(15i5,1x,a4)') info,'info'

tout=tout+0.1d0call dderkf(df, neq, t, y, tout, info, rtol, atol, idid, rwork, lrw, iwork, liw, rpar, ipar)

! write(6,*) t,' t'write(6,*) tout,' tout'write(6,*) y,' y'write(6,'(i5,1x,a4)') idid,'idid'write(6,'(15i5,1x,a4)') info,'info'

call finalend program rk_test

allocate(vector(-89:100)) 처럼정의될수있다. -89, -88, -87,.....98, 99, 100. 즉, allocate(vector(100)) 는크기가 100인 vector가생성됨을의미한다. 물론, 1부터시작하여 100까지간다는말이다. allocate(vector(1:100))과동등한표현이다. 디폴트가 1부터시작한다는이야기입니다.

설명참조: http://incredible.egloos.com/3143433

Page 48: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

48

결과물파일에적기

implicit noneinteger j,iinteger narr,mrefreal*8, allocatable :: xarr(:,:)real*8, allocatable :: yarr(:,:)logical lexistnarr=10mref=3allocate(xarr(narr,mref))allocate(yarr(narr,mref))

inquire(file='fort.12',exist=lexist)if(lexist)thenopen(12,file='fort.12',form='unformatted')read(12) yarr(:,:)close(12)

endifdo j=1,mrefdo i=1,narrxarr(i,j)=float(i)**2/float(j)enddoenddowrite(6,*) maxval(abs(xarr-yarr))open(12,file='fort.12',form='unformatted')write(12) xarr(:,:)close(12)deallocate(xarr)deallocate(yarr)stopend

implicit noneinteger j,iinteger narr,mrefreal*8, allocatable :: xarr(:,:)real*8, allocatable :: yarr(:,:)logical lexistnarr=10mref=3allocate(xarr(narr,mref))allocate(yarr(narr,mref))

inquire(file='fort.2',exist=lexist)if(lexist)thenopen(2,file='fort.2',access='direct',recl=8*narr,form='unformatted')do j=1,mrefread(2,rec=j) yarr(:,j)enddoclose(2)

endifdo j=1,mrefdo i=1,narrxarr(i,j)=float(i)**2/float(j)enddoenddowrite(6,*) maxval(abs(xarr-yarr))open(2,file='fort.2',access='direct',recl=8*narr,form='unformatted')do j=1,mrefwrite(2,rec=j) xarr(:,j)enddoclose(2)deallocate(xarr)deallocate(yarr)stopend Access: direct, serial 두 종류가 있다. Default는 serial이다.

Form: formatted, unformatted 두 종류가 있다. Default는 formatted이다.

설명참조 : http://incredible.egloos.com/3044815

Page 49: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

49

READ(*,100) i,jWRITE(*,100) i,jREAD(*,FMT=200) x,yWRITE(*,200) x,y100 FORMAT(2I) 200 FORMAT(2F10.6)

READ(*,'(2I)') i,jWRITE(*,'(2F12.6)') x,y

WRITE(6,`(2F12.6)`) 12.6, -131.45678

INTEGER :: i, j REAL, DIMENSION(10) :: a REAL, DIMENSION(10,10) :: b READ(*,*) (a(j),j=1,10) WRITE(*,*) (a(j), j=10,1,-1) WRITE(*,*) ((b(i,j),i=1,10), j=1,10)

파일에데이터를적는방법들은여러가지가있다.우선 formatted, unformatted형식을들수있다. Unformatted형식은사람이알아볼수없는형식이다.읽고/쓰는속도가빠르다. 파일사이즈도작다. 시스템호환이안될수있다.form=‘formatted’

serial, direct 접근이있다. Direct 접근은 CD에서음악을들을때, 3 번째곡을듣고다음에바로 7번째곡을듣는것처럼직접적으로접근할수있다는뜻이다. access=‘direct’이경우, 한곡이차지하는 ‘디스크용량’을미리정해두어야한다. 이를 recl라고한다. Record length.

Page 50: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

50

open(11,file=‘abcd.txt’, form=‘unformatted’, access=‘direct’, recl=8*nnsszz)

………..write(11,rec=k) (aa(i),i=1,nnsszz)…………..

Unformatted양식은기계가읽고적을수있는양식이다.

Unit number라고부른다.

read(11,rec=kk) (bb(j),j=1,nnsszz)

적을수있는/읽을수있는충분한공간(record length)를확보하고여러가지형식으로사용할수있다.Unformatted 양식으로 read/write속도가뛰어나다. 파일규모가크게줄어든다.시스템의존성이있을수있다.

cf.netCDF, HDFhdf.ncsa.uiuc.edu/products/hd5/index.html

Page 51: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

51

Inquiry list 프로그램실행중질의할수있는아이템들

사용예

EXIST=lex ! .true. or .false. OPENED=lod ! .true. or .false. NUMBER=unum ! unit number NAME=fnm ! filename ACCESS=acc ! 'DIRECT' or 'SEQUENTIAL' SEQUENTIAL=seq ! 'YES or 'NO' DIRECT=dir ! 'YES' or 'NO' FORMATTED=fmt ! 'YES' or 'NO' UNFORMATTED=unfmt ! 'YES' or 'NO' FORM=frm ! 'FORMATTED' or 'UNFORMATTED' NEXTREC=recn ! number of next record RECL=recl ! record length

inquire(file='fort.40',exist=lexist)if(lexist)then…else……….endif

allocated(abc) 처럼가변배열 abc가사용할수있는메모리를할당받았는지물어볼수있다..true., .false.값을반환한다.if(allocated(abc)) deallocate(abc)if(.not. allocated(abc)) allocate(abc(0:100))처럼사용될수있다.

Page 52: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

52

implicit nonereal*8, allocatable :: xdata(:),ydata(:)character*15, file_a,file_binteger j,jtemp,ndatareal*8 rr,prob,zzwrite(6,*) 'Enter: ndata'read(5,*) ndatawrite(6,*) 'Enter: file_A'read(5,*) file_awrite(6,*) file_awrite(6,*) 'Enter: file_B'read(5,*) file_bwrite(6,*) file_ballocate(xdata(ndata),ydata(ndata))

open(11,file=file_a,form='formatted')do j=1,ndataread(11,*) jtemp,xdata(j)enddoclose(11)open(21,file=file_b,form='formatted')do j=1,ndataread(21,*) jtemp,ydata(j)enddoclose(21)call pearsn(xdata,ydata,ndata,rr,prob,zz)write(6,*) rr,rr**2, ' r, r^2'write(6,*) prob, ' prob'write(6,*) zz, ' z'deallocate(xdata,ydata)STOPEND

설명참조: http://incredible.egloos.com/1992323

Linear correlation

-1…….1

Page 53: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

53

implicit noneinteger j, k,ireal*8 tmp

real cpu_diffreal cpu_time1real cpu_time2real ( kind = 8 ) real_diffreal ( kind = 8 ) real_time1real ( kind = 8 ) real_time2

call cpu_time (cpu_time1 )! call real_time ( real_time1 )

tmp=0.0d0do i=1,1000do j=1,1000do k=1,100tmp=tmp+sin(float(j*i))*cos(float(i*j))enddoenddoenddo

call cpu_time ( cpu_time2 )! call real_time ( real_time2 )

cpu_diff = cpu_time2 - cpu_time1! real_diff = real_time2 - real_time1

write(6,*) cpu_diff! write(6,*) real_diff

stopend

ihlee@cetus0:~/lecture_programming$ a.out16.00000

FORTRAN STOPihlee@cetus0:~/lecture_programming$

ihlee@cetus0:~/lecture_programming$ time a.out16.00000

FORTRAN STOP

real 0m16.031suser 0m16.028ssys 0m0.001sihlee@cetus0:~/lecture_programming$

설명참조: http://incredible.egloos.com/3047318

Page 54: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

54

subroutine timestamp ( )

!*****************************************************************************80!!! TIMESTAMP prints the current YMDHMS date as a time stamp.!! Example:!! May 31 2001 9:45:54.872 AM!! Modified:!! 31 May 2001!! Author:!! John Burkardt!! Parameters:!! None!implicit none

character ( len = 8 ) ampminteger dcharacter ( len = 8 ) dateinteger hinteger minteger mmcharacter ( len = 9 ), parameter, dimension(12) :: month = (/ &

'January ', 'February ', 'March ', 'April ', &'May ', 'June ', 'July ', 'August ', &'September', 'October ', 'November ', 'December ' /)

integer ninteger scharacter ( len = 10 ) timeinteger values(8)integer ycharacter ( len = 5 ) zone

!234567890implicit nonecall timestamp()stopend

-----------------------------------------March 12 2007 1:58:40.868 PMFORTRAN STOP

call date_and_time ( date, time, zone, values )

y = values(1)m = values(2)d = values(3)h = values(5)n = values(6)s = values(7)mm = values(8)

if ( h < 12 ) thenampm = 'AM'

else if ( h == 12 ) thenif ( n == 0 .and. s == 0 ) thenampm = 'Noon'

elseampm = 'PM'

end ifelseh = h - 12if ( h < 12 ) thenampm = 'PM'

else if ( h == 12 ) thenif ( n == 0 .and. s == 0 ) thenampm = 'Midnight'

elseampm = 'AM'

end ifend if

end if

write ( *, '(a,1x,i2,1x,i4,2x,i2,a1,i2.2,a1,i2.2,a1,i3.3,1x,a)' ) &trim ( month(m) ), d, y, h, ':', n, ':', s, '.', mm, trim ( ampm )

returnend

설명참조: http://incredible.egloos.com/3047077

Page 55: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

55

subroutine lbfgs_mini(object,posi,grad,nn)! Written by In-Ho Lee, KRISS, March 3 (2003).

implicit noneinteger nnreal*8 object,posi(nn),grad(nn)integer n_local,m,msavereal*8, allocatable :: diag(:),w(:)real*8 eps,xtol,gtol,t1,t2,stpmin,stpmaxinteger iprint(2),iflag,icall,mp,lp,nworkinteger jnatom,jlogical diagcoreal*8, allocatable :: xyz(:,:),fxyz(:,:)

! The driver for LBFGS must always declare LB2 as EXTERNALexternal lb2common /lb3/mp,lp,gtol,stpmin,stpmaxn_local=nnm=5 ; msave=7 ; nwork=n_local*(2*msave+1)+2*msaveallocate(diag(n_local),w(nwork))iprint(1)= 1 ; iprint(2)= 0

!! We do not wish to provide the diagonal matrices Hk0, and! therefore set DIAGCO to FALSE.

diagco= .false. ; eps= 1.0d-4 ; xtol= 1.0d-16 ; icall=0 ; iflag=0!

jnatom=nn/3allocate(xyz(jnatom,3),fxyz(jnatom,3))

!20 continue

do j=1,jnatomxyz(j,1)=posi(3*(j-1)+1)xyz(j,2)=posi(3*(j-1)+2)xyz(j,3)=posi(3*(j-1)+3)enddo

call energy_force(xyz,fxyz,object,jnatom)do j=1,jnatomgrad(3*(j-1)+1)=-fxyz(j,1)grad(3*(j-1)+2)=-fxyz(j,2)grad(3*(j-1)+3)=-fxyz(j,3)enddo

!call lbfgs(n_local,m,posi,object,grad,diagco,diag,iprint,eps,xtol,w,iflag)if(iflag <= 0) go to 50icall=icall + 1

! We allow at most 2000 evaluations of Function and Gradientif(icall > 2000) go to 50go to 20

50 continuedeallocate(diag,w)deallocate(xyz,fxyz)returnend

설명참조: http://incredible.egloos.com/3042973

함수최소화(포트란)

2차원배열과 1차원배열lbfgs루틴은 1차원배열을요구한다.응용예에서는 2차원배열이자연스러운상태이다.

Gradient, function :입력

Page 56: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

56

!234567890implicit noneinteger nm,n,matz,ierrreal*8, allocatable :: ar(:,:),ai(:,:),w(:),zr(:,:),zi(:,:),fv1(:),fv2(:),fm1(:,:)real*8 tmpinteger i,j,kmatz=0matz=1nm=3n=nmopen(1,file='input',form='formatted')read(1,*) nclose(1)write(6,*) n,' n'allocate(ar(nm,n),ai(nm,n),w(n),zr(nm,n),zi(nm,n),fv1(n),fv2(n),fm1(2,n))do i=1,ndo j=1,i ! 소위 lower-triangular-form으로저장하고있습니다.

!------[ set up the hermitian matrix : lower triangular formar(i,j)=dfloat(i+j)**2ai(i,j)=1.d0/dfloat(i-j)

!------]if(i == j) ai(i,j)=0.0d0 hermitian 이기때문에반드시만족해야함enddoenddodo i=1,ndo j=1,iar(j,i)=ar(i,j)ai(j,i)=-ai(i,j)enddoenddocall ch(nm,n,ar,ai,w,matz,zr,zi,fv1,fv2,fm1,ierr)write(6,*) 'eigenvalues'do i=1,nwrite(6,*) w(i)enddowrite(6,*) 'eigenvectors'do j=1,nwrite(6,*) (dcmplx(zr(k,j),zi(k,j)),k=1,n)enddodo i=1,ndo j=1,ntmp=0.0d0do k=1,ntmp=tmp+dcmplx(zr(k,i),-zi(k,i))*dcmplx(zr(k,j),zi(k,j))enddowrite(6,*) i,j,tmpenddoenddodeallocate(ar,ai,w,zr,zi,fv1,fv2,fm1) ! 더이상필요하지않은배열들의메모리할당을풀어줍니다.stopend

Matrix diagonalization(포트란)

Page 57: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

57

!234567890implicit noneinteger i,j,kcharacter*32 filenamecharacter*4 fninteger nsizensize=4do j=0,3call numeral (j,fn,nsize)write(6,*) fnfilename=' del'//fnwrite(6,*) filename

! call system("cp admd.seq"//filename)end dostopend

ihlee@cetus0:~/lecture_programming$ a.out0000del0000 0001del0001 0002del0002 0003del0003

FORTRAN STOPihlee@cetus0:~/lecture_programming$

설명참조: http://incredible.egloos.com/3474225

Page 58: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

58

!234567890implicit noneinteger i,j,kcharacter*32 subcommandcharacter*32 subcommand2character*4 fncharacter*9 fminteger nsizensize=4do j=0,3call numeral (j,fn,nsize)write(6,*) fnfm=' admd'//fnsubcommand=fm//'.pdb'write(6,*) subcommand

! call system("cp admd.pdb"//subcommand)subcommand2=fm//'.dssp'subcommand2=trim(subcommand)//fm//'.dssp'write(6,*) subcommand2

! call system("~/dssp/dsspcmbi "//subcommand2)end dostopend

설명참조: http://incredible.egloos.com/3474225

Page 59: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

59

MODULE cartesianTYPE point

REAL :: x, yEND TYPE pointINTERFACE OPERATOR ( .DIST. )

MODULE PROCEDURE distEND INTERFACE

CONTAINSREAL FUNCTION dist( a, b )

TYPE(point), INTENT(IN) :: a, bdist = SQRT( (a%x-b%x)**2 + (a%y-b%y)**2 )

END FUNCTION distEND MODULE cartesian

program over2USE cartesianIMPLICIT NONETYPE(point) :: a, bREAL distance

a%x=0.0d0a%y=0.0d0b%x=1.0d0b%y=1.0d0

distance = a .DIST. b

write(6,*) distance

stopend program over2

ihlee@cetus0:~/lecture_programming$ a.out1.414214

FORTRAN STOPihlee@cetus0:~/lecture_programming$

Page 60: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

60

MODULE cartesianTYPE point

REAL*8 :: x, y, zEND TYPE pointINTERFACE OPERATOR ( .DIST. )

MODULE PROCEDURE distEND INTERFACE

CONTAINSREAL*8 FUNCTION dist( a, b )

TYPE(point), INTENT(IN) :: a, bdist = SQRT( (a%x-b%x)**2 + (a%y-b%y)**2 + (a%z-b%z)**2 )

END FUNCTION distEND MODULE cartesian

program over2USE cartesianIMPLICIT NONETYPE(point) :: a, bREAL*8 distance

a%x=0.0d0a%y=0.0d0a%z=0.0d0b%x=1.0d0b%y=1.0d0b%z=1.0d0

distance = a .DIST. b

write(6,*) distance

stopend program over2

ihlee@cetus0:~/lecture_programming$ a.out1.732050807568877

FORTRAN STOPihlee@cetus0:~/lecture_programming$

TYPE COORDS_3D REAL :: x, y, z END TYPE COORDS_3D

TYPE(COORDS_3D) :: pt1, pt2

Page 61: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

61

MODULE cartesianTYPE point

REAL*8 :: x, yEND TYPE point

INTERFACE ASSIGNMENT( = )MODULE PROCEDURE max_point

END INTERFACECONTAINS

SUBROUTINE max_point( a, pt )REAL*8, INTENT(OUT) :: aTYPE(point), INTENT(IN) :: pta = MAX( pt%x, pt%y )

END SUBROUTINE max_pointEND MODULE cartesian

program over4USE cartesianIMPLICIT NONETYPE(point) :: a = point(1.7d0, 4.2d0)REAL*8 :: coord

coord = a

write(6,*) coord

stopend program over4

ihlee@cetus0:~/lecture_programming$ a.out4.200000000000000

FORTRAN STOPihlee@cetus0:~/lecture_programming$

Page 62: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

62

PROGRAM test

INTERFACEREAL*8 FUNCTION ratio(x, y)

REAL*8 ::x, yEND FUNCTION ratio

END INTERFACE

INTEGER :: i=3, j=25

PRINT *,'The ratio is ',ratio(dfloat(i),dfloat(j))

END PROGRAM test

REAL*8 FUNCTION ratio(x, y)REAL*8 :: x, yratio=x/y

END FUNCTION ratio

ihlee@cetus0:~/lecture_programming$ a.outThe ratio is 0.1200000000000000

ihlee@cetus0:~/lecture_programming$

Page 63: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

63

ihlee@cetus0:~/lecture_programming$ a.outThe ratio is 0.1200000000000000

ihlee@cetus0:~/lecture_programming$

PROGRAM test

!INTERFACE! REAL*8 FUNCTION ratio(x, y)! REAL*8 ::x, y! END FUNCTION ratio!END INTERFACE

INTEGER :: i=3, j=25real*8 ratio

PRINT *,'The ratio is ',ratio(dfloat(i),dfloat(j))

END PROGRAM test

REAL*8 FUNCTION ratio(x, y)REAL*8 :: x, yratio=x/y

END FUNCTION ratio

Procedure interface들만을모아둔하나의모듈을정의할수도있다.

Page 64: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

64

SUBROUTINE invert(a, inverse, count) REAL, INTENT(IN) :: a REAL, INTENT(OUT) :: inverse INTEGER, INTENT(INOUT) :: count inverse = 1/a count = count+1 END SUBROUTINE invert

PROGRAM test INTERFACE REAL FUNCTION func( x ) REAL, INTENT(IN) ::x END FUNCTION funcEND INTERFACE ...CALL sub1( a, b, func(2) ) ...

END PROGRAM test

REAL FUNCTION func( x ) ! external REAL, INTENT(IN) :: x func = 1/x END FUNCTION func

Page 65: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

65

MODULE stringsINTERFACE OPERATOR ( / )

MODULE PROCEDURE numEND INTERFACE

CONTAINSINTEGER FUNCTION num( s, c )

CHARACTER(len=*), INTENT(IN) :: sCHARACTER, INTENT(IN) :: cnum = 0DO i=1,LEN( s )

IF( s(i:i)==c ) num=num+1END DO

END FUNCTION numEND MODULE strings

program ov1USE stringsimplicit nonecharacter*32, ch1,ch2,ch3integer ii,jj,kk

ch1='hello world'ch2='my name is in-ho lee'ch3='who are you'ii = ch1/'l'jj = ch2/'o'kk = ch3/'a'write(6,*) iiwrite(6,*) jjwrite(6,*) kkstopend program ov1

ihlee@cetus0:~/lecture_programming$ a.out311

FORTRAN STOPihlee@cetus0:~/lecture_programming$

http://www.qmw.ac.uk/~cgaa260/BUILDING/INTR_F90/PRG_UNTS/OPOLOAD.HTM

Operator overloading

Page 66: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

66

MODULE SWAPPERINTERFACE SWAP

MODULE PROCEDURE SWAP_R, SWAP_I, SWAP_CEND INTERFACE

CONTAINSSUBROUTINE SWAP_R(A, B)IMPLICIT NONEREAL, INTENT (INOUT) :: A, BREAL :: TEMP

TEMP = A ; A = B ; B = TEMPEND SUBROUTINE SWAP_R

SUBROUTINE SWAP_I(A, B)IMPLICIT NONEINTEGER, INTENT (INOUT) :: A, BINTEGER :: TEMP

TEMP = A ; A = B ; B = TEMPEND SUBROUTINE SWAP_I

SUBROUTINE SWAP_C(A, B)IMPLICIT NONECHARACTER, INTENT (INOUT) :: A, BCHARACTER :: TEMP

TEMP = A ; A = B ; B = TEMPEND SUBROUTINE SWAP_C

END MODULE SWAPPER

PROGRAM SWAP_MAINUSE SWAPPER

IMPLICIT NONEINTEGER :: I, J, K, LREAL :: A, B, X, YCHARACTER :: C, D, E, F

I = 1 ; J = 2 ; K = 100 ; L = 200A = 7.1 ; B = 10.9 ; X = 11.1; Y = 17.0C = 'a' ; d = 'b' ; E = '1' ; F = '"'

WRITE (*,*) I, J, K, L, A, B, X, Y, C, D, E, FCALL SWAP (I, J) ; CALL SWAP (K, L)CALL SWAP (A, B) ; CALL SWAP (X, Y)CALL SWAP (C, D) ; CALL SWAP (E, F)WRITE (*,*) I, J, K, L, A, B, X, Y, C, D, E, F

END

ihlee@cetus0:~/lecture_programming$ a.out1 2 100 200 7.100000

10.90000 11.10000 17.00000 ab1"2 1 200 100 10.90000

7.100000 17.00000 11.10000 ba"1ihlee@cetus0:~/lecture_programming$

http://www-teaching.physics.ox.ac.uk/Unix+Prog/hargrove/tutorial_90/13_extra.html

Page 67: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

67

Derived Type

TYPE COORDS_3D REAL :: x, y, z END TYPE COORDS_3D

TYPE(COORDS_3D) :: pt1, pt2 pt1%x = 1.0 bubble%radius = 3.0 bubble%centre%x = 1.0

TYPE SPHERE TYPE (COORDS_3D) :: centre REAL :: radius END TYPE SPHERE

TYPE (SPHERE) :: bubble, ball

pt1 = COORDS_3D(1.,2.,3.) bubble%centre = COORDS_3D(1.,2.,3.) bubble = SPHERE(bubble%centre,10.) bubble = SPHERE(COORDS_3D(1.,2.,3.),10.)

Page 68: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

68

Multiple Precision Computation

매우특별한상황에사용된다.

2**200 = 1606938044258990275541962092341162602522202993782792835301376

아래의정수는솟수 (prime number)일까?5468317884572019103692012212053793153845065543480825746529998049913561

정밀도에 제한 받지 않고, 물론, 계산은 느려지겠지만, 정확한 계산을 필요로 하는 경우 아래의 라이버러리를 사용할 필요가 있다. 특히, 포트란 90을 활용하여 만든 라이버러리는 기본 연산들(+, -, *, /, **, log, ......)들을 통상적인 방법으로 그냥 사용하면 되게만들어 준다. 정말 환상적인 계산 방식이다. 해당 변수들만 derived type으로 정의해 주고 계산은 '그냥 이전에 하듯이 하면'(+,-,*,/, **, sqrt().......) 된다. 인터페이스 (interface) 명령어를 이용한 오버로딩을 활용한다.

http://en.wikipedia.org/wiki/Operator_overloading

The same example using derived types: ...

USE FMZM TYPE ( FM ) A,B,C,D

... D = SQRT( A**2 + B**2 + C**2 )

...

http://incredible.egloos.com/3160240

Page 69: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

69

References

http://incredible.egloos.com/2950367 에올려진두개의 pdf 파일들을추천합니다. 다운로드가능합니다.서로다른방식으로포트란 90을설명하고있는두교과서입니다.

http://www.fortran.com/fortran/ Pointer to everything Fortran http://www.arc.unm.edu/~jabed/list.html Pointer to a list of tutorials http://dynaweb.sdsc.edu:8080/library/t90_c90_y90_cray_fp?DWEB_COLLECTION=DWEB_COLLECTIONS Cray's Manual http://www.software.ibm.com/ad/fortran/xlfortran/optim.html Short optimization guide from IBM http://www.digital.com/fortran/dvf.html DEC's Digital Visual Fortran Page ftp://mycroft.plk.af.mil/pub/Fortran_90/Tutorial A tutorial by Zane Dodson http://www.nova.edu/ocean/psplot.html Postscript plotting library http://meteora.ucsd.edu/~pierce/fxdr_home_page.html Subroutines to do unformatted I/O across platforms, provided by David Pierce at UCSD http://www.nsc.liu.se/~boein/f77to90/a5.html A good reference for intrinsic functions http://www.nsc.liu.se/~boein/f77to90/ Fortran 90 for the Fortran 77 Programmerhttp://www.tat.physik.uni-tuebingen.de/~kley/lehre/ftn77/tutorial/index.html

http://www.sdsc.edu/~tkaiser/f90.html

Page 70: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

70

Practice makes perfect.

<속담> 연습이 제일이다 [배우기보다 익혀라].

백견이불여일타(?)

Page 71: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

71

Python

계산기쉘보다많은구조기능Very-high-level language많은표준모듈제공개발시간단축

No compileNo type declarationsNo memory allocation controlHigh level data structure들여쓰기: 문장을그룹화

http://pentangle.net/python/handbook/handbook.htmlhttp://en.wikipedia.org/wiki/Python_(programming_language)http://incredible.egloos.com/2950369

1990년 Guido van Rossum (http://www.python.org/~guido/)에 의해 개발된 인터프리터 언어이다. 사전적으로 python을 알아 보면 아래와 같다. 컴퓨터 산업과 관련된 단어들이 나타나고 있는 특징이 있습니다. 상대적으로, 상당히 늦게 태어난(?) 언어이다.

1 [동물】 비단뱀, 이무기2 [P~] 【그리스신화】 거대한 뱀((Apollo신이 Delphi에서 죽인)) 3 신탁(oracle); 신탁을 받는 신관(神官); 예언자 무당에 붙는 귀신[심령]

셀(shell)보다많은구조와기능제공초고수준의언어 (very-high-level language)이다. (기계보다는사람에게더욱더가까운것이수준이높다고정의함.)응용프로그램개발기간을단축할수있다. (눈에확들어오는말!)표준모듈이많이있다.대상중심 (객체지향; 대상중심; object-oriented) 언어이다.배우기쉽다.확장성이높다.다른언어와의접착력이강하다.무료언어이면서여러가지종류의시스템들에서잘작동한다.

http://www.pasteur.fr/recherche/unites/sis/formation/python/

하위도판로쉼 (Guido van Rossum)

파이썬이라는이름은하위도가좋아하는코미디〈Monty Python's Flying Circus〉에서따온것이다.

http://en.wikibooks.org/wiki/Python_Programming

Page 72: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

72

파이썬의특징

동적타이핑(dynamic typing). (실행시간에타입검사가이루어진다.) 객체의멤버에대한접근이제한되어있지않다.모듈, 클래스, 객체와같은언어의요소가내부에서접근할수있다.

파이썬은초보자부터전문가까지폭넓은사용자층을보유하고있다. 동적타이핑(dynamic typing) 범용프로그래밍언어로, 펄및루비와자주비교된다. 다양한플랫폼에서쓸수있고, 라이브러리(모듈)가풍부하여, 대학을비롯한여러교육기관, 연구기관및산업계에서이용이증가하고있다. 또파이썬은순수한프로그램언어로서의기능외에도다른언어로쓰여진모듈들을연결하는풀언어(glue language)로서자주이용된다. 실제파이썬은많은상용응용프로그램에서스크립트언어로채용되고있다. 도움말문서도정리가잘되어있으며, 유니코드문자열을지원해서다양한언어의문자처리에도능하다.

파이썬에는「건전지포함("Battery Included")」이란기본개념이있어, 프로그래머가바로사용할수있는라이브러리와통합환경이이미배포판과함께제공된다. 이로써파이썬의표준라이브러리는매우충실하다. (MS windows, 리눅스, 맥,…., 무료로제공된다.)

개발시간단축!

http://ko.wikipedia.org/wiki/%ED%8C%8C%EC%9D%B4%EC%8D%AC

다양한수준들의파이썬자료들: http://www.awaretek.com/tutorials.html#begin

Page 73: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

73

PythonControl-d

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> print "Hello world"

간단한계산기처럼사용가능하다.exit()

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> a=1. ; b=2.d0File "<stdin>", line 1a=1. ; b=2.d0

^SyntaxError: invalid syntax>>> a=1 ; b=2.>>> c=a+b>>> print c3.0>>>

유닉스명령어bc –l간단한계산기이다. quit를사용하면끝낼수있다.

ihlee@cetus0:~$ bc -lbc 1.06Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.This is free software with ABSOLUTELY NO WARRANTY.For details type `warranty'. 12.*12144quitihlee@cetus0:~$

Page 74: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

74

파이썬 언어기초문법

*들여쓰기 (indentation)는 python언어의일부이다. 멋이아니다!*#을이용하여 comment를시작할수있습니다. ``해쉬”입니다.*다음줄로이월할때확장표시는 \로한다.) "빽슬러쉬" 입니다.*변수형 (정수형,배열,실수형, 문자형을선언하지않고사용한다.*컴파일하지않는다. #!/usr/bin/env python를첫줄에넣어서바로실행가능한코드로도만든다.*함수선언은 "def" 와 ":"를사용함. 선언된함수다음줄뒤부터는들여쓰기필요함. if와 for뒤에도다음명령어들과관련하여다음줄로넘어갈경우들여쓰기가반드시필요함.*for i in range(100): 와같이사용할경우에서 i는 0부터시작하여 0,1,2,3,4, 과같이 ...99까지달리면서for loop의안쪽의내용을 100번반복한다는뜻입니다. range를 range(1,101)처럼사용하면 1부터 100까지 i가달립니다. 사실 range(10)는리스트 (배열과는차이가있음)를의미합니다. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]*FORTRAN 90 이용하던사람입장에서파일읽고쓰기가약간불편하다. 예제를잘활용하면이또한익숙해지리라믿습니다.*함수는 return되는것이없을수도있습니다. 즉, 파일을생성한다든지..... 반환되는것들은 return뒤에다줄줄이기록하면됩니다. 예를들어 return a,b,c,d처럼말입니다. 여기서 a는실수형, b는 1차원배열, c는 2차원리스트(또는터플) 그리고 d는문자열일수도있습니다. 함수를부르는곳에서제대로받기만하면됩니다. 함수이름을 abcd()라고가정하면함수를부르는곳에서 aa,bb,cc,dd=abcd()라고하면됩니다.

Page 75: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

75

실행 가능한 파이썬 스크립트

#!/usr/bin/env python#from Numeric import *#from string import atof,atoi,split#from posix import getpid,rename,remove,mkdir,rmdir,system#from shutil import copyfile#import os,sys,time,random__version__="1.0.0"

counter=0acc = 0for n in xrange(1,10000000000):

num1 = str(n).count('5')if num1 > 0 :

acc = acc+num1if acc == n:

counter=counter+1print "counter = ",counter,nif counter == 2 :

break

재사용하기위해서, 제대로테스트하기위해서스크립트로만들어둘필요가있다.chmod 755 abc.py

Page 76: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

76

system( 명령어 ) 를활용하여시스템에서계산을수행할수도있다. 파일복사도할수있다. 통상적인명령어수행이가능하다.

포트란에서 `시스템콜하기`; 파이썬과의결합?

포트란프로그램에서 CALL SYSTEM('application.py')처럼파이썬스크립트를직접불러서사용할수도있다.이러한경우 call system이전에필요한자료들을파일로정리해둔다음시스템으로잠시나간다음시스템에서준비된파이썬스크립트가자료를사용할수있게설계할수있다. 물론외부의프로그램들(스크립트에서준비된일련의명령들) 등으로 자료처리또는계산을수행한다음다시포트란프로그램으로되돌아오는방법이있다.

물론돌아오기전에포트란프로그램에서자료를읽어들일수있도록파일들을미리만들어주면좋겠다.물론파이썬스크립트가관리를해야할것이다. 마지막으로포트란프로그램에서는준비된자료들을읽어들여서계속하여포트란으로계산을수행할수있다.

자료적어두기: 파일열기/적기 ==포트란명령으로수행call system('python_driver.py') ==포트란에서시스템으로빠져나와서미리준비된파이썬스크립트실행하기.자료읽어들이기: 파일열기/읽기 ==포트란실행파일 ‘명령’으로수행

Page 77: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

77

파이썬을이용해서 sad.x라는프로그램을 2000번실행하는방식을설명한다.인풋파일을만들고, 실행한다. 아웃풋파일을특별한순번을먹여서저장한다.

for i in range(2000): # 2000번반복하기gen_sad_input() # 파일 sad.i 만들기system('sad.x >TMPFILE') # 코드 sad.x 실행하기copyfile('dim.dat', ascnum('dimer.',i))copyfile('mid.xyz', ascnum_xyz('midpt.',i)) # 파일복사하기system('rm dim.dat') # 파일지우기system('rm TMPFILE')

>>> from os import *>>> system('ls')abc.py HFB PBS_script_examples tr.pyaction_protein_draco JOB_ID_PRINTED swkim_mpiVASP_exampleadmd_cluster matplot_test test v_tubesdssp onion test1 ykm0>>>

import glob,timeimport os.pathfile_list=glob.glob('*')for f_name in file_list:

if os.path.isfile(f_name):print f_name,' is a regular file'print os.path.getsize(f_name)print os.path.getatime(f_name)print time.ctime(os.path.getatime(f_name))

elif os.path.isdir(f_name):print f_name,' is a directory'

elif os.path.islink(f_name):print f_name,' is a symbolic link'

system()명령어를사용할때, 예를들어 system('qsub work.0003/pbs_script_file')에서처럼변수형태의 pbs파일명을사용하고자할때는다음과같이한다. j=3 ; f_name=ascnum('work.',j)+'/pbs_script_file' ; system('qsub '+f_name+'')

os.path.exists

Page 78: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

78

실행하면서입력읽어들이기

#!/usr/bin/env pythonfaren_old = float(raw_input("Enter yesterday's temperature "))faren_new = float(raw_input("Enter today's temperature "))if faren_new > 90 and faren_old < 90:

print "First day of a heatwave"elif faren_new > 90:

print "Subsequent day of a heatwave"elif faren_old < 90:

print "Not the hot season"else:

print "Bye, bye heatwave"print "Program completed"

>>> raw_input()3'3'>>> input()44

ihlee@cetus0:~/lecture_programming$ py1.py Enter yesterday's temperature 99Enter today's temperature 98.Subsequent day of a heatwaveProgram completedihlee@cetus0:~/lecture_programming$

Page 79: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

79

phi_trj=[[0.]*(iidd) for j in xrange(np+1)]psi_trj=[[0.]*(iidd) for j in xrange(np+1)]for ifile in range(0,np+1):

tmp_file=asc2num('rama',ifile)+'.txt'fp_rama=open(tmp_file,'r')jth=0while 1:

line=fp_rama.readline()if not line :

breakelse:

token=line.split()phi_trj[ifile][jth]=float(token[0])psi_trj[ifile][jth]=float(token[1])jth=jth+1

fp_rama.close()

http://incredible.egloos.com/3588647

Page 80: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

80

def wwait(file_name):while 1 :

time.sleep(60.) # 60초동안잠자기if os.path.exists(file_name) :

remove(file_name)break # 파일발견되면지우고루프탈출하기

return

def mkdir_series(n_dir):for j in range(n_dir):

char=ascnum('test_dir.',j) # test_dir.0001 과같은형식으로 n_dir 개의디렉토리만들기mkdir(char)

return

touch abcd

Page 81: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

81

#!/usr/bin/env pythonfrom Numeric import *from string import atof,atoi,splitfrom posix import getpid,rename,remove,mkdir,rmdir,systemfrom shutil import copyfileimport os,sys,time,random__version__="1.0.0"

if __name__ == "__main__":## 이프로그램은현재디렉토리내에있는 *.bin 파일의목록을읽어# convert.x 라는프로그램에의해다른파일로변환되는기능을가지고# 있습니다. convert.x의사용법은 "convert.x test.bin test" 입니다.## 작성자 yeskim98, 작성일 March/26/2003#system('ls *.bin >namelist') # 리스트를파일속에저장하기f=open('namelist','r')for line in f:

name=line.split()[0]name1=name[:-4] # 뒤에서부터 4개의문자를없애기system('./convert.x '+name+' '+name1+'')

f.close()

Page 82: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

82

#!/usr/bin/env pythonfrom Numeric import * #from string import atof,atoi,splitfrom posix import getpid,rename,remove,mkdir,rmdir,systemfrom shutil import copyfileimport os,sys,time,random__version__="1.0.0"def prtjobid():# written by In-Ho Lee, KRISS, Jan. 12, 2002.f=open('JOB_ID_PRINTED','w')f.write('%15d \n' % os.getpid()) #st=time.asctime() #f.write('%23s \n' % st)f.close()return

def num2char(i): # ic=str(i)ic='0'if i == 1 : ic='1'if i == 2 : ic='2'if i == 3 : ic='3'if i == 4 : ic='4'if i == 5 : ic='5'if i == 6 : ic='6'if i == 7 : ic='7'if i == 8 : ic='8'if i == 9 : ic='9'return ic

def ascnum(ichar,number):# written by In-Ho Lee, KRISS, Jan. 12, 2002.i=int(float(number)/1000.)j=int((number-i*1000.)/100.)k=int((number-j*100.-i*1000.)/10.)l=int(number-k*10.-j*100.-i*1000.)ic=num2char(i)jc=num2char(j)kc=num2char(k)lc=num2char(l)fname=ichar+ic+jc+kc+lc # abc.0001return fname

def ascnum_xyz(ichar,number):# written by In-Ho Lee, KRISS, Jan. 12, 2002.fname=ascnum(ichar,number)+'.xyz' # abc.0001.xyzreturn fname

prtjobid()ichar='abc'for i in range(10):

print ascnum_xyz(ichar,i)

ihlee@cetus0:~/lecture_programming$ num.py abc0000.xyzabc0001.xyzabc0002.xyzabc0003.xyzabc0004.xyzabc0005.xyzabc0006.xyzabc0007.xyzabc0008.xyzabc0009.xyzihlee@cetus0:~/lecture_programming$

>>> from string import *>>> a=1>>> b=str(a)>>> print b1>>> c=str(222)>>> print c222>>>

숫자에서스트링으로변환

>>> print atof(c)222.0>>> print atoi(c)222

스트링에서숫자로변환

>>> print float(c)222.0>>> print int(c)222

>>> a=1.e0>>> a=complex(a)>>> print a(1+0j)>>>

>>> a=1>>> b=str(a).zfill(4)>>> print b0001>>> c=str(a).zfill(5)>>> print c00001>>> c=str(c)>>> print c00001>>>

Page 83: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

83

Prime number?

#!/usr/bin/env pythonfor i in range(2,10):

for x in range(2,i):if i % x == 0 :

print i, 'equals', x, '*', i/xbreak

else:print i, 'is a prime number'

ihlee@cetus0:~/lecture_programming$ prime.py3 is a prime number4 equals 2 * 25 is a prime number5 is a prime number5 is a prime number6 equals 2 * 37 is a prime number7 is a prime number7 is a prime number7 is a prime number7 is a prime number8 equals 2 * 49 is a prime number9 equals 3 * 3ihlee@cetus0:~/lecture_programming$

Page 84: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

Comparison What it tests

a < b a is less than b

a <= b a is less than or equal to b

a > b a is greater than b

a >= b a is greater than or equal to b

a == b a is equal to b

a != b a is not equal to b

a < b < c a is less than b, which is less than c

a /= b 포트란 90a .ne. b

a .lt. b 포트란 77

a .le. b 포트란 77

a .gt. b

a .ge. b

a .eq. b

a < b .and. b < c

포트란 90, python에서모두 =가두번째에위치한다고생각하면된다.>=, <=, !=(/=)에서처럼.

84

Page 85: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

85

if x == 10 and y > z: print "Some statements which only get executed if" print "x is equal to 10 AND y is greater than z."

if x == 10 or y > z:print "Some statements which get executed if either print "x is equal to 10 OR y is greater than z"

if [condition]: [Some statements executed only if [condition] is true]

else: [Some statements executed only if [condition] is false]

elif의수는여러개가가능하다.없을수도있다.

if 0 <= x <= 10:print "That is between zero and ten inclusive"

elif 10 < x < 20:print "That is between ten and twenty"

else: print "That is outside the range zero to twenty"

조건판단의결과참: 1거짓: 0

FORTRAN 90과달리 endif가없다.

Page 86: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

86

Reserved Words

and assert break class continue

def del elif else except

exec finally for from global

if import in is lambda

not or pass print raise

return try while

Data Float Int Numeric Oxphys

array close float int input

open range type write zeros

Operator Example Description

M += N M = M + N

M -= N M = M - N

M *= N M = M * N

M /= N M = M / N

M %= N M = M % N

acos asin atan cos e

exp fabs floor log log10

pi sin sqrt tan

일하고있는현재디렉토리에위에서위에표시된 reserved word를파일이름으로사용하는것을권장하지않습니다. 예를들어,Numeric.py 처럼, 사용자가만든파일이름이디렉토리에존재하면불편해집니다.모듈들을불러들일때문제가발생합니다.

Page 87: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

87

FORTRAN 90 사용할때사용하는것들에대응하는것:.and. ======= and.or. ======= or.gt. (>) ======= >.ge. (>=) ======= >=.le. (<=) ======= <=.eq. (==) ======== ==.ne. (/=) ======== !=a < b < c a is less than b, which is less than c2의제곱은 2**2 처럼사용하면됩니다.나머지는 %를이용합니다.not은논리적으로부정을표시합니다. not logical_variable처럼사용.sqrt()exp()log()log10()sin()cos()tan()asin()acos()atan()floor()fabs()piand append apply assert break class clock complex conjugate continue def del dir dot eigenvectors elif else except exec finally for from global identity if import in is lambdamatrixmultiply max mkdir min maximum minimum not or pass path print raise random reduce return remove rename rmdir shape sleep split string system sum time try wait while Data Float IntNumeric array open write close float int input range type zeros 위에나타낸단어들은 "넓은의미로예약된이름"들로일반사용자들은변수이름으로피하는것이좋습니다.

Shortcut Operators

Page 88: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

88

Class• 함수와 마찬가지로 사용하기 전에 선언

• 축구선수 : class, 호날두: (object, instance)=(객체, 실체)

• 클래스 내부에 정의된 함수를 method라고 부릅니다. (객체에 소속된 함수)

• 객체이름=클래스 형식으로 활용된다.

• Members(변수들) + methods(함수들)로 구성된다.

Method는함수와유사하지만, 특정의객체의존하는점이다르다.append는리스트에정의된 method이다.close는파일에정의된 method이다.

#!/usr/bin/env pythonclass player:

def kick(self):return 'kick the ball'

def heading(self):return 'heading the ball'

ronaldo=player()print ronaldo.kick()print ronaldo.heading()

instantiation

Page 89: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

89

#!/usr/bin/env pythonclass player:

strength= 50speed= 90stamina= 70agility= 90def kick(self):

return 'kick the ball'def heading(self):

return 'heading the ball'def take_a_rest(self):

self.stamina= self.stamina+10self.agility= self.agility+2self.speed= self.speed+5

ronaldo=player()print ronaldo.kick()print ronaldo.heading()print 'Ronaldo'print ronaldo.strengthprint ronaldo.speedprint ronaldo.staminaprint ronaldo.agility

print 'Ronaldo takes a rest'ronaldo.take_a_rest()print 'Ronaldo'print ronaldo.strengthprint ronaldo.speedprint ronaldo.staminaprint ronaldo.agility

print 'Park'park=player()print park.kick()print park.heading()print park.strengthprint park.speedprint park.staminaprint park.agilityprint 'Park takes a rest'park.take_a_rest()print 'Park'print park.strengthprint park.speedprint park.staminaprint park.agility

ihlee@cetus0:~/lecture_programming$ class1.py kick the ballheading the ballRonaldo50907090Ronaldo takes a restRonaldo50958092Parkkick the ballheading the ball50907090Park takes a restPark50958092ihlee@cetus0:~/lecture_programming$

새로운데이터형의정의는클래스로구현한다. 데이터형이가지는가능한연산을 method들로정의한다.물론, 새로운객체의초기화도가능하다.

Page 90: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

90

특별한 method

#!/usr/bin/env pythonclass Stat:

def set_data(self,player,goals,assts):self.player= playerself.goals= goalsself.assts= assts

def printdata(self):print 'player: ', self.playerprint 'goals: ', self.goalsprint 'assts: ', self.assts

def __init__(self,player,goals,assts):self.set_data(player,goals,assts)print 'A new Stat class'

ron=Stat('Ronaldo',16,2)ron.set_data('Ronaldo',17,3)ron.printdata()

lee=Stat('Lee',0,0)lee.printdata()

ihlee@cetus0:~/lecture_programming$ class3.py A new Stat classplayer: Ronaldogoals: 17assts: 3A new Stat classplayer: Leegoals: 0assts: 0ihlee@cetus0:~/lecture_programming$

통상명시적으로호출되지않는다.객체가생성되면즉시호출된다.

self: method의첫인수특별한의미를가진다. Method가호출될때, 그객체를대표한다.

Page 91: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

91

#!/usr/bin/env pythonclass Shape:

area=0.varia=9.def __add__(self,other):

return self.area + other.area

a=Shape()a.area=10.b=Shape()b.area=30.print a+b

print a.__add__(b)

ihlee@cetus0:~/lecture_programming$ class4.py 40.040.0ihlee@cetus0:~/lecture_programming$

특별한 method를사용해서연산자가하는일을정의하는것을연산자중복(overload)이라고한다.

Page 92: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

92

#!/usr/bin/env pythonclass Shape:

area=0.varia=9.def __add__(self,other):

return self.area + other.areadef __cmp__(self,other):

if self.area < other.area :return -1

elif self.area == other.area :return 0

else :return 1

a=Shape()a.area=10.b=Shape()b.area=30.print a+b

print a.__add__(b)

print a.__cmp__(b)

if a > b : print 'a > b'if a < b : print 'b > a'if a == b : print 'b = a'

ihlee@cetus0:~/lecture_programming$ class5.py 40.040.0-1b > aihlee@cetus0:~/lecture_programming$

Page 93: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

93

#!/usr/bin/env pythonf=open('abc.txt')buffer=f.read()print bufferf.close()

ihlee@cetus0:~/lecture_programming$ file.pyI am a boy.You are a girl.

ihlee@cetus0:~/lecture_programming$

#!/usr/bin/env pythonf=open('abc.txt')buffer=f.read()print bufferf.close()g=open('new_abc.txt','w')g.write('My Love')g.close()

#!/usr/bin/env pythonf=open('abc.txt')line=f.readline()print lineline=f.readline()print linef.close()

ihlee@cetus0:~/lecture_programming$ file3.py I am a boy.

You are a girl.

ihlee@cetus0:~/lecture_programming$

Page 94: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

94

#!/usr/bin/env pythonfrom string import atof__version__="1.0.0"np=0f=open('coord.xyz','r')while 1:

line=f.readline()if not line :

breaktoken=line.split()natom=int(token[0])line=f.readline()np=np+1cx= cy= cz=0.for j in range(natom):

line=f.readline()token=line.split()cx=cx+float(token[1])cy=cy+float(token[2])cz=cz+float(token[3])

cx=cx/float(natom)cy=cy/float(natom)cz=cz/float(natom)format='%21.11f %21.11f %21.11f'print format % (cx,cy,cz)

f.close()np=np-1print natom,np,'natom,np','(',np+1,'frames',')'

phi_trj=[[0.]*(iidd) for j in xrange(np+1)]psi_trj=[[0.]*(iidd) for j in xrange(np+1)]for ifile in range(0,np+1):

tmp_file=asc2num('rama',ifile)+'.txt'fp_rama=open(tmp_file,'r')jth=0while 1:

line=fp_rama.readline()if not line :

breakelse:

token=line.split()phi_trj[ifile][jth]=float(token[0])psi_trj[ifile][jth]=float(token[1])jth=jth+1

fp_rama.close()

Page 95: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

95

#!/usr/bin/env pythonimport os,sys,time,randomfrom posix import system__version__="1.0.0"natom=597nk=0np=20amp=5.0e00pseed=1421##natom=int(raw_input("natom :"))#np=int(raw_input("np :"))#nk=int(raw_input("nk :"))#amp=float(raw_input("amp :"))#pseed=int(raw_input("pseed :"))

if np <= 0:np=2

if nk <= 0:nk=np-1

print pseed, 'pseed in python'random.seed(pseed)system('grep CA confi.a > calpha_set.dat')ca_site=[]f_ca=open('calpha_set.dat','r')while 1:

line=f_ca.readline()if not line :

breakelse:

token=line.split()ca_site.append(int(token[0]))

f_ca.close()

num_calpha=len(ca_site)print num_calpha,' the number of Calpha atoms'print ca_site#akx=[ [[0.]*nk for j in range(3)] for i in range(natom) ]aky=[ [[0.]*nk for j in range(3)] for i in range(natom) ]akz=[ [[0.]*nk for j in range(3)] for i in range(natom) ]for i in range(1,natom+1):

for k in range(1,nk+1):akx_t= (random.random()-0.5)*amp/float(k)/float(k)aky_t= (random.random()-0.5)*amp/float(k)/float(k)akz_t= (random.random()-0.5)*amp/float(k)/float(k)akx[i-1][0][k-1]=akx_taky[i-1][1][k-1]=aky_takz[i-1][2][k-1]=akz_t

#g_sine=open('r_fort.40','w')g_sine.write('%8d %8d %s %s \n' %( nk,natom, 'nk','natom'))istart=0for i in range(len(ca_site)):

ica=ca_site[i]ica=ica-1if i >0 :

istart=ca_site[i-1]print istart+1,ica+1for iatom in range(istart,ica):

for k in range(nk):akx[iatom][0][k]=akx[ica][0][k]+((random.random()-0.5)*1.e-2)/float(k+1)/float(k+1)aky[iatom][1][k]=aky[ica][1][k]+((random.random()-0.5)*1.e-2)/float(k+1)/float(k+1)akz[iatom][2][k]=akz[ica][2][k]+((random.random()-0.5)*1.e-2)/float(k+1)/float(k+1)

#ica=ca_site[len(ca_site)-1]print ica+1,natomfor iatom in range(ica ,natom):

for k in range(nk):akx[iatom][0][k]=akx[ica][0][k]+((random.random()-0.5)*1.e-2)/float(k+1)/float(k+1)aky[iatom][1][k]=aky[ica][1][k]+((random.random()-0.5)*1.e-2)/float(k+1)/float(k+1)akz[iatom][2][k]=akz[ica][2][k]+((random.random()-0.5)*1.e-2)/float(k+1)/float(k+1)

#for i in range(natom):

g_sine.write('\n')for k in range(nk):

g_sine.write('%16.8f %16.8f %16.8f \n' %( akx[i][0][k], aky[i][1][k], akz[i][2][k]))g_sine.close()

배열선언과파일에적기연습

Page 96: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

96

#!/usr/bin/env pythonfrom Numeric import *from string import atof,atoi,splitfrom posix import getpid,rename,remove,mkdir,rmdir,systemfrom shutil import copyfileimport time,os,sys,random

def prtjobid():f=open('JOB_ID_PRINTED','w')f.write('%15d \n' % os.getpid())st= time.asctime()f.write('%23s \n' % st)f.close()return

print time.asctime()prtjobid()iseed=2003print iseed, ' iseed in python'random.seed(iseed)for i in range(10):

print random.random()

ihlee@cetus0:~/lecture_programming$ time_test.pyThu Jan 17 10:39:36 20082003 iseed in python0.1127637230840.9649317976690.6933097557830.2838059686630.6678829222850.7902716303750.8034380964820.8493690627710.7071054712230.0992155723476ihlee@cetus0:~/lecture_programming$

파일이름을 time.py로하면안됨.표준모듈중에 time이있기때문에…..

Page 97: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

97

상속(inheritance)이란어떤클래스가다른클래스의성질을물려받는것

#!/usr/bin/env pythonclass person:

eyes=2nose=1mouth=1ears=2arms=2legs=2def eat(self):

print 'eat'def sleep(self):

print 'sleep'def talk(self):

print 'talk'

class player(person):def football(self):

print 'play football'

lee=person()print lee.mouthlee.talk()seol=player()print seol.mouthseol.talk()seol.football()

ihlee@cetus0:~/lecture_programming$ class2.py 1talk1talkplay footballihlee@cetus0:~/lecture_programming$

Player가 person의모든속성을가지고있다.

축구선수만할수있는 football

Page 98: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

98

파이썬이포트란프로그램을부르는형식으로예를들었지만, 상황은완전히바뀔수있다. 이번에는포트란프로그램의일부로서파이썬이사용되는경우이다.물론시스템으로잠시나가있는경우이다.포트란에서 `시스템콜하기`; 파이썬과의결합?포트란프로그램에서 CALL SYSTEM('application.py')처럼파이썬스크립트를직접불러서사용할수도있다.이러한경우 call system이전에필요한자료들을파일로정리해둔다음시스템으로잠시나간다음시스템에서준비된파이썬스크립트가자료를사용할수있게설계할수있다. 물론외부의프로그램들 (스크립트에서준비된일련의명령들) 등으로자료처리또는계산을수행한다음다시포트란프로그램으로되돌아오는방법이있다. 물론돌아오기전에포트란프로그램에서자료를읽어들일수있도록파일들을미리만들어주면좋겠다, 물론파이썬스크립트가관리를해야할것이다. 마지막으로포트란프로그램에서는준비된자료들을읽어들여서계속하여포트란으로계산을수행할수있다.

자료적어두기: 파일열기/적기 ==포트란명령으로수행call system('python_driver.py') ==포트란에서빠져나와서파이썬스크립트실행하기

파이썬을스크립트로사용할경우, 프로그램인풋파일을만들수있다.배치 job을만들수있다. 아웃풋파일을분석할수도있다.

Page 99: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

99

Global variables

ihlee@cetus0:~/lecture_programming$ cat glob1.py #!/usr/bin/env python__version__="1.0.0"def demo (f_in):

global somevar # shared with main codedemo.tom = 16 # An attribute accessible from main codesomevar += 1another = 12 # A local variable, independent of main coderes = f_in+14 # Value passed in (f_in)return res

somevar = 27 # accessed in function via globalanother = 17 # not accessed in functionpval = 16 # accessed in function via parameter

print demo(pval),' demo(pval)'

print demo.tom ,' demo.tom' # function attributeprint somevar,'somevar'print another,'another'ihlee@cetus0:~/lecture_programming$ glob1.py 30 demo(pval)16 demo.tom28 somevar17 anotherihlee@cetus0:~/lecture_programming$

http://www.wellho.net/forum/Programming-in-Python-and-Ruby/Variable-scope-in-Python.html

Page 100: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

100

Numeric python; Numpy

from Numeric import * #When you create an array you must then explicitly tell Python you are doing so as follows:

>>> from Numeric import * >>> xx = array([1, 5, 6.5, -11]) >>> print xx [ 1. 5. 6.5 -11. ] >>> print xx[0] 1.0

>>> print xx[3] -11.0

>>> xx = zeros(5, Int) >>> print xx [0 0 0 0 0] >>> yy = zeros(4, Float) >>> print yy[ 0. 0. 0. 0.]

a powerful N-dimensional array object sophisticated (broadcasting) functions basic linear algebra functions

basic Fourier transforms sophisticated random number capabilities tools for integrating Fortran code. tools for integrating C/C++ code.

http://numpy.scipy.org/numpydoc/numpy.html

http://www.scipy.org/Numpy_Example_List_With_Doc/

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from Numeric import *>>> m=zeros((3,3))>>> print m[[0 0 0][0 0 0][0 0 0]]

>>> print identity(3)[[1 0 0][0 1 0][0 0 1]]

>>>

numpy.fftnumpy.linalgnumpy.randomnumpy.oldnumeric

실행속도향상,MATLAB처럼

Numeric -- -- numpy.oldnumeric

Page 101: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

101

#!/usr/bin/env python#import os,sys,time,randomfrom Numeric import *from LinearAlgebra import solve_linear_equationsfrom string import atof,atoi,splitfrom posix import getpid,rename,remove,mkdir,rmdir,systemfrom shutil import copyfile__version__="1.0.0"def gen_ak_path(np,xvec):# written by In-Ho Lee, KRISS, Jan. 29, 2003.

us=0.0 ; uf=1.0 ; du=(uf-us)/float(np) # 한줄에여러개의표현식을적을수있다.bvec=zeros(np-1,Float)for j in range(1,np):

uu=us+du*float(j)bvec[j-1]=xvec[j]-xvec[0]-uu*(xvec[np]-xvec[0])

amat=zeros((np-1,np-1),Float)for j in range(1,np):

uu=us+du*float(j)for k in range(1,np):

amat[j-1,k-1]=sin(float(k)*pi*uu) # 행렬구성ak_vec=solve_linear_equations(amat,bvec) #내방정식을풀어도 !return len(ak_vec),ak_vec

Page 102: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

102

Universal functions

>>> from Numeric import *>>> m=zeros((3,3))>>> print m[[0 0 0][0 0 0][0 0 0]]>>> print identity(3)[[1 0 0][0 1 0][0 0 1]]>>> sin(m)array([[ 0., 0., 0.],

[ 0., 0., 0.],[ 0., 0., 0.]])

>>> m=m+1.>>> print m[[ 1. 1. 1.][ 1. 1. 1.][ 1. 1. 1.]]>>> sin(m)array([[ 0.84147098, 0.84147098, 0.84147098],

[ 0.84147098, 0.84147098, 0.84147098],[ 0.84147098, 0.84147098, 0.84147098]])

>>> m=m+m>>> print m[[ 2. 2. 2.][ 2. 2. 2.][ 2. 2. 2.]]>>> n=m-0.5>>> print n[[ 1.5 1.5 1.5][ 1.5 1.5 1.5][ 1.5 1.5 1.5]]>>> qq=m*n>>> print qq[[ 3. 3. 3.][ 3. 3. 3.][ 3. 3. 3.]]>>> pp=matrixmultiply(m,n)>>> print pp[[ 9. 9. 9.][ 9. 9. 9.][ 9. 9. 9.]]>>>

http://numpy.sourceforge.net/numdoc/HTML/numdoc.htm#pgfId-57315

Page 103: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

103

#!/usr/bin/env pythonimport os,sys,timefrom shutil import copyfilefrom posix import getpid,rename,remove,mkdir,rmdir,systemfrom time import *from Numeric import *from LinearAlgebra import *

def test_sort():n=5arrin=zeros((n),Float)arrin=array([1., 3., 4., 5., 2.])indx=argsort(arrin)print indxfor i in range(5):j=indx[i]print arrin[j]

return

test_sort()

[0 4 1 2 3]1.02.03.04.05.0

#!/usr/bin/env pythonfrom Numeric import *from time import *from string import atof,atoi,splitfrom posix import getpid,rename,remove,mkdir,rmdir,systemfrom shutil import copyfileimport os,sys,random__version__="1.0.0"

if __name__ == "__main__":nnn=5at=zeros(nnn,Float)s_at=zeros(nnn,Float)at[0]=-3.at[1]=3.at[2]=-4.at[3]=-5.at[4]=-6.print at,' before'index=argsort(at)for i in range(nnn):

s_at[i]=at[index[i]]print s_at,' after'print index,' index'

[-3. 3. -4. -5. -6.] before[-6. -5. -4. -3. 3.] after[4 3 2 0 1] index

Page 104: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

104

Numeric Python (Numpy)이라는강력한모듈이있습니다. 인스톨했다면, 불러다사용할수있습니다. 과학기술용계산에필요한배열은 array1=zeros(100,Float)와같이쉽게 0.0e0으로초기화하면서만들수있습니다. 이경우 Numeric-20.3를사용했습니다. 길이가 100 (인덱스는 0,1,2,....99)인일차원배열이 0.0e0으로초기화되었습니다. (python에서는 0.0과 0.0e0는같은실수형입니다. FORTRAN식으로이야기하면실수형 real*8에해당합니다. 하지만 0.d0처럼사용하지않습니다.) 기본적으로 double precision 수준으로정확한계산을합니다. 2차원배열생성및 0.0으로초기화는 array2d=zeros((100,100),Float)와같이합니다. 원주율은 pi라는곳에저장되어있습니다. 이렇게수학적인것들을자유롭게사용하려면 Numeric이라는모듈을불어다놓은상태여야합니다. " from Numeric import *"를이용하면됩니다. 굳이설명을붙이자면 "Numeric이라는모듈에서사용가능한것들모두 (*)를사용할수있도록수입하다"입니다. 마찬가지로 "from LinearAlgebra import solve_linear_equations"를동원하여아래에표시된것처럼선형대수학문제를 solution_vector=solve_linear_equations(a_matrix,b_vector)아주간결하게해결하실수있습니다. 이계산들은 python이제법빨리수행합니다. 실질적으로는잘알려진(그리고잘검정된) 수학 package들을이용하기때문입니다. 이들은다른언어 (예를들어 C나 FORTRAN)로만들어질수있습니다.

Numeric python이설치하기전에시스템에ATLAS(Automatically Tuned Linear Algebra Software; fast linear algebra routines)가설치되어있는지확인할필요가있다. 없다면설치해야한다.ATLAS는각종소프트웨어들 MAPLE(v7 and higher), MATLAB(v6.0 and higher), Mathematica(forthcoming), MAPLE(v7 and higher), Octave등에서사용되거나사용될것이다.

Page 105: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

105

초보자 vs 숙련자

파이썬에서는 www.netlib.org에서찾아볼수있는 C나 FORTRAN으로만들어진그리고검정이끝난루틴들을이용하여계산을한다. 이들을 python으로다시작성하는것은굉장히좋지않은아이디어일뿐만아니라디버깅하는데너무나오랜시간을잡아먹을것이다. 따라서그들은 C나 FORTRAN으로돌아가야한다. 다만 python 쪽으로데이터들이자유롭게넘나들수있어야한다. 이렇게함으로써인터프리터언어의한계인느린계산으로부터생기는한계를극복할수있다. 결국은상당히효율적인 (C나 FORTRAN 속도도유지하면서 very-high-level 언어의특징은여전히살아있다.) 프로그램이완성되는것이다. 이러한아이디어는굉장한것을의미할수있다. 즉, 초보자가프로그램을해도숙련자 (전산전문가)가한것과거의같은성능을얻어낼수있다.

파이썬고유의자료형•문자열: 시퀀스자료형•리스트: 시퀀스자료형•tuple: 항상괄호로싸여있다. (시퀀스자료형)•사전 : 존재하는동안변경불가능한짝

Numeric python 설명을잘참조하면쉽게고수준으로도약할수있다.

http://numpy.scipy.org/numpy.pdf

Page 106: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

106

#!/usr/bin/env python#from Numeric import *#from string import atof,atoi,splitfrom string import *#from posix import getpid,rename,remove,mkdir,rmdir,system#from shutil import copyfile#import os,sys,time,random__version__="1.0.0"

def gc(dna):return (count(dna, 'c')+count(dna, 'g'))/float(len(dna))*100.0

print gc('atgtaatgatat')

ihlee@cetus0:~/lecture_programming$ gc.py 16.6666666667ihlee@cetus0:~/lecture_programming$

Page 107: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

107

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> 1+12>>> xx=1+10>>> print xx11>>> yy=xx+xx**2>>> print yy132>>> >>> LL=[1, 2, 3, 4, 5]>>> print LL[1, 2, 3, 4, 5]>>> sum(LL)15>>> leng(LL)Traceback (most recent call last):File "<stdin>", line 1, in ?

NameError: name 'leng' is not defined>>> len(LL)5>>> sum(LL)/len(LL)3>>>

복합자료형:list

append()extend()insert()remove()pop()index()count()sort()reverse()

Page 108: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

108

if os.path.exists('CHG') :존재할경우할일들

os.path.exists라는명령어를사용하면지금디렉토리에파일이름 CHG라는파일이존재하는지안하는지를체크할수있습니다. 즉, os.path.exists('CHG') 값이 0 (거짓을의미함)이면 'CHG'라는파일이존재하지않음을의미합니다. system()명령어를사용할때, 예를들어 system('qsub work.0003/pbs_script_file')에서처럼변수형태의pbs파일명을사용하고자할때는다음과같이한다. j=3 ; f_name=ascnum('work.',j)+'/pbs_script_file' ; system('qsub '+f_name+'')

디스크에있는파일들의목록을취할때는glob 모듈의 glob함수를사용하면아주편리하다. 실제사용될수있는형태를보면아래와같다.import glob,timeimport os.pathfile_list=glob.glob('*')for f_name in file_list:

if os.path.isfile(f_name):print f_name,' is a regular file'print os.path.getsize(f_name)print os.path.getatime(f_name)print time.ctime(os.path.getatime(f_name))

elif os.path.isdir(f_name):print f_name,' is a directory'

elif os.path.islink(f_name):print f_name,' is a symbolic link'

glob.glob('*.gif')glob.glob('*.dat') 처럼사용될수있습니다.

os.listdir('.') 도현재디렉토리의파일목록을얻을때사용할수있습니다. 현재프로세스의작업디렉토리이름:os.getcwd()

여기서설명못드린파이썬의많은기능들또는함수들은 www.google.com에서찾으시면됩니다. 다른언어에서사용하시던기능대부분이파이썬에있습니다. 보통 "키워드 + python"하시면될것입니다("python -snake -monty" 진짜뱀과티비프로그램은제외). 또는 www.python.org/doc/current/lib를직접방문하세요. os.getcwd() os.getuid() os.getuname() os.path.getsize(file_name) os.path.split(file_name)

Page 109: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

109

파일에적기

g=open('sad.i','w') # 파일 sad.i 만들기시작g.write('%16d %16.8f %s \n' % ( natom,delrr, 'natom,delrr' ))g.write('%16d %16d %16d %s \n' % ( iseed1,iseed2,ktmax, 'iseed1,iseed2,ktmax'))g.write('%16.8f %16.8f %s \n' % ( xs_local,xf_local, 'xs_local,xf_local'))g.write('%16.8f %16.8f %s \n' % ( ys_local,yf_local, 'ys_local,yf_local'))g.write('%16.8f %16.8f %s \n' % ( zs_local,zf_local, 'zs_local,zf_local'))g.close()

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> f=open('input_xx','r')>>> for line in f:... for i in range(len(line.split())):... print line.split()[i]... 12.abc>>> ihlee@cetus0:~/lecture_programming$ vi input_xxihlee@cetus0:~/lecture_programming$ cat input_xx1 2. abcihlee@cetus0:~/lecture_programming$

format='%16.8e %16.8e %16.8e %16.8e %12.5e %12.5e %22s'print format %(ac+cc+zz,ac,cc,zz,onma,etar,'o,a,p1,p2,onma,etarget')

.close()

.flush()

.write()

deff (e, f)c

Page 110: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

110

atof, atoi

ihlee@cetus0:~/lecture_programming$ cat input_xx1 2. abcihlee@cetus0:~/lecture_programming$ cat read_test.py#!/usr/bin/env pythonfrom string import atof,atoi,splitf=open("input_xx",'r')for line in f:

int_aaa=atoi(line.split()[0])rel_bbb=atof(line.split()[1])chr_ccc= line.split()[2]

print int_aaaprint rel_bbbprint chr_cccf.close()ihlee@cetus0:~/lecture_programming$ read_test.py12.0abcihlee@cetus0:~/lecture_programming$

int, float, complex

raw_input() 명령어는문자열를취급한다.

Page 111: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

111

지정파일에서 "숫자, 숫자, midpoint"를포함하는라인에서첫번째숫자뽑아내기여러개의파일들에흩어진정보를뽑아낼때아주유용한함수예

def read_energy(fname):# written by In-Ho Lee, KRISS, Jan. 12, 2002.

f=open(fname,'r')for line in f:for i in range(len(line.split())):

if line.split()[i] == 'midpoint':energy= atof(line.split()[i-2])

f.close()return energy

python 2.0 이하에서는아래의함수를이용해야함.def read_energy_saddle(fname):# written by In-Ho Lee, KRISS, March 6, 2003.

select=1f=open(fname,'r')while select :line=f.readline()for i in range(len(line.split())):

if line.split()[i] == 'midpoint':energy= atof(line.split()[i-2])select=0break

f.close()return energy

Page 112: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

112

PBS 스크립트작성하기(응용하면: 여러개의계산을 PBS를통해서할수있다. wwait 함수를동시에잘이용하면된다. PBS는여러개의 CPU를자동으로선택해주기때문이다.)system('qsub ursa_vasp') time.sleep(10.)wwait('DONE_VASP')하나의 PBS job이끝날때 touch DONE_VASP를동원하여 DONE_VASP라는파일을만들면해당계산이끝났음을python프로그램 (주기적으로끝나기를기다리는)에게알려줄수있다. (touch 는유닉스명령어로서파일을생성한것과같은효과를만들수있다. 위의경우파일크기가 0 이면서아무내용도없는파일을하나생성한다.) 이때 python프로그램은 wwait함수를동원하여 DONE_VASP가있는지없는지를확인하여 (위의예에서는 60초단위로확인한다.) 다음일들을할지기다릴지를판단하게된다. 물론, 존재하면그파일을지우고다음에할일들을하면된다. 위에서이야기한하나의 job은물론, 병렬job일수도 serial job 일수도있다.

예를들어 system('qsub work.0003/pbs_script_file')에서처럼변수형태의 pbs파일명을사용하고자할때는다음과같이한다. j=3 ; f_name=ascnum('work.',j)+'/pbs_script_file' ; system('qsub '+f_name+'')

Page 113: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

113

#!/usr/bin/env pythonfrom Numeric import * #from string import atof,atoi,splitfrom posix import getpid,rename,remove,mkdir,rmdir,systemfrom shutil import copyfileimport os,sys,time,random__version__="1.0.0"

def prtjobid():# written by In-Ho Lee, KRISS, Jan. 12, 2002.f=open('JOB_ID_PRINTED','w')f.write('%15d \n' % os.getpid()) #st=time.asctime() #f.write('%23s \n' % st)f.close()return

prtjobid()

6291Tue Jan 15 11:48:19 2008

파이썬으로작업을실행시키고있을때,현재상황을체크할수있다.ps –u ihlee작업번호, process IDkill –9 process ID로작업을죽일수있다.

ihlee@cetus0:~/lecture_programming$ ls -ltra현디렉토리에존재하는파일들을생성시간순으로배열해준다.

Page 114: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

114

Standard input

#!/usr/bin/env python#from Numeric import *#from string import atof,atoi,split#from posix import getpid,rename,remove,mkdir,rmdir,system#from shutil import copyfile#import os,sys,time,random__version__="1.0.0"print "Please give a number: "a = input()print "And another: "b = input()print "The sum of these numbers is: "print a + b

ihlee@cetus0:~/lecture_programming$ input.pyPlease give a number: 1And another: 2The sum of these numbers is: 3ihlee@cetus0:~/lecture_programming$

raw_input()

sys.exit()

#!/usr/bin/env pythonimport sysprint "Type a value: ", # comma prevents newlinevalue = sys.stdin.readline() # use stdin explicitlyprint value

ihlee@cetus0:~/lecture_programming$ stdin.pyType a value: 33

ihlee@cetus0:~/lecture_programming$ stdin.pyType a value: 33.33.

ihlee@cetus0:~/lecture_programming$ stdin.pyType a value: 'abc''abc'

ihlee@cetus0:~/lecture_programming$ stdin.pyType a value: "defg""defg"

sys.stdout.write("Hello world\n") # \n= newline

Page 115: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

115

>>> import sys>>> dir(sys)['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions']>>>

Page 116: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

116

>>> print range(0, 6) [0, 1, 2, 3, 4, 5]

>>> myfloat = 0.1 >>> myfloat = 2.0 >>> myfloat = 3.14159256 >>> myfloat = 1.6e-19 >>> myfloat = 3e8

>>> x = 5>>> print x 5

>>> print range(10, 20, 2) [10, 12, 14, 16, 18]

>>> a = b = c = 0

>>> mystring = "Here is a string" >>> mystring = 'Here is another'

>>> print a, b, c 0 0 0

>>> i = 2 >>> i = i + 1 >>> print i 3

>>> print (2 * (3 - 1)) * 4 16

>>> myinteger = 0 >>> myinteger = 15 >>> myinteger = -23 >>> myinteger = 2378

sumsquares = 0 # sumsquares must have a value because we increment # it later.

for i in [0, 1, 2, 3, 4, 5]: print "i now equal to:", i sumsquares = sumsquares + i**2 # sumsquares incremented here print "sum of squares now equal to:", sumsquares

print "------" print "Done."

Page 117: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

117

기본문법익히기

눈으로확인하면즉시, 그뜻을알아차릴수있는간결한수학적기법들을아래와같이나타내어보았습니다.FORTRAN 90에서처럼 vector와 matrix 처리가간결해졌습니다.>>> range(1,10,2)

[1, 3, 5, 7, 9]>>> range(10,1,-1)[10, 9, 8, 7, 6, 5, 4, 3, 2]>>> range(10,0,-1)[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]>>> >>> istart=1; ifinish=9 ; idirection=1>>> for i in range(istart,ifinish+1,idirection):... print i... 123456789>>> istart=9; ifinish=-1; idirection=-1 >>> for i in range(istart,ifinish+1,idirection):... print i... 987654321>>>

Page 118: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

118

from Numeric import *

>>> a=array((1,2))>>> b=array((3,4))>>> dot(a,b)11>>> a=array(((1,2),(3,4)))>>> b=a>>> matrixmultiply(a,b) # 매우간결합니다!array([[ 7, 10],

[15, 22]])

>>> sin(complex(1,3.))(8.4716454543001483+5.4126809231781934j)>>> >>> for i in [1,2,3,4]:... print i... 1234

구체적으로수행하고자하는수학적일들을잘분류하고해당라이버러리를찾아야한다. 정확한사용법을익혀사용하면된다.

http://numpy.scipy.org/numpy.pdf

Page 119: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

119

>>> z=complex(1.,2.)>>> z.conjugate()(1-2j)>>> z.real1.0>>> z.imag2.0

>>> arange(0.,1.,0.20)array([ 0. , 0.2, 0.4, 0.6, 0.8])>>> arange(0.0,1.2,0.20)array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ])

>>> >>> q=arange(0.0,1.0,0.2)>>> sin(q)array([ 0. , 0.19866933, 0.38941834, 0.56464247, 0.71735609])>>> >>> max(0.,2.,3.)3.0>>> maximum(0.,2.)2.0>>> min(0.,-1,-3.)-3.0>>> minimum(-3.,3.)-3.0>>> a=[1,2,3.,4]>>> sum(a)10.0

Page 120: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

120

>>> b=[4,3,7,9]>>> sort(b) array([3, 4, 7, 9]) # 리스트의경우와유사하지만다름.>>> amat=zeros((2,2),Float)>>> amat[0][0]=1>>> amat[1][1]=1>>> trace(amat)2.0>>> from LinearAlgebra import *>>> determinant(amat)1.0>>> eigenvalues(amat)array([ 1., 1.])>>> eigenvectors(amat)(array([ 1., 1.]), array([[ 1., 0.],

[ 0., 1.]]))>>> b=inverse(amat)>>> print b[[ 1. 0.][ 0. 1.]]>>> >>> b=zeros(2,Float)>>> solve_linear_equations(amat,b)array([ 0., 0.])>>> >>> transpose(amat)array([[ 1., 0.],

[ 0., 1.]])>>> >>> argmax(b)0>>> argmin(b)0

파이썬은여러값을하나의그룹으로처리하기위한복합자료형가지고있다.List

복합자료형:list

Seq.append()Seq.extend()Seq.insert()Seq.remove()Seq.pop()Seq.index()Seq.count()Seq.sort()Seq.reverse()

append는리스트에정의된 method이다.

Sequences Strings (type str) of length 0, 1, 2'', '1', "12", 'hello\n' Tuples (type tuple) of length 0, 1, 2, etc:() (1,) (1,2) # parentheses are optional if len > 0 Lists (type list) of length 0, 1, 2, etc: [] [1] [1,2]

Page 121: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

121

#!/usr/bin/env python#from Numeric import *#from string import atof,atoi,split#from posix import getpid,rename,remove,mkdir,rmdir,system#from shutil import copyfile#import os,sys,time,random__version__="1.0.0"

sumsquares = 0 # sumsquares must have a value because we increment# it later.

for i in [0, 1, 2, 3, 4, 5]:print "i now equal to:", isumsquares = sumsquares + i**2 # sumsquares incremented hereprint "sum of squares now equal to:", sumsquaresprint "------"

print "Done."

i now equal to: 0sum of squares now equal to: 0------i now equal to: 1sum of squares now equal to: 1------i now equal to: 2sum of squares now equal to: 5------i now equal to: 3sum of squares now equal to: 14------i now equal to: 4sum of squares now equal to: 30------i now equal to: 5sum of squares now equal to: 55------Done.ihlee@cetus0:~/lecture_programming$

Page 122: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

122

행렬 (matrix) 대각화 (diagonalization)를한번해봅시다. H는 2차원배열이면서정방행렬 (n by n)입니다.H=T+V # Hamiltonian setupval,vec=eigenvectors(H) # matrix diagonalization (해당eigenvalue/vector를찾아라!)val,vec=ev_sort(val,vec) # solution sorting에필요한함수

def ev_sort(eigval,eigvec):newval=zeros(len(eigval),Float)newvec= zeros(eigvec.shape,Float)index=argsort(eigval)for i in index:newval[i]=eigval[index[i]]newvec[i,:]=eigvec[index[i],:] #

return newval,newvec

특별히설계된라이버러리들은파이썬언어만을고집하지않는다. C, Fortran 등으로수행될수도있다.이러한경우, 실행속도가상당히뛰어나다. 아무래도파이썬은매우느린언어이다.

aaa[i,j] 와 aaa[i][j]는서로다른것이다. Numpy에서는 [i,j], 반면 list를활용할경우, [i][j]양식을활용한다.혼용가능함

Page 123: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

123

iseed=2003print iseed, ' iseed in python'random.seed(iseed) # 랜덤함수씨드지정하기for i in range(10):

print random.random() # 랜덤함수 10 번출력하기

for i in range(2000): # 2000번반복하기gen_sad_input() # 파일 sad.i 만들기system('sad.x >TMPFILE') # 코드 sad.x 실행하기copyfile('dim.dat', ascnum('dimer.',i))copyfile('mid.xyz', ascnum_xyz('midpt.',i)) # 파일복사하기system('rm dim.dat') # 파일지우기system('rm TMPFILE')

>>> def addnumbers(x, y): sum = x + y return sum

>>> x = addnumbers(5, 10) >>> print x 15

>>> def addnumbers(x, y): sum = x + y x = 100000 return [sum, x]

>>> x = 5 >>> y = 10 >>> answer = addnumbers(x, y) >>> print answer[0] 15 >>> print answer[1] 100000

Page 124: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

124

def gen_sad_input():natom=60 # 사용자함수정의ktmax=2000delrr=1.e-1xs_local= 4. -random.random()*2.xf_local= 8. +random.random()*2.ys_local=-1. -random.random()*2.yf_local= 1. +random.random()*2.zs_local=-3. -random.random()*2.zf_local= 3. +random.random()*2.iseed1= int( (random.random())*31327.0e0+0. )iseed2 = int( (random.random())*30080.0e0+0. )g=open('sad.i','w') # 파일 sad.i 만들기시작g.write('%16d %16.8f %s \n' % ( natom,delrr, 'natom,delrr' ))g.write('%16d %16d %16d %s \n' % ( iseed1,iseed2,ktmax, 'iseed1,iseed2,ktmax'))g.write('%16.8f %16.8f %s \n' % ( xs_local,xf_local, 'xs_local,xf_local'))g.write('%16.8f %16.8f %s \n' % ( ys_local,yf_local, 'ys_local,yf_local'))g.write('%16.8f %16.8f %s \n' % ( zs_local,zf_local, 'zs_local,zf_local'))g.close()return

>>> fin = open("input.dat", "r") >>> line = fin.readline() >>> print line 1 5.06 78 15

>>> data = split(line) >>> print data ['1', '5.06', '78', '15']

>>> x = int(data[0]) >>> print x 1 >>> y = float(data[1]) >>> print y 5.06

Page 125: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

125

문자열연속열중의하나

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> abc='abc'>>> print abc[0]a>>> print abc[1]b>>> print abc[2]c>>> princ abc[3]

File "<stdin>", line 1princ abc[3]

^SyntaxError: invalid syntax>>> print abc[-1]c>>> print abc[-2]b>>> print abc[-3]a>>> print abc[-4]Traceback (most recent call last):

File "<stdin>", line 1, in ?IndexError: string index out of range>>> len(abc)3>>> print sentence1[2:]is is a book.>>>

>>> sentence1='This is a book.'>>> print sentence1This is a book.>>> print sentence1[2:10]is is a >>> print sentence1[2:12]is is a bo>>> len(sentence1)15

문자열, 리스트, 사전, tuple

Page 126: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

126

#!/usr/bin/env pythonfrom string import *def how_many_words(s):

list = split(s) return len(list)

s='energy = -100.000 eV'print how_many_words(s)4

def find(str, ch): index = 0 while index < len(str): if str[index] == ch:

return index index = index + 1

return -1

>>> astring='abcdefg'>>> bstring=astring[:-1]>>> print bstringabcdef>>> print astring[:]abcdefg>>> print astring[1:]bcdefg>>> print astring[3:]defg

Page 127: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

127

Join and Split

#!/usr/bin/env pythondays = ["Monday","Tuesday","Webnesday"]all = "<br>".join(days)print allprint ''.join(days)

if "o" in "Melksham": print "yes"

say = "This is a line of text"parts = say.split(" ")

first, second = "Tom Smiota".split(" ")second, first = first, second

print partsprint firstprint second

ihlee@cetus0:~/lecture_programming$ join_split.pyMonday<br>Tuesday<br>WebnesdayMondayTuesdayWebnesday['This', 'is', 'a', 'line', 'of', 'text']SmiotaTomihlee@cetus0:~/lecture_programming$

리스트(변환가능)을문자열로전환할때, join함수를부른다.

Page 128: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

128

s.capitalize()s.count()s.endswith()s.strip()s.split()s.swapcase()s.upper()

Python 2.4 Quick ReferencePython reference card

http://rgruet.free.fr/PQR2.3.html

http://www.digilife.be/quickreferences/QRC/Python%202.4%20Quick%20Reference%20Card.pdf

Page 129: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

129

#!/usr/bin/env pythonfrom Numeric import *from string import atof,atoi,splitfrom posix import getpid,rename,remove,mkdir,rmdir,systemfrom shutil import copyfileimport os,sys,time,random__version__="1.0.0"

if __name__ == "__main__":## 이프로그램은현재디렉토리내에있는 *.bin 파일의목록을읽어# convert.x 라는프로그램에의해다른파일로변환되는기능을가지고# 있습니다. convert.x의사용법은 "convert.x test.bin test" 입니다.## 작성자 yeskim98, 작성일 March/26/2003#system('ls *.bin >namelist') # 리스트를파일속에저장하기f=open('namelist','r')for line in f:

name=line.split()[0]name1=name[:-4] # 뒤에서부터 4개의문자를없애기system('./convert.x '+name+' '+name1+'')

f.close()

abc[:]를꺼꾸로나열하기: abc[::-1]

Page 130: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

130

google 입사시험 문제양의정수 n에대해서 1과 n 사이에 1이나오는횟수를나타내는함수를 f(n)이라고한다. 예를들어 f(13)=6이다.f(n)=n이되는첫번째양수는 1이다. 두번째양수는무엇인가?

#!/usr/bin/env python#from Numeric import *#from string import atof,atoi,split#from posix import getpid,rename,remove,mkdir,rmdir,system#from shutil import copyfile#import os,sys,time,random__version__="1.0.0"

counter=0acc = 0for n in xrange(1,10000000000):

num1 = str(n).count('1')if num1 > 0 :

acc = acc+num1if acc == n:

counter=counter+1print "counter = ",counter,nif counter == 2 :

break

ihlee@cetus0:~/lecture_programming$ google0.py counter = 1 1counter = 2 199981ihlee@cetus0:~/lecture_programming$

>>> range(1,10)[1, 2, 3, 4, 5, 6, 7, 8, 9]>>> xrange(1,10) xrange(1, 10)>>>

one by one, passing each to the variable n in turn

range vs xrange

http://incredible.egloos.com/2980264

Page 131: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

131

num1 = str(n)length=len(num1)num1num=0for jj in range(length):

if num1[jj] == '1': num1num=num1num+1num1=num1num

num1 = str(n).count('1')

Page 132: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

132

사전 {dictionary}

#!/usr/bin/env pythonauthor = {"php":"Rasmus Lerdorf",\

"perl":"Larry Wall",\"python":"Guido van Rossum"}

print "Python was written by",author["python"]print "php was written by",author["php"]print "perl was written by",author["perl"]

ihlee@cetus0:~/lecture_programming$ dic1.py Python was written by Guido van Rossumphp was written by Rasmus Lerdorfperl was written by Larry Wallihlee@cetus0:~/lecture_programming$

ihlee@cetus0:~/lecture_programming$ dic2.py Python was written by Guido van Rossum

c is the child of Brian Kernighanjava is the child of James Goslingpython is the child of Guido van Rossumperl is the child of Larry Walltcl is the child of John Ousterhoutawk is the child of Brian Kernighanphp is the child of Rasmus Lerdorfihlee@cetus0:~/lecture_programming$

#!/usr/bin/env pythonauthor = {"php":"Rasmus Lerdorf",\

"perl":"Larry Wall",\"tcl":"John Ousterhout",\"awk":"Brian Kernighan",\"java":"Sun Microsystems",\"parrot":"Simon Cozens",\"python":"Guido van Rossum"}

author["c"] = "Brian Kernighan"del author["parrot"]author["java"] = "James Gosling"

print "Python was written by",author["python"]print

for language in author.keys():print language,"is the child of",author[language]

http://www.wellho.net/course/python.html

Page 133: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

133

Tuple리스트와닮았지만, 변경을할수없는것이차이점이다.연속열중의하나이다. immutable

Tuple은괄호가필요없을수도있다.>>> for i in abc:... print i... abc

>>> for i in positions:... print i... GKDFMFFW>>> for i in tpl3:... print i... 12ab

>>> tpl1=(1,2)>>> tpl2=('a', 'b')>>> print tpl1(1, 2)>>> print tpl2('a', 'b')>>> tpl3=tpl1+tpl2>>> print tpl3(1, 2, 'a', 'b')>>>

>>> for i in ss:... print i... GKDFMFFWronaldoparkrooneylee

>>> range(0,10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

문자열, 리스트, 터플: 모두연속열이다. 모두다 ‘회돌이’가가능하다.

Page 134: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

134

Tuple과리스트의차이점

#!/usr/bin/env pythondemo_tpl = (1, 3, 6, 10, 15, 21, "lots")for i in range(len(demo_tpl)):

print i,"--->",demo_tpl[i]

ihlee@cetus0:~/lecture_programming$ tpl1.py 0 ---> 11 ---> 32 ---> 63 ---> 104 ---> 155 ---> 216 ---> lotsihlee@cetus0:~/lecture_programming$

#!/usr/bin/env python

values = (100,200,300,500,1000,\2000,4000,8000,16000,32000,\64000,125000,250000,500000,\1000000)

being_values = [100,200,300,500,1000,\2000,4000,8000,16000,32000,\64000,125000,250000,500000,\1000000]

if values == being_values:print "One"

done = tuple(being_values)

if values == done:print "Two"

Two

>>> tu=tuple(range(1,4))>>> print tu (1, 2, 3)>>> ple=tuple(range(4,7))>>> tuple1=tu+ple>>> print tuple1(1, 2, 3, 4, 5, 6)>>> print tuple1[1]2>>> tuple2=tu,ple>>> print tuple2((1, 2, 3), (4, 5, 6))>>> print tuple2[1][1]5>>>

Page 135: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

135

Tuple의사용예

#!/usr/bin/env pythonmonthno = []dayno = []

mlen = (31,28,31,30,31,30,31,31,30,31,30,31)

for currentmonth in range (len(mlen)):for day in range (mlen[currentmonth]):

dayno.append(day+1)monthno.append(currentmonth+1)

# dayno += [day+1]# monthno += [currentmonth+1]

wantday = int(raw_input("Which day number in year? ")) - 1print "That's day",dayno[wantday],"of",monthno[wantday]

ihlee@cetus0:~/lecture_programming$ tup_month.pyWhich day number in year? 31That's day 31 of 1ihlee@cetus0:~/lecture_programming$ tup_month.pyWhich day number in year? 365That's day 31 of 12ihlee@cetus0:~/lecture_programming$ tup_month.pyWhich day number in year? 33That's day 2 of 2ihlee@cetus0:~/lecture_programming$

>>> aaa, bbb = -1, 1>>> print aaa,bbb-1 1>>>

리스트에추가하는방법추가

>>> ttt=tuple(range(1,6))>>> b1,b2,b3,b5 = tttTraceback (most recent call last):File "<stdin>", line 1, in ?

ValueError: unpack tuple of wrong size>>> b1,b2,b3,b4,b5 = ttt>>> print ttt(1, 2, 3, 4, 5)>>> print b1,b2,b3,b4,b51 2 3 4 5>>>

Python 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> a=[]>>> a+=[0]>>> print a[0]>>> a+=[11]>>> print a [0, 11]>>> a.append(22)>>> print a [0, 11, 22]>>>

http://www.wellho.net/course/python.html

Page 136: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

136

리스트수치, 문자열, 다른리스트를담을수있는연속열이다.연속열중의하나.

>>> names=['ronaldo', 'baggio', 'rooney']>>> print names['ronaldo', 'baggio', 'rooney']>>> print names[0]ronaldo>>> print names[1:]['baggio', 'rooney']>>> names[1]='park'>>> print names['ronaldo', 'park', 'rooney']>>> names.append('lee')>>> print names['ronaldo', 'park', 'rooney', 'lee']>>> len(names)4

>>> positions=['GK', 'DF', 'MF', 'FW']>>> ss=positions+names>>> print ss['GK', 'DF', 'MF', 'FW', 'ronaldo', 'park', 'rooney', 'lee']>>>

>>> tt=[1, 2, 3]>>> tt3=3*tt>>> print tt3[1, 2, 3, 1, 2, 3, 1, 2, 3]

>>> qq=tt3+names>>> print qq[1, 2, 3, 1, 2, 3, 1, 2, 3, 'ronaldo', 'park', 'rooney', 'lee']

Page 137: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

137

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> alist=[-1, 3, -7, 9, 8, 4, 4]>>> print alist.count(3)1>>> print alist.count(4)2>>> print alist.count(11)0>>> alist.insert(1,-9)>>> alist[-1, -9, 3, -7, 9, 8, 4, 4]>>> alist.append(88)>>> alist[-1, -9, 3, -7, 9, 8, 4, 4, 88]>>> alist.index(8)5>>> alist.remove(88)>>> alist[-1, -9, 3, -7, 9, 8, 4, 4]>>> alist.reverse()>>> alist[4, 4, 8, 9, -7, 3, -9, -1]>>> alist.sort()>>> alist[-9, -7, -1, 3, 4, 4, 8, 9]>>>

An example that uses most of the list methods:복합자료형:list

append()extend()insert()remove()pop()index()count()sort()reverse()

Page 138: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

138

String, List, Dictionary, and Class : 응용 (1/2)

http://www.onlamp.com/pub/a/python/2002/10/17/biopython.html?page=5

#!/usr/bin/env pythonclass DNA:

"""Class representing DNA as a string sequence."""

basecomplement = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'}

def __init__(self, s):"""Create DNA instance initialized to string s."""self.seq = s

def transcribe(self):"""Return as rna string."""return self.seq.replace('T', 'U')

def reverse(self):"""Return dna string in reverse order."""letters = list(self.seq)letters.reverse()return ''.join(letters)

def complement(self):"""Return the complementary dna string."""letters = list(self.seq)letters = [self.basecomplement[base] for base in letters]return ''.join(letters)

String에 replace 적용

List에 reverse 적용

Page 139: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

139

String, List, Dictionary, and Class : 응용 (2/2)

def reversecomplement(self):"""Return the reverse complement of the dna string."""letters = list(self.seq)letters.reverse()letters = [self.basecomplement[base] for base in letters]return ''.join(letters)

def gc(self):"""Return the percentage of dna composed of G+C."""s = self.seqgc = s.count('G') + s.count('C')return gc * 100.0 / len(s)

def codons(self):"""Return list of codons for the dna string."""s = self.seqend = len(s) - (len(s) % 3) - 1codons = [s[i:i+3] for i in range(0, end, 3)]return codons

String에 replace 적용

List에 reverse 적용

http://www.onlamp.com/pub/a/python/2002/10/17/biopython.html?page=5

Page 140: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

140

String, List, Dictionary, and Class : 응용#!/usr/bin/env pythonclass DNA:

"""Class representing DNA as a string sequence."""

basecomplement = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'}

def __init__(self, s):"""Create DNA instance initialized to string s."""self.seq = s

def transcribe(self):"""Return as rna string."""return self.seq.replace('T', 'U')

def reverse(self):"""Return dna string in reverse order."""letters = list(self.seq)letters.reverse()return ''.join(letters)

def complement(self):"""Return the complementary dna string."""letters = list(self.seq)letters = [self.basecomplement[base] for base in letters]return ''.join(letters)

def reversecomplement(self):"""Return the reverse complement of the dna string."""letters = list(self.seq)letters.reverse()letters = [self.basecomplement[base] for base in letters]return ''.join(letters)

def gc(self):"""Return the percentage of dna composed of G+C."""s = self.seqgc = s.count('G') + s.count('C')return gc * 100.0 / len(s)

def codons(self):"""Return list of codons for the dna string."""s = self.seqend = len(s) - (len(s) % 3) - 1codons = [s[i:i+3] for i in range(0, end, 3)]return codons

String에 replace 적용

List에 reverse 적용

http://www.onlamp.com/pub/a/python/2002/10/17/biopython.html?page=5

Page 141: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

141

String, List, Dictionary, and Class : 응용

ihlee@cetus0:~/lecture_programming$ vi dna_test.pyihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from DNA import *Traceback (most recent call last):File "<stdin>", line 1, in ?

ImportError: No module named DNA>>> from dna_test import *>>> dna1=DNA('CGACAATAC')>>> dna1.transcribe()'CGACAAUAC'>>> dna1.reverse()'CATAACAGC'>>> dna1.complement()'GCTGTTATG'>>> dna1.reversecomplement()'GTATTGTCG'>>> dna1.gc()44.444444444444443>>> dna1.codons()['CGA', 'CAA', 'TAC']>>>

Page 142: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

142

모듈

• 스크립트, 계산기에서 접근 가능한 것

• 파일:정의+문장

• 다른 모듈(메인 모듈 포함)안으로 import될 수 있다.

• .py라는 확장자를 가진다.

• 표준 모듈 (파이썬 라이버러리 레퍼런스)

모듈을부를때from 모듈 import 변수나함수처럼사용하면정확히필요한것들만불러올수도있습니다.from Numeric import sin, cos, tan, sqrt

내장함수 int(),round(),floor(),ceil()은각각, 소수부분없애기, 반올림하여정수화하기, 작거나같은수중에서가장큰정수로만들기, 크거나같은수중가장작은정수를취한다. floor와 ceil은 math 모듈에있는것이다. 정수를실수형으로바꿀때는 float()을사용한다.내장된유용한함수dir(module_name)을사용하면편리하다.모듈의이름이넘겨지면, 그모듈에서유효한이름들의목록을 - 때로는함수 - 되돌려준다.

패키지: 다른모듈들을포함한모듈, 도트모듈이름, 파이썬모듈이름영역을구조화하는방법이다.A.B라는모듈이름은 A라는패키지안에있는 B라는하부모듈을지칭한다.

Page 143: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

143

모듈불러들이기

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import fibo>>> a=10>>> b=1000>>> fib(1000)Traceback (most recent call last):File "<stdin>", line 1, in ?

NameError: name 'fib' is not defined>>> fibo.fib(1000)1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987>>> print a10>>> print b1000>>> abc=fibo.fib2(1000)>>> print abc[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]>>> print a10>>> print b1000>>>

fibo.py in lecture_programming directory

비교 : from fibo import *

Page 144: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

144

지금까지모든프로그램은한개의파일에모든것들을담고있었다. 표준모듈을수입하여많은일들을할수있다.

일반적으로사용되는많은유용한정의는모듈에수집되어있으면사용하기편리하다.

파이썬은표준모듈과다른모듈을구별하지않는다. 모듈에수입되는방식에차이가없다.모듈은정의(함수, 변수)를담고있는파일이다.

표준모듈들이많이개발되어있다는것 프로그래밍할때매우편리하다.레퍼런스라이버러리를찾아서사용할수있어야한다. 적어도인터넷으로접근할수있어야한다.프로그래밍하는사람의특성에크게의존하지않는다. (거의유사한결과물이나온다.)

http://docs.python.org/lib/lib.htmlPython Library Reference

Page 145: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

145

#!/usr/bin/env pythondef fib(n):

a, b = 0, 1while b < n:

print b,a, b = b, a+b

def fib2(n):result=[]a, b = 0, 1while b < n :

result.append(b)# print b,

a, b = b, a+breturn result

#n=100#fib(n)#print#n=100#abc=fib2(n)#print abc

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import fibo>>> fibo.fib(1000)1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987>>> fibo.fib2(1000)[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]>>>

fibo.py in lecture_programming directory

함수, 사용하기전에미리선언되어야한다.

Page 146: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

146

ihlee@cetus0:~/lecture_programming$ pythonPython 2.3.5 (#2, Oct 16 2006, 19:59:54) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from fibo import *>>> fib(500)1 1 2 3 5 8 13 21 34 55 89 144 233 377>>>

fibo.py in lecture_programming directory

사용자가만든모듈이나표준모듈이나불러들이는방법은동일하다.파이썬에서이미예약된단어들로파일이름을만들면불편해진다. 키워드.py 형식을피하는것이좋다.

Page 147: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

147

BLOSUM505 -2 -1 -2 -1 -1 -1 0 -2 -1 -2 -1 -1 -3 -1 1 0 -3 -2 0 -2 -1 -1-2 7 -1 -2 -4 1 0 -3 0 -4 -3 3 -2 -3 -3 -1 -1 -3 -1 -3 -1 0 -1-1 -1 7 2 -2 0 0 0 1 -3 -4 0 -2 -4 -2 1 0 -4 -2 -3 4 0 -1-2 -2 2 8 -4 0 2 -1 -1 -4 -4 -1 -4 -5 -1 0 -1 -5 -3 -4 5 1 -1-1 -4 -2 -4 13 -3 -3 -3 -3 -2 -2 -3 -2 -2 -4 -1 -1 -5 -3 -1 -3 -3 -2-1 1 0 0 -3 7 2 -2 1 -3 -2 2 0 -4 -1 0 -1 -1 -1 -3 0 4 -1-1 0 0 2 -3 2 6 -3 0 -4 -3 1 -2 -3 -1 -1 -1 -3 -2 -3 1 5 -10 -3 0 -1 -3 -2 -3 8 -2 -4 -4 -2 -3 -4 -2 0 -2 -3 -3 -4 -1 -2 -2-2 0 1 -1 -3 1 0 -2 10 -4 -3 0 -1 -1 -2 -1 -2 -3 2 -4 0 0 -1-1 -4 -3 -4 -2 -3 -4 -4 -4 5 2 -3 2 0 -3 -3 -1 -3 -1 4 -4 -3 -1-2 -3 -4 -4 -2 -2 -3 -4 -3 2 5 -3 3 1 -4 -3 -1 -2 -1 1 -4 -3 -1-1 3 0 -1 -3 2 1 -2 0 -3 -3 6 -2 -4 -1 0 -1 -3 -2 -3 0 1 -1-1 -2 -2 -4 -2 0 -2 -3 -1 2 3 -2 7 0 -3 -2 -1 -1 0 1 -3 -1 -1-3 -3 -4 -5 -2 -4 -3 -4 -1 0 1 -4 0 8 -4 -3 -2 1 4 -1 -4 -4 -2-1 -3 -2 -1 -4 -1 -1 -2 -2 -3 -4 -1 -3 -4 10 -1 -1 -4 -3 -3 -2 -1 -21 -1 1 0 -1 0 -1 0 -1 -3 -3 0 -2 -3 -1 5 2 -4 -2 -2 0 0 -10 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 2 5 -3 -2 0 0 -1 0-3 -3 -4 -5 -5 -1 -3 -3 -3 -3 -2 -3 -1 1 -4 -4 -3 15 2 -3 -5 -2 -3-2 -1 -2 -3 -3 -1 -2 -3 2 -1 -1 -2 0 4 -3 -2 -2 2 8 -1 -3 -2 -10 -3 -3 -4 -1 -3 -3 -4 -4 4 1 -3 1 -1 -3 -2 0 -3 -1 5 -4 -3 -1-2 -1 4 5 -3 0 1 -1 0 -4 -4 0 -3 -4 -2 0 0 -5 -3 -4 5 2 -1-1 0 0 1 -3 4 5 -2 0 -3 -3 1 -1 -4 -1 0 -1 -2 -2 -3 2 5 -1-1 -1 -1 -1 -2 -1 -1 -2 -1 -1 -1 -1 -1 -2 -2 -1 0 -3 -1 -1 -1 -1 -1

Page 148: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

148

BLOSUM624 -1 -2 -2 0 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -3 -2 0 -2 -1 0-1 5 0 -2 -3 1 0 -2 0 -3 -2 2 -1 -3 -2 -1 -1 -3 -2 -3 -1 0 -1-2 0 6 1 -3 0 0 0 1 -3 -3 0 -2 -3 -2 1 0 -4 -2 -3 3 0 -1-2 -2 1 6 -3 0 2 -1 -1 -3 -4 -1 -3 -3 -1 0 -1 -4 -3 -3 4 1 -10 -3 -3 -3 9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2-1 1 0 0 -3 5 2 -2 0 -3 -2 1 0 -3 -1 0 -1 -2 -1 -2 0 3 -1-1 0 0 2 -4 2 5 -2 0 -3 -3 1 -2 -3 -1 0 -1 -3 -2 -2 1 4 -10 -2 0 -1 -3 -2 -2 6 -2 -4 -4 -2 -3 -3 -2 0 -2 -2 -3 -3 -1 -2 -1-2 0 1 -1 -3 0 0 -2 8 -3 -3 -1 -2 -1 -2 -1 -2 -2 2 -3 0 0 -1-1 -3 -3 -3 -1 -3 -3 -4 -3 4 2 -3 1 0 -3 -2 -1 -3 -1 3 -3 -3 -1-1 -2 -3 -4 -1 -2 -3 -4 -3 2 4 -2 2 0 -3 -2 -1 -2 -1 1 -4 -3 -1-1 2 0 -1 -3 1 1 -2 -1 -3 -2 5 -1 -3 -1 0 -1 -3 -2 -2 0 1 -1-1 -1 -2 -3 -1 0 -2 -3 -2 1 2 -1 5 0 -2 -1 -1 -1 -1 1 -3 -1 -1-2 -3 -3 -3 -2 -3 -3 -3 -1 0 0 -3 0 6 -4 -2 -2 1 3 -1 -3 -3 -1-1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4 7 -1 -1 -4 -3 -2 -2 -1 -21 -1 1 0 -1 0 0 0 -1 -2 -2 0 -1 -2 -1 4 1 -3 -2 -2 0 0 00 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 1 5 -2 -2 0 -1 -1 0-3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1 1 -4 -3 -2 11 2 -3 -4 -3 -2-2 -2 -2 -3 -2 -1 -2 -3 2 -1 -1 -2 -1 3 -3 -2 -2 2 7 -1 -3 -2 -10 -3 -3 -3 -1 -2 -2 -3 -3 3 1 -2 1 -1 -2 -2 0 -3 -1 4 -3 -2 -1-2 -1 3 4 -3 0 1 -1 0 -3 -4 0 -3 -3 -2 0 -1 -4 -3 -3 4 1 -1-1 0 0 1 -3 3 4 -2 0 -3 -3 1 -1 -3 -1 0 -1 -3 -2 -2 1 4 -10 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 0 0 -2 -1 -1 -1 -1 -1

Page 149: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

149

Dynamic programming (Python) 1/4

#!/usr/bin/python# Needleman - Wunsch dynamic programming# programmed by Keehyoung Jooimport sys, string, osimport Numeric##############################################################MTX = 'BLOSUM62'#MTX = 'PAM70'd = 10 # open gap penaltyAmino = ['A','R','N','D','C','Q','E','G','H','I','L',

'K','M','F','P','S','T','W','Y','V','B','Z','X']# J, O, U not in Amino list##############################################################def read_score_matrix(S):

f=open(MTX,'r')for x in Amino:

S[x]={}line = f.readline()values = map(int,string.split(line))for i in range(len(Amino)):

y = Amino[i]S[x][y] = values[i]

Page 150: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

150

Dynamic programming (Python) 2/4def align(p,q,V):

P = []Q = []i = len(p)j = len(q)while 1:

if i==j==0: breakif V[i,j] == 0:

P.insert(0,p[i-1])Q.insert(0,q[j-1])i, j = i-1, j-1

elif V[i,j] == 1:P.insert(0,p[i-1])Q.insert(0,'-')i = i-1

else:P.insert(0,'-')Q.insert(0,q[j-1])j = j-1

P = "".join(P)Q = "".join(Q)return P, Q

Page 151: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

151

Dynamic programming (Python) 3/4

def Dynamic(p,q,Score): # Needleman - Wunsch Algorithmn=len(p)m=len(q)F=Numeric.zeros((n+1,m+1),Numeric.Int)V=Numeric.zeros((n+1,m+1),Numeric.Int)for i in range(1,n+1):

F[i,0] = -i * d # d: open gap penaltyV[i,0] = 1

for j in range(1,m+1):F[0,j] = -j * dV[0,j] = 2

for i in range(1,n+1):for j in range(1,m+1):

L = [F[i-1,j-1]+S[p[i-1]][q[j-1]],F[i-1,j] - d, F[i,j-1] - d]

F[i,j] = max(L)V[i,j] = L.index(F[i,j])

P, Q = align(p,q,V)return P, Q, F[n,m]

Page 152: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

152

Dynamic programming (Python) 4/4

##############################################################if __name__ == '__main__':

S={}read_score_matrix(S)p=raw_input('input your seq 1 : ')q=raw_input('input your seq 2 : ')p=p.upper()q=q.upper()Score = 0(P, Q, Score) = Dynamic(p,q,Score)printprint 'Alignment result.....\n'print 'Score = %d' % Scoreprint 'seq 1 : %s' % Pprint 'seq 2 : %s' % Qprint

Page 153: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

153

Ramachandran map (Python) 교재:p. 175

# Homework #5 Ramachandran_Map# 2007. 04.11 by Shin, Seung-Woo

# Import PROSS modulefrom PROSS import Proteinfrom PROSS import read_pdb

# Read PDB file#f_name_pdb=raw_input("Input PDB file name : ")#mol=read_pdb(f_name_pdb)mol=read_pdb('1chc.pdb')

# file pointer for outputfp_for_out=open('Ramachandran_map.txt','w')for atom in mol:

index=0atom.gaps()phi, psi, omega=atom.torsions()[:3]for residue in atom.elements:

fp_for_out.write('%10.2f %10.2f\n' %(phi[index],psi[index]))index+=1

fp_for_out.close()

Page 154: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

154

1chc.pdb 파일중일부

ATOM 1 N MET 1 66.104 56.583 -35.505 1.00 0.00 1CHC 85

Calpha 가발견되는자리

Page 155: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

155

Calpha-Calpha distance map (Python) (1/4)# homework 5, author: Shin, Seung-Woo# making distance matrix for Caimport math,string,os# Read PDB fileinput_file_name=raw_input("Input the file name: ")fp_for_in=open(input_file_name,'r')fp_for_tmp=open("tmp.txt",'w')atom_count=0

# 2Pass processing because we don't know the number of Ca in advance# Step 1. Parsing Ca Atom partwhile 1:

line=fp_for_in.readline()if not line: breakelse:

token=string.split(line)if(token[0]=="ATOM" and token[2]=="CA"):

line=token[0]+" "+token[5]+" "+token[6]+" "+token[7]+"\n"fp_for_tmp.write(line)atom_count=atom_count+1

fp_for_in.close()fp_for_tmp.close()

Page 156: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

156

Calpha-Calpha distance map (Python) (2/4)

# Step 2. read Ca X,Y,Z coordinates in arraya_mat=[[0]*3 for i in xrange(atom_count)]fp_for_tmp=open("tmp.txt",'r')

for i in range(0,atom_count):line=fp_for_tmp.readline()if not line: breakelse:

token=string.split(line)a_mat[i][0]=float(token[1])a_mat[i][1]=float(token[2])a_mat[i][2]=float(token[3])

fp_for_tmp.close()

Page 157: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

157

Calpha-Calpha distance map (Python) (3/4)

# Define the matrix# Fill the distance matrixdist_matrix=[[0]*atom_count for i in xrange(atom_count)]

for i in range(0,atom_count):for j in range(i,atom_count):

dist=(a_mat[i][0]-a_mat[j][0])**2+(a_mat[i][1]-a_mat[j][1])**2+(a_mat[i][2]-a_mat[j][2])**2dist=round(math.sqrt(dist))if(dist>9):

dist='.'dist_matrix[i][j]=distdist_matrix[j][i]=dist

else:dist_matrix[i][j]=int(dist)dist_matrix[j][i]=int(dist)

Page 158: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

158

Calpha-Calpha distance map (Python) (4/4)fp_for_out=open("distance_mat.txt",'w')#===========================#print distance matrix#===========================# Write first rowfp_for_out.write(" ")for i in range(1,atom_count+1):

if i%10==0:fp_for_out.write("A")

else:str0=i%10str1=str(str0)fp_for_out.write(str1)

fp_for_out.write("\n")#write dist_matrixfor i in range(0,atom_count):

i2=i+1if i2<10:

str1=" "+str(i2)+" "else:

str1=str(i2)+" "fp_for_out.write(str1)for j in range(0,atom_count):

str2=str(dist_matrix[i][j])fp_for_out.write(str2)

fp_for_out.write("\n")

fp_for_out.close()# Delete temp fileos.unlink("tmp.txt")

Page 159: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

159

Fashion changes, style remains. - Gabrielle "Coco" Chanel

Fashion is a form of ugliness so intolerable that we have to alter it every six months. - Oscar Wilde

Every generation laughs at the old fashions, but follows religiously the new. - Henry David Thoreau

Page 160: Stay hungry, stay foolish.pds24.egloos.com/pds/201201/22/11/Computer_programming... · 2012-01-22 · Computer programming (often shortened to programming or coding) is the process

160

References

http://www.python.orghttp://turing.cafe24.com/http://www.dickbaldwin.com/tocpyth.htmhttp://www.diveintopython.org/toc/index.htmlhttp://pages.cs.wisc.edu/~fischer/cs538.s07/python.tutorial.pdfhttp://numpy.sourceforge.net/numdoc/HTML/numdoc.htmhttp://www.pasteur.fr/recherche/unites/sis/formation/python/index.htmlhttp://numpy.scipy.org/numpydoc/numpy.htmlhttp://numpy.scipy.org/numpy.pdfhttp://www.wellho.net/course/python.htmlhttp://www.pentangle.net/python/handbook/handbook.pdfhttp://docs.python.org/lib/lib.htmlhttp://rgruet.free.fr/PQR2.3.htmlhttp://www.awaretek.com/tutorials.html#beginhttp://www.biopython.org