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 @@
1
+ """Empty __init__.py files for proper package structure."""
@@ -0,0 +1,470 @@
1
+ """Core siRNA design algorithms and functionality."""
2
+
3
+ import math
4
+ import time
5
+ from typing import Optional, Union
6
+
7
+ from Bio import SeqIO
8
+ from Bio.Seq import Seq
9
+
10
+ from sirnaforge.core.thermodynamics import ThermodynamicCalculator
11
+ from sirnaforge.models.sirna import DesignParameters, DesignResult, SiRNACandidate
12
+ from sirnaforge.models.sirna import SiRNACandidate as _ModelCandidate
13
+
14
+
15
+ class SiRNADesigner:
16
+ """Main siRNA design engine following the algorithm specification."""
17
+
18
+ def __init__(self, parameters: DesignParameters) -> None:
19
+ """Initialize designer with given parameters."""
20
+ self.parameters = parameters
21
+
22
+ def design_from_file(self, input_file: str) -> DesignResult:
23
+ """Design siRNAs from input FASTA file."""
24
+ start_time = time.time()
25
+
26
+ # Parse input sequences
27
+ sequences = list(SeqIO.parse(input_file, "fasta"))
28
+ if not sequences:
29
+ raise ValueError(f"No sequences found in {input_file}")
30
+
31
+ all_candidates: list[SiRNACandidate] = []
32
+ # Map guide_sequence -> set of transcript_ids where it appears
33
+ guide_to_transcripts: dict[str, set[str]] = {}
34
+
35
+ # Process each sequence
36
+ for seq_record in sequences:
37
+ transcript_id = seq_record.id
38
+ sequence = str(seq_record.seq).upper()
39
+
40
+ # Generate candidates for this sequence
41
+ candidates = self._enumerate_candidates(sequence, transcript_id)
42
+
43
+ # Apply filters
44
+ filtered_candidates = self._apply_filters(candidates)
45
+
46
+ # Score candidates
47
+ scored_candidates = self._score_candidates(filtered_candidates)
48
+
49
+ # Track which transcripts each guide appears in
50
+ for c in scored_candidates:
51
+ guide_to_transcripts.setdefault(c.guide_sequence, set()).add(c.transcript_id)
52
+
53
+ all_candidates.extend(scored_candidates)
54
+
55
+ # Sort by composite score (descending)
56
+ all_candidates.sort(key=lambda x: x.composite_score, reverse=True)
57
+
58
+ # Get top candidates only from those passing filters; fallback to all if none pass
59
+ passing = [
60
+ c
61
+ for c in all_candidates
62
+ if (c.passes_filters is True)
63
+ or (hasattr(_ModelCandidate, "FilterStatus") and c.passes_filters == _ModelCandidate.FilterStatus.PASS)
64
+ ]
65
+ top_candidates = (passing or all_candidates)[: self.parameters.top_n]
66
+
67
+ processing_time = time.time() - start_time
68
+ # Compute transcript hit metrics for each candidate (how many input transcripts contain the guide)
69
+ total_seqs = len(sequences)
70
+ for c in all_candidates:
71
+ hits = len(guide_to_transcripts.get(c.guide_sequence, {c.transcript_id}))
72
+ c.transcript_hit_count = hits
73
+ c.transcript_hit_fraction = hits / total_seqs if total_seqs > 0 else 0.0
74
+
75
+ return DesignResult(
76
+ input_file=input_file,
77
+ parameters=self.parameters,
78
+ candidates=all_candidates,
79
+ top_candidates=top_candidates,
80
+ total_sequences=len(sequences),
81
+ total_candidates=len(all_candidates),
82
+ filtered_candidates=len(
83
+ [
84
+ c
85
+ for c in all_candidates
86
+ if (c.passes_filters is True)
87
+ or (
88
+ hasattr(_ModelCandidate, "FilterStatus")
89
+ and c.passes_filters == _ModelCandidate.FilterStatus.PASS
90
+ )
91
+ ]
92
+ ),
93
+ processing_time=processing_time,
94
+ tool_versions=self._get_tool_versions(),
95
+ )
96
+
97
+ def design_from_sequence(self, sequence: str, transcript_id: str = "seq1") -> DesignResult:
98
+ """Design siRNAs from a single sequence."""
99
+ start_time = time.time()
100
+
101
+ sequence = sequence.upper()
102
+
103
+ # Generate candidates
104
+ candidates = self._enumerate_candidates(sequence, transcript_id)
105
+
106
+ # Apply filters
107
+ filtered_candidates = self._apply_filters(candidates)
108
+
109
+ # Score candidates
110
+ scored_candidates = self._score_candidates(filtered_candidates)
111
+
112
+ # Sort by composite score (descending)
113
+ scored_candidates.sort(key=lambda x: x.composite_score, reverse=True)
114
+
115
+ # Get top candidates only from those passing filters; fallback to all if none pass
116
+ passing = [
117
+ c
118
+ for c in scored_candidates
119
+ if (c.passes_filters is True)
120
+ or (hasattr(_ModelCandidate, "FilterStatus") and c.passes_filters == _ModelCandidate.FilterStatus.PASS)
121
+ ]
122
+ top_candidates = (passing or scored_candidates)[: self.parameters.top_n]
123
+
124
+ processing_time = time.time() - start_time
125
+ # For single-sequence runs, transcript hit metrics are trivial (hits=1, fraction=1.0)
126
+ for c in scored_candidates:
127
+ c.transcript_hit_count = 1
128
+ c.transcript_hit_fraction = 1.0
129
+ return DesignResult(
130
+ input_file="<direct_input>",
131
+ parameters=self.parameters,
132
+ candidates=scored_candidates,
133
+ top_candidates=top_candidates,
134
+ total_sequences=1,
135
+ total_candidates=len(scored_candidates),
136
+ filtered_candidates=len(
137
+ [
138
+ c
139
+ for c in scored_candidates
140
+ if (c.passes_filters is True)
141
+ or (
142
+ hasattr(_ModelCandidate, "FilterStatus")
143
+ and c.passes_filters == _ModelCandidate.FilterStatus.PASS
144
+ )
145
+ ]
146
+ ),
147
+ processing_time=processing_time,
148
+ tool_versions=self._get_tool_versions(),
149
+ )
150
+
151
+ def _enumerate_candidates(self, sequence: str, transcript_id: str) -> list[SiRNACandidate]:
152
+ """Enumerate all possible siRNA candidates using sliding window with early filtering."""
153
+ candidates = []
154
+ sirna_length = self.parameters.sirna_length
155
+ filters = self.parameters.filters
156
+
157
+ # Slide window across sequence
158
+ for i in range(len(sequence) - sirna_length + 1):
159
+ target_seq = sequence[i : i + sirna_length]
160
+
161
+ # Generate guide (antisense) and passenger (sense) sequences
162
+ guide_seq = str(Seq(target_seq).reverse_complement())
163
+ passenger_seq = target_seq
164
+
165
+ # Early filtering for computational efficiency
166
+ gc_content = self._calculate_gc_content(guide_seq)
167
+ if not (filters.gc_min <= gc_content <= filters.gc_max):
168
+ continue
169
+
170
+ # Early filtering: check for poly runs before creating candidate object
171
+ if self._has_poly_runs(guide_seq, filters.max_poly_runs):
172
+ continue
173
+
174
+ # Create candidate ID with project moniker and sanitized transcript id
175
+ # Format: SIRNAF_<TRANSCRIPT>_<start>_<end>
176
+ # Sanitize transcript_id: keep alphanumerics and underscore, replace others with '-'
177
+ safe_tid = "".join([c if (c.isalnum() or c == "_") else "-" for c in transcript_id])
178
+ # Truncate long transcript ids to keep IDs short while retaining uniqueness
179
+ if len(safe_tid) > 24:
180
+ safe_tid = safe_tid[:24]
181
+ candidate_id = f"SIRNAF_{safe_tid}_{i + 1}_{i + sirna_length}"
182
+
183
+ candidate = SiRNACandidate(
184
+ id=candidate_id,
185
+ transcript_id=transcript_id,
186
+ position=i + 1, # 1-based
187
+ guide_sequence=guide_seq,
188
+ passenger_sequence=passenger_seq,
189
+ gc_content=gc_content,
190
+ length=sirna_length,
191
+ asymmetry_score=0.0, # Will be calculated in scoring
192
+ composite_score=0.0, # Will be calculated in scoring
193
+ )
194
+
195
+ candidates.append(candidate)
196
+
197
+ return candidates
198
+
199
+ def _apply_filters(self, candidates: list[SiRNACandidate]) -> list[SiRNACandidate]:
200
+ """Apply remaining filters (early GC and poly-run filtering already done in enumeration)."""
201
+ filtered = []
202
+
203
+ for candidate in candidates:
204
+ issues: list[str] = []
205
+ status: Union[bool, _ModelCandidate.FilterStatus] = True
206
+
207
+ # Note: GC content and poly-run filtering already done in _enumerate_candidates
208
+ # This is mainly for any additional filters or post-processing
209
+
210
+ # Update candidate with filter results
211
+ candidate.passes_filters = status
212
+ candidate.quality_issues = issues
213
+
214
+ filtered.append(candidate)
215
+
216
+ return filtered
217
+
218
+ def _score_candidates(self, candidates: list[SiRNACandidate]) -> list[SiRNACandidate]:
219
+ """Score candidates using composite scoring algorithm."""
220
+
221
+ for candidate in candidates:
222
+ # Calculate component scores
223
+ # Thermodynamic end stabilities and asymmetry
224
+ dg5: float = float("nan")
225
+ dg3: float = float("nan")
226
+ try:
227
+ calc = ThermodynamicCalculator()
228
+ dg5, dg3, asym_score = calc.calculate_asymmetry_score(candidate)
229
+ except Exception:
230
+ # Fallback if ViennaRNA or calculation not available
231
+ asym_score = self._calculate_asymmetry_score(candidate)
232
+ dg5, dg3 = float("nan"), float("nan")
233
+ # Thermodynamic duplex stability (ΔG) and score normalization
234
+ dg_score, duplex_dg = self._calculate_duplex_score(candidate)
235
+ candidate.duplex_stability = duplex_dg
236
+ gc_score = self._calculate_gc_score(candidate.gc_content)
237
+ access_score = self._calculate_accessibility_score(candidate)
238
+ ot_score = self._calculate_off_target_score(candidate)
239
+ empirical_score = self._calculate_empirical_score(candidate)
240
+
241
+ # Optional melting temperature estimation (rough)
242
+ tm_c = float("nan")
243
+ try:
244
+ if "calc" in locals():
245
+ tm_c = calc.calculate_melting_temperature(candidate.guide_sequence, candidate.passenger_sequence)
246
+ else:
247
+ calc2 = ThermodynamicCalculator()
248
+ tm_c = calc2.calculate_melting_temperature(candidate.guide_sequence, candidate.passenger_sequence)
249
+ except Exception:
250
+ tm_c = float("nan")
251
+
252
+ # Store component scores
253
+ # TODO: The composite_score needs to have basic weighting applied with truth data
254
+ # Combine thermodynamic components: favor asymmetry with contribution from duplex stability
255
+ thermo_combo = 0.7 * asym_score + 0.3 * dg_score
256
+
257
+ candidate.component_scores = {
258
+ "asymmetry": asym_score,
259
+ # store as float; if missing, use NaN to satisfy type expectations
260
+ "duplex_stability_dg": float(duplex_dg) if duplex_dg is not None else float("nan"),
261
+ "duplex_stability_score": dg_score,
262
+ "thermo_combo": thermo_combo,
263
+ "dg_5p": float(dg5),
264
+ "dg_3p": float(dg3),
265
+ "delta_dg_end": float(dg5 - dg3) if (not math.isnan(dg5) and not math.isnan(dg3)) else float("nan"),
266
+ "melting_temp_c": float(tm_c),
267
+ "gc_content": gc_score,
268
+ "accessibility": access_score,
269
+ "off_target": ot_score,
270
+ "empirical": empirical_score,
271
+ }
272
+
273
+ # Calculate composite score using configurable weights from parameters
274
+ # Access the configured scoring weights
275
+ weights = self.parameters.scoring
276
+
277
+ # Apply the configured weights to each component
278
+ composite = (
279
+ weights.asymmetry * asym_score
280
+ + weights.gc_content * gc_score
281
+ + weights.accessibility * access_score
282
+ + weights.off_target * ot_score
283
+ + weights.empirical * empirical_score
284
+ )
285
+
286
+ # Normalize to 0-100 scale
287
+ candidate.composite_score = composite * 100
288
+ candidate.asymmetry_score = asym_score
289
+
290
+ return candidates
291
+
292
+ def _calculate_duplex_score(self, candidate: SiRNACandidate) -> tuple[float, Optional[float]]:
293
+ """Compute duplex stability ΔG and a normalized score in [0,1].
294
+
295
+ Mapping: dg in [-40, -5] kcal/mol -> score in [1, 0]. Clamp outside this range.
296
+ On failure or missing backend, returns (asymmetry_score, None) as a fallback.
297
+ """
298
+ try:
299
+ calc = ThermodynamicCalculator()
300
+ dg = calc.calculate_duplex_stability(candidate.guide_sequence, candidate.passenger_sequence)
301
+ # Normalize: more negative is better
302
+ # Clamp dg to [-40, -5]
303
+ lo, hi = -40.0, -5.0
304
+ dg_clamped = max(lo, min(hi, dg))
305
+ score = (-(dg_clamped) - 5.0) / (40.0 - 5.0)
306
+ score = max(0.0, min(1.0, score))
307
+ return score, float(dg)
308
+ except Exception:
309
+ # Fallback: use asymmetry as proxy if duplex calc not available
310
+ try:
311
+ asym = self._calculate_asymmetry_score(candidate)
312
+ except Exception:
313
+ asym = 0.5
314
+ return asym, None
315
+
316
+ def _calculate_gc_content(self, sequence: str) -> float:
317
+ """Calculate GC content percentage."""
318
+ gc_count = sequence.count("G") + sequence.count("C")
319
+ return (gc_count / len(sequence)) * 100
320
+
321
+ def _has_poly_runs(self, sequence: str, max_runs: int) -> bool:
322
+ """Check for runs of identical nucleotides exceeding threshold."""
323
+ current_base = sequence[0]
324
+ current_run = 1
325
+
326
+ for base in sequence[1:]:
327
+ if base == current_base:
328
+ current_run += 1
329
+ if current_run > max_runs:
330
+ return True
331
+ else:
332
+ current_base = base
333
+ current_run = 1
334
+
335
+ return False
336
+
337
+ def _calculate_asymmetry_score(self, candidate: SiRNACandidate) -> float:
338
+ """Calculate thermodynamic asymmetry score using enhanced method."""
339
+ try:
340
+ calc = ThermodynamicCalculator()
341
+ _, _, asymmetry_score = calc.calculate_asymmetry_score(candidate)
342
+ return asymmetry_score
343
+ except ImportError:
344
+ # Fallback to simplified version
345
+ guide = candidate.guide_sequence
346
+
347
+ # Calculate stability of 5' end (positions 1-7) vs 3' end (positions 15-21)
348
+ five_prime_end = guide[:7]
349
+ three_prime_end = guide[14:21] if len(guide) >= 21 else guide[14:]
350
+
351
+ # Simplified AT/GC ratio as proxy for stability
352
+ five_prime_gc = (five_prime_end.count("G") + five_prime_end.count("C")) / len(five_prime_end)
353
+ three_prime_gc = (three_prime_end.count("G") + three_prime_end.count("C")) / len(three_prime_end)
354
+
355
+ # Higher score when 5' end is less stable (lower GC) than 3' end
356
+ asymmetry = three_prime_gc - five_prime_gc
357
+
358
+ # Normalize to 0-1 range
359
+ return max(0.0, min(1.0, (asymmetry + 1.0) / 2.0))
360
+
361
+ def _calculate_gc_score(self, gc_content: float) -> float:
362
+ """Calculate GC content score with Gaussian penalty around 40%."""
363
+ # GC_score = exp(-((GC-40)/10)^2)
364
+ return math.exp(-(((gc_content - 40) / 10) ** 2))
365
+
366
+ def _calculate_accessibility_score(self, candidate: SiRNACandidate) -> float:
367
+ """Calculate target accessibility score using ViennaRNA when available."""
368
+ try:
369
+ calc = ThermodynamicCalculator()
370
+
371
+ # For single candidate analysis, we don't have full target sequence context
372
+ # So we'll use the guide sequence as a proxy for structure prediction
373
+ guide = candidate.guide_sequence
374
+ structure, mfe, paired_fraction = calc.calculate_secondary_structure(guide)
375
+
376
+ # Store structure info in candidate
377
+ candidate.structure = structure
378
+ candidate.mfe = mfe
379
+ candidate.paired_fraction = paired_fraction
380
+
381
+ # Accessibility score: 1 - paired_fraction
382
+ # Flag excessive pairing per filter threshold
383
+ try:
384
+ if (
385
+ hasattr(_ModelCandidate, "FilterStatus")
386
+ and paired_fraction is not None
387
+ and paired_fraction > self.parameters.filters.max_paired_fraction
388
+ and candidate.passes_filters is True
389
+ ):
390
+ candidate.passes_filters = _ModelCandidate.FilterStatus.EXCESS_PAIRING
391
+ except (AttributeError, ValueError, TypeError): # nosec B110 acceptable narrow handling
392
+ # Ignore unexpected attribute/value issues; filtering status remains unchanged.
393
+ pass
394
+ return 1.0 - paired_fraction
395
+
396
+ except ImportError:
397
+ # Fallback to simple heuristic
398
+ guide = candidate.guide_sequence
399
+ at_content = (guide.count("A") + guide.count("T") + guide.count("U")) / len(guide)
400
+
401
+ # Moderate AT content suggests better accessibility
402
+ paired_fraction = abs(at_content - 0.5) * 2.0 # heuristic inverse
403
+ candidate.paired_fraction = paired_fraction
404
+ try:
405
+ if (
406
+ hasattr(_ModelCandidate, "FilterStatus")
407
+ and paired_fraction > self.parameters.filters.max_paired_fraction
408
+ and candidate.passes_filters is True
409
+ ):
410
+ candidate.passes_filters = _ModelCandidate.FilterStatus.EXCESS_PAIRING
411
+ except (AttributeError, ValueError, TypeError): # nosec B110
412
+ pass
413
+ return 1.0 - paired_fraction
414
+
415
+ def _calculate_off_target_score(self, candidate: SiRNACandidate) -> float:
416
+ """Calculate off-target score using simplified analysis."""
417
+ # Simplified version - comprehensive off-target analysis would require
418
+ # external databases and more complex alignment tools
419
+ guide = candidate.guide_sequence
420
+
421
+ # Simple penalty for repetitive sequences
422
+ penalty = 0
423
+ for i in range(len(guide) - 6):
424
+ seed = guide[i : i + 7]
425
+ # Count occurrences of this 7-mer in the sequence
426
+ if guide.count(seed) > 1:
427
+ penalty += 10
428
+
429
+ # Transform penalty to score: OT_score = exp(-penalty/50)
430
+ candidate.off_target_penalty = penalty
431
+ return math.exp(-penalty / 50)
432
+
433
+ def _calculate_empirical_score(self, candidate: SiRNACandidate) -> float:
434
+ """Calculate empirical score using Reynolds et al. rules (simplified)."""
435
+ guide = candidate.guide_sequence
436
+ score = 0.5 # Base score
437
+
438
+ # Some simplified Reynolds rules
439
+ # Prefer A/U at position 19 (3' end of guide)
440
+ if len(guide) >= 19 and guide[18] in ["A", "U"]:
441
+ score += 0.1
442
+
443
+ # Prefer G/C at position 1
444
+ if guide[0] in ["G", "C"]:
445
+ score += 0.1
446
+
447
+ # Avoid C at position 19
448
+ if len(guide) >= 19 and guide[18] == "C":
449
+ score -= 0.1
450
+
451
+ result = max(0.0, min(1.0, score))
452
+ # Enforce minimal asymmetry threshold as a filter
453
+ try:
454
+ if (
455
+ hasattr(_ModelCandidate, "FilterStatus")
456
+ and result < self.parameters.filters.min_asymmetry_score
457
+ and candidate.passes_filters is True
458
+ ):
459
+ candidate.passes_filters = _ModelCandidate.FilterStatus.LOW_ASYMMETRY
460
+ except (AttributeError, ValueError, TypeError): # nosec B110
461
+ pass
462
+ return result
463
+
464
+ def _get_tool_versions(self) -> dict[str, str]:
465
+ """Get versions of tools used (placeholder)."""
466
+ return {
467
+ "python": "3.11.5",
468
+ "biopython": "1.81",
469
+ "sirnaforge": "0.1.0",
470
+ }