Source: https://github.com/aipoch/medical-research-skills
biopython-sequence-io
When to Use
- Converting between common sequence formats (e.g., FASTA ↔ GenBank, FASTQ → FASTA) while preserving identifiers and annotations.
- Reading and writing sequence datasets for downstream pipelines (alignment, assembly, annotation) with consistent parsing and output.
- Performing basic sequence operations (reverse complement, translation, slicing) without implementing custom parsers.
- Processing large sequence files efficiently via streaming iteration or indexed access instead of loading everything into memory.
- Computing simple sequence statistics and filtering records (length, GC content, ambiguous bases) during ingestion.
Key Features
- Sequence objects and basic operations using
Bio.Seq.Seq (slicing, reverse complement, transcription/translation).
- Robust sequence I/O via
Bio.SeqIO for parsing and writing FASTA/GenBank/FASTQ and other supported formats.
- Format conversion by reading records in one format and writing them in another.
- Scalable processing with iterator-based parsing and optional indexed access (
SeqIO.index) for large files.
- Common filtering/statistics patterns (length thresholds, GC%, quality-aware handling for FASTQ).
Dependencies
biopython>=1.80
numpy>=1.21
Example Usage
Create config/task_config.json:
{
"input_path": "data/input.fasta",
"input_format": "fasta",
"output_path": "data/output.gb",
"output_format": "genbank",
"min_length": 200,
"max_ambiguous": 0,
"index_db_path": "data/index.sqlite"
}
Run:
python scripts/sequence_io.py
scripts/sequence_io.py (runnable end-to-end):
import json
from pathlib import Path
import numpy as np
from Bio import SeqIO
def gc_fraction(seq: str) -> float:
s = seq.upper()
if not s:
return 0.0
return float((s.count("G") + s.count("C")) / len(s))
def ambiguous_count(seq: str) -> int:
# Treat anything outside A/C/G/T/U as ambiguous for simple filtering.
allowed = set("ACGTU")
return sum(1 for ch in seq.upper() if ch not in allowed)
def main() -> None:
config_path = Path("config/task_config.json")
with config_path.open("r", encoding="utf-8") as f:
cfg = json.load(f)
input_path = Path(cfg["input_path"])
input_format = cfg["input_format"]
output_path = Path(cfg["output_path"])
output_format = cfg["output_format"]
min_length = int(cfg.get("min_length", 0))
max_ambiguous = int(cfg.get("max_ambiguous", 10**9))
output_path.parent.mkdir(parents=True, exist_ok=True)
kept = 0
lengths = []
# Stream records to avoid loading the entire file into memory.
with output_path.open("w", encoding="utf-8") as out_handle:
for record in SeqIO.parse(str(input_path), input_format):
seq_str = str(record.seq)
if len(seq_str) < min_length:
continue
if ambiguous_count(seq_str) > max_ambiguous:
continue
# Example: attach simple stats as annotations (useful for GenBank output).
record.annotations["gc_fraction"] = gc_fraction(seq_str)
SeqIO.write(record, out_handle, output_format)
kept += 1
lengths.append(len(seq_str))
summary = {
"input_path": str(input_path),
"output_path": str(output_path),
"kept_records": kept,
"length_min": int(np.min(lengths)) if lengths else 0,
"length_max": int(np.max(lengths)) if lengths else 0,
"length_mean": float(np.mean(lengths)) if lengths else 0.0,
}
Path("config").mkdir(parents=True, exist_ok=True)
with Path("config/summary.json").open("w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
if __name__ == "__main__":
main()
Implementation Details
Configuration convention
- Store runtime configuration in
config/task_config.json as an intermediate artifact.
- Invoke scripts uniformly with
python scripts/<task_name>.py.
- Avoid stacking many CLI
-- parameters; prefer config files for reproducibility.
- All file I/O must specify
encoding="utf-8". JSON output must use ensure_ascii=False.
Parsing and writing
- Use
SeqIO.parse(path, format) for streaming iteration over records.
- Use
SeqIO.write(records_or_record, handle, format) to serialize records.
- For format conversion, parse in the source format and write in the target format; ensure the target format supports the fields you expect (e.g., GenBank requires richer metadata than FASTA).
Large-file strategies
- Prefer iterator-based parsing for one-pass processing.
- For random access by record ID, use
SeqIO.index(input_path, format) (creates an on-disk index depending on backend); this avoids loading all sequences into memory.
Filtering/statistics
- Typical filters include
min_length, maximum ambiguous characters, and quality-based criteria for FASTQ.
- GC fraction is computed as
(count(G)+count(C))/length on an uppercased sequence string; handle empty sequences safely.
Reference
- See
references/sequence_io.md for additional notes and format-specific behaviors.
When Not to Use
- Do not use this skill when the required source data, identifiers, files, or credentials are missing.
- Do not use this skill when the user asks for fabricated results, unsupported claims, or out-of-scope conclusions.
- Do not use this skill when a simpler direct answer is more appropriate than the documented workflow.
Required Inputs
- A clearly specified task goal aligned with the documented scope.
- All required files, identifiers, parameters, or environment variables before execution.
- Any domain constraints, formatting requirements, and expected output destination if applicable.
Recommended Workflow
- Validate the request against the skill boundary and confirm all required inputs are present.
- Select the documented execution path and prefer the simplest supported command or procedure.
- Produce the expected output using the documented file format, schema, or narrative structure.
- Run a final validation pass for completeness, consistency, and safety before returning the result.
Output Contract
- Return a structured deliverable that is directly usable without reformatting.
- If a file is produced, prefer a deterministic output name such as
biopython_sequence_io_result.md unless the skill documentation defines a better convention.
- Include a short validation summary describing what was checked, what assumptions were made, and any remaining limitations.
Validation and Safety Rules
- Validate required inputs before execution and stop early when mandatory fields or files are missing.
- Do not fabricate measurements, references, findings, or conclusions that are not supported by the provided source material.
- Emit a clear warning when credentials, privacy constraints, safety boundaries, or unsupported requests affect the result.
- Keep the output safe, reproducible, and within the documented scope at all times.
Failure Handling
- If validation fails, explain the exact missing field, file, or parameter and show the minimum fix required.
- If an external dependency or script fails, surface the command path, likely cause, and the next recovery step.
- If partial output is returned, label it clearly and identify which checks could not be completed.
Quick Validation
Run this minimal verification path before full execution when possible:
No local script validation step is required for this skill.
Expected output format:
Result file: biopython_sequence_io_result.md
Validation summary: PASS/FAIL with brief notes
Assumptions: explicit list if any
1---2name: biopython-sequence-io3description: Use Biopython to read/write/convert biological sequence files (FASTA/GenBank/FASTQ, etc.) and perform basic sequence operations; use when you need reliable sequence I/O, lightweight sequence manipulation, or scalable processing of large sequence datasets.4license: MIT5---6> **Source**: [https://github.com/aipoch/medical-research-skills](https://github.com/aipoch/medical-research-skills)
7
8# biopython-sequence-io
9
10## When to Use
11
12- Converting between common sequence formats (e.g., FASTA ↔ GenBank, FASTQ → FASTA) while preserving identifiers and annotations.
13- Reading and writing sequence datasets for downstream pipelines (alignment, assembly, annotation) with consistent parsing and output.
14- Performing basic sequence operations (reverse complement, translation, slicing) without implementing custom parsers.
15- Processing large sequence files efficiently via streaming iteration or indexed access instead of loading everything into memory.
16- Computing simple sequence statistics and filtering records (length, GC content, ambiguous bases) during ingestion.
17
18## Key Features
19
20- **Sequence objects and basic operations** using `Bio.Seq.Seq` (slicing, reverse complement, transcription/translation).
21- **Robust sequence I/O** via `Bio.SeqIO` for parsing and writing FASTA/GenBank/FASTQ and other supported formats.
22- **Format conversion** by reading records in one format and writing them in another.
23- **Scalable processing** with iterator-based parsing and optional indexed access (`SeqIO.index`) for large files.
24- **Common filtering/statistics** patterns (length thresholds, GC%, quality-aware handling for FASTQ).
25
26## Dependencies
27
28- `biopython>=1.80`
29- `numpy>=1.21`
30
31## Example Usage
32
33Create `config/task_config.json`:
34
35```json
36{
37 "input_path": "data/input.fasta",
38 "input_format": "fasta",
39 "output_path": "data/output.gb",
40 "output_format": "genbank",
41 "min_length": 200,
42 "max_ambiguous": 0,
43 "index_db_path": "data/index.sqlite"
44}
45```
46
47Run:
48
49```bash
50python scripts/sequence_io.py
51```
52
53`scripts/sequence_io.py` (runnable end-to-end):
54
55```python
56import json
57from pathlib import Path
58
59import numpy as np
60from Bio import SeqIO
61
62def gc_fraction(seq: str) -> float:
63 s = seq.upper()
64 if not s:
65 return 0.0
66 return float((s.count("G") + s.count("C")) / len(s))
67
68def ambiguous_count(seq: str) -> int:
69 # Treat anything outside A/C/G/T/U as ambiguous for simple filtering.
70 allowed = set("ACGTU")
71 return sum(1 for ch in seq.upper() if ch not in allowed)
72
73def main() -> None:
74 config_path = Path("config/task_config.json")
75 with config_path.open("r", encoding="utf-8") as f:
76 cfg = json.load(f)
77
78 input_path = Path(cfg["input_path"])
79 input_format = cfg["input_format"]
80 output_path = Path(cfg["output_path"])
81 output_format = cfg["output_format"]
82
83 min_length = int(cfg.get("min_length", 0))
84 max_ambiguous = int(cfg.get("max_ambiguous", 10**9))
85
86 output_path.parent.mkdir(parents=True, exist_ok=True)
87
88 kept = 0
89 lengths = []
90
91 # Stream records to avoid loading the entire file into memory.
92 with output_path.open("w", encoding="utf-8") as out_handle:
93 for record in SeqIO.parse(str(input_path), input_format):
94 seq_str = str(record.seq)
95
96 if len(seq_str) < min_length:
97 continue
98 if ambiguous_count(seq_str) > max_ambiguous:
99 continue
100
101 # Example: attach simple stats as annotations (useful for GenBank output).
102 record.annotations["gc_fraction"] = gc_fraction(seq_str)
103
104 SeqIO.write(record, out_handle, output_format)
105 kept += 1
106 lengths.append(len(seq_str))
107
108 summary = {
109 "input_path": str(input_path),
110 "output_path": str(output_path),
111 "kept_records": kept,
112 "length_min": int(np.min(lengths)) if lengths else 0,
113 "length_max": int(np.max(lengths)) if lengths else 0,
114 "length_mean": float(np.mean(lengths)) if lengths else 0.0,
115 }
116
117 Path("config").mkdir(parents=True, exist_ok=True)
118 with Path("config/summary.json").open("w", encoding="utf-8") as f:
119 json.dump(summary, f, ensure_ascii=False, indent=2)
120
121if __name__ == "__main__":
122 main()
123```
124
125## Implementation Details
126
127- **Configuration convention**
128 - Store runtime configuration in `config/task_config.json` as an intermediate artifact.
129 - Invoke scripts uniformly with `python scripts/<task_name>.py`.
130 - Avoid stacking many CLI `--` parameters; prefer config files for reproducibility.
131 - All file I/O must specify `encoding="utf-8"`. JSON output must use `ensure_ascii=False`.
132
133- **Parsing and writing**
134 - Use `SeqIO.parse(path, format)` for streaming iteration over records.
135 - Use `SeqIO.write(records_or_record, handle, format)` to serialize records.
136 - For format conversion, parse in the source format and write in the target format; ensure the target format supports the fields you expect (e.g., GenBank requires richer metadata than FASTA).
137
138- **Large-file strategies**
139 - Prefer iterator-based parsing for one-pass processing.
140 - For random access by record ID, use `SeqIO.index(input_path, format)` (creates an on-disk index depending on backend); this avoids loading all sequences into memory.
141
142- **Filtering/statistics**
143 - Typical filters include `min_length`, maximum ambiguous characters, and quality-based criteria for FASTQ.
144 - GC fraction is computed as `(count(G)+count(C))/length` on an uppercased sequence string; handle empty sequences safely.
145
146- **Reference**
147 - See `references/sequence_io.md` for additional notes and format-specific behaviors.
148
149## When Not to Use
150
151- Do not use this skill when the required source data, identifiers, files, or credentials are missing.
152- Do not use this skill when the user asks for fabricated results, unsupported claims, or out-of-scope conclusions.
153- Do not use this skill when a simpler direct answer is more appropriate than the documented workflow.
154
155## Required Inputs
156
157- A clearly specified task goal aligned with the documented scope.
158- All required files, identifiers, parameters, or environment variables before execution.
159- Any domain constraints, formatting requirements, and expected output destination if applicable.
160
161## Recommended Workflow
162
1631. Validate the request against the skill boundary and confirm all required inputs are present.
1642. Select the documented execution path and prefer the simplest supported command or procedure.
1653. Produce the expected output using the documented file format, schema, or narrative structure.
1664. Run a final validation pass for completeness, consistency, and safety before returning the result.
167
168## Output Contract
169
170- Return a structured deliverable that is directly usable without reformatting.
171- If a file is produced, prefer a deterministic output name such as `biopython_sequence_io_result.md` unless the skill documentation defines a better convention.
172- Include a short validation summary describing what was checked, what assumptions were made, and any remaining limitations.
173
174## Validation and Safety Rules
175
176- Validate required inputs before execution and stop early when mandatory fields or files are missing.
177- Do not fabricate measurements, references, findings, or conclusions that are not supported by the provided source material.
178- Emit a clear warning when credentials, privacy constraints, safety boundaries, or unsupported requests affect the result.
179- Keep the output safe, reproducible, and within the documented scope at all times.
180
181## Failure Handling
182
183- If validation fails, explain the exact missing field, file, or parameter and show the minimum fix required.
184- If an external dependency or script fails, surface the command path, likely cause, and the next recovery step.
185- If partial output is returned, label it clearly and identify which checks could not be completed.
186
187## Quick Validation
188
189Run this minimal verification path before full execution when possible:
190
191```text
192No local script validation step is required for this skill.
193```
194
195Expected output format:
196
197```text
198Result file: biopython_sequence_io_result.md
199Validation summary: PASS/FAIL with brief notes
200Assumptions: explicit list if any
201```