Communitygithub.com

biopython

종합적인 분자생물학 툴킷. 서열 조작, 파일 파싱(FASTA/GenBank/PDB), 계통발생학 및 프로그램 기반 NCBI/PubMed 접근(Bio.Entrez)에 사용합니다. 배치 처리, 맞춤 생정보학 파이프라인, BLAST 자동화에 최적입니다. 빠른 조회에는 gget을, 다중 서비스 통합에는 bioservices를 사용하세요.

biopython란 무엇인가요?

Biopython은 파이썬을 위한 종합적인 분자생물학 툴킷으로, DNA/RNA/단백질 서열 조작, FASTA/GenBank/PDB 등 다양한 생물정보학 파일 포맷 입출력, NCBI 데이터베이스(GenBank, PubMed 등) 프로그램 기반 접근, BLAST 검색 자동화, 서열 정렬, 단백질 구조 분석, 계통수 조작 등 방대한 기능을 제공합니다. 현재 안정 버전은 1.87이며, Python 3.10–3.14 및 PyPy3.10을 지원합니다. 이 스킬은 사용자가 생물학적 서열 데이터를 다루거나, 맞춤형 생정보학 파이프라인을 구축하거나, NCBI 데이터베이스와 상호작용해야 할 때 특히 유용합니다. 핵심 모듈인 Bio.SeqIO, Bio.Align, Bio.Entrez, Bio.Blast, Bio.PDB, Bio.Phylo 등을 통해 각 작업 영역에 특화된 기능을 제공하며, 참조 문서(references/ 디렉토리)를 통해 상세 사용법과 예제를 확인할 수 있습니다. 대규모 파일 처리를 위한 반복자 패턴, NCBI API 키를 통한 속도 제한 준수, 명시적 임포트 등 모범 사례를 따르는 것이 중요합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/biopython

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Biopython: 파이썬을 위한 전산 분자생물학

개요

Biopython은 생물학적 연산을 위한 무료 파이썬 도구 모음입니다. 서열 조작, 파일 입출력, 데이터베이스 접근, 구조 생물정보학, 계통발생학 및 기타 다양한 생물정보학 작업을 위한 기능을 제공합니다. 현재 버전은 Biopython 1.87 (2026년 3월 30일 출시)입니다. Python 3.10-3.14 및 PyPy3.10을 지원하며, NumPy가 필요합니다. Biopython 1.87은 신뢰할 수 없는 파일을 파싱할 때 Bio.Entrez.Parser의 CVE-2025-68463을 해결했으므로, 외부에서 제공된 Entrez XML을 파싱하는 워크플로우에서는 1.87+를 선호하세요.

이 스킬을 사용해야 할 때

다음과 같은 경우에 이 스킬을 사용하세요:

  • 생물학적 서열(DNA, RNA 또는 단백질) 작업
  • 생물학적 파일 포맷(FASTA, GenBank, FASTQ, PDB, mmCIF 등) 읽기, 쓰기 또는 변환
  • Entrez를 통한 NCBI 데이터베이스(GenBank, PubMed, Protein, Gene 등) 접근
  • BLAST 검색 실행 또는 BLAST 결과 파싱
  • 서열 정렬(쌍별 정렬 또는 다중 서열 정렬) 수행
  • PDB 파일에서 단백질 구조 분석
  • 계통수 생성, 조작 또는 시각화
  • 서열 모티프 찾기 또는 모티프 패턴 분석
  • 서열 통계(GC 함량, 분자량, 녹는 온도 등) 계산
  • 구조 생물정보학 작업 수행
  • 집단 유전학 데이터 작업
  • 기타 모든 전산 분자생물학 작업

핵심 역량

Biopython은 모듈형 하위 패키지로 구성되어 있으며, 각각 특정 생물정보학 영역을 다룹니다:

  1. 서열 처리 - Bio.Seq와 Bio.SeqIO: 서열 조작 및 파일 입출력
  2. 정렬 분석 - Bio.Align과 Bio.AlignIO: 쌍별 및 다중 서열 정렬
  3. 데이터베이스 접근 - Bio.Entrez: NCBI 데이터베이스 프로그램 기반 접근
  4. BLAST 작업 - Bio.Blast: BLAST 검색 실행 및 파싱
  5. 구조 생물정보학 - Bio.PDB: 3D 단백질 구조 작업
  6. 계통발생학 - Bio.Phylo: 계통수 조작 및 시각화
  7. 고급 기능 - 모티프, 집단 유전학, 서열 유틸리티 등

설치 및 설정

재현성을 위해 명시적 버전 고정으로 현재 안정 Biopython 릴리스를 설치하세요:

uv pip install "biopython==1.87"

NCBI 데이터베이스 접근을 위해 항상 이메일 주소를 설정하세요(NCBI 필수). 재사용 가능한 소프트웨어의 경우 안정적인 Entrez.tool 값을 설정하고 도구/이메일을 NCBI에 등록하세요. 더 높은 속도 제한(3 req/s 대신 10 req/s)을 위해 환경 변수에서만 NCBI_API_KEY를 읽어오세요 — 키를 하드코딩하거나 관련 없는 환경 변수를 로드하지 마세요:

import os
from Bio import Entrez

Entrez.email = "[email protected]"  # 필수 — 실제 이메일을 사용하세요
Entrez.tool = "your_tool_name"  # 선택 사항이지만 재사용 가능한 소프트웨어에 권장

# 선택 사항: https://www.ncbi.nlm.nih.gov/account/settings/ 에서 등록
if api_key := os.environ.get("NCBI_API_KEY"):
    Entrez.api_key = api_key

이 스킬 사용하기

이 스킬은 기능 영역별로 체계화된 포괄적인 문서를 제공합니다. 작업을 수행할 때는 관련 참조 문서를 참조하세요:

1. 서열 처리 (Bio.Seq 및 Bio.SeqIO)

참조: references/sequence_io.md

용도:

  • 생물학적 서열 생성 및 조작
  • 서열 파일 읽기 및 쓰기 (FASTA, GenBank, FASTQ 등)
  • 파일 포맷 간 변환
  • 대용량 파일에서 서열 추출
  • 서열 번역, 전사, 역상보 서열
  • SeqRecord 객체 작업

빠른 예시:

from Bio import SeqIO

# FASTA 파일에서 서열 읽기
for record in SeqIO.parse("sequences.fasta", "fasta"):
    print(f"{record.id}: {len(record.seq)} bp")

# GenBank를 FASTA로 변환
SeqIO.convert("input.gb", "genbank", "output.fasta", "fasta")

2. 정렬 분석 (Bio.Align 및 Bio.AlignIO)

참조: references/alignment.md

용도:

  • 쌍별 서열 정렬 (전역 및 지역)
  • 다중 서열 정렬 읽기 및 쓰기
  • 치환 행렬 사용 (BLOSUM, PAM)
  • 정렬 통계 계산
  • 정렬 매개변수 사용자 정의

빠른 예시:

from Bio import Align

# 쌍별 정렬
aligner = Align.PairwiseAligner()
aligner.mode = 'global'
alignments = aligner.align("ACCGGT", "ACGGT")
print(alignments[0])

3. 데이터베이스 접근 (Bio.Entrez)

참조: references/databases.md

용도:

  • NCBI 데이터베이스 검색 (PubMed, GenBank, Protein, Gene 등)
  • 서열 및 레코드 다운로드
  • 출판 정보 가져오기
  • 데이터베이스 간 관련 레코드 찾기
  • 적절한 속도 제한을 적용한 배치 다운로드

빠른 예시:

from Bio import Entrez
Entrez.email = "[email protected]"

# PubMed 검색
handle = Entrez.esearch(db="pubmed", term="biopython", retmax=10)
results = Entrez.read(handle)
handle.close()
print(f"{results['Count']}개의 결과를 찾았습니다")

4. BLAST 작업 (Bio.Blast)

참조: references/blast.md

용도:

  • NCBI 웹 서비스를 통한 BLAST 검색 실행
  • 로컬 BLAST 검색 실행
  • BLAST XML 출력 파싱
  • E-값 또는 동일성으로 결과 필터링
  • 히트 서열 추출

빠른 예시:

from Bio.Blast import NCBIWWW, NCBIXML

# BLAST 검색 실행
result_handle = NCBIWWW.qblast("blastn", "nt", "ATCGATCGATCG")
blast_record = NCBIXML.read(result_handle)

# 상위 히트 표시
for alignment in blast_record.alignments[:5]:
    print(f"{alignment.title}: E-value={alignment.hsps[0].expect}")

5. 구조 생물정보학 (Bio.PDB)

참조: references/structure.md

용도:

  • PDB 및 mmCIF 구조 파일 파싱
  • 단백질 구조 계층 구조 탐색 (SMCRA: Structure/Model/Chain/Residue/Atom)
  • 거리, 각도 및 이면각 계산
  • 이차 구조 할당 (DSSP)
  • 구조 중첩 및 RMSD 계산
  • 구조에서 서열 추출

빠른 예시:

from Bio.PDB import PDBParser

# 구조 파싱
parser = PDBParser(QUIET=True)
structure = parser.get_structure("1crn", "1crn.pdb")

# 알파 탄소 간 거리 계산
chain = structure[0]["A"]
distance = chain[10]["CA"] - chain[20]["CA"]
print(f"거리: {distance:.2f} Å")

6. 계통발생학 (Bio.Phylo)

참조: references/phylogenetics.md

용도:

  • 계통수 읽기 및 쓰기 (Newick, NEXUS, phyloXML)
  • 거리 행렬 또는 정렬에서 트리 구축
  • 트리 조작 (가지치기, 뿌리 변경, 사다리화)
  • 계통 발생 거리 계산
  • 컨센서스 트리 생성
  • 트리 시각화

빠른 예시:

from Bio import Phylo

# 트리 읽기 및 시각화
tree = Phylo.read("tree.nwk", "newick")
Phylo.draw_ascii(tree)

# 거리 계산
distance = tree.distance("Species_A", "Species_B")
print(f"거리: {distance:.3f}")

7. 고급 기능

참조: references/advanced.md

용도:

  • 서열 모티프 (Bio.motifs) - 모티프 패턴 찾기 및 분석
  • 집단 유전학 (Bio.PopGen) - GenePop 파일, Fst 계산, Hardy-Weinberg 검정
  • 서열 유틸리티 (Bio.SeqUtils) - GC 함량, 녹는 온도, 분자량, 단백질 분석
  • 제한 효소 분석 (Bio.Restriction) - 제한 효소 부위 찾기
  • 클러스터링 (Bio.Cluster) - K-평균 및 계층적 클러스터링
  • 유전체 다이어그램 (GenomeDiagram) - 유전체 특징 시각화

빠른 예시:

from Bio.SeqUtils import gc_fraction, molecular_weight
from Bio.Seq import Seq

seq = Seq("ATCGATCGATCG")
print(f"GC 함량: {gc_fraction(seq):.2%}")
print(f"분자량: {molecular_weight(seq, seq_type='DNA'):.2f} g/mol")

일반 워크플로우 지침

문서 읽기

사용자가 특정 Biopython 작업에 대해 물을 때:

  1. 작업 설명에 따라 관련 모듈 식별
  2. Read 도구를 사용하여 적절한 참조 파일 읽기
  3. 관련 코드 패턴 추출 및 사용자의 특정 요구에 맞게 조정
  4. 작업에 필요할 경우 여러 모듈 결합

참조 파일 검색 패턴 예시:

# 특정 함수에 대한 정보 찾기
rg -n "SeqIO.parse" references/sequence_io.md

# 특정 작업의 예시 찾기
rg -n "BLAST" references/blast.md

# 특정 개념에 대한 정보 찾기
rg -n "alignment" references/alignment.md

Biopython 코드 작성

Biopython 코드를 작성할 때 다음 원칙을 따르세요:

  1. 모듈을 명시적으로 가져오기

    from Bio import SeqIO, Entrez
    from Bio.Seq import Seq
    
  2. NCBI 데이터베이스 사용 시 Entrez 이메일 설정; 존재하는 경우 환경에서만 NCBI_API_KEY를 로드

    import os
    from Bio import Entrez
    
    Entrez.email = "[email protected]"
    Entrez.tool = "your_tool_name"
    if api_key := os.environ.get("NCBI_API_KEY"):
        Entrez.api_key = api_key
    
  3. 적절한 파일 포맷 사용 - 작업에 가장 적합한 포맷 확인

    # 일반적인 포맷: "fasta", "genbank", "fastq", "clustal", "phylip"
    
  4. 파일을 적절히 처리 - 사용 후 핸들 닫기 또는 컨텍스트 관리자 사용

    with open("file.fasta") as handle:
        records = SeqIO.parse(handle, "fasta")
    
  5. 대용량 파일에는 반복자 사용 - 모든 것을 메모리에 로드하지 않기

    for record in SeqIO.parse("large_file.fasta", "fasta"):
        # 한 번에 하나의 레코드 처리
    
  6. 오류를 적절히 처리 - 네트워크 작업 및 파일 파싱은 실패할 수 있음

    from urllib.error import HTTPError
    
    try:
        handle = Entrez.efetch(db="nucleotide", id=accession)
    except HTTPError as e:
        print(f"오류: {e}")
    

일반적인 패턴

패턴 1: GenBank에서 서열 가져오기

from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

# 서열 가져오기
handle = Entrez.efetch(db="nucleotide", id="EU490707", rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
handle.close()

print(f"설명: {record.description}")
print(f"서열 길이: {len(record.seq)}")

패턴 2: 서열 분석 파이프라인

from Bio import SeqIO
from Bio.SeqUtils import gc_fraction

for record in SeqIO.parse("sequences.fasta", "fasta"):
    # 통계 계산
    gc = gc_fraction(record.seq)
    length = len(record.seq)

    # ORF 찾기, 번역 등
    protein = record.seq.translate()

    print(f"{record.id}: {length} bp, GC={gc:.2%}")

패턴 3: BLAST 및 상위 히트 가져오기

from Bio.Blast import NCBIWWW, NCBIXML
from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

# BLAST 실행
result_handle = NCBIWWW.qblast("blastn", "nt", sequence)
blast_record = NCBIXML.read(result_handle)

# 상위 히트 Accession 가져오기
accessions = [aln.accession for aln in blast_record.alignments[:5]]

# 서열 가져오기
for acc in accessions:
    handle = Entrez.efetch(db="nucleotide", id=acc, rettype="fasta", retmode="text")
    record = SeqIO.read(handle, "fasta")
    handle.close()
    print(f">{record.description}")

패턴 4: 서열에서 계통수 구축

from Bio import AlignIO, Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor

# 정렬 읽기
alignment = AlignIO.read("alignment.fasta", "fasta")

# 거리 계산
calculator = DistanceCalculator("identity")
dm = calculator.get_distance(alignment)

# 트리 구축
constructor = DistanceTreeConstructor()
tree = constructor.nj(dm)

# 시각화
Phylo.draw_ascii(tree)

모범 사례

  1. 코드를 작성하기 전에 항상 관련 참조 문서를 읽으세요
  2. grep을 사용하여 참조 파일에서 특정 함수나 예제를 검색하세요
  3. 파싱 전에 파일 포맷을 검증하세요
  4. 누락된 데이터를 적절히 처리하세요 - 모든 레코드에 모든 필드가 있는 것은 아닙니다
  5. 다운로드한 데이터를 캐시하세요 - 동일한 서열을 반복적으로 다운로드하지 마세요
  6. NCBI 속도 제한을 준수하세요 - 재사용 가능한 소프트웨어의 경우 API 키, 등록된 도구/이메일 값을 사용하고 대규모 작업의 경우 Entrez history/배치를 사용하세요
  7. 대용량 파일을 처리하기 전에 작은 데이터셋으로 테스트하세요
  8. Biopython을 최신 상태로 유지하여 최신 기능과 버그 수정을 받으세요
  9. 번역에 적절한 유전 코드 테이블을 사용하세요
  10. 재현성을 위해 분석 매개변수를 문서화하세요

일반적인 문제 해결

문제: 로거 'Bio.Entrez'에 대한 핸들러를 찾을 수 없습니다

해결책: 이것은 단지 경고입니다. Entrez.email을 설정하여 억제하세요.

문제: NCBI에서 "HTTP Error 400"

해결책: ID/Accession이 유효하고 올바르게 포맷되었는지 확인하세요.

문제: 파일 파싱 중 "ValueError: EOF"

해결책: 파일 포맷이 지정된 포맷 문자열과 일치하는지 확인하세요.

문제: "sequences are not the same length"로 정렬 실패

해결책: AlignIO 또는 MultipleSeqAlignment를 사용하기 전에 서열이 정렬되었는지 확인하세요.

문제: BLAST 검색이 느립니다

해결책: 대규모 검색에는 로컬 BLAST를 사용하거나 결과를 캐시하세요.

문제: PDB 파서 경고

해결책: PDBParser(QUIET=True)를 사용하여 경고를 억제하거나 구조 품질을 조사하세요.

문제: Bio.HMM, Bio.MarkovModel 또는 Bio.Application에 대한 ImportError

해결책: 이러한 모듈은 Biopython 1.86에서 제거되었습니다. HMM에는 hmmlearn을, Bio.Application CLI 래퍼 대신 표준 라이브러리 subprocess 모듈을 사용하세요.

문제: 1.86+로 업그레이드 후 PairwiseAligner가 더 적은 정렬을 반환합니다

해결책: 기본 갭 점수가 1.86에서 0에서 -1로 변경되어 사소한 동점 정렬이 제거되었습니다. 필요한 경우 aligner.gap_score = 0을 설정하여 이전 동작을 복원하세요 (references/alignment.md 참조).

추가 리소스

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

cobrapy

Constraint-based metabolic modeling (COBRA). FBA, FVA, gene knockouts, flux sampling, SBML models, for systems biology and metabolic engineering analysis.

관련 스킬