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_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_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))
Esempio n. 4
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_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_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_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))
Esempio n. 9
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_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)
Esempio n. 12
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))
Esempio n. 13
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))
Esempio n. 14
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)
Esempio n. 15
0
 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))
 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))
Esempio n. 17
0
# 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')
dissonances = the_piece.get_data([noterest.NoteRestIndexer,
                                  interval.IntervalIndexer,
                                  dissonance.DissonanceIndexer],
                                 setts)

# get and display the output from the "beatStrength" indexer
print(u'\n\nRunning the NoteBeatStrengthIndexer...\n')
beat_strengths = the_piece.get_data([metre.NoteBeatStrengthIndexer], setts)
Esempio n. 18
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