sirnaforge 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. sirnaforge/__init__.py +77 -0
  2. sirnaforge/cli.py +837 -0
  3. sirnaforge/core/__init__.py +1 -0
  4. sirnaforge/core/design.py +470 -0
  5. sirnaforge/core/off_target.py +713 -0
  6. sirnaforge/core/thermodynamics.py +188 -0
  7. sirnaforge/data/__init__.py +21 -0
  8. sirnaforge/data/base.py +901 -0
  9. sirnaforge/data/gene_search.py +254 -0
  10. sirnaforge/data/mirna_manager.py +634 -0
  11. sirnaforge/data/orf_analysis.py +448 -0
  12. sirnaforge/models/__init__.py +19 -0
  13. sirnaforge/models/schemas.py +280 -0
  14. sirnaforge/models/sirna.py +337 -0
  15. sirnaforge/pipeline/__init__.py +17 -0
  16. sirnaforge/pipeline/nextflow/__init__.py +6 -0
  17. sirnaforge/pipeline/nextflow/config.py +487 -0
  18. sirnaforge/pipeline/nextflow/runner.py +462 -0
  19. sirnaforge/pipeline/nextflow/workflows/main.nf +134 -0
  20. sirnaforge/pipeline/nextflow/workflows/modules/local/aggregate_results.nf +99 -0
  21. sirnaforge/pipeline/nextflow/workflows/modules/local/build_bowtie_index.nf +58 -0
  22. sirnaforge/pipeline/nextflow/workflows/modules/local/build_bwa_index.nf +57 -0
  23. sirnaforge/pipeline/nextflow/workflows/modules/local/environment.yml +11 -0
  24. sirnaforge/pipeline/nextflow/workflows/modules/local/offtarget_analysis.nf +73 -0
  25. sirnaforge/pipeline/nextflow/workflows/modules/local/prepare_candidates.nf +65 -0
  26. sirnaforge/pipeline/nextflow/workflows/modules/local/resolve_indices.nf +65 -0
  27. sirnaforge/pipeline/nextflow/workflows/modules/local/sirnaforge_analysis.nf +0 -0
  28. sirnaforge/pipeline/nextflow/workflows/modules/local/split_candidates.nf +67 -0
  29. sirnaforge/pipeline/nextflow/workflows/nextflow.config +218 -0
  30. sirnaforge/pipeline/nextflow/workflows/subworkflows/local/sirna_offtarget_analysis.nf +147 -0
  31. sirnaforge/pipeline/resources/__init__.py +5 -0
  32. sirnaforge/pipeline/resources/genomes.yaml +28 -0
  33. sirnaforge/pipeline/resources/resources.py +177 -0
  34. sirnaforge/pipeline/resources/test_data/genomes.yaml +28 -0
  35. sirnaforge/pipeline/resources/test_data/test_candidates.fasta +10 -0
  36. sirnaforge/pipeline/resources/test_data/test_mirna_seeds.fasta +14 -0
  37. sirnaforge/pipeline/resources/test_data/test_transcriptome.fasta +6 -0
  38. sirnaforge/utils/__init__.py +1 -0
  39. sirnaforge/utils/logging_utils.py +73 -0
  40. sirnaforge/validation/__init__.py +31 -0
  41. sirnaforge/validation/config.py +110 -0
  42. sirnaforge/validation/middleware.py +302 -0
  43. sirnaforge/validation/utils.py +285 -0
  44. sirnaforge/workflow.py +1157 -0
  45. sirnaforge-0.2.0.dist-info/METADATA +938 -0
  46. sirnaforge-0.2.0.dist-info/RECORD +49 -0
  47. sirnaforge-0.2.0.dist-info/WHEEL +4 -0
  48. sirnaforge-0.2.0.dist-info/entry_points.txt +2 -0
  49. sirnaforge-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,713 @@
1
+ """Off-target analysis for siRNA design.
2
+
3
+ This module provides comprehensive off-target analysis functionality for siRNA design,
4
+ including both miRNA seed match analysis and transcriptome off-target detection.
5
+ Uses BWA-MEM2 for both short and long sequence alignments.
6
+ Optimized for both standalone use and parallelized Nextflow workflows.
7
+ """
8
+
9
+ import json
10
+ import shutil
11
+ import subprocess # nosec B404
12
+ import tempfile
13
+ from pathlib import Path
14
+ from typing import Any, Optional, Union
15
+
16
+ from sirnaforge.data.base import FastaUtils
17
+ from sirnaforge.models.sirna import SiRNACandidate
18
+ from sirnaforge.utils.logging_utils import get_logger
19
+
20
+ logger = get_logger(__name__)
21
+
22
+
23
+ # =============================================================================
24
+ # Core Analyzer Classes
25
+ # =============================================================================
26
+
27
+
28
+ def _get_executable_path(tool_name: str) -> Optional[str]:
29
+ """Get the full path to an executable, ensuring it exists."""
30
+ path = shutil.which(tool_name)
31
+ if path is None:
32
+ logger.warning(f"Tool '{tool_name}' not found in PATH")
33
+ return path
34
+
35
+
36
+ def _validate_command_args(cmd: list[str]) -> None:
37
+ """Validate command arguments for subprocess execution."""
38
+ if not cmd:
39
+ raise ValueError("Command list cannot be empty")
40
+
41
+ executable = cmd[0]
42
+ if not executable:
43
+ raise ValueError("Executable path cannot be empty")
44
+
45
+ # Ensure we have an absolute path to the executable
46
+ if not Path(executable).is_absolute():
47
+ raise ValueError(f"Executable must be an absolute path: {executable}")
48
+
49
+
50
+ # =============================================================================
51
+ # Core Analyzer Classes
52
+ # =============================================================================
53
+
54
+
55
+ class BwaAnalyzer:
56
+ """BWA-MEM2 based analyzer for both transcriptome and miRNA seed off-target search."""
57
+
58
+ def __init__(
59
+ self,
60
+ index_prefix: str,
61
+ mode: str = "transcriptome", # "transcriptome" or "mirna_seed"
62
+ seed_length: int = 12,
63
+ min_score: int = 15,
64
+ max_hits: int = 10000,
65
+ seed_start: int = 2,
66
+ seed_end: int = 8,
67
+ ):
68
+ """
69
+ Initialize BWA-MEM2 analyzer.
70
+
71
+ Args:
72
+ index_prefix: Path to BWA index
73
+ mode: Analysis mode - "transcriptome" for long targets, "mirna_seed" for short targets
74
+ seed_length: BWA seed length parameter
75
+ min_score: Minimum alignment score
76
+ max_hits: Maximum hits to return
77
+ seed_start: Seed region start (1-based)
78
+ seed_end: Seed region end (1-based)
79
+ """
80
+ self.index_prefix = index_prefix
81
+ self.mode = mode
82
+ self.seed_length = seed_length
83
+ self.min_score = min_score
84
+ self.max_hits = max_hits
85
+ self.seed_start = seed_start
86
+ self.seed_end = seed_end
87
+
88
+ # Configure parameters based on mode
89
+ if mode == "mirna_seed":
90
+ # For miRNA seed analysis: short query (6-8bp) vs short target (~22bp)
91
+ # Need very permissive parameters for ultra-short sequences
92
+ self.seed_length = min(seed_length, 6) # Max 6bp seed for 6-8bp queries
93
+ self.min_score = 6 # Very low threshold - allow imperfect matches
94
+ elif mode == "transcriptome":
95
+ # For transcriptome analysis: short query vs long target
96
+ self.seed_length = seed_length # Use provided seed length
97
+ self.min_score = min_score # Use provided min score
98
+ else:
99
+ raise ValueError(f"Unknown mode: {mode}. Use 'transcriptome' or 'mirna_seed'")
100
+
101
+ def analyze_sequences(self, sequences: dict[str, str]) -> list[dict[str, Any]]:
102
+ """
103
+ Run BWA-MEM2 analysis on sequences.
104
+
105
+ Args:
106
+ sequences: Dictionary of sequence name -> sequence
107
+
108
+ Returns:
109
+ List of alignment dictionaries
110
+ """
111
+ # Prepare sequences based on mode
112
+ analysis_sequences = self._prepare_sequences_for_analysis(sequences)
113
+
114
+ results = []
115
+ temp_fasta_path = create_temp_fasta(analysis_sequences)
116
+
117
+ try:
118
+ # Get absolute path to bwa-mem2 executable
119
+ bwa_path = _get_executable_path("bwa-mem2")
120
+ if not bwa_path:
121
+ raise FileNotFoundError("BWA-MEM2 executable not found in PATH")
122
+
123
+ # Configure BWA parameters based on mode
124
+ cmd = self._build_bwa_command(bwa_path, temp_fasta_path)
125
+
126
+ _validate_command_args(cmd)
127
+ logger.info(f"Running BWA-MEM2 ({self.mode} mode): {' '.join(cmd)}")
128
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=None, check=True) # nosec B603
129
+ results = self._parse_sam_output(result.stdout, sequences)
130
+ results = self._filter_and_rank(results)
131
+ logger.info(f"BWA-MEM2 analysis completed: {len(results)} hits found")
132
+
133
+ except subprocess.CalledProcessError as e:
134
+ logger.error(f"BWA-MEM2 failed: {e.stderr}")
135
+ except subprocess.TimeoutExpired:
136
+ logger.error("BWA-MEM2 timed out")
137
+ finally:
138
+ Path(temp_fasta_path).unlink(missing_ok=True)
139
+
140
+ return results[: self.max_hits]
141
+
142
+ def _prepare_sequences_for_analysis(self, sequences: dict[str, str]) -> dict[str, str]:
143
+ """Prepare sequences for analysis based on mode."""
144
+ if self.mode == "mirna_seed":
145
+ # Extract seed region (positions 2-8, 1-based) from siRNA sequences
146
+ prepared = {}
147
+ for name, seq in sequences.items():
148
+ if len(seq) >= self.seed_end:
149
+ seed_seq = seq[self.seed_start - 1 : self.seed_end] # Convert to 0-based indexing
150
+ prepared[name] = seed_seq
151
+ logger.debug(f"Extracted seed region for {name}: {seed_seq} (from {seq})")
152
+ else:
153
+ logger.warning(f"Sequence {name} too short for seed extraction: {seq}")
154
+ prepared[name] = seq # Use full sequence if too short
155
+ return prepared
156
+ # For transcriptome mode, use full sequences
157
+ return sequences
158
+
159
+ def _build_bwa_command(self, bwa_path: str, temp_fasta_path: str) -> list[str]:
160
+ """Build BWA command based on analysis mode."""
161
+ base_cmd = [
162
+ bwa_path,
163
+ "mem",
164
+ "-a", # Output all alignments
165
+ "-v",
166
+ "1", # Verbosity level
167
+ ]
168
+
169
+ if self.mode == "mirna_seed":
170
+ # For miRNA seed analysis: ultra-permissive parameters for 6-8bp vs ~22bp
171
+ cmd = base_cmd + [
172
+ "-k",
173
+ str(self.seed_length), # Seed length (max 6bp)
174
+ "-T",
175
+ str(self.min_score), # Minimum score (6)
176
+ "-w",
177
+ "2", # Narrow band width for short sequences
178
+ "-A",
179
+ "2", # Higher matching score to reward matches
180
+ "-B",
181
+ "1", # Low mismatch penalty
182
+ "-O",
183
+ "1,1", # Low gap open penalties
184
+ "-E",
185
+ "1,1", # Low gap extension penalties
186
+ "-L",
187
+ "8,8", # Clipping penalty for ultra-short reads
188
+ self.index_prefix,
189
+ temp_fasta_path,
190
+ ]
191
+ elif self.mode == "transcriptome":
192
+ # For transcriptome analysis: standard parameters
193
+ cmd = base_cmd + [
194
+ "-k",
195
+ str(self.seed_length), # Seed length
196
+ "-T",
197
+ str(self.min_score), # Minimum score
198
+ "-w",
199
+ "100", # Band width (larger for long targets)
200
+ self.index_prefix,
201
+ temp_fasta_path,
202
+ ]
203
+ else:
204
+ raise ValueError(f"Unknown mode: {self.mode}")
205
+
206
+ return cmd
207
+
208
+ def _parse_sam_output(self, sam_output: str, original_sequences: dict[str, str]) -> list[dict[str, Any]]:
209
+ """Parse SAM output from BWA-MEM2."""
210
+ results = []
211
+
212
+ for line in sam_output.splitlines():
213
+ if line.startswith("@") or not line.strip():
214
+ continue
215
+
216
+ parts = line.split("\t")
217
+ if len(parts) < 11:
218
+ continue
219
+
220
+ qname = parts[0]
221
+ flag = int(parts[1])
222
+ rname = parts[2]
223
+ pos = int(parts[3])
224
+ mapq = int(parts[4]) if parts[4] != "*" else 0
225
+ cigar = parts[5]
226
+
227
+ if flag & 4: # Skip unmapped
228
+ continue
229
+
230
+ strand = "-" if (flag & 16) else "+"
231
+ coord = f"{rname}:{pos}"
232
+
233
+ # Parse optional tags
234
+ tags = {}
235
+ for tag in parts[11:]:
236
+ if ":" in tag:
237
+ tag_parts = tag.split(":", 2)
238
+ if len(tag_parts) == 3:
239
+ tags[tag_parts[0]] = tag_parts[2]
240
+
241
+ nm = int(tags.get("NM", 0))
242
+ as_score = int(tags.get("AS", 0)) if "AS" in tags else None
243
+
244
+ # Parse mismatch positions from MD tag
245
+ mismatch_positions = self._parse_md_tag(tags.get("MD", ""))
246
+ seed_mismatches = sum(1 for pos in mismatch_positions if self.seed_start <= pos <= self.seed_end)
247
+
248
+ # Calculate off-target score
249
+ offtarget_score = self._calculate_offtarget_score(mismatch_positions)
250
+
251
+ result = {
252
+ "qname": qname,
253
+ "qseq": original_sequences.get(qname, ""), # Use original sequence
254
+ "rname": rname,
255
+ "coord": coord,
256
+ "strand": strand,
257
+ "cigar": cigar,
258
+ "mapq": mapq,
259
+ "as_score": as_score,
260
+ "nm": nm,
261
+ "mismatch_positions": mismatch_positions,
262
+ "seed_mismatches": seed_mismatches,
263
+ "offtarget_score": offtarget_score,
264
+ }
265
+ results.append(result)
266
+
267
+ return results
268
+
269
+ def _parse_md_tag(self, md_tag: str) -> list[int]:
270
+ """Parse MD tag to extract mismatch positions."""
271
+ positions = []
272
+ read_pos = 1
273
+ i = 0
274
+
275
+ while i < len(md_tag):
276
+ if md_tag[i].isdigit():
277
+ num_str = ""
278
+ while i < len(md_tag) and md_tag[i].isdigit():
279
+ num_str += md_tag[i]
280
+ i += 1
281
+ if num_str:
282
+ read_pos += int(num_str)
283
+ elif md_tag[i] == "^":
284
+ i += 1
285
+ while i < len(md_tag) and md_tag[i].isalpha():
286
+ i += 1
287
+ elif md_tag[i].isalpha():
288
+ positions.append(read_pos)
289
+ read_pos += 1
290
+ i += 1
291
+ else:
292
+ i += 1
293
+
294
+ return positions
295
+
296
+ def _calculate_offtarget_score(self, mismatch_positions: list[int]) -> float:
297
+ """Calculate off-target score based on mismatch positions."""
298
+ score = 0.0
299
+
300
+ for pos in mismatch_positions:
301
+ if self.seed_start <= pos <= self.seed_end:
302
+ score += 5.0 # Seed region mismatches are more critical
303
+ else:
304
+ score += 1.0 # Non-seed mismatches
305
+
306
+ if len(mismatch_positions) == 0:
307
+ score += 10.0 # Perfect matches get high penalty (bad for off-target)
308
+
309
+ return score
310
+
311
+ def _filter_and_rank(self, results: list[dict[str, Any]]) -> list[dict[str, Any]]:
312
+ """Filter and rank results by off-target score."""
313
+ results.sort(key=lambda x: (x["offtarget_score"], -x.get("as_score", 0)))
314
+ return results
315
+
316
+
317
+ class OffTargetAnalysisManager:
318
+ """Manager class for comprehensive off-target analysis using BWA-MEM2."""
319
+
320
+ def __init__(
321
+ self,
322
+ species: str,
323
+ transcriptome_path: Optional[Union[str, Path]] = None,
324
+ mirna_path: Optional[Union[str, Path]] = None,
325
+ transcriptome_index: Optional[str] = None,
326
+ mirna_index: Optional[str] = None,
327
+ ):
328
+ self.species = species
329
+ self.transcriptome_path = transcriptome_path
330
+ self.mirna_path = mirna_path
331
+ self.transcriptome_index = transcriptome_index
332
+ self.mirna_index = mirna_index
333
+
334
+ def analyze_mirna_off_targets(
335
+ self,
336
+ sequences: Union[dict[str, str], str, Path],
337
+ output_prefix: str,
338
+ ) -> tuple[str, str]:
339
+ """Analyze miRNA off-targets using BWA-MEM2 in miRNA seed mode."""
340
+ if not self.mirna_index:
341
+ raise ValueError("miRNA index not provided")
342
+
343
+ if isinstance(sequences, (str, Path)):
344
+ sequences = parse_fasta_file(str(sequences))
345
+
346
+ analyzer = BwaAnalyzer(self.mirna_index, mode="mirna_seed")
347
+ results = analyzer.analyze_sequences(sequences)
348
+
349
+ tsv_path = f"{output_prefix}_mirna_hits.tsv"
350
+ json_path = f"{output_prefix}_mirna_hits.json"
351
+
352
+ self._write_mirna_results(results, tsv_path, json_path)
353
+ return tsv_path, json_path
354
+
355
+ def analyze_transcriptome_off_targets(
356
+ self,
357
+ sequences: Union[dict[str, str], str, Path],
358
+ output_prefix: str,
359
+ ) -> tuple[str, str]:
360
+ """Analyze transcriptome off-targets using BWA-MEM2 in transcriptome mode."""
361
+ if not self.transcriptome_index:
362
+ raise ValueError("Transcriptome index not provided")
363
+
364
+ if isinstance(sequences, (str, Path)):
365
+ sequences = parse_fasta_file(str(sequences))
366
+
367
+ analyzer = BwaAnalyzer(self.transcriptome_index, mode="transcriptome")
368
+ results = analyzer.analyze_sequences(sequences)
369
+
370
+ tsv_path = f"{output_prefix}_transcriptome_hits.tsv"
371
+ json_path = f"{output_prefix}_transcriptome_hits.json"
372
+
373
+ self._write_transcriptome_results(results, tsv_path, json_path)
374
+ return tsv_path, json_path
375
+
376
+ def analyze_sirna_candidate(self, candidate: SiRNACandidate) -> dict[str, Any]:
377
+ """Analyze a single siRNA candidate for off-targets."""
378
+ sequences = {candidate.id: candidate.guide_sequence}
379
+
380
+ results: dict[str, Any] = {
381
+ "candidate_id": candidate.id,
382
+ "guide_sequence": candidate.guide_sequence,
383
+ "mirna_hits": [],
384
+ "transcriptome_hits": [],
385
+ }
386
+
387
+ if self.mirna_index:
388
+ mirna_analyzer = BwaAnalyzer(self.mirna_index, mode="mirna_seed")
389
+ results["mirna_hits"] = mirna_analyzer.analyze_sequences(sequences)
390
+
391
+ if self.transcriptome_index:
392
+ transcriptome_analyzer = BwaAnalyzer(self.transcriptome_index, mode="transcriptome")
393
+ results["transcriptome_hits"] = transcriptome_analyzer.analyze_sequences(sequences)
394
+
395
+ return results
396
+
397
+ def _write_mirna_results(self, results: list[dict[str, Any]], tsv_path: str, json_path: str) -> None:
398
+ """Write miRNA analysis results."""
399
+ # Write TSV
400
+ with Path(tsv_path).open("w") as f:
401
+ f.write("qname\tqseq\trname\tcoord\tstrand\tcigar\tmapq\tas_score\tnm\tseed_mismatches\tofftarget_score\n")
402
+ for result in results:
403
+ f.write(
404
+ f"{result['qname']}\t{result['qseq']}\t{result['rname']}\t"
405
+ f"{result['coord']}\t{result['strand']}\t{result['cigar']}\t"
406
+ f"{result['mapq']}\t{result.get('as_score', 'NA')}\t{result['nm']}\t"
407
+ f"{result['seed_mismatches']}\t{result['offtarget_score']}\n"
408
+ )
409
+
410
+ # Write JSON
411
+ with Path(json_path).open("w") as f:
412
+ json.dump(results, f, indent=2)
413
+
414
+ def _write_transcriptome_results(self, results: list[dict[str, Any]], tsv_path: str, json_path: str) -> None:
415
+ """Write transcriptome analysis results."""
416
+ # Write TSV
417
+ with Path(tsv_path).open("w") as f:
418
+ f.write("qname\tqseq\trname\tcoord\tstrand\tcigar\tmapq\tas_score\tnm\tseed_mismatches\tofftarget_score\n")
419
+ for result in results:
420
+ f.write(
421
+ f"{result['qname']}\t{result['qseq']}\t{result['rname']}\t"
422
+ f"{result['coord']}\t{result['strand']}\t{result['cigar']}\t"
423
+ f"{result['mapq']}\t{result.get('as_score', 'NA')}\t{result['nm']}\t"
424
+ f"{result['seed_mismatches']}\t{result['offtarget_score']}\n"
425
+ )
426
+
427
+ # Write JSON
428
+ with Path(json_path).open("w") as f:
429
+ json.dump(results, f, indent=2)
430
+
431
+
432
+ # =============================================================================
433
+ # Utility Functions
434
+ # =============================================================================
435
+
436
+
437
+ def create_temp_fasta(sequences: dict[str, str]) -> str:
438
+ """Create temporary FASTA file from sequences."""
439
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".fasta", delete=False) as tmp_file:
440
+ temp_path = tmp_file.name
441
+ FastaUtils.write_dict_to_fasta(sequences, temp_path)
442
+ return temp_path
443
+
444
+
445
+ def validate_and_write_sequences(
446
+ input_file: str, output_file: str, expected_length: int = 21
447
+ ) -> tuple[int, int, list[str]]:
448
+ """Validate siRNA sequences and write valid ones to output file."""
449
+ sequences = FastaUtils.parse_fasta_to_dict(input_file)
450
+
451
+ try:
452
+ valid_sequences = FastaUtils.validate_sirna_sequences(sequences, expected_length)
453
+
454
+ if valid_sequences:
455
+ FastaUtils.write_dict_to_fasta(valid_sequences, output_file)
456
+ else:
457
+ Path(output_file).touch()
458
+
459
+ invalid_count = len(sequences) - len(valid_sequences)
460
+ issues = [
461
+ f"{name}: Invalid (length={len(seq)}, expected={expected_length})"
462
+ for name, seq in sequences.items()
463
+ if name not in valid_sequences
464
+ ]
465
+
466
+ return len(valid_sequences), invalid_count, issues
467
+
468
+ except ValueError as e:
469
+ Path(output_file).touch()
470
+ return 0, len(sequences), [str(e)]
471
+
472
+
473
+ def build_bwa_index(fasta_file: str, index_prefix: str) -> str:
474
+ """Build BWA-MEM2 index for both transcriptome and miRNA off-target analysis."""
475
+ logger.info(f"Building BWA-MEM2 index from {fasta_file} with prefix {index_prefix}")
476
+
477
+ if not Path(fasta_file).exists():
478
+ raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}")
479
+
480
+ Path(index_prefix).parent.mkdir(parents=True, exist_ok=True)
481
+
482
+ # Get absolute path to bwa-mem2 executable
483
+ bwa_path = _get_executable_path("bwa-mem2")
484
+ if not bwa_path:
485
+ raise FileNotFoundError("bwa-mem2 executable not found in PATH")
486
+
487
+ cmd = [bwa_path, "index", "-p", index_prefix, fasta_file]
488
+ _validate_command_args(cmd)
489
+
490
+ try:
491
+ subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=7200) # nosec B603
492
+ logger.info(f"BWA-MEM2 index built successfully: {index_prefix}")
493
+ return index_prefix
494
+ except subprocess.CalledProcessError as e:
495
+ logger.error(f"BWA-MEM2 index build failed: {e.stderr}")
496
+ raise
497
+ except subprocess.TimeoutExpired:
498
+ logger.error("BWA-MEM2 index build timed out")
499
+ raise
500
+
501
+
502
+ def validate_sirna_sequences(
503
+ sequences: dict[str, str], expected_length: int = 21
504
+ ) -> tuple[dict[str, str], dict[str, str], list[str]]:
505
+ """Validate siRNA sequences using existing FastaUtils."""
506
+ try:
507
+ valid_sequences = FastaUtils.validate_sirna_sequences(sequences, expected_length)
508
+ invalid_sequences = {name: seq for name, seq in sequences.items() if name not in valid_sequences}
509
+ issues = [
510
+ f"{name}: Invalid sequence (length={len(seq)}, expected={expected_length})"
511
+ for name, seq in invalid_sequences.items()
512
+ ]
513
+ return valid_sequences, invalid_sequences, issues
514
+ except ValueError as e:
515
+ return {}, sequences, [str(e)]
516
+
517
+
518
+ def parse_fasta_file(fasta_file: str) -> dict[str, str]:
519
+ """Parse FASTA file using existing FastaUtils."""
520
+ return FastaUtils.parse_fasta_to_dict(fasta_file)
521
+
522
+
523
+ def write_fasta_file(sequences: dict[str, str], output_file: str) -> None:
524
+ """Write sequences to FASTA file using existing FastaUtils."""
525
+ FastaUtils.write_dict_to_fasta(sequences, output_file)
526
+
527
+
528
+ def check_tool_availability(tool: str) -> bool:
529
+ """Check if external tool is available."""
530
+ try:
531
+ # Get absolute path to tool executable
532
+ tool_path = _get_executable_path(tool)
533
+ if not tool_path:
534
+ return False
535
+
536
+ cmd = [tool_path, "--help"]
537
+ _validate_command_args(cmd)
538
+ result = subprocess.run(cmd, capture_output=True, check=False, timeout=10) # nosec B603
539
+ return result.returncode in {0, 1}
540
+ except (subprocess.TimeoutExpired, FileNotFoundError):
541
+ return False
542
+
543
+
544
+ def validate_index_files(index_prefix: str, tool: str = "bwa") -> bool:
545
+ """Validate that index files exist for given tool."""
546
+ index_path = Path(index_prefix)
547
+
548
+ if tool in ("bwa", "bwa-mem2"):
549
+ required_extensions = [".amb", ".ann", ".bwt.2bit.64", ".pac"]
550
+ else:
551
+ logger.warning(f"Unknown tool for index validation: {tool}")
552
+ return False
553
+
554
+ for ext in required_extensions:
555
+ if not (index_path.parent / f"{index_path.name}{ext}").exists():
556
+ logger.debug(f"Missing index file: {index_path.name}{ext}")
557
+ return False
558
+
559
+ return True
560
+
561
+
562
+ # =============================================================================
563
+ # Nextflow Integration Functions
564
+ # =============================================================================
565
+
566
+
567
+ def run_mirna_analysis_for_nextflow(
568
+ species: str,
569
+ sequences_file: str,
570
+ mirna_index: str,
571
+ output_prefix: str,
572
+ ) -> tuple[str, str, str]:
573
+ """Nextflow-compatible function for miRNA analysis."""
574
+ manager = OffTargetAnalysisManager(species=species, mirna_index=mirna_index)
575
+
576
+ try:
577
+ tsv_path, json_path = manager.analyze_mirna_off_targets(sequences_file, output_prefix)
578
+
579
+ # Create summary
580
+ summary_path = f"{output_prefix}_mirna_summary.txt"
581
+ with Path(summary_path).open("w") as f:
582
+ with Path(json_path).open() as jf:
583
+ results = json.load(jf)
584
+ f.write(f"Species: {species}\n")
585
+ f.write(f"Total miRNA hits: {len(results)}\n")
586
+ f.write("Analysis completed successfully\n")
587
+
588
+ return tsv_path, json_path, summary_path
589
+
590
+ except Exception as e:
591
+ error_summary = f"{output_prefix}_mirna_error.txt"
592
+ with Path(error_summary).open("w") as f:
593
+ f.write(f"miRNA analysis failed: {str(e)}\n")
594
+ return "", "", error_summary
595
+
596
+
597
+ def run_transcriptome_analysis_for_nextflow(
598
+ species: str,
599
+ sequences_file: str,
600
+ transcriptome_index: str,
601
+ output_prefix: str,
602
+ ) -> tuple[str, str, str]:
603
+ """Nextflow-compatible function for transcriptome analysis."""
604
+ manager = OffTargetAnalysisManager(species=species, transcriptome_index=transcriptome_index)
605
+
606
+ try:
607
+ tsv_path, json_path = manager.analyze_transcriptome_off_targets(sequences_file, output_prefix)
608
+
609
+ # Create summary
610
+ summary_path = f"{output_prefix}_transcriptome_summary.txt"
611
+ with Path(summary_path).open("w") as f:
612
+ with Path(json_path).open() as jf:
613
+ results = json.load(jf)
614
+ f.write(f"Species: {species}\n")
615
+ f.write(f"Total transcriptome hits: {len(results)}\n")
616
+ f.write("Analysis completed successfully\n")
617
+
618
+ return tsv_path, json_path, summary_path
619
+
620
+ except Exception as e:
621
+ error_summary = f"{output_prefix}_transcriptome_error.txt"
622
+ with Path(error_summary).open("w") as f:
623
+ f.write(f"Transcriptome analysis failed: {str(e)}\n")
624
+ return "", "", error_summary
625
+
626
+
627
+ def run_comprehensive_offtarget_analysis(
628
+ species: str,
629
+ sequences_file: str,
630
+ index_path: str,
631
+ output_prefix: str,
632
+ mode: str = "transcriptome",
633
+ bwa_k: int = 12,
634
+ bwa_T: int = 15,
635
+ max_hits: int = 10000,
636
+ seed_start: int = 2,
637
+ seed_end: int = 8,
638
+ ) -> tuple[str, str, str]:
639
+ """Run comprehensive off-target analysis for Nextflow integration."""
640
+ try:
641
+ sequences = parse_fasta_file(sequences_file)
642
+
643
+ # Use BWA analyzer for comprehensive analysis
644
+ analyzer = BwaAnalyzer(
645
+ index_prefix=index_path,
646
+ mode=mode,
647
+ seed_length=bwa_k,
648
+ min_score=bwa_T,
649
+ max_hits=max_hits,
650
+ seed_start=seed_start,
651
+ seed_end=seed_end,
652
+ )
653
+
654
+ results = analyzer.analyze_sequences(sequences)
655
+
656
+ # Write results
657
+ tsv_path = f"{output_prefix}.tsv"
658
+ json_path = f"{output_prefix}.json"
659
+ summary_path = f"{output_prefix}_summary.txt"
660
+
661
+ # Write TSV
662
+ with Path(tsv_path).open("w") as f:
663
+ f.write("qname\tqseq\trname\tcoord\tstrand\tcigar\tmapq\tas_score\tnm\tseed_mismatches\tofftarget_score\n")
664
+ for result in results:
665
+ f.write(
666
+ f"{result['qname']}\t{result['qseq']}\t{result['rname']}\t"
667
+ f"{result['coord']}\t{result['strand']}\t{result['cigar']}\t"
668
+ f"{result['mapq']}\t{result.get('as_score', 'NA')}\t{result['nm']}\t"
669
+ f"{result['seed_mismatches']}\t{result['offtarget_score']}\n"
670
+ )
671
+
672
+ # Write JSON
673
+ with Path(json_path).open("w") as f:
674
+ json.dump(results, f, indent=2)
675
+
676
+ # Write summary
677
+ with Path(summary_path).open("w") as f:
678
+ f.write(f"Species: {species}\n")
679
+ f.write(f"Total sequences analyzed: {len(sequences)}\n")
680
+ f.write(f"Total off-target hits: {len(results)}\n")
681
+ f.write(f"Analysis mode: {mode}\n")
682
+ f.write(f"Analysis parameters: bwa_k={bwa_k}, bwa_T={bwa_T}, max_hits={max_hits}\n")
683
+ f.write(f"Seed region: {seed_start}-{seed_end}\n")
684
+ f.write("Analysis completed successfully\n")
685
+
686
+ return tsv_path, json_path, summary_path
687
+
688
+ except Exception as e:
689
+ error_summary = f"{output_prefix}_error.txt"
690
+ with Path(error_summary).open("w") as f:
691
+ f.write(f"Comprehensive off-target analysis failed: {str(e)}\n")
692
+ return "", "", error_summary
693
+
694
+
695
+ # Export all main functions and classes
696
+ __all__ = [
697
+ # Core classes
698
+ "BwaAnalyzer",
699
+ "OffTargetAnalysisManager",
700
+ # Utility functions
701
+ "create_temp_fasta",
702
+ "validate_and_write_sequences",
703
+ "build_bwa_index",
704
+ "validate_sirna_sequences",
705
+ "parse_fasta_file",
706
+ "write_fasta_file",
707
+ "check_tool_availability",
708
+ "validate_index_files",
709
+ # Nextflow functions
710
+ "run_mirna_analysis_for_nextflow",
711
+ "run_transcriptome_analysis_for_nextflow",
712
+ "run_comprehensive_offtarget_analysis",
713
+ ]