/
main_objs.py
4097 lines (3598 loc) · 193 KB
/
main_objs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from music21 import *
# httpx appears to be faster than requests, will fit better with an async version
import httpx
from pathlib import Path
import pandas as pd
import numpy as np
import xml.etree.ElementTree as ET
from itertools import combinations
from itertools import combinations_with_replacement as cwr
from more_itertools import consecutive_groups
import os
import re
import collections
import verovio
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import plotly.express as px
from glob import glob
from IPython.display import SVG, HTML
main_objs_dir = os.path.dirname(os.path.abspath(__file__))
MEINSURI = 'http://www.music-encoding.org/ns/mei'
MEINS = '{%s}' % MEINSURI
suppliedPattern = re.compile("<supplied.*?(<accid.*?\/>).*?<\/supplied>", flags=re.DOTALL)
datePattern = re.compile('date isodate="(1\d*)')
accepted_filetypes = ('mei', 'mid', 'midi', 'abc', 'xml', 'musicxml')
pathDict = {}
_directedNameMemos = {}
def _directed_name_from_note_strings(note1, note2):
key = (note1.nameWithOctave, note2.nameWithOctave)
if key not in _directedNameMemos:
ret = interval.Interval(note1, note2).directedName
_directedNameMemos[key] = ret
return ret
else:
return _directedNameMemos[key]
# An extension of the music21 note class with more information easily accessible
def importScore(path, recurse=False, verbose=False):
'''
Import piece or group of pieces and return an ImportedPiece or CorpusBase object respectively.
Return None if there is an error. This function accepts piece urls, and local paths. A list of
the accepted file formats can be found in the accepted_filetypes tuple. This function also
accepts directories and will import all the score files within a passed directory. Set
recurse=True (default False) to import all score files from the passed directory *and* those
of all subdirectories. Set verbose=True (default False) to print out confirmation of import
success for each piece. If any errors are encountered, these issues will be printed out
regardless of verbose setting.
'''
if os.path.isdir(path):
files = os.listdir(path)
files = [os.path.join(path, file) for file in files]
scores = []
for file in files:
if os.path.isdir(file) and recurse:
score_list = importScore(file, recurse, verbose)
if score_list is not None and len(score_list.scores):
scores.extend(score_list.scores)
elif os.path.isfile(file):
score = importScore(file, verbose=verbose)
if score is not None:
scores.append(score)
if len(scores):
return CorpusBase(scores)
elif verbose:
print('No scores found in this directory: {}'.format(path))
return
date = None
if path in pathDict and verbose:
print('Previously imported piece detected.')
else:
mei_doc = None
if path.startswith('http'):
if verbose:
print('Downloading remote score...')
try:
to_import = httpx.get(path).text
mei_doc = ET.fromstring(to_import) if path.endswith('.mei') else None
except:
print('Error downloading', str(path) + ', please check',
'your url and try again. Continuing to next file.')
return None
elif os.path.isfile(path): # `path` is formatted like a file path
ending = path.rsplit('.', 1)[1]
if ending not in accepted_filetypes:
return None
if path.endswith('.mei'):
try:
with open(path, "r") as file:
to_import = file.read()
mei_doc = ET.fromstring(to_import)
except ET.ParseError as err:
print('Error reading the mei file tree of {}'.format(path), err, sep='\n')
else:
to_import = path
else: # `path` is actually the string of an entire piece, used for user-supplied piece in streamlit
to_import = path
if '<mei' in path[:1000]: # is an <mei> element in the beginning of the piece?
try:
mei_doc = ET.fromstring(to_import)
except ET.ParseError as err:
print('Error reading this mei file:'.format(path[:200], err, sep='\n'))
try:
if mei_doc is not None:
to_import = re.sub(suppliedPattern, '\\1', to_import)
_date = re.search(datePattern, to_import)
if _date:
date = int(_date.group(1))
score = converter.parse(to_import)
pathDict[path] = ImportedPiece(score, path, mei_doc, date)
if verbose:
print("Successfully imported", path[:180])
except:
print("Import of", str(path[:180]), "failed, please check your file, path, or url.")
return None
return pathDict[path]
def Crimport(path, recurse=False, verbose=False):
'''
Better naming convention for importing single files or directories of files. This is
an alias for importScore. See that method's doc string for instructions.'''
return importScore(path, recurse, verbose)
def _getCVFTable():
if 'CVFTable' not in pathDict:
pathDict['CVFTable'] = pd.read_csv(main_objs_dir + '/data/cadences/CVFLabels.csv', index_col='Ngram')
return pathDict['CVFTable']
def _getCadenceTable():
if 'CadenceTable' not in pathDict:
pathDict['CadenceTable'] = pd.read_csv(main_objs_dir + '/data/cadences/cadenceLabels.csv', index_col=0)
return pathDict['CadenceTable']
class ImportedPiece:
def __init__(self, score, path, mei_doc=None, date=None):
self.score = score
self.path = path
self.file_name = path.rsplit('.', 1)[0].rsplit('/')[-1]
self.mei_doc = mei_doc
self.analyses = {'note_list': None}
title, composer = path, 'Not found'
if mei_doc is not None:
title = mei_doc.find('mei:meiHead//mei:titleStmt/mei:title', namespaces={"mei": MEINSURI})
if title is not None and hasattr(title, 'text'):
title = re.sub(r'\n', '', title.text).strip()
composer = mei_doc.find('mei:meiHead//mei:titleStmt//mei:persName[@role="composer"]', namespaces={"mei": MEINSURI})
if composer is None: # for mei 3 files
composer = mei_doc.find('mei:meiHead//mei:titleStmt/mei:composer', namespaces={"mei": MEINSURI})
if composer is not None and hasattr(composer, 'text'):
composer = re.sub(r'\n', '', composer.text).strip()
else:
if self.score.metadata.title is not None:
title = self.score.metadata.title
if self.score.metadata.composer is not None:
composer = self.score.metadata.composer
self.metadata = {'title': title, 'composer': composer, 'date': date}
if not self.metadata['date']:
if hasattr(self.score.metadata, 'date') and self.score.metadata.date is not None and self.score.metadata.date != 'None':
self.metadata['date'] = int(self.score.metadata.date[:4])
elif hasattr(self.score.metadata, 'dateCreated') and self.score.metadata.date is not None and self.score.metadata.dateCreated != 'None':
# music21 v8 replaced date with dateCreated and date will be removed in v10
self.metadata['date'] = int(self.score.metadata.dateCreated[:4])
self._intervalMethods = {
# (quality, directed, compound): function returning the specified type of interval
# diatonic with quality
('q', True, True): ImportedPiece._qualityDirectedCompound,
('q', True, False): ImportedPiece._qualityDirectedSimple,
('q', False, True): lambda cell: cell.name if hasattr(cell, 'name') else cell,
('q', False, False): lambda cell: cell.semiSimpleName if hasattr(cell, 'semiSimpleName') else cell,
# diatonic interals without quality
('d', True, True): lambda cell: cell.directedName[1:] if hasattr(cell, 'directedName') else cell,
('d', True, False): ImportedPiece._noQualityDirectedSemiSimple,
('d', True, 'simple'): ImportedPiece._noQualityDirectedSimple,
('d', False, True): lambda cell: cell.name[1:] if hasattr(cell, 'name') else cell,
('d', False, False): lambda cell: cell.semiSimpleName[1:] if hasattr(cell, 'semiSimpleName') else cell,
# chromatic intervals
('c', True, True): lambda cell: str(cell.semitones) if hasattr(cell, 'semitones') else cell,
('c', True, False): lambda cell: str(cell.semitones % 12) if hasattr(cell, 'semitones') else cell,
('c', False, True): lambda cell: str(abs(cell.semitones)) if hasattr(cell, 'semitones') else cell,
('c', False, False): lambda cell: str(abs(cell.semitones) % 12) if hasattr(cell, 'semitones') else cell
}
def _getFlatParts(self):
"""
Return and store flat parts inside a piece using the score attribute.
"""
if 'FlatParts' not in self.analyses:
parts = self.score.getElementsByClass(stream.Part)
self.analyses['FlatParts'] = [part.flatten() for part in parts]
return self.analyses['FlatParts']
def _getPartNames(self):
"""
Return flat names inside a piece using the score attribute.
"""
if 'PartNames' not in self.analyses:
part_names = []
name_set = set()
for i, part in enumerate(self._getFlatParts()):
name = part.partName or 'Part-' + str(i + 1)
if name in name_set:
name = 'Part-' + str(i + 1)
elif '_' in name:
print('\n*** Warning: it is problematic to have an underscore in a part name so _ was replaced with -. ***\n')
name = name.replace('_', '-')
else:
name_set.add(name)
part_names.append(name)
self.analyses['PartNames'] = part_names
return self.analyses['PartNames']
def _getPartSeries(self):
if 'PartSeries' not in self.analyses:
part_series = []
part_names = self._getPartNames()
for i, flat_part in enumerate(self._getFlatParts()):
notesAndRests = flat_part.getElementsByClass(['Note', 'Rest', 'Chord'])
notesAndRests = [max(noteOrRest.notes) if noteOrRest.isChord else noteOrRest for noteOrRest in notesAndRests]
ser = pd.Series(notesAndRests, name=part_names[i])
ser.index = ser.apply(lambda noteOrRest: noteOrRest.offset)
ser = ser[~ser.index.duplicated()] # remove multiple events at the same offset in a given part
part_series.append(ser)
self.analyses['PartSeries'] = part_series
return self.analyses['PartSeries']
def _getPartNumberDict(self):
'''
Return a dictionary mapping part names to their numerical position on the staff,
starting at 1 and counting from the highest voice.'''
if 'PartNumberDict' not in self.analyses:
parts = self._getPartNames()
names2nums = {part: str(i + 1) for i, part in enumerate(parts)}
self.analyses['PartNumberDict'] = names2nums
return self.analyses['PartNumberDict']
def numberParts(self, df):
'''
Return the passed df with the part names in the columns replaced with numbers
where 1 is the highest staff. Works with single parts and multi-part column names.
The df's column names are changed in place, so make a copy before calling this method
if you don't want your original df to get changed.'''
_dict = self._getPartNumberDict()
cols = ['_'.join(_dict.get(part, part) for part in col.split('_')) for col in df.columns]
res = df.copy()
res.columns = cols
return res
def _getM21Objs(self):
if 'M21Objs' not in self.analyses:
part_names = self._getPartNames()
self.analyses['M21Objs'] = pd.concat(self._getPartSeries(), names=part_names, axis=1, sort=True)
return self.analyses['M21Objs']
def _remove_tied(self, noteOrRest):
if hasattr(noteOrRest, 'tie') and noteOrRest.tie is not None and noteOrRest.tie.type != 'start':
return np.nan
return noteOrRest
def _getM21ObjsNoTies(self):
if 'M21ObjsNoTies' not in self.analyses:
df = self._getM21Objs().map(self._remove_tied).dropna(how='all')
self.analyses['M21ObjsNoTies'] = df
return self.analyses['M21ObjsNoTies']
def regularize(self, df, unit=2):
'''
Return the passed `pandas.DataFrame` (df) with its observations
regularized rhythmically. Pass a duration as the `unit` parameter to
control at what regular distance observations will be made. Durations
are measured according to the music21 convention where:
eighth note = .5
quarter note = 1
half note = 2
etc.
For example, if you pass a dataframe of the notes and rests of a piece,
and set `unit` to 4, a new whatever is "sounding" (whether a note or a
rest) at every regular whole note will be kept, and any intervening
notes or rests will be removed. A breve would get renotated as two
whole notes.
Regularization also works with non-integer values. So if you wanted to
regularize at the swung eigth note, for example, you could set:
`unit=1/3`
'''
spot = df.index[0] * 1000
end = self.score.highestTime * 1000
vals = []
step = unit * 1000
while spot < end:
vals.append(spot)
spot += step
new_index = pd.Index(vals).map(lambda i: round(i) / 1000)
res = df.ffill().reindex(new_index, method='pad')
return res
def _durationHelper(self, col, n):
col = col.dropna()
vals = col.index[n:] - col.index[:-n]
return pd.Series(vals, col.index[:-n])
def _maxnDurationHelper(self, _col):
col = _col.dropna()
starts = col[(col != 'Rest') & (col.shift(1).isin(('Rest', np.nan)))]
ends = col[(col == 'Rest') & (col.shift(1) != 'Rest')]
starts.dropna(inplace=True)
ends.dropna(inplace=True)
lenStarts = len(starts)
colDurs = ends.index[-lenStarts:] - starts.index
starts[:] = colDurs
return starts
def durations(self, df=None, n=1, mask_df=None):
'''
If no arguments are passed, return a `pandas.DataFrame` of floats giving
the duration of notes and rests in each part where 1 = quarternote,
1.5 = a dotted quarter, 4 = a whole note, etc. If a df is passed, then
return a df of the same shape giving the duration of each of the cells
of this df. This is useful if you want to know what the durations of
something other than single notes and rests, such as the durations of
intervals. E.g.:
har = importedPiece.harmonic()
harDur = importedPiece.durations(df=har)
The `n` parameter should be an integer greater than zero, or -1. When
n is a positive integer, it groups together a sliding window of n
consecutive non-NaN cells in each column.
If you pass a df, it will sum
the durations 'Rest' and non-Rest cell, provided they are in the same
n-sized window. For example, set n=3 if you wanted to get the durations
of all 3-event-long pair-wise harmonic events:
har = importedPiece.harmonic()
dur_3 = importedPiece.durations(df=har, n=3)
Setting n to -1 sums the durations of all adjacent non-rest events,
excluding NaNs. You could use this to find the durations of all melodies
in a piece. Note that the results of .notes() will be used for the
`df` parameter if none is provided:
dur = importedPiece.durations(n=-1)
You can also pass a `mask_df`, which will serve as a filter, only
keeping values at the same indecies (i.e. index and columns) as mask_df.
This is needed to get the durations of ngrams.
To get the durations of ngrams, pass the same value of n and the same
dataframe you passed to .ngrams() as the `n` and `df` parameters,
then pass your dataframe of ngrams as the `mask_df`. For example:
har = importedPiece.harmonic()
mel = importedPiece.melodic()
_n = 5
ngrams = importedPiece.ngrams(df=har, other=mel, n=_n)
ngramDurations = importedPiece.durations(df=har, n=_n, mask_df=ngrams)
'''
if 'Duration' in self.analyses and df is None and n == 1 and mask_df is None:
return self.analyses['Duration']
_df = self.notes().copy() if df is None else df.copy()
highestTime = self.score.highestTime
_df.loc[highestTime, :] = 'Rest' # this is just a placeholder
if n > 0:
result = _df.apply(self._durationHelper, args=(n,))
if df is None and n == 1 and mask_df is None:
self.analyses['Duration'] = result
else: # n == -1
result = _df.apply(self._maxnDurationHelper)
result = result.astype('float64')
result.index = result.index.astype('float64')
if mask_df is not None:
mask = mask_df.map(lambda cell: True, na_action='ignore')
result = result[mask]
return result.dropna(how='all')
def lyrics(self, strip=True):
'''
Return a dataframe of the lyrics associated with each note in the piece.
If `strip` is True (default), then the lyrics will be stripped of leading
and trailing whitespace and dashes. If `strip` is False, then the lyrics will
be returned as they are in the score. Notes without lyrics are shown as NaN.
'''
key = ('Lyrics', strip)
if key not in self.analyses:
m21Objs = self._getM21ObjsNoTies()
if strip:
df = m21Objs.map(na_action='ignore',
func=lambda cell: cell.lyric.strip('\n \t-') if (cell.isNote and cell.lyric) else np.nan )
else:
df = m21Objs.map(na_action='ignore',
func=lambda cell: cell.lyric if cell.isNote else np.nan)
self.analyses[key] = df
return self.analyses[key]
def _noteRestHelper(self, noteOrRest):
if noteOrRest.isRest:
return 'Rest'
return noteOrRest.nameWithOctave
def _combineRests(self, col):
col = col.dropna()
return col[(col != 'Rest') | ((col == 'Rest') & (col.shift(1) != 'Rest'))]
def _combineUnisons(self, col):
col = col.dropna()
return col[(col == 'Rest') | (col != col.shift(1))]
def notes(self, combineRests=True, combineUnisons=False):
'''
Return a table of the notes and rests in the piece. Rests are
designated with the string "Rest". Notes are shown such that middle C
is "C4".
If `combineRests` is True (default), non-first consecutive rests will be
removed, effectively combining consecutive rests in each voice.
`combineUnisons` works the same way for consecutive attacks on the same
pitch in a given voice, however, `combineUnisons` defaults to False.
'''
if 'Notes' not in self.analyses:
df = self._getM21ObjsNoTies().map(self._noteRestHelper, na_action='ignore')
self.analyses['Notes'] = df
ret = self.analyses['Notes'].copy()
if combineRests:
ret = ret.apply(self._combineRests)
if combineUnisons:
ret = ret.apply(self._combineUnisons)
return ret
def _m21Expressions(self):
'''
Get all the expressions from music21. This includes fermatas, mordents, etc.
'''
if 'm21Expressions' not in self.analyses:
df = self._getM21ObjsNoTies().map(lambda noteOrRest: noteOrRest.expressions, na_action='ignore')
self.analyses['m21Expressions'] = df
return self.analyses['m21Expressions']
def fermatas(self):
'''
Get all the fermatas in a piece. A fermata is designated by a True value.
'''
if 'Fermatas' not in self.analyses:
df = self._m21Expressions().map(
lambda exps: any(isinstance(exp, expressions.Fermata) for exp in exps), na_action='ignore')
self.analyses['Fermatas'] = df
return self.analyses['Fermatas']
def lowLine(self):
'''
Return a series that corresponds to the lowest sounding note of the piece at
any given moment. Attack information cannot be reliably preserved so
consecutive repeated notes and rests are combined. If all parts have a rest,
then "Rest" is shown for that stretch of the piece.'''
if 'LowLine' not in self.analyses:
# use m21 objects so that you can do comparison with min
notes = self._getM21ObjsNoTies()
# you can't compare notes and rests, so replace rests with a really high note
highNote = note.Note('C9')
notes = notes.map(lambda n: highNote if n.isRest else n, na_action='ignore')
notes.ffill(inplace=True)
lowLine = notes.apply(min, axis=1)
lowLine = lowLine.apply(lambda n: n.nameWithOctave)
lowLine.replace('C9', 'Rest', inplace=True)
lowLine.name = 'Low Line'
self.analyses['LowLine'] = lowLine[lowLine != lowLine.shift()]
return self.analyses['LowLine']
def final(self):
'''
Return the final of the piece, defined as the lowest sounding note at
the end of the piece.'''
if 'Final' not in self.analyses:
lowLine = self.lowLine()
if len(lowLine.index):
final = lowLine.iat[-1]
else:
final = None
if final == 'Rest' and len(lowLine.index) > 1:
final = lowLine.iat[-2]
self.analyses['Final'] = final
return self.analyses['Final']
def highLine(self):
'''
Return a series that corresponds to the highest sounding note of the piece at
any given moment. Attack information cannot be reliably preserved so
consecutive repeated notes and rests are combined. If all parts have a rest,
then "Rest" is shown for that stretch of the piece.'''
if 'HighLine' not in self.analyses:
# use m21 objects so that you can do comparison with min
notes = self._getM21ObjsNoTies()
# you can't compare notes and rests, so replace rests with a really high note
lowNote = note.Note('C', octave=-9)
notes = notes.map(lambda n: lowNote if n.isRest else n, na_action='ignore')
notes.ffill(inplace=True)
highLine = notes.apply(max, axis=1)
highLine = highLine.apply(lambda n: n.nameWithOctave)
highLine.replace('C-9', 'Rest', inplace=True)
highLine.name = 'High Line'
self.analyses['HighLine'] = highLine[highLine != highLine.shift()]
return self.analyses['HighLine']
def _emaRowHelper(self, row):
measures = list(range(row.iat[0], row.iat[2] + 1))
ends = (row.iat[0], row.iat[2])
mCount = row.iat[2] - row.iat[0] + 1
parts = row.iloc[4:].dropna().index
part_strings = '+'.join({part for combo in parts for part in combo.split('_')})
num_parts = part_strings.count('+') + 1
beats = []
for meas in measures:
if meas == row.iat[0] and meas == row.iat[2]:
beats.append('+'.join(['@{}-{}'.format(row.iat[1], row.iat[3])]*num_parts))
elif meas == row.iat[0]: # meas < row.iat[2]
beats.append('+'.join(['@{}-end'.format(row.iat[1])]*num_parts))
elif meas > row.iat[0] and meas < row.iat[2]:
beats.append('+'.join(['@all']*num_parts))
else: # meas > row.iat[0] and meas == row.iat[2]
beats.append('+'.join(['@start-{}'.format(row.iat[3])]*num_parts))
post = ['{}-{}'.format(row.iat[0], row.iat[2]), # measures
','.join([part_strings]*mCount), # parts
','.join(beats)] # beats
return '/'.join(post)
def combineEmaAddresses(self, emas):
'''
Given a list of EMA addresses, `emas`, return a single ema address that combines them into one.
'''
if isinstance(emas, str):
return emas
if len(emas) == 1:
return emas[0]
chunks = []
num_parts = len(self._getPartNames())
last_m = self.measures().iat[-1, 0]
for ema in emas:
ema = ema.replace('start', '1')
print(ema)
_measures, _parts, _beats = ema.split('/')
_beats = _beats.replace('1.0-', '1-')
_beats = _beats.replace('1.0@', '1@')
measures, parts, beats = _measures.split(','), _parts.split(','), _beats.split(',')
for i, meas in enumerate(measures):
# handle measures
if meas == 'all':
meas == '1-{}'.format(last_m) # measures 1 through the final measure
meas = meas.replace('end', str(last_m))
if '-' in meas: # this is a measure range, e.g. 9-12
start, end = meas.split('-')
ms = [str(m) for m in range(int(start), int(end) + 1)]
meas = ms[0]
measures[i+1:i+1] = ms[1:]
# handle beats
if beats[i] == '@all' or beats[i] == '@1-end':
bs = '@all'
else:
bs = beats[i].split('+')
# handle parts
if parts[i] == 'all':
ps = [str(x) for x in range(1, num_parts + 1)]
else:
ps = parts[i].replace('end', str(num_parts))
ps = ps.split('+')
for _j, _p in enumerate(ps):
if '-' in _p:
start, end = _p.split('-')
if end == 'end':
end = num_parts
parts_in_range = [str(part) for part in range(int(start), int(end) + 1)]
for part in parts_in_range:
if isinstance(bs, str):
chunks.append((meas, part, bs))
else:
chunks.append((meas, part, bs[_j]))
if isinstance(bs, str):
chunks.append((meas, _p, bs))
else:
chunks.append((meas, _p, bs[_j]))
# collect the beats for the addresses at the same measure and part
mp2bs = {}
for chunk in chunks:
key = (chunk[0], chunk[1])
if key not in mp2bs:
mp2bs[key] = [chunk[2]]
else:
mp2bs[key].append(chunk[2])
# combine the beats into one for each measure-part combo
slices = [(*mp, '@all') if '@all' in bs else (*mp, ''.join(set(bs))) for mp, bs in mp2bs.items()]
# sort by part number, then by measure so the slices are ordered by measure then part number
df = pd.DataFrame(slices, columns=['Measure', 'Part', 'Beat']).sort_values(['Measure', 'Part'])
mpost = df.Measure.unique()
ppost = ','.join(['+'.join(df.loc[df.Measure == _m, 'Part']) for _m in mpost])
bpost = ','.join(['+'.join(df.loc[df.Measure == _m, 'Beat']) for _m in mpost])
mpost = ','.join(mpost)
return '/'.join((mpost, ppost, bpost))
def _hr_helper(self, row, ngrams):
this_hr = row["Offset"]
ret = ngrams.loc[[this_hr]]
full_ema = self.emaAddresses(df=ret, mode='')
full_ema = full_ema.reset_index()
ema = full_ema['EMA']
return ema
def _ptype_ema_helper(self, row, ngrams):
# initialize dict and df
dictionary = {}
filtered_df = pd.DataFrame()
# get row values for offsets and voices
offsets = row['Offsets']
voices = row['Voices']
# make dict
for f, s in zip(offsets, voices):
if f not in dictionary:
dictionary[f] = []
dictionary[f].append(s)
# slice of ngrams corresponding to this point
short_ngrams = ngrams.loc[offsets]
# use dict values to build offset and column sets
for offset, voice_list in dictionary.items():
exclude_columns = ['[Superius]', 'Altus']
columns_to_replace = short_ngrams.columns.difference(voice_list)
# Replace the values with NaN
short_ngrams.loc[offset, columns_to_replace] = np.nan
short_ngrams.dropna(how='all', inplace=True)
if len(filtered_df) == 0:
filtered_df = short_ngrams
else:
result = pd.concat([filtered_df, short_ngrams])
result.drop_duplicates(inplace=True)
emas = self.emaAddresses(df=result, mode='')
complete_ema = self.combineEmaAddresses(emas)
return complete_ema
this_point = row["Offsets"]
ret = ngrams.loc[set(this_point)]
addresses = self.emaAddresses(df=ret, mode='')
full_ema = self.combineEmaAddresses(addresses)
return full_ema
def emaAddresses(self, df=None, mode=''):
'''
Return a df that's the same shape as the passed df. Currently only works for 1D ngrams,
like melodic ngrams. Specifically for melodic ngrams, you have to set mode='melodic'.
Here's an example of that workflow for an imported piece called `piece`.
***Example***
mel = piece.melodic()
ng = piece.ngrams(df=mel, n=4, offsets='both')
ema = piece.emaAddresses(df=ng, mode='melodic')
***
If you want the emaAddresses of a cvfs dataframe, you can set mode='cvfs' or mode='cadences'
and passing a dataframe to the df parameter is optional in this case. CVFS and cadences
have the same EMA addresses so the results will be the same with mode='cvfs' and
mode='cadences'.
'''
mode = mode.lower()
if isinstance(df, pd.DataFrame):
ret = df.copy()
if mode == 'melodic':
newCols = []
for i in range(len(ret.columns)):
part = ret.iloc[:, i].dropna()
notes = self.notes().iloc[:, i].dropna()
new_index = []
for (_first, _last) in part.index:
new_index.append((notes.loc[:_first].index[-2], _last))
part.index = pd.MultiIndex.from_tuples(new_index, names=part.index.names)
newCols.append(part)
ret = pd.concat(newCols, axis=1, sort=True)
elif mode.startswith('c'): # cvfs mode
ret = self.cvfs(keep_keys=True, offsets='both').copy()
ngrams = ret.iloc[:, len(self._getPartNames()):]
addresses = self.emaAddresses(df=ngrams, mode='')
if isinstance(df, pd.DataFrame) and ('First' in df.index.names and 'Last' in df.index.names):
return addresses
else:
uni = addresses.index.levels[-1].unique()
ret = pd.Series(index=uni, name='EMA').astype(str)
for un in uni:
val = self.combineEmaAddresses(addresses.loc[(slice(None), un)].to_list())
ret.at[un] = val
return ret
# hr mode--works with HR dataframe, adding ema address to each hr passage (= row).
# pass in output of hr = piece.homorhythm() as the df and set mode = 'hr'
elif mode.startswith('h'): # hr mode
if isinstance(df, pd.DataFrame):
hr = df
ngram_length = int(hr.iloc[0]['ngram_length'])
nr = self.notes()
dur = self.durations(df = nr)
ngrams = self.ngrams(df = dur, n = ngram_length, offsets = 'both', exclude=[])
hr = hr.reset_index()
hr['ema'] = hr.apply(lambda row: self._hr_helper(row, ngrams), axis=1)
hr.set_index(['Measure', 'Beat', 'Offset'], inplace=True)
return hr
# for ptypes output
# pass in output of p_types = piece.presentationTypes() as the df and set mode = 'p_types'
elif mode.startswith('p'): # p_type mode
if isinstance(df, pd.DataFrame):
p_types = df
ngram_length = len(p_types.iloc[0]['Soggetti'][0])
mel = self.melodic(end=False)
ngrams = self.ngrams(df = mel, offsets = 'both', n = ngram_length)
p_types['ema'] = p_types.apply(lambda row: self._ptype_ema_helper(row, ngrams), axis=1)
return p_types
if isinstance(df, pd.DataFrame):
if len(df) >= 1:
idf = ret.index.to_frame()
_measures = self.measures().iloc[:, 0]
measures = idf.map(lambda i: _measures.loc[:i].iat[-1])
_beats = self.beatIndex()
beats = idf.map(lambda i: _beats[i])
res = pd.concat([measures['First'], beats['First'], measures['Last'], beats['Last']], axis=1, sort=True)
res.columns = ['First Measure', 'First Beat', 'Last Measure', 'Last Beat']
ret = self.numberParts(ret)
res = pd.concat([res, ret], axis=1, sort=True)
res = res.apply(self._emaRowHelper, axis=1)
res.name = 'EMA'
return res
def _getBeatUnit(self):
'''
Return a dataframe of the duration of the beat for each time signature
object in the piece. The duration is expressed as a float where 1.0 is
a quarter note, 0.5 is an eighth note, etc. This is useful for
calculating the beat strength of notes and rests.
'''
tsigs = self._getM21TSigObjs()
tsigs.columns = self._getPartNames()
df = tsigs.map(lambda tsig: tsig.beatDuration.quarterLength, na_action='ignore')
return df
def beats(self):
'''
Return a table of the beat positions of all the notes and rests.
Beats are expressed as floats. The downbeat of each measure is 1.0, and
all other metric positions in a measure are given smaller numbers
approaching zero as their metric weight decreases. Results from this
method should not be sent to the regularize method.
'''
if 'Beats' not in self.analyses:
nr = self.notes()
nrOffs = nr.apply(lambda row: row.index)
ms = self.measures().apply(lambda row: row.index)
temp = pd.concat([ms, nr], axis=1, sort=True)
ms = temp.iloc[:, :len(ms.columns)].ffill()
ms = ms[nr.notnull()]
offFromMeas = nrOffs - ms
beatDur = self._getBeatUnit()
temp = pd.concat([beatDur, nr], axis=1, sort=True)
beatDur = temp.iloc[:, :len(beatDur.columns)].ffill()
beatDur = beatDur[nr.notnull()]
self.analyses['Beats'] = (offFromMeas / beatDur) + 1
return self.analyses['Beats']
def beatIndex(self):
'''
Return a series of the first valid value in each row of .beats().
This is useful for getting the beat position of a given timepoint (i.e.
index value) in the piece. Results from this method should not be sent to
the regularize method. You would use this method to lookup the beat
position of a given offset (timepoint) in a piece. Provided there is a
note or rest in any voice at that offset, the beatIndex results will
have a value at that index.
'''
if 'BeatIndex' not in self.analyses:
ser = self.beats().dropna(how='all').apply(lambda row: row.dropna().iat[0], axis=1)
self.analyses['BeatIndex'] = ser
return self.analyses['BeatIndex']
def detailIndex(self, df, measure=True, beat=True, offset=False, t_sig=False,
sounding=False, progress=False, lowest=False, highest=False, _all=False):
'''
Return the passed dataframe with a multi-index of any combination of the
measure, beat, offset, prevailing time signature, and progress towards
the end of the piece (0-1) in the index labels. At least one must be
chosen, and the default is to have measure and beat information, but no
other information. Here are all the boolean parameters that default to False,
but that you can set to true if you also want to see them:
* offset: row's offset (distance in quarter notes from beginning, 1.0 = one quarter note)
* t_sig: the prevailing time signature
* sounding: how many voices are sounding (i.e. not resting) at this point
* progress: 0-1 how far along in the piece this moment is, 0 = beginning, 1 = last attack onset
* lowest: the lowest sounding note at this moment
* highest: the highest sounding note at this moment
You can also pass _all=True to include all five types of index information.
'''
cols = [df]
names = []
if _all:
measure, beat, offset, t_sig, sounding, progress, lowest, highest = [True] * 8
if measure:
cols.append(self.measures().iloc[:, 0])
names.append('Measure')
if beat:
cols.append(self.beatIndex())
names.append('Beat')
if offset:
cols.append(df.index.to_series())
names.append('Offset')
if t_sig:
cols.append(self.timeSignatures().iloc[:, 0])
names.append('TSig')
if sounding:
cols.append(self.soundingCount())
names.append('Sounding')
if progress:
prog = (df.index / self.notes().index[-1]).to_series()
prog.index = df.index
cols.append(prog)
names.append('Progress')
if lowest:
cols.append(self.lowLine())
names.append('Lowest')
if highest:
cols.append(self.highLine())
names.append('Highest')
temp = pd.concat(cols, axis=1, sort=True)
temp2 = temp.iloc[:, len(df.columns):].ffill()
if measure:
temp2.iloc[:, 0] = temp2.iloc[:, 0].astype(int)
mi = pd.MultiIndex.from_frame(temp2, names=names)
ret = temp.iloc[:, :len(df.columns)]
ret.index = mi
ret.dropna(inplace=True, how='all')
ret.sort_index(inplace=True)
return ret
def di(self, df, measure=True, beat=True, offset=False, t_sig=False, sounding=False,
progress=False, lowest=False, highest=False, _all=False):
"""
Convenience shortcut for .detailIndex. See that method's documentation for instructions.
"""
return self.detailIndex(df=df, measure=measure, beat=beat, offset=offset, t_sig=t_sig,
sounding=sounding, progress=progress, lowest=lowest, highest=highest, _all=_all)
def _beatStrengthHelper(self, noteOrRest):
'''
Return the beat strength of a note or rest.
This follows the music21 conventions where the downbeat is equal to 1, and
all other metric positions in a measure are given smaller numbers approaching
zero as their metric weight decreases.
'''
if hasattr(noteOrRest, 'beatStrength'):
return noteOrRest.beatStrength
return noteOrRest
def beatStrengths(self):
'''
Returns a table of the beat strengths of all the notes and rests in
the piece. This follows the music21 conventions where the downbeat is
equal to 1, and all other metric positions in a measure are given
smaller numbers approaching zero as their metric weight decreases.
Results from this method should not be sent to the regularize method.
'''
if 'BeatStrength' not in self.analyses:
df = self._getM21ObjsNoTies().map(self._beatStrengthHelper)
self.analyses['BeatStrength'] = df
return self.analyses['BeatStrength']
def _getM21TSigObjs(self):
'''
Return a dataframe of the time signature objects in the piece.
This is useful for getting the prevailing time signature at any given
moment in the piece.
'''
if 'M21TSigObjs' not in self.analyses:
tsigs = []
for part in self._getFlatParts():
tsigs.append(pd.Series({ts.offset: ts for ts in part.getTimeSignatures()}))
df = pd.concat(tsigs, axis=1, sort=True)
self.analyses['M21TSigObjs'] = df
return self.analyses['M21TSigObjs']
def timeSignatures(self):
"""
Return a data frame containing the time signatures and their offsets.
This is useful for getting the prevailing time signature at any given
moment in the piece. The time signature is expressed as a string taken
from music21's .ratioString attribute. For example, 4/4 time is
expressed as "4/4", 3/4 time is expressed as "3/4", etc.
"""
if 'TimeSignature' not in self.analyses:
df = self._getM21TSigObjs()
df = df.map(lambda ts: ts.ratioString, na_action='ignore')
df.columns = self._getPartNames()
self.analyses['TimeSignature'] = df
return self.analyses['TimeSignature']
def measures(self):
"""
This method retrieves the offsets of each measure in each voice.
Measures are expressed as integers.
"""
if "Measure" not in self.analyses:
parts = self._getFlatParts()
partMeasures = []
for part in parts:
partMeasures.append(pd.Series({m.offset: m.measureNumber \
for m in part.makeMeasures().getElementsByClass(['Measure'])}))
df = pd.concat(partMeasures, axis=1, sort=True)
df.columns = self._getPartNames()
self.analyses["Measure"] = df
return self.analyses["Measure"]
def barlines(self):
"""
This method retrieves some of the barlines. It's not clear how music21
picks them, but this seems to get all the double barlines which helps
detect section divisions.
"""
if "Barline" not in self.analyses:
parts = self._getFlatParts()
partBarlines = []
for part in parts:
partBarlines.append(pd.Series({b.offset: b.type \
for b in part.getElementsByClass(['Barline'])}))
df = pd.concat(partBarlines, axis=1, sort=True)
df.columns = self._getPartNames()
self.analyses["Barline"] = df
return self.analyses["Barline"]
def soundingCount(self):
"""
Return a series with the number of parts that currently sounding.
This information is included the .cadences method so you can filter cadence
results based on how many voices are sounding at the time of the cadence.
It is also available in the .detailIndex method to add this information to
almost any dataframe CRIM-Intervals provides.
"""
if not 'SoundingCount' in self.analyses:
nr = self.notes().ffill()
df = nr[nr != 'Rest']
ser = df.count(axis=1)
ser.name = 'Sounding'
self.analyses['SoundingCount'] = ser
return self.analyses['SoundingCount']
def _zeroIndexIntervals(ntrvl):
'''
Change diatonic intervals so that they count the number of steps, i.e.
unison = 0, second = 1, etc.
'''
if ntrvl == 'Rest':
return ntrvl
val = int(ntrvl)
if val > 0:
return str(val - 1)
return str(val + 1)
def _harmonicIntervalHelper(row):
if hasattr(row.iat[1], 'isRest') and hasattr(row.iat[0], 'isRest'):
if row.iat[1].isRest or row.iat[0].isRest:
return 'Rest'
elif row.iat[1].isNote and row.iat[0].isNote:
return interval.Interval(row.iat[0], row.iat[1])
return np.nan
def _melodicIntervalHelper(row):
if hasattr(row.iat[0], 'isRest'):
if row.iat[0].isRest:
return 'Rest'
elif row.iat[0].isNote and hasattr(row.iat[1], 'isNote') and row.iat[1].isNote:
return interval.Interval(row.iat[1], row.iat[0])
return np.nan
def _melodifyPart(ser, end):
'''
Convert a series of music21 notes or rests to melodic intervals.