Spaces:
Running
Running
File size: 7,400 Bytes
3255634 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | """Feature extraction for real-time AMR prediction.
This module extracts k-mer features from DNA sequences for prediction.
Uses the same k-mer vocabulary as the trained model.
"""
import json
import gzip
import logging
from pathlib import Path
from typing import List, Tuple, Optional
from collections import Counter
import numpy as np
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Default paths
PROJECT_ROOT = Path(__file__).parent.parent.parent
METADATA_PATH = PROJECT_ROOT / "data" / "processed" / "ncbi" / "ncbi_amr_metadata.json"
class KmerFeatureExtractor:
"""Extract k-mer features from DNA sequences using trained vocabulary.
This extractor uses the same k-mer vocabulary that was used during model
training to ensure consistent feature extraction for inference.
"""
def __init__(self, metadata_path: Optional[str] = None):
"""Initialize the feature extractor.
Args:
metadata_path: Path to metadata JSON containing feature_names.
If None, uses default path.
"""
self.metadata_path = Path(metadata_path) if metadata_path else METADATA_PATH
self.feature_names: List[str] = []
self.k: int = 6
self.kmer_to_idx: dict = {}
self._load_vocabulary()
def _load_vocabulary(self):
"""Load k-mer vocabulary from metadata file."""
if not self.metadata_path.exists():
raise FileNotFoundError(f"Metadata file not found: {self.metadata_path}")
with open(self.metadata_path) as f:
metadata = json.load(f)
self.feature_names = metadata.get("feature_names", [])
self.k = metadata.get("k", 6)
if not self.feature_names:
raise ValueError("No feature_names found in metadata")
self.kmer_to_idx = {kmer: idx for idx, kmer in enumerate(self.feature_names)}
logger.info(f"Loaded {len(self.feature_names)} k-mer features (k={self.k})")
def extract_features(self, sequence: str) -> np.ndarray:
"""Extract k-mer features from a single DNA sequence.
Args:
sequence: DNA sequence string (A, C, G, T characters)
Returns:
Feature vector of shape (n_features,) with k-mer frequencies
"""
sequence = sequence.upper().replace('\n', '').replace(' ', '')
seq_len = len(sequence) - self.k + 1
if seq_len <= 0:
logger.warning(f"Sequence too short (len={len(sequence)}, need >={self.k})")
return np.zeros(len(self.feature_names))
# Count k-mers
features = np.zeros(len(self.feature_names))
valid_count = 0
for i in range(seq_len):
kmer = sequence[i:i + self.k]
# Only count valid DNA k-mers
if all(c in "ACGT" for c in kmer):
valid_count += 1
if kmer in self.kmer_to_idx:
features[self.kmer_to_idx[kmer]] += 1
# Normalize by total valid k-mers
if valid_count > 0:
features = features / valid_count
return features
def extract_features_batch(self, sequences: List[str]) -> np.ndarray:
"""Extract k-mer features from multiple sequences.
Args:
sequences: List of DNA sequence strings
Returns:
Feature matrix of shape (n_sequences, n_features)
"""
return np.array([self.extract_features(seq) for seq in sequences])
def parse_fasta(self, content: str) -> List[Tuple[str, str]]:
"""Parse FASTA format content.
Args:
content: FASTA file content as string
Returns:
List of (header, sequence) tuples
"""
sequences = []
current_header = None
current_seq = []
for line in content.strip().split('\n'):
line = line.strip()
if line.startswith('>'):
if current_header is not None:
sequences.append((current_header, ''.join(current_seq)))
current_header = line[1:]
current_seq = []
else:
current_seq.append(line)
if current_header is not None:
sequences.append((current_header, ''.join(current_seq)))
return sequences
def parse_fastq(self, content: str) -> List[Tuple[str, str]]:
"""Parse FASTQ format content.
Args:
content: FASTQ file content as string
Returns:
List of (header, sequence) tuples
"""
sequences = []
lines = content.strip().split('\n')
i = 0
while i < len(lines):
if lines[i].startswith('@'):
header = lines[i][1:]
sequence = lines[i + 1] if i + 1 < len(lines) else ''
sequences.append((header, sequence))
i += 4 # Skip quality lines
else:
i += 1
return sequences
def extract_from_file_content(
self,
content: str,
file_format: str = "fasta"
) -> Tuple[np.ndarray, List[str]]:
"""Extract features from file content.
Args:
content: File content as string
file_format: Either 'fasta' or 'fastq'
Returns:
Tuple of (feature_matrix, sequence_headers)
"""
if file_format.lower() in ['fastq', 'fq']:
sequences = self.parse_fastq(content)
else:
sequences = self.parse_fasta(content)
if not sequences:
raise ValueError("No sequences found in file content")
headers = [h for h, _ in sequences]
seqs = [s for _, s in sequences]
# For multiple sequences, concatenate them (typical for assembled genomes)
if len(seqs) > 1:
logger.info(f"Found {len(seqs)} sequences, concatenating for feature extraction")
combined_seq = ''.join(seqs)
features = self.extract_features(combined_seq)
return features.reshape(1, -1), [f"combined_{len(seqs)}_sequences"]
else:
features = self.extract_features(seqs[0])
return features.reshape(1, -1), headers
@property
def n_features(self) -> int:
"""Number of features (k-mers) in vocabulary."""
return len(self.feature_names)
# Global extractor instance (lazy loaded)
_extractor: Optional[KmerFeatureExtractor] = None
def get_extractor() -> KmerFeatureExtractor:
"""Get or create the global feature extractor instance."""
global _extractor
if _extractor is None:
_extractor = KmerFeatureExtractor()
return _extractor
def extract_features_from_sequence(sequence: str) -> np.ndarray:
"""Convenience function to extract features from a sequence.
Args:
sequence: DNA sequence string
Returns:
Feature vector of shape (n_features,)
"""
return get_extractor().extract_features(sequence)
def extract_features_from_fasta(content: str) -> np.ndarray:
"""Convenience function to extract features from FASTA content.
Args:
content: FASTA file content
Returns:
Feature vector of shape (n_features,)
"""
features, _ = get_extractor().extract_from_file_content(content, "fasta")
return features[0] # Return first (and typically only) row
|