music21.common¶
Common is a collection of utility functions, objects, constants and dictionaries used throughout music21.
functions in common/ can import from music21.defaults, music21.exceptions21, and music21.ext and that is all (except in tests and doctests).
For historical reasons all the (non-private) functions etc. of the common/ folder are available by importing common.
split according to function – September 2015
Functions¶
-
music21.common.
basicallyEqual
(a, b)¶ returns true if a and b are equal except for whitespace differences
>>> a = " hello there " >>> b = "hello there" >>> c = " bye there " >>> common.basicallyEqual(a,b) True >>> common.basicallyEqual(a,c) False
-
music21.common.
camelCaseToHyphen
(usrStr, replacement='-')¶ Given a camel-cased string, or a mixture of numbers and characters, create a space separated string.
The replacement can be specified to be something besides a hyphen, but only a single character and not (for internal reasons) an uppercase character.
>>> common.camelCaseToHyphen('movementName') 'movement-name' >>> common.camelCaseToHyphen('movementNameName') 'movement-name-name'
>>> common.camelCaseToHyphen('fileName', replacement='_') 'file_name'
Some things you cannot do:
>>> common.camelCaseToHyphen('fileName', replacement='NotFound') Traceback (most recent call last): Exception: Replacement must be a single character.
>>> common.camelCaseToHyphen('fileName', replacement='A') Traceback (most recent call last): Exception: Replacement cannot be an uppercase character.
-
music21.common.
cd
(targetDir)¶ Useful for a temporary cd for use in a with statement:
- with cd(‘/Library/’):
- os.system(make)
will switch temporarily, and then switch back when leaving.
-
music21.common.
defaultDeepcopy
(obj, memo, callInit=True)¶ Unfortunately, it is not possible to do something like:
- def __deepcopy__(self, memo):
- if self._noDeepcopy:
- return self.__class__()
- else:
- copy.deepcopy(self, memo, ignore__deepcopy__=True)
so that’s what this is for:
- def __deepcopy__(self, memo):
- if self._noDeepcopy:
- return self.__class__()
- else:
- common.defaultDeepcopy(obj, memo)
looks through both __slots__ and __dict__ and does a deepcopy of anything in each of them and returns the new object.
If callInit is False, then only __new__() is called. This is much faster if you’re just going to overload every instance variable.
-
music21.common.
dirPartitioned
(obj, skipLeading=('__', ))¶ Given an object, return three lists of names: methods, attributes, and properties.
Note that if a name/attribute is dynamically created by a property it cannot be found until that attribute is created.
TODO: this cannot properly partiton properties from methods
-
music21.common.
formatStr
(msg, *arguments, **keywords)¶ Format one or more data elements into string suitable for printing straight to stderr or other outputs
>>> a = common.formatStr('test', '1', 2, 3) >>> print(a) test 1 2 3
-
music21.common.
getCorpusContentDirs
()¶ Get all dirs that are found in the corpus that contain content; that is, exclude dirst that have code or other resoures.
>>> fp = common.getCorpusContentDirs() >>> fp # this test will be fragile, depending on composition of dirs ['airdsAirs', 'bach', 'beethoven', 'ciconia', 'corelli', 'cpebach', 'demos', 'essenFolksong', 'handel', 'haydn', 'josquin', 'leadSheet', 'luca', 'miscFolk', 'monteverdi', 'mozart', 'oneills1850', 'palestrina', 'ryansMammoth', 'schoenberg', 'schumann', 'schumann_clara', 'theoryExercises', 'trecento', 'verdi', 'weber']
Make sure that all corpus data has a directoryInformation tag in CoreCorpus.
>>> cc = corpus.corpora.CoreCorpus() >>> failed = [] >>> di = [d.directoryName for d in cc.directoryInformation] >>> for f in fp: ... if f not in di: ... failed.append(f) >>> failed []
-
music21.common.
getCorpusFilePath
()¶ Get the stored music21 directory that contains the corpus metadata cache.
>>> fp = common.getCorpusFilePath() >>> fp.endswith('music21/corpus') or fp.endswith(r'music21\corpus') True
-
music21.common.
getMd5
(value=None)¶ Return an md5 hash from a string. If no value is given then the current time plus a random number is encoded.
>>> common.getMd5('test') '098f6bcd4621d373cade4e832627b4f6'
Return type: str
-
music21.common.
getMetadataCacheFilePath
()¶ Get the stored music21 directory that contains the corpus metadata cache.
>>> fp = common.getMetadataCacheFilePath() >>> fp.endswith('corpus/_metadataCache') or fp.endswith(r'corpus\_metadataCache') True
Return type: str
-
music21.common.
getMissingImportStr
(modNameList)¶ Given a list of missing module names, returns a nicely-formatted message to the user that gives instructions on how to expand music21 with optional packages.
>>> common.getMissingImportStr(['matplotlib']) 'Certain music21 functions might need the optional package matplotlib; if you run into errors, install it by following the instructions at http://mit.edu/music21/doc/installing/installAdditional.html' >>> common.getMissingImportStr(['matplotlib', 'numpy']) 'Certain music21 functions might need these optional packages: matplotlib, numpy; if you run into errors, install it by following the instructions at http://mit.edu/music21/doc/installing/installAdditional.html'
-
music21.common.
getNumFromStr
(usrStr, numbers='0123456789')¶ Given a string, extract any numbers. Return two strings, the numbers (as strings) and the remaining characters.
>>> common.getNumFromStr('23a') ('23', 'a') >>> common.getNumFromStr('23a954sdfwer') ('23954', 'asdfwer') >>> common.getNumFromStr('') ('', '')
Return type: tuple(str)
-
music21.common.
getPackageData
()¶ Return a list of package data in the format specified by setup.py. This creates a very inclusive list of all data types.
-
music21.common.
getPackageDir
(fpMusic21=None, relative=True, remapSep='.', packageOnly=True)¶ Manually get all directories in the music21 package, including the top level directory. This is used in setup.py.
If relative is True, relative paths will be returned.
If remapSep is set to anything other than None, the path separator will be replaced.
If packageOnly is true, only directories with __init__.py files are colllected.
-
music21.common.
getPlatform
()¶ Return the name of the platform, where platforms are divided between ‘win’ (for Windows), ‘darwin’ (for MacOS X), and ‘nix’ for (GNU/Linux and other variants).
Return type: str
-
music21.common.
getSourceFilePath
()¶ Get the music21 directory that contains source files. This is not the same as the outermost package development directory.
Return type: str
-
music21.common.
hyphenToCamelCase
(usrStr, replacement='-')¶ given a hyphen-connected-string, change it to a camelCaseConnectedString.
The replacement can be specified to be something besides a hyphen.
>>> common.hyphenToCamelCase('movement-name') 'movementName'
>>> common.hyphenToCamelCase('movement_name', replacement='_') 'movementName'
-
music21.common.
normalizeFilename
(name)¶ take a name that might contain unicode characters, punctuation, or spaces and normalize it so that it is POSIX compliant (except for the limit on length).
Takes in a string or unicode string and returns a string (unicode in Py3) without any accented characters.
>>> common.normalizeFilename(u'03-Niccolò all’lessandra.not really.xml') '03-Niccolo_alllessandra_not_really.xml'
Return type: str
-
music21.common.
pickleCopy
(obj)¶ use pickle to serialize/deserialize a copy of an object – much faster than deepcopy, but only works for things that are completely pickleable.
-
music21.common.
pitchList
(pitchL)¶ utility method that replicates the previous behavior of lists of pitches
-
music21.common.
readFileEncodingSafe
(filePath, firstGuess='utf-8')¶ Slow, but will read a file of unknown encoding as safely as possible using the LGPL chardet package in music21.ext.
Let’s try to load this file as ascii – it has a copyright symbol at the top so it won’t load in Python3:
>>> import os >>> c = os.path.join(common.getSourceFilePath(), 'common', '__init__.py') >>> f = open(c) >>> data = f.read() Traceback (most recent call last): UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position ...: ordinal not in range(128)
That won’t do! now I know that it is in utf-8, but maybe you don’t. Or it could be an old humdrum or Noteworthy file with unknown encoding. This will load it safely.
>>> data = common.readFileEncodingSafe(c) >>> data[0:30] '#-*- coding: utf-8 -*-\n#------'
Well, that’s nothing, since the first guess here is utf-8 and it’s right. So let’s give a worse first guess:
>>> data = common.readFileEncodingSafe(c, firstGuess='SHIFT_JIS') # old Japanese standard >>> data[0:30] '#-*- coding: utf-8 -*-\n#------'
It worked!
Note that this is slow enough if it gets it wrong that the firstGuess should be set to something reasonable like ‘ascii’ or ‘utf-8’.
Return type: str
-
music21.common.
relativepath
(path, start='.')¶ A cross-platform wrapper for os.path.relpath(), which returns path if under Windows, otherwise returns the relative path of path.
This avoids problems under Windows when the current working directory is on a different drive letter from path.
Return type: str
-
music21.common.
runningUnderIPython
()¶ return bool if we are running under iPython Notebook (not iPython)
(no tests, since will be different)
This post: http://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook says not to do this, but really, I can’t think of another way to have different output as default.
Return type: bool
-
music21.common.
sortFilesRecent
(fileList)¶ Given two files, sort by most recent. Return only the file paths.
>>> import os >>> a = os.listdir(os.curdir) >>> b = common.sortFilesRecent(a)
Return type: list(str)
-
music21.common.
sortModules
(moduleList)¶ Sort a lost of imported module names such that most recently modified is first. In ties, last accesstime is used then module name
Will return a different order each time depending on the last mod time
Return type: list(str)
-
music21.common.
spaceCamelCase
(usrStr, replaceUnderscore=True, fixMeList=None)¶ Given a camel-cased string, or a mixture of numbers and characters, create a space separated string.
If replaceUnderscore is True (default) then underscores also become spaces (but without the _)
>>> common.spaceCamelCase('thisIsATest') 'this Is A Test' >>> common.spaceCamelCase('ThisIsATest') 'This Is A Test' >>> common.spaceCamelCase('movement3') 'movement 3' >>> common.spaceCamelCase('opus41no1') 'opus 41 no 1' >>> common.spaceCamelCase('opus23402no219235') 'opus 23402 no 219235' >>> common.spaceCamelCase('opus23402no219235').title() 'Opus 23402 No 219235'
There is a small list called fixMeList that can fix mistakes.
>>> common.spaceCamelCase('PMFC22') 'PMFC 22'
>>> common.spaceCamelCase('hello_myke') 'hello myke' >>> common.spaceCamelCase('hello_myke', replaceUnderscore = False) 'hello_myke'
Return type: str
-
music21.common.
stripAccents
(inputString)¶ removes accents from unicode strings.
>>> s = u'trés vite'
>>> u'é' in s True
This works on Python2, but the doctest does not.
>>> if ext.six.PY3: ... common.stripAccents(s) ... else: 'tres vite' 'tres vite'
-
music21.common.
toUnicode
(usrStr)¶ Convert this tring to a uncode string; if already a unicode string, do nothing.
>>> common.toUnicode('test') 'test' >>> common.toUnicode(u'test') 'test'
Return type: str
Iterator¶
-
class
music21.common.
Iterator
(data)¶ A simple Iterator object used to handle iteration of Streams and other list-like objects.
>>> i = common.Iterator([2,3,4]) >>> for x in i: ... print(x) 2 3 4 >>> for y in i: ... print(y) 2 3 4
Iterator
methods
-
Iterator.
next
()¶
SingletonCounter¶
-
class
music21.common.
SingletonCounter
¶ A simple counter that can produce unique numbers regardless of how many instances exist.
Instantiate and then call it.
SlottedObject¶
-
class
music21.common.
SlottedObject
¶ Provides template for classes implementing slots allowing it to be pickled properly.
Only use SlottedObjects for objects that we expect to make so many of that memory storage and speed become an issue. Thus, unless you are Xenakis, Glissdata is probably not the best example:
>>> import pickle >>> class Glissdata(common.SlottedObject): ... __slots__ = ('time', 'frequency') >>> s = Glissdata() >>> s.time = 0.125 >>> s.frequency = 440.0 >>> out = pickle.dumps(s) >>> t = pickle.loads(out) >>> t.time, t.frequency (0.125, 440.0)
TestMock¶
-
class
music21.common.
TestMock
¶ A test object with attributes, methods, and properties
TestMock
read/write properties
-
TestMock.
property1
¶
-
TestMock.
property2
¶
TestMock
methods
-
TestMock.
method1
()¶
-
TestMock.
method2
()¶
Timer¶
-
class
music21.common.
Timer
¶ An object for timing. Call it to get the current time since starting.
>>> t = common.Timer() >>> now = t() >>> nownow = t() >>> nownow > now True
Call stop to stop it. Calling start again will reset the number
>>> t.stop() >>> stopTime = t() >>> stopNow = t() >>> stopTime == stopNow True
All this had better take less than one second!
>>> stopTime < 1 True
Timer
methods
-
Timer.
clear
()¶
-
Timer.
start
()¶ Explicit start method; will clear previous values. Start always happens on initialization.
-
Timer.
stop
()¶