def homeKeySig(self): ''' gets the initial, or 'home', key signature by looking at the musictext and locating the key signature at the start of the S: rule. >>> s = romanText.clercqTemperley.CTSong(romanText.clercqTemperley.textString) >>> s.homeKeySig <music21.key.Key of A major> ''' #look at 'S' Rule and grab the home key Signature if self.text and 'S:' in self.text: lines = self.text.split('\n') for line in lines: if line.startswith('S:'): for atom in line.split()[1:3]: if '[' not in atom: self._homeKeySig = key.Key('C') return self._homeKeySig elif not '/' in atom: m21keyStr = key.convertKeyStringToMusic21KeyString(atom[1:-1]) self._homeKeySig = key.Key(m21keyStr) return self._homeKeySig else: pass return self._homeKeySig
def figuredBassFromStream(streamPart): ''' Takes a :class:`~music21.stream.Part` (or another :class:`~music21.stream.Stream` subclass) and returns a :class:`~music21.figuredBass.realizer.FiguredBassLine` object whose bass notes have notations taken from the lyrics in the source stream. This method along with the :meth:`~music21.figuredBass.realizer.FiguredBassLine.realize` method provide the easiest way of converting from a notated version of a figured bass (such as in a MusicXML file) to a realized version of the same line. >>> s = tinyNotation.TinyNotationStream('4/4 C4 D8_6 E8_6 F4 G4_7 c1') >>> fb = figuredBass.realizer.figuredBassFromStream(s) >>> fbRules = figuredBass.rules.Rules() >>> fbRules.partMovementLimits = [(1,2),(2,12),(3,12)] >>> fbRealization = fb.realize(fbRules) >>> fbRealization.getNumSolutions() 13 >>> #_DOCS_SHOW fbRealization.generateRandomRealizations(8).show() .. image:: images/figuredBass/fbRealizer_fbStreamPart.* :width: 500 ''' sf = streamPart.flat sfn = sf.notes keyList = sf.getElementsByClass(key.Key) myKey = None if len(keyList) == 0: keyList = sf.getElementsByClass(key.KeySignature) if len(keyList) == 0: myKey = key.Key('C') else: if keyList[0].pitchAndMode[1] is None: mode = 'major' else: mode = keyList[0].pitchAndMode[1] myKey = key.Key(keyList[0].pitchAndMode[0], mode) else: myKey = keyList[0] tsList = sf.getElementsByClass(meter.TimeSignature) if len(tsList) == 0: ts = meter.TimeSignature('4/4') else: ts = tsList[0] fb = FiguredBassLine(myKey, ts) if streamPart.hasMeasures(): paddingLeft = streamPart.measure(0).paddingLeft if paddingLeft != 0.0: fb._paddingLeft = paddingLeft for n in sfn: if len(n.lyrics) > 0: annotationString = ", ".join([x.text for x in n.lyrics]) fb.addElement(n, annotationString) else: fb.addElement(n) return fb
def getKey(self): # alter flat symbol if self.src == '?)b:' or self.src == '?)b': return key.Key('b') else: keyStr = self.src.replace('b', '-') keyStr = keyStr.replace(':', '') keyStr = keyStr.replace('?', '') keyStr = keyStr.replace(')', '') #environLocal.printDebug(['create a key from:', keyStr]) return key.Key(keyStr)
def testOverrideDisplayStatus(self): n = note.Note('Cn') n.pitch.accidental.displayStatus = True k = key.Key('C') n.pitch.updateAccidentalDisplay(overrideStatus=True, alteredPitches=k.alteredPitches) self.assertIs(n.pitch.accidental.displayStatus, False)
def twelveBarBlues(): ''' This is a progression in Bb major based on the twelve bar blues. The progression used is: I | IV | I | I7 IV | IV | I | I7 V7 | IV6 | I | I >>> from music21.figuredBass import examples >>> from music21.figuredBass import rules >>> bluesLine = examples.twelveBarBlues() >>> #_DOCS_SHOW bluesLine.generateBassLine().show() .. image:: images/figuredBass/fbExamples_bluesBassLine.* :width: 700 >>> fbRules = rules.Rules() >>> fbRules.partMovementLimits = [(1, 4), (2, 12), (3, 12)] >>> fbRules.forbidVoiceOverlap = False >>> blRealization = bluesLine.realize(fbRules) >>> blRealization.getNumSolutions() 2224978 >>> #_DOCS_SHOW blRealization.generateRandomRealization().show() .. image:: images/figuredBass/fbExamples_twelveBarBlues.* :width: 700 ''' from music21 import converter from music21 import key s = converter.parse( "tinynotation: BB-1 E-1 BB-1 BB-1_7 E-1 E-1 BB-1 BB-1_7 F1_7 G1_6 BB-1 BB-1", makeNotation=False) s.insert(0, key.Key('B-')) return realizer.figuredBassFromStream(s)
def __init__(self, tonic=None, scale_degree_index=None): self.tonic = tonic if tonic else random_pitch() self.scale_degree_index = scale_degree_index if scale_degree_index else random.choice( range(8)) self.scale_degree = scale_degrees[self.scale_degree_index] self.scale = key.Key(self.tonic) super().__init__()
def italianA6ResolutionExample(): ''' The Italian augmented sixth chord (It+6) is the only augmented sixth chord to consist of only three pitch names, and when represented in four parts, the tonic is doubled. The tonic can resolve up, down or stay the same, and in four parts, the two tonics always resolve differently, resulting in two equally acceptable resolutions. An alternate approach to resolving the It+6 chord was taken, such that an It+6 chord could map internally to two different resolutions. Every other special resolution in fbRealizer consists of a 1:1 mapping of special chords to resolutions. Here, the It+6 chord is resolving to the dominant, minor tonic, and major tonic, respectively. In the dominant resolution shown, the tonics (D) are resolving inward, but they can resolve outward as well. In the minor tonic resolution, the higher tonic is resolving up to F, and the lower tonic remains the same. In the major tonic resolution, the higher tonic remains the same, while the lower tonic resolves up to the F#. >>> from music21.figuredBass import examples >>> from music21.figuredBass import rules >>> fbLine = examples.italianA6ResolutionExample() >>> fbRules = rules.Rules() >>> fbRules.upperPartsMaxSemitoneSeparation = None >>> fbRules.partMovementLimits.append([1,4]) >>> fbRealization = fbLine.realize(fbRules) >>> fbRealization.keyboardStyleOutput = False >>> #_DOCS_SHOW fbRealization.generateRandomRealization().show() .. image:: images/figuredBass/fbExamples_it+6.* :width: 700 ''' from music21 import converter, key s = converter.parse("tinynotation: D4 BB-4_#6,3 AA2_# D4 BB-4_#6,3 AA2_6,4 D4 BB-4_#6,3 AA2_#6,4", makeNotation=False) s.insert(0, key.Key('d')) return realizer.figuredBassFromStream(s)
def viio65ResolutionExample(): ''' For a fully diminished seventh chord resolving to the tonic, the resolution chord can contain either a doubled third (standard resolution) or a doubled tonic (alternate resolution), depending on whether the third of the diminished chord rises or falls. The user can control this in a Rules object by modifying :attr:`~music21.figuredBass.rules.Rules.doubledRootInDim7`. However, when resolving a diminished 6,5, the third is found in the bass and the proper resolution is determined in context, regardless of user preference. The following shows both cases involving a diminished 6,5. The resolution of the first diminished chord has a doubled D, while that of the second has a doubled F#. Notice that the resolution of the first involves a diminished fifth (E, Bb) going to a perfect fifth (D, A). >>> from music21.figuredBass import examples >>> fbLine = examples.viio65ResolutionExample() >>> fbRealization = fbLine.realize() >>> #_DOCS_SHOW fbRealization.generateRandomRealization().show() .. image:: images/figuredBass/fbExamples_vii65.* :width: 700 ''' from music21 import converter, key s = converter.parse("tinyNotation: 4/4 D2 E2_6,b5 D2 E2_6,b5 F#1_6", makeNotation=False) s.insert(0, key.Key('D')) return realizer.figuredBassFromStream(s)
def makeScoreWithPickup(self): """Make a short score with pick up and two voices.""" sc = stream.Score() num_voices = 2 pitches = ['C', 'A-'] for i in range(num_voices): part = stream.Part() part.id = 'part %d' % i time_sig = meter.TimeSignature('4/4') key_sig = key.Key('c') # Add pickup measure. pickup = stream.Measure() pickup.append(time_sig) pickup.append(key_sig) n1 = music21_note.Note(pitches[i]) n1.duration.quarterLength = 1 pickup.append(n1) part.append(pickup) # Add full measure. full_m = stream.Measure() full_m.append(n1) n2 = n1.transpose('M2') full_m.append(n2) full_m.repeatAppend(n1, 2) part.append(full_m) sc.insert(0, part) # Show the full score and all score elements in indented text. # sc.show('text') return sc
def _getKeyAndPrefix(rtKeyOrString): '''Given an RTKey specification, return the Key and a string prefix based on the tonic: >>> romanText.translate._getKeyAndPrefix('c') (<music21.key.Key of c minor>, 'c: ') >>> romanText.translate._getKeyAndPrefix('F#') (<music21.key.Key of F# major>, 'F#: ') >>> romanText.translate._getKeyAndPrefix('Eb') (<music21.key.Key of E- major>, 'E-: ') >>> romanText.translate._getKeyAndPrefix('Bb') (<music21.key.Key of B- major>, 'B-: ') >>> romanText.translate._getKeyAndPrefix('bb') (<music21.key.Key of b- minor>, 'b-: ') >>> romanText.translate._getKeyAndPrefix('b#') (<music21.key.Key of b# minor>, 'b#: ') ''' from music21 import key if common.isStr(rtKeyOrString): rtKeyOrString = key.convertKeyStringToMusic21KeyString(rtKeyOrString) k = key.Key(rtKeyOrString) else: k = rtKeyOrString.getKey() tonicName = k.tonic.name if k.mode == 'minor': tonicName = tonicName.lower() prefix = tonicName + ": " return k, prefix
def testTrecentoMadrigal(self): from music21 import corpus # c = corpus.parse('beethoven/opus18no1', 2).measures(1, 19) c = corpus.parse('PMFC_06_Giovanni-05_Donna').measures(1, 30) # c = corpus.parse('PMFC_06_Giovanni-05_Donna').measures(90, 118) # c = corpus.parse('PMFC_06_Piero_1').measures(1, 10) # c = corpus.parse('PMFC_06-Jacopo').measures(1, 30) # c = corpus.parse('PMFC_12_13').measures(1, 40) # fix clef fixClef = True if fixClef: startClefs = c.parts[1].getElementsByClass( 'Measure').first().getElementsByClass('Clef') if startClefs: clef1 = startClefs[0] c.parts[1].getElementsByClass('Measure').first().remove(clef1) c.parts[1].getElementsByClass('Measure').first().insert( 0, clef.Treble8vbClef()) cr = ChordReducer() # cr.printDebug = True p = cr.multiPartReduction(c, maxChords=3) # p = cr.multiPartReduction(c, closedPosition=True) from music21 import key, roman cm = key.Key('G') for thisChord in p.recurse().getElementsByClass('Chord'): thisChord.lyric = roman.romanNumeralFromChord( thisChord, cm, preferSecondaryDominants=True).figure c.insert(0, p) if self.show: c.show()
def testExpandTurns(self): from music21 import note, stream, clef, key, meter p1 = stream.Part() m1 = stream.Measure() m2 = stream.Measure() p1.append(clef.TrebleClef()) p1.append(key.Key('F', 'major')) p1.append(meter.TimeSignature('2/4')) n1 = note.Note('C5', type='half') turn0 = Turn() n1.expressions.append(turn0) n2 = note.Note('B4', type='quarter') n2.duration.dots = 1 n2.expressions.append(InvertedTurn()) m1.append(n1) m2.append(key.KeySignature(5)) m2.append(n2) m2.append(note.Rest('eighth')) p1.append(m1) p1.append(m2) realized1 = realizeOrnaments(n1) realized2 = realizeOrnaments(n2) self.assertEqual('C5 D5 C5 B-4 C5', ' '.join(n.pitch.nameWithOctave for n in realized1)) self.assertEqual('B4 A#4 B4 C#5 B4', ' '.join(n.pitch.nameWithOctave for n in realized2)) self.assertEqual(realized1[0].quarterLength, 1.0) self.assertEqual(realized1[1].quarterLength, 0.25) self.assertEqual(realized2[0].quarterLength, 0.5) self.assertEqual(realized2[1].quarterLength, 0.25) turn0.quarterLength = 0.125 realized1b = realizeOrnaments(n1) self.assertEqual(realized1b[0].quarterLength, 1.5) self.assertEqual(realized1b[1].quarterLength, 0.125)
def getKey(self): ''' This returns a Key, not a KeySignature object ''' myKey = self.src.rstrip(self.footerStrip) myKey = key.convertKeyStringToMusic21KeyString(myKey) return key.Key(myKey)
def smoothInterpretationByMeasure(self): smoothedKeysByMeasure = {} algorithm = self.weightAlgorithm for i in self.measureIndexes: baseInterpretations = self.getInterpretationByMeasure(i) if baseInterpretations is None: if i == 0: continue else: smoothedKeysByMeasure.append(None) continue for j in range(-1 * self.windowSize, self.windowSize + 1): # -2, -1, 0, 1, 2 etc. mNum = i + j if mNum < 0 or mNum >= self.numMeasures or mNum == i: continue newInterpretations = self.getInterpretationByMeasure(mNum) if newInterpretations is not None: # add newInterpretation keys into base interpretation keys if they do not appear for k in newInterpretations.keys(): if not k in baseInterpretations.keys(): baseInterpretations[k] = 0 # compute the contribution of newInterpretation to the baseInterpretation for k in baseInterpretations: coeff = algorithm(newInterpretations[k], j) baseInterpretations[k] += coeff bestName = max(baseInterpretations, key=baseInterpretations.get, default=None) smoothedKeysByMeasure.update({i: key.Key(bestName)}) return smoothedKeysByMeasure
def correct_mispelled_enharmonic_notes_according_to_key_sig(key, scale_code, note_set): """ This function is no longer useful. Turns out you can pass MIDI to music21. TODO: delete this function """ tonic = key.upper().replace('S', '#') if tonic[-1].isnumeric(): tonic = tonic[:-1] if len(tonic) > 1 and tonic[-1] == 'B': tonic[-1] = '-' key_of_tonic = music21_key.Key(tonic, constants['scales'][scale_code]['name']) notes_in_key = [key_of_tonic.pitchFromDegree(x).name for x in range(1,8)] notes_in_key = list(map(lambda x: x.replace('-', 'b').replace('#', 's').lower(), notes_in_key)) correct_spelling_of_note_set = [] for note in note_set: appended_already = False if note not in notes_in_key: for note_from_key in notes_in_key: if are_notes_enharmonically_equivalent(note_from_key, note): correct_spelling_of_note_set.append(note_from_key) appended_already = True break if appended_already == False: correct_spelling_of_note_set.append(note) return correct_spelling_of_note_set
def augmentedSixthResolutionExample(): ''' This example was retrieved from page 61 of *The Music Theory Handbook* by Marjorie Merryman. Italian (8,#6,3), French (#6,4,3), German (#6,5,3), and Swiss (#6,#4,3) augmented sixth resolutions to either the major dominant or the major/minor tonic 6,4 are supported. The first four bars show the resolutions to the dominant in the order above, while the last bar shows the German augmented sixth resolving to the tonic. >>> from music21.figuredBass import examples >>> fbLine = examples.augmentedSixthResolutionExample() >>> fbRealization = fbLine.realize() >>> #_DOCS_SHOW fbRealization.generateRandomRealization().show() .. image:: images/figuredBass/fbExamples_a6.* :width: 700 ''' from music21 import converter, key s = converter.parse( "tinynotation: 4/4 D4 BB-4_8,#6,3 AA2_# D4 BB-4_#6,4,3 " + "AA2_# D4 BB-4_#6,5,3 AA2_# D4 BB-4_#6,#4,3 AA2_# D4 " + "BB-4_#6,5,3 AA2_6,4", makeNotation=False) s.insert(0, key.Key('d')) return realizer.figuredBassFromStream(s)
def __init__( self, voiceOneNoteOne=None, voiceOneNoteTwo=None, voiceTwoNoteOne=None, voiceTwoNoteTwo=None, key_signature=None, ): base.Music21Object.__init__(self) if key_signature is None: key_signature = key.Key('C') self._key_signature = key.Key(key_signature) self._voiceOneNoteOne = voiceOneNoteOne self._voiceOneNoteTwo = voiceOneNoteTwo self._voiceTwoNoteOne = voiceTwoNoteOne self._voiceTwoNoteTwo = voiceTwoNoteTwo
def testInterveningNoteBetweenIdenticalChromaticPitches(self): p = converter.parse('tinyNotation: f#4 e f#') p.measure(1).insert(0, key.Key('G')) p.recurse().notes.last().pitch.accidental.displayStatus = False p.makeAccidentals(inPlace=True, overrideStatus=True) self.assertIs( p.measure(1).notes.first().pitch.accidental.displayStatus, False) self.assertIs( p.measure(1).notes.last().pitch.accidental.displayStatus, False)
def _generate_question(self): if not self.tonic: self.tonic = random_pitch() if not self.scale_degree_index: self.scale_degree_index = random.choice(range(8)) self.scale_degree = scale_degrees[self.scale_degree_index] self.scale = key.Key(self.tonic, 'minor') self._question = f"What is the {self.scale_degree['name']} scale degree " \ f"of {self.scale.getTonic().unicodeName} natural {self.scale.mode.capitalize()}?"
def _getHomeKeySig(self): #look at 'S' Rule and grab the home key Signature if self.text and 'S:' in self.text: lines = self.text.split('\n') for line in lines: if line.startswith('S:'): for atom in line.split()[1:3]: if '[' not in atom: self._homeKeySig = key.Key('C') return self._homeKeySig elif not '/' in atom: m21keyStr = key.convertKeyStringToMusic21KeyString( atom[1:-1]) self._homeKeySig = key.Key(m21keyStr) return self._homeKeySig else: pass return self._homeKeySig
def testGetVerticalityAtWithKey(self): from music21 import stream, key, note s = stream.Stream() s.insert(0, key.Key('C')) s.insert(0, note.Note('F#4')) scoreTree = s.asTimespans() v = scoreTree.getVerticalityAt(0.0) ps = v.pitchSet self.assertEqual(len(ps), 1)
def testImplicitToExplicitNatural(self): p = converter.parse('tinyNotation: 2/4 f4 fn4') last_note = p.recurse().notes.last() p.makeAccidentals(inPlace=True) self.assertIs(last_note.pitch.accidental.displayStatus, False) last_note.pitch.accidental.displayStatus = None p['Measure'].first().insert(0, key.Key('C-')) p.makeAccidentals(inPlace=True) self.assertIs(last_note.pitch.accidental.displayStatus, False)
def testNaturalOutsideAlteredPitches(self): p = converter.parse('tinyNotation: 2/4 f4 dn4') p.makeAccidentals(inPlace=True) last_note = p[note.Note].last() self.assertIs(last_note.pitch.accidental.displayStatus, False) # Rerun test with C-flat major last_note.pitch.accidental.displayStatus = None p['Measure'].first().insert(0, key.Key('C-')) p.makeAccidentals(inPlace=True) self.assertIs(last_note.pitch.accidental.displayStatus, True)
def xtestExpandTrills(self): from music21 import note, stream, clef, key, meter p1 = stream.Part() m1 = stream.Measure() p1.append(clef.TrebleClef()) p1.append(key.Key('D', 'major')) p1.append(meter.TimeSignature('2/4')) n1 = note.Note('E4', type='eighth') n1.expressions.append(Trill()) m1.append(n1) p1.append(m1)
def change_key(self, choice): self.reset() self.keyboard.reset() if choice == 0: self.actual_key = None else: keys = ['None', 'C', 'D', 'E', 'F', 'G', 'A', 'B'] self.actual_key = key.Key(keys[choice]) self.keyboard.on_key_change(self.actual_key) self.melody.actual_key = self.actual_key
def __init__(self, inKey=None, inTime=None): if inKey is None: inKey = key.Key('C') if inTime is None: inTime = meter.TimeSignature('4/4') self.inKey = inKey self.inTime = inTime self._paddingLeft = 0.0 self._overlaidParts = stream.Part() self._fbScale = realizerScale.FiguredBassScale(inKey.pitchFromDegree(1), inKey.mode) self._fbList = []
def xtestExpandTurns(self): from music21 import note, stream, clef, key, meter p1 = stream.Part() m1 = stream.Measure() m2 = stream.Measure() p1.append(clef.TrebleClef()) p1.append(key.Key('F', 'major')) p1.append(meter.TimeSignature('2/4')) n1 = note.Note('C5', type='half') n1.expressions.append(Turn()) n2 = note.Note('B4', type='half') n2.expressions.append(InvertedTurn()) m1.append(n1) m2.append(key.KeySignature(5)) m2.append(n2) p1.append(m1) p1.append(m2)
def testExpandTrills(self): from music21 import note, stream, clef, key, meter p1 = stream.Part() m1 = stream.Measure() p1.append(clef.TrebleClef()) p1.append(key.Key('D', 'major')) p1.append(meter.TimeSignature('1/4')) n1 = note.Note('E4', type='eighth') n1.expressions.append(Trill()) m1.append(n1) p1.append(m1) realized = realizeOrnaments(n1) self.assertIsInstance(realized, list) self.assertEqual(len(realized), 4) self.assertIsInstance(realized[0], note.Note) self.assertEqual(realized[0].quarterLength, 0.125) self.assertEqual('E4 F#4 E4 F#4', ' '.join(n.pitch.nameWithOctave for n in realized))
def exampleB(): ''' This example was retrieved from page 114 of *The Music Theory Handbook* by Marjorie Merryman. >>> from music21.figuredBass import examples >>> fbLine = examples.exampleB() >>> #_DOCS_SHOW fbLine.generateBassLine().show() .. image:: images/figuredBass/fbExamples_bassLineB.* :width: 700 First, fbLine is realized with the default rules set. >>> fbRealization1 = fbLine.realize() >>> fbRealization1.getNumSolutions() 422 >>> #_DOCS_SHOW fbRealization1.generateRandomRealization().show() .. image:: images/figuredBass/fbExamples_sol1B.* :width: 700 Now, a Rules object is created, and the restriction that the chords need to be complete is lifted. fbLine is realized once again. >>> from music21.figuredBass import rules >>> fbRules = rules.Rules() >>> fbRules.forbidIncompletePossibilities = False >>> fbRealization2 = fbLine.realize(fbRules) >>> fbRealization2.getNumSolutions() 188974 >>> #_DOCS_SHOW fbRealization2.generateRandomRealization().show() .. image:: images/figuredBass/fbExamples_sol2B.* :width: 700 ''' from music21 import converter from music21 import key s = converter.parse( "tinynotation: 4/4 D4 A4_7,5,#3 B-4 F4_6 G4_6 AA4_7,5,#3 D2", makeNotation=False) s.insert(0, key.Key('d')) return realizer.figuredBassFromStream(s)
def exampleC(): ''' This example was retrieved from page 114 of *The Music Theory Handbook* by Marjorie Merryman. >>> from music21.figuredBass import examples >>> fbLine = examples.exampleC() >>> #_DOCS_SHOW fbLine.generateBassLine().show() .. image:: images/figuredBass/fbExamples_bassLineC.* :width: 700 First, fbLine is realized with the default rules set. >>> fbRealization1 = fbLine.realize() >>> fbRealization1.getNumSolutions() 833 >>> #_DOCS_SHOW fbRealization1.generateRandomRealization().show() .. image:: images/figuredBass/fbExamples_sol1C.* :width: 700 Now, parallel fifths are allowed in realizations. The image below shows one of them. There is a parallel fifth between the bass and alto parts going from the half-diminished 6,5 (B,F#) to the dominant seventh (C#,G#) in the second measure. >>> from music21.figuredBass import rules >>> fbRules = rules.Rules() >>> fbRules.forbidParallelFifths = False >>> fbRealization2 = fbLine.realize(fbRules) >>> fbRealization2.getNumSolutions() 2427 >>> #_DOCS_SHOW fbRealization2.generateRandomRealization().show() .. image:: images/figuredBass/fbExamples_sol2C.* :width: 700 ''' from music21 import converter from music21 import key s = converter.parse( "tinynotation: 4/4 FF#4 GG#4_#6 AA4_6 FF#4 BB4_6,5 C#4_7,5,#3 F#2", makeNotation=False) s.insert(0, key.Key('f#')) return realizer.figuredBassFromStream(s)