제36회 KOBIC 차세대 생명정보학 교육 워크샵 데이터 과학을 위한 파이썬 기초
Table of Contents
개요 #
- 일시: 2017-10-24 ~ 2017-10-25
- 장소: KT인재개발원 제1연수관 203호
- 내용: 프로그래밍 언어 파이썬 집중 단기 학습을 통해 생물정보 데이터 분석 실무 능력 습득
- URL: http://kobicedu.labkm.net
강의 특징 #
- 이론과 실습 병행
- 첫째날 노트북에 직접 python 설치하여 실습 (서버에 원격 접속 (putty) 병행)
-
둘째날 개인 PC에 Jupyter 설치하여 실습
-
사전 준비 사항
- 실습시 개인 PC에 Anaconda 설치 (Anaconda_jupyter-설치방법.pdf)
강의 자료 (실습데이터 포함) #
주요 리소스 #
- http://rosalind.info 생물정보 학습을 위한 파이썬 문제 풀이 사이트
- http://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb
교육 환경 #
원격 실습 서버 접속 방법 #
로컬컴퓨터에 파이썬을 설치하여 실습하거나 원격 서버에서 실습, 실습서버 원격접속 방법은 아래 참고
Windows #
- Putty 프로그램 설치: Putty download page에서 Windows용 MSI 설치 파일 putty-version-installer.msi 다운로드 및 실행
- Putty 프로그램 실행 후, 설정창에서 다음 입력 후 저장
- Host Name: edu.kobic.re.kr
- Saved Sessions: kobic33
- kobic33 선택 후
Open
클릭하여 접속 - login as: 부분에서 부여받은 아이디 입력
- kobic@edu.kobic.re.kr`s password: 부분에서 비밀번호 입력
- 접속 성공!
Linux/OS X #
iTerm 프로그램 구동 후, 다음처럼 입력하여 접속 (kobic23 사용자라면,)
$ ssh kobic23@edu.kobic.re.kr
Jupyter 설치 방법 #
(Anaconda_jupyter-설치방법.pdf) 참고하여 설치
filezilla 설치: https://filezilla-project.org #
파이썬 참고 정보 #
- 파이썬 코딩 스타일 PEP 8
- PEP 한글 번역 프로젝트
- 파이썬 코딩 스타일 한국어 정보 파이썬 코딩 컨벤션
Matplolib 한글폰트 설정 #
윈도우에서
from matplotlib import font_manager, rc
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
맥에서
matplotlib.font_manager.get_fontconfig_fonts()
krfont = {'family': 'AppleGothic', 'weight': 'bold', 'size': 10}
matplotlib.rc('font', **krfont)
리눅스에서
matplotlib.font_manager.get_fontconfig_fonts()
krfont = {'family': 'UnDotum', 'weight': 'bold', 'size': 10}
matplotlib.rc('font', **krfont)
연습문제 풀이 (첫째날) #
set_operation.py #
#!python
a = input("Set A: ")
b = input("Set B: ")
a_set = set(a.split())
b_set = set(b.split())
print()
print('Union --->', ' '.join(a_set | b_set))
print('Intersection -->', ' '.join(a_set & b_set))
print('Difference -->', ' '.join(a_set - b_set))
countseq.py #
#!python
seq = 'AGCTACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTCTCTGACAGCAGCTTCTGAACTGGTTACCTGCCGTGAGTAAATTAAAATTTTATTGACTTAGGTCACTAAATACTTTAACCAATATAGGCATAGCGCACAGACAGATAAAAATTACAGAGTACACAACATCCATGAAACGCATTAGCACCACCATTACCACCACCATCACCACCACCATCACCATTACCATTACCACAGGTAACGGTGCGGGCTGACGCGTACAGGAAACACAGAAAAAAGCCCGCACCTGACAGTGCGGGCTTTTTTTTCGACCAAAGGTAACGAGGTAACAACCATGCGAGTGTTGAAGTTCGGCGGTACATCAGTGGCAAATGCAGAACGTTTTCTGCGGGTTGCCGATA'
numa = seq.count('A')
numg = seq.count('G')
print('Number of As:{}'.format(numa))
print('Number of Gs:{}'.format(numg))
if numa > numg:
print("A is more than G")
elif numg > numa:
print("G is more than A")
elif numg == numa:
print("Same")
gugu.py #
#!python
for i in range(2, 10):
for j in range(1, 10):
print(i * j, end=" ")
print('')
find75.py #
#!python
for n in range(1500, 2701):
if (n % 7 == 0) and (n % 5 == 0):
print(n)
starta_gene.py #
#!python
accs = ['ab56', 'bh84', 'hv76', 'ay93', 'ap97', 'bd72']
for accession in accs:
if accession.startswith('a'):
print(accession)
printnum.py #
#!python
i = 0
while True:
if i >= 10:
break
if i % 2 == 0:
i += 1
continue
print(i)
i += 1
whileseq.py #
#!python
seq = input('Enter sequence: ')
i = 0
counta = 0
countg = 0
countt = 0
countc = 0
others = 0
while i < len(seq):
if seq[i] == 'A':
counta += 1
elif seq[i] == 'T':
countt += 1
elif seq[i] == 'G':
countg += 1
elif seq[i] == 'C':
countc += 1
else:
others += 1
if counta == 15:
print('Found 15th A!')
print('Number of As:{}'.format(counta))
print('Number of Ts:{}'.format(countt))
print('Number of Gs:{}'.format(countg))
print('Number of Cs:{}'.format(countc))
print('Number of others:{}'.format(others))
print(seq[:i + 1])
break
i += 1
randomnum.py #
#!python
import random
number = random.randint(1, 20)
count = 0
while True:
answer = int(input("Enter number: "))
count += 1
if number == answer:
print("정답입니다! {}번만에 맞추셨군요!".format(count))
break
elif number > answer:
print("{} 보다 큽니다!".format(answer))
else:
print("{} 보다 작습니다!".format(answer))
count.py #
#!python
import sys
f = open(sys.argv[1], 'r')
seq = f.read()
a = seq.count('A')
t = seq.count('T')
g = seq.count('G')
c = seq.count('C')
print a, c, g, t
f.close()
trans.py #
#!python
import sys
f = open(sys.argv[1], 'r')
seq = f.read()
rna = seq.replace('T', 'U')
print(rna)
f.close()
# 만일 rna서열을 파일로 쓰고 싶다면?
with open("rnaseq.txt", "w") as outfile:
outfile.write(rna)
count_trans.py #
#!python
import sys
def countseq(seq):
a = seq.count('A')
t = seq.count('T')
g = seq.count('G')
c = seq.count('C')
return (a, t, g, c)
def trans(seq):
rna = seq.replace('T', 'U')
return rna
f = open(sys.argv[1], 'r')
dna_seq = f.read()
(a, t, g, c) = countseq(dna_seq)
rna_seq = trans(dna_seq)
print(a, t, g, c)
print(rna_seq)
f.close()
compareseq1.py #
#!python
import sys
f = sys.stdin
maxseq = ''
maxname = ''
for line in f.readlines():
name, seq = line.split(' ')
if not maxname:
maxname = name
mexseq = seq
continue
if len(seq) > len(maxseq):
maxname = name
maxseq = seq
print("SEQUNCE NAME:", maxname)
print(maxseq)
f.close()
compareseq2.py #
#!python
import sys
f = open(sys.argv[1], 'r')
maxseq = ''
maxname = ''
for line in f.readlines():
name, seq = line.split(' ')
if not maxname:
maxname = name
mexseq = seq
continue
if len(seq) > len(maxseq):
maxname = name
maxseq = seq
print("SEQUNCE NAME:", maxname)
print(maxseq)
f.close()
hamm.py #
#!python
import sys
hamming_distance = 0
f = open(sys.argv[1], 'r')
seq1, seq2 = f.readlines()
for a, b in zip(seq1, seq2):
if a != b:
hamming_distance += 1
print(hamming_distance)
f.close()
연습문제 풀이 (둘째날) #
word frequency (임의의 파일을 읽어 자주 출현하는 단어 top 20개를 빈도와 함께 출력) #
#!python
import sys
d = {}
for line in sys.stdin:
words = line.split()
for word in words:
if word in d:
d[word] += 1
else:
d[word] = 1
for word, frequency in sorted(d.items(),
key=lambda x: x[1], reverse=True)[:20]:
print(word, frequency)
구구단 함수를 이용하여 #
#!python
def print_gugu(x):
for y in range(1, 10):
print("{} x {} = {}".format(x, y, x * y))
n = input("Please insert an integer: ")
print_gugu(int(n))
명령행 인터페이스 #
#!python
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--top", help="상위 항목 표시수",
type=int, default=20)
parser.add_argument("-c", "--case_insensitive", help="대소문자 구분안함",
default=False, action="store_true")
args = parser.parse_args()
d = {}
for line in sys.stdin:
words = line.split()
for word in words:
if args.case_insensitive:
word = word.lower()
if word in d:
d[word] += 1
else:
d[word] = 1
for word, frequency in sorted(d.items(),
key=lambda x: x[1], reverse=True)[:args.top]:
print(word, frequency)
matplotlib 연습문제 5 #
#!python
import matplotlib.pyplot as plt
%matplotlib inline
data = pd.read_csv('weight.csv')
# figure, subplot 생성
fig, axes = plt.subplots(3,1, figsize=(5,20))
# 국가별 체충의 boxplot 그리기
data.boxplot(column='Weight', by='Country', ax=axes[0])
# 체중의 histogram 그리기
data['Weight'].hist(ax=axes[1], color='gray', bins=20, range=(0,120))
# 성별로 pie차트 그리기
data['Sex'].value_counts().plot(ax=axes[2], kind='pie')
plt.subplots_adjust(hspace=0.5)
#ex5.png에 저장
plt.savefig(‘ex5.png’)
matplotlib 연습문제 6 #
#!python
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
def get_len(row):
return row.end - row.start
# figure, subplot 생성
fig, axes = plt.subplots(2,1)
genes_df = pd.read_table(
"data/rice_locus.gff",
names=['chr', 'source', 'type', 'start', 'end',
'score', 'strand', 'phase', 'attrs'],
)
genes_df['length'] = genes_df.apply(get_len, axis=1)
# 0~20000 length
filtered1 = genes_df[(genes_df['chr'] == 'chr01') & (genes_df['length'] < 20000)]
filtered1['length'].hist(bins=40, ax=axes[0])
# 20000~ length
filtered2 = genes_df[(genes_df['chr'] == 'chr01') & (genes_df['length'] >= 20000)]
filtered2['length'].hist(bins=40, ax=axes[1])
plt.savefig('rice_gene_len.png')