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,129 @@
1
+ """Original GAPMS feature engineering and high/low seed rules (MIT)."""
2
+ import pandas as pd
3
+
4
+ def engineer_features(df):
5
+ df = df.copy()
6
+
7
+ # Ensure required columns exist
8
+ required_cols = [
9
+ "sequence_coverage", "mapped_peptides", "protein_length",
10
+ "protein_specific_peptides", "gene_specific_peptides",
11
+ "splice_peptides", "internal_peptides",
12
+ "N_terminal_peptides", "C_terminal_peptides"
13
+ ]
14
+
15
+ missing = [col for col in required_cols if col not in df.columns]
16
+ if missing:
17
+ raise ValueError(f"Missing required columns for feature engineering: {missing}")
18
+
19
+ # Normalization features (rates)
20
+ df['mapped_peptides_per_aa'] = (
21
+ df['mapped_peptides'] / (df['protein_length'].clip(lower=1))
22
+ ).fillna(0)
23
+
24
+ df['protein_specific_rate'] = (
25
+ df['protein_specific_peptides'] / df['mapped_peptides'].clip(lower=1)
26
+ ).fillna(0)
27
+
28
+ df['gene_specific_rate'] = (
29
+ df['gene_specific_peptides'] / df['mapped_peptides'].clip(lower=1)
30
+ ).fillna(0)
31
+
32
+ df['splice_rate'] = (
33
+ df['splice_peptides'] / df['mapped_peptides'].clip(lower=1)
34
+ ).fillna(0)
35
+
36
+ df['internal_rate'] = (
37
+ df['internal_peptides'] / df['mapped_peptides'].clip(lower=1)
38
+ ).fillna(0)
39
+
40
+ df['terminal_rate'] = (
41
+ (df['N_terminal_peptides'] + df['C_terminal_peptides']) /
42
+ df['mapped_peptides'].clip(lower=1)
43
+ ).fillna(0)
44
+
45
+ # Discriminative contrasts
46
+ df['isoform_specificity'] = (
47
+ df['protein_specific_rate'] - df['gene_specific_rate']
48
+ ).fillna(0)
49
+
50
+ # junction_evidence: splice-heavy support
51
+ df['junction_evidence'] = (
52
+ df['splice_peptides'] / df['internal_peptides'].clip(lower=1)
53
+ ).fillna(0)
54
+
55
+ # Binary flags (highly predictive and stable)
56
+ df['has_N_term'] = (df['N_terminal_peptides'] > 0).astype(int)
57
+ df['has_C_term'] = (df['C_terminal_peptides'] > 0).astype(int)
58
+ df['has_both_term'] = ((df['N_terminal_peptides'] > 0) &
59
+ (df['C_terminal_peptides'] > 0)).astype(int)
60
+ df['has_any_protein_specific'] = (df['protein_specific_peptides'] > 0).astype(int)
61
+ df['has_any_splice'] = (df['splice_peptides'] > 0).astype(int)
62
+
63
+ return df
64
+
65
+ BASE_FEATURE_COLS = [
66
+ "sequence_coverage",
67
+ "protein_specific_peptides",
68
+ "gene_specific_peptides",
69
+ "splice_peptides",
70
+ "internal_peptides",
71
+ "mapped_peptides",
72
+ "N_terminal_peptides",
73
+ "C_terminal_peptides",
74
+ "protein_length",
75
+ ]
76
+
77
+ ENGINEERED_FEATURE_COLS = [
78
+ "mapped_peptides_per_aa",
79
+ "protein_specific_rate",
80
+ "gene_specific_rate",
81
+ "splice_rate",
82
+ "internal_rate",
83
+ "terminal_rate",
84
+ "isoform_specificity",
85
+ "junction_evidence",
86
+ "has_N_term",
87
+ "has_C_term",
88
+ "has_both_term",
89
+ "has_any_protein_specific",
90
+ "has_any_splice",
91
+ ]
92
+
93
+ ITERATIVE_FEATURE_COLS = BASE_FEATURE_COLS + ENGINEERED_FEATURE_COLS
94
+
95
+ def get_high_confident_proteins(df):
96
+ high_confident = []
97
+ for _, group in df.groupby("Protein"):
98
+ for _, row in group.iterrows():
99
+ cond1 = row["protein_specific_peptides"] >= 2
100
+ cond2 = row["sequence_coverage"] >= 0.8
101
+ cond3 = row["N_terminal_peptides"] >= 1 and row["C_terminal_peptides"] >= 1 and row["gene_specific_peptides"] > 0
102
+ supported_splice_sites = row.get("supported_splice_sites", 0)
103
+ cond4 = (
104
+ supported_splice_sites == row["splice_sites"]
105
+ and supported_splice_sites > 0
106
+ and row["gene_specific_peptides"] > 0
107
+ )
108
+ if cond1 or cond2 or cond3 or cond4:
109
+ high_confident.append(row)
110
+ break
111
+ print(f"Number of high confident proteins: {len(high_confident)}")
112
+ if not high_confident:
113
+ return df.iloc[0:0].copy()
114
+ return pd.DataFrame(high_confident)
115
+
116
+ def get_low_confident_proteins(df):
117
+ low_confident = []
118
+ for _, group in df.groupby("Protein"):
119
+ for _, row in group.iterrows():
120
+ cond1 = row["mapped_peptides"] < 2
121
+ cond2 = row["gene_specific_peptides"] == 0
122
+ cond3 = row["protein_length"] < 200 or row["protein_length"] > 500
123
+ if cond1 and cond2 and cond3:
124
+ low_confident.append(row)
125
+ break
126
+ print(f"Number of low confident proteins: {len(low_confident)}")
127
+ if not low_confident:
128
+ return df.iloc[0:0].copy()
129
+ return pd.DataFrame(low_confident)
@@ -0,0 +1,201 @@
1
+ """GAPMS adapter to the frozen GeneSensus 0.6.0a3 inference engine.
2
+
3
+ The vendored algorithm is unchanged. This module normalizes GAPMS inputs,
4
+ shares its peptide mapping space and exposes the engine's original audit files.
5
+ """
6
+ from collections import defaultdict
7
+ from dataclasses import dataclass
8
+ import csv
9
+ import gzip
10
+ import json
11
+ from pathlib import Path
12
+ import shutil
13
+ import time
14
+
15
+ from peplocus.sequence import canonical, join_blocks, translate
16
+ from .common import LOG, stable_id, write_json, write_table
17
+ from .models import Model
18
+ from ._genesensus.config import load_config, input_paths
19
+ from ._genesensus.genome import Genome
20
+ from ._genesensus.loading import load_sources
21
+ from ._genesensus.graph_cache import graph_candidates
22
+ from ._genesensus.pipeline import _rna_data, run as engine_run
23
+ from ._genesensus.peptides import read_bed
24
+ from ._genesensus.provenance import sha256
25
+ from ._genesensus.support import Support
26
+ from ._genesensus.models import Transcript
27
+
28
+
29
+ @dataclass
30
+ class GraphModel:
31
+ model: Model
32
+
33
+
34
+ def write_evidence(store, metadata, path):
35
+ """Keep policy-eligible placements, including off-model ones, of each eligible I/L class."""
36
+ quality = defaultdict(set)
37
+ for peptide, row in metadata.items():
38
+ quality[canonical(peptide)].add(row['quality'])
39
+ excluded = {p for p, qq in quality.items() if qq == {'qvalue_fail'}}
40
+ rows = 0
41
+ with path.open('w') as f:
42
+ query = 'SELECT DISTINCT canonical,chrom,strand,blocks FROM active_hits ORDER BY chrom,strand,canonical,blocks'
43
+ for peptide, chrom, strand, encoded in store.db.execute(query):
44
+ if peptide in excluded:
45
+ continue
46
+ bb = json.loads(encoded); a, b = bb[0][0], bb[-1][1]
47
+ fields = [chrom,a,b,peptide,0,strand,a,b,0,len(bb),
48
+ ','.join(str(y-x) for x,y in bb), ','.join(str(x-a) for x,y in bb)]
49
+ f.write('\t'.join(map(str, fields))+'\n'); rows += 1
50
+ return dict(placements=rows, excluded_failed_identification_classes=len(excluded))
51
+
52
+
53
+ def normalize_sources(args, models, directory):
54
+ """Preserve each parsed source CDS, initial phase, exons and gene family.
55
+
56
+ Internal phases are written consistently with the initial phase already used
57
+ by the GAPMS mapper. Original issues/identities are kept in a separate audit.
58
+ RNA-reconstructed ORFs are candidates, not additional predictor votes.
59
+ """
60
+ groups = defaultdict(list)
61
+ for m in models:
62
+ if m.source != 'RNA_ORF' and m.cds:
63
+ groups[m.source].append(m)
64
+ predictions = {}; audit = []
65
+ for number, (source, mm) in enumerate(sorted(groups.items()), 1):
66
+ name = f'prediction_{number:02d}'
67
+ path = directory / (name+'.gtf')
68
+ predictions[name] = {'annotation': str(path)}
69
+ with path.open('w') as f:
70
+ for m in sorted(mm, key=lambda x:x.id):
71
+ # Safe, source-scoped IDs avoid quoting and multi-parent ambiguities.
72
+ at = f'gene_id "{stable_id("G", source, m.chrom, m.strand, m.gene)}"; transcript_id "{m.id}";'
73
+ ee = m.exons or m.cds
74
+ f.write(f'{m.chrom}\tGAPMS\ttranscript\t{min(a for a,b in ee)+1}\t{max(b for a,b in ee)}\t.\t{m.strand}\t.\t{at}\n')
75
+ for a,b in ee:
76
+ f.write(f'{m.chrom}\tGAPMS\texon\t{a+1}\t{b}\t.\t{m.strand}\t.\t{at}\n')
77
+ first = m.cds[0 if m.strand == '+' else -1]
78
+ initial = int(m.phases[first]) if m.phases[first] != '.' else 0
79
+ used = -initial; phases = {}
80
+ for a,b in (m.cds if m.strand == '+' else reversed(m.cds)):
81
+ phases[a,b] = (-used)%3; used += b-a
82
+ for a,b in m.cds:
83
+ f.write(f'{m.chrom}\tGAPMS\tCDS\t{a+1}\t{b}\t.\t{m.strand}\t{phases[a,b]}\t{at}\n')
84
+ audit.append(dict(predictor=name,source=source,source_model=m.id,original_transcript_id=m.original_id,
85
+ original_gene_id=m.gene,chrom=m.chrom,strand=m.strand,initial_phase=initial,
86
+ original_issues=m.issues,engine_candidate=Transcript(
87
+ m.chrom,m.strand,tuple(m.cds),name,m.id,initial,tuple(ee),m.gene).uid))
88
+ if len(predictions) != len(args.gtf):
89
+ raise ValueError('Each consensus annotation must contain at least one coding transcript')
90
+ write_table(directory/'source_models.tsv',list(audit[0]),audit)
91
+ return predictions, audit
92
+
93
+
94
+ def prepare(args, models, store, metadata, reference):
95
+ if args.genetic_code != 1:
96
+ raise ValueError('Multi-annotation GeneSensus consensus currently requires --genetic-code 1')
97
+ started = time.monotonic()
98
+ directory = args.output/'work/consensus_inputs'; directory.mkdir(parents=True,exist_ok=True)
99
+ predictions, audit = normalize_sources(args, models, directory)
100
+ bed = directory/'peptides.bed'; evidence = write_evidence(store,metadata,bed)
101
+ config = dict(genome=str(Path(reference.filename.decode() if isinstance(reference.filename,bytes) else reference.filename).resolve()),
102
+ predictions=predictions,peptides={'bed':str(bed)},parameters=dict(
103
+ selection_policy='state_molecular_guided',molecular_strategy='source_context',
104
+ peptide_strategy='graph_contrast',compress_diagnostics=True,
105
+ graph_beam=args.consensus_beam,graph_candidates=args.consensus_max_candidates,
106
+ graph_max_nodes=args.consensus_max_nodes,graph_max_starts=args.consensus_max_starts,threads=args.threads))
107
+ if args.bam:
108
+ # Preserve the frozen engine's RNA qualification defaults. GAPMS mapper
109
+ # thresholds remain independent and are recorded in the run manifest.
110
+ config['rna'] = dict(bam=str(args.bam),library=args.rna_library)
111
+ config_path=directory/'config.json'; write_json(config_path,config)
112
+ config=load_config(config_path)
113
+ cache=args.output/'work/genesensus_cache';cache.mkdir(exist_ok=True)
114
+ fingerprints={path:sha256(path) for path in input_paths(config)}
115
+ graphs=[]
116
+ with Genome(config['genome']) as genome:
117
+ sources,pool,phase,molecular,source_cache=load_sources(config,genome,fingerprints,cache)
118
+ rna,_=_rna_data(config,cache,args.threads,genome,fingerprints)
119
+ support=Support(rna,(),config['parameters']['minimum_rna_templates'])
120
+ support.peptide_evidence,_=read_bed(bed,keep_ambiguous=True)
121
+ found,reports,_=graph_candidates(pool,config,fingerprints,support,genome,cache)
122
+ for transcript,parents in found:
123
+ if transcript.key in pool:continue
124
+ complete,canonical_splice,protein=genome.assess(transcript)
125
+ coding=list(transcript.cds if transcript.strand=='+' else reversed(transcript.cds))
126
+ trim=transcript.phase; trimmed=[]
127
+ for a,b in coding:
128
+ n=min(trim,b-a);trim-=n
129
+ if transcript.strand=='+':a+=n
130
+ else:b-=n
131
+ if a<b:trimmed.append((a,b))
132
+ m=Model('GS.g'+transcript.uid+'.t1','consensus_graph',transcript.identifier,transcript.gene,
133
+ transcript.contig,transcript.strand,exons=list(transcript.exons),cds=list(transcript.cds),
134
+ protein=protein.rstrip('*'),coding=trimmed,complete_start=complete,complete_stop=complete)
135
+ graphs.append(GraphModel(m))
136
+ context=dict(config_path=config_path,bed=bed,cache=cache,audit=audit,preparation_evidence=evidence,graph_ids={c.model.id for c in graphs})
137
+ LOG.info('Frozen GeneSensus graph: %s unique new paths for shared peptide association',len(graphs))
138
+ return context,graphs,reports,round(time.monotonic()-started,3)
139
+
140
+
141
+ def finish(args, context, store, metadata, reference, rna, graph_reports, graph_seconds, matcher=None):
142
+ LOG.info('Selecting consensus with frozen GeneSensus 0.6.0a3 graph_contrast policy')
143
+ directory=args.output/'consensus'
144
+ feedback=[]
145
+ for iteration in range(8):
146
+ evidence=write_evidence(store,metadata,context['bed'])
147
+ if directory.exists():
148
+ shutil.rmtree(directory) # this run's derived output; engine provenance is regenerated
149
+ result=engine_run(context['config_path'],directory,threads=args.threads,cache=context['cache'])
150
+ report=result.report
151
+ selected=set();rows=[];additional_graphs=[]
152
+ with gzip.open(directory/'candidates.tsv.gz','rt') as f:
153
+ for row in csv.DictReader(f,delimiter='\t'):
154
+ if row['selected']=='True':selected.add(row['candidate'])
155
+ rows.append(row)
156
+ identifier='GS.g'+row['candidate']+'.t1'
157
+ if row['origin']!='graph' or identifier in context['graph_ids']:continue
158
+ bb=[tuple(x) for x in json.loads(row['CDS_0based_halfopen'])]
159
+ aa=translate(join_blocks(reference,row['contig'],row['strand'],bb),1).rstrip('*')
160
+ model=Model(identifier,'consensus_graph',identifier,identifier,row['contig'],row['strand'],
161
+ exons=bb,cds=bb,protein=aa,coding=bb if row['strand']=='+' else list(reversed(bb)),
162
+ complete_start=True,complete_stop=True)
163
+ additional_graphs.append(model);context['graph_ids'].add(identifier)
164
+ before=store.db.execute('SELECT COUNT(*) FROM active_hits').fetchone()[0]
165
+ if additional_graphs:
166
+ search=args.output/'work'/f'consensus_feedback_{iteration+1}'
167
+ if search.exists():shutil.rmtree(search)
168
+ search.mkdir()
169
+ queries=sorted(metadata)
170
+ store.associate(additional_graphs,queries,search,reference,1,matcher=matcher)
171
+ after=store.db.execute('SELECT COUNT(*) FROM active_hits').fetchone()[0]
172
+ feedback.append(dict(pass_number=iteration+1,new_graph_proteins=len(additional_graphs),new_mapping_rows=after-before))
173
+ if after==before:break
174
+ LOG.info('Consensus mapping feedback: %s new placements; reselecting with updated ambiguity',after-before)
175
+ else:
176
+ raise RuntimeError('Consensus mapping feedback did not stabilize within eight passes; no completed annotation is claimed')
177
+ isoforms=json.loads((directory/'isoforms.json').read_text())
178
+ additional=set(isoforms['parent_by_candidate'])
179
+ write_table(directory/'source_model_mapping.tsv',list(context['audit'][0])+['status'],
180
+ (dict(row,status='supported_alternative' if row['engine_candidate'] in additional else 'primary' if row['engine_candidate'] in selected else 'not_selected') for row in context['audit']))
181
+ # Native compressed candidates and decision JSONL remain the authoritative audit.
182
+ write_table(directory/'decisions.tsv',['candidate_id','status','origin','sources','source_ids','cds_blocks','complete','canonical','peptides'],
183
+ (dict(candidate_id=row['candidate'],status='supported_alternative' if row['candidate'] in additional else 'primary' if row['candidate'] in selected else 'not_selected',
184
+ origin=row['origin'],sources=row['sources'],source_ids=row['source_ids'],cds_blocks=row['CDS_0based_halfopen'],
185
+ complete=row['complete'],canonical=row['canonical'],peptides=row['peptides']) for row in rows))
186
+ provisional=directory/'provisional.gff3'
187
+ if provisional.exists():shutil.copyfile(provisional,directory/'unresolved_alternatives.gff3')
188
+ else:(directory/'unresolved_alternatives.gff3').write_text('##gff-version 3\n')
189
+ stats=dict(policy='automatic_multi_annotation',engine='GeneSensus',engine_version='0.6.0a3',
190
+ engine_policy='state_molecular_guided/source_context/graph_contrast',reference_used=False,
191
+ primary_models=report['primary_selected_count'],additional_isoforms=report['selected_count']-report['primary_selected_count'],
192
+ selected_models=report['selected_count'],candidates=report['candidate_count'],graph_candidates=report['novel_graph_candidates'],
193
+ graph_selected=report['selected_graph_candidates'],graph_seconds=graph_seconds,engine_seconds=report['timings']['total_seconds'],
194
+ evidence=evidence,mapping_feedback=feedback,engine_report='report.json',
195
+ limitations=['Peptide-only consensus is not guaranteed to outperform each input predictor.',
196
+ 'No protein molecular scores or residue profiles are imputed.',
197
+ 'The frozen secondary-isoform policy requires molecular corroboration or event-specific RNA; peptides alone do not admit secondary models.',
198
+ 'Unselected source structures remain in source_model_mapping.tsv and native candidate diagnostics, not as asserted new genes.',
199
+ 'RNA-reconstructed ORFs remain separate candidates and do not count as independent gene-predictor votes.'])
200
+ write_json(directory/'summary.json',stats)
201
+ return stats
gapms_v1/mapping.py ADDED
@@ -0,0 +1,144 @@
1
+ """One disk-backed mapping space shared by all annotation sources and ORFs."""
2
+ from collections import Counter, defaultdict
3
+ import csv
4
+ import json
5
+ from pathlib import Path
6
+ import shutil
7
+ import sqlite3
8
+
9
+ from peplocus.sequence import canonical, join_blocks, translate
10
+ from peplocus.digestion import protein_context
11
+ from .protein_mapper import ProteinMatcher
12
+ from .common import stable_id, write_table, read_table
13
+ from .models import write_proteins
14
+
15
+
16
+ def locus_key(chrom, strand, blocks):
17
+ merged = []
18
+ for left, right in sorted(blocks):
19
+ if merged and left == merged[-1][1]:
20
+ merged[-1][1] = right
21
+ else:
22
+ merged.append([left, right])
23
+ return (chrom, strand, json.dumps(merged, separators=(',',':')))
24
+
25
+
26
+ class EvidenceStore:
27
+ def __init__(self, path, require_tryptic=False):
28
+ self.require_tryptic = require_tryptic
29
+ self.db = sqlite3.connect(path)
30
+ self.db.execute('PRAGMA journal_mode=WAL')
31
+ self.db.execute('PRAGMA synchronous=NORMAL')
32
+ self.db.executescript('''
33
+ CREATE TABLE hits (peptide TEXT, canonical TEXT, chrom TEXT, strand TEXT, blocks TEXT,
34
+ matched TEXT, evidence TEXT, PRIMARY KEY(peptide,chrom,strand,blocks)) WITHOUT ROWID;
35
+ CREATE TABLE tryptic_hits (canonical TEXT, chrom TEXT, strand TEXT, blocks TEXT,
36
+ PRIMARY KEY(canonical,chrom,strand,blocks)) WITHOUT ROWID;
37
+ CREATE TABLE associations (model TEXT, peptide TEXT, canonical TEXT, chrom TEXT, strand TEXT,
38
+ blocks TEXT, aa_start INTEGER, aa_end INTEGER,
39
+ PRIMARY KEY(model,peptide,blocks,aa_start)) WITHOUT ROWID;
40
+ CREATE TABLE tryptic_associations (model TEXT, peptide TEXT, blocks TEXT, aa_start INTEGER,
41
+ PRIMARY KEY(model,peptide,blocks,aa_start)) WITHOUT ROWID;
42
+ CREATE INDEX hits_canonical ON hits(canonical);
43
+ CREATE INDEX associations_canonical ON associations(canonical);
44
+ ''')
45
+
46
+ condition = 'WHERE EXISTS (SELECT 1 FROM tryptic_hits t WHERE t.canonical=h.canonical AND t.chrom=h.chrom AND t.strand=h.strand AND t.blocks=h.blocks)' if require_tryptic else ''
47
+ self.db.execute('CREATE VIEW active_hits AS SELECT h.* FROM hits h '+condition)
48
+ condition = 'WHERE EXISTS (SELECT 1 FROM tryptic_associations t WHERE t.model=a.model AND t.peptide=a.peptide AND t.blocks=a.blocks AND t.aa_start=a.aa_start)' if require_tryptic else ''
49
+ self.db.execute('CREATE VIEW active_associations AS SELECT a.* FROM associations a '+condition)
50
+
51
+ def add(self, peptide, chrom, strand, blocks, matched, evidence, tryptic=False):
52
+ chrom, strand, blocks = locus_key(chrom,strand,blocks)
53
+ self.db.execute('''INSERT INTO hits VALUES (?,?,?,?,?,?,?) ON CONFLICT(peptide,chrom,strand,blocks)
54
+ DO UPDATE SET evidence=CASE WHEN instr(','||hits.evidence||',',','||excluded.evidence||',')>0
55
+ THEN hits.evidence ELSE hits.evidence||','||excluded.evidence END''',
56
+ (peptide,canonical(peptide),chrom,strand,blocks,matched,evidence))
57
+ if tryptic:self.db.execute('INSERT OR IGNORE INTO tryptic_hits VALUES (?,?,?,?)',(canonical(peptide),chrom,strand,blocks))
58
+
59
+ def import_genomic(self, path):
60
+ for row in read_table(path):
61
+ self.add(row['peptide'],row['chrom'],row['strand'],json.loads(row['blocks']),row['matched_sequence'],row['evidence'],tryptic=row.get('query_tryptic')=='True')
62
+ self.db.commit()
63
+
64
+ def associate(self, models, peptides, directory, reference, genetic_code, matcher=None):
65
+ """Search the union of all proteins once; validate every projected hit."""
66
+ proteins = directory/'all_model_proteins.faa'
67
+ write_proteins(models, proteins)
68
+ lookup = {m.id:m for m in models}
69
+ if not any(m.protein for m in models):return
70
+ (matcher or ProteinMatcher(peptides)).map(proteins, directory/'protein_mapping.tsv')
71
+ for row in read_table(directory/'protein_mapping.tsv'):
72
+ if row['protein'] == 'UNMAPPED':continue
73
+ model = lookup[row['protein']]; peptide=row['peptide']
74
+ start = int(row['location']) - 1; end = start + len(peptide)
75
+ blocks = model.project(start*3,end*3)
76
+ matched = translate(join_blocks(reference,model.chrom,model.strand,blocks),genetic_code)
77
+ if canonical(matched) != canonical(peptide):
78
+ raise RuntimeError(f'CDS projection verification failed: {model.id} {peptide}')
79
+ context=protein_context(model.protein+('*' if model.complete_stop else ''),start,end,peptide)
80
+ self.add(peptide,model.chrom,model.strand,blocks,matched,model.source,tryptic=context['query_tryptic'])
81
+ chrom,strand,encoded=locus_key(model.chrom,model.strand,blocks)
82
+ self.db.execute('INSERT OR IGNORE INTO associations VALUES (?,?,?,?,?,?,?,?)',
83
+ (model.id,peptide,canonical(peptide),chrom,strand,encoded,start,end))
84
+ if context['query_tryptic']:
85
+ self.db.execute('INSERT OR IGNORE INTO tryptic_associations VALUES (?,?,?,?)', (model.id,peptide,encoded,start))
86
+ self.db.commit()
87
+
88
+ def counts(self, all_mappings=False):
89
+ # I/L-equivalent observed sequences constitute one evidence sequence.
90
+ table='hits' if all_mappings else 'active_hits'
91
+ return dict(self.db.execute(f'SELECT canonical,count(*) FROM (SELECT DISTINCT canonical,chrom,strand,blocks FROM {table}) GROUP BY canonical'))
92
+
93
+ def model_hits(self, all_mappings=False, model_ids=None):
94
+ result=defaultdict(list)
95
+ table='associations' if all_mappings else 'active_associations'
96
+ for model,peptide,sequence,chrom,strand,encoded,start,end in self.db.execute(f'SELECT * FROM {table} ORDER BY model,canonical,aa_start'):
97
+ if model_ids is not None and model not in model_ids:continue
98
+ result[model].append(dict(peptide=peptide,canonical=sequence,chrom=chrom,strand=strand,blocks=json.loads(encoded),aa_start=start,aa_end=end,mapping_id=stable_id('L',sequence,chrom,strand,encoded)))
99
+ return result
100
+
101
+ def export(self, directory, peptides, metadata):
102
+ counts=self.counts(all_mappings=True)
103
+ analysis_counts=self.counts()
104
+ tryptic_counts=dict(self.db.execute('SELECT canonical,count(*) FROM tryptic_hits GROUP BY canonical'))
105
+ fields=['mapping_id','peptide_id','peptide','chrom','start','end','strand','blocks','matched_sequence','match_type','mapping_type','evidence','loci_for_peptide','identification_quality','tryptic_compatible','tryptic_loci_for_peptide']
106
+ mapped=set();stats=Counter()
107
+ with (directory/'mapped_peptides.tsv').open('w') as tsv, (directory/'mapped_peptides.bed').open('w') as bed, (directory/'mapped_peptides.igv.bed').open('w') as igv, (directory/'splice_peptides.bed').open('w') as splice, (directory/'tryptic_peptides.bed').open('w') as tryptic_bed:
108
+ writer=csv.DictWriter(tsv,fieldnames=fields,delimiter='\t',lineterminator='\n');writer.writeheader()
109
+ igv.write('track name="GAPMS_v1" itemRgb="On" description="Display only; reverse-strand labels reversed"\n')
110
+ query="SELECT h.*,t.canonical IS NOT NULL FROM hits h LEFT JOIN tryptic_hits t ON (h.canonical=t.canonical AND h.chrom=t.chrom AND h.strand=t.strand AND h.blocks=t.blocks) ORDER BY h.chrom,CAST(json_extract(h.blocks,'$[0][0]') AS INTEGER),h.strand,h.peptide,h.blocks"
111
+ for peptide,sequence,chrom,strand,encoded,matched,evidence,compatible in self.db.execute(query):
112
+ blocks=json.loads(encoded);left=blocks[0][0];right=blocks[-1][1]
113
+ unique=counts[sequence]==1;spliced=len(blocks)>1
114
+ row=dict(mapping_id=stable_id('L',sequence,chrom,strand,encoded),peptide_id=metadata[peptide]['peptide_id'],peptide=peptide,
115
+ chrom=chrom,start=left,end=right,strand=strand,blocks=encoded,matched_sequence=matched,
116
+ match_type='exact' if peptide==matched else 'il_equivalent',mapping_type='spliced' if spliced else 'contiguous',
117
+ evidence=evidence,loci_for_peptide=counts[sequence],identification_quality=metadata[peptide]['quality'],tryptic_compatible=bool(compatible),tryptic_loci_for_peptide=tryptic_counts.get(sequence,0))
118
+ writer.writerow(row)
119
+ fields_bed=[chrom,left,right,peptide,1000 if unique else 0,strand,left,right,'210,100,35' if spliced else '45,110,180',len(blocks),','.join(str(b-a) for a,b in blocks),','.join(str(a-left) for a,b in blocks)]
120
+ line='\t'.join(map(str,fields_bed))+'\n';bed.write(line)
121
+ if spliced:splice.write(line)
122
+ if compatible:
123
+ tryptic_fields=list(fields_bed);tryptic_fields[4]=1000 if tryptic_counts[sequence]==1 else 0
124
+ tryptic_bed.write('\t'.join(map(str,tryptic_fields))+'\n');stats['tryptic_mapping_rows']+=1
125
+ fields_bed[3]=peptide[::-1] if strand=='-' else peptide
126
+ igv.write('\t'.join(map(str,fields_bed))+'\n')
127
+ mapped.add(peptide);stats['mapping_rows']+=1
128
+ if spliced:stats['spliced_mapping_rows']+=1
129
+ write_table(directory/'unmapped_peptides.tsv',['peptide_id','peptide','length','status'],
130
+ (dict(peptide_id=metadata[p]['peptide_id'],peptide=p,length=len(p),status='unmapped_in_searched_space') for p in peptides if p not in mapped))
131
+ stats.update(dict(peptides=len(peptides),mapped_peptides=len(mapped),unmapped_peptides=len(peptides)-len(mapped),
132
+ unique_peptides=sum(counts.get(canonical(p))==1 for p in peptides),multiple_peptides=sum(counts.get(canonical(p),0)>1 for p in peptides),
133
+ canonical_evidence_sequences=len({canonical(p) for p in peptides}),
134
+ tryptic_mapped_peptides=sum(tryptic_counts.get(canonical(p),0)>0 for p in peptides),
135
+ tryptic_unique_peptides=sum(tryptic_counts.get(canonical(p),0)==1 for p in peptides),
136
+ tryptic_multiple_peptides=sum(tryptic_counts.get(canonical(p),0)>1 for p in peptides)))
137
+ write_table(directory/'peptide_locus_summary.tsv',['peptide','length','loci','status'],
138
+ (dict(peptide=p,length=len(p),loci=counts.get(canonical(p),0),status='unique' if counts.get(canonical(p))==1 else 'multiple' if counts.get(canonical(p),0)>1 else 'unmapped') for p in peptides))
139
+ stats=dict(stats)
140
+ stats.update(analysis_evidence='tryptic' if self.require_tryptic else 'all_exact',
141
+ analysis_mapped_peptides=sum(analysis_counts.get(canonical(p),0)>0 for p in peptides),
142
+ analysis_unique_peptides=sum(analysis_counts.get(canonical(p),0)==1 for p in peptides),
143
+ analysis_multiple_peptides=sum(analysis_counts.get(canonical(p),0)>1 for p in peptides))
144
+ return dict(stats)
gapms_v1/models.py ADDED
@@ -0,0 +1,169 @@
1
+ """Source-aware coding paths in zero-based, half-open genomic coordinates."""
2
+ from dataclasses import dataclass, field
3
+ import gzip
4
+ import json
5
+ from pathlib import Path
6
+ import re
7
+ from urllib.parse import unquote
8
+
9
+ from peplocus.annotation import _ATTRIBUTE, annotation_parents
10
+ from peplocus.sequence import join_blocks, translate, project
11
+ from .common import stable_id
12
+
13
+
14
+ def attributes(text):
15
+ result = {}
16
+ for match in _ATTRIBUTE.finditer(text):
17
+ key, value = match.groups()
18
+ result[key.lower()] = unquote(value.strip().strip('"\''))
19
+ return result
20
+
21
+
22
+ @dataclass
23
+ class Model:
24
+ id: str
25
+ source: str
26
+ original_id: str
27
+ gene: str
28
+ chrom: str
29
+ strand: str
30
+ exons: list = field(default_factory=list)
31
+ cds: list = field(default_factory=list)
32
+ phases: dict = field(default_factory=dict)
33
+ protein: str = ''
34
+ coding: list = field(default_factory=list)
35
+ issues: list = field(default_factory=list)
36
+ complete_start: bool = False
37
+ complete_stop: bool = False
38
+
39
+ @property
40
+ def intervals(self):
41
+ return self.exons or self.cds
42
+
43
+ @property
44
+ def junctions(self):
45
+ return tuple((a[1], b[0]) for a, b in zip(self.cds, self.cds[1:]) if a[1] < b[0])
46
+
47
+ def project(self, start, end):
48
+ return project(start, end, self.coding, self.strand)
49
+
50
+ def signature(self):
51
+ return (self.chrom, self.strand, tuple(self.coding))
52
+
53
+
54
+ def load_models(path, source, reference, lengths, genetic_code=1, allow_unstranded=False):
55
+ """Preserve isoforms and GFF Parent lists; trim only the first CDS phase."""
56
+ opener = gzip.open if str(path).endswith('.gz') else open
57
+ models = {}
58
+ gene_parents = {}
59
+ rows = []
60
+ with opener(path, 'rt') as stream:
61
+ for number, line in enumerate(stream, 1):
62
+ if line.startswith('##FASTA'):
63
+ break
64
+ if not line.strip() or line.startswith('#'):
65
+ continue
66
+ parts = line.rstrip('\n').split('\t')
67
+ if len(parts) != 9:
68
+ raise ValueError(f'{path}:{number}: expected 9 annotation columns')
69
+ chrom, _, feature, left, right, _, strand, phase, text = parts
70
+ feature = feature.lower()
71
+ attrs = attributes(text)
72
+ if feature in {'mrna', 'transcript'}:
73
+ tid = attrs.get('id') or attrs.get('transcript_id')
74
+ if tid:
75
+ gene_parents[(chrom,strand,tid)] = attrs.get('gene_id') or attrs.get('parent') or tid
76
+ if feature not in {'exon', 'cds'}:
77
+ continue
78
+ left, right = int(left) - 1, int(right)
79
+ if chrom not in lengths or not 0 <= left < right <= lengths[chrom]:
80
+ raise ValueError(f'{path}:{number}: feature outside assembly or unknown contig {chrom}')
81
+ if strand not in {'+', '-'} and not (allow_unstranded and strand=='.' and feature=='exon'):
82
+ raise ValueError(f'{path}:{number}: exon/CDS strand must be + or -')
83
+ parents = annotation_parents(text)
84
+ if not parents:
85
+ raise ValueError(f'{path}:{number}: missing transcript identity')
86
+ if phase not in {'.', '0', '1', '2'}:
87
+ raise ValueError(f'{path}:{number}: invalid CDS phase {phase}')
88
+ rows.append((parents, chrom, strand, feature, left, right, phase, attrs))
89
+ scopes={}
90
+ for parents,chrom,strand,*_ in rows:
91
+ for tid in parents:scopes.setdefault(tid,set()).add((chrom,strand))
92
+ for parents, chrom, strand, feature, left, right, phase, attrs in rows:
93
+ for tid in parents:
94
+ model = models.setdefault((chrom,strand,tid), Model(stable_id('M', source, (chrom,strand,tid) if len(scopes[tid])>1 else tid), source, tid,
95
+ attrs.get('gene_id') or gene_parents.get((chrom,strand,tid), tid), chrom, strand))
96
+ if (model.chrom, model.strand) != (chrom, strand):
97
+ raise ValueError(f'{path}: transcript {tid} has conflicting contigs or strands')
98
+ interval = (left, right)
99
+ if feature == 'exon':
100
+ model.exons.append(interval)
101
+ else:
102
+ if interval in model.phases and model.phases[interval] != phase:
103
+ model.issues.append('conflicting_duplicate_CDS_phase')
104
+ model.cds.append(interval)
105
+ model.phases[interval] = phase
106
+ if not models:
107
+ raise ValueError(f'{path}: no exon/CDS transcript models')
108
+ for model in models.values():
109
+ model.exons = sorted(set(model.exons))
110
+ model.cds = sorted(set(model.cds))
111
+ for intervals in [model.exons, model.cds]:
112
+ if any(a[1] > b[0] for a, b in zip(intervals, intervals[1:])):
113
+ raise ValueError(f'{path}: overlapping features within transcript {model.original_id}')
114
+ if not model.cds:
115
+ model.issues.append('no_CDS_annotation')
116
+ continue
117
+ coding = list(model.cds if model.strand == '+' else reversed(model.cds))
118
+ first_phase = model.phases[coding[0]]
119
+ if first_phase == '.':
120
+ model.issues.append('first_CDS_phase_unknown_assumed_zero')
121
+ trim = int(first_phase) if first_phase != '.' else 0
122
+ remaining = trim
123
+ trimmed = []
124
+ for left, right in coding:
125
+ removed = min(remaining, right-left)
126
+ remaining -= removed
127
+ if model.strand == '+':left += removed
128
+ else:right -= removed
129
+ if left < right:trimmed.append((left, right))
130
+ model.coding = trimmed
131
+ cumulative = coding[0][1] - coding[0][0] - trim
132
+ for interval in coding[1:]:
133
+ p = model.phases[interval]
134
+ if p != '.' and int(p) != (-cumulative) % 3:
135
+ model.issues.append('inconsistent_internal_CDS_phase')
136
+ cumulative += interval[1] - interval[0]
137
+ dna = join_blocks(reference, model.chrom, model.strand, model.coding)
138
+ aa = translate(dna, genetic_code)
139
+ model.complete_start = dna[:3].upper() == 'ATG'
140
+ model.complete_stop = len(dna) % 3 == 0 and aa.endswith('*')
141
+ model.protein = aa[:-1] if aa.endswith('*') else aa
142
+ if '*' in model.protein:model.issues.append('internal_stop')
143
+ if len(dna) % 3:model.issues.append('partial_terminal_codon')
144
+ return sorted(models.values(), key=lambda m: m.id)
145
+
146
+
147
+ def write_models(models, path):
148
+ """Write CDS paths with explicit source and stable model IDs; no input edits."""
149
+ with Path(path).open('w') as stream:
150
+ for model in sorted(models, key=lambda m: (m.chrom, min(m.intervals), m.strand, m.id)):
151
+ intervals = model.intervals
152
+ left = min(a for a,b in intervals); right = max(b for a,b in intervals)
153
+ # JSON string escaping is compatible with quoted GTF attributes.
154
+ attrs = '; '.join(k+' '+json.dumps(str(v)) for k,v in [
155
+ ('gene_id', model.source+':'+model.gene), ('transcript_id', model.id),
156
+ ('original_transcript_id',model.original_id),('annotation_source',model.source)])+';'
157
+ stream.write(f'{model.chrom}\tGAPMS_v1\ttranscript\t{left+1}\t{right}\t.\t{model.strand}\t.\t{attrs}\n')
158
+ for a,b in model.exons:
159
+ stream.write(f'{model.chrom}\tGAPMS_v1\texon\t{a+1}\t{b}\t.\t{model.strand}\t.\t{attrs}\n')
160
+ for a,b in model.cds:
161
+ phase = model.phases.get((a,b), '.')
162
+ stream.write(f'{model.chrom}\tGAPMS_v1\tCDS\t{a+1}\t{b}\t.\t{model.strand}\t{phase}\t{attrs}\n')
163
+
164
+
165
+ def write_proteins(models, path):
166
+ with Path(path).open('w') as stream:
167
+ for model in sorted(models, key=lambda m:m.id):
168
+ if model.protein:
169
+ stream.write(f'>{model.id}\n{model.protein}\n')