{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-alignment-8361a6a5d76d","title":"Biopython Sequence Alignment and MSA Processing","summary":"Align protein or nucleotide sequences globally or locally, convert MSA files between formats, and compute alignment statistics using Biopython.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-alignment-8361a6a5d76d","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-alignment-8361a6a5d76d","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-alignment-8361a6a5d76d.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-biopython-alignment-8361a6a5d76d\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Ensure Biopython (>=1.81) and NumPy (>=1.21) are installed before running. For protein alignments, load a substitution matrix (e.g., BLOSUM62) and configure gap penalties. For nucleotide alignments, set match\/mismatch scores and gap penalties directly.","instructions":"---\nname: biopython-alignment\ndescription: Sequence alignment and alignment file processing with Biopython (Bio.Align\/Bio.AlignIO), triggered when you need global\/local pairwise alignment, MSA read\/write\/format conversion, or alignment statistics\/filtering.\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n# biopython-alignment\n\n## When to Use\n\n- You need **global alignment** between two protein (or nucleotide) sequences and want a reproducible score and aligned strings.\n- You need **local alignment** to find the best matching fragment\/subsequence between two DNA\/RNA\/protein sequences.\n- You need to **read, write, or convert** multiple sequence alignment (MSA) files (e.g., FASTA\/Clustal\/Stockholm) using Biopython I\/O.\n- You want to compute **alignment statistics** (e.g., identity, coverage, conservation per column) and filter alignments by thresholds.\n- You need to apply **substitution matrices** (e.g., BLOSUM62) and tune gap penalties for biologically meaningful scoring.\n\n## Key Features\n\n- Pairwise alignment via `Bio.Align.PairwiseAligner` (global and local modes).\n- Alignment scoring with configurable match\/mismatch and gap penalties.\n- Protein substitution matrices via `Bio.Align.substitution_matrices` (e.g., BLOSUM\/PAM).\n- MSA parsing and serialization via `Bio.AlignIO` (read\/write\/format conversion).\n- Basic alignment statistics: identity, aligned length, coverage, and MSA column conservation.\n\n## Dependencies\n\n- `biopython>=1.81`\n- `numpy>=1.21`\n\n## Example Usage\n\n```python\n# -*- coding: utf-8 -*-\n\"\"\"\nRunnable examples for:\n1) Global protein alignment\n2) Local DNA alignment (best fragment)\n3) MSA parsing + column conservation\n\nRequires: biopython, numpy\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom io import StringIO\nimport numpy as np\n\nfrom Bio.Align import PairwiseAligner\nfrom Bio.Align import substitution_matrices\nfrom Bio import AlignIO\n\n\ndef global_protein_alignment(seq_a: str, seq_b: str) -> None:\n    matrix = substitution_matrices.load(\"BLOSUM62\")\n\n    aligner = PairwiseAligner()\n    aligner.mode = \"global\"\n    aligner.substitution_matrix = matrix\n    aligner.open_gap_score = -10.0\n    aligner.extend_gap_score = -0.5\n\n    alignments = aligner.align(seq_a, seq_b)\n    best = alignments[0]\n\n    print(\"=== Global protein alignment (best) ===\")\n    print(\"Score:\", best.score)\n    print(best)\n\n\ndef local_dna_alignment_best_fragment(seq_a: str, seq_b: str) -> None:\n    aligner = PairwiseAligner()\n    aligner.mode = \"local\"\n    aligner.match_score = 2.0\n    aligner.mismatch_score = -1.0\n    aligner.open_gap_score = -2.0\n    aligner.extend_gap_score = -0.5\n\n    best = aligner.align(seq_a, seq_b)[0]\n\n    # Extract the aligned fragment coordinates from the first aligned block.\n    # aligned is a tuple: (aligned_coords_in_seq_a, aligned_coords_in_seq_b)\n    a_blocks, b_blocks = best.aligned\n    a_start, a_end = a_blocks[0]\n    b_start, b_end = b_blocks[0]\n\n    print(\"=== Local DNA alignment (best) ===\")\n    print(\"Score:\", best.score)\n    print(best)\n    print(\"Best fragment in seq_a:\", seq_a[a_start:a_end], f\"(coords {a_start}:{a_end})\")\n    print(\"Best fragment in seq_b:\", seq_b[b_start:b_end], f\"(coords {b_start}:{b_end})\")\n\n\ndef msa_column_conservation(fasta_text: str) -> None:\n    handle = StringIO(fasta_text)\n    msa = AlignIO.read(handle, \"fasta\")  # MultipleSeqAlignment\n\n    # Convert to a 2D array of characters: shape (n_seqs, aln_len)\n    arr = np.array([list(str(rec.seq)) for rec in msa], dtype=\"U1\")\n    n_seqs, aln_len = arr.shape\n\n    # Conservation per column: fraction of the most common non-gap character.\n    # Treat '-' as gap; ignore gaps when computing the most common residue.\n    conservation = []\n    for j in range(aln_len):\n        col = arr[:, j]\n        col = col[col != \"-\"]\n        if col.size == 0:\n            conservation.append(0.0)\n            continue\n        values, counts = np.unique(col, return_counts=True)\n        conservation.append(float(counts.max() \/ counts.sum()))\n\n    print(\"=== MSA column conservation ===\")\n    print(\"n_seqs:\", n_seqs, \"aln_len:\", aln_len)\n    print(\"conservation:\", [round(x, 3) for x in conservation])\n\n\ndef main() -> None:\n    # 1) Global alignment (protein)\n    seq_a = \"MKTAYIAKQRQISFVKSHFSRQDILD\"\n    seq_b = \"MKLAYIAKQRQISFVKSHFTRQDILN\"\n    global_protein_alignment(seq_a, seq_b)\n\n    # 2) Local alignment (DNA)\n    seq_a = \"ATGCGTACGTTAGC\"\n    seq_b = \"GGGATGCGTACGAAAC\"\n    local_dna_alignment_best_fragment(seq_a, seq_b)\n\n    # 3) MSA conservation (FASTA)\n    fasta_text = \">s1\\nACGTACGT\\n>s2\\nACGTTCGT\\n>s3\\nACGTACGA\\n\"\n    msa_column_conservation(fasta_text)\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Implementation Details\n\n- **Pairwise alignment engine**: uses `Bio.Align.PairwiseAligner`, which performs dynamic programming alignment under the selected mode:\n  - `mode=\"global\"`: aligns full-length sequences end-to-end.\n  - `mode=\"local\"`: finds the highest-scoring matching region (best subsequence pair).\n- **Scoring configuration**:\n  - For proteins, prefer `substitution_matrix` (e.g., `BLOSUM62`) plus gap penalties (`open_gap_score`, `extend_gap_score`).\n  - For nucleotides, a simple scheme is common: `match_score`, `mismatch_score`, and gap penalties.\n- **Selecting the best alignment**: `aligner.align(a, b)` returns an iterable of alignments sorted by score; use `[0]` for the top-scoring result.\n- **Local \u201cbest fragment\u201d extraction**:\n  - `alignment.aligned` returns aligned coordinate blocks for each sequence.\n  - The first block `(start, end)` typically corresponds to the highest-scoring contiguous aligned region; slice the original sequences with these coordinates to obtain the fragment.\n- **MSA I\/O and statistics**:\n  - `Bio.AlignIO.read(handle, fmt)` parses an alignment into a `MultipleSeqAlignment`.\n  - Column conservation can be computed as:  \n    `max_count(non-gap residues in column) \/ total_non_gap_count(column)`.\n- **Operational conventions (recommended)**:\n  - Store runtime configuration in `config\/task_config.json` and invoke scripts as `python scripts\/<task_name>.py`.\n  - Avoid stacking many CLI `--` parameters; keep parameters in the config file.\n  - Always specify `encoding=\"utf-8\"` for file I\/O; for JSON output use `ensure_ascii=False`.","use_cases":["Align two protein sequences using BLOSUM62 matrix and gap penalties.","Find the best matching fragment between two DNA sequences.","Parse a Clustal format MSA file and compute column conservation."],"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-alignment\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T11:03:42.000000Z","updated_at":"2026-11-24T07:14:40.000000Z","seo_title":"Biopython Sequence Alignment and MSA Processing","seo_description":"Perform global\/local pairwise alignment, MSA file conversion, and alignment statistics with Biopython.","seo_keywords":["Biopython sequence alignment","MSA file conversion","Pairwise alignment","Alignment statistics","BLOSUM62 matrix"]}}