66from __future__ import annotations
77
88import logging
9+ import math
910import re
1011from typing import Any
1112
@@ -652,31 +653,53 @@ def scan_dinucleotides(
652653
653654 return violations
654655
656+ def _calc_cai (self , seq : str ) -> float :
657+ """Calculate CAI from cached ref weights (geometric mean of w values)."""
658+ _stop = {"TAA" , "TAG" , "TGA" }
659+ ws = [
660+ self ._rare_codon_weights .get (seq [i : i + 3 ], 0.001 )
661+ for i in range (0 , len (seq ) - 2 , 3 )
662+ if seq [i : i + 3 ] not in _stop
663+ ]
664+ if not ws :
665+ return 0.0
666+ return math .exp (sum (math .log (w ) for w in ws ) / len (ws ))
667+
655668 def fix_dinucleotides (
656669 self ,
657670 seq : str ,
658671 max_rounds : int = 5 ,
659672 target_dinucleotides : tuple [str , ...] = ("CG" , "TA" ),
673+ mode : str = "balanced" ,
674+ cai_floor : float = 0.75 ,
675+ max_cai_drop : float | None = None ,
660676 ) -> dict [str , Any ]:
661677 """
662678 Reduce CpG and TpA dinucleotide density via greedy synonymous substitution.
663679
664- For each codon, tries synonymous alternatives and accepts the first swap that
665- reduces the count of target dinucleotides in the 4 positions directly adjacent
666- to the codon (one pair spanning the left boundary, two within the codon, one
667- spanning the right boundary). Repeats for up to max_rounds full-sequence passes.
680+ Modes:
681+ aggressive: dinucleotide reduction only; no CAI check (Job 044 behaviour).
682+ balanced: dinucleotide reduction first; rollback each pass if final CAI
683+ drops below cai_floor.
684+ cai_preserving: rollback each pass if CAI drops more than max_cai_drop
685+ below initial CAI.
668686
669687 Args:
670688 seq: DNA coding sequence (must be divisible by 3).
671689 max_rounds: Maximum number of full-sequence passes.
672690 target_dinucleotides: Dinucleotides to reduce.
691+ mode: "aggressive" | "balanced" | "cai_preserving".
692+ cai_floor: Minimum allowed final CAI (balanced mode).
693+ max_cai_drop: Maximum allowed CAI decrease from initial
694+ (cai_preserving mode).
673695
674696 Returns:
675- Dict with modified sequence , success flag, round count , initial/final
676- dinucleotide counts, and reduction percentage .
697+ Dict with modified_seq , success, rounds , initial/final counts,
698+ reduction_pct, mode, cai_before, cai_after .
677699 """
678700 seq_upper = seq .upper ()
679701 initial_count = sum (count_dinucleotides (seq_upper , di ) for di in target_dinucleotides )
702+ initial_cai = self ._calc_cai (seq_upper )
680703
681704 if len (seq ) % 3 != 0 or len (seq ) == 0 :
682705 return {
@@ -686,14 +709,24 @@ def fix_dinucleotides(
686709 "initial_count" : initial_count ,
687710 "final_count" : initial_count ,
688711 "reduction_pct" : 0.0 ,
712+ "mode" : mode ,
713+ "cai_before" : round (initial_cai , 4 ),
714+ "cai_after" : round (initial_cai , 4 ),
689715 }
690716
717+ if mode == "aggressive" :
718+ effective_floor = 0.0
719+ elif mode == "cai_preserving" :
720+ drop = max_cai_drop if max_cai_drop is not None else 0.003
721+ effective_floor = initial_cai - drop
722+ else :
723+ effective_floor = cai_floor
724+
691725 targets_set = set (target_dinucleotides )
692726 current_seq = seq_upper
693727 round_num = 0
694728
695729 def _local_count (s : str , codon_start : int ) -> int :
696- """Count target dinucleotides in the 4 positions adjacent to codon."""
697730 n = len (s ) - 1
698731 total = 0
699732 for di in range (max (0 , codon_start - 1 ), min (n , codon_start + 3 )):
@@ -703,6 +736,7 @@ def _local_count(s: str, codon_start: int) -> int:
703736
704737 for round_num in range (1 , max_rounds + 1 ):
705738 improved = False
739+ pass_start_seq = current_seq
706740
707741 for codon_idx in range (len (current_seq ) // 3 ):
708742 codon_start = codon_idx * 3
@@ -730,6 +764,11 @@ def _local_count(s: str, codon_start: int) -> int:
730764 improved = True
731765 break
732766
767+ if mode != "aggressive" and improved :
768+ if self ._calc_cai (current_seq ) < effective_floor :
769+ current_seq = pass_start_seq
770+ break
771+
733772 if not improved :
734773 break
735774
@@ -744,6 +783,9 @@ def _local_count(s: str, codon_start: int) -> int:
744783 "initial_count" : initial_count ,
745784 "final_count" : final_count ,
746785 "reduction_pct" : reduction_pct ,
786+ "mode" : mode ,
787+ "cai_before" : round (initial_cai , 4 ),
788+ "cai_after" : round (self ._calc_cai (current_seq ), 4 ),
747789 }
748790
749791 def scan_rare_codon_runs (
0 commit comments