{"id":"biopython","name":"biopython","summary":"包括的な分子生物学ツールキット。配列操作、ファイル解析(FASTA/GenBank/PDB)、系統発生学、プログラム的NCBI/PubMedアクセス(Bio.Entrez)への利用。","body":"# Biopython: Computational Molecular Biology in Python\n\n## Overview\n\nBiopython is a comprehensive set of freely available Python tools for biological computation. It provides functionality for sequence manipulation, file I/O, database access, structural bioinformatics, phylogenetics, and many other bioinformatics tasks. The current version is **Biopython 1.87** (released 30 March 2026). It supports **Python 3.10-3.14** and PyPy3.10, and requires NumPy. Biopython 1.87 also addresses **CVE-2025-68463** in `Bio.Entrez.Parser` when parsing untrusted files, so prefer 1.87+ for workflows that parse externally supplied Entrez XML.\n\n## When to Use This Skill\n\nUse this skill when:\n\n- Working with biological sequences (DNA, RNA, or protein)\n- Reading, writing, or converting biological file formats (FASTA, GenBank, FASTQ, PDB, mmCIF, etc.)\n- Accessing NCBI databases (GenBank, PubMed, Protein, Gene, etc.) via Entrez\n- Running BLAST searches or parsing BLAST results\n- Performing sequence alignments (pairwise or multiple sequence alignments)\n- Analyzing protein structures from PDB files\n- Creating, manipulating, or visualizing phylogenetic trees\n- Finding sequence motifs or analyzing motif patterns\n- Calculating sequence statistics (GC content, molecular weight, melting temperature, etc.)\n- Performing structural bioinformatics tasks\n- Working with population genetics data\n- Any other computational molecular biology task\n\n## Core Capabilities\n\nBiopython is organized into modular sub-packages, each addressing specific bioinformatics domains:\n\n1. **Sequence Handling** - Bio.Seq and Bio.SeqIO for sequence manipulation and file I/O\n2. **Alignment Analysis** - Bio.Align and Bio.AlignIO for pairwise and multiple sequence alignments\n3. **Database Access** - Bio.Entrez for programmatic access to NCBI databases\n4. **BLAST Operations** - Bio.Blast for running and parsing BLAST searches\n5. **Structural Bioinformatics** - Bio.PDB for working with 3D protein structures\n6. **Phylogenetics** - Bio.Phylo for phylogenetic tree manipulation and visualization\n7. **Advanced Features** - Motifs, population genetics, sequence utilities, and more\n\n## Installation and Setup\n\nInstall the current stable Biopython release with an explicit version pin for reproducibility:\n\n```bash\nuv pip install \"biopython==1.87\"\n```\n\nFor NCBI database access, always set your email address (required by NCBI). For reusable software, set a stable `Entrez.tool` value and register the tool/email with NCBI. For higher rate limits (10 req/s instead of 3 req/s), read only `NCBI_API_KEY` from the environment — do not hardcode keys or load unrelated environment variables:\n\n```python\nimport os\nfrom Bio import Entrez\n\nEntrez.email = \"your.email@example.com\"  # required — use your real email\nEntrez.tool = \"your_tool_name\"  # optional but recommended for reusable software\n\n# Optional: register at https://www.ncbi.nlm.nih.gov/account/settings/\nif api_key := os.environ.get(\"NCBI_API_KEY\"):\n    Entrez.api_key = api_key\n```\n\n## Using This Skill\n\nThis skill provides comprehensive documentation organized by functionality area. When working on a task, consult the relevant reference documentation:\n\n### 1. Sequence Handling (Bio.Seq & Bio.SeqIO)\n\n**Reference:** `references/sequence_io.md`\n\nUse for:\n- Creating and manipulating biological sequences\n- Reading and writing sequence files (FASTA, GenBank, FASTQ, etc.)\n- Converting between file formats\n- Extracting sequences from large files\n- Sequence translation, transcription, and reverse complement\n- Working with SeqRecord objects\n\n**Quick example:**\n```python\nfrom Bio import SeqIO\n\n# Read sequences from FASTA file\nfor record in SeqIO.parse(\"sequences.fasta\", \"fasta\"):\n    print(f\"{record.id}: {len(record.seq)} bp\")\n\n# Convert GenBank to FASTA\nSeqIO.convert(\"input.gb\", \"genbank\", \"output.fasta\", \"fasta\")\n```\n\n### 2. Alignment Analysis (Bio.Align & Bio.AlignIO)\n\n**Reference:** `references/alignment.md`\n\nUse for:\n- Pairwise sequence alignment (global and local)\n- Reading and writing multiple sequence alignments\n- Using substitution matrices (BLOSUM, PAM)\n- Calculating alignment statistics\n- Customizing alignment parameters\n\n**Quick example:**\n```python\nfrom Bio import Align\n\n# Pairwise alignment\naligner = Align.PairwiseAligner()\naligner.mode = 'global'\nalignments = aligner.align(\"ACCGGT\", \"ACGGT\")\nprint(alignments[0])\n```\n\n### 3. Database Access (Bio.Entrez)\n\n**Reference:** `references/databases.md`\n\nUse for:\n- Searching NCBI databases (PubMed, GenBank, Protein, Gene, etc.)\n- Downloading sequences and records\n- Fetching publication information\n- Finding related records across databases\n- Batch downloading with proper rate limiting\n\n**Quick example:**\n```python\nfrom Bio import Entrez\nEntrez.email = \"your.email@example.com\"\n\n# Search PubMed\nhandle = Entrez.esearch(db=\"pubmed\", term=\"biopython\", retmax=10)\nresults = Entrez.read(handle)\nhandle.close()\nprint(f\"Found {results['Count']} results\")\n```\n\n### 4. BLAST Operations (Bio.Blast)\n\n**Reference:** `references/blast.md`\n\nUse for:\n- Running BLAST searches via NCBI web services\n- Running local BLAST searches\n- Parsing BLAST XML output\n- Filtering results by E-value or identity\n- Extracting hit sequences\n\n**Quick example:**\n```python\nfrom Bio.Blast import NCBIWWW, NCBIXML\n\n# Run BLAST search\nresult_handle = NCBIWWW.qblast(\"blastn\", \"nt\", \"ATCGATCGATCG\")\nblast_record = NCBIXML.read(result_handle)\n\n# Display top hits\nfor alignment in blast_record.alignments[:5]:\n    print(f\"{alignment.title}: E-value={alignment.hsps[0].expect}\")\n```\n\n### 5. Structural Bioinformatics (Bio.PDB)\n\n**Reference:** `references/structure.md`\n\nUse for:\n- Parsing PDB and mmCIF structure files\n- Navigating protein structure hierarchy (SMCRA: Structure/Model/Chain/Residue/Atom)\n- Calculating distances, angles, and dihedrals\n- Secondary structure assignment (DSSP)\n- Structure superimposition and RMSD calculation\n- Extracting sequences from structures\n\n**Quick example:**\n```python\nfrom Bio.PDB import PDBParser\n\n# Parse structure\nparser = PDBParser(QUIET=True)\nstructure = parser.get_structure(\"1crn\", \"1crn.pdb\")\n\n# Calculate distance between alpha carbons\nchain = structure[0][\"A\"]\ndistance = chain[10][\"CA\"] - chain[20][\"CA\"]\nprint(f\"Distance: {distance:.2f} Å\")\n```\n\n### 6. Phylogenetics (Bio.Phylo)\n\n**Reference:** `references/phylogenetics.md`\n\nUse for:\n- Reading and writing phylogenetic trees (Newick, NEXUS, phyloXML)\n- Building trees from distance matrices or alignments\n- Tree manipulation (pruning, rerooting, ladderizing)\n- Calculating phylogenetic distances\n- Creating consensus trees\n- Visualizing trees\n\n**Quick example:**\n```python\nfrom Bio import Phylo\n\n# Read and visualize tree\ntree = Phylo.read(\"tree.nwk\", \"newick\")\nPhylo.draw_ascii(tree)\n\n# Calculate distance\ndistance = tree.distance(\"Species_A\", \"Species_B\")\nprint(f\"Distance: {distance:.3f}\")\n```\n\n### 7. Advanced Features\n\n**Reference:** `references/advanced.md`\n\nUse for:\n- **Sequence motifs** (Bio.motifs) - Finding and analyzing motif patterns\n- **Population genetics** (Bio.PopGen) - GenePop files, Fst calculations, Hardy-Weinberg tests\n- **Sequence utilities** (Bio.SeqUtils) - GC content, melting temperature, molecular weight, protein analysis\n- **Restriction analysis** (Bio.Restriction) - Finding restriction enzyme sites\n- **Clustering** (Bio.Cluster) - K-means and hierarchical clustering\n- **Genome diagrams** (GenomeDiagram) - Visualizing genomic features\n\n**Quick example:**\n```python\nfrom Bio.SeqUtils import gc_fraction, molecular_weight\nfrom Bio.Seq import Seq\n\nseq = Seq(\"ATCGATCGATCG\")\nprint(f\"GC content: {gc_fraction(seq):.2%}\")\nprint(f\"Molecular weight: {molecular_weight(seq, seq_type='DNA'):.2f} g/mol\")\n```\n\n## General Workflow Guidelines\n\n### Reading Documentation\n\nWhen a user asks about a specific Biopython task:\n\n1. **Identify the relevant module** based on the task description\n2. **Read the appropriate reference file** using the Read tool\n3. **Extract relevant code patterns** and adapt them to the user's specific needs\n4. **Combine multiple modules** when the task requires it\n\nExample search patterns for reference files:\n```bash\n# Find information about specific functions\nrg -n \"SeqIO.parse\" references/sequence_io.md\n\n# Find examples of specific tasks\nrg -n \"BLAST\" references/blast.md\n\n# Find information about specific concepts\nrg -n \"alignment\" references/alignment.md\n```\n\n### Writing Biopython Code\n\nFollow these principles when writing Biopython code:\n\n1. **Import modules explicitly**\n   ```python\n   from Bio import SeqIO, Entrez\n   from Bio.Seq import Seq\n   ```\n\n2. **Set Entrez email** when using NCBI databases; load only `NCBI_API_KEY` from the environment if present\n   ```python\n   import os\n   from Bio import Entrez\n\n   Entrez.email = \"your.email@example.com\"\n   Entrez.tool = \"your_tool_name\"\n   if api_key := os.environ.get(\"NCBI_API_KEY\"):\n       Entrez.api_key = api_key\n   ```\n\n3. **Use appropriate file formats** - Check which format best suits the task\n   ```python\n   # Common formats: \"fasta\", \"genbank\", \"fastq\", \"clustal\", \"phylip\"\n   ```\n\n4. **Handle files properly** - Close handles after use or use context managers\n   ```python\n   with open(\"file.fasta\") as handle:\n       records = SeqIO.parse(handle, \"fasta\")\n   ```\n\n5. **Use iterators for large files** - Avoid loading everything into memory\n   ```python\n   for record in SeqIO.parse(\"large_file.fasta\", \"fasta\"):\n       # Process one record at a time\n   ```\n\n6. **Handle errors gracefully** - Network operations and file parsing can fail\n   ```python\n   from urllib.error import HTTPError\n\n   try:\n       handle = Entrez.efetch(db=\"nucleotide\", id=accession)\n   except HTTPError as e:\n       print(f\"Error: {e}\")\n   ```\n\n## Common Patterns\n\n### Pattern 1: Fetch Sequence from GenBank\n\n```python\nfrom Bio import Entrez, SeqIO\n\nEntrez.email = \"your.email@example.com\"\n\n# Fetch sequence\nhandle = Entrez.efetch(db=\"nucleotide\", id=\"EU490707\", rettype=\"gb\", retmode=\"text\")\nrecord = SeqIO.read(handle, \"genbank\")\nhandle.close()\n\nprint(f\"Description: {record.description}\")\nprint(f\"Sequence length: {len(record.seq)}\")\n```\n\n### Pattern 2: Sequence Analysis Pipeline\n\n```python\nfrom Bio import SeqIO\nfrom Bio.SeqUtils import gc_fraction\n\nfor record in SeqIO.parse(\"sequences.fasta\", \"fasta\"):\n    # Calculate statistics\n    gc = gc_fraction(record.seq)\n    length = len(record.seq)\n\n    # Find ORFs, translate, etc.\n    protein = record.seq.translate()\n\n    print(f\"{record.id}: {length} bp, GC={gc:.2%}\")\n```\n\n### Pattern 3: BLAST and Fetch Top Hits\n\n```python\nfrom Bio.Blast import NCBIWWW, NCBIXML\nfrom Bio import Entrez, SeqIO\n\nEntrez.email = \"your.email@example.com\"\n\n# Run BLAST\nresult_handle = NCBIWWW.qblast(\"blastn\", \"nt\", sequence)\nblast_record = NCBIXML.read(result_handle)\n\n# Get top hit accessions\naccessions = [aln.accession for aln in blast_record.alignments[:5]]\n\n# Fetch sequences\nfor acc in accessions:\n    handle = Entrez.efetch(db=\"nucleotide\", id=acc, rettype=\"fasta\", retmode=\"text\")\n    record = SeqIO.read(handle, \"fasta\")\n    handle.close()\n    print(f\">{record.description}\")\n```\n\n### Pattern 4: Build Phylogenetic Tree from Sequences\n\n```python\nfrom Bio import AlignIO, Phylo\nfrom Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor\n\n# Read alignment\nalignment = AlignIO.read(\"alignment.fasta\", \"fasta\")\n\n# Calculate distances\ncalculator = DistanceCalculator(\"identity\")\ndm = calculator.get_distance(alignment)\n\n# Build tree\nconstructor = DistanceTreeConstructor()\ntree = constructor.nj(dm)\n\n# Visualize\nPhylo.draw_ascii(tree)\n```\n\n## Best Practices\n\n1. **Always read relevant reference documentation** before writing code\n2. **Use grep to search reference files** for specific functions or examples\n3. **Validate file formats** before parsing\n4. **Handle missing data gracefully** - Not all records have all fields\n5. **Cache downloaded data** - Don't repeatedly download the same sequences\n6. **Respect NCBI rate limits** - Use API keys, registered tool/email values for reusable software, and Entrez history/batching for large jobs\n7. **Test with small datasets** before processing large files\n8. **Keep Biopython updated** to get latest features and bug fixes\n9. **Use appropriate genetic code tables** for translation\n10. **Document analysis parameters** for reproducibility\n\n## Troubleshooting Common Issues\n\n### Issue: \"No handlers could be found for logger 'Bio.Entrez'\"\n**Solution:** This is just a warning. Set Entrez.email to suppress it.\n\n### Issue: \"HTTP Error 400\" from NCBI\n**Solution:** Check that IDs/accessions are valid and properly formatted.\n\n### Issue: \"ValueError: EOF\" when parsing files\n**Solution:** Verify file format matches the specified format string.\n\n### Issue: Alignment fails with \"sequences are not the same length\"\n**Solution:** Ensure sequences are aligned before using AlignIO or MultipleSeqAlignment.\n\n### Issue: BLAST searches are slow\n**Solution:** Use local BLAST for large-scale searches, or cache results.\n\n### Issue: PDB parser warnings\n**Solution:** Use `PDBParser(QUIET=True)` to suppress warnings, or investigate structure quality.\n\n### Issue: ImportError for Bio.HMM, Bio.MarkovModel, or Bio.Application\n**Solution:** These modules were removed in Biopython 1.86. Use [hmmlearn](https://pypi.org/project/hmmlearn/) for HMMs and the standard library `subprocess` module instead of `Bio.Application` CLI wrappers.\n\n### Issue: PairwiseAligner returns fewer alignments after upgrading to 1.86+\n**Solution:** The default gap score changed from 0 to -1 in 1.86, eliminating trivial tie alignments. Set `aligner.gap_score = 0` to restore the old behavior if needed (see `references/alignment.md`).\n\n## Additional Resources\n\n- **Official Documentation**: https://biopython.org/docs/latest/\n- **Tutorial**: https://biopython.org/docs/latest/Tutorial/\n- **Cookbook**: https://biopython.org/docs/latest/Tutorial/ (advanced examples)\n- **GitHub**: https://github.com/biopython/biopython\n- **Release notes**: https://github.com/biopython/biopython/blob/master/NEWS.rst\n- **Deprecated APIs**: https://github.com/biopython/biopython/blob/master/DEPRECATED.rst\n- **Mailing List**: biopython@biopython.org\n\n## Quick Reference\n\nTo locate information in reference files, use these search patterns:\n\n```bash\n# Search for specific functions\nrg -n \"function_name\" references/*.md\n\n# Find examples of specific tasks\nrg -n \"example\" references/sequence_io.md\n\n# Find all occurrences of a module\nrg -n \"Bio.Seq\" references/*.md\n```\n\n## Summary\n\nBiopython provides comprehensive tools for computational molecular biology. When using this skill:\n\n1. **Identify the task domain** (sequences, alignments, databases, BLAST, structures, phylogenetics, or advanced)\n2. **Consult the appropriate reference file** in the `references/` directory\n3. **Adapt code examples** to the specific use case\n4. **Combine multiple modules** when needed for complex workflows\n5. **Follow best practices** for file handling, error checking, and data management\n\nThe modular reference documentation ensures detailed, searchable information for every major Biopython capability.","author":"@K-Dense-AI","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/biopython","license":"MIT","category":"writing","lang":"en","tokens":3726,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"references/advanced.md","size":14353,"sha256":"b7390943cf2dcbb35b28cbec55d7058e230564b2a1c00157e1ace08111c8fab3"},{"path":"references/alignment.md","size":9763,"sha256":"977c012dfffb7416428a520953d013ae72f5940fb035fff6d4160ce92e3a6886"},{"path":"references/blast.md","size":12934,"sha256":"8f0e08f2289c30563f9dc7dabbd15ef90bac99aa8a34e35d20161609fd74885d"},{"path":"references/databases.md","size":12268,"sha256":"46b622b0ca455285607976a30ead64c42e7b960675c695052aba041f88452b67"},{"path":"references/phylogenetics.md","size":13835,"sha256":"236b08a63dcbbeea3757dee8eaf337576149aec0abfcf93ac188bc909858f9d4"},{"path":"references/sequence_io.md","size":7691,"sha256":"90de64411ea6929794057fbabf4d6bb180e31a8cf188a97a2c1847d6772fb182"},{"path":"references/structure.md","size":12998,"sha256":"873ebde4534bcef0cd47c185d03c1713a5e07690d9bcbece3c1aed06ee4a9079"}],"requires":{"mcp":[],"tools":["Read Write Edit Bash"]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["biopython.org","www.ncbi.nlm.nih.gov"]}}