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,104 @@
|
|
|
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,molecular_states=None):
|
|
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_molecular_guided'):
|
|
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_molecular_guided':
|
|
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_molecular_guided':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
|
+
if p.get('peptide_strategy','legacy') != 'legacy' and hasattr(peptides,'features'):
|
|
83
|
+
peptide_nt,peptide_splice,peptide_sequences=peptides.features(c,
|
|
84
|
+
ambiguous=p['peptide_strategy'] != 'bounded_unique')
|
|
85
|
+
pep=peptide_sequences/(peptide_sequences+p['peptide_saturation'])
|
|
86
|
+
molecular_coding,molecular_splice=molecular_states.features(m) if molecular_states is not None else (m.length*q,0.)
|
|
87
|
+
extra=p['molecular_weight']*(molecular_coding+molecular_splice)+m.length*p['protein_weight']*protein+p['peptide_weight']*(peptide_nt+peptide_splice)+p['rna_weight']*rna_utility
|
|
88
|
+
# Two predeclared hypotheses: signed state utility vs EVM-like ratio admission.
|
|
89
|
+
positive=coding+splice+extra
|
|
90
|
+
opposite='-' if m.strand=='+' else '+'
|
|
91
|
+
opposite_intronic=sum(self.integral(self.oriented_introns,(source,m.contig,opposite),m.introns) for source in self.sources)
|
|
92
|
+
equivalent_noncoding=absent_coding+intronic+opposite_intronic+splice
|
|
93
|
+
# Protein plausibility qualifies supplied states, but adds no independent
|
|
94
|
+
# structural observation capable of satisfying structural admission.
|
|
95
|
+
admission_positive=coding+splice+m.length*p['protein_weight']*protein+p['peptide_weight']*(peptide_nt+peptide_splice)+p['rna_weight']*rna_utility
|
|
96
|
+
admitted=admission_positive>=.75*equivalent_noncoding and m.length>=p.get('minimum_coding_nt',150)
|
|
97
|
+
if p['selection_policy'] in ('state_gap','state_gap_soft','state_admitted','state_coherent','state_soft_admitted','state_splice_validated','state_molecular_guided'):
|
|
98
|
+
utility=positive-(.75 if p['selection_policy'] in ('state_gap_soft','state_soft_admitted','state_splice_validated','state_molecular_guided') else 1.)*intergenic
|
|
99
|
+
# Preserve supplied hypotheses in exact evidence-neutral ties.
|
|
100
|
+
if abs(utility)<1e-9 and c.sources:utility=1e-6
|
|
101
|
+
elif p['selection_policy'] in ('state_signed','state_rna_counts','state_rna_log'):utility=positive-.75*noncoding
|
|
102
|
+
else:utility=positive if positive>=.75*noncoding else 0.
|
|
103
|
+
if p['selection_policy'] in ('state_admitted','state_coherent','state_soft_admitted','state_splice_validated','state_molecular_guided') and not admitted:utility=0.
|
|
104
|
+
return dict(admission_positive_evidence=admission_positive,molecular_counts_for_admission=False,molecular_measured_candidate_q=c.q,molecular_source_context_coding=molecular_coding,molecular_source_context_splice=molecular_splice,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=(molecular_coding+molecular_splice)/max(m.length,1),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,83 @@
|
|
|
1
|
+
"""Optional original-protein diagnostics and self-supervised genomic splice context.
|
|
2
|
+
No protein encoder, reference annotation, or target-trained selector is required.
|
|
3
|
+
"""
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import csv,gzip,hashlib,math
|
|
6
|
+
|
|
7
|
+
LOCALIZABLE={'chimeric','splice_artifact','terminal_abnormal'}
|
|
8
|
+
ALIASES={'spurious_orf':'cryptic_orf','spurious_orfs':'cryptic_orf','spuriousorf':'cryptic_orf','spuriousorfs':'cryptic_orf','splice':'splice_artifact','terminal':'terminal_abnormal'}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def read_diagnostics(path):
|
|
12
|
+
opener=gzip.open if str(path).endswith('.gz') else open;rows={}
|
|
13
|
+
with opener(path,'rt') as f:
|
|
14
|
+
reader=csv.DictReader(f,delimiter='\t')
|
|
15
|
+
required={'protein_id','diagnostic_class','diagnostic_class_probability'}
|
|
16
|
+
if not reader.fieldnames or not required.issubset(reader.fieldnames):raise ValueError('Diagnostics require protein_id, diagnostic_class and diagnostic_class_probability')
|
|
17
|
+
for row in reader:
|
|
18
|
+
ident=row['protein_id'];category=row['diagnostic_class'].strip().lower().replace(' ','_').replace('-','_')
|
|
19
|
+
category=ALIASES.get(category,category)
|
|
20
|
+
if not ident or category not in LOCALIZABLE|{'cryptic_orf',''}:raise ValueError('Invalid diagnostic ID/class: '+ident)
|
|
21
|
+
probability=float(row['diagnostic_class_probability']) if category else None
|
|
22
|
+
if category and (not math.isfinite(probability) or not 0<=probability<=1):raise ValueError('Invalid diagnostic posterior: '+ident)
|
|
23
|
+
if row.get('binary_call')=='positive' and category:raise ValueError('Binary-positive proteins must not carry negative diagnostic classes')
|
|
24
|
+
value=(category,probability)
|
|
25
|
+
if ident in rows and rows[ident]!=value:raise ValueError('Conflicting duplicate diagnostic ID: '+ident)
|
|
26
|
+
rows[ident]=value
|
|
27
|
+
if not rows:raise ValueError('Empty diagnostic table')
|
|
28
|
+
return rows
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def prepare(candidates,source_models,config,genome,fingerprints,cache,support):
|
|
32
|
+
p=config['parameters'];strategy=p['molecular_strategy']
|
|
33
|
+
report=dict(strategy=strategy,enabled=False,reference_used=False,reference_trained=False,trained=False,new_protein_encoding=False,new_protein_localization=False)
|
|
34
|
+
if strategy=='source_context':return candidates,source_models,None,report,[],[]
|
|
35
|
+
originals=[c for c in candidates if c.sources]
|
|
36
|
+
if not any(c.q is not None for c in originals):
|
|
37
|
+
report['reason']='no_original_protein_scores';return candidates,source_models,None,report,[],[]
|
|
38
|
+
threshold=p['localizer_gate'];assert threshold is not None
|
|
39
|
+
tables={};sequence_hash={};observations={};matched=0;missing=0;source_matches={}
|
|
40
|
+
for source,models in source_models.items():
|
|
41
|
+
spec=config['predictions'][source];path=spec.get('diagnostics')
|
|
42
|
+
if path and path not in tables:tables[path]=read_diagnostics(path)
|
|
43
|
+
table=tables.get(path,{});source_matched=0
|
|
44
|
+
for model in models:
|
|
45
|
+
value=table.get(model.identifier)
|
|
46
|
+
if value is None and table:
|
|
47
|
+
if model.key not in sequence_hash:
|
|
48
|
+
aa=genome.assess(model)[2].rstrip('*');sequence_hash[model.key]=hashlib.sha256(aa.encode()).hexdigest()
|
|
49
|
+
value=table.get(sequence_hash[model.key])
|
|
50
|
+
observations[source,model.identifier]=value
|
|
51
|
+
matched+=value is not None;missing+=value is None;source_matched+=value is not None
|
|
52
|
+
source_matches[source]=dict(provided=bool(path),matched=source_matched,unobserved=len(models)-source_matched)
|
|
53
|
+
if path and models and not source_matched:raise ValueError("No diagnostic identifiers or sequence hashes match source: "+source)
|
|
54
|
+
labels={};allowed_tracks=set();eligible_profiles=0;abstained_profiles=0
|
|
55
|
+
for c in originals:
|
|
56
|
+
values=[observations.get((source,ident)) for source,ids in c.original_ids.items() for ident in ids]
|
|
57
|
+
observed=[v for v in values if v is not None and v[0]]
|
|
58
|
+
# A whole-model veto requires agreement of the supplied diagnostic calls.
|
|
59
|
+
if observed and len(observed)==len(values) and len({v[0] for v in observed})==1:
|
|
60
|
+
labels[c.uid]=(observed[0][0],min(v[1] for v in observed))
|
|
61
|
+
else:labels[c.uid]=('',0.)
|
|
62
|
+
retained=[]
|
|
63
|
+
for track in c.risks:
|
|
64
|
+
m=track.model;value=observations.get((m.source,m.identifier))
|
|
65
|
+
if value and value[0] in LOCALIZABLE and track.q is not None and track.q<threshold:
|
|
66
|
+
retained.append(track);allowed_tracks.add(id(track));eligible_profiles+=1
|
|
67
|
+
else:abstained_profiles+=1
|
|
68
|
+
c.risks=retained
|
|
69
|
+
for c in candidates:
|
|
70
|
+
if not c.sources:c.risks=[r for r in c.risks if id(getattr(r,'track',r)) in allowed_tracks]
|
|
71
|
+
from .splice_prior import train_or_load
|
|
72
|
+
from .source_splice import IntrinsicSourceMolecular
|
|
73
|
+
prior,prior_path=train_or_load(originals,source_models,genome,fingerprints,cache,threshold=threshold)
|
|
74
|
+
events=[];vetoed=[];orf_report=dict(vetoed_originals=0)
|
|
75
|
+
if strategy=='splice_orf':
|
|
76
|
+
from .orf_diagnostics import classify
|
|
77
|
+
rejected,orf_report,events=classify(originals,labels,support,p,'conflict_orf_veto')
|
|
78
|
+
vetoed=[c.model for c in originals if c.uid in rejected];keys={m.key for m in vetoed}
|
|
79
|
+
source_models={source:[m for m in models if m.key not in keys] for source,models in source_models.items()}
|
|
80
|
+
candidates=[c for c in candidates if c.uid not in rejected]
|
|
81
|
+
def factory(local_originals,parameters):return IntrinsicSourceMolecular(local_originals,parameters,prior,genome)
|
|
82
|
+
report.update(enabled=True,trained=bool(prior.training),training_scope='genomic splice-flank frequencies from input-predictor consensus qualified by frozen protein scores; no RNA or reference labels',training_sites=len(prior.training),training_groups={k:v['n'] for k,v in prior.groups.items()},prior_cache=str(prior_path),diagnostic_sources=source_matches,diagnostic_matches=matched,diagnostic_unobserved=missing,eligible_original_profiles=eligible_profiles,abstained_original_profiles=abstained_profiles,orf_diagnostic=orf_report)
|
|
83
|
+
return candidates,source_models,factory,report,events,vetoed
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""CDS frame validation against supplied predictor proteins, never reference genes."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import replace
|
|
4
|
+
from Bio import SeqIO
|
|
5
|
+
from Bio.Seq import Seq
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def normalize_phases(source_models, specs, genome):
|
|
9
|
+
report = {}
|
|
10
|
+
for source, models in source_models.items():
|
|
11
|
+
spec = specs[source]
|
|
12
|
+
proteins = {}
|
|
13
|
+
if spec.get("protein_fasta"):
|
|
14
|
+
for record in SeqIO.parse(spec["protein_fasta"], "fasta"):
|
|
15
|
+
seq = str(record.seq).upper().rstrip("*")
|
|
16
|
+
if record.id in proteins and proteins[record.id] != seq:
|
|
17
|
+
raise ValueError(
|
|
18
|
+
f"Ambiguous predictor protein ID: {source}:{record.id}"
|
|
19
|
+
)
|
|
20
|
+
proteins[record.id] = seq
|
|
21
|
+
elif spec.get("residue_profiles"):
|
|
22
|
+
try:
|
|
23
|
+
import h5py
|
|
24
|
+
except ImportError as exc:
|
|
25
|
+
raise RuntimeError(
|
|
26
|
+
"Residue profiles require genesensus[molecular]"
|
|
27
|
+
) from exc
|
|
28
|
+
with h5py.File(spec["residue_profiles"], "r") as h:
|
|
29
|
+
idkey = next((k for k in ["protein_id", "protein_ids"] if k in h), None)
|
|
30
|
+
if idkey and "sequence" in h:
|
|
31
|
+
proteins = {
|
|
32
|
+
i: s.upper().rstrip("*")
|
|
33
|
+
for i, s in zip(h[idkey].asstr()[:], h["sequence"].asstr()[:])
|
|
34
|
+
}
|
|
35
|
+
corrected = []
|
|
36
|
+
missing = 0
|
|
37
|
+
for i, m in enumerate(models):
|
|
38
|
+
expected = proteins.get(m.identifier)
|
|
39
|
+
if expected is None:
|
|
40
|
+
missing += 1
|
|
41
|
+
continue
|
|
42
|
+
dna = genome.coding_sequence(m)
|
|
43
|
+
|
|
44
|
+
def translate(phase):
|
|
45
|
+
s = dna[phase:]
|
|
46
|
+
return str(Seq(s[: len(s) // 3 * 3]).translate()).rstrip("*")
|
|
47
|
+
|
|
48
|
+
if translate(m.phase) == expected:
|
|
49
|
+
continue
|
|
50
|
+
alternatives = [p for p in range(3) if translate(p) == expected]
|
|
51
|
+
if len(alternatives) != 1:
|
|
52
|
+
raise ValueError(
|
|
53
|
+
f"Predictor protein/genome sequence mismatch or ambiguous frame: {source}:{m.identifier}"
|
|
54
|
+
)
|
|
55
|
+
new = replace(m, phase=alternatives[0])
|
|
56
|
+
models[i] = new
|
|
57
|
+
corrected.append(
|
|
58
|
+
dict(
|
|
59
|
+
identifier=m.identifier,
|
|
60
|
+
contig=m.contig,
|
|
61
|
+
old_phase=m.phase,
|
|
62
|
+
new_phase=new.phase,
|
|
63
|
+
reason="unique_translation_match_to_supplied_predictor_protein",
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
report[source] = dict(
|
|
67
|
+
frame_repairs=corrected,
|
|
68
|
+
proteins_missing_for_frame_validation=missing,
|
|
69
|
+
supplied_protein_sequences=len(proteins),
|
|
70
|
+
)
|
|
71
|
+
return report
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Conservative whole-ORF diagnostic hypotheses; reference-free, source-counted."""
|
|
2
|
+
from collections import defaultdict,Counter
|
|
3
|
+
from .graph import loci
|
|
4
|
+
from .intervals import overlap
|
|
5
|
+
from .local_molecular import frame_at
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def classify(originals,diagnostics,support,p,arm):
|
|
9
|
+
assert arm in ['isolated_orf_veto','conflict_orf_veto']
|
|
10
|
+
bykey={c.model.key:c for c in originals};components=[]
|
|
11
|
+
for models in loci([c.model for c in originals]):
|
|
12
|
+
cc=[bykey[m.key] for m in models];parent=list(range(len(cc)))
|
|
13
|
+
def root(i):
|
|
14
|
+
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
|
|
15
|
+
return i
|
|
16
|
+
for i,c in enumerate(cc):
|
|
17
|
+
for j in range(i):
|
|
18
|
+
if overlap(c.model.cds,cc[j].model.cds):parent[root(i)]=root(j)
|
|
19
|
+
groups=defaultdict(list)
|
|
20
|
+
for i,c in enumerate(cc):groups[root(i)].append(c)
|
|
21
|
+
components.extend(groups.values())
|
|
22
|
+
rejected=set();events=[];stats=Counter()
|
|
23
|
+
for cc in components:
|
|
24
|
+
sources=set().union(*(c.sources for c in cc));eligible={};protected={}
|
|
25
|
+
for c in cc:
|
|
26
|
+
category,posterior=diagnostics.get(c.uid,('',0.))
|
|
27
|
+
eligible[c.uid]=bool(c.gene_scores and all(q<p['localizer_gate'] for q in c.gene_scores) and category=='cryptic_orf' and posterior>.5)
|
|
28
|
+
reasons=[]
|
|
29
|
+
if len(c.sources)>=2:reasons.append('multiple_predictors_exact_model')
|
|
30
|
+
m=c.model
|
|
31
|
+
for other in cc:
|
|
32
|
+
if not(other.sources-c.sources):continue
|
|
33
|
+
n=other.model
|
|
34
|
+
if m.introns and m.introns==n.introns:reasons.append('multiple_predictors_intron_chain');break
|
|
35
|
+
if not m.introns and not n.introns:
|
|
36
|
+
a,b=m.cds[0];x,y=n.cds[0]
|
|
37
|
+
if ((a<=x and y<=b) or (x<=a and b<=y)) and frame_at(m,max(a,x))==frame_at(n,max(a,x)):
|
|
38
|
+
reasons.append('multiple_predictors_nested_same_frame_coding');break
|
|
39
|
+
peptide_evidence=getattr(support,'peptide_evidence',None)
|
|
40
|
+
peptide_positive=(peptide_evidence.strong_translation(c)
|
|
41
|
+
if peptide_evidence is not None and hasattr(peptide_evidence,'strong_translation')
|
|
42
|
+
else bool(c.peptides))
|
|
43
|
+
if peptide_positive:reasons.append('positive_peptide')
|
|
44
|
+
if any(support.rna_count(m,iv)>=p['minimum_rna_templates'] for iv in m.introns):reasons.append('positive_exact_rna_junction')
|
|
45
|
+
if any(support.rna_exon_counts_all.get((m.contig,m.strand,a,b),0)>=p['minimum_rna_templates'] for a,b in m.cds):reasons.append('positive_exact_rna_exon')
|
|
46
|
+
if any((m.contig,m.strand,a,b) in getattr(support,'protein_introns',set()) for a,b in m.introns):reasons.append('positive_exact_protein_alignment_junction')
|
|
47
|
+
if not m.introns and hasattr(support,'protein_score') and support.protein_score(m)==1.:reasons.append('complete_protein_alignment_coverage')
|
|
48
|
+
protected[c.uid]=reasons
|
|
49
|
+
all_bad=bool(len(sources)>=2 and len(cc)>=2 and all(eligible[c.uid] and not protected[c.uid] and len(c.sources)==1 for c in cc))
|
|
50
|
+
for c in cc:
|
|
51
|
+
veto=eligible[c.uid] and not protected[c.uid] and (len(sources)==1 or arm=='conflict_orf_veto' and all_bad)
|
|
52
|
+
if veto:rejected.add(c.uid)
|
|
53
|
+
stats['eligible_originals']+=eligible[c.uid];stats['protected_eligible_originals']+=bool(eligible[c.uid] and protected[c.uid]);stats['vetoed_originals']+=bool(veto)
|
|
54
|
+
if eligible[c.uid]:events.append(dict(candidate=c.uid,q=c.q,diagnostic_class=diagnostics[c.uid][0],diagnostic_posterior=diagnostics[c.uid][1],sources=sorted(c.sources),component_sources=sorted(sources),component_size=len(cc),protection=protected[c.uid],veto=bool(veto),reason='isolated_single_predictor_spurious_orf' if veto and len(sources)==1 else 'all_spurious_conflicting_predictors' if veto else 'protected_or_abstained'))
|
|
55
|
+
return rejected,dict(stats),events
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Positive regional peptide evidence with a conserved multi-placement budget.
|
|
2
|
+
|
|
3
|
+
Fractional weights are ambiguity allocations, not calibrated probabilities.
|
|
4
|
+
The dict interface deliberately exposes only unique genomic placements to old
|
|
5
|
+
hard splice / exon / ORF-veto guards. Ambiguous observations are soft evidence.
|
|
6
|
+
"""
|
|
7
|
+
from collections import defaultdict
|
|
8
|
+
from .peptides import Peptide, compatible
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PeptideEvidence(dict):
|
|
12
|
+
def strong_translation(self,candidate):
|
|
13
|
+
"""Tiered positive support for the existing low-score ORF veto only.
|
|
14
|
+
|
|
15
|
+
This is a conservative heuristic, not a protein-level FDR guarantee.
|
|
16
|
+
Regional peptide observations remain available for reconstruction.
|
|
17
|
+
"""
|
|
18
|
+
sequences={seq for seq in candidate.peptides if len(seq)>=9}
|
|
19
|
+
if any(len(self[seq].blocks)>1 and min(b-a for a,b in self[seq].blocks)>=3
|
|
20
|
+
for seq in sequences):return True
|
|
21
|
+
nonnested=[seq for seq in sequences if not any(seq!=other and seq in other for other in sequences)]
|
|
22
|
+
return len(nonnested)>=2
|
|
23
|
+
|
|
24
|
+
def __init__(self, unique, placements):
|
|
25
|
+
super().__init__(unique)
|
|
26
|
+
self.placements = {seq: tuple(Peptide(seq,*loc) for loc in sorted(locations))
|
|
27
|
+
for seq,locations in sorted(placements.items())}
|
|
28
|
+
self.matches = {}
|
|
29
|
+
self.bins = defaultdict(set)
|
|
30
|
+
for seq, locations in self.placements.items():
|
|
31
|
+
for index, peptide in enumerate(locations):
|
|
32
|
+
for a,b in peptide.blocks:
|
|
33
|
+
for cell in range(a//10000,(b-1)//10000+1):
|
|
34
|
+
self.bins[peptide.contig,peptide.strand,cell].add((seq,index))
|
|
35
|
+
|
|
36
|
+
def attach(self, candidates, genome):
|
|
37
|
+
for candidate in candidates:
|
|
38
|
+
model=candidate.model
|
|
39
|
+
possible=set()
|
|
40
|
+
for a,b in model.cds:
|
|
41
|
+
for cell in range(a//10000,(b-1)//10000+1):
|
|
42
|
+
possible.update(self.bins.get((model.contig,model.strand,cell),()))
|
|
43
|
+
if not possible:
|
|
44
|
+
self.matches[candidate.uid]=()
|
|
45
|
+
continue
|
|
46
|
+
protein=genome.assess(model)[2]
|
|
47
|
+
matched=[]
|
|
48
|
+
for seq,index in sorted(possible):
|
|
49
|
+
peptide=self.placements[seq][index]
|
|
50
|
+
if compatible(model,peptide,protein):
|
|
51
|
+
matched.append((seq,index))
|
|
52
|
+
if len(self.placements[seq])==1:
|
|
53
|
+
candidate.peptides.add(seq)
|
|
54
|
+
self.matches[candidate.uid]=tuple(matched)
|
|
55
|
+
|
|
56
|
+
def features(self, candidate, ambiguous=True):
|
|
57
|
+
"""At most one channel-vote/base; split credit capped by observed coding nt.
|
|
58
|
+
|
|
59
|
+
Each sequence has a total placement budget of one over the full mapping
|
|
60
|
+
universe, including locations outside the supplied annotation inventory.
|
|
61
|
+
Overlaps and repeated placements never multiply per-base coverage above
|
|
62
|
+
one. A split peptide divides its splice budget among its junctions.
|
|
63
|
+
"""
|
|
64
|
+
events=defaultdict(float); junctions=defaultdict(lambda:defaultdict(float)); sequences=set()
|
|
65
|
+
for seq,index in self.matches.get(candidate.uid,()):
|
|
66
|
+
locations=self.placements[seq]
|
|
67
|
+
if not ambiguous and len(locations)>1: continue
|
|
68
|
+
peptide=locations[index]; weight=1./len(locations)
|
|
69
|
+
sequences.add(seq)
|
|
70
|
+
for a,b in peptide.blocks:
|
|
71
|
+
events[a]+=weight; events[b]-=weight
|
|
72
|
+
jj=[(a[1],b[0]) for a,b in zip(peptide.blocks,peptide.blocks[1:])]
|
|
73
|
+
if jj:
|
|
74
|
+
for iv in jj:
|
|
75
|
+
for a,b in peptide.blocks:
|
|
76
|
+
junctions[iv][a]+=weight/len(jj)
|
|
77
|
+
junctions[iv][b]-=weight/len(jj)
|
|
78
|
+
coding=0.; active=0.; previous=None
|
|
79
|
+
for position,delta in sorted(events.items()):
|
|
80
|
+
if previous is not None:
|
|
81
|
+
coding+=(position-previous)*min(1.,max(0.,active))
|
|
82
|
+
active+=delta; previous=position
|
|
83
|
+
splice=0.
|
|
84
|
+
for a,b in candidate.model.introns:
|
|
85
|
+
covered=0.; active=0.; previous=None
|
|
86
|
+
for position,delta in sorted(junctions.get((a,b),{}).items()):
|
|
87
|
+
if previous is not None:
|
|
88
|
+
covered+=(position-previous)*min(1.,max(0.,active))
|
|
89
|
+
active+=delta; previous=position
|
|
90
|
+
splice+=min(b-a,covered)
|
|
91
|
+
return coding,splice,len(sequences)
|
|
92
|
+
|
|
93
|
+
def graph_observations(self, models, support):
|
|
94
|
+
"""Unique placements only; never import excluded-predictor junctions.
|
|
95
|
+
|
|
96
|
+
The mapper's complete HAT universe remains intact for uniqueness. A
|
|
97
|
+
split path becomes a search hint only if each junction already occurs
|
|
98
|
+
among the supplied predictions or independently supplied alignments.
|
|
99
|
+
"""
|
|
100
|
+
if not models: return ()
|
|
101
|
+
chrom,strand=models[0].contig,models[0].strand
|
|
102
|
+
lo=min(m.cds[0][0] for m in models); hi=max(m.cds[-1][1] for m in models)
|
|
103
|
+
jj={iv for m in models for iv in m.introns}
|
|
104
|
+
possible=set()
|
|
105
|
+
for m in models:
|
|
106
|
+
for a,b in m.cds:
|
|
107
|
+
for cell in range(a//10000,(b-1)//10000+1):
|
|
108
|
+
possible.update(self.bins.get((chrom,strand,cell),()))
|
|
109
|
+
result=[]
|
|
110
|
+
for seq,index in sorted(possible):
|
|
111
|
+
if len(self.placements[seq]) != 1: continue
|
|
112
|
+
p=self.placements[seq][index]
|
|
113
|
+
if p.blocks[0][0]<lo or p.blocks[-1][1]>hi: continue
|
|
114
|
+
introns=[(a[1],b[0]) for a,b in zip(p.blocks,p.blocks[1:])]
|
|
115
|
+
if any(iv not in jj and not support.supported_junction(models[0],iv) for iv in introns): continue
|
|
116
|
+
result.append(p)
|
|
117
|
+
return tuple(result)
|
|
118
|
+
|
|
119
|
+
def conservative_repair(self, candidates, chosen, valid, weights, support, p):
|
|
120
|
+
"""One-for-one local repair, retaining incumbent direct observations.
|
|
121
|
+
|
|
122
|
+
No reward for missing peptides. An intervention needs newly explained,
|
|
123
|
+
unique, locally contradictory observations: one >=9 aa split peptide
|
|
124
|
+
with >=3 nt on each block, or two nonnested >=9 aa peptide sequences.
|
|
125
|
+
These conservative fixed identification gates are not FDR estimates.
|
|
126
|
+
A peptide outside the incumbent's span cannot on its own force extension.
|
|
127
|
+
Baseline strong RNA states and all incumbent unique peptides are kept.
|
|
128
|
+
"""
|
|
129
|
+
from .intervals import overlap
|
|
130
|
+
chosen=set(chosen); events=[]
|
|
131
|
+
while True:
|
|
132
|
+
proposals=[]
|
|
133
|
+
for i,c in enumerate(candidates):
|
|
134
|
+
if i in chosen or not valid[i] or not c.complete or not c.canonical: continue
|
|
135
|
+
removed=[j for j in chosen if overlap(c.model.cds,candidates[j].model.cds)]
|
|
136
|
+
if len(removed)!=1: continue
|
|
137
|
+
j=removed[0]; old=candidates[j]
|
|
138
|
+
# Nonoverlapping retained models cannot be silently fused or lost.
|
|
139
|
+
if not set(old.peptides)<=set(c.peptides): continue
|
|
140
|
+
old_m=old.model; new_m=c.model
|
|
141
|
+
if any(support.rna_count(old_m,iv)>=p['minimum_rna_templates']
|
|
142
|
+
and iv not in new_m.introns for iv in old_m.introns): continue
|
|
143
|
+
if any(support.rna_exon_counts.get((old_m.contig,old_m.strand,*iv),0)>=p['minimum_rna_templates']
|
|
144
|
+
and iv not in new_m.cds for iv in old_m.cds): continue
|
|
145
|
+
new=[]; junction=False
|
|
146
|
+
for seq in sorted(set(c.peptides)-set(old.peptides)):
|
|
147
|
+
if len(seq)<9: continue
|
|
148
|
+
peptide=self[seq]
|
|
149
|
+
# Evidence must contradict a state inside the competing
|
|
150
|
+
# locus, not merely add an unsupported outer boundary.
|
|
151
|
+
inside=old_m.cds[0][0]<=peptide.blocks[0][0] and peptide.blocks[-1][1]<=old_m.cds[-1][1]
|
|
152
|
+
if not inside: continue
|
|
153
|
+
new.append(seq)
|
|
154
|
+
if len(peptide.blocks)>1 and min(b-a for a,b in peptide.blocks)>=3:
|
|
155
|
+
junction=True
|
|
156
|
+
nonnested=[seq for seq in new if not any(seq!=other and seq in other for other in new)]
|
|
157
|
+
if not junction and len(nonnested)<2: continue
|
|
158
|
+
proposals.append((len(nonnested),weights[i],c.uid,i,j,new,junction))
|
|
159
|
+
if not proposals: break
|
|
160
|
+
_,_,_,i,j,new,junction=max(proposals,key=lambda x:(x[0],x[1],x[2]))
|
|
161
|
+
chosen.remove(j); chosen.add(i)
|
|
162
|
+
events.append(dict(event='peptide_contrast_repair',accepted=True,candidate=candidates[i].uid,
|
|
163
|
+
incumbent=candidates[j].uid,new_unique_sequences=new,
|
|
164
|
+
directly_splice_supported=junction,baseline_utility=weights[j],
|
|
165
|
+
replacement_utility=weights[i],preserved_unique_peptides=True,
|
|
166
|
+
preserved_strong_RNA_states=True))
|
|
167
|
+
return chosen,events
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""BED12 peptide evidence: deduplicate sequences and verify translation/frame."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import bisect, csv, json, re
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class Peptide:
|
|
12
|
+
sequence: str
|
|
13
|
+
contig: str
|
|
14
|
+
strand: str
|
|
15
|
+
blocks: tuple
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def read_bed(path, sequence_table=None, keep_ambiguous=False):
|
|
19
|
+
sequences = {}
|
|
20
|
+
if sequence_table:
|
|
21
|
+
with Path(sequence_table).open() as f:
|
|
22
|
+
for row in csv.DictReader(f, delimiter="\t"):
|
|
23
|
+
if "name" not in row or "sequence" not in row:
|
|
24
|
+
raise ValueError(
|
|
25
|
+
"Peptide sequence table needs name and sequence columns"
|
|
26
|
+
)
|
|
27
|
+
if (
|
|
28
|
+
row["name"] in sequences
|
|
29
|
+
and sequences[row["name"]] != row["sequence"]
|
|
30
|
+
):
|
|
31
|
+
raise ValueError("Conflicting peptide sequence mapping")
|
|
32
|
+
sequences[row["name"]] = row["sequence"]
|
|
33
|
+
placements = defaultdict(set)
|
|
34
|
+
with Path(path).open() as f:
|
|
35
|
+
for number, line in enumerate(f, 1):
|
|
36
|
+
if not line.strip() or line.startswith(("#", "track", "browser")):
|
|
37
|
+
continue
|
|
38
|
+
row = line.rstrip().split("\t")
|
|
39
|
+
if len(row) < 12:
|
|
40
|
+
raise ValueError(
|
|
41
|
+
f"{path}:{number}: BED12 required to preserve split peptides"
|
|
42
|
+
)
|
|
43
|
+
chrom, left, right, name, _, strand = row[:6]
|
|
44
|
+
a, b = int(left), int(right)
|
|
45
|
+
n = int(row[9])
|
|
46
|
+
sizes = [int(x) for x in row[10].rstrip(",").split(",")]
|
|
47
|
+
starts = [int(x) for x in row[11].rstrip(",").split(",")]
|
|
48
|
+
if (
|
|
49
|
+
a < 0
|
|
50
|
+
or b <= a
|
|
51
|
+
or strand not in ("+", "-")
|
|
52
|
+
or n < 1
|
|
53
|
+
or len(sizes) != n
|
|
54
|
+
or len(starts) != n
|
|
55
|
+
):
|
|
56
|
+
raise ValueError(f"{path}:{number}: invalid BED12 geometry")
|
|
57
|
+
blocks = tuple((a + x, a + x + size) for x, size in zip(starts, sizes))
|
|
58
|
+
if (
|
|
59
|
+
blocks[0][0] != a
|
|
60
|
+
or blocks[-1][1] != b
|
|
61
|
+
or any(x < 0 or size <= 0 for x, size in zip(starts, sizes))
|
|
62
|
+
or any(x[1] > y[0] for x, y in zip(blocks, blocks[1:]))
|
|
63
|
+
):
|
|
64
|
+
raise ValueError(f"{path}:{number}: invalid/overlapping peptide blocks")
|
|
65
|
+
seq = sequences.get(name, name).upper().replace("I", "L")
|
|
66
|
+
if not re.fullmatch("[ACDEFGHKLMNPQRSTVWY]+", seq):
|
|
67
|
+
raise ValueError(
|
|
68
|
+
f"{path}:{number}: BED name must be a peptide sequence, or supply a name/sequence table"
|
|
69
|
+
)
|
|
70
|
+
if sum(y - x for x, y in blocks) != 3 * len(seq):
|
|
71
|
+
raise ValueError(
|
|
72
|
+
f"{path}:{number}: peptide length differs from BED coding length"
|
|
73
|
+
)
|
|
74
|
+
placements[seq].add((chrom, strand, blocks))
|
|
75
|
+
peptides = {
|
|
76
|
+
seq: Peptide(seq, *next(iter(locations)))
|
|
77
|
+
for seq, locations in sorted(placements.items())
|
|
78
|
+
if len(locations) == 1
|
|
79
|
+
}
|
|
80
|
+
if keep_ambiguous:
|
|
81
|
+
from .peptide_context import PeptideEvidence
|
|
82
|
+
peptides = PeptideEvidence(peptides, placements)
|
|
83
|
+
return peptides, dict(
|
|
84
|
+
sequences=len(placements),
|
|
85
|
+
unique_placement_sequences=len(peptides),
|
|
86
|
+
ambiguous_sequences_excluded=0 if keep_ambiguous else sum(len(v) > 1 for v in placements.values()),
|
|
87
|
+
ambiguous_sequences_retained=sum(len(v) > 1 for v in placements.values()) if keep_ambiguous else 0,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def peptide_offset(model, peptide):
|
|
92
|
+
if (model.contig, model.strand) != (peptide.contig, peptide.strand):
|
|
93
|
+
return None
|
|
94
|
+
starts = [a for a, b in model.cds]
|
|
95
|
+
indices = []
|
|
96
|
+
prefix = [0]
|
|
97
|
+
for a, b in model.cds:
|
|
98
|
+
prefix.append(prefix[-1] + b - a)
|
|
99
|
+
for a, b in peptide.blocks:
|
|
100
|
+
i = bisect.bisect_right(starts, a) - 1
|
|
101
|
+
if i < 0 or b > model.cds[i][1]:
|
|
102
|
+
return None
|
|
103
|
+
indices.append(i)
|
|
104
|
+
for j, (a, b) in enumerate(zip(indices, indices[1:])):
|
|
105
|
+
if (
|
|
106
|
+
b != a + 1
|
|
107
|
+
or peptide.blocks[j][1] != model.cds[a][1]
|
|
108
|
+
or peptide.blocks[j + 1][0] != model.cds[b][0]
|
|
109
|
+
):
|
|
110
|
+
return None
|
|
111
|
+
if model.strand == "+":
|
|
112
|
+
offset = (
|
|
113
|
+
prefix[indices[0]]
|
|
114
|
+
+ peptide.blocks[0][0]
|
|
115
|
+
- model.cds[indices[0]][0]
|
|
116
|
+
- model.phase
|
|
117
|
+
)
|
|
118
|
+
else:
|
|
119
|
+
i = indices[-1]
|
|
120
|
+
offset = (
|
|
121
|
+
model.length
|
|
122
|
+
- prefix[i]
|
|
123
|
+
- (peptide.blocks[-1][1] - model.cds[i][0])
|
|
124
|
+
- model.phase
|
|
125
|
+
)
|
|
126
|
+
return offset if offset >= 0 and offset % 3 == 0 else None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def compatible(model, peptide, protein):
|
|
130
|
+
offset=peptide_offset(model,peptide)
|
|
131
|
+
return (offset is not None and
|
|
132
|
+
protein[offset//3:offset//3+len(peptide.sequence)].replace("I","L")==peptide.sequence)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def attach_peptides(candidates, peptides, genome):
|
|
136
|
+
bins = defaultdict(set)
|
|
137
|
+
for seq, p in peptides.items():
|
|
138
|
+
for a, b in p.blocks:
|
|
139
|
+
for k in range(a // 10000, (b - 1) // 10000 + 1):
|
|
140
|
+
bins[p.contig, p.strand, k].add(seq)
|
|
141
|
+
for c in candidates:
|
|
142
|
+
m = c.model
|
|
143
|
+
ids = set()
|
|
144
|
+
for a, b in m.cds:
|
|
145
|
+
for k in range(a // 10000, (b - 1) // 10000 + 1):
|
|
146
|
+
ids.update(bins[m.contig, m.strand, k])
|
|
147
|
+
if not ids:
|
|
148
|
+
continue
|
|
149
|
+
_, _, protein = genome.assess(m)
|
|
150
|
+
c.peptides = {seq for seq in ids if compatible(m, peptides[seq], protein)}
|