API reference
The command-line workflows in Usage cover most projects. The interfaces below support custom Python workflows.
Data
Schemas and encoding
- class transcriptml.data.schemas.SequenceSchema(name, channels, base_channels=('A', 'C', 'G', 'U'), description='')[source]
Channel schema for an encoded RNA tensor.
Arrays in TranscriptML use PyTorch convention:
(N, C, L)for batches and(C, L)for a single sequence.- Parameters:
name (str)
channels (Tuple[str, ...])
base_channels (Tuple[str, ...])
description (str)
- property n_channels: int
Return the total number of channels in the schema.
- property n_base_channels: int
Return the number of nucleotide base channels.
- property annotation_channels: Tuple[str, ...]
Return non-base annotation channel names.
- to_dict()[source]
Serialize the schema to a JSON-compatible dictionary.
- Return type:
Dict[str,object]
- transcriptml.data.schemas.get_schema(schema)[source]
Resolve a schema name or return an existing schema object.
- Parameters:
schema (
str|SequenceSchema) – Registered schema name or an already constructedSequenceSchemainstance.- Return type:
- transcriptml.data.encoding.fixed_length_sequence(seq, length, *, truncate_from='5prime')[source]
Right-pad short sequences and truncate long sequences.
truncate_from="5prime"preserves the 3-prime-most bases, matching the Saluki-style legacy pipeline. The returned offset is the number of original bases removed from the 5-prime side.- Parameters:
seq (
str) – Input nucleotide sequence. Values are coerced tostr.length (
int) – Positive fixed output length.truncate_from (
str) – Side to truncate whenseqis longer thanlength; accepts"5prime"/"left"or"3prime"/"right".
- Return type:
tuple[str,int]
- transcriptml.data.encoding.encode_rna_sequence(seq, *, length=None, dtype=<class 'numpy.uint8'>, truncate_from='5prime')[source]
Encode RNA sequence as
(4, L)A/C/G/U one-hot.T is treated as U. N and all unknown symbols are encoded as all-zero columns.
- Parameters:
seq (
str) – Input RNA or DNA sequence string.length (
int|None) – Optional fixed length. When provided, the sequence is padded or truncated before encoding.dtype (
dtype|type) – NumPy dtype for the returned one-hot array.truncate_from (
str) – Side to truncate whenlengthis provided andseqis too long.
- Return type:
ndarray
- transcriptml.data.encoding.encode_sequences(seqs, *, length=None, dtype=<class 'numpy.uint8'>, truncate_from='5prime')[source]
Encode a collection of RNA sequences as
(N, 4, L).- Parameters:
seqs (
Sequence[str]) – Sequence of RNA or DNA sequence strings to encode.length (
int|None) – Optional fixed length for every encoded sequence. When omitted, the maximum input sequence length is used.dtype (
dtype|type) – NumPy dtype for the returned one-hot array.truncate_from (
str) – Side to truncate when fixed-length encoding shortens a sequence.
- Return type:
ndarray
- transcriptml.data.encoding.encode_saluki_transcript(seq, *, length=12288, cds_positions=None, splice_positions=None, dtype=<class 'numpy.uint8'>)[source]
Encode a transcript as Saluki-style
(6, L).Short transcripts are right-padded with N/all-zero columns. Long transcripts are truncated from the 5-prime side so the represented window is the 3-prime-most
lengthbases. Annotation positions are expected in original transcript coordinates and are shifted by the same truncation offset.- Parameters:
seq (
str) – Input transcript sequence.length (
int) – Fixed Saluki input length.cds_positions (
Optional[Iterable[int]]) – Optional CDS annotation positions in original transcript coordinates.splice_positions (
Optional[Iterable[int]]) – Optional splice annotation positions in original transcript coordinates.dtype (
dtype|type) – NumPy dtype for the returned encoded array.
- Return type:
ndarray
- transcriptml.data.encoding.infer_valid_length(x, *, base_channels=None)[source]
Infer the last represented non-zero column plus one.
This follows the legacy convention that N-padding is contiguous all-zero padding at the right edge. Unknown all-zero bases inside a valid transcript are allowed; they do not by themselves end the sequence.
- Parameters:
x (
ndarray) – Encoded(C, L)sequence array.base_channels (
int|None) – Optional number of leading channels to inspect. WhenNone, all channels are considered.
- Return type:
int
- transcriptml.data.encoding.infer_valid_lengths(X, *, base_channels=None)[source]
Infer valid sequence lengths for a batch of encoded arrays.
- Parameters:
X (
ndarray) – Encoded(N, C, L)batch array.base_channels (
int|None) – Optional number of leading channels to inspect for each sequence. WhenNone, all channels are considered.
- Return type:
ndarray
- transcriptml.data.encoding.decode_rna_one_hot(x, *, unknown='N')[source]
Decode base channels without treating all-zero columns as A.
- Parameters:
x (
ndarray) – Encoded array with at least four leading base channels and shape(C, L).unknown (
str) – Character to emit for ambiguous or all-zero columns.
- Return type:
str
Dataset bundles and builders
- class transcriptml.data.bundle.DatasetBundle(X, y=None, ids=None, schema='rna4', metadata=None, splits=None, config=<factory>)[source]
Self-describing processed dataset.
- Parameters:
X (ndarray)
y (ndarray | None)
ids (Sequence[str] | None)
schema (SequenceSchema | str)
metadata (Sequence[Mapping[str, Any]] | None)
splits (Mapping[str, Sequence[int]] | None)
config (Mapping[str, Any])
- transcriptml.data.bundle.save_bundle_metadata(bundle, out_dir)[source]
Write dataset sidecar metadata files for an existing
X.npy.- Parameters:
bundle (
DatasetBundle) – Dataset bundle whose identifiers, schema, metadata, splits, and config should be serialized.out_dir (
str|Path) – Directory that already contains or will sit beside the bundle arrays.
- Return type:
None
- transcriptml.data.bundle.save_bundle(bundle, out_dir)[source]
Write a complete dataset bundle, including arrays and sidecars.
- Parameters:
bundle (
DatasetBundle) – Dataset bundle containingXand optionalyarrays plus sidecar metadata.out_dir (
str|Path) – Destination directory for the complete on-disk bundle.
- Return type:
None
- transcriptml.data.bundle.load_bundle(path, *, mmap_mode=None)[source]
Load a processed dataset bundle from disk.
- Parameters:
path (
str|Path) – Directory containingX.npyand TranscriptML sidecar files.mmap_mode (
str|None) – Optional NumPy memory-map mode to pass when loading arrays.
- Return type:
- transcriptml.data.builders.build_mpra_dataset(table_path, out_dir, *, sequence_col, target_col=None, id_col=None, length=None, metadata_cols=None, split_col=None, delimiter=None, progress=True)[source]
Build an RNA4 MPRA dataset from a delimited table.
- Parameters:
table_path (
str|Path) – Input CSV/TSV-like table containing sequences and optional targets.out_dir (
str|Path) – Directory where the processed dataset bundle is written.sequence_col (
str) – Column containing RNA or DNA sequence strings.target_col (
str|None) – Optional column containing scalar regression targets.id_col (
str|None) – Optional column containing stable example identifiers. Row indices are used when omitted.length (
int|None) – Fixed encoded sequence length. WhenNone, the longest input sequence length is used.metadata_cols (
Optional[Sequence[str]]) – Optional columns to copy into bundle metadata. When omitted, non-sequence, non-target, and non-id columns are kept.split_col (
str|None) – Optional column with train/validation/test split labels.delimiter (
str|None) – Optional table delimiter override.progress (
bool) – Whether to emit progress messages while building the bundle.
- Return type:
- transcriptml.data.builders.build_saluki_dataset(*, table_path, out_dir, sequence_col, id_col, target_col=None, cds_positions_col=None, splice_positions_col=None, length=12288, metadata_cols=None, split_col=None, delimiter=None, progress=True)[source]
Build a Saluki-style fixed-length
(N, 6, L)transcript dataset.This table-based builder expects transcript sequences and optional transcript-coordinate annotation positions. Use
build_saluki_dataset_from_gtf()when starting from a genome FASTA and transcript annotation GTF.- Parameters:
table_path (
str|Path) – Input CSV/TSV-like table containing transcript sequences.out_dir (
str|Path) – Directory whereX.npyand bundle sidecars are written.sequence_col (
str) – Column containing transcript sequence strings.id_col (
str) – Column containing transcript or example identifiers.target_col (
str|None) – Optional column containing scalar regression targets.cds_positions_col (
str|None) – Optional column containing CDS position lists in transcript coordinates.splice_positions_col (
str|None) – Optional column containing splice position lists in transcript coordinates.length (
int) – Fixed Saluki input length to encode for every transcript.metadata_cols (
Optional[Sequence[str]]) – Optional columns to copy into bundle metadata. When omitted, non-input and non-target columns are kept.split_col (
str|None) – Optional column with train/validation/test split labels.delimiter (
str|None) – Optional table delimiter override.progress (
bool) – Whether to emit progress messages while building the bundle.
- Return type:
- transcriptml.data.builders.build_saluki_dataset_from_gtf(*, gtf_path, fasta_path, out_dir, targets_path=None, target_col=None, target_id_col='transcript_id', length=12288, metadata_cols=None, split_col=None, delimiter=None, progress=True)[source]
Build a Saluki-style dataset directly from transcript GTF and genome FASTA.
GTF parsing is implemented in pure Python to avoid pyranges/rtracklayer GTF compatibility issues. FASTA access uses
pyfaidxwhen installed and falls back to a small in-memory reader for tests or tiny toy genomes.- Parameters:
gtf_path (
str|Path) – GTF annotation file containing transcript exon and CDS features.fasta_path (
str|Path) – Genome FASTA file used to assemble spliced transcript sequences.out_dir (
str|Path) – Directory whereX.npyand bundle sidecars are written.targets_path (
str|Path|None) – Optional CSV/TSV-like target table used to select transcripts and provide labels or metadata.target_col (
str|None) – Optional target-table column containing scalar regression targets.target_id_col (
str) – Target-table column containing transcript identifiers that match GTFtranscript_idattributes.length (
int) – Fixed Saluki input length to encode for every transcript.metadata_cols (
Optional[Sequence[str]]) – Optional target-table columns to copy into bundle metadata.split_col (
str|None) – Optional target-table column with train/validation/test split labels.delimiter (
str|None) – Optional target-table delimiter override.progress (
bool) – Whether to emit progress messages while building the bundle.
- Return type:
Transcript annotation
- class transcriptml.data.genomics.GTFRecord(chrom, source, feature, start, end, score, strand, frame, attributes)[source]
A single GTF/GFF-like feature row with 0-based half-open coordinates.
- Parameters:
chrom (str)
source (str)
feature (str)
start (int)
end (int)
score (str)
strand (str)
frame (str)
attributes (Mapping[str, str])
- class transcriptml.data.genomics.TranscriptFeature(transcript_id, chrom, strand, exons, cds=(), attributes=<factory>)[source]
Genomic annotation needed to build one transcript.
- Parameters:
- property exon_count: int
Return the number of exon features in the transcript.
- property transcript_length: int
Return total spliced transcript length in nucleotides.
- class transcriptml.data.genomics.TranscriptRecord(transcript_id, sequence, cds_positions, splice_positions, metadata)[source]
A transcript sequence plus transcript-coordinate annotation channels.
- Parameters:
transcript_id (str)
sequence (str)
cds_positions (tuple[int, ...])
splice_positions (tuple[int, ...])
metadata (Mapping[str, object])
- transcriptml.data.genomics.reverse_complement(seq)[source]
Return the reverse complement of a DNA sequence.
- Parameters:
seq (
str) – DNA sequence string to reverse-complement.- Return type:
str
- transcriptml.data.genomics.parse_gtf_attributes(text)[source]
Parse GTF attributes without depending on pyranges/rtracklayer.
The parser accepts canonical GTF attributes such as
gene_id "G"; transcript_id "T";and common GFF3-stylekey=valueattributes found in converted files.- Parameters:
text (
str) – Raw ninth-column GTF/GFF attributes string.- Return type:
dict[str,str]
- transcriptml.data.genomics.iter_gtf_records(path, *, features=None)[source]
Yield GTF feature records using 0-based half-open coordinates.
- Parameters:
path (
str|Path) – GTF/GFF-like annotation file to read.features (
Optional[Sequence[str]]) – Optional feature names to keep, matched case-insensitively.
- Return type:
Iterator[GTFRecord]
- transcriptml.data.genomics.load_transcript_features(gtf_path, *, transcript_ids=None, progress=True)[source]
Load exon/CDS structures from a GTF without using pyranges.
- Parameters:
gtf_path (
str|Path) – GTF/GFF-like annotation file containing exon and CDS records.transcript_ids (
Union[set[str],Sequence[str],None]) – Optional transcript identifiers to retain. When omitted, all transcripts with exon records are loaded.progress (
bool) – Whether to emit progress messages while parsing.
- Return type:
dict[str,TranscriptFeature]
- transcriptml.data.genomics.extract_transcript_records(gtf_path, fasta_path, *, transcript_ids=None, progress=True)[source]
Extract transcript sequences and Saluki annotation positions from GTF/FASTA.
- Parameters:
gtf_path (
str|Path) – GTF/GFF-like annotation file containing transcript features.fasta_path (
str|Path) – Genome FASTA file used to assemble transcript sequences.transcript_ids (
Union[set[str],Sequence[str],None]) – Optional transcript identifiers to extract. When omitted, all annotated transcripts with exons are extracted.progress (
bool) – Whether to emit progress messages while extracting records.
- Return type:
list[TranscriptRecord]
- transcriptml.data.genomics.write_saluki_memmap(path, records, *, length=12288, dtype=<class 'numpy.uint8'>, progress=True)[source]
Encode transcript records to a Saluki
X.npyfile without a RAM-sized copy.- Parameters:
path (
str|Path) – Destination.npyfile for the memory-mapped encoded array.records (
Sequence[TranscriptRecord]) – Transcript records to encode in order.length (
int) – Fixed Saluki input length for each encoded transcript.dtype (
dtype|type) – NumPy dtype for the stored encoded array.progress (
bool) – Whether to emit progress messages while encoding.
- Return type:
memmap
Sequence controls
- class transcriptml.data.controls.SequenceControlOperation(operation, regions, shift=None)[source]
One sequence-control operation applied to one or more regions.
- Parameters:
operation (Literal['shuffle_nucleotides', 'shuffle_codons', 'randomize_nucleotides', 'cds_frameshift'])
regions (tuple[Literal['5utr', 'cds', '3utr', 'transcript'], ...])
shift (int | None)
- class transcriptml.data.controls.SequenceControlConfig(operations=(), seed=0, save_dir=None, save=False, cds_channel=None)[source]
Normalized training-time RNA sequence-control configuration.
- Parameters:
operations (tuple[SequenceControlOperation, ...])
seed (int)
save_dir (str | None)
save (bool)
cds_channel (str | int | None)
- transcriptml.data.controls.normalize_sequence_control_config(config)[source]
Normalize user-facing sequence-control config into explicit operations.
The preferred shape is:
{ "seed": 42, "operations": [ {"operation": "shuffle_nucleotides", "regions": ["5utr", "3utr"]}, {"operation": "shuffle_codons", "regions": ["cds"]}, {"operation": "cds_frameshift", "shift": 1} ], "save_dir": "data/saluki_control" }
Top-level shortcuts such as
"shuffle_nucleotides": ["5utr"]and the older5pUTR_ablation/CDS_ablation/3pUTR_ablationnames are also accepted.- Return type:
- Parameters:
config (object)
- transcriptml.data.controls.apply_sequence_controls_array(X, config, *, schema='saluki6', out_path=None, progress=True)[source]
Apply RNA sequence controls to an encoded array.
Base perturbations rewrite only base channels.
cds_frameshiftrewrites only the CDS/codon-start channel. The splice-junction channel is copied through unchanged.- Return type:
tuple[ndarray,dict[str,object]]- Parameters:
X (ndarray)
config (object)
schema (str | SequenceSchema)
out_path (str | Path | None)
progress (bool)
- transcriptml.data.controls.apply_sequence_controls_to_bundle(bundle, config, *, default_save_dir=None, progress=True)[source]
Apply sequence controls to a dataset bundle and optionally save it.
- Return type:
tuple[DatasetBundle,dict[str,object]]- Parameters:
bundle (DatasetBundle)
config (object)
default_save_dir (str | Path | None)
progress (bool)
Models
- class transcriptml.models.registry.ModelConfig(name, params=None)[source]
- Parameters:
name (str)
params (Dict[str, Any] | None)
- transcriptml.models.registry.list_models()[source]
Return registered model names mapped to their config class names.
- Return type:
dict[str,str]
- transcriptml.models.registry.model_default_params(name)[source]
Return default constructor parameters for a registered model.
- Parameters:
name (
str) – Registered model name.- Return type:
dict[str,Any]
- transcriptml.models.registry.build_model(config)[source]
Instantiate a registered model from configuration.
- Parameters:
config (
Union[ModelConfig,Mapping[str,Any],str]) – ModelConfig instance, mapping, or registered model name string.- Return type:
Module
- transcriptml.models.registry.save_checkpoint(path, model, model_config, *, epoch=None, metrics=None, optimizer_state=None, extra=None)[source]
Save model weights, model config, metrics, and optional training state.
- Parameters:
path (
str|Path) – Destination checkpoint path.model (
Module) – PyTorch module whose state dictionary should be saved.model_config (
Union[ModelConfig,Mapping[str,Any]]) – Model configuration used to reconstructmodel.epoch (
int|None) – Optional epoch number associated with the checkpoint.metrics (
Optional[Mapping[str,Any]]) – Optional metrics mapping to include in the checkpoint.optimizer_state (
Optional[Mapping[str,Any]]) – Optional optimizer state dictionary to include.extra (
Optional[Mapping[str,Any]]) – Optional additional top-level checkpoint fields.
- Return type:
None
- transcriptml.models.registry.load_checkpoint(path, *, map_location='cpu', strict=True)[source]
Load a TranscriptML checkpoint and rebuild its model.
- Parameters:
path (str | Path) – TranscriptML checkpoint path.
map_location (str | torch.device) – Torch map-location argument for device remapping.
strict (bool) – Whether to require an exact state-dictionary key match.
- Return type:
tuple[nn.Module, dict[str, Any]]
- class transcriptml.models.reproduce.SalukiExactConfig(seq_depth=6, filters=64, kernel_size=5, num_layers=6, dropout=0.3, augment_shift=3, ln_epsilon=0.007, keras_bn_momentum=0.9, bn_eps=0.001)[source]
- Parameters:
seq_depth (int)
filters (int)
kernel_size (int)
num_layers (int)
dropout (float)
augment_shift (int)
ln_epsilon (float)
keras_bn_momentum (float)
bn_eps (float)
- class transcriptml.models.reproduce.SalukiExact(seq_depth=6, filters=64, kernel_size=5, num_layers=6, dropout=0.3, augment_shift=3, ln_epsilon=0.007, keras_bn_momentum=0.9, bn_eps=0.001)[source]
Close PyTorch reproduction of the Basenji/Saluki rnann.py architecture.
- Parameters:
seq_depth (int)
filters (int)
kernel_size (int)
num_layers (int)
dropout (float)
augment_shift (int)
ln_epsilon (float)
keras_bn_momentum (float)
bn_eps (float)
- reset_parameters()[source]
Initialize weights to match the legacy Keras conventions.
- Return type:
None
- class transcriptml.models.saluki.SalukiLikeConfig(in_ch=6, base_ch=64, kernel_size=5, n_convs=4, pool_size=2, dropout=0.2, gru_hidden=64, gru_layers=1, bidirectional=False, head_hidden=64, output_dim=1)[source]
- Parameters:
in_ch (int)
base_ch (int)
kernel_size (int)
n_convs (int)
pool_size (int)
dropout (float)
gru_hidden (int)
gru_layers (int)
bidirectional (bool)
head_hidden (int)
output_dim (int)
- class transcriptml.models.saluki.SalukiLike(in_ch=6, base_ch=64, kernel_size=5, n_convs=4, pool_size=2, dropout=0.2, gru_hidden=64, gru_layers=1, bidirectional=False, head_hidden=64, output_dim=1)[source]
A minimal Saluki-inspired Conv/GRU model.
This keeps the useful shape of the legacy Saluki models without attempting to reproduce every experimental branch.
- Parameters:
in_ch (int)
base_ch (int)
kernel_size (int)
n_convs (int)
pool_size (int)
dropout (float)
gru_hidden (int)
gru_layers (int)
bidirectional (bool)
head_hidden (int)
output_dim (int)
- class transcriptml.models.legnet.LegNetConfig(in_ch=4, stem_ch=64, stem_ks=7, ef_ks=5, ef_block_sizes=<factory>, pool_sizes=<factory>, resize_factor=4, block_dropout=0.0, head_dropout=0.1, stem_dropout=0.0, output_dim=1)[source]
- Parameters:
in_ch (int)
stem_ch (int)
stem_ks (int)
ef_ks (int)
ef_block_sizes (list[int])
pool_sizes (list[int])
resize_factor (int)
block_dropout (float)
head_dropout (float)
stem_dropout (float)
output_dim (int)
- class transcriptml.models.legnet.LegNet(in_ch=4, stem_ch=64, stem_ks=7, ef_ks=5, ef_block_sizes=(64, 96, 128), pool_sizes=(2, 2, 2), resize_factor=4, block_dropout=0.0, head_dropout=0.1, stem_dropout=0.0, output_dim=1)[source]
A compact LegNet port based on the legacy implementation.
- Parameters:
in_ch (int)
stem_ch (int)
stem_ks (int)
ef_ks (int)
ef_block_sizes (list[int] | tuple[int, ...])
pool_sizes (list[int] | tuple[int, ...])
resize_factor (int)
block_dropout (float)
head_dropout (float)
stem_dropout (float)
output_dim (int)
- class transcriptml.models.cnn.SmallCNNConfig(in_ch=4, n_filters=64, kernel_size=9, n_layers=2, dropout=0.1, head_hidden=64, output_dim=1)[source]
- Parameters:
in_ch (int)
n_filters (int)
kernel_size (int)
n_layers (int)
dropout (float)
head_hidden (int)
output_dim (int)
- class transcriptml.models.cnn.SmallCNN(in_ch=4, n_filters=64, kernel_size=9, n_layers=2, dropout=0.1, head_hidden=64, output_dim=1)[source]
A compact sequence CNN baseline with global max/mean pooling.
- Parameters:
in_ch (int)
n_filters (int)
kernel_size (int)
n_layers (int)
dropout (float)
head_hidden (int)
output_dim (int)
Training and evaluation
- class transcriptml.training.trainer.TrainConfig(dataset, output_dir, model=<factory>, batch_size=64, epochs=20, learning_rate=0.001, weight_decay=0.0, gradient_clip_norm=0.5, patience=5, monitor='val_loss', loss=<factory>, device='cpu', num_workers=0, mmap_mode='r', seed=123, progress=True, sequence_controls=None, split_source='auto', split=<factory>)[source]
- Parameters:
dataset (str)
output_dir (str)
model (Mapping[str, Any])
batch_size (int)
epochs (int)
learning_rate (float)
weight_decay (float)
gradient_clip_norm (float | None)
patience (int)
monitor (str | Sequence[str])
loss (str | Mapping[str, Any] | None)
device (str)
num_workers (int)
mmap_mode (str | None)
seed (int)
progress (bool)
sequence_controls (Mapping[str, Any] | Sequence[Mapping[str, Any]] | None)
split_source (str)
split (Mapping[str, Any])
- transcriptml.training.trainer.train_model(bundle, config)[source]
Train a model from an in-memory dataset bundle and config.
- Parameters:
bundle (
DatasetBundle) – Dataset bundle containing encoded inputs and regression targets.config (
Union[TrainConfig,Mapping[str,Any]]) – Training configuration object or mapping of config fields.
- Return type:
dict[str,Any]
- transcriptml.training.trainer.train_from_config(config_path, *, progress=None)[source]
Load a training config and train its requested model.
- Parameters:
config_path (
str|Path) – Path to a JSON or TOML training configuration file.progress (
bool|None) – Optional override for whether progress messages are emitted.
- Return type:
dict[str,Any]
- class transcriptml.training.losses.LossOutput(loss, numerator, denominator)[source]
Scalar loss plus terms used for split-level aggregation.
- Parameters:
loss (torch.Tensor)
numerator (torch.Tensor)
denominator (torch.Tensor)
- class transcriptml.training.losses.TrainingLoss(*args, **kwargs)[source]
Base class for training losses that may consume auxiliary arrays.
- Parameters:
args (Any)
kwargs (Any)
- Return type:
Any
- class transcriptml.training.losses.RegressionMSELoss(*args, **kwargs)[source]
Unweighted mean squared error, matching the historical training loss.
- Parameters:
args (Any)
kwargs (Any)
- Return type:
Any
- class transcriptml.training.losses.WeightedMSELoss(*args, **kwargs)[source]
Weighted MSE using precomputed per-example weights.
- Parameters:
args (Any)
kwargs (Any)
- Return type:
Any
- class transcriptml.training.losses.BinomialNLLLoss(*, eps=1e-07, max_rate_time=80.0, log_base='e')[source]
Per-read binomial negative log likelihood for pulse-labeling counts.
The model prediction is interpreted as log(kdeg). The likelihood omits the binomial coefficient because it is constant with respect to model parameters; the optimized objective is therefore binomial cross entropy.
- Parameters:
eps (float)
max_rate_time (float)
log_base (str | float)
- transcriptml.training.losses.build_training_loss(config, *, metadata, n_examples)[source]
Build a configured training loss and aligned auxiliary arrays.
- Parameters:
config (
Union[str,Mapping[str,Any],None]) – Loss configuration.Noneand"mse"preserve historical unweighted MSE behavior.metadata (
Optional[Sequence[Mapping[str,Any]]]) – Optional bundle metadata aligned to examples.n_examples (
int) – Number of examples in the bundle.
- Return type:
tuple[TrainingLoss,dict[str,ndarray],dict[str,Any]]
- transcriptml.training.evaluation.predict_array(model, X, *, batch_size=128, device='cpu', progress=True)
Predict scalar outputs for every example in an array.
- Parameters:
model (torch.nn.Module) – PyTorch model that returns one scalar prediction per example.
X (np.ndarray) – Encoded
(N, C, L)input array.batch_size (int) – Number of examples to score per prediction batch.
device (str | torch.device) – Torch device used for model execution.
progress (bool) – Whether to emit progress messages while predicting.
- Return type:
np.ndarray
- transcriptml.training.evaluation.evaluate_model(model, bundle, *, indices=None, batch_size=128, device='cpu', progress=True)[source]
Evaluate a model on a dataset bundle and optional subset indices.
- Parameters:
model (torch.nn.Module) – PyTorch model that returns one scalar prediction per example.
bundle (DatasetBundle) – Dataset bundle containing encoded inputs and optional targets.
indices (Sequence[int] | None) – Optional example indices to evaluate. When omitted, all examples are evaluated.
batch_size (int) – Number of examples to score per prediction batch.
device (str | torch.device) – Torch device used for model execution.
progress (bool) – Whether to emit progress messages while evaluating.
- Return type:
dict[str, object]
- transcriptml.training.evaluation.predict_to_csv(path, *, ids, predictions, targets=None, indices=None)[source]
Write prediction rows, and optional targets, to a CSV file.
- Parameters:
path (
str|Path) – Destination CSV path.ids (
Sequence[str]) – Example identifiers aligned topredictions.predictions (
Sequence[float]) – Scalar model predictions.targets (
Optional[Sequence[float]]) – Optional scalar targets aligned topredictions.indices (
Optional[Sequence[int]]) – Optional original dataset indices aligned topredictions.
- Return type:
None
- transcriptml.training.evaluation.evaluate_checkpoint(checkpoint_path, dataset_path, out_csv=None, *, split=None, batch_size=128, device='cpu', progress=True)[source]
Load a checkpoint and evaluate it on a dataset bundle.
- Parameters:
checkpoint_path (str | Path) – TranscriptML checkpoint path to load.
dataset_path (str | Path) – Processed dataset bundle directory.
out_csv (str | Path | None) – Optional destination CSV path for predictions.
split (str | None) – Optional named split from the dataset bundle to evaluate.
batch_size (int) – Number of examples to score per prediction batch.
device (str | torch.device) – Torch device used for model execution.
progress (bool) – Whether to emit progress messages while evaluating.
- Return type:
dict[str, object]
- transcriptml.training.splits.random_split_indices(n, *, val_frac=0.1, test_frac=0.1, seed=None)[source]
Create reproducible random train/validation/test split indices.
- Parameters:
n (
int) – Total number of examples to split.val_frac (
float) – Fraction of examples assigned to validation.test_frac (
float) – Fraction of examples assigned to test.seed (
int|None) – Optional random seed for the permutation.
- Return type:
dict[str,list[int]]
- transcriptml.training.splits.predefined_split_indices(metadata, *, split_col='split', train_values=('train',), val_values=('val', 'valid', 'validation'), test_values=('test',))[source]
Create split indices from a metadata column.
- Parameters:
metadata (
Sequence[Mapping[str,object]]) – Sequence of per-example metadata mappings.split_col (
str) – Metadata key containing split labels.train_values (
Sequence[str]) – Labels interpreted as training examples.val_values (
Sequence[str]) – Labels interpreted as validation examples.test_values (
Sequence[str]) – Labels interpreted as test examples.
- Return type:
dict[str,list[int]]
- transcriptml.training.splits.normalize_splits(splits)[source]
Normalize split indices to mutable integer lists with standard keys.
- Parameters:
splits (
Mapping[str,Sequence[int]]) – Mapping from split names to index sequences.- Return type:
dict[str,list[int]]
Interpretation
- class transcriptml.interpret.predictor.Predictor(model, *, device='cpu', batch_size=128)[source]
Batched prediction wrapper for a model or callable.
- Parameters:
model (torch.nn.Module | Callable[[np.ndarray], np.ndarray])
device (str | torch.device)
batch_size (int)
- classmethod from_checkpoint(checkpoint_path, *, device='cpu', batch_size=128)[source]
Load a checkpoint and wrap the reconstructed model for prediction.
- Parameters:
checkpoint_path (str | Path) – Path to a TranscriptML checkpoint saved by the model registry.
device (str | torch.device) – Torch device used to load and run the model.
batch_size (int) – Default batch size for prediction.
- Return type:
Predictor
- predict(X, *, batch_size=None)
Predict one scalar output per input sequence.
- Parameters:
X (np.ndarray | torch.Tensor) – Encoded
(N, C, L)batch as a NumPy array or torch tensor.batch_size (int | None) – Optional batch-size override for this prediction call.
- Return type:
np.ndarray
- class transcriptml.interpret.predictor.EnsemblePredictor(predictors, *, reduction='mean')[source]
Mean or median reduction over multiple predictors.
- Parameters:
predictors (Sequence[Predictor])
reduction (str)
- predict(X, *, batch_size=None)[source]
Predict with each member and reduce predictions across members.
- Parameters:
X (np.ndarray | torch.Tensor) – Encoded
(N, C, L)batch as a NumPy array or torch tensor.batch_size (int | None) – Optional batch-size override forwarded to each member predictor.
- Return type:
np.ndarray
- class transcriptml.interpret.ism.ISMResult(deltas, reference_predictions, valid_lengths)[source]
- Parameters:
deltas (ndarray)
reference_predictions (ndarray)
valid_lengths (ndarray)
- transcriptml.interpret.ism.compute_ism(X, predictor, *, valid_lengths=None, mutation_batch_size=512, progress=True)[source]
Single-nucleotide ISM with signed mutant-minus-reference effects.
The returned
deltasarray has shape(N, 4, L). At each valid base position, the three alternative base channels store mutant-reference deltas; the original-base channel remains zero.- Parameters:
X (
ndarray) – Encoded(N, C, L)sequence batch with at least four base channels.predictor (
Predictor) – Predictor used to score reference and mutant sequences.valid_lengths (
ndarray|None) – Optional valid lengths for each sequence. When omitted, lengths are inferred fromX.mutation_batch_size (
int) – Maximum number of mutant sequences to score in one prediction batch.progress (
bool) – Whether to emit progress messages while scanning.
- Return type:
- transcriptml.interpret.ism.max_abs_effect_per_position(deltas)[source]
Summarize ISM effects by maximum absolute base substitution effect.
- Parameters:
deltas (
ndarray) – ISM delta array with shape(N, 4, L).- Return type:
ndarray
- transcriptml.interpret.ism.save_ism_result(result, out_dir, *, progress=True)[source]
Save ISM result arrays and a small JSON summary.
- Parameters:
result (
ISMResult) – ISM result object to serialize.out_dir (
str|Path) – Destination directory for arrays and summary JSON.progress (
bool) – Whether to emit progress messages while saving.
- Return type:
None
- class transcriptml.interpret.codon_ism.CodonISMResult(mutations, reference_predictions, valid_lengths, sequence_indices, position_scores=None)[source]
Result from codon-level mutational scanning.
- Parameters:
mutations (ndarray)
reference_predictions (ndarray)
valid_lengths (ndarray)
sequence_indices (ndarray)
position_scores (ndarray | None)
- transcriptml.interpret.codon_ism.mutation_table_writer(path, *, format='auto', rows_per_shard=100000)[source]
Create a streaming mutation-table writer from a path and format.
- Parameters:
path (
str|Path) – Output file path or NPZ shard directory, depending on format.format (
Literal['auto','csv','npz','parquet','arrow']) – Output format.autoinfers frompathsuffix and falls back to chunked NPZ.rows_per_shard (
int) – Maximum rows per NPZ shard whenformatisnpzor resolves to NPZ.
- Return type:
MutationTableWriter
- transcriptml.interpret.codon_ism.compute_codon_ism(X, predictor, *, schema='saluki6', valid_lengths=None, cds_channel=None, mutation_policy='synonymous-only', include_stop_codons=True, reference_batch_size=None, mutation_batch_size=512, compute_position_scores=False, writer=None, collect=True, sequence_indices=None, sequence_start=None, sequence_end=None, sequence_shard_index=None, sequence_shards=None, device='cpu', progress=True)
Run codon-level ISM and return mutant-minus-reference effects.
The primary output is a tidy long-form mutation table in
result.mutations. For large analyses, pass awriterandcollect=Falseto stream chunks without retaining every mutation row in memory.- Parameters:
X (np.ndarray | torch.Tensor) – Encoded
(N, C, L)sequence batch as a NumPy array or torch tensor.predictor (Predictor | torch.nn.Module | Callable[[np.ndarray], np.ndarray]) – Predictor, PyTorch module, or callable used to score reference and mutant sequences.
schema (str | SequenceSchema) – Sequence schema name or object describing channel layout.
valid_lengths (Sequence[int] | None) – Optional valid lengths for each sequence. When omitted, lengths are inferred from
X.cds_channel (str | int | None) – Optional CDS channel name or integer index. When omitted, the CDS channel is inferred from
schema.mutation_policy (MutationPolicy) – Alternate-codon policy, either synonymous-only or all codons.
include_stop_codons (bool) – Whether all-codon mode may include stop-codon alternates.
reference_batch_size (int | None) – Optional batch size for reference predictions.
mutation_batch_size (int) – Maximum number of mutant sequences to score in one prediction batch.
compute_position_scores (bool) – Whether to compute per-position max-absolute codon effects.
writer (MutationTableWriter | None) – Optional streaming writer for long-form mutation rows.
collect (bool) – Whether to retain mutation rows in
result.mutations.sequence_indices (Sequence[int] | None) – Optional subset of sequence indices to analyze.
sequence_start (int | None) – Optional inclusive sequence index for starting a contiguous input slice.
sequence_end (int | None) – Optional exclusive sequence index for ending a contiguous input slice.
sequence_shard_index (int | None) – Optional zero-based shard index for splitting the input sequences into equal contiguous chunks.
sequence_shards (int | None) – Optional total number of sequence shards.
device (str | torch.device) – Torch device used when
predictoris a raw PyTorch module.progress (bool) – Whether to emit progress messages while scanning.
- Return type:
CodonISMResult
- transcriptml.interpret.codon_ism.save_codon_ism_result(result, out_dir, *, save_mutations=True, progress=True)[source]
Save codon ISM arrays and, optionally, the in-memory mutation table.
- Parameters:
result (
CodonISMResult) – Codon ISM result object to serialize.out_dir (
str|Path) – Destination directory for arrays and summary JSON.save_mutations (
bool) – Whether to save in-memory mutation rows as compressed NPZ columns.progress (
bool) – Whether to emit progress messages while saving.
- Return type:
None
- class transcriptml.interpret.ablation.MotifAblationResult(instances, reference_predictions, ablation_predictions, effects, region=None)[source]
- Parameters:
instances (list[MotifInstance])
reference_predictions (ndarray)
ablation_predictions (ndarray)
effects (ndarray)
region (str | None)
- transcriptml.interpret.ablation.motif_ablation(X, predictor, *, motif, n_scrambles=10, strategy='random_different', seed=123, valid_lengths=None, region=None, schema='saluki6', cds_channel=None, progress=True)[source]
Compute motif ablation effect
A - Rfor each motif instance.- Parameters:
X (
ndarray) – Encoded(N, C, L)sequence batch with base channels first.predictor (
Predictor) – Predictor used to score reference and ablated sequences.motif (
str) – Motif string accepted byparse_motif.n_scrambles (
int) – Number of scrambled ablations to average per motif instance.strategy (
str) – Scrambling strategy name supported by the edits module.seed (
int) – Random seed used for ablation scrambling.valid_lengths (
Optional[Sequence[int]]) – Optional valid lengths for each sequence. When omitted, lengths are inferred fromX.region (
str|None) – Optional region filter limiting motif sites to5utr,cds, or3utr.schema (
str|SequenceSchema) – Sequence schema name or object used for region-aware scans.cds_channel (
str|int|None) – Optional CDS channel name or integer index for region filtering.progress (
bool) – Whether to emit progress messages while running the scan.
- Return type:
- transcriptml.interpret.ablation.save_motif_ablation_result(result, out_dir, *, progress=True)[source]
Save motif ablation arrays, instance table, and summary metadata.
- Parameters:
result (
MotifAblationResult) – Motif ablation result object to serialize.out_dir (
str|Path) – Destination directory for arrays, tables, and summary JSON.progress (
bool) – Whether to emit progress messages while saving.
- Return type:
None
- class transcriptml.interpret.context.MotifContextResult(instances, ablation_effects, context_effects, context_mask, reference_predictions, ablation_predictions, region=None)[source]
- Parameters:
instances (list[MotifInstance])
ablation_effects (ndarray)
context_effects (ndarray)
context_mask (ndarray)
reference_predictions (ndarray)
ablation_predictions (ndarray)
region (str | None)
- transcriptml.interpret.context.motif_context_scan(X, predictor, *, motif, window_size=5, context_width=None, n_motif_scrambles=10, n_window_scrambles=5, strategy='random_different', seed=123, valid_lengths=None, region=None, schema='saluki6', cds_channel=None, progress=True)[source]
Scan context windows with effect
(MA - M) - (A - R).- Parameters:
X (
ndarray) – Encoded(N, C, L)sequence batch with base channels first.predictor (
Predictor) – Predictor used to score reference, motif-ablated, and context-scrambled sequences.motif (
str) – Motif string accepted byparse_motif.window_size (
int) – Width of each context window to scramble.context_width (
int|None) – Maximum distance from the motif to scan. WhenNone, the full sequence length is considered.n_motif_scrambles (
int) – Number of motif ablations to average per context estimate.n_window_scrambles (
int) – Number of context-window scrambles to average.strategy (
str) – Scrambling strategy name supported by the edits module.seed (
int) – Random seed used for motif and context scrambling.valid_lengths (
Optional[Sequence[int]]) – Optional valid lengths for each sequence. When omitted, lengths are inferred during motif enumeration.region (
str|None) – Optional region filter limiting motif sites to5utr,cds, or3utr.schema (
str|SequenceSchema) – Sequence schema name or object used for region-aware scans.cds_channel (
str|int|None) – Optional CDS channel name or integer index for region filtering.progress (
bool) – Whether to emit progress messages while scanning.
- Return type:
- transcriptml.interpret.context.save_motif_context_result(result, out_dir, *, progress=True)[source]
Save motif context scan arrays, instance table, and summary metadata.
- Parameters:
result (
MotifContextResult) – Motif context scan result object to serialize.out_dir (
str|Path) – Destination directory for arrays, tables, and summary JSON.progress (
bool) – Whether to emit progress messages while saving.
- Return type:
None
- class transcriptml.interpret.epistasis.EpistasisResult(pairs, reference_predictions, single_ablation_predictions, paired_ablation_predictions, single_ablation_effects, paired_ablation_effects, epistasis, region=None)[source]
- Parameters:
pairs (list[PairRecord])
reference_predictions (ndarray)
single_ablation_predictions (ndarray)
paired_ablation_predictions (ndarray)
single_ablation_effects (ndarray)
paired_ablation_effects (ndarray)
epistasis (ndarray)
region (str | None)
- transcriptml.interpret.epistasis.motif_epistasis(X, predictor, *, motif, motif2=None, n_scrambles=10, strategy='random_different', seed=123, skip_overlaps=True, max_pairs=None, valid_lengths=None, region=None, schema='saluki6', cds_channel=None, progress=True)[source]
Compute pairwise epistasis
A12 - A1 - A2 + R.- Parameters:
X (
ndarray) – Encoded(N, C, L)sequence batch with base channels first.predictor (
Predictor) – Predictor used to score reference and ablated sequences.motif (
str) – Primary motif string accepted byparse_motif.motif2 (
str|None) – Optional secondary motif string. When omitted, pairs are formed among sites ofmotif.n_scrambles (
int) – Number of scrambled ablations to average for each single or paired ablation.strategy (
str) – Scrambling strategy name supported by the edits module.seed (
int) – Random seed used for ablation scrambling.skip_overlaps (
bool) – Whether to exclude overlapping motif-site pairs.max_pairs (
int|None) – Optional cap on the number of pairs to score.valid_lengths (
Optional[Sequence[int]]) – Optional valid lengths for each sequence. When omitted, lengths are inferred fromX.region (
str|None) – Optional region filter limiting motif sites to5utr,cds, or3utr.schema (
str|SequenceSchema) – Sequence schema name or object used for region-aware scans.cds_channel (
str|int|None) – Optional CDS channel name or integer index for region filtering.progress (
bool) – Whether to emit progress messages while running the analysis.
- Return type:
- transcriptml.interpret.epistasis.save_epistasis_result(result, out_dir, *, progress=True)[source]
Save epistasis arrays, pair table, and summary metadata.
- Parameters:
result (
EpistasisResult) – Epistasis result object to serialize.out_dir (
str|Path) – Destination directory for arrays, tables, and summary JSON.progress (
bool) – Whether to emit progress messages while saving.
- Return type:
None
- transcriptml.interpret.motifs.parse_motif(motif)[source]
Parse motifs with A/C/G/U/T, bracket alternatives, and N/./X wildcards.
- Parameters:
motif (
str) – Motif string containing base letters,[A|C]-style alternatives, or wildcard charactersN,., andX.- Return type:
list[set[int]]
- transcriptml.interpret.motifs.motif_length(motif)[source]
Return motif length after expanding motif syntax.
- Parameters:
motif (
Union[str,Sequence[Set[int]]]) – Motif string or already parsed sequence of allowed-base sets.- Return type:
int
- transcriptml.interpret.motifs.base_indices_from_ohe(ohe_4_by_L)[source]
Return base index per position, or -1 for all-zero/ambiguous columns.
- Parameters:
ohe_4_by_L (
ndarray) – One-hot-like array with at least four base channels and shape(C, L).- Return type:
ndarray
- transcriptml.interpret.motifs.region_matches_motif(base_region, motif_sets)[source]
Return whether base indices match parsed motif position sets.
- Parameters:
base_region (
ndarray) – Base-index vector for a candidate sequence region.motif_sets (
Sequence[Set[int]]) – Parsed motif position sets describing allowed bases at each position.
- Return type:
bool
- transcriptml.interpret.motifs.find_motif_starts(ohe_4_by_L, motif)[source]
Find start positions where a motif matches one-hot base channels.
- Parameters:
ohe_4_by_L (
ndarray) – One-hot-like array with at least four base channels and shape(C, L).motif (
Union[str,Sequence[Set[int]]]) – Motif string or already parsed sequence of allowed-base sets.
- Return type:
ndarray
- transcriptml.interpret.motifs.intervals_overlap(a0, a1, b0, b1)[source]
Return whether two half-open intervals overlap.
- Parameters:
a0 (
int) – Zero-based inclusive start of the first interval.a1 (
int) – Zero-based exclusive end of the first interval.b0 (
int) – Zero-based inclusive start of the second interval.b1 (
int) – Zero-based exclusive end of the second interval.
- Return type:
bool
Plotting
Visualize single-nucleotide ISM arrays for one transcript sequence.
The core input is an ISM array with shape (N, 4, L), where channels are interpreted as A, C, G, U by default. An optional sequence/features array with shape (N, 4, L) or (N, 6, L) adds a contribution-scaled sequence-logo track and, for six-channel inputs, a compact transcript isoform diagram. Use –no-logo or show_logo=False for long regions where per-position letters are too dense.
- transcriptml.plotting.single_nt_ism.plot_single_nt_ism(ism, seq_index, *, seq_features=None, start=0, end=None, base_labels=('A', 'C', 'G', 'U'), title=None, gene_name=None, metadata_record=None, trim_padding=True, pad_atol=0.0, show_logo=True, show_isoform=True, cmap='RdBu_r', center=0.0, robust=True, symmetric=True, vmin=None, vmax=None, logo_vlim=None, logo_ylim=1.08, logo_font='DejaVu Sans', show_cbar=True, cbar_label='ISM value', show_xticks=True, max_xticks=12, xtick_rotation=0, mean_center=False, figsize=None)[source]
Plot ISM heatmap, optional sequence logo, and optional isoform diagram.
- Parameters:
ism (
ndarray) – Array with shape (N, 4, L). Rows are nucleotide channels.seq_index (
int) – Sequence index to plot.seq_features (
ndarray|None) – Optional array with shape (N, 4, L) or (N, 6, L). The first four channels must be one-hot nucleotide sequence. If six channels are supplied, channel 4 marks codon starts and channel 5 marks 5’ splice sites.start (
int) – Zero-based, end-exclusive region to plot.end (
int|None) – Zero-based, end-exclusive region to plot.show_logo (
bool) – If False, suppress the sequence-logo track even when sequence features are provided. The isoform diagram can still be drawn from six-channel sequence features.base_labels (str | Iterable[str])
title (str | None)
gene_name (str | None)
metadata_record (dict[str, Any] | None)
trim_padding (bool)
pad_atol (float)
show_isoform (bool)
cmap (str)
center (float)
robust (bool)
symmetric (bool)
vmin (float | None)
vmax (float | None)
logo_vlim (float | None)
logo_ylim (float)
logo_font (str)
show_cbar (bool)
cbar_label (str)
show_xticks (bool)
max_xticks (int)
xtick_rotation (int)
mean_center (bool)
figsize (tuple[float, float] | None)
- Return type:
tuple[Figure,dict[str,Axes|None]]
Run setup
- transcriptml.workflows.init_run.init_run(workflow, out_dir, *, force=False)[source]
Write starter configs for a TranscriptML run.
- Parameters:
workflow (
str) – Workflow template name,salukiorlegnet.out_dir (
str|Path) – Directory to create or populate.force (
bool) – Allow writing into a non-empty output directory.
- Return type:
Path