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,19 @@
|
|
|
1
|
+
"""Splice-context qualification of existing original-source quality; no novel-protein q."""
|
|
2
|
+
from .local_molecular import LocalMolecular,frame_at
|
|
3
|
+
from .intervals import merge
|
|
4
|
+
|
|
5
|
+
class IntrinsicSourceMolecular(LocalMolecular):
|
|
6
|
+
def __init__(self,originals,parameters,prior,genome):
|
|
7
|
+
super().__init__(originals,parameters);self.prior=prior;self.genome=genome
|
|
8
|
+
def splice(self,model):
|
|
9
|
+
total=0.;width=self.p['boundary_window_nt']
|
|
10
|
+
for a,b in model.introns:
|
|
11
|
+
factor,_=self.prior.score(self.genome,model,a,b);source={}
|
|
12
|
+
for c in self.originals:
|
|
13
|
+
m=c.model
|
|
14
|
+
if ((m.contig,m.strand)!=(model.contig,model.strand) or (a,b) not in m.introns or frame_at(model,a-1)!=frame_at(m,a-1) or frame_at(model,b)!=frame_at(m,b)):continue
|
|
15
|
+
flanks=merge((max(x,u),min(y,v)) for x,y in m.cds for u,v in ((max(0,a-width),a),(b,b+width)) if max(x,u)<min(y,v))
|
|
16
|
+
value=self.correction(c,flanks)-c.q*(1-factor)
|
|
17
|
+
for s in c.sources:source[s]=max(source.get(s,-float('inf')),value)
|
|
18
|
+
if source:total+=(b-a)*sum(source.values())/len(source)
|
|
19
|
+
return total
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Reference/RNA-free splice-flank prior learned from molecular-qualified consensus.
|
|
2
|
+
Only discounts a positive protein-quality bonus; never supplies an admission vote.
|
|
3
|
+
"""
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from collections import Counter,defaultdict
|
|
6
|
+
import fcntl,hashlib,json,math,os
|
|
7
|
+
import numpy as np
|
|
8
|
+
from Bio.Seq import Seq
|
|
9
|
+
from .local_molecular import frame_at
|
|
10
|
+
from .direct_molecular import DirectMolecular
|
|
11
|
+
from .provenance import sha256,digest_object
|
|
12
|
+
|
|
13
|
+
BASES='ACGT';BINDEX={b:i for i,b in enumerate(BASES)};K=28
|
|
14
|
+
|
|
15
|
+
def context(genome,m,a,b):
|
|
16
|
+
length=genome.lengths[m.contig]
|
|
17
|
+
if m.strand=='+':
|
|
18
|
+
if a<3 or a+6>length or b<20 or b+3>length:return None
|
|
19
|
+
donor=genome.fetch(m.contig,a-3,a+6);acceptor=genome.fetch(m.contig,b-20,b+3)
|
|
20
|
+
else:
|
|
21
|
+
if b<6 or b+3>length or a<3 or a+20>length:return None
|
|
22
|
+
donor=str(Seq(genome.fetch(m.contig,b-6,b+3)).reverse_complement())
|
|
23
|
+
acceptor=str(Seq(genome.fetch(m.contig,a-3,a+20)).reverse_complement())
|
|
24
|
+
family=donor[3:5]+acceptor[18:20]
|
|
25
|
+
if family not in ['GTAG','GCAG','ATAC']:return None
|
|
26
|
+
flanks=donor[:3]+donor[5:]+acceptor[:18]+acceptor[20:]
|
|
27
|
+
if len(flanks)!=K or set(flanks)-set(BASES):return None
|
|
28
|
+
phase=(frame_at(m,a-1 if m.strand=='+' else b)+1)%3
|
|
29
|
+
key='\t'.join(map(str,(m.contig,m.strand,a,b,phase)))
|
|
30
|
+
return key,family+':'+str(phase),flanks
|
|
31
|
+
|
|
32
|
+
def background(genome,genome_sha,cache):
|
|
33
|
+
path=cache/('splice_background_'+genome_sha+'.json')
|
|
34
|
+
with (cache/'.splice_background.lock').open('a') as lock:
|
|
35
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
36
|
+
if path.exists():return json.loads(path.read_text())['probabilities']
|
|
37
|
+
counts=Counter()
|
|
38
|
+
for contig,length in genome.lengths.items():
|
|
39
|
+
for left in range(0,length,1000000):
|
|
40
|
+
seq=genome.fetch(contig,left,min(length,left+1000000))
|
|
41
|
+
counts.update({b:seq.count(b) for b in BASES})
|
|
42
|
+
total=sum(counts.values());p=[(counts[b]+1)/(total+4) for b in BASES]
|
|
43
|
+
path.write_text(json.dumps(dict(genome_sha256=genome_sha,counts=dict(counts),probabilities=p,reference_used=False))+'\n');return p
|
|
44
|
+
|
|
45
|
+
class SplicePrior:
|
|
46
|
+
def __init__(self,record):
|
|
47
|
+
self.record=record;self.bg=np.array(record['background']);self.groups=record['groups'];self.training=set(record['training_keys']);self.memo={}
|
|
48
|
+
def score(self,genome,m,a,b):
|
|
49
|
+
data=context(genome,m,a,b)
|
|
50
|
+
if data is None:return 1.,dict(observed=False,reason='unknown_or_noncanonical_context')
|
|
51
|
+
key,group,flanks=data
|
|
52
|
+
if key in self.memo:return self.memo[key]
|
|
53
|
+
record=self.groups.get(group)
|
|
54
|
+
if not record:return 1.,dict(observed=False,reason='no_qualified_training_sites',group=group)
|
|
55
|
+
counts=np.array(record['counts'],dtype=np.float64);n=record['n'];x=np.array([BINDEX[b] for b in flanks]);leave_out=key in self.training
|
|
56
|
+
if leave_out:counts[np.arange(K),x]-=1;n-=1
|
|
57
|
+
assert (counts>=0).all()
|
|
58
|
+
if n<=0:return 1.,dict(observed=False,reason='no_training_sites_after_leave_one_out',group=group)
|
|
59
|
+
p=(counts+4*self.bg[None,:])/(n+4.)
|
|
60
|
+
lr=float(np.log(p[np.arange(K),x]/self.bg[x]).sum())
|
|
61
|
+
compatibility=1/(1+math.exp(-lr)) if lr>=0 else math.exp(lr)/(1+math.exp(lr))
|
|
62
|
+
reliability=n/(n+4.*K);factor=1-reliability*(1-compatibility)
|
|
63
|
+
assert 0<=factor<=1
|
|
64
|
+
answer=factor,dict(observed=True,group=group,training_sites=n,leave_one_site_out=leave_out,log_likelihood_ratio=lr,compatibility_index=compatibility,reliability=reliability)
|
|
65
|
+
self.memo[key]=answer;return answer
|
|
66
|
+
|
|
67
|
+
def train_or_load(originals,source_models,genome,fingerprints,cache,threshold=.437721461):
|
|
68
|
+
cache=Path(cache);cache.mkdir(parents=True,exist_ok=True)
|
|
69
|
+
# RNA/peptides are deliberately absent from this identity and training data.
|
|
70
|
+
identity=digest_object(dict(genome=fingerprints[str(genome.path)],originals=[(c.uid,sorted(c.sources),c.q,c.complete,c.canonical) for c in sorted(originals,key=lambda c:c.uid)],code=sha256(__file__),minimum_sources=min(2,len(source_models)),threshold=threshold))
|
|
71
|
+
path=cache/('intrinsic_splice_'+identity+'.json')
|
|
72
|
+
with (cache/'.intrinsic_splice.lock').open('a') as lock:
|
|
73
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
74
|
+
if path.exists():
|
|
75
|
+
record=json.loads(path.read_text());assert record['identity']==identity;return SplicePrior(record),path
|
|
76
|
+
min_sources=min(2,len(source_models));sites={};support=defaultdict(set)
|
|
77
|
+
for c in originals:
|
|
78
|
+
if not c.sources or c.q is None or c.q<threshold or not c.complete or not c.canonical:continue
|
|
79
|
+
for a,b in c.model.introns:
|
|
80
|
+
data=context(genome,c.model,a,b)
|
|
81
|
+
if data is None:continue
|
|
82
|
+
key,group,flanks=data;sites[key]=(group,flanks);support[key].update(c.sources)
|
|
83
|
+
groups={};training=[]
|
|
84
|
+
for key in sorted(sites):
|
|
85
|
+
if len(support[key])<min_sources:continue
|
|
86
|
+
group,flanks=sites[key];record=groups.setdefault(group,dict(n=0,counts=np.zeros((K,4),dtype=np.int64)))
|
|
87
|
+
record['n']+=1;record['counts'][np.arange(K),[BINDEX[b] for b in flanks]]+=1;training.append(key)
|
|
88
|
+
for record in groups.values():record['counts']=record['counts'].tolist()
|
|
89
|
+
record=dict(identity=identity,reference_used=False,RNA_training=False,minimum_sources=min_sources,protein_threshold=threshold,background=background(genome,fingerprints[str(genome.path)],cache),positions=K,pseudocount_mass=4,groups=groups,training_keys=training,implementation_sha256=sha256(__file__))
|
|
90
|
+
tmp=path.with_name(path.name+'.tmp.'+str(os.getpid()));tmp.write_text(json.dumps(record,separators=(',',':'))+'\n');os.replace(tmp,path)
|
|
91
|
+
return SplicePrior(record),path
|
|
92
|
+
|
|
93
|
+
def attach(candidates,prior,genome):
|
|
94
|
+
counts=Counter();all_factors=[]
|
|
95
|
+
for c in candidates:
|
|
96
|
+
factors=[]
|
|
97
|
+
for a,b in c.model.introns:
|
|
98
|
+
factor,detail=prior.score(genome,c.model,a,b);factors.append(factor);all_factors.append(factor);counts['measured' if detail['observed'] else 'abstained']+=1
|
|
99
|
+
c.graph_evidence['intrinsic_splice_factors']=factors
|
|
100
|
+
return dict(site_evaluations=dict(counts),mean_factor=float(np.mean(all_factors)) if all_factors else None,training_sites=len(prior.training),groups={k:v['n'] for k,v in prior.groups.items()},reference_used=False,RNA_training=False)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Coding/splice versus noncoding utility, integrated with local path optimization.
|
|
2
|
+
|
|
3
|
+
Uses sparse interval integrals, capped one vote/source. No annotation reference.
|
|
4
|
+
EVM's published-source default coding/noncoding ratio 0.75 is an explicit fixed
|
|
5
|
+
compatibility convention, not a parameter fitted against this benchmark.
|
|
6
|
+
"""
|
|
7
|
+
from collections import defaultdict
|
|
8
|
+
from math import log1p
|
|
9
|
+
from bisect import bisect_left,bisect_right
|
|
10
|
+
from .intervals import merge,intersection_length
|
|
11
|
+
from .molecular import local_risk
|
|
12
|
+
|
|
13
|
+
class StateEvidence:
|
|
14
|
+
def __init__(self,source_models):
|
|
15
|
+
self.source_exons=set()
|
|
16
|
+
coding=defaultdict(list);spans=defaultdict(list);introns=defaultdict(list);oriented=defaultdict(list);exact=defaultdict(set)
|
|
17
|
+
for source,models in source_models.items():
|
|
18
|
+
for m in models:
|
|
19
|
+
self.source_exons.update((m.contig,m.strand,a,b) for a,b in m.cds)
|
|
20
|
+
coding[source,m.contig,m.strand].extend(m.cds)
|
|
21
|
+
spans[source,m.contig].append((m.cds[0][0],m.cds[-1][1]))
|
|
22
|
+
introns[source,m.contig].extend(m.introns)
|
|
23
|
+
oriented[source,m.contig,m.strand].extend(m.introns)
|
|
24
|
+
for iv in m.introns:exact[m.contig,m.strand,iv].add(source)
|
|
25
|
+
self.sources=sorted(source_models);self.exact=exact
|
|
26
|
+
self.oriented_introns=self.index(oriented)
|
|
27
|
+
self.coding=self.index(coding);self.spans=self.index(spans);self.introns=self.index(introns)
|
|
28
|
+
@staticmethod
|
|
29
|
+
def index(data):
|
|
30
|
+
return {k:(iv,tuple(a for a,b in iv),tuple(b for a,b in iv)) for k,blocks in data.items() for iv in [merge(blocks)]}
|
|
31
|
+
@staticmethod
|
|
32
|
+
def integral(index,key,regions):
|
|
33
|
+
record=index.get(key)
|
|
34
|
+
if not record:return 0
|
|
35
|
+
blocks,starts,ends=record;answer=0
|
|
36
|
+
for a,b in regions:
|
|
37
|
+
lo=bisect_right(ends,a);hi=bisect_left(starts,b)
|
|
38
|
+
answer+=intersection_length(((a,b),),blocks[lo:hi])
|
|
39
|
+
return answer
|
|
40
|
+
def features(self,c,peptides,support,p):
|
|
41
|
+
m=c.model;span=((m.cds[0][0],m.cds[-1][1]),);genomic=span[0][1]-span[0][0]
|
|
42
|
+
coding=sum(self.integral(self.coding,(s,m.contig,m.strand),m.cds) for s in self.sources)
|
|
43
|
+
splice=sum((b-a)*len(self.exact.get((m.contig,m.strand,(a,b)),())) for a,b in m.introns)
|
|
44
|
+
intergenic=sum(genomic-self.integral(self.spans,(s,m.contig),span) for s in self.sources)
|
|
45
|
+
intronic=sum(self.integral(self.introns,(s,m.contig),m.cds) for s in self.sources)
|
|
46
|
+
# Contradiction over intronic sequence includes only nonmatching splice states.
|
|
47
|
+
# Exact same-strand introns offset their own noncoding contribution.
|
|
48
|
+
rival_intron=0
|
|
49
|
+
for source in self.sources:
|
|
50
|
+
covered=self.integral(self.introns,(source,m.contig),m.introns)
|
|
51
|
+
shared=sum(b-a for a,b in m.introns if source in self.exact.get((m.contig,m.strand,(a,b)),()))
|
|
52
|
+
rival_intron+=max(0,covered-shared)
|
|
53
|
+
# Intergenic absence is relevant to candidate coding, not its declared introns.
|
|
54
|
+
absent_coding=sum(m.length-self.integral(self.spans,(s,m.contig),m.cds) for s in self.sources)
|
|
55
|
+
noncoding=absent_coding+intronic+rival_intron
|
|
56
|
+
risk,known=local_risk(c,m.cds,p['localizer_gate']);q=c.q*(1-p['risk_strength']*(risk if known else 0)) if c.q is not None else 0.
|
|
57
|
+
pep=len(c.peptides)/(len(c.peptides)+p['peptide_saturation']);rna=support.rna_score(m);protein=support.protein_score(m)
|
|
58
|
+
# Bounded per-model optional channels in coding-base equivalents.
|
|
59
|
+
weak_coding=weak_splice=0.
|
|
60
|
+
rna_geometry=bool(support.rna_blocks)
|
|
61
|
+
rna_coding=support.rna_coding_overlap(m) if rna_geometry else 0
|
|
62
|
+
rna_splice=sum((b-a)*n/(n+3.) for a,b in m.introns for n in [support.rna_count(m,(a,b))] if n>=p['minimum_rna_templates']) if rna_geometry else 0.
|
|
63
|
+
rna_utility=rna_coding+rna_splice if rna_geometry else m.length*rna
|
|
64
|
+
if p['selection_policy'] in ('state_rna_counts','state_rna_log','state_gap','state_gap_soft','state_admitted','state_coherent','state_soft_admitted','state_splice_validated','state_rna_corroborated'):
|
|
65
|
+
transform = log1p if p['selection_policy']=='state_rna_log' else float
|
|
66
|
+
rna_coding=sum((b-a)*transform(support.rna_exon_counts.get((m.contig,m.strand,a,b),0)) for a,b in m.cds)
|
|
67
|
+
rna_splice=sum((b-a)*transform(support.rna_chain_counts.get((m.contig,m.strand,a,b),0)) for a,b in m.introns if support.rna_count(m,(a,b))>=p['minimum_rna_templates'])
|
|
68
|
+
if p['selection_policy']=='state_rna_corroborated':
|
|
69
|
+
old_rna_coding,old_rna_splice=rna_coding,rna_splice
|
|
70
|
+
# Weak positive RNA can corroborate an independently predicted
|
|
71
|
+
# exact exon/junction; discovery and physical splice guards stay strict.
|
|
72
|
+
rna_coding=sum((b-a)*(support.rna_exon_counts_all.get((m.contig,m.strand,a,b),0) if (m.contig,m.strand,a,b) in self.source_exons else support.rna_exon_counts.get((m.contig,m.strand,a,b),0)) for a,b in m.cds)
|
|
73
|
+
rna_splice=sum((b-a)*support.rna_chain_counts.get((m.contig,m.strand,a,b),0) for a,b in m.introns if self.exact.get((m.contig,m.strand,(a,b))) or support.rna_count(m,(a,b))>=p['minimum_rna_templates'])
|
|
74
|
+
if p['selection_policy']=='state_rna_corroborated':weak_coding,weak_splice=rna_coding-old_rna_coding,rna_splice-old_rna_splice
|
|
75
|
+
rna_utility=rna_coding+rna_splice
|
|
76
|
+
# A peptide supports its translated blocks, never the full protein length.
|
|
77
|
+
# Union prevents overlapping peptides and repeated sequences inflating coverage.
|
|
78
|
+
peptide_blocks=merge([iv for seq in c.peptides for iv in peptides[seq].blocks])
|
|
79
|
+
peptide_nt=intersection_length(m.cds,peptide_blocks)
|
|
80
|
+
peptide_junctions={ (left[1],right[0]) for seq in c.peptides for left,right in zip(peptides[seq].blocks,peptides[seq].blocks[1:]) }
|
|
81
|
+
peptide_splice=sum(b-a for a,b in m.introns if (a,b) in peptide_junctions)
|
|
82
|
+
extra=m.length*(p['molecular_weight']*q+p['protein_weight']*protein)+p['peptide_weight']*(peptide_nt+peptide_splice)+p['rna_weight']*rna_utility
|
|
83
|
+
# Two predeclared hypotheses: signed state utility vs EVM-like ratio admission.
|
|
84
|
+
positive=coding+splice+extra
|
|
85
|
+
opposite='-' if m.strand=='+' else '+'
|
|
86
|
+
opposite_intronic=sum(self.integral(self.oriented_introns,(source,m.contig,opposite),m.introns) for source in self.sources)
|
|
87
|
+
equivalent_noncoding=absent_coding+intronic+opposite_intronic+splice
|
|
88
|
+
admitted=positive>=.75*equivalent_noncoding and m.length>=p.get('minimum_coding_nt',150)
|
|
89
|
+
if p['selection_policy'] in ('state_gap','state_gap_soft','state_admitted','state_coherent','state_soft_admitted','state_splice_validated','state_rna_corroborated'):
|
|
90
|
+
utility=positive-(.75 if p['selection_policy'] in ('state_gap_soft','state_soft_admitted','state_splice_validated','state_rna_corroborated') else 1.)*intergenic
|
|
91
|
+
# Preserve supplied hypotheses in exact evidence-neutral ties.
|
|
92
|
+
if abs(utility)<1e-9 and c.sources:utility=1e-6
|
|
93
|
+
elif p['selection_policy'] in ('state_signed','state_rna_counts','state_rna_log'):utility=positive-.75*noncoding
|
|
94
|
+
else:utility=positive if positive>=.75*noncoding else 0.
|
|
95
|
+
if p['selection_policy'] in ('state_admitted','state_coherent','state_soft_admitted','state_splice_validated','state_rna_corroborated') and not admitted:utility=0.
|
|
96
|
+
return dict(rna_weak_corroboration_coding=weak_coding,rna_weak_corroboration_splice=weak_splice,equivalent_noncoding=equivalent_noncoding,coding_noncoding_ratio=positive/max(equivalent_noncoding,1e-12),admitted=admitted,coding_support=coding,exact_splice_support=splice,absent_coding=absent_coding,intronic_contradiction=intronic,rival_intron=rival_intron,noncoding=noncoding,whole_span_intergenic_opportunity_cost=intergenic,optional_base_equivalents=extra,rna_observed_coding=rna_coding,rna_observed_splice=rna_splice,molecular=q,peptide=pep,peptide_supported_nt=peptide_nt,peptide_supported_splice=peptide_splice,rna=rna,protein=protein,utility=max(0.,utility),unclipped_utility=utility)
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Bounded structural support from optional RNA/protein evidence."""
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
import json, math, bisect
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from .intervals import merge, intersection_length
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Support:
|
|
10
|
+
def __init__(self, rna=None, proteins=(), min_rna_templates=3):
|
|
11
|
+
self.min_rna_templates = min_rna_templates
|
|
12
|
+
self.rna = {}
|
|
13
|
+
self.rna_blocks = {}
|
|
14
|
+
self.rna_internal = {}
|
|
15
|
+
self.rna_exon_counts = {}
|
|
16
|
+
self.rna_exon_counts_all = {}
|
|
17
|
+
self.rna_chain_counts = {}
|
|
18
|
+
self.rna_block_starts = {}
|
|
19
|
+
self.rna_block_ends = {}
|
|
20
|
+
self.protein_introns = set()
|
|
21
|
+
self.protein_exon_frames = set()
|
|
22
|
+
self.protein_blocks = {}
|
|
23
|
+
self.rna_bins = defaultdict(set)
|
|
24
|
+
self.protein_bins = defaultdict(set)
|
|
25
|
+
if rna:
|
|
26
|
+
data = (
|
|
27
|
+
json.loads(Path(rna).read_text())
|
|
28
|
+
if isinstance(rna, (str, Path))
|
|
29
|
+
else rna
|
|
30
|
+
)
|
|
31
|
+
if data.get("coordinate_system") != "0-based-half-open":
|
|
32
|
+
raise ValueError(
|
|
33
|
+
"RNA junctions must specify 0-based-half-open coordinates"
|
|
34
|
+
)
|
|
35
|
+
rb=defaultdict(list);ri=defaultdict(list)
|
|
36
|
+
for field,target in [('alignment_blocks',rb),('observed_internal_exons',ri)]:
|
|
37
|
+
for chrom,a,b,strand in data.get(field,[]):
|
|
38
|
+
if chrom not in data['references'] or strand not in ('+','-') or not isinstance(a,int) or not isinstance(b,int) or not 0<=a<b<=data['references'][chrom]:raise ValueError('Invalid RNA observed-block geometry')
|
|
39
|
+
target[chrom,strand].append((a,b))
|
|
40
|
+
self.rna_blocks={key:merge(v) for key,v in rb.items()}
|
|
41
|
+
self.rna_internal={key:tuple(sorted(set(v))) for key,v in ri.items()}
|
|
42
|
+
self.rna_block_starts={k:tuple(a for a,b in v) for k,v in self.rna_blocks.items()}
|
|
43
|
+
self.rna_block_ends={k:tuple(b for a,b in v) for k,v in self.rna_blocks.items()}
|
|
44
|
+
for field,target in [('observed_internal_exon_counts',self.rna_exon_counts),('rna_chain_junctions',self.rna_chain_counts),('observed_internal_exon_counts_all',self.rna_exon_counts_all)]:
|
|
45
|
+
for chrom,a,b,strand,n in data.get(field,[]):
|
|
46
|
+
if chrom not in data['references'] or strand not in ('+','-') or not 0<=a<b<=data['references'][chrom] or not isinstance(n,int) or n<1:
|
|
47
|
+
raise ValueError('Invalid RNA structure count')
|
|
48
|
+
key=(chrom,strand,a,b)
|
|
49
|
+
target[key]=max(target.get(key,0),n)
|
|
50
|
+
if 'observed_internal_exon_counts_all' in data and any(self.rna_exon_counts_all.get(k,0)<n for k,n in self.rna_exon_counts.items()):
|
|
51
|
+
raise ValueError('Unfiltered RNA exon counts must include every filtered exon count')
|
|
52
|
+
for chrom, a, b, strand, n in data["junctions"]:
|
|
53
|
+
if (
|
|
54
|
+
strand not in ("+", "-", ".")
|
|
55
|
+
or not 0 <= a < b
|
|
56
|
+
or not isinstance(n, int)
|
|
57
|
+
or n < 1
|
|
58
|
+
):
|
|
59
|
+
raise ValueError("Invalid RNA junction record")
|
|
60
|
+
key = (chrom, strand, a, b)
|
|
61
|
+
# Duplicate rows are not independent observations.
|
|
62
|
+
self.rna[key] = max(self.rna.get(key, 0), n)
|
|
63
|
+
self.rna_bins[chrom, a // 10000].add(key)
|
|
64
|
+
blocks = defaultdict(list)
|
|
65
|
+
seen = set()
|
|
66
|
+
for model in proteins:
|
|
67
|
+
if model.key in seen:
|
|
68
|
+
continue
|
|
69
|
+
seen.add(model.key)
|
|
70
|
+
used=-model.phase
|
|
71
|
+
for iv in (model.cds if model.strand=='+' else reversed(model.cds)):
|
|
72
|
+
self.protein_exon_frames.add((model.contig,model.strand,iv,used%3))
|
|
73
|
+
used+=iv[1]-iv[0]
|
|
74
|
+
|
|
75
|
+
blocks[model.contig, model.strand].extend(model.cds)
|
|
76
|
+
self.protein_introns.update(
|
|
77
|
+
(model.contig, model.strand, a, b) for a, b in model.introns
|
|
78
|
+
)
|
|
79
|
+
for chrom, strand, a, b in self.protein_introns:
|
|
80
|
+
self.protein_bins[chrom, strand, a // 10000].add((a, b))
|
|
81
|
+
self.protein_blocks = {key: merge(v) for key, v in blocks.items()}
|
|
82
|
+
self.protein_starts = {
|
|
83
|
+
k: [a for a, b in v] for k, v in self.protein_blocks.items()
|
|
84
|
+
}
|
|
85
|
+
self.protein_ends = {
|
|
86
|
+
k: [b for a, b in v] for k, v in self.protein_blocks.items()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
def rna_coding_overlap(self, model):
|
|
90
|
+
key = (model.contig, model.strand)
|
|
91
|
+
blocks = self.rna_blocks.get(key, ())
|
|
92
|
+
if not blocks:
|
|
93
|
+
return 0
|
|
94
|
+
left = bisect.bisect_right(self.rna_block_ends[key], model.cds[0][0])
|
|
95
|
+
right = bisect.bisect_left(self.rna_block_starts[key], model.cds[-1][1])
|
|
96
|
+
return intersection_length(model.cds, blocks[left:right])
|
|
97
|
+
|
|
98
|
+
def rna_count(self, model, iv):
|
|
99
|
+
a, b = iv
|
|
100
|
+
return max(
|
|
101
|
+
self.rna.get((model.contig, model.strand, a, b), 0),
|
|
102
|
+
self.rna.get((model.contig, ".", a, b), 0),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
def rna_score(self, model, introns=None):
|
|
106
|
+
ivs = model.introns if introns is None else tuple(introns)
|
|
107
|
+
if not ivs:
|
|
108
|
+
return 0.0
|
|
109
|
+
return sum(
|
|
110
|
+
(n / (n + 3.0) if n >= self.min_rna_templates else 0.0)
|
|
111
|
+
for n in (self.rna_count(model, iv) for iv in ivs)
|
|
112
|
+
) / len(ivs)
|
|
113
|
+
|
|
114
|
+
def protein_score(self, model, regions=None):
|
|
115
|
+
intervals = model.cds if regions is None else tuple(regions)
|
|
116
|
+
size = sum(b - a for a, b in intervals)
|
|
117
|
+
key = (model.contig, model.strand)
|
|
118
|
+
blocks = self.protein_blocks.get(key, ())
|
|
119
|
+
if intervals and blocks:
|
|
120
|
+
first = bisect.bisect_right(
|
|
121
|
+
self.protein_ends[key], min(a for a, b in intervals)
|
|
122
|
+
)
|
|
123
|
+
last = bisect.bisect_left(
|
|
124
|
+
self.protein_starts[key], max(b for a, b in intervals)
|
|
125
|
+
)
|
|
126
|
+
blocks = blocks[first:last]
|
|
127
|
+
coverage = intersection_length(merge(intervals), blocks) / size if size else 0.0
|
|
128
|
+
ivs = model.introns
|
|
129
|
+
junctions = (
|
|
130
|
+
sum(
|
|
131
|
+
(model.contig, model.strand, a, b) in self.protein_introns
|
|
132
|
+
for a, b in ivs
|
|
133
|
+
)
|
|
134
|
+
/ len(ivs)
|
|
135
|
+
if ivs
|
|
136
|
+
else coverage
|
|
137
|
+
)
|
|
138
|
+
return (coverage + junctions) / 2
|
|
139
|
+
|
|
140
|
+
def supported_junction(self, model, iv, predictor_votes=None):
|
|
141
|
+
a, b = iv
|
|
142
|
+
return (
|
|
143
|
+
(predictor_votes or {}).get((model.contig, model.strand, a, b), 0) >= 2
|
|
144
|
+
or self.rna_count(model, iv) >= self.min_rna_templates
|
|
145
|
+
or (model.contig, model.strand, a, b) in self.protein_introns
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
def graph_junctions(self, models):
|
|
149
|
+
if not models:
|
|
150
|
+
return []
|
|
151
|
+
m = models[0]
|
|
152
|
+
lo = min(x.cds[0][0] for x in models)
|
|
153
|
+
hi = max(x.cds[-1][1] for x in models)
|
|
154
|
+
keys = set()
|
|
155
|
+
out = []
|
|
156
|
+
for k in range(lo // 10000, (hi - 1) // 10000 + 1):
|
|
157
|
+
keys.update(self.rna_bins[m.contig, k])
|
|
158
|
+
for chrom, strand, a, b in sorted(keys):
|
|
159
|
+
n = self.rna[chrom, strand, a, b]
|
|
160
|
+
if (
|
|
161
|
+
strand in (".", m.strand)
|
|
162
|
+
and lo <= a < b <= hi
|
|
163
|
+
and n >= self.min_rna_templates
|
|
164
|
+
):
|
|
165
|
+
out.append((a, b, n / (n + 3.0), "rna"))
|
|
166
|
+
keys = set()
|
|
167
|
+
for k in range(lo // 10000, (hi - 1) // 10000 + 1):
|
|
168
|
+
keys.update(self.protein_bins[m.contig, m.strand, k])
|
|
169
|
+
out.extend((a, b, 0.5, "protein") for a, b in sorted(keys) if lo <= a < b <= hi)
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
def graph_segments(self, models):
|
|
173
|
+
if not models:
|
|
174
|
+
return []
|
|
175
|
+
m = models[0]
|
|
176
|
+
lo = min(x.cds[0][0] for x in models)
|
|
177
|
+
hi = max(x.cds[-1][1] for x in models)
|
|
178
|
+
key = (m.contig, m.strand)
|
|
179
|
+
blocks = self.protein_blocks.get(key, ())
|
|
180
|
+
rna_segments=[(max(lo,a),min(hi,b),'rna') for a,b in self.rna_internal.get(key,()) if max(lo,a)<min(hi,b)]
|
|
181
|
+
if not blocks:
|
|
182
|
+
return rna_segments
|
|
183
|
+
first = bisect.bisect_right(self.protein_ends[key], lo)
|
|
184
|
+
last = bisect.bisect_left(self.protein_starts[key], hi)
|
|
185
|
+
return rna_segments + [
|
|
186
|
+
(max(lo, a), min(hi, b), "protein")
|
|
187
|
+
for a, b in blocks[first:last]
|
|
188
|
+
if max(lo, a) < min(hi, b)
|
|
189
|
+
]
|