{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-f653946e7cf9","title":"Batch Process and Analyze Biological Sequences with Biopython","summary":"Process DNA\/RNA\/protein sequences, parse bioinformatics files, and query NCBI databases using Biopython. This skill provides a deliverable of sequence analysis results, including GC fraction and BLAST hits, and supports FASTA\/FASTQ\/GenBank\/PDB\/mmCIF formats.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-f653946e7cf9","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-f653946e7cf9","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-f653946e7cf9.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-f653946e7cf9\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Set `Entrez.email` (required by NCBI) and optionally `Entrez.api_key` to increase rate limits. For large-scale BLAST, prefer local BLAST+ over remote calls.","instructions":"---\nname: biopython\ndescription: A comprehensive toolbox for computational molecular biology; use it when you need programmatic sequence\/structure parsing, batch bioinformatics pipelines, or automated NCBI\/BLAST workflows.\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n## When to Use\n\nUse this skill when you need to:\n\n- Batch-process DNA\/RNA\/protein sequences (translation, reverse complement, statistics) as part of a custom pipeline.\n- Parse, validate, convert, or stream large bioinformatics files (FASTA\/FASTQ\/GenBank\/PDB\/mmCIF) without loading everything into memory.\n- Programmatically query and download records from NCBI (GenBank, PubMed, Gene, Protein) via `Bio.Entrez`, respecting rate limits.\n- Automate BLAST searches (web or local) and parse results to extract top hits and metadata.\n- Build or manipulate phylogenetic trees from alignments or distance matrices (e.g., NJ trees) for downstream analysis.\n\n> Note: For quick one-off queries, tools like **gget** may be more convenient; for multi-service API aggregation, **bioservices** may be a better fit.\n\n## Key Features\n\n- **Sequence objects and utilities**: `Bio.Seq`, `Bio.SeqRecord`, `Bio.SeqUtils` (GC fraction, molecular weight, translation, etc.).\n- **File I\/O and format conversion**: `Bio.SeqIO`, `Bio.AlignIO` for FASTA\/FASTQ\/GenBank and alignment formats.\n- **NCBI access**: `Bio.Entrez` for `esearch`, `efetch`, `elink`, and structured parsing via `Entrez.read`.\n- **BLAST**: `Bio.Blast.NCBIWWW` for remote BLAST and `Bio.Blast.NCBIXML` for XML parsing.\n- **Structural bioinformatics**: `Bio.PDB` for PDB\/mmCIF parsing, hierarchy traversal, and geometry calculations.\n- **Phylogenetics**: `Bio.Phylo` and `Bio.Phylo.TreeConstruction` for tree I\/O, distances, and construction.\n\nReference guides (if present in this repository) can be consulted for deeper module-specific patterns:\n- `references\/sequence_io.md`\n- `references\/alignment.md`\n- `references\/databases.md`\n- `references\/blast.md`\n- `references\/structure.md`\n- `references\/phylogenetics.md`\n- `references\/advanced.md`\n\n## Dependencies\n\n- Python **>= 3.8** (Biopython 1.85 supports Python 3)\n- `biopython==1.85`\n- `numpy>=1.20` (required by Biopython)\n\nInstall:\n\n```bash\npython -m pip install \"biopython==1.85\" \"numpy>=1.20\"\n```\n\n## Example Usage\n\nA complete, runnable example that:\n\n1) parses a FASTA file,  \n2) computes GC fraction,  \n3) runs a remote BLAST (optional),  \n4) fetches the top hit from NCBI,  \n5) prints basic results.\n\nCreate `example_biopython_pipeline.py`:\n\n```python\nfrom __future__ import annotations\n\nimport os\nimport time\nfrom typing import Optional\n\nfrom Bio import Entrez, SeqIO\nfrom Bio.SeqUtils import gc_fraction\n\n# Optional BLAST (remote). Comment out if you do not want network calls.\nfrom Bio.Blast import NCBIWWW, NCBIXML\n\n\ndef configure_entrez() -> None:\n    \"\"\"\n    NCBI requires an email. An API key increases rate limits.\n    Set these via environment variables to avoid hardcoding secrets.\n    \"\"\"\n    email = os.environ.get(\"NCBI_EMAIL\")\n    if not email:\n        raise RuntimeError(\"Set NCBI_EMAIL env var (required by NCBI). Example: export NCBI_EMAIL='you@org.org'\")\n    Entrez.email = email\n\n    api_key = os.environ.get(\"NCBI_API_KEY\")\n    if api_key:\n        Entrez.api_key = api_key\n\n\ndef read_first_fasta_record(path: str):\n    with open(path, \"r\", encoding=\"utf-8\") as handle:\n        return next(SeqIO.parse(handle, \"fasta\"))\n\n\ndef blast_top_accession(sequence: str, program: str = \"blastn\", database: str = \"nt\") -> Optional[str]:\n    \"\"\"\n    Remote BLAST can be slow and rate-limited. For large-scale BLAST, prefer local BLAST+.\n    \"\"\"\n    result_handle = NCBIWWW.qblast(program, database, sequence)\n    blast_record = NCBIXML.read(result_handle)\n\n    if not blast_record.alignments:\n        return None\n\n    # Many BLAST titles include multiple identifiers; accession is usually available directly.\n    return blast_record.alignments[0].accession\n\n\ndef fetch_fasta_by_accession(accession: str) -> str:\n    with Entrez.efetch(db=\"nucleotide\", id=accession, rettype=\"fasta\", retmode=\"text\") as handle:\n        return handle.read()\n\n\ndef main() -> None:\n    configure_entrez()\n\n    record = read_first_fasta_record(\"input.fasta\")\n    seq = record.seq\n\n    print(f\"ID: {record.id}\")\n    print(f\"Length: {len(seq)}\")\n    print(f\"GC fraction: {gc_fraction(seq):.2%}\")\n\n    # Be polite to NCBI services in batch workflows.\n    time.sleep(0.34)\n\n    top_acc = blast_top_accession(str(seq))\n    if not top_acc:\n        print(\"No BLAST hits found.\")\n        return\n\n    print(f\"Top BLAST accession: {top_acc}\")\n\n    time.sleep(0.34)\n    fasta_text = fetch_fasta_by_accession(top_acc)\n    print(\"Top hit FASTA:\")\n    print(fasta_text)\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\nRun:\n\n```bash\nexport NCBI_EMAIL=\"your.email@example.com\"\n# export NCBI_API_KEY=\"your_ncbi_api_key\"  # optional\npython example_biopython_pipeline.py\n```\n\nProvide an `input.fasta` in the same directory, e.g.:\n\n```text\n>demo\nATCGATCGATCGATCGATCG\n```\n\n## Implementation Details\n\n- **Streaming I\/O for large datasets**: Prefer iterator-based parsing (`SeqIO.parse`) to avoid loading entire files into memory. Use `SeqIO.read` only when exactly one record is expected.\n- **Entrez configuration and rate limits**:\n  - Always set `Entrez.email` (NCBI requirement).\n  - Optionally set `Entrez.api_key` to increase request limits.\n  - In batch jobs, add delays (e.g., `time.sleep(0.34)` as a conservative baseline) and implement retries for transient HTTP failures.\n- **BLAST considerations**:\n  - `NCBIWWW.qblast(...)` is convenient but can be slow and is not ideal for high-throughput workloads.\n  - Parse results with `NCBIXML.read(...)` (single record) or `NCBIXML.parse(...)` (multiple records).\n  - Filter hits by HSP metrics (e-value, identity) by iterating `alignment.hsps`.\n- **Sequence statistics and transformations**:\n  - Use `Bio.SeqUtils.gc_fraction(seq)` for GC fraction (returns 0\u20131).\n  - Use `seq.translate(table=...)` with the correct genetic code table for reproducibility.\n- **Structure parsing (if used)**:\n  - Use `Bio.PDB.PDBParser(QUIET=True)` to suppress warnings when appropriate.\n  - Navigate the SMCRA hierarchy (Structure \u2192 Model \u2192 Chain \u2192 Residue \u2192 Atom) for robust traversal and geometry calculations.\n- **Reproducibility**:\n  - Record key parameters (file formats, translation table, BLAST program\/database, e-value thresholds, NCBI query terms).\n  - Cache downloaded records when iterating to avoid repeated network calls.","use_cases":["Batch-process DNA\/RNA\/protein sequences for translation, reverse complement, and statistics.","Parse and convert large bioinformatics files (FASTA\/FASTQ\/GenBank\/PDB\/mmCIF) without loading everything into memory.","Query and download records from NCBI (GenBank, PubMed, Gene, Protein) via `Bio.Entrez`."],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/scientific-skills\/Data%20Analysis\/biopython\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T11:08:32.000000Z","updated_at":"2026-11-24T07:14:40.000000Z","seo_title":"Batch Process Biological Sequences with Biopython","seo_description":"Efficiently process DNA\/RNA\/protein sequences, parse bioinformatics files, and query NCBI databases using Biopython.","seo_keywords":["biopython sequence processing","ncbi database query","fasta file parsing","blast remote search","genbank file conversion"]}}