
    3jgt                   <   U d Z ddlmZ ddlmZmZ ddlZddl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 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 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 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! ddlm"Z" ddl#m$Z$ ddl%m&Z& ejN                  Z' ejP                  d      Z) G d dejT                        Z+ G d dejX                        Z-d Z.d Z/d Z0d!Z1d"Z2dZ3d#Z4d$Z5d%Z6d&Z7d Z8ejr                  e-jt                  e.fejv                  e-jt                  e/fejx                  e-jt                  e0fejz                  e-jt                  e1fej|                  e-jt                  e2fej~                  e-j                  e3fej                  e-j                  e4fej                  e-j                  e5fej                  e-j                  e6fej                  e-j                  e7fej                  e-j                  e8fgZJd'eKd(<   e-j                  d)e-j                  d*e-j                  d+e-j                  d,e-j                  d-e-jt                  d.e-j                  d/e-j                  d0iZNd1eKd2<   ej                  ej                  ej                  ej                  gZSd3eKd4<    G d5 d6e	j                        ZUddd7ZVd6eKd8<   d9 ZWd&ZXd:ZY ed;g d<      ZZ G d= d>e	j                        Z\ G d? d@e      Z] G dA dBe"j                        Z_ G dC dDe_e"j                        ZaddEdddFddGdEddEddGdEdGdEdH	 dWdIZbdEdGddJ	 dWdKZcddFdL	 dXdMZd	 	 	 	 dYdNZedO ZfdZdPZgdQ Zhd[dRZid\dSZj G dT dUe
j                        ZlemdVk(  rddlZ ej                  el       yy)]a  
Inner classes and functions for transcribing musical segments into braille.

This module was made in consultation with the manual "Introduction to Braille
Music Transcription, Second Edition" by Mary Turner De Garmo, 2005. It is
available from the Library of Congress
`here <https://www.loc.gov/nls/services-and-resources/music-service-and-materials/>`_,
and will henceforth be referred to as BMTM.
    )annotations)deque
namedtupleN)bar)base)chord)clef)dynamics)environment)exceptions21)expressionskey)layout)meter)note)spanner)stream)tempo)ProtoM21Object)basic)lookup)noteGrouping)text)BrailleTranscriptionHelper)opFracz
segment.pyc                      e Zd Zy)BrailleSegmentExceptionN)__name__
__module____qualname__     D/DATA/.local/lib/python3.12/site-packages/music21/braille/segment.pyr   r   :   s    r#   r   c                  0    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zy
)Affinity                  	   
   N)r   r    r!   _LOWEST	SIGNATURETTEXTMMARKLONG_TEXTEXPRINACCORDSPLIT1_NOTEGROUP	NOTEGROUPSPLIT2_NOTEGROUPr"   r#   r$   r&   r&   >   s1    GIEEMHIr#   r&   r/   r.   r,         r(   r)   z4list[tuple[type[base.Music21Object], Affinity, int]]affinityCodeszSignature GroupingzTempo Text GroupingzMetronome Mark GroupingzLong Text Expression GroupingzInaccord GroupingzNote GroupingzSplit Note Grouping AzSplit Note Grouping Bzdict[Affinity, str]affinityNameszlist[type[base.Music21Object]]excludeFromBrailleElementsc                  "    e Zd ZU ded<   ded<   y)GroupingGlobalszkey.KeySignature | NonekeySignaturezmeter.TimeSignature | NonetimeSignatureN)r   r    r!   __annotations__r"   r#   r$   r?   r?   y   s    ''++r#   r?   )r@   rA   GROUPING_GLOBALSc                     t         d   t        j                  d      t         d<   t         d   t        j                  d      t         d<   yy)z
    sets defaults for grouping globals.  Called first time anything
    in Braille is run, but saves creating two expensive objects if never run
    r@   Nr   rA   4/4)rC   r   KeySignaturer   TimeSignaturer"   r#   r$   setGroupingGlobalsrH      sK    
 '/+.+;+;A+>((0,1,?,?,F) 1r#   0   _ThreeDigitNumber)hundredstensonesc                  F    e Zd ZU dZded<   dZded<   dZded<   dZded	<   y)

SegmentKeyr   intmeasureordinalNzAffinity | Noneaffinityz
str | Nonehand)r   r    r!   rQ   rB   rR   rS   rT   r"   r#   r$   rO   rO      s*    GSGS"Hm"D(r#   rO   c                  `    e Zd ZU dZdddddddZd	ed
<   d Zd Zd Zd Z	d Z
d ZddZd Zy)BrailleElementGroupinga  
    A BrailleElementGrouping mimics a list of objects which should be displayed
    without a space in braille.

    >>> from music21.braille import segment
    >>> bg = segment.BrailleElementGrouping()
    >>> bg.append(note.Note('C4'))
    >>> bg.append(note.Note('D4'))
    >>> bg.append(note.Rest())
    >>> bg.append(note.Note('F4'))
    >>> bg
    <music21.braille.segment.BrailleElementGrouping [<music21.note.Note C>,
        <music21.note.Note D>, <music21.note.Rest quarter>, <music21.note.Note F>]>
    >>> print(bg)
    <music21.note.Note C>
    <music21.note.Note D>
    <music21.note.Rest quarter>
    <music21.note.Note F>

    These are the defaults, and they are shared across all objects.

    >>> bg.keySignature
    <music21.key.KeySignature of no sharps or flats>
    >>> bg.timeSignature
    <music21.meter.TimeSignature 4/4>

    >>> bg.descendingChords
    True

    >>> bg.showClefSigns
    False

    >>> bg.upperFirstInNoteFingering
    True

    >>> bg.withHyphen
    False

    >>> bg.numRepeats
    0
    zCThe last :class:`~music21.key.KeySignature` preceding the grouping.zFThe last :class:`~music21.meter.TimeSignature` preceding the grouping.zTrue if a :class:`~music21.chord.Chord` should be spelled
             from highest to lowest pitch
             in braille, False if the opposite is the case.zIf True, clef signs are shown in braille.
             Representation of music in braille is not
             dependent upon clefs and staves, so the clef signs would be displayed
             for referential or historical purposes.z4If True, this grouping will end with a music hyphen.z.The number of times this grouping is repeated.)r@   rA   descendingChordsshowClefSigns
withHyphen
numRepeatsdict[str, str]	_DOC_ATTRc                    t        | | _        t                t        d   | _        t        d   | _        d| _        d| _        d| _        d| _	        d| _
        y )Nr@   rA   TFr   )listinternalListrH   rC   r@   rA   rW   rX   upperFirstInNoteFingeringrY   rZ   )selflistElementss     r$   __init__zBrailleElementGrouping.__init__   sU     ,/,^<-o> $")-&r#   c                ,    t        | j                        S N)iterr_   ra   s    r$   __iter__zBrailleElementGrouping.__iter__       D%%&&r#   c                     | j                   |   S re   r_   ra   items     r$   __getitem__z"BrailleElementGrouping.__getitem__   s      &&r#   c                "    || j                   |<   y re   rk   )ra   posrm   s      r$   __setitem__z"BrailleElementGrouping.__setitem__   s    !%#r#   c                ,    t        | j                        S re   )lenr_   rg   s    r$   __len__zBrailleElementGrouping.__len__   s    4$$%%r#   c                N    |dk(  rt        d      t        | j                  |      S )Nr_   zinternalList not defined yet)AttributeErrorgetattrr_   )ra   attrs     r$   __getattr__z"BrailleElementGrouping.__getattr__   s)    >! !?@@t(($//r#   c                2   g }d}| D ]  }t        |t        j                        rf|r%|j                  dt        j
                  d           |D ]7  }	 |j                  dj                  |j                  j                               9 d}	 |j                  dj                  |j                  j                               d} | j                  dkD  r"|j                  d| j                  dz    d	       | j                  du r%|j                  d
t        j
                  d           dj                  |      }|S # t        t        f$ r |j                  t        |             Y w xY w# t        t        f$ r |j                  t        |             Y w xY w)zo
        Return a unicode braille representation
        of each object in the BrailleElementGrouping.
        Fzfull inaccord full_inaccord
Tr   z** Grouping x r9   z **zmusic hyphen music_hyphen)
isinstancer   Voiceappendr   symbolsjoin	editorialbrailleEnglishrv   	TypeErrorstrrZ   rY   )ra   
allObjectsprevious_was_voiceobjobj2outs         r$   __str__zBrailleElementGrouping.__str__   sk   
 
#(C#v||,%%%v~~o7V6W&XYD5"))$))DNN4Q4Q*RS  
 &*"0%%dii0L0L&MN &+"   ??Qt/B.C3GH??d"fnn^.L-MNOii
#
 +I6 5"))#d)45 '	2 0%%c#h/0s$   4D:4E*:)E'&E'*)FFc                ,    t        | j                        S re   )reprr_   rg   s    r$   _reprInternalz$BrailleElementGrouping._reprInternal  ri   r#   N)returnr   )r   r    r!   __doc__r\   rB   rc   rh   rn   rq   rt   ry   r   r   r"   r#   r$   rV   rV      sZ    (T ^a?8
 MF!I~ 
''&&0
<'r#   rV   c            
           e Zd ZU ddddddddd	d
	Zded<   d(d) fdZd Zd Zd Zd Z	d Z
d Zd Zed        Zd Zd Zd Zd Zd Zd Zd*dZd Zd+dZd,dZ	 	 d-d Zd*d!Zd" Zd# Zd$ Zd% Zd& Zd' Z  xZ!S ).BrailleSegmentzIf True, the previous key signature should be
                 cancelled immediately before a new key signature is encountered.zFor a given positive integer n, adds n "dummy rests"
                 near the beginning of a segment. Designed for test purposes, as they
                 are used to demonstrate measure division at the end of braille lines.zzThe maximum amount of braille characters that should be
                 present in a line. The standard is 40 characters.zwIf True, then a measure number is shown
                 following the heading (if applicable) and preceding the music.zsIf set to "right" or "left", shows the corresponding
                 hand sign at the beginning of the first line.zIf True, then a braille heading is displayed.
                 See :meth:`~music21.braille.basic.transcribeHeading`
                 for more details on headings.zIf True, then all octave marks are suppressed.
                 Designed for test purposes, as octave marks were not presented
                 until Chapter 7 of BMTM.a%  If True, then the last
                 :class:`~music21.braille.segment.BrailleElementGrouping` of this
                 segment will be followed by a music hyphen.
                 The last grouping is incomplete, because a segment
                 break occurred in the middle of a measure.zIf True, then the initial measure number of this
                 segment should be followed by a dot. This segment
                 is starting in the middle of a measure.)	cancelOutgoingKeySigdummyRestLength
lineLengthshowFirstMeasureNumbershowHandshowHeadingsuppressOctaveMarks	endHyphenbeginsMidMeasurer[   r\   c                   t         |   |       i | _        t               | _        d| _        d| _        d| _        d| _        d| _	        d| _
        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        y)a  
        A segment is "a group of measures occupying more than one braille line."
        Music is divided into segments in order to "present the music to the reader
        in a meaningful manner and to give him convenient reference points to
        use in memorization" (BMTM, 71).

        >>> brailleSeg = braille.segment.BrailleSegment()

        >>> brailleSeg.cancelOutgoingKeySig
        True
        >>> brailleSeg.dummyRestLength

        >>> brailleSeg.lineLength
        40

        >>> brailleSeg.showFirstMeasureNumber
        True

        Possible showHand values are None, 'right', 'left':

        >>> brailleSeg.showHand is None
        True

        >>> brailleSeg.showHeading
        True

        >>> brailleSeg.suppressOctaveMarks
        False

        >>> brailleSeg.endHyphen
        False

        >>> brailleSeg.beginsMidMeasure
        False

        A BrailleSegment is a type of defaultdict that returns a BrailleElementGrouping
        when a key is missing.

        >>> len(brailleSeg.keys())
        0
        >>> beg = brailleSeg[braille.segment.SegmentKey(4, 1, 9)]
        >>> type(beg) is braille.segment.BrailleElementGrouping
        True

        Of course, creating random keys like this will have consequences:

        >>> print(str(brailleSeg))
        ---begin segment---
        <music21.braille.segment BrailleSegment>
        Measure 4, Note Grouping 2:
        <BLANKLINE>
        ===
        ---end segment---
        r   NFT)superrc   _groupingDictr   groupingKeysToProcesscurrentGroupingKeypreviousGroupingKeylastNoterX   r`   rW   r   r   r   r   r   r   r   r   )ra   r   	__class__s     r$   rc   zBrailleSegment.__init__2  s    n 	J/GI8="3748 (,#(/3&&*$(!#&*##(  %r#   c                "    || j                   |<   y re   r   )ra   rm   values      r$   rq   zBrailleSegment.__setitem__~  s    #(4 r#   c                j    || j                   vrt               | j                   |<   | j                   |   S re   )r   rV   rl   s     r$   rn   zBrailleSegment.__getitem__  s4    t)))'='?Dt$!!$''r#   c                X    || j                   vr| j                  |= y t        d|d      S )NzNo item z in Segment)__dict__r   
ValueErrorrl   s     r$   __delitem__zBrailleSegment.__delitem__  s0    t}}$""4(<==r#   c                .    t        | j                  |      S re   )rw   r   rl   s     r$   ry   zBrailleSegment.__getattr__  s    t))400r#   c                    || j                   v S re   r   rl   s     r$   __contains__zBrailleSegment.__contains__  s    t))))r#   c                ,    t        | j                        S re   )rf   r   rg   s    r$   rh   zBrailleSegment.__iter__  s    D&&''r#   c                ,    t        | j                        S re   )rs   r   rg   s    r$   rt   zBrailleSegment.__len__  s    4%%&&r#   c                @    t         j                  j                  |       S )z@
        Returns the string from the BrailleText object
        )r   BrailleTextr   rg   s    r$   brailleTextzBrailleSegment.brailleText  s    
 ''--r#   c           
        d}t        | j                               }g }g }t               }|D ]  \  }}	 |j                  t        j
                  k(  r|}'	 |j                  d|j                   dt        |j                      d|j                  dz    d       t        |      }|j                  |       |} dj                  d t        ||      D              }	dj                  d	||	d
g      }
|
S # t        $ r Y w xY w)Nz(<music21.braille.segment BrailleSegment>Measure z,  r9   :
r|   c              3  0   K   | ]  \  }}| | d   yw)z
===Nr"   ).0kgs      r$   	<genexpr>z)BrailleSegment.__str__.<locals>.<genexpr>  s&      (
21 c!EN2s   z---begin segment---z---end segment---)sorteditemsrO   rS   r&   r6   r   r   rQ   r<   rR   r   r   zip)ra   nameallItemsallKeysallGroupingsprevKeyitemKeygroupinggStrallElementGroupingsr   s              r$   r   zBrailleSegment.__str__  s"   9$**,',#+Wh##x'@'@@%G A
 NN7??+2 !1!1231??Q&'s,
 x=D%G $, #ii (
G\2(
 
 ii.,,. / 
%  s   C00	C<;C<c                F   t        t        | j                                     | _        | j                  r| j                          | j                  r| j                          | j                  | j                          d| _
        | j                  r| j                  j                         | _        | j                  j                  }|t        j                  k(  r| j!                          n|t        j"                  k(  r| j%                          nk|t        j&                  k(  r| j)                          nG|t        j*                  k(  r| j-                          n#|t        j.                  k(  r| j1                          | j                  | _
        | j                  r| j2                  S )a-  
        Transcribes all noteGroupings in this dict by:

        *    First transcribes the Heading (if applicable)
        *    then the Measure Number
        *    then adds appropriate numbers of dummyRests
        *    then adds the Rest of the Note Groupings

        Returns brailleText
        N)r   r   keysr   r   extractHeadingr   extractMeasureNumberr   addDummyRestsr   popleftr   rS   r&   r7   extractNoteGroupingr1   extractSignatureGroupingr4   extractLongExpressionGroupingr5   extractInaccordGroupingr2   extractTempoTextGroupingr   )ra   cgkAffinityGroups     r$   
transcribezBrailleSegment.transcribe  s?    &+6$))++>%?"!&&%%'+ #' ((&*&@&@&H&H&JD##66??8#5#55((*!X%7%77--/!X%;%;;224!X%6%66,,.!X^^3--/'+'>'>D$ ((" r#   c                n    |D ]0  }t         j                  D ]  }t        ||      st        ||        2 y)z
        Removes temporary attributes from Music21Objects set during transcription.
        Run this only AFTER any possible re-transcription in extractNoteGrouping().
        N)r   TEMPORARY_ATTRIBUTEShasattrdelattr)ra   r   elkws       r$   _cleanupAttributesz!BrailleSegment._cleanupAttributes  s0    
 B002r?BO 1 r#   c                    | j                   t        j                  d   z  g}| j                  dj	                  |             y)uY  
        Adds as many dummy rests as self.dummyRestLength to the signatures of
        brailleText

        >>> seg = braille.segment.BrailleSegment()
        >>> seg.dummyRestLength = 4

        >>> print(braille.lookup.rests['dummy'])
        ⠄
        >>> seg.addDummyRests()
        >>> print(seg.brailleText)
        ⠄⠄⠄⠄
        dummy N)r   r   restsaddSignaturesr   )ra   
dummyRestss     r$   r   zBrailleSegment.addDummyRests  s7     **V\\'-BBC
277:./r#   c                   | j                   xs" t        t        | j                                     }|d   }|j                  }t        j                  |      }| j                  r|t        d   z  }| j                  |       y)u  
        Adds a measure number from the segmentKey needing processing

        >>> segKey = braille.segment.SegmentKey(measure=4, ordinal=1, affinity=9)
        >>> seg = braille.segment.BrailleSegment()

        Initialize a new Key

        >>> type(seg[segKey])
        <class 'music21.braille.segment.BrailleElementGrouping'>
        >>> seg.extractMeasureNumber()
        >>> print(seg.brailleText)
        ⠼⠙

        Add a dot to the measure number if the segment begins mid-measure

        >>> seg = braille.segment.BrailleSegment()
        >>> seg[segKey]
        <music21.braille.segment.BrailleElementGrouping []>

        >>> seg.beginsMidMeasure = True
        >>> seg.extractMeasureNumber()
        >>> print(seg.brailleText)
        ⠼⠙⠄
        r   dotN)
r   r   r   r   rQ   r   numberToBrailler   r   addMeasureNumber)ra   gkpfirstSegmentKeyinitMeasureNumberbrailleNumbers        r$   r   z#BrailleSegment.extractMeasureNumber  so    4 ((FE&2E,Fa&+33--.?@  WU^+Mm,r#   c                   d}d}d}d}| j                   xs" t        t        | j                                     }|r|d   j                  t
        j                  kD  rn|j                         }|j                  }| j                  j                  |      }|t
        j                  k(  rLt        |      dk\  r|d   |d   }}ndt        |      dk(  rV|d   }	t        |	t        j                        r|	}n4|	}n1|t
        j                  k(  r|d   }n|t
        j                  k(  r|d   }|rt!        ||||g      r6t#        j$                  ||||| j&                        }
| j)                  |
       yy)a  
        Extract a :class:`~music21.key.KeySignature`, :class:`~music21.meter.TimeSignature,
        :class:`~music21.tempo.TempoText` and :class:`~music21.tempo.MetronomeMark` and
        add an appropriate braille heading to the brailleText object inputted.
        Nr   r:   r9   maxLineLength)r   r   r   r   rS   r&   r3   r   r   getr1   rs   r~   r   rF   r2   anyr   transcribeHeadingr   
addHeading)ra   r@   rA   	tempoTextmetronomeMarkr   cgkr   currentBrailleGroupingkeyOrTimeSigbrailleHeadings              r$   r   zBrailleSegment.extractHeading)  sg    	 !% : : XeF499;DW>X#$Q'008>>A'//1C"||%)%7%7%;%;C%@"8#5#55-.!33I!3L3I!3L #0L/0A5#9!#<L!,0@0@A'3(4!X^^3215	!X^^3 6q 9+ $. mYFG"44"ooN OON+ Hr#   c                0   | j                   t        d      | j                  | j                      }d }d}|D ]  }t        |t        j
                        r|} t        |t        j                        st        j                  | d       t        |      }|r|j                  d|       d }|j                  |_        |j                  |_        |j                  |_        |r	t        d   nd}|t!        j"                  |      z  }| j%                  |       d} y )NzCcurrentGroupingKey must not be None to call extractInaccordGroupingFz' is neither a voice nor clef; ignoring!r   r{   r   T)r   r   r   r~   r	   Clefr   r   environRuleswarnextractBrailleElementsinsertrW   rX   r`   r   ngModtranscribeNoteGroupingaddInaccord)ra   	inaccords	last_clef
seen_voicemusic21VoiceOrClefr   brailleInaccords          r$   r   z&BrailleSegment.extractInaccordGroupingY  s   ""*bcc&&t'>'>?	$(	 
"+,dii8.	0&,,?!!%7$88_"`a12DEL##Ay1 	,5,F,FL))2)@)@L&5>5X5XL2:Dgo6"Ou;;LIIO_-J! #,r#   c                    | j                   }| j                  j                  |      }|d   }t        j                  |      }| j                  |       y)zv
        Extract the Long Expression that is in the ElementGrouping in cgk
        and add it to brailleText.
        r   N)r   r   r   r   textExpressionToBrailleaddLongExpression)ra   r   currentElementGroupinglongTextExpressionlongExprInBrailles        r$   r   z,BrailleSegment.extractLongExpressionGroupingr  sR    
 %%!%!3!3!7!7!<3A6!99:LM01r#   c                R   | j                   }| j                  }|||j                  t        j                  k7  sk|j                  t        j                  k7  sN|j
                  |j
                  k(  r<|j                  |j                  dz   k(  r |j                  |j                  k(  rd| _        | j                  ry|D cg c]  }t        |t        j                        s|! }}d}|r;| j                  %|d   }t        j                  | j                  |      }|d   | _        |S c c}w )a  
        Given a noteGrouping, should we show the octave symbol?

        >>> n1 = note.Note('C1')
        >>> n2 = note.Note('D1')
        >>> n3 = note.Note('E1')

        >>> beg1 = braille.segment.BrailleElementGrouping([n1, n2, n3])
        >>> bs1 = braille.segment.BrailleSegment()

        This is True because last note is None

        >>> bs1.lastNote is None
        True
        >>> bs1.showLeadingOctaveFromNoteGrouping(beg1)
        True

        But if we run it again, now we have a note within a fourth, so we do not
        need to show the octave:

        >>> bs1.lastNote
        <music21.note.Note E>
        >>> bs1.showLeadingOctaveFromNoteGrouping(beg1)
        False

        And that is true no matter how many times we call it on the same
        BrailleElementGrouping:

        >>> bs1.showLeadingOctaveFromNoteGrouping(beg1)
        False

        But if we give a new, much higher BrailleElementGrouping, we
        will see octave marks again.

        >>> nHigh1 = note.Note('C6')
        >>> nHigh2 = note.Note('D6')
        >>> beg2 = braille.segment.BrailleElementGrouping([nHigh1, nHigh2])
        >>> bs1.showLeadingOctaveFromNoteGrouping(beg2)
        True

        But if we set `self.suppressOctaveMarks` to True, we won't see any
        when we switch back to beg1:

        >>> bs1.suppressOctaveMarks = True
        >>> bs1.showLeadingOctaveFromNoteGrouping(beg2)
        False

        We also show octaves if for some reason two noteGroups in the same measure have
        different BrailleElementGroupings keyed to consecutive ordinals.  The code simulates
        that situation.

        >>> bs1.suppressOctaveMarks = False
        >>> bs1.previousGroupingKey = braille.segment.SegmentKey(measure=3, ordinal=1,
        ...                                          affinity=braille.segment.Affinity.NOTEGROUP)
        >>> bs1.currentGroupingKey = braille.segment.SegmentKey(measure=3, ordinal=2,
        ...                                          affinity=braille.segment.Affinity.NOTEGROUP)
        >>> bs1.showLeadingOctaveFromNoteGrouping(beg2)
        True
        >>> bs1.showLeadingOctaveFromNoteGrouping(beg1)
        True
        >>> bs1.showLeadingOctaveFromNoteGrouping(beg1)
        True

        Nr9   FTr   r'   )r   r   rS   r&   r7   rQ   rR   rT   r   r   r~   r   Noter   showOctaveWithNote)ra   r   
currentKeypreviousKeynallNotesshowLeadingOctave	firstNotes           r$   !showLeadingOctaveFromNoteGroupingz0BrailleSegment.showLeadingOctaveFromNoteGrouping}  s   B ,,
.. #*$$(:(::&&(*<*<<&&+*=*=="**k.A.AA.EE";+;+;; $##  ,H|!z!TYY/GA|H }}($QK	$)$<$<T]]I$V!$RLDM   Is   =D$D$c                    | j                   dz  }| j                   | j                  j                  z
  }||kD  rt        |      |kD  ryy)an  
        Returns boolean on whether a note grouping needs to be split in order to fit.

        Generally a noteGrouping will need to be split if the amount of space left
        is more than 1/4 of the line length and the brailleNoteGrouping cannot fit.

        >>> n1 = note.Note('C1')
        >>> n2 = note.Note('D1')
        >>> n3 = note.Note('E1')

        >>> beg1 = braille.segment.BrailleElementGrouping([n1, n2, n3])
        >>> seg = braille.segment.BrailleSegment()
        >>> seg.needsSplitToFit(beg1)
        False
        >>> seg.lineLength = 10
        >>> seg.needsSplitToFit(beg1)
        True
        r)   TF)r   currentLinetextLocationrs   )ra   brailleNoteGroupingquarterLineLength	spaceLefts       r$   needsSplitToFitzBrailleSegment.needsSplitToFit  sK    & !OOq0OOd&6&6&C&CC	))+,/@@r#   c                   t        j                         }d}d}d\  }}d}	||k  rSt        ||      \  }}||_        d|_        |j                  |      }	| j                  j                  |	|      rn|dz  }X| j                   }
|
|_        |j                  |      }| j                  }|j                  t        j                  	      }|j                  t        j                  	      }|| |<   || |<   |	|fS )
z
        Take a noteGrouping and split it at a logical place,
        returning braille transcriptions of each section.
        r   r/   NNN)beatDivisionOffsetTaddSpacer9   rS   )r   NoteGroupingTranscribersplitNoteGroupingr  rY   transcribeGroupr  	canAppendr   r   _replacer&   r6   r8   )ra   r   showLeadingOctaveOnFirstaddSpaceToFirsttranscriberr!  REASONABLE_LIMITsplitNoteGroupAsplitNoteGroupBbrailleNoteGroupingAr  brailleNoteGroupingBr  aKeybKeys                  r$   splitNoteGroupingAndTranscribez-BrailleSegment.splitNoteGroupingAndTranscribe  s     335-9*/# #331B#52._o -EK))-O&#.#>#>#O ))*>)Y!# $ 8 88(9%*::?K,,
 ""H,E,E"F""H,E,E"F$T
$T
$&:;;r#   c                N   t        j                         }| j                  t        d      | j                  | j                     }| j                  |      }||_        |j                  |      }| j                  |      }| j                  j                  ||      r| j                  j                  ||       n| j                  |      }|rE	 | j                  |||      \  }}| j                  j                  ||       | j                  |       |sU|du r&| j                   du rd|_        |j                  |      }| j                  j#                          | j                  |       | j%                  |j&                         | j)                  |       y# t        $ r d}Y w xY w)z^
        Fundamentally important method that adds a noteGrouping to the braille line.
        Nz?currentGroupingKey must not be None to call extractNoteGroupingr"  FT)r   r%  r   r   r   r  r  r'  !optionalAddKeyboardSymbolsAndDotsr  r(  r   r  r4  addToNewLiner   r   lastHyphenToSpaceaddRepeatSymbolsrZ   r   )	ra   r,  r   r  r  r#  should_splitbngAbngBs	            r$   r   z"BrailleSegment.extractNoteGrouping%  s    335""*^__))$*A*AB BB<P(9%)99,G99:MN%%&9H%M##$7(#K!%!5!56I!JL)!%!D!D\ARAI"KJD$ $$++D8+D%%d+   %-$2J2Je2S 59K1*5*E*El*S'  224!!"56l556-- / ) $)L)s   AF F$#F$c                    d|cxk  rdk  r,n n)t        |      D ]  }| j                  t        d           y|dk\  r6| j                  t        d   t        j                  |      z          d| _        yy)u  
        Adds the appropriate number of repeat symbols, following DeGarmo chapter 17.

        >>> seg = braille.segment.BrailleSegment()
        >>> seg.addRepeatSymbols(0)
        >>> print(seg.brailleText)
        >>> seg.addRepeatSymbols(1)
        >>> print(seg.brailleText)
        ⠶

        >>> seg = braille.segment.BrailleSegment()
        >>> seg.addRepeatSymbols(2)
        >>> print(seg.brailleText)
        ⠶⠀⠶

        >>> seg = braille.segment.BrailleSegment()
        >>> seg.addRepeatSymbols(3)
        >>> print(seg.brailleText)
        ⠶⠼⠉

        Does not yet handle situations beginning with Example 17-6 (repeats at
        different octaves), and further
        r   r(   repeatN)ranger   r   r   r   r   )ra   repeatTimesunused_repeatCounters      r$   r9  zBrailleSegment.addRepeatSymbolsZ  sk    0 {Q(-k(:$""78#45 );Awx053H3H3UUV DM r#   c                   d}d}| j                   }| j                  j                  |      }t        |      dk\  r|d   |d   }}nUt        |      dk(  rG| j                  j                  | j                         d   }t	        |t
        j                        r|}n|}d}| j                  r|	 |j                  }t        j                  |||      }|dk7  r| j                  |       yy# t        $ r Y :w xY w)z
        Extracts a key signature, time signature, and possibly an outgoing key signature
        from the currentGroupingKey and adds it to the BrailleText object.
        Nr:   r   r9   r   )r   r   r   rs   r~   r   rF   r   outgoingKeySigrv   r   transcribeSignaturesr   )ra   r@   rA   r   r   r   rC  
brailleSigs           r$   r   z'BrailleSegment.extractSignatureGroupingz  s    
 %%))--c2|!*6q/<?-L!#--11$2I2IJ1ML,(8(89+ ,$$)A!-!<!< //m^\
z* 	 " s   +C& &	C21C2c                &   | j                   j                  | j                         | j                  j                  t
        j                  k(  r%| j                   j                  | j                         | j                          | j                          y)z9
        Extracts a tempo text and processes it.
        N)	r   
appendleftr   r   rS   r&   r1   r   r   rg   s    r$   r   z'BrailleSegment.extractTempoTextGrouping  sj     	""--d.E.EF##,,0B0BB&&11$2J2JK!!#r#   c                    t        | j                        }d}t        | j                               D ]I  \  }}|j                  t
        j                  k7  r|||<   d}+||}|D ]  }||   j                  |        K |S )ag  
        Puts together certain types of elements according to the last digit of their key
        (if it is the same as Affinity.NOTEGROUP or not.

        >>> SK = braille.segment.SegmentKey
        >>> BS1 = braille.segment.BrailleSegment()
        >>> BS1[SK(ordinal=0, affinity=2)] = ['hi', 'hello', 'there']
        >>> BS1[SK(ordinal=1, affinity=9)] = ['these', 'get']
        >>> BS1[SK(ordinal=2, affinity=9)] = ['put', 'together']
        >>> BS1[SK(ordinal=3, affinity=4)] = ['in', 'new', 'group']
        >>> BS1[SK(ordinal=4, affinity=9)] = ['with', 'the', 'previous']
        >>> BS2 = BS1.consolidate()
        >>> for (groupingKey, groupingList) in sorted(BS2.items()):
        ...     print(groupingKey, groupingList)
        SegmentKey(measure=0, ordinal=0, affinity=2, hand=None) ['hi', 'hello', 'there']
        SegmentKey(measure=0, ordinal=1, affinity=9, hand=None) these
        get
        put
        together
        SegmentKey(measure=0, ordinal=3, affinity=4, hand=None) ['in', 'new', 'group']
        SegmentKey(measure=0, ordinal=4, affinity=9, hand=None) with
        the
        previous
        N)r   r   r   r   rS   r&   r7   r   )ra   
newSegmentpngKeygroupingKeygroupingListrm   s         r$   consolidatezBrailleSegment.consolidate  s    4 $DOO4
+1$**,+?'[,##x'9'99*6
;'>(F(Dv&--d3 ) ,@ r#   c                   t        j                  d      }t        j                  d      }t	        | j                               }d\  }}|D ]  \  }}||j                  dk\  rd|_        |j                  dk(  r|j                  t        j                  k(  r|j                  dk(  rq|j                  t        j                  k(  rTt        |d   t        j                        rt        |dd |      }nt        ||      }|r|xj                  dz  c_        | |= |j                  t        j                   k(  rJ|D ]C  }	t        |	t        j                        r|	} t        |	t         j                        s;||	_        |	}E n|j                  t        j$                  t        j                  fv rt        |d   t        j                        rit        |d   t        j&                  t        j(                  f      rd| _        n4t        |d   t        j,                  t        j.                  f      rd| _        |D 
cg c]  }
t        |
t0        j2                        s|
! }}
t5        |      dk(  r't        |d   t0        j6                        r
d|d   _        ||_        ||_        | j*                  |_        | j>                  |_        | j@                  |_         ||}} | jB                  rd|_        yyc c}
w )a%  
        Modifies the attributes of all :class:`~music21.braille.segment.BrailleElementGrouping`
        instances in a list of :class:`~music21.braille.segment.BrailleSegment` instances. The
        necessary information is retrieved from the segment and from the found clef, if any.
        r   rE   r   Nr9   TF)"r   rF   r   rG   r   r   rR   rY   rS   r&   r7   r~   r	   r   areGroupingsIdenticalrZ   r1   rC  r5   
TrebleClefAltoClefrW   BassClef	TenorClefr   GeneralNoters   RestfullMeasurer@   rA   rX   r`   r   )ra   currentKeySigcurrentTimeSigr   r  previousListrK  rL  isRepetitionbrailleElementr  allGeneralNotess               r$   addGroupingAttributesz$BrailleSegment.addGroupingAttributes  s{    ((+,,U3djjl+&2#l+7'[,&&&!+.2L+''1,'00H4F4FF'//14'00H4F4FF!,q/499='<\!"=M|'\'<\<'X#$//14/ - ##x'9'99&2N!.%2E2EF)7#NC4D4DE8E5(6 '3 %%(*;*;X=O=O)PPl1otyy9!,q/DOOT]]3ST04-#LOdmmT^^5TU05- /;"^ljDL\L\>]1l"^'1,OA<NPTPYPY1Z59OA&2(5L%)7L&,0,A,AL))-););L&595S5SL2+6,[O ,8P >>&*L#  #_s   3K+K+c           	        ddl m fd}| j                         }|j                         D cg c]$  }|j                  t
        j                  k(  r||   & }}|D ]  }|D cg c]  }t        |t        j                        s|! }}t        t        |            D ]P  }||   }	|	j                  D ]:  }
t        |
j                        rt        |
j                        s0 ||
|	||       < R  yc c}w c c}w )a  
        Goes through each :class:`~music21.braille.segment.BrailleSegment` and modifies the
        list of :attr:`~music21.note.GeneralNote.articulations` of a :class:`~music21.note.Note`
        if appropriate. In particular, two rules are applied:

        * Doubling rule => If four or more of the same :class:`~music21.articulations.Articulation`
          are found in a row, the first instance of the articulation is doubled and the rest are
          omitted.

          It is permissible (not mandatory) to observe this doubling with bowings. (BMTM, 114)
          For this reason, any :class:`~music21.articulations.TechnicalIndication` but for bowings
          (e.g. fingering, harmonic) is skipped, because it does not braille as an articulation.

        * Staccato, Tenuto rule => "If two repeated notes appear to be tied, but either is marked
          staccato or tenuto, they are treated as slurred instead of tied." (BMTM, 112)
        r   )articulationsc                   | j                   }t        | 
j                  
j                  f      r[|j                  O|j                  j
                  dk(  rd ||dz
     _        d||dz
     _        nd ||dz      _        d|_        d |_        d}t        |dz   t        |            D ]4  }||   }||j                  D cg c]  }|j                    c}v r|dz  }4 n |dk  ry |j                  j                  |        t        |dz   ||z         D ]C  }||   }|j                  D ]-  }	|	j                   |k(  s|j                  j                  |	       / E y c c}w )Nstopr9   Tr   r(   )r   r~   StaccatoTenutotietype	shortSlurr?  rs   r_  r   remove)articmusic21NoteStartr  noteIndexStart	articNamenumSequentialnoteIndexContinuemusic21NoteContinueaartOtherr_  s             r$   fixOneArticulationz;BrailleSegment.fixArticulations.<locals>.fixOneArticulation  sw   

I5=#9#9=;O;O"PQ(,,8#'',,67;H^a/04=AH^a/0:7;H^a/0415$.'+ $M%*>A+=s8}%M!&./@&A#1D1R1R S1RA1R SS!Q&M &N q  **11%8%*>A+=+9M+I&K!&./@&A# 3 A AH}}	1+99@@J !B&K !Ts   <EN)music21r_  rM  r   rS   r&   r7   r~   r   r  r?  rs   TechnicalIndicationBowing)ra   rq  rI  gpKeynoteGroupingsr   r  allNotes_outernoteIndexStart_outermusic21NoteStart_outerartic_outerr_  s              @r$   fixArticulationszBrailleSegment.fixArticulations  s    " 	*	K< %%'
*4//*;I*;#(>>X5G5G#G $E**; 	 I *L)5RAAtyy9QaNR(-c..A(B$)78L)M&#9#G#GK&{M4U4UV)+}7K7KL*'2*0	 $H )C *I Ss   )C3#C8C8(   r   rP   )r   None)r   rV   )r   bool)FF)"r   r    r!   r\   rB   rc   rq   rn   r   ry   r   rh   rt   propertyr   r   r   r   r   r   r   r   r   r  r  r4  r   r9  r   r   rM  r]  r{  __classcell__)r   s   @r$   r   r     s    !UZF#SB2 -?
</!I~ 8J&X)(
>1*(' . . D( T$0"!-F-,`2	2^!@: AF7<+<Z3.j!@+>$%N5+nAr#   r   c                  H    e Zd ZdZd
ddZed        Zd Zd Zd Z	d Z
d Zy	)BrailleGrandSegmenta  
    A BrailleGrandSegment represents a pair of segments (rightSegment, leftSegment)
    representing the right and left hands of a piano staff (or other two-staff object).

    >>> bgs = braille.segment.BrailleGrandSegment(lineLength=36)
    >>> bgs.lineLength
    36
    c                    t         j                  | |       t        j                  j                  | |       t	               | _        d | _        d | _        y )Nr   )r   rc   r   BrailleKeyboardr   allKeyPairspreviousGroupingPaircurrentGroupingPair)ra   r   s     r$   rc   zBrailleGrandSegment.__init__N  sK    <%%dz%B:?' 	$(!#' r#   c                @    t         j                  j                  |       S re   )r   r  r   rg   s    r$   r   zBrailleGrandSegment.brailleTextV  s    ##++D11r#   c                   d}g }| j                         D ]	  \  }}|ld|j                   dt        |j                      d|j                  dz    d}t        | j                  j                  |            }dj                  ||g      }nd}|ld|j                   d	t        |j                      d|j                  dz    d}t        | j                  j                  |            }	dj                  ||	g      }
nd}
|j                  d
j                  ||
dg              d
j                  d|dj                  |      dg      }|S )Nz1<music21.braille.segment BrailleGrandSegment>
===r   z Right, r   r9   r   r   z	
Measure z Left, r|   z====
z---begin grand segment---z---end grand segment---)
yieldCombinedGroupingKeysrQ   r<   rS   rR   r   r   r   r   r   )ra   r   allPairsrightKeyleftKeyrightHeadingrightContents	rightFullleftHeadingleftContentsleftFullr   s               r$   r   zBrailleGrandSegment.__str__Z  sd   C#'#A#A#CXw#x//0$X%6%678''!+,C1 
 !$D$6$6$:$:8$D EGG\=$AB		"  1$W%5%567q*+30 
  #4#5#5#9#9'#BC77K#>?OODIIy(H&EFG+ $D, ii4*24 5 
r#   c              #  (  K   d }d }d}d}t        | j                         |      D ]  }|j                  dk(  rk|f |||      r||f nS|j                  t        j
                  k(  r. ||j                  t        j                        |      r||f nd|f |}d}z|}}|j                  dk(  s|E |||      r||f n2|j                  t        j                  k  r|df d|f n|df |}d}|} |r|df |rd|f yyw)a  
        yields all the keys in order as a tuple of (rightKey, leftKey) where
        two keys are grouped if they have the same segmentKey except for the hand.

        >>> bgs = braille.segment.BrailleGrandSegment()
        >>> SegmentKey = braille.segment.SegmentKey  # namedtuple
        >>> bgs[SegmentKey(1, 1, 1, 'right')] = '1r'
        >>> bgs[SegmentKey(1, 1, 1, 'left')]  = '1l'
        >>> bgs[SegmentKey(1, 2, 3, 'right')] = '2r'
        >>> bgs[SegmentKey(1, 2, 4, 'left')] = '3l'
        >>> bgs[SegmentKey(2, 1, 9, 'left')] = '4l'
        >>> bgs[SegmentKey(2, 1, 9, 'right')] = '4r'
        >>> bgs[SegmentKey(3, 1, 9, 'right')] = '5r'
        >>> for l, r in bgs.yieldCombinedGroupingKeys():
        ...     (bgs[l], bgs[r])
        ('1r', '1l')
        ('2r', <music21.braille.segment.BrailleElementGrouping []>)
        (<music21.braille.segment.BrailleElementGrouping []>, '3l')
        ('4r', '4l')
        ('5r', <music21.braille.segment.BrailleElementGrouping []>)

        Known Bug:
            Because this puts `None` elements into the defaultDict,
            it makes the assumption that all of .keys() will be SegmentKeys
            incorrect.  In fact, if you run this method twice, the second time
            it will crash.
        c                r    | j                   dk(  rd}nd}| j                  | j                  | j                  |fS )z\
            sort by measure, then ordinal, then affinity, then hand (r then l)
            rightr'   r9   )rT   rQ   rR   rS   )
segmentKeyskHs     r$   segmentKeySortKeyzHBrailleGrandSegment.yieldCombinedGroupingKeys.<locals>.segmentKeySortKey  s<     ')&&
(:(:J<O<OQTUUr#   c                    | j                   |j                   k(  r3| j                  |j                  k(  r| j                  |j                  k(  ryy)NTF)rQ   rR   rS   )thisKey_innerotherKeys     r$   
matchOtherzABrailleGrandSegment.yieldCombinedGroupingKeys.<locals>.matchOther  sD    %%)9)99%--1A1AA%..(2C2CCr#   Nr   r  r$  left)r   r   rT   rS   r&   r7   r)  r5   )ra   r  r  storedRight
storedLeftthisKeys         r$   r  z-BrailleGrandSegment.yieldCombinedGroupingKeysy  sD    >	V	 
diik/@AG||w&)!':6&
33!**h.@.@@()9)98CTCT)9)UWab  '
33#Z00&-!%J")K'*!';7*G44$--0A0AA*D11#Wo-*D11%,
"&K!(J9 B< %%$$ s   B2D5ADc                f   t        | j                               | _        | j                  d   }|d   r|d   j                  n|d   j                  }t	        t        |            | _        | j                          d| _        | j                  r| j                  | _	        | j                  j                         | _        | j                  \  }}||j                  t        j                  k\  s|-|j                  t        j                  k\  r| j                          | j                  r| j                  S )zI
        Returns the BrailleText from the combined grouping keys
        r'   r   r9   N)r   r  r  rQ   rs   r   highestMeasureNumberLengthr   r  r  r   rS   r&   r5   r   r   )ra   lastPairhighestMeasurer  r  s        r$   r   zBrailleGrandSegment.transcribe  s    !!?!?!AB##B'08!,,!ATAT*-c..A*B'#' (,(@(@D%'+'7'7'?'?'AD$"&":":Xw%(*;*;x?P?P*P+0@0@HDUDU0U((*   r#   c                   d}d}d}d}| j                   r| j                   d   \  }}|}	 | j                  j                  |      }|j
                  t        j                  kD  rn| j                   j                          |j
                  t        j                  k(  r	 |d   |d   }}nE|j
                  t        j                  k(  r|d   }n"|j
                  t        j                  k(  r|d   }| j                   r	 t        j                   ||||| j"                        }
| j%                  |
       y# t        $ r=}	|	j                  d   dk(  r| j                  j                  |      }|}n|	Y d}	~	+d}	~	ww xY w# t        $ r( t        |t        j                        r|d   }n|d   }Y w xY w# t        j&                  $ r}|j                  d   dk7  r|Y d}~yd}~ww xY w)z
        Finds KeySignatures, TimeSignatures, TempoText, and Metronome Marks
        within the keyPairs, and removes some from allKeyPairs.
        Nr   r  r9   r   zNo heading can be made.)r  r   r   KeyErrorargsrS   r&   r3   r   r1   
IndexErrorr~   r   rF   r2   r   r   r   r   BrailleBasicException)ra   r@   rA   r   r   r  r  useKey
useElementker   bbes               r$   r   z"BrailleGrandSegment.extractHeading  s   
 	"&"2"21"5XwF!//33H=
 /$$&("4"4462<Q-A-L HNN2&qM	HNN2 *13 6	"44"ooN OON+=  771:'!%!3!3!7!7!@J$FH  " 6!*c.>.>?'1!}(21	6& ** 	xx{77	 8	sA   D/ 
E8 95F, /	E582E00E58.F)(F),G?GGc                      j                   \  }}|r|j                  }n|r|j                  }nt        d      t        j                  |d      } fd} ||      } ||      } j                  |||       y )Nz/Measure must be defined for leftKey or rightKeyF)withNumberSignc                l   | | j                   t        j                  k(  r̉j                  j	                  |       }g }|D ]  }t        |t        j                        st        |      }|j                  |_	        |j                  |_
        |j                  |_        |j                  t        j                  |             j                  |        t         d   j#                  |      }|S | Cj                  j	                  |       }t        j                  |      }j                  |       |S d}|S )Nr{   r   )rS   r&   r5   r   r   r~   r   r   r   rW   rX   r`   r   r   r  r   r   r   )rightOrLeftKeyr  voice_transmusic21Voicer   
brailleStrra   s         r$   brailleFromKeyz?BrailleGrandSegment.extractNoteGrouping.<locals>.brailleFromKeyX  s   )n.E.EIZIZ.Z ..22>B	 $-L%lFLLA #9,#GL4=4N4NL11:1H1HL.=F=`=`L:&&u'C'CL'QR++L9 %. %_5::;G
   +#1155nE"99,G
''5   
r#   )r  rQ   r   r   r   addNoteGroupings)ra   r  r  mNumcurrentMeasureNumberr  	rhBraille	lhBrailles   `       r$   r   z'BrailleGrandSegment.extractNoteGroupingM  sz    "667##D??DNOO$44T%P	0 #8,	"7+	2IyIr#   Nr|  r~  )r   r    r!   r   rc   r  r   r   r  r   r   r   r"   r#   r$   r  r  E  s=    ( 2 2>T%J :0d&Jr#   r  Tr}  F)setHandr   rW   r   r   segmentBreaksrX   r   r   r   showLongSlursAndTiesTogethershowShortSlursAndTiesTogetherslurLongPhraseWithBracketsr   r`   c                  t        | |||       t        | ||      }|D ]a  }||_        ||_        ||_        |j                          ||_        ||_        ||_        |	|_	        |
|_
        ||_        |j                          c |S )u'  
    Takes in a :class:`~music21.stream.Part`.

    Returns a list of :class:`~music21.segment.BrailleSegment` instances.

    Five functions or methods get called in the generation of segments:

    * :func:`~music21.braille.segment.prepareSlurredNotes`
    * :func:`~music21.braille.segment.getRawSegments`
    * :meth:`~music21.braille.segment.BrailleSegment.addGroupingAttributes`
    * :meth:`~music21.braille.segment.BrailleSegment.addSegmentAttributes`
    * :meth:`~music21.braille.segment.BrailleSegment.fixArticulations`

    >>> from music21.braille import test
    >>> example = test.example11_2()
    >>> allSegments = braille.segment.findSegments(example)

    >>> print(str(allSegments[0]))
    ---begin segment---
    <music21.braille.segment BrailleSegment>
    Measure 0, Signature Grouping 1:
    <music21.key.KeySignature of 3 flats>
    <music21.meter.TimeSignature 4/4>
    ===
    Measure 0, Note Grouping 1:
    <music21.clef.TrebleClef>
    <music21.note.Note B->
    ===
    Measure 1, Note Grouping 1:
    <music21.note.Note G>
    <music21.note.Note E->
    <music21.note.Note D>
    <music21.note.Note E->
    ===
    Measure 2, Note Grouping 1:
    <music21.note.Note G>
    <music21.note.Note F>
    <music21.note.Note E->
    ===
    Measure 3, Note Grouping 1:
    <music21.note.Note A->
    <music21.note.Note G>
    <music21.note.Note C>
    <music21.note.Note C>
    ===
    Measure 4, Note Grouping 1:
    <music21.note.Note B->
    <music21.note.Note B->
    ===
    Measure 5, Note Grouping 1:
    <music21.note.Note E->
    <music21.note.Note B->
    <music21.note.Note A->
    <music21.note.Note G>
    ===
    Measure 6, Note Grouping 1:
    <music21.note.Note G>
    <music21.note.Note F>
    <music21.note.Note C>
    ===
    Measure 7, Note Grouping 1:
    <music21.note.Note C>
    <music21.note.Note F>
    <music21.note.Note A->
    <music21.note.Note D>
    ===
    Measure 8, Note Grouping 1:
    <music21.note.Note E->
    music hyphen ⠐
    ===
    ---end segment---

    Second segment

    >>> print(str(allSegments[1]))
    ---begin segment---
    <music21.braille.segment BrailleSegment>
    Measure 8, Note Grouping 2:
    <music21.note.Note G>
    ===
    Measure 9, Note Grouping 1:
    <music21.note.Note G>
    <music21.note.Note F>
    <music21.note.Note F>
    <music21.note.Note F>
    ===
    Measure 10, Note Grouping 1:
    <music21.note.Note A->
    <music21.note.Note G>
    <music21.note.Note B->
    ===
    Measure 11, Note Grouping 1:
    <music21.note.Note B->
    <music21.note.Note A>
    <music21.note.Note A>
    <music21.note.Note C>
    ===
    Measure 12, Note Grouping 1:
    <music21.note.Note B->
    <music21.note.Note B->
    ===
    Measure 13, Note Grouping 1:
    <music21.note.Note E->
    <music21.note.Note B->
    <music21.note.Note A->
    <music21.note.Note G>
    ===
    Measure 14, Note Grouping 1:
    <music21.note.Note G>
    <music21.note.Note F>
    <music21.note.Note C>
    ===
    Measure 15, Note Grouping 1:
    <music21.note.Note C>
    <music21.note.Rest quarter>
    <music21.note.Note F>
    <music21.note.Rest quarter>
    ===
    Measure 16, Note Grouping 1:
    <music21.note.Note A->
    <music21.note.Note D>
    ===
    Measure 17, Note Grouping 1:
    <music21.note.Note E->
    <music21.bar.Barline type=final>
    ===
    ---end segment---
    )r  r  r  r  r   )prepareSlurredNotesgetRawSegmentsrX   r`   rW   r]  r   r   r   r   r   r   r{  )music21Partr  r   rW   r   r   r  rX   r   r   r   r  r  r  r   r`   allSegmentssegs                     r$   findSegmentsr    s    j 5Q6S3M !g][K *(A%/!!# $8 -%;"%"5 	' * r#   )r  r  r  c                  | j                   sy||}| j                         j                  j                         }| j                   j	                  t
        j                        D ]  }|j                         }|j                         }	 |j                  |      }|j                  |      }	t        |	|z
        dz   }
|si|
t        k  r`||   j                  !||   j                  j                  dk(  r|dz  }||	   j                  !||	   j                  j                  dk(  r|	dz  }	|si|
t        kD  r`||   j                  !||   j                  j                  dk(  r|dz  }||	   j                  !||	   j                  j                  dk(  r|	dz  }	|
t        k  rt!        ||	      D ]  }d||   _         T|rd||   _        d||	   _        ld||dz      _        d||	dz
     _         y# t        j                  $ r Y w xY w)aF  
    Takes in a :class:`~music21.stream.Part` and three keywords:

    * slurLongPhraseWithBrackets
    * showShortSlursAndTiesTogether
    * showLongSlursAndTiesTogether

    For any slurs present in the Part, the appropriate notes are labeled
    with attributes indicating where to put the symbols that represent
    slurring in braille. For purposes of slurring in braille, there is
    a distinction between short and long phrases. In a short phrase, a
    slur covers up to four notes. A short slur symbol should follow each
    note except the last.

    >>> import copy
    >>> from music21.braille import segment
    >>> short = converter.parse('tinynotation: 3/4 c4 d e')
    >>> s1 = spanner.Slur(short.recurse().notes.first(), short.recurse().notes.last())
    >>> short.append(s1)
    >>> short.show('text')
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.clef.TrebleClef>
        {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.bar.Barline type=final>
    {3.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note E>>
    >>> shortA = copy.deepcopy(short)
    >>> segment.prepareSlurredNotes(shortA)
    >>> shortA.recurse().notes[0].shortSlur
    True
    >>> shortA.recurse().notes[1].shortSlur
    True

    In a long phrase, a slur covers more than four notes. There are two
    options for slurring long phrases. The first is by using the bracket
    slur. By default, slurLongPhraseWithBrackets is True. The opening
    bracket sign is put before the first note, and the closing bracket
    sign is put before the last note.

    >>> long = converter.parse('tinynotation: 3/4 c8 d e f g a')
    >>> s2 = spanner.Slur(long[note.Note].first(), long[note.Note].last())
    >>> long.append(s2)
    >>> long.show('text')
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.clef.TrebleClef>
        {0.0} <music21.meter.TimeSignature 3/4>
        {0.0} <music21.note.Note C>
        {0.5} <music21.note.Note D>
        {1.0} <music21.note.Note E>
        {1.5} <music21.note.Note F>
        {2.0} <music21.note.Note G>
        {2.5} <music21.note.Note A>
        {3.0} <music21.bar.Barline type=final>
    {3.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note A>>
    >>> longA = copy.deepcopy(long)
    >>> segment.prepareSlurredNotes(longA)
    >>> longA[note.Note].first().beginLongBracketSlur
    True
    >>> longA[note.Note].last().endLongBracketSlur
    True

    The other way is by using the double slur, setting `slurLongPhraseWithBrackets`
    to False. The opening sign of the double slur is put after the first note
    (i.e. before the second note) and the closing sign is put before the last
    note (i.e. before the second to last note).

    If a value is not supplied for `showLongSlursAndTiesTogether`, it will take the
    value set for `slurLongPhraseWithBrackets`, which defaults True.

    >>> longB = copy.deepcopy(long)
    >>> segment.prepareSlurredNotes(longB, slurLongPhraseWithBrackets=False)
    >>> longB.recurse().notes[1].beginLongDoubleSlur
    True
    >>> longB.recurse().notes[-2].endLongDoubleSlur
    True

    In the event that slurs and ties are shown together in print, the slur is
    redundant. Examples are shown for slurring a short phrase; the process is
    identical for slurring a long phrase.

    Below, a tie has been added between the first two notes of the short phrase
    defined above. If showShortSlursAndTiesTogether is set to its default value of
    False, then the slur on either side of the phrase is reduced by the amount that
    ties are present, as shown below.

    >>> short.recurse().notes[0].tie = tie.Tie('start')
    >>> shortB = copy.deepcopy(short)
    >>> segment.prepareSlurredNotes(shortB)
    >>> shortB.recurse().notes[0].shortSlur
    Traceback (most recent call last):
    AttributeError: 'Note' object has no attribute 'shortSlur'
    >>> shortB.recurse().notes[0].tie
    <music21.tie.Tie start>
    >>> shortB.recurse().notes[1].shortSlur
    True

    If showShortSlursAndTiesTogether is set to True, then the slurs and ties are
    shown together (i.e. the note has both a shortSlur and a tie).

    >>> shortC = copy.deepcopy(short)
    >>> segment.prepareSlurredNotes(shortC, showShortSlursAndTiesTogether=True)
    >>> shortC.recurse().notes[0].shortSlur
    True
    >>> shortC.recurse().notes[0].tie
    <music21.tie.Tie start>

    TODO: This should not add attributes to Note objects but instead return a collection
    of sets of notes that have each element applied to it.
    Nr9   startra  T)spannerBundleflattennotesr   
getByClassr   SlurgetFirstgetLastindexr   StreamExceptionabsSEGMENT_MAXNOTESFORSHORTSLURrd  re  r?  rf  beginLongBracketSlurendLongBracketSlurbeginLongDoubleSlurendLongDoubleSlur)r  r  r  r  r  slurr  r   
beginIndexendIndexdelta	noteIndexs               r$   r  r  <  s   j $$#+'A$""$**113H))44W\\BMMO	<<>	!	2J~~h/H Hz)*Q.,:V1V $((4 ,0055@a
!%%1hx6H6L6L6Q6QU[6[A+8T0T$((4 ,0055@a
!%%1hx6H6L6L6Q6QU[6[A00":x8	04#- 9 *<@$98<"5?Ca(<;?A&8Q C ++ 	 		s   "G--HHr  c               2   g }t        |      }d}d}| j                  t        j                        D ]  }t	        |       t        |      }d}	t        j                  }
|D ]  }|rd|j                  dk7  rd|_	        |j                  |       t        |      }|j                  dk7  rd|_        d}|
t        j                  ur|	dz  }	d}d|j                  v r d|j                  v r
|t        k  rn|dkD  rd}t        |t        j                         r|t        kD  r|j"                  d	v rd}|j$                  j&                  |
k  r|	dz  }	|j$                  j&                  }|t        j(                  k(  rt        j*                  }n#|t        j,                  k(  rt        j.                  }t1        |j2                  |	||      }||vrt5               ||<   ||   }|j                  |       |dz  }|j$                  j&                  }
  |j                  |       |S )
a  
    Takes in a :class:`~music21.stream.Part`, divides it up into segments (i.e. instances of
    :class:`~music21.braille.segment.BrailleSegment`). This function assumes
    that the Part is already divided up into measures
    (see :class:`~music21.stream.Measure`). An acceptable input is shown below.

    This will automatically find appropriate segment breaks at
    :class:`~music21.braille.objects.BrailleSegmentDivision`
    or :class:`~music21.braille.objects.BrailleOptionalSegmentDivision`
    or after 48 elements if a double bar or repeat sign is encountered.

    Two functions are called for each measure during the creation of segments:

    * :func:`~music21.braille.segment.prepareBeamedNotes`
    * :func:`~music21.braille.segment.extractBrailleElements`

    >>> tn = converter.parse("tinynotation: 3/4 c4 c c e e e g g g c'2.")
    >>> tn = tn.makeNotation(cautionaryNotImmediateRepeat=False)
    >>> tn.show('text')
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.clef.TrebleClef>
        {0.0} <music21.meter.TimeSignature 3/4>
        {0.0} <music21.note.Note C>
        {1.0} <music21.note.Note C>
        {2.0} <music21.note.Note C>
    {3.0} <music21.stream.Measure 2 offset=3.0>
        {0.0} <music21.note.Note E>
        {1.0} <music21.note.Note E>
        {2.0} <music21.note.Note E>
    {6.0} <music21.stream.Measure 3 offset=6.0>
        {0.0} <music21.note.Note G>
        {1.0} <music21.note.Note G>
        {2.0} <music21.note.Note G>
    {9.0} <music21.stream.Measure 4 offset=9.0>
        {0.0} <music21.note.Note C>
        {3.0} <music21.bar.Barline type=final>

    By default, there is no break anywhere within the Part,
    and a segmentList of size 1 is returned.

    >>> import copy
    >>> from music21.braille import segment
    >>> tnA = copy.deepcopy(tn)
    >>> rawSegments = segment.getRawSegments(tnA)
    >>> len(rawSegments)
    1
    >>> rawSegments[0]
    <music21.braille.segment.BrailleSegment 1 line, 0 headings, 40 cols>

    >>> print(rawSegments[0])
    ---begin segment---
    <music21.braille.segment BrailleSegment>
    Measure 1, Signature Grouping 1:
    <music21.meter.TimeSignature 3/4>
    ===
    Measure 1, Note Grouping 1:
    <music21.clef.TrebleClef>
    <music21.note.Note C>
    <music21.note.Note C>
    <music21.note.Note C>
    ===
    Measure 2, Note Grouping 1:
    <music21.note.Note E>
    <music21.note.Note E>
    <music21.note.Note E>
    ===
    Measure 3, Note Grouping 1:
    <music21.note.Note G>
    <music21.note.Note G>
    <music21.note.Note G>
    ===
    Measure 4, Note Grouping 1:
    <music21.note.Note C>
    <music21.bar.Barline type=final>
    ===
    ---end segment---

    Now, a segment break occurs at measure 2, offset 1.0 within that measure.
    The two segments are shown below.

    >>> tnB = copy.deepcopy(tn)
    >>> tnB.measure(2).insert(1.0, braille.objects.BrailleSegmentDivision())
    >>> allSegments = segment.getRawSegments(tnB)
    >>> len(allSegments)
    2

    >>> allSegments[0]
    <music21.braille.segment.BrailleSegment 1 line, 0 headings, 40 cols>

    >>> print(allSegments[0])
    ---begin segment---
    <music21.braille.segment BrailleSegment>
    Measure 1, Signature Grouping 1:
    <music21.meter.TimeSignature 3/4>
    ===
    Measure 1, Note Grouping 1:
    <music21.clef.TrebleClef>
    <music21.note.Note C>
    <music21.note.Note C>
    <music21.note.Note C>
    ===
    Measure 2, Note Grouping 1:
    <music21.note.Note E>
    ===
    ---end segment---

    >>> allSegments[1]
    <music21.braille.segment.BrailleSegment 1 line, 0 headings, 40 cols>

    >>> print(allSegments[1])
    ---begin segment---
    <music21.braille.segment BrailleSegment>
    Measure 2, Note Grouping 2:
    <music21.note.Note E>
    <music21.note.Note E>
    ===
    Measure 3, Note Grouping 1:
    <music21.note.Note G>
    <music21.note.Note G>
    <music21.note.Note G>
    ===
    Measure 4, Note Grouping 1:
    <music21.note.Note C>
    <music21.bar.Barline type=final>
    ===
    ---end segment---

    If we insert an optional division, the division
    only appears if there are 48 elements in the current segment:

    >>> tnC = copy.deepcopy(tn)
    >>> tnC.measure(1).insert(1.0, braille.objects.BrailleOptionalSegmentDivision())
    >>> allSegments = segment.getRawSegments(tnC)
    >>> len(allSegments)
    1

    If by happenstance a segment division object is encountered where a division
    has just been created (or the very beginning),
    no unnecessary empty segment will be created:

    >>> tnD = copy.deepcopy(tn)
    >>> tnD.measure(1).insert(0, braille.objects.BrailleSegmentDivision())
    >>> allSegments = segment.getRawSegments(tnD)
    >>> len(allSegments)
    1
    r   r   F        Tr9   BrailleSegmentDivisionBrailleOptionalSegmentDivision)doublefinal)r   getElementsByClassr   MeasureprepareBeamedNotesr   r&   r0   offsetr   r   r   classesMAX_ELEMENTS_IN_SEGMENTr~   r   Barlinere  r   affinityCoder6   r5   r8   r7   rO   numberrV   )r  r  r   r  currentSegmentelementsInCurrentSegmentstartANewSegmentmusic21MeasurebrailleElementsrR   previousAffinityCoder[  r  r  brailleElementGroupings                  r$   r  r    s!   p K#}=N$%"%88H>*0@'//-N!((C/ 04N, "">2!/=!I!((C/6:N3+,('x/?/??qLG#( '>+A+AA48N8NN48OO-1'+$>3;;7,/FF"''+>> $(  ''447KK1)33@@Lx888'00!:!::'11#N$9$9$+$0$+&J
 /-C-Ez*%3J%?"")).9$)$ $2#;#;#H#H w . ID ~&r#   c           	        t               }d}| D ]  }t        |t        j                        r|}!	 t        |t        j
                        r|j                  dk(  rLt        |       |t        |t        j                  t        j                  f      r^t        |       |j                  j                  |j                  _        t        |      g|j                  _        |j!                  |       d}|j!                  |       t        |      g|j                  _         |j-                  d        t/        |      dk\  rWt        |d   t0        j2                        r:t        |d   t        j
                        rd|d   _        |j-                  d        |S # t"        $ rO}t$        D cg c]  }t        ||       nc c}w }}t'        |      st(        j+                  |        Y d}~d}~ww xY w)	a0  
    Takes in a :class:`~music21.stream.Measure` or :class:`~music21.stream.Voice`
    and returns a :class:`~music21.braille.segment.BrailleElementGrouping` of correctly ordered
    :class:`~music21.base.Music21Object` instances which can be directly transcribed to
    braille.

    >>> from music21.braille import segment
    >>> tn = converter.parse('tinynotation: 2/4 c16 c c c d d d d', makeNotation=False)
    >>> tn = tn.makeNotation(cautionaryNotImmediateRepeat=False)
    >>> measure = tn[0]
    >>> measure.append(spanner.Slur(measure.notes[0],measure.notes[-1]))
    >>> measure.show('text')
    {0.0} <music21.clef.TrebleClef>
    {0.0} <music21.meter.TimeSignature 2/4>
    {0.0} <music21.note.Note C>
    {0.25} <music21.note.Note C>
    {0.5} <music21.note.Note C>
    {0.75} <music21.note.Note C>
    {1.0} <music21.note.Note D>
    {1.25} <music21.note.Note D>
    {1.5} <music21.note.Note D>
    {1.75} <music21.note.Note D>
    {2.0} <music21.spanner.Slur <music21.note.Note C><music21.note.Note D>>
    {2.0} <music21.bar.Barline type=final>

    Spanners are dealt with in :func:`~music21.braille.segment.prepareSlurredNotes`,
    so they are not returned by this function, as seen below.

    >>> print(segment.extractBrailleElements(measure))
    <music21.meter.TimeSignature 2/4>
    <music21.clef.TrebleClef>
    <music21.note.Note C>
    <music21.note.Note C>
    <music21.note.Note C>
    <music21.note.Note C>
    <music21.note.Note D>
    <music21.note.Note D>
    <music21.note.Note D>
    <music21.note.Note D>
    <music21.bar.Barline type=final>
    Nregularc                2    | j                   | j                  fS re   r  classSortOrderxs    r$   <lambda>z(extractBrailleElements.<locals>.<lambda>  s    AHHa.>.>#?r#   r   r:   r'   c                2    | j                   | j                  fS re   r  r  s    r$   r  z(extractBrailleElements.<locals>.<lambda>  s    AHHa6F6F+Gr#   )rV   r~   r	   r   r   r  re  setAffinityCoder   rT  r   r   r   r  r   r   r   r   r=   r   r   r   sortrs   r
   Dynamicr  )music21MeasureOrVoiceallElementsr  music21ObjectnotSupportedExceptionmusic21ClassisExempts          r$   r   r     s   X )*K $I.mTYY/%I	>-5 %%2M*$!D$4$4fll#C*E  	*3@3J3J3W3W	##069)n5E	##2""9- 	}-69-6H5IM##2- /< ?@
;1KOX=M=M!Nk"os{{3-/KO*!GH ' 	>,FH,FL #=,?,FHH Hx=!!%:$;=		>s*   )FCF	G1"G,*F>=)G,,G1c                x   | j                   j                         }|D ]  }d|_        d|_         | j                  j                         }d }d }d }|j                         j                  |      j                  |      }|j                         j                  |      j                  |      }t        |      t        |      k7  rt        j                  d       yt        |      D ]  \  }	}
|
j                  dk(  r||	   }|j                  |
      }|j                  |      }||z
  dz   }|d	k  rLd
}t        |dz   |dz         D ]?  }||   j                  |
j                  k7  st        ||   t        j                         s=d} n 	 ||dz      }t        |t        j                         r-t#        |j$                        t#        |j$                        k(  rd}|s	 ||dz      j                  dk(  r	 d
|
_        	 ||dz
     }t        |t        j                         rKt#        |j$                        t#        |
j$                        k(  r |j                  |
j                  k(  rd
|
_        t        |dz   |dz         D ]  }d
||   _          y# t&        $ r Y w xY w# t&        $ r Y w xY w# t&        $ r Y Nw xY w)a#  
    Takes in a :class:`~music21.stream.Measure` and labels beamed notes
    of smaller value than an 8th with beamStart and beamContinue keywords
    in accordance with beaming rules in braille music.

    A more in-depth explanation of beaming in braille can be found in
    Chapter 15 of Introduction to Braille Music Transcription, Second
    Edition, by Mary Turner De Garmo.

    >>> from music21.braille import segment
    >>> tn = converter.parse('tinynotation: 2/4 c16 c c c d d d d')
    >>> tn = tn.makeNotation(cautionaryNotImmediateRepeat=False)
    >>> tn.show('text')
    {0.0} <music21.stream.Measure 1 offset=0.0>
        {0.0} <music21.clef.TrebleClef>
        {0.0} <music21.meter.TimeSignature 2/4>
        {0.0} <music21.note.Note C>
        {0.25} <music21.note.Note C>
        {0.5} <music21.note.Note C>
        {0.75} <music21.note.Note C>
        {1.0} <music21.note.Note D>
        {1.25} <music21.note.Note D>
        {1.5} <music21.note.Note D>
        {1.75} <music21.note.Note D>
        {2.0} <music21.bar.Barline type=final>
    >>> measure = tn[0]
    >>> segment.prepareBeamedNotes(measure)
    >>> measure.notes[0].beamStart
    True
    >>> measure.notes[1].beamContinue
    True
    >>> measure.notes[2].beamContinue
    True
    >>> measure.notes[3].beamContinue
    True
    Fc                R    | j                   d uxr t        | j                         dkD  S )Nr   )beamsrs   r   unuseds     r$   withBeamFilterz*prepareBeamedNotes.<locals>.withBeamFilterI  s#    $;#bhh-!*;;r#   c                R    | j                   j                  d      j                  dk(  S )Nr9   r  r  getByNumberre  r  s     r$   beamStartFilterz+prepareBeamedNotes.<locals>.beamStartFilterL  s"    xx##A&++w66r#   c                R    | j                   j                  d      j                  dk(  S )Nr9   ra  r  r  s     r$   beamStopFilterz*prepareBeamedNotes.<locals>.beamStopFilterO  s"    xx##A&++v55r#   zDIncorrect beaming: number of start notes != to number of stop notes.Ng      ?r9   r(   T)r  r   	beamStartbeamContinuenotesAndRestsrf   	addFilterrs   r   r   	enumeratequarterLengthr  r?  r~   r   rU  rP   beatr  )r  r  
sampleNoteallNotesAndRestsr  r  r  allStartIterallStopIter	beamIndex	startNotestopNote
startIndex	stopIndexr  allNotesOfSameValuer  afterStopNotebeforeStartNotes                      r$   r  r    s   J ##**,H
$
"'
  &33::<<76 ==?,,^<FFWL--/++N;EEnUK
<C,,`a ), 7	9 ""c)y)%++I6
$**84	J&*19 #zA~y1}=I +99Y=T=TT!"29"=tyyI&+#	 >
	,Y];M=$))4]//0C4FF&+# #	  	A.<<C D
 #		.zA~>O?DII6O001S5HH'559P9PP)-	& zA~y1}=I7;Y'4 >c !86  		  		  		s8   
AJJ=A-J-	JJ	J*)J*-	J98J9c                   t         D ],  \  }}}t        | |      s|| j                  _        || _         y t        | t
        j                        rlt        j                  | j                  _        t        | j                  j                               dkD  rt        j                  | j                  _        d| _        yt        | t              ryt        |  d      )ab  
    Takes in a :class:`~music21.base.Music21Object`, and does two things:

    * Modifies the :attr:`~music21.base.Music21Object.classSortOrder` attribute of the
      object to fit the slightly modified ordering of objects in braille music.

    * Adds an affinity code to the Editorial for the object.
      This code indicates which surrounding objects the object should be grouped with.

    A BrailleSegmentException is raised if an affinity code cannot be assigned to
    the object.

    As seen in the following example, the affinity code of a :class:`~music21.note.Note`
    and a :class:`~music21.clef.TrebleClef` are the same, because they should be grouped
    together. However, the classSortOrder indicates that the TrebleClef should come first
    in the braille.

    >>> n1 = note.Note('D5')
    >>> braille.segment.setAffinityCode(n1)
    >>> n1.editorial.affinityCode
    <Affinity.NOTEGROUP: 9>
    >>> n1.classSortOrder
    10
    >>> c1 = clef.TrebleClef()
    >>> braille.segment.setAffinityCode(c1)
    >>> c1.editorial.affinityCode
    <Affinity.NOTEGROUP: 9>
    >>> c1.classSortOrder
    7
    Nr9   r-   z" cannot be transcribed to braille.)r;   r~   r   r  r  r   TextExpressionr&   r7   rs   contentsplitr4   r   r   )r  r  code	sortOrders       r$   r  r    s    > ,9'tYm\237M##0+4M(	 ,9 -!;!;</7/A/A,}$$**,-13;3I3IM##0'($-!;<
!]O3U"V
WWr#   c                j    t        |       t        |      k(  rt        | |      D ]  \  }}||k7  s y yy)a3  
    Takes in two note groupings, noteGroupingA and noteGroupingB. Returns True
    if both groupings have identical contents. False otherwise.

    Helper for numRepeats.

    Needs two identical length groupings.

    >>> a = [note.Note('C4'), note.Note('D4')]
    >>> b = [note.Note('C4'), note.Note('D4')]
    >>> braille.segment.areGroupingsIdentical(a, b)
    True

    >>> d = b.pop()
    >>> braille.segment.areGroupingsIdentical(a, b)
    False
    >>> c = [note.Rest(), note.Note('D4')]
    >>> braille.segment.areGroupingsIdentical(a, c)
    False
    FT)rs   r   )noteGroupingAnoteGroupingBelementAelementBs       r$   rO  rO    s@    * =S//$'}$E Xx8# %F r#   c                |   t        j                         }| D ]  }|j                  |j                  |         t	        ||| j
                        \  }}t        j                  |       }g |_        |D ]  }|j                  |        t        j                  |       }g |_        |D ]  }|j                  |        ||fS )a  
    Almost identical to :func:`~music21.braille.segment.splitMeasure`, but
    functions on a :class:`~music21.braille.segment.BrailleElementGrouping`
    instead.

    >>> from music21.braille import segment
    >>> bg = segment.BrailleElementGrouping()
    >>> bg.timeSignature = meter.TimeSignature('2/2')
    >>> s = converter.parse('tinyNotation: 2/2 c4 d r e')
    >>> for n in s.recurse().notesAndRests:
    ...     bg.append(n)
    >>> left, right = segment.splitNoteGrouping(bg)
    >>> left
    <music21.braille.segment.BrailleElementGrouping
        [<music21.note.Note C>, <music21.note.Note D>]>

    >>> print(left)
    <music21.note.Note C>
    <music21.note.Note D>

    >>> right
    <music21.braille.segment.BrailleElementGrouping
        [<music21.note.Rest quarter>, <music21.note.Note E>]>

    Now split one beat division earlier than it should be.  For 2/2 that means
    one half of a beat, or one quarter note earlier:

    >>> left, right = segment.splitNoteGrouping(bg, beatDivisionOffset=1)
    >>> left
    <music21.braille.segment.BrailleElementGrouping
        [<music21.note.Note C>]>
    >>> right
    <music21.braille.segment.BrailleElementGrouping
        [<music21.note.Note D>, <music21.note.Rest quarter>, <music21.note.Note E>]>
    )	r   r  r   r  splitMeasurerA   copyr_   r   )r   r!  r  r[  leftMeasurerightMeasureleftBrailleElementsrightBrailleElementss           r$   r&  r&    s    H ^^%N&n33^D '".~/A/;/I/I#K[, ))L1')$%"">2 &  99\2(*%&##N3 '  444r#   c                   ||}n| j                         }d}|dk7  rt        |      t        |j                        kD  rt	        d| d|j                         t        |j                        t        |      z
  }	 |t        |j                  |   j                        z  }t        |      }t        j                  |j                        }d}	 |j                  |d	       |j                         d   \  }}	|	|z  }	t%        j&                         }
t%        j&                         }| D ]  }|j(                  |k\  rU|j(                  |	k  s)|j(                  |	k(  r7t+        |t,        j.                        r|
j1                  |j(                  |       g|j1                  |j(                  |        |j2                  D ]K  }|j4                  <|
j7                  |       |j9                  |       |	|j:                  j                  z  }	K n | j:                  j                  |	z
  }t=        j>                  |      }|
j1                  |	|       t=        j>                  |	      }|j1                  d|       d}|
j@                  	d}||
_         ||_         |
jC                  |        |jC                  |        |
jE                  d       |jE                  d       tG        |
       tG        |       |
j9                  |       |j9                  |       |r|
j9                  |       |j9                  |       |
|fS # t        $ r' t        j                  d| j                   d       Y w xY w# t         j"                  $ rH |d
z  }|j                  |d	       |j                         d   d   }|j                         d   d   }	Y w xY w)aS  
    Takes a :class:`~music21.stream.Measure`, divides it in two parts, and returns a
    two-tuple of (leftMeasure, rightMeasure). The parameters are as
    follows:

    * beatDivisionOffset => Adjusts the end offset of the first partition by a certain amount
      of beats to the left.
    * useTimeSignature => In the event that the Measure comes from the middle of a Part
      and thus does not define an explicit :class:`~music21.meter.TimeSignature`. If not
      provided, a TimeSignature is retrieved by
      using :meth:`~music21.stream.Measure.bestTimeSignature`.

    >>> m = stream.Measure()
    >>> m.append(note.Note('C4'))
    >>> m.append(note.Note('D4'))
    >>> left, right = braille.segment.splitMeasure(m)
    >>> left.show('text')
    {0.0} <music21.note.Note C>
    >>> right.show('text')
    {1.0} <music21.note.Note D>
    r  r   zbeatDivisionOffset z( is outside of ts.beatDivisionDurations z2Problem in converting a time signature in measure z, offset may be wrongr:   F)loadDefaultr9   r  r'   )r  T)inPlace)$bestTimeSignaturer  rs   beatDivisionDurationsr   r   r  r  r   r   r  r6  deepcopybeatSequencepartitionByCountgetLevelSpanr   MeterExceptionr   r  r  r~   r   r  r   r  rd  r   rg  durationr   rU  rA   mergeAttributes	makeBeamsr  )r  r!  useTimeSignaturetsr  duration_indexbsnumberOfPartitionsstartOffsetZeroendOffsetZeror7  r8  r  r  rest0Lengthr0r1
ts0_deletes                     r$   r5  r5  	  s   , #--/FQ!"S)A)A%BB)%&8%9 ://1/G/G.HJ  R556=O9PP	OfR55nESSTTFF^F 
r	'B2
.EB+-??+<Q+?(- VM.."K>>#LHH'XX-]2'3;;7qxx+!,  55q!"QZZ555M   !))77-GK		-B}b)		/BR J  (
$&!!#L/  0$'4({#|$r2&&s  	OR!/!6!6 77LN O	O  2a
.EB//+A.q1)"-b1	2s%   ;0L1 )M$ 1,M! M!$AN?>N?c                      e Zd Zd Zy)Testc                    ddl m} |j                  d      }|j                  d      }t	        |      }t        |d         }y )Nr   )	converterz)tinynotation: 3/4 c4 c c e e e g g g c'2.F)cautionaryNotImmediateRepeat)rr  rV  parsemakeNotationr  r   )ra   rV  tn
rawSegListr  s        r$   testGetRawSegmentszTest.testGetRawSegments~	  s<    %__HI__%_@#B'
Z]#r#   N)r   r    r!   r\  r"   r#   r$   rT  rT  |	  s    $r#   rT  __main__)r  zbool | None)r   rP   )r  zstream.Measure | stream.Voicer   rV   )r  zbase.Music21Object)r   )r   N)or   
__future__r   collectionsr   r   r6  enumtypingtunittestrr  r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   music21.prebaser   music21.brailler   r   r   r   r   music21.braille.objectsr   music21.common.numberToolsr   r   Environmentr   Music21Exceptionr   IntEnumr&   CSO_NOTECSO_REST	CSO_CHORDCSO_DYNAMICCSO_CLEFCSO_BARLINE
CSO_KEYSIGCSO_TIMESIG	CSO_TTEXT	CSO_MMARK	CSO_VOICEr  r7   rU  Chordr  r   r  r8   rF   r1   rG   	TempoTextr2   MetronomeMarkr3   r   r5   r;   rB   r4   r6   r<   r  SystemLayout
PageLayoutStaffLayoutr=   	TypedDictr?   rC   rH   r  r  rJ   
NamedTuplerO   rV   r   r   r  r  r  r  r  r   r  r  rO  r&  r5  TestCaserT  r   mainTestr"   r#   r$   <module>r     s   # )                     * ! " 1   > - ..&{&&|4	l;; 	
t|| 
 	
			 
YY""H-	YY""H-
[[($$i0x));7	YY""H-[[(++[9x)):6
(,,k:
__hnni0
(..)4\\8$$i0GC  ,NN)NN-;*66	&" 	 LL


	> : ,akk , % / G  !  24PQ  t'^ t'nmT%% m`nJ.$*>*> nJD
 &*"&!%!#$(,!;?/4,0%*+/!t 09tr 486;BF	c@ 7@	c@P  (*c #&cLR6RRjn<b/Xd@45n_'J	$8 	$ zGT r#   