/
gatherAccidentals.py
286 lines (237 loc) · 10.3 KB
/
gatherAccidentals.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
# -*- coding:utf-8 -*-
#--------------------------------------------------------
# Name: gatherAccidentals.py
# Purpose: Demo for music21 documentation
#
# Authors: Hugh Zabriskie
#
# Copyright: Copyright © 2015, 2018 Michael Scott Cuthbert and the music21 Project
# License: BSD or LGPL, see license.txt
#--------------------------------------------------------
'''
Have you ever wondered whether Bach uses more sharps than flats in the Chorales? With just a
few lines of code, music21 allows you to quickly answer this question.
Defined below is two functions that can solve this question. getAccidentalCount() combs through
a score and returns of dictionary containing a tally of each type of accidental found in the input
score (a music21.stream.Score object). getAccidentalCountSum() is simply a helpful extension of
getAccidentalCount() and is meant for counting accidentals in a batch of scores.
These tallies are dictionaries. Dictionaries are ideal for this
situation since they are simple and
mutable data structures that can associate each type of accidental
with a positive integer corresponding
to the number of occurrences of that accidental.
Both getAccidentalCount() and getAccidentalCountSum()
return a dictionary designed in this way. We use _initializeTally()
to generate the initial dictionary and
_excludeZeros() after searching the score to remove accidentals
from the dictionary that were not found at all.
The purpose of this is to simplify the data structure by removing
keys for uncommon accidentals (i.e. the triple-
sharp and the quadruple-flat). However, both functions have an
excludeZeros option (default: True) that allows you
to keep all accidentals in the dictionary regardless of the number of occurrences.
How does getAccidentalCount work? Well, it first creates our tally object,
which will be updated by incrementing the
appropriate key that corresponds to the newly found accidental.
As a basic validation check, we can check that our
input score is in a fact a music21.stream.Stream object,
and if it isn't we throw an exception. Next, we "flatten" the
score and extract a list of notes using music21.stream.Stream.flat
and music21.stream.Stream.notes. Finally, the loop
in getAccidentalCount() simply iterates though the notes in the work
and updates the tally object each time it comes
across an accidental. Interestingly, we are not simply iterating through notes.
The .notes method also gathers chords,
and indeed we do find chords within a voice in some of the Chorales,
so we must account for that. The chord is then
de-constructed into each of its pitches, and the pitches are then checked
for accidentals with pitch.accidental.
Look at the bottom of the tests to see how these functions are used to count
the total accidentals in the Bach Chorales.
Based on this demo, can you figure out how to determine how many accidentals
occur on the beat versus off the beat? How
is it similar to the demo below? What are your corner cases?
Here's some inspiration:
"Some art is off the beat, but 'Mostart' is on the beat."
'''
from music21 import exceptions21
from music21 import stream
from music21 import note
from music21 import pitch
from music21 import corpus
import unittest
#--------------------------------------------------------
def getAccidentalCount(score, includeNonAccidentals=False, excludeZeros=True):
'''
Given a score, return a dictionary with keys as accidentals and values corresponding to
the number of occurrences of each accidental.
The possible accidentals are listed in pitch.Accidental.listNames().
For the sake of brevity, any accidental not found at all will be deleted
from the dictionary before being returned. This can be prevented by setting
excludeZeros to False.
Optionally you can count for notes without accidentals as
'natural' if includeNonAccidentals = True.
>>> from pprint import pprint
>>> from music21 import *
>>> s1 = stream.Stream()
>>> getAccidentalCount(s1)
{}
>>> s2 = stream.Stream()
>>> note1 = note.Note("C4")
>>> note2 = note.Note("C#4")
>>> note3 = note.Note("D-4")
>>> for note in [note1, note2, note3]:
... s2.append(note)
>>> pprint(getAccidentalCount(s2))
{'flat': 1, 'sharp': 1}
>>> pprint(getAccidentalCount(s2, True))
{'flat': 1, 'natural': 1, 'sharp': 1}
>>> s = corpus.parse('bach/bwv66.6')
>>> getAccidentalCount(s)
{'sharp': 87}
'''
# check for non-streams
if not score.isStream:
raise GatherAccidentalsException("Input score must be a music21.stream.Stream object")
notes = score.flat.notes
tally = _initializeTally()
for obj in notes:
if obj.isChord: # react to chords
plist = obj.pitches
elif obj.isNote:
plist = [obj.pitch]
for p in plist:
accidental = p.accidental
if accidental is None:
if includeNonAccidentals:
tally['natural'] +=1
continue
tally[accidental.name] += 1
return _deleteZeros(tally, excludeZeros)
#--------------------------------------------------------
def getAccidentalCountSum(scores, includeNonAccidentals=False, excludeZeros=True):
'''
An extension of getAccidentalCount(). Given a list of scores, return an AccidentalSum
containing a tally of accidentals for all scores in the list.
>>> from pprint import pprint
>>> s1 = stream.Stream()
>>> s1.append(note.Note('C4'))
>>> s2 = stream.Score() # all types of streams are valid
>>> s2.append(note.Note('C#4'))
>>> getAccidentalCountSum([s1, s2])
{'sharp': 1}
>>> pprint(getAccidentalCountSum([s1, s2], True))
{'natural': 1, 'sharp': 1}
>>> s3 = corpus.parse('bach/bwv7.7')
>>> s4 = corpus.parse('bach/bwv66.6')
>>> pprint(getAccidentalCountSum([s3, s4], True))
{'natural': 324, 'sharp': 195}
'''
tally = _initializeTally()
for score in scores:
if not score.isStream:
raise exceptions21.Music21Exception("score must be a stream object")
scoreTally = getAccidentalCount(score, includeNonAccidentals, False)
# dict.update() won't suffice; list() for Python v3
for k in list(scoreTally.keys()):
tally[k] += scoreTally[k]
return _deleteZeros(tally, excludeZeros)
#--------------------------------------------------------
# HELPER METHODS
def _initializeTally():
'''
Private method.
TODO: change to pitch.Accidental.listNames()
>>> accidentalTally = _initializeTally()
>>> from pprint import pprint as pp
>>> pp(accidentalTally)
{'double-flat': 0,
'double-sharp': 0,
'flat': 0,
'half-flat': 0,
'half-sharp': 0,
'natural': 0,
'one-and-a-half-flat': 0,
'one-and-a-half-sharp': 0,
'quadruple-flat': 0,
'quadruple-sharp': 0,
'sharp': 0,
'triple-flat': 0,
'triple-sharp': 0}
'''
tally = dict.fromkeys(pitch.Accidental.listNames(), 0)
return tally
def _deleteZeros(tally, excludeZeros):
'''
Private method.
Searches the tally for keys with values of 0 and removes them.
The updated tally is then returned.
Usually this involves deleting the triple-flats and quadruple-sharps.
>>> from pprint import pprint
>>> dict = {'a': 5, 'b': 3, 'c': 0}
>>> pprint(_deleteZeros(dict, True))
{'a': 5, 'b': 3}
'''
if excludeZeros:
for k in list(tally.keys()):
if tally[k] is 0:
del tally[k]
return tally
#--------------------------------------------------------
class GatherAccidentalsException(exceptions21.Music21Exception):
pass
#--------------------------------------------------------
class Test(unittest.TestCase):
def runTest(self):
pass
def testGetAccidentalCountBasic(self):
s = stream.Stream()
self.assertEqual(len(s.flat.notes), 0) # the stream should be empty
self.assertEqual(getAccidentalCount(s), {})
def testGetAccidentalCountIntermediate(self):
s = stream.Stream()
s.append(note.Note("C4")) # no accidental
s.append(note.Note("C#4")) # sharp
s.append(note.Note("D-4")) # flat
self.assertEqual(getAccidentalCount(s), {'flat': 1, 'sharp': 1})
self.assertEqual(getAccidentalCount(s, True), {'flat': 1, 'sharp': 1, 'natural': 1})
note4 = note.Note("C4")
self.assertIsNone(note4.pitch.accidental)
note4.pitch.accidental = pitch.Accidental('natural') # add a natural accidental
s.append(note4)
self.assertEqual(getAccidentalCount(s), {'flat': 1, 'sharp': 1, 'natural': 1})
def testGetAccidentalCountAdvanced(self):
s = corpus.parse('bach/bwv7.7')
tally = getAccidentalCount(s)
self.assertEqual(tally, {'sharp': 108, 'natural': 7})
tally = getAccidentalCount(s, True)
self.assertEqual(tally, {'sharp': 108, 'natural': 246})
totalNotes = len(s.flat.notes)
self.assertEqual(totalNotes, tally['sharp'] + tally['natural'])
def testGetAccidentalCountSumBasic(self):
s1 = stream.Stream()
self.assertEqual(getAccidentalCountSum([s1]), {})
def testGetAccidentalCountSumIntermediate(self):
s1 = stream.Stream()
s2 = stream.Stream()
s2.append(note.Note('D-2'))
s2.append(note.Note('F#5'))
self.assertEqual(getAccidentalCountSum([s1, s2]), {'flat': 1, 'sharp': 1})
def testGetAccidentalCountSumAdvanced(self):
s1 = corpus.parse('bach/bwv7.7')
s2 = corpus.parse('bach/bwv66.6')
totalNotes = len(s1.flat.notes) + len(s2.flat.notes)
tally = getAccidentalCountSum([s1, s2], True)
self.assertEqual(tally, {'sharp': 195, 'natural': 324})
self.assertEqual(totalNotes, tally['sharp'] + tally['natural'])
class TestSlow(unittest.TestCase):
def runTest(self):
pass
def testAccidentalCountBachChorales(self):
# the total number of accidentals in the Bach Chorales
chorales = list( corpus.chorales.Iterator() )
self.assertEqual(getAccidentalCountSum(chorales, True),
{'double-sharp': 4, 'flat': 7886, 'natural': 79869, 'sharp': 14940})
if __name__ == "__main__":
import music21
music21.mainTest(Test, 'moduleRelative') # replace 'Test' with 'TestSlow' to test it on all 371 Bach Chorales.