Analyze genetic data by implementing the Burrows-Wheeler Transform used in DNA alignment. Write the function to transform a genome string into its BWT form for easier compression and searching.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The Burrows-Wheeler Transform (BWT) is a sophisticated algorithm used in bioinformatics, particularly for DNA sequence compression and alignment. Let me provide a comprehensive implementation with explanations.
The BWT works by:
Creating all rotations of the input string
Sorting them lexicographically
Returning the last column of the sorted matrix
Storing the index of the original string for reversal
This is useful in DNA analysis because:
It groups similar characters together
Makes compression algorithms work better
Enables efficient string searching and matching
Used in tools like BWA (Burrows-Wheeler Aligner)
Let me write a comprehensive solution with:
Basic BWT implementation
Inverse BWT implementation
Optimized versions
DNA sequence analysis functions
Practical use cases
Performance benchmarking
Burrows-Wheeler Transform for DNA Sequence Analysis
Here's a comprehensive implementation of BWT for genomic data analysis:
1. Basic BWT Implementation
python
from typing import Tuple, List
import numpy as np
from collections import defaultdict
from itertools import islice
class BurrowsWheelerTransform:
"""
Implements Burrows-Wheeler Transform for DNA sequence analysis.
"""
def __init__(self, sentinel: str = "$"):
"""
Initialize BWT.
Args:
sentinel: Special character marking end of string
"""
self.sentinel = sentinel
def transform(self, text: str) -> Tuple[str, int]:
"""
Transform text using Burrows-Wheeler algorithm.
Args:
text: Input DNA sequence
Returns:
Tuple of (transformed_text, original_index)
"""
if not text:
return "", 0
# Add sentinel character
text_with_sentinel = text + self.sentinel
# Generate all rotations
rotations = [text_with_sentinel[i:] + text_with_sentinel[:i]
for i in range(len(text_with_sentinel))]
# Sort rotations
sorted_rotations = sorted(enumerate(rotations), key=lambda x: x[1])
# Extract last column and original index
original_index = next(i for i, (original_idx, _) in enumerate(sorted_rotations)
if original_idx == 0)
bwt = ''.join(rotation[-1] for _, rotation in sorted_rotations)
return bwt, original_index
def inverse_transform(self, bwt: str, original_index: int) -> str:
"""
Reverse the BWT to recover original sequence.
Args:
bwt: Transformed sequence
original_index: Index of original string in sorted rotations
Returns:
Original sequence
"""
if not bwt:
return ""
# Count occurrences of each character
char_count = defaultdict(int)
first_column = sorted(bwt)
# Build transformation vector (next occurrence of each character)
next_index = [0] * len(bwt)
char_positions = defaultdict(int)
for i, char in enumerate(first_column):
next_index[char_positions[char]] = i
char_positions[char] += 1
# Reconstruct original string by following the cycle
result = []
idx = original_index
for _ in range(len(bwt) - 1): # Exclude sentinel
result.append(first_column[idx])
idx = next_index[idx]
return ''.join(result)
class OptimizedBWT:
"""
Memory-efficient BWT implementation using suffix array.
"""
def __init__(self, sentinel: str = "$"):
self.sentinel = sentinel
def build_suffix_array(self, text: str) -> List[int]:
"""
Build suffix array for efficient BWT.
"""
text_with_sentinel = text + self.sentinel
suffixes = [(text_with_sentinel[i:], i)
for i in range(len(text_with_sentinel))]
suffixes.sort()
return [i for _, i in suffixes]
def transform(self, text: str) -> Tuple[str, int]:
"""
Transform using suffix array approach.
"""
if not text:
return "", 0
text_with_sentinel = text + self.sentinel
suffix_array = self.build_suffix_array(text)
bwt = ''.join(text_with_sentinel[i - 1]
for i in suffix_array)
# Find original index (where suffix starts at 0)
original_index = next(i for i, sa in enumerate(suffix_array)
if sa == 0)
return bwt, original_index
def inverse_transform(self, bwt: str, original_index: int) -> str:
"""
Inverse transform using count vectors.
"""
if not bwt:
return ""
# Count character occurrences
count = defaultdict(int)
cumulative = {}
total = 0
for char in sorted(set(bwt)):
cumulative[char] = total
for c in bwt:
if c == char:
count[char] += 1
total += count[char]
# Build transformation vector
char_index = defaultdict(int)
next_index = [0] * len(bwt)
for i, char in enumerate(bwt):
next_index[cumulative[char] + char_index[char]] = i
char_index[char] += 1
# Reconstruct
result = []
idx = original_index
for _ in range(len(bwt) - 1):
idx = next_index[idx]
first_char = sorted(bwt)[idx]
result.append(first_char)
return ''.join(result)
# Example usage
if __name__ == "__main__":
# Test basic BWT
bwt = BurrowsWheelerTransform()
dna_seq = "AGACGTACGTA"
transformed, idx = bwt.transform(dna_seq)
print(f"Original: {dna_seq}")
print(f"Transformed: {transformed}")
print(f"Index: {idx}")
recovered = bwt.inverse_transform(transformed, idx)
print(f"Recovered: {recovered}")
print(f"Match: {recovered == dna_seq}\n")
2. DNA Sequence Analysis Functions
python
3. Practical Examples and Benchmarks
python
4. Advanced DNA Alignment Features
python
class BWABasedAligner:
"""
Burrows-Wheeler Aligner-inspired functions for DNA sequence alignment.
"""
def __init__(self):
self.analyzer = DNASequenceAnalyzer()
def align_read_to_reference(self, reference: str, read: str,
max_mismatches: int = 2) -> List[dict]:
"""
Align short read to reference genome with mismatches allowed.
"""
if len(read) > len(reference):
return []
alignments = []
for i in range(len(reference) - len(read) + 1):
ref_segment = reference[i:i + len(read)]
mismatches = sum(1 for a, b in zip(ref_segment, read) if a != b)
if mismatches <= max_mismatches:
alignments.append({
'position': i,
'mismatches': mismatches,
'ref_segment': ref_segment,
'read': read,
'match_percentage': (1 - mismatches/len(read)) * 100
})
return sorted(alignments, key=lambda x: x['mismatches'])
def calculate_edit_distance(self, seq1: str, seq2: str) -> int:
"""
Calculate Levenshtein distance between sequences.
"""
m, n = len(seq1), len(seq2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if seq1[i-1] == seq2[j-1] else 1
dp[i][j] = min(
dp[i-1][j] + 1, # deletion
dp[i][j-1] + 1, # insertion
dp[i-1][j-1] + cost # substitution
)
return dp[m][n]
# Advanced example
def advanced_example():
"""Demonstrate advanced alignment."""
reference = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"
reads = [
"AGCTTTTCAT", # Perfect match
"AGCTTTTGAT", # 1 mismatch
"TTCATTCTGA", # Match elsewhere
]
aligner = BWABasedAligner()
print("\n" + "=" * 60)
print("READ ALIGNMENT EXAMPLE")
print("=" * 60)
for read in reads:
print(f"\nRead: {read}")
alignments = aligner.align_read_to_reference(reference, read)
for alignment in alignments[:3]: # Show top 3
print(f" Position {alignment['position']}: "
f"{alignment['match_percentage']:.1f}% match "
f"({alignment['mismatches']} mismatches)")
advanced_example()