55
66from __future__ import annotations
77
8- import json
98import logging
109import re
1110from typing import Any
1211
13- logger = logging .getLogger (__name__ )
14-
12+ from factorforge .engines .v2 .rules .reverse_translator import ReverseTranslator
1513from factorforge .engines .v2 .utils import (
1614 build_aa_to_codons_map ,
1715 count_dinucleotides ,
1816 get_data_path ,
17+ load_codon_table ,
1918)
2019
20+ logger = logging .getLogger (__name__ )
21+
2122
2223class RuleEngine :
2324 """
@@ -56,13 +57,13 @@ def __init__(self, codon_table: dict[str, Any] | None = None) -> None:
5657 """
5758 if codon_table is None :
5859 # Use centralized data path management
59- data_dir = get_data_path ()
60- codon_table_path = data_dir / "nbenthamiana_codons.json"
61- with open (codon_table_path , "r" , encoding = "utf-8" ) as f :
62- codon_table = json .load (f )
60+ codon_table = load_codon_table ("nbenthamiana" , get_data_path ())
6361
6462 self .codon_table : dict [str , Any ] = codon_table
6563 self .aa_to_codons : dict [str , list [str ]] = self ._build_aa_to_codons_map ()
64+ self ._rare_codon_weights : dict [str , float ] = ReverseTranslator ._build_ref_weights (
65+ self .codon_table
66+ )
6667
6768 def _build_aa_to_codons_map (self ) -> dict [str , list [str ]]:
6869 """Build amino-acid-to-codons map"""
@@ -527,9 +528,7 @@ def fix_polya_iterative(
527528 }
528529
529530 # Max rounds exhausted
530- remaining = [
531- v for v in self .scan_polya (current_seq ) if v ["type" ] == "polya_signal"
532- ]
531+ remaining = [v for v in self .scan_polya (current_seq ) if v ["type" ] == "polya_signal" ]
533532 return {
534533 "success" : len (remaining ) == 0 ,
535534 "modified_seq" : current_seq ,
@@ -580,26 +579,30 @@ def scan_dinucleotides(
580579 tpa_count = count_dinucleotides (seq_upper , "TA" )
581580 cpg_density = cpg_count / seq_len
582581 if cpg_density > cpg_threshold :
583- violations .append ({
584- "type" : "dinucleotide_hotspot" ,
585- "dinucleotide" : "CpG" ,
586- "position" : 0 ,
587- "window_size" : seq_len ,
588- "count" : cpg_count ,
589- "density" : round (cpg_density , 4 ),
590- "severity" : "high" if cpg_density > cpg_threshold * 2 else "medium" ,
591- })
582+ violations .append (
583+ {
584+ "type" : "dinucleotide_hotspot" ,
585+ "dinucleotide" : "CpG" ,
586+ "position" : 0 ,
587+ "window_size" : seq_len ,
588+ "count" : cpg_count ,
589+ "density" : round (cpg_density , 4 ),
590+ "severity" : "high" if cpg_density > cpg_threshold * 2 else "medium" ,
591+ }
592+ )
592593 tpa_density = tpa_count / seq_len
593594 if tpa_density > tpa_threshold :
594- violations .append ({
595- "type" : "dinucleotide_hotspot" ,
596- "dinucleotide" : "TpA" ,
597- "position" : 0 ,
598- "window_size" : seq_len ,
599- "count" : tpa_count ,
600- "density" : round (tpa_density , 4 ),
601- "severity" : "high" if tpa_density > tpa_threshold * 2 else "medium" ,
602- })
595+ violations .append (
596+ {
597+ "type" : "dinucleotide_hotspot" ,
598+ "dinucleotide" : "TpA" ,
599+ "position" : 0 ,
600+ "window_size" : seq_len ,
601+ "count" : tpa_count ,
602+ "density" : round (tpa_density , 4 ),
603+ "severity" : "high" if tpa_density > tpa_threshold * 2 else "medium" ,
604+ }
605+ )
603606 return violations
604607
605608 # Rolling dinucleotide counts:
@@ -621,28 +624,96 @@ def scan_dinucleotides(
621624
622625 cpg_density = cpg_count / window
623626 if cpg_density > cpg_threshold :
624- violations .append ({
625- "type" : "dinucleotide_hotspot" ,
626- "dinucleotide" : "CpG" ,
627- "position" : i ,
628- "window_size" : window ,
629- "count" : cpg_count ,
630- "density" : round (cpg_density , 4 ),
631- "severity" : "high" if cpg_density > cpg_threshold * 2 else "medium" ,
632- })
627+ violations .append (
628+ {
629+ "type" : "dinucleotide_hotspot" ,
630+ "dinucleotide" : "CpG" ,
631+ "position" : i ,
632+ "window_size" : window ,
633+ "count" : cpg_count ,
634+ "density" : round (cpg_density , 4 ),
635+ "severity" : "high" if cpg_density > cpg_threshold * 2 else "medium" ,
636+ }
637+ )
633638
634639 tpa_density = tpa_count / window
635640 if tpa_density > tpa_threshold :
636- violations .append ({
637- "type" : "dinucleotide_hotspot" ,
638- "dinucleotide" : "TpA" ,
639- "position" : i ,
640- "window_size" : window ,
641- "count" : tpa_count ,
642- "density" : round (tpa_density , 4 ),
643- "severity" : "high" if tpa_density > tpa_threshold * 2 else "medium" ,
644- })
641+ violations .append (
642+ {
643+ "type" : "dinucleotide_hotspot" ,
644+ "dinucleotide" : "TpA" ,
645+ "position" : i ,
646+ "window_size" : window ,
647+ "count" : tpa_count ,
648+ "density" : round (tpa_density , 4 ),
649+ "severity" : "high" if tpa_density > tpa_threshold * 2 else "medium" ,
650+ }
651+ )
652+
653+ return violations
654+
655+ def scan_rare_codon_runs (
656+ self ,
657+ seq : str ,
658+ min_run : int = 3 ,
659+ rarity_threshold : float = 0.3 ,
660+ ) -> list [dict [str , Any ]]:
661+ """
662+ Detect runs of consecutive rare codons (ribosome stalling risk).
663+
664+ Rare codon: relative adaptiveness w < rarity_threshold.
665+ A run of >= min_run consecutive rare codons is flagged.
666+ Reference: Tuller et al. (2010) PMC2565806; Dana & Tuller (2014) PMC4363877.
667+
668+ Args:
669+ seq: DNA coding sequence (must be divisible by 3).
670+ min_run: Minimum consecutive rare codons to flag.
671+ rarity_threshold: CAI relative adaptiveness w below which a codon is rare.
672+
673+ Returns:
674+ List of violation dicts with type, position, codon_index, run_length,
675+ codons, and severity.
676+ """
677+ if len (seq ) % 3 != 0 or min_run < 1 :
678+ return []
679+
680+ violations : list [dict [str , Any ]] = []
681+ seq_upper = seq .upper ()
682+ stop_codons = {"TAA" , "TAG" , "TGA" }
683+ current_run_start : int | None = None
684+ current_run_codons : list [str ] = []
685+
686+ def flush_run () -> None :
687+ if current_run_start is None or len (current_run_codons ) < min_run :
688+ return
689+ violations .append (
690+ {
691+ "type" : "rare_codon_run" ,
692+ "position" : current_run_start * 3 ,
693+ "codon_index" : current_run_start ,
694+ "run_length" : len (current_run_codons ),
695+ "codons" : current_run_codons .copy (),
696+ "severity" : "high" if len (current_run_codons ) >= 5 else "medium" ,
697+ }
698+ )
699+
700+ for codon_index in range (0 , len (seq_upper ), 3 ):
701+ codon = seq_upper [codon_index : codon_index + 3 ]
702+ is_rare = codon not in stop_codons and (
703+ self ._rare_codon_weights .get (codon , 0.0 ) < rarity_threshold
704+ )
705+
706+ if is_rare :
707+ if current_run_start is None :
708+ current_run_start = codon_index // 3
709+ current_run_codons .append (codon )
710+ continue
711+
712+ flush_run ()
713+ current_run_start = None
714+ current_run_codons = []
645715
716+ flush_run ()
646717 return violations
647718
648719 def scan_all (
@@ -670,7 +741,8 @@ def scan_all(
670741 "repeats": [...],
671742 "gc_extremes": [...],
672743 "splice_sites": [...],
673- "dinucleotides": [...]
744+ "dinucleotides": [...],
745+ "rare_codon_runs": [...]
674746 }
675747
676748 Raises:
@@ -691,6 +763,7 @@ def scan_all(
691763 "gc_extremes" : self .scan_gc_extremes ,
692764 "splice_sites" : self .scan_splice_sites ,
693765 "dinucleotides" : self .scan_dinucleotides ,
766+ "rare_codon_runs" : self .scan_rare_codon_runs ,
694767 }
695768
696769 mode_name = mode .lower ().strip ()
0 commit comments