
    rhcn                      % S r SSKJr  SSKrSSKJrJr  SSKrSSKrSSK	J
r
  SSKrSSKJr  SSKrSSKrSSKrSSKJrJr  SSKJr  SS	KJrJr  SS
KJr  SSKJrJr  SSKJr  SSKJ r   SSK!J"r"J#r#  SSK$J%r%  SSKJ&r&  SSKJ'r'  SSKJ(r(  SSK)J*r*J+r+J,r,  SSK-J.r.  SSK/J0r0J1r1J2r2  SSKJ3r3  \Rh                  (       a1  SSK5r5SSK6J7r7  SSK8r8SSKJ9r9  SSKJ:r:  SSKJ;r;  \Rx                  " SSS9r=\r>\r?/ SQr@\'R                  rA\&R                  " S5      rC/ rDS  H!  rE\
" \E5      rF\Fb  M  \DR                  \E5        M#     C
CE\D(       a)  \CS!   S";   a   \CR                  \R                  " \D5      S#S$9   " S% S&\'R                  5      rJ " S' S(\'R                  5      rK " S) S*\R                  5      rM " S+ S,\R                  5      rN " S- S.\O5      rP " S/ S0\Q5      rR\S" 5       rT\S" 5       rU\R                  S;S1 j5       rW " S2 S3\(R                  5      rY\O" \Z" \Y" 5       5      5      r[S4\\S5'    " S6 S7\Y5      r] " S8 S9\R                  5      r_\Y\]/r`\aS::X  a  SSKr\R                  " 5         gg)<a  
`music21.base` is what you get in `music21` if you type ``import music21``. It
contains all the most low-level objects that also appear in the music21 module
(i.e., music21.base.Music21Object is the same as music21.Music21Object).

Music21 base classes for :class:`~music21.stream.Stream` objects and all
elements contained within them including Notes, etc. Additional objects for
defining and manipulating elements are included.

The namespace of this file, as all base.py files, is loaded into the package
that contains this file via __init__.py. Everything in this file is thus
available after importing `music21`.

>>> import music21
>>> music21.Music21Object
<class 'music21.base.Music21Object'>

>>> music21.VERSION_STR
'9.9.1'

Alternatively, after doing a complete import, these classes are available
under the module "base":

>>> base.Music21Object
<class 'music21.base.Music21Object'>
    )annotationsN)	GeneratorIterable)	find_spec)overload)__version____version_info__)common)ElementSearchOffsetSpecial)opFrac)OffsetQL
OffsetQLIn)defaults)
Derivation)DurationDurationException)	Editorial)environment)exceptions21)prebase)SitesSitesExceptionWEAKREF_ACTIVE)Style)	SortTupleZeroSortTupleLowZeroSortTupleHigh)tie)IOBasemeterstream)spanner_M21Tzmusic21.base.Music21Object)bound)	Music21Exceptionr   Music21ObjectExceptionElementExceptionGroupsMusic21ObjectElementWrapperVERSIONVERSION_STRbase)
matplotlibnumpywarnings)   1Tzmusic21:)headerc                      \ rS rSrSrg)r)   ~    N__name__
__module____qualname____firstlineno____static_attributes__r9       F/home/james-whalen/.local/lib/python3.13/site-packages/music21/base.pyr)   r)   ~       r@   r)   c                      \ rS rSrSrg)r*      r9   Nr:   r9   r@   rA   r*   r*      rB   r@   r*   c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg	)
ContextTuple   stream.Streamsiter   offsetstream.enums.RecursionTyperecurseTyper9   Nr;   r<   r=   r>   __annotations__r?   r9   r@   rA   rF   rF      s    
++r@   rF   c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg	)
ContextSortTuple   rH   rI   r   rJ   rK   rL   r9   NrM   r9   r@   rA   rP   rP      s    
++r@   rP   c                  N   ^  \ rS rSrSrU 4S jrSS jrU 4S jrU 4S jrSr	U =r
$ )	_SplitTuple   a  
>>> st = base._SplitTuple([1, 2])
>>> st.spannerList = [expressions.Trill()]
>>> st
(1, 2)
>>> st.spannerList
[<music21.expressions.Trill>]
>>> a, b = st
>>> a
1
>>> b
2
>>> st.__class__
<class 'music21.base._SplitTuple'>

OMIT_FROM_DOCS

Might have been a mistake to make an implicit return make sure that
normal tuple comparisons work, but that things do not hash the same.

st2 has the same (1, 2) value as st1 but no spanners

>>> st2 = base._SplitTuple([1, 2])
>>> st == st2
False
>>> c = set()
>>> c.add(st)
>>> st2 in c
False

>>> st3 = base._SplitTuple([1, 2])
>>> st2 == st3
True

>>> st_big = base._SplitTuple([1, 3])
>>> st2 < st_big
True
c                >   > [         [        U ]  U [        U5      5      $ N)superrS   __new__tuple)clstupEls	__class__s     rA   rX   _SplitTuple.__new__   s    [#.sE&MBBr@   c                    / U l         g rV   spannerList)selfr[   s     rA   __init___SplitTuple.__init__   s
    24r@   c                   > [        U[        5      (       d  gU R                  UR                  :w  a  g[        TU ]  U5      $ )NF)
isinstancerS   r`   rW   __eq__)ra   otherr\   s     rA   rf   _SplitTuple.__eq__   s9    %--u000w~e$$r@   c                b   > [         TU ]  5       n[        U R                  5      n[	        X45      $ rV   )rW   __hash__idr`   hash)ra   h1h2r\   s      rA   rj   _SplitTuple.__hash__   s,    W  !RH~r@   r_   )r[   t.AnyreturnNone)r;   r<   r=   r>   __doc__rX   rb   rf   rj   r?   __classcell__r\   s   @rA   rS   rS      s#    %LC5% r@   rS   c                  N   ^  \ rS rSrSrSrSS jrSS jrU 4S jrS	S jr	Sr
U =r$ )
r+      az  
Groups is a list (subclass) of strings used to identify
associations that an element might have.

(in the future, Groups will become a set subclass)

The Groups object enforces that all elements must be strings, and that
the same element cannot be provided more than once.

NOTE: In the future, spaces will not be allowed in group names.


>>> g = Groups()
>>> g.append('hello')
>>> g[0]
'hello'

>>> g.append('hello')  # not added as already present
>>> len(g)
1

>>> g
['hello']

>>> g.append(5)  # type: ignore
Traceback (most recent call last):
music21.exceptions21.GroupException: Only strings can be used as group names, not 5
r9   c                h    [        U[        5      (       d  [        R                  " SSU< 3-   5      eg )Nz)Only strings can be used as group names, znot )re   strr   GroupExceptionra   values     rA   
_validNameGroups._validName   s<    %%%--.Y26ui0@/A B B &r@   c                    U R                  U5        [        R                  X5      (       d  [        R                  X5        g g rV   )r}   list__contains__appendr{   s     rA   r   Groups.append   s0      --KK$ .r@   c                F   > U R                  U5        [        TU ]	  X5        g rV   )r}   rW   __setitem__)ra   iyr\   s      rA   r   Groups.__setitem__  s    A!r@   c                    [        U[        5      (       d  g[        U 5      [        U5      :w  a  g[        [	        U 5      [	        U5      5       H)  u  p#UR                  5       UR                  5       :w  d  M)    g   g)a  
Test Group equality. In normal lists, order matters; here it does not. More like a set.

>>> a = base.Groups()
>>> a.append('red')
>>> a.append('green')
>>> a
['red', 'green']

>>> b = base.Groups()
>>> b.append('green')
>>> a == b
False

>>> b.append('reD')  # case insensitive
>>> a == b
True

>>> a == ['red', 'green']  # need both to be groups
False

>>> c = base.Groups()
>>> c.append('black')
>>> c.append('tuba')
>>> a == c
False
FT)re   r+   lenzipsortedlower)ra   rg   eSelfeOthers       rA   rf   Groups.__eq__  s^    8 %((t9E
" ve}=ME{{}. > r@   )r|   ry   rq   rr   )rg   object)r;   r<   r=   r>   rs   	__slots__r}   r   r   rf   r?   rt   ru   s   @rA   r+   r+      s*    B IB%
"% %r@   r+   c                    [        5       nU /U R                  5       Q HH  n[        US5      (       d  M  UR                  n[	        U[
        5      (       a  U4nU[        U5      -  nMJ     [        U5      $ )z
Get equality attributes for a class.  Cached.

>>> base._getEqualityAttributes(base.Music21Object)
frozenset({'duration'})
>>> 'location' in base._getEqualityAttributes(bar.Barline)
True
>>> 'pitch' in base._getEqualityAttributes(bar.Barline)
False

equalityAttributes)setmrohasattrr   re   ry   	frozenset)rZ   r   klasskas       rA   _getEqualityAttributesr   6  sp      "	"5.//))B"c""U#b') # '((r@   c            
        ^  \ rS rSr% SrSrS\S'   Sr\r	S\S'   S	r
S
\S'   / rS\S'   SSSSS.rS\S'            Sg                 ShS jjrSiS jrSjS jr\SkS j5       r\R$                  SlS j5       rSmS jr SnSS.     SoS jjjrSnSpS jjrSqS  jrSrS! jrSsU 4S" jjr\StS# j5       r\SuS$ j5       r\R$                  SvS% j5       r\StS& j5       r\SwS' j5       r\R$                  SxS( j5       r\SyS) j5       r\R$                  SzS* j5       r\S{S+ j5       r\R$                  S|S, j5       rS}S- jr\ SS..     S~S/ jj5       r!\ SS..     SS0 jj5       r!SS..     SS1 jjr!    SS2 jr"    SS3 jr# Sn   SS4 jjr$SS}S6 jjr%SS}S7 jjr&\ \'RP                  SS5SS8.   SS9 jj5       r)\ \'RP                  SS5SS8.   SS: jj5       r)\'RP                  SS5SS8.     SS; jjr)\ SSSSSS5SS<.       SS= jj5       r*\ SSSSSSS5SS>.       SS? jj5       r*SSSSSSS5SS>.       SS@ jjr*SA r+ SnSSB. SSC jjjr, SnSSB. SSD jjjr-SE r.SSF jr/\" \.\/SGSH9r0\SySI j5       r1\1R$                  SzSJ j5       r1  S     SSK jjr2\SSL j5       r3\3R$                  SSM j5       r3SnSN jr4SO r5SP r6\" \5\6SQSH9r7  S     SSR jjr8SS r9ST r:SSU jr;S5SSV.SW jr<S5S5SSX. SSY jjr=  S   SSZ jjr>SS[ jr?\SS\ j5       r@SSS] jjrASS^ jrB\SS_ j5       rC\SsS` j5       rD\SSa j5       rE\SSb j5       rFSSc jrGSSd jrH\" \G\HSeSH9rISfrJU =rK$ )r,   iW  a  
Music21Object is the base class for all elements that can go into Streams.
Notes, Clefs, TimeSignatures are all sublcasses of Music21Object.  Durations
and Pitches (which need to be attached to Notes, etc.) are not.

All music21 objects have these pieces of information:

1.  id: identification string unique to the object's container (optional).
    Defaults to the `id()` of the element.
2.  groups: a :class:`~music21.base.Groups` object: which is a
    list of strings identifying internal sub-collections
    (voices, parts, selections) to which this element belongs
3.  duration: :class:`~music21.duration.Duration` object representing the length of the object
4.  activeSite: a reference to the currently active :class:`~music21.stream.Stream` or None
5.  offset: a floating point or Fraction value, generally in quarter lengths,
    specifying the position of the object in a site.
6.  priority: int representing the position of an object among all
    objects at the same offset.
7.  sites: a :class:`~music21.base.Sites` object that stores all
    the Streams and Contexts that an
    object is in.
8.  derivation: a :class:`~music21.derivation.Derivation` object, or None, that shows
    where the object came from.
9.  style: a :class:`~music21.style.Style` object, that contains Style information
    automatically created if it doesn't exist, so check `.hasStyleInformation` first
    if that is not desired.
10. editorial: a :class:`~music21.editorial.Editorial` object

Each of these may be passed in as a named keyword to any music21 object.

Some of these may be intercepted by the subclassing object (e.g., duration
within Note)

**Equality**

For historical reasons, music21 uses a different idea of object equality
for Music21Objects than recommended by modern Python standards.

Two Music21Objects are equal if they are the same class and same duration.

Their offset, activeSite, id, and groups do not matter for equality.

Since these two objects are therefore not interchangable, they do not have
the same hash value.

>>> obj1 = base.Music21Object(id='obj1')
>>> obj2 = base.Music21Object(id='obj2')
>>> obj1 == obj2
True
>>> hash(obj1) == hash(obj2)
False

This has the stange side effect that structures that use equality to
report containment (such as lists and tuples) will report differently from
structures that use hash values to report containment (such as dicts and sets):

>>> obj1 in [obj2]
True
>>> obj1 in {obj2}
False

Subclasses need to apply stricter criteria for equality, like Barline does here
with `.location`

>>> bar1 = bar.Barline('double', 'left')
>>> bar2 = bar.Barline('double', 'right')
>>> bar1 == bar2
False
>>> bar2.location = 'left'
>>> bar1 == bar2
True
>>> bar1.duration.type = 'whole'  # Buh?
>>> bar1 == bar2
False

In general, a subclass of Music21Object must match all super-class criteria for
equality before they can be considered equal themselves.  However, there are some
exceptions.  For instance, RomanNumeral objects with the same figure and key are
equal even if their notes are in different octaves or have different doublings.

Developers creating their own Music21Object subclasses should add a class attribute
`equalityAttributes = ('one', 'two')`.  (Remember that as a tuple of strings, if there
is only one string, don't forget the trailing comma: `('only',)`.

>>> class CarolineShawBreathMark(base.Music21Object):
...     equalityAttributes = ('direction',)
...     def __init__(self, direction, speed):
...         super().__init__(self)
...         self.direction = direction
...         self.speed = speed
>>> bm1 = CarolineShawBreathMark('in', 'fast')
>>> bm2 = CarolineShawBreathMark('out', 'fast')
>>> bm1 == bm2
False

"speed" is not in the equalityAttributes so it can differ while objects are still
equal.

>>> bm3 = CarolineShawBreathMark('in', 'slow')
>>> bm1 == bm3
True
   int | floatclassSortOrderFztype[Style]_styleClass)durationtuple[str, ...]r   z	list[str]
_DOC_ORDERzAn instance of a :class:`~music21.base.Groups`
            object which describes
            arbitrary `Groups` that this object belongs to.zka :class:`~music21.sites.Sites` object that stores
            references to Streams that hold this object.zmBoolean value for quickly identifying
            :class:`~music21.stream.Stream` objects (False by default).aQ  Property which returns an number (int or otherwise)
            depending on the class of the Music21Object that
            represents a priority for an object based on its class alone --
            used as a tie for stream sorting in case two objects have the
            same offset and priority.  Lower numbers are sorted to the left
            of higher numbers.  For instance, Clef, KeySignature, TimeSignature
            all come (in that order) before Note.

            All undefined classes have classSortOrder of 20 -- same as note.Note

            >>> m21o = base.Music21Object()
            >>> m21o.classSortOrder
            20

            >>> tc = clef.TrebleClef()
            >>> tc.classSortOrder
            0

            >>> ks = key.KeySignature(3)
            >>> ks.classSortOrder
            2


            New classes can define their own default classSortOrder

            >>> class ExampleClass(base.Music21Object):
            ...     classSortOrder = 5
            ...
            >>> ec1 = ExampleClass()
            >>> ec1.classSortOrder
            5
            )groupssitesisStreamr   dict[str, str]	_DOC_ATTRN        c
                4   Xl         S U l        Xl        S U l        S U l        X`l        S U l        X@l        Ub  Xl        SU l	        0 U l
        U=(       d
    [        5       U l        U=(       d
    [        5       U l        Ub  XPl        U	b  XR                   l        g g )Nr   )_id_activeSite_naiveOffset_activeSiteStoredOffset_derivation_style
_editorial	_durationclient	_priority_cacher+   r   r   r   
activeSiter   quarterLength)ra   rk   r   r   r   r   style	editorialrJ   r   keywordss              rA   rb   Music21Object.__init__  s     "$EI&,
 GK$ -1"'*. )1"O )+(%eg
 !(O$*7MM' %r@   c                    [         R                  " [        U R                  5      n[	        X5      (       d  g[        U5       H'  n[        X[        5      [        X[        5      :w  d  M'    g   g)z;
Define equality for Music21Objects.  See main class docs.
FT)	tcasttyper\   re   r   getattr_EQUALITY_SENTINEL_SELF_EQUALITY_SENTINEL_OTHER)ra   rg   rZ   attrs       rA   rf   Music21Object.__eq__'  sY     ffT4>>*%%%*3/D$;<u,DEF 0 r@   c                    [        U 5      S-	  $ )z'
Restore hashing, but only on id(self)
   )rk   ra   s    rA   rj   Music21Object.__hash__5  s     $x1}r@   c                `    U R                   b  U R                   $ [        R                  " U 5      $ )a  
A unique identification string or int; not to be confused with Python's
built-in `id()` method. However, if not set, will return
Python's `id()` number.

"Unique" is intended with respect to the stream hierarchy one is likely
to query with :meth:`~music21.stream.Stream.getElementById`. For
instance, the `.id` of a Voice should be unique in any single Measure,
but the id's may reset from measure to measure across a Part.
)r   builtinsrk   r   s    rA   rk   Music21Object.id;  s&     8888O{{4  r@   c                    [        U[        5      (       a4  U[        R                  :  a   SnUSU 3-  n[        R
                  " U5        Xl        g )Nz;Setting an ID that could be mistaken for a memory location zis discouraged: got )re   intr   #minIdNumberToConsiderMemoryLocationr3   warnr   )ra   new_idmsgs      rA   rk   r   K  sD    fc""v0\0\'\OC)&22CMM#r@   c                    UR                   [        U5      :w  a  UR                   U l         [        R                  " UR                  5      U l        g)ab  
Merge all elementary, static attributes. Namely,
`id` and `groups` attributes from another music21 object.
Can be useful for copy-like operations.

>>> m1 = base.Music21Object()
>>> m2 = base.Music21Object()
>>> m1.id = 'music21Object1'
>>> m1.groups.append('group1')
>>> m2.mergeAttributes(m1)
>>> m2.id
'music21Object1'
>>> 'group1' in m2.groups
True
N)rk   copydeepcopyr   )ra   rg   s     rA   mergeAttributesMusic21Object.mergeAttributesS  s3      88r%y hhDGmmELL1r@   ignoreAttributesc               d   1 SknU R                   (       d  UR                  S5        Uc  UnOX#-  n[        R                  " XUS9n[	        US0 5        [	        US[        5       5        SU;   a  [        5       Ul         [        US9nXl        SUl	        [	        USU5        UR                  5         U$ )	ai  
Subclassable __deepcopy__ helper so that the same attributes
do not need to be called for each Music21Object subclass.

ignoreAttributes is a set of attributes not to copy via
the default deepcopy style. More can be passed to it.  But calling
functions are responsible

* Changed in v9: removeFromIgnore removed;
  never used and this is performance critical.
>   r   _sitesr   r   r   r   r   r   r   __deepcopy__r   )r   addr
   defaultDeepcopysetattrr   r+   r   originmethodpurgeOrphans)ra   memor   defaultIgnoreSetnewnewDerivations         rA   _deepcopySubclassable#Music21Object._deepcopySubclassableg  s     N{{  * #//B$$TBRSXr"Xuw'''CJ ##.#-]M2 	
r@   c                $    U R                  U5      $ )a  
Helper method to copy.py's deepcopy function.  Call it from there.

memo=None is the default as specified in copy.py

Problem: if an attribute is defined with an underscore (_priority) but
is also made available through a property (e.g. priority)  using dir(self)
results in the copy happening twice. Thus, __dict__.keys() is used.

>>> from copy import deepcopy
>>> n = note.Note('A')
>>> n.offset = 1.0
>>> n.groups.append('flute')
>>> n.groups
['flute']

>>> idN = n.id
>>> idN > 10000  # pointer
True

>>> b = deepcopy(n)
>>> b.offset = 2.0

>>> n is b
False
>>> b.id != n.id
True
>>> n.pitch.accidental = '-'
>>> b.name
'A'
>>> n.offset
1.0
>>> b.offset
2.0
>>> n.groups[0] = 'bassoon'
>>> ('flute' in n.groups, 'flute' in b.groups)
(False, True)
)r   )ra   r   s     rA   r   Music21Object.__deepcopy__  s    N ))$//r@   c                N    U R                   R                  5       nS US'   S US'   U$ )Nr   r   )__dict__r   ra   states     rA   __getstate__Music21Object.__getstate__  s-    ""$#m#mr@   c                2    [         R                  U SU5        g )Nr   )r   __setattr__r   s     rA   __setstate__Music21Object.__setstate__  s    4U3r@   c                   > [        U S5      (       a  U R                  [        U 5      :X  a  [        TU ]  5       $ U R                  n [	        [        U5      5      nSU 3$ ! [        [        4 a     Nf = f)z
If `x.id` is not the same as `id(x)`, then that id is used instead:

>>> b = base.Music21Object()
>>> b._reprInternal()
'object at 0x129a903b1'
>>> b.id = 'hi'
>>> b._reprInternal()
'id=hi'
rk   id=)r   rk   rW   _reprInternalhexr   
ValueError	TypeError)ra   reprIdr\   s     rA   r   Music21Object._reprInternal  sr     tT""dggD&97(**	V%F VH~ I& 		s   A   A32A3c                    U R                   SL$ )a  
Returns True if there is a :class:`~music21.editorial.Editorial` object
already associated with this object, False otherwise.

Calling .editorial on an object will always create a new
Editorial object, so even though a new Editorial object isn't too expensive
to create, this property helps to prevent creating new Editorial objects
more than is necessary.

>>> mObj = base.Music21Object()
>>> mObj.hasEditorialInformation
False
>>> mObj.editorial
<music21.editorial.Editorial {}>
>>> mObj.hasEditorialInformation
True
Nr   r   s    rA   hasEditorialInformation%Music21Object.hasEditorialInformation  s    ( OOt+,r@   c                R    U R                   c  [        5       U l         U R                   $ )a  
a :class:`~music21.editorial.Editorial` object that stores editorial information
(comments, footnotes, harmonic information, ficta).

Created automatically as needed:

>>> n = note.Note('C4')
>>> n.editorial
<music21.editorial.Editorial {}>
>>> n.editorial.ficta = pitch.Accidental('sharp')
>>> n.editorial.ficta
<music21.pitch.Accidental sharp>
>>> n.editorial
<music21.editorial.Editorial {'ficta': <music21.pitch.Accidental sharp>}>
)r   r   r   s    rA   r   Music21Object.editorial  s!    * ??"'kDOr@   c                    Xl         g rV   r   )ra   eds     rA   r   r    s    r@   c                    U R                   SL$ )a  
Returns True if there is a :class:`~music21.style.Style` object
already associated with this object, False otherwise.

Calling .style on an object will always create a new
Style object, so even though a new Style object isn't too expensive
to create, this property helps to prevent creating new Styles more than
necessary.

>>> mObj = base.Music21Object()
>>> mObj.hasStyleInformation
False
>>> mObj.style
<music21.style.Style object at 0x10b0a2080>
>>> mObj.hasStyleInformation
True
Nr   r   s    rA   hasStyleInformation!Music21Object.hasStyleInformation  s    ( KK4'(r@   c                    U R                   (       d  U R                  nU" 5       U l        U R                  c   eU R                  $ )a*  
Returns (or Creates and then Returns) the Style object
associated with this object, or sets a new
style object.  Different classes might use
different Style objects because they might have different
style needs (such as text formatting or bezier positioning)

Eventually will also query the groups to see if they have
any styles associated with them.

>>> n = note.Note()
>>> st = n.style
>>> st
<music21.style.NoteStyle object at 0x10ba96208>
>>> st.absoluteX = 20.0
>>> st.absoluteX
20.0
>>> n.style = style.Style()
>>> n.style.absoluteX is None
True
)r  r   r   )ra   
StyleClasss     rA   r   Music21Object.style'  s;    0 ''))J$,DK{{&&&{{r@   c                    Xl         g rV   r  )ra   newStyles     rA   r   r  E  s    r@   c                .    U R                   R                  $ )a  
Set or Return the Duration as represented in Quarter Length, possibly as a fraction.

Same as setting `.duration.quarterLength`.

>>> n = note.Note()
>>> n.quarterLength = 2.0
>>> n.quarterLength
2.0
>>> n.quarterLength = 1/3
>>> n.quarterLength
Fraction(1, 3)
r   r   r   s    rA   r   Music21Object.quarterLengthK  s     }}***r@   c                $    XR                   l        g rV   r  r{   s     rA   r   r  \  s    &+#r@   c                P    U R                   c  [        U S9U l         U R                   $ )a  
Return the :class:`~music21.derivation.Derivation` object for this element.

Or create one if none exists:

>>> n = note.Note()
>>> n.derivation
<Derivation of <music21.note.Note C> from None>

Make a copy of n but change the pitch to D to see which is which later:

>>> import copy
>>> n2 = copy.deepcopy(n)
>>> n2.pitch.step = 'D'

Because n2 was originally a copy of n, it has a derivation set to show it.

>>> n2.derivation
<Derivation of <music21.note.Note D> from <music21.note.Note C> via '__deepcopy__'>
>>> n2.derivation.origin is n
True

Note that (for now at least) derivation.origin is NOT a weakref:

>>> del n
>>> n2.derivation
<Derivation of <music21.note.Note D> from <music21.note.Note C> via '__deepcopy__'>
>>> n2.derivation.origin
<music21.note.Note C>
r   )r   r   r   s    rA   
derivationMusic21Object.derivation`  s*    @ #)6Dr@   c                    Xl         g rV   )r   )ra   r   s     rA   r  r    s    (r@   c                    0 U l         g)a  
A number of music21 attributes (especially with Chords and RomanNumerals, etc.)
are expensive to compute and are therefore cached.  Generally speaking
objects are responsible for making sure that their own caches are up to date,
but a power user might want to do something in an unusual way (such as manipulating
private attributes on a Pitch object) and need to be able to clear caches.

That's what this is here for.  If all goes well, you'll never need to call it
unless you're expanding music21's core functionality.

`**keywords` is not used in Music21Object but is included for subclassing.

Look at :func:`~music21.common.decorators.cacheMethod` for the other half of this
utility.

* New in v6: exposes previously hidden functionality.
N)r   ra   r   s     rA   
clearCacheMusic21Object.clearCache  s    ( r@   returnSpecialc                   g rV   r9   ra   rI   r  s      rA   getOffsetBySiteMusic21Object.getOffsetBySite       	r@   c                   g rV   r9   r  s      rA   r  r    r   r@   c               J   Uc  U R                   $  SnU n[        5       nSnUc   UR                  XBS9nUc  M  U$ ! [         a  n[	        SU< S35      UeSnAf[
         a  nXAR                  ;   a+  USL a  [        R                  s SnA$ UR                  s SnA$ U R                  R                  n	U	c  UeU	n[        U5      U;   a  UeUR                  [        U5      5        US-  nUS:  a  Ue SnANSnAff = f! [         a  n
[	        S	U < S
U< 35      U
eSn
A
ff = f)ab  
If this class has been registered in a container such as a Stream,
that container can be provided here, and the offset in that object
can be returned.

>>> n = note.Note('A-4')  # a Music21Object
>>> n.offset = 30
>>> n.getOffsetBySite(None)
30.0

>>> s1 = stream.Stream()
>>> s1.id = 'containingStream'
>>> s1.insert(20 / 3, n)
>>> n.getOffsetBySite(s1)
Fraction(20, 3)
>>> float(n.getOffsetBySite(s1))
6.6666...

n.getOffsetBySite(None) should still return 30.0

>>> n.getOffsetBySite(None)
30.0

If the Stream does not contain the element and the element is not derived from
an element that does, then a SitesException is raised:

>>> s2 = stream.Stream()
>>> s2.id = 'notContainingStream'
>>> n.getOffsetBySite(s2)
Traceback (most recent call last):
music21.sites.SitesException: an entry for this object <music21.note.Note A-> is not
      stored in stream <music21.stream.Stream notContainingStream>

Consider this use of derivations:

>>> import copy
>>> nCopy = copy.deepcopy(n)
>>> nCopy.derivation
<Derivation of <music21.note.Note A-> from <music21.note.Note A-> via '__deepcopy__'>
>>> nCopy.getOffsetBySite(s1)
Fraction(20, 3)

nCopy can still find the offset of `n` in `s1`!
This is the primary difference between element.getOffsetBySite(stream)
and stream.elementOffset(element)

>>> s1.elementOffset(nCopy)
Traceback (most recent call last):
music21.sites.SitesException: an entry for this object ... is not
    stored in stream <music21.stream.Stream containingStream>

If the object is stored at the end of the Stream, then the highest time
is usually returned:

>>> s3 = stream.Stream()
>>> n3 = note.Note(type='whole')
>>> s3.append(n3)
>>> rb = bar.Barline()
>>> s3.storeAtEnd(rb)  # s3.rightBarline = rb would do the same
>>> rb.getOffsetBySite(s3)
4.0

However, setting returnSpecial to True will return OffsetSpecial.AT_END

>>> rb.getOffsetBySite(s3, returnSpecial=True)
<OffsetSpecial.AT_END>

Even with returnSpecial normal offsets are still returned as a float or Fraction:

>>> n3.getOffsetBySite(s3, returnSpecial=True)
0.0

* Changed in v7: stringReturns renamed to returnSpecial.
  Returns an OffsetSpecial Enum.
Nd   r  zYou were using z$ as a site, when it is not a Stream.Tr4   r   zan entry for this object z is not stored in stream )r   r   elementOffsetAttributeErrorr   r(   _endElementsr   AT_ENDhighestTimer  r   rk   r   )ra   rI   r  a	tryOrigin
originMemo	maxSearchaeepossiblyNoneTryOriginses              rA   r  r    sO   b <$$$"	A'+IJI) **9*RA )2 H- & ()$1UV (   $5$55(D0#0#7#77#'#3#33,0OO,B,B),4 5I)}
2NN2i=1NI 1} %! &  	 +D83LTHU	ss   C? ; C? C? 
C<AC<##C7C<C? C7C<C? AC72C? 7C<<C? ?
D"	DD"c                z    Ub  UR                  X5        g[        U[        5      (       a  [        U5      nX l        g)a   
Change the offset for a site.  These are equivalent:

    n1.setOffsetBySite(stream1, 20)

and

    stream1.setElementOffset(n1, 20)

Which you choose to use will depend on whether you are iterating over a list
of notes (etc.) or streams.

>>> import music21
>>> aSite = stream.Stream()
>>> aSite.id = 'aSite'
>>> a = music21.Music21Object()
>>> aSite.insert(0, a)
>>> aSite.setElementOffset(a, 20)
>>> a.setOffsetBySite(aSite, 30)
>>> a.getOffsetBySite(aSite)
30.0

And if it isn't in a Stream? Raises an exception and the offset does not change.

>>> b = note.Note('D')
>>> b.setOffsetBySite(aSite, 40)
Traceback (most recent call last):
music21.exceptions21.StreamException: Cannot set the offset for element
    <music21.note.Note D>, not in Stream <music21.stream.Stream aSite>.

>>> b.offset
0.0

Setting offset for `None` changes the "naive offset" of an object:

>>> b.setOffsetBySite(None, 32)
>>> b.offset
32.0
>>> b.activeSite is None
True

Running `setOffsetBySite` also changes the `activeSite` of the object.
N)setElementOffsetre   r   floatr   )ra   rI   r|   s      rA   setOffsetBySiteMusic21Object.setOffsetBySite(  s5    \ !!$.%%%e %r@   c                     U R                  U5      $ ! [         a     Of = fU R                  5        H   nUR                  UL d  M  UR                  s  $    [        SU  SU 35      e)a  
For an element which may not be in site, but might be in a Stream in site (or further
in streams), find the cumulative offset of the element in that site.

>>> s = stream.Score(id='mainScore')
>>> p = stream.Part()
>>> m = stream.Measure()
>>> n = note.Note()
>>> m.insert(5.0, n)
>>> p.insert(10.0, m)
>>> s.insert(0.0, p)
>>> n.getOffsetInHierarchy(s)
15.0

If no hierarchy beginning with site contains the element
and the element is not derived from
an element that does, then a SitesException is raised:

>>> s2 = stream.Score(id='otherScore')
>>> n.getOffsetInHierarchy(s2)
Traceback (most recent call last):
music21.sites.SitesException: Element <music21.note.Note C>
    is not in hierarchy of <music21.stream.Score otherScore>

But if the element is derived from an element in
a hierarchy then it can get the offset:

>>> n2 = n.transpose('P5')
>>> n2.derivation.origin is n
True
>>> n2.derivation.method
'transpose'
>>> n2.getOffsetInHierarchy(s)
15.0

There is no corresponding `.setOffsetInHierarchy()`
since it's unclear what that would mean.

See also :meth:`music21.stream.iterator.RecursiveIterator.currentHierarchyOffset`
for a method that is about 10x faster when running through a recursed stream.

* New in v3.

OMIT_FROM_DOCS

Timing: 113microseconds for a search vs 1 microsecond for getOffsetBySite
vs 0.4 for elementOffset.  Hence the short-circuit for easy looking below.

TODO: If timing permits, replace .flatten() w/ and w/o retainContainers with this routine.

Currently not possible; for instance, if b = bwv66.6

%timeit b = corpus.parse('bwv66.6') -- 24.8ms
%timeit b = corpus.parse('bwv66.6'); b.flatten() -- 42.9ms
%timeit b = corpus.parse('bwv66.6'); b.recurse().stream() -- 83.1ms
zElement z is not in hierarchy of )r  r   contextSitesrI   rJ   )ra   rI   css      rA   getOffsetInHierarchy"Music21Object.getOffsetInHierarchy]  sp    x	''-- 		
 ##%Bww$yy  & xv-EdVLMMs    
  c                p   U R                   R                  S5      n/ nUb  [        R                  " U5      (       d  U/nU Hh  nUc  M  Uc  UR	                  UR
                  5        M(  U H:  nXTR
                  R                  ;   d  M  UR	                  UR
                  5          Mf     Mj     [        US S9$ )a  
Return a list of all :class:`~music21.spanner.Spanner` objects
(or Spanner subclasses) that contain
this element. This method provides a way for
objects to be aware of what Spanners they
reside in. Note that Spanners are not Streams
but specialized Music21Objects that use a
Stream subclass, SpannerStorage, internally to keep track
of the elements that are spanned.

>>> c = note.Note('C4')
>>> d = note.Note('D4')
>>> slur1 = spanner.Slur(c, d)
>>> c.getSpannerSites() == [slur1]
True

Note that not all Spanners are in the spanner module. They
tend to reside in modules closer to their musical function:

>>> cresc = dynamics.Crescendo(d, c)

The order that Spanners are returned is by sortTuple.  For spanners
created the same way and in the same order, the order returned will
be consistent:

>>> d.getSpannerSites() == [slur1, cresc]
True

Optionally a class name or list of class names (as Classes or strings)
can be specified and only Spanners of that class will be returned

>>> dim = dynamics.Diminuendo(c, d)
>>> d.getSpannerSites(dynamics.Diminuendo) == [dim]
True

A larger class name can be used to get all subclasses:

>>> d.getSpannerSites(dynamics.DynamicWedge) == [cresc, dim]
True
>>> d.getSpannerSites(['Slur', 'Diminuendo']) == [slur1, dim]
True

Note that the order of spanners returned from this routine can vary, so
changing to a set is useful for comparisons

>>> set(d.getSpannerSites(['Slur', 'Diminuendo'])) == {dim, slur1}
True


Example: see which pairs of notes are in the same slur.

>>> e = note.Note('E4')
>>> slur2 = spanner.Slur(c, e)

>>> for n in [c, d, e]:
...    nSlurs = n.getSpannerSites(spanner.Slur)
...    for nOther in [c, d, e]:
...        if n is nOther:
...            continue
...        nOtherSlurs = nOther.getSpannerSites(spanner.Slur)
...        for thisSlur in nSlurs:
...            if thisSlur in nOtherSlurs:
...               print(f'{n.name} shares a slur with {nOther.name}')
C shares a slur with D
C shares a slur with E
D shares a slur with C
E shares a slur with C
SpannerStoragec                "    U R                  5       $ rV   )	sortTuple)xs    rA   <lambda>/Music21Object.getSpannerSites.<locals>.<lambda>  s
    !++-r@   )key)r   getSitesByClassr
   
isIterabler   r   classSetr   )ra   spannerClassListfoundpostobjspannerClasss         rA   getSpannerSitesMusic21Object.getSpannerSites  s    N 

**+;<&('$$%566$4#5 C{'CJJ'$4L#zz':'::CJJ/ %5  d 788r@   Tc                   / nU R                   R                  SS9 H~  nUR                  (       d  M  X;  d  M  U(       a@  SUR                  ;  a.  SUR                  ;  a  UR	                  [        U5      5        M`  Mb  Md  UR	                  [        U5      5        M     U HU  nU R                   R                  U5        U R                  5       nUc  M3  [        U5      U:X  d  MD  U R                  S5        MW     g)a  
A Music21Object may, due to deep copying or other reasons,
have a site (with an offset) which
no longer contains the Music21Object. These lingering sites
are called orphans. This method gets rid of them.

The `excludeStorageStreams` are SpannerStorage and VariantStorage.
TexcludeNoner<  VariantStorageN)	r   
yieldSitesr   classesr   rk   
removeById_getActiveSite_setActiveSite)ra   excludeStorageStreamsorphanssr   ps         rA   r   Music21Object.purgeOrphans   s      &&4&8A zzzdm((		9 0		 Ar!u- !B :
 NN2a5) 9 AJJ!!!$##%A}A!##D) r@   c                6    U R                   R                  US9  g)zE
Remove references to all locations in objects that no longer exist.
)rescanIsDeadN)r   purgeLocations)ra   r\  s     rA   r]  Music21Object.purgeLocations!  s     	

!!|!<r@   )getElementMethodsortByCreationTimefollowDerivationpriorityTargetOnlyc                   g rV   r9   ra   	classNamer_  r`  ra  rb  s         rA   getContextByClassMusic21Object.getContextByClass,       	r@   c                   g rV   r9   rd  s         rA   rf  rg  8  rh  r@   c               r  ^ ^^^^^ [         R                  [         R                  [         R                  [         R                  /m[         R
                  [         R                  [         R                  [         R                  [         R                  /m[         R                  [         R                  [         R                  [         R                  [         R                  [         R                  /m[         R                  [         R                  [         R                  [         R                  /n[         R                  [         R                  /nUUUU4S jnSUUUU 4S jjn	T[         ;  a  [        ST 35      eU(       a  U(       a  [        S5      eTU;   a  TT R                  ;   a  T $ T R                  SUUUS9 H  u  pnUS;   a.  U" U
SUS	9nUb#  U	" X5      (       a   U
R                  U5        Us  $ US:w  d  MB  TT;   a-  T(       a  TU
R                  ;   a  TU;   a  T U
L a  O
TU;  a  U
s  $ U" U
SUS	9nUb#  U	" X5      (       a   U
R                  U5        Us  $ TT;   d  M  T(       a  TU
R                  ;   d  M  TU;   a  T U
L a  M  U
s  $    g
! [         a     Us  $ f = f! [         a     Us  $ f = f)aO  
A very powerful method in music21 of fundamental importance: Returns
the element matching the className that is closest to this element in
its current hierarchy (or the hierarchy of the derivation origin unless
`followDerivation` is False).  For instance, take this stream of changing time
signatures:

>>> p = converter.parse('tinynotation: 3/4 C4 D E 2/4 F G A B 1/4 c')
>>> p
<music21.stream.Part 0x104ce64e0>

>>> p.show('t')
{0.0} <music21.stream.Measure 1 offset=0.0>
    {0.0} <music21.clef.BassClef>
    {0.0} <music21.meter.TimeSignature 3/4>
    {0.0} <music21.note.Note C>
    {1.0} <music21.note.Note D>
    {2.0} <music21.note.Note E>
{3.0} <music21.stream.Measure 2 offset=3.0>
    {0.0} <music21.meter.TimeSignature 2/4>
    {0.0} <music21.note.Note F>
    {1.0} <music21.note.Note G>
{5.0} <music21.stream.Measure 3 offset=5.0>
    {0.0} <music21.note.Note A>
    {1.0} <music21.note.Note B>
{7.0} <music21.stream.Measure 4 offset=7.0>
    {0.0} <music21.meter.TimeSignature 1/4>
    {0.0} <music21.note.Note C>
    {1.0} <music21.bar.Barline type=final>

Let's get the last two notes of the piece, the B and high c:

>>> m4 = p.measure(4)
>>> c = m4.notes.first()
>>> c
<music21.note.Note C>

>>> m3 = p.measure(3)
>>> b = m3.notes.last()
>>> b
<music21.note.Note B>

Now when we run `getContextByClass(meter.TimeSignature)` on c, we get a
time signature of 1/4.

>>> c.getContextByClass(meter.TimeSignature)
<music21.meter.TimeSignature 1/4>

Doing what we just did wouldn't be hard to do with other methods,
though `getContextByClass` makes it easier.  But the time signature
context for b would be much harder to get without this method, since in
order to do it, it searches backwards within the measure, finds that
there's nothing there.  It goes to the previous measure and searches
inside that one from the end backwards until it gets the proper
TimeSignature of 2/4:

>>> b.getContextByClass(meter.TimeSignature)
<music21.meter.TimeSignature 2/4>

For backwards compatibility you can also pass in a string of the
class name:

>>> b.getContextByClass('TimeSignature')
<music21.meter.TimeSignature 2/4>

But if you use Python typing or a typing-aware IDE, then the first call
(with class name) will signal that it is returning a TimeSignature object
and allow for error detection, autocomplete, etc.  The latter call
(with string) will only know that some Music21Object was returned.

The method is smart enough to stop when it gets to the beginning of the
part.  This is all you need to know for most uses.  The rest of the
docs are for advanced uses:

The method searches Sites and also associated objects to find a
matching class. Returns `None` if no match is found.

A reference to the caller is required to find the offset of the object
of the caller.

The caller may be a Sites reference from a lower-level object.  If so,
we can access the location of that lower-level object. However, if we
need a flat representation, the caller needs to be the source Stream,
not its Sites reference.

The `getElementMethod` is an enum value (new in v7) from
:class:`~music21.common.enums.ElementSearch` that selects which
Stream method is used to get elements for searching. (The historical form
of supplying one of the following values as a string is also supported.)

>>> from music21.common.enums import ElementSearch
>>> [x for x in ElementSearch]
[<ElementSearch.BEFORE>,
 <ElementSearch.AFTER>,
 <ElementSearch.AT_OR_BEFORE>,
 <ElementSearch.AT_OR_AFTER>,
 <ElementSearch.BEFORE_OFFSET>,
 <ElementSearch.AFTER_OFFSET>,
 <ElementSearch.AT_OR_BEFORE_OFFSET>,
 <ElementSearch.AT_OR_AFTER_OFFSET>,
 <ElementSearch.BEFORE_NOT_SELF>,
 <ElementSearch.AFTER_NOT_SELF>,
 <ElementSearch.ALL>]

The "after" do forward contexts -- looking ahead.

Demonstrations of these keywords:

Because `b` is a `Note`, `.getContextByClass(note.Note)` will only find itself:

>>> b.getContextByClass(note.Note) is b
True

To get the previous `Note`, use `getElementMethod=ElementSearch.BEFORE`:

>>> a = b.getContextByClass(note.Note, getElementMethod=ElementSearch.BEFORE)
>>> a
<music21.note.Note A>

This is similar to `.previous(note.Note)`, though that method is a bit more
sophisticated:

>>> b.previous(note.Note)
<music21.note.Note A>

To get the following `Note` use `getElementMethod=ElementSearch.AFTER`:

>>> c = b.getContextByClass(note.Note, getElementMethod=ElementSearch.AFTER)
>>> c
<music21.note.Note C>

This is similar to `.next(note.Note)`, though, again, that method is a bit more
sophisticated:

>>> b.next(note.Note)
<music21.note.Note C>

A Stream might contain several elements at the same offset, leading to
potentially surprising results where searching by `ElementSearch.AT_OR_BEFORE`
does not find an element that is technically the NEXT node but still at 0.0:

>>> s = stream.Stream()
>>> s.insert(0, clef.BassClef())
>>> s.next()
<music21.clef.BassClef>
>>> s.getContextByClass(clef.Clef) is None
True
>>> s.getContextByClass(clef.Clef, getElementMethod=ElementSearch.AT_OR_AFTER)
<music21.clef.BassClef>

This can be remedied by explicitly searching by offsets:

>>> s.getContextByClass(clef.Clef, getElementMethod=ElementSearch.AT_OR_BEFORE_OFFSET)
<music21.clef.BassClef>

Or by not limiting the search by temporal position at all:

>>> s.getContextByClass(clef.Clef, getElementMethod=ElementSearch.ALL)
<music21.clef.BassClef>

Notice that if searching for a `Stream` context, the element is not
guaranteed to be in that Stream.  This is obviously true in this case:

>>> p2 = stream.Part()
>>> m = stream.Measure(number=1)
>>> p2.insert(0, m)
>>> n = note.Note('D')
>>> m.insert(2.0, n)
>>> try:
...     n.getContextByClass(stream.Part).elementOffset(n)
... except Music21Exception:
...     print('not there')
not there

But it is less clear with something like this:

>>> import copy
>>> n2 = copy.deepcopy(n)
>>> try:
...     n2.getContextByClass(stream.Measure).elementOffset(n2)
... except Music21Exception:
...     print('not there')
not there

A measure context is being found, but only through the derivation chain.

>>> n2.getContextByClass(stream.Measure)
<music21.stream.Measure 1 offset=0.0>

To prevent this error, use the `followDerivation=False` setting

>>> print(n2.getContextByClass(stream.Measure, followDerivation=False))
None

Or if you want the offset of the element following the derivation chain,
call `getOffsetBySite()` on the object:

>>> n2.getOffsetBySite(n2.getContextByClass(stream.Measure))
2.0


Raises `ValueError` if `getElementMethod` is not a value in `ElementSearch`.

>>> n2.getContextByClass(expressions.TextExpression, getElementMethod='invalid')
Traceback (most recent call last):
ValueError: Invalid getElementMethod: invalid

Raises `ValueError` for incompatible values `followDerivation=True`
and `priorityTargetOnly=True`.

* Changed in v5.7: added followDerivation=False and made
  everything but the class keyword only
* New in v6: added priorityTargetOnly -- see contextSites for description.
* New in v7: added getElementMethod `all` and `ElementSearch` enum.
* Changed in v8: class-based calls return properly typed items.  Putting
  multiple types into className (never documented) is no longer allowed.

OMIT_FROM_DOCS

Testing that this works:

>>> import gc
>>> _ = gc.collect()
>>> for site, positionStart, searchType in b.contextSites(
...                                 returnSortTuples=True,
...                                 sortByCreationTime=False,
...                                 followDerivation=True
...                                 ):
...     print(site, positionStart, searchType)
<music21.stream.Measure 3 offset=5.0> SortTuple(atEnd=0, offset=1.0, ...) elementsFirst
<music21.stream.Part 0x1118cadd8> SortTuple(atEnd=0, offset=6.0, ...) flatten
c                ~  > T	(       d  SOT	4nU R                  XS9nT
T;   aa  T
[        R                  [        R                  4;   a  [        R
                  " UR                  S9nO[        R
                  " UR                  S9nT
T;   a  UR                  U5      nOUR                  U5      nUb  UR                  nU$ g)z
change the site (stream) to a Tree (using caches if possible),
then find the node before (or after) the positionStart and
return the element there or None.

flatten can be True, 'semiFlat', or False.
N)flatten	classListrJ   )asTreer   BEFORE_OFFSETAT_OR_AFTER_OFFSETr   modifyrJ   r   getNodeBeforegetNodeAfterpayload)	checkSiterl  innerPositionStartrm  siteTreecontextNoderu  BEFORE_METHODSOFFSET_METHODSre  r_  s          rA   payloadExtractor9Music21Object.getContextByClass.<locals>.payloadExtractorV  s     %.I<I '''MH>1#(C(C(5(H(H(J J)9)@)@HZHaHa)b&):)A)AI[IbIb)c&>1&445GH&334FG&%--r@   c                   >  TR                  USS9nU R                  USS9nTT;   a  X#:  a  gTT;   a  X#:  a  gg! [         a     gf = f)aV  
Long explanation for a short method.

It is possible for a contextEl to be returned that contradicts the
'Before' or 'After' criterion due to the following:

(I'll take the example of Before; After is much harder
to construct, but possible).

Assume that s is a Score, and tb2 = s.flatten()[1] and tb1 is the previous element
(would be s.flatten()[0]) -- both are at offset 0 in s and are of the same class
(so same sort order and priority) and are thus ordered entirely by insert
order.

in s we have the following.

s.sortTuple   = 0.0 <0.-20.0>  # not inserted
tb1.sortTuple = 0.0 <0.-31.1>
tb2.sortTuple = 0.0 <0.-31.2>

in s.flatten() we have:

s.flatten().sortTuple = 0.0 <0.-20.0>  # not inserted
tb1.sortTuple         = 0.0 <0.-31.3>
tb2.sortTuple         = 0.0 <0.-31.4>

Now tb2 is declared through s.flatten()[1], so its activeSite
is s.flatten().  Calling .previous() finds tb1 in s.flatten().  This is normal.

tb1 calls .previous().  Search of first site finds nothing before tb1,
so .getContextByClass() is ready to return None.  But other sites need to be checked

Search returns to s.  .getContextByClass() asks is there anything before tb1's
sort tuple of 0.0 <0.-31.3> (.3 is the insertIndex) in s?  Yes, it's tb2 at
0.0 <0.-31.2> (because s was created before s.flatten(), the insert indices of objects
in s are lower than the insert indices of objects in s.flatten() (perhaps insert indices
should be eventually made global within the context of a stream, but not global
overall? but that wasn't the solution here).  So we go back to tb2 in s. Then in
theory we should go to tb1 in s, then s, then None.  This would have certain
elements appear twice in a .previous() search, which is not optimal, but wouldn't be
such a huge bug to make this method necessary.

That'd be the only bug that would occur if we did: sf = s.flatten(), tb2 = sf[1]. But
consider the exact phrasing above:  tb2 = s.flatten()[1].
s.flatten() is created for an instant,
it is assigned to tb2's ._activeSite via weakRef, and then tb2's sortTuple is set
via this temporary stream.

Suppose tb2 is from that temp s.flatten()[1].  Then tb1 = tb2.previous() which is found
in s.flatten().  Suppose then that for some reason s._cache['flat'] gets cleaned up
(It was a bug that s._cache was being cleaned by the positioning of notes during
s_flat's setOffset,
but _cache cleanups are allowed to happen at any time,
so it's not a bug that it's being cleaned; assuming that it wouldn't be cleaned
would be the bug) and garbage collection runs.

Now we get tb1.previous() would get tb2 in s. Okay, it's redundant but not a huge deal,
and tb2.previous() gets tb1.  tb1's ._activeSite is still a weakref to s.flatten().
When tb1's getContextByClass() is called, it needs its .sortTuple().  This looks
first at .activeSite.  That is None, so it gets it from .offset which is the .offset
of the last .activeSite (even if it is dead.  A lot of code depends on .offset
still being available if .activeSite dies, so changing that is not an option for now).
So its sortTuple is 0.0 <0.-31.3>. which has a .previous() of tb2 in s, which can
call previous can get tb1, etc. So with terrible timing of cache cleanups and
garbage collecting, it's possible to get an infinite loop.

There may be ways to set activeSite on .getContextByClass() call such that this routine
is not necessary, but I could not find one that was not disruptive for normal
usages.

There are some possible issues that one could raise about "wellFormed".
Suppose for instance, that in one stream (b) we have [tb1, tb2] and
then in another stream context (a), created earlier,
we have [tb0, tb1, tb2].  tb1 is set up with (b) as an activeSite. Finding nothing
previous, it goes to (a) and finds tb2; it then discovers that in (a), tb2 is after
tb1, so it returns None for this context.  One might say, "wait a second, why
isn't tb0 returned? It's going to be skipped." To this, I would answer, the original
context in which .previous() or .getContextByClass() was called was (b). There is
no absolute obligation to find what was previous in a different site context. It is
absolutely fair game to say, "there's nothing prior to tb1".  Then why even
search other streams/sites? Because it's quite common to create a new site
for say a single measure or .getElementsByOffset(), etc., so that when leaving
this extracted section, one wants to see how that fits into a larger stream hierarchy.
T)raiseExceptionOnMissF)r>  r   )checkContextElrv  selfSortTuplecontextSortTupleAFTER_METHODSrz  r_  ra   s       rA   
wellFormed3Music21Object.getContextByClass.<locals>.wellFormeds  sq    j $yt T#1#;#;I\`#;#a   >1m6V !]2}7W ! " 
 s    < 
A	A	zInvalid getElementMethod: z;priorityTargetOnly and followDerivation cannot both be TrueT)returnSortTuplesr`  ra  rb  )elementsOnlyelementsFirstF)rl  rw  Nr  semiFlatrq   bool)r   rp  AFTER_OFFSETAT_OR_BEFORE_OFFSETrq  BEFOREAT_OR_BEFOREBEFORE_NOT_SELFAFTERAT_OR_AFTERAFTER_NOT_SELFr   rE  r7  coreSelfActiveSiter   )ra   re  r_  r`  ra  rb  
AT_METHODSNOT_SELF_METHODSr|  r  rI   positionStart
searchType	contextElr  rz  r{  s   ```           @@@rA   rf  rg  D  s   f ''&&--,,	
   ''&&--))
 &&%%%%,,((
 &&%%--,,	

 ))((

	 	:h	 h	T =09:J9KLMM"2Z[[z)i4==.HK/3/@/@!1-1	 0A 0
+D >>,T5:@MO	 (Z	-H-H//	: %$ ^+$5!* )T]] :'+;;)1AA#,T5?@MO	 (Z	-H-H//	: %$$6!* )T]] :'+;;#[0
d I * $$* * $$s$    J	J&
J#"J#&
J65J6)callerFirstr   offsetAppendr`  priorityTargetra  rb  c                   g rV   r9   )	ra   r  r  r   r  r`  r  ra  rb  s	            rA   r7  Music21Object.contextSites       	r@   )r  r   r  r`  r  r  ra  rb  c                   g rV   r9   )	ra   r  r   r  r`  r  r  ra  rb  s	            rA   r7  r  *  r  r@   c          	   #    #    SSK Jn	  Uc
  [        5       nUc  U nU R                  (       a  X;  a  [        R
                  " SU 5      n
U
R                  n[        R                  SU SU 35        U(       a6  U
R                  5       R                  S[        S5      S	9n[        XU5      v   O[        U
SU5      v   UR                  U
5        Uc  US
L a  U R                  nO[        R                  SU 35        U nU R                   R#                  UUSS9 GH  nX;   a  M  [%        XR&                  5      (       a  M'   U R                  U5      nU(       a  U R)                  U5      nOUR+                  U 5      n[-        UU-   5      nUR                  US9nUR                  nU(       a  [        UUU5      v   O[        UUR0                  U5      v   UR                  U5        [        R                  SU 3SUR3                  5        3-   5        UR5                  UUUR0                  SUS9 Hm  u  nnnU(       a  XLa    O]UR0                  nUR                  US9nX;  d  M6  U(       a  [        UUU5      v   O[        UUU5      v   UR                  U5        Mo     U(       d  GM    O   U(       Ga+  UR6                  R9                  5        GH  n[        R                  SU SU 3-   5        UR5                  SUSSUS9 H  nUR:                  U;   a  M  [        R                  SU S35        [        UR:                  UR0                  R                  US   R0                  U-   S9UR<                  5      nU(       a  Uv   O7[        UR:                  UR0                  R0                  UR<                  5      v   UR                  UR:                  5        M     GM     [        R                  S5        g! [.         a     GM  f = f7f)a"  
A generator that returns a list of namedtuples of sites to search for a context.

Each tuple contains three elements:

.site --  Stream object
.offset -- the offset or position (sortTuple) of this element in that Stream
.recurseType -- the way of searching that should be applied to search for a context.

The recurseType values are all music21.stream.enums.RecurseType:

    * FLATTEN -- flatten the stream and then look from this offset backwards.

    * ELEMENTS_ONLY -- only search the stream's personal
       elements from this offset backwards

    * ELEMENTS_FIRST -- search this stream backwards,
       and then flatten and search backwards

>>> c = corpus.parse('bwv66.6')
>>> c.id = 'bach'
>>> n = c[2][4][2]
>>> n
<music21.note.Note G#>

Returning sortTuples are important for distinguishing the order of multiple sites
at the same offset.

>>> for csTuple in n.contextSites(returnSortTuples=True):
...      yClearer = (csTuple.site, csTuple.offset.shortRepr(), csTuple.recurseType)
...      print(yClearer)
(<music21.stream.Measure 3 offset=9.0>, '0.5 <0.20...>', <RecursionType.ELEMENTS_FIRST>)
(<music21.stream.Part Alto>, '9.5 <0.20...>', <RecursionType.FLATTEN>)
(<music21.stream.Score bach>, '9.5 <0.20...>', <RecursionType.ELEMENTS_ONLY>)

Streams have themselves as the first element in their context sites, at position
zero and classSortOrder negative infinity.

This example shows the context sites for Measure 3 of the
Alto part. We will get the measure object using direct access to
indices to ensure that no other temporary
streams are created; normally, we would do `c.parts['#Alto'].measure(3)`.

>>> m = c.parts['#Alto'].getElementsByClass(stream.Measure)[3]
>>> m
<music21.stream.Measure 3 offset=9.0>

If returnSortTuples is true then ContextSortTuples are returned, where the
second element is a SortTuple:

>>> for csTuple in m.contextSites(returnSortTuples=True):
...     print(csTuple)
ContextSortTuple(site=<music21.stream.Measure 3 offset=9.0>,
                 offset=SortTuple(atEnd=0, offset=0.0, priority=-inf, ...),
                 recurseType=<RecursionType.ELEMENTS_FIRST>)
ContextSortTuple(...)
ContextSortTuple(...)

Because SortTuples are so detailed, we'll use their `shortRepr()` to see the
values, removing the insertIndex because it changes from run to run:

>>> for csTuple in m.contextSites(returnSortTuples=True):
...      yClearer = (csTuple.site, csTuple.offset.shortRepr(), csTuple.recurseType)
...      print(yClearer)
(<music21.stream.Measure 3 offset=9.0>, '0.0 <-inf.-20...>', <RecursionType.ELEMENTS_FIRST>)
(<music21.stream.Part Alto>, '9.0 <0.-20...>', <RecursionType.FLATTEN>)
(<music21.stream.Score bach>, '9.0 <0.-20...>', <RecursionType.ELEMENTS_ONLY>)

Here we make a copy of the earlier measure, and we see that its contextSites
follow the derivationChain from the original measure and still find the Part
and Score of the original Measure 3 (and also the original Measure 3)
even though mCopy is not in any of these objects.

>>> import copy
>>> mCopy = copy.deepcopy(m)
>>> mCopy.number = 3333
>>> for csTuple in mCopy.contextSites():
...      print(csTuple, mCopy in csTuple.site)
ContextTuple(site=<music21.stream.Measure 3333 offset=0.0>,
             offset=0.0,
             recurseType=<RecursionType.ELEMENTS_FIRST>) False
ContextTuple(site=<music21.stream.Measure 3 offset=9.0>,
             offset=0.0,
             recurseType=<RecursionType.ELEMENTS_FIRST>) False
ContextTuple(site=<music21.stream.Part Alto>,
             offset=9.0,
             recurseType=<RecursionType.FLATTEN>) False
ContextTuple(site=<music21.stream.Score bach>,
             offset=9.0,
             recurseType=<RecursionType.ELEMENTS_ONLY>) False

If followDerivation were False, then the Part and Score would not be found.

>>> for csTuple in mCopy.contextSites(followDerivation=False):
...     print(csTuple)
ContextTuple(site=<music21.stream.Measure 3333 offset=0.0>,
             offset=0.0,
             recurseType=<RecursionType.ELEMENTS_FIRST>)

>>> partIterator = c.parts
>>> m3 = partIterator[1].measure(3)
>>> for csTuple in m3.contextSites():
...      print(csTuple)
ContextTuple(site=<music21.stream.Measure 3 offset=9.0>,
             offset=0.0,
             recurseType=<RecursionType.ELEMENTS_FIRST>)
ContextTuple(site=<music21.stream.Part Alto>,
             offset=9.0,
             recurseType=<RecursionType.FLATTEN>)
ContextTuple(site=<music21.stream.Score bach>,
             offset=9.0,
             recurseType=<RecursionType.ELEMENTS_ONLY>)

Sorting order:

>>> p1 = stream.Part()
>>> p1.id = 'p1'
>>> m1 = stream.Measure()
>>> m1.number = 1
>>> n = note.Note()
>>> m1.append(n)
>>> p1.append(m1)
>>> for csTuple in n.contextSites():
...     print(csTuple.site)
<music21.stream.Measure 1 offset=0.0>
<music21.stream.Part p1>

>>> p2 = stream.Part()
>>> p2.id = 'p2'
>>> m2 = stream.Measure()
>>> m2.number = 2
>>> m2.append(n)
>>> p2.append(m2)

The keys could have appeared in any order, but by default
we set priorityTarget to activeSite.  So this is the same as omitting.

>>> for y in n.contextSites(priorityTarget=n.activeSite):
...     print(y[0])
<music21.stream.Measure 2 offset=0.0>
<music21.stream.Part p2>
<music21.stream.Measure 1 offset=0.0>
<music21.stream.Part p1>

We can sort sites by creationTime:

>>> for csTuple in n.contextSites(sortByCreationTime=True):
...     print(csTuple.site)
<music21.stream.Measure 2 offset=0.0>
<music21.stream.Part p2>
<music21.stream.Measure 1 offset=0.0>
<music21.stream.Part p1>

Use `reverse` for oldest first:

>>> for csTuple in n.contextSites(sortByCreationTime='reverse'):
...     print(csTuple.site)
<music21.stream.Measure 1 offset=0.0>
<music21.stream.Part p1>
<music21.stream.Measure 2 offset=0.0>
<music21.stream.Part p2>

Note that by default we search all sites, but you might want to only search
one, for instance:

>>> c = note.Note('C')
>>> m1 = stream.Measure()
>>> m1.append(c)

>>> d = note.Note('D')
>>> m2 = stream.Measure()
>>> m2.append([c, d])

>>> c.activeSite = m1
>>> c.next('Note')  # uses contextSites
<music21.note.Note D>

There is a particular site in which there is a Note after c,
but we want to know if there is one in m1 or its hierarchy, so
we can pass in activeSiteOnly to `.next()` which sets
`priorityTargetOnly=True` for contextSites

>>> print(c.next('Note', activeSiteOnly=True))
None


*  Removed in v3: priorityTarget cannot be set, in order
   to use `.sites.yieldSites()`
*  Changed in v5.5: all arguments are keyword only.
*  Changed in v6: added `priorityTargetOnly=False` to only search in the
   context of the priorityTarget.
*  Changed in v8: `returnSortTuple=True` returns a new ContextSortTuple
r   r#   Nmusic21.stream.StreamzCaller first is z with offsetAppend r   z-inf)rJ   priorityFzsortByCreationTime T)r`  r  rO  rn  zlooking in contextSites for z with position )r  r   r  r  r`  zlooking now in derivedObject, z	Yielding z  from derivedObject contextSitesr4   z%--returning from derivedObject search)music21r$   r   r   r   r   recursionTypeenvironLocal
printDebugr>  rr  r3  rP   rF   r   r   r   rQ  re   r<  r  r$  r   r   rJ   	shortReprr7  r  chainrI   rL   )ra   r  r   r  r`  r  r  ra  rb  r$   
streamSelfr  r  topLevelsiteObjstoffsetInStream	newOffsetpositionInStreaminStreamPos	recurTypeinStreamOffsethypotheticalPositionderivedObjectderivedCsTupleoffsetAdjustedCsTuples                             rA   r7  r  9  s    Z 	#<5DK}}!1VV$;TB
 * 8 8''&{m3F|nUW#$.$8$8$:$A$A"!&v %B %M +:mTT&z3FF$!&8E&A!__N##&9:L9M$NOzz,,@R<J9= - ?G '#8#899^^G,# &*%9%9'%BN%,%:%:4%@N">L#@A	#%99I9#>  $11M&w0@-PP"7,<,C,C]SSHHW##.wi8#$4$>$>$@#ABCD 5<4H4H'-44!%#5 5I 50+y &(*H!,!3!3 (8'>'>n'>'U$'
 (.x9MyYY*8^YOOHHX&152 "!w?z !)!4!4!:!:!<''4&':<.IJK '4&@&@$(!%()-+= 'A '?N &**d2  ++#N#33ST -=&++&--44N1<M<T<T>J=K4 L&22	-4)
 (33*+@+E+E+@+G+G+N+N+@+L+LN N HH^0011'?	 "=< 	 GHQ " s:   D;P>AO4CP"A P'EP4
P>PPPc              #     #    U R                  U5      nUb(  Uv   UR                  U[        R                  S9nUb  M'  gg7f)a@  
Returns a generator that yields elements found by `.getContextByClass` and
then finds the previous contexts for that element.

>>> s = stream.Stream()
>>> s.append(meter.TimeSignature('2/4'))
>>> s.append(note.Note('C'))
>>> s.append(meter.TimeSignature('3/4'))
>>> n = note.Note('D')
>>> s.append(n)


>>> for ts in n.getAllContextsByClass(meter.TimeSignature):
...     print(ts, ts.offset)
<music21.meter.TimeSignature 3/4> 1.0
<music21.meter.TimeSignature 2/4> 0.0

TODO: make it so that it does not skip over multiple matching classes
at the same offset. with sortTuple

Nr_  )rf  r   rp  )ra   re  els      rA   getAllContextsByClass#Music21Object.getAllContextsByClass  sC     , ##I.nH%%i-B]B]%^B ns
   :A A )activeSiteOnlyc                  [        U R                  SUS95      nSnU nU(       a  UR                  U[        R                  U(       + US9nSnU H=  u  pn
XhL d  M  [
        R                  " SU5      nU(       a  US   U La  US   s  $ UnSn  O   U(       a  US-  nM  X`La  U$ US-  nU(       a  M  US:X  a  [        S	5      eg
)aI	  
Get the next element found in the activeSite (or other Sites)
of this Music21Object.

The `className` can be used to specify one or more classes to match.

>>> s = corpus.parse('bwv66.6')
>>> m3 = s.parts[0].measure(3)
>>> m4 = s.parts[0].measure(4)
>>> m3
<music21.stream.Measure 3 offset=9.0>
>>> m3.show('t')
{0.0} <music21.layout.SystemLayout>
{0.0} <music21.note.Note A>
{0.5} <music21.note.Note B>
{1.0} <music21.note.Note G#>
{2.0} <music21.note.Note F#>
{3.0} <music21.note.Note A>
>>> m3.next()
<music21.layout.SystemLayout>
>>> nextM3 = m3.next('Measure')
>>> nextM3 is m4
True

Note that calling next() repeatedly gives the same object.  You'll want to
call next on that object.

>>> m3.next('Measure') is s.parts[0].measure(4)
True
>>> m3.next('Measure') is s.parts[0].measure(4)
True

So do this instead:

>>> o = m3
>>> for i in range(5):
...     print(o)
...     o = o.next('Measure')
<music21.stream.Measure 3 offset=9.0>
<music21.stream.Measure 4 offset=13.0>
<music21.stream.Measure 5 offset=17.0>
<music21.stream.Measure 6 offset=21.0>
<music21.stream.Measure 7 offset=25.0>

We can find the next element given a certain class with the `className`:

>>> n = m3.next('Note')
>>> n
<music21.note.Note A>
>>> n.measureNumber
3
>>> n is m3.notes.first()
True
>>> n.next()
<music21.note.Note B>

Notice though that when we get to the end of the set of measures, something
interesting happens (maybe it shouldn't? don't count on this.): we descend
into the last measure and give its elements instead.

We'll leave `o` where it is (m8 now) to demonstrate what happens, and also
print its Part for more information:

>>> while o is not None:
...     print(o, o.getContextByClass(stream.Part))
...     o = o.next()
<music21.stream.Measure 8 offset=29.0> <music21.stream.Part Soprano>
<music21.note.Note F#> <music21.stream.Part Soprano>
<music21.note.Note F#> <music21.stream.Part Soprano>
<music21.note.Note F#> <music21.stream.Part Soprano>
<music21.stream.Measure 9 offset=33.0> <music21.stream.Part Soprano>
<music21.note.Note F#> <music21.stream.Part Soprano>
<music21.note.Note F#> <music21.stream.Part Soprano>
<music21.note.Note E#> <music21.stream.Part Soprano>
<music21.note.Note F#> <music21.stream.Part Soprano>
<music21.bar.Barline type=final> <music21.stream.Part Soprano>

* Changed in v6: added activeSiteOnly -- see description in `.contextSites()`
T)r  rb  r   re  r_  ra  rb  Fr  r   r4   zMaximum recursion!N)r   r7  rf  r   r  r   r   r(   )ra   re  r  allSiteContexts
maxRecursethisElForNextnextElcallContinuesingleSiteContextunused_positionInContextunused_recurseTypes              rA   nextMusic21Object.next  s    f t00!-  1  
  
"44#!.!=!=%3!3#1	 5 F !LSbO!=O.VV$;VDF&)4"7%ay($*M#'L Tc a
!!OJ3 j6 ?"#788 r@   c                  U R                  U[        R                  U(       + US9nSnU R                  (       a%  Ub"  UR	                  5        H  u  pVnXPL d  M  Sn  O   U(       a  X0La	  U(       d  U$ U R
                  nUc  gUR                  U/SS9n	U	R                  U R                  5       5      n
U
c  Ub  XR                  ;   a  U$ gU
R                  $ )a+  
Get the previous element found in the activeSite or other .sites of this
Music21Object.

The `className` can be used to specify one or more classes to match.

>>> s = corpus.parse('bwv66.6')
>>> m2 = s.parts[0].getElementsByClass(stream.Measure)[2]  # pickup measure
>>> m3 = s.parts[0].getElementsByClass(stream.Measure)[3]
>>> m3
<music21.stream.Measure 3 offset=9.0>
>>> m3prev = m3.previous()
>>> m3prev
<music21.note.Note C#>
>>> m3prev is m2.notes[-1]
True
>>> m3.previous('Measure') is m2
True

We'll iterate backwards from the first note of the second measure of the Alto part.

>>> o = s.parts[1].getElementsByClass(stream.Measure)[2][0]
>>> while o:
...    print(o)
...    o = o.previous()
<music21.note.Note E>
<music21.stream.Measure 2 offset=5.0>
<music21.note.Note E>
<music21.note.Note E>
<music21.note.Note E>
<music21.note.Note F#>
<music21.stream.Measure 1 offset=1.0>
<music21.note.Note E>
<music21.meter.TimeSignature 4/4>
f# minor
<music21.tempo.MetronomeMark Quarter=96 (playback only)>
<music21.clef.TrebleClef>
<music21.stream.Measure 0 offset=0.0>
P2: Alto: Instrument 2
<music21.stream.Part Alto>
<music21.stream.Part Soprano>
<music21.metadata.Metadata object at 0x11116d080>
<music21.stream.Score bach/bwv66.6.mxl>

* Changed in v6: added activeSiteOnly -- see description in `.contextSites()`
r  FNT)rm  rl  )rf  r   r  r   r7  r   ro  rs  r>  rE  ru  )ra   re  r  prevElisInPartr8  unused1unused2activeSro  prevNodes              rA   previousMusic21Object.previous	  s    j '')9F9V9V=K9K;I ( * ==V/(.(;(;(=$W:#H )>
 f(M ooG^^yk5^IF++DNN,<=H$	5E5E(E"N'''r@   c                    [         (       a.  U R                  c  g [        R                  " U R                  5      $ U R                  $ rV   )r   r   r
   unwrapWeakrefr   s    rA   rT  Music21Object._getActiveSitev	  s;    >' ++D,<,<==###r@   c                   Ub   UR                  U 5      nX l        OS U l        [        (       a'  Uc  S U l        g [
        R                  " U5      U l        g Xl        g ! [         a  n[        SSU  SU 3-   5      UeS nAff = f)NzactiveSite cannot be set for zobject z not in the Stream )r$  r   r   r   r   r
   wrapWeakref)ra   rI   storedOffsetr0  s       rA   rU  Music21Object._setActiveSite	  s     #11$7 ,8( ,0D(>|#' #)#5#5d#; #+ " $3v%8?@ s   A 
B'A<<Ba  
        A reference to the most-recent object used to
        contain this object. In most cases, this will be a
        Stream or Stream sub-class. In most cases, an object's
        activeSite attribute is automatically set when the
        object is attached to a Stream.


        >>> n = note.Note('C#4')
        >>> p = stream.Part()
        >>> p.insert(20.0, n)
        >>> n.activeSite is p
        True
        >>> n.offset
        20.0

        >>> m = stream.Measure()
        >>> m.insert(10.0, n)
        >>> n.activeSite is m
        True
        >>> n.offset
        10.0
        >>> n.activeSite = p
        >>> n.offset
        20.0
        )docc                   U R                   nUb8  U R                  nUc  U R                  =(       d    S$  UR                  U 5      nU$ U R                  nU$ ! [         a,    [
        R                  S5        SU l        U R                  n U$ f = f)a  
The offset property sets or returns the position of this object
as a float or fractions.Fraction value
(generally in `quarterLengths`), depending on what is representable.

Offsets are measured from the start of the object's `activeSite`,
that is, the most recently referenced `Stream` or `Stream` subclass such
as `Part`, `Measure`, or `Voice`.  It is a simpler
way of calling `o.getOffsetBySite(o.activeSite, returnType='rational')`.

If we put a `Note` into a `Stream`, we will see the activeSite changes.

>>> import fractions
>>> n1 = note.Note('D#3')
>>> n1.activeSite is None
True

>>> m1 = stream.Measure()
>>> m1.number = 4
>>> m1.insert(10.0, n1)
>>> n1.offset
10.0
>>> n1.activeSite
<music21.stream.Measure 4 offset=0.0>

>>> n1.activeSite is m1
True

The most recently referenced `Stream` becomes an object's `activeSite` and
thus the place where `.offset` looks to find its number.

>>> m2 = stream.Measure()
>>> m2.insert(3/5, n1)
>>> m2.number = 5
>>> n1.offset
Fraction(3, 5)
>>> n1.activeSite is m2
True

Notice though that `.offset` depends on the `.activeSite` which is the most
recently accessed/referenced Stream.

Here we will iterate over the `elements` in `m1` and we
will see that the `.offset` of `n1` now is its offset in
`m1` even though we haven't done anything directly to `n1`.
Simply iterating over a site is enough to change the `.activeSite`
of its elements:

>>> for element in m1:
...     pass
>>> n1.offset
10.0

The property can also set the offset for the object if no
container has been set:

>>> n1 = note.Note()
>>> n1.id = 'hi'
>>> n1.offset = 20/3
>>> n1.offset
Fraction(20, 3)
>>> float(n1.offset)
6.666...

>>> s1 = stream.Stream()
>>> s1.append(n1)
>>> n1.offset
0.0
>>> s2 = stream.Stream()
>>> s2.insert(30.5, n1)
>>> n1.offset
30.5

After calling `getElementById` on `s1`, the
returned element's `offset` will be its offset in `s1`.

>>> n2 = s1.getElementById('hi')
>>> n2 is n1
True
>>> n2.offset
0.0

Iterating over the elements in a Stream will
make its `offset` be the offset in iterated
Stream.

>>> for thisElement in s2:
...     thisElement.offset
30.5

When in doubt, use `.getOffsetBySite(streamObj)`
which is safer or streamObj.elementOffset(self) which is 3x faster.

* Changed in v8: using a Duration object as an offset is not allowed.
Nr   zENot in Stream: changing activeSite to None and returning _naiveOffset)r   r   r   r$  r   r  r  r   )ra   activeSiteWeakRefr   os       rA   rJ   Music21Object.offset	  s    R !,,(J! 33:s:&,,T2  !!A " &''[]"&%% &s   A 2BBc                     [        U5      nU R                  b  U R                  R                  X5        g X l        g ! [         a    Un N>f = frV   )r   r   r   r2  r   )ra   r|   rJ   s      rA   rJ   r  :
  sJ    	E]F ??&OO,,T: &  	F	s   = AAc                   USL a  U R                   nOUnUc  U R                  nO UR                  U SS9nU[
        R                  :X  a  SnSnO[        R                  " [        U5      nSnU R                  (       d  U R                  R                  (       d  SOSnU R                  R                  [        U5      5      (       a-  U R                  R                   [        U5         R"                  nOFU R                   b7  U R                  R                   [        U R                   5         R"                  nOSn[%        XeU R&                  U R(                  Xx5      $ ! [         a    U(       a  e U R                  n GNEf = f)a  
Returns a collections.namedtuple called SortTuple(atEnd, offset, priority, classSortOrder,
isNotGrace, insertIndex)
which contains the six elements necessary to determine the sort order of any set of
objects in a Stream.

1) atEnd = {0, 1}; Elements specified to always stay at
the end of a stream (``stream.storeAtEnd``)
sort after normal elements.

2) offset = float; Offset (with respect to the active site) is the next and most
important parameter in determining the order of elements in a stream (the note on beat 1
has offset 0.0, while the note on beat 2 might have offset 1.0).

3) priority = int; Priority is a
user-specified property (default 0) that can set the order of
elements which have the same
offset (for instance, two Parts both at offset 0.0).

4) classSortOrder = int or float; ClassSortOrder
is the third level of comparison that gives an ordering to elements with different classes,
ensuring, for instance that Clefs (classSortOrder = 0) sort before Notes
(classSortOrder = 20).

5) isNotGrace = {0, 1}; 0 = grace, 1 = normal. Grace notes sort before normal notes

6) The last tie-breaker is the creation time (insertIndex) of the site object
represented by the activeSite.

By default, the site used will be the activeSite:

>>> n = note.Note()
>>> n.offset = 4.0
>>> n.priority = -3
>>> n.sortTuple()
SortTuple(atEnd=0, offset=4.0, priority=-3, classSortOrder=20,
            isNotGrace=1, insertIndex=0)

>>> st = n.sortTuple()

Check that all these values are the same as above:

>>> st.offset == n.offset
True
>>> st.priority == n.priority
True

An object's classSortOrder comes from the Class object itself:

>>> st.classSortOrder == note.Note.classSortOrder
True

SortTuples have a few methods that are documented in :class:`~music21.sorting.SortTuple`.
The most useful one for documenting is `.shortRepr()`.

>>> st.shortRepr()
'4.0 <-3.20.0>'

Inserting the note into the Stream will set the insertIndex.  Most implementations of
music21 will use a global counter rather than an actual timer.  Note that this is a
last resort, but useful for things such as multiple Parts inserted in order.  It changes
with each run, so we can't display it here.

>>> s = stream.Stream()
>>> s.insert(n)
>>> n.sortTuple()
SortTuple(atEnd=0, offset=4.0, priority=-3, classSortOrder=20,
             isNotGrace=1, insertIndex=...)

>>> nInsertIndex = n.sortTuple().insertIndex

If we create another nearly identical note, the insertIndex will be different:

>>> n2 = note.Note()
>>> n2.offset = 4.0
>>> n2.priority = -3
>>> s.insert(n2)
>>> n2InsertIndex = n2.sortTuple().insertIndex
>>> n2InsertIndex > nInsertIndex
True

>>> rb = bar.Barline()
>>> s.storeAtEnd(rb)
>>> rb.sortTuple()
SortTuple(atEnd=1, offset=0.0, priority=0, classSortOrder=-5,
            isNotGrace=1, insertIndex=...)


Normally if there's a site specified and the element is not in the site,
the offset of None will be used, but if raiseExceptionOnMiss is set to True
then a SitesException will be raised:

>>> aloneNote = note.Note()
>>> aloneNote.offset = 30
>>> aloneStream = stream.Stream(id='aloneStream')  # no insert
>>> aloneNote.sortTuple(aloneStream)
SortTuple(atEnd=0, offset=30.0, priority=0, classSortOrder=20, isNotGrace=1, insertIndex=0)

>>> aloneNote.sortTuple(aloneStream, raiseExceptionOnMiss=True)
Traceback (most recent call last):
music21.sites.SitesException: an entry for this object 0x... is not stored in
    stream <music21.stream.Stream aloneStream>
FTr  r   r4   r   )r   rJ   r$  r   r   r   r'  r   r   r   r   r   isGracer   	hasSiteIdrk   siteDictglobalSiteIndexr   r  r   )	ra   useSiter  useSiteNoFalsefoundOffsetrJ   atEnd
isNotGraceinsertIndexs	            rA   r>  Music21Object.sortTupleH
  s?   X e!__N$N !++K0,::4t:T -...FEVVHk2FE --t}}/D/DQ!
::7,,**--bk:JJK__(**--b.ABRRKK--zH 	H3 " 0' #//0s   E E<;E<c                    U R                   c  [        S5      U l         U R                   n[        R                  (       a  Uc   eU$ )z?
Get and set the duration of this object as a Duration object.
r   )r   r   r   TYPE_CHECKING)ra   d_outs     rA   r   Music21Object.duration
  s:     >>!%a[DN??$$$r@   c                    SnU R                   b  S U R                   l        Sn UR                  nXl         Xl        U(       a  U R                  SUS.5        g g ! [         a  n[        SU 35      UeS nAff = f)NFTr   )changedElementr   z$this must be a Duration object, not )r   r   r   informSitesr%  r   )ra   durationObjdurationObjAlreadyExistsqlr-  s        rA   r   r  
  s    #( >>%$(DNN!'+$	**B(N!%'  JQS!TU (  	6{mD	s   3A 
A7#A22A7c                    U R                   R                  5        H&  n[        US5      (       d  M  UR                  SSS9  M(     g)z
trigger called whenever sites need to be informed of a change
in the parameters of this object.

`changedInformation` is not used now, but it can be a dictionary
of what has changed.

subclass this to do very interesting things.
coreElementsChangedFT)updateIsFlat	keepIndexN)r   getr   r  )ra   changedInformationrX  s      rA   r  Music21Object.informSites
  s:     !Aq/00%%5D%I "r@   c                    U R                   $ rV   )r   r   s    rA   _getPriorityMusic21Object._getPriority  s    ~~r@   c                    [        U[        5      (       d  [        S5      eU R                  U:w  a  Xl        U R	                  SUS.5        gg)z4
value is an int.

Informs all sites of the change.
z!priority values must be integers.r  )r  r  N)re   r   r*   r   r  r{   s     rA   _setPriorityMusic21Object._setPriority  sF     %%%"#FGG>>U""N
NO #r@   a  
        Get and set the priority integer value.

        Priority specifies the order of processing from left (lowest number)
        to right (highest number) of objects at the same offset.  For
        instance, if you want a key change and a clef change to happen at
        the same time but the key change to appear first, then set:
        keySigElement.priority = 1; clefElement.priority = 2 this might be
        a slightly counterintuitive numbering of priority, but it does
        mean, for instance, if you had two elements at the same offset,
        an allegro tempo change and an andante tempo change, then the
        tempo change with the higher priority number would apply to the
        following notes (by being processed second).

        Default priority is 0; thus negative priorities are encouraged
        to have Elements that appear before non-priority set elements.

        In case of tie, there are defined class sort orders defined in
        `music21.base.classSortOrder`.  For instance, a key signature
        change appears before a time signature change before a
        note at the same offset.  This produces the familiar order of
        materials at the start of a musical score.

        >>> import music21
        >>> a = music21.Music21Object()
        >>> a.priority = 3
        >>> a.priority = 'high'
        Traceback (most recent call last):
        music21.base.ElementException: priority values must be integers.
        c                z   Uc
  [         S   nOUR                  S5      (       a  USS nUS:X  a  SUS'   [        R                  " U5      u  pEUc  [	        SU 35      eUR                  S5      nUS	   nUSS n[        R                  " U5      nUc  [	        SU 35      eU" 5       n	U	R                  " U 4UUUS
.UD6$ )a  
Write out a file of music notation (or an image, etc.) in a given format.  If
fp is specified as a file path then the file will be placed there.  If it is not
given then a temporary file will be created.

If fmt is not given then the default of your Environment's 'writeFormat' will
be used.  For most people that is musicxml.

Returns the full path to the file.

Some formats, including .musicxml, create a copy of the stream, pack it into a well-formed
score if necessary, and run :meth:`~music21.stream.Score.makeNotation`. To
avoid this when writing .musicxml, use `makeNotation=False`, an advanced option
that prioritizes speed but may not guarantee satisfactory notation.
NwriteFormat.r4   mxlTcompressz*cannot support output in this format yet: r   )fmtfp
subformats)r  
startswithr
   
findFormatr)   splitfindSubConverterForFormatwrite)
ra   r  r	  r   regularizedConverterFormat
unused_ext
formatSubsr
  scClassformatWriters
             rA   r  Music21Object.writeA  s    * ;}-C^^C  ab'C%<#'HZ 171B1B31G."%-(+UVYUZ)[\\YYs^
m^
223MN?(+UVYUZ)[\\y!!$ .&@%'-7. %-	. 	.r@   c                    [        U 5      $ )z
Return a text representation possible with line
breaks. This method can be overridden by subclasses
to provide alternative text representations.
reprr  s     rA   	_reprTextMusic21Object._reprTextq       Dzr@   c                    [        U 5      $ )z
Return a text representation without line breaks. This
method can be overridden by subclasses to provide
alternative text representations.
r  r   s    rA   _reprTextLineMusic21Object._reprTextLiney  r  r@   c                <   Uc/  [         R                  " 5       (       a   [        S   nO[[        S   nOQUR                  S5      (       a  USS nO5[         R                  " 5       (       a  UR                  S5      (       a  SU-   n[         R                  " U5      u  pEUc  [        S	U 35      eUR                  S5      nUS
   nUSS n[         R                  " U5      nU" 5       n	U	R                  " U U4UUS.UD6$ ! [        R                  [
        4 a    Sn Nf = f)a  
Displays an object in a format provided by the
fmt argument or, if not provided, the format set in the user's Environment

Valid formats include (but are not limited to)::

    musicxml
    text
    midi
    lily (or lilypond)
    lily.png
    lily.pdf
    lily.svg
    braille
    vexflow
    musicxml.png

N.B. score.write('lily') returns a bare lilypond file,
score.show('lily') runs it through lilypond and displays it as a png.

Some formats, including .musicxml, create a copy of the stream, pack it into a well-formed
score if necessary, and run :meth:`~music21.stream.Score.makeNotation`. To
avoid this when showing .musicxml, use `makeNotation=False`, an advanced option
that prioritizes speed but may not guarantee satisfactory notation.
NipythonShowFormatzipython.musicxml.png
showFormatr  r4   midizipython.z*cannot support showing in this format yet:r   )appr
  )r
   runningInNotebookr  r   EnvironmentExceptionKeyErrorr  r  r)   r  r  show)
ra   r  r#  r   r  r  r  r
  r  r  s
             rA   r'  Music21Object.show  s+   8 ;''))1&':;C #<0^^C  ab'C%%''CNN6,B,Bs"C171B1B31G."%-(+UVYUZ)[\\YYs^
m^
223MNy  !;-%(,6- $,	- 	-' $88(C 10C1s   	C< <DD)ra  includeNonStreamDerivationsc                  / nU nSnUS:  a{  US-
  nUR                   nUc6  USL a/  [        US5      (       a  UR                  R                  nUc  U$ UnOU$ USL d  UR                  (       a  UR                  U5        UnUS:  a  M{  U$ )a  
Return a list of Stream subclasses that this object
is contained within or (if followDerivation is set) is derived from.

This method gives access to the hierarchy that contained or
created this object.

>>> s = corpus.parse('bach/bwv66.6')
>>> noteE = s[1][2][3]
>>> noteE
<music21.note.Note E>
>>> [e for e in noteE.containerHierarchy()]
[<music21.stream.Measure 1 offset=1.0>,
 <music21.stream.Part Soprano>,
 <music21.stream.Score bach/bwv66.6.mxl>]


Note that derived objects also can follow the container hierarchy:

>>> import copy
>>> n2 = copy.deepcopy(noteE)
>>> [e for e in n2.containerHierarchy()]
[<music21.stream.Measure 1 offset=1.0>,
 <music21.stream.Part Soprano>,
 <music21.stream.Score bach/bwv66.6.mxl>]

Unless followDerivation is False:

>>> [e for e in n2.containerHierarchy(followDerivation=False)]
[]

if includeNonStreamDerivations is True then n2's containerHierarchy will include
n even though it's not a container.  It gives a good idea of how the hierarchy is being
constructed.

>>> [e for e in n2.containerHierarchy(includeNonStreamDerivations=True)]
[<music21.note.Note E>,
 <music21.stream.Measure 1 offset=1.0>,
 <music21.stream.Part Soprano>,
 <music21.stream.Score bach/bwv66.6.mxl>]


The method follows activeSites, so set the activeSite as necessary.

>>> p = stream.Part(id='newPart')
>>> m = stream.Measure(number=20)
>>> p.insert(0, m)
>>> m.insert(0, noteE)
>>> noteE.activeSite
<music21.stream.Measure 20 offset=0.0>
>>> noteE.containerHierarchy()
[<music21.stream.Measure 20 offset=0.0>,
 <music21.stream.Part newPart>]

* Changed in v5.7: `followDerivation` and
  `includeNonStreamDerivations` are now keyword only
   r   r4   Tr  )r   r   r  rootDerivationr   r   )ra   ra  r)  rH  focusendMe	candidatealts           rA   containerHierarchy Music21Object.containerHierarchy  s    ~ aiAIE ((I #t+|0L0L  **99C{#$'	K*d2i6H6HI&E) ai* r@   )retainOriginaddTiesdisplayTiedAccidentalsc                  SSK Jn  SSK Jn  [        U5      nXR                  R
                  :  a*  [        SU R                  R
                   S3SU S3-   5      eUSL a  U nO[        R                  " U 5      n[        R                  " U 5      n[        XR                  5      (       a  / n	Xl        / n
S	 GHb  n[        X{5      (       d  M  [        X{5      n[        X{/ 5        [        X/ 5        U GH"  n[        US
5      (       a.  UR                  Xx/5      nU H  nU
R!                  U5        M     MC  [        US5      (       a  UR"                  S:X  a  [        X{5      nUR!                  U5        M  UR"                  S:X  a  [        X5      nUR!                  U5        M  [        X{5      nUR!                  U5        [        X5      nUR!                  U5        M  [        X{5      nUR!                  U5        [        X5      nUR!                  U5        GM%     GMe     [%        XR                  R
                  -
  5      S:  a  U R                  R
                  nU R                  R
                  U-
  nU R                  R
                  U-
  n['        5       nUUl        ['        5       nUUl        UUl        UUl        U(       a  [        XvR(                  UR*                  45      (       a  SnUR,                  bh  UR,                  R.                  S:X  a  SnOfUR,                  R.                  S:X  a  SnSUR,                  l        O8UR,                  R.                  S:X  a  SnO[,        R0                  " S5      Ul        [        XR(                  UR*                  45      (       a  [,        R0                  " U5      nUUl        GOU(       Ga  [        XuR2                  5      (       a  [        XR2                  5      (       a  [5        UR6                  UR6                  5       H  u  nnSnUR,                  bh  UR,                  R.                  S:X  a  SnOfUR,                  R.                  S:X  a  SnSUR,                  l        O8UR,                  R.                  S:X  a  SnO[,        R0                  " S5      Ul        [,        R0                  " U5      Ul        M     U(       a  [        XvR8                  5      (       a  [        XR8                  5      (       a  [;        UR<                  5       H  u  nnUR<                  U   nUR>                  c  M$  UR>                  c  M3  U(       d/  UR>                  R@                  S:w  a  SUR>                  l!        Mg  Mi  SUR>                  l         SUR>                  l!        M     UR                  R
                  S:  a  [E        Xx/5      nO[E        US/5      nU
(       a  U
Ul#        U$ )au  
Split an Element into two Elements at a provided
`quarterLength` (offset) into the Element.

Returns a specialized tuple (_SplitTuple) that also has
a .spannerList element which is a list of spanners
that were created during the split, such as by splitting a trill
note into more than one trill.

TODO: unite into a "split" function -- document obscure uses.

>>> a = note.Note('C#5')
>>> a.duration.type = 'whole'
>>> a.articulations = [articulations.Staccato()]
>>> a.lyric = 'hi'
>>> a.expressions = [expressions.Mordent(), expressions.Trill(), expressions.Fermata()]
>>> st = a.splitAtQuarterLength(3)
>>> b, c = st
>>> b.duration.type
'half'
>>> b.duration.dots
1
>>> b.duration.quarterLength
3.0
>>> b.articulations
[]
>>> b.lyric
'hi'
>>> b.expressions
[<music21.expressions.Mordent>, <music21.expressions.Trill>]
>>> c.duration.type
'quarter'
>>> c.duration.dots
0
>>> c.duration.quarterLength
1.0
>>> c.articulations
[<music21.articulations.Staccato>]
>>> c.lyric
>>> c.expressions
[<music21.expressions.Fermata>]
>>> c.getSpannerSites()
[<music21.expressions.TrillExtension <music21.note.Note C#><music21.note.Note C#>>]

st is a _SplitTuple which can get the spanners from it for inserting into a Stream.

>>> st.spannerList
[<music21.expressions.TrillExtension <music21.note.Note C#><music21.note.Note C#>>]


Make sure that ties and accidentals remain as they should be:

>>> d = note.Note('D#4')
>>> d.duration.quarterLength = 3.0
>>> d.tie = tie.Tie('start')
>>> e, f = d.splitAtQuarterLength(2.0)
>>> e.tie, f.tie
(<music21.tie.Tie start>, <music21.tie.Tie continue>)
>>> e.pitch.accidental.displayStatus is None
True
>>> f.pitch.accidental.displayStatus
False

Should be the same for chords:

>>> g = chord.Chord(['C4', 'E4', 'G#4'])
>>> g.duration.quarterLength = 3.0
>>> g[1].tie = tie.Tie('start')
>>> h, i = g.splitAtQuarterLength(2.0)
>>> for j in range(3):
...   (h[j].tie, i[j].tie)
(<music21.tie.Tie start>, <music21.tie.Tie stop>)
(<music21.tie.Tie start>, <music21.tie.Tie continue>)
(<music21.tie.Tie start>, <music21.tie.Tie stop>)

>>> h[2].pitch.accidental.displayStatus, i[2].pitch.accidental.displayStatus
(None, False)


If quarterLength == self.quarterLength then the second element will be None.

>>> n = note.Note()
>>> n.quarterLength = 0.5
>>> firstPart, secondPart = n.splitAtQuarterLength(0.5)
>>> secondPart is None
True
>>> firstPart is n
True

(same with retainOrigin off)

>>> n = note.Note()
>>> n.quarterLength = 0.5
>>> firstPart, secondPart = n.splitAtQuarterLength(0.5, retainOrigin=False)
>>> firstPart is n
False


If quarterLength > self.quarterLength then a DurationException will be raised:

>>> n = note.Note()
>>> n.quarterLength = 0.5
>>> first, second = n.splitAtQuarterLength(0.7)
Traceback (most recent call last):
music21.duration.DurationException: cannot split a duration (0.5)
    at this quarterLength (7/10)

* Changed in v7: all but quarterLength are keyword only
r   )chord)notezcannot split a duration (z) zat this quarterLength ()T)expressionsarticulationssplitClient	tieAttachfirstlaststopNstartcontinuez	even-tiedFr   )$r  r7  r8  r   r   r   r   r   r   re   GeneralNotelyricsr   r   r   r<  r   r=  absr   Note	Unpitchedr   r   TieChordr   notesNotRest	enumeratepitches
accidentaldisplayTypedisplayStatusrS   r`   )ra   r   r3  r4  r5  r7  r8  r.  eRemainemptyLyricsr`   listTypetempthisExpressionspannersrX  eListeRemainListlenEndlenStartd1d2forceEndTieTypenewTie	componentremainComponentr   rY  remainPr  s                                 rA   splitAtQuarterLength"Music21Object.splitAtQuarterLength  s   l 	"  }-==666#+DMM,G,G+HK+M?!<= 
 4Ad#A--% g//00,.K(N8Hq##q+R(2.&*N~}==#1#=#=ql#K!)A'..q1 "* ==)33w>$+A$8E!LL8+55?*1'*DK'..~>$+A$8E!LL8*1'*DK'..~> ' 4^4&-g&@#**>:+ '+ 98 }}}:::;a? MM77M,,}<==..7Z#Z!
 z!ii%@AA$Ouu  55::(&0O UUZZ6)&,O!+AEEJUUZZ:-&0O ('IIt~~#>??1$A{{33
7KK8X8X.1!''7==.I*	?"(==, !}}))W4*4 #++v5*0-7	*"++z9*4 %(GGG$4IM&)ggo&>#% /J, z!\\22z'<<7X7X!!)),1!//!,<<+0B0B0N1<<33{B?DG..< C :E**6;?**8 - ))C/a\*BaY'B(BN	r@   c                N   [        [        U5      5      U R                  R                  :w  a'  [	        SU SU R                  R                   3-   5      e[        U5      S:X  a   [        [        R                  " U 5      /5      $ U(       d  [	        SU S35      e/ n/ n[        R                  " U 5      nUSS  HD  nUR                  UUUS9nUu  pUR                  U	5        UR                  UR                  5        MF     Ub  UR                  U5        [        U5      n
XZl        U
$ )	a5  
Given a list of quarter lengths, return a "SplitTuple" of
Music21Object objects, copied from this Music21Object,
that are partitioned and tied with the specified quarter
length list durations.

THe SplitTuple will also have a .spannerList which
contains a list of spanner created during the split, such as by splitting a trill
note into more than one trill.

TODO: unite into a "split" function -- document obscure uses.

>>> n = note.Note()
>>> n.quarterLength = 3
>>> post = n.splitByQuarterLengths([1, 1, 1])
>>> [n.quarterLength for n in post]
[1.0, 1.0, 1.0]
zhcannot split by quarter length list whose sum is not equal to the quarterLength duration of the source: z, r4   z*cannot split by this quarter length list: r  N)r4  r5  )r   sumr   r   r)   r   rS   r   r   rb  r   extendr`   )ra   quarterLengthListr4  r5  rW  r`   rQ  qlSplitr  newElstOuts              rA   splitByQuarterLengths#Music21Object.splitByQuarterLengths  s6   0 #'()T]]-H-HH(H&'r$--*E*E)FGH   !Q&d 3455"(<=N<OqQS S &(--% )"-G--g6=E[ . ]B  NELLr~~. . LL!E"'r@   c                    U R                   R                  5       nU R                   R                   Vs/ s H  n[        UR                  U-  5      PM     nnU R                  U5      nU$ s  snf )a  
Takes a Music21Object (e.g., a note.Note) and returns a list of similar
objects with only a single duration.DurationTuple in each.
Ties are added if the object supports ties.

Articulations only appear on the first note.  Same with lyrics.

Fermatas should be on last note, but not done yet.

>>> a = note.Note()
>>> a.duration.clear()  # remove defaults
>>> a.duration.addDurationTuple(duration.durationTupleFromTypeDots('half', 0))
>>> a.duration.quarterLength
2.0
>>> a.duration.addDurationTuple(duration.durationTupleFromTypeDots('whole', 0))
>>> a.duration.quarterLength
6.0
>>> b = a.splitAtDurations()
>>> b
(<music21.note.Note C>, <music21.note.Note C>)
>>> b[0].pitch == b[1].pitch
True
>>> b[0].duration
<music21.duration.Duration 2.0>
>>> b[0].duration.type
'half'
>>> b[1].duration.type
'whole'
>>> b[0].quarterLength, b[1].quarterLength
(2.0, 4.0)

>>> c = note.Note()
>>> c.quarterLength = 2.5
>>> d, e = c.splitAtDurations()
>>> d.duration.type
'half'
>>> e.duration.type
'eighth'
>>> d.tie.type
'start'
>>> print(e.tie)
<music21.tie.Tie stop>

Assume c is tied to the next note.  Then the last split note should also be tied

>>> c.tie = tie.Tie('start')
>>> d, e = c.splitAtDurations()
>>> d.tie.type
'start'
>>> e.tie.type
'continue'

Rests have no ties:

>>> f = note.Rest()
>>> f.quarterLength = 2.5
>>> g, h = f.splitAtDurations()
>>> (g.duration.type, h.duration.type)
('half', 'eighth')
>>> f.tie is None
True
>>> g.tie is None
True


It should work for complex notes with tuplets.

(this duration occurs in Modena A, Le greygnour bien, from the ars subtilior, c. 1380;
hence how I discovered this bug)

>>> n = note.Note()
>>> n.duration.quarterLength = 0.5 + 0.0625  # eighth + 64th
>>> tup = duration.Tuplet(4, 3)
>>> n.duration.appendTuplet(tup)
>>> first, last = n.splitAtDurations()
>>> (first.duration, last.duration)
(<music21.duration.Duration 0.375>, <music21.duration.Duration 0.046875>)

Notice that this duration could have been done w/o tuplets, so no tuplets in output:

>>> (first.duration.type, first.duration.dots, first.duration.tuplets)
('16th', 1, ())
>>> (last.duration.type, last.duration.dots, last.duration.tuplets)
('128th', 1, ())

Test of one with tuplets that cannot be split:

>>> n = note.Note()
>>> n.duration.quarterLength = 0.5 + 0.0625  # eighth + 64th
>>> tup = duration.Tuplet(3, 2, 'eighth')
>>> n.duration.appendTuplet(tup)
>>> (n.duration.type, n.duration.dots, n.duration.tuplets)
('complex', 0, (<music21.duration.Tuplet 3/2/eighth>,))

>>> first, last = n.splitAtDurations()
>>> (first.duration, last.duration)
(<music21.duration.Duration 1/3>, <music21.duration.Duration 1/24>)

>>> (first.duration.type, first.duration.dots, first.duration.tuplets)
('eighth', 0, (<music21.duration.Tuplet 3/2/eighth>,))
>>> (last.duration.type, last.duration.dots, last.duration.tuplets)
('64th', 0, (<music21.duration.Tuplet 3/2/64th>,))


TODO: unite this and other functions into a "split" function -- document obscure uses.

)r   aggregateTupletMultiplier
componentsr   r   rl  )ra   atmcrh  	splitLists        rA   splitAtDurationsMusic21Object.splitAtDurationsV  sc    X mm557DHMMD\D\]D\qVAOOc$9:D\]../@A	 ^s   "A*c                    SnU R                   b3  U R                   R                  (       a  U R                   R                  nU$ U R                  5        H'  nUS   nUR                  (       d  M  UR                  nM)     U$ )a.  
Return the measure number of a :class:`~music21.stream.Measure` that contains this
object if the object is in a measure.

Returns None if the object is not in a measure.  Also note that by
default Measure objects
have measure number 0.

If an object belongs to multiple measures (not in the same hierarchy)
then it returns the
measure number of the :meth:`~music21.base.Music21Object.activeSite` if that is a
:class:`~music21.stream.Measure` object.  Otherwise, it will use
:meth:`~music21.base.Music21Object.getContextByClass`
to find the number of the measure it was most recently added to.

>>> m = stream.Measure()
>>> m.number = 12
>>> n = note.Note()
>>> m.append(n)
>>> n.measureNumber
12

>>> n2 = note.Note()
>>> n2.measureNumber is None
True
>>> m2 = stream.Measure()
>>> m2.append(n2)
>>> n2.measureNumber
0

The property updates if the object's surrounding measure's number changes:

>>> m2.number = 11
>>> n2.measureNumber
11


The most recent measure added to is used unless activeSite is a measure:

>>> m.append(n2)
>>> n2.measureNumber
12
>>> n2.activeSite = m2
>>> n2.measureNumber
11

Copies can retain measure numbers until set themselves:

>>> import copy
>>> nCopy = copy.deepcopy(n2)
>>> nCopy.measureNumber
12
>>> m3 = stream.Measure()
>>> m3.number = 4
>>> m3.append(nCopy)
>>> nCopy.measureNumber
4
Nr   )r   	isMeasurenumberr7  )ra   mNumberr8  ms       rA   measureNumberMusic21Object.measureNumber  sm    z ??&4??+D+Doo,,G  '')qE;;;hhG	 *
 r@   c                   SSK Jn  U R                  nUb9  UR                  (       a(  UR	                  U 5      nU(       a  XCR
                  -  nU$ U R                  UR                  SS9nUb)   UR	                  U 5      nU(       a  XER
                  -  nU$ U R                  nU$ ! [         a    U R                  n U$ f = f)a  
Try to obtain the nearest Measure that contains this object,
and return the offset of this object within that Measure.

If a Measure is found, and that Measure has padding
defined as `paddingLeft` (for pickup measures, etc.), padding will be added to the
native offset gathered from the object.

>>> n = note.Note()
>>> n.quarterLength = 2
>>> m = stream.Measure()
>>> n._getMeasureOffset()  # returns zero when not assigned
0.0
>>> n.quarterLength = 0.5

>>> m = stream.Measure()
>>> m.repeatAppend(n, 4)
>>> [n._getMeasureOffset() for n in m.notes]
[0.0, 0.5, 1.0, 1.5]

>>> m.paddingLeft = 2.0
>>> [n._getMeasureOffset() for n in m.notes]
[2.0, 2.5, 3.0, 3.5]
>>> [n._getMeasureOffset(includeMeasurePadding=False) for n in m.notes]
[0.0, 0.5, 1.0, 1.5]
r   r#   T)r`  )
r  r$   r   rw  r$  paddingLeftrf  Measurer   rJ   )ra   includeMeasurePaddingr$   r  offsetLocalrz  s         rA   _getMeasureOffsetMusic21Object._getMeasureOffset  s    8 	# //7#4#4!//5K$222. # &&v~~$&OA}."#//$"7K,#}}4 	 #kk  & ."&++K .s   -&B# #B=<B=c                ~    SSK Jn  U R                  UR                  [        R
                  S9nUc  [        S5      eU$ )z
used by all the _getBeat, _getBeatDuration, _getBeatStrength functions.

extracted to make sure that all three of the routines use the same one.
r   r!   r  z2this object does not have a TimeSignature in Sites)r  r"   rf  TimeSignaturer   r  r)   )ra   r"   tss      rA   _getTimeSignatureForBeat&Music21Object._getTimeSignatureForBeatP  sF     	"'+'='=*>> (> (
 :()]^^	r@   c                     U R                  5       nUR                  UR                  U 5      5      $ ! [         a    [	        S5      s $ f = f)a  
Return the beat of this object as found in the most
recently positioned Measure. Beat values count from 1 and
contain a floating-point designation between 0 and 1 to
show proportional progress through the beat.

>>> n = note.Note()
>>> n.quarterLength = 0.5
>>> m = stream.Measure()
>>> m.timeSignature = meter.TimeSignature('3/4')
>>> m.repeatAppend(n, 6)
>>> [n.beat for n in m.notes]
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5]


Fractions are returned for positions that cannot be represented perfectly using floats:

>>> m.timeSignature = meter.TimeSignature('6/8')
>>> [n.beat for n in m.notes]
[1.0, Fraction(4, 3), Fraction(5, 3), 2.0, Fraction(7, 3), Fraction(8, 3)]

>>> s = stream.Stream()
>>> s.insert(0, meter.TimeSignature('3/4'))
>>> s.repeatAppend(note.Note(), 8)
>>> [n.beat for n in s.notes]
[1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0]


Notes inside flat streams can still find the original beat placement from outer
streams:

>>> p = stream.Part()
>>> ts = meter.TimeSignature('2/4')
>>> p.insert(0, ts)

>>> n = note.Note('C4', type='eighth')
>>> m1 = stream.Measure(number=1)
>>> m1.repeatAppend(n, 4)

>>> m2 = stream.Measure(number=2)
>>> m2.repeatAppend(n, 4)

>>> p.append([m1, m2])
>>> [n.beat for n in p.flatten().notes]
[1.0, 1.5, 2.0, 2.5, 1.0, 1.5, 2.0, 2.5]


Fractions print out as improper fraction strings

>>> m = stream.Measure()
>>> m.timeSignature = meter.TimeSignature('4/4')
>>> n = note.Note()
>>> n.quarterLength = 1/3
>>> m.repeatAppend(n, 12)
>>> for n in m.notes[:5]:
...    print(n.beat)
1.0
4/3
5/3
2.0
7/3

If there is no TimeSignature object in sites then returns the special float
`nan` meaning "Not a Number":

>>> isolatedNote = note.Note('E4')
>>> isolatedNote.beat
nan

Not-a-number objects do not compare equal to themselves:

>>> isolatedNote.beat == isolatedNote.beat
False

Instead, to test for `nan`, import the math module and use `isnan()`:

>>> import math
>>> math.isnan(isolatedNote.beat)
True

* Changed in v6.3: returns `nan` if
  there is no TimeSignature in sites.
  Previously raised an exception.
nan)r  getBeatProportion$getMeasureOffsetOrMeterModulusOffsetr)   r3  ra   r  s     rA   beatMusic21Object.beat_  sL    n	 ..0B''(O(OPT(UVV% 	 <	    /2 A
	A
c                     U R                  5       nUR                  UR                  U 5      5      $ ! [         a     gf = f)a  
Return a string representation of the beat of
this object as found in the most recently positioned
Measure. Beat values count from 1 and contain a
fractional designation to show progress through the beat.


>>> n = note.Note(type='eighth')
>>> m = stream.Measure()
>>> m.timeSignature = meter.TimeSignature('3/4')
>>> m.repeatAppend(n, 6)

>>> [n.beatStr for n in m.notes]
['1', '1 1/2', '2', '2 1/2', '3', '3 1/2']

>>> m.timeSignature = meter.TimeSignature('6/8')
>>> [n.beatStr for n in m.notes]
['1', '1 1/3', '1 2/3', '2', '2 1/3', '2 2/3']

>>> s = stream.Stream()
>>> s.insert(0, meter.TimeSignature('3/4'))
>>> s.repeatAppend(note.Note(type='quarter'), 8)
>>> [n.beatStr for n in s.notes]
['1', '2', '3', '1', '2', '3', '1', '2']

If there is no TimeSignature object in sites then returns 'nan' for not a number.

>>> isolatedNote = note.Note('E4')
>>> isolatedNote.beatStr
'nan'

* Changed in v6.3: returns 'nan' if
  there is no TimeSignature in sites.
  Previously raised an exception.
r  )r  getBeatProportionStrr  r)   r  s     rA   beatStrMusic21Object.beatStr  sE    J	..0B**2+R+RSW+XYY% 		s   /2 
??c                     U R                  5       nUR                  UR                  U 5      5      $ ! [         a    [	        S5      s $ f = f)a  
Return a :class:`~music21.duration.Duration` of the beat
active for this object as found in the most recently
positioned Measure.

If extending beyond the Measure, or in a Stream with a TimeSignature,
the meter modulus value will be returned.

>>> n = note.Note('C4', type='eighth')
>>> n.duration
<music21.duration.Duration 0.5>

>>> m = stream.Measure()
>>> m.timeSignature = meter.TimeSignature('3/4')
>>> m.repeatAppend(n, 6)
>>> n0 = m.notes.first()
>>> n0.beatDuration
<music21.duration.Duration 1.0>

Notice that the beat duration is the same for all these notes
and has nothing to do with the duration of the element itself

>>> [n.beatDuration.quarterLength for n in m.notes]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

Changing the time signature changes the beat duration:

>>> m.timeSignature = meter.TimeSignature('6/8')
>>> [n.beatDuration.quarterLength for n in m.notes]
[1.5, 1.5, 1.5, 1.5, 1.5, 1.5]

Complex time signatures will give different note lengths:

>>> s = stream.Stream()
>>> s.insert(0, meter.TimeSignature('2/4+3/4'))
>>> s.repeatAppend(note.Note(type='quarter'), 8)
>>> [n.beatDuration.quarterLength for n in s.notes]
[2.0, 2.0, 3.0, 3.0, 3.0, 2.0, 2.0, 3.0]

If there is no TimeSignature object in sites then returns a duration object
of Zero length.

>>> isolatedNote = note.Note('E4')
>>> isolatedNote.beatDuration
<music21.duration.Duration 0.0>

* Changed in v6.3: returns a duration.Duration object of length 0 if
  there is no TimeSignature in sites.  Previously raised an exception.
r   )r  getBeatDurationr  r)   r   r  s     rA   beatDurationMusic21Object.beatDuration  sK    f	..0B%%b&M&Md&STT% 	A;	r  c                     U R                  5       nUR                  U 5      nUR                  USSS9$ ! [         a    [	        S5      s $ f = f)a
  
Return the metrical accent of this object
in the most recently positioned Measure. Accent values
are between zero and one, and are derived from the local
TimeSignature's accent MeterSequence weights. If the offset
of this object does not match a defined accent weight, a
minimum accent weight will be returned.


>>> n = note.Note(type='eighth')
>>> m = stream.Measure()
>>> m.timeSignature = meter.TimeSignature('3/4')
>>> m.repeatAppend(n, 6)

The first note of a measure is (generally?) always beat strength 1.0:

>>> m.notes.first().beatStrength
1.0

Notes on weaker beats have lower strength:

>>> [n.beatStrength for n in m.notes]
[1.0, 0.25, 0.5, 0.25, 0.5, 0.25]

>>> m.timeSignature = meter.TimeSignature('6/8')
>>> [n.beatStrength for n in m.notes]
[1.0, 0.25, 0.25, 0.5, 0.25, 0.25]


Importantly, the actual numbers here have no particular meaning.  You cannot
"add" two beatStrengths of 0.25 and say that they have the same beat strength
as one note of 0.5.  Only the ordinal relations really matter.  Even taking
an average of beat strengths is a tiny bit methodologically suspect (though
it is common in research for lack of a better method).

We can also get the beatStrength for elements not in
a measure, if the enclosing stream has a :class:`~music21.meter.TimeSignature`.
We just assume that the time signature carries through to
hypothetical following measures:

>>> n = note.Note('E-3', type='quarter')
>>> s = stream.Stream()
>>> s.insert(0.0, meter.TimeSignature('2/2'))
>>> s.repeatAppend(n, 12)
>>> [n.beatStrength for n in s.notes]
[1.0, 0.25, 0.5, 0.25, 1.0, 0.25, 0.5, 0.25, 1.0, 0.25, 0.5, 0.25]


Changing the meter changes the output, of course, as can be seen from the
fourth quarter note onward:

>>> s.insert(4.0, meter.TimeSignature('3/4'))
>>> [n.beatStrength for n in s.notes]
[1.0, 0.25, 0.5, 0.25, 1.0, 0.5, 0.5, 1.0, 0.5, 0.5, 1.0, 0.5]


The method returns correct numbers for the prevailing time signature
even if no measures have been made:

>>> n = note.Note('E--3', type='half')
>>> s = stream.Stream()
>>> s.isMeasure
False

>>> s.insert(0, meter.TimeSignature('2/2'))
>>> s.repeatAppend(n, 16)
>>> s.notes[0].beatStrength
1.0
>>> s.notes[1].beatStrength
0.5
>>> s.notes[4].beatStrength
1.0
>>> s.notes[5].beatStrength
0.5

Getting the beatStrength of an object without a time signature in its context
returns the not-a-number special object 'nan':

>>> n2 = note.Note(type='whole')
>>> n2.beatStrength
nan
>>> from math import isnan
>>> isnan(n2.beatStrength)
True

* Changed in v6.3: return 'nan' instead of raising an exception.
TF)forcePositionMatchpermitMeterModulusr  )r  r  getAccentWeightr)   r3  )ra   r  meterModuluss      rA   beatStrengthMusic21Object.beatStrength   sc    r	 ..0BBB4HL%%l9=9> & @ @ & 	 <	 s   14 AAc                    SSK Jn  U R                  R                  S:X  a  gU R	                  UR
                  5      nUc  [        S5      $ UR                  5       nUR                  U R                  5      $ )Nr   tempor   r  )	r  r  r   r   rf  TempoIndicationr3  getSoundingMetronomeMarkdurationToSeconds)ra   r  timms       rA   _getSecondsMusic21Object._getSeconds  sb    !==&&#-##E$9$9::<((*##DMM22r@   c                0   SSK Jn  U R                  UR                  5      nUc  [	        S5      eUR                  5       nUR                  U5      U l        U R                  R                  SS9 H$  nXR                  ;   d  M  UR                  5         M&     g )Nr   r  z4this object does not have a TempoIndication in SitesTrN  )r  r  rf  r  r)   r  secondsToDurationr   r   r  elementsr  )ra   r|   r  r  r  rX  s         rA   _setSecondsMusic21Object._setSeconds  s{    !##E$9$9::()_``((*,,U3D1Azz!%%' 2r@   a*
  
        Get or set the duration of this object in seconds, assuming
        that this object has a :class:`~music21.tempo.MetronomeMark`
        or :class:`~music21.tempo.MetricModulation`
        (or any :class:`~music21.tempo.TempoIndication`) in its past context.

        >>> s = stream.Stream()
        >>> for i in range(3):
        ...    s.append(note.Note(type='quarter'))
        ...    s.append(note.Note(type='quarter', dots=1))
        >>> s.insert(0, tempo.MetronomeMark(number=60))
        >>> s.insert(2, tempo.MetronomeMark(number=120))
        >>> s.insert(4, tempo.MetronomeMark(number=30))
        >>> [n.seconds for n in s.notes]
        [1.0, 1.5, 0.5, 0.75, 2.0, 3.0]

        Setting the number of seconds on a music21 object changes its duration:

        >>> lastNote = s.notes[-1]
        >>> lastNote.duration.fullName
        'Dotted Quarter'
        >>> lastNote.seconds = 4.0
        >>> lastNote.duration.fullName
        'Half'

        Any object of length 0 has zero-second length:

        >>> tc = clef.TrebleClef()
        >>> tc.seconds
        0.0

        If an object has positive duration but no tempo indication in its context,
        then the special number 'nan' for "not-a-number" is returned:

        >>> r = note.Rest(type='whole')
        >>> r.seconds
        nan

        Check for 'nan' with the `math.isnan()` routine:

        >>> import math
        >>> math.isnan(r.seconds)
        True

        Setting seconds for an element without a tempo-indication in its sites raises
        a Music21ObjectException:

        >>> r.seconds = 2.0
        Traceback (most recent call last):
        music21.base.Music21ObjectException: this object does not have a TempoIndication in Sites

        Note that if an object is in multiple Sites with multiple Metronome marks,
        the activeSite (or the hierarchy of the activeSite)
        determines its seconds for getting or setting:

        >>> r = note.Rest(type='whole')
        >>> m1 = stream.Measure()
        >>> m1.insert(0, tempo.MetronomeMark(number=60))
        >>> m1.append(r)
        >>> r.seconds
        4.0

        >>> m2 = stream.Measure()
        >>> m2.insert(0, tempo.MetronomeMark(number=120))
        >>> m2.append(r)
        >>> r.seconds
        2.0
        >>> r.activeSite = m1
        >>> r.seconds
        4.0
        >>> r.seconds = 1.0
        >>> r.duration.type
        'quarter'
        >>> r.activeSite = m2
        >>> r.seconds = 1.0
        >>> r.duration.type
        'half'

        * Changed in v6.3: return `nan` instead of raising an exception.
        )r   r   r   r   r   r   r   r   r   r   r   r   r   rk   r   )	NNNNNNNr   N)rk   zstr | int | Noner   zGroups | Noner   zSites | Noner   zDuration | Noner   stream.Stream | Noner   zStyle | Noner   zEditorial | NonerJ   r   r   zOffsetQLIn | None)ra   r&   rq   zt.TypeGuard[_M21T])rq   r   )rq   	int | str)r   r  )rg   r,   rq   rr   rV   )ra   r&   r   dict[int, t.Any] | Noner   zset[str] | Nonerq   r&   )ra   r&   r   r  rq   r&   )rq   dict[str, t.Any])r   r  )rq   ry   r  )rq   r   )r  r   )rq   r   )r  r   )rq   r   )r|   r   )rq   r   )r   zDerivation | Nonerq   rr   )rq   rr   )rI   r  r  t.Literal[False]rq   r   )rI   r  r  r  rq   zOffsetQL | OffsetSpecial)rI   r  r|   r   )rI   r  rq   r   )rF  zIterable | Nonerq   zlist[spanner.Spanner])T)F)re  ztype[_M21T]rq   z_M21T | None)re  
str | Nonerq   zMusic21Object | None)re  ztype[_M21T] | str | Noner_  r   rq   z_M21T | Music21Object | None)r  zt.Literal[True]r  r   r`  t.Literal['reverse'] | boolrq   z'Generator[ContextSortTuple, None, None])r  r   r`  r  r  r  rq   z#Generator[ContextTuple, None, None])r  r   r`  r  r  r  rq   z6Generator[ContextTuple | ContextSortTuple, None, None])re  z type[Music21Object] | str | None)rI   r  )FF)r  z't.Literal[False] | stream.Stream | Noner  r  rq   r   )rq   r   )r  r   )NN)r  r  r	  z"str | pathlib.Path | IOBase | Nonerq   zpathlib.Path)rq   rS   )TF)rh  z&list[int | float | fractions.Fraction]rq   rS   )rq   z
int | None)rq   zfloat | fractions.Fraction)rq   zmeter.TimeSignature)rq   zfractions.Fraction | float)rq   r3  )r|   r   rq   rr   )Lr;   r<   r=   r>   rs   r   rN   r   r   r   r   r   r   rb   rf   rj   propertyrk   setterr   r   r   r   r   r   r   r   r  r   r   r  r  r   r  r4  r9  rK  r   r]  r   r  rf  r7  r  r  r  rT  rU  r   rJ   r>  r   r  r  r  r  r  r  r  r'  r1  rb  rl  rt  r{  r  r  r  r  r  r  r  r  secondsr?   rt   ru   s   @rA   r,   r,   W  s"   eN !#NI"H$K$*77 J	?<K(!I~ (V %)'+%)+/26%)-1$'26/8!/8$/8 #/8 )	/8
 0/8 #/8 +/8 "/8 !0/8b ! ! YY 2* =A+ AE+$9+ 1>+ JO+Z'0R4. - -*  0   ) )*  : \\ 
 + +  , , !  ! F ) ), 
 +0	  (	
 
  
 $	  	
 
   $	v v 	v
 
 vp3&03&)3&jGN GN 
GNT ;?X9*7X92X9t*B= 
 '33  		 
	 	 
 '33  		 
	 	 +8*D*D  T'T (	T 
"Tn 
 !$8=  *  6 
1   !$8=-2 
  6 + 
- " !$8=!& EI
 EI 6EI EI 
>EIN
_< 8<v9 "v94v9r <@Y( !&Y(8Y(B
$$< .(J: z zx ]]' ' BG/4QH>QH(,QH !QHh   __ &J
P $HL +/-.-. )-.
 
-.`7-~ $)	Wz $C 
CP $	9=9
 
9vof G GR;z Z  Z x ( (T 6 6p `  ` D3	( {K O6 OGr@   r,   r   _m21ObjDefaultDefinedKeysc                  l   ^  \ rS rSr% SrSrS/rSS0rS\S'   SSU 4S jjjr	S	 r
SS
 jrSS jrSrU =r$ )r-   i  aD  
An ElementWrapper is a way of containing any object that is not a
:class:`~music21.base.Music21Object`, so that that object can be positioned
within a :class:`~music21.stream.Stream`.

The object stored within ElementWrapper is available from the
:attr:`~music21.base.ElementWrapper.obj` attribute.  All the attributes of
the stored object (except .id and anything else that conflicts with a
Music21Object attribute) are gettable and settable by querying the
ElementWrapper.  This feature makes it possible easily to mix
Music21Objects and non-Music21Objects with similarly named attributes in
the same Stream.

This example inserts 10 random wave files into a music21 Stream and then
reports their filename and number of audio channels (in this example, it's
always 2) if they fall on a strong beat in fast 6/8

>>> import music21
>>> #_DOCS_SHOW import wave
>>> import random
>>> class Wave_read: #_DOCS_HIDE
...    def getnchannels(self): return 2 #_DOCS_HIDE

>>> s = stream.Stream()
>>> s.id = 'mainStream'
>>> s.append(meter.TimeSignature('fast 6/8'))
>>> for i in range(10):
...    #_DOCS_SHOW fileName = 'thisSound_' + str(random.randint(1, 20)) + '.wav'
...    fileName = 'thisSound_' + str(1 + ((i * 100) % 19)) + '.wav' #_DOCS_HIDE
...    soundFile = Wave_read() #_DOCS_HIDE # #make a more predictable "random" set.
...    #_DOCS_SHOW soundFile = wave.open(fileName)
...    soundFile.fileName = fileName
...    el = music21.ElementWrapper(soundFile)
...    s.insert(i, el)

>>> for j in s.getElementsByClass(base.ElementWrapper):
...    if j.beatStrength > 0.4:
...        (j.offset, j.beatStrength, j.getnchannels(), j.fileName)
(0.0, 1.0, 2, 'thisSound_1.wav')
(3.0, 1.0, 2, 'thisSound_16.wav')
(6.0, 1.0, 2, 'thisSound_12.wav')
(9.0, 1.0, 2, 'thisSound_8.wav')
>>> for j in s.getElementsByClass(base.ElementWrapper):
...    if j.beatStrength > 0.4:
...        (j.offset, j.beatStrength, j.getnchannels() + 1, j.fileName)
(0.0, 1.0, 3, 'thisSound_1.wav')
(3.0, 1.0, 3, 'thisSound_16.wav')
(6.0, 1.0, 3, 'thisSound_12.wav')
(9.0, 1.0, 3, 'thisSound_8.wav')

Test representation of an ElementWrapper

>>> for i, j in enumerate(s.getElementsByClass(base.ElementWrapper)):
...     if i == 2:
...         j.id = None
...     else:
...         j.id = str(i) + '_wrapper'
...     if i <=2:
...         print(j)
<music21.base.ElementWrapper id=0_wrapper offset=0.0 obj='<...Wave_read object...'>
<music21.base.ElementWrapper id=1_wrapper offset=1.0 obj='<...Wave_read object...'>
<music21.base.ElementWrapper offset=2.0 obj='<...Wave_read object...>'>

Equality
--------
Two ElementWrappers are equal if they would be equal as Music21Objects and they
wrap objects that are equal.

>>> list1 = ['a', 'b', 'c']
>>> a = base.ElementWrapper(list1)
>>> a.offset = 3.0

>>> list2 = ['a', 'b', 'c']
>>> b = base.ElementWrapper(list2)
>>> b.offset = 3.0
>>> a == b
True
>>> a is not b
True

Offset does not need to be equal for equality:

>>> b.offset = 4.0
>>> a == b
True

But elements must compare equal

>>> list2.append('d')
>>> a == b
False

* Changed in v9: completely different approach to equality, unified w/
  the rest of music21.
)rI  rI  z
        The object this wrapper wraps. It should not be a Music21Object, since
        if so, you might as well put that directly into the Stream itself.r   r   c                2   > Xl         [        TU ]  " S0 UD6  g )Nr9   )rI  rW   rb   )ra   rI  r   r\   s      rA   rb   ElementWrapper.__init__Y  s     $8$r@   c                   [        U R                  5      SS n[        [        U R                  5      5      S:  a  US-  nUS   S:X  a  US-  nU R                  b   SU R                   SU R
                   SU< 3$ S	U R
                   SU< 3$ )
Nr      z...<>r   z offset=z obj=zoffset=)ry   rI  r   r   rk   rJ   )ra   shortObjs     rA   r   ElementWrapper._reprInternala  s    M1R(s488}"H{c!C88	$++eH<HHT[[Mxl;;r@   c                6   US:X  a  [         R                  U SU5        g XR                  ;   a  [         R                  XU5        [         R                  U S5      nU[        ;  a   Ub  [        X15      (       a  [        X1U5        g [         R                  XU5        g )NrI  )r   r   r   __getattribute__r  r   r   )ra   namer|   	storedObjs       rA   r   ElementWrapper.__setattr__m  s    5=tUE2 == t51 ++D%8	11)I,,IU+ t51r@   c                ~    [         R                  U S5      nUc  [        SU< S35      e[        R                  X!5      $ )z
This method is only called when __getattribute__() fails.
Using this also avoids the potential recursion problems of subclassing
__getattribute__()_

see: https://stackoverflow.com/questions/371753/python-using-getattribute-method
for examples
rI  zCould not get attribute z in an object-less element)r,   r  r%  r   )ra   r  r  s      rA   __getattr__ElementWrapper.__getattr__  sC     "224?	 #;D8C]!^__&&y77r@   rV   )rI  rp   )r  ry   r|   rp   rq   rr   )r  ry   rq   rp   )r;   r<   r=   r>   rs   r   r   r   rN   rb   r   r   r  r?   rt   ru   s   @rA   r-   r-     sN    ^~ "J N!I~ % %
<2(8 8r@   r-   c                      \ rS rSrSrS rSrg)Testi  z,
All other tests moved to test/test_base.py
c                2    SSK Jn  U" U [        5       5        g )Nr   )testCopyAll)music21.test.commonTestr  globals)ra   r  s     rA   testCopyAndDeepcopyTest.testCopyAndDeepcopy  s    7D')$r@   r9   N)r;   r<   r=   r>   rs   r  r?   r9   r@   rA   r  r    s    %r@   r  __main__)rq   zfrozenset[str])crs   
__future__r   r   collections.abcr   r   r   	functoolsimportlib.utilr   typingr   r   unittestr3   weakrefmusic21._versionr   r	   r  r
   music21.common.enumsr   r   music21.common.numberToolsr   music21.common.typesr   r   r   music21.derivationr   music21.durationr   r   music21.editorialr   r   r   r   music21.sitesr   r   r   music21.styler   music21.sortingr   r   r   r   r  	fractionsior    pathlibr"   r$   r%   TypeVarr&   r.   r/   __all__r(   Environmentr  _missingImportmodNameloaderr   r   getMissingImportStrr)   r*   
NamedTuplerF   rP   rY   rS   r   r+   r   r   r   cacher   ProtoM21Objectr,   dirr  rN   r-   TestCaser  r   r;   mainTestr9   r@   rA   <module>r     s*  4 #  /   $      :  = - 5  ) 8 '     ? ?  J J ??IIg%ABE (  00 &&v.&GwF~g& '
 J>1&44^D!+ 	 	-	\:: 		|44 	,1<< ,
,q|| ,8% 8|YT Y@ !( !8  ) )@S:G** S:nt .33}3G-H ? H]8] ]8@%8 % ^,
 z r@   