Parse and analyze multiple sequence alignments using Biopython. Extract sequences, identify conserved regions, analyze gaps, work with annotations, and manipulate alignment data for downstream analysis. Use when parsing or manipulating multiple sequence alignments.
Standardmäßig ist der Prompt ausgewählt, der zuerst die Quelle prüft. Sie können zu einem direkten Befehl wechseln oder eine lokale Kopie herunterladen.
Quelldateien prüfen
Lesen Sie SKILL.md und alle von SkillsMP angezeigten Begleitdateien, bevor Sie sich für eine Installation entscheiden.
Mit Codex oder Claude installieren Kopieren Sie diesen Prompt, fügen Sie ihn in Codex, Claude oder einen anderen Assistant ein und lassen Sie die Skill-Seite prüfen und installieren.
Ein direkter Befehl überspringt den Prüf-Prompt. Prüfen Sie die Quelle, bevor Sie ihn ausführen.
Parse and analyze multiple sequence alignments using Biopython. Extract sequences, identify conserved regions, analyze gaps, work with annotations, and manipulate alignment data for downstream analysis. Use when parsing or manipulating multiple sequence alignments.
tool_type
python
primary_tool
Bio.AlignIO
MSA Parsing and Analysis
Parse multiple sequence alignments to extract information, analyze content, and prepare for downstream analysis.
Required Import
from Bio import AlignIO
from Bio.Align import MultipleSeqAlignment
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from collections import Counter
Loading Alignments
from Bio import AlignIO
alignment = AlignIO.read('alignment.fasta', 'fasta')
print(f' sequences, columns')
{len(alignment)}
{alignment.get_alignment_length()}
Extracting Sequence Information
Get All Sequence IDs
seq_ids = [record.idfor record in alignment]
Get Sequences as Strings
sequences = [str(record.seq) for record in alignment]
Get Sequence by ID
defget_sequence_by_id(alignment, seq_id):
for record in alignment:
if record.id == seq_id:
return record
returnNone
target = get_sequence_by_id(alignment, 'species_A')
Access Descriptions and Annotations
for record in alignment:
print(f'ID: {record.id}')
print(f'Description: {record.description}')
print(f'Annotations: {record.annotations}')
Column-wise Analysis
Get Single Column
column_5 = alignment[:, 5] # Returns string of characters at position 5print(column_5) # e.g., 'AAAGA'
Iterate Over Columns
for col_idx inrange(alignment.get_alignment_length()):
column = alignment[:, col_idx]
print(f'Column {col_idx}: {column}')
gap_counts = [(record.id, str(record.seq).count('-')) for record in alignment]
for seq_id, gaps in gap_counts:
print(f'{seq_id}: {gaps} gaps')
Count Gaps Per Column
defgaps_per_column(alignment):
return [alignment[:, i].count('-') for i inrange(alignment.get_alignment_length())]
gap_profile = gaps_per_column(alignment)
The AlignInfo.SummaryInfo class is deprecated in recent Biopython versions. The custom consensus_sequence() function above is the recommended approach. If you see deprecation warnings when using AlignInfo, use the custom implementation instead.
Extracting Regions
Slice by Column Range
region = alignment[:, 100:200] # Columns 100-199
Slice by Sequence Range
subset = alignment[0:10] # First 10 sequences
Extract Ungapped Regions from Reference
defextract_ungapped_regions(alignment, ref_idx=0):
ref_seq = str(alignment[ref_idx].seq)
ungapped_cols = [i for i, char inenumerate(ref_seq) if char != '-']
new_records = []
for record in alignment:
new_seq = ''.join(str(record.seq)[i] for i in ungapped_cols)
new_records.append(SeqRecord(Seq(new_seq), id=record.id, description=record.description))
return MultipleSeqAlignment(new_records)
ungapped = extract_ungapped_regions(alignment, ref_idx=0)
Sequence Filtering
Filter by Sequence ID Pattern
import re
deffilter_by_id(alignment, pattern):
regex = re.compile(pattern)
matching = [record for record in alignment if regex.search(record.id)]
return MultipleSeqAlignment(matching)
bacteria_only = filter_by_id(alignment, r'^Bac_')
Filter by Gap Content
deffilter_by_gap_content(alignment, max_gap_fraction=0.1):
filtered = []
for record in alignment:
gap_fraction = str(record.seq).count('-') / len(record.seq)
if gap_fraction <= max_gap_fraction:
filtered.append(record)
return MultipleSeqAlignment(filtered)
low_gap_seqs = filter_by_gap_content(alignment, max_gap_fraction=0.1)
Remove Duplicate Sequences
defremove_duplicates(alignment):
seen_seqs = {}
unique_records = []
for record in alignment:
seq_str = str(record.seq)
if seq_str notin seen_seqs:
seen_seqs[seq_str] = record.id
unique_records.append(record)
return MultipleSeqAlignment(unique_records)
unique_alignment = remove_duplicates(alignment)
Working with Annotations
Stockholm Format Annotations
alignment = AlignIO.read('pfam.sto', 'stockholm')
for record in alignment:
if'secondary_structure'in record.letter_annotations:
ss = record.letter_annotations['secondary_structure']
print(f'{record.id}: {ss}')
Add Annotations to Records
for record in alignment:
record.annotations['source'] = 'my_analysis'
record.annotations['quality'] = 'high'
Position Mapping
Map Alignment Position to Sequence Position
defalignment_to_sequence_position(record, align_pos):
seq_pos = 0for i, char inenumerate(str(record.seq)):
if i == align_pos:
return seq_pos if char != '-'elseNoneif char != '-':
seq_pos += 1returnNone
Map Sequence Position to Alignment Position
defsequence_to_alignment_position(record, seq_pos):
current_seq_pos = 0for i, char inenumerate(str(record.seq)):
if char != '-':
if current_seq_pos == seq_pos:
return i
current_seq_pos += 1returnNone
Quick Reference: Common Operations
Task
Code
Get column
alignment[:, col_idx]
Get sequence
alignment[seq_idx]
Column count
alignment.get_alignment_length()
Sequence count
len(alignment)
Find gaps
str(record.seq).count('-')
Consensus
Use custom consensus_sequence() function
Common Errors
Error
Cause
Solution
IndexError
Column index out of range
Check get_alignment_length()
Unequal sequence lengths
Invalid MSA
Ensure all sequences same length
Empty Counter
All gaps in column
Handle gap-only columns
Related Skills
alignment-io - Read/write alignment files in various formats
pairwise-alignment - Create pairwise alignments
msa-statistics - Calculate conservation metrics
sequence-manipulation/motif-search - Search for patterns