API

class djalgo.analysis.Index(values, weights=None)[source]

Bases: object

A class that performs various analysis on a list of values.

Parameters:
  • values (list) – A list of numerical values.

  • weights (list, optional) – A list of weights corresponding to the values. Defaults to None.

values

A list of numerical values.

Type:

list

weights

A list of weights corresponding to the values.

Type:

list

autocorrelation()[source]

Calculates the autocorrelation of the values.

Returns:

The autocorrelation values.

Return type:

list

balance()[source]

Calculates the balance index of the values.

Returns:

The balance index.

Return type:

float

dissonance(scale)[source]

Calculates the dissonance of the values with respect to a scale.

Parameters:

scale (list) – A list of values representing a musical scale.

Returns:

The dissonance.

Return type:

float

fibonacci_index()[source]

Calculates a Fibonacci index to evaluate how closely the sequence matches a Fibonacci sequence.

Returns:

The Fibonacci index, lower values indicate closer match to Fibonacci sequence.

Return type:

float

gini()[source]

Calculates the Gini index of the values.

Returns:

The Gini index.

Return type:

float

motif()[source]

Calculates the motif score of the values.

Returns:

The motif score.

Return type:

float

rhythmic(measure_length)[source]

Calculates the rhythmic score of the values.

Parameters:

measure_length (float) – The length of a measure.

Returns:

The rhythmic score.

Return type:

float

djalgo.conversion.convert(notes, to, bpm=120, time_signature=None, key_signature=None)[source]

Convert a list of musical notes to the specified format.

Parameters:
  • notes (list) – List of musical notes.

  • to (str) – Format to convert the notes to. Options are “music21”, “mido”, or “pretty_midi”.

Returns:

Converted musical notes in the specified format.

Return type:

object

Raises:

ValueError – If the specified format is not supported.

djalgo.conversion.get_program_number(instrument_name)[source]

Find the closest program number for a given instrument name.

djalgo.conversion.sequence_to_miditoolkit_instrument(notes, bpm=120, velocity=64, program=0)[source]

Convert a sequence of musical notes to a miditoolkit Instrument.

djalgo.conversion.sequence_to_mido_track(notes, bpm=120, velocity=64, program=0)[source]

Convert a sequence of musical notes to a Mido track.

djalgo.conversion.sequence_to_music21_stream(notes, bpm=120)[source]

Convert a sequence of musical notes to a music21 Stream, with a tempo mark.

djalgo.conversion.sequence_to_prettymidi_instrument(notes, bpm=120, velocity=64, program=0)[source]

Convert a sequence of musical notes to a PrettyMIDI instrument.

djalgo.conversion.sequences_to_prettymidi(parts, bpm=120, velocity=64)[source]

Convert multiple sequences of musical notes to a PrettyMIDI object.

djalgo.conversion.to_miditoolkit(notes, bpm=120, velocity=64)[source]

Convert notes to miditoolkit format based on their structure.

djalgo.conversion.to_mido(notes, bpm=120, velocity=64)[source]

Convert notes to Mido format based on their structure.

djalgo.conversion.to_music21(notes, bpm=120, time_signature=None, key_signature=None)[source]

Convert notes to music21 format based on their structure, with BPM defining the tempo.

djalgo.conversion.to_prettymidi(notes, bpm=120, velocity=64)[source]

Convert notes to PrettyMIDI format based on their structure.

djalgo.conversion.tuple_to_miditoolkit_notes(note_tuple, bpm=120, velocity=64)[source]

Convert a single note tuple to a list of miditoolkit Notes.

djalgo.conversion.tuple_to_mido_messages(note_tuple, bpm=120, velocity=64)[source]

Convert a single note tuple to a list of Mido messages.

djalgo.conversion.tuple_to_music21_element(note_tuple)[source]

Convert a single note tuple to a music21 Note, Chord, or Rest.

djalgo.conversion.tuple_to_prettymidi_element(note_tuple, bpm=120, velocity=64)[source]

Convert a single note tuple to a list of PrettyMIDI Note objects.

class djalgo.djai.GRUModel(nn_units, dropout, input_size)[source]

Bases: Module

Defines a GRU model for sequence generation.

layers

List of GRU layers.

Type:

torch.nn.ModuleList

fc

Fully connected layer for output.

Type:

torch.nn.Linear

forward(x)[source]

Defines the forward pass of the GRUModel.

Parameters:

x (torch.Tensor) – Input tensor.

Returns:

Output tensor.

Return type:

torch.Tensor

class djalgo.djai.LSTMModel(nn_units, dropout, input_size)[source]

Bases: Module

Defines an LSTM model for sequence generation.

layers

List of LSTM layers.

Type:

torch.nn.ModuleList

fc

Fully connected layer for output.

Type:

torch.nn.Linear

forward(x)[source]

Defines the forward pass of the LSTMModel.

Parameters:

x (torch.Tensor) – Input tensor.

Returns:

Output tensor.

Return type:

torch.Tensor

class djalgo.djai.ModelManager(sequence_length_input, sequence_length_output, model_type, nn_units, dropout, batch_size, learning_rate, n_heads=None)[source]

Bases: object

Manages the initialization, training, and generation of a neural network model for MIDI sequence generation.

seq_len_input

Length of input sequences.

Type:

int

seq_len_output

Length of output sequences.

Type:

int

model_type

Type of model to use (‘lstm’, ‘gru’, ‘transformer’).

Type:

str

nn_units

Number of units in each layer of the neural network.

Type:

tuple

dropout

Dropout rate for the neural network.

Type:

float

batch_size

Number of samples per batch.

Type:

int

learning_rate

Learning rate for the optimizer.

Type:

float

n_heads

Number of attention heads (used for transformer model).

Type:

int, optional

tokenizer

Tokenizer for MIDI files.

Type:

miditok.REMI

input_size

Size of the input vocabulary.

Type:

int

model

Neural network model.

Type:

torch.nn.Module

optimizer

Optimizer for training the model.

Type:

torch.optim.Optimizer

loss_fn

Loss function for training the model.

Type:

torch.nn.Module

fit(midi_files_path, epochs, verbose=None)[source]

Trains the model on the specified MIDI files for a given number of epochs.

Parameters:
  • midi_files_path (str) – Path to the directory containing MIDI files.

  • epochs (int) – Number of epochs to train the model.

  • verbose (int or None, optional) – Number of steps between progress messages or None for no messages (default: None).

Returns:

Trained model.

Return type:

torch.nn.Module

generate(length, primer_file, output_file)[source]

Generates a MIDI sequence based on a primer file and saves it to an output file.

Parameters:
  • length (int) – Length of the sequence to generate.

  • primer_file (str) – Path to the primer MIDI file.

  • output_file (str) – Path to save the generated MIDI file.

save(file_path)[source]

Saves the model state to a file.

Parameters:

file_path (str) – Path to save the model state.

class djalgo.djai.TransformerModel(nn_units, dropout, n_heads, input_size)[source]

Bases: Module

Defines a Transformer model for sequence generation.

embedding

Embedding layer to project input size to embedding dimension.

Type:

torch.nn.Linear

encoder_layers

Transformer encoder layer.

Type:

torch.nn.TransformerEncoderLayer

transformer_encoder

Transformer encoder.

Type:

torch.nn.TransformerEncoder

fc

Fully connected layer for output.

Type:

torch.nn.Linear

forward(x, attention_mask=None)[source]

Defines the forward pass of the TransformerModel.

Parameters:
  • x (torch.Tensor) – Input tensor.

  • attention_mask (torch.Tensor, optional) – Attention mask for the transformer.

Returns:

Output tensor.

Return type:

torch.Tensor

class djalgo.fractal.CellularAutomata(rule_number, width, initial_state=None)[source]

Bases: object

A class for simulating one-dimensional cellular automata based on a specific rule set.

Parameters:
  • rule_number (int or str) – Rule number for the cellular automaton, must be between 0 and 255.

  • width (int) – Number of cells in the automaton’s width.

  • initial_state (list of int, optional) – Initial state of the automaton. Defaults to all zeros with a central one.

width

The cellular automaton’s width.

Type:

int

rule_number

The rule number, zero-padded to three digits.

Type:

str

initial_state

The initial state of the automaton.

Type:

list of int

state

The current state of the automaton.

Type:

list of int

rules

The rules loaded from a JSON file.

Type:

list of tuple

generate(iterations, strips, values)[source]

Generates the evolution of the automaton, mapping binary states (0 or 1) to specific values based on provided mappings.

Parameters:
  • iterations (int) – Number of iterations to evolve the automaton.

  • strips (list of tuples) – Sections of the automaton for which to generate values.

  • values (list of dicts) – Mappings from indices in each strip to specific values.

Returns:

A list of evolutions for each strip, with binary states mapped to specified values.

Return type:

list

generate_01(iterations, strips=None)[source]

Generates a binary (0 or 1) evolution of the automaton over a specified number of iterations, optionally for specific strips.

Parameters:
  • iterations (int) – Number of iterations to evolve the automaton.

  • strips (list of tuples, optional) – Specific sections of the automaton to evolve.

Returns:

A list representing the evolution of the automaton, either as a whole or just the specified strips.

Return type:

list

load_rules(rule_number)[source]

Loads the rules from a JSON file based on the rule number.

Parameters:

rule_number (str) – The rule number as a string, zero-padded to three digits.

Returns:

A list of tuples representing the rules for the cellular automaton.

Return type:

list

plot(iterations, ax=None, strips=None, extract_strip=False, title=None, show_axis=True)[source]

Plots the evolution of the cellular automaton.

Parameters:
  • iterations (int) – Number of generations to simulate.

  • ax (matplotlib.axes.Axes, optional) – The matplotlib axis to plot on. If None, a new figure is created.

  • strips (list of tuples, optional) – Ranges to highlight or exclusively plot.

  • extract_strip (bool) – If True, only the specified strips are plotted each in separate subplots.

  • title (str, optional) – Title for the plot. Default is based on the rule number.

  • show_axis (bool) – Whether to show axis labels and grid.

Returns:

The axis with the plot.

Return type:

matplotlib.axes.Axes

update_state()[source]

Updates the state of the automaton based on its rules for one generation.

validate_strips(strips)[source]

Validates that the strips are correctly formatted and within the valid range.

Parameters:

strips (list of tuples) – Each tuple should specify the start and end indices of a strip in the automaton.

Raises:

ValueError – If strips are not properly formatted or indices are out of range.

validate_values(values, strips)[source]

Validates that the values are provided as dictionaries, and there is a dictionary for each strip.

Parameters:
  • values (list or dict) – List of dictionaries mapping indices to pitches or other data.

  • strips (list of tuples) – List of strip ranges to validate against.

Raises:

ValueError – If values are not provided as a list of dictionaries or their count doesn’t match the strips.

class djalgo.fractal.LogisticMap(rates, iterations=1000, last_n=100)[source]

Bases: object

generate()[source]
plot(ax=None, figsize=(10, 6))[source]
class djalgo.fractal.Mandelbrot(scale=None, start_note_index=0, dimensions=(800, 800), max_iter=1000, x_range=(-2.0, 1.0), y_range=(-1.5, 1.5))[source]

Bases: object

generate(method='horizontal', line_index=0)[source]
generate_mandelbrot()[source]
plot(ax=None, figsize=(10, 10), zoom_rect=None, show_numbers=False)[source]
djalgo.fractal.compute_logistic(rate_values, iterations, last_n)[source]

Compute the logistic map for a range of r values, collecting the last last_n iterations.

djalgo.fractal.generate_mandelbrot_jit(x_range, y_range, dimensions, max_iter)[source]
djalgo.fractal.logistic_map(growth_rate, pop, iterations)[source]

Compute logistic map iteratively for a given rate over many iterations.

class djalgo.genetic.Darwin(initial_phrases, mutation_rate=0.05, population_size=50, mutation_probabilities=None, scale=None, measure_length=4, time_resolution=[0.125, 4], weights=None, targets=None, seed=None)[source]

Bases: object

calculate_fitness_components(phrase)[source]

Calculate the fitness components based on the Index class for a given phrase.

Parameters:

phrase (list) – The musical phrase.

Returns:

A dictionary containing the fitness components (‘gini’, ‘balance’, ‘motif’, ‘dissonance’, ‘rhythmic’).

Return type:

dict

crossover(parent1, parent2)[source]

Combine two phrases to create a new phrase.

Parameters:
  • parent1 (list) – Parent phrases.

  • parent2 (list) – Parent phrases.

Returns:

New musical phrase generated from parents.

Return type:

list

evolve(k=25, rest_rate=0.02)[source]

Evolve the population of phrases through selection, crossover, and mutation.

Parameters:

k (int) – Number of phrases to select for the next generation.

fitness(phrase)[source]

Calculate the fitness of a phrase based on how closely it meets the desired musical metrics targets.

Parameters:

phrase (list) – Musical phrase.

Returns:

Fitness score of the phrase.

Return type:

float

mutate(phrase, rate=None, rest_rate=0.02)[source]

Mutate a musical phrase while respecting musical structures and boundaries.

select(k=25)[source]

Select top-k phrases based on fitness.

Parameters:

k (int) – Number of top phrases to select.

Returns:

Top k musical phrases.

Return type:

list

class djalgo.harmony.MusicTheoryConstants[source]

Bases: object

The Base class defines a set of musical scales, intervals, and notes. - scale_to_triad method returns the intervals for a triad based on the given scale intervals. - note_to_triad method converts a note to a triad based on the given scale intervals.

chromatic_scale = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
static convert_flat_to_sharp(note)[source]
intervals = {'M2': 2, 'M3': 4, 'M6': 9, 'M7': 11, 'P1': 0, 'P4': 5, 'P5': 7, 'P8': 12, 'm2': 1, 'm3': 3, 'm6': 8, 'm7': 10}
scale_intervals = {'chromatic': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 'diminished': [0, 2, 3, 5, 6, 8, 9, 11], 'dorian': [0, 2, 3, 5, 7, 9, 10], 'harmonic minor': [0, 2, 3, 5, 7, 8, 11], 'locrian': [0, 1, 3, 5, 6, 8, 10], 'lydian': [0, 2, 4, 6, 7, 9, 11], 'major': [0, 2, 4, 5, 7, 9, 11], 'major pentatonic': [0, 2, 4, 7, 9], 'melodic minor ascending': [0, 2, 3, 5, 7, 9, 11], 'melodic minor descending': [0, 2, 3, 5, 7, 8, 10], 'minor': [0, 2, 3, 5, 7, 8, 10], 'minor pentatonic': [0, 3, 5, 7, 10], 'mixolydian': [0, 2, 4, 5, 7, 9, 10], 'phrygian': [0, 1, 3, 5, 7, 8, 10]}
static scale_to_triad(scale)[source]

Returns the intervals for a triad based on the given scale intervals.

class djalgo.harmony.Ornament(type='grace_note', tonic=None, mode=None, by=1.0, grace_note_type='acciaccatura', grace_pitches=None, trill_rate=0.125, arpeggio_degrees=None, slide_length=4.0)[source]

Bases: MusicTheoryConstants

add_arpeggiation(notes, note_index, voice)[source]

Applies arpeggiation to a chord at a specified index in the list of notes using the degrees from a Voice instance.

Parameters:
  • notes (list) – The list of notes to be processed.

  • note_index (int) – The index of the note to which the arpeggiation will be added.

  • voice (Voice) – An instance of the Voice class.

Returns:

The list of notes with the specified arpeggiation applied to the specified chord.

Return type:

list

add_grace_note(notes, note_index)[source]

Adds a grace note (either acciaccatura or appoggiatura) to a specified note in the list.

Parameters:
  • notes (list) – The list of notes to be processed.

  • note_index (int) – The index of the note to which the trill will be added.

Returns:

The list of notes with the specified grace note added.

Return type:

list

add_mordent(notes, note_index)[source]

Simulates a mordent ornament by rapidly alternating between the original pitch and one step defined in self.by.

Parameters:
  • notes (list) – The list of notes to be processed.

  • note_index (int) – The index of the note to which the trill will be added.

Returns:

A list containing the notes that make up the mordent.

Return type:

list

add_slide(notes, note_index, slide_length=4)[source]

Simulates a slide from the current note to the next by incrementally changing the pitch.

Parameters:
  • notes (list) – The list of notes to be processed.

  • note_index (int) – The index of the note from which the slide will start.

  • slide_length (int) – The number of steps in the slide.

Returns:

The list of notes with the specified slide applied.

Return type:

list

add_trill(notes, note_index)[source]

Simulates a trill ornament by alternating between the original pitch and one step above.

Parameters:
  • notes (list) – The list of notes to be processed.

  • note_index (int) – The index of the note to which the trill will be added.

Returns:

The list of notes with the specified trill applied to the specified note.

Return type:

list

add_turn(notes, note_index)[source]

Simulates a turn ornament by playing the note above, the note itself, the note below, and returning to the note.

Parameters:
  • notes (list) – The list of notes to be processed.

  • note_index (int) – The index of the note to which the turn will be added.

Returns:

The list of notes with the specified turn applied to the specified note.

Return type:

list

generate(notes, note_index=None)[source]

Applies the specified ornamentation action and type to the list of notes.

Parameters:
  • notes (list) – The list of notes to be processed.

  • note_index (int) – The index of the note to ornament. If None, a note will be chosen randomly.

Returns:

The list of notes with the specified ornamentation applied.

Return type:

list

generate_scale(tonic, mode)[source]

Generate a complete scale based on the tonic and scale type. This function is the same as the one in the Voice class.

Parameters:
  • tonic (str) – The tonic note for the scale.

  • mode (str) – The type of scale to generate.

Returns:

A list of MIDI notes for the complete scale.

Return type:

list

class djalgo.harmony.Progression(tonic_pitch='C4', circle_of='P5', type='chords', radius=[3, 3, 1], weights=None)[source]

Bases: MusicTheoryConstants

A class representing a musical progression generator based on the circle of fifths (or any other interval).

compute_circle()[source]

Compute chords based on the circle of fifths, thirds, etc., within the specified radius.

Returns:

A tuple containing lists of root MIDI notes for major, minor, and diminished chords.

Return type:

tuple

generate(length=4, seed=None)[source]

Generate a musical progression.

Parameters:
  • length (int) – The length of the progression in number of chords. Defaults to 4.

  • seed (int) – The seed value for the random number generator. Defaults to None.

Returns:

A list of lists, where each inner list represents a chord in the progression.

Return type:

list

generate_chord(root_note_midi, chord_type)[source]

Generate a chord based on root MIDI note and chord type.

Parameters:
  • root_note_midi (int) – The root MIDI note of the chord.

  • chord_type (str) – The type of chord to generate. Can be ‘major’, ‘minor’, or ‘diminished’.

Returns:

A list of MIDI notes representing the generated chord.

Return type:

list

class djalgo.harmony.Scale(tonic, mode='major')[source]

Bases: MusicTheoryConstants

Represents a musical scale.

Parameters:
  • tonic (str) – The tonic note of the scale.

  • mode (str or list) – The type of scale. Defaults to ‘major’. If a list is provided, it represents a custom scale.

Raises:

ValueError – If the tonic note is not a valid note or if the scale type is not a valid scale.

tonic

The tonic note of the scale.

Type:

str

mode

The type of scale.

Type:

str or list

generate()[source]

Generates the full range of the scale.

Returns:

A list of MIDI note numbers representing the full range of the scale.

Return type:

list

class djalgo.harmony.Voice(mode='major', tonic='C', degrees=[0, 2, 4])[source]

Bases: MusicTheoryConstants

A class to represent a musical voice.

generate(notes, durations=None, arpeggios=False)[source]

Generate chords or arpeggios based on the given notes.

Parameters:
  • notes (list or tuple) – The notes to generate chords or arpeggios from.

  • durations (list, optional) – The durations of each note. If not provided, defaults to [1].

  • arpeggios (bool, optional) – If True, generate arpeggios instead of chords. Defaults to False.

Returns:

The generated chords or arpeggios.

Return type:

list

pitch_to_chord(pitch)[source]

Convert a MIDI note to a chord based on the scale using the specified degrees.

Parameters

pitchint

The MIDI note to convert.

Returns

list

A list of MIDI notes representing the chord.

class djalgo.loop.Polyloop(polyloops, measure_length=4, insert_rests=True)[source]

Bases: object

Represents a collection of polyloops, which are sequences of musical notes.

plot_polyloops(pulse=0.25, colors=None)[source]

Plots the given polyloops as a radar chart, including arcs to represent the duration of each note.

Parameters: - pulse (float): The duration of each pulse in beats. Defaults to 1/4. - colors (list): A list of colors to use for the plot. If not provided, a default color scheme will be used.

Returns: - fig (plotly.graph_objects.Figure): The generated radar chart figure.

class djalgo.minimalism.Minimalism[source]

Bases: object

Main class for musical minimalism.

class Process(operation='additive', direction='forward', repetition=0)[source]

Bases: object

Class for the process of musical minimalism.

additive_backward()[source]

Applies the additive backward operation to the sequence with repetition, as:

[
    'C5',
    'B4', 'C5',
    'A4', 'B4', 'C5',
    'G4', 'A4', 'B4', 'C5',
    'F4', 'G4', 'A4', 'B4', 'C5',
    'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
    'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
]
Returns:

The processed sequence.

Return type:

list

additive_forward()[source]

Applies the additive forward operation to the sequence with repetition, as:

[
    'C4',
    'C4', 'D4',
    'C4', 'D4', 'E4',
    'C4', 'D4', 'E4', 'F4',
    'C4', 'D4', 'E4', 'F4', 'G4',
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4',
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4',
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5'
]
Returns:

The processed sequence.

Return type:

list

additive_inward()[source]

Applies the additive inward operation to the sequence, as:

[
    'C4',                                     'C5',
    'C4', 'D4',                         'B4', 'C5',
    'C4', 'D4', 'E4',             'A4', 'B4', 'C5',
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5'
]
Returns:

The processed sequence.

Return type:

list

additive_outward()[source]

Applies the additive outward operation to the sequence with repetition, as:

[
                    'F4', 'G4',
                'E4', 'F4', 'G4', 'A4',
        'D4', 'E4', 'F4', 'G4', 'A4', 'B4',
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5'
]
Returns:

The processed sequence.

Return type:

list

generate(sequence)[source]

Generates the processed sequence based on the operation and direction.

Parameters:

sequence (list) – The sequence to be processed.

Returns:

The processed sequence.

Return type:

list

subtractive_backward()[source]

Applies the subtractive backward operation to the sequence, as:

[
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4',
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4',
    'C4', 'D4', 'E4', 'F4', 'G4',
    'C4', 'D4', 'E4', 'F4',
    'C4', 'D4', 'E4',
    'C4', 'D4',
    'C4'
]
Returns:

The processed sequence.

Return type:

list

subtractive_forward()[source]

Applies the subtractive forward operation to the sequence, as:

[
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
    'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
    'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
    'F4', 'G4', 'A4', 'B4', 'C5',
    'G4', 'A4', 'B4', 'C5',
    'A4', 'B4', 'C5',
    'B4', 'C5',
    'C5'
]
Returns:

The processed sequence.

Return type:

list

subtractive_inward()[source]

Applies the subtractive inward operation to the sequence, as:

[
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
        'D4', 'E4', 'F4', 'G4', 'A4', 'B4',
                'E4', 'F4', 'G4', 'A4',
                    'F4', 'G4',
]
Returns:

The processed sequence.

Return type:

list

subtractive_outward()[source]

Applies the subtractive outward operation to the sequence, as:

[
    'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5',
    'C4', 'D4', 'E4',           , 'A4', 'B4', 'C5',
    'C4', 'D4',                         'B4', 'C5',
    'C4',                                     'C5',
]
Returns:

The processed sequence.

Return type:

list

class Tintinnabuli(t_chord, direction='down', rank=0)[source]

Bases: object

Class for the Tintinnabuli style of musical minimalism.

generate(sequence)[source]

Generates the t-voice based on the t-chord, direction, and rank.

Parameters:

sequence (list) – The m-voice sequence.

Returns:

The t-voice sequence.

Return type:

list

class djalgo.rhythm.GeneticRhythm(seed, population_size, measure_length, max_generations, mutation_rate, durations)[source]

Bases: object

create_random_rhythm()[source]

Creates a random rhythm ensuring it respects the measure length and has no overlapping notes.

Returns:

A list of (duration, offset) tuples representing the rhythm.

Return type:

list

crossover(parent1, parent2)[source]

Performs crossover between two parent rhythms to produce a new child rhythm.

Parameters:
  • parent1 (list) – The first parent rhythm.

  • parent2 (list) – The second parent rhythm.

Returns:

The new child rhythm generated from the parents.

Return type:

list

ensure_measure_length(rhythm)[source]

Ensures that the rhythm respects the measure length, adjusting if necessary.

Parameters:

rhythm (list) – The rhythm to check and adjust.

Returns:

The adjusted rhythm.

Return type:

list

evaluate_fitness(rhythm)[source]

Evaluates the fitness of a rhythm based on how close it is to the total measure length.

Parameters:

rhythm (list) – The rhythm to evaluate, represented as a list of (duration, offset) tuples.

Returns:

The fitness score of the rhythm.

Return type:

int

generate()[source]

Executes the genetic algorithm, evolving the rhythms over generations.

Returns:

The best rhythm found after the last generation, sorted by ascending offset.

Return type:

list

initialize_population()[source]

Initializes a population of random rhythms.

mutate(rhythm)[source]

Performs a mutation on a rhythm with a certain probability, ensuring no note overlap.

Parameters:

rhythm (list) – The rhythm to mutate.

Returns:

The mutated rhythm.

Return type:

list

select_parents()[source]

Selects two parents for reproduction using a simple random selection approach.

Returns:

Two selected parent rhythms for crossover.

Return type:

tuple

class djalgo.rhythm.Rhythm(measure_length, durations)[source]

Bases: object

A class used to represent a Rhythm.

measure_length

the length of the measure

Type:

int

durations

the durations of the notes

Type:

list

darwin(seed=None, population_size=10, max_generations=50, mutation_rate=0.1)[source]

Executes the Darwinian evolution algorithm to generate the best rhythm.

Parameters:
  • seed (int) – The random seed for reproducibility.

  • population_size (int) – The number of rhythms in each generation.

  • max_generations (int) – The maximum number of generations to evolve.

  • mutation_rate (float) – The probability of mutating a given rhythm.

Returns:

The best rhythm found after the last generation, sorted by ascending offset.

Return type:

list

random(seed=None, rest_probability=0, max_iter=100)[source]

Generate a random rhythm as a list of (duration, offset) tuples.

Parameters:
  • duration (list) – List of possible durations.

  • measure_length (float) – Total length of the measure.

  • rest_probability (float) – Probability of a rest (i.e., removing a tuple).

  • max_iter (int) – Maximum number of iterations to generate the rhythm.

Returns:

List of (duration, offset) tuples representing the rhythm.

Return type:

list

djalgo.rhythm.beatcycle(pitches, durations)[source]

Pitches are mapped to durations in a cyclical manner, then offsets are set according to successive durations.

Parameters:
  • pitches (list) – The first list.

  • durations (list) – The second list.

Returns:

A list of notes.

Return type:

list

djalgo.rhythm.isorhythm(pitches, durations)[source]

Merges durations and pitches until both ends coincide, then sets offsets according to successive durations.

Parameters:
  • pitches (list) – The first list.

  • durations (list) – The second list.

Returns:

A list of notes.

Return type:

list

djalgo.utils.adjust_note_durations_to_prevent_overlaps(notes)[source]

Adjust the durations of notes in a list (each note is a (pitch, duration, offset) tuple) to prevent overlaps, while keeping their offsets intact.

Parameters:

notes (list) – The list of notes to be adjusted.

Returns:

The modified list with adjusted note durations.

Return type:

list

djalgo.utils.cde_to_midi(pitch)[source]
djalgo.utils.check_input(input_list)[source]

Checks if the input is a list of simple elements or a list of tuples.

Parameters:

input_list (list) – The input to check.

Returns:

‘list’ if the input is a list of simple elements,

’list of tuples’ if the input is a list of tuples, ‘unknown’ otherwise.

Return type:

str

djalgo.utils.fibonacci(a=0, b=1, base=0, scale=1)[source]

Generate a Fibonacci iterator.

This function generates a Fibonacci iterator that yields the next Fibonacci number in the sequence.

Parameters:
  • a (int) – The first number in the Fibonacci sequence (default is 0).

  • b (int) – The second number in the Fibonacci sequence (default is 1).

  • base (int) – The base value to be added to each Fibonacci number (default is 0).

  • scale (int) – The scale factor to be multiplied with each Fibonacci number (default is 1).

Yields:

int – The next Fibonacci number in the sequence.

djalgo.utils.fill_gaps_with_rests(notes, parent_offset=0.0)[source]

Analyze a sorted list of notes (each note is a (pitch, duration, offset) tuple) and insert rests (None, duration, offset) to fill gaps between notes. Notes are sorted by offset before processing to ensure accurate gap detection and filling.

Parameters:
  • notes (list) – The list of notes to be processed, not necessarily sorted.

  • parent_offset (float) – The offset to consider from the parent sequence, used in recursion.

Returns:

The modified list with gaps filled with rests, ensuring continuity.

Return type:

list

djalgo.utils.find_closest_pitch_at_measure_start(notes, measure_length)[source]

Finds the closest pitch at the beginning of each measure.

Parameters:
  • notes (list of tuples) – A list of tuples where each tuple is (pitch, duration, offset).

  • measure_length (float) – The length of a measure.

Returns:

A list of pitches, each representing the closest pitch at the start of a measure.

Return type:

list

djalgo.utils.get_degree_from_pitch(pitch, scale_list, tonic_pitch)[source]
djalgo.utils.get_octave(midi_note)[source]
djalgo.utils.get_pitch_from_degree(degree, scale_list, tonic_pitch)[source]
djalgo.utils.get_sharp(string)[source]
djalgo.utils.midi_to_cde(midi)[source]
djalgo.utils.no_overlap(notes, adjust='offsets')[source]

Adjusts the offsets of the notes to prevent overlap.

Parameters:

notes (list) – A list of tuples, where each tuple contains a note (pitch), a duration (quarterLength), and an offset.

Returns:

The list of notes with adjusted offsets or durations.

Return type:

list

djalgo.utils.offset_track(track, by)[source]

Offset the notes in a list by a given amount.

Parameters:
  • track (list) – List of notes to offset.

  • by (float) – Amount to offset the notes.

Returns:

List of notes with adjusted offsets.

Return type:

list

djalgo.utils.ql_to_seconds(ql, bpm)[source]

Convert a duration in quarter-length units to seconds.

Parameters:
  • ql (float) – Duration in quarter-length units.

  • bpm (float) – Beats per minute.

Returns:

Duration in seconds.

Return type:

float

djalgo.utils.quantize_notes(notes, measure_length, time_resolution)[source]

Quantize the durations and offsets of notes in musical phrases.

Parameters:
  • notes (list) – List of musical phrases, where each phrase is a list of tuples (pitch, duration, offset).

  • measure_length (float) – The total duration of a measure, typically in quarter notes.

  • time_resolution (float) – The smallest time unit for quantization, typically in quarter notes.

Returns:

The quantized musical phrases.

Return type:

list

djalgo.utils.repair_notes(s: list) list[source]

Apply the fill_gaps_with_rests and adjust_note_durations_to_prevent_overlaps functions to a stream.

Parameters:

s (stream.Stream) – The music21 stream to be processed.

Returns:

The modified stream with gaps filled and note durations adjusted.

Return type:

stream.Stream

djalgo.utils.round_to_list(value, scale)[source]

Rounds the given value to the nearest value in the scale list.

Parameters:
  • value (float) – The value to be rounded.

  • scale (list) – A list of values to round to.

Returns:

The value from the scale list that is closest to the given value.

Return type:

float

djalgo.utils.scale_list(numbers, to_min, to_max, min_numbers=None, max_numbers=None)[source]

Scale a list of numbers so that its range is between min_value and max_value.

Parameters:
  • numbers (list) – List of numbers to scale.

  • min_value (float) – Minimum value of the scaled list.

  • max_value (float) – Maximum value of the scaled list.

Returns:

Scaled list of numbers.

Return type:

list

djalgo.utils.set_offsets_according_to_durations(notes)[source]

Adjusts the offsets of the notes based on their durations.

Parameters:

notes (list) – A list of tuples, where each tuple contains a note (pitch), a duration (quarterLength), and an offset.

Returns:

The list of notes with adjusted offsets.

Return type:

list

djalgo.utils.tune(pitch, scale)[source]

Adjust the pitch of a note to the nearest pitch within the given scale.

Parameters:
  • pitch (int) – a MIDI pitch number to tune.

  • scale (list) – A list of pitches

Returns:

A tuned MIDI pitch number.

Return type:

pitch

class djalgo.walk.CelestialBody(distance, orbital_speed, phase=0, moons=None)[source]

Bases: object

Represents a celestial body in space.

distance

The distance of the celestial body from its parent body.

Type:

float

orbital_speed

The orbital speed of the celestial body.

Type:

float

phase

The phase of the celestial body’s orbit (default is 0).

Type:

float, optional

moons

A list of CelestialBody objects representing the moons of the celestial body (default is None).

Type:

list, optional

position(times)[source]

Calculates the position of the celestial body at the given times.

Parameters:

times (array-like) – An array-like object containing the times at which to calculate the position.

Returns:

A tuple containing the x and y coordinates of the celestial body’s position at the given times.

Return type:

tuple

simulate(times, parent_position=None)[source]

Simulates the motion of the celestial body over the given times.

Parameters:
  • times (array-like) – An array-like object containing the times at which to simulate the motion.

  • parent_position (tuple, optional) – A tuple containing the x and y coordinates of the parent body’s position (default is None).

Returns:

A list of tuples representing the distances and angles of the celestial body at the given times.

Return type:

list

class djalgo.walk.Chain(walk_range=None, walk_start=None, walk_probability=None, round_to=None, branching_probability=0.0, merging_probability=0.0)[source]

Bases: object

A class representing a chain of sequences generated using random walks.

walk_range

The range of step choices for the random walk. Defaults to [-1, 0, 1].

Type:

list

walk_start

The starting position for the random walk. Defaults to the middle value of walk_range.

Type:

int

walk_probability

The probability distribution for choosing a step in the random walk. Can be a list of step choices or a random variable object. Defaults to [-1, 0, 1].

Type:

list or object

branching_probability

The probability of branching at each step. Defaults to 0.0.

Type:

float

merging_probability

The probability of merging sequences with the same last value. Defaults to 0.0.

Type:

float

generate(length, seed=None)[source]

Generates a chain of sequences using random walks.

Parameters:
  • length (int) – The length of each sequence in the chain. Defaults to 10.

  • seed (int) – The seed value for the random number generator. Defaults to None.

Returns:

A list of sequences generated using random walks.

Return type:

list

class djalgo.walk.Kernel(walk_around=0.0, length_scale=1.0, amplitude=1.0)[source]

Bases: object

A class representing a kernel for generating sequences.

walk_around

The mean value around which the sequence will walk.

Type:

float

data

The input data used for generating the sequence.

Type:

ndarray

length_scale

The length scale parameter of the kernel.

Type:

float

amplitude

The amplitude parameter of the kernel.

Type:

float

generate(length=10, data=None, nsamples=1, seed=None)[source]

Generates a sequence using the kernel.

Parameters:
  • length (int) – The length of the sequence.

  • data (ndarray) – The input data used for generating the sequence.

  • nsamples (int) – The number of samples to generate.

  • seed (int) – The seed value for random number generation.

Returns:

The generated sequence.

Return type:

list

rbf_kernel(dimension, length_scale)[source]

Computes the radial basis function (RBF) kernel matrix.

Parameters:
  • dimension (int) – The dimension of the kernel matrix.

  • length_scale (float) – The length scale parameter of the kernel.

Returns:

The RBF kernel matrix.

Return type:

ndarray

class djalgo.walk.SolarSystem[source]

Bases: object

Represents a solar system.

planets

A list of celestial bodies in the solar system.

Type:

list

add_planet(planet)[source]

Adds a new planet to the solar system.

Parameters:

planet (CelestialBody) – A CelestialBody object representing the planet to add.

simulate(times)[source]

Simulates the motion of all planets in the solar system.

Parameters:

times (list) – A list of time points at which to simulate the motion.

Returns:

A list of simulation results for all planets.

Return type:

list