music21.stream.core

the Stream Core Mixin handles the core attributes of streams that should be thought of almost as private values and not used except by advanced programmers who need the highest speed in programming.

Nothing here promises to be stable. The music21 team can make any changes here for efficiency reasons while being considered backwards compatible so long as the public methods that call this remain stable.

All functions here will eventually begin with .core.

StreamCoreMixin

class music21.stream.core.StreamCoreMixin

Core aspects of a Stream’s behavior. Any of these can change at any time.

StreamCoreMixin read-only properties

StreamCoreMixin.spannerBundle

A low-level object for Spanner management. This is a read-only property.

StreamCoreMixin methods

StreamCoreMixin.asTimespans(classList=None, flatten=True)

Convert stream to a TimespanTree instance, a highly optimized data structure for searching through elements and offsets.

>>> score = tree.makeExampleScore()
>>> scoreTree = score.asTimespans()
>>> print(scoreTree)
<TimespanTree {20} (0.0 to 8.0) <music21.stream.Score exampleScore>>
    <ElementTimespan (0.0 to 0.0) <music21.clef.BassClef>>
    <ElementTimespan (0.0 to 0.0) <music21.meter.TimeSignature 2/4>>
    <ElementTimespan (0.0 to 0.0) <music21.instrument.Instrument 'PartA: : '>>
    <ElementTimespan (0.0 to 0.0) <music21.clef.BassClef>>
    <ElementTimespan (0.0 to 0.0) <music21.meter.TimeSignature 2/4>>
    <ElementTimespan (0.0 to 0.0) <music21.instrument.Instrument 'PartB: : '>>
    <PitchedTimespan (0.0 to 1.0) <music21.note.Note C>>
    <PitchedTimespan (0.0 to 2.0) <music21.note.Note C#>>
    <PitchedTimespan (1.0 to 2.0) <music21.note.Note D>>
    <PitchedTimespan (2.0 to 3.0) <music21.note.Note E>>
    <PitchedTimespan (2.0 to 4.0) <music21.note.Note G#>>
    <PitchedTimespan (3.0 to 4.0) <music21.note.Note F>>
    <PitchedTimespan (4.0 to 5.0) <music21.note.Note G>>
    <PitchedTimespan (4.0 to 6.0) <music21.note.Note E#>>
    <PitchedTimespan (5.0 to 6.0) <music21.note.Note A>>
    <PitchedTimespan (6.0 to 7.0) <music21.note.Note B>>
    <PitchedTimespan (6.0 to 8.0) <music21.note.Note D#>>
    <PitchedTimespan (7.0 to 8.0) <music21.note.Note C>>
    <ElementTimespan (8.0 to 8.0) <music21.bar.Barline type=final>>
    <ElementTimespan (8.0 to 8.0) <music21.bar.Barline type=final>>
StreamCoreMixin.asTree(flatten=False, classList=None, useTimespans=False, groupOffsets=False)

Returns an elementTree of the score, using exact positioning.

See tree.fromStream.asTree() for more details.

>>> score = tree.makeExampleScore()
>>> scoreTree = score.asTree(flatten=True)
>>> scoreTree
<ElementTree {20} (0.0 <0.-25...> to 8.0) <music21.stream.Score exampleScore>>
StreamCoreMixin.coreAppend(element: music21.base.Music21Object, *, setActiveSite=True)

N.B. – a “core” method, not to be used by general users. Run .append() instead.

Low level appending; like coreInsert does not error check, determine elements changed, or similar operations.

When using this method, the caller is responsible for calling Stream.coreElementsChanged after all operations are completed.

StreamCoreMixin.coreCopyAsDerivation(methodName: str, *, recurse=True, deep=True)

Make a copy of this stream with the proper derivation set.

>>> s = stream.Stream()
>>> n = note.Note()
>>> s.append(n)
>>> s2 = s.coreCopyAsDerivation('exampleCopy')
>>> s2.derivation.method
'exampleCopy'
>>> s2.derivation.origin is s
True
>>> s2[0].derivation.method
'exampleCopy'
StreamCoreMixin.coreElementsChanged(*, updateIsFlat=True, clearIsSorted=True, memo=None, keepIndex=False)

NB – a “core” stream method that is not necessary for most users.

This method is called automatically any time the elements in the Stream are changed. However, it may be called manually in case sites or other advanced features of an element have been modified. It was previously a private method and for most users should still be treated as such.

The various arguments permit optimizing the clearing of cached data in situations when completely dropping all cached data is excessive.

>>> a = stream.Stream()
>>> a.isFlat
True

Here we manipulate the private ._elements storage (which generally shouldn’t be done) using coreAppend and thus need to call .coreElementsChanged directly.

>>> a.coreAppend(stream.Stream())
>>> a.isFlat  # this is wrong.
True
>>> a.coreElementsChanged()
>>> a.isFlat
False
StreamCoreMixin.coreGatherMissingSpanners(*, recurse=True, requireAllPresent=True, insert=True, constrainingSpannerBundle: Optional[music21.spanner.SpannerBundle] = None) → Optional[List[music21.spanner.Spanner]]

find all spanners that are referenced by elements in the (recursed if recurse=True) stream and either inserts them in the Stream (if insert is True) or returns them if insert is False.

If requireAllPresent is True (default) then only those spanners whose complete spanned elements are in the Stream are returned.

Because spanners are stored weakly in .sites this is only guaranteed to find the spanners in cases where the spanner is in another stream that is still active.

Here’s a little helper function since we’ll make the same Stream several times, with two slurred notes, but without the slur itself. Python’s garbage collection will get rid of the slur if we do not prevent it

>>> preventGarbageCollection = []
>>> def getStream():
...    s = stream.Stream()
...    n = note.Note('C')
...    m = note.Note('D')
...    sl = spanner.Slur(n, m)
...    preventGarbageCollection.append(sl)
...    s.append([n, m])
...    return s

Okay now we have a Stream with two slurred notes, but without the slur. coreGatherMissingSpanners() will put it in at the beginning.

>>> s = getStream()
>>> s.show('text')
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>
>>> s.coreGatherMissingSpanners()
>>> s.show('text')
{0.0} <music21.note.Note C>
{0.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>
{1.0} <music21.note.Note D>

Now, the same Stream, but insert is False, so it will return a list of Spanners that should be inserted, rather than inserting them.

>>> s = getStream()
>>> spList = s.coreGatherMissingSpanners(insert=False)
>>> spList
[<music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>]
>>> s.show('text')
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>

Now we’ll remove the second note so not all elements of the slur are present, which by default will not insert the Slur:

>>> s = getStream()
>>> s.remove(s[-1])
>>> s.show('text')
{0.0} <music21.note.Note C>
>>> s.coreGatherMissingSpanners()
>>> s.show('text')
{0.0} <music21.note.Note C>

But with requireAllPresent=False, the spanner appears!

>>> s.coreGatherMissingSpanners(requireAllPresent=False)
>>> s.show('text')
{0.0} <music21.note.Note C>
{0.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>

With recurse=False, then spanners are not gathered inside the inner stream:

>>> t = stream.Part()
>>> s = getStream()
>>> t.insert(0, s)
>>> t.coreGatherMissingSpanners(recurse=False)
>>> t.show('text')
{0.0} <music21.stream.Stream 0x104935b00>
    {0.0} <music21.note.Note C>
    {1.0} <music21.note.Note D>

But the default acts with recursion:

>>> t.coreGatherMissingSpanners()
>>> t.show('text')
{0.0} <music21.stream.Stream 0x104935b00>
    {0.0} <music21.note.Note C>
    {1.0} <music21.note.Note D>
{0.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>

Spanners already in the stream are not put there again:

>>> s = getStream()
>>> sl = s.notes.first().getSpannerSites()[0]
>>> sl
<music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>
>>> s.insert(0, sl)
>>> s.coreGatherMissingSpanners()
>>> s.show('text')
{0.0} <music21.note.Note C>
{0.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>
{1.0} <music21.note.Note D>

Also does not happen with recursion.

>>> t = stream.Part()
>>> s = getStream()
>>> sl = s.notes.first().getSpannerSites()[0]
>>> s.insert(0, sl)
>>> t.insert(0, s)
>>> t.coreGatherMissingSpanners()
>>> t.show('text')
{0.0} <music21.stream.Stream 0x104935b00>
    {0.0} <music21.note.Note C>
    {0.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>
    {1.0} <music21.note.Note D>

If constrainingSpannerBundle is set then only spanners also present in that spannerBundle are added. This can be useful, for instance, in restoring spanners from an excerpt that might already have spanners removed. In Jacob Tyler Walls’s brilliant phrasing, it prevents regrowing zombie spanners that you thought you had killed.

Here we will constrain only to spanners also present in another Stream:

>>> s = getStream()
>>> s2 = stream.Stream()
>>> s.coreGatherMissingSpanners(constrainingSpannerBundle=s2.spannerBundle)
>>> s.show('text')
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>

Now with the same constraint, but we will put the Slur into the other stream.

>>> sl = s.notes.first().getSpannerSites()[0]
>>> s2.insert(0, sl)
>>> s.coreGatherMissingSpanners(constrainingSpannerBundle=s2.spannerBundle)
>>> s.show('text')
{0.0} <music21.note.Note C>
{0.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>
{1.0} <music21.note.Note D>
StreamCoreMixin.coreGetElementByMemoryLocation(objId)

NB – a “core” stream method that is not necessary for most users.

Low-level tool to get an element based only on the object id.

This is not the same as getElementById, which refers to the id attribute which may be manually set and not unique.

However, some implementations of python will reuse object locations, sometimes quickly, so don’t keep these around.

Used by spanner and variant.

>>> s = stream.Stream()
>>> n1 = note.Note('g')
>>> n2 = note.Note('g#')
>>> s.append(n1)
>>> s.coreGetElementByMemoryLocation(id(n1)) is n1
True
>>> s.coreGetElementByMemoryLocation(id(n2)) is None
True
>>> b = bar.Barline()
>>> s.storeAtEnd(b)
>>> s.coreGetElementByMemoryLocation(id(b)) is b
True
StreamCoreMixin.coreGuardBeforeAddElement(element, *, checkRedundancy=True)

Before adding an element, this method performs important checks on that element.

Used by:

  • insert()

  • append()

  • storeAtEnd()

  • Stream.__init__()

Returns None or raises a StreamException

>>> s = stream.Stream()
>>> s.coreGuardBeforeAddElement(s)
Traceback (most recent call last):
music21.exceptions21.StreamException: this Stream cannot be contained within itself
>>> s.append(s.iter())
Traceback (most recent call last):
music21.exceptions21.StreamException: cannot insert StreamIterator into a Stream
Iterate over it instead (User's Guide chs. 6 and 26)
>>> s.insert(4, 3.14159)
Traceback (most recent call last):
music21.exceptions21.StreamException: to put a non Music21Object in a stream,
create a music21.ElementWrapper for the item
StreamCoreMixin.coreHasElementByMemoryLocation(objId: int) → bool

NB – a “core” stream method that is not necessary for most users. use hasElement(obj)

Return True if an element object id, provided as an argument, is contained in this Stream.

>>> s = stream.Stream()
>>> n1 = note.Note('g')
>>> n2 = note.Note('g#')
>>> s.append(n1)
>>> s.coreHasElementByMemoryLocation(id(n1))
True
>>> s.coreHasElementByMemoryLocation(id(n2))
False
StreamCoreMixin.coreInsert(offset: Union[float, fractions.Fraction], element: music21.base.Music21Object, *, ignoreSort=False, setActiveSite=True)

N.B. – a “core” method, not to be used by general users. Run .insert() instead.

A faster way of inserting elements that does no checks, just insertion.

Only be used in contexts that we know we have a proper, single Music21Object. Best for usage when taking objects in a known Stream and creating a new Stream

When using this method, the caller is responsible for calling Stream.coreElementsChanged after all operations are completed.

Do not mix coreInsert with coreAppend operations.

Returns boolean if the Stream is now sorted.

StreamCoreMixin.coreSelfActiveSite(el)

Set the activeSite of el to be self.

Override for SpannerStorage, VariantStorage, which should never become the activeSite

StreamCoreMixin.coreSetElementOffset(element: music21.base.Music21Object, offset: Union[int, float, fractions.Fraction, str], *, addElement=False, setActiveSite=True)

Sets the Offset for an element, very quickly. Caller is responsible for calling coreElementsChanged() afterward.

>>> s = stream.Stream()
>>> s.id = 'Stream1'
>>> n = note.Note('B-4')
>>> s.insert(10, n)
>>> n.offset
10.0
>>> s.coreSetElementOffset(n, 20.0)
>>> n.offset
20.0
>>> n.getOffsetBySite(s)
20.0
StreamCoreMixin.coreStoreAtEnd(element, setActiveSite=True)

NB – this is a “core” method. Use .storeAtEnd() instead.

Core method for adding end elements. To be called by other methods.