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))
示例#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_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))
示例#6
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_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))
示例#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
示例#10
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))
 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))
示例#12
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 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()
示例#15
0
 def setUp(self):
     """Set up some stuff."""
     self._pathname = 'test_path'
     self.ind_piece = IndexedPiece(self._pathname)
示例#16
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()
示例#17
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))
示例#18
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()