Configuration

CoreConfig: Configuration for maelzel.core

At any given moment there is one active configuration (an instance of CoreConfig, itself a subclass of dict). The configuration allows to set default values for many settings and customize different aspects of maelzel.core:

  • notation (default page size, rendered image scaling, etc). Prefix: show

  • playback (default audio backend, instrument, etc). Prefix: play

  • offline rendering. Prefix: rec

  • quantization (complexity, quantization strategy, etc). Prefix: quant

  • etc.

Settings can be modified by simply changing the values of the active config dict:

# Get the active config
>>> from maelzel.core import *
>>> config = getConfig()
>>> config['show.pageSize'] = 'A3'

A config has a set of valid keys. An attempt to set an unknown key will result in an error. Values are also validated regarding their type and accepted values, range, etc.:

>>> config['foo'] = 'bar'
KeyError: 'Unknown key foo'
>>> config['show.pageSize'] = 'Z1'
ValueError: key show.pageSize should be one of {'a2', 'a4', 'a3'}, got Z1

Alternative key format

For convenience keys are case- and punctuation- independent. This allows to create a new CoreConfig as CoreConfig(show_staff_size=10) instead of CoreConfig(updates={'show.staffSize': 10}) or query the same key as staffsize = config['show_staff_size'] instead of staffsize = config['show.staffSize']

Persistence

Modifications to a configuration can be made persistent by saving the config.

>>> from maelzel.core import *
# Set the reference frequency to 443
>>> conf = getConfig()
>>> conf['A4'] = 443
# Set lilypond as default rendering backend
>>> conf['show.backend'] = 'lilypond'
>>> conf.save()

In a future session these changes will be picked up as default:

>>> from maelzel.core import *
>>> conf = getConfig()
>>> conf['A4']
443

Root Config

When maelzel.core is first imported the persisted config is read (if no persisted config is found the builtin default is used). This is the root config and is used as a prototype for any subsequent CoreConfig created. This enables you to modify default values based on your personal setup (for example, you can set the default rendering samplerate to 48000 if that fits your workflow better).

Example

>>> from maelzel.core import *
>>> config = getConfig()
>>> config['rec.sr']
44100
>>> rootConfig['rec.sr'] = 48000
>>> newconfig = CoreConfig()
>>> newconfig['rec.sr']
48000
>>> rootConfig.save()   # If you want this as default, save it for any future sessions

Active config

In order to create a configuration specific for a particular task it is possible to create a new config with CoreConfig or by cloning any CoreConfig.

>>> from maelzel.core import *
>>> newconfig = CoreConfig({'show.pageSize': 'a3'}, active=True)
# This is the same as
>>> newconfig = CoreConfig.root.clone({'show.pageSize': 'a3'})
>>> setConfig(newconfig)

Also creating a new Workspace will create a new config based on the root config:

>>> from maelzel.core import *
# Create a config to work with old tuning and display notation using a3 page size
>>> w = Workspace(updates={'A4': 435, 'show.pageSize': 'a3'}, active=True)
# do something with this, then deactivate the workspace
>>> n = Note("4A")
>>> print(n.freq)
435
# Play with default instr
>>> n.play()
# When finished, deactivate it to return to previous Workspace
>>> w.deactivate()
>>> Note("4A").freq
442

It is also possible to create a temporary config as a context manager. The config will be active only within its context:

>>> from maelzel.core import *
>>> scale = Chain([Note(m, dur=0.5) for m in range(60, 72)])
>>> with CoreConfig({'show.pageSize':'a3'}):
...     scale.show()

Classes

CoreConfig([updates, source, active])

A CoreConfig is a dict like object which controls many aspects of maelzel.core

Class Inheritance Diagram

digraph inheritancefaa5045b58 { bgcolor=transparent; rankdir=LR; size="8.0, 12.0"; "CheckedDict" [fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",tooltip="A dictionary which checks that the keys and values are valid"]; "ConfigDict" [fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",tooltip="This is an optionally persistent dictionary used for configuration."]; "CheckedDict" -> "ConfigDict" [arrowsize=0.5,style="setlinewidth(0.5)"]; "CoreConfig" [URL="api/maelzel.core.config.CoreConfig.html#maelzel.core.config.CoreConfig",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="A CoreConfig is a ``dict`` like object which controls many aspects of **maelzel.core**"]; "ConfigDict" -> "CoreConfig" [arrowsize=0.5,style="setlinewidth(0.5)"]; }

CoreConfig Keys

A4:
Default: 442int
Between 10 - 10000
Freq. of the Kammerton A4. Normal values are 440, 442, 443 or 432 for old tuning, but any ‘fantasy’ value can be used
splitAcceptableDeviation:
Default: 4int
When splitting notes between staves, notes within this range of the split point will be grouped together if they all fit
chordAdjustGain:
Default: Truebool
Adjust the gain of a chord according to the number of notes, to prevent clipping
reprShowFreq:
Default: Falsebool
Show frequency when printing a Note in the console
semitoneDivisions:
Default: 4int
Choices: 1, 2, 4
The number of divisions per semitone (2=quarter-tones, 4=eighth-tones)
musescorepath:
Default: ‘’str
The command to use when calling MuseScore. For macOS users: it must be an absolute path pointing to the actual binary inside the .app bundle
lilypondpath:
Default: ‘’str
The path to the lilypond binary. It must be an absolute, existing path
.reprShowFractionsAsFloat:
Default: Truebool
*All time offsets and durations are kept as rational numbers to avoid rounding errors. If this option is True, these fractions are printed as floats in order to make them more readable. *
jupyterHtmlRepr:
Default: Truebool
If True, output html inside jupyter as part of the _repr_html_ hook. Under certain circumstances (for example, when generating documentation from a notebook) this html might result in style conflict. Setting in False will just output plain text
fixStringNotenames:
Default: Falsebool
If True, pitches given as string notenames are fixed at the spelling given at creation. Otherwise pitches might be respelled to match their context for better readability. Pitches given as midi notes or frequencies are always respelled
openImagesInExternalApp:
Default: Falsebool
Force opening images with an external tool, even when inside a Jupyter notebook
enharmonic.horizontalWeight:
Default: 1int
The weight of the horizontal dimension (note sequences) when evaluating an enharmonic variant
enharmonic.verticalWeight:
Default: 0.01float
The weight of the vertical dimension (chords within a voice) when evaluating an enharmonic variant
.enharmonic.debug:
Default: Falsebool
If True, print debug information while calculating automatic enharmonic spelling
.enharmonic.threeQuarterMicrotonePenalty:
Default: 20int
show.arpeggiateChord:
Default: auto(str, bool)
Choices: auto, False, True
Arpeggiate notes of a chord when showing. In auto mode, only arpeggiate when needed
show.centsAnnotationStyle:
Default: fontsize=6; placement=belowstr
Style used for cents annotations. The format is a list of <key>=<value> pairs, separated by semicolons. Possible keys are: fontsize, box (choices: rectangle, square, circle), placement (choices: above, below), italic (flag), bold (flag). Flag keys do not need any values. Example: “fontsize=12; italic; box=rectangle”
show.centsDeviationAsTextAnnotation:
Default: Truebool
show cents deviation as text when rendering notation
.show.centsAnnotationPlusSign:
Default: Truebool
Show a plus sign for possitive cents deviations
show.centSep:
Default: ,str
Separator used when displaying multiple cents deviation (in a chord)
show.scaleFactor:
Default: 0.75float
Affects the size of the generated image when using png format
show.scaleFactorMusicxml:
Default: 0.8float
Apply a scaling factor to images rendered via musicxml
show.staffSize:
Default: 10.0float
The size of a staff, in points
show.backend:
Default: lilypondstr
Choices: lilypond, musicxml
method/backend used when rendering notation
show.format:
Default: pngstr
Choices: pdf, png, repr
Used when no explicit format is passed to .show
show.cacheImages:
Default: Truebool
If True, cache rendered images. Set it to False for debugging. call `resetImageCache()` to reset manually
show.arpeggioDuration:
Default: 0.5float
Duration used for individual notes when rendering a chord as arpeggio
show.labelStyle:
Default: fontsize=9; placement=abovestr
Text size used for labelsThe format is a list of <key>=<value> pairs, separated by semicolons. Possible keys are: fontsize, box (choices: rectangle, square, circle), placement (choices: above, below), italic (flag), bold (flag). Flag keys do not need any values. Example: “fontsize=12; italic; box=rectangle”
show.pageOrientation:
Default: portraitstr
Choices: landscape, portrait
Page orientation when rendering to pdf
show.pageSize:
Default: a4str
Choices: a2, a3, a4
The page size when rendering to pdf
show.pageMarginMillimeters:
Default: 4int
Between 0 - 1000
The page margin in mm
show.glissEndStemless:
Default: Falsebool
When the end pitch of a gliss. is shown as gracenote, make this stemless
show.glissHideTiedNotes:
Default: Truebool
Hide tied notes which are part of a glissando
show.glissLineThickness:
Default: 2int
Choices: 1, 2, 3, 4
Line thikness when rendering glissandi. The value is abstract and it isup to the renderer to interpret it
show.glissLineType:
Default: solidstr
Choices: solid, wavy
Default line type for glissandi
show.lilypondPngStaffsizeScale:
Default: 1.5float
A factor applied to the staffsize when rendering to png via lilypond. Useful if rendered images appear too small in a jupyter notebook
show.lilypondGlissandoMinimumLength:
Default: 5int
The minimum length of a glissando in points. Increase this value if glissando linesare not shown or are too short (this might be the case within the context of dottednotes or accidentals)
show.pngResolution:
Default: 200int
Choices: 100, 200, 300, 600, 1200
DPI used when rendering to png
show.measureAnnotationStyle:
Default: box=rectangle; fontsize=12str
Style for measure annotations. The format is a list of <key>=<value> pairs, separated by semicolons. Possible keys are: fontsize, box (choices: rectangle, square, circle), placement (choices: above, below), italic (flag), bold (flag). Flag keys do not need any values. Example: “fontsize=12; italic; box=rectangle”
show.rehearsalMarkStyle:
Default: box=rectangle; fontsize=13; boldstr
Style for rehearsal marks. The format is a list of <key>=<value> pairs, separated by semicolons. Possible keys are: fontsize, box (choices: rectangle, square, circle), placement (choices: above, below), italic (flag), bold (flag). Flag keys do not need any values. Example: “fontsize=12; italic; box=rectangle”
show.respellPitches:
Default: Truebool
If True, try to find a suitable enharmonic representation of pitches whichhave not been fixed already by the user. Otherwise the canonical form of eachpitch is used, independent of the context
show.horizontalSpacing:
Default: mediumstr
Choices: default, large, medium, small, xlarge
Hint for the renderer to adjust horizontal spacing. The actual result depends on the backend and the format used.
show.fillDynamicFromAmplitude:
Default: Falsebool
If True, when rendering notation, if an object has an amplitude and does not have an explicit dynamic, add a dynamic according to the amplitude
show.jupyterMaxImageWidth:
Default: 1000int
A max. width in pixels for images displayed in a jupyter notebook
show.hideRedundantDynamics:
Default: Truebool
Hide redundant dynamics within a voice
show.asoluteOffsetForDetachedObjects:
Default: Falsebool
When showing an object which has a parent but is shown detached from it, shouldthe absolute offset be used?
show.voiceMaxStaves:
Default: 1int
Between 1 - 4
The maximum number of staves per voice when showing a Voice as notation. A voiceis a sequence of non-simultaneous events (notes, chords, etc.) but these canbe exploded over multiple staves (for example, a chord might expand across awide range and would need multiple extra lines in any clef
show.clipNoteheadShape:
Default: squarestr
Choices: , cluster, cross, diamond, harmonic, normal, rectangle, rhombus, slash, square, triangle, xcircle
Notehead shape to use for clips
show.referenceStaffsize:
Default: 12.0float
Staff size used as a reference to convert between staff size and scaling factor. This allows to use staff size as a general way to indicate the scale of a score, independent of the backend
show.musicxmlFontScaling:
Default: 1.0float
A scaling factor applied to font sizes when rendering to musicxml
show.autoClefChanges:
Default: Truebool
If True, add clef changes to a quantized part if needed. Otherwise, one clef is determined for each part and is not changed along the part.
.show.autoClefChangesWindow:
Default: 1int
When adding automatic clef changes, use this window size (number of elements per evaluation)
.show.keepClefBiasFactor:
Default: 2.0float
The higher this value, the more priority is given to keeping the previous clef during automatic clef changes
play.gain:
Default: 1.0float
Between 0 - 1
Default gain used when playing/recording
play.engineName:
Default: maelzel.corestr
Name of the play engine used
play.instr:
Default: sinstr
Default instrument used for playback. A list of available instruments can be queried via `availableInstrs`. New instrument presets can be defined via `defPreset`
play.fade:
Default: 0.02float
default fade time
play.fadeShape:
Default: cosstr
Choices: cos, linear, scurve
Curve-shape used for fading in/out
play.pitchInterpolation:
Default: linearstr
Choices: cos, linear
Curve shape for interpolating between pitches
play.numChannels:
Default: 2int
Between 1 - 128
Default number of channels (channels can be set explicitely when calling startPlayEngine
play.unschedFadeout:
Default: 0.05float
fade out when stopping a note
play.backend:
Default: defaultstr
Choices: alsa, auhal, default, jack, pa_cb, portaudio, pulse
backend used for playback
play.defaultAmplitude:
Default: 1.0float
Between 0 - 1
The amplitude of a Note/Chord when an amplitude is needed and the object has an undefined amplitude. This is only used if play.useDynamics if False
play.defaultDynamic:
Default: fstr
Choices: f, ff, fff, ffff, mf, mp, p, pp, ppp, pppp
THe dynamic of a Note/Chord when a dynamic is needed. This is only used if play.useDynamics is True. Any event with an amplitude will use that amplitude instead
play.generalMidiSoundfont:
Default: ‘’str
Path to a soundfont (sf2 file) with a general midi mapping
play.soundfontAmpDiv:
Default: 16384int
A divisor used to scale the amplitude of soundfonts to a range 0-1
play.soundfontInterpolation:
Default: linearstr
Choices: cubic, linear
Interpolation used when reading sample data from a soundfont.
play.schedLatency:
Default: 0.05float
Added latency when scheduling events to ensure time precission
play.verbose:
Default: Falsebool
If True, outputs extra debugging information regarding playback
play.useDynamics:
Default: Truebool
If True, any note/chord with a set dynamic will use that to modify its playback amplitude if no explicit amplitude is set
play.waitAfterStart:
Default: 0.5float
How much to wait for the sound engine to be operational after starting it
play.gracenoteDuration:
Default: 1/14(int, float, str)
Duration assigned to a gracenote for playback (in quarternotes)
rec.blocking:
Default: Truebool
Should recording be blocking or should be done async?
rec.sr:
Default: 44100int
Choices: 44100, 48000, 88200, 96000, 144000, 176400, 192000, 352800, 384000
Sample rate used when rendering offline
rec.ksmps:
Default: 64int
Choices: 1, 16, 32, 64, 128, 256
Samples per cycle when rendering offline (passed as ksmps to csound)
rec.numChannels:
Default: 2int
Between 1 - 128
The default number of channels when rendering to disk
rec.path:
Default: ‘’str
path used to save output files when rendering offline. If not given the default can be queried via `recordPath`
rec.verbose:
Default: Falsebool
Show debug output when calling csound as a subprocess
.rec.compressionBitrate:
Default: 224int
default bitrate to use when encoding to ogg or mp3
rec.extratime:
Default: 0.0float
Between 0.0 - inf
Default extratime added when recording
htmlTheme:
Default: lightstr
Choices: dark, light
Theme used when displaying html inside jupyter
quant.minBeatFractionAcrossBeats:
Default: 0.5float
when merging durations across beats, a merged duration cannot be smaller than this duration. This is to prevent joining durations across beats which might result in high rhythmic complexity
quant.nestedTuplets:
Default: None(NoneType, bool)
Choices: False, None, True
Are nested tuples allowed when quantizing? Not all display backends support nested tuples (musescore, used to render musicxml has no support for nested tuples). If None, this flag is determined based on the complexity preset (quant.complexity)
quant.nestedTupletsInMusicxml:
Default: Falsebool
If False, nested tuplets default to False when rendering to musicxml. This is because some musicxml renderers (MuseScore, for example) do not render nested tuplets properly. Nested tuplets will still be enabled if the config options “quant.nestedTuplets” is explicitely set to True.
quant.breakSyncopationsLevel:
Default: weakstr
Choices: all, none, strong, weak
Level at which to break syncopations, one of “all” (break all syncopations), “weak (break only syncopations over secondary beats)”, “strong” (break syncopations at strong beats) or “none” (do not break any syncopations)
quant.complexity:
Default: highstr
Choices: high, highest, low, lowest, medium
*Controls the allowed complexity in the notation. The higher the complexity, the more accurate the quantization, at the cost of a more complex notation. *
.quant.divisionErrorWeight:
Default: NoneNoneType
A weight (between 0 and 1) applied to the penalty of complex quantization of the beat. The higher this value is, the simpler the subdivision chosen. If set to None, this value is derived from the complexity preset (quant.complexity)
.quant.gridErrorWeight:
Default: NoneNoneType
A weight (between 0 and 1) applied to the deviation of a quantization to the actual attack times and durations during quantization. The higher this value, the more accurate the quantization (possibly resulting in more complex subdivisions of the beat). If None, the value is derived from the complexity preset (quant.complexity)
.quant.rhythmComplexityWeight:
Default: NoneNoneType
A weight (between 0 and 1) applied to the penalty calculated from the complexity of the rhythm during quantization. A higher value results in more complex rhythms being considered for quantization. If None, the value is derived from the complexity (quant.complexity)
.quant.gridErrorExp:
Default: NoneNoneType
An exponent applied to the grid error. The grid error is a value between 0-1 which indicates how accurate the grid representation is for a given quantization (a value of 0 indicates perfect timing). An exponent betwenn 0 < exp <= 1 will make grid errors weight more dramatically as they diverge from the most accurate solution. If None, the value is derived from the complexity setting (quant.complexity)
.quant.debug:
Default: Falsebool
Turns on debugging for the quantization process. This will show how different divisions of the beat are being evaluated by the quantizer in terms of what is contributing more to the ranking. With this information it is possible to adjust the weights (quant.rhythmCompleityWeight, .quant.divisionErrorWeight, etc)
.quant.debugShowNumRows:
Default: 50int
When quantization debugging is turned on this setting limits the number of different quantization possibilities shown
dynamicCurveShape:
Default: expon(0.3)str
The shape used to create the default dynamics curve. The most convenient shape is some variation of an exponential, given as expon(exp), where exp is the exponential used. exp < 1 will result in more resolution for soft dynamics
dynamicCurveMindb:
Default: -60int
Between -160 - 0
The amplitude (in dB) corresponding to the softest dynamic
dynamicCurveMaxdb:
Default: 0int
Between -160 - 0
The amplitude (in dB) corresponding to the loudest dynamic
dynamicCurveDynamics:
Default: ppp pp p mp mf f ff fffstr
Possible dynamic steps. A string with all dynamic steps, sorted from softest to loudest