
    rhHt                   R   % S r SSKJr  SSKJrJr  SSKrSSKrSSKr	SSK
r
SSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJ r!  SSKJ"r"  SSK#J$r$  SSK%J&r&  \RN                  r'\RP                  " S5      r) " S S\RT                  5      r+ " S S\RX                  5      r-S r.S r/S r0S!r1S"r2Sr3S#r4S$r5S%r6S&r7S r8\Rr                  \-Rt                  \.4\Rv                  \-Rt                  \/4\Rx                  \-Rt                  \04\Rz                  \-Rt                  \14\R|                  \-Rt                  \24\R~                  \-R                  \34\R                  \-R                  \44\R                  \-R                  \54\R                  \-R                  \64\R                  \-R                  \74\R                  \-R                  \84/rJS'\KS('   \-R                  S)\-R                  S*\-R                  S+\-R                  S,\-R                  S-\-Rt                  S.\-R                  S/\-R                  S00rNS1\KS2'   \R                  \R                  \R                  \R                  /rSS3\KS4'    " S5 S6\	R                  5      rUSSS7.rVS6\KS8'   S9 rWS&rXS:rY\" S;/ S<Q5      rZ " S= S>\	R                  5      r\ " S? S@\5      r] " SA SB\"R                  5      r_ " SC SD\_\"R                  5      raSSESSSFSSGSESSESSGSESGSESH. SWSI jjrbSESGSSJ. SWSK jjrcSSFSL. SXSM jjrd    SYSN jreSO rfSZSP jrgSQ rhS[SR jriS\SS jrj " ST SU\
R                  5      rl\mSV:X  a  SSKr\R                  " \l5        gg)]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                      \ rS rSrSrg)BrailleSegmentException;    N)__name__
__module____qualname____firstlineno____static_attributes__r        Q/home/james-whalen/.local/lib/python3.13/site-packages/music21/braille/segment.pyr   r   ;   s    r&   r   c                  8    \ rS rSrSrSrSrSrSrSr	Sr
S	rS
rSrg)Affinity?                     	   
   r    N)r!   r"   r#   r$   _LOWEST	SIGNATURETTEXTMMARKLONG_TEXTEXPRINACCORDSPLIT1_NOTEGROUP	NOTEGROUPSPLIT2_NOTEGROUPr%   r    r&   r'   r)   r)   ?   s1    GIEEMHIr&   r)   r3   r2   r0         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                  *    \ rS rSr% S\S'   S\S'   Srg)GroupingGlobalsz   zkey.KeySignature | NonekeySignaturezmeter.TimeSignature | NonetimeSignaturer    N)r!   r"   r#   r$   __annotations__r%   r    r&   r'   rC   rC   z   s    ''++r&   rC   )rE   rF   GROUPING_GLOBALSc                     [         S   c  [        R                  " S5      [         S'   [         S   c  [        R                  " S5      [         S'   gg)z
sets defaults for grouping globals.  Called first time anything
in Braille is run, but saves creating two expensive objects if never run
rE   Nr   rF   4/4)rH   r   KeySignaturer   TimeSignaturer    r&   r'   setGroupingGlobalsrM      sK    
 '/+.+;+;A+>((0,1,?,?,F) 1r&   0   _ThreeDigitNumber)hundredstensonesc                  N    \ rS rSr% SrS\S'   SrS\S'   SrS\S'   SrS	\S
'   Sr	g)
SegmentKey   r   intmeasureordinalNzAffinity | Noneaffinityz
str | Nonehandr    )
r!   r"   r#   r$   rW   rG   rX   rY   rZ   r%   r    r&   r'   rT   rT      s*    GSGS"Hm"D(r&   rT   c                  j    \ rS rSr% SrSSSSSSS	.rS
\S'   S rS rS r	S r
S rS rSS jrS rSrg)BrailleElementGrouping   a  
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.)rE   rF   descendingChordsshowClefSigns
withHyphen
numRepeatsdict[str, str]	_DOC_ATTRc                    [        U6 U l        [        5         [        S   U l        [        S   U l        SU l        SU l        SU l        SU l	        SU l
        g )NrE   rF   TFr   )listinternalListrM   rH   rE   rF   r^   r_   upperFirstInNoteFingeringr`   ra   )selflistElementss     r'   __init__BrailleElementGrouping.__init__   sU     ,/,^<-o> $")-&r&   c                ,    [        U R                  5      $ N)iterrf   rh   s    r'   __iter__BrailleElementGrouping.__iter__       D%%&&r&   c                     U R                   U   $ rm   rf   rh   items     r'   __getitem__"BrailleElementGrouping.__getitem__   s      &&r&   c                     X R                   U'   g rm   rt   )rh   posrv   s      r'   __setitem__"BrailleElementGrouping.__setitem__   s    !%#r&   c                ,    [        U R                  5      $ rm   )lenrf   ro   s    r'   __len__BrailleElementGrouping.__len__   s    4$$%%r&   c                P    US:X  a  [        S5      e[        U R                  U5      $ )Nrf   zinternalList not defined yet)AttributeErrorgetattrrf   )rh   attrs     r'   __getattr__"BrailleElementGrouping.__getattr__   s)    >! !?@@t(($//r&   c                Z   / nSnU  H  n[        U[        R                  5      (       an  U(       a%  UR                  S[        R
                  S    35        U H8  n UR                  SR                  UR                  R                  5      5        M:     SnM   UR                  SR                  UR                  R                  5      5        SnM     U R                  S:  a"  UR                  SU R                  S-    S	35        U R                  SL a%  UR                  S
[        R
                  S    35        SR                  U5      nU$ ! [        [        4 a    UR                  [        U5      5         GM"  f = f! [        [        4 a    UR                  [        U5      5         Nf = f)zW
Return a unicode braille representation
of each object in the BrailleElementGrouping.
Fzfull inaccord full_inaccord
Tr   z** Grouping x r=   z **zmusic hyphen music_hyphen)
isinstancer   Voiceappendr   symbolsjoin	editorialbrailleEnglishr   	TypeErrorstrra   r`   )rh   
allObjectsprevious_was_voiceobjobj2outs         r'   __str__BrailleElementGrouping.__str__   sq   
 
#(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45 '	2 0%%c#h/0s$   4E4E=*E:9E:=*F*)F*c                ,    [        U R                  5      $ rm   )reprrf   ro   s    r'   _reprInternal$BrailleElementGrouping._reprInternal  rr   r&   )r^   rf   rE   ra   r_   rF   rg   r`   N)returnr   )r!   r"   r#   r$   __doc__rc   rG   rj   rp   rw   r{   r   r   r   r   r%   r    r&   r'   r\   r\      sZ    (T ^a?8
 MF!I~ 
''&&0
<'r&   r\   c            
        ^  \ rS rSr% SSSSSSSS	S
S.	rS\S'   S*S+U 4S jjjrS rS rS r	S r
S rS rS r\S 5       rS rS rS rS rS rS rS,S jrS rS-S jrS.S  jr  S/S! jrS,S" jrS# rS$ rS% rS& rS' r S( r!S)r"U =r#$ )0BrailleSegmenti  z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beginsMidMeasurerb   rc   c                  > [         TU ]  US9  0 U l        [        5       U l        SU l        SU l        SU l        SU l        SU l	        SU l
        SU l        SU l        SU l        SU l        SU l        SU l        SU l        SU l        g)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)superrj   _groupingDictr   groupingKeysToProcesscurrentGroupingKeypreviousGroupingKeylastNoter_   rg   r^   r   r   r   r   r   r   r   r   )rh   r   	__class__s     r'   rj   BrailleSegment.__init__3  s    p 	J/GI8="3748 (,#(/3&&*$(!#&*##(  %r&   c                     X R                   U'   g rm   r   )rh   rv   values      r'   r{   BrailleSegment.__setitem__  s    #(4 r&   c                l    XR                   ;  a  [        5       U R                   U'   U R                   U   $ rm   )r   r\   ru   s     r'   rw   BrailleSegment.__getitem__  s2    )))'='?Dt$!!$''r&   c                \    XR                   ;  a  U R                  U	 g [        SU< S35      $ )NzNo item z in Segment)__dict__r   
ValueErrorru   s     r'   __delitem__BrailleSegment.__delitem__  s.    }}$""4(<==r&   c                .    [        U R                  U5      $ rm   )r   r   ru   s     r'   r   BrailleSegment.__getattr__  s    t))400r&   c                    XR                   ;   $ rm   r   ru   s     r'   __contains__BrailleSegment.__contains__  s    ))))r&   c                ,    [        U R                  5      $ rm   )rn   r   ro   s    r'   rp   BrailleSegment.__iter__  s    D&&''r&   c                ,    [        U R                  5      $ rm   )r~   r   ro   s    r'   r   BrailleSegment.__len__  s    4%%&&r&   c                @    [         R                  R                  U 5      $ )z0
Returns the string from the BrailleText object
)r   BrailleTextr   ro   s    r'   brailleTextBrailleSegment.brailleText  s    
 ''--r&   c                n   Sn[        U R                  5       5      n/ n/ n[        5       nU H  u  pg UR                  [        R
                  :X  a  UnM(   UR                  SR                  UR                  [        UR                     UR                  S-   5      5        [        U5      nUR                  U5        UnM     SR                  [        [        X45      5       V	V
s/ s H  u  pSR                  XS/5      PM     sn
n	5      nSR                  SUUS/5      nU$ ! [         a     Nf = fs  sn
n	f )	Nz(<music21.braille.segment BrailleSegment>zMeasure {0}, {1} {2}:
r=   r    z
===z---begin segment---z---end segment---)sorteditemsrT   rY   r)   r:   r   r   formatrW   r@   rX   r   r   re   zip)rh   nameallItemsallKeysallGroupingsprevKeyitemKeygroupinggStrkgallElementGroupingsr   s                r'   r   BrailleSegment.__str__  s?   9$**,',#+W##x'@'@@%G A
 NN4;;GOO=J7K[K[=\=D__q=PR S x=D%G $, #ii8<S=W8X)Z8Xfq *,!)A8X)Z [ii.--/ 0 
  )Zs    D!#D1
!
D.-D.c                |   [        [        U R                  5       5      5      U l        U R                  (       a  U R                  5         U R                  (       a  U R                  5         U R                  b  U R                  5         SU l
        U R                  (       Ga  U R                  R                  5       U l        U R                  R                  nU[        R                  :X  a  U R!                  5         OU[        R"                  :X  a  U R%                  5         OnU[        R&                  :X  a  U R)                  5         OIU[        R*                  :X  a  U R-                  5         O$U[        R.                  :X  a  U R1                  5         U R                  U l
        U R                  (       a  GM  U R2                  $ )z
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   rY   r)   r;   extractNoteGroupingr5   extractSignatureGroupingr8   extractLongExpressionGroupingr9   extractInaccordGroupingr6   extractTempoTextGroupingr   )rh   cgkAffinityGroups     r'   
transcribeBrailleSegment.transcribe  sE    &+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                ~    U H7  n[         R                   H   n[        X#5      (       d  M  [        X#5        M"     M9     g)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)rh   r   elkws       r'   _cleanupAttributes!BrailleSegment._cleanupAttributes  s.    
 B002??BO 1 r&   c                    U R                   [        R                  S   -  /nU R                  SR	                  U5      5        g)u	  
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)
⠄⠄⠄⠄
dummyr   N)r   r   restsaddSignaturesr   )rh   
dummyRestss     r'   r   BrailleSegment.addDummyRests  s7     **V\\'-BBC
277:./r&   c                   U R                   =(       d"    [        [        U R                  5       5      5      nUS   nUR                  n[
        R                  " U5      nU R                  (       a  U[        S   -  nU R                  U5        g)us  
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   rW   r   numberToBrailler   r   addMeasureNumber)rh   gkpfirstSegmentKeyinitMeasureNumberbrailleNumbers        r'   r   #BrailleSegment.extractMeasureNumber  so    4 ((FE&2E,Fa&+33--.?@  WU^+Mm,r&   c                   SnSnSnSnU R                   =(       d"    [        [        U R                  5       5      5      nU(       a  US   R                  [
        R                  :  a  OUR                  5       nUR                  nU R                  R                  U5      nU[
        R                  :X  aR  [        U5      S:  a
  US   US   p!Ol[        U5      S:X  a)  US   n	[        U	[        R                  5      (       a  U	nO6U	nO3U[
        R                  :X  a  US   nOU[
        R                  :X  a  US   nU(       a  M  [!        XX4/5      (       a4  ["        R$                  " UUUUU R&                  S9n
U R)                  U
5        gg)z
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>   r=   maxLineLength)r   r   r   r   rY   r)   r7   r   r   getr5   r~   r   r   rK   r6   anyr   transcribeHeadingr   
addHeading)rh   rE   rF   	tempoTextmetronomeMarkr   cgkr   currentBrailleGroupingkeyOrTimeSigbrailleHeadings              r'   r   BrailleSegment.extractHeading'  sk    	 !% : : XeF499;DW>X#$Q'008>>A'//1C"||%)%7%7%;%;C%@"8#5#55-.!33I!3L3I!3L #0/0A5#9!#<L!,0@0@AA'3(4!X^^3215	!X^^3 6q 9+ $#. YFGG"44"ooN OON+ Hr&   c                b   U R                   c  [        S5      eU R                  U R                      nS nSnU H  n[        U[        R
                  5      (       a  UnM&  [        U[        R                  5      (       d  [        R                  U S35        [        U5      nU(       a  UR                  SU5        S nUR                  Ul        UR                  Ul        UR                  Ul        U(       a	  [        S   OSnU[         R"                  " U5      -  nU R%                  U5        SnM     g )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insertr^   r_   rg   r   ngModtranscribeNoteGroupingaddInaccord)rh   	inaccords	last_clef
seen_voicemusic21VoiceOrClefr   brailleInaccords          r'   r   &BrailleSegment.extractInaccordGroupingW  s   ""*bcc&&t'>'>?	$(	 
"+,dii8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                    U R                   nU R                  R                  U5      nUS   n[        R                  " U5      nU R                  U5        g)z^
Extract the Long Expression that is in the ElementGrouping in cgk
and add it to brailleText.
r   N)r   r   r  r   textExpressionToBrailleaddLongExpression)rh   r  currentElementGroupinglongTextExpressionlongExprInBrailles        r'   r   ,BrailleSegment.extractLongExpressionGroupingp  sR    
 %%!%!3!3!7!7!<3A6!99:LM01r&   c                   U R                   nU R                  nUb  Ub  UR                  [        R                  :w  do  UR                  [        R                  :w  dQ  UR
                  UR
                  :X  a>  UR                  UR                  S-   :X  a!  UR                  UR                  :X  a  SU l        U R                  (       a  gU Vs/ s H&  n[        U[        R                  5      (       d  M$  UPM(     nnSnU(       a=  U R                  b&  US   n[        R                  " U R                  U5      nUS   U l        U$ s  snf )aV  
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

Nr=   FTr   r+   )r   r   rY   r)   r;   rW   rX   rZ   r   r   r   r   Noter   showOctaveWithNote)rh   r   
currentKeypreviousKeynallNotesshowLeadingOctave	firstNotes           r'   !showLeadingOctaveFromNoteGrouping0BrailleSegment.showLeadingOctaveFromNoteGrouping{  s   D ,,
.. #*$$(:(::&&(*<*<<&&+*=*=="**k.A.AA.EE";+;+;; $##  ,H|!z!TYY/GA|H }}($QK	$)$<$<T]]I$V!$RLDM   Is   	#E 0E c                    U R                   S-  nU R                   U R                  R                  -
  nX2:  a  [        U5      U:  a  gg)a  
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textLocationr~   )rh   brailleNoteGroupingquarterLineLength	spaceLefts       r'   needsSplitToFitBrailleSegment.needsSplitToFit  sH    & !OOq0OOd&6&6&C&CC	)+,/@@r&   c                   [         R                  " 5       nSnSnSu  pxSn	XV:  aP  [        UUS9u  pxX$l        SUl        UR                  U5      n	U R                  R                  XS9(       a  OUS-  nMU  U R                  (       + n
Xl        UR                  U5      nU R                  nUR                  [        R                  S	9nUR                  [        R                  S	9nXpU'   XU'   X4$ )
zh
Take a noteGrouping and split it at a logical place,
returning braille transcriptions of each section.
r   r3   NNN)beatDivisionOffsetTaddSpacer=   rY   )r  NoteGroupingTranscribersplitNoteGroupingr0  r`   transcribeGroupr5  	canAppendr   r   _replacer)   r:   r<   )rh   r   showLeadingOctaveOnFirstaddSpaceToFirsttranscriberr>  REASONABLE_LIMITsplitNoteGroupAsplitNoteGroupBbrailleNoteGroupingAr0  brailleNoteGroupingBr,  aKeybKeys                  r'   splitNoteGroupingAndTranscribe-BrailleSegment.splitNoteGroupingAndTranscribe  s    335-9*# 31B#52._ -E))-O&#.#>#>#O ))*>)Y!# $ 8 88(9%*::?K,,
 ""H,E,E"F""H,E,E"F$T
$T
$;;r&   c                Z   [         R                  " 5       nU R                  c  [        S5      eU R                  U R                     nU R                  U5      nX1l        UR                  U5      nU R                  U5      nU R                  R                  XES9(       a  U R                  R                  XES9  OU R                  U5      nU(       a@   U R                  UUU5      u  pxU R                  R                  XuS9  U R                  U5        U(       dW  USL a'  U R                   SL a  SUl        UR                  U5      nU R                  R#                  5         U R                  U5        U R%                  UR&                  5        U R)                  U5        g! [         a    Sn Nf = f)zN
Fundamentally important method that adds a noteGrouping to the braille line.
Nz?currentGroupingKey must not be None to call extractNoteGroupingr?  FT)r  rB  r   r   r   r2  r0  rD  !optionalAddKeyboardSymbolsAndDotsr5  rE  r   r:  rQ  addToNewLiner   r   lastHyphenToSpaceaddRepeatSymbolsra   r   )	rh   rI  r   r0  r7  r@  should_splitbngAbngBs	            r'   r   "BrailleSegment.extractNoteGrouping$  s    335""*^__))$*A*AB BB<P(9%)99,G99:MN%%&9%M##$7#K!%!5!56I!JL)!%!D!D\ARAI"KJD $$++D+D%%d+   %-$2J2Je2S 59K1*5*E*El*S'  224!!"56l556-- / ) $)L)s   ?F F*)F*c                    SUs=:  a  S:  a.  O  O+[        U5       H  nU R                  [        S   5        M     gUS:  a7  U R                  [        S   [        R                  " U5      -   5        SU l        gg)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   )rh   repeatTimesunused_repeatCounters      r'   rW  BrailleSegment.addRepeatSymbolsY  sk    0 {Q(-k(:$""78#45 );Awx053H3H3UUV DM r&   c                   SnSnU R                   nU R                  R                  U5      n[        U5      S:  a
  US   US   p!O[[        U5      S:X  aL  U R                  R                  U R                   5      S   n[	        U[
        R                  5      (       a  UnOUnSnU R                  (       a  Ub   UR                  n[        R                  " XU5      nUS:w  a  U R                  U5        gg! [         a     N<f = f)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   r=   r   )r   r   r  r~   r   r   rK   r   outgoingKeySigr   r   transcribeSignaturesr   )rh   rE   rF   r  r   r  rc  
brailleSigs           r'   r   'BrailleSegment.extractSignatureGroupingy  s    
 %%))--c2|!*6q/<?-!#--11$2I2IJ1ML,(8(899+ ,$$)A!-!<!< //^\
z* 	 " s   7C3 3
D ?D c                (   U R                   R                  U R                  5        U R                  R                  [
        R                  :X  a%  U R                   R                  U R                  5        U R                  5         U R                  5         g)z)
Extracts a tempo text and processes it.
N)	r   
appendleftr   r   rY   r)   r5   r   r   ro   s    r'   r   'BrailleSegment.extractTempoTextGrouping  sj     	""--d.E.EF##,,0B0BB&&11$2J2JK!!#r&   c                   [        U R                  5      nSn[        U R                  5       5       HL  u  p4UR                  [
        R                  :w  a  XAU'   SnM+  Uc  UnU H  nX   R                  U5        M     MN     U$ )a  
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   rY   r)   r;   r   )rh   
newSegmentpngKeygroupingKeygroupingListrv   s         r'   consolidateBrailleSegment.consolidate  s~    4 $DOO4
+1$**,+?'[##x'9'99*6;'>(F(D&--d3 ) ,@ r&   c                b   [         R                  " S5      n[        R                  " S5      n[	        U R                  5       5      nSu  pEU GH  u  pgUb  UR                  S:  a  SUl        UR                  S:X  a  UR                  [        R                  :X  a  UR                  S:X  a{  UR                  [        R                  :X  a]  [        US   [        R                  5      (       a  [        USS U5      nO[        XW5      nU(       a  U=R                  S-  sl        X	 M  UR                  [        R                   :X  aW  U HO  n	[        U	[        R                  5      (       a  U	nM&  [        U	[         R                  5      (       d  MG  Xl        U	nMQ     GO2UR                  [        R$                  [        R                  4;   Ga  [        US   [        R                  5      (       as  [        US   [        R&                  [        R(                  45      (       a  SU l        O9[        US   [        R,                  [        R.                  45      (       a  SU l        U V
s/ s H&  n
[        U
[0        R2                  5      (       d  M$  U
PM(     nn
[5        U5      S:X  a,  [        US   [0        R6                  5      (       a
  SUS   l        Xl        X'l        U R*                  Ul        U R>                  Ul        U R@                  Ul         XgpTGM     U RB                  (       a  SUl        ggs  sn
f )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   rJ   r=  Nr=   TF)"r   rK   r   rL   r   r   rX   r`   rY   r)   r;   r   r	   r  areGroupingsIdenticalra   r5   rc  r9   
TrebleClefAltoClefr^   BassClef	TenorClefr   GeneralNoter~   RestfullMeasurerE   rF   r_   rg   r   )rh   currentKeySigcurrentTimeSigr   r-  previousListrm  rn  isRepetitionbrailleElementr.  allGeneralNotess               r'   addGroupingAttributes$BrailleSegment.addGroupingAttributes  s~    ((+,,U3djjl+&2#+7'[&&&!+.2L+''1,'00H4F4FF'//14'00H4F4FF!,q/499=='<\!"=M|'\'<\'X#$//14/ - ##x'9'99&2N!.%2E2EFF)7#NC4D4DEE8E5(6 '3 %%(*;*;X=O=O)PPl1otyy99!,q/DOOT]]3STT04-#LOdmmT^^5TUU05- /;"^ljDL\L\>]1l"^'1,OA<NPTPYPY1Z1Z59OA&2(5%)7&,0,A,AL))-););L&595S5SL2+6,O ,8P >>&*L#  #_s   "#L,	L,c           	     8  ^ SSK Jm  U4S jnU R                  5       nUR                  5        Vs/ s H'  nUR                  [
        R                  :X  d  M#  X#   PM)     nnU H  nU Vs/ s H&  n[        U[        R                  5      (       d  M$  UPM(     nn[        [        U5      5       H]  nXx   n	U	R                   HF  n
[        U
TR                  5      (       a  [        U
TR                  5      (       d  M;  U" U
U	UU5        MH     M_     M     gs  snf s  snf )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                  > U R                   n[        U T
R                  T
R                  45      (       aZ  UR                  bM  UR                  R
                  S:X  a  S X#S-
     l        SX#S-
     l        OS X#S-      l        SUl        S Ul        Sn[        US-   [        U5      5       H7  nX&   nXGR                   Vs/ s H  oR                   PM     sn;   a  US-  nM7    O   US:  a  g UR                  R                  U 5        [        US-   X5-   5       HG  nX&   nUR                   H0  n	U	R                   U:X  d  M  UR                  R                  U	5        M2     MI     g s  snf )Nstopr=   Tr   r,   )r   r   StaccatoTenutotietype	shortSlurr^  r~   r  r   remove)articmusic21NoteStartr/  noteIndexStart	articNamenumSequentialnoteIndexContinuemusic21NoteContinueaartOtherr  s             r'   fixOneArticulation;BrailleSegment.fixArticulations.<locals>.fixOneArticulation  sg   

I5=#9#9=;O;O"PQQ(,,8#'',,67;Ha/04=AHa/0:7;Ha/0415$.'+ $M%*>A+=s8}%M!&.&A#1R1R S1RA1R SS!Q&M &N q  **11%8%*>A+=+9+I&K!&.&A# 3 A AH}}	1+99@@J !B&K !Ts   >E#N)music21r  ro  r   rY   r)   r;   r   r   r*  r^  r~   TechnicalIndicationBowing)rh   r  rk  gpKeynoteGroupingsr   r.  allNotes_outernoteIndexStart_outermusic21NoteStart_outerartic_outerr  s              @r'   fixArticulationsBrailleSegment.fixArticulations   s   " 	*	K< %%'
*4//*;I*;#(>>X5G5G#G +**; 	 I *L)5RAAtyy9QaNR(-c..A(B$)7)M&#9#G#GK&{M4U4UVV)+}7K7KLL*'2*0	 $H )C *I Ss   "DD)#DD)r   r   r   r   r^   r   r   r   r   r   r_   r   r   r   r   rg   (   r   rV   )r   None)r   r\   )r   bool)FF)$r!   r"   r#   r$   rc   rG   rj   r{   rw   r   r   r   rp   r   propertyr   r   r   r   r   r   r   r   r   r2  r:  rQ  r   rW  r   r   ro  r  r  r%   __classcell__)r   s   @r'   r   r     s    !UZF#SB2 -?
</!I~ 8K& K&Z)(
>1*(' . .<( T$0"!-F-,`2	2_!B: AF7<+<Z3.j!@+>$%N5+nA Ar&   r   c                  T    \ rS rSrSrSSS jjr\S 5       rS rS r	S r
S rS	 rS
rg)BrailleGrandSegmentiD  z
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                    [         R                  XS9  [        R                  R                  XS9  [	        5       U l        S U l        S U l        g )Nr   )r   rj   r   BrailleKeyboardr   allKeyPairspreviousGroupingPaircurrentGroupingPair)rh   r   s     r'   rj   BrailleGrandSegment.__init__M  sG    <%%d%B:?' 	$(!#' r&   c                @    [         R                  R                  U 5      $ rm   )r   r  r   ro   s    r'   r   BrailleGrandSegment.brailleTextU  s    ##++D11r&   c                   Sn/ nU R                  5        GH  u  p4Ubr  SR                  UR                  [        UR                     UR
                  S-   5      n[        U R                  R                  U5      5      nSR                  XV/5      nOSnUbr  SR                  UR                  [        UR                     UR
                  S-   5      n[        U R                  R                  U5      5      n	SR                  X/5      n
OSn
UR                  SR                  XzS/5      5        GM     SR                  SUSR                  U5      S	/5      nU$ )
Nz1<music21.braille.segment BrailleGrandSegment>
===zMeasure {0} Right, {1} {2}:
r=   r   z
Measure {0} Left, {1} {2}:
r   z====
z---begin grand segment---z---end grand segment---)yieldCombinedGroupingKeysr   rW   r@   rY   rX   r   r   r  r   r   )rh   r   allPairsrightKeyleftKeyrightHeadingrightContents	rightFullleftHeadingleftContentsleftFullr   s               r'   r   BrailleGrandSegment.__str__Y  s>   C#'#A#A#CX#>EE$$mH4E4E&FHXHX[\H\ ^ #D$6$6$:$:8$D EGG\$AB		">EEOO]73C3C%DgooXYFY["4#5#5#9#9'#BC77K#>?OODIIyH&EFG $D  ii4dBGGH<M46 7
r&   c              #  \  #    S nS nSnSn[        U R                  5       US9 H  nUR                  S:X  as  Ubl  U" XT5      (       a  XT4v   OUUR                  [        R
                  :X  a/  U" UR                  [        R                  S9U5      (       a  XT4v   OSU4v   UnSnM  UnM  UR                  S:X  d  M  UbJ  U" XS5      (       a  X54v   O3UR                  [        R                  :  a  US4v   SU4v   OUS4v   UnSnM  UnM     U(       a  US4v   U(       a  SU4v   gg7f)a3  
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                t    U R                   S:X  a  SnOSnU R                  U R                  U R                  U4$ )zD
sort by measure, then ordinal, then affinity, then hand (r then l)
rightr+   r=   )rZ   rW   rX   rY   )
segmentKeyskHs     r'   segmentKeySortKeyHBrailleGrandSegment.yieldCombinedGroupingKeys.<locals>.segmentKeySortKey  s<     ')&&
(:(:J<O<OQTUUr&   c                    U R                   UR                   :X  a5  U R                  UR                  :X  a  U R                  UR                  :X  a  gg)NTF)rW   rX   rY   )thisKey_innerotherKeys     r'   
matchOtherABrailleGrandSegment.yieldCombinedGroupingKeys.<locals>.matchOther  sD    %%)9)99%--1A1AA%..(2C2CCr&   Nr   r  rA  left)r   r   rZ   rY   r)   r;   rF  r9   )rh   r  r  storedRight
storedLeftthisKeys         r'   r  -BrailleGrandSegment.yieldCombinedGroupingKeysp  sB    >	V	 
diik/@AG||w&)!'66&33!**h.@.@@()9)98CTCT)9)UWabb  '33#Z00&-!%J")K'*!'77*44$--0A0AA*D11#Wo-*D11%,
"&K!(J9 B< %%$$ s   B7D,=A/D,c                   [        U R                  5       5      U l        U R                  S   nUS   (       a  US   R                  OUS   R                  n[	        [        U5      5      U l        U R                  5         SU l        U R                  (       a  U R                  U l	        U R                  R                  5       U l        U R                  u  p4Ub  UR                  [        R                  :  d!  Ub.  UR                  [        R                  :  a  U R                  5         U R                  (       a  M  U R                  $ )z9
Returns the BrailleText from the combined grouping keys
r+   r   r=   N)r   r  r  rW   r~   r   highestMeasureNumberLengthr   r  r  r   rY   r)   r9   r   r   )rh   lastPairhighestMeasurer  r  s        r'   r   BrailleGrandSegment.transcribe  s    !!?!?!AB##B'08!,,!ATAT*-c..A*B'#' (,(@(@D%'+'7'7'?'?'AD$"&":":X%(*;*;x?P?P*P+0@0@HDUDU0U((*   r&   c                   SnSnSnSnU R                   (       a  U R                   S   u  pVUn U R                  R                  U5      nUR
                  [        R                  :  a  OU R                   R                  5         UR
                  [        R                  :X  a   US   US   p!OGUR
                  [        R                  :X  a  US   nO#UR
                  [        R                  :X  a  US   nU R                   (       a  M   [        R                   " UUUUU R"                  S9n
U R%                  U
5        g! [         a=  n	U	R                  S   S:X  a#  U R                  R                  U5      nUn Sn	A	GN1U	eSn	A	ff = f! [         a.    [        U[        R                  5      (       a  US   n NUS   n Nf = f! [        R&                   a  nUR                  S   S:w  a  Ue SnAgSnAff = f)z}
Finds KeySignatures, TimeSignatures, TempoText, and Metronome Marks
within the keyPairs, and removes some from allKeyPairs.
Nr   r  r=   r  zNo heading can be made.)r  r   r  KeyErrorargsrY   r)   r7   r   r5   
IndexErrorr   r   rK   r6   r   r
  r   r  BrailleBasicException)rh   rE   rF   r  r  r  r  useKey
useElementker  bbes               r'   r   "BrailleGrandSegment.extractHeading  s   
 	"&"2"21"5XF!//33H=
 /$$&("4"4462<Q-A- 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	sM   D: !	F 3F? :
F0E<:E<<F.F<4F<;F<?G2G--G2c                  ^  T R                   u  pU(       a  UR                  nOU(       a  UR                  nO[        S5      e[        R                  " USS9nU 4S jnU" U5      nU" U5      nT R                  XFU5        g )Nz/Measure must be defined for leftKey or rightKeyF)withNumberSignc                  > U b  U R                   [        R                  :X  a  TR                  R	                  U 5      n/ nU H  n[        U[        R                  5      (       d  M$  [        U5      nUR                  Ul	        UR                  Ul
        UR                  Ul        UR                  [        R                  " U5      5        TR                  U5        M     [         S   R#                  U5      nU$ U bD  TR                  R	                  U 5      n[        R                  " U5      nTR                  U5        U$ SnU$ )Nr   r   )rY   r)   r9   r   r  r   r   r   r  r^   r_   rg   r   r  r  r   r   r   )rightOrLeftKeyr  voice_transmusic21Voicer   
brailleStrrh   s         r'   brailleFromKey?BrailleGrandSegment.extractNoteGrouping.<locals>.brailleFromKeyN  s    )n.E.EIZIZ.Z ..22>B	 $-L%lFLLA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  rW   r   r   r   addNoteGroupings)rh   r  r  mNumcurrentMeasureNumberr  	rhBraille	lhBrailles   `       r'   r   'BrailleGrandSegment.extractNoteGroupingC  sv    "66##D??DNOO$44T%P	0 #8,	"7+	2yIr&   )r  r  r  r  Nr  r  )r!   r"   r#   r$   r   rj   r  r   r   r  r   r   r   r%   r    r&   r'   r  r  D  s=    ( 2 2.T%H :0d&Jr&   r  Tr  F)setHandr   r^   r   r  segmentBreaksr_   r   r   r   showLongSlursAndTiesTogethershowShortSlursAndTiesTogetherslurLongPhraseWithBracketsr   rg   c                  [        U UUUS9  [        XUS9nU Hb  nUUl        UUl        UUl        UR                  5         UUl        UUl        UUl        U	Ul	        U
Ul
        UUl        UR                  5         Md     U$ )uH  
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getRawSegmentsr_   rg   r^   r  r   r   r   r   r   r   r  )music21Partr  r   r^   r   r  r  r_   r   r   r   r  r  r  r   rg   allSegmentssegs                     r'   findSegmentsr  {  s    l 5Q6S3M !][K *(A%/!!# $8 -%;"%"5 	' * r&   )r  r  r  c               @   U R                   (       d  gUc  UnU R                  5       R                  R                  5       nU R                   R	                  [
        R                  5       GH  nUR                  5       nUR                  5       n UR                  U5      nUR                  U5      n	[        X-
  5      S-   n
U(       dj  U
[        ::  a`  XH   R                  b!  XH   R                  R                  S:X  a  US-  nXI   R                  b!  XI   R                  R                  S:X  a  U	S-  n	U(       dj  U
[        :  a`  XH   R                  b!  XH   R                  R                  S:X  a  US-  nXI   R                  b!  XI   R                  R                  S:X  a  U	S-  n	U
[        ::  a  [!        X5       H  nSXK   l        M     GMa  U(       a  SXH   l        SXI   l        GM}  SXHS-      l        SXIS-
     l        GM     g! [        R                   a     GM  f = f)a  
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.
Nr=   startr  T)spannerBundleflattennotesr   
getByClassr   SlurgetFirstgetLastindexr   StreamExceptionabsSEGMENT_MAXNOTESFORSHORTSLURr  r  r^  r  beginLongBracketSlurendLongBracketSlurbeginLongDoubleSlurendLongDoubleSlur)r  r  r  r  r/  slurr1  r   
beginIndexendIndexdelta	noteIndexs               r'   r  r  3  s   | $$#+'A$""$**113H))44W\\BMMO	<<>	!	2J~~h/H H)*Q.,:V1V $((4 ,0055@a
!%%1h6H6L6L6Q6QU[6[A+8T0T$((4 ,0055@a
!%%1h6H6L6L6Q6QU[6[A00":8	04#- 9 *<@$98<"5?Ca(<;?A&8Q C ++ 	 		s   "HHHr  c               `   / n[        US9nSnSnU R                  [        R                  5       GH  n[	        U5        [        U5      nSn	[        R                  n
U GH  nU(       ad  UR                  S:w  a  SUl	        UR                  U5        [        US9nUR                  S:w  a  SUl        SnU
[        R                  La  U	S-  n	SnSUR                  ;   a%  SUR                  ;   a  U[        ::  a  OUS:  a  SnM  [        U[        R                   5      (       a  U[        :  a  UR"                  S	;   a  SnUR$                  R&                  U
:  a  U	S-  n	UR$                  R&                  nU[        R(                  :X  a  [        R*                  nO$U[        R,                  :X  a  [        R.                  n[1        UR2                  U	UU5      nX;  a  [5        5       XM'   XM   nUR                  U5        US-  nUR$                  R&                  n
GM     GM     UR                  U5        U$ )
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        Tr=   BrailleSegmentDivisionBrailleOptionalSegmentDivision)doublefinal)r   getElementsByClassr   MeasureprepareBeamedNotesr  r)   r4   offsetr   r   r   classesMAX_ELEMENTS_IN_SEGMENTr   r   Barliner  r   affinityCoder:   r9   r<   r;   rT   numberr\   )r  r  r  r  currentSegmentelementsInCurrentSegmentstartANewSegmentmusic21MeasurebrailleElementsrX   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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*%3%?"")).9$)$ $2#;#;#H#H w . ID ~&r&   c           	     <   [        5       nSnU  GH   n[        U[        R                  5      (       a  UnM'   [        U[        R
                  5      (       a  UR                  S:X  a  MY  [        U5        Ub  [        U[        R                  [        R                  45      (       a^  [        U5        UR                  R                  UR                  l        [        U5      /UR                  l        UR!                  U5        SnUR!                  U5        [        U5      /UR                  l        GM#     UR-                  S S9  [/        U5      S:  a^  [        US   [0        R2                  5      (       a<  [        US   [        R
                  5      (       a  SUS   l        UR-                  S S9  U$ ! ["         a^  n[$         Vs/ s H  n[        X55      PM     Os  snf nn['        U5      (       d  [(        R+                  U 5         SnAGM    SnAGM  SnAff = f)	a  
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    U R                   U R                  4$ rm   r  classSortOrderxs    r'   <lambda>(extractBrailleElements.<locals>.<lambda>  s    AHHa.>.>#?r&   r   r>   r+   c                2    U R                   U R                  4$ rm   r*  r,  s    r'   r.  r/    s    AHHa6F6F+Gr&   )r\   r   r	   r  r   r  r  setAffinityCoder   rw  r   r   r   r  r   r   r   r   rA   r	  r  r  sortr~   r
   Dynamicr+  )music21MeasureOrVoiceallElementsr  music21ObjectnotSupportedExceptionmusic21ClassisExempts          r'   r  r    s   Z )*K $I.mTYY//%I	>-55 %%2M*$!D$4$4fll#C*E *E  	*3@3J3J3W3W	##069)n5E	##2""9- 	}-69-6H5IM##2- /< ?@
;1KOX=M=M!N!Nk"os{{33-/KO*!GH ' 	>,FH,FL #=?,FHH Hx==!!%:$;== !	>s*   /F3(CF33
H=HG.HHc                   U R                   R                  5       nU H  nSUl        SUl        M     U R                  R                  5       nS nS nS nUR                  5       R                  U5      R                  U5      nUR                  5       R                  U5      R                  U5      n[        U5      [        U5      :w  a  [        R                  S5        g[        U5       GH  u  pU
R                  S:X  a  M  X   nUR                  U
5      nUR                  U5      nX-
  S-   nUS	:  a  MM  S
n[        US-   US-   5       HF  nUU   R                  U
R                  :w  d$  [        UU   [        R                   5      (       d  MD  Sn  O    X=S-      n[        U[        R                   5      (       a.  [#        UR$                  5      [#        UR$                  5      :X  a  SnU(       d  GM
   X=S-      R                  S:X  a  GM#   S
U
l         X<S-
     n[        U[        R                   5      (       aM  [#        UR$                  5      [#        U
R$                  5      :X  a!  UR                  U
R                  :X  a  S
U
l        [        US-   US-   5       H  nS
UU   l        M     GM     g! [&         a     Nf = f! [&         a     Nf = f! [&         a     NUf = f)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                \    U R                   S L=(       a    [        U R                   5      S:  $ )Nr   )beamsr~   r   unuseds     r'   withBeamFilter*prepareBeamedNotes.<locals>.withBeamFilterJ  s#    $;#bhh-!*;;r&   c                R    U R                   R                  S5      R                  S:H  $ )Nr=   r  r=  getByNumberr  r>  s     r'   beamStartFilter+prepareBeamedNotes.<locals>.beamStartFilterM  s"    xx##A&++w66r&   c                R    U R                   R                  S5      R                  S:H  $ )Nr=   r  rC  r>  s     r'   beamStopFilter*prepareBeamedNotes.<locals>.beamStopFilterP  s"    xx##A&++v55r&   zDIncorrect beaming: number of start notes != to number of stop notes.Ng      ?r=   r,   T)r  r   	beamStartbeamContinuenotesAndRestsrn   	addFilterr~   r  r  	enumeratequarterLengthr  r^  r   r   rx  rV   beatr  )r#  r/  
sampleNoteallNotesAndRestsr@  rE  rH  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	 ""c))%++I6
$**84	&*19 #zA~y1}=I +99Y=T=TT!"29"=tyyII&+#	 >
	,];M=$))44]//0C4FF&+# #	  A.<<C D
 #		.A~>O?DII66O001S5HH'559P9PP)-	& zA~y1}=I7;Y'4 >c !86  		  		  		s8   AJ25KA3K2
J?>J?
KK
KKc                   [          H.  u  pn[        X5      (       d  M  X R                  l        X0l          g   [        U [
        R                  5      (       am  [        R                  U R                  l        [        U R                  R                  5       5      S:  a  [        R                  U R                  l        SU l        g[        U [        5      (       a  g[        U  S35      e)a  
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
Nr=   r1   z" cannot be transcribed to braille.)r?   r   r   r  r+  r   TextExpressionr)   r;   r~   contentsplitr8   r   r   )r7  r9  code	sortOrders       r'   r2  r2    s    @ ,9'Ym2237##0+4(	 ,9 -!;!;<</7/A/A,}$$**,-13;3I3IM##0'($-!;<<
!]O3U"V
WWr&   c                l    [        U 5      [        U5      :X  a  [        X5       H  u  p#X#:w  d  M    g   gg)a  
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)r~   r   )noteGroupingAnoteGroupingBelementAelementBs       r'   rr  rr    s:    * =S//$'$E X# %F r&   c                   [         R                  " 5       nU  H  nUR                  UR                  U5        M!     [	        UUU R
                  5      u  pE[        R                  " U 5      n/ Ul        U H  nUR                  U5        M     [        R                  " U 5      n/ Ul        U H  nUR                  U5        M     Xg4$ )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  splitMeasurerF   copyrf   r   )r   r>  r#  r~  leftMeasurerightMeasureleftBrailleElementsrightBrailleElementss           r'   rC  rC    s    J ^^%N&n33^D '".~/A/;/I/I#K[ ))L1')$%"">2 &  99\2(*%&##N3 ' 44r&   c                   Ub  UnOU R                  5       nSnUS:w  a  [        U5      [        UR                  5      :  a  [	        SU S3SUR                   3-   5      e[        UR                  5      [        U5      -
  n U[        UR                  U   R                  5      -  n[        U5      n[        R                  " UR                  5      nSn UR                  US	S
9  UR                  5       S   u  pX-  n	[$        R&                  " 5       n
[$        R&                  " 5       nU  H  nUR(                  U:  a]  UR(                  U	:  d/  UR(                  U	:X  a=  [+        U[,        R.                  5      (       a  U
R1                  UR(                  U5        Mp  UR1                  UR(                  U5        M     UR2                   HL  nUR4                  b<  U
R7                  U5        UR9                  U5        XR:                  R                  -  n	ML    O   U R:                  R                  U	-
  n[<        R>                  " US9nU
R1                  X5        [<        R>                  " U	S9nUR1                  SU5        S	nU
R@                  c  SnX:l         X;l         U
RC                  U 5        URC                  U 5        U
RE                  SS9  URE                  SS9  [G        U
5        [G        U5        U
R9                  U5        UR9                  U5        U(       a  U
R9                  U5        UR9                  U5        X4$ ! [         a)    [        R                  SU R                   S3-   5         GNf = f! [         R"                   aE    US-  nUR                  US	S
9  UR                  5       S   S   nUR                  5       S   S   n	 GNf = f)a  
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 zof ts.beatDivisionDurations z2Problem in converting a time signature in measure z, offset may be wrongr>   F)loadDefaultr=   r0  r+   )rO  T)inPlace)$bestTimeSignaturer  r~   beatDivisionDurationsr   r   rO  r  r  r  r  rj  deepcopybeatSequencepartitionByCountgetLevelSpanr   MeterExceptionr   r  r  r   r   r  r  r  r  r   r  durationr   rx  rF   mergeAttributes	makeBeamsr  )r#  r>  useTimeSignaturetsr  duration_indexbsnumberOfPartitionsstartOffsetZeroendOffsetZerork  rl  r-  r.  rest0Lengthr0r1
ts0_deletes                     r'   ri  ri  	  s   , #--/FQ!"S)A)A%BB)%&8%9F01I1I0JKL  R556=O9PP	QfR55nESSTTFF^F 
r	'B2
.EB+-??+<Q+?( M.."K>>#LHH'XX-]2'3;;77qxx+!,  55q!"ZZ555M   !))77-GK		-B})		/BR J  (
$&!!#/  0$'4({#|$r2&&s  	QR#1#8#8"99N OP Q	Q  2a
.EB//+A.q1)"-b1	2s%   0L; %M1 ;/M.-M.1AO
	O
c                      \ rS rSrS rSrg)Testi	  c                    SSK Jn  UR                  S5      nUR                  SS9n[	        U5      n[        US   5      ng )Nr   )	converterz)tinynotation: 3/4 c4 c c e e e g g g c'2.F)cautionaryNotImmediateRepeat)r  r  parsemakeNotationr  r   )rh   r  tn
rawSegListr?  s        r'   testGetRawSegmentsTest.testGetRawSegments	  s<    %__HI__%_@#B'
Z]#r&   r    N)r!   r"   r#   r$   r  r%   r    r&   r'   r  r  	  s    $r&   r  __main__)r  zbool | None)r  rV   )r5  zstream.Measure | stream.Voicer   r\   )r7  zbase.Music21Object)r   )r   N)or   
__future__r   collectionsr   r   rj  enumtypingtunittestr  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*  r;   rx  Chordr4  r  r  r<   rK   r5   rL   	TempoTextr6   MetronomeMarkr7   r   r9   r?   rG   r8   r:   r@   r  SystemLayout
PageLayoutStaffLayoutrA   	TypedDictrC   rH   rM   r  r  rO   
NamedTuplerT   r\   r   r   r  r  r  r  r  r  r  r2  rr  rC  ri  TestCaser  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kT%% k\eJ.$*>*> eJr	 &*"&!%!#$(,!;?/4,0%*+/!u 09ut 486;BF	l@ 7@	l@b  (*c #&cLS6SSln<b0Xf@55p_'J	$8 	$ zT r&   