Skip to content

Commit f6d522d

Browse files
munkyukim86claude
andcommitted
feat: 043 scan_rare_codon_runs() — 연속 rare codon 탐지 (ribosome stalling)
FactorForge v2 RuleEngine에 scan_rare_codon_runs() 추가. w < 0.3인 rare codon이 3개 이상 연속될 때 위반 flagging. scan_all() full 모드 포함, fast 모드 제외. pytest 380 passed. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 5770253 commit f6d522d

4 files changed

Lines changed: 224 additions & 49 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
1212
### Added
1313

1414
- Custom restriction site detection and synonymous CDS cleanup for API and web UI requests.
15+
- Rare codon run scanner in the v2 rule engine, included in full scan mode and excluded from fast scan mode.
1516

1617
---
1718

‎README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,8 @@ Protein sequence (FASTA or plain text)
5656
▼
5757
2. Rule Scan
5858
Detects PolyA signals, homopolymers,
59-
repeat sequences, forbidden restriction sites
59+
repeat sequences, rare codon runs,
60+
forbidden restriction sites
6061
│
6162
▼
6263
3. Domestication
@@ -193,7 +194,7 @@ Each optimized sequence includes:
193194
- **Optimized CDS** — synonymous codon replacements only, AA identity 100%
194195
- **CAI score** — codon adaptation index for *N. benthamiana*
195196
- **GC content** — global and first-region
196-
- **Scan report** — PolyA signals detected/fixed, homopolymers, restriction sites
197+
- **Scan report** — PolyA signals detected/fixed, homopolymers, rare codon runs, restriction sites
197198
- **Domestication report** — BsaI/BsmBI and optional custom restriction sites removed, edit count
198199
- **Construct ID** — reproducible hash for tracking
199200

‎src/factorforge/engines/v2/rules/rule_engine.py‎

Lines changed: 120 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,20 @@
55

66
from __future__ import annotations
77

8-
import json
98
import logging
109
import re
1110
from typing import Any
1211

13-
logger = logging.getLogger(__name__)
14-
12+
from factorforge.engines.v2.rules.reverse_translator import ReverseTranslator
1513
from 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

2223
class 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()
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
"""
2+
Unit tests for rare codon run scanning in RuleEngine.
3+
"""
4+
5+
import sys
6+
from pathlib import Path
7+
8+
import pytest
9+
10+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "src"))
11+
12+
from factorforge.engines.v2.rules.rule_engine import RuleEngine
13+
14+
15+
@pytest.fixture
16+
def rare_codon_table():
17+
"""Codon table where AAA is rare relative to AAG."""
18+
return {
19+
"amino_acids": {
20+
"M": {"codons": ["ATG"]},
21+
"K": {"codons": ["AAA", "AAG"]},
22+
"*": {"codons": ["TAA", "TAG", "TGA"]},
23+
},
24+
"codons": {
25+
"ATG": {"aa": "M", "frequency": 1.0},
26+
"AAA": {"aa": "K", "frequency": 0.1},
27+
"AAG": {"aa": "K", "frequency": 1.0},
28+
"TAA": {"aa": "*", "frequency": 0.34},
29+
"TAG": {"aa": "*", "frequency": 0.33},
30+
"TGA": {"aa": "*", "frequency": 0.33},
31+
},
32+
}
33+
34+
35+
@pytest.fixture
36+
def engine(rare_codon_table):
37+
"""Create RuleEngine instance with deterministic rare codon weights."""
38+
return RuleEngine(rare_codon_table)
39+
40+
41+
class TestRareCodonRuns:
42+
"""Tests for RuleEngine.scan_rare_codon_runs."""
43+
44+
def test_detects_three_codon_run(self, engine):
45+
"""Run length 3 is flagged by default."""
46+
violations = engine.scan_rare_codon_runs("ATG" + ("AAA" * 3) + "ATG")
47+
48+
assert len(violations) == 1
49+
violation = violations[0]
50+
assert violation["type"] == "rare_codon_run"
51+
assert violation["position"] == 3
52+
assert violation["codon_index"] == 1
53+
assert violation["run_length"] == 3
54+
assert violation["codons"] == ["AAA", "AAA", "AAA"]
55+
56+
def test_two_codon_run_is_below_default_threshold(self, engine):
57+
"""Run length 2 is not flagged when min_run is 3."""
58+
violations = engine.scan_rare_codon_runs("ATG" + ("AAA" * 2) + "ATG")
59+
60+
assert violations == []
61+
62+
def test_run_length_five_is_high_severity(self, engine):
63+
"""Run length 5 is high severity."""
64+
violations = engine.scan_rare_codon_runs("AAA" * 5)
65+
66+
assert len(violations) == 1
67+
assert violations[0]["run_length"] == 5
68+
assert violations[0]["severity"] == "high"
69+
70+
@pytest.mark.parametrize("run_length", [3, 4])
71+
def test_run_lengths_three_and_four_are_medium_severity(self, engine, run_length):
72+
"""Run lengths 3 and 4 are medium severity."""
73+
violations = engine.scan_rare_codon_runs("AAA" * run_length)
74+
75+
assert len(violations) == 1
76+
assert violations[0]["run_length"] == run_length
77+
assert violations[0]["severity"] == "medium"
78+
79+
def test_stop_codon_breaks_rare_codon_run(self, engine):
80+
"""Stop codons are excluded and break a rare codon run."""
81+
violations = engine.scan_rare_codon_runs(("AAA" * 2) + "TAA" + ("AAA" * 2))
82+
83+
assert violations == []
84+
85+
def test_empty_and_non_codon_length_sequences_return_empty(self, engine):
86+
"""Empty sequence and non-triplet sequence lengths return no violations."""
87+
assert engine.scan_rare_codon_runs("") == []
88+
assert engine.scan_rare_codon_runs("AAAA") == []
89+
90+
def test_scan_all_full_mode_includes_rare_codon_runs(self, engine):
91+
"""scan_all() includes rare_codon_runs in full mode."""
92+
result = engine.scan_all("ATG" * 5)
93+
94+
assert "rare_codon_runs" in result
95+
96+
def test_scan_all_fast_mode_excludes_rare_codon_runs(self, engine):
97+
"""scan_all() excludes rare_codon_runs in fast mode."""
98+
result = engine.scan_all("ATG" * 5, mode="fast")
99+
100+
assert "rare_codon_runs" not in result

0 commit comments

Comments
 (0)