def test_attacked(self):
     """tests that it gives the right results with attacked set to true"""
     settings = {'attacked': True}
     ip = IndexedPiece()
     ip._analyses['noterest'] = self.NOTES
     actual = ip.get_data('active_voices', settings=settings)
     self.assertTrue(actual.equals(self.ATT_EXPECTED))
Example #2
0
    def test_intervals_9(self):
        """same as test_8 *but* no quality"""
        # NB: the "expected" was hand-counted
        # TODO: change this into a WorkflowManager-using test when the "horizontal intervals" experiment is ready
        expected = pandas.read_csv(os.path.join(VIS_PATH, 'tests', 'expecteds',
                                                'bwv77',
                                                'A_horiz_ints_nq.csv'),
                                   comment='#',
                                   index_col=0,
                                   header=[0, 1],
                                   quotechar="'",
                                   dtype='object')
        setts = {
            'quality': False,
            'simple or compound': 'compound',
            'horiz_attach_later': True
        }

        test_ip = IndexedPiece(
            os.path.join(VIS_PATH, 'tests', 'corpus', 'bwv77.mxl'))
        actual = test_ip.get_data(
            [noterest.NoteRestIndexer, interval.HorizontalIntervalIndexer],
            setts)

        actual = actual['interval.HorizontalIntervalIndexer']
        self.assertEqual(4, len(actual.columns))
        actual = pandas.DataFrame({
            ('interval.HorizontalIntervalIndexer', '1'):
            actual['1'].dropna()
        })
        self.assertDataFramesEqual(expected, actual)
 def test_active(self):
     """tests that it gives the right results with no settings and that the get_data()
     method properly calls active_voices"""
     ip = IndexedPiece()
     ip._analyses['noterest'] = self.NOTES
     actual = ip.get_data('active_voices')
     self.assertTrue(actual.equals(self.EXPECTED))
 def test_active(self):
     """tests that it gives the right results with no settings and that the get_data()
     method properly calls active_voices"""
     ip = IndexedPiece()
     ip._analyses['noterest'] = self.NOTES
     actual = ip.get_data('active_voices')
     self.assertTrue(actual.equals(self.EXPECTED))
 def test_show(self):
     """tests that the ``show_all`` argument works when True"""
     settings = {'show_all': True}
     ip = IndexedPiece()
     ip._analyses['noterest'] = self.NOTES
     actual = ip.get_data('active_voices', settings=settings)
     self.assertTrue(actual.equals(self.SHOW_EXPECTED))
 def test_attacked(self):
     """tests that it gives the right results with attacked set to true"""
     settings = {'attacked': True}
     ip = IndexedPiece()
     ip._analyses['noterest'] = self.NOTES
     actual = ip.get_data('active_voices', settings=settings)
     self.assertTrue(actual.equals(self.ATT_EXPECTED))
 def test_meta(self):
     meta = os.path.join(VIS_PATH, 'tests', 'corpus', 'meta')
     piece = os.path.join(
         VIS_PATH, 'tests', 'corpus',
         'Missa-Fortuna-desperata_Kyrie_Josquin-Des-Prez_file6.xml')
     ind = IndexedPiece(piece, metafile=meta)
     self.assertEqual('Sacred', ind.metadata('religiosity'))
 def test_show(self):
     """tests that the ``show_all`` argument works when True"""
     settings = {'show_all': True}
     ip = IndexedPiece()
     ip._analyses['noterest'] = self.NOTES
     actual = ip.get_data('active_voices', settings=settings)
     self.assertTrue(actual.equals(self.SHOW_EXPECTED))
 def test_note_beat_strength_indexer_1(self):
     # When the parts are empty
     expected = pandas.DataFrame({'0': pandas.Series(), '1': pandas.Series()})
     test_parts = [stream.Part(), stream.Part()]
     ip = IndexedPiece()
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = test_parts # supply part_streams.
     actual = ip._get_beat_strength()['meter.NoteBeatStrengthIndexer']
     self.assertTrue(actual.equals(expected))
 def test_measure_indexer_1(self):
     # When the parts are empty
     expected = pandas.DataFrame({'0': pandas.Series(), '1': pandas.Series()})
     test_parts = [stream.Part(), stream.Part()]
     ip = IndexedPiece('phony_file_location') # it doesn't matter what the string is becuase we supply part_streams 
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = test_parts # supply part_streams.
     actual = ip._get_measure()['meter.MeasureIndexer']
     self.assertTrue(actual.equals(expected))
Example #11
0
def ngram_count(piece, settings, n):

    ngrams = []
    ngram_freq = {}

    ind_piece = IndexedPiece(piece)
    the_score = music21.converter.parse(piece)
    the_notes = noterest.NoteRestIndexer(the_score).run()

    horiz_setts = settings

    # horiz-attach-later has to be true for the ngram indexer to work
    horiz_setts['horiz_attach_later'] = True

    horiz = interval.HorizontalIntervalIndexer(the_notes, horiz_setts).run()
    vert = interval.IntervalIndexer(the_notes, settings).run()
    intls = pandas.concat([horiz, vert], axis=1)

    parts = len(the_score.parts)

    # gets ngrams between all possible combinations of parts
    for x in range(parts):
        setts = {
            'mark singles': False,
            'continuer': '1',
            'n': n,
            'horizontal': [('interval.HorizontalIntervalIndexer', str(x))]
        }

        for i in range(x + 1, parts, 1):

            num = str(x) + ',' + str(i)
            setts['vertical'] = [('interval.IntervalIndexer', num)]
            ngram_test = ind_piece.get_data([ngram.NGramIndexer], setts, intls)
            ngrams.extend(ngram_test.values.tolist())

    # count ngrams
    for my_ngram in ngrams:
        my_ngram = str(' '.join(my_ngram))

        if 'Rest' in my_ngram:
            pass

        elif my_ngram in ngram_freq.keys():
            ngram_freq[my_ngram] += 1

        else:
            ngram_freq[my_ngram] = 1

    return ngram_freq
 def test_measure_indexer_2(self):
     # When the part has no Measure objects in it but a bunch of notes.
     expected = pandas.DataFrame({'0': pandas.Series()})
     test_part = stream.Part()
     # add stuff to the test_part
     for i in range(0, 20, 2):
         add_me = note.Note('C#5', quarterLength=2.0)
         add_me.offset = i
         test_part.append(add_me)
     test_part = [test_part] # finished adding stuff to the test_part
     ip = IndexedPiece('phony_file_location') # it doesn't matter what the string is becuase we supply part_streams 
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = test_part # supply part_streams.
     actual = ip._get_measure()['meter.MeasureIndexer']
     self.assertTrue(actual.equals(expected))
 def test_duration_indexer_3(self):
     # When there are a bunch of notes
     expected = TestDurationIndexer.make_series([(float(x), 1.0) for x in range(10)])
     expected.name = 'Part_1'
     test_part = stream.Part()
     # add stuff to the test_part
     for i in range(10):
         add_me = note.Note('C4', quarterLength=1.0)
         add_me.offset = i
         test_part.append(add_me)
     ip = IndexedPiece()
     test_part = [test_part]
     ip._analyses['part_streams'] = test_part
     ip.metadata('parts', [expected.name])
     actual = ip.get_data('duration').iloc[:, 0]
     self.assertTrue(actual.equals(expected))
    def test_intervals_9(self):
        """same as test_8 *but* no quality"""
        # NB: the "expected" was hand-counted
        # TODO: change this into a WorkflowManager-using test when the "horizontal intervals" experiment is ready
        expected = pandas.read_csv(os.path.join(VIS_PATH, 'tests', 'expecteds', 'bwv77', 'A_horiz_ints_nq.csv'),
                                   comment='#', index_col=0, header=[0, 1], quotechar="'", dtype='object')
        setts = {'quality': False, 'simple or compound': 'compound', 'horiz_attach_later': True}

        test_ip = IndexedPiece(os.path.join(VIS_PATH, 'tests', 'corpus', 'bwv77.mxl'))
        actual = test_ip.get_data([noterest.NoteRestIndexer, interval.HorizontalIntervalIndexer],
                                  setts)

        actual = actual['interval.HorizontalIntervalIndexer']
        self.assertEqual(4, len(actual.columns))
        actual = pandas.DataFrame({('interval.HorizontalIntervalIndexer', '1'): actual['1'].dropna()})
        self.assertDataFramesEqual(expected, actual)
Example #15
0
 def test_type_verifier_4(self):
     # with a bunch of valid classes
     # pylint: disable=W0212
     cls_1 = type('TestExperimenter1', (Experimenter,), {})
     cls_2 = type('TestExperimenter2', (Experimenter,), {})
     cls_3 = type('TestIndexer', (Indexer,), {})
     self.assertEqual(None, IndexedPiece._type_verifier([cls_1, cls_2, cls_3]))
 def test_note_beat_strength_indexer_2(self):
     # When the part has no Note or Rest objects in it
     expected = pandas.DataFrame({'0': pandas.Series()})
     test_part = stream.Part()
     # add stuff to the test_part
     for i in range(1000):
         add_me = clef.BassClef()
         add_me.offset = i
         test_part.append(add_me)
         add_me = bar.Barline()
         add_me.offset = i
         test_part.append(add_me) # finished adding stuff to the test_part
     ip = IndexedPiece()
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = [test_part] # supply part_streams.
     actual = ip._get_beat_strength()['meter.NoteBeatStrengthIndexer']
     self.assertTrue(actual.equals(expected))
 def test_measure_indexer_3(self):
     # When there are a bunch of measures with a note in each one.
     expected = pandas.DataFrame({'0': pandas.Series(range(1, 11), index=[float(x) for x in range(10)])})
     test_part = stream.Part()
     # add stuff to the test_part
     for i in range(1, 11):
         add_me = stream.Measure()
         add_me.number = i
         add_me.insert(note.Note('C#5', quarterLength=1.0))
         add_me.offset = i
         test_part.append(add_me)
     test_part = [test_part] # finished adding stuff to the test_part
     ip = IndexedPiece('phony_file_location') # it doesn't matter what the string is becuase we supply part_streams 
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = test_part # supply part_streams.
     actual = ip._get_measure()['meter.MeasureIndexer']
     self.assertTrue(actual.equals(expected))
Example #18
0
 def setUp(self):
     """Set up stuff"""
     self.pathnames = ['test_path_1', 'test_path_2', 'test_path_3']
     self.ind_pieces = [MagicMock(spec=IndexedPiece) for _ in range(len(self.pathnames))]
     for i, ind_p in enumerate(self.ind_pieces):
         ind_p.metadata.return_value = self.pathnames[i]
     self.agg_p = AggregatedPieces(pieces=self.ind_pieces)
     self.agg_p2 = AggregatedPieces(pieces=[IndexedPiece(path) for path in self.pathnames])
 def test_missing_pswrd(self):
     meta = 'http://database.elvisproject.ca/piece/1971/'
     piece = os.path.join(
         VIS_PATH, 'tests', 'corpus',
         'Missa-Fortuna-desperata_Kyrie_Josquin-Des-Prez_file6.xml')
     try:
         IndexedPiece(piece, metafile=meta, username='******')
     except RuntimeError as run_err:
         self.assertEqual(IndexedPiece._MISSING_PASSWORD, run_err.args[0])
 def test_ngrams_1(self):
     # test that all-voice interval 2-grams work
     ind_piece = IndexedPiece(u"vis/tests/corpus/bwv2.xml")
     setts = {u"quality": False, u"simple": False}
     horiz_ints = ind_piece.get_data([noterest.NoteRestIndexer, interval.HorizontalIntervalIndexer], setts)
     vert_ints = ind_piece.get_data([noterest.NoteRestIndexer, interval.IntervalIndexer], setts)
     parts = [vert_ints[u"0,3"], vert_ints[u"1,3"], vert_ints[u"2,3"], horiz_ints[3]]
     setts[u"vertical"] = [0, 1, 2]
     setts[u"horizontal"] = [3]
     setts[u"mark singles"] = False
     setts[u"continuer"] = u"1"
     setts[u"n"] = 2
     actual = ind_piece.get_data([ngram.NGramIndexer], setts, parts)
     self.assertEqual(1, len(actual))
     actual = actual[0]
     expected = AllVoiceIntervalNGrams.series_maker(AllVoiceIntervalNGrams.twograms)
     self.assertSequenceEqual(list(expected.index), list(actual.index))
     self.assertSequenceEqual(list(expected), list(actual))
Example #21
0
class TestIndexedPieceB(TestCase):
    def setUp(self):
        self._pathname = u'test_path'
        self.ind_piece = IndexedPiece(self._pathname)

    def test_import_score_1(self):
        # That _import_score() raises an OpusWarning when it imports an Opus but "expect_opus" is
        # False
        with patch(u'vis.models.indexed_piece.converter.parse') as mock_parse:
            mock_parse.return_value = music21.stream.Opus()
            self.assertRaises(OpusWarning, self.ind_piece._import_score, known_opus=False)

    def test_import_score_2(self):
        # That _import_score() returns multiple IndexedPiece objects when it imports an Opus and
        # "expect_opus" is True
        with patch(u'vis.models.indexed_piece.converter.parse') as mock_parse:
            mock_parse.return_value = music21.stream.Opus()
            for _ in xrange(5):
                mock_parse.return_value.insert(music21.stream.Score())
            actual = self.ind_piece._import_score(known_opus=True)
            self.assertEqual(5, len(actual))
            for i, piece in enumerate(actual):
                self.assertTrue(isinstance(piece, IndexedPiece))
                self.assertEqual(i, piece._opus_id)

    def test_import_score_3(self):
        # That _import_score() raises an OpusWarning when "expect_opus" is True, but it doesn't
        # import an Opus
        with patch(u'vis.models.indexed_piece.converter.parse') as mock_parse:
            mock_parse.return_value = music21.stream.Score()
            self.assertRaises(OpusWarning, self.ind_piece._import_score, known_opus=True)

    def test_import_score_4(self):
        # That _import_score() returns the right Score object when it imports an Opus
        with patch(u'vis.models.indexed_piece.converter.parse') as mock_parse:
            mock_parse.return_value = music21.stream.Opus()
            for i in xrange(5):
                mock_parse.return_value.insert(music21.stream.Score())
                mock_parse.return_value[i].priority = 42 + i
            actual = self.ind_piece._import_score(known_opus=True)
            self.assertEqual(5, len(actual))
            for i, piece in enumerate(actual):
                self.assertEqual(42 + i, piece._import_score().priority)
 def test_note_beat_strength_indexer_3(self):
     # When there are a few notes
     expected = pandas.DataFrame({'0': pandas.Series([1.0, 0.5, 0.5, 1.0, 0.5, 0.5])})
     test_part = stream.Part()
     # add stuff to the test_part
     measure = stream.Measure()
     # In music21 beginning time signatures are preferably inserted in the first measure and a
     # timeSignature is needed to be able to calculate beatStrength
     measure.insert(0, m21_meter.TimeSignature('3/4'))
     for i in range(6):
         add_me = note.Note(u'C4', quarterLength=1.0)
         add_me.offset = i
         measure.append(add_me)
     test_part.insert(0, measure) # finished adding stuff to the test_part
     ip = IndexedPiece()
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = [test_part] # supply part_streams.
     actual = ip._get_beat_strength()['meter.NoteBeatStrengthIndexer']
     self.assertTrue(actual.equals(expected))
def main():
    piece_path = "/home/amor/Code/vis-framework/vis/tests/corpus/Kyrie.krn"
    # piece_path = "/home/amor/Code/vis-framework/vis/tests/corpus/bach.xml"
    # piece_path = "/home/amor/Code/vis-framework/vis/tests/corpus/bwv603.xml"
    # piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Reimenschnieder/1-026900B_.xml'
    #piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Jos2308.mei'
    # piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Sanctus.krn'
    ind_piece = IndexedPiece(piece_path)
    test_piece = ind_piece._import_score()
    test_parts = test_piece.parts

    # bwv603 = converter.parse(os.path.join(VIS_PATH, 'tests', 'corpus/bwv603.xml'))
    # test_part = [bwv603.parts[0], bwv603.parts[1], bwv603.parts[2], bwv603.parts[3]]

    setts = {'quality': True, 'simple or compound': 'simple'}
    horiz_setts = {'quality': False, 'simple or compound': 'compound'}

    t0 = time.time()
    actual = noterest.NoteRestIndexer(test_parts).run()
    
    # filter_setts = {'quarterLength': 2.0, 'method':None}
    # filtered_results = offset.FilterByOffsetIndexer(actual, filter_setts).run()
    # pdb.set_trace()
    dur_ind = meter.DurationIndexer(test_parts).run()
    bs_ind = meter.NoteBeatStrengthIndexer(test_parts).run()
    horiz = interval.HorizontalIntervalIndexer(actual, horiz_setts).run()
    # ind_piece._analyses['noterest'] = actual
    # h_df = ind_piece._get_h_ints(settings=horiz_setts)
    vert_ints = interval.IntervalIndexer(actual, setts).run()
    dissonances = dissonance.DissonanceIndexer([bs_ind, dur_ind, horiz, vert_ints]).run()



    t1 = time.time()
    print('Time taken to run all indexers: ')
    print(t1 - t0)

    pdb.set_trace()
def main():
    piece_path = "/home/amor/Code/vis-framework/vis/tests/corpus/Kyrie.krn"
    # piece_path = "/home/amor/Code/vis-framework/vis/tests/corpus/bach.xml"
    # piece_path = "/home/amor/Code/vis-framework/vis/tests/corpus/bwv603.xml"
    # piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Reimenschnieder/1-026900B_.xml'
    #piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Jos2308.mei'
    # piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Sanctus.krn'
    ind_piece = IndexedPiece(piece_path)
    test_piece = ind_piece._import_score()
    test_parts = test_piece.parts

    # bwv603 = converter.parse(os.path.join(VIS_PATH, 'tests', 'corpus/bwv603.xml'))
    # test_part = [bwv603.parts[0], bwv603.parts[1], bwv603.parts[2], bwv603.parts[3]]

    setts = {'quality': True, 'simple or compound': 'simple'}
    horiz_setts = {'quality': False, 'simple or compound': 'compound'}

    t0 = time.time()
    actual = noterest.NoteRestIndexer(test_parts).run()

    # filter_setts = {'quarterLength': 2.0, 'method':None}
    # filtered_results = offset.FilterByOffsetIndexer(actual, filter_setts).run()
    # pdb.set_trace()
    dur_ind = meter.DurationIndexer(test_parts).run()
    bs_ind = meter.NoteBeatStrengthIndexer(test_parts).run()
    horiz = interval.HorizontalIntervalIndexer(actual, horiz_setts).run()
    # ind_piece._analyses['noterest'] = actual
    # h_df = ind_piece._get_h_ints(settings=horiz_setts)
    vert_ints = interval.IntervalIndexer(actual, setts).run()
    dissonances = dissonance.DissonanceIndexer(
        [bs_ind, dur_ind, horiz, vert_ints]).run()

    t1 = time.time()
    print('Time taken to run all indexers: ')
    print(t1 - t0)

    pdb.set_trace()
 def test_note_beat_strength_indexer_1(self):
     # When the parts are empty
     expected = pandas.DataFrame({
         '0': pandas.Series(),
         '1': pandas.Series()
     })
     test_parts = [stream.Part(), stream.Part()]
     ip = IndexedPiece()
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = test_parts  # supply part_streams.
     actual = ip._get_beat_strength()['meter.NoteBeatStrengthIndexer']
     self.assertTrue(actual.equals(expected))
 def test_note_beat_strength_indexer_2(self):
     # When the part has no Note or Rest objects in it
     expected = pandas.DataFrame({'0': pandas.Series()})
     test_part = stream.Part()
     # add stuff to the test_part
     for i in range(1000):
         add_me = clef.BassClef()
         add_me.offset = i
         test_part.append(add_me)
         add_me = bar.Barline()
         add_me.offset = i
         test_part.append(add_me)  # finished adding stuff to the test_part
     ip = IndexedPiece()
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = [test_part]  # supply part_streams.
     actual = ip._get_beat_strength()['meter.NoteBeatStrengthIndexer']
     self.assertTrue(actual.equals(expected))
Example #27
0
 def test_duration_indexer_3(self):
     # When there are a bunch of notes
     expected = TestDurationIndexer.make_series([(float(x), 1.0)
                                                 for x in range(10)])
     expected.name = 'Part_1'
     test_part = stream.Part()
     # add stuff to the test_part
     for i in range(10):
         add_me = note.Note('C4', quarterLength=1.0)
         add_me.offset = i
         test_part.append(add_me)
     ip = IndexedPiece()
     test_part = [test_part]
     ip._analyses['part_streams'] = test_part
     ip.metadata('parts', [expected.name])
     actual = ip.get_data('duration').iloc[:, 0]
     self.assertTrue(actual.equals(expected))
Example #28
0
 def test_note_rest_indexer_2(self):
     # When the part has no Note or Rest objects in it. Really this is a test for the methods between
     # _get_part_streams() and _get_noterest().
     expected = pandas.DataFrame({'Part 1': pandas.Series()})
     test_part = stream.Part()
     # add stuff to the test_part
     for i in range(1000):
         add_me = clef.BassClef()
         add_me.offset = i
         test_part.append(add_me)
         add_me = bar.Barline()
         add_me.offset = i
         test_part.append(add_me)
     ip = IndexedPiece()
     ip._analyses['part_streams'] = [test_part]
     ip.metadata('parts', _find_part_names(ip._analyses['part_streams']))
     actual = ip.get_data('noterest')['noterest.NoteRestIndexer']
     self.assertTrue(actual.equals(expected))
 def test_note_beat_strength_indexer_3(self):
     # When there are a few notes
     expected = pandas.DataFrame(
         {'0': pandas.Series([1.0, 0.5, 0.5, 1.0, 0.5, 0.5])})
     test_part = stream.Part()
     # add stuff to the test_part
     measure = stream.Measure()
     # In music21 beginning time signatures are preferably inserted in the first measure and a
     # timeSignature is needed to be able to calculate beatStrength
     measure.insert(0, m21_meter.TimeSignature('3/4'))
     for i in range(6):
         add_me = note.Note(u'C4', quarterLength=1.0)
         add_me.offset = i
         measure.append(add_me)
     test_part.insert(0, measure)  # finished adding stuff to the test_part
     ip = IndexedPiece()
     ip.metadata('parts', expected.columns)
     ip._analyses['part_streams'] = [test_part]  # supply part_streams.
     actual = ip._get_beat_strength()['meter.NoteBeatStrengthIndexer']
     self.assertTrue(actual.equals(expected))
 def test_with_data(self):
     """tests that it gives the right results with no settings and that the get_data()
     method properly calls active_voices"""
     ip = IndexedPiece()
     actual = ip.get_data('active_voices', data=self.NOTES)
     self.assertTrue(actual.equals(self.EXPECTED))
Example #31
0
 def setUp(self):
     self._pathname = u'test_path'
     self.ind_piece = IndexedPiece(self._pathname)
Example #32
0
class TestIndexedPieceA(TestCase):
    def setUp(self):
        self._pathname = u'test_path'
        self.ind_piece = IndexedPiece(self._pathname)

    def test_metadata(self):
        # access fields which are set by default
        pathname = self.ind_piece.metadata('pathname')
        self.assertEquals(self._pathname, pathname, "pathname has changed!")
        # assign a value to a valid field
        self.ind_piece.metadata('date', 2)
        value = self.ind_piece.metadata('date')
        self.assertEquals(2, value, "extracted metadata field doesn't match assigned value")
        # assign a value to an invalid field
        self.assertRaises(AttributeError, self.ind_piece.metadata, 'field', 2)
        # access an invalid value
        self.assertRaises(AttributeError, self.ind_piece.metadata, 'invalid_field')
        # try accessing keys with invalid types
        self.assertRaises(TypeError, self.ind_piece.metadata, 2)
        self.assertRaises(TypeError, self.ind_piece.metadata, [])
        self.assertRaises(TypeError, self.ind_piece.metadata, {})

    def test_get_data_0(self):
        # try getting data for a non-Indexer, non-Experimenter class
        non_analyzer = Mock()
        self.assertRaises(TypeError, self.ind_piece.get_data, non_analyzer)

    def test_get_data_1(self):
        # get data for an Indexer requiring a Score
        mock_indexer_cls = type('MockIndexer', (Indexer,), {})
        mock_indexer_cls.required_score_type = music21.stream.Part
        mock_indexer_cls.run = MagicMock()
        mock_indexer_cls.run.return_value = u'ahhh!'
        self.assertEquals(u'ahhh!', self.ind_piece.get_data([mock_indexer_cls]))
        mock_indexer_cls.run.assert_called_once_with()

    def test_get_data_2(self):
        # get data for an Indexer requiring other data
        mock_indexer_cls = type('MockIndexer', (Indexer,), {})
        mock_init = MagicMock()
        mock_init.return_value = None
        mock_indexer_cls.__init__ = mock_init
        mock_indexer_cls.run = MagicMock()
        mock_indexer_cls.run.return_value = u'ahhh!'
        mock_indexer_cls.required_score_type = int
        self.assertEqual(u'ahhh!', self.ind_piece.get_data([mock_indexer_cls], data=[14]))
        mock_indexer_cls.run.assert_called_once_with()
        mock_init.assert_called_once_with([14], None)

    def test_get_data_3(self):
        # get data from a chained Indexer
        first_indexer_cls = type('MockIndexer', (Indexer,), {})
        first_init = MagicMock()
        first_init.return_value = None
        first_indexer_cls.__init__ = first_init
        first_indexer_cls.run = MagicMock()
        first_indexer_cls.run.return_value = [14]
        first_indexer_cls.required_score_type = music21.stream.Part
        second_indexer_cls = type('MockIndexer', (Indexer,), {})
        second_init = MagicMock()
        second_init.return_value = None
        second_indexer_cls.__init__ = second_init
        second_indexer_cls.run = MagicMock()
        second_indexer_cls.run.return_value = u'ahhh!'
        second_indexer_cls.required_score_type = int
        self.assertEqual(u'ahhh!', self.ind_piece.get_data([first_indexer_cls, second_indexer_cls]))
        first_init.assert_called_once_with([], None)
        second_init.assert_called_once_with(first_indexer_cls.run.return_value, None)
        first_indexer_cls.run.assert_called_once_with()
        second_indexer_cls.run.assert_called_once_with()

    def test_get_data_4(self):
        # chained Indexer plus settings
        first_indexer_cls = type('MockIndexer', (Indexer,), {})
        first_init = MagicMock()
        first_init.return_value = None
        first_indexer_cls.__init__ = first_init
        first_indexer_cls.run = MagicMock()
        first_indexer_cls.run.return_value = [14]
        first_indexer_cls.required_score_type = music21.stream.Part
        second_indexer_cls = type('MockIndexer', (Indexer,), {})
        second_init = MagicMock()
        second_init.return_value = None
        second_indexer_cls.__init__ = second_init
        second_indexer_cls.run = MagicMock()
        second_indexer_cls.run.return_value = u'ahhh!'
        second_indexer_cls.required_score_type = int
        settings_dict = {u'fake setting': u'so good!'}
        self.assertEqual(u'ahhh!', self.ind_piece.get_data([first_indexer_cls, second_indexer_cls],
                                                           settings_dict))
        first_init.assert_called_once_with([], settings_dict)
        second_init.assert_called_once_with(first_indexer_cls.run.return_value, settings_dict)
        first_indexer_cls.run.assert_called_once_with()
        second_indexer_cls.run.assert_called_once_with()

    def test_get_data_5(self):
        # get data from an Experimenter that requires an Indexer
        # (same as test 3, but second_indexer_cls is an Experimenter subclass)
        mock_indexer_cls = type('MockIndexer', (Indexer,), {})
        mock_init = MagicMock()
        mock_init.return_value = None
        mock_indexer_cls.__init__ = mock_init
        mock_indexer_cls.run = MagicMock()
        mock_indexer_cls.run.return_value = [14]
        mock_indexer_cls.required_score_type = music21.stream.Part
        mock_experimenter_cls = type('MockIndexer', (Experimenter,), {})
        exp_init = MagicMock()
        exp_init.return_value = None
        mock_experimenter_cls.__init__ = exp_init
        mock_experimenter_cls.run = MagicMock()
        mock_experimenter_cls.run.return_value = u'ahhh!'
        self.assertEqual(u'ahhh!', self.ind_piece.get_data([mock_indexer_cls,
                                                            mock_experimenter_cls]))
        mock_init.assert_called_once_with([], None)
        exp_init.assert_called_once_with(mock_indexer_cls.run.return_value, None)
        mock_indexer_cls.run.assert_called_once_with()
        mock_experimenter_cls.run.assert_called_once_with()

    def test_get_data_6(self):
        # That get_data() complains when an Indexer expects the results of another Indexer but
        # doesn't get them.
        mock_indexer_cls = type('MockIndexer', (Indexer,), {})
        mock_indexer_cls.required_score_type = pandas.Series
        self.assertRaises(RuntimeError, self.ind_piece.get_data, [mock_indexer_cls])

    def test_get_data_7(self):
        # That get_data() complains when you call it with something that isn't either an Indexer
        # or Experimenter.
        self.assertRaises(TypeError, self.ind_piece.get_data, [TestIndexedPieceB])

    def test_get_data_8(self):
        # That get_data() calls _get_note_rest_index() if asked for NoteRestIndexer.
        with patch.object(IndexedPiece, u'_get_note_rest_index') as mock_gnri:
            self.ind_piece.get_data([noterest.NoteRestIndexer])
            mock_gnri.assert_called_once_with(known_opus=False)

    def test_get_data_9(self):
        # That get_data() calls _get_note_rest_index() if asked for NoteRestIndexer, and another
        # test Indexer is also called. This is a regression test to monitor a bug found after
        # implementing caching of NoteRestIndexer results. Also ensure that NoteRestIndexer is only
        # instantiated once
        with patch.object(IndexedPiece, u'_get_note_rest_index') as mock_gnri:
            mock_gnri.return_value = 42
            with patch.object(IndexedPiece, u'_type_verifier') as mock_tv:
                # we'll mock _type_verifier() to avoid getting a TypeError when mock_nri_cls isn't
                # a proper subclass of Indexer
                expected = [400]
                mock_indexer_cls = type('MockIndexer', (Indexer,), {})
                mock_indexer_cls.__init__ = MagicMock()
                mock_indexer_cls.__init__.return_value = None
                mock_indexer_cls.run = MagicMock()
                mock_indexer_cls.run.return_value = expected
                actual = self.ind_piece.get_data([noterest.NoteRestIndexer, mock_indexer_cls])
                self.assertEqual(2, mock_tv.call_count)
                mock_tv.assert_has_calls([call([noterest.NoteRestIndexer, mock_indexer_cls]),
                                            call([mock_indexer_cls])])
                mock_gnri.assert_called_once_with(known_opus=False)
                mock_indexer_cls.__init__.assert_called_once_with(mock_gnri.return_value, None)
                mock_indexer_cls.run.assert_called_once_with()
                self.assertEqual(expected, actual)

    def test_get_data_10(self):
        # That get_data() calls _get_note_rest_index() if asked for NoteRestIndexer. This is a
        # regression test to monitor a bug found after implementing caching of NoteRestIndexer
        # results. Also ensure that NoteRestIndexer is only instantiated once
        with patch.object(IndexedPiece, u'_get_note_rest_index') as mock_gnri:
            mock_gnri.return_value = 42
            with patch.object(IndexedPiece, u'_type_verifier') as mock_tv:
                # we'll mock _type_verifier() to avoid getting a TypeError when mock_nri_cls isn't
                # a proper subclass of Indexer
                actual = self.ind_piece.get_data([noterest.NoteRestIndexer])
                mock_tv.assert_called_once_with([noterest.NoteRestIndexer])
                mock_gnri.assert_called_once_with(known_opus=False)
                self.assertEqual(mock_gnri.return_value, actual)

    def test_get_data_11(self):
        # That get_data() correctly passes its "known_opus" parameter to _get_note_rest_indexer()
        # and _import_score()
        with patch.object(IndexedPiece, u'_get_note_rest_index') as mock_gnri:
            self.ind_piece.get_data([noterest.NoteRestIndexer], known_opus='battery')
            mock_gnri.assert_called_once_with(known_opus='battery')
        with patch.object(IndexedPiece, u'_import_score') as mock_is:
            with patch.object(IndexedPiece, u'_type_verifier') as mock_tv:
                mock_ind = MagicMock()
                mock_ind.required_score_type = music21.stream.Part
                self.ind_piece.get_data([mock_ind], known_opus='horse')
                mock_is.assert_called_once_with(known_opus='horse')

    def test_get_data_12(self):
        # get data for an Experimenter requiring other data; this is test 2, slightly modified
        mock_experimenter_cls = type('MockExperimenter', (Experimenter,), {})
        mock_experimenter_cls.__init__ = MagicMock(return_value=None)
        mock_experimenter_cls.run = MagicMock(return_value=u'ahhh!')
        prev_data= u'data from the previous analyzers'
        self.assertEqual(u'ahhh!', self.ind_piece.get_data([mock_experimenter_cls], {}, prev_data))
        mock_experimenter_cls.run.assert_called_once_with()
        mock_experimenter_cls.__init__.assert_called_once_with(prev_data, {})

    def test_type_verifier_1(self):
        # with an Indexer
        # pylint: disable=W0212
        self.assertEqual(None, IndexedPiece._type_verifier([noterest.NoteRestIndexer]))

    def test_type_verifier_2(self):
        # with an Experimenter
        # pylint: disable=W0212
        cls = type('TestExperimenter', (Experimenter,), {})
        self.assertEqual(None, IndexedPiece._type_verifier([cls]))

    def test_type_verifier_3(self):
        # with another class
        # pylint: disable=W0212
        cls = type('TestGarbage', (object,), {})
        self.assertRaises(TypeError, IndexedPiece._type_verifier, [cls])

    def test_type_verifier_4(self):
        # with a bunch of valid classes
        # pylint: disable=W0212
        cls_1 = type('TestExperimenter1', (Experimenter,), {})
        cls_2 = type('TestExperimenter2', (Experimenter,), {})
        cls_3 = type('TestIndexer', (Indexer,), {})
        self.assertEqual(None, IndexedPiece._type_verifier([cls_1, cls_2, cls_3]))

    def test_type_verifier_5(self):
        # with a bunch of valid, but one invalid, class
        # pylint: disable=W0212
        cls_1 = type('TestExperimenter1', (Experimenter,), {})
        cls_2 = type('TestIndexer', (Indexer,), {})
        cls_3 = type('TestGarbage', (object,), {})
        self.assertRaises(TypeError, IndexedPiece._type_verifier, [cls_1, cls_2, cls_3])

    def test_get_nrindex_1(self):
        # pylint: disable=W0212
        # That _get_note_rest_index() returns self._noterest_results if it's not None.
        self.ind_piece._noterest_results = 42
        self.assertEqual(42, self.ind_piece._get_note_rest_index())

    def test_get_nrindex_2(self):
        # pylint: disable=W0212
        # That we run the NoteRestIndexer and store results in self._note_rest_results if is None.
        with patch(u'vis.models.indexed_piece.noterest.NoteRestIndexer') as mock_nri_cls:
            mock_nri = MagicMock(return_value=[14])
            mock_nri.run = MagicMock()
            mock_nri.run.return_value = [14]
            mock_nri_cls.return_value = mock_nri
            expected = [14]
            actual = self.ind_piece._get_note_rest_index()
            mock_nri.run.assert_called_once_with()
            self.assertEqual(expected, actual)
            self.assertEqual(expected, self.ind_piece._noterest_results)

    def test_get_nrindex_3(self):
        # That _get_note_rest_index() just flat-out calls _import_score() when "known_opus" is True
        with patch.object(IndexedPiece, u'_import_score') as mock_is:
            with patch.object(noterest.NoteRestIndexer, u'run') as mock_nri:
                self.ind_piece._get_note_rest_index(known_opus=True)
                mock_is.assert_called_once_with(known_opus=True)
                self.assertEqual(0, mock_nri.call_count)

    def test_unicode_1(self):
        # __unicode__() without having imported yet
        # NB: adjusting _imported is the whole point of the test
        # pylint: disable=W0212
        self.ind_piece._imported = False
        with patch(u'vis.models.indexed_piece.IndexedPiece.metadata') as mock_meta:
            mock_meta.return_value = u'42'
            expected = u'<IndexedPiece (42)>'
            actual = self.ind_piece.__unicode__()
            self.assertEqual(expected, actual)
            mock_meta.assert_called_once_with(u'pathname')

    def test_unicode_2(self):
        # __unicode__() with proper title and composer
        # NB: adjusting _imported is the whole point of the test
        # pylint: disable=W0212
        self.ind_piece._imported = True
        with patch(u'vis.models.indexed_piece.IndexedPiece.metadata') as mock_meta:
            returns = [u'some ridiculous piece', u'a no-name composer']
            def side_effect(*args):
                # NB: we need to accept "args" as a mock framework formality
                # pylint: disable=W0613
                return returns.pop(0)
            mock_meta.side_effect = side_effect
            expected = u'<IndexedPiece (some ridiculous piece by a no-name composer)>'
            actual = self.ind_piece.__unicode__()
            self.assertEqual(expected, actual)
            expected_calls = [call(u'title'), call(u'composer')]
            self.assertSequenceEqual(expected_calls, mock_meta.call_args_list)
 def test_meta(self):
     meta = os.path.join(VIS_PATH, 'tests', 'corpus', 'meta')
     piece = os.path.join(VIS_PATH, 'tests', 'corpus', 'Missa-Fortuna-desperata_Kyrie_Josquin-Des-Prez_file6.xml')
     ind = IndexedPiece(piece, metafile=meta)
     self.assertEqual('Sacred', ind.metadata('religiosity'))
Example #34
0
 def test_type_verifier_2(self):
     # with an Experimenter
     # pylint: disable=W0212
     cls = type('TestExperimenter', (Experimenter,), {})
     self.assertEqual(None, IndexedPiece._type_verifier([cls]))
Example #35
0
 def test_type_verifier_1(self):
     # with an Indexer
     # pylint: disable=W0212
     self.assertEqual(None, IndexedPiece._type_verifier([noterest.NoteRestIndexer]))
 def setUp(self):
     """Set up some stuff."""
     self._pathname = 'test_path'
     self.ind_piece = IndexedPiece(self._pathname)
class TestIndexedPieceA(TestCase):
    """The 'A' part of tests for IndexedPiece."""
    def setUp(self):
        """Set up some stuff."""
        self._pathname = 'test_path'
        self.ind_piece = IndexedPiece(self._pathname)

    def test_metadata(self):
        """access fields that are set by default"""
        pathname = self.ind_piece.metadata('pathname')
        self.assertEquals(self._pathname, pathname, "pathname has changed!")
        # assign a value to a valid field
        self.ind_piece.metadata('date', 2)
        value = self.ind_piece.metadata('date')
        self.assertEquals(
            2, value, "extracted metadata field doesn't match assigned value")
        # assign a value to an invalid field
        self.assertRaises(AttributeError, self.ind_piece.metadata, 'field', 2)
        # access an invalid value
        self.assertRaises(AttributeError, self.ind_piece.metadata,
                          'invalid_field')
        # try accessing keys with invalid types
        self.assertRaises(TypeError, self.ind_piece.metadata, 2)
        self.assertRaises(TypeError, self.ind_piece.metadata, [])
        self.assertRaises(TypeError, self.ind_piece.metadata, {})

    def test_get_data_0(self):
        """try getting data for a non-Indexer, non-Experimenter class"""
        non_analyzer = Mock()
        self.assertRaises(KeyError, self.ind_piece.get_data, non_analyzer)

    def test_get_data_1(self):
        """
        That get_data() complains when an Indexer expects the results of another Indexer but
        doesn't get them.
        """
        mock_indexer_cls = type('MockIndexer', (Indexer, ), {})
        mock_indexer_cls.required_score_type = pandas.DataFrame
        self.assertRaises(RuntimeWarning, self.ind_piece.get_data,
                          vis.analyzers.indexers.ngram.NGramIndexer)

    def test_get_data_2(self):
        """
        That get_data() complains when you call it with something that isn't either an Indexer
        or Experimenter.
        """
        self.assertRaises(KeyError, self.ind_piece.get_data, TestIndexedPieceA)

    def test_get_nrindex_1(self):
        """That _get_noterest() returns self._analyses['noterest'] if it's not None."""
        # pylint: disable=W0212
        self.ind_piece._analyses['noterest'] = 42
        self.assertEqual(42, self.ind_piece._get_noterest())

    def test_str_1(self):
        """__str__() without having imported yet"""
        # NB: adjusting _imported is the whole point of the test
        # pylint: disable=W0212
        self.ind_piece._imported = False
        with patch(
                'vis.models.indexed_piece.IndexedPiece.metadata') as mock_meta:
            mock_meta.return_value = '42'
            expected = '<IndexedPiece (42)>'
            actual = self.ind_piece.__str__()
            self.assertEqual(expected, actual)
            mock_meta.assert_called_once_with('pathname')

    def test_str_2(self):
        """__str__() with proper title and composer"""
        # NB: adjusting _imported is the whole point of the test
        # pylint: disable=W0212
        self.ind_piece._imported = True
        with patch(
                'vis.models.indexed_piece.IndexedPiece.metadata') as mock_meta:
            returns = ['some ridiculous piece', 'a no-name composer']

            def side_effect(*args):
                # NB: we need to accept "args" as a mock framework formality
                # pylint: disable=W0613
                return returns.pop(0)

            mock_meta.side_effect = side_effect
            expected = '<IndexedPiece (some ridiculous piece by a no-name composer)>'
            actual = self.ind_piece.__str__()
            self.assertEqual(expected, actual)
            expected_calls = [call('title'), call('composer')]
            self.assertSequenceEqual(expected_calls, mock_meta.call_args_list)
Example #38
0
    # '/home/amor/Code/vis-framework/vis/scripts/M_corpus/13 Flora wilt thou torment mee.xml',
    # '/home/amor/Code/vis-framework/vis/scripts/M_corpus/15 In nets of golden wyers.xml',
    # '/home/amor/Code/vis-framework/vis/scripts/M_corpus/17 O thou that art so cruell.xml',
    # '/home/amor/Code/vis-framework/vis/scripts/M_corpus/19 I should for griefe and anguish.xml',
    ]
ccr_s, ni_s = [], []
v_setts = {'quality': True, 'simple or compound': 'simple'}
h_setts = {'quality': False, 'simple or compound': 'compound'}
h_setts2 = {'quality': True, 'simple or compound': 'compound', 'horiz_attach_later': True}
n_setts = {'n': 3, 'continuer': 'P1', 'horizontal': 'lowest', 'vertical': 'all',
           'terminator': ['Rest'], 'open-ended': False, 'brackets': False}
w = 6 # w is for window
ends = []

for number, piece_path in enumerate(pieces):
    ind_piece = IndexedPiece(piece_path)
    piece = ind_piece._import_score()
    parts = piece.parts
    nr = noterest.NoteRestIndexer(parts).run()
    dr = meter.DurationIndexer(parts).run()
    ms = meter.MeasureIndexer(parts).run()
    bs = meter.NoteBeatStrengthIndexer(parts).run()
    hz = interval.HorizontalIntervalIndexer(nr, h_setts).run()
    hz2 = interval.HorizontalIntervalIndexer(nr, h_setts2).run()
    vt = interval.IntervalIndexer(nr, v_setts).run()
    # ng = new_ngram.NewNGramIndexer((vt, hz2), n_setts).run()
    ds = dissonance.DissonanceIndexer([bs, dr, hz, vt]).run()
    av = active_voices.ActiveVoicesIndexer(nr).run()
    av_sa = active_voices.ActiveVoicesIndexer(nr, {'show_all': True}).run()

class TestIndexedPieceA(TestCase):
    """The 'A' part of tests for IndexedPiece."""

    def setUp(self):
        """Set up some stuff."""
        self._pathname = 'test_path'
        self.ind_piece = IndexedPiece(self._pathname)

    def test_metadata(self):
        """access fields that are set by default"""
        pathname = self.ind_piece.metadata('pathname')
        self.assertEquals(self._pathname, pathname, "pathname has changed!")
        # assign a value to a valid field
        self.ind_piece.metadata('date', 2)
        value = self.ind_piece.metadata('date')
        self.assertEquals(2, value, "extracted metadata field doesn't match assigned value")
        # assign a value to an invalid field
        self.assertRaises(AttributeError, self.ind_piece.metadata, 'field', 2)
        # access an invalid value
        self.assertRaises(AttributeError, self.ind_piece.metadata, 'invalid_field')
        # try accessing keys with invalid types
        self.assertRaises(TypeError, self.ind_piece.metadata, 2)
        self.assertRaises(TypeError, self.ind_piece.metadata, [])
        self.assertRaises(TypeError, self.ind_piece.metadata, {})

    def test_get_data_0(self):
        """try getting data for a non-Indexer, non-Experimenter class"""
        non_analyzer = Mock()
        self.assertRaises(KeyError, self.ind_piece.get_data, non_analyzer)

    def test_get_data_1(self):
        """
        That get_data() complains when an Indexer expects the results of another Indexer but
        doesn't get them.
        """
        mock_indexer_cls = type('MockIndexer', (Indexer,), {})
        mock_indexer_cls.required_score_type = pandas.DataFrame
        self.assertRaises(RuntimeWarning, self.ind_piece.get_data, vis.analyzers.indexers.ngram.NGramIndexer)

    def test_get_data_2(self):
        """
        That get_data() complains when you call it with something that isn't either an Indexer
        or Experimenter.
        """
        self.assertRaises(KeyError, self.ind_piece.get_data, TestIndexedPieceA)

    def test_get_nrindex_1(self):
        """That _get_noterest() returns self._analyses['noterest'] if it's not None."""
        # pylint: disable=W0212
        self.ind_piece._analyses['noterest'] = 42
        self.assertEqual(42, self.ind_piece._get_noterest())

    def test_str_1(self):
        """__str__() without having imported yet"""
        # NB: adjusting _imported is the whole point of the test
        # pylint: disable=W0212
        self.ind_piece._imported = False
        with patch('vis.models.indexed_piece.IndexedPiece.metadata') as mock_meta:
            mock_meta.return_value = '42'
            expected = '<IndexedPiece (42)>'
            actual = self.ind_piece.__str__()
            self.assertEqual(expected, actual)
            mock_meta.assert_called_once_with('pathname')

    def test_str_2(self):
        """__str__() with proper title and composer"""
        # NB: adjusting _imported is the whole point of the test
        # pylint: disable=W0212
        self.ind_piece._imported = True
        with patch('vis.models.indexed_piece.IndexedPiece.metadata') as mock_meta:
            returns = ['some ridiculous piece', 'a no-name composer']
            def side_effect(*args):
                # NB: we need to accept "args" as a mock framework formality
                # pylint: disable=W0613
                return returns.pop(0)
            mock_meta.side_effect = side_effect
            expected = '<IndexedPiece (some ridiculous piece by a no-name composer)>'
            actual = self.ind_piece.__str__()
            self.assertEqual(expected, actual)
            expected_calls = [call('title'), call('composer')]
            self.assertSequenceEqual(expected_calls, mock_meta.call_args_list)
Example #40
0
from vis.analyzers.indexers import noterest, interval, new_ngram, meter, active_voices
from vis.models.indexed_piece import IndexedPiece 
from vis.models.aggregated_pieces import AggregatedPieces
import pandas
import pdb
import time

import vis
VIS_PATH = vis.__path__[0]

# piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Jos2308.mei'
# piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/bwv2.xml'
# piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Kyrie.krn'
piece_path = '/home/amor/Code/vis-framework/vis/tests/corpus/Jos0303a-Missa_De_beata_virgine-Kyrie.mei'
# piece_path = '/home/amor/Code/vis-framework/vis/scripts/Lassus_Duets/Lassus_1_Beatus_Vir.xml'
ind_piece = IndexedPiece(piece_path)
# parts = ind_piece._import_score().parts

av_setts = {'show_all': True}
v_setts = {'quality': True, 'simple or compound': 'simple', 'directed': True, 'mp': False}
h_setts = {'quality': False, 'horiz_attach_later': False, 'simple or compound': 'simple', 'directed': True, 'mp': False}
n_setts = {'n': 5, 'continuer': 'P1', 'horizontal': 'lowest', 'vertical': [('0,4',)],
           'terminator': ['Rest'], 'open-ended': False, 'brackets': False}
n_setts_2 = {'n': 5, 'continuer': 'P1', 'vertical': 'all',
           'terminator': ['Rest'], 'open-ended': False, 'brackets': False}
n_setts_3 = {'n': 2, 'continuer': 'P1', 'vertical': [('0,4',)],
           'terminator': [], 'open-ended': False, 'brackets': False}

# pieces = (IndexedPiece(piece_path2), ind_piece)
# corpus = AggregatedPieces(pieces)
pdb.set_trace()
Example #41
0
def vertical(piece, pair, settings, title):
    ind_piece = IndexedPiece(piece)

    # get notes
    the_score = music21.converter.parse(piece)
    the_notes = noterest.NoteRestIndexer(the_score).run()

    setts = {'quarterLength': 1.0, 'method': 'ffill'}
    off = offset.FilterByOffsetIndexer(the_notes, setts).run()

    vert = interval.IntervalIndexer(off, settings).run()
    my_pair = vert['interval.IntervalIndexer', pair]

    piece_range = int(the_notes.last_valid_index())

    intervals = []

    for x in range(0, piece_range, 1):

        name = [str(my_pair.get(x))]
        new_name = []

        for note in name:
            if note == 'Rest':
                pass

            elif note not in new_name:
                new_name.append(note)

            else:
                pass

        intervals.append(new_name)

    nodes = []

    for intl in intervals:

        if not intl:
            pass

        else:
            intl = sorted(intl)
            intl = ' '.join(intl)
            nodes.append(intl)

    gr = nx.DiGraph()

    node_freq = {}
    edge_freq = {}

    for i in range(len(nodes)):

        if nodes[i] in node_freq:
            node_freq[nodes[i]] += 1

        else:
            node_freq[nodes[i]] = 1

        if i + 1 < len(nodes):
            edge = nodes[i] + ' - ' + nodes[i + 1]
            if nodes[i] == nodes[i + 1]:
                pass

            elif edge in edge_freq:
                edge_freq[edge] += 1

            else:
                edge_freq[edge] = 1

    for e in range(len(nodes) - 1):

        if 'nan' in nodes[e]:
            pass

        elif 'nan' in nodes[e + 1]:
            pass

        elif not nodes[e]:
            pass

        elif not nodes[e + 1]:
            pass

        else:
            gr.add_node(nodes[e], frequency=node_freq[nodes[e]])
            gr.add_node(nodes[e + 1], frequency=node_freq[nodes[e + 1]])

            if nodes[e] == nodes[e + 1]:
                pass
            else:
                gr.add_edge(nodes[e], nodes[e + 1])

    sizes = []

    for note in node_freq.values():
        note *= 100
        sizes.append(note)

    edges = gr.edges()

    weights = []

    for i in range(len(edges)):
        edge = edges[i]
        width = edge_freq[edge[0] + ' - ' + edge[1]]
        weights.append(width)

    nx.draw_graphviz(gr,
                     node_size=sizes,
                     edge_color=weights,
                     edge_cmap=plt.cm.Blues,
                     node_color='#A0CBE2',
                     width=4,
                     arrows=False)

    fig = plt.gcf()
    fig.set_size_inches(18.5, 13.5)
    plt.savefig('output/graphs/results/' + title + '.png',
                facecolor='#97b9c3',
                transparent=True)

    plt.clf()
 def setUp(self):
     """Set up some stuff."""
     self._pathname = 'test_path'
     self.ind_piece = IndexedPiece(self._pathname)
 def test_with_data(self):
     """tests that it gives the right results with no settings and that the get_data()
     method properly calls active_voices"""
     ip = IndexedPiece()
     actual = ip.get_data('active_voices', data=self.NOTES)
     self.assertTrue(actual.equals(self.EXPECTED))
Example #44
0
# now actually import vis
from music21 import converter
from vis.analyzers.indexers import noterest, interval, dissonance, metre
from vis.analyzers.experimenters import aggregator, frequency
from vis.models.indexed_piece import IndexedPiece
from vis.workflow import WorkflowManager
from numpy import NaN, isnan
import pandas

# the piece we'll analyze... currently Kyrie of Palestrina's Missa "Dies sanctificatus"
print(u'\n\nLoading the piece and running the NoteRestIndexer...\n')
#piece_path = u'vis/tests/corpus/Palestrina-Lhomme_arme_1582-Agnus_I.krn'
piece_path = u'vis/tests/corpus/Kyrie.krn'
#piece_path = u'vis/tests/corpus/bwv2.xml'
#piece_path = u'/home/amor/Desktop/ELVIS_Meeting/J and P Lassus Files/Best duo score files/Lassus_3_Oculus.xml'
the_piece = IndexedPiece(piece_path)

# don't touch this (yet); it's settings required by DissonanceIndexer
setts = {u'quality': True, 'simple or compound': u'simple'}

# find the intervals
print(u'\n\nRunning the IntervalIndexer...\n')
intervals = the_piece.get_data([noterest.NoteRestIndexer,
                                interval.IntervalIndexer],
                               setts)
horiz_intervals = the_piece.get_data([noterest.NoteRestIndexer,
                                      interval.HorizontalIntervalIndexer],
                                     setts)

# find the dissonances
print(u'\n\nRunning the DissonanceIndexer...\n')
Example #45
0
    def build_fingerprint_matrices(self):
        # pathnames: List of paths to each piece for which a fingerprint matrix should be built
        # number_of_fingerprints: however many fingerprints you need
        interval_settings = self.interval_settings

        fingerprint_matrices = {}
        
        # Load pickled fingerprints
        if self.fp_pickle_path is not None:
            if os.path.isfile(self.fp_pickle_path):
                print "Found pickled fingerprints at '" + self.fp_pickle_path +"', importing..."
                with open(self.fp_pickle_path, 'rb') as fp_pickle:
                    fingerprint_matrices = pickle.load(fp_pickle)
            else:
                print "Warning: was asked to look for pickled fingerprints at '" + self.fp_pickle_path +"'"
                print "Couldn't find any -- new pickle file will be created."

        number_of_fingerprints = self.number_of_fingerprints

        for path in self.pathnames:
            # Skip pickled fingerprints
            if os.path.basename(path) in fingerprint_matrices.keys():
                continue
            # Setup for each piece
            #print("Indexing " + path)
            piece = IndexedPiece(path)
            piece_stream = music21.converter.parseFile(path)

            # LM: Get time signature and determine strong beats
            time_sigs = piece.get_data([metre.TimeSignatureIndexer])

            # Assuming no time signature change in whole piece, assign offsets to strong beats
            if time_sigs['metre.TimeSignatureIndexer']['0'].iloc[0] == '6/8' or time_sigs['metre.TimeSignatureIndexer']['0'].iloc[0] == '9/8':
                strong_beat_offsets = 1.5
                measures = 4
            else:
                strong_beat_offsets = 1.0
                measures = 4
            # LM: Get total number of offsets
            numer, denom = time_sigs['metre.TimeSignatureIndexer']['0'].iloc[0].split('/')
            # Four bars worth of offsets, ignoring anacrusis...
            # Add an extra strong beat at end 
            total_offsets = int(numer) * measures*4.0/int(denom) + strong_beat_offsets

            interval_settings['quarterLength'] = strong_beat_offsets
            interval_settings['intervalDistance'] = strong_beat_offsets
            interval_settings['subsection'] = (0.0, total_offsets)

            # LM: Build strong-interval frame
            strong_intervals = self.__build_strong_intervals(piece, interval_settings, strong_beat_offsets, total_offsets)

            # LM: Build weak-interval frame
            weak_intervals = self.__build_weak_intervals(piece, interval_settings, strong_beat_offsets, total_offsets)

            # LM: Assemble results
            # 1. Prepare strong_intervals -- had to change this due to change in representation... take off final column (start of new bar)
            strong_intervals = strong_intervals.T.iloc[:-1].T
            strong_intervals = self.__shift_matrix(strong_intervals)
            # Had to change this due to change in representation.... take off final row
            # strong_intervals = strong_intervals.iloc[:]
            
            # 2. Prepare weak_intervals:
            weak_intervals = weak_intervals.iloc[:]
            weak_intervals.index = my_range(strong_beat_offsets, strong_beat_offsets, total_offsets+strong_beat_offsets)

            # 3. Row of 0s --- added after discussion with Laura pertaining to fingerprint representation
            zeros = DataFrame(Series([0.0]*(len(weak_intervals))))
            zeros.index = (my_range(strong_beat_offsets, strong_beat_offsets, total_offsets+strong_beat_offsets))
            zeros = zeros.T

            # 4. Append 
            fingerprint_frame = pandas.concat([weak_intervals.T, zeros, strong_intervals])
            fingerprint_frame.index = (['w'] + fingerprint_frame.index.tolist()[1:])

            #piece_stream.show('musicxml', 'MuseScore')   
            #  DataFrame(Series([0.0]*(len(weak_intervals)+1))).reindex(range(1, len(weak_intervals)+1)).T
            fingerprint_matrices[os.path.basename(path)]=fingerprint_frame
                
            number_of_fingerprints -= 1
            if 0 == number_of_fingerprints:
                print "Max Number of Fingerprints Reached"
                break

        return fingerprint_matrices