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
sirnaforge/cli.py ADDED
@@ -0,0 +1,837 @@
1
+ """Modern CLI for siRNAforge using Typer and Rich."""
2
+
3
+ # Configure environment for ASCII compatibility before importing typer/rich
4
+ import os
5
+
6
+ os.environ.setdefault("FORCE_COLOR", "0")
7
+ os.environ.setdefault("NO_COLOR", "1")
8
+ os.environ.setdefault("TERM", "dumb")
9
+
10
+ import asyncio
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar
13
+
14
+ import typer
15
+ from Bio import SeqIO
16
+ from rich.console import Console
17
+ from rich.panel import Panel
18
+ from rich.progress import Progress, SpinnerColumn, TextColumn
19
+ from rich.table import Table
20
+
21
+ from sirnaforge.data.mirna_manager import MiRNADatabaseManager
22
+
23
+ # Monkey patch Rich console (best-effort). If this fails we continue with default behavior.
24
+ try:
25
+ import rich.console
26
+
27
+ original_init = rich.console.Console.__init__
28
+
29
+ def patched_init(self: "rich.console.Console", *args: Any, **kwargs: Any) -> None: # noqa: D401
30
+ # Force simplified terminal capabilities for deterministic CI output.
31
+ kwargs["legacy_windows"] = True
32
+ kwargs["force_terminal"] = False
33
+ original_init(self, *args, **kwargs)
34
+
35
+ if not TYPE_CHECKING: # Avoid confusing type checkers
36
+ rich.console.Console.__init__ = patched_init # type: ignore[attr-defined]
37
+ except (ImportError, AttributeError): # Narrow exceptions
38
+ # Silently ignore—output formatting will just be richer if available.
39
+ # nosec B110 - acceptable silent fallback; not security relevant
40
+ pass
41
+
42
+ from sirnaforge import __author__, __version__
43
+ from sirnaforge.core.design import SiRNADesigner
44
+ from sirnaforge.data.base import DatabaseType
45
+ from sirnaforge.data.gene_search import (
46
+ GeneSearcher,
47
+ search_gene_sync,
48
+ search_gene_with_fallback_sync,
49
+ search_multiple_databases_sync,
50
+ )
51
+ from sirnaforge.models.sirna import DesignParameters, FilterCriteria
52
+ from sirnaforge.utils.logging_utils import configure_logging
53
+ from sirnaforge.workflow import run_sirna_workflow
54
+
55
+ app = typer.Typer(
56
+ name="sirnaforge",
57
+ help="siRNAforge - siRNA design toolkit for gene silencing",
58
+ rich_markup_mode="rich",
59
+ )
60
+ # Configure console to use ASCII box characters for better compatibility
61
+ console = Console(force_terminal=False, legacy_windows=True)
62
+
63
+ # mypy-friendly alias for Typer command decorator
64
+ T = TypeVar("T", bound=Callable[..., object])
65
+ CommandDecorator = Callable[..., Callable[[T], T]]
66
+ app_command: CommandDecorator = app.command
67
+
68
+
69
+ def filter_transcripts(transcripts, include_types=None, exclude_types=None, canonical_only=False): # type: ignore
70
+ """Filter transcripts based on type and canonical status."""
71
+ filtered = transcripts
72
+
73
+ if canonical_only:
74
+ filtered = [t for t in filtered if t.is_canonical]
75
+
76
+ if include_types:
77
+ filtered = [t for t in filtered if t.transcript_type in include_types]
78
+
79
+ if exclude_types:
80
+ filtered = [t for t in filtered if t.transcript_type not in exclude_types]
81
+
82
+ return filtered
83
+
84
+
85
+ def extract_canonical_transcripts(transcripts, gene_name, output_dir=None): # type: ignore
86
+ """Extract canonical transcripts to a separate file."""
87
+ canonical = [t for t in transcripts if t.is_canonical]
88
+
89
+ if not canonical:
90
+ return None, 0
91
+
92
+ output_dir = Path.cwd() if output_dir is None else Path(output_dir)
93
+
94
+ canonical_file = output_dir / f"{gene_name}_canonical.fasta"
95
+
96
+ # Create a temporary searcher to use the save method
97
+ # TODO: directly use fasta utils
98
+ searcher = GeneSearcher()
99
+ searcher.save_transcripts_fasta(canonical, canonical_file)
100
+
101
+ return canonical_file, len(canonical)
102
+
103
+
104
+ @app_command()
105
+ def search( # noqa: PLR0912
106
+ query: str = typer.Argument(..., help="Gene ID, gene name, or transcript ID to search for"),
107
+ output: Path = typer.Option(
108
+ Path("transcripts.fasta"),
109
+ "--output",
110
+ "-o",
111
+ help="Output FASTA file for transcript sequences",
112
+ ),
113
+ database: str = typer.Option(
114
+ "ensembl",
115
+ "--database",
116
+ "-d",
117
+ help="Database to search (ensembl, refseq, gencode)",
118
+ ),
119
+ all_databases: bool = typer.Option(
120
+ False,
121
+ "--all",
122
+ "-a",
123
+ help="Search all databases",
124
+ ),
125
+ fallback: bool = typer.Option(
126
+ True,
127
+ "--fallback/--no-fallback",
128
+ help="Enable automatic fallback to other databases if access is blocked",
129
+ ),
130
+ no_sequence: bool = typer.Option(
131
+ False,
132
+ "--no-sequence",
133
+ help="Skip sequence retrieval (metadata only)",
134
+ ),
135
+ canonical_only: bool = typer.Option(
136
+ False,
137
+ "--canonical-only",
138
+ help="Extract only canonical isoforms",
139
+ ),
140
+ extract_canonical: bool = typer.Option(
141
+ True,
142
+ "--extract-canonical/--no-extract-canonical",
143
+ help="Automatically extract canonical isoforms to separate file",
144
+ ),
145
+ transcript_types: str = typer.Option(
146
+ "protein_coding,lncRNA",
147
+ "--types",
148
+ "-t",
149
+ help="Comma-separated list of transcript types to include (e.g., protein_coding,lncRNA)",
150
+ ),
151
+ exclude_types: str = typer.Option(
152
+ "nonsense_mediated_decay,retained_intron",
153
+ "--exclude-types",
154
+ help="Comma-separated list of transcript types to exclude",
155
+ ),
156
+ verbose: bool = typer.Option(
157
+ False,
158
+ "--verbose",
159
+ "-v",
160
+ help="Enable verbose output",
161
+ ),
162
+ ) -> None:
163
+ """Search for gene transcripts and retrieve sequences."""
164
+
165
+ try:
166
+ # imports moved to top
167
+
168
+ # Validate database choice
169
+ try:
170
+ db_type = DatabaseType(database.lower())
171
+ except ValueError:
172
+ console.print(f"❌ [red]Invalid database:[/red] {database}")
173
+ console.print("Valid options: ensembl, refseq, gencode")
174
+ raise typer.Exit(1)
175
+
176
+ console.print(
177
+ Panel.fit(
178
+ f"🧬 [bold blue]Gene Search[/bold blue]\n"
179
+ f"Query: [cyan]{query}[/cyan]\n"
180
+ f"Database: [yellow]{database}[/yellow]\n"
181
+ f"Fallback: [green]{'enabled' if fallback else 'disabled'}[/green]\n"
182
+ f"Output: [cyan]{output}[/cyan]\n"
183
+ f"Types: [green]{transcript_types}[/green]\n"
184
+ f"Exclude: [red]{exclude_types}[/red]",
185
+ title="Search Configuration",
186
+ )
187
+ )
188
+
189
+ # Parse transcript types
190
+ include_types = [t.strip() for t in transcript_types.split(",") if t.strip()] if transcript_types else []
191
+ exclude_types_list = [t.strip() for t in exclude_types.split(",") if t.strip()] if exclude_types else []
192
+
193
+ with Progress(
194
+ SpinnerColumn(),
195
+ TextColumn("[progress.description]{task.description}"),
196
+ console=console,
197
+ ) as progress:
198
+ if all_databases:
199
+ progress.add_task("Searching all databases...", total=None)
200
+ results = search_multiple_databases_sync(
201
+ query=query, databases=list(DatabaseType), include_sequence=not no_sequence
202
+ )
203
+ elif fallback:
204
+ progress.add_task("Searching with fallback...", total=None)
205
+ results = [search_gene_with_fallback_sync(query=query, include_sequence=not no_sequence)]
206
+ else:
207
+ progress.add_task(f"Searching {database}...", total=None)
208
+ results = [search_gene_sync(query=query, database=db_type, include_sequence=not no_sequence)]
209
+
210
+ # Display results
211
+ successful_results = [r for r in results if r.success]
212
+
213
+ if not successful_results:
214
+ console.print(f"❌ [red]No results found for:[/red] {query}")
215
+ for result in results:
216
+ if result.error:
217
+ db_name = result.database.value if hasattr(result.database, "value") else str(result.database)
218
+ console.print(f" {db_name}: {result.error}")
219
+ raise typer.Exit(1)
220
+
221
+ # Apply filtering to all transcripts
222
+ all_transcripts = []
223
+ for result in successful_results:
224
+ filtered_transcripts = filter_transcripts(
225
+ result.transcripts,
226
+ include_types=include_types,
227
+ exclude_types=exclude_types_list,
228
+ canonical_only=canonical_only,
229
+ )
230
+ result.transcripts = filtered_transcripts # Update result with filtered transcripts
231
+ all_transcripts.extend(filtered_transcripts)
232
+
233
+ # Check if filtering removed all transcripts
234
+ if not all_transcripts:
235
+ console.print("❌ [red]No transcripts found after applying filters[/red]")
236
+ console.print(f" Include types: {include_types}")
237
+ console.print(f" Exclude types: {exclude_types_list}")
238
+ raise typer.Exit(1)
239
+
240
+ # Display summary table
241
+ summary_table = Table(title="📊 Search Results")
242
+ summary_table.add_column("Database", style="cyan")
243
+ summary_table.add_column("Gene ID", style="blue")
244
+ summary_table.add_column("Gene Name", style="green")
245
+ summary_table.add_column("Transcripts", style="yellow")
246
+ summary_table.add_column("Status", style="magenta")
247
+
248
+ for result in results:
249
+ if result.success:
250
+ gene_id = result.gene_info.gene_id if result.gene_info else "N/A"
251
+ gene_name = result.gene_info.gene_name if result.gene_info else "N/A"
252
+ transcript_count = len(result.transcripts)
253
+ status = "✅ Success"
254
+ else:
255
+ gene_id = "N/A"
256
+ gene_name = "N/A"
257
+ transcript_count = 0
258
+ status = f"❌ {result.error}"
259
+
260
+ db_name = result.database.value if hasattr(result.database, "value") else str(result.database)
261
+ summary_table.add_row(db_name, gene_id, gene_name, str(transcript_count), status)
262
+
263
+ console.print(summary_table)
264
+
265
+ # Show transcript details for successful results
266
+ if successful_results and not no_sequence:
267
+ transcript_table = Table(title="🧬 Transcript Details")
268
+ transcript_table.add_column("Transcript ID", style="cyan")
269
+ transcript_table.add_column("Database", style="blue")
270
+ transcript_table.add_column("Type", style="green")
271
+ transcript_table.add_column("Length", style="yellow")
272
+ transcript_table.add_column("Canonical", style="magenta")
273
+
274
+ for transcript in all_transcripts[:10]: # Show first 10
275
+ db_name = (
276
+ transcript.database.value if hasattr(transcript.database, "value") else str(transcript.database)
277
+ )
278
+ transcript_table.add_row(
279
+ transcript.transcript_id,
280
+ db_name,
281
+ transcript.transcript_type or "N/A",
282
+ str(transcript.length) if transcript.length else "N/A",
283
+ "✓" if transcript.is_canonical else "",
284
+ )
285
+
286
+ console.print(transcript_table)
287
+
288
+ if len(all_transcripts) > 10:
289
+ console.print(f"... and {len(all_transcripts) - 10} more transcripts")
290
+
291
+ # Save sequences to FASTA if requested
292
+ if not no_sequence and all_transcripts:
293
+ searcher = GeneSearcher()
294
+ transcripts_with_sequence = [t for t in all_transcripts if t.sequence]
295
+
296
+ if transcripts_with_sequence:
297
+ searcher.save_transcripts_fasta(transcripts_with_sequence, output)
298
+ console.print(f"\n✅ [green]Saved {len(transcripts_with_sequence)} sequences to:[/green] {output}")
299
+
300
+ # Extract canonical isoforms if requested
301
+ if extract_canonical and not canonical_only:
302
+ gene_name = None
303
+ for result in successful_results:
304
+ if result.gene_info and result.gene_info.gene_name:
305
+ gene_name = result.gene_info.gene_name
306
+ break
307
+
308
+ if gene_name:
309
+ canonical_file, canonical_count = extract_canonical_transcripts(
310
+ transcripts_with_sequence, gene_name, output.parent
311
+ )
312
+ if canonical_file:
313
+ console.print(
314
+ f"📌 [blue]Extracted {canonical_count} canonical isoform(s) to:[/blue] {canonical_file}"
315
+ )
316
+ else:
317
+ console.print("ℹ️ [yellow]No canonical isoforms found[/yellow]")
318
+ else:
319
+ console.print("⚠️ [yellow]No sequences available to save[/yellow]")
320
+
321
+ console.print(
322
+ f"\n📊 [blue]Summary:[/blue] Found {len(all_transcripts)} transcripts from {len(successful_results)} database(s)"
323
+ )
324
+
325
+ except Exception as e:
326
+ console.print(f"❌ [red]Search error:[/red] {str(e)}")
327
+ if verbose:
328
+ console.print_exception()
329
+ raise typer.Exit(1)
330
+
331
+
332
+ @app_command()
333
+ def workflow(
334
+ gene_query: str = typer.Argument(..., help="Gene name or ID to analyze"),
335
+ input_fasta: Optional[Path] = typer.Option(
336
+ None,
337
+ "--input-fasta",
338
+ help="Path to an input FASTA file to use instead of performing a gene search",
339
+ exists=True,
340
+ file_okay=True,
341
+ dir_okay=False,
342
+ ),
343
+ output_dir: Path = typer.Option(
344
+ Path("sirna_workflow_output"),
345
+ "--output-dir",
346
+ "-o",
347
+ help="Output directory for all workflow results",
348
+ ),
349
+ database: str = typer.Option(
350
+ "ensembl",
351
+ "--database",
352
+ "-d",
353
+ help="Database to search (ensembl, refseq, gencode)",
354
+ ),
355
+ top_n_candidates: int = typer.Option(
356
+ 20,
357
+ "--top-n",
358
+ "-n",
359
+ min=1,
360
+ help="Number of top siRNA candidates to select (also used for off-target analysis)",
361
+ ),
362
+ genome_species: str = typer.Option(
363
+ "human,rat,rhesus",
364
+ "--genome-species",
365
+ help="Comma-separated list of genome species for off-target analysis",
366
+ ),
367
+ gc_min: float = typer.Option(
368
+ 30.0,
369
+ "--gc-min",
370
+ min=0.0,
371
+ max=100.0,
372
+ help="Minimum GC content percentage",
373
+ ),
374
+ gc_max: float = typer.Option(
375
+ 52.0,
376
+ "--gc-max",
377
+ min=0.0,
378
+ max=100.0,
379
+ help="Maximum GC content percentage",
380
+ ),
381
+ sirna_length: int = typer.Option(
382
+ 21,
383
+ "--length",
384
+ "-l",
385
+ min=19,
386
+ max=23,
387
+ help="siRNA length in nucleotides",
388
+ ),
389
+ verbose: bool = typer.Option(
390
+ False,
391
+ "--verbose",
392
+ "-v",
393
+ help="Enable verbose output",
394
+ ),
395
+ log_file: Optional[Path] = typer.Option(
396
+ None,
397
+ "--log-file",
398
+ help="Path to centralized log file (overrides SIRNAFORGE_LOG_FILE env)",
399
+ ),
400
+ json_summary: bool = typer.Option(
401
+ True,
402
+ "--json-summary/--no-json-summary",
403
+ help="Write logs/workflow_summary.json (disable to skip JSON output)",
404
+ ),
405
+ ) -> None:
406
+ """Run complete siRNA design workflow from gene query to off-target analysis."""
407
+
408
+ if gc_min >= gc_max:
409
+ console.print("❌ Error: gc-min must be less than gc-max", style="red")
410
+ raise typer.Exit(1)
411
+
412
+ # Parse genome species
413
+ species_list = [s.strip() for s in genome_species.split(",") if s.strip()]
414
+
415
+ console.print(
416
+ Panel.fit(
417
+ f"🧬 [bold blue]Complete siRNA Workflow[/bold blue]\n"
418
+ f"Gene Query: [cyan]{gene_query if not input_fasta else input_fasta.name}[/cyan]\n"
419
+ f"Database: [yellow]{database}[/yellow]\n"
420
+ f"Output Directory: [cyan]{output_dir}[/cyan]\n"
421
+ f"siRNA Length: [yellow]{sirna_length}[/yellow] nt\n"
422
+ f"GC Range: [yellow]{gc_min:.1f}%-{gc_max:.1f}%[/yellow]\n"
423
+ f"Top Candidates (used for off-target): [yellow]{top_n_candidates}[/yellow]\n"
424
+ f"Genome Species: [green]{', '.join(species_list)}[/green]",
425
+ title="Workflow Configuration",
426
+ )
427
+ )
428
+
429
+ try:
430
+ # Run the complete workflow
431
+ with Progress(
432
+ SpinnerColumn(),
433
+ TextColumn("[progress.description]{task.description}"),
434
+ console=console,
435
+ ) as progress:
436
+ task = progress.add_task("Running complete siRNA design workflow...", total=None)
437
+
438
+ # Configure logging to file inside the output dir by default if not provided
439
+ effective_log = str(log_file) if log_file else str(Path(output_dir) / "logs" / "sirnaforge.log")
440
+ configure_logging(log_file=effective_log, level=os.getenv("SIRNAFORGE_LOG_LEVEL"))
441
+
442
+ results = asyncio.run(
443
+ run_sirna_workflow(
444
+ gene_query=gene_query,
445
+ input_fasta=str(input_fasta) if input_fasta else None,
446
+ output_dir=str(output_dir),
447
+ database=database,
448
+ top_n_candidates=top_n_candidates,
449
+ genome_species=species_list,
450
+ gc_min=gc_min,
451
+ gc_max=gc_max,
452
+ sirna_length=sirna_length,
453
+ log_file=effective_log,
454
+ write_json_summary=json_summary,
455
+ )
456
+ )
457
+
458
+ progress.remove_task(task)
459
+
460
+ # Display results summary
461
+ console.print("\n✅ [bold green]Workflow completed successfully![/bold green]")
462
+
463
+ # Workflow summary
464
+ summary_table = Table(title="📊 Workflow Results Summary")
465
+ summary_table.add_column("Phase", style="cyan")
466
+ summary_table.add_column("Status", style="green")
467
+ summary_table.add_column("Details", style="white")
468
+
469
+ results.get("workflow_config", {})
470
+ transcript_summary = results.get("transcript_summary", {})
471
+ design_summary = results.get("design_summary", {})
472
+ offtarget_summary = results.get("offtarget_summary", {})
473
+
474
+ summary_table.add_row(
475
+ "📄 Transcript Retrieval",
476
+ "✅ Complete",
477
+ f"{transcript_summary.get('total_transcripts', 0)} transcripts from {database}",
478
+ )
479
+
480
+ summary_table.add_row(
481
+ "🧬 siRNAforge", "✅ Complete", f"{design_summary.get('total_candidates', 0)} candidates generated"
482
+ )
483
+
484
+ summary_table.add_row(
485
+ "🎯 Off-target Analysis",
486
+ "✅ Complete" if offtarget_summary.get("status") == "completed" else "⚠️ Partial",
487
+ f"Method: {offtarget_summary.get('method', 'basic')}",
488
+ )
489
+
490
+ console.print(summary_table)
491
+
492
+ # Output locations
493
+ console.print(f"\n📁 [bold]Results saved to:[/bold] [cyan]{output_dir}[/cyan]")
494
+ console.print("📂 Key files:")
495
+ console.print(f" • Transcripts: [blue]transcripts/{gene_query}_transcripts.fasta[/blue]")
496
+ console.print(f" • siRNA candidates (ALL): [blue]sirnaforge/{gene_query}_all.csv[/blue]")
497
+ console.print(f" • siRNA candidates (PASS): [blue]sirnaforge/{gene_query}_pass.csv[/blue]")
498
+ console.print(" • Off-target results: [blue]off_target/results/[/blue]")
499
+ console.print(" • Console stream log: [blue]logs/workflow_stream.log[/blue]")
500
+ if json_summary:
501
+ console.print(" • Workflow summary: [blue]logs/workflow_summary.json[/blue]")
502
+
503
+ if offtarget_summary.get("method") == "nextflow":
504
+ console.print(" • Full off-target report: [blue]off_target/results/offtarget_report.html[/blue]")
505
+
506
+ except Exception as e:
507
+ console.print(f"❌ [red]Workflow error:[/red] {str(e)}")
508
+ if verbose:
509
+ console.print_exception()
510
+ raise typer.Exit(1)
511
+
512
+
513
+ @app_command()
514
+ def design(
515
+ input_file: Path = typer.Argument(
516
+ ...,
517
+ help="Input FASTA file containing transcript sequences",
518
+ exists=True,
519
+ file_okay=True,
520
+ dir_okay=False,
521
+ ),
522
+ output: Path = typer.Option(
523
+ Path("sirna_results.tsv"),
524
+ "--output",
525
+ "-o",
526
+ help="Output file for siRNA candidates",
527
+ ),
528
+ length: int = typer.Option(
529
+ 21,
530
+ "--length",
531
+ "-l",
532
+ min=19,
533
+ max=23,
534
+ help="siRNA length in nucleotides",
535
+ ),
536
+ top_n: int = typer.Option(
537
+ 10,
538
+ "--top-n",
539
+ "-n",
540
+ min=1,
541
+ help="Number of top candidates to return",
542
+ ),
543
+ gc_min: float = typer.Option(
544
+ 30.0,
545
+ "--gc-min",
546
+ min=0.0,
547
+ max=100.0,
548
+ help="Minimum GC content percentage",
549
+ ),
550
+ gc_max: float = typer.Option(
551
+ 52.0,
552
+ "--gc-max",
553
+ min=0.0,
554
+ max=100.0,
555
+ help="Maximum GC content percentage",
556
+ ),
557
+ max_poly_runs: int = typer.Option(
558
+ 3,
559
+ "--max-poly-runs",
560
+ min=1,
561
+ help="Maximum consecutive identical nucleotides",
562
+ ),
563
+ genome_index: Optional[Path] = typer.Option(
564
+ None,
565
+ "--genome-index",
566
+ help="Genome index for off-target analysis",
567
+ ),
568
+ snp_file: Optional[Path] = typer.Option(
569
+ None,
570
+ "--snp-file",
571
+ help="VCF file with SNPs to avoid",
572
+ ),
573
+ skip_structure: bool = typer.Option(
574
+ False,
575
+ "--skip-structure",
576
+ help="Skip secondary structure prediction (faster)",
577
+ ),
578
+ skip_off_targets: bool = typer.Option(
579
+ False,
580
+ "--skip-off-targets",
581
+ help="Skip off-target analysis (faster)",
582
+ ),
583
+ verbose: bool = typer.Option(
584
+ False,
585
+ "--verbose",
586
+ "-v",
587
+ help="Enable verbose output",
588
+ ),
589
+ ) -> None:
590
+ """Design siRNA candidates from transcript sequences."""
591
+
592
+ if gc_min >= gc_max:
593
+ console.print("❌ Error: gc-min must be less than gc-max", style="red")
594
+ raise typer.Exit(1)
595
+
596
+ # Create parameters
597
+ filters = FilterCriteria(
598
+ gc_min=gc_min,
599
+ gc_max=gc_max,
600
+ max_poly_runs=max_poly_runs,
601
+ )
602
+
603
+ parameters = DesignParameters(
604
+ sirna_length=length,
605
+ top_n=top_n,
606
+ filters=filters,
607
+ predict_structure=not skip_structure,
608
+ check_off_targets=not skip_off_targets,
609
+ genome_index=str(genome_index) if genome_index else None,
610
+ snp_file=str(snp_file) if snp_file else None,
611
+ )
612
+
613
+ console.print(
614
+ Panel.fit(
615
+ f"🧬 [bold blue]siRNAforge Toolkit[/bold blue]\n"
616
+ f"Input: [cyan]{input_file}[/cyan]\n"
617
+ f"Output: [cyan]{output}[/cyan]\n"
618
+ f"Length: [yellow]{length}[/yellow] nt\n"
619
+ f"GC range: [yellow]{gc_min:.1f}%-{gc_max:.1f}%[/yellow]\n"
620
+ f"Top candidates: [yellow]{top_n}[/yellow]",
621
+ title="Configuration",
622
+ )
623
+ )
624
+
625
+ try:
626
+ with Progress(
627
+ SpinnerColumn(),
628
+ TextColumn("[progress.description]{task.description}"),
629
+ console=console,
630
+ ) as progress:
631
+ # Import here to avoid slow startup
632
+
633
+ task1 = progress.add_task("Loading sequences...", total=None)
634
+ designer = SiRNADesigner(parameters)
635
+
636
+ progress.update(task1, description="Designing siRNAs...")
637
+ result = designer.design_from_file(str(input_file))
638
+
639
+ progress.update(task1, description="Saving results...")
640
+ result.save_csv(str(output))
641
+
642
+ # Display results summary
643
+ summary = result.get_summary()
644
+
645
+ table = Table(title="📊 Design Summary")
646
+ table.add_column("Metric", style="cyan")
647
+ table.add_column("Value", style="yellow")
648
+
649
+ for key, value in summary.items():
650
+ table.add_row(key.replace("_", " ").title(), str(value))
651
+
652
+ console.print(table)
653
+
654
+ if result.top_candidates:
655
+ console.print("\n🏆 [bold green]Top Candidates:[/bold green]")
656
+
657
+ candidates_table = Table()
658
+ candidates_table.add_column("ID", style="cyan")
659
+ candidates_table.add_column("Transcript", style="blue")
660
+ candidates_table.add_column("Position", style="yellow")
661
+ candidates_table.add_column("Sequence", style="green")
662
+ candidates_table.add_column("GC%", style="magenta")
663
+ candidates_table.add_column("Hits", style="white")
664
+ candidates_table.add_column("Hit %", style="white")
665
+ candidates_table.add_column("Score", style="red")
666
+
667
+ for candidate in result.top_candidates[:5]: # Show top 5
668
+ candidates_table.add_row(
669
+ candidate.id,
670
+ candidate.transcript_id,
671
+ str(candidate.position),
672
+ candidate.guide_sequence,
673
+ f"{candidate.gc_content:.1f}",
674
+ str(candidate.transcript_hit_count),
675
+ f"{candidate.transcript_hit_fraction * 100:.1f}%",
676
+ f"{candidate.composite_score:.1f}",
677
+ )
678
+
679
+ console.print(candidates_table)
680
+
681
+ console.print(f"\n✅ [green]Results saved to:[/green] {output}")
682
+
683
+ except Exception as e:
684
+ console.print(f"❌ [red]Error during design:[/red] {str(e)}")
685
+ if verbose:
686
+ console.print_exception()
687
+ raise typer.Exit(1)
688
+
689
+
690
+ @app_command()
691
+ def validate(
692
+ input_file: Path = typer.Argument(
693
+ ...,
694
+ help="FASTA file to validate",
695
+ exists=True,
696
+ file_okay=True,
697
+ dir_okay=False,
698
+ ),
699
+ ) -> None:
700
+ """Validate input FASTA file format and content."""
701
+
702
+ try:
703
+ with console.status("Validating FASTA file..."):
704
+ sequences = list(SeqIO.parse(input_file, "fasta"))
705
+
706
+ if not sequences:
707
+ console.print("❌ [red]No sequences found in FASTA file[/red]")
708
+ raise typer.Exit(1)
709
+
710
+ # Validation stats
711
+ total_seqs = len(sequences)
712
+ total_length = sum(len(seq) for seq in sequences)
713
+ min_length = min(len(seq) for seq in sequences)
714
+ max_length = max(len(seq) for seq in sequences)
715
+ avg_length = total_length / total_seqs
716
+
717
+ # Check for problematic sequences
718
+ short_seqs = [seq for seq in sequences if len(seq) < 50]
719
+ ambiguous_seqs = [seq for seq in sequences if "N" in str(seq.seq)]
720
+
721
+ table = Table(title="📋 FASTA Validation Results")
722
+ table.add_column("Metric", style="cyan")
723
+ table.add_column("Value", style="yellow")
724
+
725
+ table.add_row("Total sequences", str(total_seqs))
726
+ table.add_row("Total length", f"{total_length:,} nt")
727
+ table.add_row("Average length", f"{avg_length:.1f} nt")
728
+ table.add_row("Min length", f"{min_length} nt")
729
+ table.add_row("Max length", f"{max_length} nt")
730
+ table.add_row("Short sequences (<50 nt)", str(len(short_seqs)))
731
+ table.add_row("Ambiguous sequences (with N)", str(len(ambiguous_seqs)))
732
+
733
+ console.print(table)
734
+
735
+ if short_seqs:
736
+ console.print(f"⚠️ [yellow]{len(short_seqs)} sequences are shorter than 50 nt[/yellow]")
737
+
738
+ if ambiguous_seqs:
739
+ console.print(f"⚠️ [yellow]{len(ambiguous_seqs)} sequences contain ambiguous bases (N)[/yellow]")
740
+
741
+ console.print("✅ [green]FASTA validation complete[/green]")
742
+
743
+ except Exception as e:
744
+ console.print(f"❌ [red]Validation error:[/red] {str(e)}")
745
+ raise typer.Exit(1)
746
+
747
+
748
+ @app_command()
749
+ def version() -> None:
750
+ """Show version information."""
751
+
752
+ try:
753
+ # Prefer Docker build-time APP_VERSION when the image is built with a VERSION arg
754
+ app_version = os.environ.get("APP_VERSION") if "APP_VERSION" in os.environ else __version__
755
+ console.print(
756
+ Panel.fit(
757
+ f"🧬 [bold blue]siRNAforge Toolkit[/bold blue]\n"
758
+ f"Version: [yellow]{app_version}[/yellow]\n"
759
+ f"Author: [cyan]{__author__}[/cyan]",
760
+ title="Version Info",
761
+ )
762
+ )
763
+
764
+ except ImportError:
765
+ console.print("❌ [red]Could not determine version[/red]")
766
+ raise typer.Exit(1)
767
+
768
+
769
+ @app_command()
770
+ def config() -> None:
771
+ """Show default configuration parameters."""
772
+
773
+ default_params = DesignParameters()
774
+
775
+ console.print("[bold blue]Default Design Parameters:[/bold blue]\n")
776
+
777
+ # Basic parameters
778
+ console.print("[cyan]Basic Parameters:[/cyan]")
779
+ console.print(f" siRNA length: {default_params.sirna_length} nt")
780
+ console.print(f" Top candidates: {default_params.top_n}")
781
+
782
+ # Filtering criteria
783
+ console.print("\n[cyan]Filtering Criteria:[/cyan]")
784
+ filters = default_params.filters
785
+ console.print(f" GC content: {filters.gc_min}% - {filters.gc_max}%")
786
+ console.print(f" Max poly runs: {filters.max_poly_runs}")
787
+ console.print(f" Max paired fraction: {filters.max_paired_fraction}")
788
+
789
+ # Scoring weights
790
+ console.print("\n[cyan]Scoring Weights:[/cyan]")
791
+ scoring = default_params.scoring
792
+ console.print(f" Asymmetry: {scoring.asymmetry}")
793
+ console.print(f" GC content: {scoring.gc_content}")
794
+ console.print(f" Accessibility: {scoring.accessibility}")
795
+ console.print(f" Off-target: {scoring.off_target}")
796
+ console.print(f" Empirical: {scoring.empirical}")
797
+
798
+
799
+ @app_command()
800
+ def cache(
801
+ clear: bool = typer.Option(False, "--clear", help="Clear all cached miRNA databases"),
802
+ dry_run: bool = typer.Option(False, "--dry-run", help="Show what would be deleted without actually deleting"),
803
+ info: bool = typer.Option(False, "--info", help="Show cache information"),
804
+ ) -> None:
805
+ """Manage miRNA database cache."""
806
+ if not any([clear, dry_run, info]):
807
+ console.print("❓ [yellow]No action specified. Use --clear, --dry-run, or --info[/yellow]")
808
+ console.print(" Example: sirnaforge cache --info")
809
+ return
810
+
811
+ manager = MiRNADatabaseManager()
812
+
813
+ if info or dry_run:
814
+ cache_info = manager.cache_info()
815
+ console.print("📊 [bold blue]Cache Information:[/bold blue]")
816
+ console.print(f" Directory: [cyan]{cache_info['cache_directory']}[/cyan]")
817
+ console.print(f" Files: [green]{cache_info['total_files']}[/green]")
818
+ console.print(f" Size: [yellow]{cache_info['total_size_mb']:.2f} MB[/yellow]")
819
+ console.print(f" TTL: [magenta]{cache_info['cache_ttl_days']} days[/magenta]")
820
+
821
+ if dry_run:
822
+ result = manager.clear_cache(confirm=False)
823
+ console.print("\n🔍 [bold yellow]Clear Preview:[/bold yellow]")
824
+ console.print(f" Files to delete: [red]{result['files_deleted']}[/red]")
825
+ console.print(f" Size to free: [yellow]{result['size_freed_mb']:.2f} MB[/yellow]")
826
+ console.print(f" Status: [dim]{result['status']}[/dim]")
827
+
828
+ elif clear:
829
+ result = manager.clear_cache(confirm=True)
830
+ console.print("🧹 [bold green]Cache Cleared:[/bold green]")
831
+ console.print(f" Files deleted: [red]{result['files_deleted']}[/red]")
832
+ console.print(f" Size freed: [yellow]{result['size_freed_mb']:.2f} MB[/yellow]")
833
+ console.print(f" Status: [green]{result['status']}[/green]")
834
+
835
+
836
+ if __name__ == "__main__":
837
+ app()