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,115 @@
|
|
|
1
|
+
"""Local, source-symmetric evidence comparisons; no reference features or fitting.
|
|
2
|
+
|
|
3
|
+
Predictor votes describe agreement, not independent biological observations or
|
|
4
|
+
calibrated probabilities. Coding and junction agreement are separate from q.
|
|
5
|
+
"""
|
|
6
|
+
from bisect import bisect_left, bisect_right
|
|
7
|
+
from functools import partial
|
|
8
|
+
import numpy as np
|
|
9
|
+
from .intervals import merge, subtract, disputed, intersection_length
|
|
10
|
+
from .selection import predictor_support, _peptide_pair, _rna_pair
|
|
11
|
+
from .molecular import local_risk
|
|
12
|
+
from .scoring import weighted_scores
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class LocalVotes:
|
|
16
|
+
def __init__(self, source_models):
|
|
17
|
+
self.n = len(source_models)
|
|
18
|
+
grouped = {}
|
|
19
|
+
self.junctions = {}
|
|
20
|
+
for source, models in source_models.items():
|
|
21
|
+
for m in models:
|
|
22
|
+
grouped.setdefault((source, m.contig, m.strand), []).extend(m.cds)
|
|
23
|
+
for iv in m.introns:
|
|
24
|
+
self.junctions.setdefault((m.contig, m.strand, *iv), set()).add(source)
|
|
25
|
+
self.coverage = {}
|
|
26
|
+
for key, blocks in grouped.items():
|
|
27
|
+
blocks = merge(blocks)
|
|
28
|
+
self.coverage[key] = blocks, [a for a,b in blocks], [b for a,b in blocks]
|
|
29
|
+
self.sources = tuple(sorted(source_models))
|
|
30
|
+
|
|
31
|
+
def coding(self, new, old):
|
|
32
|
+
"""Expected coding-state agreement on the same symmetric-difference bases."""
|
|
33
|
+
regions = merge(subtract(new.cds, old.cds) + subtract(old.cds, new.cds))
|
|
34
|
+
if not regions:
|
|
35
|
+
return None, None, False
|
|
36
|
+
scores = [0.0, 0.0]; total = 0; certificate = True
|
|
37
|
+
for a,b in regions:
|
|
38
|
+
bounds = {a,b}; source_blocks = []
|
|
39
|
+
for source in self.sources:
|
|
40
|
+
blocks, starts, ends = self.coverage.get((source,new.contig,new.strand),((),(),()))
|
|
41
|
+
picked = blocks[bisect_right(ends,a):bisect_left(starts,b)]
|
|
42
|
+
source_blocks.append(picked)
|
|
43
|
+
for x,y in picked:bounds.update((max(a,x),min(b,y)))
|
|
44
|
+
points = sorted(bounds)
|
|
45
|
+
for x,y in zip(points,points[1:]):
|
|
46
|
+
if x==y:continue
|
|
47
|
+
v = sum(bool(intersection_length(((x,y),), blocks)) for blocks in source_blocks)/self.n
|
|
48
|
+
on = bool(intersection_length(((x,y),), new.cds))
|
|
49
|
+
sn = v if on else 1-v
|
|
50
|
+
scores[0] += (y-x)*sn; scores[1] += (y-x)*(1-sn)
|
|
51
|
+
total += y-x; certificate &= sn > .5
|
|
52
|
+
return scores[0]/total, scores[1]/total, certificate
|
|
53
|
+
|
|
54
|
+
def structural(self, new, old):
|
|
55
|
+
a,b,cert = self.coding(new,old); values=[]; certificates=[]
|
|
56
|
+
if a is not None: values.append((a,b));certificates.append(cert)
|
|
57
|
+
ni,oi=set(new.introns),set(old.introns);ivs=ni^oi
|
|
58
|
+
if ivs:
|
|
59
|
+
ns=[]; os=[]; jc=True
|
|
60
|
+
for iv in sorted(ivs):
|
|
61
|
+
v=len(self.junctions.get((new.contig,new.strand,*iv),()))/self.n
|
|
62
|
+
sn=v if iv in ni else 1-v
|
|
63
|
+
ns.append(sn);os.append(1-sn);jc &= sn>.5
|
|
64
|
+
values.append((sum(ns)/len(ns),sum(os)/len(os)));certificates.append(jc)
|
|
65
|
+
if self.n<2 or not values:return 0.,0.,False,False
|
|
66
|
+
return (sum(x for x,y in values)/len(values),sum(y for x,y in values)/len(values),True,all(certificates))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def compare_exchange(c, old, peptides, support, chains, ivotes, n_sources, p, votes):
|
|
70
|
+
m,o=c.model,old.model; reasons=[]
|
|
71
|
+
regions=disputed(m,o,p['boundary_window_nt'])
|
|
72
|
+
sn,so,sk,certificate=votes.structural(m,o)
|
|
73
|
+
nr,nk=local_risk(c,regions,p['localizer_gate']);orr,ok=local_risk(old,regions,p['localizer_gate'])
|
|
74
|
+
qknown=c.q is not None and old.q is not None
|
|
75
|
+
if qknown:
|
|
76
|
+
mn=c.q*(1-p['risk_strength']*(nr if nk else 0));mo=old.q*(1-p['risk_strength']*(orr if ok else 0))
|
|
77
|
+
elif nk and ok:mn,mo=1-p['risk_strength']*nr,1-p['risk_strength']*orr
|
|
78
|
+
else:mn=mo=0.
|
|
79
|
+
pn,po,newpeps,oldpeps=_peptide_pair(c,old,peptides,regions,p['peptide_saturation'])
|
|
80
|
+
rn,ro=_rna_pair(c,old,support)
|
|
81
|
+
cr=tuple((max(a,x),min(b,y)) for a,b in m.cds for x,y in regions if max(a,x)<min(b,y))
|
|
82
|
+
oc=tuple((max(a,x),min(b,y)) for a,b in o.cds for x,y in regions if max(a,x)<min(b,y))
|
|
83
|
+
an,ao=support.protein_score(m,cr),support.protein_score(o,oc)
|
|
84
|
+
new_junctions=set(m.introns)-set(o.introns)
|
|
85
|
+
supported=all(support.supported_junction(m,iv,ivotes) for iv in new_junctions)
|
|
86
|
+
if not(c.complete and c.canonical):reasons.append('incomplete_or_noncanonical')
|
|
87
|
+
if c.graph_path and not supported:reasons.append('unsupported_new_junction')
|
|
88
|
+
if m.length < p['minimum_retained_fraction']*o.length and not(certificate and supported):reasons.append('uncertified_truncation')
|
|
89
|
+
if oldpeps:reasons.append('incumbent_distinguishing_peptide')
|
|
90
|
+
if ro>0 and rn==0:reasons.append('incumbent_distinguishing_rna')
|
|
91
|
+
if nk and ok and nr>orr+p['risk_advantage']:reasons.append('local_risk_regression')
|
|
92
|
+
qadv=qknown and c.q-old.q>=p['q_advantage']
|
|
93
|
+
radv=nk and ok and orr-nr>=p['risk_advantage']
|
|
94
|
+
advantage=(sk and sn>so) or qadv or (radv and not c.graph_path) or pn>po or rn>ro or an>=ao+.1
|
|
95
|
+
if not advantage:reasons.append('insufficient_distinguishing_evidence')
|
|
96
|
+
active=[qknown or(nk and ok),bool(newpeps or oldpeps),abs(rn-ro)>1e-12,abs(an-ao)>1e-12,sk and abs(sn-so)>1e-12]
|
|
97
|
+
weights=[p['molecular_weight'],p['peptide_weight'],p['rna_weight'],p['protein_weight'],p['predictor_weight']]
|
|
98
|
+
values=np.array([[mn,pn,rn,an,sn],[mo,po,ro,ao,so]],dtype=np.float64)
|
|
99
|
+
scores=weighted_scores(values,[active,active],weights,backend='cpu');delta=float(scores[0]-scores[1])
|
|
100
|
+
if delta<=p['replacement_margin']+1e-12:reasons.append('absolute_margin')
|
|
101
|
+
return dict(candidate=c.uid,incumbents=[old.uid],accepted=not reasons,reasons=reasons,
|
|
102
|
+
comparison_policy='local_exchange',graph_candidate=c.graph_path,disputed_intervals=regions,
|
|
103
|
+
channel_order=['molecular','peptide','rna','protein','local_predictor_agreement'],active_channels=active,
|
|
104
|
+
weights=weights,new_values=values[0].tolist(),old_values=values[1].tolist(),
|
|
105
|
+
new_score=float(scores[0]),old_score=float(scores[1]),absolute_margin=delta,
|
|
106
|
+
molecular_measured_both=qknown,residue_known_both=nk and ok,new_disputed_risk=nr,old_disputed_risk=orr,
|
|
107
|
+
new_unique_peptides=newpeps,old_unique_peptides=oldpeps,new_junctions_supported=supported,
|
|
108
|
+
strict_local_majority_certificate=certificate,
|
|
109
|
+
truncation_exception=bool(m.length<p['minimum_retained_fraction']*o.length and certificate and supported))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def select_exchange(candidates, source_models, peptides, support, p):
|
|
113
|
+
from .selection import select
|
|
114
|
+
return select(candidates,source_models,peptides,support,p,
|
|
115
|
+
_comparison=partial(compare_exchange,votes=LocalVotes(source_models)))
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Observed exon pairing and source-frame support for novel graph paths."""
|
|
2
|
+
|
|
3
|
+
class ExonSupport:
|
|
4
|
+
def __init__(self, source_models, support, peptides=None):
|
|
5
|
+
self.protein=support.protein_exon_frames
|
|
6
|
+
self.peptides=peptides or {}
|
|
7
|
+
self.observed=set()
|
|
8
|
+
for models in source_models.values():
|
|
9
|
+
for model in models:
|
|
10
|
+
self.observed.update(self.tokens(model))
|
|
11
|
+
self.rna={(chrom,strand,iv) for (chrom,strand),intervals in support.rna_internal.items() for iv in intervals}
|
|
12
|
+
|
|
13
|
+
@staticmethod
|
|
14
|
+
def tokens(model):
|
|
15
|
+
ordered=model.cds if model.strand=='+' else tuple(reversed(model.cds))
|
|
16
|
+
used=-model.phase
|
|
17
|
+
for i,iv in enumerate(ordered):
|
|
18
|
+
role='single' if len(ordered)==1 else 'first' if i==0 else 'last' if i==len(ordered)-1 else 'internal'
|
|
19
|
+
yield model.contig,model.strand,role,iv,used%3
|
|
20
|
+
used+=iv[1]-iv[0]
|
|
21
|
+
|
|
22
|
+
def supports(self, model, matched_peptides=()):
|
|
23
|
+
for token in self.tokens(model):
|
|
24
|
+
if token in self.observed:
|
|
25
|
+
continue
|
|
26
|
+
chrom,strand,role,iv,frame=token
|
|
27
|
+
if (chrom,strand,iv,frame) in self.protein:
|
|
28
|
+
continue
|
|
29
|
+
if any(iv in self.peptides[key].blocks[1:-1] for key in matched_peptides):
|
|
30
|
+
continue
|
|
31
|
+
# RNA does not assert coding frame; the complete ORF has been validated
|
|
32
|
+
# on the genome. It must supply the observed whole-exon geometry.
|
|
33
|
+
if role!='single' and (chrom,strand,iv) in self.rna:
|
|
34
|
+
continue
|
|
35
|
+
return False
|
|
36
|
+
return True
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Read-only indexed FASTA access; indexes never modify source FASTA directories."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import mmap
|
|
5
|
+
from Bio.Seq import Seq
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Genome:
|
|
9
|
+
def __init__(self, path):
|
|
10
|
+
self.path = Path(path)
|
|
11
|
+
self.index = {}
|
|
12
|
+
with self.path.open("rb") as f:
|
|
13
|
+
name = None
|
|
14
|
+
length = offset = bases = width = 0
|
|
15
|
+
short = False
|
|
16
|
+
while True:
|
|
17
|
+
start = f.tell()
|
|
18
|
+
line = f.readline()
|
|
19
|
+
if not line:
|
|
20
|
+
if name is not None:
|
|
21
|
+
self.index[name] = (length, offset, bases, width)
|
|
22
|
+
break
|
|
23
|
+
if line.startswith(b">"):
|
|
24
|
+
if name is not None:
|
|
25
|
+
self.index[name] = (length, offset, bases, width)
|
|
26
|
+
name = line[1:].split()[0].decode()
|
|
27
|
+
if name in self.index:
|
|
28
|
+
raise ValueError(f"Duplicate FASTA contig: {name}")
|
|
29
|
+
length = bases = width = 0
|
|
30
|
+
offset = f.tell()
|
|
31
|
+
short = False
|
|
32
|
+
else:
|
|
33
|
+
if name is None:
|
|
34
|
+
raise ValueError("FASTA sequence precedes its header")
|
|
35
|
+
seq = line.rstrip(b"\r\n")
|
|
36
|
+
if not seq:
|
|
37
|
+
raise ValueError("Blank FASTA sequence lines are unsupported")
|
|
38
|
+
if short:
|
|
39
|
+
raise ValueError(f"Irregular FASTA line wrapping: {name}")
|
|
40
|
+
if not bases:
|
|
41
|
+
bases = len(seq)
|
|
42
|
+
width = len(line)
|
|
43
|
+
if len(seq) > bases:
|
|
44
|
+
raise ValueError(f"Irregular FASTA line wrapping: {name}")
|
|
45
|
+
if len(seq) < bases:
|
|
46
|
+
short = True
|
|
47
|
+
if any(c in seq for c in (b" ", b"\t")):
|
|
48
|
+
raise ValueError("Whitespace inside FASTA sequence")
|
|
49
|
+
length += len(seq)
|
|
50
|
+
if not self.index:
|
|
51
|
+
raise ValueError("Empty genome FASTA")
|
|
52
|
+
self._file = self.path.open("rb")
|
|
53
|
+
self._map = mmap.mmap(self._file.fileno(), 0, access=mmap.ACCESS_READ)
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def from_index(cls, path, index):
|
|
57
|
+
"""Reuse a validated parent index in a worker without rescanning FASTA."""
|
|
58
|
+
self = cls.__new__(cls)
|
|
59
|
+
self.path = Path(path)
|
|
60
|
+
self.index = index
|
|
61
|
+
self._file = self.path.open("rb")
|
|
62
|
+
self._map = mmap.mmap(self._file.fileno(), 0, access=mmap.ACCESS_READ)
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def lengths(self):
|
|
67
|
+
return {name: data[0] for name, data in self.index.items()}
|
|
68
|
+
|
|
69
|
+
def fetch(self, contig, start, end):
|
|
70
|
+
if contig not in self.index:
|
|
71
|
+
raise ValueError(f"Unknown genome contig: {contig}")
|
|
72
|
+
length, offset, bases, width = self.index[contig]
|
|
73
|
+
if not 0 <= start <= end <= length:
|
|
74
|
+
raise ValueError(f"Genome interval out of bounds: {contig}:{start}-{end}")
|
|
75
|
+
if start == end:
|
|
76
|
+
return ""
|
|
77
|
+
a = offset + start // bases * width + start % bases
|
|
78
|
+
b = offset + (end - 1) // bases * width + (end - 1) % bases + 1
|
|
79
|
+
return self._map[a:b].replace(b"\n", b"").replace(b"\r", b"").decode().upper()
|
|
80
|
+
|
|
81
|
+
def coding_sequence(self, model):
|
|
82
|
+
dna = "".join(self.fetch(model.contig, a, b) for a, b in model.cds)
|
|
83
|
+
if model.strand == "-":
|
|
84
|
+
dna = str(Seq(dna).reverse_complement())
|
|
85
|
+
return dna
|
|
86
|
+
|
|
87
|
+
def assess(self, model):
|
|
88
|
+
dna = self.coding_sequence(model)
|
|
89
|
+
coding = dna[model.phase :]
|
|
90
|
+
aa = str(Seq(coding[: len(coding) // 3 * 3]).translate())
|
|
91
|
+
complete = (
|
|
92
|
+
model.phase == 0
|
|
93
|
+
and len(dna) % 3 == 0
|
|
94
|
+
and dna.startswith("ATG")
|
|
95
|
+
and aa.endswith("*")
|
|
96
|
+
and "*" not in aa[:-1]
|
|
97
|
+
and "X" not in aa
|
|
98
|
+
)
|
|
99
|
+
canonical = True
|
|
100
|
+
for a, b in model.introns:
|
|
101
|
+
if b - a < 4:
|
|
102
|
+
canonical = False
|
|
103
|
+
continue
|
|
104
|
+
left, right = self.fetch(model.contig, a, a + 2), self.fetch(
|
|
105
|
+
model.contig, b - 2, b
|
|
106
|
+
)
|
|
107
|
+
if model.strand == "-":
|
|
108
|
+
left, right = str(Seq(right).reverse_complement()), str(
|
|
109
|
+
Seq(left).reverse_complement()
|
|
110
|
+
)
|
|
111
|
+
canonical &= (left, right) in {("GT", "AG"), ("GC", "AG"), ("AT", "AC")}
|
|
112
|
+
return complete, bool(canonical), aa
|
|
113
|
+
|
|
114
|
+
def close(self):
|
|
115
|
+
self._map.close()
|
|
116
|
+
self._file.close()
|
|
117
|
+
|
|
118
|
+
def __enter__(self):
|
|
119
|
+
return self
|
|
120
|
+
|
|
121
|
+
def __exit__(self, *args):
|
|
122
|
+
self.close()
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Bounded, strand-aware exon-segment / splice-junction DAG reconstruction.
|
|
2
|
+
|
|
3
|
+
Existing coding coverage and explicit optional RNA/protein alignment segments
|
|
4
|
+
can form exon segments. RNA segments require observed internal-exon geometry.
|
|
5
|
+
Path search is bounded and reports pruning. Final ORFs are checked on the genome.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from .models import Transcript
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Edge:
|
|
16
|
+
start: int
|
|
17
|
+
end: int
|
|
18
|
+
kind: str
|
|
19
|
+
sources: tuple
|
|
20
|
+
strength: float
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class PathState:
|
|
25
|
+
score: float
|
|
26
|
+
blocks: tuple
|
|
27
|
+
bases: int
|
|
28
|
+
junctions: tuple
|
|
29
|
+
start: int
|
|
30
|
+
observed_peptides: tuple = ()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def loci(models):
|
|
34
|
+
"""Deterministic envelope components, separated by contig and strand."""
|
|
35
|
+
grouped = defaultdict(list)
|
|
36
|
+
for m in models:
|
|
37
|
+
grouped[m.contig, m.strand].append(m)
|
|
38
|
+
for key, mm in sorted(grouped.items()):
|
|
39
|
+
component = []
|
|
40
|
+
right = -1
|
|
41
|
+
for m in sorted(mm, key=lambda m: (m.cds[0][0], m.cds[-1][1], m.uid)):
|
|
42
|
+
if component and m.cds[0][0] >= right:
|
|
43
|
+
yield component
|
|
44
|
+
component = []
|
|
45
|
+
right = -1
|
|
46
|
+
component.append(m)
|
|
47
|
+
right = max(right, m.cds[-1][1])
|
|
48
|
+
if component:
|
|
49
|
+
yield component
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def build_graph(models, extra_junctions=(), extra_segments=()):
|
|
53
|
+
if not models:
|
|
54
|
+
return {}, [], []
|
|
55
|
+
chrom, strand = models[0].contig, models[0].strand
|
|
56
|
+
if any((m.contig, m.strand) != (chrom, strand) for m in models):
|
|
57
|
+
raise ValueError("A graph cannot cross contigs or strands")
|
|
58
|
+
bounds = {p for m in models for iv in m.cds for p in iv}
|
|
59
|
+
coverage = defaultdict(list)
|
|
60
|
+
junctions = defaultdict(set)
|
|
61
|
+
for m in models:
|
|
62
|
+
for a, b in m.cds:
|
|
63
|
+
coverage[a].append((1, m.source))
|
|
64
|
+
coverage[b].append((-1, m.source))
|
|
65
|
+
for iv in m.introns:
|
|
66
|
+
junctions[iv].add(m.source)
|
|
67
|
+
extra = {}
|
|
68
|
+
lo = min(bounds)
|
|
69
|
+
hi = max(bounds)
|
|
70
|
+
for a, b, label in extra_segments:
|
|
71
|
+
a, b = max(lo, a), min(hi, b)
|
|
72
|
+
if a < b:
|
|
73
|
+
bounds.update((a, b))
|
|
74
|
+
coverage[a].append((1, label))
|
|
75
|
+
coverage[b].append((-1, label))
|
|
76
|
+
for a, b, strength, label in extra_junctions:
|
|
77
|
+
if lo <= a < b <= hi:
|
|
78
|
+
bounds.update((a, b))
|
|
79
|
+
extra[a, b] = max(extra.get((a, b), 0.0), float(strength))
|
|
80
|
+
junctions[a, b].add(label)
|
|
81
|
+
bounds = sorted(bounds)
|
|
82
|
+
active = defaultdict(int)
|
|
83
|
+
graph = defaultdict(list)
|
|
84
|
+
direction = 1 if strand == "+" else -1
|
|
85
|
+
for a, b in zip(bounds, bounds[1:]):
|
|
86
|
+
for delta, source in coverage[a]:
|
|
87
|
+
active[source] += delta
|
|
88
|
+
ss = tuple(sorted(s for s, n in active.items() if n > 0))
|
|
89
|
+
if ss:
|
|
90
|
+
start, end = (a, b) if direction == 1 else (b, a)
|
|
91
|
+
graph[start].append(Edge(start, end, "coding", ss, len(ss)))
|
|
92
|
+
for (a, b), ss in sorted(junctions.items()):
|
|
93
|
+
start, end = (a, b) if direction == 1 else (b, a)
|
|
94
|
+
graph[start].append(
|
|
95
|
+
Edge(
|
|
96
|
+
start,
|
|
97
|
+
end,
|
|
98
|
+
"splice",
|
|
99
|
+
tuple(sorted(ss)),
|
|
100
|
+
len(ss) + extra.get((a, b), 0.0),
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
for edges in graph.values():
|
|
104
|
+
edges.sort(key=lambda e: (direction * e.end, e.kind, e.sources))
|
|
105
|
+
starts = sorted(
|
|
106
|
+
{m.cds[0][0] if direction == 1 else m.cds[-1][1] for m in models},
|
|
107
|
+
reverse=direction == -1,
|
|
108
|
+
)
|
|
109
|
+
ends = sorted(
|
|
110
|
+
{m.cds[-1][1] if direction == 1 else m.cds[0][0] for m in models},
|
|
111
|
+
reverse=direction == -1,
|
|
112
|
+
)
|
|
113
|
+
return dict(graph), starts, ends
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _extend(state, edge, strand, molecular_corrections=None):
|
|
117
|
+
a,b=sorted((edge.start,edge.end))
|
|
118
|
+
correction=(molecular_corrections or {}).get((edge.kind,a,b,state.bases%3),0.)
|
|
119
|
+
if edge.kind == "splice":
|
|
120
|
+
if not state.blocks:
|
|
121
|
+
return None
|
|
122
|
+
terminal = state.blocks[-1][1] if strand == "+" else state.blocks[-1][0]
|
|
123
|
+
if terminal != edge.start:
|
|
124
|
+
return None
|
|
125
|
+
return PathState(
|
|
126
|
+
state.score + 0.2 * (edge.strength + correction),
|
|
127
|
+
state.blocks,
|
|
128
|
+
state.bases,
|
|
129
|
+
state.junctions + ((min(edge.start, edge.end), max(edge.start, edge.end)),),
|
|
130
|
+
state.start,
|
|
131
|
+
state.observed_peptides,
|
|
132
|
+
)
|
|
133
|
+
a, b = sorted((edge.start, edge.end))
|
|
134
|
+
blocks = list(state.blocks)
|
|
135
|
+
# An exon cannot silently traverse a junction: only contiguous coding edges merge.
|
|
136
|
+
if blocks and (
|
|
137
|
+
(strand == "+" and blocks[-1][1] == a) or (strand == "-" and blocks[-1][0] == b)
|
|
138
|
+
):
|
|
139
|
+
blocks[-1] = (min(a, blocks[-1][0]), max(b, blocks[-1][1]))
|
|
140
|
+
else:
|
|
141
|
+
blocks.append((a, b))
|
|
142
|
+
return PathState(
|
|
143
|
+
state.score + (b - a) / 1000.0 * (edge.strength + correction),
|
|
144
|
+
tuple(blocks),
|
|
145
|
+
state.bases + b - a,
|
|
146
|
+
state.junctions,
|
|
147
|
+
state.start,
|
|
148
|
+
state.observed_peptides,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def reconstruct(
|
|
153
|
+
models,
|
|
154
|
+
genome,
|
|
155
|
+
extra_junctions=(),
|
|
156
|
+
beam=8,
|
|
157
|
+
max_candidates=32,
|
|
158
|
+
max_nodes=2000,
|
|
159
|
+
max_starts=32,
|
|
160
|
+
extra_segments=(),
|
|
161
|
+
molecular_corrections=None,
|
|
162
|
+
peptide_observations=(),
|
|
163
|
+
):
|
|
164
|
+
if min(beam, max_candidates, max_nodes, max_starts) < 1:
|
|
165
|
+
raise ValueError("Graph bounds must be positive")
|
|
166
|
+
if not models:
|
|
167
|
+
return [], dict(nodes=0, edges=0, paths_pruned=0, candidates=0)
|
|
168
|
+
graph, starts, ends = build_graph(models, extra_junctions, extra_segments)
|
|
169
|
+
strand = models[0].strand
|
|
170
|
+
chrom = models[0].contig
|
|
171
|
+
# A path with matching geometry/frame uses exactly these peptide bases.
|
|
172
|
+
# Validate their translation once, rather than retranslating whole partial
|
|
173
|
+
# ORFs and reassessing all preceding introns at each search extension.
|
|
174
|
+
if peptide_observations:
|
|
175
|
+
from Bio.Seq import Seq
|
|
176
|
+
validated=[]
|
|
177
|
+
for peptide in peptide_observations:
|
|
178
|
+
if (peptide.contig,peptide.strand)!=(chrom,strand):continue
|
|
179
|
+
if peptide.blocks[0][0]<min(m.cds[0][0] for m in models) or peptide.blocks[-1][1]>max(m.cds[-1][1] for m in models):continue
|
|
180
|
+
dna=''.join(genome.fetch(peptide.contig,a,b) for a,b in peptide.blocks)
|
|
181
|
+
if peptide.strand=='-':dna=str(Seq(dna).reverse_complement())
|
|
182
|
+
if str(Seq(dna).translate()).replace('I','L')==peptide.sequence:
|
|
183
|
+
validated.append(peptide)
|
|
184
|
+
peptide_observations=tuple(validated)
|
|
185
|
+
direction = 1 if strand == "+" else -1
|
|
186
|
+
nodes = sorted(
|
|
187
|
+
{p for v in graph.values() for e in v for p in (e.start, e.end)},
|
|
188
|
+
reverse=direction == -1,
|
|
189
|
+
)
|
|
190
|
+
report = dict(
|
|
191
|
+
nodes=len(nodes),
|
|
192
|
+
edges=sum(map(len, graph.values())),
|
|
193
|
+
paths_pruned=0,
|
|
194
|
+
candidates=0,
|
|
195
|
+
skipped=None,
|
|
196
|
+
)
|
|
197
|
+
if len(nodes) > max_nodes:
|
|
198
|
+
report["skipped"] = "node_limit"
|
|
199
|
+
return [], report
|
|
200
|
+
if len(starts) > max_starts:
|
|
201
|
+
report["skipped"] = "start_limit"
|
|
202
|
+
return [], report
|
|
203
|
+
states = defaultdict(list)
|
|
204
|
+
endset = set(ends)
|
|
205
|
+
known = {m.key for m in models}
|
|
206
|
+
found = {}
|
|
207
|
+
for start in starts:
|
|
208
|
+
states[start].append(PathState(0.0, (), 0, (), start))
|
|
209
|
+
for pos in nodes:
|
|
210
|
+
# Retain a bounded beam separately for each initial boundary and codon phase.
|
|
211
|
+
groups = defaultdict(list)
|
|
212
|
+
for state in states.pop(pos, []):
|
|
213
|
+
groups[state.start, state.bases % 3].append(state)
|
|
214
|
+
current = []
|
|
215
|
+
for key, ss in sorted(groups.items()):
|
|
216
|
+
unique = {(s.blocks, s.junctions): s for s in ss}
|
|
217
|
+
ordered = sorted(
|
|
218
|
+
unique.values(), key=lambda s: (-s.score, s.blocks, s.junctions)
|
|
219
|
+
)
|
|
220
|
+
report["paths_pruned"] += max(0, len(ordered) - beam)
|
|
221
|
+
current.extend(ordered[:beam])
|
|
222
|
+
for state in current:
|
|
223
|
+
if pos in endset and state.blocks and state.bases % 3 == 0:
|
|
224
|
+
# End only after coding, never after a splice into a terminal boundary.
|
|
225
|
+
blocks = tuple(sorted(state.blocks))
|
|
226
|
+
terminal = blocks[-1][1] if direction == 1 else blocks[0][0]
|
|
227
|
+
if terminal == pos:
|
|
228
|
+
m = Transcript(
|
|
229
|
+
chrom, strand, blocks, "graph", "graph", 0, blocks, "", "graph"
|
|
230
|
+
)
|
|
231
|
+
if m.key not in known and m.key not in found:
|
|
232
|
+
complete, canonical, _ = genome.assess(m)
|
|
233
|
+
if complete and canonical:
|
|
234
|
+
found[m.key] = (state.score, m)
|
|
235
|
+
for edge in graph.get(pos, ()):
|
|
236
|
+
if edge.kind == "splice":
|
|
237
|
+
a, b = sorted((edge.start, edge.end))
|
|
238
|
+
# Test splice grammar on the actual reference strand via a tiny model.
|
|
239
|
+
if b - a < 4:
|
|
240
|
+
continue
|
|
241
|
+
from Bio.Seq import Seq
|
|
242
|
+
|
|
243
|
+
left, right = genome.fetch(chrom, a, a + 2), genome.fetch(
|
|
244
|
+
chrom, b - 2, b
|
|
245
|
+
)
|
|
246
|
+
if strand == "-":
|
|
247
|
+
left, right = str(Seq(right).reverse_complement()), str(
|
|
248
|
+
Seq(left).reverse_complement()
|
|
249
|
+
)
|
|
250
|
+
if (left, right) not in {("GT", "AG"), ("GC", "AG"), ("AT", "AC")}:
|
|
251
|
+
continue
|
|
252
|
+
for state in current:
|
|
253
|
+
new = _extend(state, edge, strand, molecular_corrections)
|
|
254
|
+
if new is not None:
|
|
255
|
+
if peptide_observations and edge.kind=='coding':
|
|
256
|
+
# Reward only a complete, frame/translation-compatible
|
|
257
|
+
# peptide chain. Its component junctions are not free
|
|
258
|
+
# independent observations that can be recombined.
|
|
259
|
+
from .peptides import peptide_offset
|
|
260
|
+
observed=set(new.observed_peptides)
|
|
261
|
+
relevant=[p for p in peptide_observations if p.sequence not in observed
|
|
262
|
+
and new.blocks and min(a for a,b in new.blocks)<=p.blocks[0][0]
|
|
263
|
+
and max(b for a,b in new.blocks)>=p.blocks[-1][1]]
|
|
264
|
+
if relevant:
|
|
265
|
+
partial=Transcript(chrom,strand,tuple(sorted(new.blocks)),'graph','partial',0)
|
|
266
|
+
bonus=0.
|
|
267
|
+
for peptide in relevant:
|
|
268
|
+
if peptide_offset(partial,peptide) is not None:
|
|
269
|
+
observed.add(peptide.sequence)
|
|
270
|
+
bonus+=3.*len(peptide.sequence)/1000.+.2*(len(peptide.blocks)-1)
|
|
271
|
+
if bonus:
|
|
272
|
+
new=PathState(new.score+bonus,new.blocks,new.bases,new.junctions,
|
|
273
|
+
new.start,tuple(sorted(observed)))
|
|
274
|
+
states[edge.end].append(new)
|
|
275
|
+
ordered = sorted(found.values(), key=lambda x: (-x[0], x[1].key))
|
|
276
|
+
report["candidates_before_limit"] = len(ordered)
|
|
277
|
+
report["candidates"] = min(len(ordered), max_candidates)
|
|
278
|
+
report["paths_pruned"] += max(0, len(ordered) - max_candidates)
|
|
279
|
+
return [m for score, m in ordered[:max_candidates]], report
|