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.
- gapms-1.3.2.dist-info/METADATA +92 -0
- gapms-1.3.2.dist-info/RECORD +69 -0
- gapms-1.3.2.dist-info/WHEEL +5 -0
- gapms-1.3.2.dist-info/entry_points.txt +3 -0
- gapms-1.3.2.dist-info/licenses/LICENSE +21 -0
- gapms-1.3.2.dist-info/licenses/THIRD_PARTY.md +21 -0
- gapms-1.3.2.dist-info/top_level.txt +1 -0
- gapms_v1/__init__.py +2 -0
- gapms_v1/__main__.py +2 -0
- gapms_v1/_genesensus/LICENSE +27 -0
- gapms_v1/_genesensus/VENDORED.json +53 -0
- gapms_v1/_genesensus/__init__.py +10 -0
- gapms_v1/_genesensus/__main__.py +4 -0
- gapms_v1/_genesensus/adaptive.py +157 -0
- gapms_v1/_genesensus/annotation.py +126 -0
- gapms_v1/_genesensus/available.py +64 -0
- gapms_v1/_genesensus/cli.py +149 -0
- gapms_v1/_genesensus/config.py +274 -0
- gapms_v1/_genesensus/corroborated.py +60 -0
- gapms_v1/_genesensus/diagnostics.py +19 -0
- gapms_v1/_genesensus/direct_molecular.py +29 -0
- gapms_v1/_genesensus/exchange.py +115 -0
- gapms_v1/_genesensus/exon_support.py +36 -0
- gapms_v1/_genesensus/genome.py +122 -0
- gapms_v1/_genesensus/graph.py +279 -0
- gapms_v1/_genesensus/graph_cache.py +175 -0
- gapms_v1/_genesensus/intervals.py +104 -0
- gapms_v1/_genesensus/isoform_guards.py +54 -0
- gapms_v1/_genesensus/isoforms.py +117 -0
- gapms_v1/_genesensus/joint.py +60 -0
- gapms_v1/_genesensus/loading.py +166 -0
- gapms_v1/_genesensus/local_molecular.py +112 -0
- gapms_v1/_genesensus/locus_select.py +137 -0
- gapms_v1/_genesensus/models.py +93 -0
- gapms_v1/_genesensus/molecular.py +222 -0
- gapms_v1/_genesensus/molecular_exchange.py +60 -0
- gapms_v1/_genesensus/molecular_state_utility.py +104 -0
- gapms_v1/_genesensus/molecular_strategy.py +83 -0
- gapms_v1/_genesensus/normalization.py +71 -0
- gapms_v1/_genesensus/orf_diagnostics.py +55 -0
- gapms_v1/_genesensus/peptide_context.py +167 -0
- gapms_v1/_genesensus/peptides.py +150 -0
- gapms_v1/_genesensus/pipeline.py +596 -0
- gapms_v1/_genesensus/provenance.py +54 -0
- gapms_v1/_genesensus/rna.py +175 -0
- gapms_v1/_genesensus/rna_geometry.py +114 -0
- gapms_v1/_genesensus/scoped.py +17 -0
- gapms_v1/_genesensus/scoring.py +46 -0
- gapms_v1/_genesensus/selection.py +336 -0
- gapms_v1/_genesensus/source_splice.py +19 -0
- gapms_v1/_genesensus/splice_prior.py +100 -0
- gapms_v1/_genesensus/state_utility.py +96 -0
- gapms_v1/_genesensus/support.py +189 -0
- gapms_v1/assessment.py +274 -0
- gapms_v1/classification.py +117 -0
- gapms_v1/cli.py +74 -0
- gapms_v1/common.py +67 -0
- gapms_v1/confidence_features.py +129 -0
- gapms_v1/consensus_engine.py +201 -0
- gapms_v1/mapping.py +144 -0
- gapms_v1/models.py +169 -0
- gapms_v1/orf_projection.py +249 -0
- gapms_v1/outputs.py +287 -0
- gapms_v1/peptides.py +54 -0
- gapms_v1/protein_mapper.py +125 -0
- gapms_v1/refinement.py +245 -0
- gapms_v1/report_figure.py +62 -0
- gapms_v1/rnaseq.py +91 -0
- gapms_v1/workflow.py +256 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Source-context molecular corrections, never reconstructed-protein scores."""
|
|
2
|
+
from .molecular import local_risk
|
|
3
|
+
from .intervals import merge
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def frame_at(model, position):
|
|
7
|
+
used = 0
|
|
8
|
+
for a, b in model.cds:
|
|
9
|
+
if a <= position < b:
|
|
10
|
+
offset = used + position-a if model.strand == '+' else model.length-used-(position-a)-1
|
|
11
|
+
return (offset-model.phase) % 3
|
|
12
|
+
used += b-a
|
|
13
|
+
return None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LocalMolecular:
|
|
17
|
+
def __init__(self, originals, parameters):
|
|
18
|
+
self.originals = [c for c in originals if c.sources and c.q is not None]
|
|
19
|
+
self.p = parameters
|
|
20
|
+
|
|
21
|
+
def correction(self, candidate, regions):
|
|
22
|
+
risk, known = local_risk(candidate, regions, self.p['localizer_gate'])
|
|
23
|
+
q = candidate.q
|
|
24
|
+
return q - self.p['risk_strength']*(1-q)*(risk if known else 0.)
|
|
25
|
+
|
|
26
|
+
def coding(self, model, regions=None):
|
|
27
|
+
"""Integrate source-capped, same-frame corrections over coding segments."""
|
|
28
|
+
originals = [c for c in self.originals
|
|
29
|
+
if (c.model.contig,c.model.strand)==(model.contig,model.strand)]
|
|
30
|
+
total = 0.
|
|
31
|
+
for left,right in (model.cds if regions is None else regions):
|
|
32
|
+
boundaries = {left,right}
|
|
33
|
+
for c in originals:
|
|
34
|
+
for a,b in c.model.cds:
|
|
35
|
+
if max(a,left)<min(b,right):
|
|
36
|
+
boundaries.update((max(a,left),min(b,right)))
|
|
37
|
+
points = sorted(boundaries)
|
|
38
|
+
for a,b in zip(points,points[1:]):
|
|
39
|
+
source = {}
|
|
40
|
+
for c in originals:
|
|
41
|
+
if (any(x<=a and b<=y for x,y in c.model.cds)
|
|
42
|
+
and frame_at(model,a)==frame_at(c.model,a)):
|
|
43
|
+
value = self.correction(c,((a,b),))
|
|
44
|
+
for s in c.sources:
|
|
45
|
+
source[s] = max(source.get(s,-float('inf')),value)
|
|
46
|
+
if source:
|
|
47
|
+
total += (b-a)*sum(source.values())/len(source)
|
|
48
|
+
return total
|
|
49
|
+
|
|
50
|
+
def splice(self, model):
|
|
51
|
+
total = 0.
|
|
52
|
+
width = self.p['boundary_window_nt']
|
|
53
|
+
for a,b in model.introns:
|
|
54
|
+
source = {}
|
|
55
|
+
for c in self.originals:
|
|
56
|
+
m = c.model
|
|
57
|
+
if ((m.contig,m.strand)!=(model.contig,model.strand)
|
|
58
|
+
or (a,b) not in m.introns
|
|
59
|
+
or frame_at(model,a-1)!=frame_at(m,a-1)
|
|
60
|
+
or frame_at(model,b)!=frame_at(m,b)):
|
|
61
|
+
continue
|
|
62
|
+
flanks = merge((max(x,u),min(y,v)) for x,y in m.cds
|
|
63
|
+
for u,v in ((max(0,a-width),a),(b,b+width))
|
|
64
|
+
if max(x,u)<min(y,v))
|
|
65
|
+
value = self.correction(c,flanks)
|
|
66
|
+
for s in c.sources:
|
|
67
|
+
source[s] = max(source.get(s,-float('inf')),value)
|
|
68
|
+
if source:
|
|
69
|
+
total += (b-a)*sum(source.values())/len(source)
|
|
70
|
+
return total
|
|
71
|
+
|
|
72
|
+
def features(self, model):
|
|
73
|
+
return self.coding(model),self.splice(model)
|
|
74
|
+
|
|
75
|
+
def graph_corrections(self, models):
|
|
76
|
+
"""Edge priors on supplied geometry, without guessing a novel frame.
|
|
77
|
+
|
|
78
|
+
Search state phase is checked during graph extension. Corrections are
|
|
79
|
+
indexed by edge and source reading frame to avoid promoting an
|
|
80
|
+
incompatible translation during pruning.
|
|
81
|
+
"""
|
|
82
|
+
bounds = sorted({p for m in models for iv in m.cds for p in iv})
|
|
83
|
+
result = {}
|
|
84
|
+
for a,b in zip(bounds,bounds[1:]):
|
|
85
|
+
frames = {}
|
|
86
|
+
for c in self.originals:
|
|
87
|
+
if any(x<=a and b<=y for x,y in c.model.cds):
|
|
88
|
+
frame = frame_at(c.model,a if c.model.strand=='+' else b-1)
|
|
89
|
+
source = frames.setdefault(frame,{})
|
|
90
|
+
value = self.correction(c,((a,b),))
|
|
91
|
+
for s in c.sources:
|
|
92
|
+
source[s] = max(source.get(s,-float('inf')),value)
|
|
93
|
+
for frame,source in frames.items():
|
|
94
|
+
result['coding',a,b,frame] = self.p.get('molecular_weight',1.)*sum(source.values())/len(source)
|
|
95
|
+
for a,b in sorted({iv for m in models for iv in m.introns}):
|
|
96
|
+
frames = {}
|
|
97
|
+
for c in self.originals:
|
|
98
|
+
if (a,b) not in c.model.introns:
|
|
99
|
+
continue
|
|
100
|
+
m=c.model
|
|
101
|
+
position=a-1 if m.strand=='+' else b
|
|
102
|
+
frame=(frame_at(m,position)+1)%3
|
|
103
|
+
width=self.p['boundary_window_nt']
|
|
104
|
+
flanks=merge((max(x,u),min(y,v)) for x,y in m.cds
|
|
105
|
+
for u,v in ((max(0,a-width),a),(b,b+width))
|
|
106
|
+
if max(x,u)<min(y,v))
|
|
107
|
+
source=frames.setdefault(frame,{})
|
|
108
|
+
for s in c.sources:
|
|
109
|
+
source[s]=max(source.get(s,-float('inf')),self.correction(c,flanks))
|
|
110
|
+
for frame,source in frames.items():
|
|
111
|
+
result['splice',a,b,frame]=self.p.get('molecular_weight',1.)*sum(source.values())/len(source)
|
|
112
|
+
return result
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Backbone-free local coding-path compatibility optimization; no reference inputs."""
|
|
2
|
+
from collections import defaultdict
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
import math
|
|
5
|
+
from .intervals import overlap,intersection_length
|
|
6
|
+
from .graph import loci
|
|
7
|
+
from .molecular import local_risk
|
|
8
|
+
|
|
9
|
+
def similarity(a,b):
|
|
10
|
+
coding=2*intersection_length(a.cds,b.cds)/(a.length+b.length)
|
|
11
|
+
ai,bi=set(a.introns),set(b.introns)
|
|
12
|
+
if not ai and not bi:return coding
|
|
13
|
+
junction=2*len(ai&bi)/(len(ai)+len(bi))
|
|
14
|
+
return (coding+junction)/2
|
|
15
|
+
|
|
16
|
+
def independent_set(weights,conflicts,exact_limit=28):
|
|
17
|
+
n=len(weights)
|
|
18
|
+
if n<=exact_limit:
|
|
19
|
+
@lru_cache(None)
|
|
20
|
+
def solve(mask):
|
|
21
|
+
if not mask:return (0.,())
|
|
22
|
+
members=[i for i in range(n) if mask>>i&1]
|
|
23
|
+
i=max(members,key=lambda j:((conflicts[j]&mask).bit_count() if hasattr(int,'bit_count') else bin(conflicts[j]&mask).count('1'),weights[j],-j))
|
|
24
|
+
remaining=mask&~(1<<i)
|
|
25
|
+
no=solve(remaining);score,chosen=solve(remaining&~conflicts[i]);yes=(score+weights[i],tuple(sorted(chosen+(i,))))
|
|
26
|
+
return max(no,yes,key=lambda x:(round(x[0],9),tuple(-v for v in x[1])))
|
|
27
|
+
value,chosen=solve((1<<n)-1)
|
|
28
|
+
return list(chosen),dict(exact=True,states=solve.cache_info().currsize,n=n)
|
|
29
|
+
# Bounded beam over independent subsets: honest approximation, retains several orders.
|
|
30
|
+
orders=[sorted(range(n),key=lambda i:(-weights[i],i)),sorted(range(n),key=lambda i:(-weights[i]/(1+bin(conflicts[i]).count('1')),i))]
|
|
31
|
+
answers=[]
|
|
32
|
+
for order in orders:
|
|
33
|
+
chosen=[];mask=0
|
|
34
|
+
for i in order:
|
|
35
|
+
if not conflicts[i]&mask:chosen.append(i);mask|=1<<i
|
|
36
|
+
# Strictly improving single-candidate exchanges; deterministic finite descent.
|
|
37
|
+
changed=True
|
|
38
|
+
while changed:
|
|
39
|
+
changed=False
|
|
40
|
+
for i in order:
|
|
41
|
+
if i in chosen:continue
|
|
42
|
+
old=[j for j in chosen if conflicts[i]>>j&1]
|
|
43
|
+
if weights[i]>sum(weights[j] for j in old)+1e-9:
|
|
44
|
+
chosen=[j for j in chosen if j not in old]+[i];changed=True
|
|
45
|
+
answers.append((sum(weights[i] for i in chosen),tuple(sorted(chosen))))
|
|
46
|
+
score,chosen=max(answers,key=lambda x:(round(x[0],9),tuple(-v for v in x[1])))
|
|
47
|
+
return list(chosen),dict(exact=False,solver='two deterministic greedy orders with strictly improving exchanges',n=n)
|
|
48
|
+
|
|
49
|
+
def select_locus(candidates,source_models,peptides,support,p,molecular_factory=None):
|
|
50
|
+
if p["selection_policy"]=="state_molecular_guided":
|
|
51
|
+
from .molecular_state_utility import StateEvidence
|
|
52
|
+
else:
|
|
53
|
+
from .state_utility import StateEvidence
|
|
54
|
+
states=StateEvidence(source_models) if p['selection_policy'].startswith('state_') else None
|
|
55
|
+
from .exon_support import ExonSupport
|
|
56
|
+
exon_support=ExonSupport(source_models,support,peptides) if p['selection_policy'] in ('state_coherent','state_splice_validated','state_rna_corroborated','state_molecular_guided') else None
|
|
57
|
+
bykey={c.model.key:c for c in candidates};selected=[];events=[];summary=defaultdict(int)
|
|
58
|
+
for models in loci([c.model for c in candidates]):
|
|
59
|
+
cc=sorted([bykey[m.key] for m in models],key=lambda c:c.uid);originals=[c for c in cc if c.sources]
|
|
60
|
+
from .local_molecular import LocalMolecular
|
|
61
|
+
molecular_states=LocalMolecular(originals,p) if p["selection_policy"]=="state_molecular_guided" else None
|
|
62
|
+
if molecular_states is not None and p.get("direct_candidate_audit",False):
|
|
63
|
+
from .direct_molecular import DirectMolecular
|
|
64
|
+
molecular_states=DirectMolecular(cc,p)
|
|
65
|
+
if molecular_factory is not None:
|
|
66
|
+
molecular_states=molecular_factory(originals,p)
|
|
67
|
+
weights=[];features=[];valid=[]
|
|
68
|
+
for c in cc:
|
|
69
|
+
m=c.model;votes=[]
|
|
70
|
+
for source in sorted(source_models):
|
|
71
|
+
matches=[similarity(m,o.model) for o in originals if source in o.sources and overlap(m.cds,o.model.cds)]
|
|
72
|
+
votes.append(max(matches,default=0.))
|
|
73
|
+
agreement=sum(votes);risk,known=local_risk(c,m.cds,p['localizer_gate']);molecular=c.q*(1-p['risk_strength']*(risk if known else 0)) if c.q is not None else 0.
|
|
74
|
+
peptide=len(c.peptides)/(len(c.peptides)+p['peptide_saturation']);rna=support.rna_score(m);protein=support.protein_score(m)
|
|
75
|
+
# Coverage objective; unweighted gene-event form is a declared ablation.
|
|
76
|
+
units=m.length if p['selection_policy']=='locus_coverage' else 1000.
|
|
77
|
+
extra=p['molecular_weight']*molecular+p['peptide_weight']*peptide+p['rna_weight']*rna+p['protein_weight']*protein
|
|
78
|
+
score=units*(agreement+extra)
|
|
79
|
+
state_features=(states.features(c,peptides,support,p,molecular_states) if molecular_states is not None else states.features(c,peptides,support,p)) if states else {}
|
|
80
|
+
if states:
|
|
81
|
+
score=state_features['utility']
|
|
82
|
+
if molecular_states is not None:molecular=state_features['molecular']
|
|
83
|
+
# Tie-break quality only, never a material substitute for measured agreement.
|
|
84
|
+
if score>0:score+=1e-7*(int(c.complete)+int(c.canonical))
|
|
85
|
+
reason='noncoding_preferred' if states and state_features['utility']<=0 else None
|
|
86
|
+
if p['selection_policy'] in ('state_admitted','state_coherent','state_soft_admitted','state_splice_validated','state_rna_corroborated','state_molecular_guided') and not state_features['admitted']:
|
|
87
|
+
reason='below_minimum_coding_length' if m.length<p['minimum_coding_nt'] else 'insufficient_coding_to_noncoding_support'
|
|
88
|
+
if p['selection_policy'] in ('state_splice_validated','state_rna_corroborated','state_molecular_guided'):
|
|
89
|
+
if any(b-a<p['minimum_intron_nt'] for a,b in m.introns):
|
|
90
|
+
reason='intron_below_minimum_length'
|
|
91
|
+
else:
|
|
92
|
+
if not c.canonical and m.introns and 'noncanonical_introns' not in c.graph_evidence:
|
|
93
|
+
reason='unvalidated_splice_sites'
|
|
94
|
+
for iv in c.graph_evidence.get('noncanonical_introns',()):
|
|
95
|
+
# RNA or a uniquely placed, frame-verified split peptide
|
|
96
|
+
# can validate an otherwise nonstandard splice site.
|
|
97
|
+
rna_ok=support.rna_count(m,iv)>=p['minimum_rna_templates']
|
|
98
|
+
peptide_ok=any(iv in tuple((a[1],b[0]) for a,b in zip(peptides[key].blocks,peptides[key].blocks[1:])) for key in c.peptides)
|
|
99
|
+
if not (rna_ok or peptide_ok):reason='noncanonical_splice_without_direct_support'
|
|
100
|
+
if c.graph_path:
|
|
101
|
+
if exon_support is not None and not exon_support.supports(m,c.peptides):reason='unsupported_exon_pairing_or_source_frame'
|
|
102
|
+
# Every new junction needs an original predictor or positive empirical support.
|
|
103
|
+
original_introns={iv for o in originals for iv in o.model.introns}
|
|
104
|
+
if any(iv not in original_introns and not support.supported_junction(m,iv) for iv in m.introns):reason='unsupported_novel_junction'
|
|
105
|
+
# A graph path cannot fuse two nonoverlapping multi-source anchors.
|
|
106
|
+
anchors=[o for o in originals if len(o.sources)>=2 and overlap(m.cds,o.model.cds)]
|
|
107
|
+
for i,a in enumerate(anchors):
|
|
108
|
+
for b in anchors[i+1:]:
|
|
109
|
+
if a.model.cds[-1][1]<=b.model.cds[0][0] or b.model.cds[-1][1]<=a.model.cds[0][0]:
|
|
110
|
+
if not all(sum(iv in o.model.introns for o in originals)>=2 or support.rna_count(m,iv)>=p['minimum_rna_templates'] for iv in m.introns):reason='unsupported_multi_anchor_fusion'
|
|
111
|
+
valid.append(reason is None);weights.append(score if reason is None else 0.);features.append(dict(agreement_by_source=votes,molecular=molecular,peptide=peptide,rna=rna,protein=protein,units=units,utility=score,excluded_reason=reason,state_features=state_features))
|
|
112
|
+
edges=[0]*len(cc)
|
|
113
|
+
for i,a in enumerate(cc):
|
|
114
|
+
for j in range(i):
|
|
115
|
+
if overlap(a.model.cds,cc[j].model.cds):edges[i]|=1<<j;edges[j]|=1<<i
|
|
116
|
+
# Solve each actual coding-conflict component; intronic nested genes remain compatible.
|
|
117
|
+
unseen=set(range(len(cc)));chosen=set()
|
|
118
|
+
while unseen:
|
|
119
|
+
todo=[min(unseen)];component=set()
|
|
120
|
+
while todo:
|
|
121
|
+
i=todo.pop()
|
|
122
|
+
if i in component:continue
|
|
123
|
+
component.add(i);unseen.discard(i);todo.extend(j for j in unseen if edges[i]>>j&1)
|
|
124
|
+
indices=sorted(i for i in component if valid[i]);local={g:i for i,g in enumerate(indices)}
|
|
125
|
+
masks=[sum(1<<local[j] for j in indices if edges[i]>>j&1) for i in indices]
|
|
126
|
+
answer,report=independent_set([weights[i] for i in indices],masks)
|
|
127
|
+
chosen.update(indices[i] for i in answer);summary['exact_components' if report['exact'] else 'approximate_components']+=1
|
|
128
|
+
if p.get('peptide_strategy')=='graph_contrast' and hasattr(peptides,'conservative_repair'):
|
|
129
|
+
chosen,peptide_events=peptides.conservative_repair(cc,chosen,valid,weights,support,p)
|
|
130
|
+
events.extend(peptide_events)
|
|
131
|
+
summary['peptide_contrast_repairs']+=len(peptide_events)
|
|
132
|
+
for i,c in enumerate(cc):
|
|
133
|
+
events.append(dict(event='locus_optimization',candidate=c.uid,incumbents=[],accepted=i in chosen,reasons=[] if i in chosen else [features[i]['excluded_reason'] or 'lower_joint_compatibility_utility'],**features[i]))
|
|
134
|
+
if i in chosen:selected.append(c)
|
|
135
|
+
elif c.sources and features[i]['excluded_reason'] is not None:
|
|
136
|
+
events.append(dict(event='provisional',candidate=c.uid,incumbents=[],accepted=True,reasons=[features[i]['excluded_reason']],interpretation='Unresolved source hypothesis retained separately; exclusion is not evidence of gene absence'))
|
|
137
|
+
return selected,events,dict(policy=p['selection_policy'],selected=None,global_backbone=False,sources={},solver_counts=dict(summary))
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Coordinate contracts: all internal intervals are zero-based, half-open."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
import hashlib
|
|
6
|
+
from numbers import Integral
|
|
7
|
+
from typing import Optional, Tuple
|
|
8
|
+
|
|
9
|
+
Interval = Tuple[int, int]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Transcript:
|
|
14
|
+
contig: str
|
|
15
|
+
strand: str
|
|
16
|
+
cds: Tuple[Interval, ...]
|
|
17
|
+
source: str
|
|
18
|
+
identifier: str
|
|
19
|
+
phase: int = 0
|
|
20
|
+
exons: Tuple[Interval, ...] = ()
|
|
21
|
+
gene: str = ""
|
|
22
|
+
origin: str = "prediction"
|
|
23
|
+
|
|
24
|
+
def __post_init__(self):
|
|
25
|
+
if not isinstance(self.phase, Integral) or isinstance(self.phase, bool):
|
|
26
|
+
raise ValueError("CDS phase must be an integer")
|
|
27
|
+
for intervals in (self.cds, self.exons):
|
|
28
|
+
for iv in intervals:
|
|
29
|
+
if len(iv) != 2 or any(
|
|
30
|
+
not isinstance(v, Integral) or isinstance(v, bool) for v in iv
|
|
31
|
+
):
|
|
32
|
+
raise ValueError("Coordinates must be integer interval pairs")
|
|
33
|
+
object.__setattr__(self, "phase", int(self.phase))
|
|
34
|
+
object.__setattr__(self, "cds", tuple((int(a), int(b)) for a, b in self.cds))
|
|
35
|
+
object.__setattr__(
|
|
36
|
+
self, "exons", tuple((int(a), int(b)) for a, b in self.exons)
|
|
37
|
+
)
|
|
38
|
+
if not self.contig or self.strand not in ("+", "-"):
|
|
39
|
+
raise ValueError("A CDS transcript needs a contig and + or - strand")
|
|
40
|
+
if self.phase not in (0, 1, 2) or not self.cds:
|
|
41
|
+
raise ValueError("A CDS transcript needs a valid initial phase and CDS")
|
|
42
|
+
previous = -1
|
|
43
|
+
for a, b in self.cds:
|
|
44
|
+
if a < 0 or b <= a or a < previous:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"Invalid or overlapping CDS intervals: {self.identifier}"
|
|
47
|
+
)
|
|
48
|
+
previous = b
|
|
49
|
+
for a, b in self.exons:
|
|
50
|
+
if a < 0 or b <= a:
|
|
51
|
+
raise ValueError(f"Invalid exon interval: {self.identifier}")
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def key(self):
|
|
55
|
+
return self.contig, self.strand, self.cds, self.phase
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def uid(self):
|
|
59
|
+
return hashlib.sha256(repr(self.key).encode()).hexdigest()[:24]
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def introns(self):
|
|
63
|
+
return tuple(
|
|
64
|
+
(a[1], b[0]) for a, b in zip(self.cds, self.cds[1:]) if a[1] < b[0]
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def length(self):
|
|
69
|
+
return sum(b - a for a, b in self.cds)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class Candidate:
|
|
74
|
+
model: Transcript
|
|
75
|
+
sources: set = field(default_factory=set)
|
|
76
|
+
original_ids: dict = field(default_factory=dict)
|
|
77
|
+
gene_scores: list = field(default_factory=list)
|
|
78
|
+
risks: list = field(default_factory=list)
|
|
79
|
+
peptides: set = field(default_factory=set)
|
|
80
|
+
complete: bool = False
|
|
81
|
+
canonical: bool = False
|
|
82
|
+
graph_path: bool = False
|
|
83
|
+
graph_evidence: dict = field(default_factory=dict)
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def uid(self):
|
|
87
|
+
return self.model.uid
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def q(self):
|
|
91
|
+
return (
|
|
92
|
+
sum(self.gene_scores) / len(self.gene_scores) if self.gene_scores else None
|
|
93
|
+
)
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Explicit optional protein scores/profiles; no correctness labels or fitting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import csv, gzip
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def read_scores(path, id_column="protein_id", score_column="protein_likeness_score"):
|
|
11
|
+
opener = gzip.open if str(path).endswith(".gz") else open
|
|
12
|
+
result = {}
|
|
13
|
+
with opener(path, "rt") as f:
|
|
14
|
+
reader = csv.DictReader(f, delimiter="\t")
|
|
15
|
+
if (
|
|
16
|
+
not reader.fieldnames
|
|
17
|
+
or id_column not in reader.fieldnames
|
|
18
|
+
or score_column not in reader.fieldnames
|
|
19
|
+
):
|
|
20
|
+
raise ValueError(
|
|
21
|
+
f"Score table requires {id_column} and {score_column}: {path}"
|
|
22
|
+
)
|
|
23
|
+
for row in reader:
|
|
24
|
+
ident = row[id_column]
|
|
25
|
+
q = float(row[score_column])
|
|
26
|
+
if not ident or not np.isfinite(q) or not 0 <= q <= 1:
|
|
27
|
+
raise ValueError(f"Invalid molecular score: {ident}")
|
|
28
|
+
if ident in result and result[ident] != q:
|
|
29
|
+
raise ValueError(f"Conflicting duplicate molecular score: {ident}")
|
|
30
|
+
result[ident] = q
|
|
31
|
+
if not result:
|
|
32
|
+
raise ValueError("Empty score table")
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class RiskTrack:
|
|
38
|
+
model: object
|
|
39
|
+
probabilities: object
|
|
40
|
+
q: object = None
|
|
41
|
+
|
|
42
|
+
_prefix: object = field(default=None, repr=False, init=False)
|
|
43
|
+
_mean: object = field(default=None, repr=False, init=False)
|
|
44
|
+
|
|
45
|
+
def risk(self, intervals, gate=None):
|
|
46
|
+
# A diagnostic profile intended only for binary-negative proteins is
|
|
47
|
+
# unobserved outside that scope, not a measured zero-error profile.
|
|
48
|
+
if gate is not None and (self.q is None or self.q >= gate):
|
|
49
|
+
return None, False
|
|
50
|
+
if tuple(intervals) == self.model.cds:
|
|
51
|
+
if not len(self.probabilities):
|
|
52
|
+
return None, False
|
|
53
|
+
if self._mean is None:
|
|
54
|
+
self._mean = float(np.mean(self.probabilities, dtype=np.float64))
|
|
55
|
+
return self._mean, True
|
|
56
|
+
total = 0.0
|
|
57
|
+
count = 0
|
|
58
|
+
prefix = 0
|
|
59
|
+
m = self.model
|
|
60
|
+
if self._prefix is None:
|
|
61
|
+
self._prefix = np.concatenate(
|
|
62
|
+
([0.0], np.cumsum(self.probabilities, dtype=np.float64))
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def integral(position):
|
|
66
|
+
k, r = divmod(position, 3)
|
|
67
|
+
return float(self._prefix[k]) * 3 + (
|
|
68
|
+
float(self.probabilities[k]) * r if r else 0.0
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
for a, b in m.cds:
|
|
72
|
+
for x, y in intervals:
|
|
73
|
+
left, right = max(a, x), min(b, y)
|
|
74
|
+
if left >= right:
|
|
75
|
+
continue
|
|
76
|
+
if m.strand == "+":
|
|
77
|
+
start, end = (
|
|
78
|
+
prefix + left - a - m.phase,
|
|
79
|
+
prefix + right - a - m.phase,
|
|
80
|
+
)
|
|
81
|
+
else:
|
|
82
|
+
start, end = (
|
|
83
|
+
m.length - prefix - (right - a) - m.phase,
|
|
84
|
+
m.length - prefix - (left - a) - m.phase,
|
|
85
|
+
)
|
|
86
|
+
start = max(0, start)
|
|
87
|
+
end = min(len(self.probabilities) * 3, end)
|
|
88
|
+
if start < end:
|
|
89
|
+
total += integral(end) - integral(start)
|
|
90
|
+
count += end - start
|
|
91
|
+
prefix += b - a
|
|
92
|
+
return (total / count, True) if count else (None, False)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def attach_molecular(candidates, source_models, specs, genome):
|
|
96
|
+
"""Validate profile IDs and sequence correspondence, then attach measured data."""
|
|
97
|
+
bykey = {c.model.key: c for c in candidates}
|
|
98
|
+
report = {}
|
|
99
|
+
for source, models in source_models.items():
|
|
100
|
+
spec = specs.get(source, {})
|
|
101
|
+
if not spec:
|
|
102
|
+
continue
|
|
103
|
+
qs = read_scores(spec["scores"]) if spec.get("scores") else {}
|
|
104
|
+
profiles = {}
|
|
105
|
+
sequences = {}
|
|
106
|
+
if spec.get("residue_profiles"):
|
|
107
|
+
try:
|
|
108
|
+
import h5py
|
|
109
|
+
except ImportError as exc:
|
|
110
|
+
raise RuntimeError(
|
|
111
|
+
"Residue profiles require genesensus[molecular]"
|
|
112
|
+
) from exc
|
|
113
|
+
with h5py.File(spec["residue_profiles"], "r") as h:
|
|
114
|
+
idkey = next((k for k in ["protein_id", "protein_ids"] if k in h), None)
|
|
115
|
+
valkey = next(
|
|
116
|
+
(
|
|
117
|
+
k
|
|
118
|
+
for k in ["localization_probability", "probabilities"]
|
|
119
|
+
if k in h
|
|
120
|
+
),
|
|
121
|
+
None,
|
|
122
|
+
)
|
|
123
|
+
if idkey is None or valkey is None or "offsets" not in h:
|
|
124
|
+
raise ValueError(
|
|
125
|
+
"HDF5 requires protein_id, offsets and localization_probability"
|
|
126
|
+
)
|
|
127
|
+
if (
|
|
128
|
+
h[idkey].ndim != 1
|
|
129
|
+
or h["offsets"].ndim != 1
|
|
130
|
+
or h["offsets"].dtype.kind not in "iu"
|
|
131
|
+
or h[valkey].ndim != 1
|
|
132
|
+
):
|
|
133
|
+
raise ValueError(
|
|
134
|
+
"Residue IDs, integer offsets and probabilities must be one-dimensional"
|
|
135
|
+
)
|
|
136
|
+
ids = h[idkey].asstr()[:].tolist()
|
|
137
|
+
offsets = np.asarray(h["offsets"][:], dtype=np.int64)
|
|
138
|
+
values = np.asarray(h[valkey][:])
|
|
139
|
+
if any(not ident for ident in ids):
|
|
140
|
+
raise ValueError("Empty residue profile identifier")
|
|
141
|
+
if "sequence" in h and (
|
|
142
|
+
h["sequence"].ndim != 1 or len(h["sequence"]) != len(ids)
|
|
143
|
+
):
|
|
144
|
+
raise ValueError("Residue sequence count differs from identifiers")
|
|
145
|
+
if len(ids) != len(set(ids)):
|
|
146
|
+
raise ValueError("Duplicate residue profile IDs")
|
|
147
|
+
if (
|
|
148
|
+
len(offsets) != len(ids) + 1
|
|
149
|
+
or offsets[0] != 0
|
|
150
|
+
or offsets[-1] != len(values)
|
|
151
|
+
or np.any(np.diff(offsets) < 0)
|
|
152
|
+
):
|
|
153
|
+
raise ValueError("Invalid residue profile offsets")
|
|
154
|
+
if (
|
|
155
|
+
not np.all(np.isfinite(values))
|
|
156
|
+
or np.any(values < 0)
|
|
157
|
+
or np.any(values > 1)
|
|
158
|
+
):
|
|
159
|
+
raise ValueError(
|
|
160
|
+
"Residue probabilities must be finite and in [0,1]"
|
|
161
|
+
)
|
|
162
|
+
profiles = {
|
|
163
|
+
tid: values[offsets[i] : offsets[i + 1]]
|
|
164
|
+
for i, tid in enumerate(ids)
|
|
165
|
+
}
|
|
166
|
+
if "sequence" in h:
|
|
167
|
+
sequences = dict(zip(ids, h["sequence"].asstr()[:].tolist()))
|
|
168
|
+
observed = {}
|
|
169
|
+
nq = nr = 0
|
|
170
|
+
for m in models:
|
|
171
|
+
if (
|
|
172
|
+
m.identifier in observed
|
|
173
|
+
and observed[m.identifier] != m.key
|
|
174
|
+
and (m.identifier in qs or m.identifier in profiles)
|
|
175
|
+
):
|
|
176
|
+
raise ValueError(
|
|
177
|
+
f"Ambiguous molecular identifier reused across structures: {source}:{m.identifier}"
|
|
178
|
+
)
|
|
179
|
+
observed[m.identifier] = m.key
|
|
180
|
+
c = bykey[m.key]
|
|
181
|
+
if m.identifier in qs:
|
|
182
|
+
c.gene_scores.append(qs[m.identifier])
|
|
183
|
+
nq += 1
|
|
184
|
+
if m.identifier in profiles:
|
|
185
|
+
pp = profiles[m.identifier]
|
|
186
|
+
_, _, translated = genome.assess(m)
|
|
187
|
+
if m.identifier in sequences:
|
|
188
|
+
expected = sequences[m.identifier].rstrip("*").upper()
|
|
189
|
+
if translated.rstrip("*") != expected:
|
|
190
|
+
raise ValueError(
|
|
191
|
+
f"Profile/annotation translation mismatch: {source}:{m.identifier}"
|
|
192
|
+
)
|
|
193
|
+
elif len(pp) not in (len(translated), len(translated.rstrip("*"))):
|
|
194
|
+
raise ValueError(
|
|
195
|
+
f"Profile/annotation length mismatch: {source}:{m.identifier}"
|
|
196
|
+
)
|
|
197
|
+
if m.identifier in sequences and len(pp) != len(
|
|
198
|
+
sequences[m.identifier]
|
|
199
|
+
):
|
|
200
|
+
raise ValueError(
|
|
201
|
+
f"Profile/sequence length mismatch: {m.identifier}"
|
|
202
|
+
)
|
|
203
|
+
c.risks.append(RiskTrack(m, pp, qs.get(m.identifier)))
|
|
204
|
+
nr += 1
|
|
205
|
+
report[source] = dict(
|
|
206
|
+
models=len(models),
|
|
207
|
+
measured_scores=nq,
|
|
208
|
+
measured_profiles=nr,
|
|
209
|
+
unmatched_model_scores=len(models) - nq if qs else None,
|
|
210
|
+
unmatched_model_profiles=len(models) - nr if profiles else None,
|
|
211
|
+
)
|
|
212
|
+
if qs and nq == 0:
|
|
213
|
+
raise ValueError(f"No molecular score identifiers match source {source}")
|
|
214
|
+
if profiles and nr == 0:
|
|
215
|
+
raise ValueError(f"No residue identifiers match source {source}")
|
|
216
|
+
return report
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def local_risk(candidate, regions, gate=None):
|
|
220
|
+
measured = [track.risk(regions, gate) for track in candidate.risks]
|
|
221
|
+
values = [r for r, known in measured if known]
|
|
222
|
+
return (float(np.mean(values)), True) if values else (None, False)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Corroborate local predictor agreement; retain provisional genes explicitly."""
|
|
2
|
+
from .exchange import LocalVotes,compare_exchange
|
|
3
|
+
from .selection import compare,_peptide_pair,_rna_pair
|
|
4
|
+
from .molecular import local_risk
|
|
5
|
+
from .intervals import disputed,intersection_length
|
|
6
|
+
from functools import partial
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def compare_molecular(c,old,peptides,support,chains,ivotes,n_sources,p,votes):
|
|
10
|
+
regions=disputed(c.model,old.model,p['boundary_window_nt'])
|
|
11
|
+
sn,so,known,certificate=votes.structural(c.model,old.model)
|
|
12
|
+
pn,po,_,_=_peptide_pair(c,old,peptides,regions,p['peptide_saturation'])
|
|
13
|
+
rn,ro=_rna_pair(c,old,support)
|
|
14
|
+
cr=tuple((max(a,x),min(b,y)) for a,b in c.model.cds for x,y in regions if max(a,x)<min(b,y))
|
|
15
|
+
oc=tuple((max(a,x),min(b,y)) for a,b in old.model.cds for x,y in regions if max(a,x)<min(b,y))
|
|
16
|
+
an,ao=support.protein_score(c.model,cr),support.protein_score(old.model,oc)
|
|
17
|
+
nr,nk=local_risk(c,regions,p['localizer_gate']);orr,ok=local_risk(old,regions,p['localizer_gate'])
|
|
18
|
+
gate=p.get('confidence_gate')
|
|
19
|
+
molecular_consistent=c.q is not None and old.q is not None and c.q>=old.q
|
|
20
|
+
corroboration=bool(pn>po or rn>ro or an>=ao+.1 or molecular_consistent or(nk and ok and orr-nr>=p['risk_advantage']))
|
|
21
|
+
if known and sn>so and corroboration:
|
|
22
|
+
e=compare_exchange(c,old,peptides,support,chains,ivotes,n_sources,p,votes)
|
|
23
|
+
e['decision_mode']='molecularly_admissible_consensus_exchange'
|
|
24
|
+
else:
|
|
25
|
+
e=compare(c,old,peptides,support,chains,ivotes,n_sources,p)
|
|
26
|
+
e['decision_mode']='compatibility_without_corroborated_majority'
|
|
27
|
+
e['majority_corroborated']=corroboration
|
|
28
|
+
return e
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def select_molecular(candidates,source_models,peptides,support,p):
|
|
32
|
+
from .selection import select
|
|
33
|
+
votes=LocalVotes(source_models)
|
|
34
|
+
selected,events,backbone=select(candidates,source_models,peptides,support,p,
|
|
35
|
+
_comparison=partial(compare_molecular,votes=votes))
|
|
36
|
+
if p['selection_policy']!='molecular_tiered':return selected,events,backbone
|
|
37
|
+
gate=p.get('confidence_gate')
|
|
38
|
+
if gate is None:raise ValueError('Tiered selection requires an independently specified confidence_gate')
|
|
39
|
+
primary=[]
|
|
40
|
+
for c in selected:
|
|
41
|
+
m=c.model
|
|
42
|
+
# Independent predictor contradiction is unavailable with fewer than 3 sources.
|
|
43
|
+
fractions=[]
|
|
44
|
+
for source in votes.sources:
|
|
45
|
+
blocks,starts,ends=votes.coverage.get((source,m.contig,m.strand),((),(),()))
|
|
46
|
+
from bisect import bisect_left,bisect_right
|
|
47
|
+
sliced=blocks[bisect_right(ends,m.cds[0][0]):bisect_left(starts,m.cds[-1][1])]
|
|
48
|
+
fractions.append(intersection_length(m.cds,sliced)/m.length)
|
|
49
|
+
coding=sum(fractions)/len(fractions)
|
|
50
|
+
rna=any(support.rna_count(m,iv)>=p['minimum_rna_templates'] for iv in m.introns)
|
|
51
|
+
protein=support.protein_score(m)>0
|
|
52
|
+
provisional=(len(source_models)>=3 and not c.graph_path and c.q is not None and c.q<gate
|
|
53
|
+
and coding<.5 and not(c.peptides or rna or protein))
|
|
54
|
+
if provisional:
|
|
55
|
+
events.append(dict(event='provisional',candidate=c.uid,incumbents=[],accepted=True,
|
|
56
|
+
reasons=['classifier_negative_and_predictor_majority_exclusion_without_positive_empirical_support'],
|
|
57
|
+
gene_q=c.q,confidence_gate=gate,coding_agreement=coding,
|
|
58
|
+
interpretation='uncertain hypothesis retained in provisional.gff3; not a biological false-gene label'))
|
|
59
|
+
else:primary.append(c)
|
|
60
|
+
return primary,events,backbone
|