Carbon-A-1.2B / annotation_pipeline /src /post_processing.py
GenerTeam's picture
Support long records and write raw probabilities as Arrow IPC files
ee63599 verified
Raw History Blame Contribute Delete
25.5 kB
"""Post-process Carbon-A coding probabilities into GFF3, CDS FASTA, and protein FASTA.
Post-processing runs three stages on each strand of each record, in
transcript orientation:
1. The transition network (transition_network.py) reads the coding
probability track and scores the four permitted transitions at every
base: enter gene, leave gene, enter intron, leave intron.
2. The Viterbi algorithm (viterbi.py) combines the coding probabilities,
the transition probabilities, and the gene grammar into the highest-scoring
labeling of the strand into intergenic, exon, and intron bases. Runs of
exon bases form CDS intervals, intervals separated by an intron belong
to one gene, and the reading frame gives each interval its phase.
3. The confidence network (confidence_network.py) reads the coding
probabilities together with the decoded roles of the whole strand,
neighbouring genes included, and returns, for every complete gene, the
probability that its structure is exactly right.
The score of a labeling is the sum over bases of log P(CDS) for exon bases and
log(1 - P(CDS)) for all other bases, plus the log-odds of the transition at
every base where a segment begins or a gene closes, plus a fixed log-prior for
each intron's splice class. The grammar decides which labelings are admissible:
a gene opens at an ATG start codon and closes at the first in-frame stop codon
of the selected genetic code, an intron opens at a donor site and closes at an
acceptor site of a permitted class, and the reading frame continues across
each intron. The implementation expands the three labels into 30 states so
that every condition can be checked from local context.
Output filtering:
FASTA records shorter than min_record_length are skipped before sequence
encoding and Viterbi decoding. The production default is 100,000 bp;
zero disables this record-level filter.
Gene models whose whole spliced CDS is shorter than ``min_cds_length`` are
omitted after decoding. The production default is
``MIN_CDS_LENGTH_BP`` (96 bp); zero disables this gene-level filter.
This output filter does not constrain individual exon lengths or alter the
Viterbi path.
Gene confidence:
Every complete gene carries ``confidence``, the confidence network's
estimate of the probability that its structure is exactly correct, in its
GFF3 gene attributes and FASTA headers. Genes truncated by a record edge
are not scored and carry ``confidence=NA``. All genes are written;
filtering at a threshold is left to downstream tools such as
evaluation.py, whose gene-level results use a threshold of 0.1.
"""
import argparse
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from constants import (
CHUNK_SIZE_MBP,
CODON_TABLE_PATH,
CONFIDENCE_THRESHOLD,
CONFIDENCE_NETWORK_PATH,
MAX_BOUNDARY_INTRON_LENGTH_BP,
MIN_CDS_LENGTH_BP,
MIN_RECORD_LENGTH_BP,
NEGATIVE_STRAND_PROBABILITY_COLUMN,
PARQUET_BATCH_ROWS,
PARQUET_READ_BUFFER_BYTES,
POSITIVE_STRAND_PROBABILITY_COLUMN,
RECORD_ID_COLUMN,
SEQUENCE_COLUMN,
TRANSITION_NETWORK_PATH,
WARNING_DIRECTORY_SUFFIX,
WARNINGS_FILE_NAME,
)
from utils import (
load_codon_table, stop_codons_from_table,
probability_vector_from_arrow,
validate_max_boundary_intron_length,
encode_both_strands,
assemble_gene_model,
codon_table_mismatch,
write_gff3, write_cds_fasta, write_protein_fasta,
)
from confidence_network import load_confidence_network
from transition_network import load_transition_network
from viterbi import choose_viterbi_backend, decode_paths, iter_gene_exons_with_states
RAW_PROBABILITY_COLUMNS = (
RECORD_ID_COLUMN, SEQUENCE_COLUMN,
POSITIVE_STRAND_PROBABILITY_COLUMN, NEGATIVE_STRAND_PROBABILITY_COLUMN,
)
def default_output_prefix(input_path):
"""Return the default output prefix for one raw-probability file."""
for suffix in (".raw_probs.arrow", ".raw_probs.parquet"):
if input_path.endswith(suffix):
return input_path[:-len(suffix)] + ".predicted"
return os.path.splitext(input_path)[0] + ".predicted"
def read_probability_batches(input_path):
"""Return an iterator over the record batches of a raw-probability file.
The batches hold RAW_PROBABILITY_COLUMNS. The suffix selects the format:
``.arrow`` is an Arrow IPC file, as written by model inference, read one
record batch at a time; ``.parquet`` is a Parquet file with the same
columns, read PARQUET_BATCH_ROWS rows at a time.
"""
import pyarrow as pa
import pyarrow.parquet as pq
def check_columns(schema):
missing_columns = [column for column in RAW_PROBABILITY_COLUMNS if column not in schema.names]
if missing_columns:
raise ValueError(
f"raw-probability file {input_path} is missing columns: " + ", ".join(missing_columns)
)
if input_path.endswith(".arrow"):
reader = pa.ipc.open_file(pa.memory_map(input_path))
check_columns(reader.schema)
# Whole batches are read: selecting fields while reading copies the
# compressed batch into memory first.
return (
reader.get_batch(index).select(list(RAW_PROBABILITY_COLUMNS))
for index in range(reader.num_record_batches)
)
if input_path.endswith(".parquet"):
# Each column chunk is read through a buffer instead of whole, so a large
# row group is not held in memory at once; pyarrow's pre-buffering is
# off, since iter_prefetched_chunks already reads ahead.
parquet_file = pq.ParquetFile(input_path, pre_buffer=False, buffer_size=PARQUET_READ_BUFFER_BYTES)
check_columns(parquet_file.schema_arrow)
return parquet_file.iter_batches(batch_size=PARQUET_BATCH_ROWS, columns=list(RAW_PROBABILITY_COLUMNS))
raise ValueError(f"raw-probability file {input_path} must end in .arrow (Arrow IPC) or .parquet")
def iter_probability_chunks(batches, max_chunk_bp, min_record_length=0, filter_stats=None):
"""Read and encode strand tracks in chunks of at most ``max_chunk_bp`` bases.
``batches`` are record batches of RAW_PROBABILITY_COLUMNS
(read_probability_batches). Each record yields two tracks in transcript
orientation, ``(coding probabilities, encoded bases)`` for the forward
strand and for the reverse complement, each with a ``(record_id,
sequence, strand, length)`` context. A record whose two tracks hold at
most ``max_chunk_bp`` bases together joins a chunk with both, which the
CPU backend then decodes in parallel; a longer record joins one track at a
time, so that its two strands need not be held at once. Tracks that
exceed what is left of the open chunk start the next one, so a chunk
holds more than ``max_chunk_bp`` bases only when it is a single longer
track; a track is never split. Yields ``(tracks, track_contexts,
chunk_bp)``.
"""
tracks = []
track_contexts = []
chunk_bp = 0
for batch in batches:
record_ids = batch.column(RECORD_ID_COLUMN)
sequences = batch.column(SEQUENCE_COLUMN)
positive_probabilities = batch.column(POSITIVE_STRAND_PROBABILITY_COLUMN)
negative_probabilities = batch.column(NEGATIVE_STRAND_PROBABILITY_COLUMN)
for row_index in range(batch.num_rows):
sequence = sequences[row_index].as_py().upper()
record_length = len(sequence)
record_id = record_ids[row_index].as_py()
if record_length < min_record_length:
if filter_stats is not None:
filter_stats["record_count"] += 1
filter_stats["bp"] += record_length
continue
positive = probability_vector_from_arrow(positive_probabilities[row_index])
negative = probability_vector_from_arrow(negative_probabilities[row_index])
if len(positive) < record_length or len(negative) < record_length:
raise ValueError(
f"record {record_id!r} has {record_length} bases but "
f"probability lengths {len(positive)} and {len(negative)}"
)
positive = positive[:record_length]
negative = negative[:record_length]
forward_bases, reverse_bases = encode_both_strands(sequence)
strand_tracks = [
((positive, forward_bases), "+"),
((np.ascontiguousarray(negative[::-1]), reverse_bases), "-"),
]
if 2 * record_length <= max_chunk_bp:
units = [strand_tracks]
else:
units = [[strand_track] for strand_track in strand_tracks]
for unit in units:
unit_bp = len(unit) * record_length
# Tracks that do not fit in the open chunk start the next one.
if tracks and chunk_bp + unit_bp > max_chunk_bp:
yield tracks, track_contexts, chunk_bp
tracks = []
track_contexts = []
chunk_bp = 0
for track, strand in unit:
tracks.append(track)
track_contexts.append((record_id, sequence, strand, record_length))
chunk_bp += unit_bp
# A full chunk is handed over before the next record is read.
if chunk_bp >= max_chunk_bp:
yield tracks, track_contexts, chunk_bp
tracks = []
track_contexts = []
chunk_bp = 0
if tracks:
yield tracks, track_contexts, chunk_bp
def iter_prefetched_chunks(chunks):
"""Prepare the next chunk in a background thread while the caller processes the current one.
Reading and encoding the input overlaps the networks and the Viterbi
algorithm. Besides the current chunk, at most one prepared chunk is held;
while the last strand of a record is processed, that is the next record
read ahead.
"""
chunk_iterator = iter(chunks)
with ThreadPoolExecutor(max_workers=1) as executor:
next_chunk = executor.submit(next, chunk_iterator, None)
while True:
chunk = next_chunk.result()
if chunk is None:
return
next_chunk = executor.submit(next, chunk_iterator, None)
yield chunk
def decode_chunk_genes(
tracks, track_contexts, transition_network, viterbi_backend, stop_codons,
max_boundary_intron_length, min_cds_length, confidence_network,
):
"""Run the three post-processing stages on one chunk under one stop-codon set.
The chunk's transition log-odds are released once its Viterbi paths are
decoded. Returns ``(chunk_genes, short_gene_count, transition_seconds,
viterbi_seconds, confidence_seconds)``; each entry of ``chunk_genes`` is
``(gene, probabilities, oriented_exons)``.
"""
# Stage 1: transition log-odds for every oriented track of the chunk.
stage_started = time.perf_counter()
transition_log_odds = [transition_network.inference(probabilities) for probabilities, _ in tracks]
transition_seconds = time.perf_counter() - stage_started
# Stage 2: the Viterbi algorithm.
stage_started = time.perf_counter()
state_paths = decode_paths(
tracks,
transition_log_odds,
viterbi_backend,
stop_taa="TAA" in stop_codons,
stop_tag="TAG" in stop_codons,
stop_tga="TGA" in stop_codons,
max_boundary_intron_length=max_boundary_intron_length,
)
viterbi_seconds = time.perf_counter() - stage_started
del transition_log_odds
if len(state_paths) != len(track_contexts):
raise RuntimeError(
f"{viterbi_backend} Viterbi backend returned {len(state_paths)} paths "
f"for {len(track_contexts)} tracks"
)
# Gene models of the chunk, each with the oriented track and exons it
# was decoded from, grouped by strand: the confidence network reads each
# strand's decoded structure whole.
chunk_genes = []
strand_gene_indices = []
short_gene_count = 0
for state_path, track_context, (probabilities, _) in zip(state_paths, track_contexts, tracks):
record_id, sequence, strand, record_length = track_context
if len(state_path) != record_length:
raise RuntimeError(
f"{viterbi_backend} Viterbi backend returned path length {len(state_path)} "
f"for record {record_id!r} {strand} with {record_length} bases"
)
gene_indices = []
for oriented_exons, first_cds_state, last_cds_state in iter_gene_exons_with_states(state_path):
gene = assemble_gene_model(
record_id, sequence, oriented_exons, strand, record_length,
first_cds_state, last_cds_state,
stop_codons,
)
if gene is None:
continue
if len(gene["cds"]) < min_cds_length:
short_gene_count += 1
continue
gene["confidence"] = None
gene_indices.append(len(chunk_genes))
chunk_genes.append((gene, probabilities, oriented_exons))
strand_gene_indices.append((probabilities, gene_indices))
# Stage 3: the confidence of every complete gene of the chunk, strand by
# strand. Every written gene gives roles to its strand; only the complete
# ones are scored.
stage_started = time.perf_counter()
for probabilities, gene_indices in strand_gene_indices:
scored = [
position for position, gene_index in enumerate(gene_indices)
if chunk_genes[gene_index][0]["complete"]
]
if not scored:
continue
confidences = confidence_network.inference(
probabilities, [chunk_genes[gene_index][2] for gene_index in gene_indices], scored,
)
for position, confidence in zip(scored, confidences):
chunk_genes[gene_indices[position]][0]["confidence"] = float(confidence)
confidence_seconds = time.perf_counter() - stage_started
return chunk_genes, short_gene_count, transition_seconds, viterbi_seconds, confidence_seconds
def record_codon_table_warning(output_prefix, warning, stop_codons):
"""Record the outcome of the codon-table check where a batch run will see it.
A failed check (``warning`` is the message) is appended to
``WARNINGS_FILE_NAME`` in the parent of the output directory, one line per
run with the time and the directory name, and the output directory is
renamed with ``WARNING_DIRECTORY_SUFFIX``, so a batch run shows every
doubtful genome in one file and in the directory names. A passed check in
a directory that carries the suffix, typically a rerun with the right
codon table, renames it back and records that too. Returns the output
prefix after any rename. The directory is left alone when the new name is
taken or when it is the working directory.
"""
output_dir = os.path.dirname(os.path.abspath(output_prefix))
clean_dir = output_dir[:-len(WARNING_DIRECTORY_SUFFIX)] if output_dir.endswith(WARNING_DIRECTORY_SUFFIX) else output_dir
flagged_dir = clean_dir + WARNING_DIRECTORY_SUFFIX
if warning is not None:
entry = warning
target = flagged_dir
elif output_dir == flagged_dir:
entry = f"cleared: the codon-table check passed with stops={'+'.join(stop_codons)}"
target = clean_dir
else:
return output_prefix
with open(os.path.join(os.path.dirname(clean_dir), WARNINGS_FILE_NAME), "a") as handle:
handle.write(f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}\t{os.path.basename(clean_dir)}\t{entry}\n")
if target == output_dir:
return output_prefix
if os.path.exists(target) or output_dir == os.getcwd():
print(
f"[post_processing] leaving {output_dir} in place: {target} exists or it is the working directory",
file=sys.stderr, flush=True,
)
return output_prefix
os.rename(output_dir, target)
return os.path.join(target, os.path.basename(output_prefix))
def post_process_probability_file(
input_path, output_prefix, viterbi_backend, codon_to_amino_acid,
transition_network, confidence_network,
max_boundary_intron_length, chunk_mbp=None,
min_record_length=MIN_RECORD_LENGTH_BP,
min_cds_length=MIN_CDS_LENGTH_BP,
):
"""Post-process one raw-probability file into GFF3, CDS FASTA, and protein FASTA.
``viterbi_backend`` is the name returned by ``choose_viterbi_backend``;
``chunk_mbp`` defaults to the backend's chunk size (CHUNK_SIZE_MBP).
When the confidences of the complete genes contradict the codon table
(utils.codon_table_mismatch), the warning is printed and recorded in the
directory layout by ``record_codon_table_warning``.
"""
file_started = time.perf_counter()
stop_codons = tuple(stop_codons_from_table(codon_to_amino_acid))
if chunk_mbp is None:
chunk_mbp = CHUNK_SIZE_MBP[viterbi_backend]
genes = []
short_gene_count = 0
total_bp = 0
transition_seconds = 0.0
viterbi_seconds = 0.0
confidence_seconds = 0.0
filter_stats = {"record_count": 0, "bp": 0}
input_chunks = iter_probability_chunks(
read_probability_batches(input_path),
chunk_mbp * 1_000_000,
min_record_length=min_record_length,
filter_stats=filter_stats,
)
for tracks, track_contexts, chunk_bp in iter_prefetched_chunks(input_chunks):
(
chunk_genes, chunk_short_gene_count,
chunk_transition_seconds, chunk_viterbi_seconds, chunk_confidence_seconds,
) = decode_chunk_genes(
tracks, track_contexts, transition_network, viterbi_backend, stop_codons,
max_boundary_intron_length, min_cds_length, confidence_network,
)
short_gene_count += chunk_short_gene_count
transition_seconds += chunk_transition_seconds
viterbi_seconds += chunk_viterbi_seconds
confidence_seconds += chunk_confidence_seconds
genes.extend(gene for gene, _, _ in chunk_genes)
total_bp += chunk_bp
genes.sort(key=lambda gene: (gene["record_id"], gene["exons"][0][0]))
write_gff3(genes, output_prefix + ".gff")
write_cds_fasta(genes, output_prefix + ".fna")
protein_count = write_protein_fasta(genes, output_prefix + ".faa", codon_to_amino_acid)
total_seconds = time.perf_counter() - file_started
rate = total_bp / viterbi_seconds / 1e6 if viterbi_seconds else 0.0
confidences = sorted(gene["confidence"] for gene in genes if gene["confidence"] is not None)
scored_gene_count = len(confidences)
median_confidence = confidences[len(confidences) // 2] if confidences else float("nan")
confident_gene_count = sum(confidence >= CONFIDENCE_THRESHOLD for confidence in confidences)
warning = None
contradicting_groups = codon_table_mismatch(genes, stop_codons)
if contradicting_groups:
group_counts = "; ".join(
f"{confident_count} of {gene_count} {group} ({confident_count / gene_count:.0%})"
for group, confident_count, gene_count in contradicting_groups
)
warning = (
f"WARNING: too few complete genes reach confidence {CONFIDENCE_THRESHOLD} "
f"with stops={'+'.join(stop_codons)}: {group_counts}. "
f"The codon table probably does not match this genome; check --codon_table."
)
print(f"[post_processing] {warning}", file=sys.stderr, flush=True)
output_prefix = record_codon_table_warning(output_prefix, warning, stop_codons)
print(
f"[post_processing] viterbi_backend={viterbi_backend} stops={'+'.join(stop_codons)} "
f"max_boundary_intron_length={max_boundary_intron_length} "
f"min_record_length={min_record_length} "
f"{os.path.basename(input_path)}: {total_bp / 1e6:.0f} Mbp; "
f"transition network {transition_seconds:.1f}s; "
f"Viterbi {viterbi_seconds:.1f}s ({rate:.0f} Mbp/s); "
f"confidence network {confidence_seconds:.1f}s "
f"({scored_gene_count} genes scored, {confident_gene_count} at or above {CONFIDENCE_THRESHOLD}, "
f"median confidence {median_confidence:.3f}); "
f"{total_seconds:.1f}s end to end -> {len(genes)} genes "
f"({short_gene_count} shorter than {min_cds_length} bp omitted) "
f"({filter_stats['record_count']} records / "
f"{filter_stats['bp'] / 1e6:.1f} Mbp shorter than "
f"{min_record_length} bp skipped) "
f"-> {output_prefix}.gff/.fna/.faa ({protein_count} proteins)",
flush=True,
)
def parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--input", required=True, help="one *.raw_probs.arrow or *.raw_probs.parquet file")
parser.add_argument("--output", default=None, help="output prefix; defaults to <input>.predicted")
parser.add_argument(
"--viterbi_backend",
choices=["auto", "gpu", "cpu", "numba"],
default="auto",
help="Viterbi backend: gpu (CUDA), cpu (C++/OpenMP), or numba (reference); auto prefers gpu",
)
parser.add_argument(
"--codon_table",
default=str(CODON_TABLE_PATH),
help=(
"JSON object mapping all 64 ATCG codons to amino acids; '*' marks "
"stop codons"
),
)
parser.add_argument(
"--transition_network",
default=str(TRANSITION_NETWORK_PATH),
help="transition network weights (default: weights/transition_network.safetensors)",
)
parser.add_argument(
"--confidence_network",
default=str(CONFIDENCE_NETWORK_PATH),
help="confidence network weights (default: weights/confidence_network.safetensors)",
)
parser.add_argument(
"--tcn_device",
default=None,
help=(
"torch device for the transition and confidence networks "
"(default: cuda if available, else cpu)"
),
)
parser.add_argument(
"--max_boundary_intron_length",
type=int,
default=MAX_BOUNDARY_INTRON_LENGTH_BP,
help=(
"maximum visible boundary-intron length in bp; -1 is unlimited; "
"0 disables boundary introns, leaving only exon-truncated incomplete genes"
),
)
parser.add_argument(
"--chunk_mbp",
type=int,
default=None,
help=(
f"host-side chunk size in megabases (default: {CHUNK_SIZE_MBP['gpu']}, or "
f"{CHUNK_SIZE_MBP['cpu']} with the CPU Viterbi backend, which decodes the strands "
"of a chunk in parallel); post-processing takes about 50 MB of memory per megabase "
"of its largest chunk; a strand is never split, so a longer one is a chunk of its own"
),
)
parser.add_argument(
"--min_record_length",
type=int,
default=MIN_RECORD_LENGTH_BP,
help=(
"minimum input FASTA record length in bp; shorter records are skipped "
"before decoding (0 disables)"
),
)
parser.add_argument(
"--min_cds_length",
type=int,
default=MIN_CDS_LENGTH_BP,
help=(
"minimum spliced CDS length in bp for output gene models; "
"shorter models are omitted (0 disables)"
),
)
args = parser.parse_args()
try:
args.max_boundary_intron_length = validate_max_boundary_intron_length(
args.max_boundary_intron_length
)
except (TypeError, ValueError) as exc:
parser.error(str(exc))
if args.min_record_length < 0:
parser.error("--min_record_length must be non-negative")
if args.min_cds_length < 0:
parser.error("--min_cds_length must be non-negative")
return args
def main():
"""Command-line entry point."""
args = parse_args()
try:
codon_to_amino_acid = load_codon_table(args.codon_table)
except OSError as exc:
raise SystemExit(f"error: cannot read codon table {args.codon_table}: {exc}") from exc
except ValueError as exc:
raise SystemExit(f"error: {exc}") from exc
output_prefix = args.output or default_output_prefix(args.input)
viterbi_backend = choose_viterbi_backend(args.viterbi_backend)
device = torch.device(args.tcn_device or ("cuda" if torch.cuda.is_available() else "cpu"))
transition_network = load_transition_network(args.transition_network, device)
confidence_network = load_confidence_network(args.confidence_network, device)
post_process_probability_file(
args.input, output_prefix, viterbi_backend, codon_to_amino_acid,
transition_network, confidence_network,
max_boundary_intron_length=args.max_boundary_intron_length,
chunk_mbp=args.chunk_mbp,
min_record_length=args.min_record_length,
min_cds_length=args.min_cds_length,
)
if __name__ == "__main__":
main()