Developers’ Reference

The score module

class ms3.score.Score(mscx_src=None, infer_label_types=['dcml'], read_only=False, logger_name='Score', level=None, parser='bs4')[source]

Object representing a score.

infer_label_types

Changing this value results in a call to infer_types().

Type

list or dict, optional

logger

Current logger that the object is using.

Type

logging.Logger or logging.LoggerAdapter

parser

The only XML parser currently implemented is BeautifulSoup 4.

Type

{‘bs4’}

paths, files, fnames, fexts, logger_names

Dictionaries for keeping track of file information handled by handle_path().

Type

dict

handle_path(path, key)[source]

Puts the path into paths, files, fnames, fexts dicts with the given key.

property mscx

Returns the MSCX object with the parsed score.

class ms3.score.MSCX(mscx_src=None, read_only=False, parser='bs4', logger_name='MSCX', level=None)[source]

Object for interacting with the XML structure of a MuseScore 3 file.

mscx_src

MuseScore 3 file to parse.

Type

str

_parsed

Holds the MSCX score parsed by the selected parser.

Type

_MSCX_bs4

parser

Which XML parser to use.

Type

str, optional

infer_label_types :obj:`bool`, optional

For label_type 0 (simple string), mark which ones

logger_name

If you have defined a logger, pass its name.

Type

str, optional

level

Pass a level name for which (and above which) you want to see log records.

Type

{‘W’, ‘D’, ‘I’, ‘E’, ‘C’, ‘WARNING’, ‘DEBUG’, ‘INFO’, ‘ERROR’, ‘CRITICAL’}, optional

output_mscx(filepath)

Write the internal score representation to a file.

add_labels(df, label='label', mc='mc', onset='onset', staff='staff', voice='voice', **kwargs)[source]
Parameters
  • df (pandas.DataFrame) – DataFrame with labels to be added.

  • mc, onset, staff, voice (label,) – Names of the DataFrame columns for the five required parameters.

  • kwargs

    label_type, root, base, leftParen, rightParen, offset_x, offset_y, nashville

    For these parameters, the standard column names are used automatically if the columns are present. If the column names have changed, pass them as kwargs, e.g. base='name_of_the_base_column'

Returns

Return type

None

store_list(what='all', folder=None, suffix=None, **kwargs)[source]

Store one or several several lists as TSV files(s).

Parameters
  • what (str or Collection, optional) – Defaults to ‘all’ but could instead be one or several strings out of {‘notes’, ‘rests’, ‘notes_and_rests’, ‘measures’, ‘events’, ‘labels’, ‘chords’, ‘expanded’}

  • folder (str, optional) – Where to store. Defaults to the directory of the parsed MSCX file.

  • suffix (str or Collection, optional) – Suffix appended to the file name of the parsed MSCX file to create a new file name. Defaults to None, meaning that standard suffixes based on what are attached. Number of suffixes needs to be equal to the number of what.

  • **kwargs – Keyword arguments for pandas.DataFrame.to_csv(). Defaults to {'sep': '   ', 'index': False}. If ‘sep’ is changed to a different separator, the file extension(s) will be changed to ‘.csv’ rather than ‘.tsv’.

Returns

Return type

None

property version

MuseScore version with which the file was created (read-only).

The annotations module

class ms3.annotations.Annotations(tsv_path=None, df=None, index_col=None, sep='\t', infer_types={}, logger_name='Annotations', level=None, **kwargs)[source]

Class for storing, converting and manipulating annotation labels.

property label_types

Returns the counts of the label_types as dict.

get_labels(staff=None, voice=None, label_type=None, positioning=True, decode=False, drop=False, warnings=True)[source]

Returns an annotation label .

Parameters
  • staff (int, optional) – Select harmonies from a given staff only. Pass staff=1 for the upper staff.

  • label_type ({0, 1, 2, 3, 'dcml', ..}, optional) –

    If MuseScore’s harmony feature has been used, you can filter harmony types by passing

    0 for unrecognized strings 1 for Roman Numeral Analysis 2 for Nashville Numbers 3 for encoded absolute chords ‘dcml’ for labels from the DCML harmonic annotation standard … self-defined types that have been added to self.regex_dict through the use of self.infer_types()

  • positioning (bool, optional) – Set to True if you want to include information about how labels have been manually positioned.

  • decode (bool, optional) – Set to True if you don’t want to keep labels in their original form as encoded by MuseScore (with root and bass as TPC (tonal pitch class) where C = 14).

  • drop (bool, optional) – Set to True to delete the returned labels from this object.

  • warnings (bool, optional) – Set to False to suppress warnings about non-existent label_types.

expand_dcml(drop_others=True, warn_about_others=True)[source]

Expands all labels where the label_type has been inferred as ‘dcml’ and stores the DataFrame in self._expanded.

Parameters
  • drop_others (bool, optional) – Set to False if you want to keep labels in the expanded DataFrame which have not label_type ‘dcml’.

  • warn_about_others (bool, optional) – Set to False to suppress warnings about labels that have not label_type ‘dcml’. Is automatically set to False if drop_others is set to False.

Returns

Expanded DCML labels

Return type

pandas.DataFrame

The parse module

class ms3.parse.Parse(dir=None, key=None, index=None, file_re='\\.mscx$', folder_re='.*', exclude_re='^(\\.|__)', recursive=True, logger_name='Parse', level=None)[source]

Class for storing and manipulating the information from multiple parses (i.e. Score objects).

property parsed

Returns an overview of the MSCX files that have already been parsed.

add_dir(dir, key=None, index=None, file_re='\\.mscx$', folder_re='.*', exclude_re='^(\\.|__)', recursive=True)[source]

This function scans the directory dir for files matching the criteria.

Parameters
  • dir (str) – Directory to scan for files.

  • key (str, optional) –

    Pass a string to identify the loaded files.
    By default, the relative sub-directories of dir are used as keys. For example, for files within dir itself, the key would be '.', for files in the subfolder scores it would be 'scores', etc.

  • index (element or Collection of {‘key’, ‘fname’, ‘i’, Collection}) –

    Change this parameter if you want to create particular indices for multi-piece DataFrames.
    The resulting index must be unique (for identification) and have as many elements as added files.
    Every single element or Collection of elements ∈ {‘key’, ‘fname’, ‘i’, Collection} stands for an index level.
    In other words, a single level will result in a single index and a collection of levels will result in a MultiIndex.
    If you pass a Collection that does not start with one of {‘key’, ‘fname’, ‘i’}, it is interpreted as an index level itself and needs to have at least as many elements as the number of added files.
    The default None is equivalent to passing (key, i), i.e. a MultiIndex of IDs.
    ’fname’ evokes an index level made from file names.

  • file_re

  • folder_re

  • exclude_re

  • recursive

collect_lists(keys=None, notes=False, rests=False, notes_and_rests=False, measures=False, events=False, labels=False, chords=False, expanded=False, only_new=True)[source]

Extracts DataFrames from the parsed scores in keys and stores them in dictionaries.

Parameters
  • keys

  • notes

  • rests

  • notes_and_rests

  • measures

  • events

  • labels

  • chords

  • expanded

  • only_new (bool, optional) – Set to True to also retrieve lists that have already been retrieved.

Returns

Return type

None

count_annotation_layers(keys=None, per_key=False, detached=False)[source]

Returns a dict {key: Counter} or just a Counter.

Parameters
  • keys (str or Collection, defaults to None) – Key(s) for which to count annotation layers.

  • per_key (bool, optional) – If set to True, the results are returned as a dict {key: Counter}, otherwise the counts are summed up in one Counter.

  • detached (bool, optional) – Set to True in order to count layers in annotations that are currently not attached to a score.

Returns

Return type

dict or collections.Counter

count_extensions(keys=None, per_key=False)[source]

Returns a dict {key: Counter} or just a Counter.

Parameters
  • keys (str or Collection, defaults to None) – Key(s) for which to count file extensions.

  • per_key (bool, optional) – If set to True, the results are returned as a dict {key: Counter}, otherwise the counts are summed up in one Counter.

Returns

Return type

dict or collections.Counter

parse(keys=None, read_only=True, level=None, parallel=True, only_new=True, fexts=None, **kwargs)[source]

Shorthand for executing parse_mscx and parse_tsv at a time.

store_mscx(keys=None, root_dir=None, folder='.', suffix='', simulate=False)[source]

Stores the parsed MuseScore files in their current state, e.g. after detaching or attaching annotations.

The expand_dcml module

This is the same code as in the corpora repo as copied on September 24, 2020 and then adapted.

class ms3.expand_dcml.SliceMaker[source]

This class serves for storing slice notation such as :3 as a variable or passing it as function argument.

Examples

SM = SliceMaker()
some_function( slice_this, SM[3:8] )

select_all = SM[:]
df.loc[select_all]
ms3.expand_dcml.expand_labels(df, column='label', regex=None, cols={}, dropna=False, propagate=True, relative_to_global=False, chord_tones=True, absolute=False, all_in_c=False)[source]

Split harmony labels complying with the DCML syntax into columns holding their various features and allows for additional computations and transformations.

Uses: compute_chord_tones(), features2type(), labels2global_tonic(), propagate_keys(), propagate_pedal(), replace_special(), rn2tpc(), split_alternatives(), split_labels(), transform(), transpose()

Parameters
  • df (pandas.DataFrame) – Dataframe where one column contains DCML chord labels.

  • column (str) – Name of the column that holds the harmony labels.

  • regex (re.Pattern) – Compiled regular expression used to split the labels. It needs to have named groups. The group names are used as column names unless replaced by cols.

  • cols (dict, optional) – Dictionary to map the regex’s group names to deviating column names of your choice.

  • dropna (bool, optional) – Pass True if you want to drop rows where column is NaN/<NA>

  • propagate (bool, optional) – By default, information about global and local keys and about pedal points is spread throughout the DataFrame. Pass False if you only want to split the labels into their features. This ignores all following parameters because their expansions depend on information about keys.

  • relative_to_global (bool, optional) – Pass True if you want all labels expressed with respect to the global key. This levels and eliminates the features localkey and relativeroot.

  • chord_tones (bool, optional) – Pass True if you want to add four columns that contain information about each label’s chord, added, root, and bass tones. The pitches are expressed as intervals relative to the respective chord’s local key or, if relative_to_global=True, to the globalkey. The intervals are represented as integers that represent stacks of fifths over the tonic, such that 0 = tonic, 1 = dominant, -1 = subdominant, 2 = supertonic etc.

  • absolute (bool, optional) – Pass True if you want to transpose the relative chord_tones to the global key, which makes them absolute so they can be expressed as actual note names. This implies prior conversion of the chord_tones (but not of the labels) to the global tonic.

  • all_in_c (bool, optional) – Pass True to transpose chord_tones to C major/minor. This performs the same transposition of chord tones as relative_to_global but without transposing the labels, too. This option clashes with absolute=True.

Returns

Original DataFrame plus additional columns with split features.

Return type

pandas.DataFrame

ms3.expand_dcml.transpose(e, n)[source]

Add n to all elements e recursively.

ms3.expand_dcml.split_alternatives(df, column='label', inplace=False)[source]

Splits labels that come with an alternative separated by ‘-‘ and adds a new column. Only one alternative is taken into account. df is mutated inplace.

Parameters
  • df (pandas.DataFrame) – Dataframe where one column contains DCML chord labels.

  • column (str, optional) – Name of the column that holds the harmony labels.

  • inplace (bool, optional) – Pass True if you want to mutate df.

Example

>>> import pandas as pd
>>> labels = pd.read_csv('labels.csv')
>>> split_alternatives(labels, inplace=True)
ms3.expand_dcml.split_labels(df, column, regex, cols={}, dropna=False, inplace=False, **kwargs)[source]

Split harmony labels complying with the DCML syntax into columns holding their various features.

Parameters
  • df (pandas.DataFrame) – Dataframe where one column contains DCML chord labels.

  • column (str) – Name of the column that holds the harmony labels.

  • regex (re.Pattern) – Compiled regular expression used to split the labels. It needs to have named groups. The group names are used as column names unless replaced by cols.

  • cols (dict) – Dictionary to map the regex’s group names to deviating column names.

  • dropna (bool, optional) – Pass True if you want to drop rows where column is NaN/<NA>

  • inplace (bool, optional) – Pass True if you want to mutate df.

ms3.expand_dcml.features2type(numeral, form=None, figbass=None)[source]

Turns a combination of the three chord features into a chord type.

Returns

  • ‘M’ (Major triad)

  • ’m’ (Minor triad)

  • ’o’ (Diminished triad)

  • ’+’ (Augmented triad)

  • ’mm7’ (Minor seventh chord)

  • ’Mm7’ (Dominant seventh chord)

  • ’MM7’ (Major seventh chord)

  • ’mM7’ (Minor major seventh chord)

  • ’o7’ (Diminished seventh chord)

  • ’%7’ (Half-diminished seventh chord)

  • ’+7’ (Augmented (minor) seventh chord)

  • ’+M7’ (Augmented major seventh chord)

ms3.expand_dcml.replace_special(df, regex, merge=False, inplace=False, cols={}, special_map={})[source]
Move special symbols in the numeral column to a separate column and replace them by the explicit chords they stand for.
In particular, this function replaces the symbols It, Ger, and Fr.

Uses: merge_changes()

Parameters
  • df (pandas.DataFrame) – Dataframe containing DCML chord labels that have been split by split_labels().

  • regex (re.Pattern) – Compiled regular expression used to split the labels replacing the special symbols.It needs to have named groups. The group names are used as column names unless replaced by cols.

  • merge (bool, optional) – False: By default, existing values, except figbass, are overwritten. True: Merge existing with new values (for changes and relativeroot).

  • cols (dict, optional) –

    The special symbols appear in the column numeral and are moved to the column special. In case the column names for ['numeral','form', 'figbass', 'changes', 'relativeroot', 'special'] deviate, pass a dict, such as

    {'numeral':         'numeral_col_name',
     'form':            'form_col_name
     'figbass':         'figbass_col_name',
     'changes':         'changes_col_name',
     'relativeroot':    'relativeroot_col_name',
     'special':         'special_col_name'}
    

  • special_map (dict, optional) – In case you want to add or alter special symbols to be replaced, pass a replacement map, e.g. {‘N’: ‘bII6’}. The column ‘figbass’ is only altered if it’s None to allow for inversions of special chords.

  • inplace (bool, optional) – Pass True if you want to mutate df.

ms3.expand_dcml.merge_changes(left, right, *args)[source]

Merge two changes into one, e.g. b3 and +#7 to +#7b3.

Uses: changes2list()

ms3.expand_dcml.changes2list(changes, sort=True)[source]

Splits a string of changes into a list of 4-tuples.

Example

>>> changes2list('+#7b5')
[('+#7', '+', '#', '7'),
 ('b5',  '',  'b', '5')]
ms3.expand_dcml.propagate_keys(df, globalkey='globalkey', localkey='localkey', add_bool=True)[source]
Propagate information about global keys and local keys throughout the dataframe.
Pass split harmonies for one piece at a time. For concatenated pieces, use apply().

Uses: series_is_minor()

Parameters
  • df (pandas.DataFrame) – Dataframe containing DCML chord labels that have been split by split_labels().

  • localkey (globalkey,) – In case you renamed the columns, pass column names.

  • add_bool (bool, optional) – Pass True if you want to add two boolean columns which are true if the respective key is a minor key.

ms3.expand_dcml.series_is_minor(S, is_name=True)[source]

Returns boolean Series where every value in S representing a minor key/chord is True.

ms3.expand_dcml.propagate_pedal(df, relative=True, drop_pedalend=True, cols={})[source]

Propagate the pedal note for all chords within square brackets. By default, the note is expressed in relation to each label’s localkey.

Uses: rel2abs_key(), abs2rel_key()

Parameters
  • df (pandas.DataFrame) – Dataframe containing DCML chord labels that have been split by split_labels() and where the keys have been propagated using propagate_keys().

  • relative (bool, optional) – Pass False if you want the pedal note to stay the same even if the localkey changes.

  • drop_pedalend (bool, optional) – Pass False if you don’t want the column with the ending brackets to be dropped.

  • cols (dict, optional) –

    In case the column names for ['pedal','pedalend', 'globalkey', 'localkey'] deviate, pass a dict, such as

    {'pedal':       'pedal_col_name',
     'pedalend':    'pedalend_col_name',
     'globalkey':   'globalkey_col_name',
     'localkey':    'localkey_col_name'}
    

ms3.expand_dcml.abs2rel_key(absolute, localkey, global_minor=False)[source]

Expresses a Roman numeral as scale degree relative to a given localkey. The result changes depending on whether Roman numeral and localkey are interpreted within a global major or minor key.

Uses: split_sd()

Parameters
  • absolute (str) – Relative key expressed as Roman scale degree of the local key.

  • localkey (str) – The local key in terms of which absolute will be expressed.

  • global_minor (bool, optional) – Has to be set to True if absolute and localkey are scale degrees of a global minor key.

Examples

In a minor context, the key of II would appear within the key of vii as #III.

>>> abs2rel_key('iv', 'VI', global_minor=False)
'bvi'       # F minor expressed with respect to A major
>>> abs2rel_key('iv', 'vi', global_minor=False)
'vi'        # F minor expressed with respect to A minor
>>> abs2rel_key('iv', 'VI', global_minor=True)
'vi'        # F minor expressed with respect to Ab major
>>> abs2rel_key('iv', 'vi', global_minor=True)
'#vi'       # F minor expressed with respect to Ab minor
>>> abs2rel_key('VI', 'IV', global_minor=False)
'III'       # A major expressed with respect to F major
>>> abs2rel_key('VI', 'iv', global_minor=False)
'#III'       # A major expressed with respect to F minor
>>> abs2rel_key('VI', 'IV', global_minor=True)
'bIII'       # Ab major expressed with respect to F major
>>> abs2rel_key('VI', 'iv', global_minor=False)
'III'       # Ab major expressed with respect to F minor
ms3.expand_dcml.compute_chord_tones(df, bass_only=False, expand=False, cols={})[source]

Compute the chord tones for DCML harmony labels. They are returned as lists of tonal pitch classes in close position, starting with the bass note. The tonal pitch classes represent intervals relative to the local tonic:

-2: Second below tonic -1: fifth below tonic 0: tonic 1: fifth above tonic 2: second above tonic, etc.

The labels need to have undergone split_labels() and propagate_keys(). Pedal points are not taken into account.

Uses: features2tpcs()

Parameters
  • df (pandas.DataFrame) – Dataframe containing DCML chord labels that have been split by split_labels() and where the keys have been propagated using propagate_keys(add_bool=True).

  • bass_only (bool, optional) – Pass True if you need only the bass note.

  • expand (bool, optional) – Pass True if you need chord tones and added tones in separate columns.

  • cols (dict, optional) –

    In case the column names for ['mc', 'numeral', 'form', 'figbass', 'changes', 'relativeroot', 'localkey', 'globalkey'] deviate, pass a dict, such as

    {'mc':              'mc',
     'numeral':         'numeral_col_name',
     'form':            'form_col_name',
     'figbass':         'figbass_col_name',
     'changes':         'changes_col_name',
     'relativeroot':    'relativeroot_col_name',
     'localkey':        'localkey_col_name',
     'globalkey':       'globalkey_col_name'}
    

    You may also deactivate columns by setting them to None, e.g. {‘changes’: None}

Returns

For every row of df one tuple with chord tones, expressed as tonal pitch classes. If expand is True, the function returns a DataFrame with four columns: Two with tuples for chord tones and added tones, one with the chord root, and one with the bass note.

Return type

pandas.Series or pandas.DataFrame

ms3.expand_dcml.features2tpcs(numeral, form=None, figbass=None, changes=None, relativeroot=None, key='C', minor=None, merge_tones=True, bass_only=False, mc=None)[source]

Given the features of a chord label, this function returns the chord tones in the order of the inversion, starting from the bass note. The tones are expressed as tonal pitch classes, where -1=F, 0=C, 1=G etc.

Uses: changes2list(), name2tpc(), resolve_relative_keys(), rn2tpc(), sort_tpcs(), str_is_minor()

Parameters
  • numeral (str) – Roman numeral of the chord’s root

  • form ({None, 'M', 'o', '+' '%'}, optional) – Indicates the chord type if not a major or minor triad (for which `form`is None). ‘%’ and ‘M’ can only occur as tetrads, not as triads.

  • figbass ({None, '6', '64', '7', '65', '43', '2'}, optional) – Indicates chord’s inversion. Pass None for triad root position.

  • changes (str, optional) – Added steps such as ‘+6’ or suspensions such as ‘4’ or any combination such as (9+64). Numbers need to be in descending order.

  • relativeroot (str, optional) – Pass a Roman scale degree if numeral is to be applied to a different scale degree of the local key, as in ‘V65/V’

  • key (str or int, optional) – The local key expressed as the root’s note name or a tonal pitch class. If it is a name and minor is None, uppercase means major and lowercase minor. If it is a tonal pitch class, minor needs to be specified.

  • minor (bool, optional) – Pass True for minor and False for major. Can be omitted if key is a note name. This affects calculation of chords related to III, VI and VII.

  • merge_tones (bool, optional) – Pass False if you want the function to return two tuples, one with (potentially suspended) chord tones and one with added notes.

  • bass_only (bool, optional) – Return only the bass note instead of all chord tones.

  • mc (int or str) – Pass measure count to display it in warnings.

ms3.expand_dcml.str_is_minor(tone, is_name=True)[source]

Returns True if tone represents a minor key or chord.

ms3.expand_dcml.rn2tpc(rn, global_minor=False)[source]

Turn a Roman numeral into a TPC interval (e.g. for transposition purposes).

Uses: split_sd()

ms3.expand_dcml.split_sd(sd, count=False)[source]

Splits a scale degree such as ‘bbVI’ or ‘b6’ into accidentals and numeral.

Parameters
  • sd (str) – Scale degree.

  • count (bool, optional) – Pass True to get the accidentals as integer rather than as string.

ms3.expand_dcml.labels2global_tonic(df, cols={}, inplace=False)[source]

Transposes all numerals to their position in the global major or minor scale. This eliminates localkeys and relativeroots. The resulting chords are defined by [numeral, figbass, changes, globalkey_is_minor] (and pedal).

Uses: transform(), rel2abs_key^, :py:func:`resolve_relative_keys() -> str_is_minor() transpose_changes(), series_is_minor(),

Parameters
  • df (pandas.DataFrame) – Dataframe containing DCML chord labels that have been split by split_labels() and where the keys have been propagated using propagate_keys(add_bool=True).

  • cols (dict, optional) –

    In case the column names for ['numeral', 'form', 'figbass', 'changes', 'relativeroot', 'localkey', 'globalkey'] deviate, pass a dict, such as

    {'chord':           'chord_col_name'
     'pedal':           'pedal_col_name',
     'numeral':         'numeral_col_name',
     'form':            'form_col_name',
     'figbass':         'figbass_col_name',
     'changes':         'changes_col_name',
     'relativeroot':    'relativeroot_col_name',
     'localkey':        'localkey_col_name',
     'globalkey':       'globalkey_col_name'}}
    

  • inplace (bool, optional) – Pass True if you want to mutate the input.

Returns

If inplace=False, the relevant features of the transposed chords are returned. Otherwise, the original DataFrame is mutated.

Return type

pandas.DataFrame

ms3.expand_dcml.rel2abs_key(rel, localkey, global_minor=False)[source]

Expresses a Roman numeral that is expressed relative to a localkey as scale degree of the global key. For local keys {III, iii, VI, vi, VII, vii} the result changes depending on whether the global key is major or minor.

Uses: split_sd()

Parameters
  • rel (str) – Relative key or chord expressed as Roman scale degree of the local key.

  • localkey (str) – The local key to which rel is relative.

  • global_minor (bool, optional) – Has to be set to True if localkey is a scale degree of a global minor key.

Examples

If the label viio6/VI appears in the context of the local key VI or vi, viio6 the absolute key to which viio6 applies depends on the global key. The comments express the examples in relation to global C major or C minor.

>>> rel2abs_key('vi', 'VI', global_minor=False)
'#iv'       # vi of A major = F# minor
>>> rel2abs_key('vi', 'vi', global_minor=False)
'iv'        # vi of A minor = F minor
>>> rel2abs_key('vi', 'VI', global_minor=True)
'iv'        # vi of Ab major = F minor
>>> rel2abs_key('vi', 'vi', global_minor=True)
'biv'       # vi of Ab minor = Fb minor

The same examples hold if you’re expressing in terms of the global key the root of a VI-chord within the local keys VI or vi.

ms3.expand_dcml.resolve_relative_keys(relativeroot, minor=False)[source]

Resolve nested relative keys, e.g. ‘V/V/V’ => ‘VI’.

Uses: rel2abs_key(), str_is_minor()

relativerootstr

One or several relative keys, e.g. iv/v/VI (fourth scale degree of the fifth scale degree of the sixth scale degree)

minorbool, optional

Pass True if the last of the relative keys is to be interpreted within a minor context.

ms3.expand_dcml.transpose_changes(changes, old_num, new_num, old_minor=False, new_minor=False)[source]

Since the interval sizes expressed by the changes of the DCML harmony syntax depend on the numeral’s position in the scale, these may change if the numeral is transposed. This function expresses the same changes for the new position. Chord tone alterations (of 3 and 5) stay untouched.

Uses: changes2tpc()

Parameters
  • changes (str) – A string of changes following the DCML harmony standard.

  • new_num (old_num,) – Old numeral, new numeral.

  • new_minor (old_minor,) – For each numeral, pass True if it occurs in a minor context.

ms3.expand_dcml.transform_columns(df, func, columns=None, param2col=None, inplace=False, **kwargs)[source]

Wrapper function to use transform() on df[columns], leaving the other columns untouched.

Parameters
  • df (pandas.DataFrame) – DataFrame where columns (or column combinations) work as function arguments.

  • func (callable) – Function you want to apply to all elements in columns.

  • columns (list) – Columns to which you want to apply func.

  • param2col (dict or list, optional) – Mapping from parameter names of func to column names. If you pass a list of column names, the columns’ values are passed as positional arguments. Pass None if you want to use all columns as positional arguments.

  • inplace (bool, optional) – Pass True if you want to mutate df rather than getting an altered copy.

  • **kwargs (keyword arguments for transform()) –

ms3.expand_dcml.transform_note_columns(df, to, note_cols=['chord_tones', 'added_tones', 'bass_note', 'root'], minor_col='localkey_is_minor', inplace=False, **kwargs)[source]

Turns columns with line-of-fifth tonal pitch classes into another representation.

Uses: transform_columns()

Parameters
  • df (pandas.DataFrame) – DataFrame where columns (or column combinations) work as function arguments.

  • to ({'name', 'iv', 'pc', 'sd', 'rn'}) –

    The tone representation that you want to get from the note_cols.

    • ’name’: Note names. Should only be used if the stacked fifths actually represent

      absolute tonal pitch classes rather than intervals over the local tonic. In other words, make sure to use ‘name’ only if 0 means C rather than I.

    • ’iv’: Intervals such that 0 = ‘P1’, 1 = ‘P5’, 4 = ‘M3’, -3 = ‘m3’, 6 = ‘A4’,

      -6 = ‘D5’ etc.

    • ’pc’: (Relative) chromatic pitch class, or distance from tonic in semitones.

    • ’sd’: Scale degrees such that 0 = ‘1’, -1 = ‘4’, -2 = ‘b7’ in major, ‘7’ in minor etc.

      This representation requires a boolean column minor_col which is True in those rows where the stacks of fifths occur in a local minor context and False for the others. Alternatively, if all pitches are in the same mode or you simply want to express them as degrees of particular mode, you can pass the boolean keyword argument minor.

    • ’rn’: Roman numerals such that 0 = ‘I’, -2 = ‘bVII’ in major, ‘VII’ in minor etc.

      Requires boolean ‘minor’ values, see ‘sd’.

  • note_cols (list, optional) – List of columns that hold integers or collections of integers that represent stacks of fifth (0 = tonal center, 1 = fifth above, -1 = fourth above, etc).

  • minor_col (str, optional) – If to is ‘sd’ or ‘rn’, specify a boolean column where the value is True in those rows where the stacks of fifths occur in a local minor context and False for the others.

ms3.expand_dcml.changes2tpc(changes, numeral, minor=False, root_alterations=False)[source]

Given a numeral and changes, computes the intervals that the changes represent. Changes do not express absolute intervals but instead depend on the numeral and the mode.

Uses: split_sd(), changes2list()

Parameters
  • changes (str) – A string of changes following the DCML harmony standard.

  • numeral (str) – Roman numeral. If it is preceded by accidentals, it depends on the parameter root_alterations whether these are taken into account.

  • minor (bool, optional) – Set to true if the numeral occurs in a minor context.

  • root_alterations (bool, optional) – Set to True if accidentals of the root should change the result.

ms3.expand_dcml.chord2tpcs(chord, regex, **kwargs)[source]

Split a chord label into its features and apply features2tpcs().

Uses: features2tpcs()

Parameters
  • chord (str) – Chord label that can be split into the features [‘numeral’, ‘form’, ‘figbass’, ‘changes’, ‘relativeroot’].

  • regex (re.Pattern) – Compiled regex with named groups for the five features.

  • **kwargs – arguments for features2tpcs (pass MC to show it in warnings!)