gapms 1.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. gapms-1.3.2.dist-info/METADATA +92 -0
  2. gapms-1.3.2.dist-info/RECORD +69 -0
  3. gapms-1.3.2.dist-info/WHEEL +5 -0
  4. gapms-1.3.2.dist-info/entry_points.txt +3 -0
  5. gapms-1.3.2.dist-info/licenses/LICENSE +21 -0
  6. gapms-1.3.2.dist-info/licenses/THIRD_PARTY.md +21 -0
  7. gapms-1.3.2.dist-info/top_level.txt +1 -0
  8. gapms_v1/__init__.py +2 -0
  9. gapms_v1/__main__.py +2 -0
  10. gapms_v1/_genesensus/LICENSE +27 -0
  11. gapms_v1/_genesensus/VENDORED.json +53 -0
  12. gapms_v1/_genesensus/__init__.py +10 -0
  13. gapms_v1/_genesensus/__main__.py +4 -0
  14. gapms_v1/_genesensus/adaptive.py +157 -0
  15. gapms_v1/_genesensus/annotation.py +126 -0
  16. gapms_v1/_genesensus/available.py +64 -0
  17. gapms_v1/_genesensus/cli.py +149 -0
  18. gapms_v1/_genesensus/config.py +274 -0
  19. gapms_v1/_genesensus/corroborated.py +60 -0
  20. gapms_v1/_genesensus/diagnostics.py +19 -0
  21. gapms_v1/_genesensus/direct_molecular.py +29 -0
  22. gapms_v1/_genesensus/exchange.py +115 -0
  23. gapms_v1/_genesensus/exon_support.py +36 -0
  24. gapms_v1/_genesensus/genome.py +122 -0
  25. gapms_v1/_genesensus/graph.py +279 -0
  26. gapms_v1/_genesensus/graph_cache.py +175 -0
  27. gapms_v1/_genesensus/intervals.py +104 -0
  28. gapms_v1/_genesensus/isoform_guards.py +54 -0
  29. gapms_v1/_genesensus/isoforms.py +117 -0
  30. gapms_v1/_genesensus/joint.py +60 -0
  31. gapms_v1/_genesensus/loading.py +166 -0
  32. gapms_v1/_genesensus/local_molecular.py +112 -0
  33. gapms_v1/_genesensus/locus_select.py +137 -0
  34. gapms_v1/_genesensus/models.py +93 -0
  35. gapms_v1/_genesensus/molecular.py +222 -0
  36. gapms_v1/_genesensus/molecular_exchange.py +60 -0
  37. gapms_v1/_genesensus/molecular_state_utility.py +104 -0
  38. gapms_v1/_genesensus/molecular_strategy.py +83 -0
  39. gapms_v1/_genesensus/normalization.py +71 -0
  40. gapms_v1/_genesensus/orf_diagnostics.py +55 -0
  41. gapms_v1/_genesensus/peptide_context.py +167 -0
  42. gapms_v1/_genesensus/peptides.py +150 -0
  43. gapms_v1/_genesensus/pipeline.py +596 -0
  44. gapms_v1/_genesensus/provenance.py +54 -0
  45. gapms_v1/_genesensus/rna.py +175 -0
  46. gapms_v1/_genesensus/rna_geometry.py +114 -0
  47. gapms_v1/_genesensus/scoped.py +17 -0
  48. gapms_v1/_genesensus/scoring.py +46 -0
  49. gapms_v1/_genesensus/selection.py +336 -0
  50. gapms_v1/_genesensus/source_splice.py +19 -0
  51. gapms_v1/_genesensus/splice_prior.py +100 -0
  52. gapms_v1/_genesensus/state_utility.py +96 -0
  53. gapms_v1/_genesensus/support.py +189 -0
  54. gapms_v1/assessment.py +274 -0
  55. gapms_v1/classification.py +117 -0
  56. gapms_v1/cli.py +74 -0
  57. gapms_v1/common.py +67 -0
  58. gapms_v1/confidence_features.py +129 -0
  59. gapms_v1/consensus_engine.py +201 -0
  60. gapms_v1/mapping.py +144 -0
  61. gapms_v1/models.py +169 -0
  62. gapms_v1/orf_projection.py +249 -0
  63. gapms_v1/outputs.py +287 -0
  64. gapms_v1/peptides.py +54 -0
  65. gapms_v1/protein_mapper.py +125 -0
  66. gapms_v1/refinement.py +245 -0
  67. gapms_v1/report_figure.py +62 -0
  68. gapms_v1/rnaseq.py +91 -0
  69. gapms_v1/workflow.py +256 -0
@@ -0,0 +1,175 @@
1
+ """Content-addressed, bounded graph geometry cache independent of score channels."""
2
+
3
+ from pathlib import Path
4
+ from dataclasses import asdict
5
+ from concurrent.futures import ProcessPoolExecutor
6
+ import gzip, json, os, uuid
7
+ from .genome import Genome
8
+ from .graph import loci, reconstruct
9
+ from .models import Transcript
10
+ from .provenance import digest_object, sha256, verify_inputs
11
+ from .config import bam_index_paths
12
+
13
+ _GENOME = None
14
+
15
+
16
+ def _initialize(path, index):
17
+ global _GENOME
18
+ _GENOME = Genome.from_index(path, index)
19
+
20
+
21
+ def _work(args):
22
+ models, junctions, segments, settings, molecular, observations = args
23
+ base,report=reconstruct(models, _GENOME, junctions, extra_segments=segments, molecular_corrections=molecular, **settings)
24
+ if observations:
25
+ guided,guided_report=reconstruct(models,_GENOME,junctions,extra_segments=segments,
26
+ molecular_corrections=molecular,peptide_observations=observations,**settings)
27
+ # Keep every baseline path; peptide guidance cannot erase its search space.
28
+ bykey={m.key:m for m in base}
29
+ bykey.update((m.key,m) for m in guided)
30
+ report['peptide_guided_search']=guided_report
31
+ report['baseline_candidates_preserved']=len(base)
32
+ base=sorted(bykey.values(),key=lambda m:m.key)
33
+ report['candidates']=len(base)
34
+ return base,report
35
+
36
+
37
+ def _decode(row):
38
+ d = dict(row)
39
+ d["cds"] = tuple(tuple(iv) for iv in d["cds"])
40
+ d["exons"] = tuple(tuple(iv) for iv in d["exons"])
41
+ return Transcript(**d)
42
+
43
+
44
+ def graph_candidates(pool, config, fingerprints, support, genome, cache):
45
+ p = config["parameters"]
46
+ settings = dict(
47
+ beam=p["graph_beam"],
48
+ max_candidates=p["graph_candidates"],
49
+ max_nodes=p["graph_max_nodes"],
50
+ max_starts=p["graph_max_starts"],
51
+ )
52
+ originals = {
53
+ source: dict(
54
+ annotation=fingerprints[spec["annotation"]],
55
+ phase_sequence=(
56
+ fingerprints[spec["protein_fasta"]]
57
+ if spec.get("protein_fasta")
58
+ else (
59
+ fingerprints[spec["residue_profiles"]]
60
+ if spec.get("residue_profiles")
61
+ else None
62
+ )
63
+ ),
64
+ )
65
+ for source, spec in config["predictions"].items()
66
+ }
67
+ rna = config.get("rna", {})
68
+ rna_key = {
69
+ k: (fingerprints[v] if k in ("bam", "junctions") else v) for k, v in rna.items()
70
+ }
71
+ if "bam" in rna:
72
+ rna_key["indexes"] = {
73
+ path: fingerprints[path] for path in bam_index_paths(rna["bam"])
74
+ }
75
+ identity = digest_object(
76
+ dict(
77
+ genome=fingerprints[config["genome"]],
78
+ originals=originals,
79
+ rna=rna_key,
80
+ peptides=({k:fingerprints[v] for k,v in config.get('peptides',{}).items()}
81
+ if p.get('peptide_strategy')=='graph_contrast' else None),
82
+ minimum_rna_templates=p["minimum_rna_templates"],
83
+ protein=(
84
+ fingerprints[config["proteins"]["annotation"]]
85
+ if "proteins" in config
86
+ else None
87
+ ),
88
+ settings=settings,
89
+ molecular_guidance=p["selection_policy"]=="state_molecular_guided",
90
+ selection_policy=p["selection_policy"],
91
+ molecular={s:{k:fingerprints[v] for k,v in spec.items() if k in ("scores","residue_profiles")} for s,spec in config["predictions"].items()},
92
+ molecular_parameters={k:p[k] for k in ("localizer_gate","risk_strength","boundary_window_nt","molecular_weight")},
93
+ code={
94
+ name: sha256(Path(__file__).with_name(name + ".py"))
95
+ for name in [
96
+ "graph_cache",
97
+ "local_molecular",
98
+ "molecular",
99
+ "graph",
100
+ "genome",
101
+ "annotation",
102
+ "normalization",
103
+ "models",
104
+ "support",
105
+ "rna",
106
+ "peptide_context",
107
+ "peptides",
108
+ "provenance",
109
+ ]
110
+ },
111
+ )
112
+ )
113
+ cachepath = Path(cache) / ("graph-" + identity + ".json.gz")
114
+ if cachepath.is_file():
115
+ with gzip.open(cachepath, "rt") as f:
116
+ data = json.load(f)
117
+ if (
118
+ data["identity"] != identity
119
+ or digest_object(data["payload"]) != data["payload_digest"]
120
+ ):
121
+ raise ValueError("Graph cache integrity check failed: " + str(cachepath))
122
+ novel = [(_decode(x["model"]), x["parents"]) for x in data["payload"]["novel"]]
123
+ return novel, data["payload"]["reports"], dict(reused=True, key=identity)
124
+ components = list(loci([c.model for c in pool.values()]))
125
+ from .local_molecular import LocalMolecular
126
+ bykey={c.model.key:c for c in pool.values()}
127
+ args = [
128
+ (mm, support.graph_junctions(mm), support.graph_segments(mm), settings,
129
+ LocalMolecular([bykey[m.key] for m in mm],p).graph_corrections(mm)
130
+ if p['selection_policy']=='state_molecular_guided' and any(bykey[m.key].q is not None for m in mm) else {},
131
+ support.peptide_evidence.graph_observations(mm,support)
132
+ if p.get('peptide_strategy')=='graph_contrast' and hasattr(support,'peptide_evidence') else ())
133
+ for mm in components
134
+ ]
135
+ novel = []
136
+ reports = []
137
+
138
+ def collect(results):
139
+ for mm, (found, report) in zip(components, results):
140
+ reports.append(
141
+ dict(
142
+ contig=mm[0].contig,
143
+ strand=mm[0].strand,
144
+ start=min(m.cds[0][0] for m in mm),
145
+ **report,
146
+ )
147
+ )
148
+ parents = sorted({m.uid for m in mm})
149
+ novel.extend((m, parents) for m in found)
150
+
151
+ if p["threads"] == 1:
152
+ _initialize(config['genome'],genome.index)
153
+ collect(_work(row) for row in args)
154
+ else:
155
+ with ProcessPoolExecutor(
156
+ max_workers=p["threads"],
157
+ initializer=_initialize,
158
+ initargs=(config["genome"], genome.index),
159
+ ) as executor:
160
+ collect(executor.map(_work, args, chunksize=16))
161
+ verify_inputs(fingerprints, "graph cache")
162
+ payload = dict(
163
+ novel=[dict(model=asdict(m), parents=parents) for m, parents in novel],
164
+ reports=reports,
165
+ )
166
+ data = dict(
167
+ identity=identity, payload=payload, payload_digest=digest_object(payload)
168
+ )
169
+ temp = cachepath.with_name(
170
+ "." + cachepath.name + ".tmp." + str(os.getpid()) + "." + uuid.uuid4().hex
171
+ )
172
+ with gzip.open(temp, "wt", compresslevel=1) as f:
173
+ json.dump(data, f, sort_keys=True, separators=(",", ":"), allow_nan=False)
174
+ os.replace(temp, cachepath)
175
+ return novel, reports, dict(reused=False, key=identity)
@@ -0,0 +1,104 @@
1
+ """Small deterministic interval primitives and a dynamic coding-overlap index."""
2
+
3
+ from collections import defaultdict
4
+
5
+
6
+ def merge(intervals):
7
+ out = []
8
+ for a, b in sorted(intervals):
9
+ if a >= b:
10
+ continue
11
+ if out and a <= out[-1][1]:
12
+ out[-1] = (out[-1][0], max(b, out[-1][1]))
13
+ else:
14
+ out.append((a, b))
15
+ return tuple(out)
16
+
17
+
18
+ def overlap(a, b):
19
+ i = j = 0
20
+ while i < len(a) and j < len(b):
21
+ if max(a[i][0], b[j][0]) < min(a[i][1], b[j][1]):
22
+ return True
23
+ if a[i][1] < b[j][1]:
24
+ i += 1
25
+ else:
26
+ j += 1
27
+ return False
28
+
29
+
30
+ def intersection_length(a, b):
31
+ i = j = 0
32
+ n = 0
33
+ while i < len(a) and j < len(b):
34
+ n += max(0, min(a[i][1], b[j][1]) - max(a[i][0], b[j][0]))
35
+ if a[i][1] < b[j][1]:
36
+ i += 1
37
+ else:
38
+ j += 1
39
+ return n
40
+
41
+
42
+ def subtract(a, b):
43
+ out = []
44
+ b = merge(b)
45
+ for left, right in merge(a):
46
+ cursor = left
47
+ for x, y in b:
48
+ if y <= cursor:
49
+ continue
50
+ if x >= right:
51
+ break
52
+ if x > cursor:
53
+ out.append((cursor, x))
54
+ cursor = max(cursor, y)
55
+ if cursor >= right:
56
+ break
57
+ if cursor < right:
58
+ out.append((cursor, right))
59
+ return tuple(out)
60
+
61
+
62
+ def disputed(a, b, window=9):
63
+ regions = list(subtract(a.cds, b.cds)) + list(subtract(b.cds, a.cds))
64
+ for x, y in set(a.introns) ^ set(b.introns):
65
+ regions.extend(
66
+ ((max(0, x - window), x + window), (max(0, y - window), y + window))
67
+ )
68
+ return merge(regions)
69
+
70
+
71
+ class CodingIndex:
72
+ def __init__(self, bin_size=10000):
73
+ self.bin_size = bin_size
74
+ self.bins = defaultdict(set)
75
+ self.items = {}
76
+
77
+ def keys(self, model):
78
+ return {
79
+ (model.contig, model.strand, i)
80
+ for a, b in model.cds
81
+ for i in range(a // self.bin_size, (b - 1) // self.bin_size + 1)
82
+ }
83
+
84
+ def add(self, c):
85
+ if c.uid in self.items:
86
+ return
87
+ self.items[c.uid] = c
88
+ for k in self.keys(c.model):
89
+ self.bins[k].add(c.uid)
90
+
91
+ def remove(self, c):
92
+ del self.items[c.uid]
93
+ for k in self.keys(c.model):
94
+ self.bins[k].discard(c.uid)
95
+
96
+ def conflicts(self, c):
97
+ ids = set()
98
+ for k in self.keys(c.model):
99
+ ids.update(self.bins[k])
100
+ return [
101
+ self.items[i]
102
+ for i in sorted(ids)
103
+ if i != c.uid and overlap(c.model.cds, self.items[i].model.cds)
104
+ ]
@@ -0,0 +1,54 @@
1
+ """Reference-free, additive secondary-isoform admissions. Frozen pilot policy."""
2
+ from .intervals import intersection_length,subtract,disputed
3
+ from .exon_support import ExonSupport
4
+ from .molecular import local_risk
5
+ GATE=.437721461
6
+
7
+ def shared_frame_bases(a,b):
8
+ def segments(m):
9
+ used=-m.phase;out=[]
10
+ for x,y in m.cds if m.strand=='+' else reversed(m.cds):
11
+ out.append((x,y,(used-x)%3 if m.strand=='+' else (used+y-1)%3));used+=y-x
12
+ return out
13
+ total=0
14
+ for x,y,p in segments(a):
15
+ for u,v,q in segments(b):
16
+ if p==q:total+=max(0,min(y,v)-max(x,u))
17
+ return total
18
+
19
+ def relationship(alt,primary):
20
+ if alt.contig!=primary.contig or alt.strand!=primary.strand:return False,'different_contig_or_strand',0.
21
+ shared=intersection_length(alt.cds,primary.cds)
22
+ fraction=min(shared/alt.length,shared/primary.length)
23
+ if fraction<.5:return False,'insufficient_shared_coding_anchor',fraction
24
+ if shared_frame_bases(alt,primary)!=shared:return False,'shared_CDS_frame_disagreement',fraction
25
+ if alt.introns==primary.introns:return False,'same_intron_chain_terminal_variant',fraction
26
+ if not(set(alt.introns)&set(primary.introns) or set(alt.cds)&set(primary.cds)):return False,'no_shared_exact_exon_or_junction',fraction
27
+ return True,'compatible_coding_alternative',fraction
28
+
29
+ def routes(candidate,parent,support,use_scores,use_rna,diagnostics,gate=GATE):
30
+ m=candidate.model;new=sorted(set(m.introns)-set(parent.introns));lost=sorted(set(parent.introns)-set(m.introns));extra=subtract(m.cds,parent.cds);nextra=sum(b-a for a,b in extra)
31
+ q=min(candidate.gene_scores) if use_scores and candidate.gene_scores else None
32
+ qpositive=q is not None and q>=gate
33
+ rna=False;counts=[];coverage=None;retention_observations=[]
34
+ if use_rna:
35
+ counts=[support.rna_count(m,iv) for iv in new]
36
+ coverage=support.rna_coding_overlap(m) if not nextra else intersection_length(extra,support.rna_blocks.get((m.contig,m.strand),()))/nextra
37
+ # rna_coding_overlap returns a fraction; no extra coding bases requires no new-base assertion.
38
+ if not nextra:coverage=1.
39
+ if not new and lost:
40
+ for a,b in lost:
41
+ observed=[support.rna_exon_counts_all.get((m.contig,m.strand,x,y),0) for x,y in m.cds[1:-1] if x<=a and y>=b]
42
+ retention_observations.append(max(observed,default=0))
43
+ event_supported=(bool(new) and all(n>=3 for n in counts)) or (bool(lost) and not new and all(n>=3 for n in retention_observations))
44
+ rna=bool(event_supported and coverage>=.95)
45
+ risk,known=local_risk(candidate,disputed(m,parent,9),gate) if use_scores else (None,False)
46
+ spurious=bool(use_scores and q is not None and q<gate and any(cl=='cryptic_orf' and posterior>=.5 for cl,posterior in diagnostics))
47
+ risk_veto=bool(use_scores and q is not None and q<gate and known and risk>=.5)
48
+ return dict(q=q,q_positive=qpositive,distinct_predictor_sources=len(candidate.sources),RNA_event_supported=rna,new_junctions=new,lost_junctions=lost,alternative_junction_templates=counts,alternative_coding_coverage=coverage,retention_exon_observations=retention_observations,residue_risk=risk,residue_risk_observed=known,spurious_ORF_veto=spurious,residue_risk_veto=risk_veto)
49
+
50
+ def qualifies(features,policy):
51
+ molecular=features['q_positive'] and (policy=='score_positive' or features['distinct_predictor_sources']>=2)
52
+ supported=molecular or features['RNA_event_supported']
53
+ if policy=='risk_guarded' and (features['spurious_ORF_veto'] or features['residue_risk_veto']):supported=False
54
+ return bool(supported)
@@ -0,0 +1,117 @@
1
+ """Add source-supplied secondary coding isoforms after immutable primary selection."""
2
+ from collections import defaultdict, Counter
3
+ from .models import Candidate
4
+ from .intervals import CodingIndex
5
+ from .molecular import read_scores
6
+ from .isoform_guards import relationship, routes, qualifies
7
+ from .annotation import write_gff3, attributes
8
+
9
+
10
+ def admit_isoforms(primary, source_models, specs, support, genome, parameters):
11
+ """Fixed event_guarded rule; optional input names do not define eligibility."""
12
+ if parameters['isoform_policy'] == 'off':
13
+ return [], {}, [], {'policy': 'off', 'added': 0}
14
+ scores_present = any(spec.get('scores') for spec in specs.values())
15
+ rna_present = parameters.get('_isoform_rna_available', bool(getattr(support, 'rna', None)))
16
+ if not scores_present and not rna_present:
17
+ return [], {}, [], dict(policy='event_guarded', primary_models=len(primary), added=0, primary_geometries_preserved=True, RNA_available=False, scores_available=False, reason='no_isoform_admission_evidence')
18
+ eligible = set()
19
+ for source, models in source_models.items():
20
+ groups = defaultdict(list)
21
+ for m in models:
22
+ groups[m.contig, m.strand, m.gene].append(m)
23
+ for members in groups.values():
24
+ if len({m.cds for m in members}) > 1:
25
+ eligible.update(m.key for m in members)
26
+ pool = {}
27
+ for source, models in source_models.items():
28
+ scores = read_scores(specs[source]['scores']) if specs[source].get('scores') else {}
29
+ for m in models:
30
+ if m.key not in eligible:
31
+ continue
32
+ c = pool.setdefault(m.key, Candidate(m))
33
+ c.sources.add(source)
34
+ c.original_ids.setdefault(source, []).append(m.identifier)
35
+ if m.identifier in scores:
36
+ c.gene_scores.append(scores[m.identifier])
37
+ use_scores = any(spec.get('scores') for spec in specs.values())
38
+ use_rna = bool(getattr(support, 'rna', None))
39
+ # Availability is passed explicitly by the pipeline, even for empty RNA files.
40
+ use_rna = parameters.get('_isoform_rna_available', use_rna)
41
+ index = CodingIndex()
42
+ for c in primary:
43
+ index.add(c)
44
+ selected = {c.uid for c in primary}
45
+ options = []
46
+ rejected = Counter()
47
+ for c in pool.values():
48
+ if c.uid in selected:
49
+ continue
50
+ m = c.model
51
+ complete, canonical, _ = genome.assess(m)
52
+ c.complete, c.canonical = complete, canonical
53
+ if not (complete and canonical and m.length >= 150 and all(b-a >= 20 for a,b in m.introns)):
54
+ rejected['incomplete_noncanonical_or_short'] += 1
55
+ continue
56
+ conflicts = index.conflicts(c)
57
+ if len(conflicts) != 1:
58
+ rejected['zero_or_multiple_primary_genes'] += 1
59
+ continue
60
+ parent = conflicts[0].model
61
+ ok, reason, fraction = relationship(m, parent)
62
+ if not ok:
63
+ rejected[reason] += 1
64
+ continue
65
+ f = routes(c, parent, support, use_scores, use_rna, [], gate=parameters['isoform_score_gate'])
66
+ # This frozen addon does not use a residue-risk veto. Primary selection does.
67
+ rank = (int(f['RNA_event_supported']), min(f['alternative_junction_templates'], default=0) if use_rna else 0, f['q'] if use_scores and f['q'] is not None else -1, len(c.sources), fraction)
68
+ options.append((rank, c, parent, f))
69
+ added, parents, records = [], {}, []
70
+ perparent = defaultdict(list)
71
+ for rank, c, parent, f in sorted(options, key=lambda x:(tuple(-v for v in x[0]), x[1].uid)):
72
+ accepted = qualifies(f, 'event_guarded')
73
+ reason = 'supported' if accepted else 'insufficient_isoform_specific_evidence'
74
+ if accepted and len(perparent[parent.uid]) >= 2:
75
+ accepted, reason = False, 'predeclared_two_additional_isoform_budget'
76
+ if accepted and any(c.model.introns == m.introns for m in perparent[parent.uid]):
77
+ accepted, reason = False, 'duplicate_alternative_intron_chain'
78
+ if accepted:
79
+ perparent[parent.uid].append(c.model)
80
+ added.append(c)
81
+ parents[c.uid] = parent.uid
82
+ records.append(dict(event='isoform', candidate=c.uid, parent=parent.uid, sources=sorted(c.sources), accepted=accepted, reason=reason, **f))
83
+ return added, parents, records, dict(policy='event_guarded', primary_models=len(primary), added=len(added), genes_with_additions=len(perparent), structurally_eligible_candidates=len(options), structural_rejections=dict(rejected), primary_geometries_preserved=True, RNA_available=use_rna, scores_available=use_scores, peptide_admission_route=False)
84
+
85
+
86
+ def write_isoform_gff3(models, path, parents):
87
+ """Keep stable transcript IDs, share primary gene parent, and expand its span."""
88
+ available = {m.uid for m in models}
89
+ parents = {uid: parent for uid, parent in parents.items() if uid in available and parent in available}
90
+ write_gff3(models, path)
91
+ if not parents:
92
+ return
93
+ lookup = {m.uid:m for m in models}
94
+ spans = {}
95
+ for uid, parent in parents.items():
96
+ p, m = lookup[parent], lookup[uid]
97
+ ee = (p.exons or p.cds) + (m.exons or m.cds) + p.cds + m.cds
98
+ lo, hi = spans.get(parent, (min(a for a,b in ee)+1, max(b for a,b in ee)))
99
+ spans[parent] = (min(lo, min(a for a,b in ee)+1), max(hi, max(b for a,b in ee)))
100
+ lines = []
101
+ for line in path.read_text().splitlines():
102
+ if line.startswith('#'):
103
+ lines.append(line)
104
+ continue
105
+ f = line.split('\t'); a = attributes(f[8])
106
+ if f[2] == 'gene':
107
+ uid = a['ID'][4:]
108
+ if uid in parents:
109
+ continue
110
+ if uid in spans:
111
+ f[3], f[4] = map(str, spans[uid])
112
+ elif f[2] == 'mRNA':
113
+ uid = a['Parent'][4:]
114
+ if uid in parents:
115
+ f[8] = f[8].replace(';Parent=GS.g'+uid+';', ';Parent=GS.g'+parents[uid]+';')
116
+ lines.append('\t'.join(f))
117
+ path.write_text('\n'.join(lines)+'\n')
@@ -0,0 +1,60 @@
1
+ """Corroborate local predictor agreement; retain provisional genes explicitly."""
2
+ from .exchange import LocalVotes,compare_exchange
3
+ from .selection import compare,_peptide_pair,_rna_pair
4
+ from .molecular import local_risk
5
+ from .intervals import disputed,intersection_length
6
+ from functools import partial
7
+
8
+
9
+ def compare_joint(c,old,peptides,support,chains,ivotes,n_sources,p,votes):
10
+ regions=disputed(c.model,old.model,p['boundary_window_nt'])
11
+ sn,so,known,certificate=votes.structural(c.model,old.model)
12
+ pn,po,_,_=_peptide_pair(c,old,peptides,regions,p['peptide_saturation'])
13
+ rn,ro=_rna_pair(c,old,support)
14
+ cr=tuple((max(a,x),min(b,y)) for a,b in c.model.cds for x,y in regions if max(a,x)<min(b,y))
15
+ oc=tuple((max(a,x),min(b,y)) for a,b in old.model.cds for x,y in regions if max(a,x)<min(b,y))
16
+ an,ao=support.protein_score(c.model,cr),support.protein_score(old.model,oc)
17
+ nr,nk=local_risk(c,regions,p['localizer_gate']);orr,ok=local_risk(old,regions,p['localizer_gate'])
18
+ gate=p.get('confidence_gate')
19
+ molecular_consistent=c.q is not None and old.q is not None
20
+ corroboration=bool(pn>po or rn>ro or an>=ao+.1 or molecular_consistent or(nk and ok and orr-nr>=p['risk_advantage']))
21
+ if known and sn>so and corroboration:
22
+ e=compare_exchange(c,old,peptides,support,chains,ivotes,n_sources,p,votes)
23
+ e['decision_mode']='joint_evidence_exchange'
24
+ else:
25
+ e=compare(c,old,peptides,support,chains,ivotes,n_sources,p)
26
+ e['decision_mode']='compatibility_without_corroborated_majority'
27
+ e['majority_corroborated']=corroboration
28
+ return e
29
+
30
+
31
+ def select_joint(candidates,source_models,peptides,support,p):
32
+ from .selection import select
33
+ votes=LocalVotes(source_models)
34
+ selected,events,backbone=select(candidates,source_models,peptides,support,p,
35
+ _comparison=partial(compare_joint,votes=votes))
36
+ if p['selection_policy']!='joint_tiered':return selected,events,backbone
37
+ gate=p.get('confidence_gate')
38
+ if gate is None:raise ValueError('Tiered selection requires an independently specified confidence_gate')
39
+ primary=[]
40
+ for c in selected:
41
+ m=c.model
42
+ # Independent predictor contradiction is unavailable with fewer than 3 sources.
43
+ fractions=[]
44
+ for source in votes.sources:
45
+ blocks,starts,ends=votes.coverage.get((source,m.contig,m.strand),((),(),()))
46
+ from bisect import bisect_left,bisect_right
47
+ sliced=blocks[bisect_right(ends,m.cds[0][0]):bisect_left(starts,m.cds[-1][1])]
48
+ fractions.append(intersection_length(m.cds,sliced)/m.length)
49
+ coding=sum(fractions)/len(fractions)
50
+ rna=any(support.rna_count(m,iv)>=p['minimum_rna_templates'] for iv in m.introns)
51
+ protein=support.protein_score(m)>0
52
+ provisional=(len(source_models)>=3 and not c.graph_path and c.q is not None and c.q<gate
53
+ and coding<.5 and not(c.peptides or rna or protein))
54
+ if provisional:
55
+ events.append(dict(event='provisional',candidate=c.uid,incumbents=[],accepted=True,
56
+ reasons=['classifier_negative_and_predictor_majority_exclusion_without_positive_empirical_support'],
57
+ gene_q=c.q,confidence_gate=gate,coding_agreement=coding,
58
+ interpretation='uncertain hypothesis retained in provisional.gff3; not a biological false-gene label'))
59
+ else:primary.append(c)
60
+ return primary,events,backbone
@@ -0,0 +1,166 @@
1
+ """Parallel, content-addressed source validation and molecular feature caching."""
2
+
3
+ from pathlib import Path
4
+ from dataclasses import asdict
5
+ from concurrent.futures import ProcessPoolExecutor
6
+ import gzip, json, os, uuid
7
+ import numpy as np
8
+ from .annotation import read_annotation
9
+ from .normalization import normalize_phases
10
+ from .molecular import attach_molecular, RiskTrack
11
+ from .models import Transcript, Candidate
12
+ from .genome import Genome
13
+ from .provenance import digest_object, sha256, verify_inputs
14
+
15
+ _GENOME = None
16
+
17
+
18
+ def _initialize(path, index):
19
+ global _GENOME
20
+ _GENOME = Genome.from_index(path, index)
21
+
22
+
23
+ def _decode(d):
24
+ d = dict(d)
25
+ d["cds"] = tuple(tuple(x) for x in d["cds"])
26
+ d["exons"] = tuple(tuple(x) for x in d["exons"])
27
+ return Transcript(**d)
28
+
29
+
30
+ def _pack(models, candidates, phase, molecular):
31
+ positions = {id(m): i for i, m in enumerate(models)}
32
+ rows = []
33
+ for c in candidates:
34
+ risks = []
35
+ for track in c.risks:
36
+ v = np.asarray(track.probabilities)
37
+ risks.append(
38
+ dict(
39
+ model_index=positions[id(track.model)],
40
+ dtype=v.dtype.str,
41
+ data=v.tobytes().hex(),
42
+ q=track.q,
43
+ )
44
+ )
45
+ rows.append(
46
+ dict(model_index=positions[id(c.model)], scores=c.gene_scores, risks=risks)
47
+ )
48
+ return dict(
49
+ models=[asdict(m) for m in models],
50
+ candidates=rows,
51
+ phase=phase,
52
+ molecular=molecular,
53
+ )
54
+
55
+
56
+ def _unpack(data):
57
+ models = [_decode(m) for m in data["models"]]
58
+ byuid = {}
59
+ for row in data["candidates"]:
60
+ model = models[row["model_index"]]
61
+ c = Candidate(model)
62
+ byuid[model.uid] = c
63
+ c.gene_scores = list(row["scores"])
64
+ for r in row["risks"]:
65
+ dtype = np.dtype(r["dtype"])
66
+ if dtype.kind != "f" or dtype.itemsize not in (2, 4, 8):
67
+ raise ValueError("Invalid cached probability dtype")
68
+ values = np.frombuffer(bytes.fromhex(r["data"]), dtype=dtype)
69
+ c.risks.append(RiskTrack(models[r["model_index"]], values, r["q"]))
70
+ return models, list(byuid.values()), data["phase"], data["molecular"]
71
+
72
+
73
+ def _source(args, genome):
74
+ source, spec, key, cache, expected = args
75
+ path = Path(cache) / ("source-" + key + ".json.gz")
76
+ if path.is_file():
77
+ with gzip.open(path, "rt") as f:
78
+ data = json.load(f)
79
+ if data["identity"] != key or digest_object(data["payload"]) != data["digest"]:
80
+ raise ValueError("Source cache integrity check failed: " + str(path))
81
+ return source, *_unpack(data["payload"]), dict(reused=True, key=key)
82
+ models = read_annotation(spec["annotation"], source)
83
+ phase = normalize_phases({source: models}, {source: spec}, genome)[source]
84
+ pool = {}
85
+ for m in models:
86
+ pool.setdefault(m.key, Candidate(m))
87
+ molecular = attach_molecular(
88
+ list(pool.values()), {source: models}, {source: spec}, genome
89
+ ).get(source, {})
90
+ verify_inputs(expected, "source cache")
91
+ payload = _pack(models, list(pool.values()), phase, molecular)
92
+ data = dict(identity=key, payload=payload, digest=digest_object(payload))
93
+ temp = path.with_name(
94
+ "." + path.name + ".tmp." + str(os.getpid()) + "." + uuid.uuid4().hex
95
+ )
96
+ with gzip.open(temp, "wt", compresslevel=1) as f:
97
+ json.dump(data, f, sort_keys=True, separators=(",", ":"), allow_nan=False)
98
+ os.replace(temp, path)
99
+ return (
100
+ source,
101
+ models,
102
+ list(pool.values()),
103
+ phase,
104
+ molecular,
105
+ dict(reused=False, key=key),
106
+ )
107
+
108
+
109
+ def _work(args):
110
+ return _source(args, _GENOME)
111
+
112
+
113
+ def load_sources(config, genome, fingerprints, cache):
114
+ code = {
115
+ name: sha256(Path(__file__).with_name(name + ".py"))
116
+ for name in [
117
+ "loading",
118
+ "annotation",
119
+ "normalization",
120
+ "molecular",
121
+ "models",
122
+ "genome",
123
+ "provenance",
124
+ ]
125
+ }
126
+ args = []
127
+ for source, spec in sorted(config["predictions"].items()):
128
+ key = digest_object(
129
+ dict(
130
+ source=source,
131
+ inputs={name: fingerprints[path] for name, path in spec.items()},
132
+ genome=fingerprints[config["genome"]],
133
+ code=code,
134
+ )
135
+ )
136
+ expected = {path: fingerprints[path] for path in spec.values()}
137
+ expected[config["genome"]] = fingerprints[config["genome"]]
138
+ args.append((source, spec, key, str(cache), expected))
139
+ if config["parameters"]["threads"] == 1:
140
+ results = [_source(a, genome) for a in args]
141
+ else:
142
+ with ProcessPoolExecutor(
143
+ max_workers=min(config["parameters"]["threads"], len(args)),
144
+ initializer=_initialize,
145
+ initargs=(config["genome"], genome.index),
146
+ ) as executor:
147
+ results = list(executor.map(_work, args))
148
+ source_models = {}
149
+ pool = {}
150
+ phase_report = {}
151
+ molecular_report = {}
152
+ cache_report = {}
153
+ for source, models, candidates, phase, molecular, cache_info in results:
154
+ source_models[source] = models
155
+ phase_report[source] = phase
156
+ molecular_report[source] = molecular
157
+ cache_report[source] = cache_info
158
+ for m in models:
159
+ c = pool.setdefault(m.key, Candidate(m))
160
+ c.sources.add(source)
161
+ c.original_ids.setdefault(source, []).append(m.identifier)
162
+ for item in candidates:
163
+ c = pool[item.model.key]
164
+ c.gene_scores.extend(item.gene_scores)
165
+ c.risks.extend(item.risks)
166
+ return source_models, pool, phase_report, molecular_report, cache_report