-
Notifications
You must be signed in to change notification settings - Fork 0
/
musicSearch.py
1359 lines (1046 loc) · 59 KB
/
musicSearch.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 __future__ import print_function
from music21 import stream, note, duration, interval, corpus
def hasNumber(inputString):
"""
# returns True if any of the char in the string is a digit
"""
return any(char.isdigit() for char in inputString)
def isNumber(inputString):
"""
# returns True if the string is a number
"""
try:
float(inputString)
return True
except ValueError:
return False
def stringToNotes(string):
"""
# input: string of note names, separated by spaces
# output: a stream with Note objects denoted by the string
#
# sharps are denoted by '#' and flats by '-'
# octaves and rhythm are not supported in this function
# see: stringToNotesWithOctave
#
# example string: 'A B C# D E-'
"""
s = stream.Stream() # create a new Stream
for charNum in range(0, len(string)-1): # for every character except the last one in string
# the '-1' is so charNum + 1 doesn't go out of bounds
# could probably change it to do a 'try catch'
if string[charNum] in 'ABCDEFGabcdefg': # if char is a note name
newNote = note.Note() # create new Note object
if string[charNum + 1] == '#' or string[charNum + 1] == '-': # if there's an accidental
newNote.pitch.name = string[charNum:charNum + 2] # define the pitch of the Note object with the accidental
charNum = charNum + 1 # advance the charNum 'pointer' forward to account for the accidental
else: # there's no accidental
newNote.pitch.name = string[charNum] # define the pitch of the Note object (no accidental)
s.append(newNote) # put the Note object into the Stream
if string[-1] in 'ABCDEFGabcdefg': #if the last character is a note name
newNote = note.Note() # create new Note object
newNote.pitch.name = string[-1] # pitch of the Note becomes the last character of string
s.append(newNote) # append the new Note into Stream
return s # return Stream
def stringToNotesWithOctave(string):
"""
# input: string of note names, separated by spaces
# output: a stream with Note objects denoted by the string
#
# sharps are denoted by '#' and flats by '-'
# octaves ARE supported in this function as opposed to stringToNotes
#
# example string: 'A3 B-3 C#4 D4 E4'
"""
s = stream.Stream() # create a new Stream
i = 0 # i is an integer that acts as a 'pointer' to the current char to be processed
while (i < len(string) - 1): # while there is still two or more characters to be processed
if string[i] in 'ABCDEFGabcdefg': # if the first character is a note name
newNote = note.Note() # create a new Note object
if string[i + 1] == '#' or string[i + 1] == '-': # if the next character is an accidental
newNote.pitch.name = string[i:i+3] # use all three characters to determine the pitch
# 1st: note name, 2nd: accidental, 3rd: octave
i = i + 3 # advance 'pointer' by three
else: # if there is no accidental
newNote.pitch.name = string[i:i+2] # use the two charactersto determine the pitch
i = i + 2 # advance 'pointer' by two
s.append(newNote) # append the Note object to Stream
else: # if the first character isn't a note name
i = i + 1 # skip
return s # return Stream
def stringToNotesRhythm(string):
"""
# input: string of note rhythms, separated by spaces
# output: a stream with Note objects denoted by the string
#
# sharps are denoted by '#' and flats by '-'
# octaves ARE supported in this function as opposed to stringToNotes
#
# example string: '8 8'
"""
#rhythms
s = stream.Stream()
strList = []
# going through string to add spaces to places that should have them
# putting the "processed" string in strList as a list of characters
for num in range(0, len(string)):
strList.append(string[num])
if string[num].isdigit():
if num == len(string) - 1:
continue
elif string[num + 1].isalpha():
strList.append(' ')
num += 1
elif string[num + 1].isdigit():
continue
elif string[num] == '.':
if num == len(string) - 1:
continue
elif string[num + 1].isalpha():
strList.append(' ')
num += 1
# else: do nothing
newString = ''.join(strList)
tokenList = newString.split() #tokenize the newString
for token in tokenList:
if token[1] == '#' or token[1] == '-':
i = 2
else:
i = 1
digits = 0
dots = 0
newNote = note.Note(token[0:i])
while (i < len(token) and token[i].isdigit()):
i = i + 1
digits = digits + 1
newNote.duration.type = duration.convertQuarterLengthToType(4. / int(token[i - digits:i]))
while (i < len(token) and token[i] == '.'):
i = i + 1
dots = dots + 1
newNote.duration.dots = dots
s.append(newNote)
return s
def contourToNotes(string):
"""
# input: string of Parson's Code for Melodic Contours
# see https://en.wikipedia.org/wiki/Parsons_code
#
# output: a stream of Notes with the given contour
#
#
# example string: '*dduurrdrruur'
"""
s = stream.Stream() # create new Stream
nute = note.Note('g') # does not matter what note this is
# we are going to create the contour by moving nute up and down
assert string[0] == '*'
s.append(nute) # append nute into Stream for first note
string = string[1:] # take only the significant parts i.e. everything BUT the *
for char in string:
nute = note.Note()
if char == 'u' or char == 'U':
nute.ps = nute.ps + 1 # raise the pitch of nute
elif char == 'd' or char == 'D':
nute.ps = nute.ps - 1 # lower the pitch of nute
elif char == 'r' or char == 'R':
pass # the chicken
else: # if char is not in 'uUdDrR'
continue # skip the char
s.append(nute) # append the note into Stream
return s # return Stream
def sortByMeasure(streamList):
"""
# input: a list of note excerpts to be sorted
# output: sorted list by measure number of the first note in excerpt
"""
return sorted(list, key = lambda x: x.notesAndRests[0].measureNumber)
def sortTupleByMeasure(tuplelist):
"""
# input: a list of tuples (note excerpts, partNumber it was from) to be sorted
# output: sorted list by measure number of the first note in note excerpt of the tuple
"""
return sorted(list, key = lambda x: x[0].notesAndRests[0].measureNumber)
def approxInterval(interval1, interval2):
"""
# input: two intervals
# output: True if the two intervals are 'approximately the same', False otherwise
#
# To be 'approximately the same', the direction of the intervals must match
# i.e. ascending intervals will never be the same as descending ones
# The 'function' of the interval must be the same. They are grouped as the following:
# 'steps': 2nds and 3rds
# 'perfect': 4ths and 5ths
# 'leaps': 6ths and 7ths
#
# A case can be made to equate 5ths and octaves, but has not been put into practice here yet
"""
# creation of the Interval objects
ascending2 = interval.GenericInterval('ascending second')
descending2 = interval.GenericInterval('descending second')
ascending3 = interval.GenericInterval('ascending third')
descending3 = interval.GenericInterval('descending third')
ascending4 = interval.GenericInterval('ascending fourth')
descending4 = interval.GenericInterval('descending fourth')
ascending5 = interval.GenericInterval('ascending fifth')
descending5 = interval.GenericInterval('descending fifth')
ascending6 = interval.GenericInterval('ascending sixth')
descending6 = interval.GenericInterval('descending sixth')
ascending7 = interval.GenericInterval('ascending seventh')
descending7 = interval.GenericInterval('descending seventh')
if interval1 == interval2:
return True
if interval1 == ascending2 or interval1 == ascending3:
if interval2 == ascending2 or interval2 == ascending3:
return True
if interval1 == descending2 or interval1 == descending3:
if interval2 == descending2 or interval2 == descending3:
return True
if interval1 == ascending4 or interval1 == ascending5:
if interval2 == ascending4 or interval2 == ascending5:
return True
if interval1 == descending4 or interval1 == descending5:
if interval2 == descending4 or interval2 == descending5:
return True
if interval1 == ascending6 or interval1 == ascending7:
if interval2 == ascending6 or interval2 == ascending7:
return True
if interval1 == descending6 or interval1 == descending7:
if interval2 == descending6 or interval2 == descending7:
return True
return False
def exactNoteSearch(score, motifPart, motifStart, motifEnd, notes = None, print_ = 0, octave = 1, show = 0):
"""
# input:
# score - the parsed score to search in
#
# motiPart - integer indicating the part in the score to grab the notes from
#
# motifStart - integer indicating first note of the query
#
# motifEnd - integer indicating the note after the last note of query
#
# notes - string to be converted to a Stream with Notes via stringToNotes()
# The given Stream will be used to find matches instead.
# If notes isn't None, then motifPart, motifStart, and motifEnd will be ignored.
# Default value is None
#
# print_ - If True, print extra information that may be useful in the terminal
# Default value is False (0)
#
# octave - If True, match algorithm will ignore octaves, only matching note names
# If False, match algorithm will match both octaves and note names
# Default value is True
#
# show - If True, color matches to score, and use music21's show('musicxml') to visualize score
# Default value is False
#
# output: comparing the motif/theme against the score,
# returns a list of matching Streams, excerpted from the score
# A stream is a match iff all the notes match both in pitch and rhythm to the given motif/theme
#
"""
print ('\nSearching by exact note...')
flatParts = []
for part in score.parts:
flatParts.append(part.flat) # flatten each Parts in the score
noteParts = []
for part in flatParts: # extract notes and rests for each flattened Parts
noteParts.append(part.notesAndRests)
if notes != None: # if there exists a string for notes
print ('\tCustom motif used')
# a very crude way of differentiating strings with octave info and those without
if hasNumber(notes): # if the string has numbers
motif = stringToNotesWithOctave(notes) # convert string to Notes via stringToNotesWithOctave*()
else: # if the string has no numbers
motif = stringToNotes(notes) # convert string to Notes via stringToNotes()
else: # if notes == None
print ('\tMotif defined from score')
motif = flatParts[motifPart].notes[motifStart:motifEnd] # get match query from score
if print_:
print ('\tMotif is defined as follows:')
for thisNote in motif:
print ('\t\t' + thisNote.nameWithOctave + ' ' + thisNote.duration.type + ' note')
print()
matchList = [] # list of matches found
matchTupleList = [] # tuple of (Stream match, integer listNum)
matchQ = False
for listNum in range(0, len(noteParts)): # for all parts in the piece
for noteNum in range(0, len(noteParts[listNum]) - len(motif)): # for all notes in the part
for motifNoteNum in range(0, len(motif)): # for all notes in the motif
if octave: # different octaves are acceptable
if motif[motifNoteNum].name == noteParts[listNum][noteNum + motifNoteNum].name:
#matching pitch (not by octave)
if motif[motifNoteNum].duration.type == noteParts[listNum][noteNum + motifNoteNum].duration.type:
#we're also matching length
#might not be a good idea to usenote.type, since it groups all complex into 'complex'
if motifNoteNum == len(motif) - 1: # if this is the last note to match
matchQ = True # flag as a match
else: # note types are different, match failed
break
else: # note pitches are different, match failed
break
else: # notes with different octaves are different
if motif[motifNoteNum] == noteParts[listNum][noteNum + motifNoteNum]: # if note1 = note2
if motifNoteNum == len(motif) - 1:
matchQ = True
else:
break
if matchQ: # if after the forloops, matchQ is True
match = noteParts[listNum][noteNum : noteNum + len(motif)] # get the matching notes from the score
match.insert(0, flatParts[listNum].getClefs().elements[0]) # get the clef of the respective part
# NOTE! This will fail to give the correct clef if the clef changes in the middle of the piece!
# this is literally getting the first clef of the Part where the match is found
# works for Art of the Fugue though
matchList.append(match) # insert match into matchList
matchTuple = (match, listNum) # define matchTuple as (Stream, integer)
matchTupleList.append(matchTuple) # insert matchTuple into its separate list
matchQ = False # reset the match flag
print (str(len(matchTupleList)) + ' match(es) found:')
for entry in matchTupleList: # for all the tuples in matchtupleList
print ('\tPart ' + str(entry[1]) + ' from measure ' + str(entry[0].notes[0].measureNumber), end = ' ')
print ('to ' + str(entry[0].notes[-1].measureNumber))
if show:
score = colorScore(score, matchTupleList) # color the score with the matches
score.show('musicxml') # show() the score in musicxml
return matchList #should be list of exact matches
def exactPitchSearch(score, motifPart, motifStart, motifEnd, notes = None, print_ = 0, octave = 1, show = 0):
"""
# input:
# score - the parsed score to search in
#
# motiPart - integer indicating the part in the score to grab the notes from
#
# motifStart - integer indicating first note of the query
#
# motifEnd - integer indicating the note after the last note of query
#
# notes - string to be converted to a Stream with Notes via stringToNotes()
# The given Stream will be used to find matches instead.
# If notes isn't None, then motifPart, motifStart, and motifEnd will be ignored.
# Default value is None
#
# print_ - If True, print extra information that may be useful in the terminal
# Default value is False (0)
#
# octave - If True, match algorithm will ignore octaves, only matching note names
# If False, match algorithm will match both octaves and note names
# Default value is True
#
# show - If True, color matches to score, and use music21's show('musicxml') to visualize score
# Default value is False
#
# output: comparing the motif/theme against the score,
# returns a list of matching Streams, excerpted from the score
# A stream is a match iff all the notes match both in pitch (ignores rhythm/duration) to the given motif/theme
#
"""
# if notes != None, use notes as motif, and ignore motifPart, motifStart, and motifEnd
print ('\nSearching by exact pitch...')
flatParts = []
for part in score.parts:
flatParts.append(part.flat) # flatten each Parts in the score
noteParts = []
for part in flatParts: # extract notes and rests for each flattened Parts
noteParts.append(part.notesAndRests)
if notes != None: # if there exists a string for notes
print ('\tCustom motif used')
# a very crude way of differentiating strings with octave info and those without
if hasNumber(notes):
motif = stringToNotesWithOctave(notes)
else:
motif = stringToNotes(notes)
else: # if notes == None
print ('\tMotif defined from score')
motif = flatParts[motifPart].notes[motifStart:motifEnd]
if print_:
print ('\tMotif is defined as follows:')
for thisNote in motif:
print ('\t\t' + thisNote.nameWithOctave + ' ' + thisNote.duration.type + ' note')
print ('')
matchList = []
matchTupleList = []
matchQ = False
for listNum in range(0, len(noteParts)): # for all parts in the piece
for noteNum in range(0, len(noteParts[listNum]) - len(motif)): # for all notes in the part
for motifNoteNum in range(0, len(motif)): # for all notes in the motif
if motif[motifNoteNum].name == noteParts[listNum][noteNum + motifNoteNum].name:
#if the note names are the same
if octave: #allow different octaves
if motifNoteNum == len(motif) - 1:
matchQ = True
else: #don't allow different octaves
if motif[motifNoteNum].octave == noteParts[listNum][noteNum + motifNoteNum].octave:
#make sure octaves work
if motifNoteNum == len(motif) - 1:
matchQ = True
else:
break
if matchQ:# if after the forloops, matchQ is True
match = noteParts[listNum][noteNum : noteNum + len(motif)] # get the matching notes from the score
match.insert(0, flatParts[listNum].getClefs().elements[0]) # get the clef of the respective part
# NOTE! This will fail to give the correct clef if the clef changes in the middle of the piece!
# this is literally getting the first clef of the Part where the match is found
# works for Art of the Fugue though
matchList.append(match) # insert match into matchList
matchTuple = (match, listNum) # define matchTuple as (Stream, integer)
matchTupleList.append(matchTuple) # insert matchTuple into its separate list
matchQ = False # reset the match flag
print (str(len(matchTupleList)) + ' match(es) found:')
for entry in matchTupleList:
print ('\tPart %d from measure %d to %d' % (entry[1], entry[0].notes[0].measureNumber, entry[0].notes[-1].measureNumber))
if show:
score = colorScore(score, matchTupleList) # color the score with the matches
score.show('musicxml') # show() the score in musicxml
return matchList #should be list of exact matches
def exactRhythmSearch(score, motifPart, motifStart, motifEnd, rhythm = None, print_ = 0, context = 0, sort = 'part', show = 0):
"""
# input:
# score - the parsed score to search in
#
# motiPart - integer indicating the part in the score to grab the notes from
#
# motifStart - integer indicating first note of the query
#
# motifEnd - integer indicating the note after the last note of query
#
# rhythm - string to be converted to a Stream with Notes via stringToRhythm()
# The given Stream will be used to find matches instead.
# If rhythm isn't None, then motifPart, motifStart, and motifEnd will be ignored.
# Default value is None
#
# print_ - If True, print extra information that may be useful in the terminal
# Default value is False (0)
#
# context - If True, matches will include the 3 notes before or after the actual match
#
# sort - determines the sorting algorithm for printing matches in terminal
# Accepts either 'part' or 'measure'
# Default value is 'part'
#
# show - If True, color matches to score, and use music21's show('musicxml') to visualize score
# Default value is False
#
# output: comparing the motif/theme against the score,
# returns a list of matching Streams, excerpted from the score
# A stream is a match iff all the notes match both in rhythm (not pitch) to the given motif/theme
#
"""
print ('\nSearching by rhythm...')
flatParts = []
for part in score.parts:
flatParts.append(part.flat) # flatten each Parts in the score
noteParts = []
for part in flatParts: # extract notes and rests for each flattened Parts
noteParts.append(part.notesAndRests)
if rhythm != None: # if there exists a string for rhythm
motif = stringToNotesRhythm(rhythm)
if print_:
print('Searching from string')
else: # if rhythm == None
motif = flatParts[motifPart].notes[motifStart:motifEnd]
if print_:
print('Motif taken from score')
if print_:
for note in motif:
print('\t%s note' % (note.duration.fullName))
print('')
matchList = []
matchTupleList = []
matchQ = False
for listNum in range(0, len(noteParts)): # for all parts in the piece
for noteNum in range(0, len(noteParts[listNum]) - len(motif)): # for all notes in the part
for motifNoteNum in range(0, len(motif)): # for all notes in the motif
if motif[motifNoteNum].duration.quarterLength == noteParts[listNum][noteNum + motifNoteNum].duration.quarterLength:
# if the duration (in quarter length) of the first note is the same as that of the second:
if motifNoteNum == len(motif) - 1: # if this is the last notes to be matched
matchQ = True # switch match flag to True
else: # if duration doesn't equate
break
if matchQ: # if after the forloops, matchQ is True
match = noteParts[listNum][noteNum : noteNum + len(motif)] # get the matching notes from the score
match.insert(0, flatParts[listNum].getClefs().elements[0]) # get the clef of the respective part
# NOTE! This will fail to give the correct clef if the clef changes in the middle of the piece!
# this is literally getting the first clef of the Part where the match is found
# works for Art of the Fugue though
matchList.append(match) # insert match into matchList
matchTuple = (match, listNum) # define matchTuple as (Stream, integer)
matchTupleList.append(matchTuple) # insert matchTuple into its separate list
matchQ = False # reset the match flag
print(str(len(matchTupleList)) + ' match(es) found:')
if sort == 'part':
print('Sorting by parts:')
elif sort == 'measure':
print('Sorting by measures: ')
matchList = sortByMeasure(matchList) # sort matchList by measure via sortByMeasure()
matchTupleList = sortTupleByMeasure(matchTupleList) # sort matchTupleList via sortTupleByMeasure()
for entry in matchTupleList: # print all the matches found
print('\tPart %d from measure %d to %d' % (entry[1],entry[0].notes[0].measureNumber,entry[0].notes[-1].measureNumber))
if show:
score = colorScore(score, matchTupleList) # color the score with the matches
score.show('musicxml') # show() the score in musicxml
return matchList #should be list of exact matches
def exactIntervalSearch(score, motifPart, motifStart, motifEnd, notes = None, print_ = 0, context = 0, show = 0):
"""
# input:
# score - the parsed score to search in
#
# motiPart - integer indicating the part in the score to grab the notes from
#
# motifStart - integer indicating first note of the query
#
# motifEnd - integer indicating the note after the last note of query
#
# notes - string to be converted to a Stream with Notes via stringToNotes()
# The given Stream will be used to find matches instead.
# If notes isn't None, then motifPart, motifStart, and motifEnd will be ignored.
# Default value is None
#
# print_ - If True, print extra information that may be useful in the terminal
# Default value is False (0)
#
# context - If True, matches will include the 3 notes before or after the actual match
# Default value is False
#
# show - If True, color matches to score, and use music21's show('musicxml') to visualize score
# Default value is False
#
# output: comparing the motif/theme against the score,
# returns a list of matching Streams, excerpted from the score
# A Stream is a match iff all the intervals of the Stream match that of the motif
#
"""
print('\nSearching by exact intervals...')
flatParts = []
for part in score.parts:
flatParts.append(part.flat) # flatten each Parts in the score
noteParts = []
for part in flatParts: # extract notes and rests for each flattened Parts
noteParts.append(part.notesAndRests)
if notes != None: # if there exists a string for notes
print('\tCustom motif used')
# a very crude way of differentiating strings with octave info and those without
if hasNumber(notes):
motif = stringToNotesWithOctave(notes)
else:
motif = stringToNotes(notes)
else: # if notes == None
print('\tMotif taken from score')
motif = flatParts[motifPart].notes[motifStart:motifEnd]
mIntervalList = []
matchList = []
matchTupleList = []
if print_:
print('Matching the following intervals:')
for num in range(0, len(motif) - 1):
mIntervalList.append(interval.notesToChromatic(motif[num], motif[num+1]))
if print_:
print('\t' + str(mIntervalList[num]))
# the actual checking
matchQ = False; # initialization of the match flag
i = 0 # i and j are both used for context (see below)
j = 0
for listNum in range(0, len(noteParts)): # for all parts in the piece
for noteNum in range(0, len(noteParts[listNum]) - len(mIntervalList)): # for all notes in the part
for mIntervalNum in range(0, len(mIntervalList)): # for all notes in the motif
if noteParts[listNum][noteNum + mIntervalNum].isNote:
if noteParts[listNum][noteNum + mIntervalNum + 1].isNote : #check if both notes are notes at all
#if yes, make interval of this and next note, and use that to compare with motif
intervalCandidate = interval.notesToChromatic(noteParts[listNum][noteNum + mIntervalNum], noteParts[listNum][noteNum + mIntervalNum + 1])
else: # if not, break
#matchQ == False
break
if (intervalCandidate == mIntervalList[mIntervalNum]):
if mIntervalNum == len(mIntervalList) - 1:
matchQ = True
else:
break #candidate interval =/= motif interval
if matchQ: #if intervalCandidate matches motif
if context: # getting the closest three surrounding notes for the match
previousNote = noteParts[listNum][noteNum].previous() # previousNote = the element before the first note of the match
nextNote = noteParts[listNum][noteNum + len(mIntervalList) + 1].next()
# nextNote = the element after the last note of the match
for num in range(0, 3): # for 3 times
if 'Barline' in previousNote.classes: # if the previousNote is a barline
num = num - 1 # ignore it (move the pointer num back)
elif 'note' in previousNote.classes or 'rest' in previousNote.classes: # if previousNote is a note or rest
previousNote = previousNote.previous() # move previousNote to the previous note of the original previousNote
i = i + 1 # increment i
else : break # if previousNote is neither barline nor note, break
for num in range(0, 3):
if 'Barline' in nextNote.classes: # if the nextNote is a barline
num = num - 1 # ignore it (move the pointer num back)
elif 'note' in nextNote.classes or 'rest' in nextNote.classes:# if nextNote is a note or rest
nextNote = nextNote.next() # move nextNote to the next note of the original nextNote
j = j + 1 # increment j
else : break # if nextNote is neither barline nor note, break
match = noteParts[listNum][noteNum - i: noteNum + len(mIntervalList) + 1 + j]
# match takes in also i notes before and j notes after match
match.insert(0, flatParts[listNum].getClefs().elements[0]) # get the clef of the respective part
# NOTE! This will fail to give the correct clef if the clef changes in the middle of the piece!
# this is literally getting the first clef of the Part where the match is found
# works for Art of the Fugue though
matchTuple = (match, listNum)
matchList.append(match)
matchTupleList.append(matchTuple)
i = 0 # reset i, j, and matchQ
j = 0
matchQ = False
if (print_):
print('\nMATCHES:')
for num in range(0,len(matchList)): # print out all the elements within the matches
print('Match #' + str(num))
print(matchList[num])
matchList[num].show('text')
print('')
print(str(len(matchTupleList)) + ' match(es) found:')
for matchTuple in matchTupleList: # print all the matches found
print('\tPart ' + str(matchTuple[1]) + ' from measure ' + str(matchTuple[0].notes[0].measureNumber), end = ' ')
print('to ' + str(matchTuple[0].notes[-1].measureNumber))
if show:
score = colorScore(score, matchTupleList) # color the score with the matches
score.show('musicxml') # show() the score in musicxml
return matchList
def genericIntervalSearch(score, motifPart, motifStart, motifEnd,
notes = None, print_ = 0, approx = 0, context = 0,
sort = 'part', show = 0, inverse = 0, retrograde = 0):
"""
# input:
# score - the parsed score to search in
#
# motiPart - integer indicating the part in the score to grab the notes from
#
# motifStart - integer indicating first note of the query
#
# motifEnd - integer indicating the note after the last note of query
#
# notes - string to be converted to a Stream with Notes via stringToNotes()
# The given Stream will be used to find matches instead.
# If notes isn't None, then motifPart, motifStart, and motifEnd will be ignored.
# Default value is None
#
# print_ - If True, print extra information that may be useful in the terminal
# Default value is False (0)
#
# approx - If True, match by approxInterval() instead of music21.genericInterval()
# Default value is False
#
# context - If True, matches will include the 3 notes before or after the actual match
# Default value is False
#
# sort - determines the sorting algorithm for printing matches in terminal
# Accepts either 'part' or 'measure'
# Default value is 'part'
#
# show - If True, color matches to score, and use music21's show('musicxml') to visualize score
# Default value is False
#
# inverse - If True, finds matches for inverses as well
# Program will color inverse matches blue for visualization
# Default value is False
#
# retrograde - Unimplemented.
# To be made into a parameter that would allow searches for retrograde melody.
#
# output: comparing the motif/theme against the score,
# returns a list of matching Streams, excerpted from the score
# A Stream is a match iff all the generic intervals of the Stream matches that of the motif
#
"""
print('\nSearching by generic intervals...')
flatParts = []
for part in score.parts:
flatParts.append(part.flat) # flatten each Parts in the score
noteParts = []
for part in flatParts: # extract notes and rests for each flattened Parts
noteParts.append(part.notesAndRests)
if notes != None: # if there exists a string for notes
print('\tCustom motif used')
# a very crude way of differentiating strings with octave info and those without
if hasNumber(notes):
motif = stringToNotesWithOctave(notes)
else:
motif = stringToNotes(notes)
else: # if notes == None
print('\tMotif taken from score')
motif = flatParts[motifPart].notes[motifStart:motifEnd]
mIntervalList = [] # list of intervals in the motif
matchList = []
matchTupleList = []
inverseMatchList = []
inverseMatchTupleList = []
currentlyMatching = 'none'
if print_:
print('Matching the following intervals:')
for num in range(0, len(motif) - 1):
mIntervalList.append(interval.notesToGeneric(motif[num], motif[num+1]))
if print_:
print('\t' + str(mIntervalList[num]))
# the actual checking
matchQ = False;
i = 0
j = 0
for listNum in range(0, len(noteParts)): # for all parts in the piece
for noteNum in range(0, len(noteParts[listNum]) - len(mIntervalList)): # for all notes in the part
for mIntervalNum in range(0, len(mIntervalList)): # for all notes in the motif
if noteParts[listNum][noteNum + mIntervalNum].isNote:
if noteParts[listNum][noteNum + mIntervalNum + 1].isNote : #check if both notes are notes at all
#if yes, make interval of this and next note, and use that to compare with motif
intervalCandidate = interval.notesToGeneric(noteParts[listNum][noteNum + mIntervalNum], noteParts[listNum][noteNum + mIntervalNum + 1])
else: # if not, break
#matchQ == False
break
if mIntervalNum == 0: # when matching the first interval
if intervalCandidate == mIntervalList[mIntervalNum]: # if first interval match
currentlyMatching = 'regular'
elif inverse and intervalCandidate.reverse() == mIntervalList[mIntervalNum]: # if intervals are inverted
currentlyMatching = 'inverse'
elif approx:
if approxInterval(intervalCandidate, mIntervalList[mIntervalNum]):
currentlyMatching = 'regular'
elif inverse and approxInterval(intervalCandidate.reverse(), mIntervalList[mIntervalNum]):
currentlyMatching = 'inverse'
else:
currentlyMatching = 'none'
break
else: # if intervals don't match
currentlyMatching = 'none' # reset currentlyMatching
break
if mIntervalNum == len(mIntervalList) - 1: # if matching the last interval
matchQ = True
elif (intervalCandidate == mIntervalList[mIntervalNum]): # if interval matches
if currentlyMatching == 'regular':
if mIntervalNum == len(mIntervalList) - 1: # if matching last interval
matchQ = True
else: # currentlyMatching != 'regular'
currentlyMatching = 'none' # reset currentlyMatching
break
elif inverse and intervalCandidate.reverse() == mIntervalList[mIntervalNum]:
# if interval is inverted
if currentlyMatching == 'inverse':
if mIntervalNum == len(mIntervalList) - 1: # if matching last interval
matchQ = True
else:
currentlyMatching = 'none' # reset currentlyMatching
break
elif approx:
if approxInterval(intervalCandidate, mIntervalList[mIntervalNum]):
# if the two intervals are approximately the same (see approxInterval())
if currentlyMatching == 'regular':
if mIntervalNum == len(mIntervalList) - 1: # if matching last interval
matchQ = True
else:
currentlyMatching = 'none' # reset currentlyMatching
break
elif inverse and approxInterval(intervalCandidate.reverse(), mIntervalList[mIntervalNum]):
# if the inverted interval of one is approximately the same as the other (see approxInterval())
if currentlyMatching == 'inverse':
if mIntervalNum == len(mIntervalList) - 1: # if matching last interval
matchQ = True
else:
currentlyMatching = 'none' # reset currentlyMatching
break
else:
break
else:
break #candidate interval != motif interval
if matchQ: #if intervalCandidate matches motif
if context: # getting the closest three surrounding notes for the match
previousNote = noteParts[listNum][noteNum].previous() # previousNote = the element before the first note of the match
nextNote = noteParts[listNum][noteNum + len(mIntervalList) + 1].next()
# nextNote = the element after the last note of the match
for num in range(0, 3): # for 3 times
if 'Barline' in previousNote.classes: # if the previousNote is a barline
num = num - 1 # ignore it (move the pointer num back)
elif 'note' in previousNote.classes or 'rest' in previousNote.classes: # if previousNote is a note or rest
previousNote = previousNote.previous() # move previousNote to the previous note of the original previousNote
i = i + 1 # increment i
else : break # if previousNote is neither barline nor note, break
for num in range(0, 3):
if 'Barline' in nextNote.classes: # if the nextNote is a barline
num = num - 1 # ignore it (move the pointer num back)
elif 'note' in nextNote.classes or 'rest' in nextNote.classes:# if nextNote is a note or rest
nextNote = nextNote.next() # move nextNote to the next note of the original nextNote
j = j + 1 # increment j
else : break # if nextNote is neither barline nor note, break
match = noteParts[listNum][noteNum - i: noteNum + len(mIntervalList) + 1 + j]
match.insert(0, flatParts[listNum].getClefs().elements[0]) # get the clef of the respective part
# NOTE! This will fail to give the correct clef if the clef changes in the middle of the piece!
# this is literally getting the first clef of the Part where the match is found
# works for Art of the Fugue though
matchTuple = (match, listNum)
if currentlyMatching == 'regular':
matchList.append(match)
matchTupleList.append(matchTuple)
elif inverse and currentlyMatching == 'inverse':
inverseMatchList.append(match)
inverseMatchTupleList.append(matchTuple)
i = 0 # i, j, matchQ, and currentlyMatching
j = 0
matchQ = False
currentlyMatching = 'none'