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,249 @@
1
+ """Strand- and phase-aware TransDecoder projection, retained from GAPMS (MIT)."""
2
+ from pathlib import Path
3
+
4
+ def _parse_attributes(attributes_text):
5
+ """Parse GTF/GFF attributes into a dict."""
6
+ parsed = {}
7
+ for raw_part in str(attributes_text).strip().strip(';').split(';'):
8
+ part = raw_part.strip()
9
+ if not part:
10
+ continue
11
+ if '=' in part:
12
+ key, value = part.split('=', 1)
13
+ elif ' ' in part:
14
+ key, value = part.split(' ', 1)
15
+ else:
16
+ continue
17
+ parsed[key.strip()] = value.strip().strip('"')
18
+ return parsed
19
+
20
+ def _load_transcript_models(transcripts_gtf):
21
+ """Load StringTie transcript models and exon structures keyed by transcript_id."""
22
+ transcript_models = {}
23
+
24
+ with open(transcripts_gtf) as handle:
25
+ for line in handle:
26
+ if line.startswith('#') or not line.strip():
27
+ continue
28
+
29
+ fields = line.rstrip('\n').split('\t')
30
+ if len(fields) < 9:
31
+ continue
32
+
33
+ seqid, source, feature_type, start, end, score, strand, frame, attributes = fields
34
+ feature_type = feature_type.lower()
35
+ if feature_type not in {'transcript', 'mrna', 'exon'}:
36
+ continue
37
+
38
+ attrs = _parse_attributes(attributes)
39
+ transcript_id = attrs.get('transcript_id') or attrs.get('ID')
40
+ if not transcript_id:
41
+ continue
42
+
43
+ gene_id = attrs.get('gene_id') or attrs.get('gene') or attrs.get('Parent') or transcript_id
44
+ start = int(start)
45
+ end = int(end)
46
+
47
+ model = transcript_models.setdefault(
48
+ transcript_id,
49
+ {
50
+ 'seqid': seqid,
51
+ 'source': source,
52
+ 'strand': strand,
53
+ 'score': score,
54
+ 'gene_id': gene_id,
55
+ 'start': start,
56
+ 'end': end,
57
+ 'exons': [],
58
+ },
59
+ )
60
+ model['seqid'] = seqid
61
+ model['strand'] = strand
62
+ model['gene_id'] = gene_id
63
+ if score not in {None, ''}:
64
+ model['score'] = score
65
+ model['start'] = min(model['start'], start)
66
+ model['end'] = max(model['end'], end)
67
+
68
+ if feature_type == 'exon':
69
+ model['exons'].append((start, end))
70
+
71
+ for model in transcript_models.values():
72
+ if not model['exons']:
73
+ model['exons'] = [(model['start'], model['end'])]
74
+ model['exons'] = sorted(model['exons'], key=lambda exon: exon[0])
75
+
76
+ return transcript_models
77
+
78
+ def _map_transcript_interval_to_genome(feature_start, feature_end, transcript_model):
79
+ """Project a transcript-space interval back onto genomic exon coordinates."""
80
+ feature_start = int(feature_start)
81
+ feature_end = int(feature_end)
82
+ strand = transcript_model['strand']
83
+ ordered_exons = list(transcript_model['exons'])
84
+ if strand == '-':
85
+ ordered_exons = list(reversed(ordered_exons))
86
+
87
+ genomic_segments = []
88
+ transcript_cursor = 1
89
+
90
+ for exon_start, exon_end in ordered_exons:
91
+ exon_len = exon_end - exon_start + 1
92
+ transcript_exon_start = transcript_cursor
93
+ transcript_exon_end = transcript_cursor + exon_len - 1
94
+
95
+ overlap_start = max(feature_start, transcript_exon_start)
96
+ overlap_end = min(feature_end, transcript_exon_end)
97
+ if overlap_start <= overlap_end:
98
+ # gffread emits unstranded StringTie transcripts in ascending
99
+ # genomic order, so "." must be projected like a plus-strand
100
+ # transcript here.
101
+ if strand != '-':
102
+ genomic_start = exon_start + (overlap_start - transcript_exon_start)
103
+ genomic_end = exon_start + (overlap_end - transcript_exon_start)
104
+ else:
105
+ genomic_end = exon_end - (overlap_start - transcript_exon_start)
106
+ genomic_start = exon_end - (overlap_end - transcript_exon_start)
107
+
108
+ genomic_segments.append((min(genomic_start, genomic_end), max(genomic_start, genomic_end)))
109
+
110
+ transcript_cursor = transcript_exon_end + 1
111
+
112
+ return sorted(genomic_segments, key=lambda segment: segment[0])
113
+
114
+ def _genomic_orf_strand(transcript_strand, orf_strand):
115
+ """Compose transcript and TransDecoder ORF orientation on the genome."""
116
+ if orf_strand not in {'+', '-'}:
117
+ return transcript_strand
118
+ if transcript_strand == '-':
119
+ return '+' if orf_strand == '-' else '-'
120
+ # A "." StringTie transcript is extracted by gffread in genomic-plus
121
+ # orientation, so the ORF strand directly determines its genomic strand.
122
+ return orf_strand
123
+
124
+ def _next_cds_phase(segment_length, phase):
125
+ """Return the GFF phase for the next CDS segment in translation order."""
126
+ coding_length = max(int(segment_length) - int(phase), 0)
127
+ return (3 - (coding_length % 3)) % 3
128
+
129
+ def convert_transdecoder_to_genome_gtf(transdecoder_gff3, transcripts_gtf, output_gtf):
130
+ """Convert TransDecoder ORF coordinates from transcript space back to genome coordinates."""
131
+ transdecoder_gff3 = Path(transdecoder_gff3)
132
+ transcripts_gtf = Path(transcripts_gtf)
133
+ output_gtf = Path(output_gtf)
134
+
135
+ transcript_models = _load_transcript_models(transcripts_gtf)
136
+ if not transcript_models:
137
+ raise RuntimeError(f"No transcript models could be loaded from {transcripts_gtf}")
138
+
139
+ orf_records = {}
140
+ with open(transdecoder_gff3) as handle:
141
+ for line in handle:
142
+ if line.startswith('#') or not line.strip():
143
+ continue
144
+
145
+ fields = line.rstrip('\n').split('\t')
146
+ if len(fields) < 9:
147
+ continue
148
+
149
+ transcript_id, source, feature_type, start, end, score, strand, frame, attributes = fields
150
+ attrs = _parse_attributes(attributes)
151
+ feature_type = feature_type.lower()
152
+
153
+ if feature_type in {'mrna', 'transcript'}:
154
+ orf_id = attrs.get('ID') or attrs.get('transcript_id')
155
+ if not orf_id:
156
+ continue
157
+ entry = orf_records.setdefault(
158
+ orf_id,
159
+ {
160
+ 'transcript_id': transcript_id,
161
+ 'source': source,
162
+ 'score': score,
163
+ 'orf_strand': strand,
164
+ 'cds_features': [],
165
+ },
166
+ )
167
+ entry['transcript_id'] = transcript_id
168
+ if strand in {'+', '-'}:
169
+ entry['orf_strand'] = strand
170
+ if score not in {None, ''}:
171
+ entry['score'] = score
172
+ elif feature_type == 'cds':
173
+ orf_id = attrs.get('Parent') or attrs.get('protein_id') or attrs.get('transcript_id')
174
+ if not orf_id:
175
+ continue
176
+ entry = orf_records.setdefault(
177
+ orf_id,
178
+ {
179
+ 'transcript_id': transcript_id,
180
+ 'source': source,
181
+ 'score': score,
182
+ 'orf_strand': strand,
183
+ 'cds_features': [],
184
+ },
185
+ )
186
+ entry['transcript_id'] = transcript_id
187
+ entry['cds_features'].append((int(start), int(end), frame if frame != '.' else '0'))
188
+ if strand in {'+', '-'}:
189
+ entry['orf_strand'] = strand
190
+ if score not in {None, ''}:
191
+ entry['score'] = score
192
+
193
+ if not orf_records:
194
+ raise RuntimeError(f"No ORF annotations were found in {transdecoder_gff3}")
195
+
196
+ output_gtf.parent.mkdir(parents=True, exist_ok=True)
197
+ converted_orfs = 0
198
+ with open(output_gtf, 'w') as handle:
199
+ for orf_id in sorted(orf_records):
200
+ entry = orf_records[orf_id]
201
+ transcript_model = transcript_models.get(entry['transcript_id'])
202
+ if transcript_model is None or not entry['cds_features']:
203
+ continue
204
+
205
+ gene_id = transcript_model['gene_id']
206
+ seqid = transcript_model['seqid']
207
+ orf_strand = entry.get('orf_strand', '+')
208
+ strand = _genomic_orf_strand(transcript_model['strand'], orf_strand)
209
+ score = transcript_model.get('score', '.')
210
+ attributes = f'gene_id "{gene_id}"; transcript_id "{orf_id}"; protein_id "{orf_id}";'
211
+
212
+ cds_features = sorted(
213
+ entry['cds_features'],
214
+ key=lambda feature: feature[0],
215
+ reverse=orf_strand == '-',
216
+ )
217
+ projected_segments = []
218
+ for cds_start, cds_end, _ in cds_features:
219
+ genomic_segments = _map_transcript_interval_to_genome(cds_start, cds_end, transcript_model)
220
+ projected_segments.extend(genomic_segments)
221
+
222
+ if not projected_segments:
223
+ continue
224
+
225
+ projected_segments.sort(key=lambda segment: segment[0], reverse=strand == '-')
226
+ try:
227
+ phase = int(cds_features[0][2])
228
+ except (TypeError, ValueError):
229
+ phase = 0
230
+ if phase not in {0, 1, 2}:
231
+ phase = 0
232
+
233
+ handle.write(
234
+ f"{seqid}\tGAPMS\ttranscript\t{transcript_model['start']}\t{transcript_model['end']}\t{score}\t{strand}\t.\t{attributes}\n"
235
+ )
236
+ for genomic_start, genomic_end in projected_segments:
237
+ handle.write(
238
+ f"{seqid}\tGAPMS\tCDS\t{genomic_start}\t{genomic_end}\t{score}\t{strand}\t{phase}\t{attributes}\n"
239
+ )
240
+ phase = _next_cds_phase(genomic_end - genomic_start + 1, phase)
241
+
242
+ converted_orfs += 1
243
+
244
+ if converted_orfs == 0:
245
+ raise RuntimeError(
246
+ f"No TransDecoder ORFs could be projected back to genome coordinates from {transdecoder_gff3}"
247
+ )
248
+
249
+ return output_gtf
gapms_v1/outputs.py ADDED
@@ -0,0 +1,287 @@
1
+ """Small public result set and an offline HTML entry point.
2
+
3
+ This is presentation only: native mapping, assessment and consensus decisions
4
+ remain unchanged under diagnostics. Public scientific files share disk blocks
5
+ with their native copies when hard links are available.
6
+ """
7
+ import csv
8
+ import gzip
9
+ import hashlib
10
+ import html
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import shutil
15
+ from urllib.parse import quote
16
+
17
+ from .common import read_table,write_table,write_json
18
+ from .assessment import EVENT_FIELDS,MODEL_FIELDS
19
+ from .models import attributes
20
+
21
+
22
+ def records(path):
23
+ return list(read_table(path)) if path.is_file() else []
24
+
25
+
26
+ def expose(source,destination):
27
+ if destination.exists():destination.unlink()
28
+ try:os.link(source,destination)
29
+ except OSError:shutil.copyfile(source,destination)
30
+
31
+
32
+ def decoded(row,key):
33
+ value=row.get(key,'')
34
+ return json.loads(value) if value else []
35
+
36
+
37
+ def review_features(rows,path):
38
+ """Emit supported local geometry; a peptide is never expanded into a CDS."""
39
+ with path.open('w') as f:
40
+ f.write('##gff-version 3\n')
41
+ for e in rows:
42
+ eid=e['event_id'];kind=e['event_type'];chrom=e['chrom'];strand=e['strand']
43
+ at=';'.join(k+'='+quote(str(v),safe='') for k,v in dict(event_id=eid,event_type=kind,
44
+ confidence=e['confidence'],boundary_status=e.get('boundary_status',''),
45
+ whole_model_status=e.get('whole_model_status',''),proposal_requires_review='true',
46
+ reference_models=e.get('reference_model_ids',''),supporting_peptides=e.get('peptides','')).items())
47
+ if kind=='novel_orf':
48
+ bb=decoded(e,'candidate_cds_blocks')
49
+ if bb:
50
+ gene=eid+'.gene';tid=eid+'.transcript'
51
+ f.write(f'{chrom}\tGAPMS\tgene\t{bb[0][0]+1}\t{bb[-1][1]}\t.\t{strand}\t.\tID={gene};{at}\n')
52
+ f.write(f'{chrom}\tGAPMS\tmRNA\t{bb[0][0]+1}\t{bb[-1][1]}\t.\t{strand}\t.\tID={tid};Parent={gene};{at}\n')
53
+ phases={};used=0
54
+ for a,b in (bb if strand=='+' else reversed(bb)):phases[a,b]=(-used)%3;used+=b-a
55
+ for i,(a,b) in enumerate(bb,1):
56
+ f.write(f'{chrom}\tGAPMS\texon\t{a+1}\t{b}\t.\t{strand}\t.\tID={tid}.exon{i};Parent={tid}\n')
57
+ f.write(f'{chrom}\tGAPMS\tCDS\t{a+1}\t{b}\t.\t{strand}\t{phases[a,b]}\tParent={tid}\n')
58
+ continue
59
+ features=decoded(e,'proposed_feature_blocks')
60
+ precise=bool(features) and kind in ('alternative_start','alternative_stop') and sum(b-a for a,b in features)==3
61
+ feature='start_codon' if precise and kind=='alternative_start' else 'stop_codon' if precise else 'peptide_supported_region'
62
+ for i,(a,b) in enumerate(features or decoded(e,'local_peptide_blocks'),1):
63
+ f.write(f'{chrom}\tGAPMS\t{feature}\t{a+1}\t{b}\t.\t{strand}\t.\tID={eid}.region{i};{at}\n')
64
+ for i,(a,b) in enumerate(decoded(e,'diagnostic_junctions'),1):
65
+ f.write(f'{chrom}\tGAPMS\tsplice_junction\t{a+1}\t{b}\t.\t{strand}\t.\tID={eid}.junction{i};{at}\n')
66
+
67
+
68
+ def rna_support(diag,minimum):
69
+ path=diag/'transcripts/rnaseq_junctions.tsv'
70
+ if not path.exists():return {}
71
+ counts={}
72
+ for row in read_table(path):
73
+ counts[row['chrom'],int(row['start']),int(row['end']),row['strand']]=int(row['support'])
74
+ by_model={}
75
+ path=diag/'work/source_models.gtf'
76
+ if not path.exists():return {}
77
+ with path.open() as f:
78
+ for line in f:
79
+ if line.startswith('#'):continue
80
+ row=line.rstrip().split('\t')
81
+ if len(row)!=9 or row[2]!='CDS':continue
82
+ mid=attributes(row[8])['transcript_id']
83
+ by_model.setdefault((mid,row[0],row[6]),set()).add((int(row[3])-1,int(row[4])))
84
+ result={}
85
+ for (mid,ch,st),bb in by_model.items():
86
+ bb=sorted(bb);values=[max(counts.get((ch,a[1],b[0],st),0),counts.get((ch,a[1],b[0],'.'),0)) for a,b in zip(bb,bb[1:]) if a[1]<b[0]]
87
+ result[mid]=dict(rna_supported_junctions=sum(n>=minimum for n in values),rna_minimum_junction_support=min(values) if values else 'NA')
88
+ return result
89
+
90
+
91
+ def score_table(root,diag,args):
92
+ rows=records(diag/'annotation/gene_model_evidence.tsv')+records(diag/'orfs/all_predicted_orf_evidence.tsv')
93
+ rows=[row for row in rows if row['category']!='no_CDS_annotation']
94
+ if not rows:return
95
+ selection={r['source_model']:r['status'] for r in records(diag/'consensus/source_model_mapping.tsv')}
96
+ rna=rna_support(diag,args.min_junction_support) if args.bam else {}
97
+ fields=MODEL_FIELDS+['consensus_selection','classifier_score','rna_supported_junctions','rna_minimum_junction_support']
98
+ for row in rows:
99
+ row.update(consensus_selection=selection.get(row['model_id'],'not_applicable' if len(args.gtf)<2 else 'not_a_predictor_vote'),classifier_score='NA',**rna.get(row['model_id'],dict(rna_supported_junctions='NA',rna_minimum_junction_support='NA')))
100
+ # New graph proteins have no original-source table row. Native peptide count
101
+ # counts unique sequences, not an invented total including ambiguous support.
102
+ path=diag/'consensus/candidates.tsv.gz'
103
+ if path.exists():
104
+ with gzip.open(path,'rt') as f:
105
+ for c in csv.DictReader(f,delimiter='\t'):
106
+ if c['origin']!='graph' or c['selected']!='True':continue
107
+ bb=json.loads(c['CDS_0based_halfopen']);row={k:'NA' for k in fields}
108
+ row.update(model_id='GS.g'+c['candidate']+'.t1',source='consensus_graph',chrom=c['contig'],strand=c['strand'],start=bb[0][0],end=bb[-1][1],category='selected_consensus_graph',locus_discriminating_peptides=c['peptides'],consensus_selection='primary',classifier_score='NA',reasons='See native GeneSensus evidence; unknown fields are not imputed')
109
+ rows.append(row)
110
+ classification=records(diag/'classification/scores.tsv')
111
+ by_id={r['model_id']:r for r in rows}
112
+ extra=[]
113
+ for c in classification:
114
+ row=by_id.get(c['model_id'])
115
+ if row is None:
116
+ row={k:'NA' for k in fields};row.update(model_id=c['model_id'],source=c['source'],category='consensus_model',consensus_selection='primary');rows.append(row)
117
+ for key,value in c.items():
118
+ if key not in fields and key not in extra:extra.append(key)
119
+ row[key]=value
120
+ fields+=extra
121
+ for row in rows:
122
+ for key in extra:row.setdefault(key,'NA')
123
+ write_table(diag/'classification/model_details.tsv',fields,rows)
124
+ legacy_scores(root,diag,args)
125
+
126
+
127
+
128
+ def publish(root,diag,args, *, refresh=False):
129
+ summary=json.loads((diag/'reports/summary.json').read_text())
130
+ for source,name in [('mapped_peptides.bed','peptides.bed'),('mapped_peptides.igv.bed','peptides.igv.bed'),('tryptic_peptides.bed','peptides.tryptic.bed')]:
131
+ expose(diag/'mapping'/source,root/name)
132
+ supported=diag/'classification/supported_genes.gtf'
133
+ if supported.exists():expose(supported,root/'supported_genes.gtf')
134
+ if len(args.gtf)>1:
135
+ expose(diag/'consensus/annotation.gff3',root/'consensus.gff3')
136
+ expose(diag/'consensus/proteins.faa',root/'consensus_proteins.faa')
137
+ if not refresh:score_table(root,diag,args)
138
+ rescue={r['peptide']:r for r in records(diag/'mapping/rescue/rescue_peptides.tsv')}
139
+ unmapped=records(diag/'mapping/unmapped_peptides.tsv')
140
+ for row in unmapped:
141
+ n=int(rescue.get(row['peptide'],{}).get('rescue_loci',0));row['rescue_loci']=n
142
+ row['status']='rescue_only' if n else 'unmapped_in_searched_space'
143
+ for row in records(diag/'mapping/excluded_peptides.tsv'):
144
+ unmapped.append(dict(peptide_id='NA',peptide=row['peptide'],length=row['length'],status='not_searched_below_min_length',rescue_loci=0))
145
+ write_table(root/'unmapped_peptides.tsv',['peptide_id','peptide','length','status','rescue_loci'],unmapped)
146
+ events=records(diag/'refinement/annotation_change_proposals.tsv')
147
+ events+=records(diag/'orfs/novel_orf_candidates.tsv')
148
+ # The annotation-change table can already contain RNA-derived novel ORFs.
149
+ # Export/count each event once, retaining distinct biological hypotheses.
150
+ events=list({row['event_id']:row for row in events}.values())
151
+ review=root/'review'
152
+ if review.exists():shutil.rmtree(review)
153
+ if events:
154
+ review.mkdir();write_table(review/'candidates.tsv',EVENT_FIELDS,events)
155
+ for name,kinds in [('alternative_start',{'alternative_start','n_terminal_extension'}),('alternative_stop',{'alternative_stop','c_terminal_extension'}),('alternative_splice',{'alternative_splice'}),('novel_orfs',{'novel_orf'})]:
156
+ selected=[e for e in events if e['event_type'] in kinds]
157
+ if selected:review_features(selected,review/(name+'.gff3'))
158
+ staged=diag/'work/consensus_inputs'
159
+ if staged.exists():
160
+ kept=diag/'consensus/inputs';kept.mkdir(exist_ok=True)
161
+ relocated={}
162
+ for source in sorted(staged.iterdir()):
163
+ if not source.is_file():continue
164
+ destination=kept/source.name;expose(source,destination)
165
+ relocated[str(source)]=str(destination.relative_to(diag))
166
+ write_json(diag/'consensus/retained_input_paths.json',dict(relocated=relocated,original_assembly=str(args.assembly.resolve()),note='Native configuration and provenance retain the original execution paths; this map locates their retained annotation and peptide inputs after temporary-work cleanup.'))
167
+ inputs=[]
168
+ for p in args.gtf:
169
+ p=p.resolve();h=hashlib.sha256()
170
+ with p.open('rb') as f:
171
+ for chunk in iter(lambda:f.read(8*1024*1024),b''):h.update(chunk)
172
+ inputs.append(dict(path=str(p),sha256=h.hexdigest()))
173
+ write_table(diag/'input_annotations.tsv',['path','sha256'],inputs)
174
+ multi=len(args.gtf)>1;mode='Multi-annotation consensus' if multi else 'Single-annotation assessment' if args.gtf else 'RNA and peptide mapping' if args.bam else 'Peptide mapping'
175
+ explanations={'supported_genes.gtf':'High-confidence rule seeds plus classifier-positive initially unlabeled transcripts; consensus models in multi-annotation runs. Structures are preserved.',
176
+ 'all_proteins_scores.tsv':'Legacy-format protein features and final confidence calls for the assessed annotation. Additional classifier and source details are in diagnostics/classification/.',
177
+ 'peptides.bed':'All exact placements in standard BED12; includes placements excluded by the selected analysis policy.',
178
+ 'peptides.tryptic.bed':'Tryptic-compatible exact placements; multiplicity and BED scores are counted independently within this subset.',
179
+ 'peptides.igv.bed':'IGV display track; negative-strand labels are reversed for visualization.',
180
+ 'unmapped_peptides.tsv':'Queries without an exact mapping, including separately labeled rescue-only and below-minimum-length sequences.',
181
+ 'consensus.gff3':'New consensus from all supplied predictions. Review proposals have not been automatically applied.',
182
+ 'consensus_proteins.faa':'Proteins corresponding to the consensus annotation.','report.log':'Progress, warnings, errors and completion status.'}
183
+ def link(path,label=None):return '<a href="'+quote(path,safe='/')+'">'+html.escape(label or path)+'</a>'
184
+ main=''.join('<tr><td>'+link(n)+'</td><td>'+html.escape(d)+'</td></tr>' for n,d in explanations.items() if (root/n).exists())
185
+ review_links=''.join('<li>'+link(str(p.relative_to(root)))+'</li>' for p in sorted(review.glob('*'))) if review.exists() else '<li>No supported proposals were reported.</li>'
186
+ inp=''.join('<tr><td><a href="'+html.escape(Path(r['path']).as_uri(),quote=True)+'">'+html.escape(r['path'])+'</a></td><td><code>'+r['sha256']+'</code></td></tr>' for r in inputs)
187
+ m=summary['mapping'];cards=f"<p><strong>{m['mapped_peptides']:,} / {m['peptides']:,}</strong> searched peptide sequences mapped; <strong>{m['unique_peptides']:,}</strong> have one placement and <strong>{m['multiple_peptides']:,}</strong> have multiple placements.</p>"
188
+ policy=summary.get('analysis_evidence','all_exact')
189
+ cards+=f"<p><strong>Analysis evidence: {'trypsin-compatible exact placements' if policy=='tryptic' else 'all exact placements (--non-tryptic)'}</strong>. Both mapping tracks are retained. Gene scores and proposals use this selected evidence set."
190
+ if 'analysis_mapped_peptides' in m:
191
+ cards+=f" {m['analysis_mapped_peptides']:,} peptides qualify; {m['analysis_unique_peptides']:,} have one eligible placement and {m['analysis_multiple_peptides']:,} have multiple eligible placements."
192
+ cards+='</p>'
193
+ if args.bam and not args.gtf:
194
+ cards+='<p>RNA-derived ORFs are peptide-supported candidates. Novelty is not assessed because no annotation was supplied.</p>'
195
+ notes=''.join('<li>'+html.escape(x)+'</li>' for x in summary['scientific_limitations'])
196
+ text='<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>GAPMS results</title><style>body{font:16px system-ui,sans-serif;max-width:1080px;margin:40px auto;padding:0 24px;color:#24313b;line-height:1.6}h1,h2{color:#136b5b}table{border-collapse:collapse;width:100%}td,th{padding:10px;text-align:left;border-bottom:1px solid #d8e1e7;overflow-wrap:anywhere}a{color:#0867a5}code{font-size:12px}aside{padding:12px 18px;background:#eff7f4;border-left:4px solid #198870}</style><body>'
197
+ text+='<h1>GAPMS '+html.escape(summary['version'])+'</h1><h2>'+mode+'</h2>'+cards
198
+ text+='<aside>All supplied isoforms are checked before proposing changes. Peptide compatibility supports observed regions; it does not validate every exon, start, stop or complete transcript. Review GFF3s are proposals, not automatic corrections.</aside>'
199
+ details=json.loads((diag/'mapping/mapping_summary.json').read_text())
200
+ if details['engine'].get('search_scope',{}).get('splice_path_cap_reached') or summary.get('annotation_guided_search',{}).get('splice_contexts_capped'):
201
+ text+='<aside>Splice search limits were reached. Placement uniqueness is conditional on the searched paths; inspect the diagnostic summary before interpreting proposals.</aside>'
202
+ from .report_figure import overview
203
+ figure=overview(root,diag,args,summary,events)
204
+ text+=figure
205
+ text+='<h2>Main results</h2><table><tr><th>File</th><th>Meaning</th></tr>'+main+'</table>'
206
+ if (root/'all_proteins_scores.tsv').exists():text+='<p>'+link('diagnostics/score_columns.tsv','Score-table column definitions')+'</p>'
207
+ specific_events=sum(e['confidence']!='ambiguous' for e in events)
208
+ text+='<h2>Changes to review</h2><p>'+str(len(events))+' proposal rows ('+str(specific_events)+' with specific support; '+str(len(events)-specific_events)+' with ambiguous support); these are not counts of distinct genes. Start/stop files also include explicitly labeled terminal-extension proposals. Uncertain boundaries remain unresolved.</p><ul>'+review_links+'</ul>'
209
+ text+='<h2>Supplied annotations</h2><p>'+('These inputs were merged to produce the consensus.' if multi else 'The supplied annotation was assessed, not rewritten or automatically corrected.')+'</p><table><tr><th>Input path</th><th>SHA-256</th></tr>'+inp+'</table>'
210
+ text+='<details><summary>Methods, limitations and detailed evidence</summary><ul>'+notes+'</ul><p>'+link('diagnostics/reports/summary.json','Run summary')+' · '+link('diagnostics/run_manifest.json','Input and software provenance')+' · '+link('diagnostics/','Detailed diagnostics')+'</p><p>Temporary work '+('is retained (--keep-work).' if args.keep_work else 'is removed after successful completion. Use --keep-work to retain it; failed runs retain their work.')+'</p></details></body></html>'
211
+ temporary=root/'report.html.partial';temporary.write_text(text);temporary.replace(root/'report.html')
212
+ write_table(diag/'score_columns.tsv',['column','meaning'],[dict(column='classifier_score',meaning='Rule-seeded iterative XGBoost score; NA when fewer than two high or low seeds. Not a calibrated biological or consensus probability'),dict(column='consensus_selection',meaning='Selection status of each source protein or new graph model; not an assessment of experimental truth'),dict(column='locus_discriminating_peptides',meaning='Distinct I/L-equivalent peptide sequences with one placement in the searched mapping universe'),dict(column='rna_supported_junctions',meaning='Source-model introns meeting mapping-stage RNA filters and --min-junction-support; distinct from GeneSensus consensus qualification'),dict(column='NA',meaning='Unavailable or not applicable; never an invented zero or probability')])
213
+ write_json(diag/'output_layout.json',dict(layout_version=1,mode=mode,public_files=sorted(p.name for p in root.iterdir() if p.is_file()),review_files=sorted(p.name for p in review.glob('*')) if review.exists() else [],classifier_score_status='rule_seeded_iterative',supported_genes_policy='high_seeds_plus_initially_unlabeled_classifier_positive'))
214
+
215
+
216
+ LEGACY_SCORE_FIELDS = ['Protein','supported','confidence','protein_length','isoforms','splice_sites',
217
+ 'transcript_score','sequence_coverage','mapped_peptides','N_terminal_peptides','C_terminal_peptides',
218
+ 'protein_specific_peptides','gene_specific_peptides','splice_peptides','internal_peptides','external_score',
219
+ 'mapped_peptides_per_aa','protein_specific_rate','gene_specific_rate','splice_rate','internal_rate',
220
+ 'terminal_rate','isoform_specificity','junction_evidence','has_N_term','has_C_term','has_both_term',
221
+ 'has_any_protein_specific','has_any_splice']
222
+
223
+
224
+ def assessed_scores(diag,args):
225
+ rows=records(diag/'classification/scores.tsv')
226
+ if len(args.gtf)>1:return [r for r in rows if r['classification_pool']=='CONSENSUS']
227
+ if args.gtf:return [r for r in rows if r['classification_pool']!='RNA_ORF']
228
+ return rows
229
+
230
+
231
+ def legacy_scores(root,diag,args):
232
+ rows=assessed_scores(diag,args)
233
+ genes={};scores={}
234
+ for row in rows:
235
+ key=(row['classification_pool'],row['chrom'],row['strand'],row['gene_id'])
236
+ genes.setdefault(key,set()).add(row['Protein'])
237
+ # Prediction scores are metadata, never invented classifier probabilities.
238
+ for i,path in enumerate(sorted(args.gtf,key=lambda p:str(p.resolve())),1):
239
+ source=f'A{i:02d}_{path.name}'
240
+ opener=gzip.open if str(path).endswith('.gz') else open
241
+ with opener(path,'rt') as f:
242
+ for line in f:
243
+ if line.startswith('##FASTA'):break
244
+ if line.startswith('#'):continue
245
+ parts=line.rstrip().split('\t')
246
+ if len(parts)!=9 or parts[2].lower() not in {'transcript','mrna'}:continue
247
+ at=attributes(parts[8]);tid=at.get('id') or at.get('transcript_id')
248
+ try:score=float(parts[5])
249
+ except ValueError:score=0.
250
+ scores[source,parts[0],parts[6],tid]=score
251
+ public=[]
252
+ for row in rows:
253
+ row=dict(row);source=row['classification_pool']
254
+ row['isoforms']=len(genes[source,row['chrom'],row['strand'],row['gene_id']])
255
+ row['transcript_score']=scores.get((source,row['chrom'],row['strand'],row['original_transcript_id']),0.)
256
+ row['external_score']=0
257
+ row['supported']='+' if row['supported']=='True' else '-'
258
+ row['confidence']='high' if row['seed_label']=='high' else 'moderate' if row['supported']=='+' else 'no-support'
259
+ public.append(row)
260
+ public.sort(key=lambda r:(r['supported']!='+',r['confidence'],-float(r['mapped_peptides']),r['Protein']))
261
+ if rows or args.gtf:write_table(root/'all_proteins_scores.tsv',LEGACY_SCORE_FIELDS,public)
262
+
263
+
264
+ def refresh_report(output):
265
+ """Rebuild presentation from completed diagnostics without rerunning science.
266
+
267
+ Core implementation provenance and cached score/RNA evidence are preserved.
268
+ Publication code identity is recorded separately after a successful refresh.
269
+ """
270
+ from types import SimpleNamespace
271
+ from datetime import datetime, timezone
272
+ from . import __version__
273
+ root=Path(output).resolve();diag=root/'diagnostics';path=diag/'run_manifest.json'
274
+ manifest=json.loads(path.read_text())
275
+ if manifest.get('status')!='completed':raise ValueError('report refresh requires a completed run')
276
+ params=dict(manifest['parameters']);params['output']=root
277
+ for key in ['assembly','peptides','bam']:
278
+ if params.get(key) is not None:params[key]=Path(params[key])
279
+ params['gtf']=[Path(p) for p in params.get('gtf',[])]
280
+ params['keep_work']=bool(manifest.get('work_retained',False))
281
+ publish(root,diag,SimpleNamespace(**params),refresh=True)
282
+ manifest['publication']=dict(version=__version__,refreshed_utc=datetime.now(timezone.utc).isoformat(),
283
+ implementation_sha256=hashlib.sha256(Path(__file__).read_bytes()+Path(__file__).with_name('report_figure.py').read_bytes()).hexdigest(),
284
+ preserved_core_implementation_sha256=manifest['implementation_sha256'],
285
+ note='Report/event deduplication refresh only; mapping, model assessment, classifier scores and RNA evidence were preserved.')
286
+ write_json(path,manifest)
287
+ return manifest['publication']
gapms_v1/peptides.py ADDED
@@ -0,0 +1,54 @@
1
+ """Preserve identification metadata without inventing peptide confidence."""
2
+ import csv
3
+ import gzip
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from peplocus.io import read_peptides, normalize_peptide, HEADERS
8
+ from .common import stable_id, write_table
9
+
10
+
11
+ def load_peptides(args):
12
+ peptides, stats = read_peptides(args.peptides, args.peptide_column)
13
+ kept = [p for p in peptides if len(p) >= args.min_length]
14
+ if not kept:raise ValueError('no peptides meet --min-length')
15
+ metadata = {p:dict(peptide_id=stable_id('P',p), quality='unknown', qvalues=[], records=0) for p in peptides}
16
+ opener = gzip.open if str(args.peptides).endswith('.gz') else open
17
+ with opener(args.peptides, 'rt', encoding='utf-8-sig') as stream:
18
+ first = next((line for line in stream if line.strip() and not line.startswith('#')), '')
19
+ delimiter = '\t' if '\t' in first else ',' if ',' in first else None
20
+ header = [part.strip().lower() for part in first.strip().split(delimiter)] if delimiter else [first.strip().lower()]
21
+ # A one-column TSV remains a table: retain duplicate identifications and
22
+ # modification labels. An uppercase plain-list PEPTIDE is a real sequence.
23
+ plain_sequence = not delimiter and first.strip().isupper() and set(first.strip()) <= set('ACDEFGHIKLMNPQRSTVWY')
24
+ is_table = any(name in HEADERS for name in header) and not plain_sequence
25
+ rows = []
26
+ if is_table:
27
+ with opener(args.peptides, 'rt', encoding='utf-8-sig') as stream:
28
+ reader = csv.DictReader((line for line in stream if line.strip() and not line.startswith('#')), delimiter=delimiter or '\t')
29
+ peptide_key = next((key for key in reader.fieldnames if key.strip().lower() == (args.peptide_column or '').lower()), None)
30
+ peptide_key = peptide_key or next(key for key in reader.fieldnames if key.strip().lower() in HEADERS)
31
+ for index, record in enumerate(reader, 1):
32
+ peptide = normalize_peptide(record[peptide_key]); item=metadata[peptide]; item['records'] += 1
33
+ qkeys = [key for key in record if key.strip().lower().replace('_',' ').replace('-',' ') in {'q value','qvalue','peptide q value','peptide qvalue','global q value'}]
34
+ for key in qkeys:
35
+ value = record[key].strip()
36
+ if value:
37
+ qvalue = float(value)
38
+ if not 0 <= qvalue <= 1:raise ValueError(f'invalid q-value {value}')
39
+ item['qvalues'].append(qvalue)
40
+ rows.append(dict(identification_id=stable_id('I',str(args.peptides.resolve()),index),peptide_id=item['peptide_id'],peptide=peptide,original_record=json.dumps(record,sort_keys=True),input_row=index))
41
+ else:
42
+ for index, peptide in enumerate(peptides,1):
43
+ metadata[peptide]['records']=1
44
+ rows.append(dict(identification_id=stable_id('I',str(args.peptides.resolve()),index),peptide_id=metadata[peptide]['peptide_id'],peptide=peptide,original_record='',input_row=index))
45
+ for item in metadata.values():
46
+ if item['qvalues']:
47
+ item['quality'] = 'qvalue_pass' if min(item['qvalues']) <= args.max_peptide_qvalue else 'qvalue_fail'
48
+ kept_set = set(kept)
49
+ directory=args.output/'mapping';directory.mkdir(exist_ok=True)
50
+ write_table(directory/'peptide_identifications.tsv',['identification_id','peptide_id','peptide','input_row','original_record'],rows)
51
+ write_table(directory/'excluded_peptides.tsv',['peptide','length','reason'],(dict(peptide=p,length=len(p),reason='below_min_length') for p in peptides if p not in kept_set))
52
+ normalized=args.output/'mapping/queries.txt';normalized.write_text('\n'.join(kept)+'\n')
53
+ stats.update(search_peptides=len(kept),excluded_peptides=len(peptides)-len(kept))
54
+ return kept, metadata, stats, normalized