chronos

Chronos provides specialized classes and functions for working with time and rhythm in music.

The word “chronos” originates from Ancient Greek and is deeply rooted in both language and mythology. In Greek, “χρόνος” (chronos) means “time”. In Greek mythology, Chronos is personified as the god of time, symbolizing the endless passage of time and the cycles of creation and destruction within the universe.

Rhythm Pairs

class klotho.chronos.rhythm_pairs.rhythm_pair.RhythmPair(lst, subdivs=False)[source]

Bases: object

A rhythm pair derived from a tuple of integers.

A rhythm pair computes rhythmic sequences from the superimposition of evenly spaced pulse grids. Given a tuple of integers, two complementary sequences are produced: an MM (metric modulation) sequence and a non-MM sequence, along with partitions and measure groupings.

Parameters:
  • lst (tuple of int) – The tuple of integers from which to derive the rhythm pair.

  • subdivs (bool, optional) – If True, partition and measure accessors return full (label, parts) tuples; if False, only the labels are returned. Default is False.

Examples

>>> rp = RhythmPair((3, 4))
>>> rp.product
12
>>> rp.beats
(3, 1, 2, 2, 1, 3)
__init__(lst, subdivs=False)[source]
property product: int

The total product of all elements in the input tuple.

Return type:

int

property products: Tuple[int, int, int]

The total product divided by each element in the input tuple.

Return type:

tuple of int

property partitions: Tuple[Tuple[int, ...], ...]

The partitions of the non-MM sequence grouped by each product value.

When subdivs is True, each partition element is a (label, parts) tuple. When False, only the labels are returned.

Return type:

tuple of tuple

property measures: Tuple[int, ...]

The measure groupings derived from the MM sequence.

When subdivs is True, each measure element is a (label, parts) tuple. When False, only the labels are returned.

Return type:

tuple

property beats: Tuple[int, ...]

The non-MM (beat-level) rhythmic sequence.

Return type:

tuple of int

property subdivs: bool

Whether partition and measure accessors return full subdivision detail.

Return type:

bool

Rhythm Trees

class klotho.chronos.rhythm_trees.rhythm_tree.RhythmTree(span=1, meas='1/1', subdivisions=(1, 1))[source]

Bases: Tree

__init__(span=1, meas='1/1', subdivisions=(1, 1))[source]
Parameters:
  • span (int, optional) – The number of measures the tree spans. Default is 1.

  • meas (Meas, Fraction, or str, optional) – The time signature. Default is '1/1'.

  • subdivisions (tuple, optional) – The proportional subdivisions of the measure. Elements may be integers or nested (D, S) tuples. Default is (1, 1).

classmethod from_tree(tree, span=1)[source]

Construct a RhythmTree from an existing Tree.

Parameters:
  • tree (Tree) – A tree whose root node has a 'metric_duration' attribute.

  • span (int, optional) – The number of measures. Default is 1.

Return type:

RhythmTree

classmethod from_ratios(ratios, span=1)[source]

Construct a RhythmTree from a flat sequence of fractional ratios.

The ratios are converted to integer subdivisions and the time signature is inferred from the sum of absolute ratios.

Parameters:
  • ratios (tuple of Fraction, float, or str) – The proportional ratios for each leaf.

  • span (int, optional) – The number of measures. Default is 1.

Return type:

RhythmTree

property span

The number of measures this tree spans.

Return type:

int

property meas

The time signature of this tree.

Return type:

Meas

property subdivisions

The proportional subdivisions (S part) of this tree.

Return type:

tuple

property durations

The metric durations of all leaf nodes.

Return type:

tuple of Fraction

property onsets

The metric onsets of all leaf nodes.

Return type:

tuple of Fraction

property info

A formatted string summarizing the tree’s metadata, subdivisions, durations, and onsets.

Return type:

str

subtree(node, renumber=True)[source]

Extract a rhythm subtree rooted at the given node.

The subtree becomes a new RhythmTree with: - span = 1 - meas = metric_duration of the selected node - subdivisions = reconstructed from the subtree structure

Parameters:
  • node (int) – The node to use as the root of the subtree

  • renumber (bool, optional) – Whether to renumber the nodes in the new tree (default: True)

Returns:

A new RhythmTree representing the subtree

Return type:

RhythmTree

graft_subtree(target_node, subtree, mode='replace')[source]

Graft a subtree onto the tree and re-evaluate metric values.

Parameters:
  • target_node (int) – The node at which to graft.

  • subtree (RhythmTree or Tree) – The subtree to graft.

  • mode (str, optional) – Grafting mode ('replace' or 'append'). Default is 'replace'.

Returns:

The modified tree (self).

Return type:

RhythmTree

subdivide(node, S)[source]

Subdivide leaf node(s) with structure S.

Each leaf becomes a parent with children defined by S. The node’s proportion D is used as the duration; S specifies the subdivisions.

Parameters:
  • node (int or list of int) – The leaf node(s) to subdivide. Must have no children. If a list, subdivide is applied to each.

  • S (tuple or int) – Subdivisions. If int, interpreted as (1,)*S (e.g. S=3(1, 1, 1)). If tuple, must be valid S-form: each element is a non-zero integer or a (D, S) pair.

Returns:

self (for chaining)

Return type:

RhythmTree

Raises:

ValueError – If node is not found, is not a leaf, or S is invalid.

prune(node)[source]
remove_subtree(node)[source]
make_rest(node)[source]

Make a node and all its descendants into rests by setting their proportions to negative.

Parameters:

node (int) – The node ID to make into a rest along with all its descendants.

Raises:

ValueError – If the node is not found in the tree.

class klotho.chronos.rhythm_trees.meas.Meas(numerator, denominator=None)[source]

Bases: object

A time signature that preserves unreduced fractions.

Unlike Python’s Fraction, which always reduces to lowest terms, Meas keeps the numerator and denominator as given so that musically distinct time signatures such as 4/4 and 2/2 remain distinguishable.

Parameters:
  • numerator (int, float, str, Fraction, or Meas) – The numerator of the time signature, or a value that can be interpreted as a complete time signature (e.g., '3/4', Fraction(3, 4)).

  • denominator (int or None, optional) – The denominator of the time signature. When provided, numerator must also be an int. Default is None.

Raises:

ValueError – If the arguments cannot be parsed into a valid time signature, or if the denominator is zero.

Examples

>>> Meas(3, 4)
3/4
>>> Meas('6/8')
6/8
>>> Meas(Fraction(1, 4))
1/4
__init__(numerator, denominator=None)[source]
property numerator

The numerator of the time signature.

Return type:

int

property denominator

The denominator of the time signature.

Return type:

int

__eq__(other)[source]

Check strict equality of time signature representations.

Two Meas values are equal only if both their numerator and denominator match exactly (e.g., Meas(4, 4) != Meas(2, 2)).

Parameters:

other (Meas, Fraction, int, float, or str) – The value to compare against.

Return type:

bool

is_equivalent(other)[source]

Check if two time signatures represent the same metric proportion.

Unlike __eq__, this compares the rational value so that Meas(4, 4) is equivalent to Meas(2, 2).

Parameters:

other (Meas, Fraction, or str) – The value to compare against.

Return type:

bool

to_fraction()[source]

Convert to a standard Fraction.

Return type:

Fraction

reduced()[source]

Return a new Meas reduced to lowest terms.

Return type:

Meas

Tree Algorithms

Rhythm tree algorithms.

Algorithms that operate on either the S part of a rhythmic tree or its corresponding proportions.

Pseudocode for numbered algorithms by Karim Haddad unless otherwise noted.

“Let us recall that the mentioned part corresponds to the S part of a rhythmic tree composed of (DS), that is its part constituting the proportions which can also encompass other tree structures.” – Karim Haddad

klotho.chronos.rhythm_trees.algorithms.measure_ratios(subdivs)[source]

Transform the subdivisions of a rhythm tree into fractional proportions.

Algorithm 1 (MeasureRatios) from Karim Haddad. Recursively converts the S part of a rhythm tree (D S) into a flat sequence of Fraction values representing each leaf’s proportion of the whole.

Parameters:

subdivs (tuple of int or tuple) – The subdivision part (S) of a rhythm tree. Elements may be plain integers or nested (D, S) tuples for sub-trees.

Returns:

The fractional proportions for every leaf of the tree.

Return type:

tuple of Fraction

Examples

>>> measure_ratios((1, 1, 1))
(Fraction(1, 3), Fraction(1, 3), Fraction(1, 3))
klotho.chronos.rhythm_trees.algorithms.reduced_decomposition(lst, meas)[source]

Reduce proportions relative to a time signature (Tempus).

Algorithm 2 (ReducedDecomposition) from Karim Haddad. Scales each fraction by the Tempus to obtain proportions in the measure’s coordinate system.

Parameters:
  • lst (tuple of Fraction) – The list of proportions (typically from measure_ratios()).

  • meas (Fraction) – The Tempus (time signature as a fraction).

Returns:

The reduced proportions.

Return type:

tuple of Fraction

klotho.chronos.rhythm_trees.algorithms.strict_decomposition(lst, meas)[source]

Decompose proportions into a common-denominator form.

Algorithm 3 (StrictDecomposition) from Karim Haddad. Normalizes a list of proportions so that they share a common denominator, making them directly comparable as integer ratios.

Parameters:
  • lst (tuple of Fraction) – The list of proportions (typically from measure_ratios()).

  • meas (Fraction) – The Tempus (time signature as a fraction).

Returns:

Proportions with a common denominator.

Return type:

tuple of Fraction

klotho.chronos.rhythm_trees.algorithms.ratios_to_subdivs(ratios)[source]

Convert a sequence of fractional ratios to integer subdivisions.

Finds a common denominator, scales all fractions to integers, and divides by the overall GCD to obtain the simplest integer proportions.

Parameters:

ratios (tuple of Fraction) – The fractional ratios to convert.

Returns:

The equivalent integer subdivisions in lowest terms.

Return type:

tuple of int

klotho.chronos.rhythm_trees.algorithms.auto_subdiv(subdivs, n=1)[source]

Automatically subdivide each element of S using a rotational scheme.

Each element in the subdivision tuple is expanded into a nested (D, S) pair, where D is the original element and S is a uniform tuple whose length is determined by a rotationally offset element.

Parameters:
  • subdivs (tuple of int) – The subdivision part (S) of a rhythm tree.

  • n (int, optional) – The rotation offset used to select the subdivision count for each element. Default is 1.

Returns:

Nested (D, S) pairs for each element.

Return type:

tuple of tuple

klotho.chronos.rhythm_trees.algorithms.auto_subdiv_matrix(matrix, rotation_offset=1)[source]

Apply auto_subdiv() to every element in a matrix of tree specs.

Each element of the matrix is a (D, S) pair. The function applies auto_subdiv to each element’s subdivisions with a rotation offset that varies with the element’s row and column position.

Parameters:
  • matrix (tuple of tuple) – A matrix where each element is a (D, S) pair.

  • rotation_offset (int, optional) – Base offset for rotation calculations. Default is 1.

Returns:

A new matrix with auto_subdiv applied to each element.

Return type:

tuple of tuple

klotho.chronos.rhythm_trees.algorithms.rhythm_pair(lst, MM=True)[source]

Generate a rhythmic sequence from the superimposition of pulse grids.

Given a tuple of integers, this function creates evenly spaced pulse grids (one per element), merges them, and returns the inter-onset intervals. The MM flag controls whether grids are spaced by total_product // x (metric modulation mode) or by x directly.

Parameters:
  • lst (tuple of int) – The integers defining each pulse grid.

  • MM (bool, optional) – If True, use metric modulation spacing. Default is True.

Returns:

The inter-onset intervals of the combined grid.

Return type:

tuple of int

klotho.chronos.rhythm_trees.algorithms.segment(ratio)[source]

Segment a ratio into a pair of complementary integers.

Converts the ratio to a Fraction and returns (numerator, denominator - numerator). The ratio must be less than 1.

Parameters:

ratio (Fraction, float, or str) – The ratio to segment (must be < 1).

Returns:

A pair (numerator, denominator - numerator).

Return type:

tuple of int

Raises:

ValueError – If the ratio is >= 1.

klotho.chronos.rhythm_trees.algorithms.sum_proportions(S)[source]

Sum the absolute values of the top-level proportions of a subdivision.

For nested (D, S) elements, only the absolute value of D is used. For plain integers, the absolute value is summed directly.

Parameters:

S (tuple) – The subdivision part of a rhythm tree.

Returns:

The sum of absolute top-level proportions.

Return type:

int

klotho.chronos.rhythm_trees.algorithms.measure_complexity(subdivs)[source]

Determine whether a subdivision structure contains complex (non-binary) rhythms.

Recursively traverses the tree. For any nested (D, S) element, if the sum of S is not a power of two and does not equal D, the rhythm is considered complex.

Parameters:

subdivs (tuple) – The subdivision part of a rhythm tree.

Returns:

True if the tree contains complex (non-binary) rhythms.

Return type:

bool

klotho.chronos.rhythm_trees.algorithms.clean_subdivs(subdivs)[source]

Clean and normalize a subdivision tuple.

Note

Not yet implemented.

Parameters:

subdivs (tuple) – The subdivision part of a rhythm tree.

Returns:

The cleaned subdivision tuple.

Return type:

tuple

Temporal Units

Core Classes

class klotho.chronos.temporal_units.temporal.TemporalUnit(span=1, tempus='4/4', prolatio='d', beat=None, bpm=None)[source]

Bases: object

A rhythmic structure bound to a tempo, producing real-time events.

A TemporalUnit combines a RhythmTree (defined by tempus and prolatio) with a tempo specification (beat, bpm) to produce concrete onset times and durations in seconds.

Outside a Score, a temporal unit always starts at time 0 and its duration is fixed after construction. Placement within a timeline and duration adjustment are handled by ScoreItem after the unit has been added to a Score.

Parameters:
  • span (int, float, or Fraction, optional) – Number of measures. Default is 1.

  • tempus (Meas, Fraction, int, float, or str, optional) – The time signature. Default is '4/4'.

  • prolatio (tuple or str, optional) – The subdivision specification. A tuple gives explicit proportions; a string selects a preset ('d' = duration, 'r' = rest, 'p' = pulse). Default is 'd'.

  • beat (Fraction, int, float, str, or None, optional) – The beat reference for tempo calculation. When None, the denominator of the time signature is used. Default is None.

  • bpm (int, float, or None, optional) – Beats per minute. Default is None (falls back to 60).

Examples

>>> ut = TemporalUnit(tempus='4/4', prolatio='p', bpm=120)
>>> len(ut)
4
__init__(span=1, tempus='4/4', prolatio='d', beat=None, bpm=None)[source]
classmethod from_rt(rt, beat=None, bpm=None)[source]

Construct a TemporalUnit from an existing RhythmTree.

Parameters:
  • rt (RhythmTree) – The rhythm tree to wrap.

  • beat (Fraction, int, float, str, or None, optional) – Beat reference. Default is None.

  • bpm (int, float, or None, optional) – Beats per minute. Default is None.

Return type:

TemporalUnit

property nodes
property leaves

All leaves in left-to-right order (selector form of RT.leaf_nodes).

property root

1-element selector for the root node.

Chain mutations: uc.root.set_pfields(amp=0.3).

leaves_of(node)[source]

Leaves of the subtree rooted at node (selector form of RT.subtree_leaves).

at_depth(d, operator='==')[source]

Nodes at a specific depth (selector form of RT.at_depth).

successors(node)[source]

Direct children of node (selector form of RT.successors).

select(*ids)[source]

Build an ad-hoc selector from ints/selectors or iterables thereof.

property depth

Maximum depth of the underlying RT.

property k

Maximum branching factor of the underlying RT.

depth_of(node)[source]

Depth of node in the underlying RT.

out_degree(node)[source]

Out-degree of node in the underlying RT.

topological_sort()[source]

Topological sort of the underlying RT’s nodes.

property span

The number of measures that the TemporalUnit spans.

property tempus

The time signature of the TemporalUnit.

property prolationis

The S-part of a RhythmTree which describes the subdivisions of the TemporalUnit.

property rt

The RhythmTree of the TemporalUnit (returns a copy).

property metric_durations

The metric durations from the RhythmTree which describe the proportional durations of the TemporalUnit.

property metric_onsets

The metric onsets from the RhythmTree which describe the proportional onset times of the TemporalUnit.

property beat

The rhythmic ratio that describes the beat of the TemporalUnit.

property bpm

The beats per minute of the TemporalUnit.

property type

The type of the TemporalUnit.

property start: float

Absolute start time in seconds.

Always 0 for a unit outside a Score. Inside a Score the start time is assigned by placement kwargs on add().

property onsets

The real-time onset of each leaf event in seconds.

property durations

The real-time duration of each leaf event in seconds.

property duration

The total duration (in seconds) of the TemporalUnit.

property end: float

Absolute end time in seconds (start + duration).

property time

The absolute start and end times (in seconds) of the TemporalUnit.

property events

A DataFrame of all leaf events with timing and metric data.

Return type:

pandas.DataFrame

make_rest(node)[source]

Turn a node (or each node in an iterable) and all descendants into rests.

Delegates to RhythmTree.make_rest() and re-evaluates timing once at the end (batched across all provided nodes).

Parameters:

node (int or iterable of int) – A single node ID, or an iterable of node IDs, to convert to rests.

Raises:

ValueError – If any node is not found in the rhythm tree.

Return type:

None

subdivide(node, S)[source]

Subdivide a leaf node with structure (D, S).

Delegates to RhythmTree.subdivide() and invalidates cached events.

Parameters:
  • node (int) – The leaf node to subdivide.

  • S (tuple) – Valid subdivisions tuple (integers or nested (D, S) tuples).

Raises:

ValueError – If the node is not found or is not a leaf.

Return type:

None

sparsify(probability, node=None)[source]

Randomly convert leaf events to rests with a given probability.

Parameters:
  • probability (float) – Probability (0–1) that each eligible leaf becomes a rest.

  • node (int, list of int, or None, optional) – Restrict to leaves under this node (or nodes). When None, all leaves are candidates. Default is None.

repeat(n)[source]

Create a TemporalUnitSequence of n copies of this unit.

Parameters:

n (int) – Number of repetitions.

Return type:

TemporalUnitSequence

copy()[source]

Create a deep copy of this TemporalUnit.

The copy preserves any internal placement (_offset) so that containers like TemporalUnitSequence can rebuild cleanly.

class klotho.chronos.temporal_units.temporal.TemporalUnitSequence(ut_seq=None)[source]

Bases: object

An ordered sequence of TemporalUnit objects representing consecutive temporal events.

Units are automatically offset so that each begins where the previous one ends. Outside a Score, a sequence always starts at time 0 and its duration is fixed after construction.

Parameters:

ut_seq (list of TemporalUnit, optional) – Initial sequence of temporal units. Default is an empty list.

__init__(ut_seq=None)[source]
property seq

The list of TemporalUnit objects in the sequence.

property onsets

A tuple of onset times (in seconds) for each TemporalUnit in the sequence.

property durations

A tuple of durations (in seconds) for each TemporalUnit in the sequence.

property duration

The total duration (in seconds) of the sequence.

property start: float

Absolute start time in seconds (0 outside a Score).

property end: float

Absolute end time in seconds (start + duration).

property size

The total number of events across all TemporalUnits in the sequence.

property time

The absolute start and end times (in seconds) of the sequence.

append(ut, repeat=1)[source]

Append a temporal unit to the end of the sequence.

Parameters:
  • ut (TemporalUnit) – The unit to append.

  • repeat (int, optional) – Number of independent copies to append. Default is 1.

Return type:

None

prepend(ut)[source]

Prepend a temporal unit to the beginning of the sequence.

Parameters:

ut (TemporalUnit) – The unit to prepend.

Return type:

None

insert(index, ut)[source]

Insert a temporal unit at the specified index.

Parameters:
  • index (int) – The position at which to insert.

  • ut (TemporalUnit) – The unit to insert.

Raises:

IndexError – If the index is out of range.

Return type:

None

remove(index)[source]

Remove the temporal unit at the specified index.

Parameters:

index (int) – The index of the unit to remove.

Raises:

IndexError – If the index is out of range.

Return type:

None

replace(index, ut)[source]

Replace the temporal unit at the specified index.

Parameters:
  • index (int) – The index of the unit to replace.

  • ut (TemporalUnit) – The replacement unit.

Raises:

IndexError – If the index is out of range.

Return type:

None

extend(other_seq, repeat=1)[source]

Extend the sequence by appending all units from another iterable.

Parameters:
  • other_seq (TemporalUnitSequence or iterable of TemporalUnit) – The source of units to append.

  • repeat (int, optional) – Number of times to repeat the extension. Default is 1.

Return type:

None

copy()[source]

Create a deep copy of this TemporalUnitSequence.

Internal placement (_offset) is preserved on the copy so that TemporalBlock and Score can rebuild their layouts cleanly.

class klotho.chronos.temporal_units.temporal.TemporalBlock(rows=None, axis=-1, sort_rows=True)[source]

Bases: object

A collection of parallel temporal structures representing simultaneous events.

Each row can be a TemporalUnit, TemporalUnitSequence, or another TemporalBlock. Rows are aligned according to the axis parameter and optionally sorted by duration.

Parameters:
  • rows (list, optional) – Temporal structures (TemporalUnit, TemporalUnitSequence, or TemporalBlock). Default is an empty list.

  • axis (float, optional) – Alignment axis from -1 (left) through 0 (center) to 1 (right). Default is -1.

  • sort_rows (bool, optional) – Whether to sort rows by duration (longest first). Default is True.

Notes

Outside a Score, a block always starts at time 0 and its total duration is fixed after construction.

__init__(rows=None, axis=-1, sort_rows=True)[source]
classmethod from_tree_mat(matrix, meas_denom=1, subdiv=False, rotation_offset=1, beat=None, bpm=None)[source]

Create a TemporalBlock from a matrix of tree specifications.

Parameters:
  • matrix (tuple of tuple) – Matrix where each element is a (D, S) pair.

  • meas_denom (int, optional) – Denominator for measure fractions. Default is 1.

  • subdiv (bool, optional) – Whether to apply automatic subdivision. Default is False.

  • rotation_offset (int, optional) – Offset for rotation calculations. Default is 1.

  • beat (Fraction, str, float, or None, optional) – Beat ratio specification. Default is None.

  • bpm (int, float, or None, optional) – Beats per minute. Default is None.

Return type:

TemporalBlock

property height

The number of rows in the block.

property rows

The list of temporal structures in the block.

property duration

The total duration (in seconds) of the longest row in the block.

property start: float

Absolute start time in seconds (0 outside a Score).

property end: float

Absolute end time in seconds (start + duration).

property sort_rows

Whether to sort rows by duration (longest at index 0).

property axis

The temporal axis position of the block.

prepend(row)[source]

Add a temporal structure at the beginning (index 0) of the block.

Parameters:

row (TemporalUnit, TemporalUnitSequence, or TemporalBlock) – The temporal structure to prepend.

Return type:

None

append(row)[source]

Add a temporal structure at the end (highest index) of the block.

Parameters:

row (TemporalUnit, TemporalUnitSequence, or TemporalBlock) – The temporal structure to append.

Return type:

None

insert(index, row)[source]

Insert a temporal structure at the specified index.

Parameters:
Raises:

IndexError – If the index is out of range.

Return type:

None

remove(index)[source]

Remove the row at the specified index.

Parameters:

index (int) – The index of the row to remove.

Raises:

IndexError – If the index is out of range.

Return type:

None

replace(index, row)[source]

Replace the row at the specified index.

Parameters:
Raises:

IndexError – If the index is out of range.

Return type:

None

extend(other_block)[source]

Extend the block by appending all rows from another block.

Parameters:

other_block (TemporalBlock) – The block whose rows will be appended.

Return type:

None

copy()[source]

Create a deep copy of this TemporalBlock.

Internal placement (_offset) is preserved on the copy so that Score can rebuild its timeline cleanly.

Temporal Algorithms

klotho.chronos.temporal_units.algorithms.decompose(ut, prolatio=None, depth=None)[source]

Decompose a temporal structure into its constituent parts.

When depth is given, subtrees at that depth become the new units. Otherwise, each leaf duration becomes an independent unit with the specified prolatio.

Parameters:
  • ut (TemporalUnit or CompositionalUnit) – The temporal structure to decompose.

  • prolatio (tuple, str, or None, optional) – The subdivision specification for the resulting units. When None, defaults to 'd' (duration). Default is None.

  • depth (int or None, optional) – If given, decompose at the specified tree depth rather than at the leaf level. Default is None.

Returns:

A sequence of the resulting temporal units.

Return type:

TemporalUnitSequence

klotho.chronos.temporal_units.algorithms.modulate_tempo(ut, beat, bpm)[source]

Create a new unit with specified beat/bpm, preserving the original duration.

The tempus is adjusted so that the resulting unit has the same duration as ut under the new tempo parameters.

Parameters:
Returns:

A new unit with adjusted tempus and the specified beat/bpm.

Return type:

TemporalUnit or CompositionalUnit

klotho.chronos.temporal_units.algorithms.modulate_tempus(ut, span, tempus)[source]

Create a new unit with specified tempus, preserving the original duration.

The bpm is adjusted so that the resulting unit has the same duration as ut under the new tempus and span.

Parameters:
Returns:

A new unit with the specified tempus and adjusted bpm.

Return type:

TemporalUnit or CompositionalUnit

klotho.chronos.temporal_units.algorithms.convolve(x, h, beat='1/4', bpm=60)[source]

Convolve two temporal structures to produce a new sequence.

Both inputs are first decomposed (if not already sequences), then their tempus values are convolved in the signal-processing sense to produce a sequence of y_len = len(x) + len(h) - 1 units.

Parameters:
Returns:

The convolved sequence.

Return type:

TemporalUnitSequence

Utilities

Beat Utilities

klotho.chronos.utils.beat.cycles_to_frequency(cycles, duration)[source]

Calculate the frequency needed to produce a number of cycles within a duration.

Parameters:
  • cycles (int or float) – The desired number of complete cycles.

  • duration (float) – The time duration in seconds.

Returns:

The frequency in Hertz (Hz).

Return type:

float

Examples

>>> cycles_to_frequency(4, 2)
2.0
klotho.chronos.utils.beat.beat_duration(ratio, bpm, beat_ratio='1/4')[source]

Calculate the duration in seconds of a musical beat given a ratio and tempo.

The beat duration is determined by the ratio of the beat to a reference beat duration (beat_ratio), scaled by the tempo factor derived from beats per minute (BPM).

Parameters:
  • ratio (int, float, Fraction, or str) – The ratio of the desired beat duration to a whole note (e.g., '1/4' for a quarter note).

  • bpm (int or float) – The tempo in beats per minute.

  • beat_ratio (int, float, Fraction, or str, optional) – The reference beat duration ratio. Default is '1/4' (quarter note).

Returns:

The beat duration in seconds.

Return type:

float

Examples

>>> beat_duration('1/4', 120)
0.5
klotho.chronos.utils.beat.calc_onsets(durations)[source]

Calculate onset times from a sequence of durations.

Each onset is the cumulative sum of the absolute values of all preceding durations, starting from zero.

Parameters:

durations (tuple) – A sequence of duration values (may include negative values for rests).

Returns:

The onset times corresponding to each duration.

Return type:

tuple

Examples

>>> calc_onsets((Fraction(1, 4), Fraction(1, 4), Fraction(1, 2)))
(0, Fraction(1, 4), Fraction(1, 2))

Tempo Utilities

class klotho.chronos.utils.tempo.TEMPO(value)[source]

Bases: MinMaxEnum

Enum for musical tempo markings mapped to beats per minute (bpm).

Each tempo marking is associated with a range of beats per minute. This enumeration returns a tuple representing the minimum and maximum bpm for each tempo.

Tempo Markings

Name

Tempo Marking

BPM Range

Larghissimo

extremely slow

12 – 24

Adagissimo_Grave

very slow, solemn

24 – 40

Largo

slow and broad

40 – 66

Larghetto

rather slow and broad

44 – 66

Adagio

slow and expressive

44 – 68

Adagietto

slower than andante

46 – 80

Lento

slow

52 – 108

Andante

walking pace

56 – 108

Andantino

slightly faster than andante

80 – 108

Marcia_Moderato

moderate march

66 – 80

Andante_Moderato

between andante and moderato

80 – 108

Moderato

moderate speed

108 – 120

Allegretto

moderately fast

112 – 120

Allegro_Moderato

slightly less than allegro

116 – 120

Allegro

fast, bright

120 – 156

Molto_Allegro_Allegro_Vivace

slightly faster than allegro

124 – 156

Vivace

lively, fast

156 – 176

Vivacissimo_Allegrissimo

very fast, bright

172 – 176

Presto

very fast

168 – 200

Prestissimo

extremely fast

200 – 300

Examples

>>> TEMPO.Adagio.min
44
>>> TEMPO.Adagio.max
68
Larghissimo = (12, 24)
Adagissimo_Grave = (24, 40)
Largo = (40, 66)
Larghetto = (44, 66)
Adagio = (44, 68)
Adagietto = (46, 80)
Lento = (52, 108)
Andante = (56, 108)
Andantino = (80, 108)
Marcia_Moderato = (66, 80)
Andante_Moderato = (80, 108)
Moderato = (108, 120)
Allegretto = (112, 120)
Allegro_Moderato = (116, 120)
Allegro = (120, 156)
Molto_Allegro_Allegro_Vivace = (124, 156)
Vivace = (156, 176)
Vivacissimo_Allegrissimo = (172, 176)
Presto = (168, 200)
Prestissimo = (200, 300)
klotho.chronos.utils.tempo.metric_modulation(current_tempo, current_beat_value, new_beat_value)[source]

Determine the new tempo for a metric modulation between two beat values.

Metric modulation maintains the duration of a beat constant while changing the note value that represents the beat, effectively changing the tempo.

See: https://en.wikipedia.org/wiki/Metric_modulation

Parameters:
  • current_tempo (float) – The original tempo in beats per minute.

  • current_beat_value (Fraction, str, or float) – The note value (as a fraction of a whole note) representing one beat before modulation.

  • new_beat_value (Fraction, str, or float) – The note value (as a fraction of a whole note) representing one beat after modulation.

Returns:

The new tempo in beats per minute after the metric modulation.

Return type:

float

Examples

>>> metric_modulation(120, '1/4', '1/8')
240.0
klotho.chronos.utils.tempo.tempo_for_duration(metric_ratio, reference_beat, duration)[source]

Calculate the tempo required for a metric ratio to last a specified duration.

Parameters:
  • metric_ratio (Fraction, str, or float) – The metric ratio representing the total duration (e.g., '4/4').

  • reference_beat (Fraction, str, or float) – The beat value that defines the tempo (e.g., '1/4' for a quarter note).

  • duration (float) – The desired duration in seconds.

Returns:

The tempo in beats per minute.

Return type:

float

Examples

>>> tempo_for_duration('4/4', '1/4', 2.0)
120.0
klotho.chronos.utils.tempo.beat_for_duration(metric_ratio, bpm, duration)[source]

Calculate the reference beat value for a metric ratio at a given tempo and duration.

Parameters:
  • metric_ratio (Fraction, str, or float) – The metric ratio representing the total duration (e.g., '4/4').

  • bpm (float) – The tempo in beats per minute.

  • duration (float) – The desired duration in seconds.

Returns:

The reference beat value as a fraction.

Return type:

Fraction

Examples

>>> beat_for_duration('4/4', 120, 2.0)
Fraction(1, 4)

Time Conversion

klotho.chronos.utils.time_conversion.seconds_to_hmsms(seconds, as_string=True)[source]

Convert a duration from seconds to hours, minutes, seconds, and milliseconds.

Parameters:
  • seconds (float) – The duration in seconds.

  • as_string (bool, optional) – Whether to return the result as a formatted string or a tuple. Default is True.

Returns:

If as_string is True, a formatted string like '1h:01m:01s:500ms' showing non-zero units. If False, a tuple of (hours, minutes, seconds, milliseconds).

Return type:

str or tuple of int

Examples

>>> seconds_to_hmsms(3661.5)
'1h:01m:01s:500ms'
>>> seconds_to_hmsms(3661.5, as_string=False)
(1, 1, 1, 500)
klotho.chronos.utils.time_conversion.hmsms_to_seconds(h=0, m=0, s=0, ms=0)[source]

Convert hours, minutes, seconds, and milliseconds to total seconds.

Parameters:
  • h (int, optional) – Hours. Default is 0.

  • m (int, optional) – Minutes. Default is 0.

  • s (int, optional) – Seconds. Default is 0.

  • ms (int, optional) – Milliseconds. Default is 0.

Returns:

Total duration in seconds.

Return type:

float

Examples

>>> hmsms_to_seconds(h=1, m=30, s=45, ms=500)
5445.5
klotho.chronos.utils.time_conversion.seconds_to_hmsf(seconds, fps=30, as_string=True)[source]

Convert a duration from seconds to hours, minutes, seconds, and frames.

Parameters:
  • seconds (float) – The duration in seconds.

  • fps (int, optional) – Frames per second. Default is 30.

  • as_string (bool, optional) – Whether to return the result as a formatted string or a tuple. Default is True.

Returns:

If as_string is True, a formatted string like '1h:01m:01s:15f'. If False, a tuple of (hours, minutes, seconds, frames).

Return type:

str or tuple of int

Examples

>>> seconds_to_hmsf(3661.5, fps=30)
'1h:01m:01s:15f'
>>> seconds_to_hmsf(3661.5, fps=30, as_string=False)
(1, 1, 1, 15)
klotho.chronos.utils.time_conversion.hmsf_to_seconds(h=0, m=0, s=0, f=0, fps=30)[source]

Convert hours, minutes, seconds, and frames to total seconds.

Parameters:
  • h (int, optional) – Hours. Default is 0.

  • m (int, optional) – Minutes. Default is 0.

  • s (int, optional) – Seconds. Default is 0.

  • f (int, optional) – Frames. Default is 0.

  • fps (int, optional) – Frames per second. Default is 30.

Returns:

Total duration in seconds.

Return type:

float

Examples

>>> hmsf_to_seconds(h=1, m=30, s=45, f=15, fps=30)
5445.5