Skip to content

API reference

Only names exported directly from scoda are part of the supported public API.

Musical values and transformations

Immutable musical values and transformations used by S-Coda.

Note dataclass

Note(
    start,
    end,
    pitch,
    velocity,
    channel=0,
    release_velocity=0,
)

A half-open MIDI note interval [start, end) in sequence ticks.

TimeSignature dataclass

TimeSignature(
    time,
    numerator,
    denominator,
    clocks_per_click=24,
    notated_32nd_notes_per_beat=8,
)

A MIDI time-signature event at an absolute sequence tick.

KeySignature dataclass

KeySignature(time, key)

A MIDI key-signature event at an absolute sequence tick.

Tempo dataclass

Tempo(time, microseconds_per_quarter)

A MIDI tempo event expressed as microseconds per quarter note.

ControlChange dataclass

ControlChange(time, control, value, channel=0)

A channel-specific MIDI controller update at an absolute tick.

ProgramChange dataclass

ProgramChange(time, program, channel=0)

A channel-specific MIDI program update at an absolute tick.

BarSpan dataclass

BarSpan(start, end, time_signature, key_signature=None)

An absolute bar interval with the musical context active at its start.

Sequence dataclass

Sequence(
    notes=(),
    events=(),
    duration_ticks=0,
    ticks_per_quarter=24,
)

Canonical immutable collection of notes, timed events, and duration.

is_empty

is_empty()

Return whether the sequence contains no sounding notes.

duration_relation

duration_relation(other)

Return this duration divided by other in musical time.

similarity

similarity(
    other,
    *,
    compare_velocity=True,
    compare_channel=True,
    compare_program=True,
)

Return multiset overlap of note intervals and selected attributes.

pad

pad(duration_ticks)

Extend the represented duration to at least duration_ticks.

cutoff

cutoff(maximum_length, reduced_length=None)

Shorten sequences above maximum_length to the selected target.

with_channel

with_channel(channel)

Return a copy with every channel-specific value on channel.

with_velocity

with_velocity(velocity)

Return a copy with note velocities replaced or transformed.

filter_events

filter_events(predicate)

Return a copy containing only events accepted by predicate.

transpose

transpose(
    semitones, *, out_of_range="error", pitch_range=(0, 127)
)

Transpose notes and key signatures by an integer number of semitones.

quantise

quantise(step_sizes)

Move note boundaries and event times to the nearest allowed grid point.

quantise_note_lengths

quantise_note_lengths(
    note_values, *, duration_extension_ticks=None
)

Replace note durations with the nearest allowed note value.

quantise_and_normalise

quantise_and_normalise(
    step_sizes,
    note_values,
    *,
    duration_extension_ticks=None,
)

Quantise positions and durations while retaining canonical invariants.

resample

resample(ticks_per_quarter)

Return this sequence expressed at a different tick resolution.

slice

slice(start, end)

Return a clipped half-open tick window [start, end) with local timing.

Crossing notes are deliberately clipped. This is a self-contained excerpt, not a lossless partition: concatenation cannot recover ties. Use :func:bar_spans with the original notes for lossless bar views.

split

split(capacities)

Split the sequence consecutively using the supplied tick capacities.

merge classmethod

merge(sequences)

Overlay sequences that share one tick resolution.

concatenate classmethod

concatenate(sequences)

Join sequences end to end without changing their tick resolution.

SequenceBuilder

SequenceBuilder(ticks_per_quarter=24)

Mutable construction helper that produces an immutable :class:Sequence.

add_note

add_note(note)

Append one validated note and return this builder.

add_event

add_event(event)

Append one supported timed event and return this builder.

set_duration

set_duration(duration_ticks)

Set a duration that contains every value currently in the builder.

build

build()

Construct and return an immutable canonical sequence.

bar_spans

bar_spans(sequence, *, strict=True)

Return bar intervals through sequence.duration_ticks in one pass.

split_bars

split_bars(
    sequences,
    *,
    meta_track_index=0,
    strict=True,
    carry_context=True,
)

Return clipped bar excerpts, optionally carrying active MIDI context.

Notes crossing boundaries become independent fragments. Tokenise the original sequences, not concatenated excerpts, to preserve articulation.

Duration policies

A duration palette, optionally repeated at a fixed tick interval.

With extensions enabled the domain is n * duration_extension_ticks + v for non-negative n and a configured base value v. The extension interval equals the largest base value, making decomposition unique and exact multiples representable without a zero-duration note.

floor

floor(duration)

Return the largest representable duration not exceeding a gap.

nearest

nearest(duration)

Return the nearest duration; an exact tie selects the shorter one.

decompose

decompose(duration)

Return the unique extension count and base value of a duration.

Music theory

Bases: StrEnum

A standard MIDI major or minor key signature.

Enum values use the spellings accepted by MIDI files. Enharmonic keys are preserved when parsed, while transposition returns one canonical spelling for each pitch class and mode.

transpose

transpose(semitones)

Return this key transposed by semitones without changing mode.

MIDI

Deterministic conversion between Mido objects and immutable S-Coda values.

MidiDiagnostic dataclass

MidiDiagnostic(
    code, severity, track, message_index, tick, details
)

One deterministic MIDI import observation or repair.

MidiImportReport dataclass

MidiImportReport(
    source_ticks_per_quarter,
    target_ticks_per_quarter,
    tracks_read,
    notes_created,
    diagnostics=(),
)

Immutable summary of a MIDI import and every emitted diagnostic.

repaired property

repaired

Return whether malformed information required a deterministic repair.

lossy property

lossy

Return whether any source information was changed or ignored.

warnings property

warnings

Return diagnostics for deliberately ignored unsupported information.

errors property

errors

Return diagnostics for malformed information or required repairs.

MidiLoadResult dataclass

MidiLoadResult(sequences, report)

Canonical imported sequences together with their complete report.

load_midi

load_midi(
    source,
    *,
    track_groups=None,
    meta_track_indices=None,
    meta_target=0,
    target_ticks_per_quarter=None,
    mode="repair",
    unclosed_note_policy="close_at_track_end",
)

Load MIDI into canonical sequences and return all repairs as diagnostics.

to_mido

to_mido(sequences, *, meta_source=0, track_names=None)

Convert canonical sequences to a deterministic Mido file.

save_midi

save_midi(
    sequences,
    destination,
    *,
    meta_source=0,
    track_names=None,
)

Write canonical sequences to a deterministic standard MIDI file.

Tokenisation

Canonical notelike tokenisation for immutable S-Coda sequences.

NotelikeConfig dataclass

NotelikeConfig(
    ticks_per_quarter=24,
    num_tracks=1,
    pitch_range=(21, 108),
    note_values=(
        4,
        6,
        8,
        9,
        12,
        16,
        18,
        24,
        32,
        36,
        48,
        64,
        72,
        96,
    ),
    velocity_bins=1,
    include_time_signatures=False,
    max_bar_quarters=4,
    duration_extension_ticks=None,
)

Immutable configuration for :class:NotelikeTokeniser.

NotelikeTokeniser

NotelikeTokeniser(config=None)

Bases: _IncrementalTokeniser

Canonical notelike grammar with explicit immutable configuration.

vocabulary_size property

vocabulary_size

Return the number of tokens in the vocabulary.

__reduce__

__reduce__()

Reconstruct the immutable codec from its config when pickled.

The derived lookup tables intentionally use read-only mapping proxies, which Python's default pickler cannot serialise. The complete codec is deterministic from :attr:config, so multiprocessing workers can safely and compactly rebuild it instead of serialising derived state.

encode

encode(tokens)

Encode token strings as vocabulary IDs.

decode

decode(token_ids)

Decode vocabulary IDs as token strings.

next_completion_token_id

next_completion_token_id(state)

Return the next canonical tail token without introducing an attack.

At an onset horizon existing notes may still sound. Advance through that tail in the current meter, then emit sto. Dangling track or extension prefixes require a note and cannot be completed this way.

completion_token_ids

completion_token_ids(state, *, max_tokens=None)

Return a deterministic attack-free suffix, including terminal stop.

tokenise

tokenise(sequences)

Return a complete framed canonical stream for synchronised sequences.

tokenise_body

tokenise_body(sequences)

Return the canonical, deliberately lossy stream body without framing.

detokenise

detokenise(tokens)

Validate and decode a complete canonical stream into normalised tracks.

body_metadata

body_metadata(tokens, *, impute_pitch=False)

Return metadata aligned one-to-one with an unframed token body.

prefix_metadata

prefix_metadata(tokens, *, impute_pitch=False)

Return metadata aligned one-to-one with a valid framed-stream prefix.

metadata

metadata(tokens, *, impute_pitch=False)

Return metadata aligned one-to-one with a complete token stream.

TokeniserState dataclass

TokeniserState(
    started=False,
    ended=False,
    active_track=None,
    bar_count=0,
    bar_position=0,
    bar_capacity=96,
    pending_note_ticks=0,
    duration_extension_ticks=0,
    meter_numerator=4,
    meter_denominator=4,
    meter_declared=False,
    position_track_floor=-1,
    last_note_key=None,
    valid=True,
    phase="initial",
)

Immutable grammar state used for incremental constrained decoding.

TokenMetadata dataclass

TokenMetadata(
    token_index,
    token_index_in_bar,
    tick,
    tick_in_bar,
    track_index,
    pitch,
    circle_of_fifths,
)

Per-token structural and musical metadata aligned with a token stream.

__len__

__len__()

Return the number of tokens represented by this metadata.

VocabularyManifest dataclass

VocabularyManifest(
    codec_id, normalised_config_json, tokens, sha256
)

Deterministic identity of one codec configuration and ordered vocabulary.

size property

size

Return the number of tokens in the vocabulary.

normalised_config property

normalised_config

Return the canonical JSON configuration as a new dictionary.

create_tokeniser

create_tokeniser(codec_id, config=None)

Construct a tokeniser from a persisted codec identifier and configuration.

Errors

Public exception hierarchy for S-Coda.

ScodaError

Bases: Exception

Base class for all library-defined errors.

ValidationError

Bases: ScodaError, ValueError

Raised when a public value violates a core invariant.

SequenceError

Bases: ScodaError

Raised when a sequence transformation cannot be performed safely.

MidiError

Bases: ScodaError

Base class for MIDI conversion errors.

MidiImportError

MidiImportError(message, report=None)

Bases: MidiError

Raised when strict MIDI import encounters malformed input.

TokenisationError

Bases: ScodaError

Raised for invalid tokens, configurations, or token streams.