コード例 #1
0
    def test_for_book_example_2(self):
        print('----- test for book example 2 -----')

        source_instance_expression = '{<A-Major:i> [sA:4 A A A] qA:4 [iA:4 A] <:iv> qA:4 [sA:4 A A A] qA:4}'
        target_instance_expression = '{<G-Major:i> wA:4 <:iv> wA:4}'
        lge = LineGrammarExecutor()

        source_instance_line, source_instance_hct = lge.parse(
            source_instance_expression)

        actors = source_instance_line.get_all_notes()
        for a in actors:
            print("{0}".format(a))

        target_instance_line, target_instance_hct = lge.parse(
            target_instance_expression)
        target_hcs = target_instance_hct.hc_list()
        for hc in target_hcs:
            print("{0}".format(hc))

        pitch_range = PitchRange(
            DiatonicPitch.parse('C:4').chromatic_distance,
            DiatonicPitch.parse('C:6').chromatic_distance)

        p_map = PMap.create(source_instance_expression, pitch_range,
                            [('G-Major:I', Duration(3, 4)),
                             ('G-Major:IV', Duration(3, 4))])

        actors = p_map.actors

        policies = OrderedSet()
        policies.add(
            StepSequenceConstraint(
                [actors[0], actors[1], actors[2], actors[3]], [1, 1, 1]))
        policies.add(ChordalPitchConstraint(actors[0]))
        policies.add(ChordalPitchConstraint(actors[4]))
        policies.add(ChordalPitchConstraint(actors[8]))
        policies.add(
            StepSequenceConstraint(
                [actors[8], actors[9], actors[10], actors[11]], [1, -1, -1]))
        policies.add(EqualPitchConstraint([actors[0], actors[12]]))
        policies.add(EqualPitchConstraint([actors[4], actors[7]]))
        policies.add(
            RelativeDiatonicConstraint(actors[4], actors[5],
                                       Interval(3, IntervalType.Major),
                                       Interval(1, IntervalType.Perfect)))
        policies.add(StepSequenceConstraint([actors[5], actors[6]], [-1]))

        # policies.add(ChordalPitchConstraint(actors[7]))

        solver = PitchConstraintSolver(policies)

        full_results, partial_results = solver.solve(p_map)
        print('Results has {0} results.'.format(len(full_results)))

        for pm in full_results:
            if str(pm[actors[7]].note.diatonic_pitch) == 'D:4' and str(
                    pm[actors[0]].note.diatonic_pitch) == 'G:4':
                print("{0}".format(pm))
コード例 #2
0
    def test_simple_cross_tonality(self):
        logging.debug('Start test_simple_cross_tonality')

        # upper_policy_context = TestStepSequenceConstraint.policy_creator(ModalityType.Major, DiatonicTone('C'), 'tIV',
        #                                                             'C:2', 'C:8')
        lower_policy_context_1 = TestStepSequenceConstraint.policy_creator(ModalityType.Major, DiatonicTone('G'), 'tV',
                                                                           'C:2', 'C:8')
        lower_policy_context_2 = TestStepSequenceConstraint.policy_creator(ModalityType.Major, DiatonicTone('B'), 'tV',
                                                                           'C:2', 'C:8')
        upper_pitch_txts = ['C:5', 'D:5', 'E:5', 'F:5']
        tonalities = [lower_policy_context_1, lower_policy_context_1, lower_policy_context_2, lower_policy_context_2]
        differentials = [1, 1, 1]
        actors = list()
        p_map = dict()
        for i in range(0, len(upper_pitch_txts)):
            upper_note = Note(DiatonicPitch.parse(upper_pitch_txts[i]), Duration(1, 8))
            lower_note = ContextualNote(tonalities[i])
            actors.append(upper_note)
            p_map[upper_note] = lower_note

        policy = StepSequenceConstraint(actors, differentials)

        p_map[actors[0]].note = Note(DiatonicPitch.parse('B:5'), Duration(1, 8))
        answers = ['B:6', 'C:6', 'C#:6', 'D#:6']
        for i in range(1, len(actors)):
            notes = policy.values(p_map, actors[i])
            for note in notes:
                print(note.diatonic_pitch)
            assert str(next(iter(notes)).diatonic_pitch) == answers[i]
        print("------")

        upper_pitch_txts = ['F#:5', 'E:5', 'D:5', 'C:5']
        tonalities = [lower_policy_context_1, lower_policy_context_1, lower_policy_context_2, lower_policy_context_2]
        differentials = [-1, -1, -1]
        actors = list()
        p_map = dict()
        for i in range(0, len(upper_pitch_txts)):
            upper_note = Note(DiatonicPitch.parse(upper_pitch_txts[i]), Duration(1, 8))
            lower_note = ContextualNote(tonalities[i])
            actors.append(upper_note)
            p_map[upper_note] = lower_note

        policy = StepSequenceConstraint(actors, differentials)

        p_map[actors[0]].note = Note(DiatonicPitch.parse('F#:6'), Duration(1, 8))
        answers = ['F#:6', 'E:6', 'D#:6', 'C#:6']
        for i in range(1, len(actors)):
            notes = policy.values(p_map, actors[i])
            for note in notes:
                print(note.diatonic_pitch)
            assert str(next(iter(notes)).diatonic_pitch) == answers[i]
        print("------")

        logging.debug('End test_simple_cross_tonality')
コード例 #3
0
def motif_example():
    print('----- motif_example (Fgure 17.25) -----')

    line_str = '{<C-Major: I> iC:4 D E D E E E E C D E D E E E E C D E D E E E E wE}'

    score = create_score(line_str, 'piano', (4, 4, 'swww'))
    tonality = score.hct.get_hc_by_position(0).tonality
    all_notes = score.line.get_all_notes()

    constraints = {
        StepSequenceConstraint(
            [all_notes[0], all_notes[1], all_notes[2], all_notes[3]],
            [1, 1, -1])
    }
    motif = Motif([all_notes[0], all_notes[1], all_notes[2], all_notes[3]],
                  constraints)
    motif1 = motif.copy_to(all_notes[8])
    motif2 = motif.copy_to(all_notes[16])
    form = MelodicForm([motif, motif1, motif2])

    # 11 scalar notes to C:4 (0) to G:5 (11) with pitch unit 1/11
    interpreter = ScalarRangeInterpreter(tonality, DiatonicPitch.parse('C:4'),
                                         0, Fraction(1, 11))

    pitch_function = GenericUnivariatePitchFunction(three_sin, Position(0),
                                                    Position(3), False,
                                                    interpreter)
    t_reshape = TReshape(score, pitch_function, Range(0, 3), form, True)

    results = t_reshape.apply()

    filters = MinCurveFitFilter(pitch_function, results)
    print('{0} filtered results'.format(len(filters.scored_results)))

    for index in range(0, min(5, len(filters.scored_results))):
        result = filters.scored_results[index]
        print('[{0}] {1} ({2})'.format(index, str_line(result[0].line),
                                       result[1]))
コード例 #4
0
    def test_compute_simple_scale_tones(self):
        print('Start test_compute_simple_scale_tones')

        # upper_policy_context = TestStepSequenceConstraint.policy_creator(ModalityType.Major, DiatonicTone('Ab'),
        # 'tIV',
        #                                                            'C:2', 'C:8')
        lower_policy_context = TestStepSequenceConstraint.policy_creator(ModalityType.Major, DiatonicTone('G'), 'tV',
                                                                         'C:2', 'C:8')
        upper_pitch_txts = ['C:5', 'D:5', 'E:5', 'G:5', 'B:5', 'C:6', 'B:5', 'G:5', 'E:5', 'D:5', 'C:5', 'C:5']
        actors = list()
        differentials = [1, 1, 2, 2, 1, -1, -2, -2, -1, -1, 0]
        p_map = PMap()
        for pitch_txt in upper_pitch_txts:
            upper_note = Note(DiatonicPitch.parse(pitch_txt), Duration(1, 8))
            lower_note = ContextualNote(lower_policy_context)
            p_map[upper_note] = lower_note
            actors.append(upper_note)

        policy = StepSequenceConstraint(actors, differentials)

        notes = policy.values(p_map, actors[2])

        print('uninitialized: {0} notes'.format(len(notes)))
        for note in notes:
            print(note.diatonic_pitch)
        print('-----')

        assert len(notes) == 7 * 6 + 1
        assert str(next(iter(notes)).diatonic_pitch) == 'C:2'
        note = None
        for n in notes:
            note = n
        assert note is not None
        assert str(note.diatonic_pitch) == 'C:8'

        p_map[actors[0]].note = Note(DiatonicPitch.parse('F#:4'), Duration(1, 8))
        answers = ['F#:4', 'G:4', 'A:4', 'C:5', 'E:5', 'F#:5', 'E:5', 'C:5', 'A:4', 'G:4', 'F#:4', 'F#:4']
        for i in range(1, len(actors)):
            notes = policy.values(p_map, actors[i])
            for note in notes:
                print(note.diatonic_pitch)
            assert str(next(iter(notes)).diatonic_pitch) == answers[i]
        print('-----')

        p_map[actors[-1]].note = Note(DiatonicPitch.parse('F#:4'), Duration(1, 8))
        p_map[actors[0]].note = None
        answers = ['F#:4', 'G:4', 'A:4', 'C:5', 'E:5', 'F#:5', 'E:5', 'C:5', 'A:4', 'G:4', 'F#:4', 'F#:4']
        for i in range(1, len(actors)):
            notes = policy.values(p_map, actors[i])
            for note in notes:
                print(note.diatonic_pitch)
            assert str(next(iter(notes)).diatonic_pitch) == answers[i]
        print('-----')

        p_map[actors[6]].note = Note(DiatonicPitch.parse('E:5'), Duration(1, 8))
        p_map[actors[-1]].note = None
        answers = ['E:5', 'G:4', 'A:4', 'C:5', 'E:5', 'F#:5', 'E:5', 'C:5', 'A:4', 'G:4', 'F#:4', 'F#:4']
        for i in range(1, len(actors)):
            notes = policy.values(p_map, actors[i])
            for note in notes:
                print(note.diatonic_pitch)
            assert str(next(iter(notes)).diatonic_pitch) == answers[i]
        print('-----')

        logging.debug('End test_compute_simple_scale_tones')
コード例 #5
0
ファイル: test_t_reshape.py プロジェクト: dpazel/music_rep
    def test_pitch_sequence_shape(self):
        print('----- test_pitch_sequence_shape -----')

        s_notes = [
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),

            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
            ('E:4', 'e'),
        ]
        chords = [('tI', 1), ('tIV', 1), ('tV', 1), ('tVI', 1)]

        score = TestTReshape.create_score(s_notes, ModalityType.Major, 'Bb', chords, 'violin', (4, 4, 'swww'))
        all_notes = score.line.get_all_notes()

        eflat_interp = ScalarRangeInterpreter(Tonality.create(ModalityType.Major, DiatonicToneCache.get_tone('Bb')),
                                              'Bb:3', 0)
        pitch_function = GenericUnivariatePitchFunction(TestTReshape.e_flat_linear, Position(0), Position(1), False,
                                                        eflat_interp)

        # The first note should have one of 2 values, Eb:4, G:4
        constraints = {
            ChordalPitchConstraint(all_notes[0]),
            # You need this kind of constraint to limit possibilities.
            PitchRangeConstraint([all_notes[0]], PitchRange.create('Bb:3', 'A:4')),
            StepSequenceConstraint([all_notes[3], all_notes[4], all_notes[5], all_notes[6]], [-1, -1, -1]),
        }

        motif = Motif(score.line, constraints, 'A')

        melodic_form = MelodicForm([motif])

        time_range = Range(0, 3)

        treshape = TReshape(score, pitch_function, time_range, melodic_form, True)
        results = treshape.apply()
        assert results is not None
        for i in range(0, len(results)):
            print('--- result[{0}] ---'.format(i))
            print(results[i].line)

        for result in results:
            notes = result.line.get_all_notes()
            if str(notes[3].diatonic_pitch) == 'Eb:4':
                assert 'D:4' == str(notes[4].diatonic_pitch)
                assert 'C:4' == str(notes[5].diatonic_pitch)
                assert 'Bb:3' == str(notes[6].diatonic_pitch)
            else:
                assert 'D:4' == str(notes[3].diatonic_pitch)
                assert 'C:4' == str(notes[4].diatonic_pitch)
                assert 'Bb:3' == str(notes[5].diatonic_pitch)
                assert 'A:3' == str(notes[6].diatonic_pitch)
コード例 #6
0
ファイル: test_p_map.py プロジェクト: dpazel/music_rep
    def test_compute_simple_scale_tones(self):
        logging.debug('Start test_compute_simple_scale_tones')

        lower_policy_context = TestPMap.policy_creator(ModalityType.Major,
                                                       DiatonicTone('G'), 'tV',
                                                       'C:2', 'C:8')
        upper_pitch_txts = [
            'C:5', 'D:5', 'E:5', 'G:5', 'B:5', 'C:6', 'B:5', 'G:5', 'E:5',
            'D:5', 'C:5', 'C:5'
        ]
        actors = list()
        differentials = [1, 1, 2, 2, 1, -1, -2, -2, -1, -1, 0]
        p_map = OrderedDict()
        for pitch_txt in upper_pitch_txts:
            upper_note = Note(DiatonicPitch.parse(pitch_txt), Duration(1, 8))
            lower_note = ContextualNote(lower_policy_context)
            p_map[upper_note] = lower_note
            actors.append(upper_note)

        policy = StepSequenceConstraint(actors, differentials)
        p_map[actors[2]].note = Note(DiatonicPitch.parse('G:5'),
                                     Duration(1, 8))

        solver = PitchConstraintSolver([policy])
        results = None
        try:
            results, _ = solver.solve(p_map)
            if results is None:
                print("Results is None")
            else:
                print("Results is not None")
                if len(results) == 0:
                    print("Results is empty")
                else:
                    print('Results has {0} results.'.format(len(results)))

                    # verify
                    for pm in results:
                        if not policy.verify(pm.p_map):
                            print('Policy failure: {0}'.format(
                                type(policy).__name__))
                            print(pm)
                            continue

                    for pm in results:
                        print(pm)

        except Exception as e:
            print(e)
            # print >> sys.stderr, traceback.format_exc()
            traceback.print_exc()

        assert results is not None
        assert len(results) == 1
        pm = next(iter(results))

        answers = [
            'E:5', 'F#:5', 'G:5', 'B:5', 'D:6', 'E:6', 'D:6', 'B:5', 'G:5',
            'F#:5', 'E:5', 'E:5'
        ]
        for i in range(0, len(actors)):
            assert str(pm[actors[i]].note.diatonic_pitch) == answers[i]
        print('-----')

        #  Build a line and test apply on pm
        line = Line()
        begin_note = Note(DiatonicPitch.parse('A:2'), Duration(1, 2))
        end_note = Note(DiatonicPitch.parse('B:2'), Duration(1, 2))
        offset = Offset(0)
        line.pin(begin_note, offset)
        offset = offset + begin_note.duration.duration
        for note in actors:
            line.pin(note, offset)
            offset += note.duration.duration
        line.pin(end_note, offset)

        new_line = pm.apply(line)
        assert new_line is not None
        assert new_line != line

        all_notes = new_line.get_all_notes()
        assert len(all_notes) == 2 + len(actors)

        assert str(all_notes[0].diatonic_pitch) == 'A:2'
        assert str(all_notes[-1].diatonic_pitch) == 'B:2'

        for i in range(1, len(all_notes) - 1):
            assert str(all_notes[i].diatonic_pitch) == answers[i - 1]
コード例 #7
0
    def test_simple_setup(self):
        print('--- test_simple_setup')

        line = Line()

        notes = [
            Note(DiatonicPitch.parse('a:4'), Duration(1, 4)),
            Note(DiatonicPitch.parse('b:4'), Duration(1, 4)),
            Note(DiatonicPitch.parse('c:4'), Duration(1, 4)),
            Note(DiatonicPitch.parse('d:4'), Duration(1, 4)),
            Note(DiatonicPitch.parse('e:4'), Duration(1, 2)),
            Note(DiatonicPitch.parse('f:4'), Duration(1, 2)),
        ]

        location = 0
        for note in notes:
            line.pin(note, Offset(location))
            location += note.duration.duration

        tempo_seq = TempoEventSequence()
        ts_seq = EventSequence()
        tempo_seq.add(TempoEvent(Tempo(60, Duration(1, 4)), Position(0)))
        ts_seq.add(
            TimeSignatureEvent(TimeSignature(3, Duration(1, 4), 'sww'),
                               Position(0)))

        diatonic_tonality = Tonality.create(ModalityType.Major,
                                            DiatonicTone("C"))
        chord_t = TertianChordTemplate.parse('tIV')
        chord = chord_t.create_chord(diatonic_tonality)

        hc_track = HarmonicContextTrack()
        hc_track.append(
            HarmonicContext(diatonic_tonality, chord, Duration(1, 1)))
        hc_track.append(
            HarmonicContext(diatonic_tonality, chord, Duration(1, 2)))
        hc_track.append(
            HarmonicContext(diatonic_tonality, chord, Duration(1, 2)))

        c = InstrumentCatalog.instance()
        violin = c.get_instrument("violin")

        score = LiteScore(line, hc_track, violin, tempo_seq, ts_seq)

        constraints = [
            OnBeatConstraint(notes[1], BeatType.Strong),
            StepSequenceConstraint(notes, [1, 1, 1, -1, -1])
        ]

        solver = MelodicConstraintSolver.create(score, constraints)

        cheat = {notes[2]: DiatonicPitch.parse('E:5')}

        results = solver.solve(cheat)
        assert results is not None
        assert results.beat_results is not None
        assert results.pitch_results is not None

        print(len(results.beat_results))
        print(len(results.pitch_results))
        assert 1 == len(results.beat_results)
        assert 1 == len(results.pitch_results)

        new_line = results.apply(next(iter(results.beat_results)),
                                 next(iter(results.pitch_results)))
        assert new_line is not None

        print(new_line)
        all_notes = new_line.get_all_notes()
        assert 'C:5' == str(all_notes[0].diatonic_pitch)
        assert 'D:5' == str(all_notes[1].diatonic_pitch)
        assert 'E:5' == str(all_notes[2].diatonic_pitch)
        assert 'F:5' == str(all_notes[3].diatonic_pitch)
        assert 'E:5' == str(all_notes[4].diatonic_pitch)
        assert 'D:5' == str(all_notes[5].diatonic_pitch)

        assert Position(3, 4) == all_notes[1].get_absolute_position()