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
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
"""Public inference API; optional evidence, graph reconstruction and guarded selection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
import time, json, csv, os, resource, traceback, uuid, fcntl, logging
|
|
10
|
+
import numpy as np
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .config import load_config, input_paths, bam_index_paths
|
|
13
|
+
from .provenance import (
|
|
14
|
+
sha256,
|
|
15
|
+
digest_object,
|
|
16
|
+
atomic_json,
|
|
17
|
+
software_record,
|
|
18
|
+
verify_inputs,
|
|
19
|
+
)
|
|
20
|
+
from .annotation import read_annotation, write_gff3
|
|
21
|
+
from .genome import Genome
|
|
22
|
+
from .models import Candidate
|
|
23
|
+
from .diagnostics import diagnostic_writer
|
|
24
|
+
from .normalization import normalize_phases
|
|
25
|
+
from .loading import load_sources
|
|
26
|
+
from .molecular import attach_molecular, local_risk, RiskTrack
|
|
27
|
+
from .peptides import read_bed, attach_peptides
|
|
28
|
+
from .support import Support
|
|
29
|
+
from .graph import loci, reconstruct
|
|
30
|
+
from .graph_cache import graph_candidates
|
|
31
|
+
from .selection import select, predictor_support, _structure
|
|
32
|
+
from .scoring import weighted_scores
|
|
33
|
+
from .intervals import intersection_length
|
|
34
|
+
from .isoforms import admit_isoforms, write_isoform_gff3
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class RunResult:
|
|
39
|
+
output: Path
|
|
40
|
+
annotation: Path
|
|
41
|
+
report: dict
|
|
42
|
+
reused: bool = False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
LOGGER = logging.getLogger("genesensus")
|
|
46
|
+
_GRAPH_GENOME = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _graph_initialize(path, index):
|
|
50
|
+
global _GRAPH_GENOME
|
|
51
|
+
_GRAPH_GENOME = Genome.from_index(path, index)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _graph_work(args):
|
|
55
|
+
models, junctions, settings = args
|
|
56
|
+
return reconstruct(models, _GRAPH_GENOME, junctions, **settings)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _frame_at(m, pos):
|
|
60
|
+
used = 0
|
|
61
|
+
for a, b in m.cds:
|
|
62
|
+
if a <= pos < b:
|
|
63
|
+
offset = (
|
|
64
|
+
used + pos - a if m.strand == "+" else m.length - used - (pos - a) - 1
|
|
65
|
+
)
|
|
66
|
+
return (offset - m.phase) % 3
|
|
67
|
+
used += b - a
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class InheritedRisk:
|
|
73
|
+
track: object
|
|
74
|
+
intervals: tuple
|
|
75
|
+
|
|
76
|
+
def risk(self, regions, gate=None):
|
|
77
|
+
intersections = tuple(
|
|
78
|
+
(max(a, x), min(b, y))
|
|
79
|
+
for a, b in self.intervals
|
|
80
|
+
for x, y in regions
|
|
81
|
+
if max(a, x) < min(b, y)
|
|
82
|
+
)
|
|
83
|
+
return self.track.risk(intersections, gate)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def inherit_local_risks(candidate, original_candidates):
|
|
87
|
+
"""Same-frame sequence priors only; never manufacture a novel protein q."""
|
|
88
|
+
m = candidate.model
|
|
89
|
+
for original in original_candidates:
|
|
90
|
+
o = original.model
|
|
91
|
+
if (m.contig, m.strand) != (o.contig, o.strand):
|
|
92
|
+
continue
|
|
93
|
+
valid = []
|
|
94
|
+
for a, b in m.cds:
|
|
95
|
+
for x, y in o.cds:
|
|
96
|
+
left, right = max(a, x), min(b, y)
|
|
97
|
+
if left < right and _frame_at(m, left) == _frame_at(o, left):
|
|
98
|
+
valid.append((left, right))
|
|
99
|
+
if valid:
|
|
100
|
+
for track in original.risks:
|
|
101
|
+
candidate.risks.append(InheritedRisk(track, tuple(valid)))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _rna_data(config, cache, threads, genome, fingerprints):
|
|
105
|
+
if "rna" not in config:
|
|
106
|
+
return None, dict(available=False)
|
|
107
|
+
from .rna import extract_junctions, write_junctions
|
|
108
|
+
|
|
109
|
+
geometry_mode=config.get("parameters",{}).get("selection_policy","legacy") in ("state_soft_admitted","state_splice_validated", "state_rna_corroborated", "state_molecular_guided")
|
|
110
|
+
spec = dict(config["rna"])
|
|
111
|
+
library = spec.pop("library", "unstranded")
|
|
112
|
+
if "junctions" in spec:
|
|
113
|
+
data = json.loads(Path(spec["junctions"]).read_text())
|
|
114
|
+
if data.get("format_version") != 1 or not data.get("references"):
|
|
115
|
+
raise ValueError(
|
|
116
|
+
"RNA junction cache requires format_version=1 and reference lengths"
|
|
117
|
+
)
|
|
118
|
+
if data.get("settings", {}).get("library", library) != library:
|
|
119
|
+
raise ValueError("RNA cache library mode differs from requested library")
|
|
120
|
+
for name, length in data.get("references", {}).items():
|
|
121
|
+
if genome.lengths.get(name) != length:
|
|
122
|
+
raise ValueError("Cached RNA/genome reference mismatch: " + name)
|
|
123
|
+
for row in data.get("junctions", []):
|
|
124
|
+
if (
|
|
125
|
+
len(row) != 5
|
|
126
|
+
or row[0] not in genome.lengths
|
|
127
|
+
or any(isinstance(v, bool) or not isinstance(v, int) for v in row[1:3])
|
|
128
|
+
or not 0 <= row[1] < row[2] <= genome.lengths[row[0]]
|
|
129
|
+
):
|
|
130
|
+
raise ValueError("Cached RNA junction/genome coordinate mismatch")
|
|
131
|
+
if geometry_mode and data.get('junctions') and not all(k in data for k in ['rna_chain_junctions','observed_internal_exon_counts']):
|
|
132
|
+
raise ValueError('This state policy requires observed RNA-chain geometry: supply an indexed BAM or a geometry cache produced by this release')
|
|
133
|
+
declared_minimum=data.get('alignment_geometry_provenance',{}).get('internal_exon_min_templates')
|
|
134
|
+
if geometry_mode and declared_minimum is not None and declared_minimum!=config['parameters']['minimum_rna_templates']:
|
|
135
|
+
raise ValueError('RNA cache discovery template threshold differs from the run configuration; regenerate the cache with matching settings')
|
|
136
|
+
if config['parameters']['selection_policy'] in ('state_rna_corroborated','state_molecular_guided') and data.get('junctions') and 'observed_internal_exon_counts_all' not in data:
|
|
137
|
+
raise ValueError('RNA corroboration requires unfiltered observed internal-exon counts; use an indexed BAM or a cache produced by this release')
|
|
138
|
+
return data, dict(
|
|
139
|
+
available=True, cached=True, records=len(data.get("junctions", []))
|
|
140
|
+
)
|
|
141
|
+
bam = spec.pop("bam")
|
|
142
|
+
expected = {path: fingerprints[path] for path in [bam] + bam_index_paths(bam)}
|
|
143
|
+
geometry_identity={}
|
|
144
|
+
if geometry_mode:
|
|
145
|
+
expected[str(genome.path)]=fingerprints[str(genome.path)]
|
|
146
|
+
geometry_identity=dict(helper=sha256(Path(__file__).parent/'rna_geometry.py'),minimum_templates=config['parameters']['minimum_rna_templates'])
|
|
147
|
+
key = digest_object(
|
|
148
|
+
dict(
|
|
149
|
+
geometry=geometry_identity,
|
|
150
|
+
inputs=expected,
|
|
151
|
+
references=genome.lengths,
|
|
152
|
+
library=library,
|
|
153
|
+
settings=spec,
|
|
154
|
+
extractor=sha256(Path(__file__).parent / "rna.py"),
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
path = cache / f"rna-{key}.json"
|
|
158
|
+
if path.is_file():
|
|
159
|
+
record = json.loads(path.read_text())
|
|
160
|
+
if record.get("identity") != key or digest_object(
|
|
161
|
+
record["payload"]
|
|
162
|
+
) != record.get("payload_digest"):
|
|
163
|
+
raise ValueError("RNA cache integrity check failed: " + str(path))
|
|
164
|
+
data = record["payload"]
|
|
165
|
+
return data, dict(available=True, cached=True, records=len(data["junctions"]))
|
|
166
|
+
data = extract_junctions(
|
|
167
|
+
bam, genome.lengths, threads=threads, library=library, **spec
|
|
168
|
+
)
|
|
169
|
+
if geometry_mode:
|
|
170
|
+
from .rna_geometry import augment_geometry
|
|
171
|
+
data=augment_geometry(bam,genome,data,threads=threads,minimum_templates=config['parameters']['minimum_rna_templates'])
|
|
172
|
+
verify_inputs(expected, "RNA cache")
|
|
173
|
+
atomic_json(
|
|
174
|
+
path, dict(identity=key, payload=data, payload_digest=digest_object(data))
|
|
175
|
+
)
|
|
176
|
+
return data, dict(available=True, cached=False, records=len(data["junctions"]))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _run(config_path, output, threads=None, cache=None, resume=False):
|
|
180
|
+
start = time.perf_counter()
|
|
181
|
+
LOGGER.info("Validating configuration and fingerprinting inputs")
|
|
182
|
+
config = load_config(config_path)
|
|
183
|
+
if threads is not None:
|
|
184
|
+
if threads < 1:
|
|
185
|
+
raise ValueError("threads must be positive")
|
|
186
|
+
config["parameters"]["threads"] = threads
|
|
187
|
+
p = config["parameters"]
|
|
188
|
+
software = software_record()
|
|
189
|
+
fingerprints = {path: sha256(path) for path in input_paths(config)}
|
|
190
|
+
identity = digest_object(
|
|
191
|
+
dict(
|
|
192
|
+
config=config,
|
|
193
|
+
inputs=fingerprints,
|
|
194
|
+
version=__version__,
|
|
195
|
+
code=software["package_code"],
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
output = Path(output).resolve()
|
|
199
|
+
if output.exists():
|
|
200
|
+
frozen = output / "provenance.json"
|
|
201
|
+
if not resume or not frozen.is_file():
|
|
202
|
+
raise ValueError(
|
|
203
|
+
"Output already exists; use --resume only for a completed identical run"
|
|
204
|
+
)
|
|
205
|
+
record = json.loads(frozen.read_text())
|
|
206
|
+
if record["run_identity"] != identity:
|
|
207
|
+
raise ValueError(
|
|
208
|
+
"Cannot resume: configuration, inputs or package code changed"
|
|
209
|
+
)
|
|
210
|
+
for rel, h in record["output_sha256"].items():
|
|
211
|
+
if sha256(output / rel) != h:
|
|
212
|
+
raise ValueError(
|
|
213
|
+
"Cannot resume: completed output checksum changed: " + rel
|
|
214
|
+
)
|
|
215
|
+
return RunResult(
|
|
216
|
+
output,
|
|
217
|
+
output / "annotation.gff3",
|
|
218
|
+
json.loads((output / "report.json").read_text()),
|
|
219
|
+
True,
|
|
220
|
+
)
|
|
221
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
222
|
+
work = output.with_name(
|
|
223
|
+
"." + output.name + ".partial." + str(os.getpid()) + "." + uuid.uuid4().hex[:10]
|
|
224
|
+
)
|
|
225
|
+
if work.exists():
|
|
226
|
+
raise ValueError("Partial directory already exists: " + str(work))
|
|
227
|
+
work.mkdir()
|
|
228
|
+
cache = Path(cache).resolve() if cache else output.parent / ".genesensus-cache"
|
|
229
|
+
cache.mkdir(parents=True, exist_ok=True)
|
|
230
|
+
timings = {"fingerprint_inputs": time.perf_counter() - start}
|
|
231
|
+
mark = time.perf_counter()
|
|
232
|
+
try:
|
|
233
|
+
with Genome(config["genome"]) as genome:
|
|
234
|
+
source_models, pool, phase_report, molecular_report, source_cache_report = (
|
|
235
|
+
load_sources(config, genome, fingerprints, cache)
|
|
236
|
+
)
|
|
237
|
+
LOGGER.info(
|
|
238
|
+
"Loaded %d original candidates; molecular validation complete",
|
|
239
|
+
len(pool),
|
|
240
|
+
)
|
|
241
|
+
original_candidates = list(pool.values())
|
|
242
|
+
isoform_source_models = {s: list(mm) for s, mm in source_models.items()}
|
|
243
|
+
protein_models = (
|
|
244
|
+
read_annotation(
|
|
245
|
+
config["proteins"]["annotation"],
|
|
246
|
+
"protein",
|
|
247
|
+
origin="protein_alignment",
|
|
248
|
+
)
|
|
249
|
+
if "proteins" in config
|
|
250
|
+
else []
|
|
251
|
+
)
|
|
252
|
+
# Protein alignments supply indexed segments/junctions, not hundreds
|
|
253
|
+
# of redundant, partial homolog paths or terminal boundary candidates.
|
|
254
|
+
protein_count = len(protein_models)
|
|
255
|
+
for model in protein_models:
|
|
256
|
+
if (
|
|
257
|
+
model.contig not in genome.lengths
|
|
258
|
+
or model.cds[-1][1] > genome.lengths[model.contig]
|
|
259
|
+
):
|
|
260
|
+
raise ValueError(
|
|
261
|
+
"Protein alignment/genome coordinate mismatch: "
|
|
262
|
+
+ model.identifier
|
|
263
|
+
)
|
|
264
|
+
for c in pool.values():
|
|
265
|
+
c.complete, c.canonical, _ = genome.assess(c.model)
|
|
266
|
+
timings["load_validate_inputs"] = time.perf_counter() - mark
|
|
267
|
+
mark = time.perf_counter()
|
|
268
|
+
rna, rna_report = _rna_data(
|
|
269
|
+
config, cache, p["threads"], genome, fingerprints
|
|
270
|
+
)
|
|
271
|
+
support = Support(rna, protein_models, p["minimum_rna_templates"])
|
|
272
|
+
peptides = {}
|
|
273
|
+
peptide_report = dict(available=False)
|
|
274
|
+
if 'peptides' in config and p['peptide_strategy'] != 'legacy':
|
|
275
|
+
peptides, peptide_report = read_bed(config['peptides']['bed'],
|
|
276
|
+
config['peptides'].get('sequences'), keep_ambiguous=True)
|
|
277
|
+
support.peptide_evidence = peptides
|
|
278
|
+
peptide_report['available'] = True
|
|
279
|
+
del protein_models
|
|
280
|
+
timings["rna_evidence"] = time.perf_counter() - mark
|
|
281
|
+
mark = time.perf_counter()
|
|
282
|
+
LOGGER.info(
|
|
283
|
+
"Optional alignment evidence loaded; starting graph reconstruction"
|
|
284
|
+
)
|
|
285
|
+
graph_reports = []
|
|
286
|
+
novel = []
|
|
287
|
+
graph_cache_report = dict(reused=False, disabled=not p["graph"])
|
|
288
|
+
if p["graph"]:
|
|
289
|
+
novel, graph_reports, graph_cache_report = graph_candidates(
|
|
290
|
+
pool, config, fingerprints, support, genome, cache
|
|
291
|
+
)
|
|
292
|
+
parent_lookup = {c.uid: c for c in pool.values()}
|
|
293
|
+
for model, parent_ids in novel:
|
|
294
|
+
if model.key in pool:
|
|
295
|
+
continue
|
|
296
|
+
c = Candidate(model, complete=True, canonical=True, graph_path=True)
|
|
297
|
+
originals = [
|
|
298
|
+
parent_lookup[uid]
|
|
299
|
+
for uid in parent_ids
|
|
300
|
+
if parent_lookup[uid].sources
|
|
301
|
+
]
|
|
302
|
+
inherit_local_risks(c, originals)
|
|
303
|
+
c.graph_evidence = dict(
|
|
304
|
+
parent_candidates=parent_ids,
|
|
305
|
+
molecular_score="unmeasured",
|
|
306
|
+
residue_evidence="same-frame_local_prior_not_a_rescored_protein",
|
|
307
|
+
)
|
|
308
|
+
pool[model.key] = c
|
|
309
|
+
LOGGER.info(
|
|
310
|
+
"Graph stage produced %d novel paths; cache reused=%s",
|
|
311
|
+
len(novel),
|
|
312
|
+
graph_cache_report.get("reused"),
|
|
313
|
+
)
|
|
314
|
+
candidates = sorted(pool.values(), key=lambda c: c.uid)
|
|
315
|
+
if p['selection_policy'] in ('state_splice_validated','state_rna_corroborated','state_molecular_guided'):
|
|
316
|
+
from Bio.Seq import Seq
|
|
317
|
+
for candidate in candidates:
|
|
318
|
+
if candidate.canonical:
|
|
319
|
+
continue
|
|
320
|
+
bad=[]
|
|
321
|
+
for a,b in candidate.model.introns:
|
|
322
|
+
if b-a<4:
|
|
323
|
+
bad.append((a,b));continue
|
|
324
|
+
left=genome.fetch(candidate.model.contig,a,a+2)
|
|
325
|
+
right=genome.fetch(candidate.model.contig,b-2,b)
|
|
326
|
+
if candidate.model.strand=='-':
|
|
327
|
+
left,right=str(Seq(right).reverse_complement()),str(Seq(left).reverse_complement())
|
|
328
|
+
if (left,right) not in {('GT','AG'),('GC','AG'),('AT','AC')}:
|
|
329
|
+
bad.append((a,b))
|
|
330
|
+
candidate.graph_evidence['noncanonical_introns']=bad
|
|
331
|
+
|
|
332
|
+
timings["graph_reconstruction"] = time.perf_counter() - mark
|
|
333
|
+
mark = time.perf_counter()
|
|
334
|
+
if "peptides" in config:
|
|
335
|
+
if p['peptide_strategy'] == 'legacy':
|
|
336
|
+
peptides, peptide_report = read_bed(
|
|
337
|
+
config["peptides"]["bed"], config["peptides"].get("sequences")
|
|
338
|
+
)
|
|
339
|
+
attach_peptides(candidates, peptides, genome)
|
|
340
|
+
else:
|
|
341
|
+
peptides.attach(candidates, genome)
|
|
342
|
+
peptide_report["available"] = True
|
|
343
|
+
timings["peptide_mapping"] = time.perf_counter() - mark
|
|
344
|
+
mark = time.perf_counter()
|
|
345
|
+
from .molecular_strategy import prepare as prepare_molecular_strategy
|
|
346
|
+
candidates, source_models, molecular_factory, molecular_strategy_report, diagnostic_events, vetoed_orfs = prepare_molecular_strategy(candidates, source_models, config, genome, fingerprints, cache, support)
|
|
347
|
+
if vetoed_orfs:
|
|
348
|
+
write_gff3(vetoed_orfs, work / "provisional_spurious.gff3")
|
|
349
|
+
atomic_json(work / "molecular_diagnostics.json", diagnostic_events)
|
|
350
|
+
# Numeric bulk scoring is the optional CUDA workload; irregular graph and
|
|
351
|
+
# local decisions remain CPU work. Scores do not impute missing values.
|
|
352
|
+
chains, _, _ = predictor_support(candidates)
|
|
353
|
+
features = []
|
|
354
|
+
available = []
|
|
355
|
+
for c in candidates:
|
|
356
|
+
risk, known = local_risk(c, c.model.cds, p["localizer_gate"])
|
|
357
|
+
molecular = (
|
|
358
|
+
(c.q * (1 - p["risk_strength"] * (risk if known else 0.0)))
|
|
359
|
+
if c.q is not None
|
|
360
|
+
else 0.0
|
|
361
|
+
)
|
|
362
|
+
features.append(
|
|
363
|
+
[
|
|
364
|
+
molecular,
|
|
365
|
+
len(c.peptides) / (len(c.peptides) + p["peptide_saturation"]),
|
|
366
|
+
support.rna_score(c.model),
|
|
367
|
+
support.protein_score(c.model),
|
|
368
|
+
_structure(c, len(source_models), chains),
|
|
369
|
+
]
|
|
370
|
+
)
|
|
371
|
+
available.append(
|
|
372
|
+
[
|
|
373
|
+
c.q is not None,
|
|
374
|
+
bool(peptides),
|
|
375
|
+
rna is not None,
|
|
376
|
+
protein_count > 0,
|
|
377
|
+
True,
|
|
378
|
+
]
|
|
379
|
+
)
|
|
380
|
+
LOGGER.info(
|
|
381
|
+
"Scoring %d candidates and selecting guarded alternatives",
|
|
382
|
+
len(candidates),
|
|
383
|
+
)
|
|
384
|
+
prior = weighted_scores(
|
|
385
|
+
np.asarray(features).reshape(-1,5),
|
|
386
|
+
np.asarray(available).reshape(-1,5),
|
|
387
|
+
[
|
|
388
|
+
p["molecular_weight"],
|
|
389
|
+
p["peptide_weight"],
|
|
390
|
+
p["rna_weight"],
|
|
391
|
+
p["protein_weight"],
|
|
392
|
+
p["structure_weight"],
|
|
393
|
+
],
|
|
394
|
+
p["backend"],
|
|
395
|
+
)
|
|
396
|
+
for c, value in zip(candidates, prior):
|
|
397
|
+
c.graph_evidence["global_evidence_score"] = float(value)
|
|
398
|
+
timings["bulk_scoring"] = time.perf_counter() - mark
|
|
399
|
+
mark = time.perf_counter()
|
|
400
|
+
selected, decisions, backbone = select(
|
|
401
|
+
candidates, source_models, peptides, support, p, molecular_factory=molecular_factory
|
|
402
|
+
)
|
|
403
|
+
timings["guarded_selection"] = time.perf_counter() - mark
|
|
404
|
+
isoform_start = time.perf_counter()
|
|
405
|
+
primary_count = len(selected)
|
|
406
|
+
if p['isoform_policy'] != 'off':
|
|
407
|
+
write_gff3([c.model for c in selected], work / 'primary_annotation.gff3')
|
|
408
|
+
isoform_parameters = dict(p, _isoform_rna_available='rna' in config)
|
|
409
|
+
isoform_added, isoform_parents, isoform_decisions, isoform_report = admit_isoforms(
|
|
410
|
+
selected, isoform_source_models, config['predictions'], support, genome, isoform_parameters)
|
|
411
|
+
selected = list(selected) + isoform_added
|
|
412
|
+
decisions.extend(isoform_decisions)
|
|
413
|
+
known_uids = {c.uid for c in candidates}
|
|
414
|
+
candidates.extend(c for c in isoform_added if c.uid not in known_uids)
|
|
415
|
+
if p['isoform_policy'] != 'off':
|
|
416
|
+
write_gff3([c.model for c in isoform_added], work / 'additional_isoforms.gff3')
|
|
417
|
+
atomic_json(work / 'isoforms.json', dict(summary=isoform_report, decisions=isoform_decisions, parent_by_candidate=isoform_parents))
|
|
418
|
+
timings['isoform_admission'] = time.perf_counter() - isoform_start
|
|
419
|
+
mark = time.perf_counter()
|
|
420
|
+
LOGGER.info(
|
|
421
|
+
"Selected %d models; writing and verifying outputs", len(selected)
|
|
422
|
+
)
|
|
423
|
+
write_isoform_gff3([c.model for c in selected], work / "annotation.gff3", isoform_parents)
|
|
424
|
+
with (work / "proteins.faa").open("w") as f:
|
|
425
|
+
for c in sorted(selected, key=lambda c: c.uid):
|
|
426
|
+
_, _, protein = genome.assess(c.model)
|
|
427
|
+
f.write(">GS.g" + c.uid + ".t1\n" + protein.rstrip("*") + "\n")
|
|
428
|
+
deferred = {d['candidate'] for d in decisions if d['event']=='provisional' and d['accepted']}
|
|
429
|
+
deferred -= {c.uid for c in selected}
|
|
430
|
+
if deferred:
|
|
431
|
+
provisional = [c for c in candidates if c.uid in deferred]
|
|
432
|
+
write_gff3([c.model for c in provisional], work / 'provisional.gff3')
|
|
433
|
+
with (work/'provisional_proteins.faa').open('w') as f:
|
|
434
|
+
for c in sorted(provisional,key=lambda c:c.uid):
|
|
435
|
+
_,_,protein=genome.assess(c.model)
|
|
436
|
+
f.write('>GS.g'+c.uid+'.t1\n'+protein.rstrip('*')+'\n')
|
|
437
|
+
if p['selection_policy'] in ('corroborated_tiered','molecular_tiered','joint_tiered','available_tiered'):
|
|
438
|
+
write_isoform_gff3([c.model for c in selected]+[c.model for c in candidates if c.uid in deferred], work/'full_annotation.gff3', isoform_parents)
|
|
439
|
+
if p['selection_policy']=='available_tiered':
|
|
440
|
+
strict = {d['candidate'] for d in decisions if d['event']=='consensus_provisional' and d['accepted']}
|
|
441
|
+
all_selected = list(selected)+[c for c in candidates if c.uid in deferred]
|
|
442
|
+
write_isoform_gff3([c.model for c in all_selected if c.uid not in strict],work/'consensus_annotation.gff3', isoform_parents)
|
|
443
|
+
write_gff3([c.model for c in all_selected if c.uid in strict],work/'consensus_provisional.gff3')
|
|
444
|
+
with (work/'consensus_provisional_proteins.faa').open('w') as f:
|
|
445
|
+
for c in sorted(all_selected,key=lambda c:c.uid):
|
|
446
|
+
if c.uid in strict:
|
|
447
|
+
_,_,protein=genome.assess(c.model)
|
|
448
|
+
f.write('>GS.g'+c.uid+'.t1\n'+protein.rstrip('*')+'\n')
|
|
449
|
+
ids = {c.uid for c in selected}
|
|
450
|
+
with diagnostic_writer(work / ("candidates.tsv.gz" if p["compress_diagnostics"] else "candidates.tsv"), p["compress_diagnostics"]) as f:
|
|
451
|
+
w = csv.writer(f, delimiter="\t")
|
|
452
|
+
w.writerow(
|
|
453
|
+
[
|
|
454
|
+
"candidate",
|
|
455
|
+
"contig",
|
|
456
|
+
"strand",
|
|
457
|
+
"CDS_0based_halfopen",
|
|
458
|
+
"origin",
|
|
459
|
+
"sources",
|
|
460
|
+
"source_ids",
|
|
461
|
+
"gene_q",
|
|
462
|
+
"q_measured",
|
|
463
|
+
"residue_tracks",
|
|
464
|
+
"complete",
|
|
465
|
+
"canonical",
|
|
466
|
+
"peptides",
|
|
467
|
+
"selected",
|
|
468
|
+
"graph_details",
|
|
469
|
+
]
|
|
470
|
+
)
|
|
471
|
+
for c in candidates:
|
|
472
|
+
w.writerow(
|
|
473
|
+
[
|
|
474
|
+
c.uid,
|
|
475
|
+
c.model.contig,
|
|
476
|
+
c.model.strand,
|
|
477
|
+
json.dumps(c.model.cds),
|
|
478
|
+
c.model.origin,
|
|
479
|
+
",".join(sorted(c.sources)),
|
|
480
|
+
json.dumps(c.original_ids,sort_keys=True),
|
|
481
|
+
c.q,
|
|
482
|
+
c.q is not None,
|
|
483
|
+
len(c.risks),
|
|
484
|
+
c.complete,
|
|
485
|
+
c.canonical,
|
|
486
|
+
len(c.peptides),
|
|
487
|
+
c.uid in ids,
|
|
488
|
+
json.dumps(c.graph_evidence, sort_keys=True),
|
|
489
|
+
]
|
|
490
|
+
)
|
|
491
|
+
with diagnostic_writer(work / ("decisions.jsonl.gz" if p["compress_diagnostics"] else "decisions.jsonl"), p["compress_diagnostics"]) as f:
|
|
492
|
+
for d in decisions:
|
|
493
|
+
f.write(json.dumps(d, sort_keys=True, allow_nan=False) + "\n")
|
|
494
|
+
atomic_json(work / "graph_report.json", graph_reports)
|
|
495
|
+
timings["write_outputs"] = time.perf_counter() - mark
|
|
496
|
+
mark = time.perf_counter()
|
|
497
|
+
for path, h in fingerprints.items():
|
|
498
|
+
if sha256(path) != h:
|
|
499
|
+
raise ValueError("Input changed while inference was running: " + path)
|
|
500
|
+
for name, h in software["package_code"].items():
|
|
501
|
+
if sha256(Path(__file__).with_name(name)) != h:
|
|
502
|
+
raise ValueError(
|
|
503
|
+
"Package code changed while inference was running: " + name
|
|
504
|
+
)
|
|
505
|
+
timings["verify_inputs"] = time.perf_counter() - mark
|
|
506
|
+
timings["total_seconds"] = time.perf_counter() - start
|
|
507
|
+
report = dict(
|
|
508
|
+
version=__version__,
|
|
509
|
+
predictors={s: len(mm) for s, mm in source_models.items()},
|
|
510
|
+
candidate_count=len(candidates),
|
|
511
|
+
graph_cache=graph_cache_report,
|
|
512
|
+
selected_count=len(selected),
|
|
513
|
+
primary_selected_count=primary_count,
|
|
514
|
+
isoforms=isoform_report,
|
|
515
|
+
diagnostics_compressed=p["compress_diagnostics"],
|
|
516
|
+
provisional_count=sum(d["event"]=="provisional" and d["accepted"] for d in decisions),
|
|
517
|
+
consensus_provisional_count=sum(d["event"]=="consensus_provisional" and d["accepted"] for d in decisions),
|
|
518
|
+
novel_graph_candidates=sum(c.graph_path for c in candidates),
|
|
519
|
+
selected_graph_candidates=sum(c.graph_path for c in selected),
|
|
520
|
+
backbone=backbone,
|
|
521
|
+
molecular=molecular_report,
|
|
522
|
+
molecular_strategy=molecular_strategy_report,
|
|
523
|
+
source_cache=source_cache_report,
|
|
524
|
+
phase_validation=phase_report,
|
|
525
|
+
peptides=peptide_report,
|
|
526
|
+
rna=rna_report,
|
|
527
|
+
protein_alignment_models=protein_count,
|
|
528
|
+
timings=timings,
|
|
529
|
+
peak_parent_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
|
|
530
|
+
max_finished_child_rss_kib=resource.getrusage(
|
|
531
|
+
resource.RUSAGE_CHILDREN
|
|
532
|
+
).ru_maxrss,
|
|
533
|
+
accepted_additions=sum(
|
|
534
|
+
d["accepted"] and d["event"] == "addition" for d in decisions
|
|
535
|
+
),
|
|
536
|
+
accepted_replacements=sum(
|
|
537
|
+
d["accepted"] and d["event"] == "replacement" for d in decisions
|
|
538
|
+
),
|
|
539
|
+
reference_used=False,
|
|
540
|
+
trained=molecular_strategy_report["trained"],
|
|
541
|
+
reference_trained=False,
|
|
542
|
+
backend=p["backend"],
|
|
543
|
+
)
|
|
544
|
+
atomic_json(work / "report.json", report)
|
|
545
|
+
atomic_json(work / "configuration.json", config)
|
|
546
|
+
outputs = {p.name: sha256(p) for p in work.iterdir() if p.is_file()}
|
|
547
|
+
atomic_json(
|
|
548
|
+
work / "provenance.json",
|
|
549
|
+
dict(
|
|
550
|
+
run_identity=identity,
|
|
551
|
+
created_utc=datetime.now(timezone.utc).isoformat(),
|
|
552
|
+
input_sha256=fingerprints,
|
|
553
|
+
output_sha256=outputs,
|
|
554
|
+
software=software,
|
|
555
|
+
reference_used=False,
|
|
556
|
+
trained=molecular_strategy_report["trained"],
|
|
557
|
+
reference_trained=False,
|
|
558
|
+
),
|
|
559
|
+
)
|
|
560
|
+
if output.exists():
|
|
561
|
+
raise ValueError("Output appeared during run; refusing overwrite")
|
|
562
|
+
os.rename(work, output)
|
|
563
|
+
return RunResult(output, output / "annotation.gff3", report)
|
|
564
|
+
except BaseException as exc:
|
|
565
|
+
atomic_json(
|
|
566
|
+
work / "failure.json",
|
|
567
|
+
dict(
|
|
568
|
+
error=type(exc).__name__,
|
|
569
|
+
message=str(exc),
|
|
570
|
+
traceback=traceback.format_exc(),
|
|
571
|
+
completed=False,
|
|
572
|
+
),
|
|
573
|
+
)
|
|
574
|
+
raise
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def run(config_path, output, threads=None, cache=None, resume=False):
|
|
578
|
+
"""Run with an OS-released advisory lock and atomic completed output publication."""
|
|
579
|
+
target = Path(output).resolve()
|
|
580
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
581
|
+
lockpath = target.parent / ("." + target.name + ".lock")
|
|
582
|
+
with lockpath.open("a+") as lock:
|
|
583
|
+
try:
|
|
584
|
+
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
585
|
+
except BlockingIOError as exc:
|
|
586
|
+
raise RuntimeError(
|
|
587
|
+
"Another GeneSensus run owns this output: " + str(target)
|
|
588
|
+
) from exc
|
|
589
|
+
lock.seek(0)
|
|
590
|
+
lock.truncate()
|
|
591
|
+
lock.write(json.dumps(dict(pid=os.getpid(), output=str(target))) + "\n")
|
|
592
|
+
lock.flush()
|
|
593
|
+
try:
|
|
594
|
+
return _run(config_path, target, threads, cache, resume)
|
|
595
|
+
finally:
|
|
596
|
+
fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Content fingerprints and atomic JSON writes; no mutation of input files."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import hashlib, json, os, platform, sys, importlib.metadata, uuid
|
|
5
|
+
from . import __version__
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def sha256(path):
|
|
9
|
+
digest = hashlib.sha256()
|
|
10
|
+
with Path(path).open("rb") as f:
|
|
11
|
+
for block in iter(lambda: f.read(8 << 20), b""):
|
|
12
|
+
digest.update(block)
|
|
13
|
+
return digest.hexdigest()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def digest_object(obj):
|
|
17
|
+
return hashlib.sha256(
|
|
18
|
+
json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
|
|
19
|
+
).hexdigest()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def verify_inputs(expected, context):
|
|
23
|
+
"""Do not publish derived cache data under fingerprints of changed inputs."""
|
|
24
|
+
for path, digest in expected.items():
|
|
25
|
+
if sha256(path) != digest:
|
|
26
|
+
raise ValueError(f"Input changed before publishing {context}: {path}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def atomic_json(path, value):
|
|
30
|
+
path = Path(path)
|
|
31
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
tmp = path.with_name(
|
|
33
|
+
path.name + ".tmp." + str(os.getpid()) + "." + uuid.uuid4().hex
|
|
34
|
+
)
|
|
35
|
+
with tmp.open("w") as f:
|
|
36
|
+
json.dump(value, f, sort_keys=True, indent=2, allow_nan=False)
|
|
37
|
+
f.write("\n")
|
|
38
|
+
os.replace(tmp, path)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def software_record():
|
|
42
|
+
versions = {}
|
|
43
|
+
for package in ["numpy", "biopython", "pysam", "h5py", "torch"]:
|
|
44
|
+
try:
|
|
45
|
+
versions[package] = importlib.metadata.version(package)
|
|
46
|
+
except importlib.metadata.PackageNotFoundError:
|
|
47
|
+
pass
|
|
48
|
+
return dict(
|
|
49
|
+
genesensus=__version__,
|
|
50
|
+
python=sys.version,
|
|
51
|
+
platform=platform.platform(),
|
|
52
|
+
dependencies=versions,
|
|
53
|
+
package_code={p.name: sha256(p) for p in Path(__file__).parent.glob("*.py")},
|
|
54
|
+
)
|