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
gapms_v1/workflow.py ADDED
@@ -0,0 +1,256 @@
1
+ """Unified four-mode orchestration; legacy workflow code is left intact."""
2
+ from dataclasses import replace
3
+ from datetime import datetime, timezone
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import os
8
+ from pathlib import Path
9
+ import shutil
10
+ import subprocess
11
+ import time
12
+
13
+ import pysam
14
+ from peplocus.io import prepare_reference
15
+ from peplocus.junctions import Junction, extract_bam, write_junctions
16
+ from peplocus.annotation import read_annotation
17
+ from peplocus import map_peptides, __version__ as peplocus_version
18
+ from . import __version__
19
+ from .common import LOG, input_identity, stable_id, write_json, write_table
20
+ from .peptides import load_peptides
21
+ from .models import load_models, write_models
22
+ from .mapping import EvidenceStore
23
+ from .assessment import assess
24
+ from .refinement import refine_annotations
25
+ from . import consensus_engine as consensus
26
+ from .protein_mapper import ProteinMatcher
27
+ from .rnaseq import reconstruct, validate_bam
28
+
29
+
30
+ def fingerprint():
31
+ digest=hashlib.sha256()
32
+ import peplocus
33
+ digest.update(peplocus_version.encode())
34
+ for root in [Path(__file__).parent,Path(peplocus.__file__).parent]:
35
+ for path in sorted(root.rglob('*.py')):
36
+ digest.update(str(path.relative_to(root)).encode());digest.update(path.read_bytes())
37
+ return digest.hexdigest()
38
+
39
+
40
+ def tool_versions(bam):
41
+ result={'pysam':pysam.__version__,'peplocus':peplocus_version}
42
+ if bam:
43
+ for name,flags in [('stringtie',['--version']),('TransDecoder.LongOrfs',['--version']),('TransDecoder.Predict',['--version'])]:
44
+ executable=shutil.which(name)
45
+ if not executable:raise ValueError(f'missing BAM reconstruction tool: {name}')
46
+ try:
47
+ process=subprocess.run([executable]+flags,capture_output=True,text=True,timeout=15)
48
+ result[name]={'path':executable,'version_output':(process.stdout+process.stderr).strip()[:500]}
49
+ except subprocess.TimeoutExpired:
50
+ result[name]={'path':executable,'version_output':'version_probe_timed_out'}
51
+ return result
52
+
53
+
54
+ def _run(args):
55
+ started=time.monotonic()
56
+ args.output=args.output.resolve()
57
+ if len(args.gtf)>1 and args.genetic_code!=1:
58
+ raise ValueError('Multi-annotation GeneSensus consensus currently requires --genetic-code 1')
59
+ if args.bam and args.genetic_code!=1:
60
+ raise ValueError('BAM ORF prediction currently requires --genetic-code 1')
61
+ inputs=[args.assembly,args.peptides]+args.gtf+([args.bam] if args.bam else [])
62
+ for path in inputs:
63
+ if not path.is_file():raise ValueError(f'input does not exist: {path}')
64
+ # Resolve all paths before external commands change their working directory.
65
+ args.assembly=args.assembly.resolve();args.peptides=args.peptides.resolve()
66
+ args.gtf=[p.resolve() for p in args.gtf];args.bam=args.bam.resolve() if args.bam else None
67
+ if len(set(args.gtf))!=len(args.gtf):raise ValueError('same annotation supplied more than once')
68
+ params={k:str(v) if isinstance(v,Path) else [str(x) for x in v] if k=='gtf' else v for k,v in vars(args).items() if k not in {'resume','output'}}
69
+ identities=[input_identity(p) for p in inputs]
70
+ run_key=stable_id('R',params,identities,fingerprint())
71
+ manifest_path=args.output/'run_manifest.json'
72
+ previous=None
73
+ if args.output.exists() and any(args.output.iterdir()):
74
+ if not args.resume or not manifest_path.exists():raise ValueError('output is nonempty; choose a new directory or use --resume for the same run')
75
+ previous=json.loads(manifest_path.read_text())
76
+ if previous['run_key']!=run_key:raise ValueError('resume refused: inputs, parameters or implementation differ')
77
+ if previous['status']=='completed':
78
+ LOG.info('Run already completed: %s',args.output);return
79
+ args.output.mkdir(parents=True,exist_ok=True)
80
+ for directory in ['logs','mapping','reports','work']:(args.output/directory).mkdir(exist_ok=True)
81
+ handler=logging.FileHandler(args.output/'logs/workflow.log')
82
+ handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
83
+ LOG.setLevel(logging.INFO);LOG.addHandler(handler)
84
+ if not any(isinstance(h,logging.StreamHandler) and not isinstance(h,logging.FileHandler) for h in LOG.handlers):
85
+ stream=logging.StreamHandler();stream.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'));LOG.addHandler(stream)
86
+ manifest=dict(version=__version__,run_key=run_key,status='running',started_utc=datetime.now(timezone.utc).isoformat(),
87
+ parameters=params,inputs=identities,implementation_sha256=fingerprint(),commands=previous.get('commands',[]) if previous else [],
88
+ host=os.uname().nodename,slurm_job_id=os.environ.get('SLURM_JOB_ID'),mode='integrated' if args.gtf and args.bam else 'annotation' if args.gtf else 'rnaseq' if args.bam else 'mapping')
89
+ write_json(manifest_path,manifest)
90
+ store=None
91
+ try:
92
+ manifest['external_tools']=tool_versions(args.bam)
93
+ manifest['automatic_consensus']=len(args.gtf)>1
94
+ LOG.info('GAPMS v%s %s workflow; %s threads',__version__,manifest['mode'],args.threads)
95
+ peptides,metadata,input_stats,normalized=load_peptides(args)
96
+ genome,index,lengths=prepare_reference(args.assembly,args.output/'work/reference')
97
+ manifest['assembly_contigs']=len(lengths);manifest['assembly_bases']=sum(lengths.values())
98
+ with pysam.FastaFile(genome,filepath_index=index) as reference:
99
+ if args.bam:validate_bam(args.bam,lengths)
100
+ models=[];source_rows=[]
101
+ for i,path in enumerate(sorted(args.gtf,key=lambda p:str(p)),1):
102
+ source=f'A{i:02d}_{path.name}'
103
+ models.extend(load_models(path,source,reference,lengths,args.genetic_code))
104
+ source_rows.append(dict(source=source,path=str(path),kind='input_annotation'))
105
+ rna_path=None
106
+ if args.bam:
107
+ LOG.info('Reconstructing RNA-supported transcripts and candidate ORFs')
108
+ rna_path=reconstruct(args,reference,lengths,manifest['commands'])
109
+ models.extend(load_models(rna_path,'RNA_ORF',reference,lengths,args.genetic_code))
110
+ source_rows.append(dict(source='RNA_ORF',path=str(rna_path),kind='StringTie_TransDecoder'))
111
+ write_table(args.output/'reports/annotation_sources.tsv',['source','path','kind'],source_rows)
112
+ rna_junctions=[];rna_stats={}
113
+ rna_file=args.output/'transcripts/rnaseq_junctions.tsv'
114
+ if args.bam:
115
+ from peplocus.junctions import read_junctions
116
+ cache=args.output/'work/rna_junction_stats.json'
117
+ if args.resume and rna_file.exists() and cache.exists():
118
+ rna_junctions=read_junctions(rna_file,reference,lengths,min_support=args.min_junction_support)
119
+ rna_stats=json.loads(cache.read_text())
120
+ else:
121
+ LOG.info('Extracting RNA splice-junction observations')
122
+ rna_junctions,rna_stats=extract_bam(args.bam,reference,lengths,args.min_mapq,args.min_read_anchor,args.min_junction_support)
123
+ write_junctions(rna_file,rna_junctions);write_json(cache,rna_stats)
124
+ junctions={(j.chrom,j.start,j.end,j.strand):j for j in rna_junctions}
125
+ if models:
126
+ combined=args.output/'work/source_models.gtf';write_models(models,combined)
127
+ annotation_junctions,annotation_stats=read_annotation(combined,reference,lengths)
128
+ for j in annotation_junctions:
129
+ key=(j.chrom,j.start,j.end,j.strand)
130
+ old=junctions.get(key)
131
+ junctions[key]=replace(j,source='annotation,bam',support=old.support) if old else j
132
+ manifest['annotation_junction_statistics']=annotation_stats
133
+ junction_file=args.output/'work/search_junctions.tsv';write_junctions(junction_file,junctions.values())
134
+ engine=args.output/'work/peplocus'
135
+ if not(args.resume and (engine/'summary.json').exists()):
136
+ if engine.exists():shutil.rmtree(engine)
137
+ options=dict(threads=args.threads,genetic_code=args.genetic_code,min_length=args.min_length,
138
+ igv_display_bed=True,max_junctions=args.max_junctions,max_paths_per_junction=args.max_paths_per_junction)
139
+ # Reuse the already extracted, source-aware junction union.
140
+ # Annotation edges with zero reads remain eligible via their source label.
141
+ if models or rna_junctions:options['junctions']=str(junction_file)
142
+ options['min_junction_support']=args.min_junction_support
143
+ if args.rescue_one_edit:options.update(rescue_one_edit=True,min_rescue_length=args.rescue_min_length)
144
+ manifest['commands'].append({'component':'peplocus','version':peplocus_version,
145
+ 'api':'peplocus.map_peptides','assembly':str(args.assembly),'peptides':str(normalized),'out':str(engine),'options':options})
146
+ write_json(manifest_path,manifest)
147
+ LOG.info('Mapping peptides with PepLocus %s against the assembly and unified splice paths',peplocus_version)
148
+ map_peptides(args.assembly,normalized,engine,**options)
149
+ engine_summary=json.loads((engine/'summary.json').read_text())
150
+ args.splice_search_capped=engine_summary.get('search_scope',{}).get('splice_path_cap_reached',False)
151
+ store_path=args.output/'work/evidence.sqlite'
152
+ for suffix in ['', '-wal','-shm']:
153
+ Path(str(store_path)+suffix).unlink(missing_ok=True)
154
+ store=EvidenceStore(store_path, require_tryptic=not getattr(args,'non_tryptic',False))
155
+ LOG.info('Analysis evidence: %s; both mapping tracks are retained', 'trypsin-compatible exact placements' if store.require_tryptic else 'all exact placements')
156
+ store.import_genomic(engine/'mappings.tsv')
157
+ protein_matcher=ProteinMatcher(peptides) if models else None
158
+ if models:
159
+ LOG.info('Associating peptides with %s source-aware coding models',len(models))
160
+ protein_dir=args.output/'work/protein_search'
161
+ if protein_dir.exists():shutil.rmtree(protein_dir)
162
+ protein_dir.mkdir()
163
+ store.associate(models,peptides,protein_dir,reference,args.genetic_code,matcher=protein_matcher)
164
+ consensus_stats={}
165
+ if len(args.gtf)>1:
166
+ LOG.info('Multiple annotation inputs: automatic consensus is enabled')
167
+ consensus_candidates,graph_models,graph_reports,graph_seconds=consensus.prepare(args,models,store,metadata,reference)
168
+ if graph_models:
169
+ graph_dir=args.output/'work/consensus_protein_search'
170
+ if graph_dir.exists():shutil.rmtree(graph_dir)
171
+ graph_dir.mkdir()
172
+ store.associate([c.model for c in graph_models],peptides,graph_dir,reference,args.genetic_code,matcher=protein_matcher)
173
+ guided_events=[];refinement_stats={}
174
+ if args.gtf:
175
+ guided_events,refinement_stats=refine_annotations(args,models,store,metadata,reference,{(j.chrom,j.start,j.end,j.strand):j.support for j in rna_junctions})
176
+ if refinement_stats.get('splice_contexts_capped'):args.splice_search_capped=True
177
+ if len(args.gtf)>1:
178
+ consensus_stats=consensus.finish(args,consensus_candidates,store,metadata,reference,
179
+ {(j.chrom,j.start,j.end,j.strand):j.support for j in rna_junctions},graph_reports,graph_seconds,matcher=protein_matcher)
180
+ mapping_stats=store.export(args.output/'mapping',peptides,metadata)
181
+ model_stats=assess(args,models,store,metadata,{(j.chrom,j.start,j.end,j.strand):j.support for j in rna_junctions},guided_events) if models else {}
182
+ if models:
183
+ from .classification import run as classify_models
184
+ classify_models(args,models,store,metadata,peptides,protein_matcher,reference,lengths)
185
+ limits=json.loads((engine/'summary.json').read_text())
186
+ write_json(args.output/'mapping/mapping_summary.json',dict(mapping=mapping_stats,engine=limits,
187
+ annotation_guided_search=refinement_stats,interpretation='Exact genomic placements, verified local annotation-guided paths and full-CDS projections; rescue is separate and excluded from model/event evidence.'))
188
+ if args.rescue_one_edit:
189
+ rescue=args.output/'mapping/rescue';rescue.mkdir(exist_ok=True)
190
+ shutil.copyfile(engine/'peptides.tsv',rescue/'rescue_peptides.tsv')
191
+ for name in ['mappings.tsv','peptides.tsv','all_mappings.bed','tryptic_mappings.bed']:
192
+ path=engine/'rescue'/name
193
+ if path.is_file():shutil.copyfile(path,rescue/('rescue_'+name if name in {'mappings.tsv','peptides.tsv'} else name))
194
+ summary=dict(version=__version__,analysis_evidence='all_exact' if getattr(args,'non_tryptic',False) else 'tryptic',mode=manifest['mode'],consensus=consensus_stats,input=input_stats,mapping=mapping_stats,assessment=model_stats,annotation_guided_search=refinement_stats,rna_junctions=rna_stats,
195
+ seconds=round(time.monotonic()-started,3),scientific_limitations=[
196
+ 'Mapping validates sequence compatibility, not peptide identification accuracy.',
197
+ 'I/L-equivalent sequences are one evidence unit; reported multiplicity is within the searched genome and supported splice paths.',
198
+ 'No peptide support does not imply an incorrect annotation.',
199
+ 'RNA-supported local splice paths do not prove full-length transcript connectivity.',
200
+ 'Novel and boundary events are candidates for annotation review, not experimentally confirmed changes.',
201
+ 'Partial ORFs and uncertain peptide quality do not receive high-confidence candidate status.',
202
+ 'Full unannotated ORF reconstruction requires BAM; supplied annotations also support bounded local refinement without BAM.',
203
+ 'Rule-seeded iterative classifier scores are not calibrated biological probabilities; seed cross-validation measures rule agreement, not independent annotation accuracy.'])
204
+ write_json(args.output/'reports/summary.json',summary)
205
+ after=[input_identity(p) for p in inputs]
206
+ if identities!=after:raise RuntimeError('an input identity changed during the run')
207
+ manifest.update(status='core_completed',completed_utc=datetime.now(timezone.utc).isoformat(),seconds=summary['seconds'])
208
+ write_json(manifest_path,manifest)
209
+ LOG.info('Completed: %s/%s peptide sequences mapped; results: %s',mapping_stats['mapped_peptides'],len(peptides),args.output)
210
+ except BaseException as error:
211
+ manifest.update(status='failed',error=str(error),failed_utc=datetime.now(timezone.utc).isoformat())
212
+ write_json(manifest_path,manifest)
213
+ LOG.exception('Workflow failed')
214
+ raise
215
+ finally:
216
+ if store is not None:store.db.close()
217
+ LOG.removeHandler(handler);handler.close()
218
+
219
+
220
+ def run(args):
221
+ """Keep the public directory small; execute native stages inside diagnostics."""
222
+ import copy
223
+ from .outputs import publish
224
+ root=args.output.resolve();diag=root/'diagnostics'
225
+ if root.exists() and any(root.iterdir()):
226
+ if not args.resume:
227
+ raise ValueError('output is nonempty; choose a new directory or use --resume for the same run')
228
+ if not (diag/'run_manifest.json').exists() and any(p.name not in {'report.log','diagnostics'} for p in root.iterdir()):
229
+ raise ValueError('resume requires an existing GAPMS run manifest')
230
+ root.mkdir(parents=True,exist_ok=True)
231
+ handler=logging.FileHandler(root/'report.log');handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(name)s: %(message)s'))
232
+ logger=logging.getLogger();level=logger.level;logger.setLevel(logging.INFO);logger.addHandler(handler)
233
+ internal=copy.copy(args);internal.output=diag
234
+ prior=diag/'run_manifest.json'
235
+ already_completed=prior.exists() and json.loads(prior.read_text()).get('status')=='completed'
236
+ try:
237
+ _run(internal)
238
+ if args.resume and already_completed and (root/'report.html').exists():
239
+ LOG.info('Results available: %s',root/'report.html');return
240
+ LOG.info('Publishing the result overview and review files')
241
+ publish(root,diag,args)
242
+ work=diag/'work'
243
+ if not args.keep_work and work.exists():
244
+ try:shutil.rmtree(work)
245
+ except OSError as error:LOG.warning('Temporary work could not be fully removed: %s',error)
246
+ manifest_path=diag/'run_manifest.json';manifest=json.loads(manifest_path.read_text())
247
+ manifest.update(status='completed',public_output=str(root),output_layout_version=1,work_retained=work.exists());write_json(manifest_path,manifest)
248
+ LOG.info('Results ready: %s',root/'report.html')
249
+ except BaseException as error:
250
+ path=diag/'run_manifest.json'
251
+ if path.exists():
252
+ manifest=json.loads(path.read_text());manifest.update(status='failed',error=str(error));write_json(path,manifest)
253
+ LOG.exception('Run failed; work and diagnostics retained')
254
+ raise
255
+ finally:
256
+ logger.removeHandler(handler);handler.close();logger.setLevel(level)