music21.common¶
Utility constants, dictionaries, functions, and objects used throughout music21.
Functions¶
-
music21.common.
fromRoman
(num)¶ Convert a Roman numeral (upper or lower) to an int
http://code.activestate.com/recipes/81611-roman-numerals/
>>> common.fromRoman('ii') 2 >>> common.fromRoman('vii') 7
Works with both IIII and IV forms:
>>> common.fromRoman('MCCCCLXXXIX') 1489 >>> common.fromRoman('MCDLXXXIX') 1489
Some people consider this an error, but you see it in medieval documents:
>>> common.fromRoman('ic') 99
But things like this are never seen, and thus cause an error:
>>> common.fromRoman('vx') Traceback (most recent call last): Music21CommonException: input contains an invalid subtraction element: vx
Return type: int
-
music21.common.
toRoman
(num)¶ Convert a number from 1 to 3999 to a roman numeral
>>> common.toRoman(2) 'II' >>> common.toRoman(7) 'VII' >>> common.toRoman(1999) 'MCMXCIX'
>>> common.toRoman("hi") Traceback (most recent call last): TypeError: expected integer, got <... 'str'>
Return type: str
-
music21.common.
almostEquals
(x, y=0.0, grain=1e-07)¶ almostEquals(x, y) – returns True if x and y are within grain (default 0.0000001) of each other
Allows comparisons between floats that are normally inconsistent.
>>> common.almostEquals(1.000000001, 1) True >>> common.almostEquals(1.001, 1) False >>> common.almostEquals(1.001, 1, grain=0.1) True
For very small grains, just compare Fractions without converting...
Return type: bool
-
music21.common.
approximateGCD
(values, grain=0.0001)¶ Given a list of values, find the lowest common divisor of floating point values.
>>> common.approximateGCD([2.5,10, .25]) 0.25 >>> common.approximateGCD([2.5,10]) 2.5 >>> common.approximateGCD([2,10]) 2.0 >>> common.approximateGCD([1.5, 5, 2, 7]) 0.5 >>> common.approximateGCD([2,5,10]) 1.0 >>> common.approximateGCD([2,5,10,.25]) 0.25 >>> common.strTrimFloat(common.approximateGCD([1/3.,2/3.])) '0.3333' >>> common.strTrimFloat(common.approximateGCD([5/3.,2/3.,4])) '0.3333' >>> common.strTrimFloat(common.approximateGCD([5/3.,2/3.,5])) '0.3333' >>> common.strTrimFloat(common.approximateGCD([5/3.,2/3.,5/6.,3/6.])) '0.1667'
Return type: float
-
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.
classToClassStr
(classObj)¶ Convert a class object to a class string.
>>> common.classToClassStr(note.Note) 'Note' >>> common.classToClassStr(chord.Chord) 'Chord'
Return type: str
-
music21.common.
cleanupFloat
(floatNum, maxDenominator=65535)¶ Cleans up a floating point number by converting it to a fractions.Fraction object limited to a denominator of maxDenominator
>>> common.cleanupFloat(0.33333327824) 0.333333333333...
>>> common.cleanupFloat(0.142857) 0.1428571428571...
>>> common.cleanupFloat(1.5) 1.5
Fractions are passed through silently...
>>> import fractions >>> common.cleanupFloat(fractions.Fraction(4, 3)) Fraction(4, 3)
-
music21.common.
contiguousList
(inputListOrTuple)¶ returns bool True or False if a list containing ints contains only contiguous (increasing) values
requires the list to be sorted first
>>> l = [3, 4, 5, 6] >>> common.contiguousList(l) True >>> l.append(8) >>> common.contiguousList(l) False
Sorting matters
>>> l.append(7) >>> common.contiguousList(l) False >>> common.contiguousList(sorted(l)) True
Return type: bool
-
music21.common.
decimalToTuplet
(decNum)¶ For simple decimals (usually > 1), a quick way to figure out the fraction in lowest terms that gives a valid tuplet.
No it does not work really fast. No it does not return tuplets with denominators over 100. Too bad, math geeks. This is real life. :-)
returns (numerator, denominator)
>>> common.decimalToTuplet(1.5) (3, 2) >>> common.decimalToTuplet(1.25) (5, 4)
If decNum is < 1, the denominator will be greater than the numerator:
>>> common.decimalToTuplet(.8) (4, 5)
If decNum is <= 0, returns a ZeroDivisionError:
>>> common.decimalToTuplet(-.02) Traceback (most recent call last): ZeroDivisionError: number must be greater than zero
TODO: replace with fractions...
Return type: tuple(int)
-
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.
dotMultiplier
(dots)¶ dotMultiplier(dots) returns how long to multiply the note length of a note in order to get the note length with n dots
>>> common.dotMultiplier(1) Fraction(3, 2) >>> common.dotMultiplier(2) Fraction(7, 4) >>> common.dotMultiplier(3) Fraction(15, 8)
Return type: Fraction
-
music21.common.
euclidGCD
(a, b)¶ use Euclid’s algorithm to find the GCD of a and b
>>> common.euclidGCD(2,4) 2 >>> common.euclidGCD(20,8) 4 >>> common.euclidGCD(20,16) 4
Return type: int
-
music21.common.
findFormat
(fmt)¶ Given a format defined either by a format name, abbreviation, or an extension, return the regularized format name as well as the output exensions.
DEPRECATED May 2014 – moving to converter
All but the first element of the tuple are deprecated for use, since the extension can vary by subconverter (e.g., lily.png)
Note that .mxl and .mx are only considered MusicXML input formats.
>>> common.findFormat('mx') ('musicxml', '.xml') >>> common.findFormat('.mxl') ('musicxml', '.xml') >>> common.findFormat('musicxml') ('musicxml', '.xml') >>> common.findFormat('lily') ('lilypond', '.ly') >>> common.findFormat('lily.png') ('lilypond', '.ly') >>> common.findFormat('humdrum') ('humdrum', '.krn') >>> common.findFormat('txt') ('text', '.txt') >>> common.findFormat('textline') ('textline', '.txt') >>> common.findFormat('midi') ('midi', '.mid') >>> common.findFormat('abc') ('abc', '.abc') >>> common.findFormat('scl') ('scala', '.scl') >>> common.findFormat('braille') ('braille', '.txt') >>> common.findFormat('vexflow') ('vexflow', '.html') >>> common.findFormat('capx') ('capella', '.capx')
>>> common.findFormat('mx') ('musicxml', '.xml')
#>>> common.findFormat(‘png’) #(‘musicxml.png’, ‘.png’)
#>>> common.findFormat(‘ipython’) #(‘ipython’, ‘.png’) # >>> common.findFormat(‘ipython.png’) # (‘ipython’, ‘.png’) # >>> common.findFormat(‘musicxml.png’) # (‘musicxml.png’, ‘.png’)
Works the same whether you have a leading dot or not:
>>> common.findFormat('md') ('musedata', '.md') >>> common.findFormat('.md') ('musedata', '.md')
If you give something we can’t deal with, returns a Tuple of None, None:
>>> common.findFormat('wpd') (None, None)
-
music21.common.
findFormatExtFile
(fp)¶ Given a file path (relative or absolute) find format and extension used (not the output extension)
DEPRECATED May 2014 – moving to converter
>>> common.findFormatExtFile('test.mx') ('musicxml', '.mx') >>> common.findFormatExtFile('long/file/path/test-2009.03.02.xml') ('musicxml', '.xml') >>> common.findFormatExtFile('long/file/path.intermediate.png/test-2009.03.xml') ('musicxml', '.xml')
>>> common.findFormatExtFile('test') (None, None)
Windows drive >>> common.findFormatExtFile(‘d:/long/file/path/test.xml’) (‘musicxml’, ‘.xml’)
On a windows networked filesystem >>> common.findFormatExtFile(‘\longfilepathtest.krn’) (‘humdrum’, ‘.krn’)
-
music21.common.
findFormatExtURL
(url)¶ Given a URL, attempt to find the extension. This may scrub arguments in a URL, or simply look at the last characters.
DEPRECATED May 2014 – moving to converter
>>> urlA = 'http://somesite.com/?l=cc/schubert/piano/d0576&file=d0576-06.krn&f=xml' >>> urlB = 'http://somesite.com/cgi-bin/ksdata?l=cc/schubert/piano/d0576&file=d0576-06.krn&f=kern' >>> urlC = 'http://somesite.com/cgi-bin/ksdata?l=cc/bach/cello&file=bwv1007-01.krn&f=xml' >>> urlF = 'http://junk'
>>> common.findFormatExtURL(urlA) ('musicxml', '.xml') >>> common.findFormatExtURL(urlB) ('humdrum', '.krn') >>> common.findFormatExtURL(urlC) ('musicxml', '.xml') >>> common.findFormatExtURL(urlF) (None, None)
-
music21.common.
findFormatFile
(fp)¶ Given a file path (relative or absolute) return the format
DEPRECATED May 2014 – moving to converter
>>> common.findFormatFile('test.xml') 'musicxml' >>> common.findFormatFile('long/file/path/test-2009.03.02.xml') 'musicxml' >>> common.findFormatFile('long/file/path.intermediate.png/test-2009.03.xml') 'musicxml'
On a windows networked filesystem >>> common.findFormatFile(‘\longfilepathtest.krn’) ‘humdrum’
-
music21.common.
findInputExtension
(fmt)¶ DEPRECATED May 2014 – moving to converter
Given an input format or music21 format, find and return all possible input extensions.
>>> a = common.findInputExtension('musicxml') >>> a ('.xml', '.mxl', '.mx', '.musicxml') >>> a = common.findInputExtension('humdrum') >>> a ('.krn',) >>> common.findInputExtension('musedata') ('.md', '.musedata', '.zip')
mx is not a music21 format but it is a file format
>>> common.findInputExtension('mx') ('.xml', '.mxl', '.mx', '.musicxml')
Leading dots don’t matter...
>>> common.findInputExtension('.mx') ('.xml', '.mxl', '.mx', '.musicxml')
blah is neither
>>> common.findInputExtension('blah') is None True
-
music21.common.
findSubConverterForFormat
(fmt)¶ return a converter.subConverter.SubConverter subclass for a given format – this is a music21 format name, not a file extension. Or returns None
>>> common.findSubConverterForFormat('musicxml') <class 'music21.converter.subConverters.ConverterMusicXML'>
>>> common.findSubConverterForFormat('text') <class 'music21.converter.subConverters.ConverterText'>
Some subconverters have format aliases
>>> common.findSubConverterForFormat('t') <class 'music21.converter.subConverters.ConverterText'>
-
music21.common.
findWeakRef
(target)¶ Given an object or composition of objects, find an attribute that is a weakref. This is a diagnostic tool.
-
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']
-
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.
groupContiguousIntegers
(src)¶ Given a list of integers, group contiguous values into sub lists
>>> common.groupContiguousIntegers([3, 5, 6]) [[3], [5, 6]] >>> common.groupContiguousIntegers([3, 4, 6]) [[3, 4], [6]] >>> common.groupContiguousIntegers([3, 4, 6, 7]) [[3, 4], [6, 7]] >>> common.groupContiguousIntegers([3, 4, 6, 7, 20]) [[3, 4], [6, 7], [20]] >>> common.groupContiguousIntegers([3, 4, 5, 6, 7]) [[3, 4, 5, 6, 7]] >>> common.groupContiguousIntegers([3]) [[3]] >>> common.groupContiguousIntegers([3, 200]) [[3], [200]]
-
music21.common.
isIterable
(usrData)¶ Returns True if is the object can be iter’d over and is NOT a string
>>> common.isIterable([5, 10]) True >>> common.isIterable('sharp') False >>> common.isIterable((None, None)) True >>> common.isIterable(stream.Stream()) True
Return type: bool
-
music21.common.
isListLike
(usrData)¶ Returns True if is a List or a Set or a Tuple
>>> common.isListLike([]) True >>> common.isListLike('sharp') False >>> common.isListLike((None, None)) True >>> common.isListLike( set(['a','b','c','c']) ) True >>> common.isListLike(stream.Stream()) False
Return type: bool
-
music21.common.
isNum
(usrData)¶ check if usrData is a number (float, int, long, Decimal), return boolean TODO: consider using numbers class (wasn’t available until 2.6)
>>> common.isNum(3.0) True >>> common.isNum(3) True >>> common.isNum('three') False
True and False are NOT numbers:
>>> common.isNum(True) False >>> common.isNum(False) False >>> common.isNum(None) False
Return type: bool
-
music21.common.
isStr
(usrData)¶ Check of usrData is some form of string, including unicode.
>>> common.isStr(3) False >>> common.isStr('sharp') True >>> common.isStr(u'flat') True
Return type: bool
-
music21.common.
isWeakref
(referent)¶ Test if an object is a weakref
>>> class Mock(object): ... pass >>> a1 = Mock() >>> a2 = Mock() >>> common.isWeakref(a1) False >>> common.isWeakref(3) False >>> common.isWeakref(common.wrapWeakref(a1)) True
-
music21.common.
lcm
(filterList)¶ Find the least common multiple of a list of values
>>> common.lcm([3,4,5]) 60 >>> common.lcm([3,4]) 12 >>> common.lcm([1,2]) 2 >>> common.lcm([3,6]) 6
Return type: int
-
music21.common.
mixedNumeral
(expr, limitDenominator=65535)¶ Returns a string representing a mixedNumeral form of a number
>>> common.mixedNumeral(1.333333) '1 1/3' >>> common.mixedNumeral(0.333333) '1/3' >>> common.mixedNumeral(-1.333333) '-1 1/3' >>> common.mixedNumeral(-0.333333) '-1/3'
>>> common.mixedNumeral(0) '0' >>> common.mixedNumeral(-0) '0'
Works with Fraction objects too
>>> from fractions import Fraction >>> common.mixedNumeral( Fraction(31,7) ) '4 3/7' >>> common.mixedNumeral( Fraction(1,5) ) '1/5' >>> common.mixedNumeral( Fraction(-1,5) ) '-1/5' >>> common.mixedNumeral( Fraction(-31,7) ) '-4 3/7'
Denominator is limited by default but can be changed.
>>> common.mixedNumeral(2.0000001) '2' >>> common.mixedNumeral(2.0000001, limitDenominator=10000000) '2 1/10000000'
-
music21.common.
nearestCommonFraction
(x, grain=0.01)¶ Given a value that suggests a floating point fraction, like .33, return a Fraction or float that provides greater specification, such as .333333333
>>> import fractions >>> common.nearestCommonFraction(.333) Fraction(1, 3) >>> common.nearestCommonFraction(.33) Fraction(1, 3) >>> common.nearestCommonFraction(.35) == fractions.Fraction(1, 3) False >>> common.nearestCommonFraction(.2) == 0.2 True >>> common.nearestCommonFraction(.125) 0.125
Return type: float
-
music21.common.
nearestMultiple
(n, unit)¶ Given a positive value n, return the nearest multiple of the supplied unit as well as the absolute difference (error) to seven significant digits and the signed difference.
>>> print(common.nearestMultiple(.25, .25)) (0.25, 0.0, 0.0) >>> print(common.nearestMultiple(.35, .25)) (0.25, 0.1..., 0.1...) >>> print(common.nearestMultiple(.20, .25)) (0.25, 0.05..., -0.05...)
Note that this one also has an error of .1 but it’s a positive error off of 0.5 >>> print(common.nearestMultiple(.4, .25)) (0.5, 0.1..., -0.1...)
>>> common.nearestMultiple(.4, .25)[0] 0.5 >>> common.nearestMultiple(23404.001, .125)[0] 23404.0 >>> common.nearestMultiple(23404.134, .125)[0] 23404.125
Error is always positive, but signed difference can be negative.
>>> common.nearestMultiple(23404 - 0.0625, .125) (23404.0, 0.0625, -0.0625)
>>> common.nearestMultiple(.001, .125)[0] 0.0
>>> common.almostEquals(common.nearestMultiple(.25, (1/3.))[0], .33333333) True >>> common.almostEquals(common.nearestMultiple(.55, (1/3.))[0], .66666666) True >>> common.almostEquals(common.nearestMultiple(234.69, (1/3.))[0], 234.6666666) True >>> common.almostEquals(common.nearestMultiple(18.123, (1/6.))[0], 18.16666666) True
>>> common.nearestMultiple(-0.5, 0.125) Traceback (most recent call last): ValueError: n (-0.5) is less than zero. Thus cannot find nearest multiple for a value less than the unit, 0.125
Return type: tuple(float)
-
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.
numToIntOrFloat
(value)¶ Given a number, return an integer if it is very close to an integer, otherwise, return a float.
>>> common.numToIntOrFloat(1.0) 1 >>> common.numToIntOrFloat(1.00003) 1.00003 >>> common.numToIntOrFloat(1.5) 1.5 >>> common.numToIntOrFloat(1.0000000005) 1
Return type: float
-
music21.common.
opFrac
(num)¶ opFrac -> optionally convert a number to a fraction or back.
Important music21 2.x function for working with offsets and quarterLengths
Takes in a number (or None) and converts it to a Fraction with denominator less than limitDenominator if it is not binary expressible; otherwise return a float. Or if the Fraction can be converted back to a binary expressable float then do so.
This function should be called often to ensure that values being passed around are floats and ints wherever possible and fractions where needed.
The naming of this method violates music21’s general rule of no abbreviations, but it is important to make it short enough so that no one will be afraid of calling it often. It also doesn’t have a setting for maxDenominator so that it will expand in Code Completion easily. That is to say, this function has been set up to be used, so please use it.
This is a performance critical operation. Do not alter it in any way without running many timing tests.
>>> from fractions import Fraction >>> defaults.limitOffsetDenominator 65535 >>> common.opFrac(3) 3.0 >>> common.opFrac(1.0/3) Fraction(1, 3) >>> common.opFrac(1.0/4) 0.25 >>> f = Fraction(1,3) >>> common.opFrac(f + f + f) 1.0 >>> common.opFrac(0.123456789) Fraction(10, 81) >>> common.opFrac(None) is None True
-
music21.common.
ordinalAbbreviation
(value, plural=False)¶ Return the ordinal abbreviations for integers
>>> common.ordinalAbbreviation(3) 'rd' >>> common.ordinalAbbreviation(255) 'th' >>> common.ordinalAbbreviation(255, plural=True) 'ths'
Return type: str
-
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 = common.getSourceFilePath() + os.sep + 'common.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] u'#-*- 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] u'#-*- 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.
roundToHalfInteger
(num)¶ Given a floating-point number, round to the nearest half-integer. Returns int or float
>>> common.roundToHalfInteger(1.2) 1 >>> common.roundToHalfInteger(1.35) 1.5 >>> common.roundToHalfInteger(1.8) 2 >>> common.roundToHalfInteger(1.6234) 1.5
.25 rounds up:
>>> common.roundToHalfInteger(0.25) 0.5
as does .75
>>> common.roundToHalfInteger(0.75) 1
unlike python round function, does the same for 1.25 and 1.75
>>> common.roundToHalfInteger(1.25) 1.5 >>> common.roundToHalfInteger(1.75) 2
negative numbers however, round up on the boundaries
>>> common.roundToHalfInteger(-0.26) -0.5 >>> common.roundToHalfInteger(-0.25) 0
Return type: float
-
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)¶ 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'
>>> common.spaceCamelCase('hello_myke') 'hello myke' >>> common.spaceCamelCase('hello_myke', replaceUnderscore = False) 'hello_myke'
Return type: str
-
music21.common.
standardDeviation
(coll, bassel=False)¶ Given a collection of values, return the standard deviation.
>>> common.standardDeviation([2,4,4,4,5,5,7,9]) 2.0 >>> common.standardDeviation([600, 470, 170, 430, 300]) 147.3227... >>> common.standardDeviation([4, 2, 5, 8, 6], bassel=True) 2.23606...
Return type: float
-
music21.common.
strTrimFloat
(floatNum, maxNum=4)¶ returns a string from a float that is at most maxNum of decimial digits long, but never less than 1.
>>> common.strTrimFloat(42.3333333333) '42.3333' >>> common.strTrimFloat(42.3333333333, 2) '42.33' >>> common.strTrimFloat(6.66666666666666, 2) '6.67' >>> common.strTrimFloat(2.0) '2.0' >>> common.strTrimFloat(-5) '-5.0'
-
music21.common.
stripAccents
(inputString)¶ removes accents from unicode strings.
>>> s = u'tr\u00e8s vite' >>> u'\u00e8' in s True >>> common.stripAccents(s) u'tres vite'
-
music21.common.
subConverterList
()¶ returns a list of subconverter classes available to music21 in converter/subConverters, including the stub SubConverter class
DEPRECATED May 2015: moved to converter. #TODO: Remove
-
music21.common.
toUnicode
(usrStr)¶ Convert this tring to a uncode string; if already a unicode string, do nothing.
>>> common.toUnicode('test') u'test' >>> common.toUnicode(u'test') u'test'
Return type: str
-
music21.common.
unitBoundaryProportion
(series)¶ Take a series of parts with an implied sum, and create unit-interval boundaries proportional to the series components.
>>> common.unitBoundaryProportion([1,1,2]) [(0, 0.25), (0.25, 0.5), (0.5, 1.0)] >>> common.unitBoundaryProportion([8,1,1]) [(0, 0.8...), (0.8..., 0.9...), (0.9..., 1.0)]
Return type: list(tuple(float))
-
music21.common.
unitNormalizeProportion
(values)¶ Normalize values within the unit interval, where max is determined by the sum of the series.
>>> common.unitNormalizeProportion([0,3,4]) [0.0, 0.42857142857142855, 0.5714285714285714] >>> common.unitNormalizeProportion([1,1,1]) [0.3333333..., 0.333333..., 0.333333...]
On 32-bit computers this number is inexact. On 64-bit it works fine.
#>>> common.unitNormalizeProportion([.2, .6, .2]) #[0.20000000000000001, 0.59999999999999998, 0.20000000000000001]
Return type: list(float)
-
music21.common.
unwrapWeakref
(referent)¶ Utility function that gets an object that might be an object itself or a weak reference to an object. It returns obj() if it’s a weakref. and obj if it’s not.
>>> class Mock(object): ... pass >>> a1 = Mock() >>> a2 = Mock() >>> a2.strong = a1 >>> a2.weak = common.wrapWeakref(a1) >>> common.unwrapWeakref(a2.strong) is a1 True >>> common.unwrapWeakref(a2.weak) is a1 True >>> common.unwrapWeakref(a2.strong) is common.unwrapWeakref(a2.weak) True
-
music21.common.
weightedSelection
(values, weights, randomGenerator=None)¶ Given a list of values and an equal-sized list of weights, return a randomly selected value using the weight.
Example: sum -1 and 1 for 100 values; should be around 0 or at least between -30 and 30
>>> -30 < sum([common.weightedSelection([-1, 1], [1,1]) for x in range(100)]) < 30 True
Return type: int
-
music21.common.
wrapWeakref
(referent)¶ utility function that wraps objects as weakrefs but does not wrap already wrapped objects; also prevents wrapping the unwrapable “None” type, etc.
>>> import weakref >>> class Mock(object): ... pass >>> a1 = Mock() >>> ref1 = common.wrapWeakref(a1) >>> ref1 <weakref at 0x101f29ae8; to 'Mock' at 0x101e45358> >>> ref2 = common.wrapWeakref(ref1) >>> ref2 <weakref at 0x101f299af; to 'Mock' at 0x101e45358> >>> ref3 = common.wrapWeakref(5) >>> ref3 5
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
()¶