gapms 1.3.2__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 (69) hide show
  1. gapms-1.3.2.dist-info/METADATA +92 -0
  2. gapms-1.3.2.dist-info/RECORD +69 -0
  3. gapms-1.3.2.dist-info/WHEEL +5 -0
  4. gapms-1.3.2.dist-info/entry_points.txt +3 -0
  5. gapms-1.3.2.dist-info/licenses/LICENSE +21 -0
  6. gapms-1.3.2.dist-info/licenses/THIRD_PARTY.md +21 -0
  7. gapms-1.3.2.dist-info/top_level.txt +1 -0
  8. gapms_v1/__init__.py +2 -0
  9. gapms_v1/__main__.py +2 -0
  10. gapms_v1/_genesensus/LICENSE +27 -0
  11. gapms_v1/_genesensus/VENDORED.json +53 -0
  12. gapms_v1/_genesensus/__init__.py +10 -0
  13. gapms_v1/_genesensus/__main__.py +4 -0
  14. gapms_v1/_genesensus/adaptive.py +157 -0
  15. gapms_v1/_genesensus/annotation.py +126 -0
  16. gapms_v1/_genesensus/available.py +64 -0
  17. gapms_v1/_genesensus/cli.py +149 -0
  18. gapms_v1/_genesensus/config.py +274 -0
  19. gapms_v1/_genesensus/corroborated.py +60 -0
  20. gapms_v1/_genesensus/diagnostics.py +19 -0
  21. gapms_v1/_genesensus/direct_molecular.py +29 -0
  22. gapms_v1/_genesensus/exchange.py +115 -0
  23. gapms_v1/_genesensus/exon_support.py +36 -0
  24. gapms_v1/_genesensus/genome.py +122 -0
  25. gapms_v1/_genesensus/graph.py +279 -0
  26. gapms_v1/_genesensus/graph_cache.py +175 -0
  27. gapms_v1/_genesensus/intervals.py +104 -0
  28. gapms_v1/_genesensus/isoform_guards.py +54 -0
  29. gapms_v1/_genesensus/isoforms.py +117 -0
  30. gapms_v1/_genesensus/joint.py +60 -0
  31. gapms_v1/_genesensus/loading.py +166 -0
  32. gapms_v1/_genesensus/local_molecular.py +112 -0
  33. gapms_v1/_genesensus/locus_select.py +137 -0
  34. gapms_v1/_genesensus/models.py +93 -0
  35. gapms_v1/_genesensus/molecular.py +222 -0
  36. gapms_v1/_genesensus/molecular_exchange.py +60 -0
  37. gapms_v1/_genesensus/molecular_state_utility.py +104 -0
  38. gapms_v1/_genesensus/molecular_strategy.py +83 -0
  39. gapms_v1/_genesensus/normalization.py +71 -0
  40. gapms_v1/_genesensus/orf_diagnostics.py +55 -0
  41. gapms_v1/_genesensus/peptide_context.py +167 -0
  42. gapms_v1/_genesensus/peptides.py +150 -0
  43. gapms_v1/_genesensus/pipeline.py +596 -0
  44. gapms_v1/_genesensus/provenance.py +54 -0
  45. gapms_v1/_genesensus/rna.py +175 -0
  46. gapms_v1/_genesensus/rna_geometry.py +114 -0
  47. gapms_v1/_genesensus/scoped.py +17 -0
  48. gapms_v1/_genesensus/scoring.py +46 -0
  49. gapms_v1/_genesensus/selection.py +336 -0
  50. gapms_v1/_genesensus/source_splice.py +19 -0
  51. gapms_v1/_genesensus/splice_prior.py +100 -0
  52. gapms_v1/_genesensus/state_utility.py +96 -0
  53. gapms_v1/_genesensus/support.py +189 -0
  54. gapms_v1/assessment.py +274 -0
  55. gapms_v1/classification.py +117 -0
  56. gapms_v1/cli.py +74 -0
  57. gapms_v1/common.py +67 -0
  58. gapms_v1/confidence_features.py +129 -0
  59. gapms_v1/consensus_engine.py +201 -0
  60. gapms_v1/mapping.py +144 -0
  61. gapms_v1/models.py +169 -0
  62. gapms_v1/orf_projection.py +249 -0
  63. gapms_v1/outputs.py +287 -0
  64. gapms_v1/peptides.py +54 -0
  65. gapms_v1/protein_mapper.py +125 -0
  66. gapms_v1/refinement.py +245 -0
  67. gapms_v1/report_figure.py +62 -0
  68. gapms_v1/rnaseq.py +91 -0
  69. gapms_v1/workflow.py +256 -0
@@ -0,0 +1,175 @@
1
+ """Optional RNA-seq junction adapter. No alignment or gene inference subprocesses."""
2
+
3
+ from collections import Counter, defaultdict
4
+ from concurrent.futures import ProcessPoolExecutor
5
+ from pathlib import Path
6
+ import json
7
+
8
+
9
+ def alignment_index(bam, lengths):
10
+ """Select CSI explicitly; automatic BAI preference can truncate long contigs."""
11
+ bam = Path(bam)
12
+ csi = [Path(str(bam) + '.csi'), bam.with_suffix('.csi')]
13
+ bai = [Path(str(bam) + '.bai'), bam.with_suffix('.bai')]
14
+ for index in csi:
15
+ if index.is_file():
16
+ return str(index)
17
+ if any(length > 2**29 for length in lengths.values()):
18
+ raise ValueError(
19
+ 'RNA BAM with contigs longer than 2^29 bases requires a CSI index; '
20
+ 'BAI retrieval may silently omit alignments. Create a CSI index '
21
+ '(samtools index -c reads.bam), or supply a validated junction JSON.'
22
+ )
23
+ for index in bai:
24
+ if index.is_file():
25
+ return str(index)
26
+ raise ValueError('RNA BAM index is missing; indexed BAM or junction JSON required')
27
+
28
+
29
+ def transcript_strand(read, library):
30
+ if library == "unstranded":
31
+ return "."
32
+ if library not in ("firststrand", "secondstrand"):
33
+ raise ValueError("Unknown RNA library strandedness")
34
+ same = library == "secondstrand"
35
+ if read.is_paired and read.is_read2:
36
+ same = not same
37
+ reverse = read.is_reverse if same else not read.is_reverse
38
+ return "-" if reverse else "+"
39
+
40
+
41
+ def _extract_contig(args):
42
+ import pysam
43
+
44
+ bam, contig, settings, index = args
45
+ counts = defaultdict(set)
46
+ stats = Counter()
47
+ with pysam.AlignmentFile(bam, "rb", index_filename=index) as reader:
48
+ for read in reader.fetch(contig):
49
+ stats["records"] += 1
50
+ if (
51
+ read.is_unmapped
52
+ or read.is_secondary
53
+ or read.is_supplementary
54
+ or read.is_qcfail
55
+ ):
56
+ stats["filtered_flags"] += 1
57
+ continue
58
+ if settings["skip_duplicates"] and read.is_duplicate:
59
+ stats["filtered_duplicates"] += 1
60
+ continue
61
+ nh = read.get_tag("NH") if read.has_tag("NH") else None
62
+ if nh is not None and nh != 1:
63
+ stats["filtered_multimappers"] += 1
64
+ continue
65
+ if read.mapping_quality == 255:
66
+ if nh != 1:
67
+ stats["filtered_unknown_mapq"] += 1
68
+ continue
69
+ elif read.mapping_quality < settings["min_mapq"]:
70
+ stats["filtered_mapq"] += 1
71
+ continue
72
+ cigar = read.cigartuples or []
73
+ pos = read.reference_start
74
+ strand = transcript_strand(read, settings["library"])
75
+ rg = read.get_tag("RG") if read.has_tag("RG") else ""
76
+ for i, (op, n) in enumerate(cigar):
77
+ if op == 3:
78
+ left = (
79
+ cigar[i - 1][1] if i > 0 and cigar[i - 1][0] in (0, 7, 8) else 0
80
+ )
81
+ right = (
82
+ cigar[i + 1][1]
83
+ if i + 1 < len(cigar) and cigar[i + 1][0] in (0, 7, 8)
84
+ else 0
85
+ )
86
+ if (
87
+ settings["min_intron"] <= n <= settings["max_intron"]
88
+ and min(left, right) >= settings["min_overhang"]
89
+ ):
90
+ counts[pos, pos + n, strand].add((rg, read.query_name))
91
+ else:
92
+ stats["filtered_junction_geometry"] += 1
93
+ if op in (0, 2, 3, 7, 8):
94
+ pos += n
95
+ stats["accepted_records"] += 1
96
+ return (
97
+ contig,
98
+ [
99
+ (a, b, strand, len(names))
100
+ for (a, b, strand), names in sorted(counts.items())
101
+ ],
102
+ dict(stats),
103
+ )
104
+
105
+
106
+ def extract_junctions(
107
+ bam,
108
+ genome_lengths,
109
+ threads=1,
110
+ min_mapq=20,
111
+ min_overhang=8,
112
+ min_intron=20,
113
+ max_intron=500000,
114
+ library="unstranded",
115
+ skip_duplicates=True,
116
+ ):
117
+ try:
118
+ import pysam
119
+ except ImportError as exc:
120
+ raise RuntimeError("RNA evidence requires pip install genesensus[rna]") from exc
121
+ if (
122
+ threads < 1
123
+ or min_mapq < 0
124
+ or min_overhang < 1
125
+ or not 1 <= min_intron <= max_intron
126
+ ):
127
+ raise ValueError("Invalid RNA extraction thresholds")
128
+ if library not in ("unstranded", "firststrand", "secondstrand"):
129
+ raise ValueError("Invalid RNA library mode")
130
+ with pysam.AlignmentFile(str(bam), "rb") as reader:
131
+ lengths = dict(zip(reader.references, reader.lengths))
132
+ bad = {
133
+ name: (length, genome_lengths.get(name))
134
+ for name, length in lengths.items()
135
+ if genome_lengths.get(name) != length
136
+ }
137
+ if bad:
138
+ raise ValueError(
139
+ "BAM/genome reference mismatch: " + repr(list(bad.items())[:10])
140
+ )
141
+ index = alignment_index(bam, lengths)
142
+ with pysam.AlignmentFile(str(bam), "rb", index_filename=index) as reader:
143
+ if not reader.has_index():
144
+ raise ValueError("RNA BAM must have a readable index")
145
+ settings = dict(
146
+ min_mapq=min_mapq,
147
+ min_overhang=min_overhang,
148
+ min_intron=min_intron,
149
+ max_intron=max_intron,
150
+ library=library,
151
+ skip_duplicates=skip_duplicates,
152
+ )
153
+ args = [(str(bam), c, settings, index) for c in sorted(lengths)]
154
+ if threads == 1:
155
+ results = list(map(_extract_contig, args))
156
+ else:
157
+ with ProcessPoolExecutor(max_workers=threads) as executor:
158
+ results = list(executor.map(_extract_contig, args))
159
+ return dict(
160
+ format_version=1,
161
+ coordinate_system="0-based-half-open",
162
+ index_kind="CSI" if index.endswith('.csi') else "BAI",
163
+ settings=settings,
164
+ junctions=[
165
+ [chrom, a, b, s, n] for chrom, rows, stats in results for a, b, s, n in rows
166
+ ],
167
+ stats=dict(sum((Counter(stats) for c, rows, stats in results), Counter())),
168
+ references=lengths,
169
+ )
170
+
171
+
172
+ def write_junctions(data, path):
173
+ Path(path).write_text(
174
+ json.dumps(data, sort_keys=True, separators=(",", ":")) + "\n"
175
+ )
@@ -0,0 +1,114 @@
1
+ """Native observed RNA-chain geometry; references here are genomic DNA only.
2
+
3
+ Caller owns input fingerprints and cache publication. This adapter preserves the
4
+ junction template counts from extract_junctions and adds unique-chain geometry.
5
+ """
6
+ from collections import Counter,defaultdict
7
+ from concurrent.futures import ProcessPoolExecutor
8
+ from .rna import alignment_index,transcript_strand
9
+ from .genome import Genome
10
+
11
+ _GENOME=None
12
+
13
+ def _initialize(path,index):
14
+ global _GENOME
15
+ _GENOME=Genome.from_index(path,index)
16
+
17
+ def fragments(start,cigar,settings):
18
+ pos=left=start;blocks=[];valid=[]
19
+ for i,(op,n) in enumerate(cigar):
20
+ if op==3:
21
+ blocks.append((left,pos))
22
+ before=cigar[i-1][1] if i and cigar[i-1][0] in (0,7,8) else 0
23
+ after=cigar[i+1][1] if i+1<len(cigar) and cigar[i+1][0] in (0,7,8) else 0
24
+ valid.append(settings['min_intron']<=n<=settings['max_intron'] and min(before,after)>=settings['min_overhang'])
25
+ pos+=n;left=pos
26
+ elif op in (0,2,7,8):
27
+ pos+=n
28
+ blocks.append((left,pos));run=[blocks[0]];answer=[]
29
+ for ok,block in zip(valid,blocks[1:]):
30
+ if ok:
31
+ run.append(block)
32
+ else:
33
+ if len(run)>1:answer.append(tuple(run))
34
+ run=[block]
35
+ if len(run)>1:answer.append(tuple(run))
36
+ return answer
37
+
38
+ def _accepted(read,settings):
39
+ if read.is_unmapped or read.is_secondary or read.is_supplementary or read.is_qcfail:return False
40
+ if settings['skip_duplicates'] and read.is_duplicate:return False
41
+ nh=read.get_tag('NH') if read.has_tag('NH') else None
42
+ if nh is not None and nh!=1:return False
43
+ if read.mapping_quality==255:return nh==1
44
+ return read.mapping_quality>=settings['min_mapq']
45
+
46
+ def _orientations(read,chrom,blocks,settings,genome):
47
+ strand=transcript_strand(read,settings['library'])
48
+ if strand!='.':return [strand]
49
+ xs=read.get_tag('XS') if read.has_tag('XS') else None
50
+ if xs in ('+','-'):return [xs]
51
+ votes=set()
52
+ for left,right in zip(blocks,blocks[1:]):
53
+ motif=(genome.fetch(chrom,left[1],left[1]+2).upper(),genome.fetch(chrom,right[0]-2,right[0]).upper())
54
+ if motif in {('GT','AG'),('GC','AG'),('AT','AC')}:votes.add('+')
55
+ elif motif in {('CT','AC'),('CT','GC'),('GT','AT')}:votes.add('-')
56
+ return sorted(votes) if len(votes)==1 else ['+','-']
57
+
58
+ def _work(args,genome=None):
59
+ import pysam
60
+ bam,chrom,settings,index,prior,minimum=args
61
+ genome=genome if genome is not None else _GENOME
62
+ junctions=Counter();exons=Counter();all_exons=Counter();observed=set();seen=set();stats=Counter()
63
+ def templates(a,b,strand):return max(prior.get((a,b,strand),0),prior.get((a,b,'.'),0))
64
+ with pysam.AlignmentFile(str(bam),'rb',index_filename=index) as reader:
65
+ for read in reader.fetch(chrom):
66
+ stats['records']+=1
67
+ if not _accepted(read,settings):continue
68
+ for chain in fragments(read.reference_start,read.cigartuples or [],settings):
69
+ # Unstranded compatibility preserves the same collapse convention
70
+ # as the matched control. Known-strand libraries retain strand.
71
+ strand=transcript_strand(read,settings['library'])
72
+ key=chain if strand=='.' else (strand,chain)
73
+ if key in seen:continue
74
+ seen.add(key);stats['unique_geometry_chains']+=1
75
+ introns=[(left[1],right[0]) for left,right in zip(chain,chain[1:])]
76
+ observed.update(introns)
77
+ for orient in _orientations(read,chrom,chain,settings,genome):
78
+ stats['emitted_alignment_chains']+=1
79
+ for a,b in introns:junctions[a,b,orient]+=1
80
+ for i,(a,b) in enumerate(chain[1:-1],1):
81
+ all_exons[a,b,orient]+=1
82
+ if templates(*introns[i-1],orient)>=minimum and templates(*introns[i],orient)>=minimum:
83
+ exons[a,b,orient]+=1
84
+ assert observed=={(a,b) for a,b,s in prior},('RNA geometry differs from junction extraction',chrom)
85
+ return chrom,junctions,exons,all_exons,dict(stats)
86
+
87
+ def augment_geometry(bam,genome,prior,threads=1,minimum_templates=3):
88
+ """Add structure counts in a second indexed pass; never assemble transcripts.
89
+
90
+ `genome` is an opened genesensus.genome.Genome. `prior` is the immutable
91
+ output of extract_junctions. Counts represent distinct genomic chain
92
+ geometries, not independent templates; original template counts are kept.
93
+ """
94
+ if isinstance(threads,bool) or not isinstance(threads,int) or threads<1:raise ValueError('threads must be a positive integer')
95
+ if isinstance(minimum_templates,bool) or not isinstance(minimum_templates,int) or minimum_templates<1:raise ValueError('minimum_templates must be a positive integer')
96
+ if prior.get('format_version')!=1 or prior.get('coordinate_system')!='0-based-half-open':raise ValueError('Invalid RNA junction cache format')
97
+ lengths=prior['references']
98
+ if not all(genome.lengths.get(c)==n for c,n in lengths.items()):raise ValueError('RNA/genome reference mismatch')
99
+ settings=dict(prior['settings']);index=alignment_index(bam,lengths);local=defaultdict(dict)
100
+ for chrom,a,b,strand,n in prior['junctions']:
101
+ key=(a,b,strand);local[chrom][key]=max(local[chrom].get(key,0),n)
102
+ args=[(str(bam),c,settings,index,local[c],minimum_templates) for c in sorted(lengths)]
103
+ if threads==1:
104
+ results=[_work(arg,genome) for arg in args]
105
+ else:
106
+ with ProcessPoolExecutor(max_workers=threads,initializer=_initialize,initargs=(str(genome.path),genome.index)) as executor:
107
+ results=list(executor.map(_work,args))
108
+ data=dict(prior)
109
+ data['rna_chain_junctions']=[[chrom,a,b,strand,n] for chrom,junctions,exons,all_exons,stats in results for (a,b,strand),n in sorted(junctions.items())]
110
+ data['observed_internal_exon_counts']=[[chrom,a,b,strand,n] for chrom,junctions,exons,all_exons,stats in results for (a,b,strand),n in sorted(exons.items())]
111
+ data['observed_internal_exon_counts_all']=[[chrom,a,b,strand,n] for chrom,junctions,exons,all_exons,stats in results for (a,b,strand),n in sorted(all_exons.items())]
112
+ data['observed_internal_exons']=[row[:-1] for row in data['observed_internal_exon_counts']]
113
+ data['alignment_geometry_provenance']=dict(method='native indexed observed-chain extraction',reference_annotations_used=False,transcript_assembly=False,junction_geometry_unchanged=True,internal_exon_min_templates=minimum_templates,unfiltered_exon_count_policy='All retained observed internal exon geometries, scoring source-exact exons only; not discovery',depth_policy='One vote per unique genomic chain geometry; template counts unchanged',source_bam=str(bam),stats=dict(sum((Counter(stats) for c,j,e,all_e,stats in results),Counter())))
114
+ return data
@@ -0,0 +1,17 @@
1
+ """Context-dependent local conflict decisions; compatibility admissions/fallback.
2
+
3
+ No empirical distinction: retain the existing molecular/consensus decision.
4
+ Local peptide, RNA or alignment observations: apply coverage-aware local guards.
5
+ No source is chosen by peptide counts or canonical-ORF fractions.
6
+ """
7
+ from .adaptive import compare_adaptive
8
+ from .selection import compare
9
+
10
+ def compare_scoped(c,old,peptides,support,chains,votes,n_sources,p):
11
+ local=compare_adaptive(c,old,peptides,support,chains,votes,n_sources,p)
12
+ if any(k in local['channels'] for k in ('peptide','rna','protein')):
13
+ local['decision_mode']='local_empirical'
14
+ return local
15
+ result=compare(c,old,peptides,support,chains,votes,n_sources,p)
16
+ result.update(policy='scoped',decision_mode='compatibility_without_local_empirical')
17
+ return result
@@ -0,0 +1,46 @@
1
+ """Vectorized CPU aggregation and experimental, hardware-unvalidated CUDA scoring."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def weighted_scores(values, available, weights, backend="cpu"):
7
+ v = np.asarray(values, dtype=np.float64)
8
+ mask = np.asarray(available, dtype=bool)
9
+ w = np.asarray(weights, dtype=np.float64)
10
+ if v.ndim != 2 or v.shape != mask.shape or w.shape != (v.shape[1],):
11
+ raise ValueError("Incompatible score matrix shapes")
12
+ if (
13
+ not np.all(np.isfinite(v))
14
+ or np.any(v < 0)
15
+ or np.any(v > 1)
16
+ or not np.all(np.isfinite(w))
17
+ or np.any(w < 0)
18
+ ):
19
+ raise ValueError("Scores must be in [0,1] and weights finite/nonnegative")
20
+ if backend not in ("cpu", "auto", "cuda"):
21
+ raise ValueError("Backend must be cpu, auto or cuda")
22
+ # Sparse graph/search work is CPU-bound. Auto stays CPU until profiling proves otherwise.
23
+ if backend in ("cpu", "auto"):
24
+ active = mask * w
25
+ den = active.sum(axis=1)
26
+ return np.divide(
27
+ (v * active).sum(axis=1), den, out=np.zeros(len(v)), where=den > 0
28
+ )
29
+ try:
30
+ import torch
31
+ except ImportError as exc:
32
+ raise RuntimeError("CUDA scoring requires genesensus[gpu]") from exc
33
+ if not torch.cuda.is_available():
34
+ raise RuntimeError("CUDA was requested but no CUDA device is available")
35
+ with torch.inference_mode():
36
+ x = torch.as_tensor(v, device="cuda", dtype=torch.float64)
37
+ a = torch.as_tensor(mask, device="cuda") * torch.as_tensor(
38
+ w, device="cuda", dtype=torch.float64
39
+ )
40
+ den = a.sum(1)
41
+ result = torch.where(
42
+ den > 0,
43
+ (x * a).sum(1) / den.clamp_min(1e-300),
44
+ torch.zeros(len(v), device="cuda", dtype=torch.float64),
45
+ )
46
+ return result.cpu().numpy()
@@ -0,0 +1,336 @@
1
+ """Deterministic RF2-style conservative additions and local guarded replacements."""
2
+
3
+ from collections import defaultdict
4
+ import statistics
5
+ import numpy as np
6
+ from .intervals import CodingIndex, disputed, overlap, intersection_length
7
+ from .molecular import local_risk
8
+ from .scoring import weighted_scores
9
+
10
+ DEFAULTS = dict(
11
+ isoform_policy="event_guarded",
12
+ isoform_score_gate=0.437721461,
13
+ selection_policy="state_molecular_guided",
14
+ molecular_strategy="source_context",
15
+ peptide_strategy="legacy",
16
+ minimum_coding_nt=150,
17
+ minimum_intron_nt=20,
18
+ predictor_weight=1.0,
19
+ confidence_gate=None,
20
+ compress_diagnostics=False,
21
+ risk_strength=0.25,
22
+ q_advantage=0.1,
23
+ risk_advantage=0.2,
24
+ replacement_margin=0.1,
25
+ minimum_retained_fraction=0.9,
26
+ boundary_window_nt=9,
27
+ localizer_gate=None,
28
+ molecular_weight=1.0,
29
+ peptide_weight=1.0,
30
+ rna_weight=1.0,
31
+ protein_weight=0.5,
32
+ structure_weight=0.25,
33
+ peptide_saturation=2.0,
34
+ addition_q=0.437721461,
35
+ minimum_rna_templates=3,
36
+ graph=True,
37
+ graph_beam=8,
38
+ graph_candidates=32,
39
+ graph_max_nodes=2000,
40
+ graph_max_starts=32,
41
+ threads=1,
42
+ backend="cpu",
43
+ )
44
+
45
+
46
+ def chain_key(m):
47
+ return (m.contig, m.strand, m.introns if m.introns else ("single", m.cds))
48
+
49
+
50
+ def predictor_support(candidates):
51
+ chains = defaultdict(set)
52
+ introns = defaultdict(set)
53
+ exons = defaultdict(set)
54
+ for c in candidates:
55
+ m = c.model
56
+ chains[chain_key(m)].update(c.sources)
57
+ for a, b in m.introns:
58
+ introns[m.contig, m.strand, a, b].update(c.sources)
59
+ for a, b in m.cds:
60
+ exons[m.contig, m.strand, a, b].update(c.sources)
61
+ return (
62
+ chains,
63
+ {k: len(v) for k, v in introns.items()},
64
+ {k: len(v) for k, v in exons.items()},
65
+ )
66
+
67
+
68
+ def choose_backbone(candidates, source_models, chains, parameters):
69
+ bykey = {c.model.key: c for c in candidates}
70
+ rank = []
71
+ report = {}
72
+ for source, models in sorted(source_models.items()):
73
+ cc = [bykey[m.key] for m in models]
74
+ quality = [c.q for c in cc if c.q is not None]
75
+ fraction = len(quality) / len(cc)
76
+ agreement = statistics.mean(
77
+ len(chains[chain_key(c.model)]) / len(source_models) for c in cc
78
+ )
79
+ report[source] = dict(
80
+ models=len(models),
81
+ q_coverage=fraction,
82
+ median_q=statistics.median(quality) if quality else None,
83
+ mean_chain_agreement=agreement,
84
+ )
85
+ use_molecular = all(v["q_coverage"] >= 0.95 for v in report.values())
86
+ for source, data in report.items():
87
+ value = data["median_q"] if use_molecular else data["mean_chain_agreement"]
88
+ rank.append((-value, source))
89
+ selected = min(rank)[1]
90
+ return selected, dict(
91
+ policy="median_gene_score" if use_molecular else "mean_chain_agreement",
92
+ sources=report,
93
+ selected=selected,
94
+ )
95
+
96
+
97
+ def _structure(c, n_sources, chains):
98
+ return (
99
+ 0.5 * len(chains.get(chain_key(c.model), ())) / max(1, n_sources)
100
+ + 0.25 * int(c.complete)
101
+ + 0.25 * int(c.canonical)
102
+ )
103
+
104
+
105
+ def _peptide_pair(c, old, peptides, regions, saturation):
106
+ new_only = {
107
+ s for s in c.peptides - old.peptides if overlap(peptides[s].blocks, regions)
108
+ }
109
+ old_only = {
110
+ s for s in old.peptides - c.peptides if overlap(peptides[s].blocks, regions)
111
+ }
112
+ return (
113
+ len(new_only) / (len(new_only) + saturation),
114
+ len(old_only) / (len(old_only) + saturation),
115
+ sorted(new_only),
116
+ sorted(old_only),
117
+ )
118
+
119
+
120
+ def _rna_pair(c, old, support):
121
+ ni = set(c.model.introns) - set(old.model.introns)
122
+ oi = set(old.model.introns) - set(c.model.introns)
123
+ return support.rna_score(c.model, ni), support.rna_score(old.model, oi)
124
+
125
+
126
+ def compare(c, old, peptides, support, chains, ivotes, n_sources, p):
127
+ m, o = c.model, old.model
128
+ reasons = []
129
+ if not (c.complete and c.canonical):
130
+ reasons.append("incomplete_or_noncanonical")
131
+ if m.length < p["minimum_retained_fraction"] * o.length:
132
+ reasons.append("truncation")
133
+ regions = disputed(m, o, p["boundary_window_nt"])
134
+ nr, nk = local_risk(c, regions, p["localizer_gate"])
135
+ oldr, ok = local_risk(old, regions, p["localizer_gate"])
136
+ qknown = c.q is not None and old.q is not None
137
+ if qknown:
138
+ mn = c.q * (1 - p["risk_strength"] * (nr if nk else 0))
139
+ mo = old.q * (1 - p["risk_strength"] * (oldr if ok else 0))
140
+ elif nk and ok:
141
+ mn = 1 - p["risk_strength"] * nr
142
+ mo = 1 - p["risk_strength"] * oldr
143
+ else:
144
+ mn = mo = 0.0
145
+ pn, po, newpeps, oldpeps = _peptide_pair(
146
+ c, old, peptides, regions, p["peptide_saturation"]
147
+ )
148
+ rn, ro = _rna_pair(c, old, support)
149
+ # Compare protein evidence only over portions of each CDS in the dispute.
150
+ cr = tuple(
151
+ (max(a, x), min(b, y))
152
+ for a, b in m.cds
153
+ for x, y in regions
154
+ if max(a, x) < min(b, y)
155
+ )
156
+ orr = tuple(
157
+ (max(a, x), min(b, y))
158
+ for a, b in o.cds
159
+ for x, y in regions
160
+ if max(a, x) < min(b, y)
161
+ )
162
+ an, ao = support.protein_score(m, cr), support.protein_score(o, orr)
163
+ sn, so = _structure(c, n_sources, chains), _structure(old, n_sources, chains)
164
+ active = [
165
+ qknown or (nk and ok),
166
+ bool(newpeps or oldpeps),
167
+ max(rn, ro) > 0 and abs(rn - ro) > 1e-12,
168
+ max(an, ao) > 0 and abs(an - ao) > 1e-12,
169
+ abs(sn - so) > 1e-12,
170
+ ]
171
+ weights = [
172
+ p["molecular_weight"],
173
+ p["peptide_weight"],
174
+ p["rna_weight"],
175
+ p["protein_weight"],
176
+ p["structure_weight"],
177
+ ]
178
+ qadv = qknown and c.q - old.q >= p["q_advantage"]
179
+ radv = nk and ok and oldr - nr >= p["risk_advantage"]
180
+ new_introns = set(m.introns) - set(o.introns)
181
+ supported = all(support.supported_junction(m, iv, ivotes) for iv in new_introns)
182
+ if c.graph_path and not supported:
183
+ reasons.append("unsupported_new_junction")
184
+ structural_advantage = (
185
+ c.complete
186
+ and not old.complete
187
+ and supported
188
+ and len(chains.get(chain_key(m), ())) >= 2
189
+ )
190
+ advantage = (
191
+ qadv
192
+ or (radv and not c.graph_path)
193
+ or pn > po
194
+ or rn > ro
195
+ or an >= ao + 0.1
196
+ or structural_advantage
197
+ )
198
+ if not advantage:
199
+ reasons.append("insufficient_distinguishing_evidence")
200
+ if nk and ok and nr > oldr + p["risk_advantage"]:
201
+ reasons.append("local_risk_regression")
202
+ values = np.array([[mn, pn, rn, an, sn], [mo, po, ro, ao, so]], dtype=np.float64)
203
+ scores = weighted_scores(values, [active, active], weights, backend="cpu")
204
+ margin = (scores[0] - scores[1]) / max(scores[1], 1e-9)
205
+ if margin <= p["replacement_margin"] + 1e-12:
206
+ reasons.append("margin")
207
+ return dict(
208
+ candidate=c.uid,
209
+ incumbents=[old.uid],
210
+ accepted=not reasons,
211
+ reasons=reasons,
212
+ molecular_measured_both=qknown,
213
+ residue_known_both=nk and ok,
214
+ q_gain=c.q - old.q if qknown else None,
215
+ new_disputed_risk=nr,
216
+ old_disputed_risk=oldr,
217
+ new_unique_peptides=newpeps,
218
+ old_unique_peptides=oldpeps,
219
+ active_channels=active,
220
+ channel_order=["molecular", "peptide", "rna", "protein", "structure"],
221
+ weights=weights,
222
+ new_values=values[0].tolist(),
223
+ old_values=values[1].tolist(),
224
+ weighted_delta=[
225
+ float(w * (a - b)) if on else 0.0
226
+ for a, b, w, on in zip(values[0], values[1], weights, active)
227
+ ],
228
+ new_score=float(scores[0]),
229
+ old_score=float(scores[1]),
230
+ relative_margin=float(margin),
231
+ graph_candidate=c.graph_path,
232
+ disputed_intervals=regions,
233
+ new_junctions_supported=supported,
234
+ )
235
+
236
+
237
+ def select(candidates, source_models, peptides, support, p, _comparison=None, molecular_factory=None):
238
+ if p.get("selection_policy") in ("locus_coverage", "locus_gene", "state_signed", "state_ratio", "state_rna_counts", "state_rna_log", "state_gap", "state_gap_soft", "state_admitted", "state_coherent", "state_soft_admitted", "state_splice_validated", "state_rna_corroborated", "state_molecular_guided") and _comparison is None:
239
+ from .locus_select import select_locus
240
+ return select_locus(candidates, source_models, peptides, support, p, molecular_factory=molecular_factory)
241
+ if p.get("selection_policy") in ("available_exchange", "available_tiered") and _comparison is None:
242
+ from .available import select_available
243
+ return select_available(candidates, source_models, peptides, support, p)
244
+ if p.get("selection_policy") in ("joint_exchange", "joint_tiered") and _comparison is None:
245
+ from .joint import select_joint
246
+ return select_joint(candidates, source_models, peptides, support, p)
247
+ if p.get("selection_policy") in ("molecular_exchange", "molecular_tiered") and _comparison is None:
248
+ from .molecular_exchange import select_molecular
249
+ return select_molecular(candidates, source_models, peptides, support, p)
250
+ if p.get("selection_policy") in ("corroborated_exchange", "corroborated_tiered") and _comparison is None:
251
+ from .corroborated import select_corroborated
252
+ return select_corroborated(candidates, source_models, peptides, support, p)
253
+ if p.get("selection_policy") == "local_exchange" and _comparison is None:
254
+ from .exchange import select_exchange
255
+ return select_exchange(candidates, source_models, peptides, support, p)
256
+ if p.get("selection_policy", "legacy") == "scoped" and _comparison is None:
257
+ from .scoped import compare_scoped
258
+ return select(candidates, source_models, peptides, support, p, _comparison=compare_scoped)
259
+ if p.get("selection_policy", "legacy") != "legacy" and _comparison is None:
260
+ from .adaptive import select_adaptive
261
+ return select_adaptive(candidates, source_models, peptides, support, p)
262
+ chains, ivotes, evotes = predictor_support(candidates)
263
+ source, source_report = choose_backbone(candidates, source_models, chains, p)
264
+ lookup = {c.model.key: c for c in candidates}
265
+ index = CodingIndex()
266
+ events = []
267
+ for m in source_models[source]:
268
+ index.add(lookup[m.key])
269
+ ordered = sorted(
270
+ candidates,
271
+ key=lambda c: (
272
+ c.q is None,
273
+ -(c.q if c.q is not None else 0.0),
274
+ -c.graph_evidence.get("global_evidence_score", 0.0),
275
+ -_structure(c, len(source_models), chains),
276
+ c.uid,
277
+ ),
278
+ )
279
+ for c in ordered:
280
+ if c.uid in index.items:
281
+ continue
282
+ olds = index.conflicts(c)
283
+ m = c.model
284
+ if not olds:
285
+ reasons = []
286
+ if not (c.complete and c.canonical):
287
+ reasons.append("incomplete_or_noncanonical")
288
+ consensus = len(chains.get(chain_key(m), ())) >= 2
289
+ empirical = (
290
+ len(c.peptides) >= 2
291
+ or (bool(m.introns) and support.rna_score(m) >= 0.5)
292
+ or support.protein_score(m) >= 0.8
293
+ )
294
+ independent_exons = any(
295
+ evotes.get((m.contig, m.strand, a, b), 0) >= 2 for a, b in m.cds
296
+ )
297
+ molecular_private = (
298
+ c.q is not None and c.q >= p["addition_q"] and independent_exons
299
+ )
300
+ if not (consensus or empirical or molecular_private):
301
+ reasons.append("unsupported_addition")
302
+ e = dict(
303
+ event="addition",
304
+ candidate=c.uid,
305
+ incumbents=[],
306
+ accepted=not reasons,
307
+ reasons=reasons,
308
+ consensus=consensus,
309
+ empirical=empirical,
310
+ molecular_private=molecular_private,
311
+ graph_candidate=c.graph_path,
312
+ )
313
+ events.append(e)
314
+ if not reasons:
315
+ index.add(c)
316
+ elif len(olds) > 1:
317
+ events.append(
318
+ dict(
319
+ event="replacement",
320
+ candidate=c.uid,
321
+ incumbents=[o.uid for o in olds],
322
+ accepted=False,
323
+ reasons=["fusion_or_multiple_incumbents"],
324
+ graph_candidate=c.graph_path,
325
+ )
326
+ )
327
+ else:
328
+ e = (_comparison or compare)(
329
+ c, olds[0], peptides, support, chains, ivotes, len(source_models), p
330
+ )
331
+ e["event"] = "replacement"
332
+ events.append(e)
333
+ if e["accepted"]:
334
+ index.remove(olds[0])
335
+ index.add(c)
336
+ return sorted(index.items.values(), key=lambda c: c.uid), events, source_report