gapms 1.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. gapms-1.3.2.dist-info/METADATA +92 -0
  2. gapms-1.3.2.dist-info/RECORD +69 -0
  3. gapms-1.3.2.dist-info/WHEEL +5 -0
  4. gapms-1.3.2.dist-info/entry_points.txt +3 -0
  5. gapms-1.3.2.dist-info/licenses/LICENSE +21 -0
  6. gapms-1.3.2.dist-info/licenses/THIRD_PARTY.md +21 -0
  7. gapms-1.3.2.dist-info/top_level.txt +1 -0
  8. gapms_v1/__init__.py +2 -0
  9. gapms_v1/__main__.py +2 -0
  10. gapms_v1/_genesensus/LICENSE +27 -0
  11. gapms_v1/_genesensus/VENDORED.json +53 -0
  12. gapms_v1/_genesensus/__init__.py +10 -0
  13. gapms_v1/_genesensus/__main__.py +4 -0
  14. gapms_v1/_genesensus/adaptive.py +157 -0
  15. gapms_v1/_genesensus/annotation.py +126 -0
  16. gapms_v1/_genesensus/available.py +64 -0
  17. gapms_v1/_genesensus/cli.py +149 -0
  18. gapms_v1/_genesensus/config.py +274 -0
  19. gapms_v1/_genesensus/corroborated.py +60 -0
  20. gapms_v1/_genesensus/diagnostics.py +19 -0
  21. gapms_v1/_genesensus/direct_molecular.py +29 -0
  22. gapms_v1/_genesensus/exchange.py +115 -0
  23. gapms_v1/_genesensus/exon_support.py +36 -0
  24. gapms_v1/_genesensus/genome.py +122 -0
  25. gapms_v1/_genesensus/graph.py +279 -0
  26. gapms_v1/_genesensus/graph_cache.py +175 -0
  27. gapms_v1/_genesensus/intervals.py +104 -0
  28. gapms_v1/_genesensus/isoform_guards.py +54 -0
  29. gapms_v1/_genesensus/isoforms.py +117 -0
  30. gapms_v1/_genesensus/joint.py +60 -0
  31. gapms_v1/_genesensus/loading.py +166 -0
  32. gapms_v1/_genesensus/local_molecular.py +112 -0
  33. gapms_v1/_genesensus/locus_select.py +137 -0
  34. gapms_v1/_genesensus/models.py +93 -0
  35. gapms_v1/_genesensus/molecular.py +222 -0
  36. gapms_v1/_genesensus/molecular_exchange.py +60 -0
  37. gapms_v1/_genesensus/molecular_state_utility.py +104 -0
  38. gapms_v1/_genesensus/molecular_strategy.py +83 -0
  39. gapms_v1/_genesensus/normalization.py +71 -0
  40. gapms_v1/_genesensus/orf_diagnostics.py +55 -0
  41. gapms_v1/_genesensus/peptide_context.py +167 -0
  42. gapms_v1/_genesensus/peptides.py +150 -0
  43. gapms_v1/_genesensus/pipeline.py +596 -0
  44. gapms_v1/_genesensus/provenance.py +54 -0
  45. gapms_v1/_genesensus/rna.py +175 -0
  46. gapms_v1/_genesensus/rna_geometry.py +114 -0
  47. gapms_v1/_genesensus/scoped.py +17 -0
  48. gapms_v1/_genesensus/scoring.py +46 -0
  49. gapms_v1/_genesensus/selection.py +336 -0
  50. gapms_v1/_genesensus/source_splice.py +19 -0
  51. gapms_v1/_genesensus/splice_prior.py +100 -0
  52. gapms_v1/_genesensus/state_utility.py +96 -0
  53. gapms_v1/_genesensus/support.py +189 -0
  54. gapms_v1/assessment.py +274 -0
  55. gapms_v1/classification.py +117 -0
  56. gapms_v1/cli.py +74 -0
  57. gapms_v1/common.py +67 -0
  58. gapms_v1/confidence_features.py +129 -0
  59. gapms_v1/consensus_engine.py +201 -0
  60. gapms_v1/mapping.py +144 -0
  61. gapms_v1/models.py +169 -0
  62. gapms_v1/orf_projection.py +249 -0
  63. gapms_v1/outputs.py +287 -0
  64. gapms_v1/peptides.py +54 -0
  65. gapms_v1/protein_mapper.py +125 -0
  66. gapms_v1/refinement.py +245 -0
  67. gapms_v1/report_figure.py +62 -0
  68. gapms_v1/rnaseq.py +91 -0
  69. gapms_v1/workflow.py +256 -0
@@ -0,0 +1,125 @@
1
+ """Reusable exact, I/L-equivalent peptide-to-protein search.
2
+
3
+ Build one C-backed peptide automaton and scan independent protein FASTAs.
4
+ Return all overlapping occurrences with one-based protein coordinates.
5
+ """
6
+ from collections import defaultdict, OrderedDict
7
+ import json
8
+ from pathlib import Path
9
+ import tempfile
10
+ import time
11
+
12
+ import ahocorasick
13
+ from Bio import SeqIO
14
+
15
+ from peplocus.io import normalize_peptide, read_peptides
16
+
17
+
18
+ class ProteinMatcher:
19
+ """Share a peptide automaton between prediction and BAM-derived proteins."""
20
+
21
+ def __init__(self, peptides):
22
+ started = time.monotonic()
23
+ self.peptides = tuple(sorted({normalize_peptide(p) for p in peptides}))
24
+ if not self.peptides:
25
+ raise ValueError("no peptides to search")
26
+ grouped = defaultdict(list)
27
+ for index, peptide in enumerate(self.peptides):
28
+ grouped[peptide.replace("I", "L")].append(index)
29
+ automaton = ahocorasick.Automaton()
30
+ for pattern, indices in grouped.items():
31
+ automaton.add_word(pattern, (len(pattern), tuple(indices)))
32
+ automaton.make_automaton()
33
+ self.automaton = automaton
34
+ self.build_seconds = time.monotonic() - started
35
+ self.searches = 0
36
+ # Reuse sequence searches across identical source/consensus proteins.
37
+ # Bound both sequence storage and highly repetitive hit lists.
38
+ self._sequence_hits = OrderedDict()
39
+ self._cached_residues = 0
40
+ self._cached_hits = 0
41
+ self._max_cached_residues = 32_000_000
42
+ self._max_cached_hits = 1_000_000
43
+
44
+ @classmethod
45
+ def from_file(cls, path, column=None):
46
+ """Read validated plain, FASTA, CSV or TSV peptide input."""
47
+ peptides, _ = read_peptides(path, column)
48
+ return cls(peptides)
49
+
50
+ def map(self, proteins, output):
51
+ """Write a new mapping TSV and timing/count summary for one FASTA."""
52
+ output = Path(output)
53
+ if output.exists():
54
+ raise ValueError(f"output already exists: {output}")
55
+ started = time.monotonic()
56
+ hits = defaultdict(list)
57
+ seen = set()
58
+ residues = 0
59
+ scanned = reused = 0
60
+ for record in SeqIO.parse(proteins, "fasta"):
61
+ if record.id in seen:
62
+ raise ValueError(f"duplicate protein FASTA identifier: {record.id}")
63
+ seen.add(record.id)
64
+ # Preserve stops/unknown residues as barriers and retain coordinates.
65
+ sequence = str(record.seq).upper().replace("I", "L")
66
+ residues += len(sequence)
67
+ matches = self._sequence_hits.get(sequence)
68
+ if matches is None:
69
+ scanned += 1
70
+ matches = tuple(self.automaton.iter(sequence))
71
+ if len(sequence) <= self._max_cached_residues and len(matches) <= self._max_cached_hits:
72
+ while self._sequence_hits and (self._cached_residues + len(sequence) > self._max_cached_residues or self._cached_hits + len(matches) > self._max_cached_hits):
73
+ old_sequence, old_matches = self._sequence_hits.popitem(last=False)
74
+ self._cached_residues -= len(old_sequence)
75
+ self._cached_hits -= len(old_matches)
76
+ self._sequence_hits[sequence] = matches
77
+ self._cached_residues += len(sequence)
78
+ self._cached_hits += len(matches)
79
+ else:
80
+ reused += 1
81
+ self._sequence_hits.move_to_end(sequence)
82
+ for end, (length, indices) in matches:
83
+ for index in indices:
84
+ hits[index].append((record.id, end - length + 2))
85
+ if not seen:
86
+ raise ValueError("protein FASTA is empty")
87
+ scan_seconds = time.monotonic() - started
88
+
89
+ output.parent.mkdir(parents=True, exist_ok=True)
90
+ temporary = None
91
+ try:
92
+ with tempfile.NamedTemporaryFile(
93
+ mode="w", dir=output.parent, prefix=output.name + ".",
94
+ suffix=".partial", delete=False,
95
+ ) as handle:
96
+ temporary = Path(handle.name)
97
+ handle.write("peptide\tprotein\tlocation\n")
98
+ for index, peptide in enumerate(self.peptides):
99
+ placements = hits.get(index)
100
+ if placements:
101
+ for protein, start in sorted(placements):
102
+ handle.write(f"{peptide}\t{protein}\t{start}\n")
103
+ else:
104
+ handle.write(f"{peptide}\tUNMAPPED\t0\n")
105
+ temporary.replace(output)
106
+ finally:
107
+ if temporary is not None:
108
+ temporary.unlink(missing_ok=True)
109
+
110
+ self.searches += 1
111
+ stats = dict(
112
+ backend="aho-corasick", il_equivalent=True,
113
+ peptides=len(self.peptides), proteins=len(seen),
114
+ protein_residues=residues, mapped_peptides=len(hits),
115
+ protein_sequences_scanned=scanned, protein_sequences_reused=reused,
116
+ cached_protein_sequences=len(self._sequence_hits),
117
+ cached_protein_residues=self._cached_residues, cached_pattern_hits=self._cached_hits,
118
+ unmapped_peptides=len(self.peptides) - len(hits),
119
+ mapping_rows=sum(map(len, hits.values())), automaton_builds=1,
120
+ automaton_searches=self.searches, build_seconds=self.build_seconds,
121
+ scan_seconds=scan_seconds,
122
+ search_and_output_seconds=time.monotonic() - started,
123
+ )
124
+ output.with_suffix(".summary.json").write_text(json.dumps(stats, indent=2) + "\n")
125
+ return output
gapms_v1/refinement.py ADDED
@@ -0,0 +1,245 @@
1
+ """Bounded annotation-guided peptide evidence; no RNA reconstruction required.
2
+
3
+ Hypotheses are local coding paths, not inferred full-length transcripts. New
4
+ paths are inserted before multiplicity and confidence are evaluated.
5
+ """
6
+ from collections import Counter, defaultdict
7
+ from itertools import product
8
+ import json
9
+ import time
10
+
11
+ import ahocorasick
12
+
13
+ from peplocus.digestion import cleavage_context, protein_context
14
+ from peplocus.sequence import canonical, join_blocks, translate, project
15
+ from .assessment import EVENT_FIELDS, boundary
16
+ from .common import LOG, stable_id, write_table
17
+ from .mapping import locus_key
18
+
19
+
20
+ def ordered(blocks, strand):
21
+ blocks=json.loads(locus_key('',strand,blocks)[2])
22
+ return [tuple(b) for b in (blocks if strand=='+' else reversed(blocks))]
23
+
24
+
25
+ def sliced(model, start, end):
26
+ return ordered(project(start,end,model.coding,model.strand),model.strand)
27
+
28
+
29
+ def cleavage(protein, start, end, native_start=False, native_end=False):
30
+ previous=protein[start-1] if start else ''
31
+ following=protein[end:end+1]
32
+ standard=set('ACDEFGHIKLMNPQRSTVWY')
33
+ n_ok=(start==0 and native_start) or bool(previous in {'K','R'} and protein[start:start+1]!='P')
34
+ c_ok=(native_end and (end==len(protein) or following=='*')) or bool(protein[end-1:end] in {'K','R'} and following in standard-{'P'})
35
+ return dict(previous_aa=previous,following_aa=following,n_terminus='protein_boundary' if start==0 and native_start else 'tryptic' if n_ok else 'nontryptic' if previous in standard else 'upstream_stop_boundary' if previous=='*' else 'unknown',c_terminus='protein_boundary' if native_end and (end==len(protein) or following=='*') else 'tryptic' if c_ok else 'nontryptic' if following else 'unknown',tryptic_n=n_ok,tryptic_c=c_ok)
36
+
37
+
38
+ def refine_annotations(args, annotations, store, metadata, reference, rna_junctions):
39
+ started=time.monotonic()
40
+ annotations=[m for m in annotations if m.source!='RNA_ORF' and m.coding]
41
+ stats=Counter();pending=[]
42
+ radius=getattr(args,'refinement_window',3000)
43
+ splice_radius=getattr(args,'refinement_splice_window',30)
44
+ cap=getattr(args,'max_refinement_paths',64)
45
+ anchor=getattr(args,'min_refinement_anchor',9)
46
+ max_peptide=max(map(len,metadata))
47
+ max_nt=3*(max_peptide+1)
48
+ lookup={m.id:m for m in annotations}
49
+ known_paths=set();ordinary_n_paths=set();internal=[];model_occurrences=defaultdict(list)
50
+ aliases=defaultdict(list)
51
+ for p in metadata:
52
+ if len(p)>=args.min_length:aliases[canonical(p)].append(p)
53
+ # One streaming pass; RNA associations do not explain annotation novelty.
54
+ for mid,peptide,sequence,chrom,strand,encoded,start,end in store.db.execute('SELECT * FROM associations'):
55
+ if mid not in lookup:continue
56
+ known_paths.add((sequence,chrom,strand,encoded))
57
+ m=lookup[mid]
58
+ if not store.require_tryptic or protein_context(m.protein+('*' if m.complete_stop else ''),start,end,peptide)['query_tryptic']:
59
+ model_occurrences[mid].append((start,sequence))
60
+ context=cleavage(m.protein,start,end,True,m.complete_stop)
61
+ if start==0 or context['tryptic_n']:ordinary_n_paths.add((sequence,chrom,strand,encoded))
62
+ if m.issues or start<=0 or not m.protein[start:].startswith('M'):continue
63
+ context=cleavage(m.protein,start,end,True,m.complete_stop)
64
+ if context['n_terminus']!='nontryptic' or not context['tryptic_c']:continue
65
+ codon=m.project(start*3,start*3+3)
66
+ if join_blocks(reference,m.chrom,m.strand,codon).upper()!='ATG':continue
67
+ internal.append((m,peptide,sequence,json.loads(encoded),start,context,codon))
68
+ eligible=set(aliases)
69
+ explained_sequences={key[0] for key in known_paths}
70
+ eligible-=explained_sequences
71
+ for sequence,chrom,strand,encoded in store.db.execute('SELECT canonical,chrom,strand,blocks FROM active_hits'):
72
+ if (sequence,chrom,strand,encoded) not in known_paths:eligible.add(sequence)
73
+ stats['unexplained_query_sequences']=len(eligible)
74
+ automaton=None
75
+ if aliases:
76
+ automaton=ahocorasick.Automaton()
77
+ for sequence in sorted(aliases):automaton.add_word(sequence,sequence)
78
+ automaton.make_automaton()
79
+ known_boundaries={which:{(m.chrom,m.strand,boundary(m,which)) for m in annotations} for which in ('start','end')}
80
+ def is_known_boundary(model, point, which):
81
+ return (model.chrom,model.strand,point) in known_boundaries[which]
82
+ def add(kind,model,peptide,blocks,context,diagnostic_edges=(),status='unresolved',feature=(),upstream=None):
83
+ chrom,strand,encoded=locus_key(model.chrom,model.strand,blocks)
84
+ sequence=canonical(peptide)
85
+ if kind!='alternative_start' and (sequence,chrom,strand,encoded) in known_paths:return
86
+ matched=translate(join_blocks(reference,chrom,strand,json.loads(encoded)),args.genetic_code)
87
+ if canonical(matched)!=sequence:raise RuntimeError('annotation-guided projection verification failed')
88
+ # Evaluate the proposed path, preserving possible starts and initiator-M
89
+ # removal. These are plausibility checks, not proof of initiation.
90
+ compatible=cleavage_context(peptide,context.get('previous_aa',''),context.get('following_aa',''))['enzyme_compatible']
91
+ store.add(peptide,chrom,strand,json.loads(encoded),matched,'annotation_guided',tryptic=compatible)
92
+ if store.require_tryptic and not compatible:
93
+ stats['nontryptic_local_matches_excluded']+=1
94
+ return
95
+ pending.append(dict(kind=kind,model=model,peptide=peptide,sequence=sequence,blocks=json.loads(encoded),encoded=encoded,context=context,edges=tuple(diagnostic_edges),status=status,feature=list(feature),upstream=upstream))
96
+ def scan(model, segments, kind, old_offset, terminal_stop=False):
97
+ if automaton is None:return
98
+ protein=translate(join_blocks(reference,model.chrom,model.strand,segments),args.genetic_code)
99
+ if kind=='n_terminal_extension':
100
+ # Only the stop-free path connected to the existing coding start.
101
+ stop=protein.rfind('*',0,old_offset//3)
102
+ valid_start=stop+1
103
+ stop_after=protein.find('*',old_offset//3)
104
+ valid_end=stop_after if stop_after>=0 else len(protein)
105
+ else:
106
+ valid_start=0;stop_after=protein.find('*');valid_end=stop_after if stop_after>=0 else len(protein)
107
+ for end,sequence in automaton.iter(canonical(protein)):
108
+ end+=1;start=end-len(sequence)
109
+ if start<valid_start or end>valid_end:continue
110
+ if kind=='n_terminal_extension' and start*3>=old_offset:continue
111
+ if kind=='n_terminal_extension' and 'X' in protein[start:old_offset//3]:continue
112
+ if kind=='c_terminal_extension' and 'X' in protein[old_offset//3:end]:continue
113
+ if kind=='c_terminal_extension' and end*3<=old_offset:continue
114
+ blocks=project(start*3,end*3,segments,model.strand)
115
+ context=cleavage(protein,start,end,False,stop_after==end)
116
+ event_kind=kind;status='boundary_unresolved';feature=[]
117
+ if kind=='n_terminal_extension' and protein[start:start+1]=='M' and context['n_terminus'] in {'nontryptic','upstream_stop_boundary'} and context['tryptic_c']:
118
+ codon=project(start*3,start*3+3,segments,model.strand)
119
+ if join_blocks(reference,model.chrom,model.strand,codon).upper()=='ATG':
120
+ point=codon[0][0] if model.strand=='+' else codon[-1][1]
121
+ if not is_known_boundary(model,point,'start'):
122
+ event_kind='alternative_start';status='ATG_supported_start_candidate';feature=list(codon)
123
+ if kind=='c_terminal_extension' and stop_after>=0:
124
+ codon=project(stop_after*3,(stop_after+1)*3,segments,model.strand)
125
+ point=codon[-1][1] if model.strand=='+' else codon[0][0]
126
+ if not is_known_boundary(model,point,'end'):
127
+ event_kind='alternative_stop';status='genomic_stop_inferred';feature=list(codon)
128
+ else:
129
+ status='extension_with_already_annotated_end'
130
+ stats['extensions_with_already_annotated_stop']+=1
131
+ for peptide in aliases[sequence]:add(event_kind,model,peptide,blocks,context,status=status,feature=feature)
132
+ # Downstream starts are a special context test, not a new sequence/path.
133
+ for m,peptide,sequence,blocks,start,context,codon in internal:
134
+ point=codon[0][0] if m.strand=='+' else codon[-1][1]
135
+ if is_known_boundary(m,point,'start'):
136
+ stats['internal_starts_already_annotated']+=1;continue
137
+ upstream=len({p for offset,p in model_occurrences[m.id] if offset<start})
138
+ add('alternative_start',m,peptide,blocks,context,status='internal_ATG_nontryptic_N_terminus',feature=codon,upstream=upstream)
139
+ representatives={}
140
+ for m in annotations:
141
+ if not m.issues and m.protein:representatives.setdefault(m.signature(),m)
142
+ LOG.info('Annotation-guided refinement: %s coding paths, %s unexplained peptide sequences',len(representatives),len(eligible))
143
+ for m in representatives.values():
144
+ if automaton is None:break
145
+ total=sum(b-a for a,b in m.coding)
146
+ first=m.coding[0];last=m.coding[-1]
147
+ extent=first[0] if m.strand=='+' else reference.get_reference_length(m.chrom)-first[1]
148
+ extension=min(radius,extent)//3*3
149
+ if extension:
150
+ prefix=(first[0]-extension,first[0]) if m.strand=='+' else (first[1],first[1]+extension)
151
+ segments=ordered([prefix]+sliced(m,0,min(total,max_nt)),m.strand)
152
+ scan(m,segments,'n_terminal_extension',extension)
153
+ if not m.complete_stop:
154
+ extent=reference.get_reference_length(m.chrom)-last[1] if m.strand=='+' else last[0]
155
+ extension=min(radius,extent)
156
+ if extension:
157
+ suffix=(last[1],last[1]+extension) if m.strand=='+' else (last[0]-extension,last[0])
158
+ start=max(0,(total-max_nt)//3*3)
159
+ segments=ordered(sliced(m,start,total)+[suffix],m.strand)
160
+ scan(m,segments,'c_terminal_extension',total-start)
161
+ known_edges={(m.chrom,m.strand,a,b) for m in annotations for a,b in m.junctions}
162
+ seen=set()
163
+ if automaton is not None and not getattr(args,'no_refinement_splice',False):
164
+ for m in representatives.values():
165
+ genomic=sorted(m.coding);offsets={};offset=0
166
+ for block in m.coding:offsets[block]=offset;offset+=block[1]-block[0]
167
+ for i,left in enumerate(genomic[:-1]):
168
+ for skip in (0,1):
169
+ k=i+1+skip
170
+ if k>=len(genomic):continue
171
+ right=genomic[k];a,b=left;c,d=right
172
+ skipped=sum(v-u for u,v in genomic[i+1:k])
173
+ context_key=(m.chrom,m.strand,a,b,c,d,offsets[left if m.strand=='+' else right]%3,skipped%3)
174
+ if context_key in seen:continue
175
+ seen.add(context_key)
176
+ low_motif,high_motif=('GT','AG') if m.strand=='+' else ('CT','AC')
177
+ low_start=max(a+1,b-splice_radius);low_end=min(d-1,b+splice_radius)
178
+ high_start=max(a+1,c-splice_radius);high_end=min(d-1,c+splice_radius)
179
+ low_seq=reference.fetch(m.chrom,low_start,min(reference.get_reference_length(m.chrom),low_end+2)).upper()
180
+ high_base=max(0,high_start-2);high_seq=reference.fetch(m.chrom,high_base,high_end).upper()
181
+ donors=[x for x in range(low_start,low_end+1) if low_seq[x-low_start:x-low_start+2]==low_motif]
182
+ acceptors=[x for x in range(high_start,high_end+1) if high_seq[x-2-high_base:x-high_base]==high_motif]
183
+ skipped=sum(v-u for u,v in genomic[i+1:k])
184
+ variants=[(x,y) for x,y in product(donors,acceptors) if y-x>=20 and (x-b-(y-c)-skipped)%3==0 and (m.chrom,m.strand,x,y) not in known_edges]
185
+ variants.sort(key=lambda xy:(abs(xy[0]-b)+abs(xy[1]-c),xy))
186
+ if len(variants)>cap:stats['splice_contexts_capped']+=1
187
+ for x,y in variants[:cap]:
188
+ stats['local_splice_paths_searched']+=1
189
+ if m.strand=='+':
190
+ start=max(a,x-max_nt);start+=(-(offsets[left]+start-a))%3
191
+ segments=[(start,x),(y,min(d,y+max_nt))]
192
+ else:
193
+ end=min(d,y+max_nt);end-=(-(offsets[right]+d-end))%3
194
+ segments=[(y,end),(max(a,x-max_nt),x)]
195
+ if any(u>=v for u,v in segments):continue
196
+ protein=translate(join_blocks(reference,m.chrom,m.strand,segments),args.genetic_code)
197
+ for end,sequence in automaton.iter(canonical(protein)):
198
+ end+=1;start=end-len(sequence)
199
+ if '*' in protein[:end]:continue
200
+ blocks=project(start*3,end*3,segments,m.strand)
201
+ if len(blocks)!=2 or min(v-u for u,v in blocks)<anchor:continue
202
+ context=cleavage(protein,start,end,False,False)
203
+ for peptide in aliases[sequence]:add('alternative_splice',m,peptide,blocks,context,[(x,y)],'junction_sequence_verified')
204
+ store.db.commit()
205
+ counts=store.counts()
206
+ grouped={}
207
+ for p in pending:
208
+ # Internal starts require locus specificity after all new paths were added.
209
+ if p['kind']=='alternative_start' and (p['sequence'],p['model'].chrom,p['model'].strand,p['encoded']) in ordinary_n_paths:
210
+ stats['start_matches_explained_by_another_isoform_cleavage']+=1;continue
211
+ if p['kind']=='alternative_start' and counts[p['sequence']]!=1:
212
+ stats['nonunique_internal_start_matches']+=1;continue
213
+ m=p['model']
214
+ locus_anchor=boundary(m,'start' if p['kind']=='n_terminal_extension' else 'end') if not p['edges'] and not p['feature'] else None
215
+ key=(p['kind'],m.chrom,m.strand,m.source,m.gene,tuple(p['edges']),p['status'],tuple(map(tuple,p['feature'])),locus_anchor)
216
+ group=grouped.setdefault(key,[]);group.append(p)
217
+ rows=[]
218
+ for key,items in sorted(grouped.items(),key=lambda x:str(x[0])):
219
+ kind,chrom,strand,source,gene,edges,status,feature,locus_anchor=key
220
+ seqs=sorted({p['sequence'] for p in items});refs={p['model'].id:p['model'] for p in items}
221
+ blocks=sorted({tuple(b) for p in items for b in p['blocks']});unique=any(counts[p]==1 for p in seqs)
222
+ qualities={metadata[p['peptide']]['quality'] for p in items}
223
+ q='qvalue_pass' if 'qvalue_pass' in qualities else 'qvalue_fail' if 'qvalue_fail' in qualities else 'unknown'
224
+ support_edges=sorted({(a[1],b[0]) for p in items for a,b in zip(p['blocks'],p['blocks'][1:]) if a[1]<b[0]})
225
+ minimum=min((rna_junctions.get((chrom,a,b,strand),0) for a,b in support_edges),default=0)
226
+ confidence='ambiguous' if not unique or q=='qvalue_fail' else 'rna_peptide_supported' if support_edges and minimum>=args.min_junction_support else 'peptide_supported'
227
+ limits=['local_evidence_does_not_validate_full_transcript','bounded_annotation_guided_search_not_exhaustive','peptide_identification_quality_'+q,'uniqueness_relative_to_searched_paths','coding_connection_is_hypothetical_until_independently_supported']
228
+ if not all(p['context']['tryptic_n'] and p['context']['tryptic_c'] for p in items):limits.append('not_fully_tryptic_in_proposed_local_context')
229
+ if kind=='alternative_start':limits+=['proteolytic_processing_not_excluded','translation_initiation_not_confirmed','upstream_peptide_absence_does_not_establish_absence_of_translation']
230
+ if kind=='alternative_stop':limits.append('stop_inferred_from_assembly_not_directly_observed')
231
+ if stats['splice_contexts_capped']:limits.append('annotation_guided_splice_search_capped')
232
+ ident=stable_id('AG',key)
233
+ rows.append(dict(event_id=ident,event_type=kind,candidate_model_id='',reference_model_ids=sorted(refs),annotation_sources=sorted({m.source for m in refs.values()}),chrom=chrom,start=blocks[0][0],end=blocks[-1][1],strand=strand,candidate_cds_blocks=[],reference_cds_blocks={m.id:sorted(m.coding) for m in refs.values()},relationship='annotation_guided_local_change',peptides=seqs,mapping_ids=sorted({stable_id('L',p['sequence'],chrom,strand,p['encoded']) for p in items}),distinct_diagnostic_peptides=len(seqs),mapping_multiplicity={p:counts[p] for p in seqs},rna_junctions=[dict(chrom=chrom,start=a,end=b,strand=strand,reads=rna_junctions.get((chrom,a,b,strand),0)) for a,b in support_edges],minimum_rna_support=minimum,confidence=confidence,reasons=status,limitations=limits,coding_structure_id='',local_peptide_blocks=blocks,diagnostic_junctions=list(edges),splice_chain_changed=bool(edges),whole_model_status='local_evidence_only',whole_model_review_reasons=['no_full_transcript_inferred'],uniqueness_scope='searched_assembly_and_supplied_splice_paths',evidence_origin='annotation_guided',boundary_status=status,cleavage_context=[dict(peptide=p['sequence'],reference_model_id=p['model'].id,**p['context']) for p in items],upstream_peptide_support=max((p['upstream'] for p in items if p['upstream'] is not None),default=None),proposed_feature_blocks=list(feature)))
234
+ directory=args.output/'refinement';directory.mkdir(exist_ok=True)
235
+ write_table(directory/'annotation_guided_events.tsv',EVENT_FIELDS,rows)
236
+ with (directory/'annotation_guided_features.gtf').open('w') as stream:
237
+ for row in rows:
238
+ feature='start_codon' if row['event_type']=='alternative_start' else 'stop_codon' if row['event_type']=='alternative_stop' else 'peptide_supported_region'
239
+ for a,b in row['proposed_feature_blocks'] or row['local_peptide_blocks']:
240
+ attrs='; '.join(k+' '+json.dumps(str(v)) for k,v in [('gene_id',row['annotation_sources'][0]+':'+lookup[row['reference_model_ids'][0]].gene),('transcript_id',row['event_id']),('event_id',row['event_id']),('event_type',row['event_type']),('evidence_origin','annotation_guided'),('interpretation','local_candidate_requires_review')])+';'
241
+ stream.write(f'{row["chrom"]}\tGAPMS_v1\t{feature}\t{a+1}\t{b}\t.\t{row["strand"]}\t.\t{attrs}\n')
242
+ stats.update(events=len(rows),internal_start_matches_examined=len(internal))
243
+ result=dict(stats,seconds=round(time.monotonic()-started,3),refinement_window_nt=radius,splice_window_nt=splice_radius,max_paths_per_context=cap,min_peptide_anchor_nt=anchor,scope='contiguous terminal extensions, internal ATG starts, nearby canonical GT-AG junction shifts and single-exon skips; no arbitrary new-exon or full-transcript inference')
244
+ LOG.info('Annotation-guided refinement completed: %s local events, %s splice paths',len(rows),stats['local_splice_paths_searched'])
245
+ return rows,result
@@ -0,0 +1,62 @@
1
+ """Offline, exportable two-panel result figure with explicit counting units."""
2
+ import base64
3
+ from collections import Counter
4
+ from .common import write_json
5
+
6
+
7
+ def overview(root,diag,args,summary,events):
8
+ import matplotlib
9
+ matplotlib.use('Agg')
10
+ import matplotlib.pyplot as plt
11
+ from .outputs import assessed_scores
12
+ rows=assessed_scores(diag,args)
13
+ mapping=summary['mapping'];total=summary.get('input',{}).get('unique_peptides',mapping['peptides']);mapped=mapping['mapped_peptides']
14
+ pairs=sum(int(r['mapped_peptides']) for r in rows)
15
+ n=sum(int(r['N_terminal_peptides']) for r in rows)
16
+ c=sum(int(r['C_terminal_peptides']) for r in rows)
17
+ splice=sum(int(r['splice_peptides']) for r in rows)
18
+ internal=sum(int(r['internal_peptides']) for r in rows)
19
+ # Each review proposal is counted once; a proposal is not a distinct gene.
20
+ unique_events=list({e['event_id']:e for e in events}.values())
21
+ counts=Counter(e['event_type'] for e in unique_events)
22
+ ambiguous=Counter(e['event_type'] for e in unique_events if e['confidence']=='ambiguous')
23
+ specific=counts-ambiguous
24
+ categories=[('novel_orf','Novel ORF'),('alternative_start','Alternative start'),('n_terminal_extension','N-terminal extension'),
25
+ ('alternative_stop','Alternative stop'),('c_terminal_extension','C-terminal extension'),('alternative_splice','Alternative splice')]
26
+ plt.rcParams.update({'font.family':'DejaVu Sans','font.size':11,'svg.fonttype':'none'})
27
+ fig,(left,right)=plt.subplots(1,2,figsize=(15,5.8),gridspec_kw={'width_ratios':[1.15,1]})
28
+ teal='#198678';gray='#e1e7eb';blue='#3e77ae';orange='#d9933a'
29
+ data=[('Mapped',mapped,total-mapped,total,teal),('N-terminal',n,max(0,pairs-n),pairs,blue),
30
+ ('C-terminal',c,max(0,pairs-c),pairs,blue),
31
+ ('Splice',splice,max(0,pairs-splice),pairs,orange),
32
+ ('Internal',internal,max(0,pairs-internal),pairs,'#8a74a6')]
33
+ for y,(label,a,b,den,color) in enumerate(data):
34
+ pct=100*a/den if den else 0
35
+ left.barh(y,pct,color=color,height=.56)
36
+ left.barh(y,100-pct,left=pct,color=gray,height=.56)
37
+ left.text(102,y,f'{pct:.1f}%' if den else 'N/A',va='center',fontsize=11)
38
+ if label=='Mapped':left.text(0,-.58,f'{mapped:,} mapped / {total:,} peptides',fontsize=11,color='#344451')
39
+ left.set(yticks=range(len(data)),yticklabels=[d[0] for d in data],xlim=(0,117),xticks=[0,25,50,75,100],xlabel='Percent')
40
+ left.set_ylim(len(data)-.35,-1);left.set_title('A Peptide support',loc='left',fontweight='bold',pad=18)
41
+ from matplotlib.patches import Patch
42
+ left.legend(handles=[Patch(color=teal,label='Mapped'),Patch(color=blue,label='Terminal'),Patch(color=orange,label='Splice'),Patch(color='#8a74a6',label='Internal'),Patch(color=gray,label='Remaining')],loc='upper left',bbox_to_anchor=(-.03,-.18),ncol=3,frameon=False,fontsize=10)
43
+ values=[counts[k] for k,label in categories]
44
+ specific_values=[specific[k] for k,label in categories]
45
+ ambiguous_values=[ambiguous[k] for k,label in categories]
46
+ right.barh(range(len(values)),specific_values,color=teal,height=.58,label='Specific support')
47
+ right.barh(range(len(values)),ambiguous_values,left=specific_values,color='#b8bfc5',height=.58,label='Ambiguous support')
48
+ right.legend(loc='upper left',bbox_to_anchor=(-.03,-.18),frameon=False,fontsize=10)
49
+ right.set(yticks=range(len(values)),yticklabels=[label for k,label in categories],xlabel='Proposals')
50
+ right.invert_yaxis();right.set_title('B Changes to review',loc='left',fontweight='bold',pad=18)
51
+ maximum=max(values,default=0);right.set_xlim(0,max(1,maximum)*1.25)
52
+ for y,value in enumerate(values):right.text(value+max(1,maximum)*.025,y,f'{value:,}',va='center')
53
+ from matplotlib.ticker import MaxNLocator
54
+ right.xaxis.set_major_locator(MaxNLocator(integer=True,nbins=4))
55
+ for ax in [left,right]:
56
+ ax.spines[['top','right','left']].set_visible(False);ax.tick_params(axis='y',length=0);ax.set_axisbelow(True);ax.grid(axis='x',alpha=.15)
57
+ fig.subplots_adjust(left=.15,right=.97,top=.85,bottom=.24,wspace=.85)
58
+ directory=diag/'reports';svg=directory/'overview.svg';png=directory/'overview.png'
59
+ fig.savefig(svg);fig.savefig(png,dpi=180);plt.close(fig)
60
+ write_json(directory/'overview_counts.json',dict(peptides=total,mapped=mapped,peptide_protein_pairs=pairs,N_terminal=n,C_terminal=c,splice=splice,internal=internal,events=dict(counts),events_specific=dict(specific),events_ambiguous=dict(ambiguous),annotation='consensus' if len(args.gtf)>1 else 'supplied' if args.gtf else 'RNA_ORFs'))
61
+ data=base64.b64encode(svg.read_bytes()).decode('ascii')
62
+ return '<h2>Overview</h2><img style="width:100%;height:auto" alt="Peptide mapping, terminal and splice support, and review proposal counts" src="data:image/svg+xml;base64,'+data+'"><p><a href="diagnostics/reports/overview.svg">SVG</a> · <a href="diagnostics/reports/overview.png">PNG</a></p>'
gapms_v1/rnaseq.py ADDED
@@ -0,0 +1,91 @@
1
+ """RNA transcript reconstruction with read-only assembly access."""
2
+ from pathlib import Path
3
+ import os
4
+ import shutil
5
+ import json
6
+ from collections import defaultdict
7
+
8
+ import pysam
9
+ from peplocus.sequence import join_blocks
10
+ from .common import run_command, stable_id, write_table
11
+ from .models import load_models
12
+
13
+
14
+ def validate_bam(path, lengths):
15
+ with pysam.AlignmentFile(str(path), 'rb') as bam:
16
+ if bam.header.to_dict().get('HD', {}).get('SO') != 'coordinate':
17
+ raise ValueError('RNA reconstruction requires a coordinate-sorted BAM (HD:SO:coordinate)')
18
+ if not set(bam.references) & set(lengths):
19
+ raise ValueError('BAM and assembly have no matching contig names')
20
+ for name, length in zip(bam.references, bam.lengths):
21
+ if name in lengths and lengths[name] != length:
22
+ raise ValueError(f'BAM/assembly length mismatch for {name}')
23
+ # BAM is read sequentially by junction extraction and StringTie; no input index is created.
24
+
25
+
26
+
27
+ def canonicalize_transcripts(models, path, provenance):
28
+ """Remove StringTie scheduling-dependent names/order, preserving gene groups."""
29
+ groups=defaultdict(set)
30
+ for m in models:groups[m.chrom,m.strand,m.gene].add(tuple(m.intervals))
31
+ genes={key:stable_id('RG',key[0],key[1],sorted(paths)) for key,paths in groups.items()}
32
+ unique={};records=[]
33
+ for m in models:
34
+ old_transcript=m.original_id;old_gene=m.gene
35
+ gene=genes[m.chrom,m.strand,old_gene]
36
+ transcript=stable_id('RT',gene,m.chrom,m.strand,m.intervals)
37
+ records.append(dict(original_transcript_id=old_transcript,original_gene_id=old_gene,
38
+ transcript_id=transcript,gene_id=gene,chrom=m.chrom,strand=m.strand,exon_blocks=m.intervals))
39
+ m.original_id=transcript;m.gene=gene;m.id=stable_id('M',m.source,transcript)
40
+ unique.setdefault(transcript,m)
41
+ result=sorted(unique.values(),key=lambda m:m.original_id)
42
+ with Path(path).open('w') as out:
43
+ for m in result:
44
+ attributes=f'gene_id "{m.gene}"; transcript_id "{m.original_id}";'
45
+ left=min(a for a,b in m.intervals);right=max(b for a,b in m.intervals)
46
+ out.write(f'{m.chrom}\tGAPMS\ttranscript\t{left+1}\t{right}\t.\t{m.strand}\t.\t{attributes}\n')
47
+ for a,b in sorted(m.intervals):out.write(f'{m.chrom}\tGAPMS\texon\t{a+1}\t{b}\t.\t{m.strand}\t.\t{attributes}\n')
48
+ write_table(provenance,['original_transcript_id','original_gene_id','transcript_id','gene_id','chrom','strand','exon_blocks'],
49
+ sorted(records,key=lambda r:(r['transcript_id'],r['original_transcript_id'])))
50
+ return result
51
+
52
+
53
+ def reconstruct(args, reference, lengths, commands):
54
+ out = args.output
55
+ directory = out/'transcripts'; directory.mkdir(exist_ok=True)
56
+ products = out/'orfs'; products.mkdir(exist_ok=True)
57
+ required = ['stringtie', 'TransDecoder.LongOrfs', 'TransDecoder.Predict']
58
+ missing = [name for name in required if not shutil.which(name)]
59
+ if missing:raise RuntimeError('BAM mode requires: '+', '.join(missing))
60
+ transcripts = directory/'assembled_transcripts.gtf'
61
+ marker = directory/'reconstruction.complete.json'
62
+ raw_predictions=out/'work/rna_prediction';raw_predictions.mkdir(parents=True,exist_ok=True)
63
+ projected = raw_predictions/'all_predicted_orfs.gtf'
64
+ if args.resume and marker.exists() and projected.exists():
65
+ return projected
66
+ run_command(['stringtie', args.bam, '-p', args.threads, '-o', transcripts], directory,
67
+ out/'logs/stringtie.log', commands)
68
+ models = load_models(transcripts, 'RNA_transcripts', reference, lengths, args.genetic_code, allow_unstranded=True)
69
+ shutil.copy2(transcripts,directory/'stringtie_original.gtf')
70
+ models=canonicalize_transcripts(models,transcripts,directory/'transcript_identifiers.tsv')
71
+ write_table(directory/'transcript_orientation.tsv', ['transcript_id','input_strand','extraction_orientation'],
72
+ (dict(transcript_id=m.original_id,input_strand=m.strand,extraction_orientation='-' if m.strand=='-' else '+') for m in models))
73
+ fasta = directory/'assembled_transcripts.fa'
74
+ with fasta.open('w') as stream:
75
+ for model in models:
76
+ dna = join_blocks(reference, model.chrom, model.strand, model.intervals)
77
+ stream.write(f'>{model.original_id}\n{dna}\n')
78
+ if args.genetic_code != 1:
79
+ raise ValueError('TransDecoder reconstruction currently supports genetic code 1 only; mapping/GTF-only modes accept other codes')
80
+ # TransDecoder PWM code seeds its RNG, but hash traversal also affects
81
+ # training/start refinement. Fix Perl ordering only for these child tools.
82
+ td_env=dict(os.environ, PERL_HASH_SEED='0', PERL_PERTURB_KEYS='0')
83
+ run_command(['TransDecoder.LongOrfs', '-t', fasta, '-m', args.min_orf_aa], directory,
84
+ out/'logs/transdecoder_longorfs.log', commands, env=td_env)
85
+ run_command(['TransDecoder.Predict', '-t', fasta, '--cpu', args.threads], directory,
86
+ out/'logs/transdecoder_predict.log', commands, env=td_env)
87
+ from .orf_projection import convert_transdecoder_to_genome_gtf
88
+ convert_transdecoder_to_genome_gtf(str(fasta)+'.transdecoder.gff3', transcripts, projected)
89
+ from .common import write_json
90
+ write_json(marker, {'completed':True,'projected_gtf':str(projected)})
91
+ return projected