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,64 @@
|
|
|
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_available(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
|
+
comparable=(c.q is not None and old.q is not None) or(nk and ok) or bool(pn or po) or abs(rn-ro)>1e-12 or abs(an-ao)>1e-12
|
|
22
|
+
if known and abs(sn-so)>1e-12 and comparable:
|
|
23
|
+
e=compare_exchange(c,old,peptides,support,chains,ivotes,n_sources,p,votes)
|
|
24
|
+
e['decision_mode']='availability_aware_joint_exchange'
|
|
25
|
+
else:
|
|
26
|
+
e=compare(c,old,peptides,support,chains,ivotes,n_sources,p)
|
|
27
|
+
e['decision_mode']='compatibility_without_corroborated_majority'
|
|
28
|
+
e['external_channel_comparable']=bool(comparable)
|
|
29
|
+
e['positive_distinguishing_evidence']=corroboration
|
|
30
|
+
return e
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def select_available(candidates,source_models,peptides,support,p):
|
|
34
|
+
from .selection import select
|
|
35
|
+
votes=LocalVotes(source_models)
|
|
36
|
+
selected,events,backbone=select(candidates,source_models,peptides,support,p,
|
|
37
|
+
_comparison=partial(compare_available,votes=votes))
|
|
38
|
+
if p['selection_policy']!='available_tiered':return selected,events,backbone
|
|
39
|
+
gate=p.get('confidence_gate')
|
|
40
|
+
if gate is None:raise ValueError('Tiered selection requires an independently specified confidence_gate')
|
|
41
|
+
primary=[]
|
|
42
|
+
for c in selected:
|
|
43
|
+
m=c.model
|
|
44
|
+
# Independent predictor contradiction is unavailable with fewer than 3 sources.
|
|
45
|
+
fractions=[]
|
|
46
|
+
for source in votes.sources:
|
|
47
|
+
blocks,starts,ends=votes.coverage.get((source,m.contig,m.strand),((),(),()))
|
|
48
|
+
from bisect import bisect_left,bisect_right
|
|
49
|
+
sliced=blocks[bisect_right(ends,m.cds[0][0]):bisect_left(starts,m.cds[-1][1])]
|
|
50
|
+
fractions.append(intersection_length(m.cds,sliced)/m.length)
|
|
51
|
+
coding=sum(fractions)/len(fractions)
|
|
52
|
+
rna=any(support.rna_count(m,iv)>=p['minimum_rna_templates'] for iv in m.introns)
|
|
53
|
+
protein=support.protein_score(m)>0
|
|
54
|
+
consensus_provisional=(len(source_models)>=3 and coding<.5 and not(c.peptides or rna or protein))
|
|
55
|
+
if consensus_provisional:
|
|
56
|
+
events.append(dict(event='consensus_provisional',candidate=c.uid,incumbents=[],accepted=True,reasons=['predictor_majority_exclusion_without_positive_empirical_support'],coding_agreement=coding,interpretation='optional stricter structural-confidence view; not a false-gene label'))
|
|
57
|
+
provisional=(consensus_provisional and not c.graph_path and c.q is not None and c.q<gate)
|
|
58
|
+
if provisional:
|
|
59
|
+
events.append(dict(event='provisional',candidate=c.uid,incumbents=[],accepted=True,
|
|
60
|
+
reasons=['classifier_negative_and_predictor_majority_exclusion_without_positive_empirical_support'],
|
|
61
|
+
gene_q=c.q,confidence_gate=gate,coding_agreement=coding,
|
|
62
|
+
interpretation='uncertain hypothesis retained in provisional.gff3; not a biological false-gene label'))
|
|
63
|
+
else:primary.append(c)
|
|
64
|
+
return primary,events,backbone
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Command line entry point. Evaluation references are never accepted by run."""
|
|
2
|
+
|
|
3
|
+
import argparse, json, sys, logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from . import __version__
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def parser():
|
|
9
|
+
p = argparse.ArgumentParser(
|
|
10
|
+
prog="genesensus",
|
|
11
|
+
description="Evidence-guided gene reconstruction and refinement",
|
|
12
|
+
)
|
|
13
|
+
p.add_argument("--version", action="version", version="GeneSensus " + __version__)
|
|
14
|
+
p.add_argument("--debug", action="store_true", help="Show a traceback on error")
|
|
15
|
+
commands = p.add_subparsers(dest="command", required=True)
|
|
16
|
+
run = commands.add_parser(
|
|
17
|
+
"run", help="Integrate predictor annotations and optional evidence"
|
|
18
|
+
)
|
|
19
|
+
run.add_argument("config", help="Inference-only JSON configuration")
|
|
20
|
+
run.add_argument("-o", "--output", required=True, help="New output directory")
|
|
21
|
+
run.add_argument(
|
|
22
|
+
"-t",
|
|
23
|
+
"--threads",
|
|
24
|
+
type=int,
|
|
25
|
+
default=None,
|
|
26
|
+
help="Independent graph worker processes",
|
|
27
|
+
)
|
|
28
|
+
run.add_argument("--cache", help="Reusable source, graph and RNA feature cache directory")
|
|
29
|
+
run.add_argument(
|
|
30
|
+
"--resume",
|
|
31
|
+
action="store_true",
|
|
32
|
+
help="Verify and reuse a completed identical output",
|
|
33
|
+
)
|
|
34
|
+
validate = commands.add_parser(
|
|
35
|
+
"validate", help="Validate configuration, input paths and genome coordinates"
|
|
36
|
+
)
|
|
37
|
+
validate.add_argument("config")
|
|
38
|
+
prepare = commands.add_parser(
|
|
39
|
+
"prepare-rna", help="Prepare observed splice and exon evidence from an indexed BAM"
|
|
40
|
+
)
|
|
41
|
+
prepare.add_argument("--bam", required=True)
|
|
42
|
+
prepare.add_argument("--genome", required=True)
|
|
43
|
+
prepare.add_argument("-o", "--output", required=True)
|
|
44
|
+
prepare.add_argument("-t", "--threads", type=int, default=1)
|
|
45
|
+
prepare.add_argument(
|
|
46
|
+
"--library",
|
|
47
|
+
choices=["unstranded", "firststrand", "secondstrand"],
|
|
48
|
+
default="unstranded",
|
|
49
|
+
)
|
|
50
|
+
prepare.add_argument("--min-mapq", type=int, default=20)
|
|
51
|
+
prepare.add_argument("--min-overhang", type=int, default=8)
|
|
52
|
+
prepare.add_argument("--minimum-templates", type=int, default=3, help="Minimum templates for novel RNA exon discovery; must match the run configuration")
|
|
53
|
+
return p
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main(argv=None):
|
|
57
|
+
args = parser().parse_args(argv)
|
|
58
|
+
logging.basicConfig(
|
|
59
|
+
level=logging.DEBUG if args.debug else logging.INFO,
|
|
60
|
+
format="%(asctime)s %(levelname)s %(message)s",
|
|
61
|
+
)
|
|
62
|
+
try:
|
|
63
|
+
if args.command == "run":
|
|
64
|
+
from .pipeline import run
|
|
65
|
+
|
|
66
|
+
result = run(
|
|
67
|
+
args.config, args.output, args.threads, args.cache, args.resume
|
|
68
|
+
)
|
|
69
|
+
print(
|
|
70
|
+
json.dumps(
|
|
71
|
+
dict(
|
|
72
|
+
output=str(result.output),
|
|
73
|
+
annotation=str(result.annotation),
|
|
74
|
+
reused=result.reused,
|
|
75
|
+
selected=result.report["selected_count"],
|
|
76
|
+
novel_graph_selected=result.report["selected_graph_candidates"],
|
|
77
|
+
seconds=result.report["timings"]["total_seconds"],
|
|
78
|
+
),
|
|
79
|
+
sort_keys=True,
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
return 0
|
|
83
|
+
if args.command == "validate":
|
|
84
|
+
from .config import load_config, input_paths
|
|
85
|
+
from .annotation import read_annotation
|
|
86
|
+
from .genome import Genome
|
|
87
|
+
|
|
88
|
+
cfg = load_config(args.config)
|
|
89
|
+
paths = input_paths(cfg)
|
|
90
|
+
counts = {}
|
|
91
|
+
with Genome(cfg["genome"]) as genome:
|
|
92
|
+
lengths = genome.lengths
|
|
93
|
+
for source, spec in cfg["predictions"].items():
|
|
94
|
+
models = read_annotation(spec["annotation"], source)
|
|
95
|
+
counts[source] = len(models)
|
|
96
|
+
for m in models:
|
|
97
|
+
if m.contig not in lengths or m.cds[-1][1] > lengths[m.contig]:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
"Annotation/genome coordinate mismatch: " + m.identifier
|
|
100
|
+
)
|
|
101
|
+
print(
|
|
102
|
+
json.dumps(
|
|
103
|
+
dict(valid=True, predictors=counts, input_files=len(paths)),
|
|
104
|
+
sort_keys=True,
|
|
105
|
+
)
|
|
106
|
+
)
|
|
107
|
+
return 0
|
|
108
|
+
if args.command == "prepare-rna":
|
|
109
|
+
from .genome import Genome
|
|
110
|
+
from .rna import extract_junctions, write_junctions
|
|
111
|
+
from .rna_geometry import augment_geometry
|
|
112
|
+
|
|
113
|
+
out = Path(args.output)
|
|
114
|
+
if out.exists():
|
|
115
|
+
raise ValueError("RNA output already exists; refusing overwrite")
|
|
116
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
117
|
+
with Genome(args.genome) as genome:
|
|
118
|
+
data = extract_junctions(
|
|
119
|
+
args.bam,
|
|
120
|
+
genome.lengths,
|
|
121
|
+
args.threads,
|
|
122
|
+
args.min_mapq,
|
|
123
|
+
args.min_overhang,
|
|
124
|
+
library=args.library,
|
|
125
|
+
)
|
|
126
|
+
data = augment_geometry(args.bam, genome, data, threads=args.threads, minimum_templates=args.minimum_templates)
|
|
127
|
+
temp = out.with_name("." + out.name + ".partial")
|
|
128
|
+
if temp.exists():
|
|
129
|
+
raise ValueError("Partial RNA output already exists")
|
|
130
|
+
write_junctions(data, temp)
|
|
131
|
+
temp.rename(out)
|
|
132
|
+
print(json.dumps(dict(output=str(out), junctions=len(data["junctions"]))))
|
|
133
|
+
return 0
|
|
134
|
+
except KeyboardInterrupt:
|
|
135
|
+
print(
|
|
136
|
+
"GeneSensus interrupted; incomplete run artifacts are preserved.",
|
|
137
|
+
file=sys.stderr,
|
|
138
|
+
)
|
|
139
|
+
return 130
|
|
140
|
+
except Exception as exc:
|
|
141
|
+
if args.debug:
|
|
142
|
+
raise
|
|
143
|
+
print("GeneSensus: " + str(exc), file=sys.stderr)
|
|
144
|
+
return 2
|
|
145
|
+
return 0
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__":
|
|
149
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Strict inference-only configuration; reference evaluation has a separate interface."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import json, math, re
|
|
5
|
+
from .selection import DEFAULTS
|
|
6
|
+
|
|
7
|
+
PATH_KEYS = {
|
|
8
|
+
"annotation",
|
|
9
|
+
"scores",
|
|
10
|
+
"residue_profiles",
|
|
11
|
+
"diagnostics",
|
|
12
|
+
"protein_fasta",
|
|
13
|
+
"bed",
|
|
14
|
+
"sequences",
|
|
15
|
+
"bam",
|
|
16
|
+
"junctions",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def load_config(path):
|
|
21
|
+
path = Path(path).resolve()
|
|
22
|
+
data = json.loads(path.read_text())
|
|
23
|
+
allowed = {"genome", "predictions", "peptides", "rna", "proteins", "parameters"}
|
|
24
|
+
if not isinstance(data, dict) or set(data) - allowed:
|
|
25
|
+
raise ValueError(
|
|
26
|
+
"Unknown inference configuration keys: " + repr(sorted(set(data) - allowed))
|
|
27
|
+
)
|
|
28
|
+
if (
|
|
29
|
+
not isinstance(data.get("genome"), str)
|
|
30
|
+
or not isinstance(data.get("predictions"), dict)
|
|
31
|
+
or not data["predictions"]
|
|
32
|
+
):
|
|
33
|
+
raise ValueError("Config requires genome and nonempty named predictions")
|
|
34
|
+
|
|
35
|
+
def resolve(p):
|
|
36
|
+
if not isinstance(p, str) or not p:
|
|
37
|
+
raise ValueError("Input paths must be nonempty strings")
|
|
38
|
+
q = Path(p).expanduser()
|
|
39
|
+
q = q if q.is_absolute() else path.parent / q
|
|
40
|
+
if not q.is_file():
|
|
41
|
+
raise ValueError("Input file does not exist: " + str(q))
|
|
42
|
+
return str(q.resolve())
|
|
43
|
+
|
|
44
|
+
result = dict(genome=resolve(data["genome"]), predictions={})
|
|
45
|
+
for source, spec in sorted(data["predictions"].items()):
|
|
46
|
+
if not re.fullmatch("[A-Za-z0-9_.-]+", source) or source.lower() in (
|
|
47
|
+
"refseq",
|
|
48
|
+
"reference",
|
|
49
|
+
"araport",
|
|
50
|
+
"truth",
|
|
51
|
+
"ground_truth",
|
|
52
|
+
):
|
|
53
|
+
raise ValueError("Invalid or reserved predictor source name: " + source)
|
|
54
|
+
if isinstance(spec, str):
|
|
55
|
+
spec = {"annotation": spec}
|
|
56
|
+
if (
|
|
57
|
+
not isinstance(spec, dict)
|
|
58
|
+
or set(spec) - {"annotation", "scores", "residue_profiles", "protein_fasta", "diagnostics"}
|
|
59
|
+
or "annotation" not in spec
|
|
60
|
+
):
|
|
61
|
+
raise ValueError("Invalid predictor specification: " + source)
|
|
62
|
+
result["predictions"][source] = {k: resolve(v) for k, v in spec.items()}
|
|
63
|
+
for kind, p in result["predictions"][source].items():
|
|
64
|
+
name = Path(p).name.lower()
|
|
65
|
+
if ".ref." in name or "araport" in name or name.startswith("refseq_"):
|
|
66
|
+
raise ValueError(
|
|
67
|
+
"Target reference annotation/scores are not inference inputs: " + p
|
|
68
|
+
)
|
|
69
|
+
for name, keys, required in [
|
|
70
|
+
("peptides", {"bed", "sequences"}, "bed"),
|
|
71
|
+
(
|
|
72
|
+
"rna",
|
|
73
|
+
{
|
|
74
|
+
"bam",
|
|
75
|
+
"junctions",
|
|
76
|
+
"library",
|
|
77
|
+
"min_mapq",
|
|
78
|
+
"min_overhang",
|
|
79
|
+
"min_intron",
|
|
80
|
+
"max_intron",
|
|
81
|
+
"skip_duplicates",
|
|
82
|
+
},
|
|
83
|
+
None,
|
|
84
|
+
),
|
|
85
|
+
("proteins", {"annotation"}, "annotation"),
|
|
86
|
+
]:
|
|
87
|
+
spec = data.get(name)
|
|
88
|
+
if spec is None:
|
|
89
|
+
continue
|
|
90
|
+
if (
|
|
91
|
+
not isinstance(spec, dict)
|
|
92
|
+
or set(spec) - keys
|
|
93
|
+
or (required and required not in spec)
|
|
94
|
+
):
|
|
95
|
+
raise ValueError("Invalid " + name + " evidence specification")
|
|
96
|
+
if name == "rna" and sum(k in spec for k in ("bam", "junctions")) != 1:
|
|
97
|
+
raise ValueError("RNA requires exactly one of bam or junctions")
|
|
98
|
+
result[name] = {k: resolve(v) if k in PATH_KEYS else v for k, v in spec.items()}
|
|
99
|
+
params = dict(DEFAULTS)
|
|
100
|
+
extra = data.get("parameters", {})
|
|
101
|
+
if not isinstance(extra, dict) or set(extra) - set(params):
|
|
102
|
+
raise ValueError(
|
|
103
|
+
"Unknown algorithm parameters: " + repr(sorted(set(extra) - set(params)))
|
|
104
|
+
)
|
|
105
|
+
params.update(extra)
|
|
106
|
+
if params['peptide_strategy'] not in ('legacy','bounded_unique','fractional','graph_contrast'):
|
|
107
|
+
raise ValueError('Invalid peptide_strategy')
|
|
108
|
+
if params['peptide_strategy'] != 'legacy' and params['selection_policy'] != 'state_molecular_guided':
|
|
109
|
+
raise ValueError('Peptide context strategies require state_molecular_guided selection')
|
|
110
|
+
if params["isoform_policy"] not in ("off", "event_guarded"):
|
|
111
|
+
raise ValueError("Invalid isoform_policy")
|
|
112
|
+
if params["molecular_strategy"] not in ("source_context", "splice_context", "splice_orf"):
|
|
113
|
+
raise ValueError("Invalid molecular_strategy")
|
|
114
|
+
if params["molecular_strategy"] != "source_context" and params["selection_policy"] != "state_molecular_guided":
|
|
115
|
+
raise ValueError("Molecular splice strategies require state_molecular_guided selection")
|
|
116
|
+
if params["molecular_strategy"] != "source_context" and params["localizer_gate"] is None:
|
|
117
|
+
params["localizer_gate"] = params["addition_q"]
|
|
118
|
+
if isinstance(params["minimum_intron_nt"],bool) or not isinstance(params["minimum_intron_nt"],int) or params["minimum_intron_nt"]<4:
|
|
119
|
+
raise ValueError("minimum_intron_nt must be an integer >=4")
|
|
120
|
+
if isinstance(params["minimum_coding_nt"],bool) or not isinstance(params["minimum_coding_nt"],int) or params["minimum_coding_nt"]<0:
|
|
121
|
+
raise ValueError("minimum_coding_nt must be a nonnegative integer")
|
|
122
|
+
if params["selection_policy"] not in ("state_signed", "state_ratio", "state_rna_counts", "state_rna_log", "state_gap", "state_gap_soft", "state_admitted", "state_coherent", "state_soft_admitted", "state_splice_validated", "state_rna_corroborated", "state_molecular_guided", "locus_coverage", "locus_gene", "legacy", "adaptive_guarded", "adaptive_locus", "scoped", "local_exchange", "corroborated_exchange", "corroborated_tiered", "molecular_exchange", "molecular_tiered", "joint_exchange", "joint_tiered", "available_exchange", "available_tiered"):
|
|
123
|
+
raise ValueError("Invalid selection_policy")
|
|
124
|
+
for key in [
|
|
125
|
+
"threads",
|
|
126
|
+
"graph_beam",
|
|
127
|
+
"graph_candidates",
|
|
128
|
+
"graph_max_nodes",
|
|
129
|
+
"graph_max_starts",
|
|
130
|
+
"minimum_rna_templates",
|
|
131
|
+
]:
|
|
132
|
+
if (
|
|
133
|
+
isinstance(params[key], bool)
|
|
134
|
+
or not isinstance(params[key], int)
|
|
135
|
+
or params[key] < 1
|
|
136
|
+
):
|
|
137
|
+
raise ValueError(key + " must be a positive integer")
|
|
138
|
+
if not isinstance(params["compress_diagnostics"], bool):
|
|
139
|
+
raise ValueError("compress_diagnostics must be boolean")
|
|
140
|
+
if not isinstance(params["graph"], bool):
|
|
141
|
+
raise ValueError("graph must be boolean")
|
|
142
|
+
for key in [
|
|
143
|
+
"isoform_score_gate",
|
|
144
|
+
"risk_strength",
|
|
145
|
+
"q_advantage",
|
|
146
|
+
"risk_advantage",
|
|
147
|
+
"minimum_retained_fraction",
|
|
148
|
+
"addition_q",
|
|
149
|
+
]:
|
|
150
|
+
if (
|
|
151
|
+
not isinstance(params[key], (int, float))
|
|
152
|
+
or isinstance(params[key], bool)
|
|
153
|
+
or not math.isfinite(params[key])
|
|
154
|
+
or not 0 <= params[key] <= 1
|
|
155
|
+
):
|
|
156
|
+
raise ValueError(key + " must be in [0,1]")
|
|
157
|
+
if params["minimum_retained_fraction"] == 0:
|
|
158
|
+
raise ValueError("Retained fraction must be positive")
|
|
159
|
+
for key in [
|
|
160
|
+
"replacement_margin",
|
|
161
|
+
"molecular_weight",
|
|
162
|
+
"predictor_weight",
|
|
163
|
+
"peptide_weight",
|
|
164
|
+
"rna_weight",
|
|
165
|
+
"protein_weight",
|
|
166
|
+
"structure_weight",
|
|
167
|
+
"peptide_saturation",
|
|
168
|
+
"boundary_window_nt",
|
|
169
|
+
]:
|
|
170
|
+
if (
|
|
171
|
+
not isinstance(params[key], (int, float))
|
|
172
|
+
or isinstance(params[key], bool)
|
|
173
|
+
or not math.isfinite(params[key])
|
|
174
|
+
or params[key] < 0
|
|
175
|
+
):
|
|
176
|
+
raise ValueError(key + " must be finite and nonnegative")
|
|
177
|
+
if params["peptide_saturation"] == 0:
|
|
178
|
+
raise ValueError("Peptide saturation must be positive")
|
|
179
|
+
if params["backend"] not in ("cpu", "auto", "cuda"):
|
|
180
|
+
raise ValueError("Invalid scoring backend")
|
|
181
|
+
if params["confidence_gate"] is not None and (isinstance(params["confidence_gate"], bool) or not isinstance(params["confidence_gate"], (float,int)) or not math.isfinite(params["confidence_gate"]) or not 0 <= params["confidence_gate"] <= 1):
|
|
182
|
+
raise ValueError("confidence_gate must be finite in [0,1]")
|
|
183
|
+
if params["localizer_gate"] is not None and not 0 <= params["localizer_gate"] <= 1:
|
|
184
|
+
raise ValueError("Invalid localizer gate")
|
|
185
|
+
if not isinstance(params["boundary_window_nt"], int) or isinstance(
|
|
186
|
+
params["boundary_window_nt"], bool
|
|
187
|
+
):
|
|
188
|
+
raise ValueError("boundary_window_nt must be an integer")
|
|
189
|
+
if params["localizer_gate"] is not None and (
|
|
190
|
+
isinstance(params["localizer_gate"], bool)
|
|
191
|
+
or not isinstance(params["localizer_gate"], (int, float))
|
|
192
|
+
or not math.isfinite(params["localizer_gate"])
|
|
193
|
+
):
|
|
194
|
+
raise ValueError("localizer_gate must be a finite number or null")
|
|
195
|
+
if (
|
|
196
|
+
sum(
|
|
197
|
+
params[k]
|
|
198
|
+
for k in [
|
|
199
|
+
"molecular_weight",
|
|
200
|
+
"predictor_weight",
|
|
201
|
+
"peptide_weight",
|
|
202
|
+
"rna_weight",
|
|
203
|
+
"protein_weight",
|
|
204
|
+
"structure_weight",
|
|
205
|
+
]
|
|
206
|
+
)
|
|
207
|
+
<= 0
|
|
208
|
+
):
|
|
209
|
+
raise ValueError("At least one evidence weight must be positive")
|
|
210
|
+
if "rna" in result:
|
|
211
|
+
rna = result["rna"]
|
|
212
|
+
if rna.get("library", "unstranded") not in (
|
|
213
|
+
"unstranded",
|
|
214
|
+
"firststrand",
|
|
215
|
+
"secondstrand",
|
|
216
|
+
):
|
|
217
|
+
raise ValueError("Invalid RNA library mode")
|
|
218
|
+
for key in ["min_mapq", "min_overhang", "min_intron", "max_intron"]:
|
|
219
|
+
if key in rna and (
|
|
220
|
+
not isinstance(rna[key], int)
|
|
221
|
+
or isinstance(rna[key], bool)
|
|
222
|
+
or rna[key] < (0 if key == "min_mapq" else 1)
|
|
223
|
+
):
|
|
224
|
+
raise ValueError("Invalid RNA " + key)
|
|
225
|
+
if rna.get("max_intron", 500000) < rna.get("min_intron", 20):
|
|
226
|
+
raise ValueError("RNA max_intron must not be below min_intron")
|
|
227
|
+
if "skip_duplicates" in rna and not isinstance(rna["skip_duplicates"], bool):
|
|
228
|
+
raise ValueError("RNA skip_duplicates must be boolean")
|
|
229
|
+
result["parameters"] = params
|
|
230
|
+
for source, spec in result['predictions'].items():
|
|
231
|
+
if 'residue_profiles' not in spec:
|
|
232
|
+
continue
|
|
233
|
+
try:
|
|
234
|
+
import h5py
|
|
235
|
+
except ImportError as exc:
|
|
236
|
+
raise RuntimeError('Residue profiles require genesensus[molecular]') from exc
|
|
237
|
+
with h5py.File(spec['residue_profiles'], 'r') as profiles:
|
|
238
|
+
interpretation = str(profiles.attrs.get('interpretation', '')).lower()
|
|
239
|
+
if 'binary-negative' in interpretation:
|
|
240
|
+
if params['localizer_gate'] is None or 'scores' not in spec:
|
|
241
|
+
raise ValueError(
|
|
242
|
+
'Residue profiles for '+source+' declare binary-negative scope; '
|
|
243
|
+
'provide binary scores and parameters.localizer_gate from the '
|
|
244
|
+
'independently validated score model. Positive/unclassified '
|
|
245
|
+
'profiles are excluded, not assigned zero risk.'
|
|
246
|
+
)
|
|
247
|
+
return result
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def bam_index_paths(bam):
|
|
251
|
+
bam = Path(bam)
|
|
252
|
+
possible = [
|
|
253
|
+
Path(str(bam) + ".bai"),
|
|
254
|
+
bam.with_suffix(".bai"),
|
|
255
|
+
Path(str(bam) + ".csi"),
|
|
256
|
+
bam.with_suffix(".csi"),
|
|
257
|
+
]
|
|
258
|
+
indexes = sorted({str(p.resolve()) for p in possible if p.is_file()})
|
|
259
|
+
if not indexes:
|
|
260
|
+
raise ValueError("RNA BAM index is missing")
|
|
261
|
+
return indexes
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def input_paths(config):
|
|
265
|
+
out = {config["genome"]}
|
|
266
|
+
for spec in config["predictions"].values():
|
|
267
|
+
out.update(spec.values())
|
|
268
|
+
for key in ["peptides", "rna", "proteins"]:
|
|
269
|
+
for k, v in config.get(key, {}).items():
|
|
270
|
+
if k in PATH_KEYS:
|
|
271
|
+
out.add(v)
|
|
272
|
+
if "bam" in config.get("rna", {}):
|
|
273
|
+
out.update(bam_index_paths(config["rna"]["bam"]))
|
|
274
|
+
return sorted(out)
|
|
@@ -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_corroborated(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
|
+
q_crossing=gate is not None and c.q is not None and old.q is not None and c.q>=gate>old.q
|
|
20
|
+
corroboration=bool(pn>po or rn>ro or an>=ao+.1 or q_crossing 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']='independently_corroborated_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_corroborated(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_corroborated,votes=votes))
|
|
36
|
+
if p['selection_policy']!='corroborated_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,19 @@
|
|
|
1
|
+
"""Lossless optional streaming compression for large audit tables."""
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import gzip,io
|
|
5
|
+
|
|
6
|
+
@contextmanager
|
|
7
|
+
def diagnostic_writer(path,compressed=False):
|
|
8
|
+
path=Path(path)
|
|
9
|
+
if not compressed:
|
|
10
|
+
with path.open('w',encoding='utf-8',newline='') as handle:yield handle
|
|
11
|
+
else:
|
|
12
|
+
with path.open('wb') as raw:
|
|
13
|
+
with gzip.GzipFile(filename='',fileobj=raw,mode='wb',mtime=0,compresslevel=1) as zipped:
|
|
14
|
+
with io.TextIOWrapper(zipped,encoding='utf-8',newline='') as handle:yield handle
|
|
15
|
+
|
|
16
|
+
def diagnostic_reader(folder,name):
|
|
17
|
+
path=Path(folder)/name
|
|
18
|
+
if path.exists():return path.open('r',encoding='utf-8',newline='')
|
|
19
|
+
return gzip.open(str(path)+'.gz','rt',encoding='utf-8',newline='')
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Direct measured candidate quality, with conditional local error adjustments.
|
|
2
|
+
|
|
3
|
+
One additional bounded quality channel; no structural admission contribution.
|
|
4
|
+
The source-context channel remains the controlled comparator. This is a
|
|
5
|
+
protein plausibility measurement, not calibrated transcript correctness.
|
|
6
|
+
"""
|
|
7
|
+
from .molecular import local_risk
|
|
8
|
+
from .local_molecular import LocalMolecular
|
|
9
|
+
from .intervals import merge
|
|
10
|
+
|
|
11
|
+
class DirectMolecular(LocalMolecular):
|
|
12
|
+
def __init__(self,candidates,parameters):
|
|
13
|
+
super().__init__(candidates,parameters)
|
|
14
|
+
self.bykey={c.model.key:c for c in candidates}
|
|
15
|
+
|
|
16
|
+
def features(self,model):
|
|
17
|
+
candidate=self.bykey[model.key]
|
|
18
|
+
if candidate.q is None:
|
|
19
|
+
# Missing is unobserved. Do not substitute an inherited protein q.
|
|
20
|
+
return 0.,0.
|
|
21
|
+
coding=model.length*self.correction(candidate,model.cds)
|
|
22
|
+
splice=0.
|
|
23
|
+
width=self.p['boundary_window_nt']
|
|
24
|
+
for a,b in model.introns:
|
|
25
|
+
flanks=merge((max(x,u),min(y,v)) for x,y in model.cds
|
|
26
|
+
for u,v in ((max(0,a-width),a),(b,b+width))
|
|
27
|
+
if max(x,u)<min(y,v))
|
|
28
|
+
splice+=(b-a)*self.correction(candidate,flanks)
|
|
29
|
+
return coding,splice
|