Skip to content

Commit

Permalink
Small simplifications and speed-ups
Browse files Browse the repository at this point in the history
  • Loading branch information
TimFelixBeyer committed Mar 1, 2024
1 parent 0927e39 commit f1ab28c
Show file tree
Hide file tree
Showing 11 changed files with 111 additions and 126 deletions.
2 changes: 1 addition & 1 deletion music21/abcFormat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -719,7 +719,7 @@ def getMetronomeMarkObject(self) -> tempo.MetronomeMark|None:
# there may be more than one dur divided by a space
referent = 0.0 # in quarter lengths
for dur in durs.split(' '):
if dur.count('/') > 0:
if '/' in dur:
n, d = dur.split('/')
else: # this is an error case
environLocal.printDebug(['incorrectly encoded / unparsable duration:', dur])
Expand Down
2 changes: 1 addition & 1 deletion music21/braille/segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -2060,7 +2060,7 @@ def extractBrailleElements(
except BrailleSegmentException as notSupportedException: # pragma: no cover
isExempt = [isinstance(music21Object, music21Class)
for music21Class in excludeFromBrailleElements]
if isExempt.count(True) == 0:
if not any(isExempt):
environRules.warn(f'{notSupportedException}')

allElements.sort(key=lambda x: (x.offset, x.classSortOrder))
Expand Down
10 changes: 5 additions & 5 deletions music21/chord/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -834,12 +834,12 @@ def __getitem__(self, key: int|str|note.Note|pitch.Pitch):

keyErrorStr = f'Cannot access component with: {key!r}'
if isinstance(key, str):
if key.count('.'):
if '.' in key:
key, attrStr = key.split('.', 1)
if not attrStr.count('.'):
attributes = (attrStr,)
else:
if '.' in attrStr:
attributes = tuple(attrStr.split('.'))
else:
attributes = (attrStr,)
else:
attributes = ()

Expand Down Expand Up @@ -931,7 +931,7 @@ def __setitem__(self, key, value):
Traceback (most recent call last):
ValueError: Chord index must be set to a valid note object
'''
if isinstance(key, str) and key.count('.'):
if isinstance(key, str) and '.' in key:
keySplit = key.split('.')
keyFind = '.'.join(keySplit[0:-1])
attr = keySplit[-1]
Expand Down
8 changes: 4 additions & 4 deletions music21/duration.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ def dottedMatch(qLen: OffsetQLIn,
durType, match = quarterLengthToClosestType(preDottedLength)
except DurationException:
continue
if match is True:
if match:
return (dots, durType)
return (False, False)

Expand Down Expand Up @@ -441,8 +441,8 @@ def quarterLengthToNonPowerOf2Tuplet(

def quarterLengthToTuplet(
qLen: OffsetQLIn,
maxToReturn=4,
tupletNumerators=defaultTupletNumerators
maxToReturn: int = 4,
tupletNumerators: list[int] = defaultTupletNumerators
) -> list[Tuplet]:
'''
Returns a list of possible Tuplet objects for a
Expand Down Expand Up @@ -738,7 +738,7 @@ def quarterConversion(qLen: OffsetQLIn) -> QuarterLengthConversion:

def convertTypeToQuarterLength(
dType: str,
dots=0,
dots: int = 0,
tuplets: list[Tuplet]|None = None,
dotGroups=None
) -> OffsetQL:
Expand Down
141 changes: 67 additions & 74 deletions music21/humdrum/spineParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1328,7 +1328,7 @@ def parse(self):
thisObject = SpineComment(eventC)
if thisObject.comment == '':
thisObject = None
elif eventC.count(' '):
elif ' ' in eventC:
thisObject = self.processChordEvent(eventC)
else: # Note or Rest
thisObject = self.processNoteEvent(eventC)
Expand Down Expand Up @@ -2209,7 +2209,7 @@ def hdStringToNote(contents):

# Detect rests first, because rests can contain manual positioning information,
# which is also detected by the `matchedNote` variable above.
if contents.count('r'):
if 'r' in contents:
thisObject = note.Rest()

elif matchedNote:
Expand All @@ -2232,91 +2232,88 @@ def hdStringToNote(contents):
thisObject.pitch.accidental = matchedSharp.group(0)
elif matchedFlat:
thisObject.pitch.accidental = matchedFlat.group(0)
elif contents.count('n'):
elif 'n' in contents:
thisObject.pitch.accidental = 'n'

# 3.2.2 -- Slurs, Ties, Phrases
# TODO: add music21 phrase information
if contents.count('{'):
for i in range(contents.count('{')):
pass # phraseMark start
if contents.count('}'):
for i in range(contents.count('}')):
pass # phraseMark end
if contents.count('('):
for i in range(contents.count('(')):
pass # slur start
if contents.count(')'):
for i in range(contents.count(')')):
pass # slur end
if contents.count('['):
for i in range(contents.count('{')):
pass # phraseMark start
for i in range(contents.count('}')):
pass # phraseMark end
for i in range(contents.count('(')):
pass # slur start
for i in range(contents.count(')')):
pass # slur end
if '[' in contents:
thisObject.tie = tie.Tie('start')
elif contents.count(']'):
elif ']' in contents:
thisObject.tie = tie.Tie('stop')
elif contents.count('_'):
elif '_' in contents:
thisObject.tie = tie.Tie('continue')

# 3.2.3 Ornaments
if contents.count('t'):
if 't' in contents:
thisObject.expressions.append(expressions.HalfStepTrill())
elif contents.count('T'):
elif 'T' in contents:
thisObject.expressions.append(expressions.WholeStepTrill())

if contents.count('w'):
if 'w' in contents:
thisObject.expressions.append(expressions.HalfStepInvertedMordent())
elif contents.count('W'):
elif 'W' in contents:
thisObject.expressions.append(expressions.WholeStepInvertedMordent())
elif contents.count('m'):
elif 'm' in contents:
thisObject.expressions.append(expressions.HalfStepMordent())
elif contents.count('M'):
elif 'M' in contents:
thisObject.expressions.append(expressions.WholeStepMordent())

if contents.count('S'):
if 'S' in contents:
thisObject.expressions.append(expressions.Turn())
elif contents.count('$'):
elif '$' in contents:
thisObject.expressions.append(expressions.InvertedTurn())
elif contents.count('R'):
elif 'R' in contents:
t1 = expressions.Turn()
t1.connectedToPrevious = True # true by default, but explicitly
thisObject.expressions.append(t1)

if contents.count(':'):
if ':' in contents:
# TODO: deal with arpeggiation -- should have been in a
# chord structure
pass

if contents.count('O'):
if 'O' in contents:
thisObject.expressions.append(expressions.Ornament())
# generic ornament

# 3.2.4 Articulation Marks
if contents.count("'"):
if "'" in contents:
thisObject.articulations.append(articulations.Staccato())
if contents.count('"'):
if '"' in contents:
thisObject.articulations.append(articulations.Pizzicato())
if contents.count('`'):
if '`' in contents:
# called 'attacca' mark but means staccatissimo:
# http://www.music-cog.ohio-state.edu/Humdrum/representations/kern.rep.html
thisObject.articulations.append(articulations.Staccatissimo())
if contents.count('~'):
if '~' in contents:
thisObject.articulations.append(articulations.Tenuto())
if contents.count('^'):
if '^' in contents:
thisObject.articulations.append(articulations.Accent())
if contents.count(';'):
if ';' in contents:
thisObject.expressions.append(expressions.Fermata())

# 3.2.5 Up & Down Bows
if contents.count('v'):
if 'v' in contents:
thisObject.articulations.append(articulations.UpBow())
elif contents.count('u'):
elif 'u' in contents:
thisObject.articulations.append(articulations.DownBow())

# 3.2.6 Stem Directions
if contents.count('/'):
if '/' in contents:
thisObject.stemDirection = 'up'
elif contents.count('\\'):
elif '\\' in contents:
thisObject.stemDirection = 'down'


# 3.2.7 Duration +
# 3.2.8 N-Tuplets

Expand All @@ -2327,7 +2324,7 @@ def hdStringToNote(contents):
durationFirst = int(foundRational.group(1))
durationSecond = float(foundRational.group(2))
thisObject.duration.quarterLength = 4 * durationSecond / durationFirst
if contents.count('.'):
if '.' in contents:
thisObject.duration.dots = contents.count('.')

elif foundNumber:
Expand All @@ -2337,20 +2334,16 @@ def hdStringToNote(contents):
if durationString == '000':
# for larger values, see https://extras.humdrum.org/man/rscale/
thisObject.duration.type = 'maxima'
if contents.count('.'):
thisObject.duration.dots = contents.count('.')
elif durationString == '00':
# for larger values, see https://extras.humdrum.org/man/rscale/
thisObject.duration.type = 'longa'
if contents.count('.'):
thisObject.duration.dots = contents.count('.')
else:
thisObject.duration.type = 'breve'
if contents.count('.'):
thisObject.duration.dots = contents.count('.')
if '.' in contents:
thisObject.duration.dots = contents.count('.')
elif durationType in duration.typeFromNumDict:
thisObject.duration.type = duration.typeFromNumDict[durationType]
if contents.count('.'):
if '.' in contents:
thisObject.duration.dots = contents.count('.')
else:
dT = int(durationType) + 0.0
Expand All @@ -2369,26 +2362,26 @@ def hdStringToNote(contents):
# humdrum tuplets that breaks normal usage. TODO: Refactor adding a Flavor = 'JRP'
# code that uses this other method...
JRP = flavors['JRP']
if JRP is False and contents.count('.'):
if JRP is False and '.' in contents:
newTup.durationNormal = duration.durationTupleFromTypeDots(
newTup.durationNormal.type, contents.count('.'))

thisObject.duration.appendTuplet(newTup)
if JRP is True and contents.count('.'):
if JRP is True and '.' in contents:
thisObject.duration.dots = contents.count('.')
# call Duration.TupletFixer after to correct this.

# 3.2.9 Grace Notes and Groupettos
if contents.count('q'):
# 3.2.9 Grace Notes and Groupettos
if 'q' in contents:
thisObject = thisObject.getGrace()
thisObject.duration.type = 'eighth'
elif contents.count('Q'):
elif 'Q' in contents:
thisObject = thisObject.getGrace()
thisObject.duration.slash = False
thisObject.duration.type = 'eighth'
elif contents.count('P'):
elif 'P' in contents:
thisObject = thisObject.getGrace(appoggiatura=True)
elif contents.count('p'):
elif 'p' in contents:
pass # end appoggiatura duration -- not needed in music21...

# 3.2.10 Beaming
Expand Down Expand Up @@ -2428,53 +2421,53 @@ def hdStringToMeasure(contents, previousMeasure=None):

barline = bar.Barline()

if contents.count('-'):
if '-' in contents:
barline.type = 'none'
elif contents.count("'"):
elif "'" in contents:
barline.type = 'short'
elif contents.count('`'):
elif '`' in contents:
barline.type = 'tick'
elif contents.count('||'):
elif '||' in contents:
barline.type = 'double'
if contents.count(':') > 1:
barline.repeatDots = 'both'
elif contents.count(':|'):
elif ':|' in contents:
barline.repeatDots = 'left'
elif contents.count('|:'):
elif '|:' in contents:
barline.repeatDots = 'right'
elif contents.count('!!'):
elif '!!' in contents:
barline.type = 'heavy-heavy'
if contents.count(':') > 1:
barline.repeatDots = 'both'
elif contents.count(':!'):
elif ':!' in contents:
barline.repeatDots = 'left'
elif contents.count('!:'):
elif '!:' in contents:
barline.repeatDots = 'right'
elif contents.count('|!'):
elif '|!' in contents:
barline.type = 'final'
if contents.count(':') > 1:
barline.repeatDots = 'both'
elif contents.count(':|'):
elif ':|' in contents:
barline.repeatDots = 'left'
elif contents.count('!:'):
elif '!:' in contents:
barline.repeatDots = 'right'
elif contents.count('!|'):
elif '!|' in contents:
barline.type = 'heavy-light'
if contents.count(':') > 1:
barline.repeatDots = 'both'
elif contents.count(':!'):
elif ':!' in contents:
barline.repeatDots = 'left'
elif contents.count('|:'):
elif '|:' in contents:
barline.repeatDots = 'right'
elif contents.count('|'):
elif '|' in contents:
barline.type = 'regular'
if contents.count(':') > 1:
barline.repeatDots = 'both'
elif contents.count(':|'):
elif ':|' in contents:
barline.repeatDots = 'left'
elif contents.count('|:'):
elif '|:' in contents:
barline.repeatDots = 'right'
elif contents.count('=='):
elif '==' in contents:
barline.type = 'double'
if contents.count(':') > 1:
barline.repeatDots = 'both'
Expand All @@ -2484,7 +2477,7 @@ def hdStringToMeasure(contents, previousMeasure=None):
'Cannot import a double bar visually rendered as a single bar -- '
+ 'not sure exactly what that would mean anyhow.')

if contents.count(';'):
if ';' in contents:
barline.pause = expressions.Fermata()

if previousMeasure is not None:
Expand Down
Loading

0 comments on commit f1ab28c

Please sign in to comment.