Skip to content

Commit

Permalink
Merge pull request #416 from cuthbertLab/lint_figured_bass
Browse files Browse the repository at this point in the history
Lint and add TypeHints to FiguredBass
  • Loading branch information
mscuthbert committed Jul 17, 2019
2 parents 111385f + ac4d224 commit 046c349
Show file tree
Hide file tree
Showing 9 changed files with 145 additions and 121 deletions.
6 changes: 4 additions & 2 deletions music21/figuredBass/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,8 @@ def checkSinglePossibilities(music21Stream, functionToApply, color="#FF0000", de
.. image:: images/figuredBass/corelli_voiceCrossing.*
:width: 700
'''
debugInfo = []
if debug is True:
debugInfo = []
debugInfo.append("Function To Apply: " + functionToApply.__name__)
debugInfo.append("{0!s:25}{1!s}".format("(Offset, End Time):", "Part Numbers:"))

Expand Down Expand Up @@ -295,8 +295,8 @@ def checkConsecutivePossibilities(music21Stream, functionToApply, color="#FF0000
.. image:: images/figuredBass/checker_parallelOctaves.*
:width: 700
'''
debugInfo = []
if debug is True:
debugInfo = []
debugInfo.append("Function To Apply: " + functionToApply.__name__)
debugInfo.append("{0!s:25}{1!s:25}{2!s}".format(
"(Offset A, End Time A):", "(Offset B, End Time B):", "Part Numbers:"))
Expand Down Expand Up @@ -366,12 +366,14 @@ def voiceCrossing(possibA):
for part1Index in range(len(possibA)):
try: # noqa
higherPitch = possibA[part1Index]
# noinspection PyStatementEffect
higherPitch.ps # pylint: disable=pointless-statement
except AttributeError:
continue
for part2Index in range(part1Index + 1, len(possibA)):
try: # noqa
lowerPitch = possibA[part2Index]
# noinspection PyStatementEffect
lowerPitch.ps # pylint: disable=pointless-statement
except AttributeError:
continue
Expand Down
4 changes: 2 additions & 2 deletions music21/figuredBass/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,8 +409,8 @@ def generateBoogieVamp(blRealization=None, numRepeats=5):
fbRules.partMovementLimits = [(1, 4), (2, 12), (3, 12)]
fbRules.forbidVoiceOverlap = False
blRealization = bluesLine.realize(fbRules)
sampleScore = blRealization.generateRandomRealizations(numRepeats)

sampleScore = blRealization.generateRandomRealizations(numRepeats)
boogieBassLine = converter.parse("tinynotation: BB-8. D16 F8. G16 A-8. G16 F8. D16",
makeNotation=False)

Expand Down Expand Up @@ -454,8 +454,8 @@ def generateTripletBlues(blRealization=None, numRepeats=5): # 12/8
fbRules.partMovementLimits = [(1, 4), (2, 12), (3, 12)]
fbRules.forbidVoiceOverlap = False
blRealization = bluesLine.realize(fbRules)
sampleScore = blRealization.generateRandomRealizations(numRepeats)

sampleScore = blRealization.generateRandomRealizations(numRepeats)
tripletBassLine = converter.parse("tinynotation: BB-4 BB-8 D4 D8 F4 F8 A-8 G8 F8",
makeNotation=False)

Expand Down
24 changes: 12 additions & 12 deletions music21/figuredBass/notation.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class Notation(prebase.ProtoM21Object):
Breaks apart and stores the information in a figured bass notation
column, which is a string of figures, each associated with a number
and an optional modifier. The figures are delimited using commas.
Examples include "7,5,#3", "6,4", and "6,4+,2".
Examples include '7,5,#3', '6,4', and '6,4+,2'.
Valid modifiers include those accepted by :class:`~music21.pitch.Accidental`,
Expand All @@ -51,31 +51,31 @@ class Notation(prebase.ProtoM21Object):
by a modifier, or if a stand-alone modifier implies a 3.
* None, "" or "5" -> "5,3"
* None, '' or '5' -> '5,3'
* "6" -> "6,3"
* '6' -> '6,3'
* "7" -> "7,5,3"
* '7' -> '7,5,3'
* "6,5" -> "6,5,3"
* '6,5' -> '6,5,3'
* "4,3" -> "6,4,3"
* '4,3' -> '6,4,3'
* "4,2" or "2" -> "6,4,2"
* '4,2' or '2' -> '6,4,2'
* "9" -> "9,7,5,3"
* '9' -> '9,7,5,3'
* "11" -> "11,9,7,5,3"
* '11' -> '11,9,7,5,3'
* "13" -> "13,11,9,7,5,3"
* '13' -> '13,11,9,7,5,3'
Figures are saved in order from left to right as found in the notationColumn.
Expand Down Expand Up @@ -247,7 +247,7 @@ def _translateToLonghand(self):
>>> from music21.figuredBass import notation as n
>>> notation1 = n.Notation('#6,5') #__init__ method calls _parseNotationColumn()
>>> notation1 = n.Notation('#6,5') # __init__ method calls _parseNotationColumn()
>>> str(notation1.origNumbers) + ' -> ' + str(notation1.numbers)
'(6, 5) -> (6, 5, 3)'
>>> str(notation1.origModStrings) + ' -> ' + str(notation1.modifierStrings)
Expand Down Expand Up @@ -440,7 +440,7 @@ class Modifier(prebase.ProtoM21Object):
<accidental sharp>
If None or "" is provided for modifierString, then the accidental is None.
If None or '' is provided for modifierString, then the accidental is None.
>>> m3a = notation.Modifier(None)
>>> m3a
Expand Down
10 changes: 5 additions & 5 deletions music21/figuredBass/possibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ def isIncomplete(possibA, pitchNamesToContain):
isIncompleteV = True
if not isIncompleteV and (len(pitchNamesContained) > len(pitchNamesToContain)):
isIncompleteV = False
# raise PossibilityException(str(possibA) + "
# contains pitch names not found in pitchNamesToContain.")
# raise PossibilityException(str(possibA) + '
# contains pitch names not found in pitchNamesToContain.')

return isIncompleteV

Expand Down Expand Up @@ -810,8 +810,8 @@ def couldBeItalianA6Resolution(possibA, possibB, threePartChordInfo=None, restri
music21.figuredBass.possibility.PossibilityException: possibA does not spell out an It+6 chord.
The method is called "couldBeItalianA6Resolution" as opposed
to "isItalianA6Resolution" because it is designed to work in
The method is called `couldBeItalianA6Resolution` as opposed
to `isItalianA6Resolution` because it is designed to work in
tandem with :meth:`~music21.figuredBass.possibility.parallelOctaves`
and :meth:`~music21.figuredBass.possibility.isIncomplete` in
a Segment. Consider the following examples with possibA1 above as the
Expand All @@ -837,7 +837,7 @@ def couldBeItalianA6Resolution(possibA, possibB, threePartChordInfo=None, restri
if threePartChordInfo is None:
augSixthChord = chord.Chord(possibA)
if not augSixthChord.isItalianAugmentedSixth():
raise PossibilityException("possibA does not spell out an It+6 chord.")
raise PossibilityException('possibA does not spell out an It+6 chord.')
bass = augSixthChord.bass()
root = augSixthChord.root()
third = augSixthChord.getChordStep(3)
Expand Down
34 changes: 17 additions & 17 deletions music21/figuredBass/realizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ def addElement(self, bassObject, notationString=None):
elif 'RomanNumeral' in c or 'ChordSymbol' in c:
self._fbList.append(bassObject) # a roman Numeral object
else:
raise FiguredBassLineException("Not a valid bassObject (only note.Note, " +
"harmony.ChordSymbol, and roman.RomanNumeral supported) was %r" % bassObject)
raise FiguredBassLineException('Not a valid bassObject (only note.Note, ' +
'harmony.ChordSymbol, and roman.RomanNumeral supported) was %r' % bassObject)

def generateBassLine(self):
'''
Expand All @@ -251,8 +251,8 @@ def generateBassLine(self):
>>> from music21 import note
>>> fbLine = realizer.FiguredBassLine(key.Key('B'), meter.TimeSignature('3/4'))
>>> fbLine.addElement(note.Note('B2'))
>>> fbLine.addElement(note.Note('C#3'), "6")
>>> fbLine.addElement(note.Note('D#3'), "6")
>>> fbLine.addElement(note.Note('C#3'), '6')
>>> fbLine.addElement(note.Note('D#3'), '6')
>>> #_DOCS_SHOW fbLine.generateBassLine().show()
.. image:: images/figuredBass/fbRealizer_bassLine.*
Expand Down Expand Up @@ -382,8 +382,8 @@ def realize(self, fbRules=None, numParts=4, maxPitch=None):
>>> from music21 import note
>>> fbLine = realizer.FiguredBassLine(key.Key('B'), meter.TimeSignature('3/4'))
>>> fbLine.addElement(note.Note('B2'))
>>> fbLine.addElement(note.Note('C#3'), "6")
>>> fbLine.addElement(note.Note('D#3'), "6")
>>> fbLine.addElement(note.Note('C#3'), '6')
>>> fbLine.addElement(note.Note('D#3'), '6')
>>> fbRules = rules.Rules()
>>> r1 = fbLine.realize(fbRules)
>>> r1.getNumSolutions()
Expand Down Expand Up @@ -471,7 +471,7 @@ def realize(self, fbRules=None, numParts=4, maxPitch=None):
segmentA = segmentList[0]
segmentA.correctA = list(segmentA.allCorrectSinglePossibilities())
elif not segmentList:
raise FiguredBassLineException("No (bassNote, notationString) pairs to realize.")
raise FiguredBassLineException('No (bassNote, notationString) pairs to realize.')

return Realization(realizedSegmentList=segmentList, inKey=self.inKey,
inTime=self.inTime, overlaidParts=self._overlaidParts[0:-1],
Expand All @@ -494,6 +494,7 @@ def _trimAllMovements(self, segmentList):
elif len(segmentList) >= 3:
segmentList.reverse()
# gets this wrong... # pylint: disable=cell-var-from-loop
movementsAB = None
for segmentIndex in range(1, len(segmentList) - 1):
movementsAB = segmentList[segmentIndex + 1].movements
movementsBC = segmentList[segmentIndex].movements
Expand All @@ -503,8 +504,7 @@ def _trimAllMovements(self, segmentList):
del movementsBC[possibB]
for (possibA, possibBList) in list(movementsAB.items()):
movementsAB[possibA] = list(
# pylint: disable=cell-var-from-loop
filter(lambda possibB: (possibB in movementsBC), possibBList))
filter(lambda possibBB: (possibBB in movementsBC), possibBList))

for (possibA, possibBList) in list(movementsAB.items()):
if not possibBList:
Expand Down Expand Up @@ -615,13 +615,13 @@ def getAllPossibilityProgressions(self):

for segmentIndex in range(1, len(self._segmentList)-1):
currMovements = self._segmentList[segmentIndex].movements
for unused_progIndex in range(len(progressions)):
prog = progressions.pop(0)
possibB = prog[-1]
for unused_progressionIndex in range(len(progressions)):
progression = progressions.pop(0)
possibB = progression[-1]
for possibC in currMovements[possibB]:
newProg = copy.copy(prog)
newProg.append(possibC)
progressions.append(newProg)
newProgression = copy.copy(progression)
newProgression.append(possibC)
progressions.append(newProgression)

return progressions

Expand All @@ -637,7 +637,7 @@ def getRandomPossibilityProgression(self):

currMovements = self._segmentList[0].movements
if self.getNumSolutions() == 0:
raise FiguredBassLineException("Zero solutions")
raise FiguredBassLineException('Zero solutions')
prevPossib = random.sample(currMovements.keys(), 1)[0]
progression.append(prevPossib)

Expand Down Expand Up @@ -732,7 +732,7 @@ def generateAllRealizations(self):
allSols = stream.Score()
possibilityProgressions = self.getAllPossibilityProgressions()
if not possibilityProgressions:
raise FiguredBassLineException("Zero solutions")
raise FiguredBassLineException('Zero solutions')
sol0 = self.generateRealizationFromPossibilityProgression(possibilityProgressions[0])
for music21Part in sol0:
allSols.append(music21Part)
Expand Down
8 changes: 4 additions & 4 deletions music21/figuredBass/realizerScale.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def __init__(self, scaleValue='C', scaleMode='major'):
self.realizerScale = foo(scaleValue)
self.keySig = key.KeySignature(key.pitchToSharps(scaleValue, scaleMode))
except KeyError:
raise FiguredBassScaleException("Unsupported scale type-> " + scaleMode)
raise FiguredBassScaleException('Unsupported scale type-> ' + scaleMode)

def getPitchNames(self, bassPitch, notationString=None):
'''
Expand Down Expand Up @@ -191,7 +191,7 @@ def getPitches(self, bassPitch, notationString=None, maxPitch=None):
return allPitches

def __repr__(self):
return "<music21.figuredBass.realizerScale.FiguredBassScale: %s>" % repr(self.realizerScale)
return '<music21.figuredBass.realizerScale.FiguredBassScale: %s>' % repr(self.realizerScale)


class FiguredBassScaleException(exceptions21.Music21Exception):
Expand All @@ -218,9 +218,9 @@ def convertToPitch(pitchString):
try:
return pitch.Pitch(pitchString)
except:
raise ValueError("Cannot convert string " + pitchString + " to a music21 Pitch.")
raise ValueError('Cannot convert string ' + pitchString + ' to a music21 Pitch.')

raise TypeError("Cannot convert " + pitchString + " to a music21 Pitch.")
raise TypeError('Cannot convert ' + pitchString + ' to a music21 Pitch.')


# ------------------------------------------------------------------------------
Expand Down

0 comments on commit 046c349

Please sign in to comment.