
    3jn                      U d Z ddlmZ ddlZddlmZmZ ddlZddlZddl	m
Z
 ddlZddlmZ ddlZddlZddlZddlmZmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlmZ ddlm Z  ddl!m"Z"m#Z# ddl$m%Z% ddlm&Z& ddlm'Z' ddlm(Z( ddl)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2 ddlm3Z3 ejh                  r4ddl5Z5ddl6m7Z7 ddl8Z8ddlm9Z9 ddlm:Z: ddlm;Z;  ejx                  dd      Z=eZ>eZ?g dZ@e'j                  ZA e&j                  d      ZCg ZDd D ]  ZE e
eE      ZFeFeDj                  eE         [
[EeDr*eCd!   d"v r#eCj                   ej                  eD      d#$        G d% d&e'j                        ZJ G d' d(e'j                        ZK G d) d*ej                        ZM G d+ d,ej                        ZN G d- d.eO      ZP G d/ d0eQ      ZR eS       ZT eS       ZUej                  d;d1       ZW G d2 d3e(j                        ZY eO eZ eY                   Z[d4e\d5<    G d6 d7eY      Z] G d8 d9ej                        Z_eYe]gZ`ead:k(  rddlZ ej                          yy)<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
'10.5.0'

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                      e Zd Zy)r)   N__name__
__module____qualname__     9/DATA/.local/lib/python3.12/site-packages/music21/base.pyr)   r)   }       r=   r)   c                      e Zd Zy)r*   Nr8   r<   r=   r>   r*   r*      r?   r=   r*   c                  ,    e Zd ZU ded<   ded<   ded<   y)ContextTuplestream.Streamsiter   offsetstream.enums.RecursionTyperecurseTypeNr9   r:   r;   __annotations__r<   r=   r>   rB   rB      s    
++r=   rB   c                  ,    e Zd ZU ded<   ded<   ded<   y)ContextSortTuplerC   rD   r   rE   rF   rG   NrH   r<   r=   r>   rK   rK      s    
++r=   rK   c                  >     e Zd ZdZ fdZddZ fdZ fdZ xZS )_SplitTuplea  
    >>> 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                >    t         t        |   | t        |            S N)superrM   __new__tuple)clstupEls	__class__s     r>   rQ   z_SplitTuple.__new__   s    [#.sE&MBBr=   c                    g | _         y rO   )spannerList)selfrT   s     r>   __init__z_SplitTuple.__init__   s
    24r=   c                x    t        |t              sy| j                  |j                  k7  ryt        |   |      S )NF)
isinstancerM   rW   rP   __eq__)rX   otherrU   s     r>   r\   z_SplitTuple.__eq__   s6    %-u000w~e$$r=   c                d    t         |          }t        | j                        }t	        ||f      S rO   )rP   __hash__idrW   hash)rX   h1h2rU   s      r>   r_   z_SplitTuple.__hash__   s.    W  !RH~r=   )rT   t.AnyreturnNone)	r9   r:   r;   __doc__rQ   rY   r\   r_   __classcell__rU   s   @r>   rM   rM      s#    %LC5% r=   rM   c                  >     e Zd ZdZdZddZddZ fdZddZ xZ	S )	r+   a  
    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
    r<   c                T    t        |t              st        j                  d|      y )Nz-Only strings can be used as group names, not )r[   strr   GroupExceptionrX   values     r>   
_validNamezGroups._validName   s5    %%-- /55:I/? @ @ &r=   c                    | j                  |       t        j                  | |      st        j                  | |       y y rO   )rp   list__contains__appendrn   s     r>   rt   zGroups.append   s1      u-KKe$ .r=   c                H    | j                  |       t        | 	  ||       y rO   )rp   rP   __setitem__)rX   iyrU   s      r>   rv   zGroups.__setitem__   s    Aq!r=   c                    t        |t              syt        |       t        |      k7  ryt        t	        |       t	        |            D ](  \  }}|j                         |j                         k7  s( y y)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)r[   r+   lenzipsortedlower)rX   r]   eSelfeOthers       r>   r\   zGroups.__eq__  s]    8 %(t9E
" ve}=ME6{{}. > r=   )ro   rl   re   rf   )r]   object)
r9   r:   r;   rg   	__slots__rp   rt   rv   r\   rh   ri   s   @r>   r+   r+      s%    @ I@%
"%r=   r+   c                    t               }| g| j                         D ]<  }t        |d      s|j                  }t	        |t
              r|f}|t        |      z  }> t        |      S )a  
    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   r[   rl   	frozenset)rS   r   klasskas       r>   _getEqualityAttributesr   4  sj      "	"5./))B"c"U#b') # '((r=   c            
          e Zd ZU dZdZded<   dZeZded<   dZ	d	ed
<   g Z
ded<   dddddZded<   	 	 	 	 	 	 	 	 	 de	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dfdZdgdZdhdZedid       Zej"                  djd       ZdkdZ	 dldd	 	 	 	 	 dmdZdldndZdodZdpd Zdq fd!Zedrd"       Zedsd#       Zej"                  dtd$       Zedrd%       Zedud&       Zej"                  dvd'       Zedwd(       Zej"                  dxd)       Zedyd*       Zej"                  dzd+       Zd{d,Zedd-	 	 	 	 	 d|d.       Z edd-	 	 	 	 	 d}d/       Z dd-	 	 	 	 	 d}d0Z 	 	 	 	 d~d1Z!	 	 	 	 dd2Z"	 dl	 	 	 dd3Z#dd{d5Z$dd{d6Z%ee&jN                  dd4dd7	 	 	 dd8       Z(ee&jN                  dd4dd7	 	 	 dd9       Z(e&jN                  dd4dd7	 	 	 	 	 dd:Z(edddddd4dd;	 	 	 	 	 	 	 dd<       Z)eddddddd4dd=	 	 	 	 	 	 	 dd>       Z)ddddddd4dd=	 	 	 	 	 	 	 dd?Z)d@ Z*	 dlddA	 ddBZ+	 dlddA	 ddCZ,dD Z-ddEZ. ee-e.dFG      Z/edwdH       Z0e0j"                  dxdI       Z0	 	 d	 	 	 	 	 ddJZ1eddK       Z2e2j"                  ddL       Z2dldMZ3dN Z4dO Z5 ee4e5dPG      Z6	 	 d	 	 	 	 	 ddQZ7dR Z8dS Z9ddTZ:d4ddUdVZ;d4d4ddW	 ddXZ<	 	 d	 	 	 ddYZ=ddZZ>edd[       Z?ddd\Z@dd]ZAedd^       ZBedqd_       ZCedd`       ZDedda       ZEddbZFddcZG eeFeGddG      ZH xZIS )r,   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
                (   || _         d | _        || _        d | _        d | _        || _        d | _        || _        || |_        d| _	        i | _
        |xs
 t               | _        |xs
 t               | _        ||| _        |	|	| j                   _        y y )Nr   )_id_activeSite_naiveOffset_activeSiteStoredOffset_derivation_style
_editorial	_durationclient	_priority_cacher+   r   r   r   
activeSiter   quarterLength)rX   r`   r   r   r   r   style	editorialrE   r   keywordss              r>   rY   zMusic21Object.__init__  s     "$EI&,
 GK$ -1"'*. )1"HO )+(%eg
 !(DO$*7DMM' %r=   c                    t        j                  t        | j                        }t	        ||      syt        |      D ]'  }t        | |t              t        ||t              k7  s' y y)zK
        Define equality for Music21Objects.  See main class docs.
        FT)	tcasttyperU   r[   r   getattr_EQUALITY_SENTINEL_SELF_EQUALITY_SENTINEL_OTHER)rX   r]   rS   attrs       r>   r\   zMusic21Object.__eq__%  s\     ffT4>>*%%*3/Dd$;<ud,DEF 0 r=   c                    t        |       dz	  S )z7
        Restore hashing, but only on id(self)
           )r`   rX   s    r>   r_   zMusic21Object.__hash__3  s     $x1}r=   c                \    | j                   | j                   S t        j                  |       S )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   builtinsr`   r   s    r>   r`   zMusic21Object.id9  s&     8888O{{4  r=   c                    t        |t              r4|t        j                  kD  r!d}|d| z  }t	        j
                  |d       || _        y )Nz;Setting an ID that could be mistaken for a memory location zis discouraged: got    )
stacklevel)r[   intr   #minIdNumberToConsiderMemoryLocationr3   warnr   )rX   new_idmsgs      r>   r`   zMusic21Object.idI  sE    fc"v0\0\'\OC)&22CMM#!,r=   c                    |j                   t        |      k7  r|j                   | _         t        j                  |j                        | _        y)a  
        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)r`   copydeepcopyr   )rX   r]   s     r>   mergeAttributeszMusic21Object.mergeAttributesQ  s3      88r%y hhDGmmELL1r=   ignoreAttributesc               @   h d}| j                   s|j                  d       ||}n||z  }t        j                  | ||      }i |_        t               |_        d|v rt               |_         t        |      }| |_	        d|_
        ||_        |j                          |S )a  
        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   __deepcopy__)r   addr
   defaultDeepcopyr   r   r   r+   r   originmethodr   purgeOrphans)rX   memor   defaultIgnoreSetnewnewDerivations         r>   _deepcopySubclassablez#Music21Object._deepcopySubclassablee  s     N{{  * #//2BB$$T4BRS
W
''CJ ##.#-' 	
r=   c                $    | j                  |      S )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   )rX   r   s     r>   r   zMusic21Object.__deepcopy__  s    N ))$//r=   c                N    | j                   j                         }d |d<   d |d<   |S )Nr   r   )__dict__r   rX   states     r>   __getstate__zMusic21Object.__getstate__  s-    ""$#m#mr=   c                2    t         j                  | d|       y )Nr   )r   __setattr__r   s     r>   __setstate__zMusic21Object.__setstate__  s    4U3r=   c                    t        | d      r| j                  t        |       k(  rt        |          S | j                  }	 t	        t        |            }d| S # t        t        f$ r Y w xY w)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'
        r`   id=)r   r`   rP   _reprInternalhexr   
ValueError	TypeError)rX   reprIdrU   s     r>   r   zMusic21Object._reprInternal  so     tT"dggD&97(**	V%F VH~ I& 		s   A A,+A,c                    | j                   duS )ax  
        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    r>   hasEditorialInformationz%Music21Object.hasEditorialInformation  s    ( d**r=   c                P    | j                   t               | _         | j                   S )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    r>   r   zMusic21Object.editorial  s!    * ??"'kDOr=   c                    || _         y rO   r   )rX   eds     r>   r   zMusic21Object.editorial  s	    r=   c                    | j                   duS )aU  
        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    r>   hasStyleInformationz!Music21Object.hasStyleInformation  s    ( {{$&&r=   c                ~    | j                   s| j                  } |       | _        | j                  J | j                  S )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   )rX   
StyleClasss     r>   r   zMusic21Object.style%  s;    0 ''))J$,DK{{&&&{{r=   c                    || _         y rO   r   )rX   newStyles     r>   r   zMusic21Object.styleC  s	    r=   c                .    | j                   j                  S )aV  
        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    r>   r   zMusic21Object.quarterLengthI  s     }}***r=   c                &    || j                   _        y rO   r   rn   s     r>   r   zMusic21Object.quarterLengthZ  s    &+#r=   c                T    | j                   t        |       | _         | j                   S )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    r>   
derivationzMusic21Object.derivation^  s*    @ #)6Dr=   c                    || _         y rO   )r   )rX   r   s     r>   r   zMusic21Object.derivation  s
    (r=   c                    i | _         y)aI  
        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   rX   r   s     r>   
clearCachezMusic21Object.clearCache  s    ( r=   returnSpecialc                    y rO   r<   rX   rD   r   s      r>   getOffsetBySitezMusic21Object.getOffsetBySite       	r=   c                    y rO   r<   r   s      r>   r   zMusic21Object.getOffsetBySite  r   r=   c               Z   || j                   S 	 d}| }t               }d}|-	 |r|j                  |d      }n|j                  |d      }|-|S # t        $ r}t	        d|d      |d}~wt
        $ r}||j                  v r(|rt        j                  cY d}~S |j                  cY d}~S | j                  j                  }	|	||	}t        |      |v r||j                  t        |             |dz  }|d	k  r|Y d}~d}~ww xY w# t        $ r}
t	        d
| d|      |
d}
~
ww xY w)a*
  
        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   Tr   FzYou were using z$ as a site, when it is not a Stream.r4   r   zan entry for this object z is not stored in stream )r   r   elementOffsetAttributeErrorr   r(   _endElementsr   AT_ENDhighestTimer   r   r`   r   )rX   rD   r   a	tryOrigin
originMemo	maxSearchaeepossiblyNoneTryOriginses              r>   r   zMusic21Object.getOffsetBySite  sf   b <$$$'	A'+IJI) $ ..y.M ..y.N )< H/ & ()$1UV (   D$5$55(#0#7#77#'#3#33,0OO,B,B),4 5I)}
2NN2i=1NI 1} %# (  	 +D83LTHU	sw   D
 )A D
 D
 	DA**D6DDD
 D&D'D
 ,AD=D
 DD
 
	D*D%%D*c                r    ||j                  | |       yt        |t              rt        |      }|| _        y)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)setElementOffsetr[   r   floatr   )rX   rD   ro   s      r>   setOffsetBySitezMusic21Object.setOffsetBySite+  s6    \ !!$.%%e %Dr=   c                    	 | j                  |      S # t        $ r Y nw xY w| j                         D ]  }|j                  |u s|j                  c S  t        d|  d|       )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   contextSitesrD   rE   )rX   rD   css      r>   getOffsetInHierarchyz"Music21Object.getOffsetInHierarchy`  sp    x	''-- 		
 ##%Bww$yy  & xv-EdVLMMs    	c                T   | j                   j                  d      }g }|t        j                  |      s|g}|D ]_  }|||j	                  |j
                         $|D ]7  }||j
                  j                  v s|j	                  |j
                          _ a t        |d       S )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                "    | j                         S rO   )	sortTuple)xs    r>   <lambda>z/Music21Object.getSpannerSites.<locals>.<lambda>   s
    !++-r=   )key)r   getSitesByClassr
   
isIterablert   r   classSetr|   )rX   spannerClassListfoundpostobjspannerClasss         r>   getSpannerSiteszMusic21Object.getSpannerSites  s    L 

**+;<&('$$%56$4#5 C{'CJJ'$4L#szz':'::CJJ/ %5  d 788r=   Tc                   g }| j                   j                  d      D ]i  }|j                  s| |vs|r9d|j                  vs&d|j                  vs5|j	                  t        |             P|j	                  t        |             k |D ]P  }| j                   j                  |       | j                         }|1t        |      |k(  s@| j                  d       R y)aA  
        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   classesrt   r`   
removeById_getActiveSite_setActiveSite)rX   excludeStorageStreamsorphanssrw   ps         r>   r   zMusic21Object.purgeOrphans  s      &&4&8A zzd!m((		9 0		 Ar!u-NN2a5) 9 AJJ!!!$##%A}A!##D) r=   c                <    | j                   j                  |       y)zU
        Remove references to all locations in objects that no longer exist.
        )rescanIsDeadN)r   purgeLocations)rX   r5  s     r>   r6  zMusic21Object.purgeLocations#  s     	

!!|!<r=   )getElementMethodsortByCreationTimefollowDerivationpriorityTargetOnlyc                    y rO   r<   rX   	classNamer7  r8  r9  r:  s         r>   getContextByClasszMusic21Object.getContextByClass.       	r=   c                    y rO   r<   r<  s         r>   r>  zMusic21Object.getContextByClass:  r?  r=   c                   t         j                  t         j                  t         j                  t         j                  gt         j
                  t         j                  t         j                  t         j                  t         j                  gt         j                  t         j                  t         j                  t         j                  t         j                  t         j                  gt         j                  t         j                  t         j                  t         j                  g}t         j                  t         j                  g}fd}d fd}	t         vrt        d       |r|rt        d      |v r j                  v r S  j                  d|||      D ]  \  }
}}|dv r, ||
d|	      }| |	||
      r	 |
j                  |       |c S |dk7  s=v r!r|
j                  v r|v r |
u rn|vr|
c S  ||
d|	      }| |	||
      r	 |
j                  |       |c S v sr|
j                  v s|v r |
u r|
c S  y
# t        $ r Y |c S w xY w# t        $ r Y |c S w xY w)a#  
        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                v   	sdn	f}| j                  ||      }
v rc
t        j                  t        j                  fv r!t	        j
                  |j                        }n t        j
                  |j                        }
v r|j                  |      }n|j                  |      }||j                  }|S y)a  
            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rE   )asTreer   BEFORE_OFFSETAT_OR_AFTER_OFFSETr   modifyrE   r   getNodeBeforegetNodeAfterpayload)	checkSiterC  innerPositionStartrD  siteTreecontextNoderL  BEFORE_METHODSOFFSET_METHODSr=  r7  s          r>   payloadExtractorz9Music21Object.getContextByClass.<locals>.payloadExtractorW  s     %.I<I ''9'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                    	 j                  |d      }| j                  |d      }v r||k  ryv r||kD  ryy# t        $ r Y yw xY w)a  
            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   )checkContextElrM  selfSortTuplecontextSortTupleAFTER_METHODSrQ  r7  rX   s       r>   
wellFormedz3Music21Object.getContextByClass.<locals>.wellFormedt  sw    j $yt T#1#;#;I\`#;#a   >1mFV6V !]2}GW7W ! " 
 s   &> 	A
	A
zInvalid getElementMethod: z;priorityTargetOnly and followDerivation cannot both be TrueT)returnSortTuplesr8  r9  r:  )elementsOnlyelementsFirstF)rC  rN  Nr\  semiFlatre   bool)r   rG  AFTER_OFFSETAT_OR_BEFORE_OFFSETrH  BEFOREAT_OR_BEFOREBEFORE_NOT_SELFAFTERAT_OR_AFTERAFTER_NOT_SELFr   r   r  coreSelfActiveSiter   )rX   r=  r7  r8  r9  r:  
AT_METHODSNOT_SELF_METHODSrS  rZ  rD   positionStart
searchType	contextElrY  rQ  rR  s   ```           @@@r>   r>  zMusic21Object.getContextByClassF  s   d ''&&--,,	
   ''&&--))
 &&%%%%,,((
 &&%%--,,	

 ))((

	: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	4-H//	: %$ ^+$5!* )T]] :'+;;)1AA#,T5?@MO	 (Z	4-H//	: %$$6!* )T]] :'+;;#[0
d I * $$* * $$s$   I$I0	I-,I-0	I?>I?)callerFirstr   offsetAppendr8  priorityTargetr9  r:  c                    y rO   r<   )	rX   r[  ro  r   rp  r8  rq  r9  r:  s	            r>   r  zMusic21Object.contextSites       	r=   )ro  r   rp  r8  rq  r[  r9  r:  c                    y rO   r<   )	rX   ro  r   rp  r8  rq  r[  r9  r:  s	            r>   r  zMusic21Object.contextSites+  rs  r=   c          	   #    K   ddl m}	 |
t               }|| }| j                  r| |vrt	        j
                  d|       }
|
j                  }t        j                  d| d|        |r:|
j                         j                  dt        d      	      }t        |
||       nt        |
d|       |j                  |
       ||d
u r| j                  }nt        j                  d|        | }| j                   j#                  ||d      D ]q  }||v r	t%        ||	j&                        r 	 | j                  |      }|r| j)                  |      }n|j+                  |       }t-        ||z         }|j                  |      }|j                  }|rt        |||       nt        ||j0                  |       |j                  |       t        j                  d| d|j3                                 |j5                  |||j0                  d|      D ]c  \  }}}|r||ur nW|j0                  }|j                  |      }||vs2|rt        |||       nt        |||       |j                  |       e |sr n |r#|j6                  j9                         D ]  }t        j                  d| d|        |j5                  d|dd|      D ]  }|j:                  |v rt        j                  d| d       t        |j:                  |j0                  j                  |d   j0                  |z         |j<                        }|r| n7t        |j:                  |j0                  j0                  |j<                         |j                  |j:                           t        j                  d       y# t.        $ r Y w xY ww)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)rE   priorityFzsortByCreationTime T)r8  rq  r)  rE  zlooking in contextSites for z with position )ro  r   rp  r[  r8  zlooking now in derivedObject, z	Yielding z  from derivedObject contextSitesr4   z%--returning from derivedObject search)music21r$   r   r   r   r   recursionTypeenvironLocal
printDebugr  rI  r  rK   rB   r   r   r   r+  r[   r  r   r  r   r   rE   	shortReprr  r   chainrD   rG   )rX   ro  r   rp  r8  rq  r[  r9  r:  r$   
streamSelfry  rW  topLevelsiteObjstoffsetInStream	newOffsetpositionInStreaminStreamPos	recurTypeinStreamOffsethypotheticalPositionderivedObjectderivedCsTupleoffsetAdjustedCsTuples                             r>   r  zMusic21Object.contextSites:  s    X 	#<5DK}}T!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 $'6#8#89^^G,# &*%9%9'%BN%,%:%:4%@N">L#@A	#%99I9#>  $11M&w0@-PP"7,<,C,C]SSHHW##.wi!"2"<"<">!?AB 5<4H4H'-44!%#5 5I 50+y &(.*H!,!3!3 (8'>'>n'>'U$4' (.x9MyYY*8^YOOHHX&354 "y?| !)!4!4!:!:!<''4$o%8HI '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HS " s9   D+O.AN>CO6O?D?O>	OO
OOc              #     K   | j                  |      }|)| |j                  |t        j                        }|(yyw)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r7  )r>  r   rG  )rX   r=  els      r>   getAllContextsByClassz#Music21Object.getAllContextsByClass  sD     * ##I.nH%%i-B]B]%^B ns
   ;A A )activeSiteOnlyc               V   t        | j                  d|            }d}| }|rw|j                  |t        j                  | |      }d}|D ]6  \  }}	}
||u st        j                  d|      }|r|d   | ur|d   c S |}d} n |r|dz  }k|| ur|S |dz  }|rw|dk(  rt        d	      y
)aZ  
        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[  r:  r   r=  r7  r9  r:  Frv  r   r4   zMaximum recursion!N)rr   r  r>  r   rh  r   r   r(   )rX   r=  r  allSiteContexts
maxRecursethisElForNextnextElcallContinuesingleSiteContextunused_positionInContextunused_recurseTypes              r>   nextz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
T!!OJ3 6 ?"#788 r=   c                  | j                  |t        j                  | |      }d}| j                  r#|!|j	                         D ]  \  }}}|| u sd} n |r|| ur|s|S | j
                  }|y|j                  |gd      }	|	j                  | j                               }
|
|||j                  v r|S y|
j                  S )al  
        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)rD  rC  )r>  r   re  r   r  r   rF  rJ  r  r   rL  )rX   r=  r  prevElisInPartr  unused1unused2activeSrF  prevNodes              r>   previouszMusic21Object.previous	  s    j '')9F9V9V=K9K;I ( * ==V/(.(;(;(=$GW:#H )>
 fD(M ooG^^yk5^IF++DNN,<=H$	W5E5E(E"N'''r=   c                ~    t         r,| j                  y t        j                  | j                        S | j                  S rO   )r   r   r
   unwrapWeakrefr   s    r>   r.  zMusic21Object._getActiveSitev	  s9    ' ++D,<,<==###r=   c                    |	 |j                  |       }|| _        nd | _        t        r%|d | _        y t        j                  |      | _        y || _        y # t        $ r}t        d|  d|       |d }~ww xY w)Nz$activeSite cannot be set for object z not in the Stream )r  r   r   r   r   r
   wrapWeakref)rX   rD   storedOffsetr  s       r>   r/  zMusic21Object._setActiveSite	  s     #11$7 ,8D( ,0D(|#' #)#5#5d#; #D+ " $"V#6tf> s   A 	A7 A22A7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                   | j                   }|2| j                  }|| j                  xs dS 	 |j                  |       }|S | j                  }|S # t        $ r, t
        j                  d       d| _        | j                  }Y |S w xY w)aU  
        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   rz  r{  r   )rX   activeSiteWeakRefr   os       r>   rE   zMusic21Object.offset	  s    R !,,(J! 33:s:&,,T2  !!A " &''[]"&%% &s   A 1BBc                    	 t        |      }| j                  | j                  j                  | |       y || _        y # t        $ r |}Y >w xY wrO   )r   r   r   r  r   )rX   ro   rE   s      r>   rE   zMusic21Object.offset:
  sN    	E]F ??&OO,,T6: &D  	F	s   > AAc                   |du r| j                   }n|}|| j                  }n	 |j                  | d      }|t
        j                  k(  rd}d}nt        j                  t        |      }d}| j                  s| j                  j                  sdnd}| j                  j                  t        |            r-| j                  j                   t        |         j"                  }nE| j                   7| j                  j                   t        | j                            j"                  }nd}t%        ||| j&                  | j(                  ||      S # t        $ r |r | j                  }Y /w xY w)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   rE   r  r   r   r   r  r   r   r   r   r   isGracer   	hasSiteIdr`   siteDictglobalSiteIndexr   rw  r   )	rX   useSiterU  useSiteNoFalsefoundOffsetrE   atEnd
isNotGraceinsertIndexs	            r>   r  zMusic21Object.sortTupleH
  s@   V 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                ~    | j                   t        d      | _         | j                   }t        j                  r|J |S )zO
        Get and set the duration of this object as a Duration object.
        r   )r   r   r   TYPE_CHECKING)rX   d_outs     r>   r   zMusic21Object.duration
  s:     >>!%a[DN??$$$r=   c                    d}| j                   d | j                   _        d}	 |j                  }|| _         | |_        |r| j                  d|d       y y # t        $ r}t        d|       |d }~ww xY w)NFTr   )changedElementr   z$this must be a Duration object, not )r   r   r   informSitesr  r   )rX   durationObjdurationObjAlreadyExistsqlr  s        r>   r   zMusic21Object.duration
  s    #( >>%$(DNN!'+$	**B(DN!%K'  JQS!TU (  	6{mD	s   0A 	A2A--A2c                    | j                   j                         D ]"  }t        |d      s|j                  dd       $ y)a  
        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  )rX   changedInformationr2  s      r>   r  zMusic21Object.informSites
  s7     !Aq/0%%5D%I "r=   c                    | j                   S rO   )r   r   s    r>   _getPriorityzMusic21Object._getPriority  s    ~~r=   c                    t        |t              st        d      | j                  |k7  r|| _        | j	                  d|d       yy)zL
        value is an int.

        Informs all sites of the change.
        z!priority values must be integers.rw  )r  rw  N)r[   r   r*   r   r  rn   s     r>   _setPriorityzMusic21Object._setPriority  sE     %%"#FGG>>U""DN
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                f   |
t         d   }n|j                  d      r|dd }|dk(  rd|d<   t        j                  |      \  }}|t	        d|       |j                  d      }|d	   }|dd }t        j                  |      }|t	        d|        |       }	 |	j                  | f|||d
|S )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)rz  
startswithr
   
findFormatr)   splitfindSubConverterForFormatwrite)
rX   r  r  r   regularizedConverterFormat
unused_ext
formatSubsr  scClassformatWriters
             r>   r  zMusic21Object.write@  s    * ;}-C^^C ab'C%<#'HZ 171B1B31G."J%-(+UVYUZ)[\\YYs^
m^
223MN?(+UVYUZ)[\\y!|!!$ .&@%'-7. %-	. 	.r=   c                    t        |       S )z
        Return a text representation possible with line
        breaks. This method can be overridden by subclasses
        to provide alternative text representations.
        reprr   s     r>   	_reprTextzMusic21Object._reprTextp       Dzr=   c                    t        |       S )z
        Return a text representation without line breaks. This
        method can be overridden by subclasses to provide
        alternative text representations.
        r  r   s    r>   _reprTextLinezMusic21Object._reprTextLinex  r  r=   c                   |)t        j                         r	 t        d   }nKt        d   }nA|j                  d      r|dd }n*t        j                         r|j                  d      rd|z   }t        j                  |      \  }}|t        d	|       |j                  d      }|d
   }|dd }t        j                  |      } |       }	 |	j                  | |f||d|S # t        j                  t
        f$ r d}Y w xY w)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
   runningInNotebookrz  r   EnvironmentExceptionKeyErrorr  r  r)   r  r  show)
rX   r  r  r   r  r  r  r  r  r  s
             r>   r  zMusic21Object.show  s#   8 ;'')1&':;C #<0^^C ab'C%%'CNN6,Bs"C171B1B31G."J%-(+UVYUZ)[\\YYs^
m^
223MNy |  !;-%(,6- $,	- 	-' $88(C 10C1s   	C# #D D)r9  includeNonStreamDerivationsc                   g }| }d}|dkD  rk|dz
  }|j                   }|/|du r)t        |d      r|j                  j                  }||S |}n|S |du s|j                  r|j                  |       |}|dkD  rk|S )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   rt   )rX   r9  r  r#  focusendMe	candidatealts           r>   containerHierarchyz Music21Object.containerHierarchy  s    z aiAIE ((I #t+|0L  **99C{#$'	K*d2i6H6HI&E) ai* r=   )retainOriginaddTiesdisplayTiedAccidentalsc                  ddl m} ddl m} t        |      }|| j                  j
                  kD  r&t        d| j                  j
                   d| d      |du r| }nt        j                  |       }t        j                  |       }t        ||j                        r	g }	|	|_        g }
dD ]R  }t        ||      st        ||      }t        ||g        t        ||g        |D ]  }t        |d	      r,|j                  ||g      }|D ]  }|
j!                  |        <t        |d
      r|j"                  dk(  rt        ||      }|j!                  |       u|j"                  dk(  rt        ||      }|j!                  |       t        ||      }|j!                  |       t        ||      }|j!                  |       t        ||      }|j!                  |       t        ||      }|j!                  |        U t%        || j                  j
                  z
        dk  r| j                  j
                  }| j                  j
                  |z
  }| j                  j
                  |z
  }t'               }||_        t'               }||_        ||_        ||_        |rt        ||j(                  |j*                  f      rd}|j,                  e|j,                  j.                  dk(  rd}nc|j,                  j.                  dk(  rd}d|j,                  _        n6|j,                  j.                  dk(  rd}nt-        j0                  d      |_        t        ||j(                  |j*                  f      rt-        j0                  |      }||_        n|rt        ||j2                        rt        ||j2                        rt5        |j6                  |j6                        D ]  \  }}d}|j,                  e|j,                  j.                  dk(  rd}nc|j,                  j.                  dk(  rd}d|j,                  _        n6|j,                  j.                  dk(  rd}nt-        j0                  d      |_        t-        j0                  |      |_         |rt        ||j8                        rt        ||j8                        rt;        |j<                        D ]~  \  }}|j<                  |   }|j>                  "|j>                  /|s,|j>                  j@                  dk7  sKd|j>                  _!        ]d|j>                  _         d|j>                  _!         |j                  j
                  dkD  rtE        ||g      }ntE        |dg      }|
r|
|_#        |S )a3  
        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) at this quarterLength ()T)expressionsarticulationssplitClient	tieAttachfirstlaststopNstartcontinuez	even-tiedFr   )$rx  r  r  r   r   r   r   r   r   r[   GeneralNotelyricsr   r   setattrr   rt   r  absr   Note	Unpitchedr   r   TieChordr{   notesNotRest	enumeratepitches
accidentaldisplayTypedisplayStatusrM   rW   )rX   r   r  r  r  r  r  r  eRemainemptyLyricsrW   listTypetempthisExpressionspannersr2  eListeRemainListlenEndlenStartd1d2forceEndTieTypenewTie	componentremainComponentrw   r3  remainPr  s                                 r>   splitAtQuarterLengthz"Music21Object.splitAtQuarterLength  s   f 	"  }-4==666#+DMM,G,G+H I**7; 
 4Ad#A--% gt//0,.K(GN8Hq(#q(+8R(2.&*N~}=#1#=#=q'l#K!)A'..q1 "* =)33w>$+Ax$8E!LL8+55?*1'8*DK'..~>$+Ax$8E!LL8*1'8*DK'..~> '8 4^4&-gx&@#**>:+ '+ 98 }t}}:::;a? MM77M,,}<==..7Z#Z!
 z!dii%@A$Ouu  55::(&0O UUZZ6)&,O!+AEEJUUZZ:-&0O ('DIIt~~#>?1$Au{{3
7EKK8X.1!''7==.I*	?"(==, !}}))W4*4 #++v5*0-7	*"++z9*4 %(GGG$4IM&)ggo&>#% /J, z!T\\2z'4<<7X!!)),1!//!,<<+0B0B0N1<<33{B?DG..<9D**6;?**8 - ))C/a\*BaY'B(BN	r=   c                <   t        t        |            | j                  j                  k7  r%t	        d| d| j                  j                         t        |      dk(  rt        t        j                  |       g      S |st	        d| d      g }g }t        j                  |       }|dd D ]G  }|j                  |||      }|\  }	}|j                  |	       |j                  |j                         I ||j                  |       t        |      }
||
_        |
S )	a  
        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)r  r  )r   sumr   r   r)   rz   rM   r   r   r'  rt   extendrW   )rX   quarterLengthListr  r  r  rW   r  qlSplitr  newElstOuts              r>   splitByQuarterLengthsz#Music21Object.splitByQuarterLengths  s7   0 #'()T]]-H-HH(F$%R(C(C'DF   !Q&d 3455"(<=N<OqQS S &(--% )"-G--g6=E[ . ]B  NE7LLr~~. . LL!E"'r=   c                    | j                   j                         }| j                   j                  D cg c]  }t        |j                  |z         }}| j                  |      }|S c c}w )aL  
        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   r0  )rX   atmcr,  	splitLists        r>   splitAtDurationszMusic21Object.splitAtDurationsP  sc    T mm557DHMMD\D\]D\qVAOOc$9:D\]../@A	 ^s   A'c                    d}| j                   .| j                   j                  r| j                   j                  }|S | j                         D ]   }|d   }|j                  s|j                  }" |S )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numberr  )rX   mNumberr  ms       r>   measureNumberzMusic21Object.measureNumber  sk    x ??&4??+D+Doo,,G  '')qE;;hhG	 *
 r=   c                   ddl m} | j                  }|Ot        ||j                        r9|j                  |       }|r$|j                  rt        ||j                  z         }|S | j                  |j                  d      }|:	 |j                  |       }|r$|j                  rt        ||j                  z         }|S | j                  }|S # t        $ r | j                  }Y |S w xY w)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)r8  )rx  r$   r   r[   Measurer  paddingLeftr   r>  r   rE   )rX   includeMeasurePaddingr$   r  offsetLocalr<  s         r>   _getMeasureOffsetzMusic21Object._getMeasureOffset
  s    8 	# //:gv~~#F!//5K$)<)<$[73F3F%FG. # &&v~~$&OA}."#//$"7K,&,[1==-H&I 	 #kk  & ."&++K .s   7C C$#C$c                    ddl m} | j                  |j                  t        j
                        }|t        d      |S )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)rx  r"   r>  TimeSignaturer   rb  r)   )rX   r"   tss      r>   _getTimeSignatureForBeatz&Music21Object._getTimeSignatureForBeatG  sF     	"'+'='=*>> (> (
 :()]^^	r=   c                    	 | j                         }|j                  |j                  |             S # t        $ r t	        d      cY S w xY w)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)rG  getBeatProportion$getMeasureOffsetOrMeterModulusOffsetr)   r  rX   rF  s     r>   beatzMusic21Object.beatV  sL    f	 ..0B''(O(OPT(UVV% 	 <	    /2 A	A	c                    	 | j                         }|j                  |j                  |             S # t        $ r Y yw xY w)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.
        rI  )rG  getBeatProportionStrrK  r)   rL  s     r>   beatStrzMusic21Object.beatStr  sE    F	..0B**2+R+RSW+XYY% 		s   /2 	>>c                    	 | j                         }|j                  |j                  |             S # t        $ r t	        d      cY S w xY w)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   )rG  getBeatDurationrK  r)   r   rL  s     r>   beatDurationzMusic21Object.beatDuration  sK    f	..0B%%b&M&Md&STT% 	A;	rN  c                    	 | j                         }|j                  |       }|j                  |dd      S # t        $ r t	        d      cY S w xY w)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permitMeterModulusrI  )rG  rK  getAccentWeightr)   r  )rX   rF  meterModuluss      r>   beatStrengthzMusic21Object.beatStrength  sc    j	 ..0BBB4HL%%l9=9> & @ @ & 	 <	 s   47 AAc                    ddl m} | j                  j                  dk(  ry| j	                  |j
                        }|t        d      S |j                         }|j                  | j                        S )Nr   tempor   rI  )	rx  r]  r   r   r>  TempoIndicationr  getSoundingMetronomeMarkdurationToSeconds)rX   r]  timms       r>   _getSecondszMusic21Object._getSecondsp  sb    !==&&#-##E$9$9::<((*##DMM22r=   c                ,   ddl m} | j                  |j                        }|t	        d      |j                         }|j                  |      | _        | j                  j                  d      D ]!  }| |j                  v s|j                          # y )Nr   r\  z4this object does not have a TempoIndication in SitesTr(  )rx  r]  r>  r^  r)   r_  secondsToDurationr   r   r  elementsr  )rX   ro   r]  ra  rb  r2  s         r>   _setSecondszMusic21Object._setSeconds}  s}    !##E$9$9::()_``((*,,U3D1Aqzz!%%' 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.
        )	NNNNNNNr   N)r`   zstr | int | Noner   zGroups | Noner   zSites | Noner   zDuration | Noner   stream.Stream | Noner   zStyle | Noner   zEditorial | NonerE   r   r   zOffsetQLIn | None)re   zt.TypeGuard[t.Self])re   r   )re   	int | str)r   ri  )r]   r,   re   rf   rO   )r   dict[int, t.Any] | Noner   zset[str] | Nonere   t.Self)r   rj  re   rk  )re   dict[str, t.Any])r   rl  )re   rl   r_  )re   r   )r   r   )re   r   )r   r   )re   r   )ro   r   )re   r   )r   zDerivation | Nonere   rf   )re   rf   )rD   rh  r   t.Literal[False]re   r   )rD   rh  r   r`  re   zOffsetQL | OffsetSpecial)rD   rh  ro   r   )rD   rh  re   r   )r!  zIterable | Nonere   zlist[spanner.Spanner])T)F)r=  ztype[_M21T]re   z_M21T | None)r=  
str | Nonere   zMusic21Object | None)r=  ztype[_M21T] | str | Noner7  r   re   z_M21T | Music21Object | None)r[  zt.Literal[True]rp  r   r8  t.Literal['reverse'] | boolre   z'Generator[ContextSortTuple, None, None])rp  r   r8  ro  r[  rm  re   z#Generator[ContextTuple, None, None])rp  r   r8  ro  r[  r`  re   z6Generator[ContextTuple | ContextSortTuple, None, None])r=  z type[Music21Object] | str | None)rD   rh  )FF)r  z't.Literal[False] | stream.Stream | NonerU  r`  re   r   )re   r   )r  r   )NN)r  rn  r  z"str | pathlib.Path | IOBase | Nonere   zpathlib.Path)re   rM   )TF)r,  z&list[int | float | fractions.Fraction]re   rM   )re   z
int | None)rA  r`  re   r   )re   zmeter.TimeSignature)re   zfractions.Fraction | float)re   r  )ro   r   re   rf   )Jr9   r:   r;   rg   r   rI   r   r   r   r   r   r   rY   r\   r_   propertyr`   setterr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r&  r   r6  r   rd  r>  r  r  r  r  r.  r/  r   rE   r  r   r  r  r  rw  r  r  r  r  r  r'  r0  r7  r=  rC  rG  rM  rQ  rT  rZ  rc  rg  secondsrh   ri   s   @r>   r,   r,   U  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P+Z'0R4. + +*  0   ' '*  : \\ 
 + +  , , !  ! F ) ), 
 +0	  (	
 
  
 $	  	
 
   $	{ { 	{
 
 {z3&03&)3&jGN GN 
GNT ;?W9*7W92W9r*B= 
 '33  		 
	 	 
 '33  		 
	 	 +8*D*D  S'S (	S 
"Sl 
 !$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PH>PH(,PH !PHf   __ &J
P $HL +/-.-. )-.
 
-.`7-~ $)	Uv $@ 
@J $	9=9
 
9vmb F FP;z V  V p & &P 6 6p \  \ |3	( {K O6 OGr=   r,   r   _m21ObjDefaultDefinedKeysc                  Z     e Zd ZU dZdZdgZddiZded<   dd fdZd Z	dd	Z
dd
Z xZS )r-   a  
    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.
    )r$  r$  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    || _         t        |   di | y )Nr<   )r$  rP   rY   )rX   r$  r   rU   s      r>   rY   zElementWrapper.__init__F  s     $8$r=   c                   t        | j                        dd }t        t        | j                              dkD  r|dz  }|d   dk(  r|dz  }| j                  d| j                   d| j
                   d|S d	| j
                   d|S )
Nr      z...<>r   z offset=z obj=zoffset=)rl   r$  rz   r   r`   rE   )rX   shortObjs     r>   r   zElementWrapper._reprInternalN  s    M1R(s488}"H{c!C88	$++eH<HHT[[Mxl;;r=   c                *   |dk(  rt         j                  | d|       y || j                  v rt         j                  | ||       t         j                  | d      }|t        vr|t        ||      rt        |||       y t         j                  | ||       y )Nr$  )r   r   r   __getattribute__rs  r   r	  )rX   namero   	storedObjs       r>   r   zElementWrapper.__setattr__Z  s    5=tUE2 4== tT51 ++D%8	11)It,ItU+ tT51r=   c                |    t         j                  | d      }|t        d|d      t        j                  ||      S )a%  
        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
        r$  zCould not get attribute z in an object-less element)r,   r|  r  r   )rX   r}  r~  s      r>   __getattr__zElementWrapper.__getattr__n  sE     "224?	 #;D8C]!^__&&y$77r=   rO   )r$  rd   )r}  rl   ro   rd   re   rf   )r}  rl   re   rd   )r9   r:   r;   rg   r   r   r   rI   rY   r   r   r  rh   ri   s   @r>   r-   r-     sD    ^~ "J N!I~ %
<2(8r=   r-   c                      e Zd ZdZd Zy)Testz4
    All other tests moved to test/test_base.py
    c                2    ddl m}  || t                      y )Nr   )testCopyAll)music21.test.commonTestr  globals)rX   r  s     r>   testCopyAndDeepcopyzTest.testCopyAndDeepcopy  s    7D')$r=   N)r9   r:   r;   rg   r  r<   r=   r>   r  r  }  s    %r=   r  __main__)re   zfrozenset[str])crg   
__future__r   r   collections.abcr   r   r   	functoolsimportlib.utilr   typingr   r   unittestr3   weakrefmusic21._versionr   r	   rx  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(   Environmentrz  _missingImportmodNameloaderrt   r   getMissingImportStrr)   r*   
NamedTuplerB   rK   rR   rM   rr   r+   r   r   r   cacher   ProtoM21Objectr,   dirrs  rI   r-   TestCaser  r   r9   mainTestr<   r=   r>   <module>r     s3  4 #  /   $      :  = - 5  ) 8 '     ? ?  J J ??AIIg%ABE (  00 &{&&v.&GwF~g& '
 J>14&44^D!+ 	 	-	\:: 		|44 	,1<< ,
,q|| ,8% 8|XT X~ !( !8  ) )@B:G** B:Lt .33}3G-H ? H]8] ]8@%8 % ^,
 zG r=   