This module defines objects for representing key signatures as well as key areas. The KeySignature is used in Measure objects for defining notated key signatures.
The Key object is a fuller representation not just of a key signature but also of the key of a region.
Utility function to change strings in the form of “Eb” to “E-” (for E-flat major) and leaves alone proper music21 strings (like “E-” or “f#”). A little bit complex because of parsing bb as B-flat minor and Bb as B-flat major.
>>> from music21 import *
>>> key.convertKeyStringToMusic21KeyString('Eb')
'E-'
>>> key.convertKeyStringToMusic21KeyString('f#')
'f#'
>>> key.convertKeyStringToMusic21KeyString('bb')
'b-'
>>> key.convertKeyStringToMusic21KeyString('Bb')
'B-'
>>> key.convertKeyStringToMusic21KeyString('b#')
'b#'
>>> key.convertKeyStringToMusic21KeyString('c')
'c'
Given a pitch or music21.pitch.Pitch object, return the number of sharps found in that mode.
The mode parameter can be ‘major’, ‘minor’, or most of the common church/jazz modes (‘dorian’, ‘mixolydian’, etc.) including Locrian.
If mode is omitted or not found, the default mode is major.
(extra points to anyone who can find the earliest reference to the Locrian mode in print. David Cohen and I (MSC) have been looking for this for years).
>>> from music21 import *
>>> key.pitchToSharps('c')
0
>>> key.pitchToSharps('c', 'minor')
-3
>>> key.pitchToSharps('a', 'minor')
0
>>> key.pitchToSharps('d')
2
>>> key.pitchToSharps('e-')
-3
>>> key.pitchToSharps('a')
3
>>> key.pitchToSharps('e', 'minor')
1
>>> key.pitchToSharps('f#', 'major')
6
>>> key.pitchToSharps('g-', 'major')
-6
>>> key.pitchToSharps('c#')
7
>>> key.pitchToSharps('g#')
8
>>> key.pitchToSharps('e', 'dorian')
2
>>> key.pitchToSharps('d', 'dorian')
0
>>> key.pitchToSharps('g', 'mixolydian')
0
>>> key.pitchToSharps('e-', 'lydian')
-2
>>> key.pitchToSharps('e-', 'lydian')
-2
>>> key.pitchToSharps('a', 'phrygian')
-1
>>> key.pitchToSharps('e', 'phrygian')
0
>>> key.pitchToSharps('f#')
6
>>> key.pitchToSharps('f-')
-8
>>> key.pitchToSharps('f--')
-15
>>> key.pitchToSharps('f--', 'locrian')
-20
But quarter tones don’t work:
>>> key.pitchToSharps('C~')
Traceback (most recent call last):
KeyException: Cannot determine sharps for quarter-tone keys! silly!
Given a number a positive/negative number of sharps, return a Pitch object set to the appropriate major key value.
>>> from music21 import *
>>> key.sharpsToPitch(1)
G
>>> key.sharpsToPitch(1)
G
>>> key.sharpsToPitch(2)
D
>>> key.sharpsToPitch(-2)
B-
>>> key.sharpsToPitch(-6)
G-
Note that these are music21.pitch.Pitch objects not just names:
>>> k1 = key.sharpsToPitch(6)
>>> k1
F#
>>> k1.step
'F'
>>> k1.accidental
<accidental sharp>
Inherits from: Music21Object, JSONSerializer
A KeySignature object specifies the signature to be used for a piece; it takes in zero, one, or two arguments. The first argument is an int giving the number of sharps, or if negative the number of flats. The second argument (deprecated – do not use) specifies the mode of the piece (‘major’, ‘minor’, or None for unknown).
If you are starting with the name of a key, see the Key object.
>>> from music21 import *
>>> A = key.KeySignature(3)
>>> A
<music21.key.KeySignature of 3 sharps>
>>> Eflat = key.KeySignature(-3)
>>> Eflat
<music21.key.KeySignature of 3 flats>
If you want to get a real Key, then use the Key object instead:
>>> illegal = key.KeySignature('c#')
Traceback (most recent call last):
KeySignatureException: Cannot get a KeySignature from this "number" of sharps: "c#"; did you mean to use a key.Key() object instead?
>>> legal = key.Key('c#')
>>> legal.sharps
4
>>> legal
<music21.key.Key of c# minor>
KeySignature attributes
- classSortOrder¶
Property which returns an number (int or otherwise) depending on the class of the Music21Object that represents a priority for an object based on its class alone – used as a tie for stream sorting in case two objects have the same offset and priority. Lower numbers are sorted to the left of higher numbers. For instance, Clef, KeySignature, TimeSignature all come (in that order) before Note.
All undefined classes have classSortOrder of 20 – same as note.Note
>>> from music21 import * >>> tc = clef.TrebleClef() >>> tc.classSortOrder 0 >>> ks = key.KeySignature(3) >>> ks.classSortOrder 1New classes can define their own default classSortOrder
>>> class ExampleClass(base.Music21Object): ... classSortOrderDefault = 5 ... >>> ec1 = ExampleClass() >>> ec1.classSortOrder 5Attributes inherited from Music21Object: isSpanner, isStream, isVariant, hideObjectOnPrint, groups, id
KeySignature properties
- alteredPitches¶
Return a list of music21.pitch.Pitch objects that are altered by this KeySignature. That is, all Pitch objects that will receive an accidental.
>>> from music21 import * >>> a = key.KeySignature(3) >>> a.alteredPitches [F#, C#, G#] >>> b = key.KeySignature(1) >>> b.alteredPitches [F#]>>> c = key.KeySignature(9) >>> c.alteredPitches [F#, C#, G#, D#, A#, E#, B#, F##, C##] >>> d = key.KeySignature(-3) >>> d.alteredPitches [B-, E-, A-]>>> e = key.KeySignature(-1) >>> e.alteredPitches [B-] >>> f = key.KeySignature(-6) >>> f.alteredPitches [B-, E-, A-, D-, G-, C-]>>> g = key.KeySignature(-8) >>> g.alteredPitches [B-, E-, A-, D-, G-, C-, F-, B--]
- mode¶
Get or set the mode.
- mx¶
Returns a musicxml.KeySignature object
>>> a = KeySignature(3) >>> a.sharps = -3 >>> mxKey = a.mx >>> mxKey.get('fifths') -3
- pitchAndMode¶
Returns a a two value list containing a music21.pitch.Pitch object that names this key and the value of mode.
>>> from music21 import * >>> key.KeySignature(-7).pitchAndMode (C-, None) >>> key.KeySignature(-6).pitchAndMode (G-, None) >>> key.KeySignature(-3).pitchAndMode (E-, None) >>> key.KeySignature(0).pitchAndMode (C, None) >>> key.KeySignature(1).pitchAndMode (G, None) >>> csharp = key.KeySignature(4) >>> csharp.mode = "minor" >>> csharp.pitchAndMode (C#, 'minor') >>> csharpPitch = csharp.pitchAndMode[0] >>> csharpPitch.accidental <accidental sharp>
- sharps¶
Get or set the number of sharps.
Properties inherited from Music21Object: activeSite, beat, beatDuration, beatStr, beatStrength, classes, derivationHierarchy, duration, isGrace, measureNumber, offset, priority, seconds
Properties inherited from JSONSerializer: json
KeySignature methods
- accidentalByStep(step)¶
Given a step (C, D, E, F, etc.) return the accidental for that note in this key (using the natural minor for minor) or None if there is none.
>>> from music21 import * >>> g = key.KeySignature(1) >>> g.accidentalByStep("F") <accidental sharp> >>> g.accidentalByStep("G")>>> f = KeySignature(-1) >>> bbNote = note.Note("B-5") >>> f.accidentalByStep(bbNote.step) <accidental flat>Fix a wrong note in F-major:
>>> wrongBNote = note.Note("B#4") >>> if f.accidentalByStep(wrongBNote.step) != wrongBNote.accidental: ... wrongBNote.accidental = f.accidentalByStep(wrongBNote.step) >>> wrongBNote <music21.note.Note B->Set all notes to the correct notes for a key using the note’s Key Context. Before:
>>> from music21 import * >>> s1 = stream.Stream() >>> s1.append(key.KeySignature(4)) # E-major or C-sharp-minor >>> s1.append(note.HalfNote("C")) >>> s1.append(note.HalfNote("E-")) >>> s1.append(key.KeySignature(-4)) # A-flat-major or F-minor >>> s1.append(note.WholeNote("A")) >>> s1.append(note.WholeNote("F#")) >>> s1.show()![]()
After:
>>> for n in s1.notes: ... n.accidental = n.getContextByClass(key.KeySignature).accidentalByStep(n.step) >>> s1.show()![]()
- getScale()¶
Return a scale that is representative of this key.
>>> from music21 import * >>> ks = key.KeySignature(3) >>> ks <music21.key.KeySignature of 3 sharps> >>> ks.getScale() <music21.scale.MajorScale A major>
- transpose(value, inPlace=False)¶
Transpose the KeySignature by the user-provided value. If the value is an integer, the transposition is treated in half steps. If the value is a string, any Interval string specification can be provided. Alternatively, a music21.interval.Interval object can be supplied.
>>> a = KeySignature(2) >>> a.pitchAndMode (D, None) >>> b = a.transpose('p5') >>> b.pitchAndMode (A, None) >>> b.sharps 3 >>> c = b.transpose('-m2') >>> c.pitchAndMode (G#, None) >>> c.sharps 8 >>> d = c.transpose('-a3') >>> d.pitchAndMode (E-, None) >>> d.sharps -3Methods inherited from Music21Object: searchActiveSiteByAttr(), getContextAttr(), setContextAttr(), addContext(), addLocation(), addLocationAndActiveSite(), freezeIds(), getAllContextsByClass(), getCommonSiteIds(), getCommonSites(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), next(), previous(), purgeLocations(), purgeOrphans(), purgeUndeclaredIds(), removeLocationBySite(), removeLocationBySiteId(), setOffsetBySite(), show(), splitAtDurations(), splitAtQuarterLength(), splitByQuarterLengths(), unfreezeIds(), unwrapWeakref(), wrapWeakref(), write()
Methods inherited from JSONSerializer: jsonAttributes(), jsonComponentFactory(), jsonPrint(), jsonRead(), jsonWrite()
Inherits from: KeySignature, DiatonicScale, ConcreteScale, Scale, Music21Object, JSONSerializer
Note that a key is a sort of hypothetical/conceptual object. It probably has a scale (or scales) associated with it and a KeySignature, but not necessarily.
>>> from music21 import *
>>> cm = key.Key('c') # cminor.
>>> cm
<music21.key.Key of c minor>
>>> cm.sharps
-3
>>> cm.pitchFromDegree(3)
E-4
>>> cm.pitchFromDegree(7)
B-4
>>> Csharpmaj = key.Key('C#')
>>> Csharpmaj
<music21.key.Key of C# major>
>>> Csharpmaj.sharps
7
>>> Fflatmaj = key.Key('F-')
>>> Fflatmaj
<music21.key.Key of F- major>
>>> Fflatmaj.sharps
-8
>>> Fflatmaj.accidentalByStep('B')
<accidental double-flat>
Key attributes
Attributes without Documentation: correlationCoefficient, alternateInterpretations
Attributes inherited from KeySignature: classSortOrder
Attributes inherited from ConcreteScale: tonic, boundRange
Attributes inherited from Scale: type
Attributes inherited from Music21Object: isSpanner, isStream, isVariant, hideObjectOnPrint, groups, id
Key properties
Properties inherited from KeySignature: alteredPitches, mode, mx, pitchAndMode, sharps
Properties inherited from DiatonicScale: musicxml
Properties inherited from ConcreteScale: abstract, chord, isConcrete, name, pitches
Properties inherited from Music21Object: activeSite, beat, beatDuration, beatStr, beatStrength, classes, derivationHierarchy, duration, isGrace, measureNumber, offset, priority, seconds
Properties inherited from JSONSerializer: json
Key methods
- tonalCertainty(method='correlationCoefficient', *args, **keywords)¶
Provide a measure of tonal ambiguity for Key determined with one of many methods.
The correlationCoefficient assumes that the alternateInterpretations list has been filled from the use of a KeyWeightKeyAnalysis subclass.
Methods inherited from KeySignature: accidentalByStep(), getScale(), transpose()
Methods inherited from DiatonicScale: getDominant(), getLeadingTone(), getParallelMajor(), getParallelMinor(), getRelativeMajor(), getRelativeMinor(), getTonic()
Methods inherited from ConcreteScale: derive(), deriveByDegree(), deriveRanked(), findMissing(), getChord(), getDegreeMaxUnique(), getPitches(), getScalaStorage(), getScaleDegreeAndAccidentalFromPitch(), getScaleDegreeFromPitch(), intervalBetweenDegrees(), isNext(), match(), next(), pitchFromDegree(), pitchesFromScaleDegrees(), romanNumeral(), show(), solfeg(), tune(), write()
Methods inherited from Music21Object: searchActiveSiteByAttr(), getContextAttr(), setContextAttr(), addContext(), addLocation(), addLocationAndActiveSite(), freezeIds(), getAllContextsByClass(), getCommonSiteIds(), getCommonSites(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), previous(), purgeLocations(), purgeOrphans(), purgeUndeclaredIds(), removeLocationBySite(), removeLocationBySiteId(), setOffsetBySite(), splitAtDurations(), splitAtQuarterLength(), splitByQuarterLengths(), unfreezeIds(), unwrapWeakref(), wrapWeakref()
Methods inherited from JSONSerializer: jsonAttributes(), jsonComponentFactory(), jsonPrint(), jsonRead(), jsonWrite()