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>, arrays=<factory>)[source]
Self-describing processed dataset.
Xand optionalyretain TranscriptML’s original compact contract. Workflows with additional aligned targets (for example, RBPNet count profiles) may usearrays. Every named array must shareX’s first dimension and is serialized as an ordinary<name>.npyfile.- 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])
arrays (Mapping[str, ndarray])
- 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)
RBPNet/eCLIP data
Warning
All RBPNet/eCLIP APIs in this section are experimental. Preprocessing and modeling have been minimally tested and have only been confirmed to process data successfully and train reasonable models on PUM2 eCLIP data. They need substantially more validation than other TranscriptML APIs.
Universal eCLIP preprocessing orchestration.
- class transcriptml.rbpnet.preprocessing.Sample(name, path, role)[source]
One named BAM sample and its experimental role.
- Parameters:
name (str)
path (Path)
role (str)
- class transcriptml.rbpnet.preprocessing.PipelineConfig(genome_fasta, gtf, sminput, ips, output_dir, coordinate_space='mature_transcript', read1_rna_strand='opposite', min_mapq=1, exclude_duplicates=True, signal_compression='gzip', signal_compression_level=1, overwrite=False, progress=True)[source]
Configuration for canonical transcript-oriented eCLIP preprocessing.
- transcriptml.rbpnet.preprocessing.preprocess_eclip(config)[source]
Create a reusable canonical transcript-oriented eCLIP experiment.
The HDF5 track is concatenated selected-locus space and stays lazy on read. This stage deliberately performs no peak calling or region selection.
- Return type:
dict- Parameters:
config (PipelineConfig)
Lazy, ergonomic access to a processed transcript-space eCLIP experiment.
- class transcriptml.rbpnet.experiment.RegionRecord(start, end, region_type)[source]
- Parameters:
start (int)
end (int)
region_type (str)
- class transcriptml.rbpnet.experiment.TranscriptRecord(gene_id, transcript_id, chromosome, strand, length, signal_offset, sminput_tpm, regions, coordinate_space='mature_transcript', genomic_start=0, genomic_end=0)[source]
- Parameters:
gene_id (str)
transcript_id (str)
chromosome (str)
strand (str)
length (int)
signal_offset (int)
sminput_tpm (float)
regions (tuple[RegionRecord, ...])
coordinate_space (str)
genomic_start (int)
genomic_end (int)
- class transcriptml.rbpnet.experiment.SampleRecord(name, role, effective_library_size)[source]
- Parameters:
name (str)
role (str)
effective_library_size (int | None)
- class transcriptml.rbpnet.experiment.GenomicBlock(chromosome, start, end)[source]
- Parameters:
chromosome (str)
start (int)
end (int)
- class transcriptml.rbpnet.experiment.ProcessedECLIPDataset(processed_dir)[source]
Thin lazy reader for one canonical processed eCLIP directory.
Small metadata tables are loaded at construction. FASTA and HDF5 handles are opened only on first access and are never inherited when the reader is pickled, making the object safe to construct before worker processes.
- Parameters:
processed_dir (str | Path)
- get_profiles(transcript_id, start, end)[source]
Return all sample profiles in manifest order for one interval.
- Return type:
ndarray- Parameters:
transcript_id (str)
start (int)
end (int)
- get_genomic_blocks(transcript_id, start, end)[source]
Map one locus interval to compact ascending genomic blocks.
- Return type:
tuple[GenomicBlock,...]- Parameters:
transcript_id (str)
start (int)
end (int)
Descriptive configurable scanning over canonical transcript-space signals.
- class transcriptml.rbpnet.windows.WindowScanConfig(processed_dir, output_prefix, window_size=100, stride=50, min_sminput_tpm=0.0, pseudocount=1.0, omit_incomplete_terminal_windows=True, overwrite=False, batch_size=10000, progress=True)[source]
Configuration for a descriptive transcript-window scan.
- Parameters:
processed_dir (Path)
output_prefix (Path)
window_size (int)
stride (int)
min_sminput_tpm (float)
pseudocount (float)
omit_incomplete_terminal_windows (bool)
overwrite (bool)
batch_size (int)
progress (bool)
- transcriptml.rbpnet.windows.generate_window_bounds(transcript_length, window_size, stride, omit_incomplete_terminal_windows=True)[source]
Yield deterministic zero-based, half-open transcript windows.
- Return type:
Iterator[tuple[int,int]]- Parameters:
transcript_length (int)
window_size (int)
stride (int)
omit_incomplete_terminal_windows (bool)
- transcriptml.rbpnet.windows.calculate_gc_fraction(sequence)[source]
Calculate GC bases divided by total length; ambiguous bases are non-GC.
- Return type:
float- Parameters:
sequence (str)
- transcriptml.rbpnet.windows.summarize_regions(regions, start, end)[source]
Summarize exact region overlap and label boundary-crossing windows mixed.
- Return type:
tuple[str,dict[str,int],dict[str,float]]- Parameters:
regions (Iterable[RegionRecord])
start (int)
end (int)
- transcriptml.rbpnet.windows.scan_windows(config)[source]
Write equivalent gzipped TSV and Parquet descriptive window tables.
- Return type:
dict- Parameters:
config (WindowScanConfig)
Explicit, versioned region selection over descriptive eCLIP windows.
- class transcriptml.rbpnet.selection.SelectionConfig(processed_dir, windows, output_prefix, strategy, overwrite=False, progress=True, batch_size=10000, original_min_pvalue=0.01, original_min_count=8, original_min_height=2, original_advance=50, poisson_null='ip_locus_density', sminput_poisson_pseudocount=1.0, min_total_count=None, min_sminput_count=0, min_ip_count=0, min_sminput_tpm=0.0, replicate_mode='per_ip', region_types=None, discard_mixed=False, only_mixed=False, peak_fdr=0.05, peak_min_log2_ratio=1.0, negative_fdr=0.05, negative_max_log2_ratio=-0.5, stitch_gap=0)[source]
Configuration for selecting eligible experimental loci.
Defaults for
original_rbpnetreproduce the published Horlacher et al. candidate rules.broad_coveragedefaults to replicate-wise IP+SMInput >= 6. Peak/gray/negative thresholds remain configurable scientific starting points.- Parameters:
processed_dir (Path)
windows (Path)
output_prefix (Path)
strategy (str)
overwrite (bool)
progress (bool)
batch_size (int)
original_min_pvalue (float)
original_min_count (int)
original_min_height (int)
original_advance (int)
poisson_null (str)
sminput_poisson_pseudocount (float)
min_total_count (int | None)
min_sminput_count (int)
min_ip_count (int)
min_sminput_tpm (float)
replicate_mode (str)
region_types (tuple[str, ...] | str | None)
discard_mixed (bool)
only_mixed (bool)
peak_fdr (float)
peak_min_log2_ratio (float)
negative_fdr (float)
negative_max_log2_ratio (float)
stitch_gap (int)
- class transcriptml.rbpnet.selection.SelectionManifest(path, table, metadata)[source]
Loaded selection table and its versioned provenance metadata.
- Parameters:
path (Path)
table (pyarrow.Table)
metadata (dict)
- transcriptml.rbpnet.selection.select_regions(config)[source]
Select biological loci and write a versioned lightweight manifest.
- Return type:
dict- Parameters:
config (SelectionConfig)
- transcriptml.rbpnet.selection.load_selection_manifest(path)[source]
Load and validate a version-1 Parquet selection manifest.
- Return type:
- Parameters:
path (str | Path)
Materialize selected eCLIP loci as a TranscriptML RBPNet array bundle.
- class transcriptml.rbpnet.bundle.RBPNetBundleConfig(processed_dir, selection_manifest, output_dir, input_length=300, profile_length=300, max_jitter=0, transcript_end_policy='shift_to_fit', overwrite=False, progress=True)[source]
Configuration for fixed-shape RBPNet bundle materialization.
- Parameters:
processed_dir (Path)
selection_manifest (Path)
output_dir (Path)
input_length (int)
profile_length (int)
max_jitter (int)
transcript_end_policy (str)
overwrite (bool)
progress (bool)
- transcriptml.rbpnet.bundle.jitter_crop_offset(*, anchor, materialized_start, locus_length, crop_length, jitter_shift)[source]
Derive a legal future crop offset from explicit biological coordinates.
This is the coordinate contract used by
shift_to_fitbundles. Requested shifts near a boundary can map to the same closest legal crop.- Return type:
int- Parameters:
anchor (int)
materialized_start (int)
locus_length (int)
crop_length (int)
jitter_shift (int)
- transcriptml.rbpnet.bundle.make_rbpnet_bundle(config)[source]
Materialize selected loci into memory-mappable NumPy arrays.
input_lengthandprofile_lengthdescribe future training crops. The stored widths add2 * max_jitterso a future loader can choose a shared positional shift without reopening FASTA or HDF5 files.- Return type:
- Parameters:
config (RBPNetBundleConfig)
- transcriptml.rbpnet.bundle.load_rbpnet_bundle(path, *, mmap_mode='r')[source]
Load and validate a materialized RBPNet bundle.
- Return type:
- Parameters:
path (str | Path)
mmap_mode (str | None)
Jitter-aware structured batches over materialized RBPNet bundles.
- class transcriptml.rbpnet.dataset.RBPNetBatch(sequence, pooled_ip_profile, sminput_profile, individual_ip_profiles, ip_measurement_counts, sminput_measurement_counts, ip_library_sizes, sminput_library_size, depth_offsets, measurement_mask, profile_valid_mask, sequence_valid_mask, jitter_shift, crop_start, selection_start, selection_end, indices, example_ids, replicate_names)[source]
One structured RBPNet mini-batch.
- Parameters:
sequence (torch.Tensor)
pooled_ip_profile (torch.Tensor)
sminput_profile (torch.Tensor)
individual_ip_profiles (torch.Tensor)
ip_measurement_counts (torch.Tensor)
sminput_measurement_counts (torch.Tensor)
ip_library_sizes (torch.Tensor)
sminput_library_size (torch.Tensor)
depth_offsets (torch.Tensor)
measurement_mask (torch.Tensor)
profile_valid_mask (torch.Tensor)
sequence_valid_mask (torch.Tensor)
jitter_shift (torch.Tensor)
crop_start (torch.Tensor)
selection_start (torch.Tensor)
selection_end (torch.Tensor)
indices (torch.Tensor)
example_ids (tuple[str, ...])
replicate_names (tuple[str, ...])
- class transcriptml.rbpnet.dataset.RBPNetDataset(bundle, *, crop_length=None, max_train_jitter=0, training=False, seed=123, require_full_measurement_interval=True)[source]
Lazy fixed-crop view of one memory-mappable RBPNet bundle.
Training jitter is deterministic for a given
(seed, epoch, index)and therefore works consistently with zero or multiple DataLoader workers. Evaluation uses shift zero unless an explicit shift is requested throughitem_for_shift().- Parameters:
bundle (DatasetBundle)
crop_length (int | None)
max_train_jitter (int)
training (bool)
seed (int)
require_full_measurement_interval (bool)
- transcriptml.rbpnet.dataset.collate_rbpnet(batch)[source]
Stack structured examples without obscuring replicate/sample axes.
- Return type:
- Parameters:
batch (list[Mapping[str, object]])
- transcriptml.rbpnet.dataset.deduplicate_locus_indices(bundle, indices)[source]
Remove replicate-eligibility duplicate rows while retaining all R tracks.
- Return type:
tuple[list[int],int]- Parameters:
bundle (DatasetBundle)
indices (Sequence[int])
Stable structured likelihoods for TranscriptML RBPNet models.
- class transcriptml.rbpnet.losses.RBPNetLossConfig(name='rbpnet', lambda_ip_profile=1.0, lambda_sm_profile=1.0, lambda_enrichment=1.0, include_multinomial_constant=True, include_binomial_constant=True)[source]
Weights and reporting choices for the structured RBPNet objective.
- Parameters:
name (str)
lambda_ip_profile (float)
lambda_sm_profile (float)
lambda_enrichment (float)
include_multinomial_constant (bool)
include_binomial_constant (bool)
- class transcriptml.rbpnet.losses.RBPNetLossOutput(loss, components, numerators, denominators)[source]
Total differentiable loss plus independently aggregatable components.
- Parameters:
loss (torch.Tensor)
components (Mapping[str, torch.Tensor])
numerators (Mapping[str, torch.Tensor])
denominators (Mapping[str, torch.Tensor])
- transcriptml.rbpnet.losses.multinomial_nll(log_probs, counts, *, valid_positions=None, include_constant=True)[source]
Mean multinomial NLL over loci with nonzero profile totals.
Zero-total profiles contain no positional information and are excluded from the mean. With
include_constant=True(the default), this is the complete multinomial NLL, including thelgammacombinatorial term.- Return type:
ReducedLikelihood
- Parameters:
log_probs (torch.Tensor)
counts (torch.Tensor)
valid_positions (torch.Tensor | None)
include_constant (bool)
- transcriptml.rbpnet.losses.replicate_binomial_nll(eta, ip_counts, sminput_counts, depth_offsets, *, include_constant=True)[source]
Binomial NLL over valid locus-replicate observations.
etais one sequence-derived log enrichment per locus. Known effective library sizes enter only throughdepth_offsets = log(L_IP/L_SM).- Return type:
ReducedLikelihood- Parameters:
eta (torch.Tensor)
ip_counts (torch.Tensor)
sminput_counts (torch.Tensor)
depth_offsets (torch.Tensor)
include_constant (bool)
- class transcriptml.rbpnet.losses.RBPNetObjective(config=None, *, enrichment_enabled)[source]
Target/control profile objective with an optional independent eta head.
- Parameters:
config (RBPNetLossConfig | Mapping[str, object] | str | None)
enrichment_enabled (bool)
Structured RBPNet training integrated with TranscriptML checkpoints/configs.
- transcriptml.rbpnet.training.train_rbpnet_model(bundle, cfg)[source]
Train a registered RBPNet model without routing through scalar targets.
- Return type:
dict[str,Any]- Parameters:
bundle (DatasetBundle)
- transcriptml.rbpnet.training.evaluate_rbpnet_model(model, bundle, *, indices=None, batch_size=128, device='cpu', loss_config=None, progress=True)
Deterministically evaluate structured profile/enrichment likelihoods.
- Return type:
dict[str, Any]
- Parameters:
model (RBPNet)
bundle (DatasetBundle)
indices (Sequence[int] | None)
batch_size (int)
device (str | torch.device)
loss_config (str | Mapping[str, object] | None)
progress (bool)
- transcriptml.rbpnet.training.write_rbpnet_predictions(path, metrics)[source]
Write pi, eta, and replicate-specific predicted IP fractions.
- Return type:
None- Parameters:
path (str | Path)
metrics (Mapping[str, Any])
Structured, checkpoint-split-aware evaluation reports for RBPNet.
- transcriptml.rbpnet.evaluation.resolve_rbpnet_checkpoint_indices(checkpoint, *, split, n_examples)[source]
Resolve a named RBPNet split exclusively from checkpoint artifacts.
- Return type:
tuple[str,list[int]]- Parameters:
checkpoint (Mapping[str, object])
split (str | None)
n_examples (int)
- transcriptml.rbpnet.evaluation.evaluate_rbpnet_report(model, checkpoint, bundle, output_dir, *, split=None, batch_size=128, device='cpu', save_profiles=False, calibration_bins=10, enrichment_pseudocount=0.5, representative_seed=123, representative_per_tier=3, representative_min_profile_count=10, checkpoint_path=None, progress=True)[source]
Create a complete deterministic RBPNet evaluation report directory.
- Return type:
dict[str, object]
- Parameters:
model (RBPNet)
checkpoint (Mapping[str, object])
bundle (DatasetBundle)
output_dir (str | Path)
split (str | None)
batch_size (int)
device (str | torch.device)
save_profiles (bool)
calibration_bins (int)
enrichment_pseudocount (float)
representative_seed (int)
representative_per_tier (int)
representative_min_profile_count (int)
checkpoint_path (str | Path | None)
progress (bool)
Numerically explicit metrics for structured RBPNet evaluation.
- transcriptml.rbpnet.evaluation_metrics.profile_metrics(counts, probabilities, *, valid_mask=None, control_probabilities=None)[source]
Calculate complete-likelihood and normalized profile-shape metrics.
Rows with zero observed counts retain their count and valid-position count but receive
NaNfor empirical-profile metrics. Probabilities are normalized over valid positions; counts outside the mask are rejected. Natural logarithms are used throughout.- Return type:
dict[str,ndarray]- Parameters:
counts (ndarray)
probabilities (ndarray)
valid_mask (ndarray | None)
control_probabilities (ndarray | None)
- transcriptml.rbpnet.evaluation_metrics.enrichment_metrics(eta, ip_counts, sminput_counts, depth_offsets, *, pseudocount=0.5)[source]
Calculate replicate-aware binomial metrics and descriptive enrichment.
- Return type:
dict[str,ndarray]- Parameters:
eta (ndarray)
ip_counts (ndarray)
sminput_counts (ndarray)
depth_offsets (ndarray)
pseudocount (float)
- transcriptml.rbpnet.evaluation_metrics.replicate_ceiling_metrics(replicate_profiles, *, valid_mask=None)[source]
Compare each IP replicate with the pooled profile of all other replicates.
- Return type:
dict[str,ndarray]- Parameters:
replicate_profiles (ndarray)
valid_mask (ndarray | None)
- transcriptml.rbpnet.evaluation_metrics.calibration_rows(predicted_probability, ip_counts, total_counts, replicate_names, *, n_bins=10)[source]
Build read-weighted fixed-width predicted-probability calibration bins.
- Return type:
list[dict[str,object]]- Parameters:
predicted_probability (ndarray)
ip_counts (ndarray)
total_counts (ndarray)
replicate_names (Sequence[str])
n_bins (int)
- transcriptml.rbpnet.evaluation_metrics.aggregate_observations(values, *, locus_ids, gene_ids, read_weights=None, micro_numerators=None)[source]
Calculate locus-macro, gene-macro, and read-micro summaries.
Replicate observations sharing a locus are averaged before locus- and gene-macro aggregation. Read micro is a read-weighted mean, or equivalently
sum(micro_numerators)/sum(read_weights)when explicit numerators are supplied (for example complete NLL rather than NLL times read count).- Return type:
dict[str,dict[str,float|int]]- Parameters:
values (ndarray)
locus_ids (Sequence[object])
gene_ids (Sequence[object])
read_weights (ndarray | None)
micro_numerators (ndarray | None)
- transcriptml.rbpnet.evaluation_metrics.select_representative_examples(metric, *, eligible=None, seed=123, per_tier=3)[source]
Reproducibly sample good/middle/poor examples from rank tertiles.
- Return type:
list[dict[str,object]]- Parameters:
metric (ndarray)
eligible (ndarray | None)
seed (int)
per_tier (int)
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, pooling='max', dropout=0.3, augment_shift=3, ln_epsilon=0.007, keras_bn_momentum=0.9, bn_eps=0.001, head_layernorm=False)[source]
- Parameters:
seq_depth (int)
filters (int)
kernel_size (int)
num_layers (int)
pooling (str)
dropout (float)
augment_shift (int)
ln_epsilon (float)
keras_bn_momentum (float)
bn_eps (float)
head_layernorm (bool)
- class transcriptml.models.reproduce.SalukiExact(seq_depth=6, filters=64, kernel_size=5, num_layers=6, pooling='max', dropout=0.3, augment_shift=3, ln_epsilon=0.007, keras_bn_momentum=0.9, bn_eps=0.001, head_layernorm=False)[source]
Close PyTorch reproduction of the Basenji/Saluki rnann.py architecture.
- Parameters:
seq_depth (int)
filters (int)
kernel_size (int)
num_layers (int)
pooling (str)
dropout (float)
augment_shift (int)
ln_epsilon (float)
keras_bn_momentum (float)
bn_eps (float)
head_layernorm (bool)
- 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)
Warning
The RBPNet model API below is experimental and has only received minimal validation on PUM2 eCLIP data.
Configurable sequence-only RBPNet profile and enrichment model.
- class transcriptml.models.rbpnet.RBPNetConfig(in_ch=4, n_filters=128, initial_kernel_size=12, n_residual_blocks=5, residual_kernel_size=6, dilations=None, normalization='batch', dropout=0.25, initial_bias=False, residual_bias=True, profile_head_type='transpose_conv', profile_head_kernel_size=25, profile_head_bias=True, enrichment_head_type='none', enrichment_hidden=64, enrichment_dropout=0.0, profile_length=300, batch_norm_eps=1e-05, batch_norm_momentum=0.1)[source]
Configuration for the first TranscriptML RBPNet model family.
- Parameters:
in_ch (int)
n_filters (int)
initial_kernel_size (int)
n_residual_blocks (int)
residual_kernel_size (int)
dilations (list[int] | None)
normalization (str)
dropout (float)
initial_bias (bool)
residual_bias (bool)
profile_head_type (str)
profile_head_kernel_size (int)
profile_head_bias (bool)
enrichment_head_type (str)
enrichment_hidden (int)
enrichment_dropout (float)
profile_length (int | None)
batch_norm_eps (float)
batch_norm_momentum (float)
- class transcriptml.models.rbpnet.RBPNetOutput(target_logits, control_logits, target_log_probs, control_log_probs, target_probs, control_probs, mixing_logit, pi, ip_log_probs, ip_probs, enrichment_logit=None)[source]
Structured differentiable outputs from
RBPNet.- Parameters:
target_logits (torch.Tensor)
control_logits (torch.Tensor)
target_log_probs (torch.Tensor)
control_log_probs (torch.Tensor)
target_probs (torch.Tensor)
control_probs (torch.Tensor)
mixing_logit (torch.Tensor)
pi (torch.Tensor)
ip_log_probs (torch.Tensor)
ip_probs (torch.Tensor)
enrichment_logit (torch.Tensor | None)
- transcriptml.models.rbpnet.theoretical_receptive_field(initial_kernel_size, residual_kernel_size, dilations)[source]
Return the position-preserving trunk’s theoretical receptive-field width.
- Return type:
int- Parameters:
initial_kernel_size (int)
residual_kernel_size (int)
dilations (list[int] | tuple[int, ...])
- class transcriptml.models.rbpnet.SamePadConv1d(in_channels, out_channels, kernel_size, *, dilation=1, bias=True)[source]
Conv1d with explicit, version-stable asymmetric same padding.
- Parameters:
in_channels (int)
out_channels (int)
kernel_size (int)
dilation (int)
bias (bool)
- class transcriptml.models.rbpnet.SameLengthConvTranspose1d(in_channels, out_channels, kernel_size, *, bias=True)[source]
Stride-one transposed convolution cropped to the indexed input length.
- Parameters:
in_channels (int)
out_channels (int)
kernel_size (int)
bias (bool)
- class transcriptml.models.rbpnet.RBPNet(in_ch=4, n_filters=128, initial_kernel_size=12, n_residual_blocks=5, residual_kernel_size=6, dilations=None, normalization='batch', dropout=0.25, initial_bias=False, residual_bias=True, profile_head_type='transpose_conv', profile_head_kernel_size=25, profile_head_bias=True, enrichment_head_type='none', enrichment_hidden=64, enrichment_dropout=0.0, profile_length=300, batch_norm_eps=1e-05, batch_norm_momentum=0.1)[source]
Sequence-only RBPNet with latent target/control mixture and optional eta.
- Parameters:
in_ch (int)
n_filters (int)
initial_kernel_size (int)
n_residual_blocks (int)
residual_kernel_size (int)
dilations (list[int] | tuple[int, ...] | None)
normalization (str)
dropout (float)
initial_bias (bool)
residual_bias (bool)
profile_head_type (str)
profile_head_kernel_size (int)
profile_head_bias (bool)
enrichment_head_type (str)
enrichment_hidden (int)
enrichment_dropout (float)
profile_length (int | None)
batch_norm_eps (float)
batch_norm_momentum (float)
- property receptive_field: int
Theoretical receptive-field width of the shared trunk.
- property receptive_field_extents: tuple[int, int]
Return left/right trunk context extents under explicit same padding.
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, optimizer='adamw', lr_scheduler=None, mixed_precision=False, gradient_clip_norm=0.5, patience=5, monitor='val_loss', loss=<factory>, device='cpu', num_workers=0, mmap_mode='r', seed=123, progress=True, debug_epoch_predictions=False, head_layernorm=False, sequence_controls=None, split_source='auto', cv_plan=None, fold=None, max_train_jitter=0, allow_random_window_split=False, deduplicate_loci=True, split=<factory>)[source]
- Parameters:
dataset (str)
output_dir (str)
model (Mapping[str, Any])
batch_size (int)
epochs (int)
learning_rate (float)
weight_decay (float)
optimizer (str | Mapping[str, Any])
lr_scheduler (str | Mapping[str, Any] | None)
mixed_precision (bool)
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)
debug_epoch_predictions (bool)
head_layernorm (bool)
sequence_controls (Mapping[str, Any] | Sequence[Mapping[str, Any]] | None)
split_source (str)
cv_plan (str | None)
fold (int | None)
max_train_jitter (int)
allow_random_window_split (bool)
deduplicate_loci (bool)
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, cv_plan=None, fold=None, dataset=None, output_dir=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.cv_plan (
str|Path|None) – Optional chromosome CV plan overriding the config.fold (
int|None) – Optional zero-based CV test fold overriding the config.dataset (
str|Path|None) – Optional dataset-directory override.output_dir (
str|Path|None) – Optional output-directory override.
- 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_fold_checkpoints(checkpoint_paths, dataset_path, out_csv=None, *, batch_size=128, device='cpu', progress=True, test_only=False)[source]
Average predictions from fold checkpoints evaluated on one shared dataset.
By default every checkpoint scores every example in the dataset, producing an ensemble prediction. With
test_only=True, each checkpoint instead scores its own fold test split, producing one out-of-fold prediction per example.- Parameters:
checkpoint_paths (Sequence[str | Path]) – Non-empty sequence of TranscriptML checkpoints.
dataset_path (str | Path) – Shared dataset bundle scored by every checkpoint.
out_csv (str | Path | None) – Optional destination for per-example ensemble predictions and residuals. A sibling
.summary.jsonfile is also written.batch_size (int) – Number of examples to score per prediction batch.
device (str | torch.device) – Torch device used to load and run each model.
progress (bool) – Whether to emit progress messages while evaluating.
test_only (bool) – Whether each checkpoint should score only the test indices from its sibling fold
dataset/splits.json. Test splits must cover every dataset example exactly once.
- Return type:
dict[str, object]
- Returns:
A dictionary containing
average_predictions, example identifiers and indices, fold provenance, and, when targets are available,targets,average_residuals(truth minus prediction), MSE, Pearson correlation, and mean residual.
- transcriptml.training.evaluation.evaluate_checkpoint(checkpoint_path, dataset_path, out_csv=None, *, out_dir=None, split=None, batch_size=128, device='cpu', save_profiles=False, calibration_bins=10, enrichment_pseudocount=0.5, representative_seed=123, representative_per_tier=3, representative_min_profile_count=10, 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 legacy destination CSV path for predictions.
out_dir (str | Path | None) – Structured report directory for RBPNet checkpoints.
split (str | None) – Named split to evaluate. RBPNet resolves this exclusively from checkpoint artifacts and defaults to
test; scalar models retain the existing dataset-bundle behavior.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.
save_profiles (bool)
calibration_bins (int)
enrichment_pseudocount (float)
representative_seed (int)
representative_per_tier (int)
representative_min_profile_count (int)
- 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.group_split_indices(metadata, *, group_col='group_gene_id', val_frac=0.1, test_frac=0.1, seed=None)[source]
Split complete biological groups while approximately balancing rows.
This is the safe default for overlapping RBPNet windows. Groups are shuffled reproducibly and then assigned to test, validation, and training without ever dividing a group between splits.
- Return type:
dict[str,list[int]]- Parameters:
metadata (Sequence[Mapping[str, object]])
group_col (str)
val_frac (float)
test_frac (float)
seed (int | None)
- transcriptml.training.splits.validate_group_disjoint(splits, metadata, *, group_col='group_gene_id')[source]
Raise when one biological group occurs in multiple dataset splits.
- Return type:
None- Parameters:
splits (Mapping[str, Sequence[int]])
metadata (Sequence[Mapping[str, object]])
group_col (str)
- 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.window_ism.WindowISMResult(window_starts, window_mask, mean_deltas, mean_abs_deltas, std_deltas, reference_predictions, valid_lengths, input_shape, window_size, stride, n_ablations, seed)[source]
Window-level random-mutagenesis effects for a sequence batch.
- Parameters:
window_starts (ndarray)
window_mask (ndarray)
mean_deltas (ndarray)
mean_abs_deltas (ndarray)
std_deltas (ndarray)
reference_predictions (ndarray)
valid_lengths (ndarray)
input_shape (tuple[int, int, int])
window_size (int)
stride (int)
n_ablations (int)
seed (int)
- transcriptml.interpret.window_ism.generate_window_starts(valid_length, window_size, stride)[source]
Generate fixed-width window starts, including a terminally anchored window.
The final window ends exactly at
valid_length. Together with the requirementstride <= window_size, this guarantees full base coverage for any sequence at least as long as the requested window.- Parameters:
valid_length (
int) – Number of represented sequence positions.window_size (
int) – Width of every window.stride (
int) – Distance between regular window starts.
- Return type:
ndarray
- transcriptml.interpret.window_ism.compute_window_ism(X, predictor, *, window_size, stride=None, n_ablations=30, seed=123, valid_lengths=None, mutation_batch_size=512, progress=True)[source]
Compute repeated random-mutagenesis effects for fixed-width windows.
Every nucleotide in a scored window is independently replaced by a uniformly sampled alternative base. Effects are signed mutant-minus- reference prediction differences. Replicate-level effects are summarized online as their mean, mean absolute value, and population standard deviation.
- 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.window_size (
int) – Number of bases mutated in each window.stride (
int|None) – Distance between regular starts. Defaults towindow_size.n_ablations (
int) – Number of independently mutated sequences per window.seed (
int) – Non-negative base seed for deterministic per-window generators.valid_lengths (
Optional[Sequence[int]]) – Optional represented length for each sequence.mutation_batch_size (
int) – Maximum number of mutants queued per prediction call.progress (
bool) – Whether to emit progress messages.
- Return type:
- transcriptml.interpret.window_ism.save_window_ism_result(result, out_dir, *, checkpoint=None, dataset=None, sequence_ids=None, progress=True)[source]
Save window-ISM arrays and reproducibility metadata.
- Return type:
None- Parameters:
result (WindowISMResult)
out_dir (str | Path)
checkpoint (str | Path | None)
dataset (str | Path | None)
sequence_ids (Sequence[str] | None)
progress (bool)
- 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.region_ablation.RegionAblationConfig(n_ablations=100, n_ablations_for=<factory>, junction_counts=(1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50), junction_min_spacing=25, seed=123)[source]
Configuration for repeated region and junction perturbations.
- Parameters:
n_ablations (int)
n_ablations_for (Mapping[str, int])
junction_counts (tuple[int, ...])
junction_min_spacing (int)
seed (int)
- normalized()[source]
Validate values and return an immutable normalized configuration.
- Return type:
- class transcriptml.interpret.region_ablation.RegionAblationInstance(instance_index, seq_index, sequence_id, transcript_class, operation, region, valid_length, region_start, region_end, region_length, n_replicates, junction_count=None, reference_junction_count=None, requested_min_spacing=None, effective_min_spacing=None)[source]
One transcript-condition row aligned to region-ablation arrays.
- Parameters:
instance_index (int)
seq_index (int)
sequence_id (str)
transcript_class (str)
operation (str)
region (str)
valid_length (int)
region_start (int)
region_end (int)
region_length (int)
n_replicates (int)
junction_count (int | None)
reference_junction_count (int | None)
requested_min_spacing (int | None)
effective_min_spacing (int | None)
- class transcriptml.interpret.region_ablation.RegionAblationResult(instances, skipped, reference_predictions, ablation_predictions, effects, replicate_mask, mean_effects, mean_abs_effects, std_effects, analysis_indices, transcript_classes, config, input_shape, schema_name, cds_channel_index, splice_channel_index, sequence_ids, storage_dir=None)[source]
Raw and summarized repeated region-ablation predictions.
- Parameters:
instances (list[RegionAblationInstance])
skipped (list[SkippedRegionAblation])
reference_predictions (ndarray)
ablation_predictions (ndarray)
effects (ndarray)
replicate_mask (ndarray)
mean_effects (ndarray)
mean_abs_effects (ndarray)
std_effects (ndarray)
analysis_indices (ndarray)
transcript_classes (tuple[str, ...])
config (RegionAblationConfig)
input_shape (tuple[int, int, int])
schema_name (str)
cds_channel_index (int)
splice_channel_index (int)
sequence_ids (tuple[str, ...])
storage_dir (Path | None)
- transcriptml.interpret.region_ablation.region_ablation(X, predictor, *, schema='saluki6', sequence_ids=None, metadata=None, config=None, valid_lengths=None, cds_channel=None, splice_channel=None, reference_batch_size=None, mutation_batch_size=512, sequence_indices=None, sequence_start=None, sequence_end=None, sequence_shard_index=None, sequence_shards=None, storage_dir=None, progress=True)[source]
Run repeated region sequence edits and exon-junction density scans.
- Return type:
- Parameters:
X (ndarray)
predictor (Predictor)
schema (str | SequenceSchema)
sequence_ids (Sequence[str] | None)
metadata (Sequence[Mapping[str, object]] | None)
config (RegionAblationConfig | None)
valid_lengths (Sequence[int] | None)
cds_channel (str | int | None)
splice_channel (str | int | None)
reference_batch_size (int | None)
mutation_batch_size (int)
sequence_indices (Sequence[int] | None)
sequence_start (int | None)
sequence_end (int | None)
sequence_shard_index (int | None)
sequence_shards (int | None)
storage_dir (str | Path | None)
progress (bool)
- transcriptml.interpret.region_ablation.save_region_ablation_result(result, out_dir, *, checkpoint=None, dataset=None, progress=True)[source]
Save raw arrays, condition tables, and reproducibility metadata.
- Return type:
None- Parameters:
result (RegionAblationResult)
out_dir (str | Path)
checkpoint (str | Path | None)
dataset (str | Path | None)
progress (bool)
- 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
Immutable, example-balanced chromosome cross-validation plans.
- class transcriptml.workflows.chromosome_cv.ChromosomeCVPlan(n_folds, group_col, n_examples, chromosome_counts, fold_groups, fold_example_counts, plan_id, algorithm='largest_chromosome_first_greedy', transcriptml_version='0.1.0')[source]
A versioned assignment of complete chromosomes to fold groups.
- Parameters:
n_folds (int)
group_col (str)
n_examples (int)
chromosome_counts (Mapping[str, int])
fold_groups (tuple[tuple[str, ...], ...])
fold_example_counts (tuple[int, ...])
plan_id (str)
algorithm (str)
transcriptml_version (str)
- class transcriptml.workflows.chromosome_cv.ChromosomeCVResolution(fold, validation_fold, groups, indices)[source]
Train/validation/test groups and row indices for one CV run.
- Parameters:
fold (int)
validation_fold (int)
groups (Mapping[str, tuple[str, ...]])
indices (Mapping[str, list[int]])
- transcriptml.workflows.chromosome_cv.create_chromosome_cv_plan(metadata, *, n_folds, group_col='group_chromosome')[source]
Greedily balance complete chromosomes by their example counts.
- Return type:
- Parameters:
metadata (Sequence[Mapping[str, object]])
n_folds (int)
group_col (str)
- transcriptml.workflows.chromosome_cv.save_chromosome_cv_plan(plan, path)[source]
Write a stable human-readable chromosome CV plan JSON file.
- Return type:
Path- Parameters:
plan (ChromosomeCVPlan)
path (str | Path)
- transcriptml.workflows.chromosome_cv.load_chromosome_cv_plan(path)[source]
Load and validate an immutable chromosome CV plan.
- Return type:
- Parameters:
path (str | Path)
- transcriptml.workflows.chromosome_cv.resolve_chromosome_cv_plan(plan, metadata, *, fold)[source]
Resolve one test fold, the following validation fold, and training rows.
- Return type:
- Parameters:
plan (ChromosomeCVPlan)
metadata (Sequence[Mapping[str, object]])
fold (int)
- 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:saluki,legnet, orrbpnet.out_dir (
str|Path) – Directory to create or populate.force (
bool) – Allow writing into a non-empty output directory.
- Return type:
Path