Example #1
0
def test_createGraph():
    """Test createGraph module member."""

    scale = MajorScale('C')

    chord_generator = Generator(
        pitches = scale.getPitches('C','B'),
        select = lambda chord: chord.isTriad()
    )

    max_norm_vl = EfficientVoiceLeading(
        scale = scale,
        metric = lambda delta: la.norm(delta, inf)
    )

    graph, _ = createGraph(
        generator = chord_generator,
        voice_leading = max_norm_vl,
        tolerance = lambda x: x == 1.0,
        label = lambda chord: chordSymbolFigure(chord, inversion=0)
    )

    string = ''
    for node, neighbors in graph.adjacency():
        line = node + ': '
        for neighbor, edge in neighbors.items():
            line += ' {} ({}),'.format(
                neighbor, edge['distance']
            )
        string += line[:-1] + '\n'
    assert string[:-1] == graph_string
Example #2
0
def test_EfficientVoiceLeading():
    """Test EfficientVoiceLeading module class."""
    D_minor_scale = MinorScale('D')
    D_minor_scale = Chord(D_minor_scale.getPitches('D4', 'C5'))
    E_major_scale = MajorScale('E')
    E_major_scale = Chord(E_major_scale.getPitches('E4', 'D#5'))
    scale = ChromaticScale('C')
    voice_leading = EfficientVoiceLeading(
        scale=ChromaticScale('C'), metric=lambda delta: la.norm(delta, inf))
    vl, dist = voice_leading(
        D_minor_scale,
        E_major_scale,
    )
    assert vl == [1, 1, 0, 1, 1, 0, 1]
    assert dist == 1.0
Example #3
0
def test_scalePoint():
    """Test scalePoint module method."""
    scale = ChromaticScale('C')
    scalar_point = scalePoint(chord, scale)
    assert scalar_point == [0, 4, 7]
    scale = MajorScale('C')
    scalar_point = scalePoint(chord, scale)
    assert scalar_point == [0, 2, 4]
Example #4
0
def test_standardSimplex():
    """Test standardSimplex module method."""
    scale = ChromaticScale('C')
    standard_simplex = standardSimplex(chord, scale)
    assert standard_simplex == [11 / 12, 4 / 12, 3 / 12]
    standard_simplex = standardSimplex(chord, scale, False)
    assert standard_simplex == [11, 4, 3]
    scale = MajorScale('C')
    standard_simplex = standardSimplex(chord, scale)
    assert standard_simplex == [6 / 7, 2 / 7, 2 / 7]
    standard_simplex = standardSimplex(chord, scale, False)
    assert standard_simplex == [6, 2, 2]
def compose_repository_song(repo_data):
    vprint('Composing a song using the data from your Git Repository...')
    song = Stream()

    scale = MajorScale('%s4' % random.choice('ABCDEFG'))
    print('Using Scale: %s' % scale)
    clips, phrases = phrasify(repo_data, scale)

    for sha in repo_data:
        for clip in phrases[hash(sha)]:
            for note in clips[clip]:
                song.append(note)

    return song
Example #6
0
"""
Example of generator primitives.

This example generates the space of C chords identify by
their ordered pitch class string that are also triads.
"""

from orbichord.generator import Generator
from orbichord.symbol import chordSymbolFigure
from music21.scale import MajorScale

scale = MajorScale('C')

chord_generator = Generator(pitches=scale.getPitches('C', 'B'),
                            select=lambda chord: chord.isTriad())

for chord in chord_generator.run():
    print('{} {} - {}'.format(chord, chord.orderedPitchClassesString,
                              chordSymbolFigure(chord, inversion=0)))
Example #7
0
from music21.chord import Chord
from music21.scale import MajorScale
from numpy import inf
from numpy import linalg as la
from orbichord.chordinate import EfficientVoiceLeading

CMaj = Chord('C E G')
GMaj = Chord('G B D')

max_norm_vl = EfficientVoiceLeading(scale=MajorScale('C'),
                                    metric=lambda delta: la.norm(delta, inf))
taxicab_norm_vl = EfficientVoiceLeading(scale=MajorScale('C'),
                                        metric=lambda delta: la.norm(delta, 1))
euclidean_norm_vl = EfficientVoiceLeading(
    scale=MajorScale('C'), metric=lambda delta: la.norm(delta, 2))

vl, distance = max_norm_vl(CMaj, GMaj)
print('CMaj-GMaj maximum norm efficient voice leading:', vl)
print('CMaj-GMaj maximum norm distance:', distance)

vl, distance = taxicab_norm_vl(CMaj, GMaj)
print('CMaj-GMaj taxicab norm efficient voice leading:', vl)
print('CMaj-GMaj taxicab norm distance:', distance)

vl, distance = euclidean_norm_vl(CMaj, GMaj)
print('CMaj-GMaj euclidean norm efficient voice leading:', vl)
print('CMaj-GMaj euclidean norm distance:', distance)
from music21.chord import Chord
from music21.scale import MajorScale, ChromaticScale
from orbichord.chordinate import interscalarMatrix, Permutation

scale = MajorScale('C')

# Chords are good twins

chordA = Chord('C E G')
chordB = Chord('A C E')

# Interscalar assuming any permutation
matrix = interscalarMatrix(chordA, chordB, scale)
print(matrix)
# Interscalar assuming cyclic permutation
matrix = interscalarMatrix(chordA,
                           chordB,
                           scale,
                           permutation=Permutation.CYCLIC)
print(matrix)
# Interscalar assuming no permutation
matrix = interscalarMatrix(chordA, chordB, scale, permutation=Permutation.NONE)
print(matrix)

# First ans second chord is good and bad twin, respectively.

chordA = Chord('C E G')
chordB = Chord('A E C')

# Interscalar assuming any permutation
matrix = interscalarMatrix(chordA, chordB, scale)
"""
Example of generator primitives.

This example generates the space of C tetrachords identify by
their ordered pitch class string that contain a triad.
"""

from orbichord.generator import Generator
from orbichord.identify import chordSymbolIndex
from orbichord.symbol import chordSymbolFigure, hasChordSymbolFigure
from music21.scale import MajorScale

scale = MajorScale('C')

chord_generator = Generator(
    dimension = 4,
    pitches = scale.getPitches('C','B'),
    identify = chordSymbolIndex,
    select = lambda chord: \
        hasChordSymbolFigure(chord) and\
        chord.containsTriad()
)

for chord in chord_generator.run():
    print('{} {} - {}'.format(chord, chord.orderedPitchClassesString,
                              chordSymbolFigure(chord, inversion=0)))
Example #10
0
def main1():
    all_pitches = MajorScale(tonic="C").getPitches("C1", "C8")
    pitch2index = {p: ix for ix, p in enumerate(all_pitches)}
    C2 = Pitch("C2")
    C3 = Pitch("C3")
    C4 = Pitch("C4")
    C5 = Pitch("C5")
    C6 = Pitch("C6")

    def get_next_triplets(triplet: Triplet) -> Set[Triplet]:
        next_triplets = set()
        for i, pitch in enumerate(triplet.pitches):
            # TODO: improve construct_graph to accept negative values here
            for diff in [1]:
                # TODO: make this a utility function
                moved_pitch = all_pitches[pitch2index[pitch] + diff]
                if moved_pitch in triplet.pitches:
                    continue
                next_pitches = tuple(
                    p if i != j else moved_pitch for j, p in enumerate(triplet.pitches)
                )
                if (
                    not C2 <= next_pitches[0] <= C4
                    or not C3 <= next_pitches[1] <= C5
                    or not C4 <= next_pitches[2] <= C6
                ):
                    continue
                next_triplets.add(Triplet(next_pitches))
        return next_triplets

    init_pitches = (Pitch("C2"), Pitch("C3"), Pitch("C4"))
    init_triplet = Triplet(init_pitches)
    _, edges = construct_graph(init_triplet, get_next_triplets, 48)
    G = nx.DiGraph()
    G.add_edges_from(edges)
    plot_hierarchical_graph(G)  # blocking

    progression = []
    chord = init_triplet
    while chord:
        progression.append(chord)
        successors = list(G.successors(chord))
        if successors:
            chord = successors[len(successors) // 2]
        else:
            chord = None
    print(progression)

    sounds, _ = midi.initialize()

    _ = query_sound(sounds, Section.STRINGS, Instrument.BASSES, Articulation.SPICCATO)
    celli = query_sound(
        sounds, Section.STRINGS, Instrument.CELLI, Articulation.SPICCATO
    )
    violas = query_sound(
        sounds, Section.STRINGS, Instrument.VIOLAS, Articulation.SPICCATO
    )
    violins = query_sound(
        sounds, Section.STRINGS, Instrument.VIOLINS_1, Articulation.SPICCATO
    )

    _ = query_sound(sounds, Section.BRASS, Instrument.TUBA, Articulation.STACCATISSIMO)
    trombones = query_sound(
        sounds, Section.BRASS, Instrument.TENOR_TROMBONES_A3, Articulation.STACCATISSIMO
    )
    trumpets = query_sound(
        sounds, Section.BRASS, Instrument.TRUMPETS_A3, Articulation.STACCATISSIMO
    )
    horns = query_sound(
        sounds, Section.BRASS, Instrument.HORNS_A4, Articulation.STACCATISSIMO
    )

    strings = (celli, violas, violins)
    brass = (trombones, trumpets, horns)
    dt = 0.175
    dur = 0.125

    p = Player()
    for measure, triplet in enumerate(progression):
        for beat in range(4):
            for note, snd in zip(triplet.pitches, strings):
                p.schedule(snd, Pitch(note).midi, (beat + measure * 4) * dt, dur, 100)
        for note, snd in zip(triplet.pitches, brass):
            p.schedule(snd, Pitch(note).midi, measure * 4 * dt, dur * 2, 100)
            p.schedule(snd, Pitch(note).midi, (measure * 4 + 3.25) * dt, dur * 0.5, 100)
    p.play()
Example #11
0
from music21.scale import MajorScale

__all__ = ["calculate_mode_degrees"]

major_c_scale = MajorScale(tonic="C")


class ModeDegree:
    def __init__(self, *, value, alter=0):
        assert value in [1, 2, 3, 4, 5, 6, 7]
        assert alter in [0, -1.0]

        self.value = value
        self.alter = alter
        self.prefix = "flat-" if self.alter == -1.0 else ""
        self.descr = f"{self.prefix}{self.value}"

    @classmethod
    def from_note_pair(self, *, note, base_note):
        diatonic_distance = (note.pitch.diatonicNoteNum - base_note.pitch.diatonicNoteNum) % 7 + 1
        alter = note.pitch.alter

        if alter not in [0, -1.0]:  # pragma: no cover
            raise NotImplementedError(f"Unexpected alteration of note: '{note.nameWithOctave}'")

        return ModeDegree(value=diatonic_distance, alter=alter)

    def __repr__(self):
        return f"<ModeDegree: {self.descr}>"

    def __str__(self):
Example #12
0
def test_interscalarMatrix():
    """Test interscalarMatrix module method."""
    scale = MajorScale('C')
    ref_chord = Chord('F B D')
    delta = interscalarMatrix(chord, ref_chord, scale)
    assert delta == [[1, 1, 2], [3, -3, -3], [-1, -1, -1]]