gapms 1.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gapms-1.3.2.dist-info/METADATA +92 -0
- gapms-1.3.2.dist-info/RECORD +69 -0
- gapms-1.3.2.dist-info/WHEEL +5 -0
- gapms-1.3.2.dist-info/entry_points.txt +3 -0
- gapms-1.3.2.dist-info/licenses/LICENSE +21 -0
- gapms-1.3.2.dist-info/licenses/THIRD_PARTY.md +21 -0
- gapms-1.3.2.dist-info/top_level.txt +1 -0
- gapms_v1/__init__.py +2 -0
- gapms_v1/__main__.py +2 -0
- gapms_v1/_genesensus/LICENSE +27 -0
- gapms_v1/_genesensus/VENDORED.json +53 -0
- gapms_v1/_genesensus/__init__.py +10 -0
- gapms_v1/_genesensus/__main__.py +4 -0
- gapms_v1/_genesensus/adaptive.py +157 -0
- gapms_v1/_genesensus/annotation.py +126 -0
- gapms_v1/_genesensus/available.py +64 -0
- gapms_v1/_genesensus/cli.py +149 -0
- gapms_v1/_genesensus/config.py +274 -0
- gapms_v1/_genesensus/corroborated.py +60 -0
- gapms_v1/_genesensus/diagnostics.py +19 -0
- gapms_v1/_genesensus/direct_molecular.py +29 -0
- gapms_v1/_genesensus/exchange.py +115 -0
- gapms_v1/_genesensus/exon_support.py +36 -0
- gapms_v1/_genesensus/genome.py +122 -0
- gapms_v1/_genesensus/graph.py +279 -0
- gapms_v1/_genesensus/graph_cache.py +175 -0
- gapms_v1/_genesensus/intervals.py +104 -0
- gapms_v1/_genesensus/isoform_guards.py +54 -0
- gapms_v1/_genesensus/isoforms.py +117 -0
- gapms_v1/_genesensus/joint.py +60 -0
- gapms_v1/_genesensus/loading.py +166 -0
- gapms_v1/_genesensus/local_molecular.py +112 -0
- gapms_v1/_genesensus/locus_select.py +137 -0
- gapms_v1/_genesensus/models.py +93 -0
- gapms_v1/_genesensus/molecular.py +222 -0
- gapms_v1/_genesensus/molecular_exchange.py +60 -0
- gapms_v1/_genesensus/molecular_state_utility.py +104 -0
- gapms_v1/_genesensus/molecular_strategy.py +83 -0
- gapms_v1/_genesensus/normalization.py +71 -0
- gapms_v1/_genesensus/orf_diagnostics.py +55 -0
- gapms_v1/_genesensus/peptide_context.py +167 -0
- gapms_v1/_genesensus/peptides.py +150 -0
- gapms_v1/_genesensus/pipeline.py +596 -0
- gapms_v1/_genesensus/provenance.py +54 -0
- gapms_v1/_genesensus/rna.py +175 -0
- gapms_v1/_genesensus/rna_geometry.py +114 -0
- gapms_v1/_genesensus/scoped.py +17 -0
- gapms_v1/_genesensus/scoring.py +46 -0
- gapms_v1/_genesensus/selection.py +336 -0
- gapms_v1/_genesensus/source_splice.py +19 -0
- gapms_v1/_genesensus/splice_prior.py +100 -0
- gapms_v1/_genesensus/state_utility.py +96 -0
- gapms_v1/_genesensus/support.py +189 -0
- gapms_v1/assessment.py +274 -0
- gapms_v1/classification.py +117 -0
- gapms_v1/cli.py +74 -0
- gapms_v1/common.py +67 -0
- gapms_v1/confidence_features.py +129 -0
- gapms_v1/consensus_engine.py +201 -0
- gapms_v1/mapping.py +144 -0
- gapms_v1/models.py +169 -0
- gapms_v1/orf_projection.py +249 -0
- gapms_v1/outputs.py +287 -0
- gapms_v1/peptides.py +54 -0
- gapms_v1/protein_mapper.py +125 -0
- gapms_v1/refinement.py +245 -0
- gapms_v1/report_figure.py +62 -0
- gapms_v1/rnaseq.py +91 -0
- gapms_v1/workflow.py +256 -0
gapms_v1/assessment.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Conservative model assessment and event-specific annotation proposals."""
|
|
2
|
+
from collections import Counter, defaultdict
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from peplocus.sequence import canonical
|
|
6
|
+
from .common import stable_id, write_table
|
|
7
|
+
from .models import write_models, write_proteins
|
|
8
|
+
|
|
9
|
+
MODEL_FIELDS=['model_id','source','original_transcript_id','gene_id','chrom','start','end','strand','category','distinct_peptides','locus_discriminating_peptides','non_nested_discriminating_peptides','peptides','mapping_ids','complete_start','complete_stop','issues','quality','reasons']
|
|
10
|
+
EVENT_FIELDS=['event_id','event_type','candidate_model_id','reference_model_ids','annotation_sources','chrom','start','end','strand','candidate_cds_blocks','reference_cds_blocks','relationship','peptides','mapping_ids','distinct_diagnostic_peptides','mapping_multiplicity','rna_junctions','minimum_rna_support','confidence','reasons','limitations','coding_structure_id','local_peptide_blocks','diagnostic_junctions','splice_chain_changed','whole_model_status','whole_model_review_reasons','uniqueness_scope','evidence_origin','boundary_status','cleavage_context','upstream_peptide_support','proposed_feature_blocks']
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def non_nested(sequences):
|
|
14
|
+
result=[]
|
|
15
|
+
for sequence in sorted(set(sequences),key=lambda s:(-len(s),s)):
|
|
16
|
+
if not any(sequence in longer for longer in result):result.append(sequence)
|
|
17
|
+
return result
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def interval_overlap(left,right):
|
|
21
|
+
return any(max(a,c)<min(b,d) for a,b in left for c,d in right)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ModelIndex:
|
|
25
|
+
"""Bin transcript extents; avoid candidate-by-entire-annotation comparisons."""
|
|
26
|
+
def __init__(self,models):
|
|
27
|
+
self.bins=defaultdict(list)
|
|
28
|
+
for m in models:
|
|
29
|
+
a=min(x for x,y in m.intervals);b=max(y for x,y in m.intervals)
|
|
30
|
+
for bin_id in range(a//100000,(b-1)//100000+1):self.bins[(m.chrom,bin_id)].append(m)
|
|
31
|
+
|
|
32
|
+
def overlap(self,model):
|
|
33
|
+
a=min(x for x,y in model.intervals);b=max(y for x,y in model.intervals);found={}
|
|
34
|
+
for bin_id in range(a//100000,(b-1)//100000+1):
|
|
35
|
+
for m in self.bins.get((model.chrom,bin_id),[]):
|
|
36
|
+
x=min(x for x,y in m.intervals);y=max(y for x,y in m.intervals)
|
|
37
|
+
if max(a,x)<min(b,y):found[m.id]=m
|
|
38
|
+
return sorted(found.values(),key=lambda m:m.id)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def relationship(candidate,references):
|
|
42
|
+
if not references:return 'intergenic'
|
|
43
|
+
same=[m for m in references if m.strand==candidate.strand]
|
|
44
|
+
if not same:return 'antisense'
|
|
45
|
+
overlapping=[m for m in same if interval_overlap(candidate.cds,m.cds)]
|
|
46
|
+
if not overlapping:
|
|
47
|
+
if any(interval_overlap(candidate.cds,m.exons) for m in same):return 'UTR_associated'
|
|
48
|
+
return 'intronic'
|
|
49
|
+
def frame_at(m,position):
|
|
50
|
+
offset=0
|
|
51
|
+
for a,b in m.coding:
|
|
52
|
+
if a<=position<b:return (offset+(position-a if m.strand=='+' else b-1-position))%3
|
|
53
|
+
offset+=b-a
|
|
54
|
+
for m in overlapping:
|
|
55
|
+
for a,b in candidate.cds:
|
|
56
|
+
for c,d in m.cds:
|
|
57
|
+
position=max(a,c)
|
|
58
|
+
if position<min(b,d) and frame_at(candidate,position)==frame_at(m,position):return 'new_transcript_isoform'
|
|
59
|
+
return 'overlapping_alternative_frame'
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def boundary(model,which):
|
|
63
|
+
segment=model.coding[0] if which=='start' else model.coding[-1]
|
|
64
|
+
if which=='start':return segment[0] if model.strand=='+' else segment[1]
|
|
65
|
+
return segment[1] if model.strand=='+' else segment[0]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def beyond(hit,reference,which):
|
|
69
|
+
point=boundary(reference,which)
|
|
70
|
+
left=min(a for a,b in hit['blocks']);right=max(b for a,b in hit['blocks'])
|
|
71
|
+
if which=='start':return left<point if reference.strand=='+' else right>point
|
|
72
|
+
return right>point if reference.strand=='+' else left<point
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def assess(args,models,store,metadata,rna_junctions,guided_events=None):
|
|
76
|
+
hits=store.model_hits();counts=store.counts();by_id={m.id:m for m in models}
|
|
77
|
+
qualities=defaultdict(list)
|
|
78
|
+
for p,item in metadata.items():qualities[canonical(p)].append(item['quality'])
|
|
79
|
+
def quality(sequences):
|
|
80
|
+
if sequences and all('qvalue_pass' in qualities[p] for p in sequences):return 'qvalue_pass'
|
|
81
|
+
if any('qvalue_fail' in qualities[p] and 'qvalue_pass' not in qualities[p] for p in sequences):return 'qvalue_fail'
|
|
82
|
+
return 'unknown'
|
|
83
|
+
records=[];categories={}
|
|
84
|
+
for model in models:
|
|
85
|
+
placements=hits[model.id];sequences={h['canonical'] for h in placements}
|
|
86
|
+
unique={p for p in sequences if counts[p]==1}
|
|
87
|
+
if not model.cds:category='no_CDS_annotation'
|
|
88
|
+
elif not sequences:category='no_observed_peptide_support'
|
|
89
|
+
elif model.issues:category='ambiguous'
|
|
90
|
+
elif unique:category='peptide_supported'
|
|
91
|
+
else:category='ambiguous'
|
|
92
|
+
categories[model.id]=category
|
|
93
|
+
records.append(dict(model_id=model.id,source=model.source,original_transcript_id=model.original_id,gene_id=model.gene,
|
|
94
|
+
chrom=model.chrom,start=min(a for a,b in model.intervals),end=max(b for a,b in model.intervals),strand=model.strand,
|
|
95
|
+
category=category,distinct_peptides=len(sequences),locus_discriminating_peptides=len(unique),
|
|
96
|
+
non_nested_discriminating_peptides=len(non_nested(unique)),peptides=sorted(sequences),mapping_ids=sorted({h['mapping_id'] for h in placements}),
|
|
97
|
+
complete_start=model.complete_start,complete_stop=model.complete_stop,issues=sorted(set(model.issues)),quality=quality(sequences),
|
|
98
|
+
reasons='no_observed_evidence_is_not_evidence_of_incorrect_annotation' if not sequences else 'placement_multiplicity_within_searched_genome_and_splice_paths; I/L aliases counted once'))
|
|
99
|
+
annotation=[m for m in models if m.source!='RNA_ORF'];candidates=[m for m in models if m.source=='RNA_ORF']
|
|
100
|
+
supported_candidates=[m for m in candidates if hits[m.id]]
|
|
101
|
+
if args.gtf:
|
|
102
|
+
directory=args.output/'annotation';directory.mkdir(exist_ok=True)
|
|
103
|
+
original_rows=[r for r in records if r['source']!='RNA_ORF']
|
|
104
|
+
write_table(directory/'gene_model_evidence.tsv',MODEL_FIELDS,original_rows)
|
|
105
|
+
for category,filename in [('no_observed_peptide_support','no_peptide_support_gene_models.tsv'),('ambiguous','ambiguous_gene_models.tsv')]:
|
|
106
|
+
write_table(directory/filename,MODEL_FIELDS,(r for r in original_rows if r['category']==category))
|
|
107
|
+
write_models([m for m in annotation if categories[m.id]=='peptide_supported'],directory/'supported_gene_models.gtf')
|
|
108
|
+
genes=defaultdict(list)
|
|
109
|
+
for r in original_rows:genes[(r['source'],r['chrom'],r['strand'],r['gene_id'])].append(r)
|
|
110
|
+
gene_rows=[]
|
|
111
|
+
for (source,chrom,strand,gene),rows in sorted(genes.items()):
|
|
112
|
+
sequences={p for row in rows for p in row['peptides']}
|
|
113
|
+
gene_rows.append(dict(source=source,chrom=chrom,strand=strand,gene_id=gene,models=len(rows),distinct_peptides=len(sequences),locus_discriminating_peptides=sum(counts[p]==1 for p in sequences),category='peptide_supported' if sequences else 'no_observed_peptide_support'))
|
|
114
|
+
write_table(directory/'gene_evidence.tsv',['source','chrom','strand','gene_id','models','distinct_peptides','locus_discriminating_peptides','category'],gene_rows)
|
|
115
|
+
if args.bam:
|
|
116
|
+
directory=args.output/'orfs'
|
|
117
|
+
rna_records=[r for r in records if r['source']=='RNA_ORF']
|
|
118
|
+
write_table(directory/'all_predicted_orf_evidence.tsv',MODEL_FIELDS,rna_records)
|
|
119
|
+
write_table(directory/'orf_peptide_evidence.tsv',MODEL_FIELDS,(r for r in rna_records if r['distinct_peptides']>0))
|
|
120
|
+
write_table(directory/'orfs_without_peptide_support.tsv',MODEL_FIELDS,(r for r in rna_records if r['distinct_peptides']==0))
|
|
121
|
+
write_models(supported_candidates,directory/'candidate_orfs.gtf')
|
|
122
|
+
write_proteins(supported_candidates,directory/'candidate_orfs.faa')
|
|
123
|
+
write_models(candidates,directory/'all_predicted_orfs.gtf')
|
|
124
|
+
write_proteins(candidates,directory/'all_predicted_orfs.faa')
|
|
125
|
+
write_table(directory/'partial_or_ambiguous_orfs.tsv',MODEL_FIELDS,(r for r in rna_records if r['distinct_peptides']>0 and (not r['complete_start'] or not r['complete_stop'] or r['category']=='ambiguous')))
|
|
126
|
+
(directory/'README.txt').write_text('candidate_orfs.gtf, candidate_orfs.faa and orf_peptide_evidence.tsv contain only RNA-derived ORFs with at least one exact/I-L-equivalent peptide placement. Shared or ambiguous support is retained and labeled; peptide support does not establish identification quality, isoform specificity, novelty or full-model correctness. all_predicted_orfs.gtf, all_predicted_orfs.faa and all_predicted_orf_evidence.tsv retain the complete reconstruction for audit. orfs_without_peptide_support.tsv lists predictions without observed peptide support; absence of support does not establish that an ORF is incorrect. partial_or_ambiguous_orfs.tsv contains only peptide-supported candidates.\n')
|
|
127
|
+
# Locus specificity alone does not distinguish alternative coding structures.
|
|
128
|
+
sequence_models=defaultdict(set)
|
|
129
|
+
for model in models:
|
|
130
|
+
for hit in hits[model.id]:sequence_models[hit['canonical']].add(model.id)
|
|
131
|
+
reference_index=ModelIndex(annotation)
|
|
132
|
+
reference_loci=defaultdict(set)
|
|
133
|
+
# Enzyme filtering controls positive support, not whether an existing
|
|
134
|
+
# annotated isoform already explains the observed genomic placement.
|
|
135
|
+
annotation_hits=store.model_hits(all_mappings=True,model_ids={m.id for m in annotation}) if annotation and candidates else {}
|
|
136
|
+
for m in annotation:
|
|
137
|
+
for hit in annotation_hits.get(m.id,[]):reference_loci[hit['canonical']].add((m.chrom,m.strand,tuple(tuple(b) for b in hit['blocks'])))
|
|
138
|
+
events=[];isoform_checks=[]
|
|
139
|
+
annotated_paths=defaultdict(list)
|
|
140
|
+
annotated_junctions_by_locus=defaultdict(set)
|
|
141
|
+
for model in annotation:
|
|
142
|
+
annotated_junctions_by_locus[model.chrom,model.strand].update(model.junctions)
|
|
143
|
+
annotated_junctions_by_locus[model.chrom,model.strand].update(
|
|
144
|
+
(a[1],b[0]) for a,b in zip(model.exons,model.exons[1:]) if a[1]<b[0])
|
|
145
|
+
for model in annotation:
|
|
146
|
+
if model.coding:annotated_paths[model.signature()].append(model.id)
|
|
147
|
+
for candidate in candidates:
|
|
148
|
+
# Without a supplied annotation, sequence support cannot establish novelty.
|
|
149
|
+
# Keep peptide-supported RNA ORFs in candidate_orfs and their evidence table.
|
|
150
|
+
if not hits[candidate.id] or not annotation:continue
|
|
151
|
+
refs=reference_index.overlap(candidate)
|
|
152
|
+
relation=relationship(candidate,refs)
|
|
153
|
+
all_hits=hits[candidate.id]
|
|
154
|
+
diagnostic=[h for h in all_hits if (candidate.chrom,candidate.strand,tuple(tuple(b) for b in h['blocks'])) not in reference_loci[h['canonical']]]
|
|
155
|
+
same=[m for m in refs if m.coding and relationship(candidate,[m])=='new_transcript_isoform']
|
|
156
|
+
known_starts=[m.id for m in same if boundary(m,'start')==boundary(candidate,'start')]
|
|
157
|
+
known_ends=[m.id for m in same if boundary(m,'end')==boundary(candidate,'end')]
|
|
158
|
+
# A known splice boundary is not new merely because its annotation
|
|
159
|
+
# has a different reading frame, gene ID or comparison-model subset.
|
|
160
|
+
annotated_junctions=annotated_junctions_by_locus[candidate.chrom,candidate.strand]
|
|
161
|
+
new_junctions=set(candidate.junctions)-annotated_junctions
|
|
162
|
+
exact=sorted(annotated_paths.get(candidate.signature(),[]))
|
|
163
|
+
isoform_checks.append(dict(candidate_model_id=candidate.id,chrom=candidate.chrom,strand=candidate.strand,coding_structure_id=stable_id('CDS',candidate.signature()),exact_annotated_isoform_ids=exact,comparable_annotated_isoform_ids=sorted(m.id for m in same),known_start_isoform_ids=sorted(known_starts),known_end_isoform_ids=sorted(known_ends),new_junctions=sorted(new_junctions),observed_peptide_sequences=len({h['canonical'] for h in all_hits}),diagnostic_peptide_sequences=len({h['canonical'] for h in diagnostic}),interpretation='exact_annotated_isoform' if exact else 'existing_isoforms_explain_all_observed_peptides' if not diagnostic else 'diagnostic_evidence_requires_feature_specific_review'))
|
|
164
|
+
if exact:continue
|
|
165
|
+
rna_keys=[(candidate.chrom,a,b,candidate.strand) for a,b in candidate.junctions]
|
|
166
|
+
minimum=min((rna_junctions.get(k,0) for k in rna_keys),default=0)
|
|
167
|
+
def event(kind,placements,related,extra='',rna_required=False):
|
|
168
|
+
if not placements:return
|
|
169
|
+
sequences={h['canonical'] for h in placements}
|
|
170
|
+
unique={p for p in sequences if counts[p]==1}
|
|
171
|
+
coherent=not candidate.issues and bool(candidate.protein)
|
|
172
|
+
compatible=set.intersection(*(sequence_models[p] for p in sequences)) - {candidate.id}
|
|
173
|
+
competitors=sorted(mid for mid in compatible if by_id[mid].signature()!=candidate.signature())
|
|
174
|
+
high=(len(non_nested(unique))>=2 and coherent and candidate.complete_start and candidate.complete_stop and quality(unique)=='qvalue_pass'
|
|
175
|
+
and set(candidate.protein)<=set('ACDEFGHIKLMNPQRSTVWY')
|
|
176
|
+
and (not rna_keys or minimum>=args.min_junction_support))
|
|
177
|
+
if rna_required and minimum<args.min_junction_support:high=False
|
|
178
|
+
if getattr(args,'splice_search_capped',False) or competitors:high=False
|
|
179
|
+
confidence='high_confidence_candidate' if high else ('rna_peptide_supported' if minimum>=args.min_junction_support and unique and coherent else 'peptide_supported' if unique and coherent else 'ambiguous')
|
|
180
|
+
if competitors:confidence='ambiguous'
|
|
181
|
+
limitations=['candidate_annotation_change_requires_review','peptide_identification_quality_'+quality(sequences),'RNA_junctions_do_not_prove_full_length_connectivity']
|
|
182
|
+
if any(counts[p]>1 for p in sequences):limitations.append('non_discriminating_peptides_present')
|
|
183
|
+
if len(non_nested(unique))<2:limitations.append('fewer_than_two_non_nested_locus_discriminating_peptides')
|
|
184
|
+
if competitors:limitations.append('equally_compatible_coding_models:'+','.join(competitors))
|
|
185
|
+
if set(candidate.protein)-set('ACDEFGHIKLMNPQRSTVWY*'):limitations.append('unresolved_amino_acids_in_candidate_ORF')
|
|
186
|
+
if candidate.issues:limitations.extend(candidate.issues)
|
|
187
|
+
if getattr(args,'splice_search_capped',False):limitations.append('splice_path_search_capped_uniqueness_incomplete')
|
|
188
|
+
if kind=='alternative_start':limitations.extend(['proteolytic_processing_not_excluded','initiation_site_not_experimentally_confirmed'])
|
|
189
|
+
if kind=='alternative_stop':limitations.append('stop_position_inferred_from_ORF_sequence')
|
|
190
|
+
if kind=='c_terminal_extension':limitations.append('termination_site_unresolved_no_complete_stop_codon')
|
|
191
|
+
limitations.append('uniqueness_is_relative_to_searched_splice_paths_not_all_possible_splicing')
|
|
192
|
+
review_reasons=[]
|
|
193
|
+
if not candidate.complete_start:review_reasons.append('incomplete_start')
|
|
194
|
+
if not candidate.complete_stop:review_reasons.append('incomplete_stop')
|
|
195
|
+
if candidate.issues:review_reasons.append('candidate_sequence_or_phase_issues')
|
|
196
|
+
if confidence=='ambiguous':review_reasons.append('ambiguous_diagnostic_evidence')
|
|
197
|
+
if any(rna_junctions.get(k,0)<args.min_junction_support for k in rna_keys):review_reasons.append('coding_junction_without_required_RNA_support')
|
|
198
|
+
if len(non_nested(unique))<2:review_reasons.append('fewer_than_two_independent_diagnostic_peptides')
|
|
199
|
+
genes={(m.source,m.gene) for m in related if m.strand==candidate.strand and interval_overlap(candidate.cds,m.cds)}
|
|
200
|
+
if len(genes)>1:review_reasons.append('overlaps_multiple_annotation_gene_ids_review_fusion_or_isoforms')
|
|
201
|
+
if any(any(sum(max(0,min(b,d)-max(a,c)) for c,d in candidate.coding)<b-a for a,b in m.coding) for m in related if m.coding):review_reasons.append('compared_annotation_CDS_not_fully_preserved_local_support_does_not_validate_deletions')
|
|
202
|
+
changed=any(set(candidate.junctions)!=set(m.junctions) for m in related if m.coding)
|
|
203
|
+
if kind in {'alternative_stop','c_terminal_extension'} and changed:limitations.append('terminal_change_accompanied_by_splice_chain_change')
|
|
204
|
+
# This is a context model, never a whole-gene replacement inferred from local evidence.
|
|
205
|
+
status='local_evidence_only' if review_reasons else 'complete_model_for_manual_review'
|
|
206
|
+
diagnostic_junctions=sorted({(a[1],b[0]) for h in placements for a,b in zip(h['blocks'],h['blocks'][1:]) if (a[1],b[0]) in new_junctions})
|
|
207
|
+
event_id=stable_id('E',kind,candidate.id,sorted(m.id for m in related))
|
|
208
|
+
events.append(dict(event_id=event_id,event_type=kind,candidate_model_id=candidate.id,
|
|
209
|
+
reference_model_ids=sorted(m.id for m in related),annotation_sources=sorted({m.source for m in related}),chrom=candidate.chrom,
|
|
210
|
+
start=min(a for a,b in candidate.cds),end=max(b for a,b in candidate.cds),strand=candidate.strand,
|
|
211
|
+
candidate_cds_blocks=sorted(candidate.coding),reference_cds_blocks={m.id:sorted(m.coding) for m in related},relationship=relation,
|
|
212
|
+
peptides=sorted(sequences),mapping_ids=sorted({h['mapping_id'] for h in placements}),distinct_diagnostic_peptides=len(sequences),
|
|
213
|
+
mapping_multiplicity={p:counts[p] for p in sorted(sequences)},rna_junctions=[dict(chrom=k[0],start=k[1],end=k[2],strand=k[3],reads=rna_junctions.get(k,0)) for k in rna_keys],
|
|
214
|
+
minimum_rna_support=minimum,confidence=confidence,coding_structure_id=stable_id('CDS',candidate.signature()),local_peptide_blocks=sorted({tuple(b) for h in placements for b in h['blocks']}),diagnostic_junctions=diagnostic_junctions,splice_chain_changed=changed,whole_model_status=status,whole_model_review_reasons=review_reasons,uniqueness_scope='searched_assembly_and_supplied_splice_paths',reasons=extra or 'direct_peptide_compatibility_with_candidate_coding_path',limitations=limitations))
|
|
215
|
+
if diagnostic and relation!='new_transcript_isoform':event('novel_orf',diagnostic,refs)
|
|
216
|
+
elif relation=='intergenic':event('novel_orf',all_hits,refs,'no_comparable_annotation_provided' if not annotation else 'intergenic_peptide_supported_ORF')
|
|
217
|
+
if same:
|
|
218
|
+
# A peptide elsewhere in the protein never supports a changed boundary/junction.
|
|
219
|
+
for ref in same:
|
|
220
|
+
if not known_starts and boundary(candidate,'start')!=boundary(ref,'start') and candidate.complete_start:
|
|
221
|
+
terminal=[h for h in diagnostic if beyond(h,ref,'start') and (h['aa_start']==0 or (h['aa_start']==1 and candidate.protein.startswith('M') and candidate.protein[1:2] in 'ACGPSTV'))]
|
|
222
|
+
event('alternative_start',terminal,[ref],'diagnostic_N_terminal_peptide; ATG_start; tryptic_and_initiator_processing_context_recorded')
|
|
223
|
+
if not known_ends and boundary(candidate,'end')!=boundary(ref,'end'):
|
|
224
|
+
terminal=[h for h in diagnostic if beyond(h,ref,'end')]
|
|
225
|
+
event('alternative_stop' if candidate.complete_stop else 'c_terminal_extension',terminal,[ref],'diagnostic_peptide_extends_beyond_annotated_coding_end')
|
|
226
|
+
crossing=[h for h in diagnostic if any((a[1],b[0]) in new_junctions for a,b in zip(h['blocks'],h['blocks'][1:]))]
|
|
227
|
+
if new_junctions:event('alternative_splice',crossing,same,'peptide_directly_crosses_junction_absent_from_overlapping_reference_CDS',True)
|
|
228
|
+
if args.bam:
|
|
229
|
+
write_table(args.output/'orfs/annotation_isoform_checks.tsv',['candidate_model_id','chrom','strand','coding_structure_id','exact_annotated_isoform_ids','comparable_annotated_isoform_ids','known_start_isoform_ids','known_end_isoform_ids','new_junctions','observed_peptide_sequences','diagnostic_peptide_sequences','interpretation'],isoform_checks)
|
|
230
|
+
# A coding model has one primary classification; component events remain auditable.
|
|
231
|
+
grouped=defaultdict(list)
|
|
232
|
+
for row in events:grouped[row['candidate_model_id']].append(row)
|
|
233
|
+
primary=[]
|
|
234
|
+
for model_id,rows in sorted(grouped.items()):
|
|
235
|
+
kinds=sorted({row['event_type'] for row in rows})
|
|
236
|
+
primary.append(dict(candidate_model_id=model_id,category=kinds[0] if len(kinds)==1 else 'combined_refinement',component_changes=kinds,event_ids=[row['event_id'] for row in rows]))
|
|
237
|
+
if args.bam:
|
|
238
|
+
write_table(args.output/'orfs/candidate_classification.tsv',['candidate_model_id','category','component_changes','event_ids'],primary)
|
|
239
|
+
for row in events:row['evidence_origin']='RNA_ORF'
|
|
240
|
+
rna_event_count=len(events)
|
|
241
|
+
events.extend(guided_events or [])
|
|
242
|
+
events.sort(key=lambda e:(e['chrom'],e['start'],e['strand'],e['event_type'],e['event_id']))
|
|
243
|
+
if args.bam:
|
|
244
|
+
directory=args.output/'orfs'
|
|
245
|
+
novel=[e for e in events if e['event_type']=='novel_orf']
|
|
246
|
+
write_table(directory/'novel_orf_candidates.tsv',EVENT_FIELDS,novel)
|
|
247
|
+
novel_models=[by_id[i] for i in sorted({e['candidate_model_id'] for e in novel}) if i in by_id]
|
|
248
|
+
write_models(novel_models,directory/'novel_orf_candidates.gtf');write_proteins(novel_models,directory/'novel_orf_candidates.faa')
|
|
249
|
+
if args.gtf:
|
|
250
|
+
directory=args.output/'refinement';directory.mkdir(exist_ok=True)
|
|
251
|
+
for kind in ['alternative_start','alternative_stop','alternative_splice','n_terminal_extension','c_terminal_extension']:
|
|
252
|
+
selected=[e for e in events if e['event_type']==kind]
|
|
253
|
+
write_table(directory/(kind+'_candidates.tsv'),EVENT_FIELDS,selected)
|
|
254
|
+
context_models=[by_id[i] for i in sorted({e['candidate_model_id'] for e in selected}) if i in by_id]
|
|
255
|
+
context_path=directory/(kind+'_rna_model_context.gtf')
|
|
256
|
+
if context_models:write_models(context_models,context_path)
|
|
257
|
+
else:context_path.unlink(missing_ok=True)
|
|
258
|
+
write_table(directory/'annotation_change_proposals.tsv',EVENT_FIELDS,events)
|
|
259
|
+
write_table(directory/'local_evidence_only.tsv',EVENT_FIELDS,(e for e in events if e['whole_model_status']=='local_evidence_only'))
|
|
260
|
+
write_table(directory/'complete_models_for_manual_review.tsv',EVENT_FIELDS,(e for e in events if e['whole_model_status']=='complete_model_for_manual_review'))
|
|
261
|
+
with (directory/'local_peptide_evidence.bed').open('w') as stream:
|
|
262
|
+
for e in events:
|
|
263
|
+
for i,(a,b) in enumerate(e['local_peptide_blocks'],1):
|
|
264
|
+
stream.write(f"{e['chrom']}\t{a}\t{b}\t{e['event_id']}.{i}\t0\t{e['strand']}\n")
|
|
265
|
+
(directory/'README.txt').write_text('Annotation-guided events have local features in annotation_guided_features.gtf; their candidate_model_id and full-CDS blocks are empty because no full transcript was inferred. RNA and annotation-guided rows can support the same local feature and are not counts of distinct genes. Files ending _rna_model_context.gtf contain full RNA models for context and manual review only. They are not corrected annotations or automatic replacements. Local peptide blocks and diagnostic junctions in the event tables delimit the direct evidence. local_peptide_evidence.bed contains separate supported blocks (BED6), not reconstructed CDSs. Complete models still require independent full-structure validation. IDs are run-scoped; join with the run/crop. Coding structure IDs collapse duplicate CDS paths within an assembly; retain run identity across assemblies.\n')
|
|
266
|
+
# Traceable individual protein occurrences, including N-terminal cleavage context.
|
|
267
|
+
occurrence_rows=[]
|
|
268
|
+
for model in models:
|
|
269
|
+
for h in hits[model.id]:
|
|
270
|
+
previous=model.protein[h['aa_start']-1] if h['aa_start'] else ''
|
|
271
|
+
first=model.protein[h['aa_start']:h['aa_start']+1]
|
|
272
|
+
occurrence_rows.append(dict(model_id=model.id,mapping_id=h['mapping_id'],peptide=h['peptide'],aa_start=h['aa_start'],aa_end=h['aa_end'],previous_aa=previous,n_terminal_context='protein_N_terminus' if not previous else 'tryptic' if previous in 'KR' and first!='P' else 'nontryptic',initiator_methionine_processing=h['aa_start']==1 and model.protein.startswith('M') and first in 'ACGPSTV'))
|
|
273
|
+
write_table(args.output/'mapping/model_peptide_occurrences.tsv',['model_id','mapping_id','peptide','aa_start','aa_end','previous_aa','n_terminal_context','initiator_methionine_processing'],occurrence_rows)
|
|
274
|
+
return dict(novelty_assessed=bool(annotation),rna_event_rows=rna_event_count,annotation_guided_event_rows=len(guided_events or []),isoform_checks=dict(Counter(row['interpretation'] for row in isoform_checks)),distinct_candidate_cds_paths=len({m.signature() for m in supported_candidates if m.coding}),distinct_predicted_cds_paths=len({m.signature() for m in candidates if m.coding}),whole_model_statuses=dict(Counter(e['whole_model_status'] for e in events)),models=len(models),annotation_models=len(annotation),predicted_orfs=len(candidates),candidate_orfs=len(supported_candidates),orfs_without_peptide_support=len(candidates)-len(supported_candidates),model_categories=dict(Counter(categories.values())),candidate_categories=dict(Counter(r['category'] for r in primary)),annotation_events=dict(Counter(e['event_type'] for e in events)),event_confidences=dict(Counter(e['confidence'] for e in events)))
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Legacy rule-seeded iterative classification, independent of consensus voting."""
|
|
2
|
+
from collections import defaultdict
|
|
3
|
+
import contextlib
|
|
4
|
+
import io
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
|
|
8
|
+
from sklearn.base import clone
|
|
9
|
+
from xgboost import XGBClassifier
|
|
10
|
+
from .confidence_features import engineer_features
|
|
11
|
+
from .confidence_features import get_high_confident_proteins, get_low_confident_proteins, ITERATIVE_FEATURE_COLS
|
|
12
|
+
from .common import LOG, write_json
|
|
13
|
+
from .models import load_models, write_models
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def features(models, hits, metadata):
|
|
17
|
+
"""Indexed peptide features; specificity is within this annotation pool."""
|
|
18
|
+
proteins=defaultdict(set);genes=defaultdict(set);occurrences={}
|
|
19
|
+
for m in models:
|
|
20
|
+
pp=defaultdict(set)
|
|
21
|
+
for h in hits.get(m.id,[]):
|
|
22
|
+
if metadata[h['peptide']]['quality']=='qvalue_fail':continue
|
|
23
|
+
pp[h['canonical']].add((h['aa_start'],h['aa_end']))
|
|
24
|
+
occurrences[m.id]=pp
|
|
25
|
+
for peptide in pp:
|
|
26
|
+
proteins[peptide].add(m.id);genes[peptide].add((m.chrom,m.strand,m.gene))
|
|
27
|
+
rows=[]
|
|
28
|
+
for m in models:
|
|
29
|
+
pp=occurrences[m.id];intervals=sorted({v for vv in pp.values() for v in vv})
|
|
30
|
+
covered=0;end=0
|
|
31
|
+
for a,b in intervals:covered+=max(0,b-max(a,end));end=max(end,b)
|
|
32
|
+
ordered=m.coding # Already in translation order on both strands.
|
|
33
|
+
boundaries=[];used=0
|
|
34
|
+
for i,(a,b) in enumerate(ordered[:-1]):
|
|
35
|
+
used+=b-a
|
|
36
|
+
following=ordered[i+1]
|
|
37
|
+
if (b<following[0] if m.strand=='+' else following[1]<a):boundaries.append(used)
|
|
38
|
+
def spans(v,j):return v[0]*3<j<v[1]*3
|
|
39
|
+
supported=sum(any(all(spans(v,j) for v in vv) for vv in pp.values()) for j in boundaries)
|
|
40
|
+
splice=sum(all(any(spans(v,j) for j in boundaries) for v in vv) for vv in pp.values())
|
|
41
|
+
rows.append(dict(Protein=m.id,model_id=m.id,source=m.source,original_id=m.original_id,original_transcript_id=m.original_id,
|
|
42
|
+
gene_id=m.gene,chrom=m.chrom,strand=m.strand,start=min(a for a,b in m.cds),end=max(b for a,b in m.cds),
|
|
43
|
+
sequence_coverage=round(covered/max(1,len(m.protein)),2),protein_length=len(m.protein),
|
|
44
|
+
mapped_peptides=len(pp),protein_specific_peptides=sum(len(proteins[p])==1 for p in pp),
|
|
45
|
+
gene_specific_peptides=sum(len(genes[p])==1 for p in pp),splice_peptides=splice,
|
|
46
|
+
internal_peptides=len(pp)-splice,splice_sites=len(boundaries),supported_splice_sites=supported,
|
|
47
|
+
N_terminal_peptides=sum(all(a==0 or (a==1 and m.protein.startswith('M')) for a,b in vv) for vv in pp.values()),
|
|
48
|
+
C_terminal_peptides=sum(all(b==len(m.protein) for a,b in vv) for vv in pp.values())))
|
|
49
|
+
return engineer_features(pd.DataFrame(rows))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def classify(df, directory, threads):
|
|
53
|
+
directory.mkdir(parents=True,exist_ok=True)
|
|
54
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
55
|
+
high=set(get_high_confident_proteins(df).index);low=set(get_low_confident_proteins(df).index)-high
|
|
56
|
+
initial=pd.Series('unlabeled',index=df.index)
|
|
57
|
+
initial.loc[list(high)]='high';initial.loc[list(low)]='low'
|
|
58
|
+
labels=pd.Series(np.nan,index=df.index);labels.loc[list(high)]=1;labels.loc[list(low)]=0
|
|
59
|
+
df=df.copy();df['seed_label']=initial;df['classifier_score']='NA'
|
|
60
|
+
audit=dict(high_seeds=len(high),low_seeds=len(low),initially_unlabeled=int((initial=='unlabeled').sum()),iterations=[],status='insufficient_seeds')
|
|
61
|
+
if min(len(high),len(low))>=2:
|
|
62
|
+
cv=StratifiedKFold(n_splits=min(5,len(high),len(low)),shuffle=True,random_state=42)
|
|
63
|
+
# Parallelize folds, each estimator uses one CPU: respect the job allocation.
|
|
64
|
+
search=RandomizedSearchCV(XGBClassifier(eval_metric='logloss',random_state=42,n_jobs=1),
|
|
65
|
+
dict(n_estimators=[100,200],max_depth=[3,5,7],learning_rate=[.01,.1],subsample=[.8,1.],
|
|
66
|
+
colsample_bytree=[.8,1.],scale_pos_weight=[1,2,5]),n_iter=20,scoring='roc_auc',cv=cv,
|
|
67
|
+
random_state=42,n_jobs=threads,pre_dispatch=threads)
|
|
68
|
+
ix=labels.notna();search.fit(df.loc[ix,ITERATIVE_FEATURE_COLS],labels[ix])
|
|
69
|
+
model=search.best_estimator_;audit.update(status='trained',best_parameters=search.best_params_,seed_cv_auroc=float(search.best_score_))
|
|
70
|
+
for iteration in range(1,6):
|
|
71
|
+
ix=labels.isna()
|
|
72
|
+
if not ix.any():break
|
|
73
|
+
probabilities=pd.Series(model.predict_proba(df.loc[ix,ITERATIVE_FEATURE_COLS])[:,1],index=df.index[ix])
|
|
74
|
+
pos=probabilities.index[probabilities>=.9];neg=probabilities.index[probabilities<=.1]
|
|
75
|
+
audit['iterations'].append(dict(iteration=iteration,new_positive=len(pos),new_negative=len(neg)))
|
|
76
|
+
if not len(pos)+len(neg):break
|
|
77
|
+
labels.loc[pos]=1;labels.loc[neg]=0;ix=labels.notna()
|
|
78
|
+
model=clone(model);model.fit(df.loc[ix,ITERATIVE_FEATURE_COLS],labels[ix])
|
|
79
|
+
df['classifier_score']=model.predict_proba(df[ITERATIVE_FEATURE_COLS])[:,1]
|
|
80
|
+
model.save_model(directory/'model.json')
|
|
81
|
+
df['iterative_label']=labels.fillna(-1).astype(int)
|
|
82
|
+
positive=df['classifier_score'].map(lambda p:False if p=='NA' else float(p)>=.5)
|
|
83
|
+
df['supported']=(initial=='high')|((initial=='unlabeled')&positive)
|
|
84
|
+
df['confidence']=np.where(initial=='high','high',np.where(df['supported'],'moderate',np.where(initial=='low','low','unresolved' if audit['status']!='trained' else 'not_supported')))
|
|
85
|
+
audit['supported']=int(df.supported.sum());write_json(directory/'summary.json',audit)
|
|
86
|
+
df.to_csv(directory/'scores.tsv',sep='\t',index=False)
|
|
87
|
+
LOG.info('Classifier %s: %s high seeds, %s low seeds, %s supported',audit['status'],len(high),len(low),audit['supported'])
|
|
88
|
+
return df,audit
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def run(args, models, store, metadata, peptides, matcher, reference, lengths):
|
|
92
|
+
directory=args.output/'classification';directory.mkdir(exist_ok=True)
|
|
93
|
+
pools=defaultdict(list)
|
|
94
|
+
for m in models:
|
|
95
|
+
if m.protein:pools[m.source].append(m)
|
|
96
|
+
if len(args.gtf)>1:
|
|
97
|
+
annotation=args.output/'consensus/annotation.gff3'
|
|
98
|
+
has_cds=any('\tCDS\t' in line for line in annotation.open())
|
|
99
|
+
selected=load_models(annotation,'CONSENSUS',reference,lengths,args.genetic_code) if has_cds else []
|
|
100
|
+
for m in selected:m.id=m.original_id
|
|
101
|
+
selected=[m for m in selected if m.protein]
|
|
102
|
+
if selected:
|
|
103
|
+
work=args.output/'work/classifier_consensus';work.mkdir(exist_ok=True)
|
|
104
|
+
before=store.counts();store.associate(selected,peptides,work,reference,args.genetic_code,matcher=matcher)
|
|
105
|
+
if before!=store.counts():raise RuntimeError('Classification changed the peptide mapping universe')
|
|
106
|
+
pools['CONSENSUS']=selected
|
|
107
|
+
hits=store.model_hits();tables=[];summaries={};supported=[]
|
|
108
|
+
for source,pool in sorted(pools.items()):
|
|
109
|
+
df,audit=classify(features(pool,hits,metadata),directory/source,args.threads)
|
|
110
|
+
df['classification_pool']=source;tables.append(df);summaries[source]=audit
|
|
111
|
+
if source=='CONSENSUS' or (len(args.gtf)<2 and source!='RNA_ORF'):
|
|
112
|
+
keep=set(df.loc[df.supported,'model_id']);supported.extend(m for m in pool if m.id in keep)
|
|
113
|
+
elif not args.gtf and source=='RNA_ORF':
|
|
114
|
+
keep=set(df.loc[df.supported,'model_id']);supported.extend(m for m in pool if m.id in keep)
|
|
115
|
+
if tables:pd.concat(tables,ignore_index=True).to_csv(directory/'scores.tsv',sep='\t',index=False)
|
|
116
|
+
write_models(supported,directory/'supported_genes.gtf');write_json(directory/'summary.json',summaries)
|
|
117
|
+
return summaries
|
gapms_v1/cli.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Four biological input types; all other options control technical policy."""
|
|
2
|
+
import argparse
|
|
3
|
+
import logging
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import __version__
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def positive(text):
|
|
11
|
+
value = int(text)
|
|
12
|
+
if value < 1:
|
|
13
|
+
raise argparse.ArgumentTypeError('must be positive')
|
|
14
|
+
return value
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parser(advanced=False):
|
|
18
|
+
p = argparse.ArgumentParser(prog='gapms',description='GAPMS v1: peptide-driven genome mapping and annotation evidence')
|
|
19
|
+
p.add_argument('--help-all', action='store_true', help='show all controls and exit')
|
|
20
|
+
p.add_argument('--version', action='version', version=f'GAPMS v1 {__version__}')
|
|
21
|
+
p.add_argument('-a', '--assembly', type=Path, required=True)
|
|
22
|
+
p.add_argument('-p', '--peptides', type=Path, required=True)
|
|
23
|
+
p.add_argument('-g', '--gtf', '--gff', type=Path, action='append', default=[], help='repeat for automatic peptide-guided consensus of all supplied sources')
|
|
24
|
+
p.add_argument('-b', '--bam', type=Path)
|
|
25
|
+
p.add_argument('-o', '--output', type=Path, default=Path('GAPMS_output'), help='output directory (default: ./GAPMS_output)')
|
|
26
|
+
p.add_argument('-t', '--threads', type=positive, default=8)
|
|
27
|
+
p.add_argument('--non-tryptic', action='store_true', help='use all exact placements as evidence instead of only trypsin-compatible placements')
|
|
28
|
+
p.add_argument('--peptide-column')
|
|
29
|
+
p.add_argument('--min-length', type=positive, default=7, help='minimum exact-match peptide length (default: 7); excluded queries are reported')
|
|
30
|
+
p.add_argument('--genetic-code', type=positive, default=1)
|
|
31
|
+
p.add_argument('--rescue-one-edit', action='store_true', help='separate exploratory rescue; never used as exact model/event evidence')
|
|
32
|
+
p.add_argument('--min-rescue-length', '--rescue-min-length', dest='rescue_min_length', type=positive, default=9)
|
|
33
|
+
p.add_argument('--min-junction-support', type=positive, default=2)
|
|
34
|
+
p.add_argument('--min-mapq', type=int, default=10)
|
|
35
|
+
p.add_argument('--min-read-anchor', type=positive, default=8)
|
|
36
|
+
p.add_argument('--max-junctions', type=positive, default=3)
|
|
37
|
+
p.add_argument('--max-paths-per-junction', type=int, default=1000)
|
|
38
|
+
p.add_argument('--min-orf-aa', type=positive, default=100, help='TransDecoder minimum ORF size (default: 100 aa; partial/single-peptide ORFs remain reportable)')
|
|
39
|
+
p.add_argument('--max-peptide-qvalue', type=float, default=0.01)
|
|
40
|
+
p.add_argument('--refinement-window', type=positive, default=3000, help='maximum contiguous CDS extension searched in nucleotides (default: 3000)')
|
|
41
|
+
p.add_argument('--refinement-splice-window', type=int, default=30, help='splice-site shift radius in nucleotides (default: 30; zero searches single-exon skips at existing sites)')
|
|
42
|
+
p.add_argument('--max-refinement-paths', type=positive, default=64, help='maximum canonical phase-preserving paths per local exon pair')
|
|
43
|
+
p.add_argument('--min-refinement-anchor', type=positive, default=9, help='minimum peptide nucleotides on each side of a discovered junction')
|
|
44
|
+
p.add_argument('--no-refinement-splice', action='store_true', help='disable annotation-guided local splice discovery; terminal refinement remains enabled')
|
|
45
|
+
p.add_argument('--consensus-beam', type=positive, default=8, help='bounded paths per graph start and phase')
|
|
46
|
+
p.add_argument('--consensus-max-nodes', type=positive, default=2000)
|
|
47
|
+
p.add_argument('--consensus-max-starts', type=positive, default=32)
|
|
48
|
+
p.add_argument('--consensus-max-candidates', type=positive, default=32, help='new graph candidates per locus; original models are never pruned')
|
|
49
|
+
p.add_argument('--rna-library', choices=['unstranded','firststrand','secondstrand'], default='unstranded', help='RNA library protocol for consensus evidence; default: unstranded')
|
|
50
|
+
p.add_argument('--keep-work', action='store_true', help='retain temporary search files after successful completion; failed runs always retain them')
|
|
51
|
+
p.add_argument('--resume', action='store_true', help='resume only when inputs, parameters and implementation fingerprint agree')
|
|
52
|
+
if not advanced:
|
|
53
|
+
essential={'help','help_all','version','assembly','peptides','gtf','bam','output','threads','non_tryptic'}
|
|
54
|
+
for action in p._actions:
|
|
55
|
+
if action.dest not in essential:action.help=argparse.SUPPRESS
|
|
56
|
+
return p
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def main(argv=None):
|
|
60
|
+
argv=sys.argv[1:] if argv is None else list(argv)
|
|
61
|
+
if '--help-all' in argv:
|
|
62
|
+
parser(advanced=True).print_help();return 0
|
|
63
|
+
args = parser().parse_args(argv)
|
|
64
|
+
del args.help_all
|
|
65
|
+
if args.refinement_splice_window < 0:parser().error('refinement splice window must be nonnegative')
|
|
66
|
+
if args.min_mapq < 0 or args.max_paths_per_junction < 0 or not 0 <= args.max_peptide_qvalue <= 1:
|
|
67
|
+
parser().error('MAPQ/path cap must be nonnegative and q-value must be in [0,1]')
|
|
68
|
+
from .workflow import run
|
|
69
|
+
try:
|
|
70
|
+
run(args)
|
|
71
|
+
except (ValueError, OSError, RuntimeError) as error:
|
|
72
|
+
logging.getLogger('gapms_v1').error('%s', error)
|
|
73
|
+
return 1
|
|
74
|
+
return 0
|
gapms_v1/common.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Deterministic identifiers, auditable tables and safe subprocess records."""
|
|
2
|
+
import csv
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import subprocess
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
LOG = logging.getLogger('gapms_v1')
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def stable_id(prefix, *values):
|
|
14
|
+
encoded = json.dumps(values, separators=(',', ':'), sort_keys=True).encode()
|
|
15
|
+
return prefix + hashlib.sha256(encoded).hexdigest()[:20]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def write_table(path, fields, rows):
|
|
19
|
+
path = Path(path)
|
|
20
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
with path.open('w') as handle:
|
|
22
|
+
writer = csv.DictWriter(handle, fieldnames=fields, delimiter='\t', lineterminator='\n', extrasaction='ignore')
|
|
23
|
+
writer.writeheader()
|
|
24
|
+
for row in rows:
|
|
25
|
+
writer.writerow({k: json.dumps(v, separators=(',', ':')) if isinstance(v, (list, dict, tuple)) else v for k, v in row.items() if k in fields})
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def read_table(path):
|
|
29
|
+
with Path(path).open() as handle:
|
|
30
|
+
yield from csv.DictReader(handle, delimiter='\t')
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def write_json(path, value):
|
|
34
|
+
path = Path(path)
|
|
35
|
+
tmp = path.with_suffix(path.suffix + '.partial')
|
|
36
|
+
tmp.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n')
|
|
37
|
+
tmp.replace(path)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def run_command(command, cwd, log, commands, env=None):
|
|
41
|
+
command = [str(v) for v in command]
|
|
42
|
+
entry = dict(command=command, cwd=str(cwd), started=time.time())
|
|
43
|
+
if env is not None:
|
|
44
|
+
entry['environment']={k:env[k] for k in ('PERL_HASH_SEED','PERL_PERTURB_KEYS') if k in env}
|
|
45
|
+
commands.append(entry)
|
|
46
|
+
LOG.info('Running %s', ' '.join(command))
|
|
47
|
+
with Path(log).open('w') as stream:
|
|
48
|
+
result = subprocess.run(command, cwd=cwd, stdout=stream, stderr=subprocess.STDOUT, env=env)
|
|
49
|
+
entry.update(returncode=result.returncode, seconds=time.time() - entry['started'])
|
|
50
|
+
if result.returncode:
|
|
51
|
+
raise RuntimeError(f'{command[0]} failed ({result.returncode}); see {log}')
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def input_identity(path, checksum_limit=32 * 1024**2):
|
|
55
|
+
path = Path(path).resolve()
|
|
56
|
+
st = path.stat()
|
|
57
|
+
identity = dict(path=str(path), bytes=st.st_size, mtime_ns=st.st_mtime_ns)
|
|
58
|
+
if st.st_size <= checksum_limit:
|
|
59
|
+
identity['sha256'] = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
60
|
+
else:
|
|
61
|
+
with path.open('rb') as stream:
|
|
62
|
+
first = stream.read(1024**2)
|
|
63
|
+
stream.seek(max(0, st.st_size - 1024**2))
|
|
64
|
+
last = stream.read(1024**2)
|
|
65
|
+
identity['sampled_sha256'] = hashlib.sha256(first + last).hexdigest()
|
|
66
|
+
identity['checksum_scope'] = 'first_and_last_1MiB_plus_size_mtime; not full checksum'
|
|
67
|
+
return identity
|