Example #1
0
def generateScore(chords, lengths=None, ts="4/4"):
    """Generates a four-part score from a sequence of chords.

    Soprano and alto parts are displayed on the top (treble) clef, while tenor
    and bass parts are displayed on the bottom (bass) clef, with correct stem
    directions.
    """
    if lengths is None:
        lengths = [1 for _ in chords]
    voices = [Voice([Piano()]) for _ in range(4)]
    for chord, length in zip(chords, lengths):
        bass, tenor, alto, soprano = [
            Note(p, quarterLength=length) for p in chord.pitches
        ]
        bass.addLyric(chord.lyric)
        bass.stemDirection = alto.stemDirection = "down"
        tenor.stemDirection = soprano.stemDirection = "up"
        voices[0].append(soprano)
        voices[1].append(alto)
        voices[2].append(tenor)
        voices[3].append(bass)

    female = Part([TrebleClef(), TimeSignature(ts), voices[0], voices[1]])
    male = Part([BassClef(), TimeSignature(ts), voices[2], voices[3]])
    score = Score([female, male])
    return score
Example #2
0
    def testBeatProportionFromTimeSignature(self):
        # given meter, ql, beat proportion, and beat ql
        data = [
            ['2/4', (0, 0.5, 1, 1.5), (1, 1.5, 2, 2.5), (1, 1, 1, 1)],
            ['3/4', (0, 0.5, 1, 1.5), (1, 1.5, 2, 2.5), (1, 1, 1, 1)],
            ['4/4', (0, 0.5, 1, 1.5), (1, 1.5, 2, 2.5), (1, 1, 1, 1)],
            [
                '6/8', (0, 0.5, 1, 1.5, 2), (1, 4 / 3, 5 / 3, 2.0, 7 / 3),
                (1.5, 1.5, 1.5, 1.5, 1.5)
            ],
            [
                '9/8', (0, 0.5, 1, 1.5, 2), (1, 4 / 3, 5 / 3, 2.0, 7 / 3),
                (1.5, 1.5, 1.5, 1.5, 1.5)
            ],
            [
                '12/8', (0, 0.5, 1, 1.5, 2), (1, 4 / 3, 5 / 3, 2.0, 7 / 3),
                (1.5, 1.5, 1.5, 1.5, 1.5)
            ],
            [
                '2/8+3/8', (0, 0.5, 1, 1.5), (1, 1.5, 2, 7 / 3),
                (1, 1, 1.5, 1.5, 1.5)
            ],
        ]

        for tsStr, src, dst, beatDur in data:
            ts = TimeSignature(tsStr)
            for i in range(len(src)):
                ql = src[i]
                self.assertAlmostEqual(ts.getBeatProportion(ql), dst[i], 4)
                self.assertEqual(
                    ts.getBeatDuration(ql).quarterLength, beatDur[i])
Example #3
0
    def testMixedDurationsBeams(self):
        fourFour = TimeSignature('4/4')
        n = note.Note
        dList = [
            n(type='eighth'),
            n(type='quarter'),
            n(type='eighth'),
            n(type='eighth'),
            n(type='quarter'),
            n(type='eighth')
        ]
        beamList = fourFour.getBeams(dList)
        self.assertEqual(beamList, [None] * 6)

        dList = [
            n(type='eighth'),
            n(type='quarter'),
            n(type='eighth'),
            n(type='eighth'),
            n(type='eighth'),
            n(type='quarter')
        ]
        beamList = fourFour.getBeams(dList)
        self.assertEqual([repr(b) for b in beamList], [
            'None', 'None', 'None',
            '<music21.beam.Beams <music21.beam.Beam 1/start>>',
            '<music21.beam.Beams <music21.beam.Beam 1/stop>>', 'None'
        ])
Example #4
0
def reframe_ts(ts, new_denominator=None):
    """
	Function for reducing a `music21.meter.TimeSignature` object (lowest denominator of 1) to
	a given denominiator.

	:param ts: a music21.meter.TimeSignature object.
	:return: a new time signature that is fully reduced by removing all possible powers of 2.
	:rtype: music21.meter.TimeSignature

	>>> from music21.meter import TimeSignature
	>>> reframe_ts(TimeSignature("4/16"))
	<music21.meter.TimeSignature 1/4>
	>>> reframe_ts(TimeSignature("4/4"), new_denominator=2)
	<music21.meter.TimeSignature 2/2>
	"""
    numerator = ts.numerator
    denominator = ts.denominator
    if new_denominator is None:
        new_denominator = VALID_DENOMINATORS[0]
    else:
        assert new_denominator in set(VALID_DENOMINATORS)

    if new_denominator <= ts.numerator:
        while numerator % 2 == 0 and denominator > new_denominator:
            numerator = numerator / 2
            denominator = denominator / 2
    else:
        while denominator < new_denominator:
            numerator = numerator * 2
            denominator = denominator * 2

    reduced_ts_str = f"{int(numerator)}/{int(denominator)}"
    return TimeSignature(reduced_ts_str)
Example #5
0
def decode_score(encoding, num_measures, ts, image=False):
    score = Stream()
    score.timeSignature = TimeSignature(ts)
    steps_per_measure = len(encoding) / num_measures
    measure_ind = 0
    while measure_ind < num_measures:
        start_beat = int(measure_ind * steps_per_measure)
        end_beat = int((measure_ind + 1) * steps_per_measure)
        measure = Measure()
        for beat_ind in range(start_beat, end_beat):
            if image:
                played_pitches = np.nonzero(encoding[beat_ind])[0]
            else:
                played_pitches = np.nonzero(encoding[beat_ind])
            if len(played_pitches) == 0:
                measure.append(Rest(quarterLength=4.0 / GRANULARITY))
            else:
                played_notes = [
                    midi_to_note(int(pitch + MIN_PITCH))
                    for pitch in played_pitches
                ]
                chord = Chord(played_notes, quarterLength=4.0 / GRANULARITY)
                measure.append(chord)
        score.append(measure)
        measure_ind += 1
    return score
Example #6
0
def valid_score(score_name, time_signatures=set(), pickups=False, parts=set(), note_range=[], num_measures=0, \
 key_signatures=set(), granularity=0, consistent_measures=False, consistent_time=False, consistent_key=False, \
 consistent_parts=False, percent_indivisible=0.0, has_key_signature=False, num_steps=0):

    score_stats = score_to_stats[score_name]

    discarded = False

    if parts and score_stats['num_parts'] not in parts:
        discarded = True
        pruning_stats['discarded_num_parts'].add(score_name)
    if time_signatures and not score_stats['time_signatures'].issubset(
            time_signatures):
        discarded = True
        pruning_stats['discarded_time_signature'].add(score_name)
    if key_signatures and not score_stats['key_signatures'].issubset(
            key_signatures):
        discarded = True
        pruning_stats['discarded_key_signature'].add(score_name)
    if pickups and score_stats['has_pickup']:
        discarded = True
        pruning_stats['discarded_has_pickup'].add(score_name)
    if num_measures and score_stats['num_measures'] < num_measures:
        discarded = True
        pruning_stats['discarded_num_measures'].add(score_name)
    if note_range and note_range[0] and note_range[1] and (
            score_stats['min_note'] < note_range[0]
            or score_stats['max_note'] > note_range[1]):
        discarded = True
        pruning_stats['discarded_note_range'].add(score_name)
    if consistent_measures and not score_stats['consistent_measures']:
        discarded = True
        pruning_stats['discarded_consistent_measures'].add(score_name)
    if granularity and score_stats['granularity'] > granularity:
        discarded = True
        pruning_stats['discarded_granularity'].add(score_name)
    if percent_indivisible and score_stats['1%+_divisible']:
        discarded = True
        pruning_stats['discarded_%_divisible'].add(score_name)
    if consistent_time and not score_stats['consistent_time']:
        discarded = True
        pruning_stats['discarded_consistent_time'].add(score_name)
    if consistent_key and not score_stats['consistent_key']:
        discarded = True
        pruning_stats['discarded_consistent_key'].add(score_name)
    if consistent_parts and not score_stats['consistent_parts']:
        discarded = True
        pruning_stats['discarded_consistent_parts'].add(score_name)
    if num_steps:
        if len(score_stats['time_signatures']) == 1:
            ts = TimeSignature(list(score_stats['time_signatures'])[0])
            if num_steps != score_stats['num_measures'] * (
                    GRANULARITY * ts.beatCount *
                    ts.beatDuration.quarterLength / 4.0):
                discarded = True
                pruning_stats['discarded_num_steps'].add(score_name)
        else:
            discarded = True
            pruning_stats['discarded_num_steps'].add(score_name)
    return discarded
def createEasyScale():
    myScale = "d8 e f g a b"
    time1 = TimeSignature("3/4")
    s1 = TinyNotationStream(myScale, time1)
#    s1.timeSignature = time1
#    s1.showTimeSignature = True
    s1.show('lily.png')
Example #8
0
def get_time(file):
    with open(file["path"], "r") as f:
        for line in f:
            m = time_signature_pattern.match(line)
            if m:
                return TimeSignature("{}/{}".format(
                    m.group(4), int(1 / 2**-int(m.group(5)))))
Example #9
0
    def testMeterDeepcopy(self):
        a = MeterSequence()
        a.load('4/4', 4)
        b = copy.deepcopy(a)
        self.assertNotEqual(a, b)

        c = TimeSignature('4/4')
        d = copy.deepcopy(c)
        self.assertNotEqual(c, d)
Example #10
0
    def testGetBeams(self):
        ts = TimeSignature('6/8')
        durList = [16, 16, 16, 16, 8, 16, 16, 16, 16, 8]

        notesList = [note.Note(quarterLength=4 / d) for d in durList]
        beams = ts.getBeams(notesList)
        match = '''[<music21.beam.Beams <music21.beam.Beam 1/start>/<music21.beam.Beam 2/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/stop>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>,
        <music21.beam.Beams <music21.beam.Beam 1/start>/<music21.beam.Beam 2/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/stop>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>]'''

        self.assertTrue(common.whitespaceEqual(str(beams), match))
Example #11
0
def make_music21_score(
    part_names=('violin', 'flute', 'oboe', 'clarinet', 'alto_saxophone',
                'trumpet', 'bass', 'percussion'),
    title='Title',
    composer='Jonathan Marmor',
    time_signature=None,
    starting_tempo_bpm=60,
    starting_tempo_quarter_duration=1.0,
    timestamp=None,
):
    if not timestamp:
        timestamp = datetime.datetime.utcnow()
    metadata = Metadata()
    metadata.title = title
    metadata.composer = composer
    metadata.date = timestamp.strftime('%Y/%m/%d')

    score = Score()
    score.insert(0, metadata)

    for part_name in part_names:

        instrument_name, instrument_number = parse_part_name(part_name)

        instrument = instrument_data[instrument_name]

        part = Part()

        metronome_mark = MetronomeMark(
            number=starting_tempo_bpm,
            referent=Duration(starting_tempo_quarter_duration))
        part.append(metronome_mark)

        if time_signature:
            # Should be a string like '12/8'
            music21_time_signature = TimeSignature(time_signature)
            part.append(music21_time_signature)

        m21_instrument = instrument['class']()
        m21_instrument.partName = instrument['name']
        m21_instrument.partAbbreviation = instrument['abbreviation']

        if instrument_number > 1:
            m21_instrument.partName = '{} {}'.format(instrument['name'],
                                                     instrument_number)
            m21_instrument.partAbbreviation = '{} {}'.format(
                instrument['abbreviation'], instrument_number)

        part.insert(0, m21_instrument)

        clef = instrument.get('clef')
        if clef:
            part.append(clef())

        score.insert(0, part)

    return score
Example #12
0
 def testMeterBeam(self):
     ts = TimeSignature('6/8', 2)
     b = [duration.Duration('16th')] * 12
     s = stream.Stream()
     s.insert(0, ts)
     for x in b:
         n = note.Note()
         n.duration = x
         s.append(n)
     s.show()
Example #13
0
 def testBasic(self):
     a = stream.Stream()
     for meterStrDenominator in [1, 2, 4, 8, 16, 32]:
         for meterStrNumerator in [2, 3, 4, 5, 6, 7, 9, 11, 12, 13]:
             ts = TimeSignature(
                 f'{meterStrNumerator}/{meterStrDenominator}')
             m = stream.Measure()
             m.timeSignature = ts
             a.insert(m.timeSignature.barDuration.quarterLength, m)
     a.show()
Example #14
0
    def testMusicxmlDirectOut(self):
        # test rendering musicxml directly from meter
        from music21.musicxml import m21ToXml

        ts = TimeSignature('3/8')
        xmlOut = m21ToXml.GeneralObjectExporter().parse(ts).decode('utf-8')

        match = '<time><beats>3</beats><beat-type>8</beat-type></time>'
        xmlOut = xmlOut.replace(' ', '')
        xmlOut = xmlOut.replace('\n', '')
        self.assertNotEqual(xmlOut.find(match), -1)
def test_18():
    """
    NB: This test is designed specifically to ensure that the _event_finder()
    doesn't stop processing when it doesn't find an element of the expected types
    at an offset. You should ask it to look for Rest objects only.
    """
    top, bot = _setup_parts()
    top.append(Note('G4', quarterLength=0.5))
    top.append(Rest(quarterLength=0.5))
    bot.append(TimeSignature('4/4'))
    bot.append(Note('G3', quarterLength=0.5))
    bot.append(Rest(quarterLength=0.5))
    return Score([top, bot])
Example #16
0
    def testCompound(self):
        a = stream.Stream()
        meterStrDenominator = [1, 2, 4, 8, 16, 32]
        meterStrNumerator = [2, 3, 4, 5, 6, 7, 9, 11, 12, 13]

        for i in range(30):
            msg = []
            for j in range(1, random.choice([2, 4])):
                msg.append('%s/%s' % (random.choice(meterStrNumerator),
                                      random.choice(meterStrDenominator)))
            ts = TimeSignature('+'.join(msg))
            m = stream.Measure()
            m.timeSignature = ts
            a.insert(m.timeSignature.barDuration.quarterLength, m)
        a.show()
Example #17
0
    def testDefaultBeatPartitions(self):
        src = ['2/2', '2/4', '2/8', '6/4', '6/8', '6/16']
        for tsStr in src:
            ts = TimeSignature(tsStr)
            self.assertEqual(len(ts.beatSequence), 2)
            self.assertEqual(ts.beatCountName, 'Duple')
            if ts.numerator == 2:
                for ms in ts.beatSequence:  # should be divided in two
                    self.assertEqual(len(ms), 2)
            elif ts.numerator == 6:
                for ms in ts.beatSequence:  # should be divided in three
                    self.assertEqual(len(ms), 3)

        src = ['3/2', '3/4', '3/8', '9/4', '9/8', '9/16']
        for tsStr in src:
            ts = TimeSignature(tsStr)
            self.assertEqual(len(ts.beatSequence), 3)
            self.assertEqual(ts.beatCountName, 'Triple')
            if ts.numerator == 3:
                for ms in ts.beatSequence:  # should be divided in two
                    self.assertEqual(len(ms), 2)
            elif ts.numerator == 9:
                for ms in ts.beatSequence:  # should be divided in three
                    self.assertEqual(len(ms), 3)

        src = ['4/2', '4/4', '4/8', '12/4', '12/8', '12/16']
        for tsStr in src:
            ts = TimeSignature(tsStr)
            self.assertEqual(len(ts.beatSequence), 4)
            self.assertEqual(ts.beatCountName, 'Quadruple')
            if ts.numerator == 4:
                for ms in ts.beatSequence:  # should be divided in two
                    self.assertEqual(len(ms), 2)
            elif ts.numerator == 12:
                for ms in ts.beatSequence:  # should be divided in three
                    self.assertEqual(len(ms), 3)

        src = ['5/2', '5/4', '5/8', '15/4', '15/8', '15/16']
        for tsStr in src:
            ts = TimeSignature(tsStr)
            self.assertEqual(len(ts.beatSequence), 5)
            self.assertEqual(ts.beatCountName, 'Quintuple')
            if ts.numerator == 5:
                for ms in ts.beatSequence:  # should be divided in two
                    self.assertEqual(len(ms), 2)
            elif ts.numerator == 15:
                for ms in ts.beatSequence:  # should be divided in three
                    self.assertEqual(len(ms), 3)

        src = ['18/4', '18/8', '18/16']
        for tsStr in src:
            ts = TimeSignature(tsStr)
            self.assertEqual(len(ts.beatSequence), 6)
            self.assertEqual(ts.beatCountName, 'Sextuple')
            if ts.numerator == 18:
                for ms in ts.beatSequence:  # should be divided in three
                    self.assertEqual(len(ms), 3)

        # odd or unusual partitions
        src = ['13/4', '19/8', '17/16']
        for tsStr in src:
            firstPart, unused = tsStr.split('/')
            ts = TimeSignature(tsStr)
            # self.assertEqual(len(ts.beatSequence), 6)
            self.assertEqual(ts.beatCountName,
                             firstPart + '-uple')  # "13-uple" etc.
Example #18
0
def tensors_to_stream(outputs, config, metadata=None):
    cur_measure_number = 0
    parts = {}
    for part_name in outputs.keys():
        if part_name == 'extra':
            continue
        part = Part(id=part_name)
        parts[part_name] = part

    last_time_signature = None
    cur_time_signature = '4/4'
    for step in range(outputs['soprano'].shape[0]):
        extra = outputs['extra'][step]
        if extra[indices_extra['has_time_signature_3/4']].item() == 1:
            cur_time_signature = '3/4'
        elif extra[indices_extra['has_time_signature_4/4']].item() == 1:
            cur_time_signature = '4/4'
        elif extra[indices_extra['has_time_signature_3/2']].item() == 1:
            cur_time_signature = '3/2'
        cur_time_pos = extra[indices_extra['time_pos']].item()
        has_fermata = extra[indices_extra['has_fermata']].item() == 1

        if cur_time_pos == 1.0 or cur_measure_number == 0:
            for part_name, part in parts.items():
                part.append(Measure(number=cur_measure_number))
                if cur_measure_number == 0:
                    if part_name in ['soprano', 'alto']:
                        part[-1].append(clef.TrebleClef())
                    else:
                        part[-1].append(clef.BassClef())
                    key = int(
                        torch.argmax(
                            outputs['extra'][0, indices_extra['has_sharps_0']:
                                             indices_extra['has_sharps_11'] +
                                             1],
                            dim=0).item())
                    if key >= 6:
                        key -= 12
                    part[-1].append(KeySignature(key))
                    part[-1].append(MetronomeMark(number=90))
            cur_measure_number += 1

        if last_time_signature is None or cur_time_signature != last_time_signature:
            for part in parts.values():
                part[-1].append(TimeSignature(cur_time_signature))
            last_time_signature = cur_time_signature

        for part_name, part in parts.items():
            idx = torch.argmax(outputs[part_name][step]).item()
            if idx == indices_parts['is_continued']:
                try:
                    last_element = part[-1].flat.notesAndRests[-1]
                    cur_element = deepcopy(last_element)
                    if last_element.tie is not None and last_element.tie.type == 'stop':
                        last_element.tie = Tie('continue')
                    else:
                        last_element.tie = Tie('start')
                    cur_element.tie = Tie('stop')
                except IndexError:
                    logging.debug(
                        'Warning: "is_continued" on first beat. Replaced by rest.'
                    )
                    cur_element = Rest(quarterLength=config.time_grid)
                part[-1].append(cur_element)
            elif idx == indices_parts['is_rest']:
                part[-1].append(Rest(quarterLength=config.time_grid))
            else:
                pitch = Pitch()
                part[-1].append(Note(pitch, quarterLength=config.time_grid))
                # Set pitch value AFTER appending to measure in order to avoid unnecessary accidentals
                pitch.midi = idx + min_pitches[part_name] - len(indices_parts)

        if has_fermata:
            for part in parts.values():
                fermata = Fermata()
                fermata.type = 'upright'
                part[-1][-1].expressions.append(fermata)

    score = Score()
    if metadata is not None:
        score.append(Metadata())
        score.metadata.title = f"{metadata.title} ({metadata.number})"
        score.metadata.composer = f"Melody: {metadata.composer}\nArrangement: BachNet ({datetime.now().year})"
    for part in parts.values():
        part[-1].rightBarline = 'light-heavy'

    score.append(parts['soprano'])
    if 'alto' in parts:
        score.append(parts['alto'])
        score.append(parts['tenor'])
    score.append(parts['bass'])

    score.stripTies(inPlace=True, retainContainers=True)

    return score
Example #19
0
 def testCompoundSameDenominator(self):
     ts328 = TimeSignature('3+2/8')
     beatSeq = ts328.beamSequence
     self.assertEqual(str(beatSeq), '{3/8+2/8}')
Example #20
0
    def testSetDefaultAccentWeights(self):
        # these tests take the level to 3. in some cases, a level of 2
        # is not sufficient to normalize all denominators
        pairs = [
            ('4/4', [1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125]),
            ('3/4', [
                1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.5, 0.125,
                0.25, 0.125
            ]),
            ('2/4', [1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125]),

            # divided at 4th 8th
            ('6/8', [
                1.0, 0.125, 0.25, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125,
                0.25, 0.125
            ]),

            # all beats are even b/c this is un-partitioned
            ('5/4', [
                1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.5, 0.125,
                0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125
            ]),
            ('9/4', [
                1.0, 0.125, 0.25, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125,
                0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.25, 0.125
            ]),
            ('18/4', [
                1.0, 0.125, 0.25, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125,
                0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.25, 0.125, 0.5, 0.125,
                0.25, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.25, 0.125,
                0.5, 0.125, 0.25, 0.125, 0.25, 0.125
            ]),
            ('11/8', [
                1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.5, 0.125,
                0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125,
                0.5, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.5, 0.125,
                0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125,
                0.5, 0.125, 0.25, 0.125
            ]),
            ('2/8+3/8',
             [1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.25, 0.125]),
            ('3/8+2/8+3/4', [
                1.0, 0.0625, 0.125, 0.0625, 0.25, 0.0625, 0.125, 0.0625, 0.25,
                0.0625, 0.125, 0.0625, 0.5, 0.0625, 0.125, 0.0625, 0.25,
                0.0625, 0.125, 0.0625, 0.5, 0.03125, 0.0625, 0.03125, 0.125,
                0.03125, 0.0625, 0.03125, 0.25, 0.03125, 0.0625, 0.03125,
                0.125, 0.03125, 0.0625, 0.03125, 0.25, 0.03125, 0.0625,
                0.03125, 0.125, 0.03125, 0.0625, 0.03125
            ]),
            ('1/2+2/16', [
                1.0, 0.015625, 0.03125, 0.015625, 0.0625, 0.015625, 0.03125,
                0.015625, 0.125, 0.015625, 0.03125, 0.015625, 0.0625, 0.015625,
                0.03125, 0.015625, 0.25, 0.015625, 0.03125, 0.015625, 0.0625,
                0.015625, 0.03125, 0.015625, 0.125, 0.015625, 0.03125,
                0.015625, 0.0625, 0.015625, 0.03125, 0.015625, 0.5, 0.0625,
                0.125, 0.0625, 0.25, 0.0625, 0.125, 0.0625
            ]),
        ]

        for tsStr, match in pairs:
            # environLocal.printDebug([tsStr])
            ts1 = TimeSignature(tsStr)
            ts1._setDefaultAccentWeights(3)  # going to a lower level here
            self.assertEqual([mt.weight for mt in ts1.accentSequence], match)
def _setup_parts():
    top = Part()
    top.append(TimeSignature('4/4'))
    bottom = Part()
    bottom.append(TimeSignature('4/4'))
    return top, bottom
Example #22
0
    def __init__(self, ranges=False):
        score = self.score = Score()
        self.instruments = self.i = Instruments()
        self.parts = Parts(self.i)

        # Make Metadata
        timestamp = datetime.datetime.utcnow()
        metadata = Metadata()
        metadata.title = 'Early Montreal'
        metadata.composer = 'Jonathan Marmor'
        metadata.date = timestamp.strftime('%Y/%m/%d')
        score.insert(0, metadata)

        [score.insert(0, part) for part in self.parts.l]
        score.insert(0, StaffGroup(self.parts.l))

        if ranges:
            # Don't make a piece, just show the instrument ranges
            for inst, part in zip(self.instruments.l, self.parts.l):
                measure = Measure()
                measure.timeSignature = TimeSignature('4/4')
                low = Note(inst.lowest_note)
                measure.append(low)
                high = Note(inst.highest_note)
                measure.append(high)
                part.append(measure)
            return

        # 18 to 21 minutes
        piece_duration_minutes = scale(random.random(), 0, 1, 18, 21)

        # Make the "songs"
        songs = []
        total_minutes = 0
        n = 1
        while total_minutes < piece_duration_minutes:
            print 'Song {}'.format(n)
            n += 1
            song = Song(self)
            songs.append(song)
            total_minutes += song.duration_minutes

        # Make notation
        previous_duration = None
        for song in songs:
            for bar in song.bars:
                for part in bar.parts:
                    measure = Measure()
                    if bar.tempo:
                        measure.insert(
                            0,
                            MetronomeMark(number=bar.tempo,
                                          referent=Duration(1)))
                        measure.leftBarline = 'double'
                    if bar.duration != previous_duration:
                        ts = TimeSignature('{}/4'.format(bar.duration))
                        measure.timeSignature = ts

                    # Fix Durations
                    durations = [note['duration'] for note in part['notes']]

                    components_list = split_at_beats(durations)
                    components_list = [
                        join_quarters(note_components)
                        for note_components in components_list
                    ]
                    for note, components in zip(part['notes'],
                                                components_list):
                        note['durations'] = components

                    for note in part['notes']:
                        if note['pitch'] == 'rest':
                            n = Rest()
                        if isinstance(note['pitch'], list):
                            pitches = []
                            for pitch_number in note['pitch']:
                                p = Pitch(pitch_number)
                                # Force all flats
                                if p.accidental.name == 'sharp':
                                    p = p.getEnharmonic()
                                pitches.append(p)
                            n = Chord(notes=pitches)

                            # TODO add slurs
                            # TODO add glissandos
                            # TODO add -50 cent marks

                        else:
                            p = Pitch(note['pitch'])
                            # Force all flats
                            if p.accidental.name == 'sharp':
                                p = p.getEnharmonic()
                            n = Note(p)

                            # TODO add slurs
                            # TODO add glissandos
                            # TODO add -50 cent marks

                        d = Duration()
                        if note['duration'] == 0:
                            d.quarterLength = .5
                            d = d.getGraceDuration()
                        else:
                            d.fill(note['durations'])
                        n.duration = d

                        measure.append(n)

                    self.parts.d[part['instrument_name']].append(measure)
                previous_duration = bar.duration
def badMeter():
    myScale = "a2 a2"
    time1 = TimeSignature("3/4")
    s1 = TinyNotationStream(myScale, time1)
    s1.show('lily.png')
    s1.show('midi')
Example #24
0
    def test_getBeams_offset(self):
        '''
        Test getting Beams from a Measure that has an anacrusis that makes the
        first note not beamed.
        '''
        m = stream.Measure()
        m.repeatAppend(note.Note(type='eighth'), 5)
        ts = TimeSignature('2/2')

        beams = ts.getBeams(m, measureStartOffset=1.5)
        self.assertIsNone(beams[0])
        for b in beams[1:]:
            self.assertIsNotNone(b)
        match = '''[None,
        <music21.beam.Beams <music21.beam.Beam 1/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>]'''
        self.assertTrue(common.whitespaceEqual(str(beams), match))

        m.append(note.Note(type='eighth'))
        beams = ts.getBeams(m, measureStartOffset=1.0)
        match = '''[<music21.beam.Beams <music21.beam.Beam 1/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>,
        <music21.beam.Beams <music21.beam.Beam 1/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>]'''
        self.assertTrue(common.whitespaceEqual(str(beams), match), str(beams))

        m = stream.Measure()
        m.repeatAppend(note.Note(type='eighth'), 5)
        ts = TimeSignature('3/2')

        beams = ts.getBeams(m, measureStartOffset=3.5)
        match = '''[None,
        <music21.beam.Beams <music21.beam.Beam 1/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>]'''
        self.assertTrue(common.whitespaceEqual(str(beams), match))

        m = stream.Measure()
        m.repeatAppend(note.Note(type='eighth'), 4)
        ts = TimeSignature('6/8')
        beams = ts.getBeams(m, measureStartOffset=1.0)
        match = '''[None,
        <music21.beam.Beams <music21.beam.Beam 1/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>]'''
        self.assertTrue(common.whitespaceEqual(str(beams), match))

        m.append(note.Note(type='eighth'))
        beams = ts.getBeams(m, measureStartOffset=0.5)
        match = '''[<music21.beam.Beams <music21.beam.Beam 1/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>,
        <music21.beam.Beams <music21.beam.Beam 1/start>>,
        <music21.beam.Beams <music21.beam.Beam 1/continue>>,
        <music21.beam.Beams <music21.beam.Beam 1/stop>>]'''
        self.assertTrue(common.whitespaceEqual(str(beams), match), str(beams))
Example #25
0
 def testSingle(self):
     '''Need to test direct meter creation w/o stream
     '''
     a = TimeSignature('3/16')
     a.show()
Example #26
0
    def __init__(self, number, piece, movement):
        self.number = number
        self.piece = piece
        self.movement = movement

        instrument_opts = piece.instruments.names[:]

        self.note_opts = {}
        for name in instrument_opts:
            self.note_opts[name] = piece.i.d[name].all_notes

        form = self.form = song_forms.choose()

        self.duration = len(form) * 4

        self.type = 'solo'
        if number % 2:
            self.type = 'ensemble'

        if self.type == 'solo':
            if len(movement.solo_ensemble_options) == 0:
                movement.solo_ensemble_options = piece.i.get_unison_ensembles(min_notes=6)
                print 'Hey, we ran out of unison ensembles! Cool!'
            solo_ensemble_hash = random.choice(movement.solo_ensemble_options.keys())
            self.soloists = movement.solo_ensemble_options[solo_ensemble_hash]['instruments']
            self.soloist_names = [s.nickname for s in self.soloists]
            self.soloists_shared_notes = movement.solo_ensemble_options[solo_ensemble_hash]['notes']
            # Remove chosen ensemble from options
            del movement.solo_ensemble_options[solo_ensemble_hash]

            # remove chosen soloists from instrument options for the song
            for soloist in self.soloist_names:
                instrument_opts.remove(soloist)

            self.accompanist_names = instrument_opts

            len_accompanists = len(self.accompanist_names)
            if len_accompanists == 2:
                ensemble_size = 2
            elif len_accompanists == 3:
                ensemble_size = random.choice([2, 3])
            elif len_accompanists == 4:
                ensemble_size = random.choice([1, 2, 3, 4])

            self.accompanist_names = random.sample(self.accompanist_names, ensemble_size)


        else:
            # who plays, who sits out?
            # ensemble_size = weighted_choice([3, 4, 5, 6], [1, 4, 5, 4])
            # self.ensemble_names = random.sample(instrument_opts, ensemble_size)

            # Everyone plays
            self.ensemble_names = instrument_opts


        # make a phrase for each unique part of the form (eg, an `a` in `abacabac`)
        unique_phrases = []
        for f in set(form):
            if self.type == 'solo':
                PhraseClass = SoloPhrase
            elif self.type == 'ensemble':
                PhraseClass = EnsemblePhrase
            unique_phrases.append(PhraseClass(piece, movement, self))

        # Copy the phrases in the order specified by form
        phrases = []
        for f in form:
            phrases.append(unique_phrases[f])

        # Render phrases as music21 objects
        for phrase in phrases:
            for part in phrase.parts:
                measure = Measure()
                if movement.first_measure:
                    ts = TimeSignature('4/4')

                    # ts.beatSequence = ts.beatSequence.subdivide(4)
                    ts.beamSequence = ts.beamSequence.subdivide(4)


                    # ts.beatSequence.partitionByList(subdivide(self.duration, 4))
                    # for i, b in enumerate(ts.beatSequence):
                    #     if b.duration.quarterLength == 4:
                    #         ts.beatSequence[i] = b.subdivide(2)
                    #         # ts.beatSequence[i][0] = b.subdivide(2)
                    #         # ts.beatSequence[i][1] = b.subdivide(2)
                    #     elif b.duration.quarterLength == 3:
                    #         ts.beatSequence[i] = b.subdivideByList([2, 1])
                    #         # ts.beatSequence[i][0] = ts.beatSequence[i].subdivide(2)
                    #     elif b.duration.quarterLength == 2:
                    #         ts.beatSequence[i] = b.subdivide(2)




                    measure.timeSignature = ts

                    # ts.getBeams()

                self.fix_durations(part['notes'])

                for note in part['notes']:
                    if note['pitch'] == 'rest':
                        n = Rest()
                    else:
                        p = Pitch(note['pitch'])
                        # Force all flats
                        if p.accidental.name == 'sharp':
                            p = p.getEnharmonic()
                        n = Note(p)

                        # TODO add slurs
                        # TODO add glissandos
                        # TODO add -50 cent marks

                    d = Duration()
                    d.fill(note['durations'])
                    n.duration = d

                    measure.append(n)

                # if len(measure.notesAndRests) > 1:
                #     measure.sliceByBeat(inPlace=True)

                # measure.makeBeams(inPlace=True)

                piece.parts.d[part['instrument_name']].append(measure)
            movement.first_measure = False