The active wokspace

There is always an active Workspace. When maelzel.core is imported a new Workspace is created, which can be retrieved via getWorkspace

[15]:
from maelzel.core import *
from IPython.display import display

w = getWorkspace()
w
[15]:
Workspace(scorestruct=ScoreStruct(tempo=96, timesig=(3, 4)), config={}, dynamicCurve=DynamicCurve(shape=expon(0.3), mindb=-60.0, maxdb=0.0))

Alternatively the active workspace can be accessed via the active class variable, as Workspace.active

[9]:
w is Workspace.active
[9]:
True

The active workspace contains the working environment. The most important attributes encapsulated here are the score structure (.scorestruct) and the core configuration (.config)

Each new Workspace contains a basic ScoreStruct (4/4, quarter=60) and a copy of the root config

[24]:
w.scorestruct
[24]:

ScoreStruct

Meas. IndexTimesigTempo (quarter note)LabelRehearsalBarline
04/460
...
[25]:
w.config
[25]:

CoreConfig: maelzel:core


KeyValueTypeDescr
A4442between 10 - 10000Freq. of the Kammerton A4. Normal values are 440, 442, 443 or 432 for old tuning, but any 'fantasy' value can be used
chordAdjustGainTruetype: boolAdjust the gain of a chord according to the number of notes, to prevent clipping
dynamicCurveDynamicsppp pp p mp mf f ff ffftype: strPossible dynamic steps. A string with all dynamic steps, sorted from softest to loudest
dynamicCurveMaxdb0between -160 - 0The amplitude (in dB) corresponding to the loudest dynamic
dynamicCurveMindb-60between -160 - 0The amplitude (in dB) corresponding to the softest dynamic
dynamicCurveShapeexpon(0.3)type: strThe 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
enharmonic.horizontalWeight1type: intThe weight of the horizontal dimension (note sequences) when evaluating an enharmonic variant
enharmonic.verticalWeight0.01type: floatThe weight of the vertical dimension (chords within a voice) when evaluating an enharmonic variant
fixStringNotenamesFalsetype: boolIf 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
htmlThemelight{dark, light}Theme used when displaying html inside jupyter
jupyterHtmlReprTruetype: boolIf 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
lilypondpathtype: strThe path to the lilypond binary. It must be an absolute, existing path
musescorepathtype: strThe command to use when calling MuseScore. For macOS users: it must be an absolute path pointing to the actual binary inside the .app bundle
openImagesInExternalAppFalsetype: boolForce opening images with an external tool, even when inside a Jupyter notebook
play.backenddefault{alsa, auhal, default, jack, pa_cb, portaudio, pulse}backend used for playback
play.defaultAmplitude1.0between 0 - 1The 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.defaultDynamicf{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.engineNamemaelzel.coretype: strName of the play engine used
play.fade0.02type: floatdefault fade time
play.fadeShapecos{cos, linear, scurve}Curve-shape used for fading in/out
play.gain1.0between 0 - 1Default gain used when playing/recording
play.generalMidiSoundfonttype: strPath to a soundfont (sf2 file) with a general midi mapping
play.gracenoteDuration1/14type: (int, float, str)Duration assigned to a gracenote for playback (in quarternotes)
play.instrsintype: strDefault instrument used for playback. A list of available instruments can be queried via `availableInstrs`. New instrument presets can be defined via `defPreset`
play.numChannels2between 1 - 128Default number of channels (channels can be set explicitely when calling startPlayEngine
play.pitchInterpolationlinear{cos, linear}Curve shape for interpolating between pitches
play.schedLatency0.05type: floatAdded latency when scheduling events to ensure time precission
play.soundfontAmpDiv16384type: intA divisor used to scale the amplitude of soundfonts to a range 0-1
play.soundfontInterpolationlinear{cubic, linear}Interpolation used when reading sample data from a soundfont.
play.unschedFadeout0.05type: floatfade out when stopping a note
play.useDynamicsTruetype: boolIf True, any note/chord with a set dynamic will use that to modify its playback amplitude if no explicit amplitude is set
play.verboseFalsetype: boolIf True, outputs extra debugging information regarding playback
play.waitAfterStart0.5type: floatHow much to wait for the sound engine to be operational after starting it
quant.breakSyncopationsLevelnone{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.complexityhigh{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.minBeatFractionAcrossBeats0.5type: floatwhen 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.nestedTupletsNone{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.nestedTupletsInMusicxmlFalsetype: boolIf 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.
rec.blockingTruetype: boolShould recording be blocking or should be done async?
rec.extratime0.0between 0.0 - infDefault extratime added when recording
rec.ksmps64{1, 16, 32, 64, 128, 256}Samples per cycle when rendering offline (passed as ksmps to csound)
rec.numChannels2between 1 - 128The default number of channels when rendering to disk
rec.pathtype: strpath used to save output files when rendering offline. If not given the default can be queried via `recordPath`
rec.sr44100{44100, 48000, 88200, 96000, 144000, 176400, 192000, 352800, 384000}Sample rate used when rendering offline
rec.verboseFalsetype: boolShow debug output when calling csound as a subprocess
reprShowFreqFalsetype: boolShow frequency when printing a Note in the console
semitoneDivisions4{1, 2, 4}The number of divisions per semitone (2=quarter-tones, 4=eighth-tones)
show.arpeggiateChordauto{auto, False, True}Arpeggiate notes of a chord when showing. In auto mode, only arpeggiate when needed
show.arpeggioDuration0.5type: floatDuration used for individual notes when rendering a chord as arpeggio
show.asoluteOffsetForDetachedObjectsFalsetype: boolWhen showing an object which has a parent but is shown detached from it, shouldthe absolute offset be used?
show.autoClefChangesTruetype: boolIf 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.backendlilypond{lilypond, musicxml}method/backend used when rendering notation
show.cacheImagesTruetype: boolIf True, cache rendered images. Set it to False for debugging. call `resetImageCache()` to reset manually
show.centSep,type: strSeparator used when displaying multiple cents deviation (in a chord)
show.centsAnnotationStylefontsize=6; placement=belowtype: strStyle used for cents annotations. The format is a list of = 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.centsDeviationAsTextAnnotationTruetype: boolshow cents deviation as text when rendering notation
show.clipNoteheadShapesquare{, cluster, cross, diamond, harmonic, normal, rectangle, rhombus, slash, square, triangle, xcircle}Notehead shape to use for clips
show.fillDynamicFromAmplitudeFalsetype: boolIf 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.formatpng{pdf, png, repr}Used when no explicit format is passed to .show
show.glissEndStemlessFalsetype: boolWhen the end pitch of a gliss. is shown as gracenote, make this stemless
show.glissHideTiedNotesTruetype: boolHide tied notes which are part of a glissando
show.glissLineThickness2{1, 2, 3, 4}Line thikness when rendering glissandi. The value is abstract and it isup to the renderer to interpret it
show.glissLineTypesolid{solid, wavy}Default line type for glissandi
show.hideRedundantDynamicsTruetype: boolHide redundant dynamics within a voice
show.horizontalSpacingmedium{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.jupyterMaxImageWidth1000type: intA max. width in pixels for images displayed in a jupyter notebook
show.labelStylefontsize=9; placement=abovetype: strText size used for labelsThe format is a list of = 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.lilypondGlissandoMinimumLength5type: intThe 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.lilypondPngStaffsizeScale1.5type: floatA factor applied to the staffsize when rendering to png via lilypond. Useful if rendered images appear too small in a jupyter notebook
show.measureAnnotationStylebox=rectangle; fontsize=12type: strStyle for measure annotations. The format is a list of = 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.pageMarginMillimeters4between 0 - 1000The page margin in mm
show.pageOrientationportrait{landscape, portrait}Page orientation when rendering to pdf
show.pageSizea4{a2, a3, a4}The page size when rendering to pdf
show.pngResolution200{100, 200, 300, 600, 1200}DPI used when rendering to png
show.referenceStaffsize12.0type: floatStaff 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.rehearsalMarkStylebox=rectangle; fontsize=13; boldtype: strStyle for rehearsal marks. The format is a list of = 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.respellPitchesTruetype: boolIf 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.scaleFactor0.75type: floatAffects the size of the generated image when using png format
show.scaleFactorMusicxml0.8type: floatApply a scaling factor to images rendered via musicxml
show.staffSize10.0type: floatThe size of a staff, in points
show.voiceMaxStaves1between 1 - 4The 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
splitAcceptableDeviation4type: intWhen splitting notes between staves, notes within this range of the split point will be grouped together if they all fit
.enharmonic.debugFalsetype: boolIf True, print debug information while calculating automatic enharmonic spelling
.enharmonic.threeQuarterMicrotonePenalty20type: intNone
.quant.debugFalsetype: boolTurns 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.debugShowNumRows50type: intWhen quantization debugging is turned on this setting limits the number of different quantization possibilities shown
.quant.divisionErrorWeightNonetype: NoneTypeA 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.gridErrorExpNonetype: NoneTypeAn 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.gridErrorWeightNonetype: NoneTypeA 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.rhythmComplexityWeightNonetype: NoneTypeA 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)
.rec.compressionBitrate224type: intdefault bitrate to use when encoding to ogg or mp3
.reprShowFractionsAsFloatTruetype: boolAll 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.
.show.autoClefChangesWindow1type: intWhen adding automatic clef changes, use this window size (number of elements per evaluation)
.show.centsAnnotationPlusSignTruetype: boolShow a plus sign for possitive cents deviations
.show.keepClefBiasFactor2.0type: floatThe higher this value, the more priority is given to keeping the previous clef during automatic clef changes

Modifying the active Workspace vs creating a new Workspace

If you are not planning on working on multiple scores simultaneously, the most convenient way to setup your own score structure or to customize the configuration is to modify the active workspace. For example, the score structure can be set via setScoreStruct

[17]:
# Reset the scorestruct to the default
setScoreStruct()

chain = Chain(r"""
    4C:0.5
    4D:2
    4E:1
""")
chain.show()
chain.rec(nchnls=1, instr='piano')
../_images/notebooks_getWorkspace_8_0.png
[17]:
OfflineRenderer(outfile="/home/em/.local/share/maelzel/recordings/rec-2023-07-15T18:14:55.294.wav", 1 channels, 3.52 secs, 44100 Hz)

[11]:
setScoreStruct(timesig=(3, 4), tempo=96)
chain.show()
chain.rec(nchnls=1, instr='piano')

../_images/notebooks_getWorkspace_9_0.png
[11]:
OfflineRenderer(outfile="/home/em/.local/share/maelzel/recordings/rec-2023-07-15T18:12:43.483.wav", 1 channels, 2.21 secs, 44100 Hz)

Or you can create an independent Workspace with its own scorestruct:

[12]:
w = Workspace(scorestruct=ScoreStruct(timesig=(5, 8), tempo=112), active=True)
chain
[12]:
Chain([4C:0.5♩, 4D:2♩, 4E:1♩], dur=3.5)

Deactivating the active Workspace activates the previous workspace (there should always be an active Workspace)

[13]:
w.deactivate()
chain
[13]:
Chain([4C:0.5♩, 4D:2♩, 4E:1♩], dur=3.5)

As a side note, if you just want to test something under a different scorestruct, you can do use a ScoreStruct as a context manager. This clones the active Workspace with the given ScoreStruct and activates this newly created Workspace, to deactivate it when to context is exited.

[18]:
with ScoreStruct(r'''
    7/16, 116
    11/16, 48
'''):
    chain.show()
    display(chain.rec(nchnls=1, instr='piano'))

../_images/notebooks_getWorkspace_15_0.png
OfflineRenderer(outfile="/home/em/.local/share/maelzel/recordings/rec-2023-07-15T18:14:59.880.wav", 1 channels, 3.11 secs, 44100 Hz)

The same is valid for the configuration. You can modify the active Workspace by changing its config, either via setConfig or by directly assigning to .config:

[21]:
setScoreStruct()

chain = Chain(r'''
  C4+15:1
  4Eb-19:0.5
  3B+:1.5
''')
chain
[21]:
Chain([4C+15:1♩, 4Eb-19:0.5♩, 3B+:1.5♩], dur=3)
[22]:
config = CoreConfig()
config['show.centsDeviationAsTextAnnotation'] = False

setConfig(config)   # This is the same as calling `config.activate()`
chain
[22]:
Chain([4C+15:1♩, 4Eb-19:0.5♩, 3B+:1.5♩], dur=3)

Reset the config to the root config

[23]:
CoreConfig.root.activate()
chain
[23]:
Chain([4C+15:1♩, 4Eb-19:0.5♩, 3B+:1.5♩], dur=3)