
    3jt                    D   d 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	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mZ ddlmZmZ ddlmZmZ ej8                  rddlmZ  G d de
      Z G d dej@                        Z!e"dk(  rddlZ ejF                  e!       yy)a  
the Stream Core Mixin handles the core attributes of streams that
should be thought of almost as private values and not used except
by advanced programmers who need the highest speed in programming.

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

All functions here will eventually begin with `.core`.
    )annotationsN)Fraction)Music21Object)OffsetSpecial)opFrac)OffsetQLOffsetQLSpecial
M21ObjType)spanner)tree)StreamExceptionImmutableStreamException)StreamIteratorRecursiveIterator)Streamc                      e Zd ZdZd fdZddd	 	 	 	 	 ddZdd	 	 	 ddZddd		 	 	 	 	 dd
Zddddd	 	 	 	 	 	 	 	 	 d dZddd	 	 	 d!dZ	d Z
dddZd"dZed        ZddddZd ZddddddZddddd	 	 	 	 	 	 	 	 	 d#dZ xZS )$
StreamCorez
    Core aspects of a Stream's behavior.  Any of these can change at any time.
    Users are encouraged only to create stream.Stream objects.
    c                j    t        |   di | i | _        g | _        g | _        d| _        d| _        y )NT )super__init___offsetDict	_elements_endElementsisSortedisFlat)selfkeywords	__class__s     @/DATA/.local/lib/python3.12/site-packages/music21/stream/core.pyr   zStreamCore.__init__1   s@    $8$
 NP /1 24    FT)
ignoreSortsetActiveSitec                  d}|sz| j                   du rl| j                  }||k  rd}nX||k(  rS| j                  sd}nD| j                  d   j                         }|j                         j	                  |      }||k  rd}| j                  ||d|       |j                  j                  |        | j                  j                  |       |S )a  
        N.B. -- a "core" method, not to be used by general users.  Run .insert() instead.

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

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

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

        Do not mix coreInsert with coreAppend operations.

        Returns boolean if the Stream (assuming it was sorted before) is still guaranteed
        to be sorted.  (False doesn't mean that it's not sorted, just that we can't guarantee it.)
        If you don't care and plan to sort the stream later, then use `ignoreSort=True`.

        No need to opFrac before getting here -- the inner routine will do it for us.
        FT)offset
addElementr#   )	r   highestTimer   	sortTuplemodifycoreSetElementOffsetsitesaddappend)	r   r&   elementr"   r#   storeSortedhthighestSortTuplethisSortTuples	            r    
coreInsertzStreamCore.coreInsertG   s    @ 
 }}$%%;"&K6\>>&*+/>>"+=+G+G+I((/(9(9(;(B(B&(B(Q+m;*.K!!'	 	" 	
 	$ 	g&r!   )r#   c               8   | j                   }| j                  ||d       |j                  j                  |        |r| j	                  |       | j
                  j                  |       | j                  t        ||j                  j                  z                y)ar  
        N.B. -- a "core" method, not to be used by general users.  Run .append() instead.

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

        When using this method, the caller is responsible for calling
        Stream.coreElementsChanged after all operations are completed.
        Tr(   N)r)   r,   r-   r.   coreSelfActiveSiter   r/   _setHighestTimer   durationquarterLength)r   r0   r#   r2   s       r    
coreAppendzStreamCore.coreAppend   s    " !!'2$!?$##G,g&
 	VB)9)9)G)G$GHIr!   r'   c                   	 t        |      }t	        |      }|s || j
                  vrt        d| d|  d      ||f| j
                  |<   |r| j                  |       yy# t        $ r$}|t        vrt        d|d|       |Y d}~{d}~ww xY w)a  
        Sets the Offset for an element, very quickly.
        Caller is responsible for calling :meth:`~music21.stream.core.coreElementsChanged`
        afterward.

        >>> s = stream.Stream()
        >>> s.id = 'Stream1'
        >>> n = note.Note('B-4')
        >>> s.insert(10, n)
        >>> n.offset
        10.0
        >>> s.coreSetElementOffset(n, 20.0)
        >>> n.offset
        20.0
        >>> n.getOffsetBySite(s)
        20.0
        zCannot set offset to z for Nz"Cannot set the offset for element z, not in Stream .)r   	TypeErrorr   r   idr   r8   )r   r0   r&   r(   r#   teidEls          r    r,   zStreamCore.coreSetElementOffset   s    6	`F^F
 '{d$*:*::!4WI=MdVSTUW W"('!2##G,   	`]*%(=fZuWI&VW]__ +	`s   A   	B)BBN)updateIsFlatclearIsSortedmemo	keepIndexc                  t        | dd      st        d      |g }t        |       |v ry|j                  t        |              | j                  T| j                  j
                  }|dv r:t        j                  d| j                  j                        }|j                          | j                  D ]  }|j                  |        |rd| _        |r-d| _        | j                  D ]  }|j                  sd| _         n | j                   rGd}	|rd	| j                   v r| j                   d	   }	| j                          |r|	|	| j                   d	<   yyyy)
a  
        NB -- a "core" stream method that is not necessary for most users.

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

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

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

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

        >>> a.coreAppend(stream.Stream())
        >>> a.isFlat  # this is wrong.
        True

        >>> a.coreElementsChanged()
        >>> a.isFlat
        False
        _mutableTzBcoreElementsChanged should not be triggered on an immutable streamN)flatsemiflatzmusic21.stream.Stream)rE   Findex)getattrr   r@   r/   _derivationmethodtcastorigin
clearCacher-   coreElementsChangedr   r   r   isStream_cache)
r   rC   rD   rE   rF   sdmrQ   
livingSitee
indexCaches
             r    rS   zStreamCore.coreElementsChanged   sQ   F tZ.*T  <Dd8tBtH '""))C**23&&9P9=9I9I9P9P3R!!#
 **J***5 % !DMDK^^ ::"'DK $ ;;JW3![[1
 OOZ3'1G$ 4y r!   )recursedeepc                   ddl m} |rt        j                  |       }nt        j                  |       }||j                  _        |r+|r)t        ||j                        r|j                  |d       |S )a  
        *This is a Core method that most users will not need to use.*

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

        >>> s = stream.Stream()
        >>> n = note.Note()
        >>> s.append(n)
        >>> s2 = s.coreCopyAsDerivation('exampleCopy')
        >>> s2.derivation.method
        'exampleCopy'
        >>> s2.derivation.origin is s
        True
        >>> s2[0].derivation.method
        'exampleCopy'
        r   )streamT)rZ   )	music21r]   copydeepcopy
derivationrN   
isinstancer   setDerivationMethod)r   
methodNamerZ   r[   r]   posts         r    coreCopyAsDerivationzStreamCore.coreCopyAsDerivation3  s[    ( 	#==&D99T?D!+t
4 ?$$Z$>r!   c                    | j                   D ]  }t        |      |k(  s|c S  | j                  D ]  }t        |      |k(  s|c S  y)aW  
        NB -- a "core" stream method that is not necessary for most users.

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

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

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

        Used by spanner and variant.

        >>> s = stream.Stream()
        >>> n1 = note.Note('g')
        >>> n2 = note.Note('g#')
        >>> s.append(n1)
        >>> s.coreGetElementByMemoryLocation(id(n1)) is n1
        True
        >>> s.coreGetElementByMemoryLocation(id(n2)) is None
        True
        >>> b = bar.Barline()
        >>> s.storeAtEnd(b)
        >>> s.coreGetElementByMemoryLocation(id(b)) is b
        True
        N)r   r@   r   )r   objIdrX   s      r    coreGetElementByMemoryLocationz)StreamCore.coreGetElementByMemoryLocationS  sI    : A!u~   ""A!u~ # r!   )checkRedundancyc                  || u rt        d      t        |t              s0t        |t              rt        d      t        d|ddz   dz         |rxt	        |      }|| j
                  v r_| j                  | j                  fD ]7  }|D ]0  }||u st        d|dt	        |       d	| dt	        |        d
	       9 | j
                  |= |j                          y)a/  
        Before adding an element, this method performs
        important checks on that element.

        Used by:

          - :meth:`~music21.stream.Stream.insert`
          - :meth:`~music21.stream.Stream.append`
          - :meth:`~music21.stream.Stream.storeAtEnd`
          - `Stream.__init__()`

        Returns None or raises a StreamException

        >>> s = stream.Stream()
        >>> s.coreGuardBeforeAddElement(s)
        Traceback (most recent call last):
        music21.exceptions21.StreamException: this Stream cannot be contained within itself

        >>> s.append(s.iter())
        Traceback (most recent call last):
        music21.exceptions21.StreamException: cannot insert StreamIterator into a Stream
        Iterate over it instead (User's Guide chs. 6 and 26)

        >>> s.insert(4, 3.14159)
        Traceback (most recent call last):
        music21.exceptions21.StreamException: The object you tried to add to
        the Stream, 3.14159, is not a Music21Object.  Use an ElementWrapper
        object if this is what you intend.

        z-this Stream cannot be contained within itselfz_cannot insert StreamIterator into a Stream
Iterate over it instead (User's Guide chs. 6 and 26)z+The object you tried to add to the Stream, z, z6is not a Music21Object.  Use an ElementWrapper object zif this is what you intend.zthe object (z, id()=z" is already found in this Stream ()N)	r   rb   r   r   r@   r   r   r   purgeLocations)r   r0   rj   	idElementsearch_place	eInStreams         r    coreGuardBeforeAddElementz$StreamCore.coreGuardBeforeAddElementy  s   > d?!"QRR'=1'>2%KL L "=g[KJK/01 1 7ID,,, &*^^T5F5F$GL%1	$/"1".wkG NDDH87SUVZS[R\\]!_#  &2 %H $$Y/
 	 r!   c                    | j                  |t        j                  d       |j                  j	                  |        |r| j                  |       | j                  j                  |       y)z
        NB -- this is a "core" method.  General users should use .storeAtEnd() instead.

        Core method for adding end elements.
        To be called by other methods.
        Tr7   N)r,   r   AT_ENDr-   r.   r8   r   r/   )r   r0   r#   s      r    coreStoreAtEndzStreamCore.coreStoreAtEnd  sV     	!!'=+?+?D!Q$##G,  )r!   c                    d| j                   vs| j                   d   M| j                  t        j                  fd      }t        j                  t        |            | j                   d<   | j                   d   S )zZ
        A low-level object for Spanner management. This is a read-only property.
        spannerBundleF)classFilterrestoreActiveSites)rU   rZ   r   SpannerSpannerBundlelist)r   spannerss     r    rv   zStreamCore.spannerBundle  sd    
 $++-_1M1U||0BW\|]H+2+@+@h+PDKK({{?++r!   flatten	classListc                  t        t        |xs d      |f      }dt        |      z   }|| j                  vs| j                  |   1t        j
                  j                  | ||      }|| j                  |<   | j                  |   S )a  
        Convert stream to a :class:`~music21.tree.trees.TimespanTree` instance, a
        highly optimized data structure for searching through elements and
        offsets.

        >>> score = tree.examples.makeExampleScore()
        >>> scoreTree = score.asTimespans()
        >>> print(scoreTree)
        <TimespanTree {20} (0.0 to 8.0) <music21.stream.Score exampleScore>>
            <ElementTimespan (0.0 to 0.0) <music21.clef.BassClef>>
            <ElementTimespan (0.0 to 0.0) <music21.meter.TimeSignature 2/4>>
            <ElementTimespan (0.0 to 0.0) <music21.instrument.Instrument 'PartA: : '>>
            <ElementTimespan (0.0 to 0.0) <music21.clef.BassClef>>
            <ElementTimespan (0.0 to 0.0) <music21.meter.TimeSignature 2/4>>
            <ElementTimespan (0.0 to 0.0) <music21.instrument.Instrument 'PartB: : '>>
            <PitchedTimespan (0.0 to 1.0) <music21.note.Note C>>
            <PitchedTimespan (0.0 to 2.0) <music21.note.Note C#>>
            <PitchedTimespan (1.0 to 2.0) <music21.note.Note D>>
            <PitchedTimespan (2.0 to 3.0) <music21.note.Note E>>
            <PitchedTimespan (2.0 to 4.0) <music21.note.Note G#>>
            <PitchedTimespan (3.0 to 4.0) <music21.note.Note F>>
            <PitchedTimespan (4.0 to 5.0) <music21.note.Note G>>
            <PitchedTimespan (4.0 to 6.0) <music21.note.Note E#>>
            <PitchedTimespan (5.0 to 6.0) <music21.note.Note A>>
            <PitchedTimespan (6.0 to 7.0) <music21.note.Note B>>
            <PitchedTimespan (6.0 to 8.0) <music21.note.Note D#>>
            <PitchedTimespan (7.0 to 8.0) <music21.note.Note C>>
            <ElementTimespan (8.0 to 8.0) <music21.bar.Barline type=final>>
            <ElementTimespan (8.0 to 8.0) <music21.bar.Barline type=final>>
        r   timespanTreer}   )hashtuplestrrU   r   
fromStreamasTimespans)r   r~   r   hashedAttributescacheKeyhashedTimespanTrees         r    r   zStreamCore.asTimespans  s    >  yB!7 AB!C(8$994;;&$++h*?*G!%!<!<TELGP "= "R %7DKK!{{8$$r!   c                    | |_         y)z
        Set the activeSite of el to be self.

        Override for SpannerStorage, VariantStorage, which should never
        become the activeSite
        N)
activeSite)r   els     r    r8   zStreamCore.coreSelfActiveSite  s     r!   r~   r   useTimespansgroupOffsetsc               X   t         j                  rt        | t              sJ t	        t        |xs d      |||f      }dt        |      z   }|| j                  vs| j                  |   3t        j                  j                  | ||||      }|| j                  |<   | j                  |   S )a]  
        Returns an elementTree of the score, using exact positioning.

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

        >>> score = tree.examples.makeExampleScore()
        >>> scoreTree = score.asTree(flatten=True)
        >>> scoreTree
        <ElementTree {20} (0.0 <0.-25...> to 8.0) <music21.stream.Score exampleScore>>
        r   elementTreer   )rO   TYPE_CHECKINGrb   r   r   r   r   rU   r   r   asTree)r   r~   r   r   r   r   r   hashedElementTrees           r    r   zStreamCore.asTree  s     ??dF+++yB!7!(!-!-!/ 0 !3'7#884;;&$++h*?*G $ 6 6t?FAJDPDP	 !7 !R
 %6DKK!{{8$$r!   )rZ   requireAllPresentinsertconstrainingSpannerBundlec                  | j                   }|r| j                         }n| j                         }g }t        |      D ]]  }|j	                         D ]H  }	|	|v r|	|v r||	|vr|r"d}
|	j                         D ]
  }||vsd}
 n |
s8|j                  |	       J _ |s|S |r+|D ]  }	| j                  d|	        | j                  d       y)a  
        find all spanners that are referenced by elements in the
        (recursed if recurse=True) stream and either inserts them in the Stream
        (if insert is True) or returns them if insert is False.

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

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

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

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

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

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

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

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

        Now we'll remove the second note so not all elements of the Slur
        are present. This, by default, will not insert the Slur:

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

        But with `requireAllPresent=False`, the spanner appears!

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

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

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

        But the default acts with recursion:

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

        Spanners already in the stream are not put there again:

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

        Also does not happen with recursion.

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

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

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

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

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

        >>> sl = s.notes.first().getSpannerSites()[0]
        >>> s2.insert(0, sl)
        >>> s.coreGatherMissingSpanners(constrainingSpannerBundle=s2.spannerBundle)
        >>> s.show('text')
        {0.0} <music21.note.Note C>
        {0.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>
        {1.0} <music21.note.Note D>
        NTFr   )rC   )	rv   rZ   iterr{   getSpannerSitesgetSpannedElementsr/   r5   rS   )r   rZ   r   r   r   sbsItercollectListr   spallFoundspannedElements               r    coreGatherMissingSpannersz$StreamCore.coreGatherMissingSpanners   s    h LLNEIIKEu+B((*8$,8RG`=`$%)H*,*?*?*A)6',H! +B $ ""2& + $ !2& "$$%$8r!   )returnNone)r&   r   r0   r   r   bool)r0   r   r   r   )r0   r   r&   z&int | float | Fraction | OffsetSpecialr   r   )
rC   r   rD   r   rE   zlist[int] | NonerF   r   r   r   )r   r
   rd   r   r   r
   )T)
rZ   r   r   r   r   r   r   zspanner.SpannerBundle | Noner   zlist[spanner.Spanner] | None)__name__
__module____qualname____doc__r   r5   r<   r,   rS   rf   ri   rq   rt   propertyrv   r   r8   r   r   __classcell__)r   s   @r    r   r   ,   s   6 ?? ? 
?J 	JJ
 
JL (-(- 1(- 
(-Z ""#]2 ]2 	]2
 ]2 ]2 
]2D &*"&), ,6@#L EI ?!B*  , , &*T &%P !&EX] %< "&@Du u  	u
 u $>u 
$ur!   r   c                      e Zd Zy)TestN)r   r   r   r   r!   r    r   r     s    r!   r   __main__)$r   
__future__r   r_   	fractionsr   typingrO   unittestmusic21.baser   music21.common.enumsr   music21.common.numberToolsr   music21.common.typesr   r	   r
   r^   r   r   music21.exceptions21r   r   music21.stream.iteratorr   r   r   music21.streamr   r   TestCaser   r   mainTestr   r!   r    <module>r      s    #     & . - F F   J E ??%i
 i
h	8 	 zGT r!   