Token Classification
Transformers
Safetensors
generanno
dna
genomics
biology
genome-annotation
custom_code
Instructions to use HuggingFaceBio/Carbon-A-1.2B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use HuggingFaceBio/Carbon-A-1.2B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="HuggingFaceBio/Carbon-A-1.2B", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForTokenClassification model = AutoModelForTokenClassification.from_pretrained("HuggingFaceBio/Carbon-A-1.2B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Support long records and write raw probabilities as Arrow IPC files
Browse files- README.md +1 -1
- annotation_pipeline/README.md +8 -6
- annotation_pipeline/run_annotation.sh +17 -6
- annotation_pipeline/src/confidence_network.py +109 -46
- annotation_pipeline/src/constants.py +33 -22
- annotation_pipeline/src/model_inference.py +119 -75
- annotation_pipeline/src/post_processing.py +141 -85
- annotation_pipeline/src/tcn.py +21 -19
- annotation_pipeline/src/transition_network.py +21 -15
- annotation_pipeline/src/utils.py +159 -108
- annotation_pipeline/src/viterbi.py +110 -111
- annotation_pipeline/src/viterbi_backends/viterbi_cpu.cpp +123 -684
- annotation_pipeline/src/viterbi_backends/{decode_cpu.py → viterbi_cpu.py} +15 -26
- annotation_pipeline/src/viterbi_backends/viterbi_gpu.cu +0 -0
- annotation_pipeline/src/viterbi_backends/{decode_gpu.py → viterbi_gpu.py} +39 -83
- annotation_pipeline/src/viterbi_backends/viterbi_grammar.h +705 -0
- requirements.txt +0 -1
README.md
CHANGED
|
@@ -57,7 +57,7 @@ The input is a FASTA or GenBank file, optionally gzip-compressed. Carbon-A reads
|
|
| 57 |
|
| 58 |
- `prediction.gff`: genes, mRNAs, and CDS. Every gene carries a model-derived `confidence` score for its predicted structure; higher values indicate greater model confidence.
|
| 59 |
- `prediction.fna` and `prediction.faa`: the CDS and protein sequences.
|
| 60 |
-
- `*.raw_probs.parquet`: the per-base CDS probabilities.
|
| 61 |
|
| 62 |
All genes are written. The reported results count the genes with a confidence of at least 0.1.
|
| 63 |
|
|
|
|
| 57 |
|
| 58 |
- `prediction.gff`: genes, mRNAs, and CDS. Every gene carries a model-derived `confidence` score for its predicted structure; higher values indicate greater model confidence.
|
| 59 |
- `prediction.fna` and `prediction.faa`: the CDS and protein sequences.
|
| 60 |
+
- `*.raw_probs.arrow` or `*.raw_probs.parquet`: the per-base CDS probabilities.
|
| 61 |
|
| 62 |
All genes are written. The reported results count the genes with a confidence of at least 0.1.
|
| 63 |
|
annotation_pipeline/README.md
CHANGED
|
@@ -97,7 +97,7 @@ The results are written below the current directory:
|
|
| 97 |
|
| 98 |
```text
|
| 99 |
results/<accession>/
|
| 100 |
-
*.raw_probs.
|
| 101 |
prediction.gff
|
| 102 |
prediction.fna
|
| 103 |
prediction.faa
|
|
@@ -112,8 +112,10 @@ and post-processing use every core available to them; `OMP_NUM_THREADS` sets
|
|
| 112 |
the number of threads. `--model` selects another model, a
|
| 113 |
Hub id or a local directory (default: `CARBON_A_MODEL`, otherwise
|
| 114 |
`HuggingFaceBio/Carbon-A-1.2B`), and `--revision` a branch, tag, or commit of a
|
| 115 |
-
model on the Hub (default: the latest).
|
| 116 |
-
|
|
|
|
|
|
|
| 117 |
|
| 118 |
When the codon-table check described below fails, the post-processing itself
|
| 119 |
appends the warning to `results/WARNINGS.txt` (time, accession, message with
|
|
@@ -134,7 +136,7 @@ results count the genes whose confidence reaches 0.1 (see Reference evaluation).
|
|
| 134 |
post-processing excludes records shorter than 100,000 bp and spliced CDS
|
| 135 |
models shorter than 96 bp. Set `--min-record-length 0` or `--min-cds-length 0`
|
| 136 |
to disable the corresponding filter. Use `--skip-inference` to rerun only
|
| 137 |
-
post-processing from an existing raw-probability
|
| 138 |
|
| 139 |
Post-processing options: `--transition-network FILE` and
|
| 140 |
`--confidence-network FILE` select other weight files and `--tcn-device DEVICE`
|
|
@@ -143,7 +145,7 @@ convolutional network (TCN); the default is `cuda` when available.
|
|
| 143 |
On CUDA the networks run under bfloat16 autocast, the precision used for all
|
| 144 |
reported results; on CPU they run in float32. `--viterbi-backend` selects the
|
| 145 |
Viterbi backend. `src/post_processing.py` can also be run directly on a
|
| 146 |
-
raw-probability
|
| 147 |
|
| 148 |
`GCF_000189635.1` (Tetrahymena thermophila) automatically uses NCBI translation
|
| 149 |
table 6. Other accessions use the standard translation table unless an
|
|
@@ -248,7 +250,7 @@ After all stages, each genome uses this layout:
|
|
| 248 |
|
| 249 |
```text
|
| 250 |
results/<accession>/
|
| 251 |
-
*.raw_probs.
|
| 252 |
prediction.gff
|
| 253 |
prediction.fna
|
| 254 |
prediction.faa
|
|
|
|
| 97 |
|
| 98 |
```text
|
| 99 |
results/<accession>/
|
| 100 |
+
*.raw_probs.arrow
|
| 101 |
prediction.gff
|
| 102 |
prediction.fna
|
| 103 |
prediction.faa
|
|
|
|
| 112 |
the number of threads. `--model` selects another model, a
|
| 113 |
Hub id or a local directory (default: `CARBON_A_MODEL`, otherwise
|
| 114 |
`HuggingFaceBio/Carbon-A-1.2B`), and `--revision` a branch, tag, or commit of a
|
| 115 |
+
model on the Hub (default: the latest). The raw probabilities are written as an
|
| 116 |
+
Arrow IPC file; `--raw-probs-format parquet` writes a Parquet file
|
| 117 |
+
(`*.raw_probs.parquet`) instead, for records of at most 1,000,000,000 bp.
|
| 118 |
+
`run_annotation.sh --help` lists every option.
|
| 119 |
|
| 120 |
When the codon-table check described below fails, the post-processing itself
|
| 121 |
appends the warning to `results/WARNINGS.txt` (time, accession, message with
|
|
|
|
| 136 |
post-processing excludes records shorter than 100,000 bp and spliced CDS
|
| 137 |
models shorter than 96 bp. Set `--min-record-length 0` or `--min-cds-length 0`
|
| 138 |
to disable the corresponding filter. Use `--skip-inference` to rerun only
|
| 139 |
+
post-processing from an existing raw-probability file.
|
| 140 |
|
| 141 |
Post-processing options: `--transition-network FILE` and
|
| 142 |
`--confidence-network FILE` select other weight files and `--tcn-device DEVICE`
|
|
|
|
| 145 |
On CUDA the networks run under bfloat16 autocast, the precision used for all
|
| 146 |
reported results; on CPU they run in float32. `--viterbi-backend` selects the
|
| 147 |
Viterbi backend. `src/post_processing.py` can also be run directly on a
|
| 148 |
+
raw-probability file.
|
| 149 |
|
| 150 |
`GCF_000189635.1` (Tetrahymena thermophila) automatically uses NCBI translation
|
| 151 |
table 6. Other accessions use the standard translation table unless an
|
|
|
|
| 250 |
|
| 251 |
```text
|
| 252 |
results/<accession>/
|
| 253 |
+
*.raw_probs.arrow
|
| 254 |
prediction.gff
|
| 255 |
prediction.fna
|
| 256 |
prediction.faa
|
annotation_pipeline/run_annotation.sh
CHANGED
|
@@ -24,6 +24,7 @@ GPU_COUNT="-1"
|
|
| 24 |
BATCH_SIZE="1"
|
| 25 |
DISPATCH_CHUNK_SIZE="4"
|
| 26 |
ATTN_IMPLEMENTATION="flash_attention_2"
|
|
|
|
| 27 |
SKIP_INFERENCE=0
|
| 28 |
|
| 29 |
TRANSITION_NETWORK=""
|
|
@@ -32,7 +33,7 @@ TCN_DEVICE=""
|
|
| 32 |
MIN_RECORD_LENGTH="100000"
|
| 33 |
MIN_CDS_LENGTH="96"
|
| 34 |
MAX_BOUNDARY_INTRON_LENGTH="20000"
|
| 35 |
-
CHUNK_MBP="
|
| 36 |
|
| 37 |
PREDICTION_PREFIX=""
|
| 38 |
RAW_PROBS=""
|
|
@@ -65,7 +66,10 @@ Inference:
|
|
| 65 |
--dispatch-chunk-size N Per-GPU dispatch chunk size (default: 4).
|
| 66 |
--attn-implementation NAME flash_attention_2 (default; used for all reported results)
|
| 67 |
or sdpa (needs no flash-attn package; not bit-identical).
|
| 68 |
-
--
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
Post-processing:
|
| 71 |
--viterbi-backend NAME Viterbi backend: auto, gpu, cpu, or numba (default: auto).
|
|
@@ -79,7 +83,8 @@ Post-processing:
|
|
| 79 |
--min-cds-length N Minimum spliced CDS length (default: 96).
|
| 80 |
--max-boundary-intron-length N
|
| 81 |
Maximum boundary intron length (default: 20000).
|
| 82 |
-
--chunk-mbp N Post-processing chunk size in Mbp (default:
|
|
|
|
| 83 |
|
| 84 |
-h, --help Show this help message.
|
| 85 |
EOF
|
|
@@ -190,6 +195,11 @@ parse_args() {
|
|
| 190 |
ATTN_IMPLEMENTATION="$2"
|
| 191 |
shift 2
|
| 192 |
;;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
--skip-inference)
|
| 194 |
SKIP_INFERENCE=1
|
| 195 |
shift
|
|
@@ -270,6 +280,7 @@ run_inference() {
|
|
| 270 |
--batch_size "$BATCH_SIZE"
|
| 271 |
--dispatch_chunk_size "$DISPATCH_CHUNK_SIZE"
|
| 272 |
--attn_implementation "$ATTN_IMPLEMENTATION"
|
|
|
|
| 273 |
)
|
| 274 |
[[ -n "$MODEL" ]] && inference_args+=(--model_name "$MODEL")
|
| 275 |
[[ -n "$REVISION" ]] && inference_args+=(--revision "$REVISION")
|
|
@@ -279,9 +290,9 @@ run_inference() {
|
|
| 279 |
}
|
| 280 |
|
| 281 |
select_raw_probs() {
|
| 282 |
-
local candidates=("$OUTPUT_DIR"/*.raw_probs.parquet)
|
| 283 |
(( ${#candidates[@]} > 0 )) || \
|
| 284 |
-
die "no raw-probability
|
| 285 |
|
| 286 |
RAW_PROBS="${candidates[0]}"
|
| 287 |
local candidate
|
|
@@ -301,10 +312,10 @@ run_postprocessing() {
|
|
| 301 |
--viterbi_backend "$VITERBI_BACKEND"
|
| 302 |
--codon_table "$CODON_TABLE"
|
| 303 |
--max_boundary_intron_length "$MAX_BOUNDARY_INTRON_LENGTH"
|
| 304 |
-
--chunk_mbp "$CHUNK_MBP"
|
| 305 |
--min_record_length "$MIN_RECORD_LENGTH"
|
| 306 |
--min_cds_length "$MIN_CDS_LENGTH"
|
| 307 |
)
|
|
|
|
| 308 |
[[ -n "$TRANSITION_NETWORK" ]] && postprocess_args+=(--transition_network "$TRANSITION_NETWORK")
|
| 309 |
[[ -n "$CONFIDENCE_NETWORK" ]] && postprocess_args+=(--confidence_network "$CONFIDENCE_NETWORK")
|
| 310 |
[[ -n "$TCN_DEVICE" ]] && postprocess_args+=(--tcn_device "$TCN_DEVICE")
|
|
|
|
| 24 |
BATCH_SIZE="1"
|
| 25 |
DISPATCH_CHUNK_SIZE="4"
|
| 26 |
ATTN_IMPLEMENTATION="flash_attention_2"
|
| 27 |
+
RAW_PROBS_FORMAT="arrow"
|
| 28 |
SKIP_INFERENCE=0
|
| 29 |
|
| 30 |
TRANSITION_NETWORK=""
|
|
|
|
| 33 |
MIN_RECORD_LENGTH="100000"
|
| 34 |
MIN_CDS_LENGTH="96"
|
| 35 |
MAX_BOUNDARY_INTRON_LENGTH="20000"
|
| 36 |
+
CHUNK_MBP=""
|
| 37 |
|
| 38 |
PREDICTION_PREFIX=""
|
| 39 |
RAW_PROBS=""
|
|
|
|
| 66 |
--dispatch-chunk-size N Per-GPU dispatch chunk size (default: 4).
|
| 67 |
--attn-implementation NAME flash_attention_2 (default; used for all reported results)
|
| 68 |
or sdpa (needs no flash-attn package; not bit-identical).
|
| 69 |
+
--raw-probs-format NAME arrow (default; Arrow IPC, *.raw_probs.arrow) or parquet
|
| 70 |
+
(*.raw_probs.parquet; records of at most 1,000,000,000 bp).
|
| 71 |
+
--skip-inference Reuse the newest *.raw_probs.arrow or *.raw_probs.parquet
|
| 72 |
+
in --output-dir.
|
| 73 |
|
| 74 |
Post-processing:
|
| 75 |
--viterbi-backend NAME Viterbi backend: auto, gpu, cpu, or numba (default: auto).
|
|
|
|
| 83 |
--min-cds-length N Minimum spliced CDS length (default: 96).
|
| 84 |
--max-boundary-intron-length N
|
| 85 |
Maximum boundary intron length (default: 20000).
|
| 86 |
+
--chunk-mbp N Post-processing chunk size in Mbp (default: 25, or 1000
|
| 87 |
+
with the CPU Viterbi backend).
|
| 88 |
|
| 89 |
-h, --help Show this help message.
|
| 90 |
EOF
|
|
|
|
| 195 |
ATTN_IMPLEMENTATION="$2"
|
| 196 |
shift 2
|
| 197 |
;;
|
| 198 |
+
--raw-probs-format|--raw_probs_format)
|
| 199 |
+
require_value "$1" "$#"
|
| 200 |
+
RAW_PROBS_FORMAT="$2"
|
| 201 |
+
shift 2
|
| 202 |
+
;;
|
| 203 |
--skip-inference)
|
| 204 |
SKIP_INFERENCE=1
|
| 205 |
shift
|
|
|
|
| 280 |
--batch_size "$BATCH_SIZE"
|
| 281 |
--dispatch_chunk_size "$DISPATCH_CHUNK_SIZE"
|
| 282 |
--attn_implementation "$ATTN_IMPLEMENTATION"
|
| 283 |
+
--raw_probs_format "$RAW_PROBS_FORMAT"
|
| 284 |
)
|
| 285 |
[[ -n "$MODEL" ]] && inference_args+=(--model_name "$MODEL")
|
| 286 |
[[ -n "$REVISION" ]] && inference_args+=(--revision "$REVISION")
|
|
|
|
| 290 |
}
|
| 291 |
|
| 292 |
select_raw_probs() {
|
| 293 |
+
local candidates=("$OUTPUT_DIR"/*.raw_probs.arrow "$OUTPUT_DIR"/*.raw_probs.parquet)
|
| 294 |
(( ${#candidates[@]} > 0 )) || \
|
| 295 |
+
die "no raw-probability file found in $OUTPUT_DIR"
|
| 296 |
|
| 297 |
RAW_PROBS="${candidates[0]}"
|
| 298 |
local candidate
|
|
|
|
| 312 |
--viterbi_backend "$VITERBI_BACKEND"
|
| 313 |
--codon_table "$CODON_TABLE"
|
| 314 |
--max_boundary_intron_length "$MAX_BOUNDARY_INTRON_LENGTH"
|
|
|
|
| 315 |
--min_record_length "$MIN_RECORD_LENGTH"
|
| 316 |
--min_cds_length "$MIN_CDS_LENGTH"
|
| 317 |
)
|
| 318 |
+
[[ -n "$CHUNK_MBP" ]] && postprocess_args+=(--chunk_mbp "$CHUNK_MBP")
|
| 319 |
[[ -n "$TRANSITION_NETWORK" ]] && postprocess_args+=(--transition_network "$TRANSITION_NETWORK")
|
| 320 |
[[ -n "$CONFIDENCE_NETWORK" ]] && postprocess_args+=(--confidence_network "$CONFIDENCE_NETWORK")
|
| 321 |
[[ -n "$TCN_DEVICE" ]] && postprocess_args+=(--tcn_device "$TCN_DEVICE")
|
annotation_pipeline/src/confidence_network.py
CHANGED
|
@@ -12,22 +12,25 @@ vector per base. For each scored gene, the feature vectors at its exon bases
|
|
| 12 |
are pooled by two attention heads and an MLP maps the pooled vectors to the
|
| 13 |
confidence logit; the sigmoid of the logit is the confidence.
|
| 14 |
|
| 15 |
-
``inference`` does this for a strand of any length
|
| 16 |
-
|
| 17 |
network's context radius of its base, so only the windows of that radius
|
| 18 |
around the scored exons are read, concatenated and processed in chunks the
|
| 19 |
-
way the transition network reads a record (tcn.chunked_inference)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
|
| 25 |
import numpy as np
|
| 26 |
import torch
|
| 27 |
from torch import nn
|
| 28 |
|
| 29 |
-
from constants import NETWORK_CHUNK_BP
|
| 30 |
from tcn import TCN, chunked_inference, coding_log_odds, load_weights
|
|
|
|
| 31 |
|
| 32 |
CONFIDENCE_NETWORK_TYPE = "confidence_network"
|
| 33 |
|
|
@@ -50,7 +53,7 @@ def input_tracks(probabilities, roles):
|
|
| 50 |
if probabilities.ndim != 2 or roles.shape != probabilities.shape:
|
| 51 |
raise ValueError("probabilities and roles must both have shape [batch, bases]")
|
| 52 |
log_odds = coding_log_odds(probabilities)
|
| 53 |
-
role_tracks = nn.functional.one_hot(roles, num_classes=len(ROLE_NAMES)).to(log_odds.dtype)
|
| 54 |
sign = role_tracks[..., ROLE_EXON] * 2 - 1
|
| 55 |
return torch.cat(((log_odds * sign)[:, None, :], role_tracks.transpose(1, 2)), dim=1)
|
| 56 |
|
|
@@ -83,27 +86,26 @@ class ConfidenceNetwork(nn.Module):
|
|
| 83 |
"""Return the ``[bases, channels]`` features of a strand, or a chunk of one, given as ``[bases]`` tensors."""
|
| 84 |
return self.encoder(input_tracks(probabilities[None, :], roles[None, :]))[0]
|
| 85 |
|
| 86 |
-
def gene_logits(self,
|
| 87 |
"""Return one confidence logit per gene from the features at its exon bases.
|
| 88 |
|
| 89 |
-
``
|
| 90 |
-
|
| 91 |
-
the
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
"""
|
| 95 |
-
|
| 96 |
-
if not
|
| 97 |
raise ValueError("at least one gene is required")
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
| 101 |
|
| 102 |
-
lengths = torch.as_tensor(
|
| 103 |
-
[len(features) for features in exon_features],
|
| 104 |
-
dtype=torch.long, device=exon_features[0].device,
|
| 105 |
-
)
|
| 106 |
-
features = torch.cat(exon_features)
|
| 107 |
# The gene every base belongs to, repeated for every head.
|
| 108 |
gene_of_base = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths)
|
| 109 |
gene_of_base_per_head = gene_of_base[:, None].expand(-1, self.attention_heads)
|
|
@@ -125,41 +127,79 @@ class ConfidenceNetwork(nn.Module):
|
|
| 125 |
return self.readout(pooled.flatten(1)).squeeze(1)
|
| 126 |
|
| 127 |
@torch.inference_mode()
|
| 128 |
-
def inference(self, probabilities, exons_by_gene, scored, chunk_bp=NETWORK_CHUNK_BP):
|
| 129 |
"""Return the confidence of each scored gene of one strand.
|
| 130 |
|
| 131 |
-
``probabilities`` is the strand's coding-probability track in
|
| 132 |
orientation; ``exons_by_gene`` holds the inclusive exon intervals, in
|
| 133 |
transcript order, of every gene decoded on the strand; ``scored`` lists
|
| 134 |
the positions in ``exons_by_gene`` of the complete genes to score.
|
| 135 |
-
Every decoded gene gives roles to the strand. The
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
"""
|
| 138 |
scored = list(scored)
|
|
|
|
| 139 |
if not scored:
|
| 140 |
return np.zeros(0, dtype=np.float64)
|
| 141 |
device = next(self.parameters()).device
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
probabilities = np.asarray(probabilities)
|
| 143 |
roles = strand_roles(exons_by_gene, len(probabilities))
|
| 144 |
scored_exons = [exons_by_gene[index] for index in scored]
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
window_probabilities = np.concatenate([probabilities[start:stop] for start, stop in windows])
|
| 150 |
window_roles = np.concatenate([roles[start:stop] for start, stop in windows])
|
| 151 |
-
# 2. Where
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
# 3. Encode the concatenated windows in chunks; keep the features at the exon bases.
|
| 156 |
-
features = chunked_inference(
|
| 157 |
-
self.encode, self.context_radius, (window_probabilities, window_roles), device, chunk_bp,
|
| 158 |
)
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
|
| 165 |
def load_confidence_network(path, device):
|
|
@@ -181,12 +221,12 @@ def load_confidence_network(path, device):
|
|
| 181 |
|
| 182 |
|
| 183 |
def strand_roles(exons_by_gene, record_length):
|
| 184 |
-
"""Return the role of every base of a strand from the oriented exons of its decoded genes.
|
| 185 |
|
| 186 |
A base inside a gene's span is intron unless some gene has an exon there;
|
| 187 |
every other base is intergenic. Every decoded gene counts, complete or not.
|
| 188 |
"""
|
| 189 |
-
roles = np.full(record_length, ROLE_INTERGENIC, dtype=np.
|
| 190 |
for oriented_exons in exons_by_gene:
|
| 191 |
roles[oriented_exons[0][0]:oriented_exons[-1][1] + 1] = ROLE_INTRON
|
| 192 |
for oriented_exons in exons_by_gene:
|
|
@@ -225,8 +265,31 @@ def exon_windows(scored_exons, record_length, context_radius):
|
|
| 225 |
|
| 226 |
|
| 227 |
def positions_in_windows(positions, windows):
|
| 228 |
-
"""Map
|
| 229 |
window_starts = np.asarray([start for start, _ in windows], dtype=np.int64)
|
| 230 |
concatenated_starts = np.concatenate(([0], np.cumsum([stop - start for start, stop in windows])[:-1]))
|
| 231 |
window = np.searchsorted(window_starts, positions, side="right") - 1
|
| 232 |
return positions - window_starts[window] + concatenated_starts[window]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
are pooled by two attention heads and an MLP maps the pooled vectors to the
|
| 13 |
confidence logit; the sigmoid of the logit is the confidence.
|
| 14 |
|
| 15 |
+
``inference`` does this for a strand of any length within a bounded amount of
|
| 16 |
+
device memory. A feature vector depends only on the strand within the
|
| 17 |
network's context radius of its base, so only the windows of that radius
|
| 18 |
around the scored exons are read, concatenated and processed in chunks the
|
| 19 |
+
way the transition network reads a record (tcn.chunked_inference), and only
|
| 20 |
+
the features at exon bases are kept. The genes are pooled in groups whose
|
| 21 |
+
exon bases fit the device memory budget; a strand whose genes fit in one
|
| 22 |
+
group is scored in one pass. Only complete genes are scored; a gene truncated
|
| 23 |
+
by a record edge has no complete structure to judge, but its decoded bases
|
| 24 |
+
still give roles to the strand for its neighbours.
|
| 25 |
"""
|
| 26 |
|
| 27 |
import numpy as np
|
| 28 |
import torch
|
| 29 |
from torch import nn
|
| 30 |
|
| 31 |
+
from constants import CONFIDENCE_NETWORK_BYTES_PER_EXON_BASE, GPU_MEMORY_FRACTION, NETWORK_CHUNK_BP
|
| 32 |
from tcn import TCN, chunked_inference, coding_log_odds, load_weights
|
| 33 |
+
from utils import validate_memory_budget_bytes
|
| 34 |
|
| 35 |
CONFIDENCE_NETWORK_TYPE = "confidence_network"
|
| 36 |
|
|
|
|
| 53 |
if probabilities.ndim != 2 or roles.shape != probabilities.shape:
|
| 54 |
raise ValueError("probabilities and roles must both have shape [batch, bases]")
|
| 55 |
log_odds = coding_log_odds(probabilities)
|
| 56 |
+
role_tracks = nn.functional.one_hot(roles.long(), num_classes=len(ROLE_NAMES)).to(log_odds.dtype)
|
| 57 |
sign = role_tracks[..., ROLE_EXON] * 2 - 1
|
| 58 |
return torch.cat(((log_odds * sign)[:, None, :], role_tracks.transpose(1, 2)), dim=1)
|
| 59 |
|
|
|
|
| 86 |
"""Return the ``[bases, channels]`` features of a strand, or a chunk of one, given as ``[bases]`` tensors."""
|
| 87 |
return self.encoder(input_tracks(probabilities[None, :], roles[None, :]))[0]
|
| 88 |
|
| 89 |
+
def gene_logits(self, features, exon_base_counts):
|
| 90 |
"""Return one confidence logit per gene from the features at its exon bases.
|
| 91 |
|
| 92 |
+
``features`` is the ``[exon_bases, channels]`` tensor of the features at
|
| 93 |
+
the exon bases of the genes, gene after gene; ``exon_base_counts``
|
| 94 |
+
gives the number of exon bases of each gene. Each head gives every
|
| 95 |
+
exon base an attention logit; the softmax over the bases of one gene
|
| 96 |
+
weights their feature vectors into one pooled vector per head. Genes
|
| 97 |
+
are pooled side by side with segment sums, so no gene is padded to the
|
| 98 |
+
length of another.
|
| 99 |
"""
|
| 100 |
+
exon_base_counts = [int(count) for count in exon_base_counts]
|
| 101 |
+
if not exon_base_counts:
|
| 102 |
raise ValueError("at least one gene is required")
|
| 103 |
+
if min(exon_base_counts) < 1:
|
| 104 |
+
raise ValueError("a gene must contain at least one exon base")
|
| 105 |
+
if features.ndim != 2 or len(features) != sum(exon_base_counts):
|
| 106 |
+
raise ValueError("features must hold one row per exon base of the genes")
|
| 107 |
|
| 108 |
+
lengths = torch.as_tensor(exon_base_counts, dtype=torch.long, device=features.device)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
# The gene every base belongs to, repeated for every head.
|
| 110 |
gene_of_base = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths)
|
| 111 |
gene_of_base_per_head = gene_of_base[:, None].expand(-1, self.attention_heads)
|
|
|
|
| 127 |
return self.readout(pooled.flatten(1)).squeeze(1)
|
| 128 |
|
| 129 |
@torch.inference_mode()
|
| 130 |
+
def inference(self, probabilities, exons_by_gene, scored, chunk_bp=NETWORK_CHUNK_BP, memory_budget_bytes=None):
|
| 131 |
"""Return the confidence of each scored gene of one strand.
|
| 132 |
|
| 133 |
+
``probabilities`` is the strand's coding-probability track in transcript
|
| 134 |
orientation; ``exons_by_gene`` holds the inclusive exon intervals, in
|
| 135 |
transcript order, of every gene decoded on the strand; ``scored`` lists
|
| 136 |
the positions in ``exons_by_gene`` of the complete genes to score.
|
| 137 |
+
Every decoded gene gives roles to the strand. The scored genes are
|
| 138 |
+
taken in the order of ``scored``, in groups whose exon bases fit
|
| 139 |
+
``memory_budget_bytes`` of device memory at
|
| 140 |
+
CONFIDENCE_NETWORK_BYTES_PER_EXON_BASE each; a gene too large for the
|
| 141 |
+
budget forms a group alone. ``None`` takes GPU_MEMORY_FRACTION of the
|
| 142 |
+
free memory of a CUDA device, and scores all genes in one group on the
|
| 143 |
+
CPU. The confidences come back as a float64 array in the order of
|
| 144 |
+
``scored``.
|
| 145 |
"""
|
| 146 |
scored = list(scored)
|
| 147 |
+
memory_budget_bytes = validate_memory_budget_bytes(memory_budget_bytes)
|
| 148 |
if not scored:
|
| 149 |
return np.zeros(0, dtype=np.float64)
|
| 150 |
device = next(self.parameters()).device
|
| 151 |
+
if memory_budget_bytes is None and device.type == "cuda":
|
| 152 |
+
# Memory that torch has cached but does not use is free for the network's tensors.
|
| 153 |
+
free_bytes = (
|
| 154 |
+
torch.cuda.mem_get_info(device)[0]
|
| 155 |
+
+ torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)
|
| 156 |
+
)
|
| 157 |
+
memory_budget_bytes = int(free_bytes * GPU_MEMORY_FRACTION)
|
| 158 |
+
max_group_exon_bases = (
|
| 159 |
+
None if memory_budget_bytes is None else memory_budget_bytes // CONFIDENCE_NETWORK_BYTES_PER_EXON_BASE
|
| 160 |
+
)
|
| 161 |
probabilities = np.asarray(probabilities)
|
| 162 |
roles = strand_roles(exons_by_gene, len(probabilities))
|
| 163 |
scored_exons = [exons_by_gene[index] for index in scored]
|
| 164 |
+
exon_base_counts = [
|
| 165 |
+
sum(exon_stop_inclusive - exon_start + 1 for exon_start, exon_stop_inclusive in oriented_exons)
|
| 166 |
+
for oriented_exons in scored_exons
|
| 167 |
+
]
|
| 168 |
+
logits = torch.cat([
|
| 169 |
+
self.group_logits(probabilities, roles, scored_exons[start:stop], exon_base_counts[start:stop], chunk_bp)
|
| 170 |
+
for start, stop in gene_groups(exon_base_counts, max_group_exon_bases)
|
| 171 |
+
])
|
| 172 |
+
return torch.sigmoid(logits.to(torch.float64)).cpu().numpy()
|
| 173 |
+
|
| 174 |
+
def group_logits(self, probabilities, roles, group_exons, exon_base_counts, chunk_bp):
|
| 175 |
+
"""Return the confidence logits of a group of genes of one strand.
|
| 176 |
+
|
| 177 |
+
``roles`` holds the decoded role of every base of the strand
|
| 178 |
+
(``strand_roles``), ``group_exons`` the oriented exons of the genes of
|
| 179 |
+
the group, and ``exon_base_counts`` their numbers of exon bases.
|
| 180 |
+
"""
|
| 181 |
+
device = next(self.parameters()).device
|
| 182 |
+
# 1. Keep only the bases an exon of the group can see: the window of one
|
| 183 |
+
# context radius around every exon, merged, in strand order.
|
| 184 |
+
windows = exon_windows(group_exons, len(probabilities), self.context_radius)
|
| 185 |
window_probabilities = np.concatenate([probabilities[start:stop] for start, stop in windows])
|
| 186 |
window_roles = np.concatenate([roles[start:stop] for start, stop in windows])
|
| 187 |
+
# 2. Where the exon bases lie in the concatenated windows, gene after
|
| 188 |
+
# gene in transcript order, and the same positions in increasing order.
|
| 189 |
+
positions = positions_in_windows(
|
| 190 |
+
np.concatenate([exon_positions(oriented_exons) for oriented_exons in group_exons]), windows,
|
|
|
|
|
|
|
|
|
|
| 191 |
)
|
| 192 |
+
order = np.argsort(positions, kind="stable")
|
| 193 |
+
sorted_positions = positions[order]
|
| 194 |
+
# 3. Encode the concatenated windows in chunks; keep the features at the exon bases only.
|
| 195 |
+
features = np.empty((len(positions), self.encoder.channels), dtype=np.float32)
|
| 196 |
+
for start, stop, chunk_features in chunked_inference(
|
| 197 |
+
self.encode, self.context_radius, (window_probabilities, window_roles), device, chunk_bp,
|
| 198 |
+
):
|
| 199 |
+
first, last = np.searchsorted(sorted_positions, (start, stop))
|
| 200 |
+
features[order[first:last]] = chunk_features[sorted_positions[first:last] - start]
|
| 201 |
+
# 4. Pool each gene's exon features into its confidence logit.
|
| 202 |
+
return self.gene_logits(torch.as_tensor(features).to(device), exon_base_counts)
|
| 203 |
|
| 204 |
|
| 205 |
def load_confidence_network(path, device):
|
|
|
|
| 221 |
|
| 222 |
|
| 223 |
def strand_roles(exons_by_gene, record_length):
|
| 224 |
+
"""Return the int8 role of every base of a strand from the oriented exons of its decoded genes.
|
| 225 |
|
| 226 |
A base inside a gene's span is intron unless some gene has an exon there;
|
| 227 |
every other base is intergenic. Every decoded gene counts, complete or not.
|
| 228 |
"""
|
| 229 |
+
roles = np.full(record_length, ROLE_INTERGENIC, dtype=np.int8)
|
| 230 |
for oriented_exons in exons_by_gene:
|
| 231 |
roles[oriented_exons[0][0]:oriented_exons[-1][1] + 1] = ROLE_INTRON
|
| 232 |
for oriented_exons in exons_by_gene:
|
|
|
|
| 265 |
|
| 266 |
|
| 267 |
def positions_in_windows(positions, windows):
|
| 268 |
+
"""Map strand positions inside ``windows`` to positions in the concatenated windows."""
|
| 269 |
window_starts = np.asarray([start for start, _ in windows], dtype=np.int64)
|
| 270 |
concatenated_starts = np.concatenate(([0], np.cumsum([stop - start for start, stop in windows])[:-1]))
|
| 271 |
window = np.searchsorted(window_starts, positions, side="right") - 1
|
| 272 |
return positions - window_starts[window] + concatenated_starts[window]
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def gene_groups(exon_base_counts, max_group_exon_bases):
|
| 276 |
+
"""Split genes, in order, into consecutive groups of at most ``max_group_exon_bases`` exon bases.
|
| 277 |
+
|
| 278 |
+
``exon_base_counts`` gives the number of exon bases of each gene. A gene
|
| 279 |
+
with more exon bases than the limit forms a group alone; ``None`` puts all
|
| 280 |
+
genes in one group. Returns the groups as ``(start, stop)`` ranges of
|
| 281 |
+
positions in ``exon_base_counts``.
|
| 282 |
+
"""
|
| 283 |
+
groups = []
|
| 284 |
+
start = group_exon_bases = 0
|
| 285 |
+
for position, count in enumerate(exon_base_counts):
|
| 286 |
+
if (
|
| 287 |
+
max_group_exon_bases is not None and position > start
|
| 288 |
+
and group_exon_bases + count > max_group_exon_bases
|
| 289 |
+
):
|
| 290 |
+
groups.append((start, position))
|
| 291 |
+
start, group_exon_bases = position, 0
|
| 292 |
+
group_exon_bases += count
|
| 293 |
+
if start < len(exon_base_counts):
|
| 294 |
+
groups.append((start, len(exon_base_counts)))
|
| 295 |
+
return groups
|
annotation_pipeline/src/constants.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""Shared constants for the Carbon-A annotation pipeline.
|
| 2 |
|
| 3 |
Keep cross-module data contracts and tunable pipeline parameters here. Private
|
| 4 |
-
implementation details, such as
|
| 5 |
with the modules that own them.
|
| 6 |
"""
|
| 7 |
|
|
@@ -91,10 +91,10 @@ AT_AC_INTRON_LOG_PRIOR = math.log(0.001 / 0.99)
|
|
| 91 |
WEIGHTS_DIRECTORY = PROJECT_DIRECTORY / "weights"
|
| 92 |
TRANSITION_NETWORK_PATH = WEIGHTS_DIRECTORY / "transition_network.safetensors"
|
| 93 |
CONFIDENCE_NETWORK_PATH = WEIGHTS_DIRECTORY / "confidence_network.safetensors"
|
| 94 |
-
# Per-base transition
|
| 95 |
-
#
|
| 96 |
-
#
|
| 97 |
-
#
|
| 98 |
TRANSITION_NAMES = ("enter_gene", "leave_gene", "enter_intron", "leave_intron")
|
| 99 |
TRANSITION_COUNT = len(TRANSITION_NAMES)
|
| 100 |
ENTER_GENE, LEAVE_GENE, ENTER_INTRON, LEAVE_INTRON = range(TRANSITION_COUNT)
|
|
@@ -102,36 +102,47 @@ NETWORK_INPUT_MIN_PROB = 1.0e-4
|
|
| 102 |
# Both networks read long tracks in chunks of this many bases, each evaluated
|
| 103 |
# with the network's full context on both sides (tcn.chunked_inference), so a
|
| 104 |
# chromosome never has to fit in GPU memory at once. (The post-processing
|
| 105 |
-
# driver separately groups whole
|
| 106 |
NETWORK_CHUNK_BP = 262_144
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
# Native Viterbi implementations accumulate int32 fixed-point scores.
|
| 108 |
-
# Transition
|
| 109 |
-
#
|
| 110 |
FIXED_POINT_SCORE_SCALE = 16384.0
|
| 111 |
|
| 112 |
# Boundary introns model genes truncated at a record edge. A finite limit
|
| 113 |
# prevents an incomplete path from hiding a long region as one intron.
|
| 114 |
MAX_BOUNDARY_INTRON_LENGTH_BP = 20_000
|
| 115 |
|
| 116 |
-
# Records shorter than this are skipped.
|
| 117 |
-
# target size because a sequence record is never split.
|
| 118 |
MIN_RECORD_LENGTH_BP = 100_000
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
PARQUET_BATCH_ROWS = 1
|
|
|
|
| 121 |
CODON_TABLE_PATH = PROJECT_DIRECTORY / "codon_tables" / "standard.json"
|
| 122 |
|
| 123 |
|
| 124 |
-
# GPU Viterbi backend
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
#
|
| 129 |
-
#
|
| 130 |
-
|
| 131 |
-
#
|
| 132 |
-
#
|
| 133 |
-
|
| 134 |
-
GPU_ESTIMATED_BYTES_PER_BASE = 34
|
| 135 |
|
| 136 |
|
| 137 |
# Gene-level results count the predicted genes whose confidence reaches this
|
|
|
|
| 1 |
"""Shared constants for the Carbon-A annotation pipeline.
|
| 2 |
|
| 3 |
Keep cross-module data contracts and tunable pipeline parameters here. Private
|
| 4 |
+
implementation details, such as Viterbi state ids and evaluation regexes, stay
|
| 5 |
with the modules that own them.
|
| 6 |
"""
|
| 7 |
|
|
|
|
| 91 |
WEIGHTS_DIRECTORY = PROJECT_DIRECTORY / "weights"
|
| 92 |
TRANSITION_NETWORK_PATH = WEIGHTS_DIRECTORY / "transition_network.safetensors"
|
| 93 |
CONFIDENCE_NETWORK_PATH = WEIGHTS_DIRECTORY / "confidence_network.safetensors"
|
| 94 |
+
# Per-base transition tracks handed to the Viterbi backends, in this column
|
| 95 |
+
# order. They are stored as log-odds against staying in the backends'
|
| 96 |
+
# fixed-point units; the native backends and the Numba reference share the
|
| 97 |
+
# layout.
|
| 98 |
TRANSITION_NAMES = ("enter_gene", "leave_gene", "enter_intron", "leave_intron")
|
| 99 |
TRANSITION_COUNT = len(TRANSITION_NAMES)
|
| 100 |
ENTER_GENE, LEAVE_GENE, ENTER_INTRON, LEAVE_INTRON = range(TRANSITION_COUNT)
|
|
|
|
| 102 |
# Both networks read long tracks in chunks of this many bases, each evaluated
|
| 103 |
# with the network's full context on both sides (tcn.chunked_inference), so a
|
| 104 |
# chromosome never has to fit in GPU memory at once. (The post-processing
|
| 105 |
+
# driver separately groups whole strands into host-side chunks, chunk_mbp.)
|
| 106 |
NETWORK_CHUNK_BP = 262_144
|
| 107 |
+
# Device memory the shipped confidence network needs per exon base of the
|
| 108 |
+
# genes it pools at once. The peak is in the attention MLP: the base's 32
|
| 109 |
+
# float32 features, the 32 float32 hidden values before and the 32 after GELU,
|
| 110 |
+
# and the base's int64 gene index. The genes of a strand are pooled in groups
|
| 111 |
+
# whose exon bases fit GPU_MEMORY_FRACTION of the free device memory at this
|
| 112 |
+
# size.
|
| 113 |
+
CONFIDENCE_NETWORK_BYTES_PER_EXON_BASE = 392
|
| 114 |
# Native Viterbi implementations accumulate int32 fixed-point scores.
|
| 115 |
+
# Transition log-odds are exchanged in the same units: nats multiplied by
|
| 116 |
+
# this scale and rounded.
|
| 117 |
FIXED_POINT_SCORE_SCALE = 16384.0
|
| 118 |
|
| 119 |
# Boundary introns model genes truncated at a record edge. A finite limit
|
| 120 |
# prevents an incomplete path from hiding a long region as one intron.
|
| 121 |
MAX_BOUNDARY_INTRON_LENGTH_BP = 20_000
|
| 122 |
|
| 123 |
+
# Records shorter than this are skipped.
|
|
|
|
| 124 |
MIN_RECORD_LENGTH_BP = 100_000
|
| 125 |
+
# Host-side chunk size in megabases by Viterbi backend. Post-processing takes
|
| 126 |
+
# about 50 MB of host memory per megabase of its largest chunk. The CPU
|
| 127 |
+
# backend decodes the strands of a chunk in parallel, one thread each, so it
|
| 128 |
+
# is given large chunks; the other backends gain nothing from them. A strand
|
| 129 |
+
# is never split: one longer than the chunk size is a chunk of its own.
|
| 130 |
+
CHUNK_SIZE_MBP = {"gpu": 25, "cpu": 1000, "numba": 25}
|
| 131 |
PARQUET_BATCH_ROWS = 1
|
| 132 |
+
PARQUET_READ_BUFFER_BYTES = 8 << 20
|
| 133 |
CODON_TABLE_PATH = PROJECT_DIRECTORY / "codon_tables" / "standard.json"
|
| 134 |
|
| 135 |
|
| 136 |
+
# GPU Viterbi backend parameters.
|
| 137 |
+
# Bases per segment; a batch whose transition log-odds are too large for this
|
| 138 |
+
# length to keep segment scores within int32 gets the longest length that does.
|
| 139 |
+
GPU_SEGMENT_LENGTH = 300
|
| 140 |
+
# Segments per group in stage 3 of the GPU backend; 0 takes the square root of
|
| 141 |
+
# the longest record's segment count, rounded up.
|
| 142 |
+
GPU_SEGMENT_GROUP_LENGTH = 0
|
| 143 |
+
# The device memory budget of a GPU Viterbi call and of the confidence
|
| 144 |
+
# network's pooling, as a fraction of the free device memory.
|
| 145 |
+
GPU_MEMORY_FRACTION = 0.90
|
|
|
|
| 146 |
|
| 147 |
|
| 148 |
# Gene-level results count the predicted genes whose confidence reaches this
|
annotation_pipeline/src/model_inference.py
CHANGED
|
@@ -10,17 +10,8 @@ import warnings
|
|
| 10 |
from typing import Any, Dict, IO, List, Optional, Sequence, Tuple
|
| 11 |
|
| 12 |
import numpy as np
|
| 13 |
-
import
|
| 14 |
-
|
| 15 |
-
try:
|
| 16 |
-
import pyarrow as pa
|
| 17 |
-
import pyarrow.parquet as pq
|
| 18 |
-
|
| 19 |
-
HAS_PYARROW = True
|
| 20 |
-
except ImportError:
|
| 21 |
-
pa = None
|
| 22 |
-
pq = None
|
| 23 |
-
HAS_PYARROW = False
|
| 24 |
import torch
|
| 25 |
import torch.multiprocessing as mp
|
| 26 |
from tqdm import tqdm
|
|
@@ -36,6 +27,8 @@ from constants import (
|
|
| 36 |
HEAD_NAMES,
|
| 37 |
MODEL_NAME,
|
| 38 |
OVERLAP_LENGTH,
|
|
|
|
|
|
|
| 39 |
)
|
| 40 |
|
| 41 |
FASTA_SUFFIXES = (".fasta", ".fa", ".fna", ".ffn", ".faa", ".fas")
|
|
@@ -44,7 +37,7 @@ GENBANK_SUFFIXES = (".gb", ".gbk", ".gbff")
|
|
| 44 |
|
| 45 |
def parse_arguments() -> argparse.Namespace:
|
| 46 |
parser = argparse.ArgumentParser(
|
| 47 |
-
description="Pure model inference for CDS annotation. Outputs raw softmax probabilities to
|
| 48 |
)
|
| 49 |
|
| 50 |
parser.add_argument(
|
|
@@ -124,7 +117,18 @@ def parse_arguments() -> argparse.Namespace:
|
|
| 124 |
type=str,
|
| 125 |
choices=["float16", "float32"],
|
| 126 |
default="float16",
|
| 127 |
-
help="Data type for saved CDS probabilities
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
)
|
| 129 |
parser.add_argument(
|
| 130 |
"--save_non_coding_prob",
|
|
@@ -248,79 +252,116 @@ def get_record_name(header: str) -> str:
|
|
| 248 |
return text.split()[0] if text else "record"
|
| 249 |
|
| 250 |
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
|
| 261 |
-
def
|
| 262 |
records: Sequence[Tuple[str, str]],
|
| 263 |
probs_per_head: Sequence[Sequence[np.ndarray]],
|
| 264 |
head_names: Sequence[str],
|
| 265 |
output_path: str,
|
| 266 |
prob_dtype: str,
|
| 267 |
save_non_coding_prob: bool,
|
|
|
|
| 268 |
) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
if not probs_per_head:
|
| 270 |
raise ValueError("No probabilities to write.")
|
| 271 |
|
| 272 |
os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
|
| 273 |
np_dtype = np.float16 if prob_dtype == "float16" else np.float32
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
)
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
]
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
else:
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
for h, head_name in enumerate(head_names):
|
| 312 |
-
row[f"pred_prob_{head_name}_cds"] = np.asarray(
|
| 313 |
-
probs_per_head[h][i], dtype=np_dtype
|
| 314 |
-
).tolist()
|
| 315 |
-
if save_non_coding_prob:
|
| 316 |
-
row[f"pred_prob_{head_name}_non_coding"] = np.asarray(
|
| 317 |
-
1.0 - probs_per_head[h][i], dtype=np_dtype
|
| 318 |
-
).tolist()
|
| 319 |
-
data.append(row)
|
| 320 |
-
df = pd.DataFrame(data)
|
| 321 |
-
df.to_parquet(output_path, index=False)
|
| 322 |
-
|
| 323 |
-
print(f"✅ Raw probability parquet written to {output_path}")
|
| 324 |
|
| 325 |
|
| 326 |
def select_inference_devices(
|
|
@@ -999,13 +1040,13 @@ def read_input_records(
|
|
| 999 |
return records
|
| 1000 |
|
| 1001 |
|
| 1002 |
-
def
|
| 1003 |
-
output_dir: str, input_path: str, run_timestamp: str
|
| 1004 |
) -> str:
|
| 1005 |
input_filename = strip_gzip_suffix(os.path.basename(input_path))
|
| 1006 |
base_input_name = os.path.splitext(input_filename)[0]
|
| 1007 |
return os.path.join(
|
| 1008 |
-
output_dir, f"{base_input_name}_{run_timestamp}.raw_probs.
|
| 1009 |
)
|
| 1010 |
|
| 1011 |
|
|
@@ -1068,6 +1109,8 @@ def main() -> None:
|
|
| 1068 |
if not records:
|
| 1069 |
print("⚠️ No sequences found, skipping.")
|
| 1070 |
continue
|
|
|
|
|
|
|
| 1071 |
|
| 1072 |
probs_per_head = infer_records(
|
| 1073 |
records=records,
|
|
@@ -1088,16 +1131,17 @@ def main() -> None:
|
|
| 1088 |
if len(probs_per_head) == 2
|
| 1089 |
else [f"head_{i}" for i in range(len(probs_per_head))]
|
| 1090 |
)
|
| 1091 |
-
|
| 1092 |
-
args.output_path, input_path, run_timestamp
|
| 1093 |
)
|
| 1094 |
-
|
| 1095 |
records=records,
|
| 1096 |
probs_per_head=probs_per_head,
|
| 1097 |
head_names=head_names,
|
| 1098 |
-
output_path=
|
| 1099 |
prob_dtype=args.prob_dtype,
|
| 1100 |
save_non_coding_prob=args.save_non_coding_prob,
|
|
|
|
| 1101 |
)
|
| 1102 |
except KeyboardInterrupt:
|
| 1103 |
interrupted = True
|
|
|
|
| 10 |
from typing import Any, Dict, IO, List, Optional, Sequence, Tuple
|
| 11 |
|
| 12 |
import numpy as np
|
| 13 |
+
import pyarrow as pa
|
| 14 |
+
import pyarrow.parquet as pq
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
import torch
|
| 16 |
import torch.multiprocessing as mp
|
| 17 |
from tqdm import tqdm
|
|
|
|
| 27 |
HEAD_NAMES,
|
| 28 |
MODEL_NAME,
|
| 29 |
OVERLAP_LENGTH,
|
| 30 |
+
RECORD_ID_COLUMN,
|
| 31 |
+
SEQUENCE_COLUMN,
|
| 32 |
)
|
| 33 |
|
| 34 |
FASTA_SUFFIXES = (".fasta", ".fa", ".fna", ".ffn", ".faa", ".fas")
|
|
|
|
| 37 |
|
| 38 |
def parse_arguments() -> argparse.Namespace:
|
| 39 |
parser = argparse.ArgumentParser(
|
| 40 |
+
description="Pure model inference for CDS annotation. Outputs raw softmax probabilities to an Arrow IPC or Parquet file.",
|
| 41 |
)
|
| 42 |
|
| 43 |
parser.add_argument(
|
|
|
|
| 117 |
type=str,
|
| 118 |
choices=["float16", "float32"],
|
| 119 |
default="float16",
|
| 120 |
+
help="Data type for saved CDS probabilities",
|
| 121 |
+
)
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
"--raw_probs_format",
|
| 124 |
+
type=str,
|
| 125 |
+
choices=["arrow", "parquet"],
|
| 126 |
+
default="arrow",
|
| 127 |
+
help=(
|
| 128 |
+
"File format of the raw probabilities: arrow (Arrow IPC, *.raw_probs.arrow) or parquet "
|
| 129 |
+
"(*.raw_probs.parquet; records of at most 1,000,000,000 bases, 500,000,000 with "
|
| 130 |
+
"--prob_dtype float32)"
|
| 131 |
+
),
|
| 132 |
)
|
| 133 |
parser.add_argument(
|
| 134 |
"--save_non_coding_prob",
|
|
|
|
| 252 |
return text.split()[0] if text else "record"
|
| 253 |
|
| 254 |
|
| 255 |
+
# Consecutive records share a record batch of an Arrow IPC raw-probability
|
| 256 |
+
# file, or a row group of a Parquet one, up to this many bases; a longer
|
| 257 |
+
# record forms one of its own.
|
| 258 |
+
RAW_PROBS_BATCH_BASES = 1 << 20
|
| 259 |
+
|
| 260 |
+
# Parquet keeps the probabilities of a record in one data page (pyarrow 23 and
|
| 261 |
+
# later), and a data page holds less than 2 GiB: a float16 probability takes
|
| 262 |
+
# at most about 2 bytes there and a float32 one about 4, so these limits keep
|
| 263 |
+
# the page below 2 GiB. Longer records are refused before inference; the Arrow
|
| 264 |
+
# IPC format has no such limit.
|
| 265 |
+
PARQUET_MAX_RECORD_BASES = {"float16": 1_000_000_000, "float32": 500_000_000}
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def check_parquet_record_lengths(records: Sequence[Tuple[str, str]], prob_dtype: str) -> None:
|
| 269 |
+
"""Raise ValueError for the first record too long for a Parquet raw-probability file."""
|
| 270 |
+
max_bases = PARQUET_MAX_RECORD_BASES[prob_dtype]
|
| 271 |
+
for header, sequence in records:
|
| 272 |
+
if len(sequence) > max_bases:
|
| 273 |
+
raise ValueError(
|
| 274 |
+
f"record {get_record_name(header)!r} has {len(sequence):,} bases; a Parquet "
|
| 275 |
+
f"raw-probability file holds records of at most {max_bases:,} bases with "
|
| 276 |
+
f"--prob_dtype {prob_dtype}. Use --raw_probs_format arrow."
|
| 277 |
+
)
|
| 278 |
|
| 279 |
|
| 280 |
+
def write_raw_probs(
|
| 281 |
records: Sequence[Tuple[str, str]],
|
| 282 |
probs_per_head: Sequence[Sequence[np.ndarray]],
|
| 283 |
head_names: Sequence[str],
|
| 284 |
output_path: str,
|
| 285 |
prob_dtype: str,
|
| 286 |
save_non_coding_prob: bool,
|
| 287 |
+
raw_probs_format: str,
|
| 288 |
) -> None:
|
| 289 |
+
"""Write every record and its probabilities to a zstd-compressed raw-probability file.
|
| 290 |
+
|
| 291 |
+
The file holds one row per record: the record name, the sequence and, for
|
| 292 |
+
every head, ``pred_prob_<head>_cds`` (with ``save_non_coding_prob`` also
|
| 293 |
+
``pred_prob_<head>_non_coding``) as a list of ``prob_dtype`` values, one
|
| 294 |
+
per base. ``raw_probs_format`` selects the file: ``arrow``, an Arrow IPC
|
| 295 |
+
file with large strings and lists, whose 64-bit offsets let a record
|
| 296 |
+
exceed 2**31 bases; or ``parquet``, a Parquet file with strings and lists,
|
| 297 |
+
for records of at most PARQUET_MAX_RECORD_BASES bases.
|
| 298 |
+
"""
|
| 299 |
if not probs_per_head:
|
| 300 |
raise ValueError("No probabilities to write.")
|
| 301 |
|
| 302 |
os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
|
| 303 |
np_dtype = np.float16 if prob_dtype == "float16" else np.float32
|
| 304 |
+
value_type = pa.float16() if prob_dtype == "float16" else pa.float32()
|
| 305 |
+
large_types = raw_probs_format == "arrow"
|
| 306 |
+
string_type = pa.large_string() if large_types else pa.string()
|
| 307 |
+
list_type = pa.large_list(value_type) if large_types else pa.list_(value_type)
|
| 308 |
+
offset_type = pa.int64() if large_types else pa.int32()
|
| 309 |
+
list_array_type = pa.LargeListArray if large_types else pa.ListArray
|
| 310 |
+
# (column name, head index, whether the column holds P(non-coding))
|
| 311 |
+
probability_columns: List[Tuple[str, int, bool]] = []
|
| 312 |
+
for h, head_name in enumerate(head_names):
|
| 313 |
+
probability_columns.append((f"pred_prob_{head_name}_cds", h, False))
|
| 314 |
+
if save_non_coding_prob:
|
| 315 |
+
probability_columns.append((f"pred_prob_{head_name}_non_coding", h, True))
|
| 316 |
+
schema = pa.schema(
|
| 317 |
+
[(RECORD_ID_COLUMN, string_type), (SEQUENCE_COLUMN, string_type)]
|
| 318 |
+
+ [(name, list_type) for name, _, _ in probability_columns]
|
| 319 |
+
)
|
| 320 |
|
| 321 |
+
def probability_array(h: int, non_coding: bool, start: int, stop: int) -> pa.Array:
|
| 322 |
+
"""Return the probabilities of records start to stop - 1 as one list array."""
|
| 323 |
+
arrays = [np.asarray(arr, dtype=np_dtype) for arr in probs_per_head[h][start:stop]]
|
| 324 |
+
if non_coding:
|
| 325 |
+
arrays = [np.asarray(1.0 - arr, dtype=np_dtype) for arr in arrays]
|
| 326 |
+
offsets = np.zeros(len(arrays) + 1, dtype=np.int64)
|
| 327 |
+
np.cumsum([len(arr) for arr in arrays], out=offsets[1:])
|
| 328 |
+
values = arrays[0] if len(arrays) == 1 else np.concatenate(arrays)
|
| 329 |
+
return list_array_type.from_arrays(
|
| 330 |
+
pa.array(offsets, type=offset_type), pa.array(values, type=value_type)
|
| 331 |
+
)
|
| 332 |
|
| 333 |
+
def record_batches():
|
| 334 |
+
"""Yield record batches of whole records, at most RAW_PROBS_BATCH_BASES bases unless one record is longer."""
|
| 335 |
+
start = 0
|
| 336 |
+
while start < len(records):
|
| 337 |
+
stop, batch_bases = start + 1, len(records[start][1])
|
| 338 |
+
while stop < len(records) and batch_bases + len(records[stop][1]) <= RAW_PROBS_BATCH_BASES:
|
| 339 |
+
batch_bases += len(records[stop][1])
|
| 340 |
+
stop += 1
|
| 341 |
+
batch_records = records[start:stop]
|
| 342 |
+
yield pa.record_batch(
|
| 343 |
+
[
|
| 344 |
+
pa.array([get_record_name(header) for header, _ in batch_records], type=string_type),
|
| 345 |
+
pa.array([sequence for _, sequence in batch_records], type=string_type),
|
| 346 |
]
|
| 347 |
+
+ [probability_array(h, non_coding, start, stop) for _, h, non_coding in probability_columns],
|
| 348 |
+
schema=schema,
|
| 349 |
+
)
|
| 350 |
+
start = stop
|
| 351 |
+
|
| 352 |
+
if raw_probs_format == "arrow":
|
| 353 |
+
# The IPC format needs 64-bit lengths for arrays of 2**31 or more values.
|
| 354 |
+
options = pa.ipc.IpcWriteOptions(compression="zstd", allow_64bit=True)
|
| 355 |
+
with pa.ipc.new_file(output_path, schema, options=options) as writer:
|
| 356 |
+
for batch in record_batches():
|
| 357 |
+
writer.write_batch(batch)
|
| 358 |
else:
|
| 359 |
+
# Every record batch becomes one row group.
|
| 360 |
+
with pq.ParquetWriter(output_path, schema, compression="zstd") as writer:
|
| 361 |
+
for batch in record_batches():
|
| 362 |
+
writer.write_batch(batch)
|
| 363 |
+
|
| 364 |
+
print(f"✅ Raw probabilities written to {output_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
|
| 366 |
|
| 367 |
def select_inference_devices(
|
|
|
|
| 1040 |
return records
|
| 1041 |
|
| 1042 |
|
| 1043 |
+
def make_raw_probs_path(
|
| 1044 |
+
output_dir: str, input_path: str, run_timestamp: str, raw_probs_format: str
|
| 1045 |
) -> str:
|
| 1046 |
input_filename = strip_gzip_suffix(os.path.basename(input_path))
|
| 1047 |
base_input_name = os.path.splitext(input_filename)[0]
|
| 1048 |
return os.path.join(
|
| 1049 |
+
output_dir, f"{base_input_name}_{run_timestamp}.raw_probs.{raw_probs_format}"
|
| 1050 |
)
|
| 1051 |
|
| 1052 |
|
|
|
|
| 1109 |
if not records:
|
| 1110 |
print("⚠️ No sequences found, skipping.")
|
| 1111 |
continue
|
| 1112 |
+
if args.raw_probs_format == "parquet":
|
| 1113 |
+
check_parquet_record_lengths(records, args.prob_dtype)
|
| 1114 |
|
| 1115 |
probs_per_head = infer_records(
|
| 1116 |
records=records,
|
|
|
|
| 1131 |
if len(probs_per_head) == 2
|
| 1132 |
else [f"head_{i}" for i in range(len(probs_per_head))]
|
| 1133 |
)
|
| 1134 |
+
raw_probs_path = make_raw_probs_path(
|
| 1135 |
+
args.output_path, input_path, run_timestamp, args.raw_probs_format
|
| 1136 |
)
|
| 1137 |
+
write_raw_probs(
|
| 1138 |
records=records,
|
| 1139 |
probs_per_head=probs_per_head,
|
| 1140 |
head_names=head_names,
|
| 1141 |
+
output_path=raw_probs_path,
|
| 1142 |
prob_dtype=args.prob_dtype,
|
| 1143 |
save_non_coding_prob=args.save_non_coding_prob,
|
| 1144 |
+
raw_probs_format=args.raw_probs_format,
|
| 1145 |
)
|
| 1146 |
except KeyboardInterrupt:
|
| 1147 |
interrupted = True
|
annotation_pipeline/src/post_processing.py
CHANGED
|
@@ -68,6 +68,7 @@ from constants import (
|
|
| 68 |
MIN_RECORD_LENGTH_BP,
|
| 69 |
NEGATIVE_STRAND_PROBABILITY_COLUMN,
|
| 70 |
PARQUET_BATCH_ROWS,
|
|
|
|
| 71 |
POSITIVE_STRAND_PROBABILITY_COLUMN,
|
| 72 |
RECORD_ID_COLUMN,
|
| 73 |
SEQUENCE_COLUMN,
|
|
@@ -77,7 +78,7 @@ from constants import (
|
|
| 77 |
)
|
| 78 |
from utils import (
|
| 79 |
load_codon_table, stop_codons_from_table,
|
| 80 |
-
|
| 81 |
validate_max_boundary_intron_length,
|
| 82 |
encode_both_strands,
|
| 83 |
assemble_gene_model,
|
|
@@ -89,40 +90,82 @@ from transition_network import load_transition_network
|
|
| 89 |
from viterbi import choose_viterbi_backend, decode_paths, iter_gene_exons_with_states
|
| 90 |
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
def default_output_prefix(input_path):
|
| 93 |
-
"""Return the default output prefix for one raw-probability
|
| 94 |
-
|
| 95 |
-
|
|
|
|
| 96 |
return os.path.splitext(input_path)[0] + ".predicted"
|
| 97 |
|
| 98 |
|
| 99 |
-
def
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
"""
|
| 112 |
-
required_columns = [record_id_col, sequence_col, positive_col, negative_col]
|
| 113 |
tracks = []
|
| 114 |
track_contexts = []
|
| 115 |
chunk_bp = 0
|
| 116 |
|
| 117 |
-
for batch in
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
record_ids = columns_by_name[record_id_col]
|
| 123 |
-
sequences = columns_by_name[sequence_col]
|
| 124 |
-
positive_probabilities = columns_by_name[positive_col]
|
| 125 |
-
negative_probabilities = columns_by_name[negative_col]
|
| 126 |
|
| 127 |
for row_index in range(batch.num_rows):
|
| 128 |
sequence = sequences[row_index].as_py().upper()
|
|
@@ -133,8 +176,8 @@ def iter_probability_chunks(
|
|
| 133 |
filter_stats["record_count"] += 1
|
| 134 |
filter_stats["bp"] += record_length
|
| 135 |
continue
|
| 136 |
-
positive =
|
| 137 |
-
negative =
|
| 138 |
if len(positive) < record_length or len(negative) < record_length:
|
| 139 |
raise ValueError(
|
| 140 |
f"record {record_id!r} has {record_length} bases but "
|
|
@@ -144,27 +187,44 @@ def iter_probability_chunks(
|
|
| 144 |
positive = positive[:record_length]
|
| 145 |
negative = negative[:record_length]
|
| 146 |
forward_bases, reverse_bases = encode_both_strands(sequence)
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
if tracks:
|
| 160 |
yield tracks, track_contexts, chunk_bp
|
| 161 |
|
| 162 |
|
| 163 |
def iter_prefetched_chunks(chunks):
|
| 164 |
-
"""Prepare
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
| 168 |
"""
|
| 169 |
chunk_iterator = iter(chunks)
|
| 170 |
with ThreadPoolExecutor(max_workers=1) as executor:
|
|
@@ -178,19 +238,26 @@ def iter_prefetched_chunks(chunks):
|
|
| 178 |
|
| 179 |
|
| 180 |
def decode_chunk_genes(
|
| 181 |
-
tracks, track_contexts,
|
| 182 |
max_boundary_intron_length, min_cds_length, confidence_network,
|
| 183 |
):
|
| 184 |
-
"""
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
|
|
|
| 189 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
stage_started = time.perf_counter()
|
| 191 |
state_paths = decode_paths(
|
| 192 |
tracks,
|
| 193 |
-
|
| 194 |
viterbi_backend,
|
| 195 |
stop_taa="TAA" in stop_codons,
|
| 196 |
stop_tag="TAG" in stop_codons,
|
|
@@ -198,6 +265,7 @@ def decode_chunk_genes(
|
|
| 198 |
max_boundary_intron_length=max_boundary_intron_length,
|
| 199 |
)
|
| 200 |
viterbi_seconds = time.perf_counter() - stage_started
|
|
|
|
| 201 |
if len(state_paths) != len(track_contexts):
|
| 202 |
raise RuntimeError(
|
| 203 |
f"{viterbi_backend} Viterbi backend returned {len(state_paths)} paths "
|
|
@@ -234,8 +302,9 @@ def decode_chunk_genes(
|
|
| 234 |
chunk_genes.append((gene, probabilities, oriented_exons))
|
| 235 |
strand_gene_indices.append((probabilities, gene_indices))
|
| 236 |
|
| 237 |
-
#
|
| 238 |
-
# written gene gives roles to its strand; only the complete
|
|
|
|
| 239 |
stage_started = time.perf_counter()
|
| 240 |
for probabilities, gene_indices in strand_gene_indices:
|
| 241 |
scored = [
|
|
@@ -250,7 +319,7 @@ def decode_chunk_genes(
|
|
| 250 |
for position, confidence in zip(scored, confidences):
|
| 251 |
chunk_genes[gene_indices[position]][0]["confidence"] = float(confidence)
|
| 252 |
confidence_seconds = time.perf_counter() - stage_started
|
| 253 |
-
return chunk_genes, short_gene_count, viterbi_seconds, confidence_seconds
|
| 254 |
|
| 255 |
|
| 256 |
def record_codon_table_warning(output_prefix, warning, stop_codons):
|
|
@@ -295,34 +364,22 @@ def record_codon_table_warning(output_prefix, warning, stop_codons):
|
|
| 295 |
def post_process_probability_file(
|
| 296 |
input_path, output_prefix, viterbi_backend, codon_to_amino_acid,
|
| 297 |
transition_network, confidence_network,
|
| 298 |
-
max_boundary_intron_length, chunk_mbp,
|
| 299 |
min_record_length=MIN_RECORD_LENGTH_BP,
|
| 300 |
min_cds_length=MIN_CDS_LENGTH_BP,
|
| 301 |
):
|
| 302 |
-
"""Post-process one raw-probability
|
| 303 |
|
| 304 |
-
``viterbi_backend`` is the name returned by ``choose_viterbi_backend``
|
|
|
|
| 305 |
When the confidences of the complete genes contradict the codon table
|
| 306 |
(utils.codon_table_mismatch), the warning is printed and recorded in the
|
| 307 |
directory layout by ``record_codon_table_warning``.
|
| 308 |
"""
|
| 309 |
-
import pyarrow.parquet as pq
|
| 310 |
-
|
| 311 |
file_started = time.perf_counter()
|
| 312 |
stop_codons = tuple(stop_codons_from_table(codon_to_amino_acid))
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
RECORD_ID_COLUMN,
|
| 316 |
-
SEQUENCE_COLUMN,
|
| 317 |
-
POSITIVE_STRAND_PROBABILITY_COLUMN,
|
| 318 |
-
NEGATIVE_STRAND_PROBABILITY_COLUMN,
|
| 319 |
-
}
|
| 320 |
-
missing_columns = required_columns - set(parquet_file.schema_arrow.names)
|
| 321 |
-
if missing_columns:
|
| 322 |
-
raise ValueError(
|
| 323 |
-
"raw probability parquet is missing columns: "
|
| 324 |
-
+ ", ".join(sorted(missing_columns))
|
| 325 |
-
)
|
| 326 |
|
| 327 |
genes = []
|
| 328 |
short_gene_count = 0
|
|
@@ -333,27 +390,21 @@ def post_process_probability_file(
|
|
| 333 |
filter_stats = {"record_count": 0, "bp": 0}
|
| 334 |
|
| 335 |
input_chunks = iter_probability_chunks(
|
| 336 |
-
|
| 337 |
-
POSITIVE_STRAND_PROBABILITY_COLUMN, NEGATIVE_STRAND_PROBABILITY_COLUMN,
|
| 338 |
chunk_mbp * 1_000_000,
|
| 339 |
min_record_length=min_record_length,
|
| 340 |
filter_stats=filter_stats,
|
| 341 |
)
|
| 342 |
for tracks, track_contexts, chunk_bp in iter_prefetched_chunks(input_chunks):
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
]
|
| 349 |
-
transition_seconds += time.perf_counter() - stage_started
|
| 350 |
-
|
| 351 |
-
# Stages 2 and 3: the Viterbi algorithm, gene models, and their confidences.
|
| 352 |
-
chunk_genes, chunk_short_gene_count, chunk_viterbi_seconds, chunk_confidence_seconds = decode_chunk_genes(
|
| 353 |
-
tracks, track_contexts, transition_probabilities, viterbi_backend, stop_codons,
|
| 354 |
max_boundary_intron_length, min_cds_length, confidence_network,
|
| 355 |
)
|
| 356 |
short_gene_count += chunk_short_gene_count
|
|
|
|
| 357 |
viterbi_seconds += chunk_viterbi_seconds
|
| 358 |
confidence_seconds += chunk_confidence_seconds
|
| 359 |
|
|
@@ -408,7 +459,7 @@ def post_process_probability_file(
|
|
| 408 |
def parse_args():
|
| 409 |
"""Parse command-line arguments."""
|
| 410 |
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 411 |
-
parser.add_argument("--input", required=True, help="one *.raw_probs.parquet file")
|
| 412 |
parser.add_argument("--output", default=None, help="output prefix; defaults to <input>.predicted")
|
| 413 |
parser.add_argument(
|
| 414 |
"--viterbi_backend",
|
|
@@ -421,7 +472,7 @@ def parse_args():
|
|
| 421 |
default=str(CODON_TABLE_PATH),
|
| 422 |
help=(
|
| 423 |
"JSON object mapping all 64 ATCG codons to amino acids; '*' marks "
|
| 424 |
-
"
|
| 425 |
),
|
| 426 |
)
|
| 427 |
parser.add_argument(
|
|
@@ -454,8 +505,13 @@ def parse_args():
|
|
| 454 |
parser.add_argument(
|
| 455 |
"--chunk_mbp",
|
| 456 |
type=int,
|
| 457 |
-
default=
|
| 458 |
-
help=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 459 |
)
|
| 460 |
parser.add_argument(
|
| 461 |
"--min_record_length",
|
|
|
|
| 68 |
MIN_RECORD_LENGTH_BP,
|
| 69 |
NEGATIVE_STRAND_PROBABILITY_COLUMN,
|
| 70 |
PARQUET_BATCH_ROWS,
|
| 71 |
+
PARQUET_READ_BUFFER_BYTES,
|
| 72 |
POSITIVE_STRAND_PROBABILITY_COLUMN,
|
| 73 |
RECORD_ID_COLUMN,
|
| 74 |
SEQUENCE_COLUMN,
|
|
|
|
| 78 |
)
|
| 79 |
from utils import (
|
| 80 |
load_codon_table, stop_codons_from_table,
|
| 81 |
+
probability_vector_from_arrow,
|
| 82 |
validate_max_boundary_intron_length,
|
| 83 |
encode_both_strands,
|
| 84 |
assemble_gene_model,
|
|
|
|
| 90 |
from viterbi import choose_viterbi_backend, decode_paths, iter_gene_exons_with_states
|
| 91 |
|
| 92 |
|
| 93 |
+
RAW_PROBABILITY_COLUMNS = (
|
| 94 |
+
RECORD_ID_COLUMN, SEQUENCE_COLUMN,
|
| 95 |
+
POSITIVE_STRAND_PROBABILITY_COLUMN, NEGATIVE_STRAND_PROBABILITY_COLUMN,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
def default_output_prefix(input_path):
|
| 100 |
+
"""Return the default output prefix for one raw-probability file."""
|
| 101 |
+
for suffix in (".raw_probs.arrow", ".raw_probs.parquet"):
|
| 102 |
+
if input_path.endswith(suffix):
|
| 103 |
+
return input_path[:-len(suffix)] + ".predicted"
|
| 104 |
return os.path.splitext(input_path)[0] + ".predicted"
|
| 105 |
|
| 106 |
|
| 107 |
+
def read_probability_batches(input_path):
|
| 108 |
+
"""Return an iterator over the record batches of a raw-probability file.
|
| 109 |
+
|
| 110 |
+
The batches hold RAW_PROBABILITY_COLUMNS. The suffix selects the format:
|
| 111 |
+
``.arrow`` is an Arrow IPC file, as written by model inference, read one
|
| 112 |
+
record batch at a time; ``.parquet`` is a Parquet file with the same
|
| 113 |
+
columns, read PARQUET_BATCH_ROWS rows at a time.
|
| 114 |
+
"""
|
| 115 |
+
import pyarrow as pa
|
| 116 |
+
import pyarrow.parquet as pq
|
| 117 |
|
| 118 |
+
def check_columns(schema):
|
| 119 |
+
missing_columns = [column for column in RAW_PROBABILITY_COLUMNS if column not in schema.names]
|
| 120 |
+
if missing_columns:
|
| 121 |
+
raise ValueError(
|
| 122 |
+
f"raw-probability file {input_path} is missing columns: " + ", ".join(missing_columns)
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if input_path.endswith(".arrow"):
|
| 126 |
+
reader = pa.ipc.open_file(pa.memory_map(input_path))
|
| 127 |
+
check_columns(reader.schema)
|
| 128 |
+
# Whole batches are read: selecting fields while reading copies the
|
| 129 |
+
# compressed batch into memory first.
|
| 130 |
+
return (
|
| 131 |
+
reader.get_batch(index).select(list(RAW_PROBABILITY_COLUMNS))
|
| 132 |
+
for index in range(reader.num_record_batches)
|
| 133 |
+
)
|
| 134 |
+
if input_path.endswith(".parquet"):
|
| 135 |
+
# Each column chunk is read through a buffer instead of whole, so a large
|
| 136 |
+
# row group is not held in memory at once; pyarrow's pre-buffering is
|
| 137 |
+
# off, since iter_prefetched_chunks already reads ahead.
|
| 138 |
+
parquet_file = pq.ParquetFile(input_path, pre_buffer=False, buffer_size=PARQUET_READ_BUFFER_BYTES)
|
| 139 |
+
check_columns(parquet_file.schema_arrow)
|
| 140 |
+
return parquet_file.iter_batches(batch_size=PARQUET_BATCH_ROWS, columns=list(RAW_PROBABILITY_COLUMNS))
|
| 141 |
+
raise ValueError(f"raw-probability file {input_path} must end in .arrow (Arrow IPC) or .parquet")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def iter_probability_chunks(batches, max_chunk_bp, min_record_length=0, filter_stats=None):
|
| 145 |
+
"""Read and encode strand tracks in chunks of at most ``max_chunk_bp`` bases.
|
| 146 |
+
|
| 147 |
+
``batches`` are record batches of RAW_PROBABILITY_COLUMNS
|
| 148 |
+
(read_probability_batches). Each record yields two tracks in transcript
|
| 149 |
+
orientation, ``(coding probabilities, encoded bases)`` for the forward
|
| 150 |
+
strand and for the reverse complement, each with a ``(record_id,
|
| 151 |
+
sequence, strand, length)`` context. A record whose two tracks hold at
|
| 152 |
+
most ``max_chunk_bp`` bases together joins a chunk with both, which the
|
| 153 |
+
CPU backend then decodes in parallel; a longer record joins one track at a
|
| 154 |
+
time, so that its two strands need not be held at once. Tracks that
|
| 155 |
+
exceed what is left of the open chunk start the next one, so a chunk
|
| 156 |
+
holds more than ``max_chunk_bp`` bases only when it is a single longer
|
| 157 |
+
track; a track is never split. Yields ``(tracks, track_contexts,
|
| 158 |
+
chunk_bp)``.
|
| 159 |
"""
|
|
|
|
| 160 |
tracks = []
|
| 161 |
track_contexts = []
|
| 162 |
chunk_bp = 0
|
| 163 |
|
| 164 |
+
for batch in batches:
|
| 165 |
+
record_ids = batch.column(RECORD_ID_COLUMN)
|
| 166 |
+
sequences = batch.column(SEQUENCE_COLUMN)
|
| 167 |
+
positive_probabilities = batch.column(POSITIVE_STRAND_PROBABILITY_COLUMN)
|
| 168 |
+
negative_probabilities = batch.column(NEGATIVE_STRAND_PROBABILITY_COLUMN)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
for row_index in range(batch.num_rows):
|
| 171 |
sequence = sequences[row_index].as_py().upper()
|
|
|
|
| 176 |
filter_stats["record_count"] += 1
|
| 177 |
filter_stats["bp"] += record_length
|
| 178 |
continue
|
| 179 |
+
positive = probability_vector_from_arrow(positive_probabilities[row_index])
|
| 180 |
+
negative = probability_vector_from_arrow(negative_probabilities[row_index])
|
| 181 |
if len(positive) < record_length or len(negative) < record_length:
|
| 182 |
raise ValueError(
|
| 183 |
f"record {record_id!r} has {record_length} bases but "
|
|
|
|
| 187 |
positive = positive[:record_length]
|
| 188 |
negative = negative[:record_length]
|
| 189 |
forward_bases, reverse_bases = encode_both_strands(sequence)
|
| 190 |
+
strand_tracks = [
|
| 191 |
+
((positive, forward_bases), "+"),
|
| 192 |
+
((np.ascontiguousarray(negative[::-1]), reverse_bases), "-"),
|
| 193 |
+
]
|
| 194 |
+
if 2 * record_length <= max_chunk_bp:
|
| 195 |
+
units = [strand_tracks]
|
| 196 |
+
else:
|
| 197 |
+
units = [[strand_track] for strand_track in strand_tracks]
|
| 198 |
+
for unit in units:
|
| 199 |
+
unit_bp = len(unit) * record_length
|
| 200 |
+
# Tracks that do not fit in the open chunk start the next one.
|
| 201 |
+
if tracks and chunk_bp + unit_bp > max_chunk_bp:
|
| 202 |
+
yield tracks, track_contexts, chunk_bp
|
| 203 |
+
tracks = []
|
| 204 |
+
track_contexts = []
|
| 205 |
+
chunk_bp = 0
|
| 206 |
+
for track, strand in unit:
|
| 207 |
+
tracks.append(track)
|
| 208 |
+
track_contexts.append((record_id, sequence, strand, record_length))
|
| 209 |
+
chunk_bp += unit_bp
|
| 210 |
+
# A full chunk is handed over before the next record is read.
|
| 211 |
+
if chunk_bp >= max_chunk_bp:
|
| 212 |
+
yield tracks, track_contexts, chunk_bp
|
| 213 |
+
tracks = []
|
| 214 |
+
track_contexts = []
|
| 215 |
+
chunk_bp = 0
|
| 216 |
|
| 217 |
if tracks:
|
| 218 |
yield tracks, track_contexts, chunk_bp
|
| 219 |
|
| 220 |
|
| 221 |
def iter_prefetched_chunks(chunks):
|
| 222 |
+
"""Prepare the next chunk in a background thread while the caller processes the current one.
|
| 223 |
|
| 224 |
+
Reading and encoding the input overlaps the networks and the Viterbi
|
| 225 |
+
algorithm. Besides the current chunk, at most one prepared chunk is held;
|
| 226 |
+
while the last strand of a record is processed, that is the next record
|
| 227 |
+
read ahead.
|
| 228 |
"""
|
| 229 |
chunk_iterator = iter(chunks)
|
| 230 |
with ThreadPoolExecutor(max_workers=1) as executor:
|
|
|
|
| 238 |
|
| 239 |
|
| 240 |
def decode_chunk_genes(
|
| 241 |
+
tracks, track_contexts, transition_network, viterbi_backend, stop_codons,
|
| 242 |
max_boundary_intron_length, min_cds_length, confidence_network,
|
| 243 |
):
|
| 244 |
+
"""Run the three post-processing stages on one chunk under one stop-codon set.
|
| 245 |
|
| 246 |
+
The chunk's transition log-odds are released once its Viterbi paths are
|
| 247 |
+
decoded. Returns ``(chunk_genes, short_gene_count, transition_seconds,
|
| 248 |
+
viterbi_seconds, confidence_seconds)``; each entry of ``chunk_genes`` is
|
| 249 |
+
``(gene, probabilities, oriented_exons)``.
|
| 250 |
"""
|
| 251 |
+
# Stage 1: transition log-odds for every oriented track of the chunk.
|
| 252 |
+
stage_started = time.perf_counter()
|
| 253 |
+
transition_log_odds = [transition_network.inference(probabilities) for probabilities, _ in tracks]
|
| 254 |
+
transition_seconds = time.perf_counter() - stage_started
|
| 255 |
+
|
| 256 |
+
# Stage 2: the Viterbi algorithm.
|
| 257 |
stage_started = time.perf_counter()
|
| 258 |
state_paths = decode_paths(
|
| 259 |
tracks,
|
| 260 |
+
transition_log_odds,
|
| 261 |
viterbi_backend,
|
| 262 |
stop_taa="TAA" in stop_codons,
|
| 263 |
stop_tag="TAG" in stop_codons,
|
|
|
|
| 265 |
max_boundary_intron_length=max_boundary_intron_length,
|
| 266 |
)
|
| 267 |
viterbi_seconds = time.perf_counter() - stage_started
|
| 268 |
+
del transition_log_odds
|
| 269 |
if len(state_paths) != len(track_contexts):
|
| 270 |
raise RuntimeError(
|
| 271 |
f"{viterbi_backend} Viterbi backend returned {len(state_paths)} paths "
|
|
|
|
| 302 |
chunk_genes.append((gene, probabilities, oriented_exons))
|
| 303 |
strand_gene_indices.append((probabilities, gene_indices))
|
| 304 |
|
| 305 |
+
# Stage 3: the confidence of every complete gene of the chunk, strand by
|
| 306 |
+
# strand. Every written gene gives roles to its strand; only the complete
|
| 307 |
+
# ones are scored.
|
| 308 |
stage_started = time.perf_counter()
|
| 309 |
for probabilities, gene_indices in strand_gene_indices:
|
| 310 |
scored = [
|
|
|
|
| 319 |
for position, confidence in zip(scored, confidences):
|
| 320 |
chunk_genes[gene_indices[position]][0]["confidence"] = float(confidence)
|
| 321 |
confidence_seconds = time.perf_counter() - stage_started
|
| 322 |
+
return chunk_genes, short_gene_count, transition_seconds, viterbi_seconds, confidence_seconds
|
| 323 |
|
| 324 |
|
| 325 |
def record_codon_table_warning(output_prefix, warning, stop_codons):
|
|
|
|
| 364 |
def post_process_probability_file(
|
| 365 |
input_path, output_prefix, viterbi_backend, codon_to_amino_acid,
|
| 366 |
transition_network, confidence_network,
|
| 367 |
+
max_boundary_intron_length, chunk_mbp=None,
|
| 368 |
min_record_length=MIN_RECORD_LENGTH_BP,
|
| 369 |
min_cds_length=MIN_CDS_LENGTH_BP,
|
| 370 |
):
|
| 371 |
+
"""Post-process one raw-probability file into GFF3, CDS FASTA, and protein FASTA.
|
| 372 |
|
| 373 |
+
``viterbi_backend`` is the name returned by ``choose_viterbi_backend``;
|
| 374 |
+
``chunk_mbp`` defaults to the backend's chunk size (CHUNK_SIZE_MBP).
|
| 375 |
When the confidences of the complete genes contradict the codon table
|
| 376 |
(utils.codon_table_mismatch), the warning is printed and recorded in the
|
| 377 |
directory layout by ``record_codon_table_warning``.
|
| 378 |
"""
|
|
|
|
|
|
|
| 379 |
file_started = time.perf_counter()
|
| 380 |
stop_codons = tuple(stop_codons_from_table(codon_to_amino_acid))
|
| 381 |
+
if chunk_mbp is None:
|
| 382 |
+
chunk_mbp = CHUNK_SIZE_MBP[viterbi_backend]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
|
| 384 |
genes = []
|
| 385 |
short_gene_count = 0
|
|
|
|
| 390 |
filter_stats = {"record_count": 0, "bp": 0}
|
| 391 |
|
| 392 |
input_chunks = iter_probability_chunks(
|
| 393 |
+
read_probability_batches(input_path),
|
|
|
|
| 394 |
chunk_mbp * 1_000_000,
|
| 395 |
min_record_length=min_record_length,
|
| 396 |
filter_stats=filter_stats,
|
| 397 |
)
|
| 398 |
for tracks, track_contexts, chunk_bp in iter_prefetched_chunks(input_chunks):
|
| 399 |
+
(
|
| 400 |
+
chunk_genes, chunk_short_gene_count,
|
| 401 |
+
chunk_transition_seconds, chunk_viterbi_seconds, chunk_confidence_seconds,
|
| 402 |
+
) = decode_chunk_genes(
|
| 403 |
+
tracks, track_contexts, transition_network, viterbi_backend, stop_codons,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
max_boundary_intron_length, min_cds_length, confidence_network,
|
| 405 |
)
|
| 406 |
short_gene_count += chunk_short_gene_count
|
| 407 |
+
transition_seconds += chunk_transition_seconds
|
| 408 |
viterbi_seconds += chunk_viterbi_seconds
|
| 409 |
confidence_seconds += chunk_confidence_seconds
|
| 410 |
|
|
|
|
| 459 |
def parse_args():
|
| 460 |
"""Parse command-line arguments."""
|
| 461 |
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 462 |
+
parser.add_argument("--input", required=True, help="one *.raw_probs.arrow or *.raw_probs.parquet file")
|
| 463 |
parser.add_argument("--output", default=None, help="output prefix; defaults to <input>.predicted")
|
| 464 |
parser.add_argument(
|
| 465 |
"--viterbi_backend",
|
|
|
|
| 472 |
default=str(CODON_TABLE_PATH),
|
| 473 |
help=(
|
| 474 |
"JSON object mapping all 64 ATCG codons to amino acids; '*' marks "
|
| 475 |
+
"stop codons"
|
| 476 |
),
|
| 477 |
)
|
| 478 |
parser.add_argument(
|
|
|
|
| 505 |
parser.add_argument(
|
| 506 |
"--chunk_mbp",
|
| 507 |
type=int,
|
| 508 |
+
default=None,
|
| 509 |
+
help=(
|
| 510 |
+
f"host-side chunk size in megabases (default: {CHUNK_SIZE_MBP['gpu']}, or "
|
| 511 |
+
f"{CHUNK_SIZE_MBP['cpu']} with the CPU Viterbi backend, which decodes the strands "
|
| 512 |
+
"of a chunk in parallel); post-processing takes about 50 MB of memory per megabase "
|
| 513 |
+
"of its largest chunk; a strand is never split, so a longer one is a chunk of its own"
|
| 514 |
+
),
|
| 515 |
)
|
| 516 |
parser.add_argument(
|
| 517 |
"--min_record_length",
|
annotation_pipeline/src/tcn.py
CHANGED
|
@@ -87,17 +87,19 @@ def coding_log_odds(probabilities):
|
|
| 87 |
def chunked_inference(network, context_radius, tracks, device, chunk_bp=NETWORK_CHUNK_BP):
|
| 88 |
"""Run a per-base network over long tracks, one chunk at a time.
|
| 89 |
|
| 90 |
-
``tracks`` are per-base arrays of one common length in
|
| 91 |
orientation. ``network(*chunks)`` receives corresponding chunks of them as
|
| 92 |
tensors on ``device`` and returns one output row per base; each output
|
| 93 |
depends on the inputs within ``context_radius`` bases of its base. The
|
| 94 |
tracks are processed in chunks of at most ``chunk_bp`` bases, each
|
| 95 |
evaluated with ``context_radius`` extra bases on both sides, clipped to
|
| 96 |
the tracks, so the outputs equal those of one pass over the whole tracks
|
| 97 |
-
while only one chunk is ever on the device. Returns
|
| 98 |
-
``
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
| 101 |
"""
|
| 102 |
tracks = [np.asarray(track) for track in tracks]
|
| 103 |
if not tracks or any(track.ndim != 1 for track in tracks) or len({len(track) for track in tracks}) != 1:
|
|
@@ -108,20 +110,20 @@ def chunked_inference(network, context_radius, tracks, device, chunk_bp=NETWORK_
|
|
| 108 |
if chunk_bp < 1:
|
| 109 |
raise ValueError("chunk size must be positive")
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
return
|
| 125 |
|
| 126 |
|
| 127 |
def load_weights(path):
|
|
|
|
| 87 |
def chunked_inference(network, context_radius, tracks, device, chunk_bp=NETWORK_CHUNK_BP):
|
| 88 |
"""Run a per-base network over long tracks, one chunk at a time.
|
| 89 |
|
| 90 |
+
``tracks`` are per-base arrays of one common length in transcript
|
| 91 |
orientation. ``network(*chunks)`` receives corresponding chunks of them as
|
| 92 |
tensors on ``device`` and returns one output row per base; each output
|
| 93 |
depends on the inputs within ``context_radius`` bases of its base. The
|
| 94 |
tracks are processed in chunks of at most ``chunk_bp`` bases, each
|
| 95 |
evaluated with ``context_radius`` extra bases on both sides, clipped to
|
| 96 |
the tracks, so the outputs equal those of one pass over the whole tracks
|
| 97 |
+
while only one chunk is ever on the device. Returns an iterator over
|
| 98 |
+
``(start, stop, outputs)``, one per chunk in track order: ``outputs`` is
|
| 99 |
+
the float32 CPU array of the output rows of bases ``start`` to
|
| 100 |
+
``stop - 1``, and the caller keeps what it needs of it. On CUDA the
|
| 101 |
+
network runs under bfloat16 autocast, the precision used for all reported
|
| 102 |
+
results; on CPU it runs in float32.
|
| 103 |
"""
|
| 104 |
tracks = [np.asarray(track) for track in tracks]
|
| 105 |
if not tracks or any(track.ndim != 1 for track in tracks) or len({len(track) for track in tracks}) != 1:
|
|
|
|
| 110 |
if chunk_bp < 1:
|
| 111 |
raise ValueError("chunk size must be positive")
|
| 112 |
|
| 113 |
+
def chunk_outputs():
|
| 114 |
+
for start in range(0, length, chunk_bp):
|
| 115 |
+
stop = min(start + chunk_bp, length)
|
| 116 |
+
window_start = max(0, start - context_radius)
|
| 117 |
+
window_stop = min(length, stop + context_radius)
|
| 118 |
+
# Every window is copied: tracks read from a raw-probability file
|
| 119 |
+
# are read-only views of its buffers.
|
| 120 |
+
with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 121 |
+
window_outputs = network(*(
|
| 122 |
+
torch.tensor(track[window_start:window_stop], device=device) for track in tracks
|
| 123 |
+
))
|
| 124 |
+
yield start, stop, window_outputs[start - window_start:stop - window_start].float().cpu().numpy()
|
| 125 |
+
|
| 126 |
+
return chunk_outputs()
|
| 127 |
|
| 128 |
|
| 129 |
def load_weights(path):
|
annotation_pipeline/src/transition_network.py
CHANGED
|
@@ -16,9 +16,9 @@ possibilities, staying or one of the four transitions:
|
|
| 16 |
The Viterbi algorithm (viterbi.py) adds the log-probability of the
|
| 17 |
possibility it selects at every boundary to the path score. Because every path
|
| 18 |
selects exactly one per boundary, subtracting log P(stay) at each
|
| 19 |
-
boundary changes the score of every path by the same constant, so
|
| 20 |
-
|
| 21 |
-
nothing. The four log-odds are attached to the base where the new segment
|
| 22 |
begins or, for leaving a gene, to the base that closes it:
|
| 23 |
|
| 24 |
enter_gene(i) = log P(enter_gene | boundary i) - log P(stay | boundary i)
|
|
@@ -28,8 +28,9 @@ begins or, for leaving a gene, to the base that closes it:
|
|
| 28 |
|
| 29 |
Records are scored in chunks read with the network's full context on both
|
| 30 |
sides (tcn.chunked_inference), so a chromosome never has to fit in GPU memory
|
| 31 |
-
at once.
|
| 32 |
-
|
|
|
|
| 33 |
"""
|
| 34 |
|
| 35 |
import numpy as np
|
|
@@ -47,6 +48,7 @@ from constants import (
|
|
| 47 |
TRANSITION_NAMES,
|
| 48 |
)
|
| 49 |
from tcn import TCN, chunked_inference, coding_log_odds, load_weights
|
|
|
|
| 50 |
|
| 51 |
TRANSITION_NETWORK_TYPE = "transition_network"
|
| 52 |
|
|
@@ -86,24 +88,28 @@ class TransitionNetwork(nn.Module):
|
|
| 86 |
|
| 87 |
@torch.inference_mode()
|
| 88 |
def inference(self, probabilities, chunk_bp=NETWORK_CHUNK_BP):
|
| 89 |
-
"""Return the transition
|
| 90 |
-
|
| 91 |
-
The result is
|
| 92 |
-
column order, each value the transition's log-odds against staying
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
| 96 |
"""
|
| 97 |
-
probabilities = np.asarray(probabilities
|
| 98 |
if probabilities.ndim != 1 or len(probabilities) == 0:
|
| 99 |
raise ValueError("probabilities must be a nonempty vector")
|
| 100 |
|
| 101 |
def network(chunk):
|
| 102 |
return self(chunk[None, :])[0]
|
| 103 |
|
| 104 |
-
|
|
|
|
| 105 |
network, self.context_radius, (probabilities,), next(self.parameters()).device, chunk_bp,
|
| 106 |
-
)
|
|
|
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
def transition_log_odds_from_logits(transition_logits):
|
|
|
|
| 16 |
The Viterbi algorithm (viterbi.py) adds the log-probability of the
|
| 17 |
possibility it selects at every boundary to the path score. Because every path
|
| 18 |
selects exactly one per boundary, subtracting log P(stay) at each
|
| 19 |
+
boundary changes the score of every path by the same constant, so Viterbi
|
| 20 |
+
receives each transition as its log-odds relative to staying, and staying
|
| 21 |
+
costs nothing. The four log-odds are attached to the base where the new segment
|
| 22 |
begins or, for leaving a gene, to the base that closes it:
|
| 23 |
|
| 24 |
enter_gene(i) = log P(enter_gene | boundary i) - log P(stay | boundary i)
|
|
|
|
| 28 |
|
| 29 |
Records are scored in chunks read with the network's full context on both
|
| 30 |
sides (tcn.chunked_inference), so a chromosome never has to fit in GPU memory
|
| 31 |
+
at once. Every chunk of scores is converted to the Viterbi backends'
|
| 32 |
+
fixed-point units as it is computed (utils.quantize_transition_log_odds), and
|
| 33 |
+
the scores leave this module as int32 arrays.
|
| 34 |
"""
|
| 35 |
|
| 36 |
import numpy as np
|
|
|
|
| 48 |
TRANSITION_NAMES,
|
| 49 |
)
|
| 50 |
from tcn import TCN, chunked_inference, coding_log_odds, load_weights
|
| 51 |
+
from utils import quantize_transition_log_odds
|
| 52 |
|
| 53 |
TRANSITION_NETWORK_TYPE = "transition_network"
|
| 54 |
|
|
|
|
| 88 |
|
| 89 |
@torch.inference_mode()
|
| 90 |
def inference(self, probabilities, chunk_bp=NETWORK_CHUNK_BP):
|
| 91 |
+
"""Return the transition log-odds of one oriented coding-probability track.
|
| 92 |
+
|
| 93 |
+
The result is an int32 ``(bases, 4)`` array in ``TRANSITION_NAMES``
|
| 94 |
+
column order, each value the transition's log-odds against staying in
|
| 95 |
+
the Viterbi backends' fixed-point units. The track is processed in
|
| 96 |
+
``chunk_bp`` chunks with the network's full context on both sides
|
| 97 |
+
(tcn.chunked_inference), so the values equal those of scoring the
|
| 98 |
+
whole record at once; each chunk is quantized as it is computed.
|
| 99 |
"""
|
| 100 |
+
probabilities = np.asarray(probabilities)
|
| 101 |
if probabilities.ndim != 1 or len(probabilities) == 0:
|
| 102 |
raise ValueError("probabilities must be a nonempty vector")
|
| 103 |
|
| 104 |
def network(chunk):
|
| 105 |
return self(chunk[None, :])[0]
|
| 106 |
|
| 107 |
+
transition_log_odds = np.empty((len(probabilities), TRANSITION_COUNT), dtype=np.int32)
|
| 108 |
+
for start, stop, chunk_log_odds in chunked_inference(
|
| 109 |
network, self.context_radius, (probabilities,), next(self.parameters()).device, chunk_bp,
|
| 110 |
+
):
|
| 111 |
+
transition_log_odds[start:stop] = quantize_transition_log_odds(chunk_log_odds)
|
| 112 |
+
return transition_log_odds
|
| 113 |
|
| 114 |
|
| 115 |
def transition_log_odds_from_logits(transition_logits):
|
annotation_pipeline/src/utils.py
CHANGED
|
@@ -82,8 +82,21 @@ def validate_reconstruction_batch_size(value):
|
|
| 82 |
return value
|
| 83 |
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
# Codon tables are flat JSON objects: all 64 concrete codons map to one-letter
|
| 86 |
-
# amino acid symbols, and "*"
|
| 87 |
ALL_CODONS = frozenset(
|
| 88 |
first + second + third
|
| 89 |
for first in CODON_BASES
|
|
@@ -133,7 +146,7 @@ def validate_codon_table(codon_to_amino_acid):
|
|
| 133 |
)
|
| 134 |
if unsupported_stop_codons:
|
| 135 |
raise ValueError(
|
| 136 |
-
"
|
| 137 |
+ ",".join(unsupported_stop_codons)
|
| 138 |
)
|
| 139 |
|
|
@@ -198,110 +211,110 @@ def build_translation_lookup(codon_to_amino_acid):
|
|
| 198 |
return lookup
|
| 199 |
|
| 200 |
|
| 201 |
-
#
|
| 202 |
PREFIX_TYPE_COUNT = 6
|
| 203 |
STATE_COUNT = 30
|
| 204 |
|
| 205 |
# Prefix type ids carried by exon and intron states. Codon phase is the number
|
| 206 |
# of CDS bases already consumed in the current codon. Prefix types retain the
|
| 207 |
# additional bases needed to recognize a standard stop on the next emission.
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
#
|
| 216 |
-
#
|
| 217 |
INTERGENIC = 0
|
| 218 |
START_A = 1
|
| 219 |
START_AT = 2
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
STOP = 9
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
LEADING_BOUNDARY_INTRON = 28
|
| 246 |
TRAILING_BOUNDARY_INTRON = 29
|
| 247 |
|
| 248 |
EXON_STATE_BY_PREFIX_TYPE = np.array((
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
), dtype=np.int64)
|
| 256 |
|
| 257 |
GT_GC_AG_INTRON_FIRST_STATE_BY_PREFIX_TYPE = np.array((
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
), dtype=np.int64)
|
| 265 |
|
| 266 |
GT_GC_AG_INTRON_READY_STATE_BY_PREFIX_TYPE = np.array((
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
), dtype=np.int64)
|
| 274 |
|
| 275 |
AT_AC_INTRON_STATE_BY_PREFIX_TYPE = np.array((
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
), dtype=np.int64)
|
| 283 |
|
| 284 |
|
| 285 |
# Unlike codon phase above, GFF3 phase is the number of visible bases to skip at
|
| 286 |
# the beginning of a CDS feature before reaching the first complete codon. A
|
| 287 |
# boundary-truncated gene's first state retains enough information to recover it.
|
| 288 |
-
|
| 289 |
START_A: 0,
|
| 290 |
START_AT: 2,
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
STOP: 1,
|
| 298 |
}
|
| 299 |
|
| 300 |
|
| 301 |
-
def
|
| 302 |
"""Return the initial GFF3 phase encoded by the first visible CDS state."""
|
| 303 |
try:
|
| 304 |
-
return
|
| 305 |
except KeyError as exc:
|
| 306 |
raise ValueError(f"state {state} does not emit CDS") from exc
|
| 307 |
|
|
@@ -325,7 +338,7 @@ def encode_both_strands(sequence):
|
|
| 325 |
return forward_bases, reverse_bases
|
| 326 |
|
| 327 |
|
| 328 |
-
def
|
| 329 |
"""Convert one PyArrow list cell to a 1D float16 probability array."""
|
| 330 |
if not hasattr(value, "values"):
|
| 331 |
raise TypeError("probability column must contain PyArrow list values")
|
|
@@ -337,63 +350,101 @@ def probability_vector_from_parquet(value):
|
|
| 337 |
|
| 338 |
|
| 339 |
def prepare_decode_tasks(tasks):
|
| 340 |
-
"""Normalize
|
| 341 |
prepared_tasks = []
|
| 342 |
for task_index, (probabilities, encoded_bases) in enumerate(tasks):
|
| 343 |
probability_array = np.ascontiguousarray(probabilities, dtype=np.float16)
|
| 344 |
base_array = np.ascontiguousarray(encoded_bases, dtype=np.int8)
|
| 345 |
if probability_array.ndim != 1:
|
| 346 |
raise ValueError(
|
| 347 |
-
f"
|
| 348 |
f"got {probability_array.shape}"
|
| 349 |
)
|
| 350 |
if base_array.ndim != 1:
|
| 351 |
raise ValueError(
|
| 352 |
-
f"
|
| 353 |
f"got {base_array.shape}"
|
| 354 |
)
|
| 355 |
if len(probability_array) != len(base_array):
|
| 356 |
raise ValueError(
|
| 357 |
-
f"
|
| 358 |
f"probabilities but {len(base_array)} encoded bases"
|
| 359 |
)
|
| 360 |
if len(probability_array) == 0:
|
| 361 |
-
raise ValueError(f"
|
| 362 |
prepared_tasks.append((probability_array, base_array))
|
| 363 |
return prepared_tasks
|
| 364 |
|
| 365 |
|
| 366 |
-
def
|
| 367 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
The columns follow ``TRANSITION_NAMES``: enter gene, leave gene, enter
|
| 370 |
intron, leave intron. Each value is the transition network's log-odds
|
| 371 |
-
against staying
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
units as contiguous int32 arrays.
|
| 375 |
"""
|
| 376 |
-
|
| 377 |
-
if len(
|
| 378 |
raise ValueError(
|
| 379 |
-
f"{len(
|
| 380 |
-
f"{len(prepared_tasks)}
|
| 381 |
)
|
| 382 |
-
|
| 383 |
-
prepared_scores = []
|
| 384 |
for task_index, (log_odds, (probabilities, _)) in enumerate(
|
| 385 |
-
zip(
|
| 386 |
):
|
| 387 |
-
|
| 388 |
-
if
|
| 389 |
raise ValueError(
|
| 390 |
-
f"
|
| 391 |
-
f"{(len(probabilities), TRANSITION_COUNT)}, got {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
)
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
prepared_scores.append(np.ascontiguousarray(scaled, dtype=np.int32))
|
| 396 |
-
return prepared_scores
|
| 397 |
|
| 398 |
|
| 399 |
def build_cds_sequence(genome_sequence, transcript_order_exons, strand):
|
|
@@ -412,15 +463,15 @@ def build_cds_sequence(genome_sequence, transcript_order_exons, strand):
|
|
| 412 |
return reverse_complement(genomic_order_sequence)
|
| 413 |
|
| 414 |
|
| 415 |
-
def compute_gff_cds_phases(transcript_order_exons,
|
| 416 |
"""Return GFF3 phases, preserving the first visible codon's phase."""
|
| 417 |
-
if
|
| 418 |
-
raise ValueError("initial
|
| 419 |
|
| 420 |
phases = []
|
| 421 |
consumed_bases = 0
|
| 422 |
for start, end in transcript_order_exons:
|
| 423 |
-
phase = (
|
| 424 |
phases.append(phase)
|
| 425 |
consumed_bases += end - start + 1
|
| 426 |
return phases
|
|
@@ -433,7 +484,7 @@ def has_internal_stop_codon(
|
|
| 433 |
):
|
| 434 |
"""Return whether a translated CDS contains a non-terminal stop codon.
|
| 435 |
|
| 436 |
-
This is a diagnostic check: the
|
| 437 |
result false. A stop is terminal only when its third base is the final CDS
|
| 438 |
base; a stop before an incomplete trailing codon is still internal.
|
| 439 |
"""
|
|
@@ -462,7 +513,7 @@ def classify_cds_completion(
|
|
| 462 |
Reasons are comma-separated so boundary-truncated predictions can state
|
| 463 |
every visible problem inside one GFF3 attribute, for example
|
| 464 |
``no_start,no_stop``. ``short_intron``
|
| 465 |
-
records a
|
| 466 |
Start and stop presence comes from the decoded states, then the sequence
|
| 467 |
is checked as a consistency guard.
|
| 468 |
"""
|
|
@@ -636,7 +687,7 @@ def assemble_gene_model(
|
|
| 636 |
stop_codons=STOP_CODONS,
|
| 637 |
):
|
| 638 |
"""Build one output gene from its exons and boundary CDS states."""
|
| 639 |
-
|
| 640 |
if strand == "+":
|
| 641 |
transcript_order_exons = [
|
| 642 |
(int(start), int(end)) for start, end in oriented_exons
|
|
@@ -653,7 +704,7 @@ def assemble_gene_model(
|
|
| 653 |
|
| 654 |
transcript_order_phases = compute_gff_cds_phases(
|
| 655 |
transcript_order_exons,
|
| 656 |
-
|
| 657 |
)
|
| 658 |
genomic_order = sorted(
|
| 659 |
zip(transcript_order_exons, transcript_order_phases),
|
|
@@ -662,12 +713,12 @@ def assemble_gene_model(
|
|
| 662 |
|
| 663 |
assert not has_internal_stop_codon(
|
| 664 |
cds_sequence,
|
| 665 |
-
|
| 666 |
stop_codons,
|
| 667 |
), (
|
| 668 |
-
"
|
| 669 |
f"record_id={record_id!r}, strand={strand}, "
|
| 670 |
-
f"phase={
|
| 671 |
)
|
| 672 |
complete, incomplete_reason = classify_cds_completion(
|
| 673 |
cds_sequence,
|
|
@@ -680,7 +731,7 @@ def assemble_gene_model(
|
|
| 680 |
"record_id": record_id,
|
| 681 |
"strand": strand,
|
| 682 |
"cds": cds_sequence,
|
| 683 |
-
"translation_frame":
|
| 684 |
"complete": complete,
|
| 685 |
"incomplete_reason": incomplete_reason,
|
| 686 |
"exons": [exon for exon, phase in genomic_order],
|
|
|
|
| 82 |
return value
|
| 83 |
|
| 84 |
|
| 85 |
+
def validate_memory_budget_bytes(value):
|
| 86 |
+
"""Return a device memory budget in bytes, or ``None`` for the default."""
|
| 87 |
+
if value is None:
|
| 88 |
+
return None
|
| 89 |
+
try:
|
| 90 |
+
value = operator.index(value)
|
| 91 |
+
except TypeError as exc:
|
| 92 |
+
raise TypeError("memory_budget_bytes must be an integer or None") from exc
|
| 93 |
+
if value <= 0:
|
| 94 |
+
raise ValueError("memory_budget_bytes must be positive or None")
|
| 95 |
+
return value
|
| 96 |
+
|
| 97 |
+
|
| 98 |
# Codon tables are flat JSON objects: all 64 concrete codons map to one-letter
|
| 99 |
+
# amino acid symbols, and "*" marks the stop codons Viterbi recognizes.
|
| 100 |
ALL_CODONS = frozenset(
|
| 101 |
first + second + third
|
| 102 |
for first in CODON_BASES
|
|
|
|
| 146 |
)
|
| 147 |
if unsupported_stop_codons:
|
| 148 |
raise ValueError(
|
| 149 |
+
"codon table stop codons must be a subset of TAA,TAG,TGA: "
|
| 150 |
+ ",".join(unsupported_stop_codons)
|
| 151 |
)
|
| 152 |
|
|
|
|
| 211 |
return lookup
|
| 212 |
|
| 213 |
|
| 214 |
+
# The Viterbi states (State design in viterbi.py).
|
| 215 |
PREFIX_TYPE_COUNT = 6
|
| 216 |
STATE_COUNT = 30
|
| 217 |
|
| 218 |
# Prefix type ids carried by exon and intron states. Codon phase is the number
|
| 219 |
# of CDS bases already consumed in the current codon. Prefix types retain the
|
| 220 |
# additional bases needed to recognize a standard stop on the next emission.
|
| 221 |
+
PHASE0 = 0 # codon phase 0; codon boundary, no open prefix
|
| 222 |
+
PHASE1_PREFIX_T = 1 # codon phase 1; one-base prefix T
|
| 223 |
+
PHASE1_PREFIX_OTHER = 2 # codon phase 1; one-base prefix other
|
| 224 |
+
PHASE2_PREFIX_TA = 3 # codon phase 2; prefix TA, so A/G completes TAA/TAG
|
| 225 |
+
PHASE2_PREFIX_TG = 4 # codon phase 2; prefix TG, so A completes TGA
|
| 226 |
+
PHASE2_PREFIX_OTHER = 5 # codon phase 2; other prefix, so no stop can be completed
|
| 227 |
+
|
| 228 |
+
# State ids, grouped by biological role. The tables below map each prefix type
|
| 229 |
+
# to its exon and intron states.
|
| 230 |
INTERGENIC = 0
|
| 231 |
START_A = 1
|
| 232 |
START_AT = 2
|
| 233 |
+
EXON_PHASE0 = 3
|
| 234 |
+
EXON_PHASE1_PREFIX_T = 4
|
| 235 |
+
EXON_PHASE1_PREFIX_OTHER = 5
|
| 236 |
+
EXON_PHASE2_PREFIX_TA = 6
|
| 237 |
+
EXON_PHASE2_PREFIX_TG = 7
|
| 238 |
+
EXON_PHASE2_PREFIX_OTHER = 8
|
| 239 |
STOP = 9
|
| 240 |
+
GT_GC_AG_INTRON_FIRST_PHASE0 = 10
|
| 241 |
+
GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_T = 11
|
| 242 |
+
GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_OTHER = 12
|
| 243 |
+
GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TA = 13
|
| 244 |
+
GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TG = 14
|
| 245 |
+
GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_OTHER = 15
|
| 246 |
+
GT_GC_AG_INTRON_READY_PHASE0 = 16
|
| 247 |
+
GT_GC_AG_INTRON_READY_PHASE1_PREFIX_T = 17
|
| 248 |
+
GT_GC_AG_INTRON_READY_PHASE1_PREFIX_OTHER = 18
|
| 249 |
+
GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TA = 19
|
| 250 |
+
GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TG = 20
|
| 251 |
+
GT_GC_AG_INTRON_READY_PHASE2_PREFIX_OTHER = 21
|
| 252 |
+
AT_AC_INTRON_PHASE0 = 22
|
| 253 |
+
AT_AC_INTRON_PHASE1_PREFIX_T = 23
|
| 254 |
+
AT_AC_INTRON_PHASE1_PREFIX_OTHER = 24
|
| 255 |
+
AT_AC_INTRON_PHASE2_PREFIX_TA = 25
|
| 256 |
+
AT_AC_INTRON_PHASE2_PREFIX_TG = 26
|
| 257 |
+
AT_AC_INTRON_PHASE2_PREFIX_OTHER = 27
|
| 258 |
LEADING_BOUNDARY_INTRON = 28
|
| 259 |
TRAILING_BOUNDARY_INTRON = 29
|
| 260 |
|
| 261 |
EXON_STATE_BY_PREFIX_TYPE = np.array((
|
| 262 |
+
EXON_PHASE0,
|
| 263 |
+
EXON_PHASE1_PREFIX_T,
|
| 264 |
+
EXON_PHASE1_PREFIX_OTHER,
|
| 265 |
+
EXON_PHASE2_PREFIX_TA,
|
| 266 |
+
EXON_PHASE2_PREFIX_TG,
|
| 267 |
+
EXON_PHASE2_PREFIX_OTHER,
|
| 268 |
), dtype=np.int64)
|
| 269 |
|
| 270 |
GT_GC_AG_INTRON_FIRST_STATE_BY_PREFIX_TYPE = np.array((
|
| 271 |
+
GT_GC_AG_INTRON_FIRST_PHASE0,
|
| 272 |
+
GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_T,
|
| 273 |
+
GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_OTHER,
|
| 274 |
+
GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TA,
|
| 275 |
+
GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TG,
|
| 276 |
+
GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_OTHER,
|
| 277 |
), dtype=np.int64)
|
| 278 |
|
| 279 |
GT_GC_AG_INTRON_READY_STATE_BY_PREFIX_TYPE = np.array((
|
| 280 |
+
GT_GC_AG_INTRON_READY_PHASE0,
|
| 281 |
+
GT_GC_AG_INTRON_READY_PHASE1_PREFIX_T,
|
| 282 |
+
GT_GC_AG_INTRON_READY_PHASE1_PREFIX_OTHER,
|
| 283 |
+
GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TA,
|
| 284 |
+
GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TG,
|
| 285 |
+
GT_GC_AG_INTRON_READY_PHASE2_PREFIX_OTHER,
|
| 286 |
), dtype=np.int64)
|
| 287 |
|
| 288 |
AT_AC_INTRON_STATE_BY_PREFIX_TYPE = np.array((
|
| 289 |
+
AT_AC_INTRON_PHASE0,
|
| 290 |
+
AT_AC_INTRON_PHASE1_PREFIX_T,
|
| 291 |
+
AT_AC_INTRON_PHASE1_PREFIX_OTHER,
|
| 292 |
+
AT_AC_INTRON_PHASE2_PREFIX_TA,
|
| 293 |
+
AT_AC_INTRON_PHASE2_PREFIX_TG,
|
| 294 |
+
AT_AC_INTRON_PHASE2_PREFIX_OTHER,
|
| 295 |
), dtype=np.int64)
|
| 296 |
|
| 297 |
|
| 298 |
# Unlike codon phase above, GFF3 phase is the number of visible bases to skip at
|
| 299 |
# the beginning of a CDS feature before reaching the first complete codon. A
|
| 300 |
# boundary-truncated gene's first state retains enough information to recover it.
|
| 301 |
+
INITIAL_GFF3_PHASE_BY_STATE = {
|
| 302 |
START_A: 0,
|
| 303 |
START_AT: 2,
|
| 304 |
+
EXON_PHASE0: 1,
|
| 305 |
+
EXON_PHASE1_PREFIX_T: 0,
|
| 306 |
+
EXON_PHASE1_PREFIX_OTHER: 0,
|
| 307 |
+
EXON_PHASE2_PREFIX_TA: 2,
|
| 308 |
+
EXON_PHASE2_PREFIX_TG: 2,
|
| 309 |
+
EXON_PHASE2_PREFIX_OTHER: 2,
|
| 310 |
STOP: 1,
|
| 311 |
}
|
| 312 |
|
| 313 |
|
| 314 |
+
def initial_gff3_phase_from_state(state):
|
| 315 |
"""Return the initial GFF3 phase encoded by the first visible CDS state."""
|
| 316 |
try:
|
| 317 |
+
return INITIAL_GFF3_PHASE_BY_STATE[int(state)]
|
| 318 |
except KeyError as exc:
|
| 319 |
raise ValueError(f"state {state} does not emit CDS") from exc
|
| 320 |
|
|
|
|
| 338 |
return forward_bases, reverse_bases
|
| 339 |
|
| 340 |
|
| 341 |
+
def probability_vector_from_arrow(value):
|
| 342 |
"""Convert one PyArrow list cell to a 1D float16 probability array."""
|
| 343 |
if not hasattr(value, "values"):
|
| 344 |
raise TypeError("probability column must contain PyArrow list values")
|
|
|
|
| 350 |
|
| 351 |
|
| 352 |
def prepare_decode_tasks(tasks):
|
| 353 |
+
"""Normalize Viterbi tasks and reject invalid shapes or lengths."""
|
| 354 |
prepared_tasks = []
|
| 355 |
for task_index, (probabilities, encoded_bases) in enumerate(tasks):
|
| 356 |
probability_array = np.ascontiguousarray(probabilities, dtype=np.float16)
|
| 357 |
base_array = np.ascontiguousarray(encoded_bases, dtype=np.int8)
|
| 358 |
if probability_array.ndim != 1:
|
| 359 |
raise ValueError(
|
| 360 |
+
f"Viterbi task {task_index} probabilities must be 1D, "
|
| 361 |
f"got {probability_array.shape}"
|
| 362 |
)
|
| 363 |
if base_array.ndim != 1:
|
| 364 |
raise ValueError(
|
| 365 |
+
f"Viterbi task {task_index} encoded bases must be 1D, "
|
| 366 |
f"got {base_array.shape}"
|
| 367 |
)
|
| 368 |
if len(probability_array) != len(base_array):
|
| 369 |
raise ValueError(
|
| 370 |
+
f"Viterbi task {task_index} has {len(probability_array)} "
|
| 371 |
f"probabilities but {len(base_array)} encoded bases"
|
| 372 |
)
|
| 373 |
if len(probability_array) == 0:
|
| 374 |
+
raise ValueError(f"Viterbi task {task_index} is empty")
|
| 375 |
prepared_tasks.append((probability_array, base_array))
|
| 376 |
return prepared_tasks
|
| 377 |
|
| 378 |
|
| 379 |
+
def pack_decode_tasks(prepared_tasks, prepared_transition_log_odds):
|
| 380 |
+
"""Return prepared Viterbi tasks as one batch for a native backend.
|
| 381 |
+
|
| 382 |
+
The batch is the P(CDS) bits (uint16), the encoded bases, the int32
|
| 383 |
+
transition scores, and the record offsets, one more than the tasks. A
|
| 384 |
+
single task is passed on without a copy.
|
| 385 |
+
"""
|
| 386 |
+
record_offsets = np.zeros(len(prepared_tasks) + 1, np.int64)
|
| 387 |
+
np.cumsum([len(encoded_bases) for _, encoded_bases in prepared_tasks], out=record_offsets[1:])
|
| 388 |
+
if len(prepared_tasks) == 1:
|
| 389 |
+
[(probabilities, encoded_bases)] = prepared_tasks
|
| 390 |
+
[transition_scores] = prepared_transition_log_odds
|
| 391 |
+
else:
|
| 392 |
+
probabilities = np.concatenate([probabilities for probabilities, _ in prepared_tasks])
|
| 393 |
+
encoded_bases = np.concatenate([encoded_bases for _, encoded_bases in prepared_tasks])
|
| 394 |
+
transition_scores = np.concatenate(prepared_transition_log_odds)
|
| 395 |
+
return probabilities.view(np.uint16), encoded_bases, transition_scores, record_offsets
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def quantize_transition_log_odds(log_odds):
|
| 399 |
+
"""Return transition log-odds in nats as the Viterbi backends' int32 fixed-point scores.
|
| 400 |
+
|
| 401 |
+
Every value is multiplied by ``FIXED_POINT_SCORE_SCALE`` and rounded to
|
| 402 |
+
the nearest integer. float16 and float32 values are scaled in float32,
|
| 403 |
+
other values in float64; the scale is a power of two, so the product is
|
| 404 |
+
exact and rounds to the same integer in either precision.
|
| 405 |
+
"""
|
| 406 |
+
log_odds = np.asarray(log_odds)
|
| 407 |
+
exact_dtype = np.float32 if log_odds.dtype in (np.float16, np.float32) else np.float64
|
| 408 |
+
scaled = np.rint(log_odds.astype(exact_dtype, copy=False) * exact_dtype(FIXED_POINT_SCORE_SCALE))
|
| 409 |
+
limits = np.iinfo(np.int32)
|
| 410 |
+
# As Python floats the extremes compare exactly with the int32 limits; NaN fails.
|
| 411 |
+
if scaled.size and not limits.min <= float(scaled.min()) <= float(scaled.max()) <= limits.max:
|
| 412 |
+
raise OverflowError("transition log-odds exceed the int32 fixed-point range")
|
| 413 |
+
return scaled.astype(np.int32)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def prepare_transition_log_odds(transition_log_odds, prepared_tasks):
|
| 417 |
+
"""Check one ``(bases, 4)`` int32 transition log-odds array per task for the Viterbi backends.
|
| 418 |
|
| 419 |
The columns follow ``TRANSITION_NAMES``: enter gene, leave gene, enter
|
| 420 |
intron, leave intron. Each value is the transition network's log-odds
|
| 421 |
+
against staying in ``FIXED_POINT_SCORE_SCALE`` units
|
| 422 |
+
(``quantize_transition_log_odds``), aligned base by base with the task's
|
| 423 |
+
probabilities. The arrays come back C-contiguous.
|
|
|
|
| 424 |
"""
|
| 425 |
+
transition_log_odds = list(transition_log_odds)
|
| 426 |
+
if len(transition_log_odds) != len(prepared_tasks):
|
| 427 |
raise ValueError(
|
| 428 |
+
f"{len(transition_log_odds)} transition log-odds arrays for "
|
| 429 |
+
f"{len(prepared_tasks)} Viterbi tasks"
|
| 430 |
)
|
| 431 |
+
prepared_log_odds = []
|
|
|
|
| 432 |
for task_index, (log_odds, (probabilities, _)) in enumerate(
|
| 433 |
+
zip(transition_log_odds, prepared_tasks)
|
| 434 |
):
|
| 435 |
+
log_odds = np.asarray(log_odds)
|
| 436 |
+
if log_odds.shape != (len(probabilities), TRANSITION_COUNT):
|
| 437 |
raise ValueError(
|
| 438 |
+
f"Viterbi task {task_index} transition log-odds must have shape "
|
| 439 |
+
f"{(len(probabilities), TRANSITION_COUNT)}, got {log_odds.shape}"
|
| 440 |
+
)
|
| 441 |
+
if log_odds.dtype != np.int32:
|
| 442 |
+
raise TypeError(
|
| 443 |
+
f"Viterbi task {task_index} transition log-odds must be int32 fixed-point scores, "
|
| 444 |
+
f"got {log_odds.dtype}"
|
| 445 |
)
|
| 446 |
+
prepared_log_odds.append(np.ascontiguousarray(log_odds))
|
| 447 |
+
return prepared_log_odds
|
|
|
|
|
|
|
| 448 |
|
| 449 |
|
| 450 |
def build_cds_sequence(genome_sequence, transcript_order_exons, strand):
|
|
|
|
| 463 |
return reverse_complement(genomic_order_sequence)
|
| 464 |
|
| 465 |
|
| 466 |
+
def compute_gff_cds_phases(transcript_order_exons, initial_gff3_phase=0):
|
| 467 |
"""Return GFF3 phases, preserving the first visible codon's phase."""
|
| 468 |
+
if initial_gff3_phase not in (0, 1, 2):
|
| 469 |
+
raise ValueError("initial GFF3 phase must be 0, 1, or 2")
|
| 470 |
|
| 471 |
phases = []
|
| 472 |
consumed_bases = 0
|
| 473 |
for start, end in transcript_order_exons:
|
| 474 |
+
phase = (initial_gff3_phase - consumed_bases) % 3
|
| 475 |
phases.append(phase)
|
| 476 |
consumed_bases += end - start + 1
|
| 477 |
return phases
|
|
|
|
| 484 |
):
|
| 485 |
"""Return whether a translated CDS contains a non-terminal stop codon.
|
| 486 |
|
| 487 |
+
This is a diagnostic check: the Viterbi grammar should normally make the
|
| 488 |
result false. A stop is terminal only when its third base is the final CDS
|
| 489 |
base; a stop before an incomplete trailing codon is still internal.
|
| 490 |
"""
|
|
|
|
| 513 |
Reasons are comma-separated so boundary-truncated predictions can state
|
| 514 |
every visible problem inside one GFF3 attribute, for example
|
| 515 |
``no_start,no_stop``. ``short_intron``
|
| 516 |
+
records a Viterbi path with fewer than four bases between adjacent exons.
|
| 517 |
Start and stop presence comes from the decoded states, then the sequence
|
| 518 |
is checked as a consistency guard.
|
| 519 |
"""
|
|
|
|
| 687 |
stop_codons=STOP_CODONS,
|
| 688 |
):
|
| 689 |
"""Build one output gene from its exons and boundary CDS states."""
|
| 690 |
+
initial_gff3_phase = initial_gff3_phase_from_state(first_cds_state)
|
| 691 |
if strand == "+":
|
| 692 |
transcript_order_exons = [
|
| 693 |
(int(start), int(end)) for start, end in oriented_exons
|
|
|
|
| 704 |
|
| 705 |
transcript_order_phases = compute_gff_cds_phases(
|
| 706 |
transcript_order_exons,
|
| 707 |
+
initial_gff3_phase,
|
| 708 |
)
|
| 709 |
genomic_order = sorted(
|
| 710 |
zip(transcript_order_exons, transcript_order_phases),
|
|
|
|
| 713 |
|
| 714 |
assert not has_internal_stop_codon(
|
| 715 |
cds_sequence,
|
| 716 |
+
initial_gff3_phase,
|
| 717 |
stop_codons,
|
| 718 |
), (
|
| 719 |
+
"Viterbi produced an internal stop codon: "
|
| 720 |
f"record_id={record_id!r}, strand={strand}, "
|
| 721 |
+
f"phase={initial_gff3_phase}, exons={transcript_order_exons}"
|
| 722 |
)
|
| 723 |
complete, incomplete_reason = classify_cds_completion(
|
| 724 |
cds_sequence,
|
|
|
|
| 731 |
"record_id": record_id,
|
| 732 |
"strand": strand,
|
| 733 |
"cds": cds_sequence,
|
| 734 |
+
"translation_frame": initial_gff3_phase,
|
| 735 |
"complete": complete,
|
| 736 |
"incomplete_reason": incomplete_reason,
|
| 737 |
"exons": [exon for exon, phase in genomic_order],
|
annotation_pipeline/src/viterbi.py
CHANGED
|
@@ -22,17 +22,17 @@ Viterbi backend: the equivalent native implementations in viterbi_backends/
|
|
| 22 |
|
| 23 |
State design:
|
| 24 |
|
| 25 |
-
To recognize stop codons,
|
| 26 |
-
|
| 27 |
-
|
| 28 |
bases, 0, 1, or 2, have been consumed in the current codon:
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
|
| 37 |
GFF3 phase uses a different convention: it records how many visible bases
|
| 38 |
to skip before the next complete codon, rather than bases already consumed.
|
|
@@ -43,43 +43,44 @@ State design:
|
|
| 43 |
state table because both exit at AG, but each uses its own intron prior.
|
| 44 |
AT-AC uses a separate state table because it exits at AC.
|
| 45 |
|
| 46 |
-
The
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
| 78 |
|
| 79 |
Transition rules:
|
| 80 |
|
| 81 |
INTERGENIC self-loops or starts a start codon ATG. START_A -> START_AT ->
|
| 82 |
-
|
| 83 |
selected stops enter STOP. STOP exits to INTERGENIC. Exons may enter
|
| 84 |
GT-AG/GC-AG introns at G followed by T/C, or AT-AC introns at A followed
|
| 85 |
by T. GT/GC-AG introns enter FIRST, then must consume one more intron base
|
|
@@ -90,7 +91,7 @@ Transition rules:
|
|
| 90 |
Opening an intron adds the explicit log prior for its splice class. The
|
| 91 |
supported frequencies are 0.990 for GT-AG, 0.009 for GC-AG, and 0.001 for
|
| 92 |
AT-AC, each divided by the 0.99 GT-AG baseline before taking the logarithm.
|
| 93 |
-
The GT-AG prior is therefore exactly zero, but remains an explicit
|
| 94 |
parameter in the Numba, CPU, and CUDA implementations.
|
| 95 |
|
| 96 |
Except for the two boundary-intron guards described below, a sequence base
|
|
@@ -107,8 +108,8 @@ Transition rules:
|
|
| 107 |
scores at both ends of the intron and still pays the splice-class prior. If
|
| 108 |
it wins, the model strongly prefers those bases to be non-coding, while the
|
| 109 |
ambiguous sequence provides too little evidence for a reliable repair. The path is retained and its gene is reported as
|
| 110 |
-
incomplete with reason short_intron instead of expanding the
|
| 111 |
-
|
| 112 |
|
| 113 |
The transition network's four probabilities enter the score as log-odds
|
| 114 |
against staying, charged on the base where the new segment begins or, for
|
|
@@ -193,15 +194,15 @@ from constants import (
|
|
| 193 |
MIN_PROB,
|
| 194 |
)
|
| 195 |
from utils import (
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
STATE_COUNT, INTERGENIC, START_A, START_AT,
|
| 199 |
LEADING_BOUNDARY_INTRON, TRAILING_BOUNDARY_INTRON,
|
| 200 |
EXON_STATE_BY_PREFIX_TYPE,
|
| 201 |
GT_GC_AG_INTRON_FIRST_STATE_BY_PREFIX_TYPE,
|
| 202 |
GT_GC_AG_INTRON_READY_STATE_BY_PREFIX_TYPE,
|
| 203 |
AT_AC_INTRON_STATE_BY_PREFIX_TYPE,
|
| 204 |
-
prepare_decode_tasks,
|
| 205 |
validate_max_boundary_intron_length,
|
| 206 |
)
|
| 207 |
|
|
@@ -241,41 +242,41 @@ def is_exact_enabled_stop_codon(
|
|
| 241 |
@njit(cache=True, inline="always")
|
| 242 |
def next_coding_state_after_base(prefix_type, base, stop_taa, stop_tag, stop_tga):
|
| 243 |
"""Return the exon/STOP state after emitting one coding base."""
|
| 244 |
-
#
|
| 245 |
-
#
|
| 246 |
-
if prefix_type ==
|
| 247 |
if base == BASE_T:
|
| 248 |
-
return EXON_STATE_BY_PREFIX_TYPE[
|
| 249 |
-
return EXON_STATE_BY_PREFIX_TYPE[
|
| 250 |
|
| 251 |
-
#
|
| 252 |
-
if prefix_type ==
|
| 253 |
if base == BASE_A:
|
| 254 |
-
return EXON_STATE_BY_PREFIX_TYPE[
|
| 255 |
if base == BASE_G:
|
| 256 |
-
return EXON_STATE_BY_PREFIX_TYPE[
|
| 257 |
-
return EXON_STATE_BY_PREFIX_TYPE[
|
| 258 |
|
| 259 |
-
#
|
| 260 |
-
# create a possible standard stop prefix.
|
| 261 |
-
if prefix_type ==
|
| 262 |
-
return EXON_STATE_BY_PREFIX_TYPE[
|
| 263 |
|
| 264 |
-
#
|
| 265 |
-
if prefix_type ==
|
| 266 |
if base == BASE_A and stop_taa:
|
| 267 |
return STOP
|
| 268 |
if base == BASE_G and stop_tag:
|
| 269 |
return STOP
|
| 270 |
-
return
|
| 271 |
|
| 272 |
-
#
|
| 273 |
-
if prefix_type ==
|
| 274 |
if base == BASE_A and stop_tga:
|
| 275 |
return STOP
|
| 276 |
-
return
|
| 277 |
|
| 278 |
-
return
|
| 279 |
|
| 280 |
|
| 281 |
@njit(cache=True, inline="always")
|
|
@@ -324,7 +325,7 @@ def emit_coding_base(
|
|
| 324 |
|
| 325 |
@njit(cache=True)
|
| 326 |
def initialize_first_base_scores(
|
| 327 |
-
coding_scores, noncoding_scores,
|
| 328 |
stop_taa, stop_tag, stop_tga, boundary_introns_enabled,
|
| 329 |
current_scores,
|
| 330 |
):
|
|
@@ -355,18 +356,18 @@ def initialize_first_base_scores(
|
|
| 355 |
# observed base and unknown bases to the left of the record boundary. They
|
| 356 |
# remain legal when boundary introns are disabled, allowing a record to
|
| 357 |
# begin inside an exon.
|
| 358 |
-
current_scores[EXON_STATE_BY_PREFIX_TYPE[
|
| 359 |
-
current_scores[EXON_STATE_BY_PREFIX_TYPE[
|
| 360 |
if base == BASE_N:
|
| 361 |
for prefix_type in range(PREFIX_TYPE_COUNT):
|
| 362 |
current_scores[EXON_STATE_BY_PREFIX_TYPE[prefix_type]] = coding_score
|
| 363 |
else:
|
| 364 |
-
one_base_prefix_type =
|
| 365 |
current_scores[EXON_STATE_BY_PREFIX_TYPE[one_base_prefix_type]] = coding_score
|
| 366 |
if base == BASE_A:
|
| 367 |
-
current_scores[EXON_STATE_BY_PREFIX_TYPE[
|
| 368 |
elif base == BASE_G:
|
| 369 |
-
current_scores[EXON_STATE_BY_PREFIX_TYPE[
|
| 370 |
|
| 371 |
# The record may begin with the last observed base of a stop codon whose
|
| 372 |
# first two bases lie outside the left boundary.
|
|
@@ -374,7 +375,7 @@ def initialize_first_base_scores(
|
|
| 374 |
base_matches(base, BASE_A) and (stop_taa or stop_tga)
|
| 375 |
) or (base_matches(base, BASE_G) and stop_tag)
|
| 376 |
if can_end_stop:
|
| 377 |
-
current_scores[STOP] = coding_score +
|
| 378 |
|
| 379 |
if boundary_introns_enabled:
|
| 380 |
# A record that starts inside an intron has no observable preceding
|
|
@@ -392,12 +393,12 @@ def initialize_first_base_scores(
|
|
| 392 |
and third_start_base_matches
|
| 393 |
)
|
| 394 |
if has_atg_start:
|
| 395 |
-
current_scores[START_A] = coding_score +
|
| 396 |
|
| 397 |
|
| 398 |
@njit(cache=True)
|
| 399 |
def run_viterbi_forward(
|
| 400 |
-
coding_scores, noncoding_scores,
|
| 401 |
stop_taa, stop_tag, stop_tga,
|
| 402 |
gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,
|
| 403 |
max_boundary_intron_length,
|
|
@@ -405,11 +406,11 @@ def run_viterbi_forward(
|
|
| 405 |
):
|
| 406 |
"""Run the source-state Viterbi forward pass and fill backpointers.
|
| 407 |
|
| 408 |
-
``
|
| 409 |
network scores in nats, in ``TRANSITION_NAMES`` column order.
|
| 410 |
"""
|
| 411 |
initialize_first_base_scores(
|
| 412 |
-
coding_scores, noncoding_scores,
|
| 413 |
stop_taa, stop_tag, stop_tga, max_boundary_intron_length != 0,
|
| 414 |
current_scores,
|
| 415 |
)
|
|
@@ -420,10 +421,10 @@ def run_viterbi_forward(
|
|
| 420 |
base = bases[position]
|
| 421 |
coding_score = coding_scores[position]
|
| 422 |
noncoding_score = noncoding_scores[position]
|
| 423 |
-
enter_gene_log_odds =
|
| 424 |
-
leave_gene_log_odds =
|
| 425 |
-
enter_intron_log_odds =
|
| 426 |
-
leave_intron_log_odds =
|
| 427 |
|
| 428 |
# Donor tests look at the current and next base. At the final base the
|
| 429 |
# unavailable next base may complete a donor outside the record.
|
|
@@ -497,7 +498,9 @@ def run_viterbi_forward(
|
|
| 497 |
)
|
| 498 |
)
|
| 499 |
can_enter_trailing_boundary_intron = (
|
| 500 |
-
|
|
|
|
|
|
|
| 501 |
and (
|
| 502 |
boundary_intron_length_is_unlimited
|
| 503 |
or record_length - position <= max_boundary_intron_length
|
|
@@ -532,7 +535,7 @@ def run_viterbi_forward(
|
|
| 532 |
STOP,
|
| 533 |
)
|
| 534 |
|
| 535 |
-
# 3. Start codon ATG consumes T and G, then enters
|
| 536 |
if current_scores[START_A] != -np.inf:
|
| 537 |
keep_best_transition(
|
| 538 |
next_scores, predecessors, START_AT,
|
|
@@ -540,7 +543,7 @@ def run_viterbi_forward(
|
|
| 540 |
)
|
| 541 |
if current_scores[START_AT] != -np.inf:
|
| 542 |
keep_best_transition(
|
| 543 |
-
next_scores, predecessors,
|
| 544 |
current_scores[START_AT] + coding_score,
|
| 545 |
START_AT,
|
| 546 |
)
|
|
@@ -559,11 +562,11 @@ def run_viterbi_forward(
|
|
| 559 |
current_scores[LEADING_BOUNDARY_INTRON] + noncoding_score,
|
| 560 |
LEADING_BOUNDARY_INTRON,
|
| 561 |
)
|
| 562 |
-
|
| 563 |
(has_ag_acceptor or has_ac_acceptor)
|
| 564 |
and not has_exact_acceptor_followed_by_atg
|
| 565 |
)
|
| 566 |
-
if
|
| 567 |
for prefix_type in range(PREFIX_TYPE_COUNT):
|
| 568 |
emit_coding_base(
|
| 569 |
current_scores, next_scores, predecessors,
|
|
@@ -619,11 +622,7 @@ def run_viterbi_forward(
|
|
| 619 |
exon_state,
|
| 620 |
)
|
| 621 |
|
| 622 |
-
if
|
| 623 |
-
has_any_donor
|
| 624 |
-
and not has_exact_enabled_stop_followed_by_donor
|
| 625 |
-
and can_enter_trailing_boundary_intron
|
| 626 |
-
):
|
| 627 |
if has_gt_ag_donor:
|
| 628 |
keep_best_transition(
|
| 629 |
next_scores, predecessors,
|
|
@@ -735,7 +734,7 @@ def best_final_state(current_scores):
|
|
| 735 |
|
| 736 |
@njit(cache=True, nogil=True)
|
| 737 |
def decode_one_track(
|
| 738 |
-
coding_scores, noncoding_scores,
|
| 739 |
stop_taa, stop_tag, stop_tga,
|
| 740 |
gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,
|
| 741 |
max_boundary_intron_length,
|
|
@@ -745,7 +744,7 @@ def decode_one_track(
|
|
| 745 |
current_scores = np.empty(STATE_COUNT, np.float64)
|
| 746 |
backpointers = np.empty((record_length, STATE_COUNT), np.int8)
|
| 747 |
run_viterbi_forward(
|
| 748 |
-
coding_scores, noncoding_scores,
|
| 749 |
stop_taa, stop_tag, stop_tga,
|
| 750 |
gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,
|
| 751 |
max_boundary_intron_length,
|
|
@@ -761,26 +760,26 @@ def decode_one_track(
|
|
| 761 |
|
| 762 |
def decode_paths_with_numba(
|
| 763 |
tasks,
|
| 764 |
-
|
| 765 |
stop_taa=True, stop_tag=True, stop_tga=True,
|
| 766 |
gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,
|
| 767 |
gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,
|
| 768 |
at_ac_intron_log_prior=AT_AC_INTRON_LOG_PRIOR,
|
| 769 |
max_boundary_intron_length=MAX_BOUNDARY_INTRON_LENGTH_BP,
|
| 770 |
):
|
| 771 |
-
"""Decode ``[(probabilities, encoded_bases), ...]`` with the
|
| 772 |
|
| 773 |
-
``
|
| 774 |
-
each transition's log-odds against staying
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
"""
|
| 779 |
max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)
|
| 780 |
tasks = prepare_decode_tasks(tasks)
|
| 781 |
-
|
| 782 |
paths = []
|
| 783 |
-
for (probabilities, encoded_bases), fixed_point_scores in zip(tasks,
|
| 784 |
coding_probabilities = probabilities.astype(np.float64)
|
| 785 |
np.clip(coding_probabilities, MIN_PROB, MAX_PROB, out=coding_probabilities)
|
| 786 |
record_length = coding_probabilities.shape[0]
|
|
@@ -917,7 +916,7 @@ def choose_viterbi_backend(requested_backend):
|
|
| 917 |
return "numba"
|
| 918 |
|
| 919 |
try:
|
| 920 |
-
module = importlib.import_module(f"viterbi_backends.
|
| 921 |
ok, reason = module.available()
|
| 922 |
if ok:
|
| 923 |
return backend
|
|
@@ -928,13 +927,13 @@ def choose_viterbi_backend(requested_backend):
|
|
| 928 |
raise RuntimeError("no Viterbi backend available: " + "; ".join(reasons))
|
| 929 |
|
| 930 |
|
| 931 |
-
def decode_paths(tasks,
|
| 932 |
"""Run the Viterbi algorithm on ``viterbi_backend`` (``gpu``, ``cpu``, or ``numba``).
|
| 933 |
|
| 934 |
Every backend takes the arguments of ``decode_paths_with_numba`` and
|
| 935 |
returns identical state paths.
|
| 936 |
"""
|
| 937 |
if viterbi_backend == "numba":
|
| 938 |
-
return decode_paths_with_numba(tasks,
|
| 939 |
-
module = importlib.import_module(f"viterbi_backends.
|
| 940 |
-
return module.decode_paths(tasks,
|
|
|
|
| 22 |
|
| 23 |
State design:
|
| 24 |
|
| 25 |
+
To recognize stop codons, a state only needs to record which stop prefix,
|
| 26 |
+
if any, has already been seen inside the current codon. That memory is
|
| 27 |
+
stored as one of six prefix types. Codon phase here means how many CDS
|
| 28 |
bases, 0, 1, or 2, have been consumed in the current codon:
|
| 29 |
|
| 30 |
+
PHASE0 codon phase 0; codon boundary, no open prefix
|
| 31 |
+
PHASE1_PREFIX_T codon phase 1; one-base prefix T
|
| 32 |
+
PHASE1_PREFIX_OTHER codon phase 1; one-base prefix other
|
| 33 |
+
PHASE2_PREFIX_TA codon phase 2; prefix TA, so A/G completes TAA/TAG
|
| 34 |
+
PHASE2_PREFIX_TG codon phase 2; prefix TG, so A completes TGA
|
| 35 |
+
PHASE2_PREFIX_OTHER codon phase 2; other prefix, so no stop can be completed
|
| 36 |
|
| 37 |
GFF3 phase uses a different convention: it records how many visible bases
|
| 38 |
to skip before the next complete codon, rather than bases already consumed.
|
|
|
|
| 43 |
state table because both exit at AG, but each uses its own intron prior.
|
| 44 |
AT-AC uses a separate state table because it exits at AC.
|
| 45 |
|
| 46 |
+
The state ids are defined in utils.py. Exon and intron state names end in
|
| 47 |
+
the prefix type the state carries:
|
| 48 |
+
|
| 49 |
+
0 INTERGENIC non-coding outside genes
|
| 50 |
+
1 START_A A of start codon ATG
|
| 51 |
+
2 START_AT T of start codon ATG; its G is EXON_PHASE0
|
| 52 |
+
3 EXON_PHASE0 CDS base that completes a codon
|
| 53 |
+
4 EXON_PHASE1_PREFIX_T first codon base T
|
| 54 |
+
5 EXON_PHASE1_PREFIX_OTHER first codon base A, C, or G
|
| 55 |
+
6 EXON_PHASE2_PREFIX_TA second codon base A after T
|
| 56 |
+
7 EXON_PHASE2_PREFIX_TG second codon base G after T
|
| 57 |
+
8 EXON_PHASE2_PREFIX_OTHER second codon base; no stop can be completed
|
| 58 |
+
9 STOP last base of the terminal in-frame stop codon
|
| 59 |
+
10 GT_GC_AG_INTRON_FIRST_PHASE0 first GT/GC-AG intron base
|
| 60 |
+
11 GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_T first GT/GC-AG intron base
|
| 61 |
+
12 GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_OTHER first GT/GC-AG intron base
|
| 62 |
+
13 GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TA first GT/GC-AG intron base
|
| 63 |
+
14 GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TG first GT/GC-AG intron base
|
| 64 |
+
15 GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_OTHER first GT/GC-AG intron base
|
| 65 |
+
16 GT_GC_AG_INTRON_READY_PHASE0 later GT/GC-AG intron base
|
| 66 |
+
17 GT_GC_AG_INTRON_READY_PHASE1_PREFIX_T later GT/GC-AG intron base
|
| 67 |
+
18 GT_GC_AG_INTRON_READY_PHASE1_PREFIX_OTHER later GT/GC-AG intron base
|
| 68 |
+
19 GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TA later GT/GC-AG intron base
|
| 69 |
+
20 GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TG later GT/GC-AG intron base
|
| 70 |
+
21 GT_GC_AG_INTRON_READY_PHASE2_PREFIX_OTHER later GT/GC-AG intron base
|
| 71 |
+
22 AT_AC_INTRON_PHASE0 AT-AC intron base
|
| 72 |
+
23 AT_AC_INTRON_PHASE1_PREFIX_T AT-AC intron base
|
| 73 |
+
24 AT_AC_INTRON_PHASE1_PREFIX_OTHER AT-AC intron base
|
| 74 |
+
25 AT_AC_INTRON_PHASE2_PREFIX_TA AT-AC intron base
|
| 75 |
+
26 AT_AC_INTRON_PHASE2_PREFIX_TG AT-AC intron base
|
| 76 |
+
27 AT_AC_INTRON_PHASE2_PREFIX_OTHER AT-AC intron base
|
| 77 |
+
28 LEADING_BOUNDARY_INTRON intron extending from the left record boundary
|
| 78 |
+
29 TRAILING_BOUNDARY_INTRON intron extending to the right record boundary
|
| 79 |
|
| 80 |
Transition rules:
|
| 81 |
|
| 82 |
INTERGENIC self-loops or starts a start codon ATG. START_A -> START_AT ->
|
| 83 |
+
EXON_PHASE0. Exons consume coding bases and update prefix type;
|
| 84 |
selected stops enter STOP. STOP exits to INTERGENIC. Exons may enter
|
| 85 |
GT-AG/GC-AG introns at G followed by T/C, or AT-AC introns at A followed
|
| 86 |
by T. GT/GC-AG introns enter FIRST, then must consume one more intron base
|
|
|
|
| 91 |
Opening an intron adds the explicit log prior for its splice class. The
|
| 92 |
supported frequencies are 0.990 for GT-AG, 0.009 for GC-AG, and 0.001 for
|
| 93 |
AT-AC, each divided by the 0.99 GT-AG baseline before taking the logarithm.
|
| 94 |
+
The GT-AG prior is therefore exactly zero, but remains an explicit
|
| 95 |
parameter in the Numba, CPU, and CUDA implementations.
|
| 96 |
|
| 97 |
Except for the two boundary-intron guards described below, a sequence base
|
|
|
|
| 108 |
scores at both ends of the intron and still pays the splice-class prior. If
|
| 109 |
it wins, the model strongly prefers those bases to be non-coding, while the
|
| 110 |
ambiguous sequence provides too little evidence for a reliable repair. The path is retained and its gene is reported as
|
| 111 |
+
incomplete with reason short_intron instead of expanding the state space
|
| 112 |
+
solely for this rare condition.
|
| 113 |
|
| 114 |
The transition network's four probabilities enter the score as log-odds
|
| 115 |
against staying, charged on the base where the new segment begins or, for
|
|
|
|
| 194 |
MIN_PROB,
|
| 195 |
)
|
| 196 |
from utils import (
|
| 197 |
+
PHASE0, PHASE1_PREFIX_T, PHASE1_PREFIX_OTHER,
|
| 198 |
+
PHASE2_PREFIX_TA, PHASE2_PREFIX_TG, PHASE2_PREFIX_OTHER, PREFIX_TYPE_COUNT,
|
| 199 |
+
STATE_COUNT, INTERGENIC, START_A, START_AT, EXON_PHASE0, STOP,
|
| 200 |
LEADING_BOUNDARY_INTRON, TRAILING_BOUNDARY_INTRON,
|
| 201 |
EXON_STATE_BY_PREFIX_TYPE,
|
| 202 |
GT_GC_AG_INTRON_FIRST_STATE_BY_PREFIX_TYPE,
|
| 203 |
GT_GC_AG_INTRON_READY_STATE_BY_PREFIX_TYPE,
|
| 204 |
AT_AC_INTRON_STATE_BY_PREFIX_TYPE,
|
| 205 |
+
prepare_decode_tasks, prepare_transition_log_odds,
|
| 206 |
validate_max_boundary_intron_length,
|
| 207 |
)
|
| 208 |
|
|
|
|
| 242 |
@njit(cache=True, inline="always")
|
| 243 |
def next_coding_state_after_base(prefix_type, base, stop_taa, stop_tag, stop_tga):
|
| 244 |
"""Return the exon/STOP state after emitting one coding base."""
|
| 245 |
+
# PHASE0 means the previous coding base ended a codon. A new T can still
|
| 246 |
+
# become TAA/TAG/TGA; every other base cannot start a stop codon.
|
| 247 |
+
if prefix_type == PHASE0:
|
| 248 |
if base == BASE_T:
|
| 249 |
+
return EXON_STATE_BY_PREFIX_TYPE[PHASE1_PREFIX_T]
|
| 250 |
+
return EXON_STATE_BY_PREFIX_TYPE[PHASE1_PREFIX_OTHER]
|
| 251 |
|
| 252 |
+
# PHASE1_PREFIX_T means the current codon prefix is exactly T.
|
| 253 |
+
if prefix_type == PHASE1_PREFIX_T:
|
| 254 |
if base == BASE_A:
|
| 255 |
+
return EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_TA]
|
| 256 |
if base == BASE_G:
|
| 257 |
+
return EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_TG]
|
| 258 |
+
return EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_OTHER]
|
| 259 |
|
| 260 |
+
# PHASE1_PREFIX_OTHER is a one-base prefix other than T, so the second base
|
| 261 |
+
# cannot create a possible standard stop prefix.
|
| 262 |
+
if prefix_type == PHASE1_PREFIX_OTHER:
|
| 263 |
+
return EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_OTHER]
|
| 264 |
|
| 265 |
+
# PHASE2_PREFIX_TA is TA. A or G completes TAA/TAG if those stops are enabled.
|
| 266 |
+
if prefix_type == PHASE2_PREFIX_TA:
|
| 267 |
if base == BASE_A and stop_taa:
|
| 268 |
return STOP
|
| 269 |
if base == BASE_G and stop_tag:
|
| 270 |
return STOP
|
| 271 |
+
return EXON_PHASE0
|
| 272 |
|
| 273 |
+
# PHASE2_PREFIX_TG is TG. A completes TGA if that stop is enabled.
|
| 274 |
+
if prefix_type == PHASE2_PREFIX_TG:
|
| 275 |
if base == BASE_A and stop_tga:
|
| 276 |
return STOP
|
| 277 |
+
return EXON_PHASE0
|
| 278 |
|
| 279 |
+
return EXON_PHASE0
|
| 280 |
|
| 281 |
|
| 282 |
@njit(cache=True, inline="always")
|
|
|
|
| 325 |
|
| 326 |
@njit(cache=True)
|
| 327 |
def initialize_first_base_scores(
|
| 328 |
+
coding_scores, noncoding_scores, transition_log_odds, bases, record_length,
|
| 329 |
stop_taa, stop_tag, stop_tga, boundary_introns_enabled,
|
| 330 |
current_scores,
|
| 331 |
):
|
|
|
|
| 356 |
# observed base and unknown bases to the left of the record boundary. They
|
| 357 |
# remain legal when boundary introns are disabled, allowing a record to
|
| 358 |
# begin inside an exon.
|
| 359 |
+
current_scores[EXON_STATE_BY_PREFIX_TYPE[PHASE0]] = coding_score
|
| 360 |
+
current_scores[EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_OTHER]] = coding_score
|
| 361 |
if base == BASE_N:
|
| 362 |
for prefix_type in range(PREFIX_TYPE_COUNT):
|
| 363 |
current_scores[EXON_STATE_BY_PREFIX_TYPE[prefix_type]] = coding_score
|
| 364 |
else:
|
| 365 |
+
one_base_prefix_type = PHASE1_PREFIX_T if base == BASE_T else PHASE1_PREFIX_OTHER
|
| 366 |
current_scores[EXON_STATE_BY_PREFIX_TYPE[one_base_prefix_type]] = coding_score
|
| 367 |
if base == BASE_A:
|
| 368 |
+
current_scores[EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_TA]] = coding_score
|
| 369 |
elif base == BASE_G:
|
| 370 |
+
current_scores[EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_TG]] = coding_score
|
| 371 |
|
| 372 |
# The record may begin with the last observed base of a stop codon whose
|
| 373 |
# first two bases lie outside the left boundary.
|
|
|
|
| 375 |
base_matches(base, BASE_A) and (stop_taa or stop_tga)
|
| 376 |
) or (base_matches(base, BASE_G) and stop_tag)
|
| 377 |
if can_end_stop:
|
| 378 |
+
current_scores[STOP] = coding_score + transition_log_odds[0, LEAVE_GENE]
|
| 379 |
|
| 380 |
if boundary_introns_enabled:
|
| 381 |
# A record that starts inside an intron has no observable preceding
|
|
|
|
| 393 |
and third_start_base_matches
|
| 394 |
)
|
| 395 |
if has_atg_start:
|
| 396 |
+
current_scores[START_A] = coding_score + transition_log_odds[0, ENTER_GENE]
|
| 397 |
|
| 398 |
|
| 399 |
@njit(cache=True)
|
| 400 |
def run_viterbi_forward(
|
| 401 |
+
coding_scores, noncoding_scores, transition_log_odds, bases, record_length,
|
| 402 |
stop_taa, stop_tag, stop_tga,
|
| 403 |
gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,
|
| 404 |
max_boundary_intron_length,
|
|
|
|
| 406 |
):
|
| 407 |
"""Run the source-state Viterbi forward pass and fill backpointers.
|
| 408 |
|
| 409 |
+
``transition_log_odds`` is the ``(record_length, 4)`` array of transition
|
| 410 |
network scores in nats, in ``TRANSITION_NAMES`` column order.
|
| 411 |
"""
|
| 412 |
initialize_first_base_scores(
|
| 413 |
+
coding_scores, noncoding_scores, transition_log_odds, bases, record_length,
|
| 414 |
stop_taa, stop_tag, stop_tga, max_boundary_intron_length != 0,
|
| 415 |
current_scores,
|
| 416 |
)
|
|
|
|
| 421 |
base = bases[position]
|
| 422 |
coding_score = coding_scores[position]
|
| 423 |
noncoding_score = noncoding_scores[position]
|
| 424 |
+
enter_gene_log_odds = transition_log_odds[position, ENTER_GENE]
|
| 425 |
+
leave_gene_log_odds = transition_log_odds[position, LEAVE_GENE]
|
| 426 |
+
enter_intron_log_odds = transition_log_odds[position, ENTER_INTRON]
|
| 427 |
+
leave_intron_log_odds = transition_log_odds[position, LEAVE_INTRON]
|
| 428 |
|
| 429 |
# Donor tests look at the current and next base. At the final base the
|
| 430 |
# unavailable next base may complete a donor outside the record.
|
|
|
|
| 498 |
)
|
| 499 |
)
|
| 500 |
can_enter_trailing_boundary_intron = (
|
| 501 |
+
has_any_donor
|
| 502 |
+
and not has_exact_enabled_stop_followed_by_donor
|
| 503 |
+
and boundary_introns_enabled
|
| 504 |
and (
|
| 505 |
boundary_intron_length_is_unlimited
|
| 506 |
or record_length - position <= max_boundary_intron_length
|
|
|
|
| 535 |
STOP,
|
| 536 |
)
|
| 537 |
|
| 538 |
+
# 3. Start codon ATG consumes T and G, then enters EXON_PHASE0.
|
| 539 |
if current_scores[START_A] != -np.inf:
|
| 540 |
keep_best_transition(
|
| 541 |
next_scores, predecessors, START_AT,
|
|
|
|
| 543 |
)
|
| 544 |
if current_scores[START_AT] != -np.inf:
|
| 545 |
keep_best_transition(
|
| 546 |
+
next_scores, predecessors, EXON_PHASE0,
|
| 547 |
current_scores[START_AT] + coding_score,
|
| 548 |
START_AT,
|
| 549 |
)
|
|
|
|
| 562 |
current_scores[LEADING_BOUNDARY_INTRON] + noncoding_score,
|
| 563 |
LEADING_BOUNDARY_INTRON,
|
| 564 |
)
|
| 565 |
+
can_exit_leading_boundary_intron = (
|
| 566 |
(has_ag_acceptor or has_ac_acceptor)
|
| 567 |
and not has_exact_acceptor_followed_by_atg
|
| 568 |
)
|
| 569 |
+
if can_exit_leading_boundary_intron:
|
| 570 |
for prefix_type in range(PREFIX_TYPE_COUNT):
|
| 571 |
emit_coding_base(
|
| 572 |
current_scores, next_scores, predecessors,
|
|
|
|
| 622 |
exon_state,
|
| 623 |
)
|
| 624 |
|
| 625 |
+
if can_enter_trailing_boundary_intron:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 626 |
if has_gt_ag_donor:
|
| 627 |
keep_best_transition(
|
| 628 |
next_scores, predecessors,
|
|
|
|
| 734 |
|
| 735 |
@njit(cache=True, nogil=True)
|
| 736 |
def decode_one_track(
|
| 737 |
+
coding_scores, noncoding_scores, transition_log_odds, bases, record_length,
|
| 738 |
stop_taa, stop_tag, stop_tga,
|
| 739 |
gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,
|
| 740 |
max_boundary_intron_length,
|
|
|
|
| 744 |
current_scores = np.empty(STATE_COUNT, np.float64)
|
| 745 |
backpointers = np.empty((record_length, STATE_COUNT), np.int8)
|
| 746 |
run_viterbi_forward(
|
| 747 |
+
coding_scores, noncoding_scores, transition_log_odds, bases, record_length,
|
| 748 |
stop_taa, stop_tag, stop_tga,
|
| 749 |
gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,
|
| 750 |
max_boundary_intron_length,
|
|
|
|
| 760 |
|
| 761 |
def decode_paths_with_numba(
|
| 762 |
tasks,
|
| 763 |
+
transition_log_odds,
|
| 764 |
stop_taa=True, stop_tag=True, stop_tga=True,
|
| 765 |
gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,
|
| 766 |
gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,
|
| 767 |
at_ac_intron_log_prior=AT_AC_INTRON_LOG_PRIOR,
|
| 768 |
max_boundary_intron_length=MAX_BOUNDARY_INTRON_LENGTH_BP,
|
| 769 |
):
|
| 770 |
+
"""Decode ``[(probabilities, encoded_bases), ...]`` with the Numba reference implementation.
|
| 771 |
|
| 772 |
+
``transition_log_odds`` holds one ``(bases, 4)`` int32 array per task with
|
| 773 |
+
each transition's log-odds against staying in ``FIXED_POINT_SCORE_SCALE``
|
| 774 |
+
units (``utils.quantize_transition_log_odds``), the values the native
|
| 775 |
+
backends accumulate. The reference divides them by
|
| 776 |
+
``FIXED_POINT_SCORE_SCALE`` to work in nats.
|
| 777 |
"""
|
| 778 |
max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)
|
| 779 |
tasks = prepare_decode_tasks(tasks)
|
| 780 |
+
transition_log_odds = prepare_transition_log_odds(transition_log_odds, tasks)
|
| 781 |
paths = []
|
| 782 |
+
for (probabilities, encoded_bases), fixed_point_scores in zip(tasks, transition_log_odds):
|
| 783 |
coding_probabilities = probabilities.astype(np.float64)
|
| 784 |
np.clip(coding_probabilities, MIN_PROB, MAX_PROB, out=coding_probabilities)
|
| 785 |
record_length = coding_probabilities.shape[0]
|
|
|
|
| 916 |
return "numba"
|
| 917 |
|
| 918 |
try:
|
| 919 |
+
module = importlib.import_module(f"viterbi_backends.viterbi_{backend}")
|
| 920 |
ok, reason = module.available()
|
| 921 |
if ok:
|
| 922 |
return backend
|
|
|
|
| 927 |
raise RuntimeError("no Viterbi backend available: " + "; ".join(reasons))
|
| 928 |
|
| 929 |
|
| 930 |
+
def decode_paths(tasks, transition_log_odds, viterbi_backend, **options):
|
| 931 |
"""Run the Viterbi algorithm on ``viterbi_backend`` (``gpu``, ``cpu``, or ``numba``).
|
| 932 |
|
| 933 |
Every backend takes the arguments of ``decode_paths_with_numba`` and
|
| 934 |
returns identical state paths.
|
| 935 |
"""
|
| 936 |
if viterbi_backend == "numba":
|
| 937 |
+
return decode_paths_with_numba(tasks, transition_log_odds, **options)
|
| 938 |
+
module = importlib.import_module(f"viterbi_backends.viterbi_{viterbi_backend}")
|
| 939 |
+
return module.decode_paths(tasks, transition_log_odds, **options)
|
annotation_pipeline/src/viterbi_backends/viterbi_cpu.cpp
CHANGED
|
@@ -1,717 +1,151 @@
|
|
| 1 |
-
// viterbi_cpu.cpp -- CPU Viterbi backend
|
| 2 |
//
|
| 3 |
-
//
|
| 4 |
-
//
|
| 5 |
-
//
|
| 6 |
-
//
|
| 7 |
-
// - Python supplies explicit GT-AG, GC-AG, and AT-AC log priors;
|
| 8 |
-
// - N freely matches any concrete base in codons and splice signals;
|
| 9 |
-
// - dedicated leading/trailing states represent introns crossing a record edge;
|
| 10 |
-
// - the transition network supplies the probabilities of the four permitted
|
| 11 |
-
// transitions per base (enter gene, leave gene, enter intron, leave
|
| 12 |
-
// intron) as log-odds in the decoder's fixed-point units;
|
| 13 |
-
// - stop read-through is disabled.
|
| 14 |
//
|
| 15 |
-
//
|
| 16 |
-
//
|
| 17 |
-
//
|
| 18 |
-
//
|
| 19 |
-
//
|
| 20 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
#include <cstdint>
|
| 22 |
-
#include <cmath>
|
| 23 |
-
#include <cstring>
|
| 24 |
#include <stdexcept>
|
|
|
|
| 25 |
#include <vector>
|
| 26 |
-
#include <omp.h>
|
| 27 |
|
| 28 |
-
|
| 29 |
-
using StepScore = int32_t;
|
| 30 |
-
static const double SCORE_SCALE = 16384.0;
|
| 31 |
-
static inline StepScore score_from_nats(double nats) {
|
| 32 |
-
return static_cast<StepScore>(std::llround(nats * SCORE_SCALE));
|
| 33 |
-
}
|
| 34 |
-
// Fixed-point code uses this sentinel in place of IEEE -inf.
|
| 35 |
-
static const AccumulatedScore UNREACHABLE_ACCUMULATED_SCORE = -4'000'000'000'000'000'000LL;
|
| 36 |
-
static const int64_t DEFAULT_RECONSTRUCTION_BATCH_SIZE = 8'000'000;
|
| 37 |
-
|
| 38 |
-
static const int STATE_COUNT = 30;
|
| 39 |
-
static const int PREFIX_TYPE_COUNT = 6;
|
| 40 |
-
static const int INTERGENIC = 0;
|
| 41 |
-
static const int START_A = 1;
|
| 42 |
-
static const int START_AT = 2;
|
| 43 |
-
static const int EXON_PREFIX_TYPE_0 = 3;
|
| 44 |
-
static const int STOP = 9;
|
| 45 |
-
static const int GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 = 10;
|
| 46 |
-
static const int GT_GC_AG_INTRON_READY_PREFIX_TYPE_0 = 16;
|
| 47 |
-
static const int AT_AC_INTRON_PREFIX_TYPE_0 = 22;
|
| 48 |
-
static const int LEADING_BOUNDARY_INTRON = 28;
|
| 49 |
-
static const int TRAILING_BOUNDARY_INTRON = 29;
|
| 50 |
-
|
| 51 |
-
// State layout matches viterbi.py and viterbi_gpu.cu:
|
| 52 |
-
// 0 intergenic; 1..2 ATG start; 3..8 exon prefix types; 9 stop;
|
| 53 |
-
// 10..15 GT/GC-AG FIRST; 16..21 GT/GC-AG READY; 22..27 AT-AC;
|
| 54 |
-
// 28 leading boundary intron; 29 trailing boundary intron.
|
| 55 |
-
|
| 56 |
-
static const int BASE_A = 0;
|
| 57 |
-
static const int BASE_T = 1;
|
| 58 |
-
static const int BASE_C = 2;
|
| 59 |
-
static const int BASE_G = 3;
|
| 60 |
-
static const int BASE_N = 4;
|
| 61 |
-
|
| 62 |
-
// Transition probability tracks per base, in the column order of constants.py.
|
| 63 |
-
// They arrive from Python as log-odds against staying, already quantized to
|
| 64 |
-
// the decoder's fixed-point units, so they add directly to path scores.
|
| 65 |
-
static const int ENTER_GENE = 0;
|
| 66 |
-
static const int LEAVE_GENE = 1;
|
| 67 |
-
static const int ENTER_INTRON = 2;
|
| 68 |
-
static const int LEAVE_INTRON = 3;
|
| 69 |
-
static const int TRANSITION_COUNT = 4;
|
| 70 |
-
|
| 71 |
-
static inline bool is_exon_state(int state) {
|
| 72 |
-
return state >= EXON_PREFIX_TYPE_0
|
| 73 |
-
&& state < EXON_PREFIX_TYPE_0 + PREFIX_TYPE_COUNT;
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
static inline bool is_gt_gc_intron_entry_state(int state) {
|
| 77 |
-
return state >= GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0
|
| 78 |
-
&& state < GT_GC_AG_INTRON_READY_PREFIX_TYPE_0;
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
static inline bool is_gt_gc_acceptor_state(int state) {
|
| 82 |
-
return state >= GT_GC_AG_INTRON_READY_PREFIX_TYPE_0
|
| 83 |
-
&& state < AT_AC_INTRON_PREFIX_TYPE_0;
|
| 84 |
-
}
|
| 85 |
-
|
| 86 |
-
static inline bool is_at_ac_intron_state(int state) {
|
| 87 |
-
return state >= AT_AC_INTRON_PREFIX_TYPE_0
|
| 88 |
-
&& state < LEADING_BOUNDARY_INTRON;
|
| 89 |
-
}
|
| 90 |
-
|
| 91 |
-
// Transition log-odds of one legal state change. Each value is attached to the
|
| 92 |
-
// base where the new segment begins: the first start-codon base (enter gene),
|
| 93 |
-
// the last stop-codon base (leave gene, charged on the base that closes the
|
| 94 |
-
// gene), the first intron base (enter intron), or the first exon base after an
|
| 95 |
-
// intron (leave intron). Introns that cross a record edge are entered and left
|
| 96 |
-
// the same way.
|
| 97 |
-
static inline StepScore transition_log_odds(
|
| 98 |
-
int source_state, int target_state, const StepScore* position_transition_probabilities
|
| 99 |
-
) {
|
| 100 |
-
if (source_state == INTERGENIC && target_state == START_A) {
|
| 101 |
-
return position_transition_probabilities[ENTER_GENE];
|
| 102 |
-
}
|
| 103 |
-
// Leaving the gene takes precedence when an intron exit completes a stop
|
| 104 |
-
// codon that was split by the intron.
|
| 105 |
-
if (target_state == STOP) return position_transition_probabilities[LEAVE_GENE];
|
| 106 |
-
if (is_exon_state(source_state)
|
| 107 |
-
&& (is_gt_gc_intron_entry_state(target_state)
|
| 108 |
-
|| is_at_ac_intron_state(target_state)
|
| 109 |
-
|| target_state == TRAILING_BOUNDARY_INTRON)) {
|
| 110 |
-
return position_transition_probabilities[ENTER_INTRON];
|
| 111 |
-
}
|
| 112 |
-
if ((is_gt_gc_acceptor_state(source_state)
|
| 113 |
-
|| is_at_ac_intron_state(source_state)
|
| 114 |
-
|| source_state == LEADING_BOUNDARY_INTRON)
|
| 115 |
-
&& is_exon_state(target_state)) {
|
| 116 |
-
return position_transition_probabilities[LEAVE_INTRON];
|
| 117 |
-
}
|
| 118 |
-
return StepScore(0);
|
| 119 |
-
}
|
| 120 |
-
|
| 121 |
-
static inline bool base_matches(int observed_base, int expected_base) {
|
| 122 |
-
return observed_base == expected_base || observed_base == BASE_N;
|
| 123 |
-
}
|
| 124 |
-
|
| 125 |
-
static inline bool is_exact_enabled_stop_codon(
|
| 126 |
-
int first_base, int second_base, int third_base,
|
| 127 |
-
bool stop_taa, bool stop_tag, bool stop_tga
|
| 128 |
-
) {
|
| 129 |
-
if (first_base != BASE_T) return false;
|
| 130 |
-
if (second_base == BASE_A) {
|
| 131 |
-
if (third_base == BASE_A && stop_taa) return true;
|
| 132 |
-
if (third_base == BASE_G && stop_tag) return true;
|
| 133 |
-
}
|
| 134 |
-
return second_base == BASE_G
|
| 135 |
-
&& third_base == BASE_A
|
| 136 |
-
&& stop_tga;
|
| 137 |
-
}
|
| 138 |
-
|
| 139 |
-
static StepScore coding_score_lookup[65536], noncoding_score_lookup[65536];
|
| 140 |
-
|
| 141 |
-
static double half_bits_to_double(uint16_t half_bits) {
|
| 142 |
-
uint32_t sign = static_cast<uint32_t>(half_bits & 0x8000) << 16;
|
| 143 |
-
uint32_t exponent = (half_bits >> 10) & 0x1F;
|
| 144 |
-
uint32_t mantissa = half_bits & 0x3FF;
|
| 145 |
-
uint32_t float_bits;
|
| 146 |
-
if (exponent == 0) {
|
| 147 |
-
if (mantissa == 0) {
|
| 148 |
-
float_bits = sign;
|
| 149 |
-
} else {
|
| 150 |
-
int normalization_shift = -1;
|
| 151 |
-
do {
|
| 152 |
-
normalization_shift++;
|
| 153 |
-
mantissa <<= 1;
|
| 154 |
-
} while (!(mantissa & 0x400));
|
| 155 |
-
float_bits = sign
|
| 156 |
-
| (static_cast<uint32_t>(127 - 15 - normalization_shift) << 23)
|
| 157 |
-
| ((mantissa & 0x3FF) << 13);
|
| 158 |
-
}
|
| 159 |
-
} else if (exponent == 0x1F) {
|
| 160 |
-
float_bits = sign | 0x7F800000u | (mantissa << 13);
|
| 161 |
-
} else {
|
| 162 |
-
float_bits = sign | ((exponent + (127 - 15)) << 23) | (mantissa << 13);
|
| 163 |
-
}
|
| 164 |
-
float value;
|
| 165 |
-
memcpy(&value, &float_bits, sizeof(value));
|
| 166 |
-
return static_cast<double>(value);
|
| 167 |
-
}
|
| 168 |
-
|
| 169 |
-
static bool build_log_score_lookup() {
|
| 170 |
-
for (int index = 0; index < 65536; index++) {
|
| 171 |
-
double probability = half_bits_to_double(static_cast<uint16_t>(index));
|
| 172 |
-
if (probability < 1e-6) probability = 1e-6;
|
| 173 |
-
else if (probability > 1.0 - 1e-6) probability = 1.0 - 1e-6;
|
| 174 |
-
coding_score_lookup[index] = score_from_nats(log(probability));
|
| 175 |
-
noncoding_score_lookup[index] = score_from_nats(log(1.0 - probability));
|
| 176 |
-
}
|
| 177 |
-
return true;
|
| 178 |
-
}
|
| 179 |
-
|
| 180 |
-
static inline int exon_state_for_prefix(int prefix_type) {
|
| 181 |
-
return EXON_PREFIX_TYPE_0 + prefix_type;
|
| 182 |
-
}
|
| 183 |
|
| 184 |
-
static
|
| 185 |
-
int prefix_type, int base,
|
| 186 |
-
bool stop_taa, bool stop_tag, bool stop_tga
|
| 187 |
-
) {
|
| 188 |
-
if (prefix_type == 0) return base == BASE_T ? exon_state_for_prefix(1) : exon_state_for_prefix(2);
|
| 189 |
-
if (prefix_type == 1) {
|
| 190 |
-
if (base == BASE_A) return exon_state_for_prefix(3);
|
| 191 |
-
if (base == BASE_G) return exon_state_for_prefix(4);
|
| 192 |
-
return exon_state_for_prefix(5);
|
| 193 |
-
}
|
| 194 |
-
if (prefix_type == 2) return exon_state_for_prefix(5);
|
| 195 |
-
if (prefix_type == 3) {
|
| 196 |
-
if (base == BASE_A && stop_taa) return STOP;
|
| 197 |
-
if (base == BASE_G && stop_tag) return STOP;
|
| 198 |
-
return exon_state_for_prefix(0);
|
| 199 |
-
}
|
| 200 |
-
if (prefix_type == 4) {
|
| 201 |
-
if (base == BASE_A && stop_tga) return STOP;
|
| 202 |
-
return exon_state_for_prefix(0);
|
| 203 |
-
}
|
| 204 |
-
return exon_state_for_prefix(0);
|
| 205 |
-
}
|
| 206 |
|
| 207 |
-
static
|
| 208 |
-
|
| 209 |
-
int target_state, AccumulatedScore candidate_score, int source_state,
|
| 210 |
-
const StepScore* position_transition_probabilities
|
| 211 |
-
) {
|
| 212 |
-
candidate_score += transition_log_odds(
|
| 213 |
-
source_state, target_state, position_transition_probabilities
|
| 214 |
-
);
|
| 215 |
-
if (candidate_score > next_scores[target_state]) {
|
| 216 |
-
next_scores[target_state] = candidate_score;
|
| 217 |
-
predecessors[target_state] = static_cast<int8_t>(source_state);
|
| 218 |
-
}
|
| 219 |
-
}
|
| 220 |
|
| 221 |
-
|
| 222 |
-
const AccumulatedScore* current_scores, AccumulatedScore* next_scores,
|
| 223 |
-
int8_t* predecessors, int source_state, int prefix_type,
|
| 224 |
-
StepScore coding_score, const StepScore* position_transition_probabilities, int base,
|
| 225 |
-
bool stop_taa, bool stop_tag, bool stop_tga
|
| 226 |
-
) {
|
| 227 |
-
AccumulatedScore source_score = current_scores[source_state];
|
| 228 |
-
if (source_score == UNREACHABLE_ACCUMULATED_SCORE) return;
|
| 229 |
-
AccumulatedScore candidate_score = source_score + coding_score;
|
| 230 |
-
if (base == BASE_N) {
|
| 231 |
-
for (int resolved_base = BASE_A; resolved_base <= BASE_G; resolved_base++) {
|
| 232 |
-
int target_state = next_coding_state_after_base(
|
| 233 |
-
prefix_type, resolved_base, stop_taa, stop_tag, stop_tga
|
| 234 |
-
);
|
| 235 |
-
keep_best_transition(
|
| 236 |
-
next_scores, predecessors, target_state, candidate_score, source_state,
|
| 237 |
-
position_transition_probabilities
|
| 238 |
-
);
|
| 239 |
-
}
|
| 240 |
-
} else {
|
| 241 |
-
int target_state = next_coding_state_after_base(
|
| 242 |
-
prefix_type, base, stop_taa, stop_tag, stop_tga
|
| 243 |
-
);
|
| 244 |
-
keep_best_transition(
|
| 245 |
-
next_scores, predecessors, target_state, candidate_score, source_state,
|
| 246 |
-
position_transition_probabilities
|
| 247 |
-
);
|
| 248 |
-
}
|
| 249 |
-
}
|
| 250 |
-
|
| 251 |
-
// Transitions across the left record edge are charged like interior ones: a
|
| 252 |
-
// start codon beginning at the first base is charged enter_gene[0] and a stop
|
| 253 |
-
// codon completed there is charged leave_gene[0]; every other first-base state
|
| 254 |
-
// is charged nothing.
|
| 255 |
static void initialize_first_base_scores(
|
| 256 |
-
const uint16_t* probability_bits, const
|
| 257 |
-
const
|
| 258 |
-
|
| 259 |
-
bool boundary_introns_enabled, AccumulatedScore* current_scores
|
| 260 |
) {
|
| 261 |
-
StepScore coding_score =
|
| 262 |
-
StepScore noncoding_score =
|
| 263 |
-
int base = bases[0];
|
| 264 |
-
|
| 265 |
for (int state = 0; state < STATE_COUNT; state++) {
|
| 266 |
-
current_scores[state] =
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
current_scores[exon_state_for_prefix(0)] = coding_score;
|
| 271 |
-
current_scores[exon_state_for_prefix(5)] = coding_score;
|
| 272 |
-
if (base == BASE_N) {
|
| 273 |
-
for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {
|
| 274 |
-
current_scores[exon_state_for_prefix(prefix_type)] = coding_score;
|
| 275 |
-
}
|
| 276 |
-
} else {
|
| 277 |
-
int one_base_prefix_type = base == BASE_T ? 1 : 2;
|
| 278 |
-
current_scores[exon_state_for_prefix(one_base_prefix_type)] = coding_score;
|
| 279 |
-
if (base == BASE_A) current_scores[exon_state_for_prefix(3)] = coding_score;
|
| 280 |
-
else if (base == BASE_G) current_scores[exon_state_for_prefix(4)] = coding_score;
|
| 281 |
-
}
|
| 282 |
-
if ((base_matches(base, BASE_A) && (stop_taa || stop_tga))
|
| 283 |
-
|| (base_matches(base, BASE_G) && stop_tag)) {
|
| 284 |
-
current_scores[STOP] = static_cast<AccumulatedScore>(coding_score)
|
| 285 |
-
+ transition_probabilities[LEAVE_GENE];
|
| 286 |
-
}
|
| 287 |
-
|
| 288 |
-
if (boundary_introns_enabled) {
|
| 289 |
-
current_scores[LEADING_BOUNDARY_INTRON] = noncoding_score;
|
| 290 |
-
}
|
| 291 |
-
|
| 292 |
-
bool second_start_base_matches = record_length == 1 || base_matches(bases[1], BASE_T);
|
| 293 |
-
bool third_start_base_matches = record_length <= 2 || base_matches(bases[2], BASE_G);
|
| 294 |
-
bool has_atg_start = base_matches(base, BASE_A)
|
| 295 |
-
&& second_start_base_matches
|
| 296 |
-
&& third_start_base_matches;
|
| 297 |
-
if (has_atg_start) {
|
| 298 |
-
current_scores[START_A] = static_cast<AccumulatedScore>(coding_score)
|
| 299 |
-
+ transition_probabilities[ENTER_GENE];
|
| 300 |
}
|
| 301 |
}
|
| 302 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
static void run_viterbi_forward(
|
| 304 |
const uint16_t* probability_bits, const int8_t* bases,
|
| 305 |
-
const StepScore*
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
int max_boundary_intron_length,
|
| 309 |
-
bool stop_taa, bool stop_tag, bool stop_tga,
|
| 310 |
-
int8_t* backpointers, AccumulatedScore* output_scores,
|
| 311 |
-
const AccumulatedScore* input_scores = nullptr
|
| 312 |
) {
|
| 313 |
AccumulatedScore current_buffer[STATE_COUNT];
|
| 314 |
AccumulatedScore next_buffer[STATE_COUNT];
|
| 315 |
AccumulatedScore* current_scores = current_buffer;
|
| 316 |
AccumulatedScore* next_scores = next_buffer;
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
|
|
|
|
|
|
| 324 |
);
|
| 325 |
-
} else {
|
| 326 |
-
for (int state = 0; state < STATE_COUNT; state++) {
|
| 327 |
-
current_scores[state] = input_scores[state];
|
| 328 |
-
}
|
| 329 |
-
}
|
| 330 |
-
|
| 331 |
-
for (int position = segment_start + 1; position <= segment_end; position++) {
|
| 332 |
-
int base = bases[position];
|
| 333 |
-
StepScore coding_score = coding_score_lookup[probability_bits[position]];
|
| 334 |
-
StepScore noncoding_score = noncoding_score_lookup[probability_bits[position]];
|
| 335 |
-
const StepScore* position_transition_probabilities =
|
| 336 |
-
transition_probabilities + static_cast<size_t>(position) * TRANSITION_COUNT;
|
| 337 |
-
|
| 338 |
-
// Missing motif bases at record edges are unknown. Internal positions
|
| 339 |
-
// still require the complete start, donor, or acceptor motif.
|
| 340 |
-
bool next_base_is_missing = position + 1 == record_length;
|
| 341 |
-
int next_base = next_base_is_missing ? -1 : bases[position + 1];
|
| 342 |
-
bool has_gt_ag_donor = base_matches(base, BASE_G)
|
| 343 |
-
&& (next_base_is_missing || base_matches(next_base, BASE_T));
|
| 344 |
-
bool has_gc_ag_donor = base_matches(base, BASE_G)
|
| 345 |
-
&& (next_base_is_missing || base_matches(next_base, BASE_C));
|
| 346 |
-
bool acceptor_first_base_matches = position == 1
|
| 347 |
-
|| base_matches(bases[position - 2], BASE_A);
|
| 348 |
-
bool has_ag_acceptor = acceptor_first_base_matches
|
| 349 |
-
&& base_matches(bases[position - 1], BASE_G);
|
| 350 |
-
bool has_ac_acceptor = acceptor_first_base_matches
|
| 351 |
-
&& base_matches(bases[position - 1], BASE_C);
|
| 352 |
-
bool third_start_base_matches = position + 2 >= record_length
|
| 353 |
-
|| base_matches(bases[position + 2], BASE_G);
|
| 354 |
-
bool has_atg_start = base_matches(base, BASE_A)
|
| 355 |
-
&& (next_base_is_missing || base_matches(next_base, BASE_T))
|
| 356 |
-
&& third_start_base_matches;
|
| 357 |
-
// Boundary guards require exact five-base patterns. N and missing
|
| 358 |
-
// edge context remain valid for ordinary motif matching only.
|
| 359 |
-
bool has_exact_acceptor_followed_by_atg = position >= 2
|
| 360 |
-
&& position + 2 < record_length
|
| 361 |
-
&& bases[position - 2] == BASE_A
|
| 362 |
-
&& (bases[position - 1] == BASE_G || bases[position - 1] == BASE_C)
|
| 363 |
-
&& base == BASE_A
|
| 364 |
-
&& next_base == BASE_T
|
| 365 |
-
&& bases[position + 2] == BASE_G;
|
| 366 |
-
bool has_at_ac_donor = base_matches(base, BASE_A)
|
| 367 |
-
&& (next_base_is_missing || base_matches(next_base, BASE_T));
|
| 368 |
-
bool has_any_donor = has_gt_ag_donor || has_gc_ag_donor || has_at_ac_donor;
|
| 369 |
-
bool has_exact_donor = position + 1 < record_length
|
| 370 |
-
&& ((base == BASE_G && (next_base == BASE_T || next_base == BASE_C))
|
| 371 |
-
|| (base == BASE_A && next_base == BASE_T));
|
| 372 |
-
bool has_exact_enabled_stop_followed_by_donor = false;
|
| 373 |
-
if (has_exact_donor && position >= 3) {
|
| 374 |
-
has_exact_enabled_stop_followed_by_donor = is_exact_enabled_stop_codon(
|
| 375 |
-
bases[position - 3], bases[position - 2], bases[position - 1],
|
| 376 |
-
stop_taa, stop_tag, stop_tga
|
| 377 |
-
);
|
| 378 |
-
}
|
| 379 |
-
// A leading self-loop into position makes its run position + 1 bases.
|
| 380 |
-
// A trailing entry here emits record_length - position bases through
|
| 381 |
-
// the right edge, so both limits follow directly from coordinates.
|
| 382 |
-
bool boundary_introns_enabled = max_boundary_intron_length != 0;
|
| 383 |
-
bool boundary_intron_length_is_unlimited = max_boundary_intron_length == -1;
|
| 384 |
-
bool can_extend_leading_boundary_intron =
|
| 385 |
-
boundary_introns_enabled
|
| 386 |
-
&& (boundary_intron_length_is_unlimited
|
| 387 |
-
|| position < max_boundary_intron_length);
|
| 388 |
-
bool can_enter_trailing_boundary_intron =
|
| 389 |
-
boundary_introns_enabled
|
| 390 |
-
&& (boundary_intron_length_is_unlimited
|
| 391 |
-
|| record_length - position <= max_boundary_intron_length);
|
| 392 |
-
|
| 393 |
-
int8_t local_predecessors[STATE_COUNT];
|
| 394 |
int8_t* predecessors = backpointers
|
| 395 |
-
? &backpointers[
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
// Intergenic, stop, and start-codon transitions.
|
| 405 |
-
if (current_scores[INTERGENIC] != UNREACHABLE_ACCUMULATED_SCORE) {
|
| 406 |
-
keep_best_transition(
|
| 407 |
-
next_scores, predecessors, INTERGENIC,
|
| 408 |
-
current_scores[INTERGENIC] + noncoding_score, INTERGENIC,
|
| 409 |
-
position_transition_probabilities
|
| 410 |
-
);
|
| 411 |
-
if (has_atg_start) {
|
| 412 |
-
keep_best_transition(
|
| 413 |
-
next_scores, predecessors, START_A,
|
| 414 |
-
current_scores[INTERGENIC] + coding_score,
|
| 415 |
-
INTERGENIC,
|
| 416 |
-
position_transition_probabilities
|
| 417 |
-
);
|
| 418 |
-
}
|
| 419 |
-
}
|
| 420 |
-
|
| 421 |
-
if (current_scores[STOP] != UNREACHABLE_ACCUMULATED_SCORE) {
|
| 422 |
-
keep_best_transition(
|
| 423 |
-
next_scores, predecessors, INTERGENIC,
|
| 424 |
-
current_scores[STOP] + noncoding_score, STOP,
|
| 425 |
-
position_transition_probabilities
|
| 426 |
-
);
|
| 427 |
-
}
|
| 428 |
-
|
| 429 |
-
if (current_scores[START_A] != UNREACHABLE_ACCUMULATED_SCORE) {
|
| 430 |
-
keep_best_transition(
|
| 431 |
-
next_scores, predecessors, START_AT,
|
| 432 |
-
current_scores[START_A] + coding_score, START_A,
|
| 433 |
-
position_transition_probabilities
|
| 434 |
-
);
|
| 435 |
-
}
|
| 436 |
-
if (current_scores[START_AT] != UNREACHABLE_ACCUMULATED_SCORE) {
|
| 437 |
-
keep_best_transition(
|
| 438 |
-
next_scores, predecessors, exon_state_for_prefix(0),
|
| 439 |
-
current_scores[START_AT] + coding_score, START_AT,
|
| 440 |
-
position_transition_probabilities
|
| 441 |
-
);
|
| 442 |
-
}
|
| 443 |
-
|
| 444 |
-
// Every prefix type is allowed when the leading boundary intron exits,
|
| 445 |
-
// so the state carries none. Only an exact acceptor followed by an
|
| 446 |
-
// exact ATG activates the guard; N leaves both paths available.
|
| 447 |
-
if (current_scores[LEADING_BOUNDARY_INTRON] != UNREACHABLE_ACCUMULATED_SCORE) {
|
| 448 |
-
if (can_extend_leading_boundary_intron) {
|
| 449 |
-
keep_best_transition(
|
| 450 |
-
next_scores, predecessors, LEADING_BOUNDARY_INTRON,
|
| 451 |
-
current_scores[LEADING_BOUNDARY_INTRON] + noncoding_score,
|
| 452 |
-
LEADING_BOUNDARY_INTRON,
|
| 453 |
-
position_transition_probabilities
|
| 454 |
-
);
|
| 455 |
-
}
|
| 456 |
-
bool can_exit_leading_intron =
|
| 457 |
-
(has_ag_acceptor || has_ac_acceptor)
|
| 458 |
-
&& !has_exact_acceptor_followed_by_atg;
|
| 459 |
-
if (can_exit_leading_intron) {
|
| 460 |
-
for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {
|
| 461 |
-
emit_coding_base(
|
| 462 |
-
current_scores, next_scores, predecessors,
|
| 463 |
-
LEADING_BOUNDARY_INTRON, prefix_type,
|
| 464 |
-
coding_score, position_transition_probabilities,
|
| 465 |
-
base, stop_taa, stop_tag, stop_tga
|
| 466 |
-
);
|
| 467 |
-
}
|
| 468 |
-
}
|
| 469 |
-
}
|
| 470 |
-
|
| 471 |
-
// Exons emit coding bases, open an ordinary internal intron, or enter
|
| 472 |
-
// the trailing state when the intron continues beyond the record.
|
| 473 |
-
for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {
|
| 474 |
-
int exon_state = exon_state_for_prefix(prefix_type);
|
| 475 |
-
AccumulatedScore exon_score = current_scores[exon_state];
|
| 476 |
-
if (exon_score == UNREACHABLE_ACCUMULATED_SCORE) continue;
|
| 477 |
-
|
| 478 |
-
emit_coding_base(
|
| 479 |
-
current_scores, next_scores, predecessors,
|
| 480 |
-
exon_state, prefix_type,
|
| 481 |
-
coding_score, position_transition_probabilities,
|
| 482 |
-
base, stop_taa, stop_tag, stop_tga
|
| 483 |
-
);
|
| 484 |
-
|
| 485 |
-
if (has_gt_ag_donor) {
|
| 486 |
-
keep_best_transition(
|
| 487 |
-
next_scores, predecessors,
|
| 488 |
-
GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 + prefix_type,
|
| 489 |
-
exon_score + noncoding_score + gt_ag_intron_score,
|
| 490 |
-
exon_state,
|
| 491 |
-
position_transition_probabilities
|
| 492 |
-
);
|
| 493 |
-
}
|
| 494 |
-
if (has_gc_ag_donor) {
|
| 495 |
-
keep_best_transition(
|
| 496 |
-
next_scores, predecessors,
|
| 497 |
-
GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 + prefix_type,
|
| 498 |
-
exon_score + noncoding_score + gc_ag_intron_score,
|
| 499 |
-
exon_state,
|
| 500 |
-
position_transition_probabilities
|
| 501 |
-
);
|
| 502 |
-
}
|
| 503 |
-
if (has_at_ac_donor) {
|
| 504 |
-
keep_best_transition(
|
| 505 |
-
next_scores, predecessors, AT_AC_INTRON_PREFIX_TYPE_0 + prefix_type,
|
| 506 |
-
exon_score + noncoding_score + at_ac_intron_score,
|
| 507 |
-
exon_state,
|
| 508 |
-
position_transition_probabilities
|
| 509 |
-
);
|
| 510 |
-
}
|
| 511 |
-
if (has_any_donor
|
| 512 |
-
&& !has_exact_enabled_stop_followed_by_donor
|
| 513 |
-
&& can_enter_trailing_boundary_intron) {
|
| 514 |
-
if (has_gt_ag_donor) {
|
| 515 |
-
keep_best_transition(
|
| 516 |
-
next_scores, predecessors, TRAILING_BOUNDARY_INTRON,
|
| 517 |
-
exon_score + noncoding_score + gt_ag_intron_score,
|
| 518 |
-
exon_state,
|
| 519 |
-
position_transition_probabilities
|
| 520 |
-
);
|
| 521 |
-
}
|
| 522 |
-
if (has_gc_ag_donor) {
|
| 523 |
-
keep_best_transition(
|
| 524 |
-
next_scores, predecessors, TRAILING_BOUNDARY_INTRON,
|
| 525 |
-
exon_score + noncoding_score + gc_ag_intron_score,
|
| 526 |
-
exon_state,
|
| 527 |
-
position_transition_probabilities
|
| 528 |
-
);
|
| 529 |
-
}
|
| 530 |
-
if (has_at_ac_donor) {
|
| 531 |
-
keep_best_transition(
|
| 532 |
-
next_scores, predecessors, TRAILING_BOUNDARY_INTRON,
|
| 533 |
-
exon_score + noncoding_score + at_ac_intron_score,
|
| 534 |
-
exon_state,
|
| 535 |
-
position_transition_probabilities
|
| 536 |
-
);
|
| 537 |
-
}
|
| 538 |
-
}
|
| 539 |
-
}
|
| 540 |
-
|
| 541 |
-
// FIRST consumes one additional base before AG exit is legal.
|
| 542 |
-
for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {
|
| 543 |
-
int intron_state = GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 + prefix_type;
|
| 544 |
-
if (current_scores[intron_state] == UNREACHABLE_ACCUMULATED_SCORE) continue;
|
| 545 |
-
keep_best_transition(
|
| 546 |
-
next_scores, predecessors,
|
| 547 |
-
GT_GC_AG_INTRON_READY_PREFIX_TYPE_0 + prefix_type,
|
| 548 |
-
current_scores[intron_state] + noncoding_score, intron_state,
|
| 549 |
-
position_transition_probabilities
|
| 550 |
-
);
|
| 551 |
-
}
|
| 552 |
-
|
| 553 |
-
// READY self-loops or exits a GT/GC-AG intron after AG.
|
| 554 |
-
for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {
|
| 555 |
-
int intron_state = GT_GC_AG_INTRON_READY_PREFIX_TYPE_0 + prefix_type;
|
| 556 |
-
if (current_scores[intron_state] == UNREACHABLE_ACCUMULATED_SCORE) continue;
|
| 557 |
-
keep_best_transition(
|
| 558 |
-
next_scores, predecessors, intron_state,
|
| 559 |
-
current_scores[intron_state] + noncoding_score, intron_state,
|
| 560 |
-
position_transition_probabilities
|
| 561 |
-
);
|
| 562 |
-
if (has_ag_acceptor) {
|
| 563 |
-
emit_coding_base(
|
| 564 |
-
current_scores, next_scores, predecessors,
|
| 565 |
-
intron_state, prefix_type,
|
| 566 |
-
coding_score, position_transition_probabilities,
|
| 567 |
-
base, stop_taa, stop_tag, stop_tga
|
| 568 |
-
);
|
| 569 |
-
}
|
| 570 |
-
}
|
| 571 |
-
|
| 572 |
-
// AT-AC introns self-loop or exit after AC.
|
| 573 |
-
for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {
|
| 574 |
-
int intron_state = AT_AC_INTRON_PREFIX_TYPE_0 + prefix_type;
|
| 575 |
-
if (current_scores[intron_state] == UNREACHABLE_ACCUMULATED_SCORE) continue;
|
| 576 |
-
keep_best_transition(
|
| 577 |
-
next_scores, predecessors, intron_state,
|
| 578 |
-
current_scores[intron_state] + noncoding_score, intron_state,
|
| 579 |
-
position_transition_probabilities
|
| 580 |
-
);
|
| 581 |
-
if (has_ac_acceptor) {
|
| 582 |
-
emit_coding_base(
|
| 583 |
-
current_scores, next_scores, predecessors,
|
| 584 |
-
intron_state, prefix_type,
|
| 585 |
-
coding_score, position_transition_probabilities,
|
| 586 |
-
base, stop_taa, stop_tag, stop_tga
|
| 587 |
-
);
|
| 588 |
-
}
|
| 589 |
-
}
|
| 590 |
-
|
| 591 |
-
// A trailing boundary intron cannot return to an exon.
|
| 592 |
-
if (current_scores[TRAILING_BOUNDARY_INTRON] != UNREACHABLE_ACCUMULATED_SCORE) {
|
| 593 |
-
keep_best_transition(
|
| 594 |
-
next_scores, predecessors, TRAILING_BOUNDARY_INTRON,
|
| 595 |
-
current_scores[TRAILING_BOUNDARY_INTRON] + noncoding_score,
|
| 596 |
-
TRAILING_BOUNDARY_INTRON,
|
| 597 |
-
position_transition_probabilities
|
| 598 |
);
|
|
|
|
|
|
|
| 599 |
}
|
| 600 |
|
| 601 |
-
|
| 602 |
-
current_scores = next_scores;
|
| 603 |
-
next_scores = previous_scores;
|
| 604 |
}
|
| 605 |
|
| 606 |
-
|
| 607 |
-
for (int state = 0; state < STATE_COUNT; state++) {
|
| 608 |
-
output_scores[state] = current_scores[state];
|
| 609 |
-
}
|
| 610 |
-
}
|
| 611 |
-
}
|
| 612 |
-
|
| 613 |
-
static int best_final_state(const AccumulatedScore* current_scores) {
|
| 614 |
-
int best_state = INTERGENIC;
|
| 615 |
-
for (int state = START_A; state <= STOP; state++) {
|
| 616 |
-
if (current_scores[state] > current_scores[best_state]) best_state = state;
|
| 617 |
-
}
|
| 618 |
-
if (current_scores[TRAILING_BOUNDARY_INTRON] > current_scores[best_state]) {
|
| 619 |
-
best_state = TRAILING_BOUNDARY_INTRON;
|
| 620 |
-
}
|
| 621 |
-
return best_state;
|
| 622 |
}
|
| 623 |
|
| 624 |
static void decode_one_track(
|
| 625 |
const uint16_t* probability_bits, const int8_t* bases,
|
| 626 |
-
const StepScore*
|
| 627 |
-
|
| 628 |
-
int max_boundary_intron_length,
|
| 629 |
-
bool stop_taa, bool stop_tag, bool stop_tga,
|
| 630 |
int64_t reconstruction_batch_size, int8_t* path,
|
| 631 |
std::vector<int8_t>& backpointer_buffer,
|
| 632 |
std::vector<AccumulatedScore>& checkpoints
|
| 633 |
) {
|
| 634 |
if (record_length <= 0) return;
|
| 635 |
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
probability_bits, bases, transition_probabilities, record_length, 0, record_length - 1, true,
|
| 641 |
-
gt_ag_intron_score, gc_ag_intron_score, at_ac_intron_score,
|
| 642 |
-
max_boundary_intron_length,
|
| 643 |
-
stop_taa, stop_tag, stop_tga,
|
| 644 |
-
backpointer_buffer.data(), final_scores
|
| 645 |
-
);
|
| 646 |
-
|
| 647 |
-
int state = best_final_state(final_scores);
|
| 648 |
-
for (int64_t position = record_length - 1; position >= 1; position--) {
|
| 649 |
-
path[position] = static_cast<int8_t>(state);
|
| 650 |
-
state = static_cast<int>(
|
| 651 |
-
backpointer_buffer[static_cast<size_t>(position - 1) * STATE_COUNT + state]
|
| 652 |
-
);
|
| 653 |
-
}
|
| 654 |
-
path[0] = static_cast<int8_t>(state);
|
| 655 |
-
return;
|
| 656 |
-
}
|
| 657 |
-
|
| 658 |
-
int64_t window_count = (
|
| 659 |
-
record_length - 1 + reconstruction_batch_size - 1
|
| 660 |
-
) / reconstruction_batch_size;
|
| 661 |
if (window_count < 1) window_count = 1;
|
| 662 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 663 |
|
| 664 |
-
//
|
| 665 |
-
AccumulatedScore
|
| 666 |
initialize_first_base_scores(
|
| 667 |
-
probability_bits,
|
| 668 |
-
stop_taa, stop_tag, stop_tga,
|
| 669 |
-
max_boundary_intron_length != 0,
|
| 670 |
-
current_scores
|
| 671 |
);
|
| 672 |
for (int64_t window = 0; window < window_count; window++) {
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
current_scores[state];
|
| 676 |
-
}
|
| 677 |
-
int64_t segment_start = window * reconstruction_batch_size;
|
| 678 |
-
int64_t segment_end = segment_start + reconstruction_batch_size;
|
| 679 |
-
if (segment_end > record_length - 1) segment_end = record_length - 1;
|
| 680 |
run_viterbi_forward(
|
| 681 |
-
probability_bits, bases,
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
max_boundary_intron_length,
|
| 685 |
-
stop_taa, stop_tag, stop_tga,
|
| 686 |
-
nullptr, current_scores, current_scores
|
| 687 |
);
|
| 688 |
}
|
| 689 |
-
for (int state = 0; state < STATE_COUNT; state++) {
|
| 690 |
-
checkpoints[static_cast<size_t>(window_count) * STATE_COUNT + state] =
|
| 691 |
-
current_scores[state];
|
| 692 |
-
}
|
| 693 |
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
// Recompute one window at a time and immediately backtrace it.
|
| 697 |
for (int64_t window = window_count - 1; window >= 0; window--) {
|
| 698 |
-
int64_t
|
| 699 |
-
int64_t
|
| 700 |
-
if (
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
for (int64_t position =
|
| 711 |
path[position] = static_cast<int8_t>(state);
|
| 712 |
-
state = static_cast<int>(
|
| 713 |
-
static_cast<size_t>(position -
|
| 714 |
-
|
| 715 |
}
|
| 716 |
}
|
| 717 |
path[0] = static_cast<int8_t>(state);
|
|
@@ -719,7 +153,7 @@ static void decode_one_track(
|
|
| 719 |
|
| 720 |
extern "C" void decode_batch_on_cpu(
|
| 721 |
const uint16_t* probability_bits, const int8_t* bases,
|
| 722 |
-
const StepScore*
|
| 723 |
const int64_t* record_offsets, int record_count,
|
| 724 |
int stop_taa, int stop_tag, int stop_tga,
|
| 725 |
double gt_ag_intron_log_prior, double gc_ag_intron_log_prior,
|
|
@@ -727,12 +161,19 @@ extern "C" void decode_batch_on_cpu(
|
|
| 727 |
int max_boundary_intron_length,
|
| 728 |
int64_t requested_reconstruction_batch_size, int8_t* output_paths
|
| 729 |
) {
|
| 730 |
-
static const bool
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 736 |
int64_t reconstruction_batch_size = requested_reconstruction_batch_size == 0
|
| 737 |
? DEFAULT_RECONSTRUCTION_BATCH_SIZE
|
| 738 |
: requested_reconstruction_batch_size;
|
|
@@ -744,14 +185,11 @@ extern "C" void decode_batch_on_cpu(
|
|
| 744 |
#pragma omp for schedule(dynamic, 1)
|
| 745 |
for (int record = 0; record < record_count; record++) {
|
| 746 |
int64_t offset = record_offsets[record];
|
| 747 |
-
|
| 748 |
decode_one_track(
|
| 749 |
probability_bits + offset, bases + offset,
|
| 750 |
-
|
| 751 |
-
record_length,
|
| 752 |
-
gt_ag_intron_score, gc_ag_intron_score, at_ac_intron_score,
|
| 753 |
-
max_boundary_intron_length,
|
| 754 |
-
stop_taa != 0, stop_tag != 0, stop_tga != 0,
|
| 755 |
reconstruction_batch_size, output_paths + offset,
|
| 756 |
backpointer_buffer, checkpoints
|
| 757 |
);
|
|
@@ -766,7 +204,7 @@ namespace py = pybind11;
|
|
| 766 |
|
| 767 |
static py::array_t<int8_t> decode_packed_paths(
|
| 768 |
py::array_t<unsigned short> probability_array, py::array_t<int8_t> encoded_bases,
|
| 769 |
-
py::array_t<StepScore>
|
| 770 |
py::array_t<int64_t> record_offsets_array,
|
| 771 |
int stop_taa, int stop_tag, int stop_tga,
|
| 772 |
double gt_ag_intron_log_prior, double gc_ag_intron_log_prior,
|
|
@@ -774,23 +212,24 @@ static py::array_t<int8_t> decode_packed_paths(
|
|
| 774 |
int max_boundary_intron_length,
|
| 775 |
int64_t reconstruction_batch_size
|
| 776 |
) {
|
| 777 |
-
if (
|
| 778 |
throw std::invalid_argument(
|
| 779 |
-
"transition
|
| 780 |
);
|
| 781 |
}
|
| 782 |
int record_count = static_cast<int>(record_offsets_array.size()) - 1;
|
| 783 |
auto state_paths = py::array_t<int8_t>(encoded_bases.size());
|
| 784 |
const uint16_t* probability_bits = probability_array.data();
|
| 785 |
const int8_t* base_data = encoded_bases.data();
|
| 786 |
-
const StepScore*
|
| 787 |
const int64_t* record_offsets = record_offsets_array.data();
|
| 788 |
int8_t* output_paths = state_paths.mutable_data();
|
| 789 |
{
|
| 790 |
-
//
|
|
|
|
| 791 |
py::gil_scoped_release release;
|
| 792 |
decode_batch_on_cpu(
|
| 793 |
-
probability_bits, base_data,
|
| 794 |
stop_taa, stop_tag, stop_tga,
|
| 795 |
gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,
|
| 796 |
max_boundary_intron_length,
|
|
@@ -801,6 +240,6 @@ static py::array_t<int8_t> decode_packed_paths(
|
|
| 801 |
}
|
| 802 |
|
| 803 |
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 804 |
-
m.def("decode", &decode_packed_paths, "
|
| 805 |
}
|
| 806 |
#endif
|
|
|
|
| 1 |
+
// viterbi_cpu.cpp -- CPU Viterbi backend (C++/OpenMP).
|
| 2 |
//
|
| 3 |
+
// The grammar comes from viterbi_grammar.h. OpenMP threads decode records in
|
| 4 |
+
// parallel, one record per thread at a time. For each base the recursion asks
|
| 5 |
+
// best_transition_to_state for all 30 targets; path scores are int64 and are
|
| 6 |
+
// never renormalized, so no state is dropped for falling behind the best one.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
//
|
| 8 |
+
// A record is decoded in windows of reconstruction_batch_size bases, in two
|
| 9 |
+
// passes. The forward pass runs the recursion over the whole record, keeps the
|
| 10 |
+
// 30 path scores at the first base of every window, and records backpointers
|
| 11 |
+
// in the last window only. The backward pass visits the windows from last to
|
| 12 |
+
// first: it reruns the recursion over every window but the last from the
|
| 13 |
+
// window's scores, recording backpointers, and traces the path through the
|
| 14 |
+
// window from the state chosen at its right end. Backpointer memory is one
|
| 15 |
+
// window whatever the record length, and a record of one window takes one
|
| 16 |
+
// pass.
|
| 17 |
+
#include <algorithm>
|
| 18 |
#include <cstdint>
|
|
|
|
|
|
|
| 19 |
#include <stdexcept>
|
| 20 |
+
#include <utility>
|
| 21 |
#include <vector>
|
|
|
|
| 22 |
|
| 23 |
+
#include "viterbi_grammar.h"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
static const int64_t DEFAULT_RECONSTRUCTION_BATCH_SIZE = 8'000'000;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
static StepScore coding_score_table[EMISSION_TABLE_SIZE];
|
| 28 |
+
static StepScore noncoding_score_table[EMISSION_TABLE_SIZE];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
// The 30 path scores at base 0 of a record.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
static void initialize_first_base_scores(
|
| 32 |
+
const uint16_t* probability_bits, const int8_t* bases,
|
| 33 |
+
const StepScore* transition_log_odds, int64_t record_length,
|
| 34 |
+
const ViterbiConfig& config, AccumulatedScore* current_scores
|
|
|
|
| 35 |
) {
|
| 36 |
+
StepScore coding_score = coding_score_table[probability_bits[0]];
|
| 37 |
+
StepScore noncoding_score = noncoding_score_table[probability_bits[0]];
|
|
|
|
|
|
|
| 38 |
for (int state = 0; state < STATE_COUNT; state++) {
|
| 39 |
+
current_scores[state] = first_base_score<AccumulatedScore>(
|
| 40 |
+
state, bases, 0, record_length, coding_score, noncoding_score,
|
| 41 |
+
transition_log_odds, config
|
| 42 |
+
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
}
|
| 44 |
}
|
| 45 |
|
| 46 |
+
// Runs the recursion from base start to base end of a record. scores holds
|
| 47 |
+
// the 30 path scores at start on entry and those at end on return. With
|
| 48 |
+
// backpointers, row p - start - 1 receives the best predecessor of every state
|
| 49 |
+
// at base p.
|
| 50 |
static void run_viterbi_forward(
|
| 51 |
const uint16_t* probability_bits, const int8_t* bases,
|
| 52 |
+
const StepScore* transition_log_odds, int64_t record_length,
|
| 53 |
+
int64_t start, int64_t end, const ViterbiConfig& config,
|
| 54 |
+
AccumulatedScore* scores, int8_t* backpointers
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
) {
|
| 56 |
AccumulatedScore current_buffer[STATE_COUNT];
|
| 57 |
AccumulatedScore next_buffer[STATE_COUNT];
|
| 58 |
AccumulatedScore* current_scores = current_buffer;
|
| 59 |
AccumulatedScore* next_scores = next_buffer;
|
| 60 |
+
std::copy(scores, scores + STATE_COUNT, current_scores);
|
| 61 |
+
|
| 62 |
+
for (int64_t position = start + 1; position <= end; position++) {
|
| 63 |
+
PositionSignals signals = compute_position_signals(
|
| 64 |
+
bases, 0, record_length, position,
|
| 65 |
+
coding_score_table[probability_bits[position]],
|
| 66 |
+
noncoding_score_table[probability_bits[position]],
|
| 67 |
+
transition_log_odds + position * TRANSITION_COUNT,
|
| 68 |
+
config
|
| 69 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
int8_t* predecessors = backpointers
|
| 71 |
+
? &backpointers[static_cast<size_t>(position - start - 1) * STATE_COUNT]
|
| 72 |
+
: nullptr;
|
| 73 |
+
#if defined(__GNUC__)
|
| 74 |
+
#pragma GCC unroll 30
|
| 75 |
+
#endif
|
| 76 |
+
for (int target_state = 0; target_state < STATE_COUNT; target_state++) {
|
| 77 |
+
TransitionChoice<AccumulatedScore> best = best_transition_to_state(
|
| 78 |
+
target_state, current_scores, signals, config
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
);
|
| 80 |
+
next_scores[target_state] = best.score;
|
| 81 |
+
if (predecessors) predecessors[target_state] = static_cast<int8_t>(best.source_state);
|
| 82 |
}
|
| 83 |
|
| 84 |
+
std::swap(current_scores, next_scores);
|
|
|
|
|
|
|
| 85 |
}
|
| 86 |
|
| 87 |
+
std::copy(current_scores, current_scores + STATE_COUNT, scores);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
}
|
| 89 |
|
| 90 |
static void decode_one_track(
|
| 91 |
const uint16_t* probability_bits, const int8_t* bases,
|
| 92 |
+
const StepScore* transition_log_odds, int64_t record_length,
|
| 93 |
+
const ViterbiConfig& config,
|
|
|
|
|
|
|
| 94 |
int64_t reconstruction_batch_size, int8_t* path,
|
| 95 |
std::vector<int8_t>& backpointer_buffer,
|
| 96 |
std::vector<AccumulatedScore>& checkpoints
|
| 97 |
) {
|
| 98 |
if (record_length <= 0) return;
|
| 99 |
|
| 100 |
+
// Window w runs the recursion from base w * reconstruction_batch_size to
|
| 101 |
+
// the first base of window w + 1, or to the record's last base.
|
| 102 |
+
const int64_t last_base = record_length - 1;
|
| 103 |
+
int64_t window_count = (last_base + reconstruction_batch_size - 1) / reconstruction_batch_size;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
if (window_count < 1) window_count = 1;
|
| 105 |
+
auto window_start = [&](int64_t window) { return window * reconstruction_batch_size; };
|
| 106 |
+
auto window_end = [&](int64_t window) {
|
| 107 |
+
return std::min(window_start(window) + reconstruction_batch_size, last_base);
|
| 108 |
+
};
|
| 109 |
+
checkpoints.resize(static_cast<size_t>(window_count) * STATE_COUNT);
|
| 110 |
+
backpointer_buffer.resize(
|
| 111 |
+
static_cast<size_t>(std::min(reconstruction_batch_size, last_base)) * STATE_COUNT
|
| 112 |
+
);
|
| 113 |
|
| 114 |
+
// Forward pass.
|
| 115 |
+
AccumulatedScore scores[STATE_COUNT];
|
| 116 |
initialize_first_base_scores(
|
| 117 |
+
probability_bits, bases, transition_log_odds, record_length, config, scores
|
|
|
|
|
|
|
|
|
|
| 118 |
);
|
| 119 |
for (int64_t window = 0; window < window_count; window++) {
|
| 120 |
+
std::copy(scores, scores + STATE_COUNT, &checkpoints[static_cast<size_t>(window) * STATE_COUNT]);
|
| 121 |
+
const bool is_last_window = window == window_count - 1;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
run_viterbi_forward(
|
| 123 |
+
probability_bits, bases, transition_log_odds, record_length,
|
| 124 |
+
window_start(window), window_end(window), config,
|
| 125 |
+
scores, is_last_window ? backpointer_buffer.data() : nullptr
|
|
|
|
|
|
|
|
|
|
| 126 |
);
|
| 127 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
// Backward pass.
|
| 130 |
+
int state = best_final_state(scores);
|
|
|
|
| 131 |
for (int64_t window = window_count - 1; window >= 0; window--) {
|
| 132 |
+
const int64_t start = window_start(window);
|
| 133 |
+
const int64_t end = window_end(window);
|
| 134 |
+
if (window < window_count - 1) {
|
| 135 |
+
std::copy(
|
| 136 |
+
&checkpoints[static_cast<size_t>(window) * STATE_COUNT],
|
| 137 |
+
&checkpoints[static_cast<size_t>(window + 1) * STATE_COUNT], scores
|
| 138 |
+
);
|
| 139 |
+
run_viterbi_forward(
|
| 140 |
+
probability_bits, bases, transition_log_odds, record_length,
|
| 141 |
+
start, end, config, scores, backpointer_buffer.data()
|
| 142 |
+
);
|
| 143 |
+
}
|
| 144 |
+
for (int64_t position = end; position > start; position--) {
|
| 145 |
path[position] = static_cast<int8_t>(state);
|
| 146 |
+
state = static_cast<int>(
|
| 147 |
+
backpointer_buffer[static_cast<size_t>(position - start - 1) * STATE_COUNT + state]
|
| 148 |
+
);
|
| 149 |
}
|
| 150 |
}
|
| 151 |
path[0] = static_cast<int8_t>(state);
|
|
|
|
| 153 |
|
| 154 |
extern "C" void decode_batch_on_cpu(
|
| 155 |
const uint16_t* probability_bits, const int8_t* bases,
|
| 156 |
+
const StepScore* transition_log_odds,
|
| 157 |
const int64_t* record_offsets, int record_count,
|
| 158 |
int stop_taa, int stop_tag, int stop_tga,
|
| 159 |
double gt_ag_intron_log_prior, double gc_ag_intron_log_prior,
|
|
|
|
| 161 |
int max_boundary_intron_length,
|
| 162 |
int64_t requested_reconstruction_batch_size, int8_t* output_paths
|
| 163 |
) {
|
| 164 |
+
static const bool emission_tables_ready = [] {
|
| 165 |
+
build_emission_score_tables(coding_score_table, noncoding_score_table);
|
| 166 |
+
return true;
|
| 167 |
+
}();
|
| 168 |
+
(void)emission_tables_ready;
|
| 169 |
+
|
| 170 |
+
const ViterbiConfig config = {
|
| 171 |
+
stop_taa != 0, stop_tag != 0, stop_tga != 0,
|
| 172 |
+
score_from_nats(gt_ag_intron_log_prior),
|
| 173 |
+
score_from_nats(gc_ag_intron_log_prior),
|
| 174 |
+
score_from_nats(at_ac_intron_log_prior),
|
| 175 |
+
max_boundary_intron_length,
|
| 176 |
+
};
|
| 177 |
int64_t reconstruction_batch_size = requested_reconstruction_batch_size == 0
|
| 178 |
? DEFAULT_RECONSTRUCTION_BATCH_SIZE
|
| 179 |
: requested_reconstruction_batch_size;
|
|
|
|
| 185 |
#pragma omp for schedule(dynamic, 1)
|
| 186 |
for (int record = 0; record < record_count; record++) {
|
| 187 |
int64_t offset = record_offsets[record];
|
| 188 |
+
int64_t record_length = record_offsets[record + 1] - offset;
|
| 189 |
decode_one_track(
|
| 190 |
probability_bits + offset, bases + offset,
|
| 191 |
+
transition_log_odds + static_cast<size_t>(offset) * TRANSITION_COUNT,
|
| 192 |
+
record_length, config,
|
|
|
|
|
|
|
|
|
|
| 193 |
reconstruction_batch_size, output_paths + offset,
|
| 194 |
backpointer_buffer, checkpoints
|
| 195 |
);
|
|
|
|
| 204 |
|
| 205 |
static py::array_t<int8_t> decode_packed_paths(
|
| 206 |
py::array_t<unsigned short> probability_array, py::array_t<int8_t> encoded_bases,
|
| 207 |
+
py::array_t<StepScore> transition_log_odds,
|
| 208 |
py::array_t<int64_t> record_offsets_array,
|
| 209 |
int stop_taa, int stop_tag, int stop_tga,
|
| 210 |
double gt_ag_intron_log_prior, double gc_ag_intron_log_prior,
|
|
|
|
| 212 |
int max_boundary_intron_length,
|
| 213 |
int64_t reconstruction_batch_size
|
| 214 |
) {
|
| 215 |
+
if (transition_log_odds.size() != encoded_bases.size() * TRANSITION_COUNT) {
|
| 216 |
throw std::invalid_argument(
|
| 217 |
+
"transition log-odds must contain four values per encoded base"
|
| 218 |
);
|
| 219 |
}
|
| 220 |
int record_count = static_cast<int>(record_offsets_array.size()) - 1;
|
| 221 |
auto state_paths = py::array_t<int8_t>(encoded_bases.size());
|
| 222 |
const uint16_t* probability_bits = probability_array.data();
|
| 223 |
const int8_t* base_data = encoded_bases.data();
|
| 224 |
+
const StepScore* transition_log_odds_data = transition_log_odds.data();
|
| 225 |
const int64_t* record_offsets = record_offsets_array.data();
|
| 226 |
int8_t* output_paths = state_paths.mutable_data();
|
| 227 |
{
|
| 228 |
+
// The batch is decoded without the GIL, so the Python reader can prepare
|
| 229 |
+
// the next input chunk meanwhile.
|
| 230 |
py::gil_scoped_release release;
|
| 231 |
decode_batch_on_cpu(
|
| 232 |
+
probability_bits, base_data, transition_log_odds_data, record_offsets, record_count,
|
| 233 |
stop_taa, stop_tag, stop_tga,
|
| 234 |
gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,
|
| 235 |
max_boundary_intron_length,
|
|
|
|
| 240 |
}
|
| 241 |
|
| 242 |
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 243 |
+
m.def("decode", &decode_packed_paths, "Run Viterbi on a batch of tracks");
|
| 244 |
}
|
| 245 |
#endif
|
annotation_pipeline/src/viterbi_backends/{decode_cpu.py → viterbi_cpu.py}
RENAMED
|
@@ -3,11 +3,11 @@
|
|
| 3 |
The C++ extension is JIT-compiled by torch.utils.cpp_extension.load on first
|
| 4 |
use and cached under ~/.cache/torch_extensions. Tasks are
|
| 5 |
``(P(CDS), encoded_bases)`` pairs; every task is accompanied by a
|
| 6 |
-
``(bases, 4)`` array holding the transition network's log-odds against
|
| 7 |
-
for the four permitted transitions, in
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
"""
|
| 12 |
import os
|
| 13 |
import sys
|
|
@@ -22,8 +22,9 @@ from constants import (
|
|
| 22 |
MAX_BOUNDARY_INTRON_LENGTH_BP,
|
| 23 |
)
|
| 24 |
from utils import (
|
|
|
|
| 25 |
prepare_decode_tasks,
|
| 26 |
-
|
| 27 |
validate_max_boundary_intron_length,
|
| 28 |
validate_reconstruction_batch_size,
|
| 29 |
)
|
|
@@ -62,7 +63,7 @@ def available():
|
|
| 62 |
|
| 63 |
def decode_paths(
|
| 64 |
tasks,
|
| 65 |
-
|
| 66 |
stop_taa=True, stop_tag=True, stop_tga=True,
|
| 67 |
gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,
|
| 68 |
gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,
|
|
@@ -72,33 +73,24 @@ def decode_paths(
|
|
| 72 |
):
|
| 73 |
"""Decode probability/base tasks with the CPU Viterbi backend.
|
| 74 |
|
| 75 |
-
``
|
| 76 |
-
|
| 77 |
``reconstruction_batch_size`` is the number of bases processed together
|
| 78 |
during final path reconstruction. ``None`` uses the backend default.
|
| 79 |
"""
|
| 80 |
max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)
|
| 81 |
reconstruction_batch_size = validate_reconstruction_batch_size(reconstruction_batch_size)
|
| 82 |
tasks = prepare_decode_tasks(tasks)
|
| 83 |
-
|
| 84 |
if not tasks:
|
| 85 |
return []
|
| 86 |
module = _load()
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
record_offsets[index + 1] = record_offsets[index] + len(encoded_bases)
|
| 90 |
-
|
| 91 |
-
probability_bits = np.ascontiguousarray(
|
| 92 |
-
np.concatenate([np.asarray(probabilities, np.float16) for probabilities, _ in tasks])
|
| 93 |
-
).view(np.uint16)
|
| 94 |
-
encoded_bases = np.ascontiguousarray(
|
| 95 |
-
np.concatenate([np.asarray(bases, np.int8) for _, bases in tasks]),
|
| 96 |
-
dtype=np.int8,
|
| 97 |
)
|
| 98 |
-
packed_transition_probabilities = np.ascontiguousarray(np.concatenate(transition_probabilities), dtype=np.int32)
|
| 99 |
combined_path = np.asarray(
|
| 100 |
module.decode(
|
| 101 |
-
probability_bits, encoded_bases,
|
| 102 |
int(stop_taa), int(stop_tag), int(stop_tga),
|
| 103 |
float(gt_ag_intron_log_prior), float(gc_ag_intron_log_prior),
|
| 104 |
float(at_ac_intron_log_prior),
|
|
@@ -106,7 +98,4 @@ def decode_paths(
|
|
| 106 |
0 if reconstruction_batch_size is None else reconstruction_batch_size,
|
| 107 |
)
|
| 108 |
)
|
| 109 |
-
return [
|
| 110 |
-
combined_path[int(record_offsets[index]):int(record_offsets[index + 1])]
|
| 111 |
-
for index in range(len(tasks))
|
| 112 |
-
]
|
|
|
|
| 3 |
The C++ extension is JIT-compiled by torch.utils.cpp_extension.load on first
|
| 4 |
use and cached under ~/.cache/torch_extensions. Tasks are
|
| 5 |
``(P(CDS), encoded_bases)`` pairs; every task is accompanied by a
|
| 6 |
+
``(bases, 4)`` int32 array holding the transition network's log-odds against
|
| 7 |
+
staying for the four permitted transitions, in the kernel's fixed-point units
|
| 8 |
+
(``utils.quantize_transition_log_odds``). Stop codons, all three intron-class
|
| 9 |
+
priors, and the boundary-intron length limit are explicit across every
|
| 10 |
+
Viterbi backend.
|
| 11 |
"""
|
| 12 |
import os
|
| 13 |
import sys
|
|
|
|
| 22 |
MAX_BOUNDARY_INTRON_LENGTH_BP,
|
| 23 |
)
|
| 24 |
from utils import (
|
| 25 |
+
pack_decode_tasks,
|
| 26 |
prepare_decode_tasks,
|
| 27 |
+
prepare_transition_log_odds,
|
| 28 |
validate_max_boundary_intron_length,
|
| 29 |
validate_reconstruction_batch_size,
|
| 30 |
)
|
|
|
|
| 63 |
|
| 64 |
def decode_paths(
|
| 65 |
tasks,
|
| 66 |
+
transition_log_odds,
|
| 67 |
stop_taa=True, stop_tag=True, stop_tga=True,
|
| 68 |
gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,
|
| 69 |
gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,
|
|
|
|
| 73 |
):
|
| 74 |
"""Decode probability/base tasks with the CPU Viterbi backend.
|
| 75 |
|
| 76 |
+
``transition_log_odds`` holds one ``(bases, 4)`` int32 array per task of
|
| 77 |
+
fixed-point log-odds in ``TRANSITION_NAMES`` column order.
|
| 78 |
``reconstruction_batch_size`` is the number of bases processed together
|
| 79 |
during final path reconstruction. ``None`` uses the backend default.
|
| 80 |
"""
|
| 81 |
max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)
|
| 82 |
reconstruction_batch_size = validate_reconstruction_batch_size(reconstruction_batch_size)
|
| 83 |
tasks = prepare_decode_tasks(tasks)
|
| 84 |
+
transition_log_odds = prepare_transition_log_odds(transition_log_odds, tasks)
|
| 85 |
if not tasks:
|
| 86 |
return []
|
| 87 |
module = _load()
|
| 88 |
+
probability_bits, encoded_bases, transition_scores, record_offsets = pack_decode_tasks(
|
| 89 |
+
tasks, transition_log_odds
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
)
|
|
|
|
| 91 |
combined_path = np.asarray(
|
| 92 |
module.decode(
|
| 93 |
+
probability_bits, encoded_bases, transition_scores, record_offsets,
|
| 94 |
int(stop_taa), int(stop_tag), int(stop_tga),
|
| 95 |
float(gt_ag_intron_log_prior), float(gc_ag_intron_log_prior),
|
| 96 |
float(at_ac_intron_log_prior),
|
|
|
|
| 98 |
0 if reconstruction_batch_size is None else reconstruction_batch_size,
|
| 99 |
)
|
| 100 |
)
|
| 101 |
+
return np.split(combined_path, record_offsets[1:-1])
|
|
|
|
|
|
|
|
|
annotation_pipeline/src/viterbi_backends/viterbi_gpu.cu
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
annotation_pipeline/src/viterbi_backends/{decode_gpu.py → viterbi_gpu.py}
RENAMED
|
@@ -2,15 +2,16 @@
|
|
| 2 |
|
| 3 |
The CUDA extension is JIT-compiled by torch.utils.cpp_extension.load on first
|
| 4 |
use. Tasks are ``(P(CDS), encoded_bases)`` pairs; every task is accompanied by
|
| 5 |
-
a ``(bases, 4)`` array holding the transition network's log-odds against
|
| 6 |
-
staying for the four permitted transitions, in
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
decode_paths
|
| 12 |
-
|
| 13 |
-
|
|
|
|
| 14 |
"""
|
| 15 |
import os
|
| 16 |
import sys
|
|
@@ -21,18 +22,18 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
| 21 |
from constants import (
|
| 22 |
AT_AC_INTRON_LOG_PRIOR,
|
| 23 |
GC_AG_INTRON_LOG_PRIOR,
|
| 24 |
-
GPU_ESTIMATED_BYTES_PER_BASE,
|
| 25 |
-
GPU_MAX_BATCH_BASES,
|
| 26 |
GPU_MEMORY_FRACTION,
|
| 27 |
-
|
| 28 |
GPU_SEGMENT_LENGTH,
|
| 29 |
GT_AG_INTRON_LOG_PRIOR,
|
| 30 |
MAX_BOUNDARY_INTRON_LENGTH_BP,
|
| 31 |
)
|
| 32 |
from utils import (
|
|
|
|
| 33 |
prepare_decode_tasks,
|
| 34 |
-
|
| 35 |
validate_max_boundary_intron_length,
|
|
|
|
| 36 |
validate_reconstruction_batch_size,
|
| 37 |
)
|
| 38 |
|
|
@@ -67,71 +68,33 @@ def available():
|
|
| 67 |
return False, f"{type(exc).__name__}: {exc}"
|
| 68 |
|
| 69 |
|
| 70 |
-
def batch_base_budget(free_bytes):
|
| 71 |
-
"""Return a VRAM-based sub-batch size that also fits CUDA int32 indexing."""
|
| 72 |
-
memory_budget = max(
|
| 73 |
-
GPU_MIN_BATCH_BASES,
|
| 74 |
-
int(free_bytes * GPU_MEMORY_FRACTION / GPU_ESTIMATED_BYTES_PER_BASE),
|
| 75 |
-
)
|
| 76 |
-
return min(memory_budget, GPU_MAX_BATCH_BASES)
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
def _decode_batch(module, tasks, transition_probabilities, reconstruction_batch_size):
|
| 80 |
-
"""Pack and decode one GPU sub-batch."""
|
| 81 |
-
record_offsets = np.zeros(len(tasks) + 1, np.int64)
|
| 82 |
-
for index, (_, encoded_bases) in enumerate(tasks):
|
| 83 |
-
record_offsets[index + 1] = record_offsets[index] + len(encoded_bases)
|
| 84 |
-
|
| 85 |
-
probability_bits = np.ascontiguousarray(
|
| 86 |
-
np.concatenate([np.asarray(probabilities, np.float16) for probabilities, _ in tasks])
|
| 87 |
-
).view(np.uint16)
|
| 88 |
-
encoded_bases = np.ascontiguousarray(
|
| 89 |
-
np.concatenate([np.asarray(bases, np.int8) for _, bases in tasks]),
|
| 90 |
-
dtype=np.int8,
|
| 91 |
-
)
|
| 92 |
-
packed_transition_probabilities = np.ascontiguousarray(np.concatenate(transition_probabilities), dtype=np.int32)
|
| 93 |
-
combined_path = np.asarray(
|
| 94 |
-
module.decode(
|
| 95 |
-
probability_bits, encoded_bases, packed_transition_probabilities, record_offsets,
|
| 96 |
-
GPU_SEGMENT_LENGTH,
|
| 97 |
-
0 if reconstruction_batch_size is None else reconstruction_batch_size,
|
| 98 |
-
)
|
| 99 |
-
)
|
| 100 |
-
return [
|
| 101 |
-
combined_path[int(record_offsets[index]):int(record_offsets[index + 1])]
|
| 102 |
-
for index in range(len(tasks))
|
| 103 |
-
]
|
| 104 |
-
|
| 105 |
-
|
| 106 |
def decode_paths(
|
| 107 |
tasks,
|
| 108 |
-
|
| 109 |
stop_taa=True, stop_tag=True, stop_tga=True,
|
| 110 |
gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,
|
| 111 |
gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,
|
| 112 |
at_ac_intron_log_prior=AT_AC_INTRON_LOG_PRIOR,
|
| 113 |
max_boundary_intron_length=MAX_BOUNDARY_INTRON_LENGTH_BP,
|
| 114 |
reconstruction_batch_size=None,
|
|
|
|
| 115 |
):
|
| 116 |
"""Decode probability/base tasks with the GPU Viterbi backend.
|
| 117 |
|
| 118 |
-
``
|
| 119 |
-
|
| 120 |
-
``reconstruction_batch_size`` is the number of bases
|
| 121 |
-
|
|
|
|
|
|
|
| 122 |
"""
|
| 123 |
max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)
|
| 124 |
reconstruction_batch_size = validate_reconstruction_batch_size(reconstruction_batch_size)
|
|
|
|
| 125 |
tasks = prepare_decode_tasks(tasks)
|
| 126 |
-
|
| 127 |
if not tasks:
|
| 128 |
return []
|
| 129 |
-
for _, encoded_bases in tasks:
|
| 130 |
-
if len(encoded_bases) > GPU_MAX_BATCH_BASES:
|
| 131 |
-
raise ValueError(
|
| 132 |
-
f"one GPU Viterbi backend record has {len(encoded_bases)} bases; "
|
| 133 |
-
f"the maximum supported length is {GPU_MAX_BATCH_BASES}"
|
| 134 |
-
)
|
| 135 |
import torch
|
| 136 |
|
| 137 |
module = _load()
|
|
@@ -141,27 +104,20 @@ def decode_paths(
|
|
| 141 |
float(at_ac_intron_log_prior),
|
| 142 |
int(max_boundary_intron_length),
|
| 143 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
next_record_bases = len(tasks[batch_end][1])
|
| 155 |
-
if batch_end > batch_start and batch_bases + next_record_bases > base_budget:
|
| 156 |
-
break
|
| 157 |
-
batch_bases += next_record_bases
|
| 158 |
-
batch_end += 1
|
| 159 |
-
|
| 160 |
-
decoded_paths.extend(
|
| 161 |
-
_decode_batch(
|
| 162 |
-
module, tasks[batch_start:batch_end],
|
| 163 |
-
transition_probabilities[batch_start:batch_end], reconstruction_batch_size,
|
| 164 |
-
)
|
| 165 |
)
|
| 166 |
-
|
| 167 |
-
return
|
|
|
|
| 2 |
|
| 3 |
The CUDA extension is JIT-compiled by torch.utils.cpp_extension.load on first
|
| 4 |
use. Tasks are ``(P(CDS), encoded_bases)`` pairs; every task is accompanied by
|
| 5 |
+
a ``(bases, 4)`` int32 array holding the transition network's log-odds against
|
| 6 |
+
staying for the four permitted transitions, in the kernel's fixed-point units
|
| 7 |
+
(``utils.quantize_transition_log_odds``). Stop codons, all three intron-class
|
| 8 |
+
priors, and the boundary-intron length limit are explicit across every
|
| 9 |
+
Viterbi backend.
|
| 10 |
+
|
| 11 |
+
decode_paths decodes all tasks in one call. The CUDA code keeps its device
|
| 12 |
+
memory within a budget, by default GPU_MEMORY_FRACTION of the free device
|
| 13 |
+
memory, by decoding the batch in windows (viterbi_gpu.cu), so records of any
|
| 14 |
+
length fit.
|
| 15 |
"""
|
| 16 |
import os
|
| 17 |
import sys
|
|
|
|
| 22 |
from constants import (
|
| 23 |
AT_AC_INTRON_LOG_PRIOR,
|
| 24 |
GC_AG_INTRON_LOG_PRIOR,
|
|
|
|
|
|
|
| 25 |
GPU_MEMORY_FRACTION,
|
| 26 |
+
GPU_SEGMENT_GROUP_LENGTH,
|
| 27 |
GPU_SEGMENT_LENGTH,
|
| 28 |
GT_AG_INTRON_LOG_PRIOR,
|
| 29 |
MAX_BOUNDARY_INTRON_LENGTH_BP,
|
| 30 |
)
|
| 31 |
from utils import (
|
| 32 |
+
pack_decode_tasks,
|
| 33 |
prepare_decode_tasks,
|
| 34 |
+
prepare_transition_log_odds,
|
| 35 |
validate_max_boundary_intron_length,
|
| 36 |
+
validate_memory_budget_bytes,
|
| 37 |
validate_reconstruction_batch_size,
|
| 38 |
)
|
| 39 |
|
|
|
|
| 68 |
return False, f"{type(exc).__name__}: {exc}"
|
| 69 |
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
def decode_paths(
|
| 72 |
tasks,
|
| 73 |
+
transition_log_odds,
|
| 74 |
stop_taa=True, stop_tag=True, stop_tga=True,
|
| 75 |
gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,
|
| 76 |
gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,
|
| 77 |
at_ac_intron_log_prior=AT_AC_INTRON_LOG_PRIOR,
|
| 78 |
max_boundary_intron_length=MAX_BOUNDARY_INTRON_LENGTH_BP,
|
| 79 |
reconstruction_batch_size=None,
|
| 80 |
+
memory_budget_bytes=None,
|
| 81 |
):
|
| 82 |
"""Decode probability/base tasks with the GPU Viterbi backend.
|
| 83 |
|
| 84 |
+
``transition_log_odds`` holds one ``(bases, 4)`` int32 array per task of
|
| 85 |
+
fixed-point log-odds in ``TRANSITION_NAMES`` column order.
|
| 86 |
+
``reconstruction_batch_size`` is the number of bases whose backpointers
|
| 87 |
+
are held at once during path reconstruction; ``None`` sizes it from the
|
| 88 |
+
memory budget. ``memory_budget_bytes`` bounds the device memory of the
|
| 89 |
+
call; ``None`` takes ``GPU_MEMORY_FRACTION`` of the free device memory.
|
| 90 |
"""
|
| 91 |
max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)
|
| 92 |
reconstruction_batch_size = validate_reconstruction_batch_size(reconstruction_batch_size)
|
| 93 |
+
memory_budget_bytes = validate_memory_budget_bytes(memory_budget_bytes)
|
| 94 |
tasks = prepare_decode_tasks(tasks)
|
| 95 |
+
transition_log_odds = prepare_transition_log_odds(transition_log_odds, tasks)
|
| 96 |
if not tasks:
|
| 97 |
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
import torch
|
| 99 |
|
| 100 |
module = _load()
|
|
|
|
| 104 |
float(at_ac_intron_log_prior),
|
| 105 |
int(max_boundary_intron_length),
|
| 106 |
)
|
| 107 |
+
if memory_budget_bytes is None:
|
| 108 |
+
# Memory that torch has cached but does not use counts as free.
|
| 109 |
+
torch.cuda.empty_cache()
|
| 110 |
+
memory_budget_bytes = int(torch.cuda.mem_get_info()[0] * GPU_MEMORY_FRACTION)
|
| 111 |
|
| 112 |
+
probability_bits, encoded_bases, transition_scores, record_offsets = pack_decode_tasks(
|
| 113 |
+
tasks, transition_log_odds
|
| 114 |
+
)
|
| 115 |
+
combined_path = np.asarray(
|
| 116 |
+
module.decode(
|
| 117 |
+
probability_bits, encoded_bases, transition_scores, record_offsets,
|
| 118 |
+
GPU_SEGMENT_LENGTH, GPU_SEGMENT_GROUP_LENGTH,
|
| 119 |
+
0 if reconstruction_batch_size is None else reconstruction_batch_size,
|
| 120 |
+
memory_budget_bytes,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
)
|
| 122 |
+
)
|
| 123 |
+
return np.split(combined_path, record_offsets[1:-1])
|
annotation_pipeline/src/viterbi_backends/viterbi_grammar.h
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// viterbi_grammar.h -- the Viterbi grammar shared by the CPU and GPU backends.
|
| 2 |
+
//
|
| 3 |
+
// viterbi.py describes Viterbi in full: the score of a labeling, the 30
|
| 4 |
+
// states, the transition rules, and the handling of record boundaries. This
|
| 5 |
+
// header implements the same grammar, with the same state ids, for
|
| 6 |
+
// viterbi_cpu.cpp and viterbi_gpu.cu. Both backends take every decision about
|
| 7 |
+
// which state changes are legal and what they score from the functions here;
|
| 8 |
+
// they differ only in how they organize the recursion along a record. The
|
| 9 |
+
// functions compile as host code under g++ and as host and device code under
|
| 10 |
+
// nvcc.
|
| 11 |
+
//
|
| 12 |
+
// States (ids as in utils.py; the State design section of viterbi.py
|
| 13 |
+
// describes each one):
|
| 14 |
+
//
|
| 15 |
+
// 0 INTERGENIC non-coding outside genes
|
| 16 |
+
// 1 START_A A of start codon ATG
|
| 17 |
+
// 2 START_AT T of start codon ATG; its G is EXON_PHASE0
|
| 18 |
+
// 3..8 EXON_<prefix type> CDS base
|
| 19 |
+
// 9 STOP last base of the terminal in-frame stop codon
|
| 20 |
+
// 10..15 GT_GC_AG_INTRON_FIRST_<prefix type> first GT/GC-AG intron base
|
| 21 |
+
// 16..21 GT_GC_AG_INTRON_READY_<prefix type> later GT/GC-AG intron base
|
| 22 |
+
// 22..27 AT_AC_INTRON_<prefix type> AT-AC intron base
|
| 23 |
+
// 28 LEADING_BOUNDARY_INTRON intron extending from the left record boundary
|
| 24 |
+
// 29 TRAILING_BOUNDARY_INTRON intron extending to the right record boundary
|
| 25 |
+
//
|
| 26 |
+
// The prefix type records how much of the current codon has been read and
|
| 27 |
+
// whether it can still become a stop codon. Within each family the states
|
| 28 |
+
// follow the prefix types in this order:
|
| 29 |
+
//
|
| 30 |
+
// PHASE0 codon phase 0; codon boundary, no open prefix
|
| 31 |
+
// PHASE1_PREFIX_T codon phase 1; one-base prefix T
|
| 32 |
+
// PHASE1_PREFIX_OTHER codon phase 1; one-base prefix other
|
| 33 |
+
// PHASE2_PREFIX_TA codon phase 2; prefix TA, so A/G completes TAA/TAG
|
| 34 |
+
// PHASE2_PREFIX_TG codon phase 2; prefix TG, so A completes TGA
|
| 35 |
+
// PHASE2_PREFIX_OTHER codon phase 2; other prefix, so no stop can be completed
|
| 36 |
+
//
|
| 37 |
+
// Exon states carry the current prefix type while emitting coding bases.
|
| 38 |
+
// Intron states carry the prefix type from the exon before the donor, so
|
| 39 |
+
// the acceptor resumes CDS in the same frame.
|
| 40 |
+
//
|
| 41 |
+
// Scores:
|
| 42 |
+
//
|
| 43 |
+
// Scores are integers: nats multiplied by 16,384 (FIXED_POINT_SCORE_SCALE
|
| 44 |
+
// in constants.py) and rounded. Base p scores coding = log P(CDS) in
|
| 45 |
+
// START_A through STOP and noncoding = log(1 - P(CDS)) in every other
|
| 46 |
+
// state, with P clipped to [1e-6, 1 - 1e-6]. build_emission_score_tables
|
| 47 |
+
// computes both for all 65,536 fp16 bit patterns of P; both backends read
|
| 48 |
+
// emission scores from these tables. The intron priors and the transition
|
| 49 |
+
// network's log-odds are in the same units. Path scores are int64 on the
|
| 50 |
+
// CPU; the CUDA backend keeps int32 scores within a segment and int64
|
| 51 |
+
// scores across segments. A state that no path reaches holds a sentinel
|
| 52 |
+
// below every reachable score and is never extended.
|
| 53 |
+
//
|
| 54 |
+
// Recursion:
|
| 55 |
+
//
|
| 56 |
+
// Both backends advance the Viterbi recursion one base at a time:
|
| 57 |
+
//
|
| 58 |
+
// score[p][t] = max over the predecessors s of t at base p of
|
| 59 |
+
// score[p - 1][s] + added(s -> t, p)
|
| 60 |
+
//
|
| 61 |
+
// best_transition_to_state evaluates this for one target state t. It
|
| 62 |
+
// visits the predecessors of t in the order of the table below and keeps
|
| 63 |
+
// the first best one, so equal scores resolve to the predecessor listed
|
| 64 |
+
// first. The Numba reference in viterbi.py offers the same candidates in
|
| 65 |
+
// the same order. The CPU backend calls it for the 30 targets in turn; the
|
| 66 |
+
// CUDA kernels call it for all 30 targets from one thread, or for one
|
| 67 |
+
// target in each lane of a warp.
|
| 68 |
+
//
|
| 69 |
+
// compute_position_signals reads bases p - 3 through p + 2 and returns
|
| 70 |
+
// every condition the table tests at base p, with the emission scores and
|
| 71 |
+
// the four transition log-odds of base p. A motif base outside the record
|
| 72 |
+
// matches any base. The two boundary-intron guards, a concrete acceptor
|
| 73 |
+
// followed by ATG and a concrete enabled stop codon followed by a donor,
|
| 74 |
+
// apply only when every base of their pattern is inside the record and
|
| 75 |
+
// concrete (Transition rules and Record boundaries in viterbi.py).
|
| 76 |
+
//
|
| 77 |
+
// Predecessors:
|
| 78 |
+
//
|
| 79 |
+
// The predecessors of each target state at base p, listed in the order
|
| 80 |
+
// that breaks ties, and the score each adds. EXON_* stands for the six
|
| 81 |
+
// exon states in prefix-type order, and likewise for the intron families;
|
| 82 |
+
// <prefix type> is the prefix type of the target.
|
| 83 |
+
//
|
| 84 |
+
// INTERGENIC
|
| 85 |
+
// INTERGENIC noncoding
|
| 86 |
+
// STOP noncoding
|
| 87 |
+
// START_A
|
| 88 |
+
// INTERGENIC, if an ATG starts at p coding + enter gene
|
| 89 |
+
// START_AT
|
| 90 |
+
// START_A coding
|
| 91 |
+
// EXON_<prefix type>
|
| 92 |
+
// START_AT, for EXON_PHASE0 coding
|
| 93 |
+
// LEADING_BOUNDARY_INTRON, if it can exit at p coding + leave intron
|
| 94 |
+
// EXON_*, by the coding table coding
|
| 95 |
+
// GT_GC_AG_INTRON_READY_*, by the coding table, coding + leave intron
|
| 96 |
+
// if an AG acceptor ends at p - 1
|
| 97 |
+
// AT_AC_INTRON_*, by the coding table, coding + leave intron
|
| 98 |
+
// if an AC acceptor ends at p - 1
|
| 99 |
+
// STOP
|
| 100 |
+
// as for EXON_<prefix type>, without START_AT coding + leave gene
|
| 101 |
+
// GT_GC_AG_INTRON_FIRST_<prefix type>
|
| 102 |
+
// EXON_<prefix type>, if a GT or GC donor noncoding + prior + enter intron
|
| 103 |
+
// starts at p
|
| 104 |
+
// GT_GC_AG_INTRON_READY_<prefix type>
|
| 105 |
+
// GT_GC_AG_INTRON_FIRST_<prefix type> noncoding
|
| 106 |
+
// GT_GC_AG_INTRON_READY_<prefix type> noncoding
|
| 107 |
+
// AT_AC_INTRON_<prefix type>
|
| 108 |
+
// EXON_<prefix type>, if an AT donor starts at p noncoding + prior + enter intron
|
| 109 |
+
// AT_AC_INTRON_<prefix type> noncoding
|
| 110 |
+
// LEADING_BOUNDARY_INTRON
|
| 111 |
+
// LEADING_BOUNDARY_INTRON, if it can extend to p noncoding
|
| 112 |
+
// TRAILING_BOUNDARY_INTRON
|
| 113 |
+
// EXON_*, if it can be entered at p noncoding + prior + enter intron
|
| 114 |
+
// TRAILING_BOUNDARY_INTRON noncoding
|
| 115 |
+
//
|
| 116 |
+
// prior is the log prior of the intron's splice class. When the donor at
|
| 117 |
+
// p fits more than one class that leads to the target, which needs an N
|
| 118 |
+
// at p or p + 1 or p at the last base, the highest of their priors counts.
|
| 119 |
+
//
|
| 120 |
+
// LEADING_BOUNDARY_INTRON can exit at p when an AG or AC acceptor ends at
|
| 121 |
+
// p - 1, the acceptor/ATG guard does not apply, and the coding table
|
| 122 |
+
// reaches the target from at least one prefix type. It can extend to p
|
| 123 |
+
// while bases 0 through p number at most max_boundary_intron_length.
|
| 124 |
+
// TRAILING_BOUNDARY_INTRON can be entered at p when a donor starts at p,
|
| 125 |
+
// the stop/donor guard does not apply, and bases p through the record end
|
| 126 |
+
// number at most max_boundary_intron_length.
|
| 127 |
+
//
|
| 128 |
+
// Coding table:
|
| 129 |
+
//
|
| 130 |
+
// A coding base moves an exon from one prefix type to the next (State
|
| 131 |
+
// design in viterbi.py). Read backwards, this rule gives the prefix types
|
| 132 |
+
// that reach each coding target with the base at p:
|
| 133 |
+
//
|
| 134 |
+
// EXON_PHASE0 from PHASE2_PREFIX_TA with T, C, A unless TAA is enabled,
|
| 135 |
+
// or G unless TAG is enabled
|
| 136 |
+
// from PHASE2_PREFIX_TG with T, C, G, or A unless TGA is enabled
|
| 137 |
+
// from PHASE2_PREFIX_OTHER with any base
|
| 138 |
+
// EXON_PHASE1_PREFIX_T from PHASE0 with T
|
| 139 |
+
// EXON_PHASE1_PREFIX_OTHER from PHASE0 with A, C, or G
|
| 140 |
+
// EXON_PHASE2_PREFIX_TA from PHASE1_PREFIX_T with A
|
| 141 |
+
// EXON_PHASE2_PREFIX_TG from PHASE1_PREFIX_T with G
|
| 142 |
+
// EXON_PHASE2_PREFIX_OTHER from PHASE1_PREFIX_T with C or T
|
| 143 |
+
// from PHASE1_PREFIX_OTHER with any base
|
| 144 |
+
// STOP from PHASE2_PREFIX_TA with A if TAA is enabled,
|
| 145 |
+
// or G if TAG is enabled
|
| 146 |
+
// from PHASE2_PREFIX_TG with A if TGA is enabled
|
| 147 |
+
//
|
| 148 |
+
// N matches every base, so it meets every condition that names a base.
|
| 149 |
+
// EXON_*, GT_GC_AG_INTRON_READY_*, and AT_AC_INTRON_* are each read through
|
| 150 |
+
// this table in increasing prefix type.
|
| 151 |
+
//
|
| 152 |
+
// Record boundaries:
|
| 153 |
+
//
|
| 154 |
+
// first_base_score gives each state's score at base 0, as
|
| 155 |
+
// initialize_first_base_scores does in viterbi.py. best_final_state
|
| 156 |
+
// chooses the state that ends the record: the highest-scoring of
|
| 157 |
+
// INTERGENIC, START_A through STOP, and TRAILING_BOUNDARY_INTRON, the
|
| 158 |
+
// first in this order on a tie.
|
| 159 |
+
//
|
| 160 |
+
// ViterbiConfig holds the enabled stop codons, the three intron log priors in
|
| 161 |
+
// score units, and max_boundary_intron_length (0 disables both
|
| 162 |
+
// boundary-intron states, -1 removes the limit).
|
| 163 |
+
#pragma once
|
| 164 |
+
|
| 165 |
+
#include <cmath>
|
| 166 |
+
#include <cstdint>
|
| 167 |
+
#include <cstring>
|
| 168 |
+
|
| 169 |
+
#if defined(__CUDACC__)
|
| 170 |
+
#define VITERBI_INLINE __host__ __device__ __forceinline__
|
| 171 |
+
#elif defined(__GNUC__)
|
| 172 |
+
// GCC and Clang both define __GNUC__.
|
| 173 |
+
#define VITERBI_INLINE inline __attribute__((always_inline))
|
| 174 |
+
#else
|
| 175 |
+
#define VITERBI_INLINE inline
|
| 176 |
+
#endif
|
| 177 |
+
|
| 178 |
+
// ---------------------------------------------------------------------------
|
| 179 |
+
// Scores
|
| 180 |
+
// ---------------------------------------------------------------------------
|
| 181 |
+
|
| 182 |
+
// One base's emission score, intron prior, or transition log-odds.
|
| 183 |
+
using StepScore = int32_t;
|
| 184 |
+
// Path scores inside one GPU segment.
|
| 185 |
+
using SegmentScore = int32_t;
|
| 186 |
+
// Path scores accumulated over a record.
|
| 187 |
+
using AccumulatedScore = int64_t;
|
| 188 |
+
|
| 189 |
+
constexpr double FIXED_POINT_SCORE_SCALE = 16384.0;
|
| 190 |
+
constexpr double MIN_PROB = 1e-6;
|
| 191 |
+
|
| 192 |
+
// Every reachable score stays far above these sentinels: a GPU segment is
|
| 193 |
+
// short enough to keep its path scores above -1.8e9.
|
| 194 |
+
constexpr SegmentScore UNREACHABLE_SEGMENT_SCORE = -2000000000;
|
| 195 |
+
constexpr AccumulatedScore UNREACHABLE_ACCUMULATED_SCORE = -4000000000000000000LL;
|
| 196 |
+
|
| 197 |
+
VITERBI_INLINE SegmentScore unreachable_score(SegmentScore) { return UNREACHABLE_SEGMENT_SCORE; }
|
| 198 |
+
VITERBI_INLINE AccumulatedScore unreachable_score(AccumulatedScore) {
|
| 199 |
+
return UNREACHABLE_ACCUMULATED_SCORE;
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
template <typename Score>
|
| 203 |
+
VITERBI_INLINE bool is_unreachable(Score score) {
|
| 204 |
+
return score == unreachable_score(Score{});
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
inline StepScore score_from_nats(double nats) {
|
| 208 |
+
return static_cast<StepScore>(std::llround(nats * FIXED_POINT_SCORE_SCALE));
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
// ---------------------------------------------------------------------------
|
| 212 |
+
// States, bases, and transition columns
|
| 213 |
+
// ---------------------------------------------------------------------------
|
| 214 |
+
|
| 215 |
+
constexpr int STATE_COUNT = 30;
|
| 216 |
+
constexpr int PREFIX_TYPE_COUNT = 6;
|
| 217 |
+
|
| 218 |
+
constexpr int PHASE0 = 0;
|
| 219 |
+
constexpr int PHASE1_PREFIX_T = 1;
|
| 220 |
+
constexpr int PHASE1_PREFIX_OTHER = 2;
|
| 221 |
+
constexpr int PHASE2_PREFIX_TA = 3;
|
| 222 |
+
constexpr int PHASE2_PREFIX_TG = 4;
|
| 223 |
+
constexpr int PHASE2_PREFIX_OTHER = 5;
|
| 224 |
+
|
| 225 |
+
constexpr int INTERGENIC = 0;
|
| 226 |
+
constexpr int START_A = 1;
|
| 227 |
+
constexpr int START_AT = 2;
|
| 228 |
+
constexpr int EXON_PHASE0 = 3;
|
| 229 |
+
constexpr int EXON_PHASE1_PREFIX_T = 4;
|
| 230 |
+
constexpr int EXON_PHASE1_PREFIX_OTHER = 5;
|
| 231 |
+
constexpr int EXON_PHASE2_PREFIX_TA = 6;
|
| 232 |
+
constexpr int EXON_PHASE2_PREFIX_TG = 7;
|
| 233 |
+
constexpr int EXON_PHASE2_PREFIX_OTHER = 8;
|
| 234 |
+
constexpr int STOP = 9;
|
| 235 |
+
constexpr int GT_GC_AG_INTRON_FIRST_PHASE0 = 10;
|
| 236 |
+
constexpr int GT_GC_AG_INTRON_READY_PHASE0 = 16;
|
| 237 |
+
constexpr int AT_AC_INTRON_PHASE0 = 22;
|
| 238 |
+
constexpr int LEADING_BOUNDARY_INTRON = 28;
|
| 239 |
+
constexpr int TRAILING_BOUNDARY_INTRON = 29;
|
| 240 |
+
|
| 241 |
+
constexpr int BASE_A = 0;
|
| 242 |
+
constexpr int BASE_T = 1;
|
| 243 |
+
constexpr int BASE_C = 2;
|
| 244 |
+
constexpr int BASE_G = 3;
|
| 245 |
+
constexpr int BASE_N = 4;
|
| 246 |
+
|
| 247 |
+
// Columns of the per-base transition log-odds, in the order of constants.py.
|
| 248 |
+
constexpr int ENTER_GENE = 0;
|
| 249 |
+
constexpr int LEAVE_GENE = 1;
|
| 250 |
+
constexpr int ENTER_INTRON = 2;
|
| 251 |
+
constexpr int LEAVE_INTRON = 3;
|
| 252 |
+
constexpr int TRANSITION_COUNT = 4;
|
| 253 |
+
|
| 254 |
+
struct ViterbiConfig {
|
| 255 |
+
bool stop_taa;
|
| 256 |
+
bool stop_tag;
|
| 257 |
+
bool stop_tga;
|
| 258 |
+
StepScore gt_ag_intron_log_prior;
|
| 259 |
+
StepScore gc_ag_intron_log_prior;
|
| 260 |
+
StepScore at_ac_intron_log_prior;
|
| 261 |
+
int max_boundary_intron_length;
|
| 262 |
+
};
|
| 263 |
+
|
| 264 |
+
// ---------------------------------------------------------------------------
|
| 265 |
+
// Emission scores
|
| 266 |
+
// ---------------------------------------------------------------------------
|
| 267 |
+
|
| 268 |
+
constexpr int EMISSION_TABLE_SIZE = 65536;
|
| 269 |
+
|
| 270 |
+
// The value of an fp16 bit pattern, exact for every pattern.
|
| 271 |
+
inline double half_bits_to_double(uint16_t half_bits) {
|
| 272 |
+
uint32_t sign = static_cast<uint32_t>(half_bits & 0x8000) << 16;
|
| 273 |
+
uint32_t exponent = (half_bits >> 10) & 0x1F;
|
| 274 |
+
uint32_t mantissa = half_bits & 0x3FF;
|
| 275 |
+
uint32_t float_bits;
|
| 276 |
+
if (exponent == 0) {
|
| 277 |
+
if (mantissa == 0) {
|
| 278 |
+
float_bits = sign;
|
| 279 |
+
} else {
|
| 280 |
+
int normalization_shift = -1;
|
| 281 |
+
do {
|
| 282 |
+
normalization_shift++;
|
| 283 |
+
mantissa <<= 1;
|
| 284 |
+
} while (!(mantissa & 0x400));
|
| 285 |
+
float_bits = sign
|
| 286 |
+
| (static_cast<uint32_t>(127 - 15 - normalization_shift) << 23)
|
| 287 |
+
| ((mantissa & 0x3FF) << 13);
|
| 288 |
+
}
|
| 289 |
+
} else if (exponent == 0x1F) {
|
| 290 |
+
float_bits = sign | 0x7F800000u | (mantissa << 13);
|
| 291 |
+
} else {
|
| 292 |
+
float_bits = sign | ((exponent + (127 - 15)) << 23) | (mantissa << 13);
|
| 293 |
+
}
|
| 294 |
+
float value;
|
| 295 |
+
std::memcpy(&value, &float_bits, sizeof(value));
|
| 296 |
+
return static_cast<double>(value);
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
// coding_scores[bits] = log P and noncoding_scores[bits] = log(1 - P), where P
|
| 300 |
+
// is the fp16 value of bits clipped to [MIN_PROB, 1 - MIN_PROB].
|
| 301 |
+
inline void build_emission_score_tables(StepScore* coding_scores, StepScore* noncoding_scores) {
|
| 302 |
+
for (int bits = 0; bits < EMISSION_TABLE_SIZE; bits++) {
|
| 303 |
+
double probability = half_bits_to_double(static_cast<uint16_t>(bits));
|
| 304 |
+
if (probability < MIN_PROB) probability = MIN_PROB;
|
| 305 |
+
else if (probability > 1.0 - MIN_PROB) probability = 1.0 - MIN_PROB;
|
| 306 |
+
coding_scores[bits] = score_from_nats(std::log(probability));
|
| 307 |
+
noncoding_scores[bits] = score_from_nats(std::log(1.0 - probability));
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
// ---------------------------------------------------------------------------
|
| 312 |
+
// Position signals
|
| 313 |
+
// ---------------------------------------------------------------------------
|
| 314 |
+
|
| 315 |
+
VITERBI_INLINE bool base_matches(int observed_base, int expected_base) {
|
| 316 |
+
return observed_base == expected_base || observed_base == BASE_N;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
VITERBI_INLINE bool is_exact_enabled_stop_codon(
|
| 320 |
+
int first_base, int second_base, int third_base, const ViterbiConfig& config
|
| 321 |
+
) {
|
| 322 |
+
if (first_base != BASE_T) return false;
|
| 323 |
+
if (second_base == BASE_A) {
|
| 324 |
+
if (third_base == BASE_A && config.stop_taa) return true;
|
| 325 |
+
if (third_base == BASE_G && config.stop_tag) return true;
|
| 326 |
+
}
|
| 327 |
+
return second_base == BASE_G && third_base == BASE_A && config.stop_tga;
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
// Everything the predecessor table reads at base p.
|
| 331 |
+
struct PositionSignals {
|
| 332 |
+
StepScore coding_score;
|
| 333 |
+
StepScore noncoding_score;
|
| 334 |
+
StepScore enter_gene_log_odds;
|
| 335 |
+
StepScore leave_gene_log_odds;
|
| 336 |
+
StepScore enter_intron_log_odds;
|
| 337 |
+
StepScore leave_intron_log_odds;
|
| 338 |
+
|
| 339 |
+
bool has_gt_ag_donor; // GT starts at p
|
| 340 |
+
bool has_gc_ag_donor; // GC starts at p
|
| 341 |
+
bool has_at_ac_donor; // AT starts at p
|
| 342 |
+
bool has_ag_acceptor; // AG ends at p - 1
|
| 343 |
+
bool has_ac_acceptor; // AC ends at p - 1
|
| 344 |
+
bool has_atg_start; // ATG starts at p
|
| 345 |
+
// The highest prior among the GT-AG and GC-AG donors at p, and among all
|
| 346 |
+
// donors at p.
|
| 347 |
+
StepScore gt_gc_ag_donor_log_prior;
|
| 348 |
+
StepScore any_donor_log_prior;
|
| 349 |
+
|
| 350 |
+
bool can_exit_leading_boundary_intron;
|
| 351 |
+
bool can_extend_leading_boundary_intron;
|
| 352 |
+
bool can_enter_trailing_boundary_intron;
|
| 353 |
+
|
| 354 |
+
// The coding table: moves_x_to_y is whether base p moves prefix type x to
|
| 355 |
+
// prefix type y (phase0, t, phase1_other, ta, tg, phase2_other) or to STOP.
|
| 356 |
+
// PHASE1_PREFIX_OTHER -> PHASE2_PREFIX_OTHER and PHASE2_PREFIX_OTHER ->
|
| 357 |
+
// PHASE0 take every base.
|
| 358 |
+
bool moves_phase0_to_t;
|
| 359 |
+
bool moves_phase0_to_phase1_other;
|
| 360 |
+
bool moves_t_to_ta;
|
| 361 |
+
bool moves_t_to_tg;
|
| 362 |
+
bool moves_t_to_phase2_other;
|
| 363 |
+
bool moves_ta_to_phase0;
|
| 364 |
+
bool moves_tg_to_phase0;
|
| 365 |
+
bool moves_ta_to_stop;
|
| 366 |
+
bool moves_tg_to_stop;
|
| 367 |
+
};
|
| 368 |
+
|
| 369 |
+
// bases[record_offset + q] is base q of the record, and transitions points at
|
| 370 |
+
// the four log-odds of base position; 1 <= position < record_length.
|
| 371 |
+
VITERBI_INLINE PositionSignals compute_position_signals(
|
| 372 |
+
const int8_t* bases, int64_t record_offset, int64_t record_length, int64_t position,
|
| 373 |
+
StepScore coding_score, StepScore noncoding_score, const StepScore* transitions,
|
| 374 |
+
const ViterbiConfig& config
|
| 375 |
+
) {
|
| 376 |
+
auto base_at = [&](int64_t record_position) -> int {
|
| 377 |
+
return bases[record_offset + record_position];
|
| 378 |
+
};
|
| 379 |
+
PositionSignals signals;
|
| 380 |
+
signals.coding_score = coding_score;
|
| 381 |
+
signals.noncoding_score = noncoding_score;
|
| 382 |
+
signals.enter_gene_log_odds = transitions[ENTER_GENE];
|
| 383 |
+
signals.leave_gene_log_odds = transitions[LEAVE_GENE];
|
| 384 |
+
signals.enter_intron_log_odds = transitions[ENTER_INTRON];
|
| 385 |
+
signals.leave_intron_log_odds = transitions[LEAVE_INTRON];
|
| 386 |
+
|
| 387 |
+
const int base = base_at(position);
|
| 388 |
+
const bool next_base_is_missing = position + 1 == record_length;
|
| 389 |
+
const int next_base = next_base_is_missing ? -1 : base_at(position + 1);
|
| 390 |
+
|
| 391 |
+
// Motifs. A base outside the record matches any base.
|
| 392 |
+
signals.has_gt_ag_donor = base_matches(base, BASE_G)
|
| 393 |
+
&& (next_base_is_missing || base_matches(next_base, BASE_T));
|
| 394 |
+
signals.has_gc_ag_donor = base_matches(base, BASE_G)
|
| 395 |
+
&& (next_base_is_missing || base_matches(next_base, BASE_C));
|
| 396 |
+
signals.has_at_ac_donor = base_matches(base, BASE_A)
|
| 397 |
+
&& (next_base_is_missing || base_matches(next_base, BASE_T));
|
| 398 |
+
const bool acceptor_first_base_matches = position == 1
|
| 399 |
+
|| base_matches(base_at(position - 2), BASE_A);
|
| 400 |
+
signals.has_ag_acceptor = acceptor_first_base_matches
|
| 401 |
+
&& base_matches(base_at(position - 1), BASE_G);
|
| 402 |
+
signals.has_ac_acceptor = acceptor_first_base_matches
|
| 403 |
+
&& base_matches(base_at(position - 1), BASE_C);
|
| 404 |
+
const bool third_start_base_matches = position + 2 >= record_length
|
| 405 |
+
|| base_matches(base_at(position + 2), BASE_G);
|
| 406 |
+
signals.has_atg_start = base_matches(base, BASE_A)
|
| 407 |
+
&& (next_base_is_missing || base_matches(next_base, BASE_T))
|
| 408 |
+
&& third_start_base_matches;
|
| 409 |
+
|
| 410 |
+
StepScore gt_gc_ag_donor_log_prior = UNREACHABLE_SEGMENT_SCORE;
|
| 411 |
+
if (signals.has_gt_ag_donor) gt_gc_ag_donor_log_prior = config.gt_ag_intron_log_prior;
|
| 412 |
+
if (signals.has_gc_ag_donor && config.gc_ag_intron_log_prior > gt_gc_ag_donor_log_prior) {
|
| 413 |
+
gt_gc_ag_donor_log_prior = config.gc_ag_intron_log_prior;
|
| 414 |
+
}
|
| 415 |
+
StepScore any_donor_log_prior = gt_gc_ag_donor_log_prior;
|
| 416 |
+
if (signals.has_at_ac_donor && config.at_ac_intron_log_prior > any_donor_log_prior) {
|
| 417 |
+
any_donor_log_prior = config.at_ac_intron_log_prior;
|
| 418 |
+
}
|
| 419 |
+
signals.gt_gc_ag_donor_log_prior = gt_gc_ag_donor_log_prior;
|
| 420 |
+
signals.any_donor_log_prior = any_donor_log_prior;
|
| 421 |
+
|
| 422 |
+
// The boundary-intron guards need concrete bases inside the record.
|
| 423 |
+
const bool has_exact_acceptor_followed_by_atg = position >= 2
|
| 424 |
+
&& position + 2 < record_length
|
| 425 |
+
&& base_at(position - 2) == BASE_A
|
| 426 |
+
&& (base_at(position - 1) == BASE_G || base_at(position - 1) == BASE_C)
|
| 427 |
+
&& base == BASE_A
|
| 428 |
+
&& next_base == BASE_T
|
| 429 |
+
&& base_at(position + 2) == BASE_G;
|
| 430 |
+
const bool has_exact_donor = position + 1 < record_length
|
| 431 |
+
&& ((base == BASE_G && (next_base == BASE_T || next_base == BASE_C))
|
| 432 |
+
|| (base == BASE_A && next_base == BASE_T));
|
| 433 |
+
const bool has_exact_enabled_stop_followed_by_donor = has_exact_donor
|
| 434 |
+
&& position >= 3
|
| 435 |
+
&& is_exact_enabled_stop_codon(
|
| 436 |
+
base_at(position - 3), base_at(position - 2), base_at(position - 1), config
|
| 437 |
+
);
|
| 438 |
+
|
| 439 |
+
// A leading intron through p is p + 1 bases long; a trailing intron
|
| 440 |
+
// entered at p is record_length - p bases long.
|
| 441 |
+
const bool boundary_introns_enabled = config.max_boundary_intron_length != 0;
|
| 442 |
+
const bool boundary_intron_length_is_unlimited = config.max_boundary_intron_length == -1;
|
| 443 |
+
signals.can_exit_leading_boundary_intron = (signals.has_ag_acceptor || signals.has_ac_acceptor)
|
| 444 |
+
&& !has_exact_acceptor_followed_by_atg;
|
| 445 |
+
signals.can_extend_leading_boundary_intron = boundary_introns_enabled
|
| 446 |
+
&& (boundary_intron_length_is_unlimited
|
| 447 |
+
|| position < config.max_boundary_intron_length);
|
| 448 |
+
signals.can_enter_trailing_boundary_intron =
|
| 449 |
+
(signals.has_gt_ag_donor || signals.has_gc_ag_donor || signals.has_at_ac_donor)
|
| 450 |
+
&& !has_exact_enabled_stop_followed_by_donor
|
| 451 |
+
&& boundary_introns_enabled
|
| 452 |
+
&& (boundary_intron_length_is_unlimited
|
| 453 |
+
|| record_length - position <= config.max_boundary_intron_length);
|
| 454 |
+
|
| 455 |
+
const bool base_is_a = base_matches(base, BASE_A);
|
| 456 |
+
const bool base_is_c = base_matches(base, BASE_C);
|
| 457 |
+
const bool base_is_g = base_matches(base, BASE_G);
|
| 458 |
+
const bool base_is_t = base_matches(base, BASE_T);
|
| 459 |
+
signals.moves_phase0_to_t = base_is_t;
|
| 460 |
+
signals.moves_phase0_to_phase1_other = base_is_a || base_is_c || base_is_g;
|
| 461 |
+
signals.moves_t_to_ta = base_is_a;
|
| 462 |
+
signals.moves_t_to_tg = base_is_g;
|
| 463 |
+
signals.moves_t_to_phase2_other = base_is_c || base_is_t;
|
| 464 |
+
signals.moves_ta_to_phase0 = base_is_t || base_is_c
|
| 465 |
+
|| (base_is_a && !config.stop_taa) || (base_is_g && !config.stop_tag);
|
| 466 |
+
signals.moves_tg_to_phase0 = base_is_t || base_is_c || base_is_g
|
| 467 |
+
|| (base_is_a && !config.stop_tga);
|
| 468 |
+
signals.moves_ta_to_stop = (base_is_a && config.stop_taa) || (base_is_g && config.stop_tag);
|
| 469 |
+
signals.moves_tg_to_stop = base_is_a && config.stop_tga;
|
| 470 |
+
return signals;
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
// ---------------------------------------------------------------------------
|
| 474 |
+
// The predecessor table
|
| 475 |
+
// ---------------------------------------------------------------------------
|
| 476 |
+
|
| 477 |
+
template <typename Score>
|
| 478 |
+
struct TransitionChoice {
|
| 479 |
+
Score score;
|
| 480 |
+
int source_state;
|
| 481 |
+
};
|
| 482 |
+
|
| 483 |
+
template <typename Score>
|
| 484 |
+
VITERBI_INLINE void consider_predecessor(
|
| 485 |
+
TransitionChoice<Score>& best, const Score* scores, int source_state, Score added_score
|
| 486 |
+
) {
|
| 487 |
+
Score source_score = scores[source_state];
|
| 488 |
+
if (is_unreachable(source_score)) return;
|
| 489 |
+
Score candidate_score = source_score + added_score;
|
| 490 |
+
if (candidate_score > best.score) {
|
| 491 |
+
best.score = candidate_score;
|
| 492 |
+
best.source_state = source_state;
|
| 493 |
+
}
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
// The members of one source group that the coding table moves into
|
| 497 |
+
// target_state, in increasing prefix type. The member of prefix type t is
|
| 498 |
+
// state first_state + stride * t. LEADING_BOUNDARY_INTRON resumes with any
|
| 499 |
+
// prefix type, so it is the group with first_state LEADING_BOUNDARY_INTRON
|
| 500 |
+
// and stride 0.
|
| 501 |
+
template <typename Score>
|
| 502 |
+
VITERBI_INLINE void consider_coding_predecessors(
|
| 503 |
+
TransitionChoice<Score>& best, const Score* scores, int target_state,
|
| 504 |
+
int first_state, int stride, Score added_score, const PositionSignals& signals
|
| 505 |
+
) {
|
| 506 |
+
switch (target_state) {
|
| 507 |
+
case EXON_PHASE0:
|
| 508 |
+
if (signals.moves_ta_to_phase0) {
|
| 509 |
+
consider_predecessor(best, scores, first_state + PHASE2_PREFIX_TA * stride, added_score);
|
| 510 |
+
}
|
| 511 |
+
if (signals.moves_tg_to_phase0) {
|
| 512 |
+
consider_predecessor(best, scores, first_state + PHASE2_PREFIX_TG * stride, added_score);
|
| 513 |
+
}
|
| 514 |
+
consider_predecessor(best, scores, first_state + PHASE2_PREFIX_OTHER * stride, added_score);
|
| 515 |
+
break;
|
| 516 |
+
case EXON_PHASE1_PREFIX_T:
|
| 517 |
+
if (signals.moves_phase0_to_t) {
|
| 518 |
+
consider_predecessor(best, scores, first_state + PHASE0 * stride, added_score);
|
| 519 |
+
}
|
| 520 |
+
break;
|
| 521 |
+
case EXON_PHASE1_PREFIX_OTHER:
|
| 522 |
+
if (signals.moves_phase0_to_phase1_other) {
|
| 523 |
+
consider_predecessor(best, scores, first_state + PHASE0 * stride, added_score);
|
| 524 |
+
}
|
| 525 |
+
break;
|
| 526 |
+
case EXON_PHASE2_PREFIX_TA:
|
| 527 |
+
if (signals.moves_t_to_ta) {
|
| 528 |
+
consider_predecessor(best, scores, first_state + PHASE1_PREFIX_T * stride, added_score);
|
| 529 |
+
}
|
| 530 |
+
break;
|
| 531 |
+
case EXON_PHASE2_PREFIX_TG:
|
| 532 |
+
if (signals.moves_t_to_tg) {
|
| 533 |
+
consider_predecessor(best, scores, first_state + PHASE1_PREFIX_T * stride, added_score);
|
| 534 |
+
}
|
| 535 |
+
break;
|
| 536 |
+
case EXON_PHASE2_PREFIX_OTHER:
|
| 537 |
+
if (signals.moves_t_to_phase2_other) {
|
| 538 |
+
consider_predecessor(best, scores, first_state + PHASE1_PREFIX_T * stride, added_score);
|
| 539 |
+
}
|
| 540 |
+
consider_predecessor(best, scores, first_state + PHASE1_PREFIX_OTHER * stride, added_score);
|
| 541 |
+
break;
|
| 542 |
+
case STOP:
|
| 543 |
+
if (signals.moves_ta_to_stop) {
|
| 544 |
+
consider_predecessor(best, scores, first_state + PHASE2_PREFIX_TA * stride, added_score);
|
| 545 |
+
}
|
| 546 |
+
if (signals.moves_tg_to_stop) {
|
| 547 |
+
consider_predecessor(best, scores, first_state + PHASE2_PREFIX_TG * stride, added_score);
|
| 548 |
+
}
|
| 549 |
+
break;
|
| 550 |
+
}
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
// The best predecessor of target_state at base p and the path score it gives;
|
| 554 |
+
// an unreachable score if no predecessor is reachable.
|
| 555 |
+
template <typename Score>
|
| 556 |
+
VITERBI_INLINE TransitionChoice<Score> best_transition_to_state(
|
| 557 |
+
int target_state, const Score* scores, const PositionSignals& signals,
|
| 558 |
+
const ViterbiConfig& config
|
| 559 |
+
) {
|
| 560 |
+
TransitionChoice<Score> best = {unreachable_score(Score{}), 0};
|
| 561 |
+
const Score coding = signals.coding_score;
|
| 562 |
+
const Score noncoding = signals.noncoding_score;
|
| 563 |
+
|
| 564 |
+
if (target_state == INTERGENIC) {
|
| 565 |
+
consider_predecessor(best, scores, INTERGENIC, noncoding);
|
| 566 |
+
consider_predecessor(best, scores, STOP, noncoding);
|
| 567 |
+
} else if (target_state == START_A) {
|
| 568 |
+
if (signals.has_atg_start) {
|
| 569 |
+
consider_predecessor(best, scores, INTERGENIC, coding + signals.enter_gene_log_odds);
|
| 570 |
+
}
|
| 571 |
+
} else if (target_state == START_AT) {
|
| 572 |
+
consider_predecessor(best, scores, START_A, coding);
|
| 573 |
+
} else if (target_state <= STOP) {
|
| 574 |
+
// An exon state or STOP. Every transition into STOP is charged leave gene.
|
| 575 |
+
const Score from_exon = target_state == STOP ? coding + signals.leave_gene_log_odds : coding;
|
| 576 |
+
const Score from_intron = target_state == STOP
|
| 577 |
+
? coding + signals.leave_gene_log_odds
|
| 578 |
+
: coding + signals.leave_intron_log_odds;
|
| 579 |
+
if (target_state == EXON_PHASE0) {
|
| 580 |
+
consider_predecessor(best, scores, START_AT, coding);
|
| 581 |
+
}
|
| 582 |
+
if (signals.can_exit_leading_boundary_intron) {
|
| 583 |
+
consider_coding_predecessors(
|
| 584 |
+
best, scores, target_state, LEADING_BOUNDARY_INTRON, 0, from_intron, signals
|
| 585 |
+
);
|
| 586 |
+
}
|
| 587 |
+
consider_coding_predecessors(
|
| 588 |
+
best, scores, target_state, EXON_PHASE0, 1, from_exon, signals
|
| 589 |
+
);
|
| 590 |
+
if (signals.has_ag_acceptor) {
|
| 591 |
+
consider_coding_predecessors(
|
| 592 |
+
best, scores, target_state, GT_GC_AG_INTRON_READY_PHASE0, 1,
|
| 593 |
+
from_intron, signals
|
| 594 |
+
);
|
| 595 |
+
}
|
| 596 |
+
if (signals.has_ac_acceptor) {
|
| 597 |
+
consider_coding_predecessors(
|
| 598 |
+
best, scores, target_state, AT_AC_INTRON_PHASE0, 1, from_intron, signals
|
| 599 |
+
);
|
| 600 |
+
}
|
| 601 |
+
} else if (target_state < GT_GC_AG_INTRON_READY_PHASE0) {
|
| 602 |
+
const int prefix_type = target_state - GT_GC_AG_INTRON_FIRST_PHASE0;
|
| 603 |
+
if (signals.has_gt_ag_donor || signals.has_gc_ag_donor) {
|
| 604 |
+
consider_predecessor(
|
| 605 |
+
best, scores, EXON_PHASE0 + prefix_type,
|
| 606 |
+
noncoding + signals.gt_gc_ag_donor_log_prior + signals.enter_intron_log_odds
|
| 607 |
+
);
|
| 608 |
+
}
|
| 609 |
+
} else if (target_state < AT_AC_INTRON_PHASE0) {
|
| 610 |
+
const int prefix_type = target_state - GT_GC_AG_INTRON_READY_PHASE0;
|
| 611 |
+
consider_predecessor(
|
| 612 |
+
best, scores, GT_GC_AG_INTRON_FIRST_PHASE0 + prefix_type, noncoding
|
| 613 |
+
);
|
| 614 |
+
consider_predecessor(best, scores, target_state, noncoding);
|
| 615 |
+
} else if (target_state < LEADING_BOUNDARY_INTRON) {
|
| 616 |
+
const int prefix_type = target_state - AT_AC_INTRON_PHASE0;
|
| 617 |
+
if (signals.has_at_ac_donor) {
|
| 618 |
+
consider_predecessor(
|
| 619 |
+
best, scores, EXON_PHASE0 + prefix_type,
|
| 620 |
+
noncoding + config.at_ac_intron_log_prior + signals.enter_intron_log_odds
|
| 621 |
+
);
|
| 622 |
+
}
|
| 623 |
+
consider_predecessor(best, scores, target_state, noncoding);
|
| 624 |
+
} else if (target_state == LEADING_BOUNDARY_INTRON) {
|
| 625 |
+
if (signals.can_extend_leading_boundary_intron) {
|
| 626 |
+
consider_predecessor(best, scores, LEADING_BOUNDARY_INTRON, noncoding);
|
| 627 |
+
}
|
| 628 |
+
} else {
|
| 629 |
+
if (signals.can_enter_trailing_boundary_intron) {
|
| 630 |
+
const Score from_exon = noncoding + signals.any_donor_log_prior + signals.enter_intron_log_odds;
|
| 631 |
+
consider_predecessor(best, scores, EXON_PHASE0, from_exon);
|
| 632 |
+
consider_predecessor(best, scores, EXON_PHASE1_PREFIX_T, from_exon);
|
| 633 |
+
consider_predecessor(best, scores, EXON_PHASE1_PREFIX_OTHER, from_exon);
|
| 634 |
+
consider_predecessor(best, scores, EXON_PHASE2_PREFIX_TA, from_exon);
|
| 635 |
+
consider_predecessor(best, scores, EXON_PHASE2_PREFIX_TG, from_exon);
|
| 636 |
+
consider_predecessor(best, scores, EXON_PHASE2_PREFIX_OTHER, from_exon);
|
| 637 |
+
}
|
| 638 |
+
consider_predecessor(best, scores, TRAILING_BOUNDARY_INTRON, noncoding);
|
| 639 |
+
}
|
| 640 |
+
return best;
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
// ---------------------------------------------------------------------------
|
| 644 |
+
// Record boundaries
|
| 645 |
+
// ---------------------------------------------------------------------------
|
| 646 |
+
|
| 647 |
+
// The score of state at base 0. bases[record_offset + q] is base q of the
|
| 648 |
+
// record, and transitions points at the four log-odds of base 0. A record may
|
| 649 |
+
// begin anywhere in a gene, so every state that base 0 and unknown bases
|
| 650 |
+
// before it allow is reachable.
|
| 651 |
+
template <typename Score>
|
| 652 |
+
VITERBI_INLINE Score first_base_score(
|
| 653 |
+
int state, const int8_t* bases, int64_t record_offset, int64_t record_length,
|
| 654 |
+
StepScore coding_score, StepScore noncoding_score, const StepScore* transitions,
|
| 655 |
+
const ViterbiConfig& config
|
| 656 |
+
) {
|
| 657 |
+
const int base = bases[record_offset];
|
| 658 |
+
const Score coding = coding_score;
|
| 659 |
+
const Score noncoding = noncoding_score;
|
| 660 |
+
const Score unreachable = unreachable_score(Score{});
|
| 661 |
+
switch (state) {
|
| 662 |
+
case INTERGENIC:
|
| 663 |
+
return noncoding;
|
| 664 |
+
case START_A: {
|
| 665 |
+
// The start codon may continue beyond the right edge.
|
| 666 |
+
const bool has_atg_start = base_matches(base, BASE_A)
|
| 667 |
+
&& (record_length == 1 || base_matches(bases[record_offset + 1], BASE_T))
|
| 668 |
+
&& (record_length <= 2 || base_matches(bases[record_offset + 2], BASE_G));
|
| 669 |
+
return has_atg_start ? coding + transitions[ENTER_GENE] : unreachable;
|
| 670 |
+
}
|
| 671 |
+
case EXON_PHASE0:
|
| 672 |
+
case EXON_PHASE2_PREFIX_OTHER:
|
| 673 |
+
return coding;
|
| 674 |
+
case EXON_PHASE1_PREFIX_T:
|
| 675 |
+
return base_matches(base, BASE_T) ? coding : unreachable;
|
| 676 |
+
case EXON_PHASE1_PREFIX_OTHER:
|
| 677 |
+
return base != BASE_T ? coding : unreachable;
|
| 678 |
+
case EXON_PHASE2_PREFIX_TA:
|
| 679 |
+
return base_matches(base, BASE_A) ? coding : unreachable;
|
| 680 |
+
case EXON_PHASE2_PREFIX_TG:
|
| 681 |
+
return base_matches(base, BASE_G) ? coding : unreachable;
|
| 682 |
+
case STOP: {
|
| 683 |
+
// The last base of a stop codon that began before the record.
|
| 684 |
+
const bool can_end_stop = (base_matches(base, BASE_A) && (config.stop_taa || config.stop_tga))
|
| 685 |
+
|| (base_matches(base, BASE_G) && config.stop_tag);
|
| 686 |
+
return can_end_stop ? coding + transitions[LEAVE_GENE] : unreachable;
|
| 687 |
+
}
|
| 688 |
+
case LEADING_BOUNDARY_INTRON:
|
| 689 |
+
return config.max_boundary_intron_length != 0 ? noncoding : unreachable;
|
| 690 |
+
default:
|
| 691 |
+
return unreachable;
|
| 692 |
+
}
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
template <typename Score>
|
| 696 |
+
VITERBI_INLINE int best_final_state(const Score* scores) {
|
| 697 |
+
int best_state = INTERGENIC;
|
| 698 |
+
for (int state = START_A; state <= STOP; state++) {
|
| 699 |
+
if (scores[state] > scores[best_state]) best_state = state;
|
| 700 |
+
}
|
| 701 |
+
if (scores[TRAILING_BOUNDARY_INTRON] > scores[best_state]) {
|
| 702 |
+
best_state = TRAILING_BOUNDARY_INTRON;
|
| 703 |
+
}
|
| 704 |
+
return best_state;
|
| 705 |
+
}
|
requirements.txt
CHANGED
|
@@ -8,7 +8,6 @@ numpy>=1.24
|
|
| 8 |
biopython>=1.83,<2
|
| 9 |
|
| 10 |
# Annotation pipeline (annotation_pipeline/, Linux only)
|
| 11 |
-
pandas
|
| 12 |
pyarrow
|
| 13 |
tqdm
|
| 14 |
numba
|
|
|
|
| 8 |
biopython>=1.83,<2
|
| 9 |
|
| 10 |
# Annotation pipeline (annotation_pipeline/, Linux only)
|
|
|
|
| 11 |
pyarrow
|
| 12 |
tqdm
|
| 13 |
numba
|