Previous topic

music21.medren

Next topic

music21.meter

Table Of Contents

Table Of Contents

music21.metadata

Classes and functions for creating and processing metadata associated with scores, works, and fragments, such as titles, movements, authors, publishers, and regions.

The Metadata object is the main public interface to metadata components. A Metadata object can be added to a Stream and used to set common score attributes, such as title and composer. A Metadata object found at offset zero can be accessed through a Stream’s metadata property.

The following example creates a Stream object, adds a Note object, and configures and adds the title and composer properties of a Metadata object.

>>> from music21 import *
>>> s = stream.Stream()
>>> s.append(note.Note())
>>> s.insert(metadata.Metadata())
>>> s.metadata.title = 'title'
>>> s.metadata.composer = 'composer'
>>> s.show()
_images/moduleMetadata-01.png
music21.metadata.abbreviationToRole(value)

Get ROLE_ABBREVIATIONS as string-like attributes, used for Contributors.

>>> from music21 import *
>>> metadata.abbreviationToRole('com')
'composer'
>>> metadata.abbreviationToRole('lib')
'librettist'
>>> for id in metadata.ROLE_ABBREVIATIONS:
...    post = metadata.abbreviationToRole(id)
music21.metadata.abbreviationToWorkId(value)

Get work id abbreviations.

>>> from music21 import *
>>> metadata.abbreviationToWorkId('otl')
'title'
>>> for id in metadata.WORK_ID_ABBREVIATIONS:
...    post = metadata.abbreviationToWorkId(id)
music21.metadata.errorToSymbol(value)

Convert an error string (appoximate, uncertain) into a symbol.

>>> from music21 import *
>>> metadata.errorToSymbol('approximate')
'~'
>>> metadata.errorToSymbol('uncertain')
'?'
music21.metadata.roleToAbbreviation(value)

Get a role id from a string representation.

>>> from music21 import *
>>> metadata.roleToAbbreviation('composer')
'com'
>>> for n in metadata.ROLES:
...     post = metadata.roleToAbbreviation(n)
music21.metadata.workIdToAbbreviation(value)

Get a work abbreviation from a string representation.

>>> from music21 import *
>>> metadata.workIdToAbbreviation('localeOfComposition')
'opc'
>>> for n in metadata.WORK_IDS:
...     post = metadata.workIdToAbbreviation(n)

Metadata

Inherits from: Music21Object

class music21.metadata.Metadata(*args, **keywords)

Metadata represent data for a work or fragment, including title, composer, dates, and other relevant information.

Metadata is a Music21Object subclass, meaing that it can be positioned on a Stream by offset and have a Duration.

In many cases, each Stream will have a single Metadata object at the zero offset position.

>>> from music21 import *
>>> md = metadata.Metadata(title='Concerto in F')
>>> md.title
'Concerto in F'
>>> md = Metadata(otl='Concerto in F') # can use abbreviations
>>> md.title
'Concerto in F'
>>> md.setWorkId('otl', 'Rhapsody in Blue')
>>> md.otl
'Rhapsody in Blue'
>>> md.title
'Rhapsody in Blue'

Metadata 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 *
>>> m21o = base.Music21Object()
>>> m21o.classSortOrder
20

>>> tc = clef.TrebleClef()
>>> tc.classSortOrder
0
>>> ks = key.KeySignature(3)
>>> ks.classSortOrder
1

New classes can define their own default classSortOrder

>>> class ExampleClass(base.Music21Object):
...     classSortOrderDefault = 5
...
>>> ec1 = ExampleClass()
>>> ec1.classSortOrder
5

Attributes inherited from Music21Object: isSpanner, isStream, isVariant, hideObjectOnPrint, xPosition, sites, groups, id

Metadata properties

alternativeTitle

Get or set the alternative title.

>>> from music21 import *
>>> md = metadata.Metadata(popularTitle='Eroica')
>>> md.alternativeTitle = 'Heroic Symphony'
>>> md.alternativeTitle
'Heroic Symphony'
composer

Get or set the composer of this work. More than one composer may be specified.

The composer attribute does not live in Metadata, but creates a Contributor object in the Metadata object.

>>> from music21 import *
>>> md = metadata.Metadata(title='Third Symphony', popularTitle='Eroica', composer='Beethoven, Ludwig van')
>>> md.composer
'Beethoven, Ludwig van'
composers

Get a list of all Contributor objects defined as composer of this work.

date

Get or set the date of this work as one of the following date objects: DateSingle, DateRelative, DateBetween, DateSelection,

>>> from music21 import *
>>> md = metadata.Metadata(title='Third Symphony', popularTitle='Eroica', composer='Beethoven, Ludwig van')
>>> md.date = '2010'
>>> md.date
'2010/--/--'

>>> md.date = metadata.DateBetween(['2009/12/31', '2010/1/28'])
>>> md.date
'2009/12/31 to 2010/01/28'
localeOfComposition

Get or set the locale of composition, or origin, of the work.

movementName

Get or set the movement title.

movementNumber

Get or set the movement number.

number

Get or set the number of the work.

opusNumber

Get or set the opus number.

title

Get the title of the work, or the next-matched title string available from a related parameter fields.

>>> from music21 import *
>>> md = metadata.Metadata(title='Third Symphony')
>>> md.title
'Third Symphony'

>>> md = metadata.Metadata(popularTitle='Eroica')
>>> md.title
'Eroica'
>>> md = metadata.Metadata(title='Third Symphony', popularTitle='Eroica')
>>> md.title
'Third Symphony'
>>> md.popularTitle
'Eroica'
>>> md.otp
'Eroica'

Properties inherited from Music21Object: classes, fullyQualifiedClasses, activeSite, beat, beatDuration, beatStr, beatStrength, derivationHierarchy, duration, isGrace, measureNumber, offset, priority, seconds

Metadata methods

addContributor(c)

Assign a Contributor object to this Metadata.

>>> from music21 import *
>>> md = metadata.Metadata(title='Third Symphony')
>>> c = metadata.Contributor()
>>> c.name = 'Beethoven, Ludwig van'
>>> c.role = 'composer'
>>> md.addContributor(c)
>>> md.composer
'Beethoven, Ludwig van'
>>> md.composer = 'frank'
>>> md.composers
['Beethoven, Ludwig van', 'frank']
getContributorsByRole(value)

Return a Contributor if defined for a provided role.

>>> from music21 import *
>>> md = metadata.Metadata(title='Third Symphony')

>>> c = metadata.Contributor()
>>> c.name = 'Beethoven, Ludwig van'
>>> c.role = 'composer'
>>> md.addContributor(c)
>>> cList = md.getContributorsByRole('composer')
>>> cList[0].name
'Beethoven, Ludwig van'

Some musicxml files have contributors with no role defined. To get these contributors, search for getContributorsByRole(None). N.B. upon output to MusicXML, music21 gives these contributors the generic role of “creator”

>>> c2 = metadata.Contributor()
>>> c2.name = 'Beth Hadley'
>>> md.addContributor(c2)
>>> noRoleList = md.getContributorsByRole(None)
>>> len(noRoleList)
1
>>> noRoleList[0].role
>>> noRoleList[0].name
'Beth Hadley'
search(query, field=None)

Search one or all fields with a query, given either as a string or a regular expression match.

>>> from music21 import *
>>> md = metadata.Metadata()
>>> md.composer = 'Beethoven, Ludwig van'
>>> md.title = 'Third Symphony'

>>> md.search('beethoven', 'composer')
(True, 'composer')
>>> md.search('beethoven', 'compose')
(True, 'composer')
>>> md.search('frank', 'composer')
(False, None)
>>> md.search('frank')
(False, None)
>>> md.search('third')
(True, 'title')
>>> md.search('third', 'composer')
(False, None)
>>> md.search('third', 'title')
(True, 'title')

>>> md.search('third|fourth')
(True, 'title')
>>> md.search('thove(.*)')
(True, 'composer')
setWorkId(idStr, value)

Directly set a workd id, given either as a full string name or as a three character abbreviation. The following work id abbreviations and their full id string are given as follows. In many cases the Metadata object support properties for convenient access to these work ids.

Id abbreviations and strings: otl / title, otp / popularTitle, ota / alternativeTitle, opr / parentTitle, oac / actNumber, osc / sceneNumber, omv / movementNumber, omd / movementName, ops / opusNumber, onm / number, ovm / volume, ode / dedication, oco / commission, gtl / groupTitle, gaw / associatedWork, gco / collectionDesignation, txo / textOriginalLanguage, txl / textLanguage, ocy / countryOfComposition, opc / localeOfComposition.

>>> from music21 import *
>>> md = metadata.Metadata(title='Quartet')
>>> md.title
'Quartet'
>>> md.setWorkId('otl', 'Trio')
>>> md.title
'Trio'
>>> md.setWorkId('sdf', None)
Traceback (most recent call last):
MetadataException: no work id available with id: sdf

Methods inherited from Music21Object: findAttributeInHierarchy(), getContextAttr(), setContextAttr(), addContext(), addLocation(), getAllContextsByClass(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), next(), previous(), purgeLocations(), purgeOrphans(), removeLocationBySite(), removeLocationBySiteId(), setOffsetBySite(), show(), splitAtDurations(), splitAtQuarterLength(), splitByQuarterLengths(), unwrapWeakref(), wrapWeakref(), write()

Text

class music21.metadata.Text(data='', language=None)

One unit of text data: a title, a name, or some other text data. Store the string and a language name or code. This object can be used and/or subclassed for a variety for of text storage.

>>> from music21 import *
>>> td = metadata.Text('concerto in d', 'en')
>>> str(td)
'concerto in d'

Text properties

language

Set the language of the Text stored within.

>>> from music21 import *
>>> t = metadata.Text('my text')
>>> t.language = 'en'
>>> t.language
'en'

Text methods

getNormalizedArticle()

Return a string representation with normalized articles.

>>> from music21 import *
>>> td = metadata.Text('Ale is Dear, The', 'en')
>>> str(td)
'Ale is Dear, The'
>>> td.getNormalizedArticle()
'The Ale is Dear'

>>> td.language = 'de'
>>> td.getNormalizedArticle()
'Ale is Dear, The'

Date

class music21.metadata.Date(*args, **keywords)

A single date value, specified by year, month, day, hour, minute, and second. Note that this class has been created, instead of using Python’s datetime, to provide greater flexibility for processing unconventional dates, ancient dates, dates with error, and date ranges.

The datetime property can be used to retrieve a datetime object when necessary.

Additionally, each value can be specified as uncertain or approximate; if None, assumed to be certain.

Data objects are fundamental components of DateSingle and related subclasses that represent single dates and date ranges.

>>> from music21 import *
>>> a = metadata.Date(year=1843, yearError='approximate')
>>> a.year
1843
>>> a.yearError
'approximate'

>>> a = metadata.Date(year='1843?')
>>> a.yearError
'uncertain'

Date attributes

Attributes without Documentation: attrStrFormat, minuteError, monthError, hour, hourError, dayError, attrNames, month, second, secondError, yearError, year, day, minute

Date properties

datetime

Get a datetime object from a metadata.Date() object

>>> from music21 import *
>>> a = metadata.Date(year=1843, month=3, day=3)
>>> str(a)
'1843/03/03'
>>> a.datetime
datetime.datetime(1843, 3, 3, 0, 0)

Lack of a required date element raises an exception:

>>> a = metadata.Date(year=1843, month=3)
>>> str(a)
'1843/03/--'
>>> a.datetime
Traceback (most recent call last):
...
TypeError: Required argument 'day' (pos 3) not found
hasError

Return True if any data points have error defined.

>>> from music21 import *
>>> a = metadata.Date(year=1843, month=3, day=3, dayError='approximate')
>>> a.hasError
True
>>> b = metadata.Date(year=1843, month=3, day=3, minute=3)
>>> b.hasError
False
hasTime

Return True if any time elements are defined.

>>> from music21 import *
>>> a = metadata.Date(year=1843, month=3, day=3)
>>> a.hasTime
False
>>> b = metadata.Date(year=1843, month=3, day=3, minute=3)
>>> b.hasTime
True

Date methods

load(value)

Load values by string, datetime object, or Date object.

>>> from music21 import *
>>> a = metadata.Date(year=1843, month=3, day=3)
>>> b = metadata.Date()
>>> b.load(a)
>>> b.year
1843
loadDatetime(dt)

Load time data from a datetime object.

>>> from music21 import *
>>> import datetime
>>> dt = datetime.datetime(2005, 02, 01)
>>> dt
datetime.datetime(2005, 2, 1, 0, 0)

>>> m21mdDate = metadata.Date()
>>> m21mdDate.loadDatetime(dt)
>>> str(m21mdDate)
'2005/02/01'
loadOther(other)

Load values based on another Date object:

>>> from music21 import *
>>> a = metadata.Date(year=1843, month=3, day=3)
>>> b = metadata.Date()
>>> b.loadOther(a)
>>> b.year
1843
loadStr(dateStr)

Load a string date representation.

Assume year/month/day/hour:minute:second

>>> from music21 import *
>>> d = metadata.Date()
>>> d.loadStr('3030?/12~/?4')
>>> d.month, d.monthError
(12, 'approximate')
>>> d.year, d.yearError
(3030, 'uncertain')
>>> d.month, d.monthError
(12, 'approximate')
>>> d.day, d.dayError
(4, 'uncertain')

>>> d = metadata.Date()
>>> d.loadStr('1834/12/4/4:50:32')
>>> d.minute, d.second
(50, 32)

DateSingle

class music21.metadata.DateSingle(data='', relevance='certain')

Store a date, either as certain, approximate, or uncertain relevance.

The relevance attribute is limited within each DateSingle subclass depending on the design of the class. Alternative relevance types should be configured as other DateSingle subclasses.

>>> from music21 import *
>>> dd = metadata.DateSingle('2009/12/31', 'approximate')
>>> str(dd)
'2009/12/31'
>>> dd.relevance
'approximate'

>>> dd = metadata.DateSingle('1805/3/12', 'uncertain')
>>> str(dd)
'1805/03/12'

DateSingle attributes

Attributes without Documentation: isSingle

DateSingle properties

datetime

Get a datetime object.

>>> from music21 import *
>>> a = metadata.DateSingle('1843/03/03')
>>> str(a)
'1843/03/03'
>>> a.datetime
datetime.datetime(1843, 3, 3, 0, 0)

>>> a = metadata.DateSingle('1843/03')
>>> str(a)
'1843/03/--'
relevance

No documentation.

DateRelative

Inherits from: DateSingle

class music21.metadata.DateRelative(data='', relevance='after')

Store a relative date, sometime prior or sometime after

>>> from music21 import *
>>> dd = metadata.DateRelative('2009/12/31', 'prior')
>>> str(dd)
'2009/12/31'

>>> dd = metadata.DateRelative('2009/12/31', 'certain')
Traceback (most recent call last):
MetadataException: relevance value is not supported by this object: certain

DateBetween

Inherits from: DateSingle

class music21.metadata.DateBetween(data=[], relevance='between')

Store a relative date, sometime between two dates

>>> from music21 import *
>>> dd = metadata.DateBetween(['2009/12/31', '2010/1/28'])
>>> str(dd)
'2009/12/31 to 2010/01/28'

>>> dd = metadata.DateBetween(['2009/12/31', '2010/1/28'], 'certain')
Traceback (most recent call last):
MetadataException: relevance value is not supported by this object: certain

DateSelection

Inherits from: DateSingle

class music21.metadata.DateSelection(data='', relevance='or')

Store a selection of dates, or a collection of dates that might all be possible

>>> from music21 import *
>>> dd = metadata.DateSelection(['2009/12/31', '2010/1/28', '1894/1/28'], 'or')
>>> str(dd)
'2009/12/31 or 2010/01/28 or 1894/01/28'

>>> dd = metadata.DateSelection(['2009/12/31', '2010/1/28'], 'certain')
Traceback (most recent call last):
MetadataException: relevance value is not supported by this object: certain

Contributor

class music21.metadata.Contributor(*args, **keywords)

A person that contributed to a work. Can be a composer, lyricist, arranger, or other type of contributor. In MusicXML, these are “creator” elements.

>>> from music21 import *
>>> td = metadata.Contributor(role='composer', name='Chopin, Fryderyk')
>>> td.role
'composer'
>>> td.name
'Chopin, Fryderyk'
>>> td.relevance
'contributor'

Contributor attributes

Attributes without Documentation: relevance

Contributor properties

name

Returns the text name, or the first of many names entered.

>>> from music21 import *
>>> td = metadata.Contributor(role='composer', names=['Chopin, Fryderyk', 'Chopin, Frederick'])
>>> td.name
'Chopin, Fryderyk'
>>> td.names
['Chopin, Fryderyk', 'Chopin, Frederick']
names

Returns all names in a list.

>>> from music21 import *
>>> td = metadata.Contributor(role='composer', names=['Chopin, Fryderyk', 'Chopin, Frederick'])
>>> td.names
['Chopin, Fryderyk', 'Chopin, Frederick']
role

The role is what part this Contributor plays in the work. Both full roll strings and roll abbreviations may be used.

>>> from music21 import *
>>> td = metadata.Contributor()
>>> td.role = 'composer'
>>> td.role
'composer'
>>> td.role = 'lor'
>>> td.role
'orchestrator'

Contributor methods

age()

Calculate the age at death of the Contributor, returning a datetime.timedelta object.

>>> from music21 import *
>>> a = metadata.Contributor(name='Beethoven, Ludwig van', role='composer', birth='1770/12/17', death='1827/3/26')
>>> a.role
'composer'
>>> a.age()
datetime.timedelta(20552)
>>> str(a.age())
'20552 days, 0:00:00'
>>> a.age().days / 365
56

Creator

Inherits from: Contributor

class music21.metadata.Creator(*args, **keywords)

A person that created a work. Can be a composer, lyricist, arranger, or other type of contributor.

In MusicXML, these are “creator” elements.

>>> from music21 import *
>>> td = metadata.Creator(role='composer', name='Chopin, Fryderyk')
>>> td.role
'composer'
>>> td.name
'Chopin, Fryderyk'
>>> td.relevance
'creator'

Imprint

class music21.metadata.Imprint(*args, **keywords)

An object representation of imprint, or publication.

MetadataBundle

class music21.metadata.MetadataBundle(name='default')

An object that provides access to, searches within, and stores and loads multiple Metadata objects.

Additionally, multiple MetadataBundles can be merged for additional processing. See corpus.metadata.metadataCache for the module that builds these.

MetadataBundle attributes

storage

A dictionary containing the Metadata objects that have been parsed. Keys are strings

name

The name of the type of MetadataBundle being made, can be “default”, “corpus”, or “virtual”. Possibly also “local”.

MetadataBundle methods

addFromPaths(pathList, printDebugAfter=0)

Parse and store metadata from numerous files.

If any files cannot be loaded, their file paths will be collected in a list that is returned

Returns a list of file paths with errors and stores the extracted metadata in self.storage.

if printDebugAfter is set to an int, say 100, then after every 100 files are parsed a message will be printed to stderr giving an update on progress.

>>> from music21 import *
>>> mb = metadata.MetadataBundle()
>>> mb.addFromPaths(corpus.getWorkList('bwv66.6'))
[]
>>> len(mb.storage)
1
corpusPathToKey(fp, number=None)

Given a file path or corpus path, return the meta-data path

>>> from music21 import *
>>> mb = metadata.MetadataBundle()
>>> mb.corpusPathToKey('bach/bwv1007/prelude').endswith('bach_bwv1007_prelude')
True
>>> mb.corpusPathToKey('/beethoven/opus59no1/movement1.xml').endswith('beethoven_opus59no1_movement1_xml')
True
read(fp=None)

Load self from the file path suggested by the name of this MetadataBundle.

if fp is None (typical), run self._getFilePath()

search(query, field=None, extList=None)

Perform search, on all stored metadata, permit regular expression matching.

Return pairs of file paths and work numbers, or None

>>> from music21 import *
>>> mb = metadata.MetadataBundle()
>>> mb.addFromPaths(corpus.getWorkList('ciconia'))
[]
>>> mb.updateAccessPaths(corpus.getWorkList('ciconia'))
>>> post = mb.search('cicon', 'composer')
>>> len(post[0])
2
>>> post = mb.search('cicon', 'composer', extList=['.krn'])
>>> len(post) # no files in this format
0
>>> post = mb.search('cicon', 'composer', extList=['.xml'])
>>> len(post)  # shouldn't this be 11?
1
updateAccessPaths(pathList)

For each stored Metatadata object, create an entry in the dictionary ._accessPaths where each key is a simple version of the corpus name of the file and the value is the complete, local file path that returns this.

Uses corpusPathToKey() to generate the keys

The pathList parameter is a list of all file paths on the users local system.

>>> from music21 import *
>>> mb = metadata.MetadataBundle()
>>> mb.addFromPaths(corpus.getWorkList('bwv66.6'))
[]
>>> len(mb._accessPaths)
0

>>> mb.updateAccessPaths(corpus.getWorkList('bwv66.6'))
>>> len(mb._accessPaths)
1
>>> print mb._accessPaths
{u'bach_bwv66_6_mxl': u'D:\\eclipse_dev\\music21base\\music21\\corpus\\bach\\bwv66.6.mxl'}

A slower (but not too slow test) that should do much more. This is what corpus._updateMetadataBundle() does. Notice that many of our files contain multiple scores, so while there are 2,300 files, there are over 13,000 scores.

>>> coreCorpusPaths = corpus.getCorePaths()
>>> len(coreCorpusPaths)
2300
>>> mdCoreBundle = metadata.MetadataBundle('core')
>>> mdCoreBundle.read()
>>> len(mdCoreBundle._accessPaths)
0
>>> mdCoreBundle.updateAccessPaths(coreCorpusPaths)
>>> len(mdCoreBundle._accessPaths)
13564

Note that some scores inside an Opus file may have a number in the key that is not present in the path:

>>> mdCoreBundle._accessPaths['essenFolksong_han1_abc_1']
u'D:\\eclipse_dev\\music21base\\music21\\corpus\\essenFolksong\\han1.abc'
write()

Write the JSON storage of all Metadata or RichMetadata contained in this object.

TODO: Test!

RichMetadata

Inherits from: Metadata, Music21Object

class music21.metadata.RichMetadata(*args, **keywords)

RichMetadata adds to Metadata information about the contents of the Score it is attached to. TimeSignature, KeySignature and related analytical is stored. RichMetadata are generally only created in the process of creating stored JSON metadata.

>>> from music21 import *
>>> rmd = metadata.RichMetadata(title='Concerto in F')
>>> rmd.title
'Concerto in F'
>>> rmd.keySignatureFirst = key.KeySignature(-1)
>>> 'keySignatureFirst' in rmd._searchAttributes
True

RichMetadata attributes

Attributes without Documentation: timeSignatures, tempos, keySignatureFirst, noteCount, keySignatures, ambitus, tempoFirst, pitchHighest, timeSignatureFirst, quarterLength, pitchLowest

Attributes inherited from Metadata: classSortOrder

Attributes inherited from Music21Object: isSpanner, isStream, isVariant, xPosition, id, sites, groups, hideObjectOnPrint

RichMetadata properties

RichMetadata methods

merge(other, favorSelf=False)

Given another Metadata or RichMetadata object, combine all attributes and return a new object.

>>> from music21 import *
>>> md = metadata.Metadata(title='Concerto in F')
>>> md.title
'Concerto in F'
>>> rmd = metadata.RichMetadata()
>>> rmd.merge(md)
>>> rmd.title
'Concerto in F'
update(streamObj)

Given a Stream object, update attributes with stored objects.

Methods inherited from Metadata: addContributor(), getContributorsByRole(), search(), setWorkId()

Methods inherited from Music21Object: findAttributeInHierarchy(), getContextAttr(), setContextAttr(), addContext(), addLocation(), getAllContextsByClass(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), next(), previous(), purgeLocations(), purgeOrphans(), removeLocationBySite(), removeLocationBySiteId(), setOffsetBySite(), show(), splitAtDurations(), splitAtQuarterLength(), splitByQuarterLengths(), unwrapWeakref(), wrapWeakref(), write()