'2010.06.24': 3.932, }), ('schumann/opus41no1/movement2', 7, {'2009.12.14': 5.88, '2009.12.15': 5.126, '2010.06.24': 5.799, }), ('luca/gloria', 4, {'2009.12.14': 3.174, '2009.12.15': 2.954, '2010.06.24': 3.063, }), ]: t = common.Timer() t.start() x = corpus.parseWork(known, forceSource=True) t.stop() dur = t() environLocal.printDebug(['timing tolerance for', known, 'this run:', t, 'best runs:', ['%s: %s' % (x, y) for x, y in best.items()]]) self.assertEqual(True, dur <= max) # performance test if __name__ == "__main__": music21.mainTest(TestPerformance)
ap('7---') elif 'PageLayout' in elClasses and layoutToBreaks: popHyphens() ap('77---') elif 'LineBreak' in elClasses: popHyphens() ap('7---') elif 'PageBreak' in elClasses: popHyphens() ap('77---') elif 'ColumnBreak' in elClasses: popHyphens() ap('777---') else: error(el, ErrorLevel.LOG) return ''.join(volpianoTokens) class Test(unittest.TestCase): pass def testNoteNames(self): pass if __name__ == '__main__': import music21 music21.mainTest(Test, 'importPlusRelative')
while tss: timespan = tss.pop() currentTimespansInList = sorted(tss, key=lambda x: (x.offset, x.endTime)) tsTree.removeTimespan(timespan) currentTimespansInTree = [x for x in tsTree] self.assertEqual(currentTimespansInTree, currentTimespansInList, (attempt, currentTimespansInTree, currentTimespansInList)) if tsTree.rootNode is not None: currentPosition = min( x.offset for x in currentTimespansInList) currentEndTime = max( x.endTime for x in currentTimespansInList) self.assertEqual(tsTree.rootNode.endTimeLow, min(x.endTime for x in currentTimespansInList)) self.assertEqual(tsTree.rootNode.endTimeHigh, max(x.endTime for x in currentTimespansInList)) self.assertEqual(tsTree.lowestPosition(), currentPosition) self.assertEqual(tsTree.endTime, currentEndTime) for i in range(len(currentTimespansInTree)): self.assertEqual(currentTimespansInList[i], currentTimespansInTree[i]) #------------------------------------------------------------------------------ if __name__ == "__main__": import music21 music21.mainTest(Test) #, runTest='testElementsStoppingAt')
Interval 6 ⠴ Rest eighth ⠭ Barline final ⠣⠅ Measure 35 Left, Note Grouping 1: Ascending Chord: Octave 3 ⠸ B 16th ⠾ Interval 3 ⠬ Rest 16th ⠍ Ascending Chord: Octave 2 ⠘ B eighth ⠚ Interval 3 ⠬ Interval 5 ⠔ Rest eighth ⠭ Barline final ⠣⠅ ==== ---end grand segment--- ''' self.maxDiff = None self.assertEqual(x.splitlines(), y.splitlines()) if __name__ == "__main__": import music21 music21.mainTest(Test) #, runTest='testVerdiDebug') #------------------------------------------------------------------------------ # eof
if fp is None: fp = environLocal.getTempFile('.qm') for n in obj.flat.notes: music = music + n.name + ' ' music += '\n' with open(fp, 'w') as f: f.write(music) return fp if __name__ == '__main__': import music21 music21.mainTest() # from music21 import common # # converter.registerSubconverter(QMConverter) # # print('\nFILE') # print('+++++++++++++++++++++++++') # # parserPath = common.getSourceFilePath() / 'converter' # testPath = parserPath / 'quarterMusicTestIn.qm' # # a = converter.parse(testPath) # # a.show('text') # #
# def testWTCImport03(self): # score = corpus.parse('bach/bwv862', 1) # self.assertEqual( # score.metadata.title, # 'WTC I: Prelude and Fugue in A flat major', # ) # def testWTCImport04(self): # score = corpus.parse('bach/bwv888', 1) # self.assertEqual( # score.metadata.title, # 'WTC II: Prelude and Fugue in A major', # ) # #s.show() # def testWorkReferences(self): # s = corpus.getWorkReferences() # # # presenly 19 top level lists # self.assertEqual(len(s)>=19, True) # self.assertEqual(len(s[0].keys()), 4) if __name__ == '__main__': import music21 music21.mainTest('noDocTest',Test) # ----------------------------------------------------------------------------- # eof
self.assertEqual( score.metadata.search( 'qu.d', field='title', ), (True, 'title'), ) self.assertEqual( score.metadata.search( re.compile('(.*)canon(.*)'), ), (True, 'movementName'), ) def testRichMetadata02(self): from music21 import corpus from music21 import metadata score = corpus.parse('bwv66.6') richMetadata = metadata.RichMetadata() richMetadata.merge(score.metadata) richMetadata.update(score) self.assertEqual(richMetadata.noteCount, 165) self.assertEqual(richMetadata.quarterLength, 36.0) # ----------------------------------------------------------------------------- if __name__ == '__main__': import music21 music21.mainTest(Test, 'noDocTest')
('weighted', 'pc', 'duration'), ('weighted', 'dynamics'), ]: # s.plot(*args, doneAction='write') s.plot(*args, doneAction=None) def testHorizontalInstrumentationB(self): from music21 import corpus, dynamics s = corpus.parse('bwv66.6') dyn = ['p', 'mf', 'f', 'ff', 'mp', 'fff', 'ppp'] i = 0 for p in s.parts: for m in p.getElementsByClass('Measure'): m.insert(0, dynamics.Dynamic(dyn[i % len(dyn)])) i += 1 s.plot('dolan', fillByMeasure=True, segmentByTarget=True, doneAction=None) # ----------------------------------------------------------------------------- _DOC_ORDER = [plotStream] # ----------------------------------------------------------------------------- if __name__ == '__main__': import music21 music21.mainTest( Test) # , runTest='testPlot3DPitchSpaceQuarterLengthCount')
(x.offset, x.endTime)) tsTree.removeTimespan(timespan) currentTimespansInTree = [x for x in tsTree] self.assertEqual( currentTimespansInTree, currentTimespansInList, (attempt, currentTimespansInTree, currentTimespansInList)) if tsTree.rootNode is not None: currentPosition = min(x.offset for x in currentTimespansInList) currentEndTime = max(x.endTime for x in currentTimespansInList) self.assertEqual( tsTree.rootNode.endTimeLow, min(x.endTime for x in currentTimespansInList)) self.assertEqual( tsTree.rootNode.endTimeHigh, max(x.endTime for x in currentTimespansInList)) self.assertEqual(tsTree.lowestPosition(), currentPosition) self.assertEqual(tsTree.endTime, currentEndTime) # pylint: disable=consider-using-enumerate for i in range(len(currentTimespansInTree)): self.assertEqual(currentTimespansInList[i], currentTimespansInTree[i]) # ----------------------------------------------------------------------------- if __name__ == "__main__": import music21 music21.mainTest(Test) #, runTest='testGetVerticalityAtWithKey')
"tempos": [], "timeSignatureFirst": "4/4", "timeSignatures": [ "4/4" ] }, "__class__": "music21.metadata.RichMetadata", "__version__": [ """ + str(VERSION[0]) + """, """ + str(VERSION[1]) + """, """ + str(VERSION[2]) + """ ] } """ ), ) # ------------------------------------------------------------------------------ if __name__ == "__main__": import music21 music21.mainTest(Test, "noDocTest")
#print(sfTree) sf.isSorted = False sf._cache = {} sfTreeSlow = sf.asTree() for i in range(len(sf)): fasti = sfTree[i] slowi = sfTreeSlow[i] self.assertIs(fasti, slowi) def testAutoSortExample(self): from music21.tree import makeExampleScore sc = makeExampleScore() sc.sort() t = asTree(sc) self.assertEqual(t.endTime, 8.0) #print(repr(t)) # def xtestExampleScoreAsTimespans(self): # from music21 import tree # score = tree.makeExampleScore() # treeList = tree.fromStream.listOfTreesByClass(score, useTimespans=True) # tl0 = treeList[0] #--------------------- if __name__ == '__main__': import music21 music21.mainTest(Test) #, runTest='testAutoSortExample')
These are the same as MusicXML staff-type, except uppercase and "other" which reflects any other type. Probably the best way of using "other" is to designate what it means with a .editorial.staffTypeExplanation = 'other' >>> stream.enums.StaffType.OSSIA <StaffType.OSSIA: 'ossia'> To get the musicxml name: >>> stream.enums.StaffType.OSSIA.value 'ossia' >>> stream.enums.StaffType('cue') <StaffType.CUE: 'cue'> >>> stream.enums.StaffType('tiny') Traceback (most recent call last): ValueError: 'tiny' is not a valid StaffType ''' REGULAR = 'regular' OSSIA = 'ossia' CUE = 'cue' EDITORIAL = 'editorial' ALTERNATE = 'alternate' OTHER = 'other' if __name__ == '__main__': from music21 import mainTest mainTest()
player.play() player.stop() # # effects need special soundfont # def testSpecialEffect(self): player = StreamPlayer2( soundfont='/usr/share/sounds/sf2/FluidR3_GM.sf2') player.setMidiFile('../_midi/novelette.mid') """ synth = player.getFluidSynth() result = fluid_synth_reverb_on(synth, -1, True) print(f'Set reverb on with result {result}.') result = fluid_synth_set_reverb_level(synth, 0.9) print(f'Set reverb level with result {result}.') result = fluid_synth_chorus_on(synth, -1, True) print(f'Set chorus on with result {result}.') result = fluid_synth_set_chorus(synth, 50, 5.0, 2.5, 10.0, 1) print(f'Set chrorus params with result {result}.') """ player.play() player.stop() # # # if __name__ == '__main__': mainTest(TestExternal)
from music21.romanText import testFiles from music21 import converter unused_s = converter.parse(testFiles.mozartK283_2_opening, format='romanText') #s.show('text') #------------------------------------------------------------------------------- # define presented order in documentation _DOC_ORDER = [] if __name__ == "__main__": import music21 #from music21 import converter #r = converter.parse('/Users/cuthbert/desktop/dmitri_rn2.rntxt', format='romantext') #r.show('text') #import time #t = time.time() #import sys #sys.argv.append('PivotInCopyMultiple2') music21.mainTest(Test, TestSlow) #print(time.time() - t) #------------------------------------------------------------------------------ # eof
sf.isSorted = False sf._cache = {} sfTreeSlow = sf.asTree() for i in range(len(sf)): fasti = sfTree[i] slowi = sfTreeSlow[i] self.assertIs(fasti, slowi) def testAutoSortExample(self): from music21.tree import makeExampleScore sc = makeExampleScore() sc.sort() t = asTree(sc) self.assertEqual(t.endTime, 8.0) #print(repr(t)) # def xtestExampleScoreAsTimespans(self): # from music21 import tree # score = tree.makeExampleScore() # treeList = tree.fromStream.listOfTreesByClass(score, useTimespans=True) # tl0 = treeList[0] #--------------------- if __name__ == '__main__': import music21 music21.mainTest(Test) #, runTest='testAutoSortExample')
): for dot in basic.yieldDots(self.trans[-1][0]): self.trans.insert( -1, dot) # insert one before the end, not append... prev._brailleEnglish.append("Dot 3 {0}".format(dot)) return True # only append max one dot. return False def transcribeNoteGrouping(brailleElementGrouping, showLeadingOctave=True): ''' transcribe a group of notes, possibly excluding certain attributes. To be DEPRECATED -- called only be BrailleGrandSegment now. ''' ngt = NoteGroupingTranscriber() ngt.showLeadingOctave = showLeadingOctave return ngt.transcribeGroup(brailleElementGrouping) # ------------------------------------------------------------------------------ class Test(unittest.TestCase): def runTest(self): pass if __name__ == '__main__': import music21 music21.mainTest(Test) # , runTest='testGetRawSegments')
and prev.content[-1] != '.') # TE is an abbreviation, no extra dot 3 necessary ): for dot in basic.yieldDots(self.trans[-1][0]): self.trans.insert(-1, dot) # insert one before the end, not append... prev._brailleEnglish.append("Dot 3 {0}".format(dot)) return True # only append max one dot. return False def transcribeNoteGrouping(brailleElementGrouping, showLeadingOctave=True): ''' transcribe a group of notes, possibly excluding certain attributes. To be DEPRECATED -- called only be BrailleGrandSegment now. ''' ngt = NoteGroupingTranscriber() ngt.showLeadingOctave = showLeadingOctave return ngt.transcribeGroup(brailleElementGrouping) # ------------------------------------------------------------------------------ class Test(unittest.TestCase): def runTest(self): pass if __name__ == "__main__": import music21 music21.mainTest(Test) #, runTest='testGetRawSegments')
}, "keySignatureFirst": "<music21.key.KeySignature of 3 sharps, mode minor>", "keySignatures": [ "<music21.key.KeySignature of 3 sharps, mode minor>" ], "noteCount": 165, "pitchHighest": "E5", "pitchLowest": "F#2", "quarterLength": 36.0, "tempos": [], "timeSignatureFirst": "4/4", "timeSignatures": [ "4/4" ] }, "__class__": "music21.metadata.RichMetadata", "__version__": [ ''' + str(VERSION[0]) + ''', ''' + str(VERSION[1]) + ''', ''' + str(VERSION[2]) + ''' ] } ''', )) #------------------------------------------------------------------------------ if __name__ == "__main__": import music21 music21.mainTest(Test, 'noDocTest')
except KeyError: # no color match raise GraphException('invalid color name: %s' % color) elif common.isListLike(color): percent = False for sub in color: if sub < 1: percent = True break if percent: if len(color) == 1: color = [color[0], color[0], color[0]] # convert to 0 100% values as strings with % symbol colorStrList = [str(x * 100) + "%" for x in color] return webcolors.rgb_percent_to_hex(colorStrList) else: # assume integers return webcolors.rgb_to_hex(tuple(color)) raise GraphException('invalid color specification: %s' % color) class Test(unittest.TestCase): def testColors(self): self.assertEqual(getColor([0.5, 0.5, 0.5]), '#808080') self.assertEqual(getColor(0.5), '#808080') self.assertEqual(getColor(255), '#ffffff') self.assertEqual(getColor('Steel Blue'), '#4682b4') if __name__ == "__main__": # sys.arg test options will be used in mainTest() import music21 music21.mainTest(Test) #TestExternal, 'noDocTest') #, runTest='testGetPlotsToMakeA')
Default editorialMarkDict = {2:[1]} ''' if editorialMarkDict is None: editorialMarkDict = {2: [1]} for vsNum, partNumList in editorialMarkDict.items(): for unused_counter_partNum in partNumList: self.vsnt.verticalities[vsNum].getObjectsByPart( 0, classFilterList=[ 'Note' ]).editorial[editorialDictKey] = editorialValue class Test(unittest.TestCase): def runTest(self): pass class TestExternal(unittest.TestCase): # pragma: no cover def runTest(self): pass def demo(self): pass if __name__ == "__main__": import music21 music21.mainTest(Test, 'moduleRelative') #te = TestExternal() #te.demo()
def testRuleFrequency(self): import time print(time.ctime()) (num1, num2, num3, num4a, num4b) = ruleFrequency() print(time.ctime()) print(num1) print(num2) print(num3) print(num4a) print(num4b) self.assertEqual(num4a, 57) self.assertEqual(num4b, 104) if (__name__ == "__main__"): #runPiece(267) # (totalDict, foundPieceOpus) = findCorrections(correctionType="min6", startPiece=21, endPiece=22) # print totalDict # if len(foundPieceOpus) > 0: # foundPieceOpus.show('lily.png') import music21 music21.mainTest(Test) #TestExternal) #, TestExternal) # correctedMin6() # correctedMaj3() # improvedHarmony() #------------------------------------------------------------------------------ # eof
def testFastPopulate(self): ''' tests that the isSorted speed up trick ends up producing identical results. ''' from music21 import corpus sf = corpus.parse('bwv66.6').flat sfTree = sf.asTree() #print(sfTree) sf.isSorted = False sf._cache = {} sfTreeSlow = sf.asTree() for i in range(len(sf)): fasti = sfTree[i] slowi = sfTreeSlow[i] self.assertIs(fasti, slowi) # def xtestExampleScoreAsTimespans(self): # from music21 import tree # score = tree.makeExampleScore() # treeList = tree.fromStream.listOfTreesByClass(score, useTimespans=True) # tl0 = treeList[0] #--------------------- if __name__ == '__main__': import music21 music21.mainTest(Test) #, runTest='testExampleScoreAsTimespans')
match = False for skip in ['_', '__', 'Test', 'Exception']: if part.startswith(skip) or part.endswith(skip): match = True if match: continue name = getattr(sys.modules[self.__module__], part) if callable(name) and not isinstance(name, types.FunctionType): try: # see if obj can be made w/ args obj = name() except TypeError: continue a = copy.copy(obj) b = copy.deepcopy(obj) self.assertIsNot(a, None) self.assertIsNot(b, None) # ----------------------------------------------------------------------------- _DOC_ORDER = ( Editorial, ) if __name__ == "__main__": #import doctest #doctest.testmod() import music21 music21.mainTest(Test)
print(thisRondeaux.title) thisRondeaux.incipit.show('musicxml') def xtestGloria(self): ''' test showing a Gloria's incipit to see if it works ''' gloriaS = GloriaSheet() thisGloria = gloriaS.makeWork(20) if thisGloria.title != "": thisGloria.asScore().show() def xtestAsScore(self): deduto = BallataSheet().workByTitle('deduto') self.assertEqual(deduto.title, 'Deduto sey a quel') # for s in deduto.snippets: # s.show('text') dedutoScore = deduto.asScore() dedutoScore.show() pass if __name__ == "__main__": import music21 music21.mainTest(Test, 'moduleRelative') #, TestExternal) #------------------------------------------------------------------------------ # eof
>>> b = corpus.parse('bwv66.6') >>> bRecurse = b.recurse() >>> i = 0 >>> for x in bRecurse: ... i += 1 ... if i > 12: ... break >>> bRecurse.streamStack() [<music21.stream.Score 0x1049a0710>, <music21.stream.Part Soprano>, <music21.stream.Measure 1 offset=1.0>] ''' return [i.srcStream for i in self.iteratorStack()] class Test(unittest.TestCase): pass def testRecursiveActiveSites(self): from music21 import converter s = converter.parse('tinyNotation: 4/4 c1 c4 d=id2 e f') rec = s.recurse() n = rec.getElementById('id2') self.assertEqual(n.activeSite.number, 2) if __name__ == '__main__': import music21 music21.mainTest(Test) #, runTest='testRecursiveActiveSites')
# def testWTCImport03(self): # score = corpus.parse('bach/bwv862', 1) # self.assertEqual( # score.metadata.title, # 'WTC I: Prelude and Fugue in A flat major', # ) # def testWTCImport04(self): # score = corpus.parse('bach/bwv888', 1) # self.assertEqual( # score.metadata.title, # 'WTC II: Prelude and Fugue in A major', # ) # #s.show() # def testWorkReferences(self): # s = corpus.getWorkReferences() # # # presenly 19 top level lists # self.assertEqual(len(s)>=19, True) # self.assertEqual(len(s[0].keys()), 4) if __name__ == "__main__": import music21 music21.mainTest('noDocTest',Test) #------------------------------------------------------------------------------ # eof
# initialOffset=0.0, # flatten=True, # classLists=classLists) # return listOfTimespanTrees[0] #--------------------- class Test(unittest.TestCase): def testFastPopulate(self): ''' tests that the isSorted speed up trick ends up producing identical results. ''' from music21 import corpus sf = corpus.parse('bwv66.6').flat sfTree = sf.asTree() #print(sfTree) sf.isSorted = False sf._cache = {} sfTreeSlow = sf.asTree() for i in range(len(sf)): fasti = sfTree[i] slowi = sfTreeSlow[i] self.assertIs(fasti, slowi) #--------------------- if __name__ == '__main__': import music21 music21.mainTest(Test) #, runTest='testFastPopulate')
popHyphens() ap('7---') elif 'PageLayout' in elClasses and layoutToBreaks: popHyphens() ap('77---') elif 'LineBreak' in elClasses: popHyphens() ap('7---') elif 'PageBreak' in elClasses: popHyphens() ap('77---') elif 'ColumnBreak' in elClasses: popHyphens() ap('777---') else: error(el, ErrorLevel.LOG) return ''.join(volpianoTokens) class Test(unittest.TestCase): pass def testNoteNames(self): pass if __name__ == '__main__': import music21 music21.mainTest(Test, 'importPlusRelative')
print [note1.name + str(note1.octave) for note1 in cantusFirmus.notes] if not goodHarmony: print "bad harmony" else: print "harmony good" if not goodMelody: print "bad melody" else: print "melody good" except ModalCounterpointException: pass d1 = duration.Duration() d1.type = "whole" for tN in hopeThisWorks2.notes: tN.duration = d1 for tN in cantusFirmus.notes: tN.duration = d1 lilyOut = twoStreamLily(hopeThisWorks2, cantusFirmus) lilyOut.showPNGandPlayMIDI() def twoStreamLily(st1, st2): lilyOut = lily.LilyString() lilyOut += "<< \\time 4/4\n" lilyOut += " \\new Staff { " lilyOut += st1.lily + " } \n" lilyOut += " \\new Staff { " lilyOut += st2.lily + " } \n" lilyOut += ">> \n" return lilyOut if (__name__ == "__main__"): music21.mainTest(TestExternal) #TestExternal
Created automatically as needed: >>> acc = pitch.Accidental() >>> acc.editorial <music21.editorial.Editorial {}> >>> acc.editorial.ficta = pitch.Accidental('sharp') >>> acc.editorial.ficta <accidental sharp> >>> acc.editorial <music21.editorial.Editorial {'ficta': <accidental sharp>}> ''' from music21 import editorial if self._editorial is None: self._editorial = editorial.Editorial() return self._editorial @editorial.setter def editorial(self, ed): self._editorial = ed class Test(unittest.TestCase): pass if __name__ == '__main__': import music21 music21.mainTest(Test) # , runTest='')
while tss: timespan = tss.pop() currentTimespansInList = sorted(tss, key=lambda x: (x.offset, x.endTime)) tsTree.removeTimespan(timespan) currentTimespansInTree = [x for x in tsTree] self.assertEqual(currentTimespansInTree, currentTimespansInList, (attempt, currentTimespansInTree, currentTimespansInList)) if tsTree.rootNode is not None: currentPosition = min( x.offset for x in currentTimespansInList) currentEndTime = max( x.endTime for x in currentTimespansInList) self.assertEqual(tsTree.rootNode.endTimeLow, min(x.endTime for x in currentTimespansInList)) self.assertEqual(tsTree.rootNode.endTimeHigh, max(x.endTime for x in currentTimespansInList)) self.assertEqual(tsTree.lowestPosition(), currentPosition) self.assertEqual(tsTree.endTime, currentEndTime) for i in range(len(currentTimespansInTree)): self.assertEqual(currentTimespansInList[i], currentTimespansInTree[i]) #------------------------------------------------------------------------------ if __name__ == "__main__": import music21 music21.mainTest(Test) #, runTest='testGetVerticalityAtWithKey')
'cicon', field='composer', fileExtensions=('.krn',), ) self.assertEqual(len(searchResult), 0) searchResult = mdb.search( 'cicon', field='composer', fileExtensions=('.xml',), ) self.assertEqual(len(searchResult), 1) # ----------------------------------------------------------------------------- _DOC_ORDER = ( MetadataBundle, ) __all__ = [ 'MetadataEntry', 'MetadataBundle', ] if __name__ == '__main__': import music21 music21.mainTest(Test) # , runTest='testFileExtensions') # -----------------------------------------------------------------------------
>>> b = corpus.parse('bwv66.6') >>> bRecurse = b.recurse() >>> i = 0 >>> for x in bRecurse: ... i += 1 ... if i > 12: ... break >>> bRecurse.streamStack() [<music21.stream.Score 0x1049a0710>, <music21.stream.Part Soprano>, <music21.stream.Measure 1 offset=1.0>] ''' return [i.srcStream for i in self.iteratorStack()] class Test(unittest.TestCase): pass def testRecursiveActiveSites(self): from music21 import converter s = converter.parse('tinyNotation: 4/4 c1 c4 d=id2 e f') rec = s.recurse() n = rec.getElementById('id2') self.assertEqual(n.activeSite.number, 2) _DOC_ORDER = [StreamIterator, RecursiveIterator, OffsetIterator] if __name__ == '__main__': import music21 music21.mainTest(Test) #, runTest='testRecursiveActiveSites')
print(thisRondeaux.title) thisRondeaux.incipit.show('musicxml') def xtestGloria(self): ''' test showing a Gloria's incipit to see if it works ''' gloriaS = GloriaSheet() thisGloria = gloriaS.makeWork(20) if thisGloria.title != "": thisGloria.asScore().show() def xtestAsScore(self): deduto = BallataSheet().workByTitle('deduto') self.assertEqual(deduto.title, u'Deduto sey a quel') # for s in deduto.snippets: # s.show('text') dedutoScore = deduto.asScore() dedutoScore.show() pass if __name__ == "__main__": import music21 music21.mainTest(Test) #, TestExternal) #------------------------------------------------------------------------------ # eof
self.assertEqual(nst1[0].lyric, "Mi-") self.assertEqual(nst1[2].isRest, True) self.assertEqual(nst1[5].name, "G") self.assertEqual(nst1[7].name, "A-") class TestExternal(unittest.TestCase): def xtestCreateEasyScale(self): myScale = "d8 e f g a b" time1 = meter.TimeSignature("3/4") tinyNotation = TinyNotationStream(myScale, time1) tinyNotation.lily.showPDF() def testMusicXMLExt(self): cadB = TinyNotationStream("c8 B- B- A c trip{d16 c B-} A8 B- A0", "2/4") # last = cadB[10] # cadB = stream.Stream() # n1 = music21.note.Note() # n1.duration.type = "whole" # cadB.append(n1) # cadB.lily.showPDF() cadB.show() # ------------------------------------------------------------------------------- # define presented order in documentation _DOC_ORDER = [TinyNotationNote, TinyNotationStream, HarmonyStream, HarmonyNote] if __name__ == "__main__": music21.mainTest(TestExternal, Test)
Rest eighth ⠭ Barline final ⠣⠅ Measure 35 Left, Note Grouping 1: Ascending Chord: Octave 3 ⠸ B 16th ⠾ Interval 3 ⠬ Rest 16th ⠍ Ascending Chord: Octave 2 ⠘ B eighth ⠚ Interval 3 ⠬ Interval 5 ⠔ Rest eighth ⠭ Barline final ⠣⠅ ==== ---end grand segment--- ''' self.maxDiff = None self.assertEqual(x.splitlines(), y.splitlines()) if __name__ == "__main__": import music21 music21.mainTest(Test) #, runTest='testVerdiDebug') # ----------------------------------------------------------------------------- # eof
>>> acc = pitch.Accidental() >>> acc.editorial <music21.editorial.Editorial {} > >>> acc.editorial.ficta = pitch.Accidental('sharp') >>> acc.editorial.ficta <accidental sharp> >>> acc.editorial <music21.editorial.Editorial {'ficta': <accidental sharp>} > ''' from music21 import editorial if self._editorial is None: self._editorial = editorial.Editorial() return self._editorial @editorial.setter def editorial(self, ed): self._editorial = ed class Test(unittest.TestCase): pass if __name__ == '__main__': import music21 music21.mainTest(Test) #, runTest='') # ----------------------------------------------------------------------------- # eof
# >>> virtualCorpus.getWorkList('junk') # [] # # ''' # if not common.isListLike(fileExtensions): # fileExtensions = [fileExtensions] # for obj in VirtualCorpus._virtualWorks: # if obj.corpusPath is not None and workName.lower() in obj.corpusPath.lower(): # return obj.getUrlByExt(fileExtensions) # return [] # # __all__ = ( 'Corpus', 'CoreCorpus', 'LocalCorpus', # 'VirtualCorpus', ) _DOC_ORDER = ( Corpus, CoreCorpus, LocalCorpus, # VirtualCorpus, ) if __name__ == '__main__': import music21 music21.mainTest()
# def testWTCImport03(self): # score = corpus.parse('bach/bwv862', 1) # self.assertEqual( # score.metadata.title, # 'WTC I: Prelude and Fugue in A flat major', # ) # def testWTCImport04(self): # score = corpus.parse('bach/bwv888', 1) # self.assertEqual( # score.metadata.title, # 'WTC II: Prelude and Fugue in A major', # ) # #s.show() # def testWorkReferences(self): # s = corpus.getWorkReferences() # # # presenly 19 top level lists # self.assertEqual(len(s)>=19, True) # self.assertEqual(len(s[0].keys()), 4) if __name__ == "__main__": import music21 music21.mainTest("noDocTest", Test) # ------------------------------------------------------------------------------ # eof
elif common.isListLike(color): percent = False for sub in color: if sub < 1: percent = True break if percent: if len(color) == 1: color = [color[0], color[0], color[0]] # convert to 0 100% values as strings with % symbol colorStrList = [str(x * 100) + "%" for x in color] return webcolors.rgb_percent_to_hex(colorStrList) else: # assume integers return webcolors.rgb_to_hex(tuple(color)) raise GraphException('invalid color specification: %s' % color) class Test(unittest.TestCase): def testColors(self): self.assertEqual(getColor([0.5, 0.5, 0.5]), '#808080') self.assertEqual(getColor(0.5), '#808080') self.assertEqual(getColor(255), '#ffffff') self.assertEqual(getColor('Steel Blue'), '#4682b4') if __name__ == "__main__": # sys.arg test options will be used in mainTest() import music21 music21.mainTest( Test) #TestExternal, 'noDocTest') #, runTest='testGetPlotsToMakeA')
return jsf.jsonWrite(filePath) return self #------------------------------------------------------------------------------ class Test(unittest.TestCase): def runTest(self): pass #------------------------------------------------------------------------------ _DOC_ORDER = ( MetadataBundle, ) __all__ = [ 'MetadataEntry', 'MetadataBundle', ] if __name__ == "__main__": import music21 music21.mainTest(Test) #, runTest='testUserSpecifiedPath') #------------------------------------------------------------------------------
return client.data # ----------------------------------------------------------------------------- class Test(unittest.TestCase): def testCountingAxisFormat(self): def countingAxisFormatter(n, formatDict): if n.pitch.accidental is not None: formatDict['color'] = 'red' return n.pitch.diatonicNoteNum from music21.graph.plot import Histogram from music21 import converter s = converter.parse('tinynotation: 4/4 C4 D E F C D# E F#') hist = Histogram(s) hist.doneAction = None hist.axisX = Axis(hist, 'x') hist.axisX.extractOneElement = countingAxisFormatter hist.run() self.assertEqual(hist.data, [(1, 2, {}), (2, 2, { 'color': 'red' }), (3, 2, {}), (4, 2, { 'color': 'red' })]) # ----------------------------------------------------------------------------- if __name__ == '__main__': import music21 music21.mainTest(Test)
]: #s.plot(*args, doneAction='write') s.plot(*args, doneAction=None) def testHorizontalInstrumentationB(self): from music21 import corpus, dynamics s = corpus.parse('bwv66.6') dyn = ['p', 'mf', 'f', 'ff', 'mp', 'fff', 'ppp'] i = 0 for p in s.parts: for m in p.getElementsByClass('Measure'): m.insert(0, dynamics.Dynamic(dyn[i % len(dyn)])) i += 1 s.plot('dolan', fillByMeasure=True, segmentByTarget=True, doneAction=None) #------------------------------------------------------------------------------ _DOC_ORDER = [plotStream] #------------------------------------------------------------------------------ if __name__ == "__main__": import music21 music21.mainTest(Test) #, runTest='testPlot3DPitchSpaceQuarterLengthCount') #------------------------------------------------------------------------------ # eof
def iterateSequencePairwise(self, sequence): prev = None for x in sequence: cur = x if prev is not None: yield prev, cur prev = cur def runNBConvert(self, ipythonNotebookFilePath): try: from nbconvert import nbconvertapp as nb except ImportError: environLocal.warn("nbconvert is not installed, run pip3 install nbconvert") raise outputPath = os.path.splitext(self.sourceToAutogenerated(ipythonNotebookFilePath))[0] app = nb.NbConvertApp.instance() # @UndefinedVariable app.initialize(argv=['--to', 'rst', '--output', outputPath, ipythonNotebookFilePath]) app.writer.build_directory = os.path.dirname(ipythonNotebookFilePath) app.start() return True if __name__ == '__main__': i = IPythonNotebookReSTWriter() p5 = i.ipythonNotebookFilePaths[5] i.convertOneNotebook(p5) import music21 music21.mainTest('moduleRelative')
ci = CapellaImporter() #ci.readCapellaXMLFile(r'd:/desktop/achsorgd.capx') import os capellaDirPath = common.getSourceFilePath() + os.path.sep + 'capella' oswaldPath = capellaDirPath + os.path.sep + r'Nu_rue_mit_sorgen.capx' partScore = ci.scoreFromFile(oswaldPath) partScore.show() def xtestImportSorgen(self): ci = CapellaImporter() import os capellaDirPath = common.getSourceFilePath() + os.path.sep + 'capella' oswaldPath = capellaDirPath + os.path.sep + r'Nu_rue_mit_sorgen.capx' ci.readCapellaXMLFile(oswaldPath) ci.parseXMLText() #firstSystemObject = ci.mainDom.documentElement.getElementsByTagName('system')[0] #m21SystemObj = ci.systemFromSystem(firstSystemObject) #m21SystemObj.show('text') #scoreElement = ci.mainDom.documentElement.getElementsByTagName('score')[0] scoreObj = ci.systemScoreFromScore(ci.mainDom.documentElement) partScore = ci.partScoreFromSystemScore(scoreObj) partScore.show() #ci.walkNodes() #print ci.xmlText if __name__ == '__main__': import music21 music21.mainTest(Test, TestExternal)
'cicon', field='composer', fileExtensions=('.krn',), ) self.assertEqual(len(searchResult), 0) searchResult = mdb.search( 'cicon', field='composer', fileExtensions=('.xml'), ) self.assertEqual(len(searchResult), 1) # ----------------------------------------------------------------------------- _DOC_ORDER = ( MetadataBundle, ) __all__ = [ 'MetadataEntry', 'MetadataBundle', ] if __name__ == '__main__': import music21 music21.mainTest(Test) #, runTest='testFileExtensions') # -----------------------------------------------------------------------------
self.assertIsNone(notPChord.pivotChord) #s.show('text') def testEndings(self): # has first and second endings... from music21.romanText import testFiles from music21 import converter unused_s = converter.parse(testFiles.mozartK283_2_opening, format='romanText') #s.show('text') #------------------------------------------------------------------------------- # define presented order in documentation _DOC_ORDER = [] if __name__ == "__main__": import music21 #from music21 import converter #r = converter.parse('d:/desktop/riemenschneider001.txt', format='romantext') #import sys #sys.argv.append('testSecondaryInCopyMultiple') music21.mainTest(Test, TestSlow) #------------------------------------------------------------------------------ # eof
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) # replace 'Test' with 'TestSlow' to test it on all 371 Bach Chorales.
if show is True: print(tCounter.output) tCounter.displayStream.show('lily.png') def testAll(show = True, fast = False): sacredTonality(show) if fast is False: nonLandiniTonality(show) anonBallataTonality(show) landiniTonality(show) class Test(unittest.TestCase): pass def runTest(self): testAll(show = False, fast = True) class TestExternal(unittest.TestCase): pass def runTest(self): testAll(show = True, fast = False) if __name__ == "__main__": music21.mainTest(Test) #External) #------------------------------------------------------------------------------ # eof
o = romanTextToStreamOpus(testFiles.mozartK279) self.assertEqual(o.scores[0].metadata.movementNumber, '1') self.assertEqual(o.scores[0].metadata.composer, 'Mozart') self.assertEqual(o.scores[1].metadata.movementNumber, '2') self.assertEqual(o.scores[1].metadata.composer, 'Mozart') self.assertEqual(o.scores[2].metadata.movementNumber, '3') self.assertEqual(o.scores[2].metadata.composer, 'Mozart') # test using converter. from music21 import converter s = converter.parse(testFiles.mozartK279) self.assertEqual('Opus' in s.classes, True) self.assertEqual(len(s.scores), 3) # make sure a normal file is still a Score s = converter.parse(testFiles.riemenschneider001) self.assertEqual('Score' in s.classes, True) #------------------------------------------------------------------------------- # define presented order in documentation _DOC_ORDER = [] if __name__ == "__main__": music21.mainTest()#Test) #------------------------------------------------------------------------------ # eof