The layout.py module contains two types of objects that specify the layout on page (or screen) for Scores and other Stream objects. There are two main types of Layout objects: (1) layout describing elements and (2) layout defining Streams.
(1) ScoreLayout, PageLayout, SystemLayout, and StaffLayout objects describe the size of pages, the geometry of page and system margins, the distance between staves, etc. The model for these layout objects is taken directly (perhaps too directly?) from MusicXML. These objects all inherit from a BaseLayout class, primarily as an aid to finding all of these objects as a group. ScoreLayouts give defaults for each page, system, and staff. Thus they contain PageLayout, SystemLayout, and currently one or more StaffLayout objects (but probably just one. MusicXML allows more than StaffLayout object because multiple staves can be in a Part. Music21 uses the concept of a PartStaff for a Part that is played by the same performer as another. e.g., the left hand of the Piano is a PartStaff paired with the right hand).
PageLayout and SystemLayout objects also have a property, ‘isNew’, which if set to True signifies that a new page or system should begin here. In theory, one could define new dimensions for a page or system in the middle of the system or page without setting isNew to True, in which case these measurements would start applying on the next page. In practice, there’s really one good place to use these Layout objects and that’s in the first part in a score at offset 0 of the first measure on a page or system (or for ScoreLayout, at the beginning of a piece outside of any parts). But it’s not an error to put them in other places, such as at offset 0 of the first measure of a page or system in all the other parts. In fact, MusicXML tends to do this, and it ends up not being a waste if a program extracts a single part from the middle of a score.
These objects are standard Music21Object types, but many properties such as .duration, .beat, will probably not apply.
When exporting to MusicXML (which is currently the only format in which music21 can and does preserve these markings), many MusicXML readers will ignore these tags (or worse, add a new page or system when PageLayout and SystemLayout objects are found but also add theme wherever they want). In Finale, this behavior disappears if the MusicXML document notes that it <supports> new-page and new-system markings. Music21 will add the appropriate <supports> tags if the containing Stream has .definesExplicitPageBreaks and .definesExplicitSystemBreaks set to True. When importing a score that has the <supports> tag set, music21 will set .definesExplicitXXXXBreaks to True for the outer score and the inner parts. However, this means that if the score is manipulated enough that the prior layout information is obsolete, programs will need to set these properties to False or move the Layout tags accordingly.
(2) The second set of objects are Stream subclasses that can be employed when a program needs to easily iterate around the systems and pages defined through the layout objects just described, or to get the exact position on a page (or a graphical representation of a page) for a particular measure or system. (Individual notes coming soon). Normal Score streams can be changed into LayoutStreams by calling divideByPages(s) on them. A Score that was organized: Score->Parts->Measures would then become: LayoutScore->Pages->Systems->Parts->Measures.
The new LayoutScore has methods that enable querying what page or system a measure is in, and specifically where on a page a measure is (or the dimensions of every measure in the piece). However do not call .show() on a LayoutScore – the normal score it’s derived from will work just fine. Nor does calling .show() on a Page or System work yet, but once the LayoutStream has been created, code like this can be done:
s = stream.Stream(...) ls = layout.divideByPages(s) pg2sys3 = ls.pages[1].systems[2] # n.b.! 1, 2 startMeasure, endMeasure = pg2sys3.startMeasure, pg2sys3.endMeasure scoreExcerpt = s.measures(startMeasure, endMeasure) scoreExcerpt.show() # will show page 2, system 3
Note that while the the coordinates given by music21 for a musicxml score (based on margins, staff size, etc.) generally reflect what is actually in a musicxml producer, unfortuantely, x-positions are far less accurately produced by most editors. For instance, Finale scores with measure sizes that have been manually adjusted tend to show their unadjusted measure width and not their actual measure width in the MusicXML.
SmartScore Pro tends to produce very good MusicXML layout data.
Divides a score into a series of smaller scores according to page breaks. Only searches for PageLayout.isNew or SystemLayout.isNew on the first part. Returns a new LayoutScore object.
If fastMeasures is True, then the newly created System objects do not have Clef signs, Key Signatures, or necessarily all the applicable spanners in them. On the other hand, the position (on the page) information will be just as correct with fastMeasures = True and it will run much faster on large scores (because our spanner gathering algorithm is currently O(n^2); something TODO: to fix.)
>>> from music21 import *
>>> lt = corpus.parse('demos/layoutTest.xml')
>>> len(lt.parts)
3
>>> len(lt.parts[0].getElementsByClass('Measure'))
80
Divide the score up into layout.Page objects
>>> layoutScore = layout.divideByPages(lt, fastMeasures = True)
>>> len(layoutScore.pages)
4
>>> lastPage = layoutScore.pages[-1]
>>> lastPage.measureStart
64
>>> lastPage.measureEnd
80
the layoutScore is a subclass of stream.Opus:
>>> layoutScore
<music21.layout.LayoutScore ...>
>>> 'Opus' in layoutScore.classes
True
Pages are subclasses of Opus also, since they contain Scores
>>> lastPage
<music21.layout.Page ...>
>>> 'Opus' in lastPage.classes
True
Each page now has Systems not parts.
>>> firstPage = layoutScore.pages[0]
>>> len(firstPage.systems)
4
>>> firstSystem = firstPage.systems[0]
>>> firstSystem.measureStart
1
>>> firstSystem.measureEnd
5
Systems are a subclass of Score:
>>> firstSystem
<music21.layout.System ...>
>>> 'Score' in firstSystem.classes
True
Each System has staves (layout.Staff objects) not parts, though Staff is a subclass of Part
>>> secondStaff = firstSystem.staves[1]
>>> print len(secondStaff.getElementsByClass('Measure'))
5
>>> secondStaff
<music21.layout.Staff ...>
>>> 'Part' in secondStaff.classes
True
get a list where each entry is a 2-tuplet whose first number refers to the first measure on a page and whose second number is the last measure on the page.
Inherits from: LayoutBase, Music21Object
Parameters for configuring a score’s layout.
PageLayout objects may be found on Measure or Part Streams.
>>> from music21 import *
>>> pl = layout.PageLayout(pageNumber = 4, leftMargin=234, rightMargin=124, pageHeight=4000, pageWidth=3000, isNew=True)
>>> pl.pageNumber
4
>>> pl.rightMargin
124
>>> pl.leftMargin
234
>>> pl.isNew
True
This object represents both <print new-page> and <page-layout> elements in musicxml
## TODO – make sure that the first pageLayout and systemLayout for each page are working together.
ScoreLayout attributes
Attributes without Documentation: pageLayout, musicFont, scalingMillimeters, appearance, scalingTenths, wordFont, staffLayoutList, systemLayout
Attributes inherited from Music21Object: classSortOrder, isSpanner, isStream, isVariant, hideObjectOnPrint, xPosition, sites, groups, id
ScoreLayout properties
Properties inherited from Music21Object: classes, fullyQualifiedClasses, activeSite, beat, beatDuration, beatStr, beatStrength, derivationHierarchy, duration, isGrace, measureNumber, offset, priority, seconds
ScoreLayout methods
- tenthsToMillimeters(tenths)¶
given the scalingMillimeters and scalingTenths, return the value in millimeters of a number of musicxml “tenths” where a tenth is a tenth of the distance from one staff line to another
returns 0.0 if either of scalingMillimeters or scalingTenths is undefined.
>>> from music21 import * >>> sl = layout.ScoreLayout(scalingMillimeters = 2.0, scalingTenths=10) >>> print sl.tenthsToMillimeters(10) 2.0 >>> print sl.tenthsToMillimeters(17) # printing to round 3.4Methods 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()
Inherits from: LayoutBase, Music21Object
Parameters for configuring a page’s layout.
PageLayout objects may be found on Measure or Part Streams.
>>> from music21 import *
>>> pl = layout.PageLayout(pageNumber = 4, leftMargin=234, rightMargin=124, pageHeight=4000, pageWidth=3000, isNew=True)
>>> pl.pageNumber
4
>>> pl.rightMargin
124
>>> pl.leftMargin
234
>>> pl.isNew
True
This object represents both <print new-page> and <page-layout> elements in musicxml
## TODO – make sure that the first pageLayout and systemLayout for each page are working together.
PageLayout attributes
Attributes without Documentation: bottomMargin, pageHeight, topMargin, rightMargin, isNew, pageNumber, pageWidth, leftMargin
Attributes inherited from Music21Object: classSortOrder, isSpanner, isStream, isVariant, hideObjectOnPrint, xPosition, sites, groups, id
PageLayout properties
Properties inherited from Music21Object: classes, fullyQualifiedClasses, activeSite, beat, beatDuration, beatStr, beatStrength, derivationHierarchy, duration, isGrace, measureNumber, offset, priority, seconds
PageLayout methods
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()
Inherits from: LayoutBase, Music21Object
Object that configures or alters a system’s layout.
SystemLayout objects may be found on Measure or Part Streams.
Importantly, if isNew is True then this object indicates that a new system should start here.
>>> from music21 import *
>>> sl = layout.SystemLayout(leftMargin=234, rightMargin=124, distance=3, isNew=True)
>>> sl.distance
3
>>> sl.rightMargin
124
>>> sl.leftMargin
234
>>> sl.isNew
True
SystemLayout attributes
Attributes without Documentation: distance, rightMargin, isNew, topDistance, leftMargin
Attributes inherited from Music21Object: classSortOrder, isSpanner, isStream, isVariant, hideObjectOnPrint, xPosition, sites, groups, id
SystemLayout properties
Properties inherited from Music21Object: classes, fullyQualifiedClasses, activeSite, beat, beatDuration, beatStr, beatStrength, derivationHierarchy, duration, isGrace, measureNumber, offset, priority, seconds
SystemLayout methods
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()
Inherits from: LayoutBase, Music21Object
Object that configures or alters the distance between one staff and another in a system.
StaffLayout objects may be found on Measure or Part Streams.
The musicxml equivalent <staff-layout> lives in the <defaults> and in <print> attributes.
>>> from music21 import *
>>> sl = layout.StaffLayout(distance=3, staffNumber=1, staffSize = 113)
>>> sl.distance
3
The “number” attribute refers to which staff number in a part group this refers to. Thus, it’s not necessary in music21, but we store it if it’s there. (defaults to None)
>>> sl.staffNumber
1
Music21 also stores the <staff-size> and eventually <staff-lines> of the <attributes> tag in a StaffLayout object. TODO: make it export properly.
staffSize is a percentage of the base staff size, so this defines a staff 13% larger than normal.
>>> sl.staffSize
113.0
>>> sl
<music21.layout.StaffLayout distance 3, staffNumber 1, staffSize 113.0>
StaffLayout attributes
Attributes without Documentation: distance, staffNumber, staffSize, hidden
Attributes inherited from Music21Object: classSortOrder, isSpanner, isStream, isVariant, hideObjectOnPrint, xPosition, sites, groups, id
StaffLayout properties
Properties inherited from Music21Object: classes, fullyQualifiedClasses, activeSite, beat, beatDuration, beatStr, beatStrength, derivationHierarchy, duration, isGrace, measureNumber, offset, priority, seconds
StaffLayout methods
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()
Inherits from: Opus, Stream, Music21Object
Designation that this Score is divided into Pages, Systems, Staves (=Parts), Measures, etc.
Used for computing location of notes, etc.
If the score does not change between calls to the various getPosition calls, it is much faster as it uses a cache.
LayoutScore attributes
Attributes without Documentation: startMeasure, scoreLayout, endMeasure
Attributes inherited from Stream: isMeasure, isStream, definesExplicitPageBreaks, isFlat, autoSort, isSorted, flattenedRepresentationOf, definesExplicitSystemBreaks
Attributes inherited from Music21Object: classSortOrder, isSpanner, isVariant, xPosition, id, sites, groups, hideObjectOnPrint
LayoutScore properties
- pages¶
No documentation.
Properties inherited from Opus: scores
Properties inherited from Stream: notes, pitches, atSoundingPitch, beat, beatDuration, beatStr, beatStrength, derivationChain, derivationMethod, derivesFrom, duration, elements, finalBarline, flat, highestOffset, highestTime, isGapless, lowestOffset, metadata, notesAndRests, offsetMap, rootDerivation, seconds, secondsMap, semiFlat, sorted, spannerBundle, spanners, variants, voices
Properties inherited from Music21Object: activeSite, classes, derivationHierarchy, fullyQualifiedClasses, isGrace, measureNumber, offset, priority
LayoutScore methods
- getAllMeasurePositionsInDocument(returnFormat='tenths', printUpdates=False)¶
returns a list of dictionaries, where each dictionary gives the measure number and other information, etc. in the document.
# >>> from music21 import * # >>> g = corpus.parse(‘luca/gloria’) # >>> gl = layout.divideByPages(g) # >>> gl.getAllMeasurePositionsInDocument()
- getMarginsAndSizeForPageId(pageId)¶
return a tuple of (top, left, bottom, right, width, height) margins for a given pageId in tenths
Default of (100, 100, 100, 100, 850, 1100) if undefined
>>> from music21 import * >>> g = corpus.parse('luca/gloria') >>> g.parts[0].getElementsByClass('Measure')[22].getElementsByClass('PageLayout')[0].leftMargin = 204.0 >>> gl = layout.divideByPages(g) >>> gl.getMarginsAndSizeForPageId(1) (171.0, 204.0, 171.0, 171.0, 1457.0, 1886.0)
- getPageAndSystemNumberFromMeasureNumber(measureNumber)¶
Given a layoutScore from divideByPages and a measureNumber returns a tuple of (pageId, systemId). Note that pageId is probably one less than the page number, assuming that the first page number is 1, the pageId for the first page will be 0.
Similarly, the first systemId on each page will be 0
>>> from music21 import * >>> lt = corpus.parse('demos/layoutTest.xml') >>> l = layout.divideByPages(lt, fastMeasures=True) >>> l.getPageAndSystemNumberFromMeasureNumber(80) (3, 3)
- getPositionForStaff(pageId, systemId, staffId)¶
return a tuple of (top, bottom) for a staff, specified by a given pageId, systemId, and staffId in tenths of a staff-space.
This distance is specified with respect to the top of the system.
Staff scaling (<staff-details> in musicxml inside an <attributes> object) is taken into account, but not non 5-line staves. Thus a normally sized staff is always of height 40 (4 spaces of 10-tenths each)
>>> from music21 import * >>> lt = corpus.parse('demos/layoutTest.xml') >>> ls = layout.divideByPages(lt, fastMeasures = True)The first staff (staff 0) of each page/system always begins at height 0 and should end at height 40 if it is a 5-line staff (not taken into account) with no staffSize changes
>>> ls.getPositionForStaff(0, 0, 0) (0.0, 40.0) >>> ls.getPositionForStaff(1, 0, 0) (0.0, 40.0)The second staff (staff 1) begins at the end of staff 0 (40.0) + the appropriate staffDistance and adds the height of the staff. Staff 1 here has a size of 80 which means 80% of the normal staff size. 40 * 0.8 = 32.0:
>>> ls.getPositionForStaff(0, 0, 1) (133.0, 165.0)The third staff (staff 2) begins after the second staff (staff 1) but is a normal size staff
>>> ls.getPositionForStaff(0, 0, 2) (266.0, 306.0)The first staff (staff 0) of the second system (system 1) also begins at 0 and as a normally-sized staff, has height of 40:
>>> ls.getPositionForStaff(0, 1, 0) (0.0, 40.0)The spacing between the staves has changed in the second system, but the staff height has not:
>>> ls.getPositionForStaff(0, 1, 1) (183.0, 215.0) >>> ls.getPositionForStaff(0, 1, 2) (356.0, 396.0)In the third system (system 2), the staff distance reverts to the distance of system 0, but the staffSize is now 120 or 48 tenths (40 * 1.2 = 48)
>>> ls.getPositionForStaff(0, 2, 1) (117.0, 165.0)Page 1 (0), System 4 (3), Staff 2 (1) is a hidden (“optimized”) system. Thus its staffLayout notes this:
>>> staffLayout031 = ls.pages[0].systems[3].staves[1].staffLayout >>> staffLayout031 <music21.layout.StaffLayout distance None, staffNumber None, staffSize 80.0> >>> staffLayout031.hidden TrueThus, the position for this staff will have the same top and bottom, and the position for the next staff will have the same top as the previous staff:
>>> ls.getPositionForStaff(0, 3, 0) (0.0, 40.0) >>> ls.getPositionForStaff(0, 3, 1) (40.0, 40.0) >>> ls.getPositionForStaff(0, 3, 2) (133.0, 173.0)Tests for a score with PartStaff objects:
>>> lt = corpus.parse('demos/layoutTestMore.xml', forceSource=True) >>> ls = layout.divideByPages(lt, fastMeasures = True) >>> ls.getPositionForStaff(0, 0, 0) (0.0, 40.0) >>> ls.getPositionForStaff(0, 0, 1) (133.0, 173.0) >>> ls.getPositionForStaff(0, 0, 2) (235.0, 275.0) >>> ls.getPositionForStaff(0, 2, 0) (0.0, 40.0) >>> ls.getPositionForStaff(0, 2, 1) (40.0, 40.0) >>> ls.getPositionForStaff(0, 2, 2) (40.0, 40.0)System 4 has the top staff hidden, which has been causing problems:
>>> ls.getPositionForStaff(0, 4, 0) (0.0, 0.0) >>> ls.getPositionForStaff(0, 4, 1) (0.0, 40.0)
- getPositionForStaffMeasure(staffId, measureNumber, returnFormat='tenths')¶
Given a layoutScore from divideByPages, a staffId, and a measureNumber, returns a tuple of ((top, left), (bottom, right), pageId) allowing an exact position for the measure on the page. If returnFormat is “tenths”, then it will be returned in tenths.
If returnFormat is “float”, returns each as a number from 0 to 1 where 0 is the top or left of the page, and 1 is the bottom or right of the page.
>>> from music21 import * >>> lt = corpus.parse('demos/layoutTest.xml') >>> ls = layout.divideByPages(lt, fastMeasures = True)The first measure of staff one begins at 336 tenths from the top (125 for the margin top and 211 for the top-staff-distance). It begins 170.0 from the left (100 for the page-margin-left, 70 for staff-margin-left). It ends 40.0 below that (staffHeight) and 247.0 to the right (measure width)
>>> ls.getPositionForStaffMeasure(0, 1) ((336.0, 170.0), (376.0, 417.0), 0)The other staves for the same measure are below this one:
>>> ls.getPositionForStaffMeasure(1, 1) ((469.0, 170.0), (501.0, 417.0), 0) >>> ls.getPositionForStaffMeasure(2, 1) ((602.0, 170.0), (642.0, 417.0), 0)If float is requested for returning, then the numbers are the fraction of the distance across the page.
>>> ls.getPositionForStaffMeasure(0, 1, returnFormat='float') ((0.152..., 0.0996...), (0.170..., 0.244...), 0)Moving over the page boundary:
>>> ls.getPositionForStaffMeasure(0, 23) ((1703.0, 1345.0), (1743.0, 1606.0), 0) >>> ls.getPositionForStaffMeasure(1, 23) #hidden ((1743.0, 1345.0), (1743.0, 1606.0), 0) >>> ls.getPositionForStaffMeasure(0, 24) ((195.0, 100.0), (235.0, 431.0), 1) >>> ls.getPositionForStaffMeasure(1, 24) ((328.0, 100.0), (360.0, 431.0), 1)
- getPositionForSystem(pageId, systemId)¶
first systems on a page use a different positioning.
returns a tuple of the (top, left, right, and bottom) where each unit is relative to the page margins
N.B. right is NOT the width – it is different. It is the offset to the right margin. weird, inconsistent, but most useful... bottom is the hard part to compute...
>>> from music21 import * >>> lt = corpus.parse('demos/layoutTestMore.xml') >>> ls = layout.divideByPages(lt, fastMeasures = True) >>> ls.getPositionForSystem(0, 0) (211.0, 70.0, 0.0, 696.0) >>> ls.getPositionForSystem(0, 1) (810.0, 0.0, 0.0, 1173.0) >>> ls.getPositionForSystem(0, 2) (1340.0, 67.0, 92.0, 1610.0) >>> ls.getPositionForSystem(0, 3) (1724.0, 0.0, 0.0, 2030.0) >>> ls.getPositionForSystem(0, 4) (2144.0, 0.0, 0.0, 2583.0)
- getStaffDistanceFromPrevious(pageId, systemId, staffId)¶
return the distance of this staff from the previous staff in the same system
for staffId = 0, this is always 0.0
TODO:tests, now that this is out from previous
- getStaffHiddenAttribute(pageId, systemId, staffId)¶
returns the staffLayout.hidden attribute for a staffId, or if it is not defined, recursively search through previous staves until one is found.
>>> from music21 import * >>> lt = corpus.parse('demos/layoutTestMore.xml', forceSource=True) >>> ls = layout.divideByPages(lt, fastMeasures = True) >>> ls.getStaffHiddenAttribute(0, 0, 0) False >>> ls.getStaffHiddenAttribute(0, 0, 1) False >>> ls.getStaffHiddenAttribute(0, 1, 1) True >>> ls.getStaffHiddenAttribute(0, 2, 1) True >>> ls.getStaffHiddenAttribute(0, 3, 1) False
- getStaffSizeFromLayout(pageId, systemId, staffId)¶
Get the currently active staff-size for a given pageId, systemId, and staffId.
Note that this does not take into account the hiddenness of the staff, which if True makes the effective size 0.0 – see getStaffHiddenAttribute
>>> from music21 import * >>> lt = corpus.parse('demos/layoutTest.xml', forceSource=True) >>> ls = layout.divideByPages(lt, fastMeasures = True) >>> ls.getStaffSizeFromLayout(0, 0, 0) 40.0 >>> ls.getStaffSizeFromLayout(0, 0, 1) 32.0 >>> ls.getStaffSizeFromLayout(0, 0, 2) 40.0 >>> ls.getStaffSizeFromLayout(0, 1, 1) 32.0 >>> ls.getStaffSizeFromLayout(0, 2, 1) 48.0 >>> ls.getStaffSizeFromLayout(0, 3, 1) 32.0
- getSystemBeforeThis(pageId, systemId)¶
given a pageId and systemId, get the (pageId, systemId) for the previous system.
return (None, None) if it’s the first system on the first page
This test score has five systems on the first page, three on the second, and two on the third
>>> from music21 import * >>> lt = corpus.parse('demos/layoutTestMore.xml', forceSource=True) >>> ls = layout.divideByPages(lt, fastMeasures = True) >>> systemId = 1 >>> pageId = 2 # last system, last page >>> while systemId is not None: ... pageId, systemId = ls.getSystemBeforeThis(pageId, systemId) ... print (pageId, systemId), (2, 0) (1, 2) (1, 1) (1, 0) (0, 4) (0, 3) (0, 2) (0, 1) (0, 0) (None, None)
- measurePositionWithinSystem(measureNumber, pageId=None, systemId=None)¶
Given a measure number, find the start and end X positions (with respect to the system margins) for the measure.
if pageId and systemId are given, then it will speed up the search. But not necessary
no staffId is needed since (at least for now) all measures begin and end at the same X position
>>> from music21 import * >>> l = corpus.parse('demos/layoutTest.xml') >>> ls = layout.divideByPages(l, fastMeasures = True) >>> ls.measurePositionWithinSystem(1, 0, 0) (0.0, 247.0) >>> ls.measurePositionWithinSystem(2, 0, 0) (247.0, 544.0) >>> ls.measurePositionWithinSystem(3, 0, 0) (544.0, 841.0)Measure positions reset at the start of a new system
>>> ls.measurePositionWithinSystem(6) (0.0, 331.0) >>> ls.measurePositionWithinSystem(7) (331.0, 549.0)Methods inherited from Opus: getNumbers(), getScoreByNumber(), getScoreByTitle(), mergeScores(), show(), write()
Methods inherited from Stream: append(), insert(), insertAndShift(), transpose(), augmentOrDiminish(), scaleOffsets(), scaleDurations(), activateVariants(), addGroupForElements(), allPlayingWhileSounding(), analyze(), attachIntervalsBetweenStreams(), attachMelodicIntervals(), attributeCount(), beatAndMeasureFromOffset(), bestClef(), chordify(), expandRepeats(), explode(), extendDuration(), extendDurationAndGetBoundaries(), extendTies(), extractContext(), findConsecutiveNotes(), findGaps(), flattenUnnecessaryVoices(), getClefs(), getElementAfterElement(), getElementAtOrBefore(), getElementBeforeOffset(), getElementById(), getElementsByClass(), getElementsByGroup(), getElementsByOffset(), getElementsNotOfClass(), getInstrument(), getInstruments(), getKeySignatures(), getOffsetByElement(), getOverlaps(), getSimultaneous(), getTimeSignatures(), groupElementsByOffset(), hasElement(), hasElementOfClass(), hasMeasures(), hasPartLikeStreams(), hasVoices(), haveAccidentalsBeenMade(), haveBeamsBeenMade(), index(), insertIntoNoteOrChord(), internalize(), invertDiatonic(), isSequence(), isTwelveTone(), isWellFormedNotation(), lyrics(), makeAccidentals(), makeBeams(), makeChords(), makeImmutable(), makeMeasures(), makeMutable(), makeNotation(), makeRests(), makeTies(), makeTupletBrackets(), makeVariantBlocks(), makeVoices(), measure(), measureOffsetMap(), measureTemplate(), measures(), melodicIntervals(), mergeElements(), metronomeMarkBoundaries(), pitchAttributeCount(), playingWhenAttacked(), plot(), pop(), quantize(), realizeOrnaments(), recurse(), remove(), removeByClass(), removeByNotOfClass(), repeatAppend(), repeatInsert(), replace(), restoreActiveSites(), shiftElements(), showVariantAsOssialikePart(), simultaneousAttacks(), sliceAtOffsets(), sliceByBeat(), sliceByGreatestDivisor(), sliceByQuarterLengths(), sort(), splitAtQuarterLength(), splitByClass(), storeAtEnd(), stripTies(), toSoundingPitch(), toWrittenPitch(), transferOffsetToElements(), trimPlayingWhileSounding(), unwrapWeakref(), voicesToParts(), wrapWeakref()
Methods inherited from Music21Object: addContext(), addLocation(), findAttributeInHierarchy(), getAllContextsByClass(), getContextAttr(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), next(), previous(), purgeLocations(), purgeOrphans(), removeLocationBySite(), removeLocationBySiteId(), setContextAttr(), setOffsetBySite(), splitAtDurations(), splitByQuarterLengths()
Inherits from: Opus, Stream, Music21Object
Designation that all the music in this Stream belongs on a single notated page.
Page attributes
Attributes without Documentation: pageNumber, pageLayout, systemEnd, measureStart, systemStart, measureEnd
Attributes inherited from Stream: isMeasure, isStream, definesExplicitPageBreaks, isFlat, autoSort, isSorted, flattenedRepresentationOf, definesExplicitSystemBreaks
Attributes inherited from Music21Object: classSortOrder, isSpanner, isVariant, xPosition, id, sites, groups, hideObjectOnPrint
Page properties
- systems¶
No documentation.
Properties inherited from Opus: scores
Properties inherited from Stream: notes, pitches, atSoundingPitch, beat, beatDuration, beatStr, beatStrength, derivationChain, derivationMethod, derivesFrom, duration, elements, finalBarline, flat, highestOffset, highestTime, isGapless, lowestOffset, metadata, notesAndRests, offsetMap, rootDerivation, seconds, secondsMap, semiFlat, sorted, spannerBundle, spanners, variants, voices
Properties inherited from Music21Object: activeSite, classes, derivationHierarchy, fullyQualifiedClasses, isGrace, measureNumber, offset, priority
Page methods
Methods inherited from Opus: getNumbers(), getScoreByNumber(), getScoreByTitle(), mergeScores(), show(), write()
Methods inherited from Stream: append(), insert(), insertAndShift(), transpose(), augmentOrDiminish(), scaleOffsets(), scaleDurations(), activateVariants(), addGroupForElements(), allPlayingWhileSounding(), analyze(), attachIntervalsBetweenStreams(), attachMelodicIntervals(), attributeCount(), beatAndMeasureFromOffset(), bestClef(), chordify(), expandRepeats(), explode(), extendDuration(), extendDurationAndGetBoundaries(), extendTies(), extractContext(), findConsecutiveNotes(), findGaps(), flattenUnnecessaryVoices(), getClefs(), getElementAfterElement(), getElementAtOrBefore(), getElementBeforeOffset(), getElementById(), getElementsByClass(), getElementsByGroup(), getElementsByOffset(), getElementsNotOfClass(), getInstrument(), getInstruments(), getKeySignatures(), getOffsetByElement(), getOverlaps(), getSimultaneous(), getTimeSignatures(), groupElementsByOffset(), hasElement(), hasElementOfClass(), hasMeasures(), hasPartLikeStreams(), hasVoices(), haveAccidentalsBeenMade(), haveBeamsBeenMade(), index(), insertIntoNoteOrChord(), internalize(), invertDiatonic(), isSequence(), isTwelveTone(), isWellFormedNotation(), lyrics(), makeAccidentals(), makeBeams(), makeChords(), makeImmutable(), makeMeasures(), makeMutable(), makeNotation(), makeRests(), makeTies(), makeTupletBrackets(), makeVariantBlocks(), makeVoices(), measure(), measureOffsetMap(), measureTemplate(), measures(), melodicIntervals(), mergeElements(), metronomeMarkBoundaries(), pitchAttributeCount(), playingWhenAttacked(), plot(), pop(), quantize(), realizeOrnaments(), recurse(), remove(), removeByClass(), removeByNotOfClass(), repeatAppend(), repeatInsert(), replace(), restoreActiveSites(), shiftElements(), showVariantAsOssialikePart(), simultaneousAttacks(), sliceAtOffsets(), sliceByBeat(), sliceByGreatestDivisor(), sliceByQuarterLengths(), sort(), splitAtQuarterLength(), splitByClass(), storeAtEnd(), stripTies(), toSoundingPitch(), toWrittenPitch(), transferOffsetToElements(), trimPlayingWhileSounding(), unwrapWeakref(), voicesToParts(), wrapWeakref()
Methods inherited from Music21Object: addContext(), addLocation(), findAttributeInHierarchy(), getAllContextsByClass(), getContextAttr(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), next(), previous(), purgeLocations(), purgeOrphans(), removeLocationBySite(), removeLocationBySiteId(), setContextAttr(), setOffsetBySite(), splitAtDurations(), splitByQuarterLengths()
Inherits from: Score, Stream, Music21Object
Designation that all the music in this Stream belongs on a single notated system.
System attributes
Attributes without Documentation: systemLayout, systemNumber, measureStart, measureEnd
Attributes inherited from Stream: isMeasure, isStream, definesExplicitPageBreaks, isFlat, autoSort, isSorted, flattenedRepresentationOf, definesExplicitSystemBreaks
Attributes inherited from Music21Object: classSortOrder, isSpanner, isVariant, xPosition, id, sites, groups, hideObjectOnPrint
System properties
- staves¶
No documentation.
Properties inherited from Score: parts
Properties inherited from Stream: notes, pitches, atSoundingPitch, beat, beatDuration, beatStr, beatStrength, derivationChain, derivationMethod, derivesFrom, duration, elements, finalBarline, flat, highestOffset, highestTime, isGapless, lowestOffset, metadata, notesAndRests, offsetMap, rootDerivation, seconds, secondsMap, semiFlat, sorted, spannerBundle, spanners, variants, voices
Properties inherited from Music21Object: activeSite, classes, derivationHierarchy, fullyQualifiedClasses, isGrace, measureNumber, offset, priority
System methods
Methods inherited from Score: expandRepeats(), flattenParts(), implode(), makeNotation(), measure(), measureOffsetMap(), measures(), partsToVoices(), sliceByGreatestDivisor()
Methods inherited from Stream: append(), insert(), insertAndShift(), transpose(), augmentOrDiminish(), scaleOffsets(), scaleDurations(), activateVariants(), addGroupForElements(), allPlayingWhileSounding(), analyze(), attachIntervalsBetweenStreams(), attachMelodicIntervals(), attributeCount(), beatAndMeasureFromOffset(), bestClef(), chordify(), explode(), extendDuration(), extendDurationAndGetBoundaries(), extendTies(), extractContext(), findConsecutiveNotes(), findGaps(), flattenUnnecessaryVoices(), getClefs(), getElementAfterElement(), getElementAtOrBefore(), getElementBeforeOffset(), getElementById(), getElementsByClass(), getElementsByGroup(), getElementsByOffset(), getElementsNotOfClass(), getInstrument(), getInstruments(), getKeySignatures(), getOffsetByElement(), getOverlaps(), getSimultaneous(), getTimeSignatures(), groupElementsByOffset(), hasElement(), hasElementOfClass(), hasMeasures(), hasPartLikeStreams(), hasVoices(), haveAccidentalsBeenMade(), haveBeamsBeenMade(), index(), insertIntoNoteOrChord(), internalize(), invertDiatonic(), isSequence(), isTwelveTone(), isWellFormedNotation(), lyrics(), makeAccidentals(), makeBeams(), makeChords(), makeImmutable(), makeMeasures(), makeMutable(), makeRests(), makeTies(), makeTupletBrackets(), makeVariantBlocks(), makeVoices(), measureTemplate(), melodicIntervals(), mergeElements(), metronomeMarkBoundaries(), pitchAttributeCount(), playingWhenAttacked(), plot(), pop(), quantize(), realizeOrnaments(), recurse(), remove(), removeByClass(), removeByNotOfClass(), repeatAppend(), repeatInsert(), replace(), restoreActiveSites(), shiftElements(), showVariantAsOssialikePart(), simultaneousAttacks(), sliceAtOffsets(), sliceByBeat(), sliceByQuarterLengths(), sort(), splitAtQuarterLength(), splitByClass(), storeAtEnd(), stripTies(), toSoundingPitch(), toWrittenPitch(), transferOffsetToElements(), trimPlayingWhileSounding(), unwrapWeakref(), voicesToParts(), wrapWeakref()
Methods inherited from Music21Object: addContext(), addLocation(), findAttributeInHierarchy(), getAllContextsByClass(), getContextAttr(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), next(), previous(), purgeLocations(), purgeOrphans(), removeLocationBySite(), removeLocationBySiteId(), setContextAttr(), setOffsetBySite(), show(), splitAtDurations(), splitByQuarterLengths(), write()
Inherits from: Part, Stream, Music21Object
Designation that all the music in this Stream belongs on a single Staff.
Staff attributes
Attributes without Documentation: staffLayout, staffNumber, height, inheritedHeight, optimized
Attributes inherited from Part: staffLines
Attributes inherited from Stream: isMeasure, isStream, definesExplicitPageBreaks, isFlat, autoSort, isSorted, flattenedRepresentationOf, definesExplicitSystemBreaks
Attributes inherited from Music21Object: classSortOrder, isSpanner, isVariant, xPosition, id, sites, groups, hideObjectOnPrint
Staff properties
Properties inherited from Stream: notes, pitches, atSoundingPitch, beat, beatDuration, beatStr, beatStrength, derivationChain, derivationMethod, derivesFrom, duration, elements, finalBarline, flat, highestOffset, highestTime, isGapless, lowestOffset, metadata, notesAndRests, offsetMap, rootDerivation, seconds, secondsMap, semiFlat, sorted, spannerBundle, spanners, variants, voices
Properties inherited from Music21Object: activeSite, classes, derivationHierarchy, fullyQualifiedClasses, isGrace, measureNumber, offset, priority
Staff methods
Methods inherited from Part: makeAccidentals()
Methods inherited from Stream: append(), insert(), insertAndShift(), transpose(), augmentOrDiminish(), scaleOffsets(), scaleDurations(), activateVariants(), addGroupForElements(), allPlayingWhileSounding(), analyze(), attachIntervalsBetweenStreams(), attachMelodicIntervals(), attributeCount(), beatAndMeasureFromOffset(), bestClef(), chordify(), expandRepeats(), explode(), extendDuration(), extendDurationAndGetBoundaries(), extendTies(), extractContext(), findConsecutiveNotes(), findGaps(), flattenUnnecessaryVoices(), getClefs(), getElementAfterElement(), getElementAtOrBefore(), getElementBeforeOffset(), getElementById(), getElementsByClass(), getElementsByGroup(), getElementsByOffset(), getElementsNotOfClass(), getInstrument(), getInstruments(), getKeySignatures(), getOffsetByElement(), getOverlaps(), getSimultaneous(), getTimeSignatures(), groupElementsByOffset(), hasElement(), hasElementOfClass(), hasMeasures(), hasPartLikeStreams(), hasVoices(), haveAccidentalsBeenMade(), haveBeamsBeenMade(), index(), insertIntoNoteOrChord(), internalize(), invertDiatonic(), isSequence(), isTwelveTone(), isWellFormedNotation(), lyrics(), makeBeams(), makeChords(), makeImmutable(), makeMeasures(), makeMutable(), makeNotation(), makeRests(), makeTies(), makeTupletBrackets(), makeVariantBlocks(), makeVoices(), measure(), measureOffsetMap(), measureTemplate(), measures(), melodicIntervals(), mergeElements(), metronomeMarkBoundaries(), pitchAttributeCount(), playingWhenAttacked(), plot(), pop(), quantize(), realizeOrnaments(), recurse(), remove(), removeByClass(), removeByNotOfClass(), repeatAppend(), repeatInsert(), replace(), restoreActiveSites(), shiftElements(), showVariantAsOssialikePart(), simultaneousAttacks(), sliceAtOffsets(), sliceByBeat(), sliceByGreatestDivisor(), sliceByQuarterLengths(), sort(), splitAtQuarterLength(), splitByClass(), storeAtEnd(), stripTies(), toSoundingPitch(), toWrittenPitch(), transferOffsetToElements(), trimPlayingWhileSounding(), unwrapWeakref(), voicesToParts(), wrapWeakref()
Methods inherited from Music21Object: addContext(), addLocation(), findAttributeInHierarchy(), getAllContextsByClass(), getContextAttr(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), next(), previous(), purgeLocations(), purgeOrphans(), removeLocationBySite(), removeLocationBySiteId(), setContextAttr(), setOffsetBySite(), show(), splitAtDurations(), splitByQuarterLengths(), write()
Inherits from: Spanner, Music21Object
A StaffGroup defines a collection of one or more Parts, specifying that they should be shown together with a bracket, brace, or other symbol, and may have a common name.
>>> from music21 import *
>>> p1 = stream.Part()
>>> p2 = stream.Part()
>>> p1.append(note.WholeNote('C5'))
>>> p1.append(note.WholeNote('D5'))
>>> p2.append(note.WholeNote('C3'))
>>> p2.append(note.WholeNote('D3'))
>>> p3 = stream.Part()
>>> p3.append(note.WholeNote('F#4'))
>>> p3.append(note.WholeNote('G#4'))
>>> s = stream.Score()
>>> s.insert(0, p1)
>>> s.insert(0, p2)
>>> s.insert(0, p3)
>>> staffGroup1 = layout.StaffGroup([p1, p2], name='Marimba', abbreviation='Mba.', symbol='brace')
>>> staffGroup1.barTogether = 'Mensurstrich'
>>> s.insert(0, staffGroup1)
>>> staffGroup2 = layout.StaffGroup([p3], name='Xylophone', abbreviation='Xyl.', symbol='bracket')
>>> s.insert(0, staffGroup2)
>>> s.show()
StaffGroup attributes
Attributes without Documentation: abbreviation, name
Attributes inherited from Spanner: isSpanner, completeStatus, spannedElements, idLocal
Attributes inherited from Music21Object: classSortOrder, isStream, isVariant, id, sites, groups, xPosition, hideObjectOnPrint
StaffGroup properties
- barTogether¶
Get or set the barTogether value, with either Boolean values or yes or no strings. Or the string ‘Mensurstrich’ which indicates baring between staves but not in staves.
Currently Mensurstrich i
>>> from music21 import * >>> sg = layout.StaffGroup() >>> sg.barTogether = 'yes' >>> sg.barTogether True >>> sg.barTogether = 'Mensurstrich' >>> sg.barTogether 'Mensurstrich'
- symbol¶
Get or set the symbol value, with either Boolean values or yes or no strings.
>>> from music21 import * >>> sg = layout.StaffGroup() >>> sg.symbol = 'Brace' >>> sg.symbol 'brace'Properties inherited from Music21Object: classes, fullyQualifiedClasses, activeSite, beat, beatDuration, beatStr, beatStrength, derivationHierarchy, duration, isGrace, measureNumber, offset, priority, seconds
StaffGroup methods
Methods inherited from Spanner: addSpannedElements(), getDurationBySite(), getDurationSpanBySite(), getFirst(), getLast(), getOffsetSpanBySite(), getOffsetsBySite(), getSpannedElementIds(), getSpannedElements(), getSpannedElementsByClass(), getSpannerStorageId(), hasSpannedElement(), isFirst(), isLast(), purgeLocations(), purgeOrphans(), replaceSpannedElement(), unwrapWeakref(), wrapWeakref()
Methods inherited from Music21Object: findAttributeInHierarchy(), getContextAttr(), setContextAttr(), addContext(), addLocation(), getAllContextsByClass(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), hasSite(), hasSpannerSite(), hasVariantSite(), isClassOrSubclass(), mergeAttributes(), next(), previous(), removeLocationBySite(), removeLocationBySiteId(), setOffsetBySite(), show(), splitAtDurations(), splitAtQuarterLength(), splitByQuarterLengths(), write()