
    rh%                      S r SSKJr  SSKJr  SSKJr  SSKrSSK	J
r
  SSKJrJrJrJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  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!  \RD                  (       a  SSK#J$r$  \RJ                  " S5      r&Sr'Sr(\( S3\( S3\( S3\( S 3\( S!3\( S"3\( S#3\( S$34r) " S% S&\RT                  5      r+ " S' S(\RT                  5      r, " S) S*\RT                  5      r- " S+ S,\RT                  5      r.S-r/S.r0S/r1S0r2S1r3S2r4S3r5S4r6S5r7S6r8S7r9S8r:S9r; " S: S;5      r<  S       SS< jjr=  S     SS= jjr>SS> jr?0 S?S@_SASB_SCSD_SESD_SFSG_SHSI_SJSI_SKSL_SMSM_SNSB_SOS@_SPSQ_SRSS_STSU_SVSW_SXSS_SYSU_SS0Er@S@SBSDSGSMSQSSSUSWSSZ.
rAS[S\S]S^S_S`SaSbScSdSeSfSgShSgSi.rB0 Sj\R                  _Sk\R                  _Sl\R                  _Sm\R                  _Sn\R                  _So\R                  _Sp\R                  _Sq\R                  _Sr\R                  _Ss\R                  _St\R                  _Su\R                  _Sv\R                  _Sw\R                  _Sx\R                  _Sy\R                  _Sz\R                  _\R                  \R                  \R                  \R                  \R                  \R                  \R                  \R                  \R                  \R                  \R                  \R                  \R                  S{.ErWS|S}S~SSSS.rXS rYS rZS r[S r\S r]S r^    SS jr_S r`S raS rbS rcS rdS re  S SS jjrfS rgSS jrhS riS rjS rkS rlS rmS rnS roS rpS rqS rrS rsS rtS ruSS jrvSS jrwSS jrxSS jrySS jrzSS jr{SS jr|SS jr}SS jr~SS jrSS jrSS jrSS jrSS jrSS jrSS jrSS jrSS jrSS jrSS jrSS jrS rS rSS jrSSSS.S jrS rS r\{\z\\\\y\\\\~\\\\\\\v\\x\w\/r\S:X  a  SSKr\GR&                  " 5         gg)a  
These are the public interfaces for the MEI module by Christopher Antila

To convert a string with MEI markup into music21 objects,
use :meth:`~music21.mei.MeiToM21Converter.convertFromString`.

In the future, most of the functions in this module should be moved to a separate, import-only
module, so that functions for writing music21-to-MEI will fit nicely.

**Simple "How-To"**

Use :class:`MeiToM21Converter` to convert a string to a set of music21 objects. In the future, the
:class:`M21ToMeiConverter` class will convert a set of music21 objects into a string with an MEI
document.

>>> meiString = """<?xml version="1.0" encoding="UTF-8"?>
... <mei xmlns="http://www.music-encoding.org/ns/mei" meiversion="2013">
...     <music>
...     <score>
...         <scoreDef meter.count="6" meter.unit="8">
...             <staffGrp>
...                 <staffDef n="1" clef.shape="F" clef.line="4"/>
...             </staffGrp>
...         </scoreDef>
...         <section>
...             <scoreDef key.sig="1f" key.mode="major"/>
...             <measure n="1">
...                 <staff n="1">
...                     <layer n="1">
...                         <beam>
...                             <note pname="E" oct="3" dur="8" artic="stacc"/>
...                             <note pname="E" oct="3" dur="8"/>
...                             <note pname="E" oct="3" dur="8"/>
...                         </beam>
...                         <chord dur="4" dots="1">
...                             <note pname="F" oct="2"/>
...                             <note pname="A" oct="2" accid="f"/>
...                         </chord>
...                     </layer>
...                 </staff>
...             </measure>
...         </section>
... </score>
...     </music>
... </mei>
... """
>>> conv = mei.MeiToM21Converter(meiString)
>>> result = conv.run()
>>> result
<music21.stream.Score 0x10ee474f0>

**Terminology**

This module's documentation adheres to the following terminology regarding XML documents, using
this snippet, ``<note pname="C"/>`` as an example:

- the entire snippet is an *element*.
- the word ``note`` is the *tag*.
- the word ``pname`` is an *attribute*.
- the letter ``C`` is a *value*.

Because Python also uses "attributes," an XML attribute is always preceded by an "at sign," as in
@pname, whereas a Python attribute is set as :attr:`pname`.

**Ignored Elements**

The following elements are not yet imported, though you might expect they would be:

* <sb>: a system break, since this is not usually semantically significant
* <lb>: a line break, since this is not usually semantically significant
* <pb>: a page break, since this is not usually semantically significant

**Where Elements Are Processed**

Most elements are processed in functions called :func:`tagFromElement`, where "tag" is replaced by
the element's tag name (e.g., :func:`staffDefFromElement` for <staffDef> elements). These functions
convert from a Python :class:`xml.etree.ElementTree.Element`
object to the appropriate music21 object.

However, certain elements are processed primarily in
another way, by "private" functions that are not
documented in this API. Rather than converting an :class:`Element` object into a music21 object,
these functions modify the MEI document tree by adding instructions for the :func:`tagFromElement`
functions. The elements processed by private functions include:

* <slur>
* <tie>
* <beamSpan>
* <tupletSpan>

Whereas you can expect functions like :func:`clefFromElement`
to convert a <clef> into a :class:`Clef`
with no loss of information. Because we cannot provide a simple one-to-one conversion for  slurs,
ties, and tuplets, we have kept their conversion functions "private,"
to emphasize the fact that you
must use the :class:`MeiToM21Converter` to process them properly.

**Guidelines for Encoders**

While we aim for the best possible compatibility, the MEI
specification is very large. The following
guidelines will help you produce a file that this MEI-to-music21 module will import correctly and
in the most efficient way. These should not necessarily be considered recommendations when using
MEI in any other context.

* Tuplets indicated only in a @tuplet attribute do not work.
* For elements that allow @startid, @endid, and @plist attributes,
  use all three for faster importing.
* For a <tupletSpan> that does not specify a @plist attribute, a tuplet spanning more than two
  measures will always and unavoidably be imported incorrectly.
* For any tuplet, specify at least @num and @numbase. The module refuses to import a tuplet that
  does not have the @numbase attribute.
* Retain consistent @n values for the same layer, staff, and instrument throughout the score.
* Always indicate the duration of <mRest> and <mSpace> elements.
* Avoid using the <barLine> element if you require well-formatted output from music21, since (as of
  January 2015) the music21-to-something converters will only output a :class:`Barline` that is
  part of a :class:`Measure`.

**List of Supported Elements**

Alphabetical list of the elements currently supported by this module:

* :func:`accidFromElement`
* :func:`articFromElement`
* :func:`barLineFromElement`
* :func:`beamFromElement`
* :func:`chordFromElement`
* :func:`clefFromElement`
* :func:`dotFromElement`
* :func:`instrDefFromElement`
* :func:`layerFromElement`
* :func:`measureFromElement`
* :func:`noteFromElement`
* :func:`restFromElement`
* :func:`mRestFromElement`
* :func:`spaceFromElement`
* :func:`mSpaceFromElement`
* :func:`scoreFromElement`
* :func:`scoreDefFromElement`
* :func:`sectionFromElement`
* :func:`staffFromElement`
* :func:`staffDefFromElement`
* :func:`staffGrpFromElement`
* :func:`sylFromElement`
* :func:`tupletFromElement`
* :func:`verseFromElement`

To know which MEI attributes are known to import correctly, read the documentation for the relevant
element. For example, to know whether the @color attribute on a <note> element is supported, read
the "Attributes/Elements Implemented" section of the :func:`noteFromElement` documentation.

**List of Ignored Elements**

The following elements are (silently) ignored by the MEI-to-music21 converter because they primarily
affect the layout and typesetting of a musical score. We may choose to implement these elements in
the future, but they are a lower priority because music21 is not primarily a layout or typesetting
tool.

* <multiRest>: a multi-measure rest (these will be "converted" to single-measure rests)
* <pb>: a page break
* <lb>: a line break
* <sb>: a system break
    )annotations)defaultdict)deepcopyN)uuid4)Element
ParseError
fromstringElementTree)articulations)bar)chord)clefduration)environment)exceptions21)
instrument)interval)key)metadata)meter)note)pitch)stream)spanner)tie)Fractionzmei.basez({http://www.w3.org/XML/1998/namespace}idz&{http://www.music-encoding.org/ns/mei}sblbpbslurr   
tupletSpanbeamSpaninstrDefc                      \ rS rSrSrSrg)MeiValidityError   zN
When there is an otherwise-unspecified validity error that prevents parsing.
 N__name__
__module____qualname____firstlineno____doc____static_attributes__r(       J/home/james-whalen/.local/lib/python3.13/site-packages/music21/mei/base.pyr&   r&           	r0   r&   c                      \ rS rSrSrSrg)MeiValueError   z)
When an attribute has an invalid value.
r(   Nr)   r(   r0   r1   r4   r4      r2   r0   r4   c                      \ rS rSrSrSrg)MeiAttributeError   z+
When an element has an invalid attribute.
r(   Nr)   r(   r0   r1   r7   r7      r2   r0   r7   c                      \ rS rSrSrSrg)MeiElementError   z$
When an element itself is invalid.
r(   Nr)   r(   r0   r1   r:   r:      r2   r0   r:   zSMEI module had {} failures and {} errors; run music21/mei/base.py to find out more.zMEI document is not valid XML.z<Root element should be <mei> in the MEI namespace, not <{}>.z-Found unexpected tag while parsing MEI: <{}>.z'Unexpected value for "{}" attribute: {}z4There appear to be no <staffDef> tags in this score.z5Found a <layer> without @n attribute and no override.z5Could not find the @{} so we could not create the {}.z@Both @num and @numbase attributes are required on <tuplet> tags.z-Importing {} without {} is not yet supported.z,Found an unprocessed <{}> element in a <{}>.z,Unable to decipher the composition date "{}"z&Verse number must be an int (got "{}")c                  ,    \ rS rSrSrSS jrSS jrSrg)	MeiToM21Converteri  a  
A :class:`MeiToM21Converter` instance manages the conversion of an MEI document into music21
objects.

If ``theDocument`` does not have <mei> as the root element, the class raises an
:class:`MeiElementError`. If ``theDocument`` is not a valid XML file, the class raises an
:class:`MeiValidityError`.

:param str theDocument: A string containing an MEI document.
:raises: :exc:`MeiElementError` when the root element is not <mei>
:raises: :exc:`MeiValidityError` when the MEI file is not valid XML.
Nc                   [         R                  S5        Uc  [        [         S35      U l        O [        U5      U l        [        U R                  [        5      (       a  U R                  R                  5       U l        [         S3U R                  R                  :w  a2  [        [        R                  U R                  R                  5      5      e[!        S 5      U l        [$        R&                  " 5       U l        g ! [         aA  n[         R                  S5        [         R                  SU 35        [        [        5      eS nAff = f)Nz"*** initializing MeiToM21Convertermeiz:

ERROR: Parsing the MEI document with ElementTree failed.zWe got the following error:
c                     0 $ Nr(   r(   r0   r1   <lambda>,MeiToM21Converter.__init__.<locals>.<lambda>A  s    2r0   )environLocal
printDebugr   MEI_NSdocumentRootr	   r   r&   _INVALID_XML_DOC
isinstancer
   getroottagr:   _WRONG_ROOT_ELEMENTformatr   m21Attrr   SpannerBundle
slurBundle)selftheDocumentparseErrs      r1   __init__MeiToM21Converter.__init__$  s    	 DE '6(# 7D9$.{$;! $++[99 %)$5$5$=$=$?!~!2!2!6!66%&9&@&@ARARAVAV&WXX #:. "//1-  9''RT''*Gz(RS&'788	9s   C? ?
E
	<EE
c           	        [         R                  S5        [        U 5        [        U 5        [	        U 5        [        U 5        [        U 5        [         R                  S5        [        U R                  R                  S[         S[         S35      U R                  5      n[         R                  S5        [        U R                  5      Ul        U$ )z
Run conversion of the internal MEI document to produce a music21 object.

Returns a :class:`~music21.stream.Stream` subclass, depending on the MEI document.
z$*** pre-processing spanning elementsz*** processing <score> elements.//music//scorez*** preparing metadata)rD   rE   _ppSlurs_ppTies_ppBeams
_ppTuplets_ppConcludescoreFromElementrG   findrF   rP   makeMetadatar   )rQ   theScores     r1   runMeiToM21Converter.runG  s     	 FG4D AB#""Sxu#EFOO 	 89():):;r0   )rG   rN   rP   rA   )returnzstream.Stream)r*   r+   r,   r-   r.   rT   rc   r/   r(   r0   r1   r=   r=     s    !2Fr0   r=   c                0   U (       d  [         R                  " 5       $ U(       a"  Ub  [         R                  " U [        U5      US9$ U(       a  [         R                  " U [        U5      S9$ Ub  [         R                  " XS9$ [         R                  " U 5      $ )a  
Safely build a :class:`~music21.pitch.Pitch` from a string.

When :meth:`~music21.pitch.Pitch.__init__` is given an empty string,
it raises a :exc:`~music21.pitch.PitchException`. This
function instead returns a default :class:`~music21.pitch.Pitch` instance.

name: Desired name of the :class:`~music21.pitch.Pitch`.

accidental: (Optional) Symbol for the accidental.

octave: (Optional) Octave number.

Returns A :class:`~music21.pitch.Pitch` with the appropriate properties.

>>> from music21.mei.base import safePitch  # OMIT_FROM_DOCS
>>> safePitch('D#6')
<music21.pitch.Pitch D#6>
>>> safePitch('D', '#', '6')
<music21.pitch.Pitch D#6>
>>> safePitch('D', '#')
<music21.pitch.Pitch D#>
)octave
accidental)rg   )rh   )r   Pitchint)namerh   rg   s      r1   	safePitchrl   b  sn    8 {{}*({{4F
KK{{4F44{{477{{4  r0   c                >    [         R                  " U 5      nXl        U$ )a&  
Given a ``base`` duration and a number of ``dots``, create a :class:`~music21.duration.Duration`
instance with the
appropriate ``quarterLength`` value.

Returns a :class:`Duration` corresponding to the fully-augmented value.

**Examples**

>>> from fractions import Fraction
>>> mei.base.makeDuration(base=2.0, dots=0).quarterLength  # half note, no dots
2.0
>>> mei.base.makeDuration(base=2.0, dots=1).quarterLength  # half note, one dot
3.0
>>> mei.base.makeDuration(base=2, dots=2).quarterLength  # 'base' can be an int or float
3.5
>>> mei.base.makeDuration(2.0, 10).quarterLength  # you want ridiculous dots? Sure!
3.998046875
>>> mei.base.makeDuration(0.33333333333333333333, 0).quarterLength  # works with fractions too
Fraction(1, 3)
>>> mei.base.makeDuration(Fraction(1, 3), 1).quarterLength
0.5
)r   Durationdots)basero   returnDurations      r1   makeDurationrr     s     6 &&t,Nr0   c                    S[          S3n/ nU R                  U5       H:  nUR                  S5      U;  d  M  UR                  UR                  S5      5        M<     U(       d  [	        [
        5      e[        U5      $ )a  
Find the @n values for all <staffDef> elements in a <score> element. This assumes that every
MEI <staff> corresponds to a music21 :class:`~music21.stream.Part`.

scoreElem is the <score> `Element` in which to find the part names.
Returns all the unique @n values associated with a part in the <score>.

**Example**

>>> meiDoc = """<?xml version="1.0" encoding="UTF-8"?>
... <score xmlns="http://www.music-encoding.org/ns/mei">
...     <scoreDef>
...         <staffGrp>
...             <staffDef n="1" clef.shape="G" clef.line="2"/>
...             <staffDef n="2" clef.shape="F" clef.line="4"/>
...         </staffGrp>
...     </scoreDef>
...     <section>
...         <!-- ... some music ... -->
...         <staffDef n="2" clef.shape="C" clef.line="4"/>
...         <!-- ... some music ... -->
...     </section>
... </score>"""
>>> import xml.etree.ElementTree as ETree
>>> meiDoc = ETree.fromstring(meiDoc)
>>> mei.base.allPartsPresent(meiDoc)
('1', '2')

Even though there are three <staffDef> elements in the document, there are only two unique @n
attributes. The second appearance of <staffDef> with @n="2" signals a change of clef on that
same staff---not that there is a new staff.
rW   staffDefn)rF   findallgetappendr&   _SEEMINGLY_NO_PARTStuple)	scoreElem
xpathQuerypartNsrt   s       r1   allPartsPresentr~     sn    F vhh'JF%%j1<<F*MM(,,s+, 2 233=r0   s#f-ssz##xffz--xsz###tstfz---ru   nfnssuz#~sd~fu`fdz-`nund)
r   r   r   r   ru   r   r   r   r   Ng      0@g       @g      @g       @g      ?g      ?g      ?g      ?g      ?g      ?g      ?g      ?g      p?g      `?)longbreve124816326412825651210242048Naccstacctenstaccissmarcspiccdoitplopfalldnbowupbowharmsnapstopopen	dbltonguetoe)
trpltongueheeltaplhpizzdotstrokeripbendflipsmear
fingernaildampdampalldasheddotteddoublefinalnoneregular)r   r   dblendinvissinglec                d     X    $ ! [          a    [        [        R                  X5      5      ef = f)a  
Helper function for other functions that need to translate the value of an attribute to another
known value. :func:`_attrTranslator` tries to return the value of ``attr`` in ``mapping`` and,
if ``attr`` isn't in ``mapping``, an exception is raised.

:param str attr: The value of the attribute to look up in ``mapping``.
:param str name: Name of the attribute, used when raising an exception (read below).
:param mapping: A mapping type (nominally a dict) with relevant key-value pairs.

:raises: :exc:`MeiValueError` when ``attr`` is not found in ``mapping``. The error message will
    be of this format: 'Unexpected value for "name" attribute: attr'.

Examples:

>>> from music21.mei.base import _attrTranslator, _ACCID_ATTR_DICT, _DUR_ATTR_DICT
>>> _attrTranslator('s', 'accid', _ACCID_ATTR_DICT)
'#'
>>> _attrTranslator('9', 'dur', _DUR_ATTR_DICT)
Traceback (most recent call last):
music21.mei.base.MeiValueError: Unexpected value for "dur" attribute: 9
)KeyErrorr4   _UNEXPECTED_ATTR_VALUErM   )attrrk   mappings      r1   _attrTranslatorr     s8    ,G} G299$EFFGs    )/c                $    [        U S[        5      $ )z
Use :func:`_attrTranslator` to convert the value of an "accid" attribute to its music21 string.

>>> mei.base._accidentalFromAttr('s')
'#'
accid)r   _ACCID_ATTR_DICTr   s    r1   _accidentalFromAttrr   8  s     4*:;;r0   c                $    [        U S[        5      $ )z
Use :func:`_attrTranslator` to convert the value of an @accid.ges
attribute to its music21 string.

>>> mei.base._accidGesFromAttr('s')
'#'
	accid.ges)r   _ACCID_GES_ATTR_DICTr   s    r1   _accidGesFromAttrr   B  s     4.BCCr0   c                $    [        U S[        5      $ )z
Use :func:`_attrTranslator` to convert an MEI "dur" attribute to a music21 quarterLength.

>>> mei.base._qlDurationFromAttr('4')
1.0

.. note:: This function only handles data.DURATION.cmn, not data.DURATION.mensural.
dur)r   _DUR_ATTR_DICTr   s    r1   _qlDurationFromAttrr   M  s     477r0   c                    SU :X  a*  [         R                  " 5       [         R                  " 5       4$ SU :X  a*  [         R                  " 5       [         R                  " 5       4$ [	        U S[
        5      " 5       4$ )a  
Use :func:`_attrTranslator` to convert an MEI "artic" attribute to a
:class:`music21.articulations.Articulation` subclass.

:returns: A **tuple** of one or two :class:`Articulation` subclasses.

.. note:: This function returns a singleton tuple *unless* ``attr`` is ``'marc-stacc'`` or
    ``'ten-stacc'``. These return ``(StrongAccent, Staccato)`` and ``(Tenuto, Staccato)``,
    respectively.
z
marc-staccz	ten-staccartic)r   StrongAccentStaccatoTenutor   _ARTIC_ATTR_DICTr   s    r1   _articulationFromAttrr   Y  sd     t**,m.D.D.FGG		$$&(>(>(@AAg/?@BDDr0   c                n    / nU R                  S5       H  nUR                  [        U5      5        M     U$ )z
Use :func:`_articulationFromAttr` to convert the actual value of an MEI "artic" attribute
(including multiple items) into a list suitable for :attr:`GeneralNote.articulations`.
 )splitextendr   )r   	articList	eachArtics      r1   _makeArticListr   l  s5    
 IZZ_	.y9: %r0   c                2    SSSSS.nSU:X  a  SX    -  $ X    $ )a  
Use :func:`_getOctaveShift` to calculate the :attr:`octaveShift` attribute for a
:class:`~music21.clef.Clef` subclass. Any of the arguments may be ``None``.

:param str dis: The "dis" attribute from the <clef> tag.
:param str disPlace: The "dis.place" attribute from the <clef> tag.

:returns: The octave displacement compared to the clef's normal position. This may be 0.
:rtype: integer
r            )Nr   1522belowr(   )disdisPlaceoctavesDicts      r1   _getOctaveShiftr   w  s1     !15K(K$$$r0   c                    U R                  S5      (       a  gU R                  S5      (       a  [        U S   5      $ S[        U S   5      -  $ )a  
Use :func:`_sharpsFromAttr` to convert MEI's ``data.KEYSIGNATURE`` datatype to an integer
representing the number of sharps, for use with music21's :class:`~music21.key.KeySignature`.

:param str signature: The @key.sig attribute.
:returns: The number of sharps.
:rtype: int

>>> from music21.mei.base import _sharpsFromAttr
>>> _sharpsFromAttr('3s')
3
>>> _sharpsFromAttr('3f')
-3
>>> _sharpsFromAttr('0')
0
0r   r   r   )
startswithendswithrj   )	signatures    r1   _sharpsFromAttrr     sL    " C  			C	 	 9Q<  C	!%%%r0   c           	     v   [         R                  S5        U nUR                  R                  S[         S[         S[         S35       H  nUR                  S5      b  UR                  S5      b  [        [        5       5      n[        R                  " 5       nX4l
        UR                  R                  U5        X1R                  [        UR                  S5      5         S	'   X1R                  [        UR                  S5      5         S
'   M  [         R                  [         R#                  SS5      5        M     g)a
  
Pre-processing helper for :func:`convertFromString` that handles slurs specified in <slur>
elements. The input is a :class:`MeiToM21Converter` with data about the file currently being
processed. This function reads from ``theConverter.documentRoot`` and writes into
``theConverter.m21Attr`` and ``theConverter.slurBundle``.

:param theConverter: The object responsible for storing data about this import.
:type theConverter: :class:`MeiToM21Converter`.

**This Preprocessor**

The slur preprocessor adds @m21SlurStart and @m21SlurEnd attributes to elements that are at the
beginning or end of a slur. The value of these attributes is the ``idLocal`` of a :class:`Slur`
in the :attr:`slurBundle` attribute of ``theConverter``. This attribute is not part of the MEI
specification, and must therefore be handled specially.

If :func:`noteFromElement` encounters an element like ``<note m21SlurStart="82f87cd7"/>``, the
resulting :class:`music21.note.Note` should be set as the starting point of the slur with an
``idLocal`` of ``'82f87cd7'``.

**Example of Changes to ``m21Attr``**

The ``theConverter.m21Attr`` attribute must be a defaultdict that returns an empty (regular)
dict for non-existant keys. The defaultdict stores the @xml:id attribute of an element; the
dict holds attribute names and their values that should be added to the element with the
given @xml:id.

For example, if the value of ``m21Attr['fe93129e']['tie']`` is ``'i'``, then this means the
element with an @xml:id of ``'fe93129e'`` should have the @tie attribute set to ``'i'``.

**Example**

Consider the following example.

>>> meiDoc = """<?xml version="1.0" encoding="UTF-8"?>
... <mei xmlns="http://www.music-encoding.org/ns/mei" meiversion="2013">
...     <music><score>
...     <section>
...         <note xml:id="1234"/>
...         <note xml:id="2345"/>
...         <slur startid="#1234" endid="#2345"/>
...     </section>
...     </score></music>
... </mei>"""
>>> theConverter = mei.base.MeiToM21Converter(meiDoc)
>>>
>>> mei.base._ppSlurs(theConverter)
>>> 'm21SlurStart' in theConverter.m21Attr['1234']
True
>>> 'm21SlurEnd' in theConverter.m21Attr['2345']
True
>>> theConverter.slurBundle
<music21.spanner.SpannerBundle of size 1>
>>> firstSpanner = list(theConverter.slurBundle)[0]
>>> (theConverter.m21Attr['1234']['m21SlurStart'] ==
...  theConverter.m21Attr['2345']['m21SlurEnd'] ==
...  firstSpanner.idLocal)
True

This example is a little artificial because of the limitations of a doctest, where we need to
know all values in advance. The point here is that the values of 'm21SlurStart' and 'm21SlurEnd'
of a particular slur-attached object will match the 'idLocal' of a slur in :attr:`slurBundle`.
The "id" is a UUID determined at runtime, which looks something like
``'d3731f89-8a2f-4b82-ad02-f0bc6f5f8b04'``.
z*** pre-processing slursrW   rX   score//r!   startidNendidm21SlurStart
m21SlurEndz<slur>@startid and @endid)rD   rE   rG   iterfindrF   rw   strr   r   SluridLocalrP   rx   rN   removeOctothorpewarn_UNIMPLEMENTED_IMPORTrM   )theConverterceachSlurthisIdLocalthisSlurs        r1   rZ   rZ     s    F 67ANN++&xt< <<	".8<<3H3Teg,K||~H*LL)S^II&x||I'>?@POZII&x||G'<=>|L3::8EZ[\r0   c           	        [         R                  S5        U nUR                  R                  S[         S[         S[         S35       H  nUR                  S5      bh  UR                  S5      bV  S	UR                  [        UR                  S5      5         S'   S
UR                  [        UR                  S5      5         S'   M}  [         R                  [        R                  SS5      5        M     g)ag  
Pre-processing helper for :func:`convertFromString` that handles ties specified in <tie>
elements. The input is a :class:`MeiToM21Converter` with data about the file currently being
processed. This function reads from ``theConverter.documentRoot`` and writes into
``theConverter.m21Attr``.

:param theConverter: The object responsible for storing data about this import.
:type theConverter: :class:`MeiToM21Converter`.

**This Preprocessor**

The tie preprocessor works similarly to the slur preprocessor, adding @tie attributes. The
value of these attributes conforms to the MEI Guidelines, so no special action is required.

**Example of ``m21Attr``**

The ``theConverter.m21Attr`` attribute must be a defaultdict that returns an empty (regular)
dict for non-existent keys. The defaultdict stores the @xml:id attribute of an element; the
dict holds attribute names and their values that should be added to the element with the
given @xml:id.

For example, if the value of ``m21Attr['fe93129e']['tie']`` is ``'i'``, then this means the
element with an @xml:id of ``'fe93129e'`` should have the @tie attribute set to ``'i'``.
z*** pre-processing tiesrW   rX   r   r   r   Nr   itz<tie>r  )rD   rE   rG   r  rF   rw   rN   r  r  r	  rM   )r
  r  eachTies      r1   r[   r[     s    2 56A>>**&xs;=;;y!-'++g2F2RILAII&w{{9'=>?FGJAII&w{{7';<=eD3::7DYZ[=r0   c           	        [         R                  S5        U nUR                  R                  S[         S[         S[         S35       GH  nUR                  S5      b  UR                  S5      c+  [         R                  [        R                  S	S
5      5        MS  SUR                  [        UR                  S5      5         S'   SUR                  [        UR                  S5      5         S'   UR                  SS5      R                  S5       H5  n[        U5      nSUR                  U   ;  d  M#  SUR                  U   S'   M7     GM     g)a  
Pre-processing helper for :func:`convertFromString` that handles beams specified in <beamSpan>
elements. The input is a :class:`MeiToM21Converter` with data about the file currently being
processed. This function reads from ``theConverter.documentRoot`` and writes into
``theConverter.m21Attr``.

:param theConverter: The object responsible for storing data about this import.
:type theConverter: :class:`MeiToM21Converter`.

**This Preprocessor**

The beam preprocessor works similarly to the slur preprocessor, adding the @m21Beam attribute.
The value of this attribute is either ``'start'``, ``'continue'``, or ``'stop'``, indicating
the music21 ``type`` of the primary beam attached to this element. This attribute is not
part of the MEI specification, and must therefore be handled specially.

**Example of ``m21Attr``**

The ``theConverter.m21Attr`` argument must be a defaultdict that returns an empty (regular)
dict for non-existent keys. The defaultdict stores the @xml:id attribute of an element; the
dict holds attribute names and their values that should be added to the element with the
given @xml:id.

For example, if the value of ``m21Attr['fe93129e']['tie']`` is ``'i'``, then this means the
element with an @xml:id of ``'fe93129e'`` should have the @tie attribute set to ``'i'``.
z*** pre-processing beamsrW   rX   r   r#   r   Nr   z
<beamSpan>r  startm21Beamr   plist r   continue)rD   rE   rG   r  rF   rw   r  r	  rM   rN   r  r   )r
  r  eachBeam	eachXmlids       r1   r\   r\   #  s    6 67A NN++&xx@B<<	"*hll7.C.K3::<I^_`JQ		"8<<	#:;<YGHN		"8<<#89:9E "gr288=I(3I 		) 442<		)$Y/ >Br0   c           	     D   [         R                  S5        U nUR                  R                  S[         S[         S[         S35       GH  nUR                  S5      b  UR                  S5      c=  UR                  S	5      c+  [         R                  [        R                  S
S5      5        Me  UR                  S	5      b  UR                  S	S5      R                  S5       HY  n[        U5      nU(       d  M  UR                  S5      UR                  U   S'   UR                  S5      UR                  U   S'   M[     M  [        UR                  S5      5      n[        UR                  S5      5      nSUR                  U   S'   UR                  S5      UR                  U   S'   UR                  S5      UR                  U   S'   SUR                  U   S'   UR                  S5      UR                  U   S'   UR                  S5      UR                  U   S'   GM     g)a  
Pre-processing helper for :func:`convertFromString` that handles tuplets specified in
<tupletSpan> elements. The input is a :class:`MeiToM21Converter` with data about the file
currently being processed. This function reads from ``theConverter.documentRoot`` and writes
into ``theConverter.m21Attr``.

:param theConverter: The object responsible for storing data about this import.
:type theConverter: :class:`MeiToM21Converter`.

**This Preprocessor**

The slur preprocessor works similarly to the slur preprocessor, adding @m21TupletNum and
@m21TupletNumbase attributes. The value of these attributes corresponds to the @num and
@numbase attributes found on a <tuplet> element. This preprocessor also performs a significant
amount of guesswork to try to handle <tupletSpan> elements that do not include a @plist
attribute. This attribute is not part of the MEI specification, and must therefore be handled
specially.

**Example of ``m21Attr``**

The ``theConverter.m21Attr`` attribute must be a defaultdict that returns an empty (regular)
dict for non-existent keys. The defaultdict stores the @xml:id attribute of an element; the
dict holds attribute names and their values that should be added to the element with the
given @xml:id.

For example, if the value of ``m21Attr['fe93129e']['tie']`` is ``'i'``, then this means the
element with an @xml:id of ``'fe93129e'`` should have the @tie attribute set to ``'i'``.
z*** pre-processing tupletsrW   rX   r   r"   r   Nr   r  z<tupletSpan>z@startid and @endid or @plistr  r   numm21TupletNumnumbasem21TupletNumbaser  m21TupletSearchr   )rD   rE   rG   r  rF   rw   r  r	  rM   r   r  rN   )r
  r  
eachTupletr  r   r   s         r1   r]   r]   W  s   : 89A nn--&xzBD
^^I&.*..2I2QNN7+33::>;Z\ ]^^G$0 (^^GR8>>sC	,Y7	9;E>>%;PAIIi(8?I~~i?XAIIi();< D 'z~~i'@AG$Z^^G%<=E4;AIIg011;1FAIIg~.5?^^I5NAIIg1227AIIe.//9~~e/DAIIe^,3=>>)3LAIIe/09Dr0   c           
        [         R                  S5        U nUR                  R                  S5       H  nUR	                  [
        5      UR                  ;   d  M(  UR                  UR	                  [
        5          HJ  nUR                  X2R	                  US5      UR                  UR	                  [
        5         U   -   5        ML     M     g)a  
Pre-processing helper for :func:`convertFromString` that adds attributes from ``m21Attr`` to the
appropriate elements in ``documentRoot``. The input is a :class:`MeiToM21Converter` with data
about the file currently being processed. This function reads from ``theConverter.m21Attr`` and
writes into ``theConverter.documentRoot``.

:param theConverter: The object responsible for storing data about this import.
:type theConverter: :class:`MeiToM21Converter`.

**Example of ``m21Attr``**

The ``m21Attr`` argument must be a defaultdict that returns an empty (regular) dict for
non-existent keys. The defaultdict stores the @xml:id attribute of an element; the dict holds
attribute names and their values that should be added to the element with the given @xml:id.

For example, if the value of ``m21Attr['fe93129e']['tie']`` is ``'i'``, then this means the
element with an @xml:id of ``'fe93129e'`` should have the @tie attribute set to ``'i'``.

**This Preprocessor**
The slur preprocessor adds all attributes from the ``m21Attr`` to the appropriate element in
``documentRoot``. In effect, it finds the element corresponding to each key in ``m21Attr``,
then iterates the keys in its dict, *appending* the ``m21Attr``-specified value to any existing
value.
z*** concluding pre-processingz*//*r  N)rD   rE   rG   r  rw   _XMLIDrN   set)r
  r  
eachObjecteachAttrs       r1   r^   r^     s    2 ;<A nn--f5
 >>&!QYY.IIjnnV&<=x..2*F,-IIjnnV6L,Mh,W+X Z >	 6r0   c                   / nU  H  nUR                   U;   a^  XR                      " XS5      n[        U[        [        45      (       a  U H  nUR	                  U5        M     M^  UR	                  U5        Mq  UR                   [
        ;  d  M  [        R                  [        R                  UR                   U5      5        M     U$ )a<	  
From an iterable of MEI ``elements``, use functions in the ``mapping`` to convert each element
to its music21 object. This function was designed for use with elements that may contain other
elements; the contained elements will be converted as appropriate.

If an element itself has embedded elements (i.e., its converter function in ``mapping`` returns
a sequence), those elements will appear in the returned sequence in order---there are no
hierarchic lists.

:param elements: A list of :class:`Element` objects to convert to music21 objects.
:type elements: iterable of :class:`~xml.etree.ElementTree.Element`
:param mapping: A dictionary where keys are the :attr:`Element.tag` attribute and values are
    the function to call to convert that :class:`Element` to a music21 object.
:type mapping: mapping of str to function
:param str callerTag: The tag of the element on behalf of which this function is processing
    sub-elements (e.g., 'note' or 'staffDef'). Do not include < and >. This is used in a
    warning message on finding an unprocessed element.
:param slurBundle: A slur bundle, as used by the other :func:`*fromElements` functions.
:type slurBundle: :class:`music21.spanner.SlurBundle`
:returns: A list of the music21 objects returned by the converter functions, or an empty list
    if no objects were returned.
:rtype: sequence of :class:`~music21.base.Music21Object`

**Examples:**

Because there is no ``'rest'`` key in the ``mapping``, that :class:`Element` is ignored.

>>> from xml.etree.ElementTree import Element
>>> elements = [Element('note'), Element('rest'), Element('note')]
>>> mapping = {'note': lambda x, y: note.Note('D2')}
>>> mei.base._processEmbeddedElements(elements, mapping, 'doctest')
[<music21.note.Note D>, <music21.note.Note D>]

If debugging is enabled for the previous example, this warning would be displayed:

``mei.base: Found an unprocessed <rest> element in a <doctest>.

The "beam" element holds "note" elements. All elements appear in a single level of the list:

>>> elements = [Element('note'), Element('beam'), Element('note')]
>>> mapping = {'note': lambda x, y: note.Note('D2'),
...            'beam': lambda x, y: [note.Note('E2') for _ in range(2)]}
>>> mei.base._processEmbeddedElements(elements, mapping)
[<music21.note.Note D>, <music21.note.Note E>, <music21.note.Note E>, <music21.note.Note D>]
)
rK   rI   rz   listrx   _IGNORE_UNPROCESSEDrD   rE   _UNPROCESSED_SUBELEMENTrM   )elementsr   	callerTagrP   	processedeachElemresultr%  s           r1   _processEmbeddedElementsr0    s    h I<<7"\\*8@F&5$-00"(J$$Z0 #)   (\\!44##$;$B$B8<<QZ$[\  r0   c                x    [         R                  " U R                  S5      < SU R                  S5      < 35      $ )a1  
From any tag with @meter.count and @meter.unit attributes, make a :class:`TimeSignature`.

:param :class:`~xml.etree.ElementTree.Element` elem: An :class:`Element` with @meter.count and
    @meter.unit attributes.
:returns: The corresponding time signature.
:rtype: :class:`~music21.meter.TimeSignature`
meter.count/z
meter.unit)r   TimeSignaturerw   )elems    r1   _timeSigFromAttrsr6    s4     $((="9!<Adhh|>T=WXYYr0   c                   U R                  S5      bi  U R                  SS5      nU R                  S5      nUc  [        S5      e[        U R                  S5      5      nUc  UnOX#-   n[        R                  " XAS9$ [        R
                  " [        U R                  S5      5      S9nUR                  U R                  SS	5      S
9$ )z
From any tag with (at minimum) either @key.pname or @key.sig attributes, make a
:class:`KeySignature` or :class:`Key`, as possible.

elem is an :class:`Element` with either the @key.pname or @key.sig attribute.

Returns the key or key signature.
	key.pnamezkey.moder  zKey missing stepz	key.accid)tonicmodekey.sig)sharpsmajor)r:  )rw   r&   r   r   KeyKeySignaturer   asKey)r5  r:  steprh   r9  kss         r1   _keySigFromAttrsrC    s     xx( xx
B'xx$<"#566(+)>?
E%EwwU.. _TXXi5H%IJxxTXXj':x;;r0   c                   [        U R                  SS5      5      n[        U R                  SS5      5      n[        X!-
  5      S[        U5      S-  S-   -  :  a5  US:  a  US[        U5      S-  -  -  nOUS:  a  US[        U5      S-  -  -  nUS:  a  US-  nOUS:  a  US-  n[        R                  " [        R
                  " U5      [        R                  " U5      5      $ )a  
From any element with the @trans.diat and @trans.semi attributes, make an :class:`Interval` that
represents the interval of transposition from written to concert pitch.

:param :class:`~xml.etree.ElementTree.Element` elem: An :class:`Element` with the @trans.diat
    and @trans.semi attributes.
:returns: The interval of transposition from written to concert pitch.
:rtype: :class:`music21.interval.Interval`
z
trans.diatr   
trans.semi      r      )rj   rw   absr   intervalFromGenericAndChromaticGenericIntervalChromaticInterval)r5  	transDiat	transSemis      r1   _transpositionFromAttrsrO  /  s     DHH\1-.IDHH\1-.I 9 !AY2)=)A$BB q=c)n233I]c)n233I 1}Q		QQ	33H4L4LY4W4<4N4Ny4Y[ [r0   c                   U R                  S5      (       aM  SU :X  a  [        S5      [        S5      4$ SU :X  a  [        R                  " SSS9$ [        R                  " S5      $ [        R                  " [        U S	[        5      5      $ )
a  
Use :func:`_attrTranslator` to convert the value of a "left" or "right" attribute to a
:class:`Barline` or :class:`Repeat` or occasionally a list of :class:`Repeat`. The only time a
list is returned is when "attr" is ``'rptboth'``, in which case the end and start barlines are
both returned.

:param str attr: The MEI @left or @right attribute to convert to a barline.
:returns: The barline.
:rtype: :class:`music21.bar.Barline` or :class:`~music21.bar.Repeat` or list of them
rptrptbothrptendrptstartr   r   )timesr  right)r   _barlineFromAttrr   RepeatBarliner   _BAR_ATTR_DICTr   s    r1   rW  rW  Y  sq     u#H-/?
/KKK::e1--::g&&{{?4.IJJr0   c                    SU ;   d  SU ;   a  SU ;   a  [         R                  " S5      $ SU ;   a  [         R                  " S5      $ [         R                  " S5      $ )z
Convert a @tie attribute to the required :class:`Tie` object.

:param str attr: The MEI @tie attribute to convert.
:return: The relevant :class:`Tie` object.
:rtype: :class:`music21.tie.Tie`
mr  r  r  r  r   )r   Tier   s    r1   _tieFromAttrr^  q  sJ     d{sd{sd{wwz""	wwwwwvr0   c                  ^^ SnUU4S jnU R                  S5      b  U" U R                  S5      5      nU R                  S5      b  U" U R                  S5      5      nU R                  S5      b  U R                  S5      R                  S5      nU H^  nUu  pxSU:X  aA  [        R                  " 5       n	Xyl        TR                  U	5        U	R                  T5        SnMN  S	U:X  d  MV  U" U5      nM`     U$ )
a  
If relevant, add a slur to an ``obj`` (object) that was created from an ``elem`` (element).

:param elem: The :class:`Element` that caused creation of the ``obj``.
:type elem: :class:`xml.etree.ElementTree.Element`
:param obj: The musical object (:class:`Note`, :class:`Chord`, etc.) created from ``elem``, to
    which a slur might be attached.
:type obj: :class:`music21.base.Music21Object`
:param slurBundle: The :class:`Slur`-holding :class:`SpannerBundle` associated with the
    :class:`Stream` that holds ``obj``.
:type slurBundle: :class:`music21.spanner.SpannerBundle`
:returns: Whether at least one slur was added.
:rtype: bool

**A Note about Importing Slurs**

Because of how the MEI format specifies slurs, the strategy required for proper import to
music21 is not obvious. There are two ways to specify a slur:

#. With a ``@slur`` attribute, in which case :func:`addSlurs` reads the attribute and manages
   creating a :class:`Slur` object, adding the affected objects to it, and storing the
   :class:`Slur` in the ``slurBundle``.
#. With a ``<slur>`` element, which requires pre-processing. In this case, :class:`Slur` objects
   must already exist in the ``slurBundle``, and special attributes must be added to the
   affected elements (``@m21SlurStart`` to the element at the start of the slur and
   ``@m21SlurEnd`` to the element at the end). These attributes hold the ``id`` of a
   :class:`Slur` in the ``slurBundle``, allowing :func:`addSlurs` to find the slur and add
   ``obj`` to it.

.. caution:: If an ``elem`` has an @m21SlurStart or @m21SlurEnd attribute that refer to an
    object not found in the ``slurBundle``, the slur is silently dropped.
Fc                n   >  TR                  U 5      S   R                  T5        g! [         a     gf = f)z9
Avoid crashing when getByIdLocl() doesn't find the slur
r   TF)getByIdLocaladdSpannedElements
IndexError)theIdobjrP   s    r1   wrapGetByIdLocal"addSlurs.<locals>.wrapGetByIdLocal  s;    	##E*1-@@E 		s   #' 
44r   r  r!   r   r  Tr  )rw   r   r   r  r  rx   rb  )
r5  re  rP   	addedSlurrf  
theseSlursr  slurNumslurTypenewSlurs
    ``       r1   addSlursrm    s    B I	 xx+$TXXn%=>	xx)$TXXl%;<	xx#XXf%++C0
"H (Gh!,,.")!!'***3/ 	,W5	 # r0   c                   Sn[        U 5       H  u  p#[        US5      (       d  M  US:X  a  SnOSn[        R                  " UR                  R                  5      S:  d  MS  UR
                  (       a  Mf  UR
                  R                  UR                  R                  U5        UnM     X   R
                  R                  S5        U $ )ad  
Beam some things together. The function beams every object that has a :attr:`beams` attribute,
leaving the other objects unmodified.

:param someThings: An iterable of things to beam together.
:type someThings: iterable of :class:`~music21.base.Music21Object`
:returns: ``someThings`` with relevant objects beamed together.
:rtype: same as ``someThings``
r   beamsr  r     r   )	enumeratehasattrr   convertTypeToNumbertypero  fillsetAll)
someThingsiLastBeamedNoter  thingbeamTypes        r1   beamTogetherr{    s     Oj)5'"""$"% ++ENN,?,?@1DU[[[  !4!4h?"# * %%,,V4r0   c                <    U R                  S5      (       a  U SS $ U $ )aT  
Given a string with an @xml:id to search for, remove a leading octothorpe, if present.

>>> from music21.mei.base import removeOctothorpe
>>> removeOctothorpe('110a923d-a13a-4a2e-b85c-e1d438e4c5d6')
'110a923d-a13a-4a2e-b85c-e1d438e4c5d6'
>>> removeOctothorpe('#e46cbe82-95fc-4522-9f7a-700e41a40c8e')
'e46cbe82-95fc-4522-9f7a-700e41a40c8e'
r   r   N)r   )xmlids    r1   r  r    s&     QRyr0   c                    [         R                  " 5       nU R                  S[         S35      nUb!  [	        X!5      n[        X!5      n[        X!5      nU$ )aB  
Produce metadata objects for all the metadata stored in the MEI header.

:param documentRoot: The MEI document's root element.
:type documentRoot: :class:`~xml.etree.ElementTree.Element`
:returns: A :class:`Metadata` object with some of the metadata stored in the MEI document.
:rtype: :class:`music21.metadata.Metadata`
rW   work)r   Metadatar`   rF   metaSetTitlemetaSetComposermetaSetDate)rG   metar  s      r1   ra   ra     sT     Ds6($/0DD't*4&Kr0   c                v   SnU R                  S[         S[         S35       HG  nUR                  SS5      S:X  a  UR                  nM'  UR                  b  M6  UR                  Ul        MI     U(       a  UR                   SU S	3Ul        U R                  S[         S
35      nUb  UR                  Ul        U$ )a  
From a <work> element, find the title, subtitle, and movement name (<tempo> element) and store
the values in a :class:`Metadata` object.

:param work: A <work> :class:`~xml.etree.ElementTree.Element` with metadata you want to find.
:param meta: The :class:`~music21.metadata.Metadata` object in which to store the metadata.
:return: The ``meta`` argument, having relevant metadata added.
N./
titleStmt/titlert  r  subtitlez ()tempo)rv   rF   rw   textr  r`   movementName)r  r  r  r  r  s        r1   r  r    s     H6(*VHEBC99VR J.zzHZZDJ	 D  

|2hZq1
II6(%()E!JJKr0   c           	        / nU R                  S[         S[         S[         S35       HH  nUR                  S5      S:X  d  M  UR                  (       d  M-  UR	                  UR                  5        MJ     U R                  S[         S[         S35       Hx  nUR                  (       a  UR	                  UR                  5        M1  UR                  S[         S35      nUR                  (       d  M]  UR	                  UR                  5        Mz     [        U5      S:X  a  US   Ul        U$ [        U5      S:  a  X!l        U$ )	a\  
From a <work> element, find the composer(s) and store the values in a :class:`Metadata` object.

:param work: A <work> :class:`~xml.etree.ElementTree.Element` with metadata you want to find.
:param meta: The :class:`~music21.metadata.Metadata` object in which to store the metadata.
:return: The ``meta`` argument, having relevant metadata added.
r  r  z	respStmt/persNamerolecomposerr   r   )	rv   rF   rw   r  rx   r`   lenr  	composers)r  r  r  r  r  s        r1   r  r  )  s    ILL2fXZxyPX!YZ<<:-(---X]]+ [ LL2fXZxx!HI==X]]+}}r&%:;H}}}  / J 9~!! K 
Y!	"Kr0   c           	     4   U R                  S[         S[         S[         S35      nUGb3  UR                  (       d  UR                  S5      (       ar  UR                  S5      (       a  UR                  S5      OUR                  n[        R
                  " 5       n UR                  UR                  SS5      5        XAl        U$ UR                  S5      (       a  UR                  S5      OUR                  S	5      nUR                  S
5      (       a  UR                  S
5      OUR                  S5      nU(       a#  U(       a  [        R                  " XV45      Ul        U$ ! [         a,    [        R                  [        R                  U5      5         U$ f = f)al  
From a <work> element, find the date (range) of composition and store the values in a
:class:`Metadata` object.

:param work: A <work> :class:`~xml.etree.ElementTree.Element` with metadata you want to find.
:param meta: The :class:`~music21.metadata.Metadata` object in which to store the metadata.
:return: The ``meta`` argument, having relevant metadata added.
r  zhistory/z	creation/dateisodater   r3  	notbefore	startdatenotafterenddate)r`   rF   r  rw   r   DateloadStrreplacedateCreated
ValueErrorrD   r  _MISSED_DATErM   DateBetween)r  r  r  dateStrtheDate	dateStartdateEnds          r1   r  r  D  s?    99r&&6($GHD99++-1XXi-@-@dhhy)diiGmmoG+S 9: $+  K 26+1F1F-DHHU`LaI.2hhz.B.Bdhhz*QZH[GW#+#7#78L#M K  @!!,"5"5g">? K@s   !E! !2FFc                    U  Vs/ s H&  n[        U[        R                  5      (       d  M$  UPM(     n n[        U 5      S:X  a  U S   R                  $ [        S5      es  snf )an  
From a list of objects with mixed type, find the "id" of the :class:`music21.stream.Voice`
instance.

:param list fromThese: A list of objects of any type, at least one of which must be a
    :class:`~music21.stream.Voice` instance.
:returns: The ``id`` of the :class:`Voice` instance.
:raises: :exc:`RuntimeError` if zero or many :class:`Voice` objects are found.
r   r   z3getVoiceId: found too few or too many Voice objects)rI   r   Voicer  idRuntimeError)	fromTheseitems     r1   
getVoiceIdr  a  sQ     #,N)$z$/M)IN
9~|PQQ	 Os
   #AAc                `   [        U [        [        [        45      (       d  U /n SnOSnU  GH  n[        U[        R
                  [        R                  [        R                  45      (       d  MD  UR                  S5      bD  UR                  S5      Ul
        UR                  S5      Ul        UR                  S5      Ul        M  UR                  R                  [        R                  " [!        UR                  S5      5      [!        UR                  S5      5      UR                  R"                  UR                  R"                  S95        UR                  S5      b0  UR                  S5      UR                  R$                  S   l        GMd  UR                  S	S
5      R'                  S5      (       a!  SUR                  R$                  S   l        GM  UR                  S	S
5      R'                  S5      (       d  GM  SUR                  R$                  S   l        GM     U(       a  U $ U S   $ )a  
Scale the duration of some objects by a ratio indicated by a tuplet. The ``elem`` must have the
@m21TupletNum and @m21TupletNumbase attributes set, and optionally the @m21TupletSearch or
@m21TupletType attributes.

The @m21TupletNum and @m21TupletNumbase attributes should be equal to the @num and @numbase
values of the <tuplet> or <tupletSpan> that indicates this tuplet.

The @m21TupletSearch attribute, whose value must either be ``'start'`` or ``'end'``, is required
when a <tupletSpan> does not include a @plist attribute. It indicates that the importer must
"search" for a tuplet near the end of the import process, which involves scaling the durations
of all objects discovered between those with the "start" and "end" search values.

The @m21TupletType attribute is set directly as the :attr:`type` attribute of the music21
object's :class:`Tuplet` object. If @m21TupletType is not set, the @tuplet attribute will be
consulted. Note that this attribute is ignored if the @m21TupletSearch attribute is present,
since the ``type`` will be set later by the tuplet-finding algorithm.

.. note:: Objects without a :attr:`duration` attribute will be skipped silently, unless they
    will be given the @m21TupletSearch attribute.

:param objs: The object(s) whose durations will be scaled.
    You may provide either a single object
    or an iterable; the return type corresponds to the input type.
:type objs: (list of) :class:`~music21.base.Music21Object`
:param elem: An :class:`Element` with the appropriate attributes (as specified above).
:type elem: :class:`xml.etree.ElementTree.Element`
:returns: ``objs`` with scaled durations.
:rtype: (list of) :class:`~music21.base.Music21Object`
FTr   r  r  )numberNotesActualnumberNotesNormaldurationNormaldurationActualm21TupletTyper   tupletr  r  r  r  r   )rI   r(  r$  rz   r   NoteRestr   Chordrw   r   r  r  r   appendTupletTupletrj   rt  tupletsr   )objsr5  wasListre  s       r1   scaleToTupletr  r  s   > dT3.//v#		499ekkBCCXX'(4"&((+<"=C#xx7C#'88,>#?C  LL%%hoo"%dhh~&>"?"%dhh/A&B"C"||00"||00	'2 3 xx(4/3xx/H$$Q',(B'22377/6$$Q',(B'22377/5$$Q',- 0 Awr0   c                D   SnSnSnU  GH  n[        U[        R                  [        R                  [        R
                  45      (       d  MD  [        US5      (       aB  UR                  S:X  a2  Sn[        UR                  5      n[        UR                  5      nU?U?	U?
U(       d  M  [        U[        S[        U5      [        U5      S95        [        US5      (       d  M  UR                  S:X  d  M  S	UR                  R                  S
   l        U?U?	U?
SnGM     U $ )a  
Given a list of music21 objects, possibly containing :attr:`m21TupletSearch`,
:attr:`m21TupletNum`, and :attr:`m21TupletNumbase` attributes, adjust the durations of the
objects as specified by those "m21Tuplet" attributes, then remove the attributes.

This function finishes processing for tuplets encoded as a <tupletSpan> where @startid and
@endid are indicated, but not @plist. Knowing the starting and ending object in the tuplet, we
can guess that all the Note, Rest, and Chord objects between the starting and ending objects
in that <layer> are part of the tuplet. (Grace notes retain a 0.0 duration).

.. note:: At the moment, this will likely only work for simple tuplets---not nested tuplets.

:param theLayer: Objects from the <layer> in which to search for objects that have the
    :attr:`m21TupletSearch` attribute.
:type theScore: list
:returns: The same list, with durations adjusted to account for tuplets.
FNr   r  Tr  r  r  r   r   r   )rI   r   r  r  r   r  rr  r   rj   r  r  r  r   r  r   r  rt  )theLayer	inATuplet	tupletNumtupletNumbaseeachNotes        r1   _guessTupletsr    s   0 IIM(TYY		5;;$GHH8.//H4L4LPW4WIH112I 9 9:M(%)9(GB9<Y=@=O%Q R x!2338P8PTY8Y4:!!))!,1,)- "	9 < Or0   c                h   SnSnU/ U/ 0nU R                  S5      b  XB   R                  [        U 5      5        U R                  S5      c  U R                  S5      b  XB   R                  [        U 5      5        U R	                  [
         S35       H  nUR                  [        XQ5      5        M     U$ )ab  
<scoreDef> Container for score meta-information.

In MEI 2013: pg.431 (445 in PDF) (MEI.shared module)

This function returns a dictionary with objects that may relate to the entire score, to all
parts at a particular moment, or only to a specific part at a particular moment. The dictionary
keys determine the object's scope. If the key is:

* ``'whole-score objects'``, it applies to the entire score (e.g., page size);
* ``'all-part objects'``, it applies to all parts at the moment this <scoreDef> appears;
* the @n attribute of a part, it applies only to
  that part at the moment this <scoreDef> appears.

While the multi-part objects will be held in a list, the single-part objects will be in a dict
like that returned by :func:`staffDefFromElement`.

Note that it is the caller's responsibility to determine the right action if there are
conflicting objects in the returned dictionary.

For example:

>>> meiDoc = """<?xml version="1.0" encoding="UTF-8"?>
... <scoreDef meter.count="3" meter.unit="4" xmlns="http://www.music-encoding.org/ns/mei">
...     <staffGrp>
...         <staffDef n="1" label="Clarinet"/>
...         <staffGrp>
...             <staffDef n="2" label="Flute"/>
...             <staffDef n="3" label="Violin"/>
...         </staffGrp>
...     </staffGrp>
... </scoreDef>
... """
>>> from xml.etree import ElementTree as ET
>>> scoreDef = ET.fromstring(meiDoc)
>>> result = mei.base.scoreDefFromElement(scoreDef)
>>> len(result)
5
>>> result['1']
{'instrument': <music21.instrument.Clarinet '1: Clarinet: Clarinet'>}
>>> result['3']
{'instrument': <music21.instrument.Violin '3: Violin: Violin'>}
>>> result['all-part objects']
[<music21.meter.TimeSignature 3/4>]
>>> result['whole-score objects']
[]

:param elem: The ``<scoreDef>`` element to process.
:type elem: :class:`~xml.etree.ElementTree.Element`
:returns: Objects from the ``<scoreDef>``, as described above.
:rtype: dict

**Attributes/Elements Implemented:**

- (att.meterSigDefault.log (@meter.count, @meter.unit))
- (att.keySigDefault.log (@key.accid, @key.mode, @key.pname, @key.sig))
- contained <staffGrp>

**Attributes/Elements in Testing:** None

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.scoreDef.log

    - (att.cleffing.log (@clef.shape, @clef.line, @clef.dis, @clef.dis.place))
    - (att.duration.default (@dur.default, @num.default, @numbase.default))
    - (att.keySigDefault.log (@key.sig.mixed))
    - (att.octavedefault (@octave.default))
    - (att.transposition (@trans.diat, @trans.semi))
    - (att.scoreDef.log.cmn (att.beaming.log (@beam.group, @beam.rests)))
    - (att.scoreDef.log.mensural

        - (att.mensural.log (@mensur.dot, @mensur.sign,
             @mensur.slash, @proport.num, @proport.numbase)
        - (att.mensural.shared (@modusmaior, @modusminor, @prolatio, @tempus))))

- att.scoreDef.vis (all)
- att.scoreDef.ges (all)
- att.scoreDef.anl (none exist)

**Contained Elements not Implemented:**

- MEI.cmn: meterSig meterSigGrp
- MEI.harmony: chordTable
- MEI.linkalign: timeline
- MEI.midi: instrGrp
- MEI.shared: keySig pgFoot pgFoot2 pgHead pgHead2
- MEI.usersymbols: symbolTable
all-part objectszwhole-score objectsr2  r8  r;  staffGrp)rw   rx   r6  rC  r  rF   updatestaffGrpFromElement)r5  rP   allParts
wholeScoreposteachGrps         r1   scoreDefFromElementr    s    z "H&Jb*b)D xx*/56 xx(DHHY,?,K.t45 ==F88!45'<= 6 Kr0   c                    [          S3n[          S3nUb  UO0 nU R                  S5       HO  nUR                  U:X  a  [        XQ5      X%R	                  S5      '   M1  UR                  U:X  d  MC  [        XQU5        MQ     U$ )a  
<staffGrp> A group of bracketed or braced staves.

In MEI 2013: pg.448 (462 in PDF) (MEI.shared module)

For now, this function is merely a container-processor  for <staffDef> elements contained
in this <staffGrp> element given as the "elem" argument. That is, the function does not yet
create the brackets/braces and labels expected of a staff group.
Note however that all <staffDef>
elements will be processed, even if they're contained within several layers of <staffGrp>.

:param elem: The ``<staffGrp>`` element to process.
:type elem: :class:`~xml.etree.ElementTree.Element`
:returns: Dictionary where keys are the @n attribute on a contained <staffDef>, and values are
    the result of calling :func:`staffDefFromElement` with that <staffDef>.

**Attributes/Elements Implemented:**

- contained <staffDef>
- contained <staffGrp>

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.declaring (@decls)
- att.facsimile (@facs)
- att.staffGrp.vis (@barthru)

    - (att.labels.addl (@label.abbr))
    - (att.staffgroupingsym (@symbol))
    - (att.visibility (@visible))

- att.staffGrp.ges (att.instrumentident (@instr))

**Contained Elements not Implemented:**

- MEI.midi: instrDef
- MEI.shared: grpSym label
rt   r  *ru   )rF   rv   rK   staffDefFromElementrw   r  )r5  rP   staffDefDictstaffDefTagstaffGroupTagels         r1   r  r  e  s}    V HH%Khh'M#/#;<Lll366[ (;B(KL% VV}$=   r0   c           	     P   [          S3[        0nU R                  [          S35      nUb  S[        U5      0nO) S[        R
                  " U R                  SS5      5      0nSU;   aK  U R                  S5      US   l        U R                  S5      US   l	        U R                  S5      US   l
        U R                  S5      b1  SU;  a  [        R                  " 5       US'   [        U 5      US   l        U R                  S	5      b  [        U 5      US
'   U R                  S5      c  U R                  S5      b  [        U 5      US'   U R                  S5      b[  [!        SU R                  S5      U R                  S5      U R                  S5      U R                  S5      S.5      n[        U5      US'   [#        U R%                  S5      X R&                  U5      nU H(  n[)        U[*        R,                  5      (       d  M$  XcS'   M*     U$ ! [        R                   a    0 n GNf = f)a  
<staffDef> Container for staff meta-information.

In MEI 2013: pg.445 (459 in PDF) (MEI.shared module)

:returns: A dict with various types of metadata information, depending on what is specified in
    this <staffDef> element. Read below for more information.
:rtype: dict

**Possible Return Values**

The contents of the returned dictionary depend on the contents of the <staffDef> element. The
dictionary keys correspond to types of information. Possible keys include:

- ``'instrument'``: for a :class:`music21.instrument.Instrument` subclass
- ``'clef'``: for a :class:`music21.clef.Clef` subclass
- ``'key'``: for a :class:`music21.key.Key` or :class:`~music21.key.KeySignature` subclass
- ``'meter'``: for a :class:`music21.meter.TimeSignature`

**Examples**

This <staffDef> only returns a single item.

>>> meiDoc = """<?xml version="1.0" encoding="UTF-8"?>
... <staffDef n="1" label="Clarinet" xmlns="http://www.music-encoding.org/ns/mei"/>
... """
>>> from xml.etree import ElementTree as ET
>>> staffDef = ET.fromstring(meiDoc)
>>> result = mei.base.staffDefFromElement(staffDef)
>>> len(result)
1
>>> result
{'instrument': <music21.instrument.Clarinet '1: Clarinet: Clarinet'>}
>>> result['instrument'].partId
'1'
>>> result['instrument'].partName
'Clarinet'

This <staffDef> returns many objects.

>>> meiDoc = """<?xml version="1.0" encoding="UTF-8"?>
... <staffDef n="2" label="Tuba" key.pname="B" key.accid="f" key.mode="major"
...  xmlns="http://www.music-encoding.org/ns/mei">
...     <clef shape="F" line="4"/>
... </staffDef>
... """
>>> from xml.etree import ElementTree as ET
>>> staffDef = ET.fromstring(meiDoc)
>>> result = mei.base.staffDefFromElement(staffDef)
>>> len(result)
3
>>> result['instrument']
<music21.instrument.Tuba '2: Tuba: Tuba'>
>>> result['clef']
<music21.clef.BassClef>
>>> result['key']
<music21.key.Key of B- major>

**Attributes/Elements Implemented:**

- @label (att.common) as Instrument.partName
- @label.abbr (att.labels.addl) as Instrument.partAbbreviation
- @n (att.common) as Instrument.partId
- (att.keySigDefault.log (@key.accid, @key.mode, @key.pname, @key.sig))
- (att.meterSigDefault.log (@meter.count, @meter.unit))
- (att.cleffing.log (@clef.shape, @clef.line, @clef.dis, @clef.dis.place))
  (via :func:`clefFromElement`)
- @trans.diat and @trans.demi (att.transposition)
- <instrDef> held within
- <clef> held within

**Attributes/Elements Ignored:**

- @key.sig.mixed (from att.keySigDefault.log)

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@n, @xml:base) (att.id (@xml:id))
- att.declaring (@decls)
- att.staffDef.log

    - (att.duration.default (@dur.default, @num.default, @numbase.default))
    - (att.octavedefault (@octave.default))
    - (att.staffDef.log.cmn (att.beaming.log (@beam.group, @beam.rests)))
    - (att.staffDef.log.mensural

        - (att.mensural.log (@mensur.dot, @mensur.sign, @mensur.slash,
                             @proport.num, @proport.numbase)
        - (att.mensural.shared (@modusmaior, @modusminor, @prolatio, @tempus))))

- att.staffDef.vis (all)
- att.staffDef.ges (all)
- att.staffDef.anl (none exist)

**Contained Elements not Implemented:**

- MEI.cmn: meterSig meterSigGrp
- MEI.mensural: mensural support
- MEI.shared: clefGrp keySig label layerDef
r   r$   r   labelr  z
label.abbrru   rE  r2  r   r8  r;  r   z
clef.shapez	clef.linezclef.diszclef.dis.place)shapeliner   	dis.placer  )rF   clefFromElementr`   instrDefFromElementr   
fromStringrw   InstrumentExceptionpartNamepartAbbreviationpartId
InstrumentrO  transpositionr6  rC  r   r0  rv   rK   rI   r   Clef)r5  rP   tagToFunctionr  r  embeddedItemseachItems          r1   r  r    s   P xt_o6M 99xx()D1$78	 *"7"7"8M"NOD t&*hhw&7\#.2hh|.D\+$(HHSM\! xx)t#!+!6!6!8D+B4+H\( xx*)$/W xx(DHHY,?,K&t,U xx),/-xx
+!XX&67	
 'r*V,T\\#->xxYcdM!h		**#L " KQ -- 	D	s   (H H%$H%c                    g)a  
Returns ``1`` no matter what is passed in.

<dot> Dot of augmentation or division.

In MEI 2013: pg.304 (318 in PDF) (MEI.shared module)

:returns: 1
:rtype: int

**Attributes/Elements Implemented:** none

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.facsimile (@facs)
- att.dot.log (all)
- att.dot.vis (all)
- att.dot.gesatt.dot.anl (all)

**Elements not Implemented:** none
r   r(   r5  rP   s     r1   dotFromElementr  =  s    2 r0   c                D    U R                  S5      nUb  [        U5      $ / $ )aK  
<artic> An indication of how to play a note or chord.

In MEI 2013: pg.259 (273 in PDF) (MEI.shared module)

:returns: A list of :class:`~music21.articulations.Articulation` objects.

**Examples**

This function is normally called by, for example, :func:`noteFromElement`, to determine the
:class:`Articulation` objects that will be assigned to the
:attr:`~music21.note.GeneralNote.articulations` attribute.

>>> from xml.etree import ElementTree as ET
>>> meiSnippet = '<artic artic="acc" xmlns="http://www.music-encoding.org/ns/mei"/>'
>>> meiSnippet = ET.fromstring(meiSnippet)
>>> mei.base.articFromElement(meiSnippet)
[<music21.articulations.Accent>]

A single <artic> element may indicate many :class:`Articulation` objects.

>>> meiSnippet = '<artic artic="acc ten" xmlns="http://www.music-encoding.org/ns/mei"/>'
>>> meiSnippet = ET.fromstring(meiSnippet)
>>> mei.base.articFromElement(meiSnippet)
[<music21.articulations.Accent>, <music21.articulations.Tenuto>]

**Attributes Implemented:**

- @artic

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.facsimile (@facs)
- att.typography (@fontfam, @fontname, @fontsize, @fontstyle, @fontweight)
- att.artic.log

    - (att.controlevent

        - (att.plist (@plist, @evaluate))
        - (att.timestamp.musical (@tstamp))
        - (att.timestamp.performed (@tstamp.ges, @tstamp.real))
        - (att.staffident (@staff))
        - (att.layerident (@layer)))

- att.artic.vis (all)
- att.artic.gesatt.artic.anl (all)

**Contained Elements not Implemented:** none
r   )rw   r   )r5  rP   articElements      r1   articFromElementr  Y  s)    j 88G$Ll++	r0   c                    U R                  S5      b  [        U R                  SS5      5      $ [        U R                  S5      5      $ )am  
<accid> Records a temporary alteration to the pitch of a note.

In MEI 2013: pg.248 (262 in PDF) (MEI.shared module)

:returns: A string indicating the music21 representation of this accidental.

**Examples**

Unlike most of the ___FromElement() functions, this does not return any music21 object---just
a string. Accidentals up to triple-sharp and triple-flat are supported.

>>> from xml.etree import ElementTree as ET
>>> meiSnippet = '<accid accid="s" xmlns="http://www.music-encoding.org/ns/mei"/>'
>>> meiSnippet = ET.fromstring(meiSnippet)
>>> mei.base.accidFromElement(meiSnippet)
'#'
>>> meiSnippet = '<accid accid="tf" xmlns="http://www.music-encoding.org/ns/mei"/>'
>>> meiSnippet = ET.fromstring(meiSnippet)
>>> mei.base.accidFromElement(meiSnippet)
'---'

**Attributes/Elements Implemented:**

- @accid (from att.accid.log)
- @accid.ges (from att.accid.ges)

.. note:: If set, the @accid.ges attribute is always imported as the music21 :class:`Accidental`
    for this note. We assume it corresponds to the accidental implied by a key signature.

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.facsimile (@facs)
- att.typography (@fontfam, @fontname, @fontsize, @fontstyle, @fontweight)
- att.accid.log (@func)

    - (att.controlevent

        - (att.plist (@plist, @evaluate))
        - (att.timestamp.musical (@tstamp))
        - (att.timestamp.performed (@tstamp.ges, @tstamp.real))
        - (att.staffident (@staff)) (att.layerident (@layer)))

- att.accid.vis (all)
- att.accid.anl (all)

**Contained Elements not Implemented:** none
r   r  r   )rw   r   r   r  s     r1   accidFromElementr    s>    h xx( +r!:;;"488G#455r0   c                   U R                  S5      nSSSSS.nSSS	S
SS.nSU:X  a!  U R                  X@R                  S5         -   nOnSU:X  a5  X@R                  S5         U R                  -   X@R                  S5         -   nO3SU:X  a!  X@R                  S5         U R                  -   nOU R                  nX2   nU(       a  [        R                  " XVSS9$ [        R                  " US9$ )a  
<syl> Individual lyric syllable.

In MEI 2013: pg.454 (468 in PDF) (MEI.shared module)

:returns: An appropriately-configured :class:`music21.note.Lyric`.

**Attributes/Elements Implemented:**

- @con and @wordpos (from att.syl.log)

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.facsimile (@facs)
- att.syl.vis (att.typography (@fontfam, @fontname, @fontsize, @fontstyle, @fontweight))

    - (att.visualoffset (att.visualoffset.ho (@ho))

        - (att.visualoffset.to (@to))
        - (att.visualoffset.vo (@vo)))

    - (att.xy (@x, @y))
    - (att.horizontalalign (@halign))

- att.syl.anl (att.common.anl (@copyof, @corresp, @next, @prev, @sameas, @synch)

    -  (att.alignment (@when)))

**Contained Elements not Implemented:**

- MEI.edittrans: (all)
- MEI.figtable: fig
- MEI.namesdates: corpName geogName periodName persName styleName
- MEI.ptrref: ptr ref
- MEI.shared: address bibl date identifier lb name num rend repository stack title
wordposbeginmiddler   N)r  r\  r  Nr   r   r   _)r   dr  uNr  conr\  r  T)r  syllabicapplyRaw)r  )rw   r  r   Lyric)r5  rP   wordPoswordPosDictconDictr  r  s          r1   sylFromElementr    s    P hhy!GhU$GKc#SAG
g~yy788E?33	xx'$))3ghhuo6NN	xx'$))3yy#HzztFFzzt$$r0   c           
     f   U R                  S[         S35       Vs/ s H  n[        U5      PM     nnU H$  n [        U R	                  SU5      5      Ul        M&     U$ s  snf ! [        [        4 a<    [        R                  [        R                  U R	                  SU5      5      5         Mz  f = f)a  
<verse> Lyric verse.

In MEI 2013: pg.480 (494 in PDF) (MEI.lyrics module)

:param int backupN: The backup verse number to use if no @n attribute exists on ``elem``.
:returns: The appropriately-configured :class:`Lyric` objects.
:rtype: list of :class:`music21.note.Lyric`

**Attributes/Elements Implemented:**

- @n and <syl>

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.facsimile (@facs)
- att.lang (@xml:lang)
- att.verse.log (@refrain, @rhythm)
- att.verse.vis (att.typography (@fontfam, @fontname, @fontsize, @fontstyle, @fontweight))

    - (att.visualoffset.to (@to))
    - ((att.visualoffset.vo (@vo))

        - (att.xy (@x, @y))

- att.verse.anl (att.common.anl (@copyof, @corresp, @next, @prev, @sameas, @synch)

    - (att.alignment (@when)))

**Contained Elements not Implemented:**

- MEI.shared: dir dynam lb space tempo
r  sylru   )rv   rF   r  rj   rw   number	TypeErrorr  rD   r  _BAD_VERSE_NUMBERrM   )r5  backupNrP   r   	syllableseachSyls         r1   verseFromElementr    s    J -1LL2fXS9I,JK,Jq",JIK	P #w!78GN 
  L :& 	P/66txxW7MNO	Ps   A A$$AB0/B0c           	     ~   [          S3[        [          S3[        [          S3[        [          S3[        0n[        U R                  S5      5      n[        U R                  SS5      X0R                  SS5      5      n[        R                  " U5      n[        U R                  S5      5      n[        U[        U R                  S	S
5      5      5      nXCl        S
n[        U R                  S5      UU R                   U5       H  n[#        U[        5      (       a  XV-  nM  [#        U[$        R&                  5      (       a  UR$                  R)                  U5        MZ  [#        U[*        5      (       a'  [,        R.                  " U5      UR,                  l        M  [#        U[        R2                  5      (       d  M  U/Ul        M     U R                  S5      b>  [,        R.                  " [7        U R                  SS5      5      5      UR,                  l        Ub  [9        XU5        U R                  [:        5      b  U R                  [:        5      Ul        U R                  S5      b3  UR$                  R?                  [A        U R                  S5      5      5        U R                  S5      b  [C        U R                  S5      5      Ul"        US
:  a)  [        [        U R                  S5      5      U5      Ul        U R                  S5      b/  [        RF                  " UR                  RH                  5      Ul        U R                  S5      bm  [        RJ                  " UR                  RL                  5      S:  a?  URN                  RQ                  UR                  RL                  U R                  S5      5        U R                  S5      b  [S        X05      nU RU                  S[          S35      bN  / n[W        U R                  S[          S35      5       H   u  pUR?                  [Y        XS-   S95        M"     Xsl        U$ )a  
<note> is a single pitched event.

In MEI 2013: pg.382 (396 in PDF) (MEI.shared module)

.. note:: If set, the @accid.ges attribute is always imported as the music21 :class:`Accidental`
    for this note. We assume it corresponds to the accidental implied by a key signature.

.. note:: If ``elem`` contains both <syl> and <verse> elements as immediate children, the lyrics
    indicated with <verse> element(s) will always obliterate those given indicated with <syl>
    elements.

**Attributes/Elements Implemented:**

- @accid and <accid>
- @accid.ges for key signatures
- @pname, from att.pitch: [a--g]
- @oct, from att.octave: [0..9]
- @dur, from att.duration.musical: (via _qlDurationFromAttr())
- @dots: [0..4], and <dot> contained within
- @xml:id (or id), an XML id (submitted as the Music21Object "id")
- @artic and <artic>
- @tie, (many of "[i|m|t]")
- @slur, (many of "[i|m|t][1-6]")
- @grace, from att.note.ges.cmn: partial implementation (notes marked as grace, but the
    duration is 0 because we ignore the question of which neighbouring note to borrow time from)
- <syl> and <verse>

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base)
- att.facsimile (@facs)
- att.note.log

    - (att.event

        - (att.timestamp.musical (@tstamp))
        - (att.timestamp.performed (@tstamp.ges, @tstamp.real))
        - (att.staffident (@staff))
        - (att.layerident (@layer)))

    - (att.fermatapresent (@fermata))
    - (att.syltext (@syl))
    - (att.note.log.cmn

        - (att.tupletpresent (@tuplet))
        - (att.beamed (@beam))
        - (att.lvpresent (@lv))
        - (att.ornam (@ornam)))

    - (att.note.log.mensural (@lig))

- att.note.vis (all)

- att.note.ges

    - (@oct.ges, @pname.ges, @pnum)
    - att.articulation.performed (@artic.ges))
    - (att.duration.performed (@dur.ges))
    - (att.instrumentident (@instr))
    - (att.note.ges.cmn (@gliss)

        - (att.graced (@grace, @grace.time)))  <-- partially implemented

    - (att.note.ges.mensural (att.duration.ratio (@num, @numbase)))
    - (att.note.ges.tablature (@tab.fret, @tab.string))

- att.note.anl (all)

**Contained Elements not Implemented:**

- MEI.critapp: app
- MEI.edittrans: (all)
r   r   r   r   pnamer  octr   ro   r   r  r   r   gracer  rp  r  r  verser   )r  )-rF   r  r  r  r  r   rw   rl   r   r  r   rr   rj   r   r0  rv   rK   rI   r   Articulationrx   r  r   
Accidentalrh   r  lyricsr   rm  r#  r  r   r   r^  r   GraceDurationquarterLengthrs  rt  ro  ru  r  r`   rq  r  )
r5  rP   r  theNotetheDurationdotElements
subElement
tempLyricsr  	eachVerses
             r1   noteFromElementr  :  sT   \ xs^^xu%'7xu%'7xs^^5M "$((7"34G"-w8KLGii G &dhhuo6K{C0C,DEK" K.t||C/@/</3xx/9;
 j#&&%K
M$>$>??!!((4
C((','7'7
'CGMM$
DJJ//(\GN; xx(#(#3#34Edhh{\^F_4`#a  
+ xx#XXf%
 xx$$$^DHHW4E%FG xx""488E?3 Q'(;DHHUO(LkZ xx$#11'2B2B2P2PQ xx	&''(8(8(=(=>BMMw//44dhhy6IJ xx+. yy2fXU#$0
%dllRxu3E&FGLA.ya%HI H#Nr0   c           	     F   [        U R                  S5      5      n[        U[        U R                  SS5      5      5      n[        R
                  " US9nU R                  [        5      b  U R                  [        5      Ul        U R                  S5      b  [        X05      nU$ )a  
<rest/> is a non-sounding event found in the source being transcribed

In MEI 2013: pg.424 (438 in PDF) (MEI.shared module)

**Attributes/Elements Implemented:**

- xml:id (or id), an XML id (submitted as the Music21Object "id")
- dur, from att.duration.musical: (via _qlDurationFromAttr())
- dots, from att.augmentdots: [0..4]

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base)
- att.facsimile (@facs)
- att.rest.log

    - (att.event

        - (att.timestamp.musical (@tstamp))
        - (att.timestamp.performed (@tstamp.ges, @tstamp.real))
        - (att.staffident (@staff))
        - (att.layerident (@layer)))

    - (att.fermatapresent (@fermata))

        - (att.tupletpresent (@tuplet))
        - (att.rest.log.cmn (att.beamed (@beam)))

- att.rest.vis (all)
- att.rest.ges (all)
- att.rest.anl (all)

**Contained Elements not Implemented:** none
r   ro   r   r   r  )	r   rw   rr   rj   r   r  r#  r  r  )r5  rP   r  theRests       r1   restFromElementr    s    P &dhhuo6K{C0C,DEKii-Gxx#XXf%
 xx+.Nr0   c                d    U R                  S5      b  [        X5      $ [        X5      nSUl        U$ )a  
<mRest/> Complete measure rest in any meter.

In MEI 2013: pg.375 (389 in PDF) (MEI.cmn module)

This is a function wrapper for :func:`restFromElement`.

.. note:: If the <mRest> element does not have a @dur attribute, it will have the default
    duration of 1.0. This must be fixed later, so the :class:`Rest` object returned from this
    method is given the :attr:`m21wasMRest` attribute, set to True.
r   T)rw   r  m21wasMRest)r5  rP   r  s      r1   mRestFromElementr  	  s4     xx"t00!$3"r0   c           	     h   [        U R                  S5      5      n[        U[        U R                  SS5      5      5      n[        R
                  " US9nSUR                  l        U R                  [        5      b  U R                  [        5      Ul	        U R                  S5      b  [        X05      nU$ )a  
<space>  A placeholder used to fill an incomplete measure, layer, etc. most often so that the
combined duration of the events equals the number of beats in the measure.

Returns a Rest element with hideObjectOnPrint = True

In MEI 2013: pg.440 (455 in PDF) (MEI.shared module)
r   ro   r   r   Tr  )r   rw   rr   rj   r   r  stylehideObjectOnPrintr#  r  r  )r5  rP   r  theSpaces       r1   spaceFromElementr#  !	  s     &dhhuo6K{C0C,DEKyy+.H'+HNN$xx#hhv& xx+ 0Or0   c                d    U R                  S5      b  [        X5      $ [        X5      nSUl        U$ )a  
<mSpace/> A measure containing only empty space in any meter.

In MEI 2013: pg.377 (391 in PDF) (MEI.cmn module)

This is a function wrapper for :func:`spaceFromElement`.

.. note:: If the <mSpace> element does not have a @dur attribute, it will have the default
    duration of 1.0. This must be fixed later, so the :class:`Space` object returned from this
    method is given the :attr:`m21wasMRest` attribute, set to True.
r   T)rw   r#  r  )r5  rP   r"  s      r1   mSpaceFromElementr%  ;	  s4     xx"11#D5#r0   c           	     X   [          S3S [          S3[        0n/ nU R                  [          S35       H  nUR                  [	        XA5      5        M     [
        R                  " US9n[        U R                  S5      5      n[        U[        U R                  SS5      5      5      nXSl        [        U R                  S5      UU R                  U5       H?  n[        U[         R"                  5      (       d  M$  UR                   R                  U5        MA     Ub  [%        XU5        U R                  [&        5      b  U R                  [&        5      Ul        U R                  S5      b3  UR                   R+                  [-        U R                  S5      5      5        U R                  S	5      b  [/        U R                  S	5      5      Ul        U R                  S
5      b/  [        R2                  " UR                  R4                  5      Ul        U R                  S5      bm  [        R6                  " UR                  R8                  5      S:  a?  UR:                  R=                  UR                  R8                  U R                  S5      5        U R                  S5      b  [?        X05      nU$ )a)  
<chord> is a simultaneous sounding of two or
more notes in the same layer with the same duration.

In MEI 2013: pg.280 (294 in PDF) (MEI.shared module)

**Attributes/Elements Implemented:**

- @xml:id (or id), an XML id (submitted as the Music21Object "id")
- <note> contained within
- @dur, from att.duration.musical: (via _qlDurationFromAttr())
- @dots, from att.augmentdots: [0..4]
- @artic and <artic>
- @tie, (many of "[i|m|t]")
- @slur, (many of "[i|m|t][1-6]")
- @grace, from att.note.ges.cmn: partial implementation (notes marked as grace, but the
    duration is 0 because we ignore the question of which neighbouring note to borrow time from)

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base)
- att.facsimile (@facs)
- att.chord.log

    - (att.event

        - (att.timestamp.musical (@tstamp))
        - (att.timestamp.performed (@tstamp.ges, @tstamp.real))
        - (att.staffident (@staff))
        - (att.layerident (@layer)))

    - (att.fermatapresent (@fermata))
    - (att.syltext (@syl))
    - (att.chord.log.cmn

        - (att.tupletpresent (@tuplet))
        - (att.beamed (@beam))
        - (att.lvpresent (@lv))
        - (att.ornam (@ornam)))

- att.chord.vis (all)
- att.chord.ges

    - (att.articulation.performed (@artic.ges))
    - (att.duration.performed (@dur.ges))
    - (att.instrumentident (@instr))
    - (att.chord.ges.cmn (att.graced (@grace, @grace.time)))  <-- partially implemented

- att.chord.anl (all)

**Contained Elements not Implemented:**

- MEI.edittrans: (all)
r   c                     g rA   r(   )r   s    r1   rB   "chordFromElement.<locals>.<lambda>	  s    r0   r   )notesr   ro   r   r  r   r  r  rp  r  ) rF   r  r  rx   r  r   r  r   rw   rr   rj   r   r0  rv   rK   rI   r   r  rm  r#  r  r   r   r^  r   r  r  rs  rt  ro  ru  r  )r5  rP   r  theChordr  r  r  s          r1   chordFromElementr+  Q	  s   t xt_oxu%'79M HMMVHD/2=> 3{{*H &dhhuo6K{C0C,DEK# /t||C/@/</3xx/9;
 j-"<"<==""))*5; , xx#hhv& xx$%%nTXXg5F&GH xx"#DHHUO4 xx$$2283D3D3R3RS xx	&''(9(9(>(>?!CNN 1 1 6 68KL xx+ 0Or0   c           	        SU R                  S5      :X  a  [        R                  " 5       nOSU R                  S5      :X  a  [        R                  " 5       nO^[        R                  " U R                  S5      U R                  S5      -   [        U R                  S5      U R                  S5      5      S9nU R                  [        5      b  U R                  [        5      Ul        U$ )a  
<clef> Indication of the exact location of a particular note on the staff and, therefore,
the other notes as well.

In MEI 2013: pg.284 (298 in PDF) (MEI.shared module)

**Attributes/Elements Implemented:**

- @xml:id (or id), an XML id (submitted as the Music21Object "id")
- @shape, from att.clef.gesatt.clef.log
- @line, from att.clef.gesatt.clef.log
- @dis, from att.clef.gesatt.clef.log
- @dis.place, from att.clef.gesatt.clef.log

**Attributes/Elements Ignored:**

- @cautionary, since this has no obvious implication for a music21 Clef
- @octave, since this is likely obscure

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base)
- att.event

    - (att.timestamp.musical (@tstamp))
    - (att.timestamp.performed (@tstamp.ges, @tstamp.real))
    - (att.staffident (@staff))
    - (att.layerident (@layer))

- att.facsimile (@facs)
- att.clef.anl (all)
- att.clef.vis (all)

**Contained Elements not Implemented:** none
percr  TABr  r   r  )octaveShift)rw   r   PercussionClefTabClefclefFromStringr   r#  r  )r5  rP   theClefs      r1   r  r  	  s    L '""%%'	$((7#	#,,.%%dhhw&7$((6:J&J2A$((5/BF((;BW3YZ xx#XXf%
Nr0   c                j   U R                  S5      b.  [        R                  " [        U R                  S5      5      5      $  [        R                  " U R                  S5      5      $ ! [
        [        R                  4 a1    [        R                  " 5       nU R                  SS5      Ul        Us $ f = f)aO  
<instrDef> (instrument definition)---MIDI instrument declaration.

In MEI 2013: pg.344 (358 in PDF) (MEI.midi module)

:returns: An :class:`Instrument`

**Attributes/Elements Implemented:**

- @midi.instrname (att.midiinstrument)
- @midi.instrnum (att.midiinstrument)

**Attributes/Elements in Testing:** none

**Attributes/Elements Ignored:**

- @xml:id

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base)
- att.channelized (@midi.channel, @midi.duty, @midi.port, @midi.track)
- att.midiinstrument (@midi.pan, @midi.volume)

**Contained Elements not Implemented:** none
zmidi.instrnumzmidi.instrnamer  )	rw   r   instrumentFromMidiProgramrj   r  AttributeErrorr  r  r  )r5  rP   theInstrs      r1   r  r  	  s    8 xx ,33C8Q4RSS	((2B)CDD
 > >? 	!,,.H $)92 >HO	s   $A' 'AB21B2c                <   [          S3[        [          S3[        [          S3[        [          S3[        [          S3[
        [          S3[        [          S3[        [          S3[        0n[        U R                  S	5      X R                  U5      n[        U5      nU$ )
aY  
<beam> A container for a series of explicitly beamed events that begins and ends entirely
       within a measure.

In MEI 2013: pg.264 (278 in PDF) (MEI.cmn module)

:param elem: The ``<beam>`` element to process.
:type elem: :class:`~xml.etree.ElementTree.Element`
:returns: An iterable of all the objects contained within the ``<beam>`` container.
:rtype: list of :class:`~music21.base.Music21Object`

**Example**

Here, three :class:`Note` objects are beamed together. Take note that the function returns
a list of three objects, none of which is a :class:`Beam` or similar.

>>> from xml.etree import ElementTree as ET
>>> meiSnippet = """<beam xmlns="http://www.music-encoding.org/ns/mei">
...     <note pname='A' oct='7' dur='8'/>
...     <note pname='B' oct='7' dur='8'/>
...     <note pname='C' oct='6' dur='8'/>
... </beam>"""
>>> meiSnippet = ET.fromstring(meiSnippet)
>>> result = mei.base.beamFromElement(meiSnippet)
>>> isinstance(result, list)
True
>>> len(result)
3
>>> result[0].pitch.nameWithOctave
'A7'
>>> result[0].beams
<music21.beam.Beams <music21.beam.Beam 1/start>>
>>> result[1].pitch.nameWithOctave
'B7'
>>> result[1].beams
<music21.beam.Beams <music21.beam.Beam 1/continue>>
>>> result[2].pitch.nameWithOctave
'C6'
>>> result[2].beams
<music21.beam.Beams <music21.beam.Beam 1/stop>>

**Attributes/Elements Implemented:**

- <clef>, <chord>, <note>, <rest>, <space>, <tuplet>, <beam>, <barLine>

**Attributes/Elements Ignored:**

- @xml:id

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base)
- att.facsimile (@facs)
- att.beam.log

    - (att.event

        - (att.timestamp.musical (@tstamp))
        - (att.timestamp.performed (@tstamp.ges, @tstamp.real))
        - (att.staffident (@staff))
        - (att.layerident (@layer)))

    - (att.beamedwith (@beam.with))

- att.beam.vis (all)
- att.beam.gesatt.beam.anl (all)

**Contained Elements not Implemented:**

- MEI.cmn: bTrem beatRpt fTrem halfmRpt meterSig meterSigGrp
- MEI.critapp: app
- MEI.edittrans: (all)
- MEI.mensural: ligature mensur proport
- MEI.shared: clefGrp custos keySig pad
r   r   r   restr  beamspacebarLiner  )rF   r  r+  r  r  tupletFromElementbeamFromElementr#  barLineFromElementr0  rv   rK   r{  )r5  rP   r  beamedStuffs       r1   r>  r>  
  s    f ($(%*($($(&,($(%*('.	M +4<<+<mXXWabK{+Kr0   c                8    [        U R                  SS5      5      $ )a,  
<barLine> Vertical line drawn through one or more staves that divides musical notation into
metrical units.

In MEI 2013: pg.262 (276 in PDF) (MEI.shared module)

:returns: A :class:`music21.bar.Barline` or :class:`~music21.bar.Repeat`, depending on the
    value of @rend. If @rend is ``'rptboth'``, a 2-tuplet of :class:`Repeat` objects will be
    returned, represented an "end" and "start" barline, as specified in the :mod:`music21.bar`
    documentation.

.. note:: The music21-to-other converters expect that a :class:`Barline` will be attached to a
    :class:`Measure`, which it will not be when imported from MEI as a <barLine> element.
    However, this function does import correctly to a :class:`Barline` that you can access from
    Python in the :class:`Stream` object as expected.

**Attributes/Elements Implemented:**

- @rend from att.barLine.log

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.facsimile (@facs)
- att.pointing (@xlink:actuate, @xlink:role, @xlink:show, @target, @targettype, @xlink:title)
- att.barLine.log

    - (att.meterconformance.bar (@metcon, @control))

- att.barLine.vis

    - (att.barplacement (@barplace, @taktplace))
    - (att.color (@color))
    - (att.measurement (@unit))
    - (att.width (@width))

- att.barLine.ges (att.timestamp.musical (@tstamp))
- att.barLine.anl

    - (att.common.anl

        - (@copyof, @corresp, @next, @prev, @sameas, @synch)
        - (att.alignment (@when)))

**Contained Elements not Implemented:** none
rendr   )rW  rw   r  s     r1   r?  r?  
  s    b DHHVX677r0   c                   [          S3[        [          S3[        [          S3[        [          S3[        [          S3[
        [          S3[        [          S3[        [          S3[        0nU R                  S	5      b  U R                  S5      c  [        [        5      e[        U R                  S5      X R                  U5      n[        SU R                  S	5      U R                  S5      S9n[!        X45      nS
nS
n[#        U5       HN  u  pxUc#  [%        U[&        R(                  5      (       a  UnM+  [%        U[&        R(                  5      (       d  ML  UnMP     SX5   R*                  R,                  S   l        Uc!  SX5   R*                  R,                  S   l        O SX6   R*                  R,                  S   l        [1        U5      n[3        U5      $ )a  
<tuplet> A group of notes with "irregular" (sometimes called "irrational") rhythmic values,
for example, three notes in the time normally occupied by two or nine in the time of five.

In MEI 2013: pg.473 (487 in PDF) (MEI.cmn module)

:param elem: The ``<tuplet>`` element to process.
:type elem: :class:`~xml.etree.ElementTree.Element`
:returns: An iterable of all the objects contained within the ``<tuplet>`` container.
:rtype: tuple of :class:`~music21.base.Music21Object`

**Attributes/Elements Implemented:**

- <tuplet>, <beam>, <note>, <rest>, <chord>, <clef>, <space>, <barLine>
- @num and @numbase

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.facsimile (@facs)
- att.tuplet.log

    - (att.event

        - (att.timestamp.musical (@tstamp))
        - (att.timestamp.performed (@tstamp.ges, @tstamp.real))
        - (att.staffident (@staff))
        - (att.layerident (@layer)))

    - (att.beamedwith (@beam.with))
    - (att.augmentdots (@dots))
    - (att.duration.additive (@dur))
    - (att.startendid (@endid) (att.startid (@startid)))

- att.tuplet.vis (all)
- att.tuplet.ges (att.duration.performed (@dur.ges))
- att.tuplet.anl (all)

**Contained Elements not Implemented:**

- MEI.cmn: bTrem beatRpt fTrem halfmRpt meterSig meterSigGrp
- MEI.critapp: app
- MEI.edittrans: (all)
- MEI.mensural: ligature mensur proport
- MEI.shared: clefGrp custos keySig pad
r  r:  r   r9  r   r   r;  r<  r  Nr  r  r  r  r  r   r   )rF   r=  r>  r  r  r+  r  r#  r?  rw   r7   _MISSING_TUPLET_DATAr0  rv   rK   r   r  rq  rI   r   GeneralNoter   r  rt  r{  rz   )	r5  rP   r  tupletMembersnewElem	firstNotelastNoter  eachObjs	            r1   r=  r=  
  s   f (&,($($($(%*($(%*('.	M xx$((9"5"= 455 -T\\#->xxYcdM c$((S\J]^G!-9M
 IH.
GT5E5E!F!FI!1!122H	 / 9@M%%--a05<B ))11!49;A((0038 !/Mr0   c                z   [          S3[        [          S3[        [          S3[        [          S3[        [          S3[
        [          S3[        [          S3[        [          S3[        [          S	3[        [          S
3[        0
n[        U R                  S5      X0R                  U5      n[        U5      n[        R                   " 5       nU H  nUR#                  U5        M     UR%                  5         U(       a  Xl        U$ U R)                  S5      b  U R)                  S5      Ul        U$ [+        [,        5      e)a  
<layer> An independent stream of events on a staff.

In MEI 2013: pg.353 (367 in PDF) (MEI.shared module)

.. note:: The :class:`Voice` object's :attr:`~music21.stream.Voice.id` attribute must be set
    properly in order to ensure continuity of voices between measures. If the ``elem`` does not
    have an @n attribute, you can set one with the ``overrideN`` parameter in this function. If
    you provide a value for ``overrideN``, it will be used instead of the ``elemn`` object's
    @n attribute.

    Because improperly-set :attr:`~music21.stream.Voice.id` attributes nearly guarantees errors
    in the imported :class:`Score`, either ``overrideN`` or @n must be specified.

:param elem: The ``<layer>`` element to process.
:type elem: :class:`~xml.etree.ElementTree.Element`
:param str overrideN: The value to be set as the ``id``
    attribute in the outputted :class:`Voice`.
:returns: A :class:`Voice` with the objects found in the provided :class:`Element`.
:rtype: :class:`music21.stream.Voice`
:raises: :exc:`MeiAttributeError` if neither ``overrideN`` nor @n are specified.

**Attributes/Elements Implemented:**

- <clef>, <chord>, <note>, <rest>, <mRest>, <beam>, <tuplet>, <space>, <mSpace> , and
  <barLine> contained within
- @n, from att.common

**Attributes Ignored:**

- @xml:id

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @xml:base)
- att.declaring (@decls)
- att.facsimile (@facs)
- att.layer.log (@def) and (att.meterconformance (@metcon))
- att.layer.vis (att.visibility (@visible))
- att.layer.gesatt.layer.anl (all)

**Contained Elements not Implemented:**

- MEI.cmn: arpeg bTrem beamSpan beatRpt bend breath fTrem fermata gliss hairpin halfmRpt
           harpPedal mRpt mRpt2 meterSig meterSigGrp multiRest multiRpt octave pedal
           reh slur tie tuplet tupletSpan
- MEI.cmnOrnaments: mordent trill turn
- MEI.critapp: app
- MEI.edittrans: (all)
- MEI.harmony: harm
- MEI.lyrics: lyrics
- MEI.mensural: ligature mensur proport
- MEI.midi: midi
- MEI.neumes: ineume syllable uneume
- MEI.shared: accid annot artic barLine clefGrp custos dir dot dynam keySig pad pb phrase sb
              scoreDef staffDef tempo
- MEI.text: div
- MEI.usersymbols: anchoredText curve line symbol
r   r   r   r9  mRestr:  r  r;  mSpacer<  r  ru   )rF   r  r+  r  r  r  r>  r=  r#  r%  r?  r0  r  rK   r  r   r  
coreAppendcoreElementsChangedr  rw   r7   _MISSING_VOICE_ID)r5  	overrideNrP   r  r  theVoiceeachs          r1   layerFromElementrT    s&   @ ($(%*($($(%*($(&,(%*(&,('.M (c(:M88U_`H X&H ||~HD!   "  O 
#	"hhsm O   122r0   c           	        [          S3n0 n/ nSnU R                  S5       H  nX&R                  :X  a*  UR                  [	        XeUS95        [        U5      S-    nM<  UR                  U;   a%  UR                  X6R                     " Xa5      5        Mq  UR                  [        ;  d  M  [        R                  [        R                  UR                  U R                  5      5        M     U$ )a  
<staff> A group of equidistant horizontal lines on which notes are placed in order to
represent pitch or a grouping element for individual 'strands' of notes, rests, etc. that may
or may not actually be rendered on staff lines; that is, both diastematic and non-diastematic
signs.

In MEI 2013: pg.444 (458 in PDF) (MEI.shared module)

:param elem: The ``<staff>`` element to process.
:type elem: :class:`~xml.etree.ElementTree.Element`
:returns: The :class:`Voice` classes corresponding to the ``<layer>`` tags in ``elem``.
:rtype: list of :class:`music21.stream.Voice`

**Attributes/Elements Implemented:**

- <layer> contained within

**Attributes Ignored:**

- @xml:id

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base)
- att.declaring (@decls)
- att.facsimile (@facs)
- att.staff.log (@def) (att.meterconformance (@metcon))
- att.staff.vis (att.visibility (@visible))
- att.staff.gesatt.staff.anl (all)

**Contained Elements not Implemented:**

- MEI.cmn: ossia
- MEI.critapp: app
- MEI.edittrans: (all)
- MEI.shared: annot pb sb scoreDef staffDef
- MEI.text: div
- MEI.usersymbols: anchoredText curve line symbol
layerr   r  rP   r   )rF   r  rK   rx   rT  rj   r)  rD   rE   r*  rM   )r5  rP   layerTagNamer  layerscurrentNValueeachTags          r1   staffFromElementr\  w  s    V XU#LMF M ==%;;&MM*7jYZ"=1A56M[[M)MM-4WIJ[[ 33##$;$B$B7;;PTPXPX$YZ & Mr0   c                :   U R                  5        H  nU H~  n[        U[        R                  5      (       d  M$  U HT  n[	        US5      (       d  M  Xl        [        R                  " U5      Ul        [        R                  " U5      Ul        U?MV     M     M     g)ak  
Helper function for measureFromElement(), not intended to be used elsewhere. It's a separate
function only (1) to reduce duplication, and (2) to improve testability.

Iterate the imported objects of <layer> elements in the <staff> elements in a <measure>,
detecting those with the "m21wasMRest" attribute and setting their duration to "targetLength."

The "staves" argument should be a dictionary where the values are Measure objects with at least
one Voice object inside.

The "targetLength" argument should be the duration of the measure.

Nothing is returned; the duration of affected objects is modified in-place.
r  N)	valuesrI   r   Streamrr  r  r   rn   r  )stavestargetLengtheachMeasure	eachVoicer%  s        r1   _correctMRestDursrd    s{     }}$Ii77'
:}55/;,)1):):<)HI&+3+<+<\+JK(". ( % 'r0   c                >   U R                  S5      bx  [        U R                  S5      5      n[        US5      (       a  US   nUR                  5        H4  n[	        U[
        R                  5      (       d  M$  [        U5      Ul        M6     U R                  S5      b  [        U R                  S5      5      n[        US5      (       a  US   US'   US   nUR                  5        H4  n[	        U[
        R                  5      (       d  M$  [        U5      Ul	        M6     U$ )a  
This is a helper function for :func:`measureFromElement`, made independent only to improve
that function's ease of testing.

Given a <measure> element and a dictionary with the :class:`Measure` objects that have already
been processed, change the barlines of the :class:`Measure` objects in accordance with the
element's @left and @right attributes.

:param :class:`~xml.etree.ElementTree.Element` elem: The ``<measure>`` tag to process.
:param dict staves: Dictionary where keys are @n attributes and values are corresponding
    :class:`~music21.stream.Measure` objects.
:returns: The ``staves`` dictionary with properly-set barlines.
:rtype: dict
left__len__r   rV  
next @leftr   )
rw   rW  rr  r^  rI   r   Measurer   leftBarlinerightBarline)r5  r`  barsrb  s       r1   _makeBarlinesrm    s     xx# 014##7D!==?K+v~~66*24.' + xx$ 124###'7F< 7D!==?K+v~~66+3D>( + Mr0   c           
        0 n0 n[          S3n[          S3nSn	U R                  S5       GH@  n
XzR                  :X  a|  [        R                  " [        U
US9[        U R                  SU5      5      S9XZR                  S5      '   XZR                  S5         R                  R                  nU	b  X:  a  Un	M  M  XR                  :X  aN  U
R                  S5      nUc+  [        R                  [        R                  SS	5      5        M  [        X5      Xl'   M  U
R                  [        ;  d  GM  [        R!                  ["        R                  U
R                  U R                  5      5        GMC     UR%                  5        H0  u  pUR'                  5        H  nX\   R)                  S
U5        M     M2     U Hu  nX;  d  M
  [        R*                  " [,        R.                  " U	S9/5      nSUl        SUS
   l        [        R                  " U/[        U R                  SU5      5      S9X_'   Mw     U	[4        S   :X  a<  Ub9  XR6                  R                  :w  a   [9        XTR6                  R                  5        O[9        XY5        [;        X5      nU$ )a  
<measure> Unit of musical time consisting of a fixed number of note-values of a given type, as
determined by the prevailing meter, and delimited in musical notation by two bar lines.

In MEI 2013: pg.365 (379 in PDF) (MEI.cmn module)

:param elem: The ``<measure>`` element to process.
:type elem: :class:`~xml.etree.ElementTree.Element`
:param int backupNum: A fallback value for the resulting
    :class:`~music21.stream.Measure` objects' number attribute.
:param expectedNs: A list of the expected @n attributes for the <staff> tags in this <measure>.
    If an expected <staff> isn't in the <measure>, it will be created with a full-measure rest.
:type expectedNs: iterable of str
:param activeMeter: The :class:`~music21.meter.TimeSignature` active in this <measure>. This is
    used to adjust the duration of an <mRest> that was given without a @dur attribute.
:returns: A dictionary where keys are the @n attributes for <staff> tags found in this
    <measure>, and values are :class:`~music21.stream.Measure` objects that should be appended
    to the :class:`~music21.stream.Part` instance with the value's @n attributes.
:rtype: dict of :class:`~music21.stream.Measure`

.. note:: When the right barline is set to ``'rptboth'`` in MEI, it requires adjusting the left
    barline of the following <measure>. If this happens, the :class:`Repeat` object is assigned
    to the ``'next @left'`` key in the returned dictionary.

**Attributes/Elements Implemented:**

- contained elements: <staff> and <staffDef>
- @right and @left (att.measure.log)
- @n (att.common)

**Attributes Ignored:**

- @xml:id (att.id)
- <slur> and <tie> contained within. These spanners will usually be attached to their starting
  and ending notes with @xml:id attributes, so it's not necessary to process them when
  encountered in a <measure>. Furthermore, because the possibility exists for cross-measure
  slurs and ties, we can't guarantee we'll be able to process all spanners until all
  spanner-attachable objects are processed. So we manage these tags at a higher level.

**Attributes/Elements in Testing:** none

**Attributes not Implemented:**

- att.common (@label, @xml:base)
- att.declaring (@decls)
- att.facsimile (@facs)
- att.typed (@type, @subtype)
- att.pointing (@xlink:actuate, @xlink:role, @xlink:show, @target, @targettype, @xlink:title)
- att.measure.log (att.meterconformance.bar (@metcon, @control))
- att.measure.vis (all)
- att.measure.ges (att.timestamp.performed (@tstamp.ges, @tstamp.real))
- att.measure.anl (all)

**Contained Elements not Implemented:**

- MEI.cmn: arpeg beamSpan bend breath fermata gliss hairpin harpPedal octave ossia pedal reh
           tupletSpan
- MEI.cmnOrnaments: mordent trill turn
- MEI.critapp: app
- MEI.edittrans: add choice corr damage del gap handShift orig reg restore sic subst supplied
                 unclear
- MEI.harmony: harm
- MEI.lyrics: lyrics
- MEI.midi: midi
- MEI.shared: annot dir dynam pb phrase sb tempo
- MEI.text: div
- MEI.usersymbols: anchoredText curve line symbol
staffrt   Nr  rW  ru   )r  
<staffDef>@nr   )r  r   T)rF   r  rK   r   ri  r\  rj   rw   r   r  rD   r  r	  rM   r  r)  rE   r*  itemsr^  insertr  r   r  r  r  r   barDurationrd  rm  )r5  	backupNum
expectedNsrP   activeMeterr`  stavesWaitingstaffTagr  maxBarDurationr.  thisBarDurationwhichNeachDictrJ  eachN	restVoices                    r1   measureFromElementr    s2   J FM HHH%K N MM#&||#(.7GS]8_>A$((3PYBZ>[)]F<<$% %\\#%67@@NNO%)I!0 *JLL(\\#&F~!!"7">">|T"RS(;H(Q%\\!44##$;$B$B8<<QUQYQY$Z[ '( *//1(G N!!!W- ) 2 diin&M%NOIIL'+IaL$"NNI;s488CQZC[?\]FM  	...'"9"9"G"GG&"9"9"G"GH 	&1 4(FMr0   rw  nextMeasureLeftbackupMeasureNumc          
     \   [          S3n[          S3n[          S3n[          S3n	[          S3n
U Vs0 s H  o/ _M     nnU Vs0 s H  o/ _M     nnU R                  S5       GH  nXR                  :X  a  XpR                  :X  a~  US-  n[        XUUUS9nU HV  nUU    H  nUU   R	                  S	U5        M     / UU'   Ub  [        U5      UU   l        UU   R                  UU   5        MX     SU;   a  US   nM  S
nM  XR                  :X  a  [        X5      nUS    Ha  n[        U[        R                  5      (       a  Un[        U5       H.  u  nnUS	:X  a  UnO[        U5      nUU   R                  U5        M0     Mc     U H9  nUU;   d  M  UU   R                  5        H  nUU   R                  U5        M     M;     GMf  XR                  :X  a  UR                  S5      bf  [        X5      R                  5        HF  n[        U[        R                  5      (       a  UnXR                  S5         R                  U5        MH     GM  [         R#                  [$        R'                  SS5      5        GM  X~R                  :X  Ga;  [)        UUUUUUS9u  np4nUR+                  5        GH  u  nnUU   (       a  S
nS
n[        UU   5       H+  u  nn[        U[,        R.                  5      (       d  M'  UnUn  O   U(       a  UR	                  S	U5        UU   U	 U HB  n[        U[0        R2                  5      (       d  M$  UU    H  nUR	                  SU5        M       O   / UU'   XpR                  :X  a  U H  nUU   R                  U5        M     M  X`R                  :X  d  M  UU   R                  U5        GM     GMd  UR                  [4        ;  d  GM{  [         R7                  [8        R'                  UR                  U R                  5      5        GM     XXE4$ s  snf s  snf )a  
This function is the "core" of both :func:`sectionFromElement` and :func:`scoreFromElement`,
since both elements are treated quite similarly (though not identically). It's a separate and
shared function to reduce code duplication and
increase ease of testing. It's a "public" function
to help spread the burden of API documentation complexity: while the parameters and return
values are described in this function, the compliance with the MEI Guidelines is described in
both :func:`sectionFromElement` and :func:`scoreFromElement`, as expected.

**Required Parameters**

:param elem: The <section> or <score> element to process.
:type elem: :class:`xml.etree.ElementTree.Element`
:param allPartNs: A list or tuple of the expected @n attributes for the <staff> tags in this
    <section>. This tells the function how many parts there are and what @n values they use.
:type allPartNs: iterable of str
:param slurBundle: This :class:`SpannerBundle` holds the :class:`~music21.spanner.Slur` objects
    created during pre-processing. The slurs are attached to their respective :class:`Note` and
    :class:`Chord` objects as they are processed.
:type slurBundle: :class:`music21.spanner.SpannerBundle`

**Optional Keyword Parameters**

The following parameters are all optional, and must be specified as a keyword argument (i.e.,
you specify the parameter name before its value).

:param activeMeter: The :class:`~music21.meter.TimeSignature` active at the start of this
    <section> or <score>. This is updated automatically as the music is processed, and the
    :class:`TimeSignature` active at the end of the element is returned.
:type activeMeter: :class:`music21.meter.TimeSignature`
:param nextMeasureLeft: The @left attribute to use for the next <measure> element encountered.
    This is used for situations where one <measure> element specified a @right attribute that
    must be imported by music21 as *both* the right barline of one measure and the left barline
    of the following; at the moment this is only @rptboth, which requires a :class:`Repeat` in
    both cases.
:type nextMeasureLeft: :class:`music21.bar.Barline` or :class:`music21.bar.Repeat`
:param backupMeasureNum: In case a <measure> element is missing its @n attribute,
    :func:`measureFromElement` will use this automatically-incremented number instead. The
    ``backupMeasureNum`` corresponding to the final <measure> in this <score> or <section> is
    returned from this function.
:type backupMeasureNum: int
:returns: Four-tuple with a dictionary of results, the new value of ``activeMeter``, the new
    value of ``nextMeasureLeft``, and the new value of ``backupMeasureNum``.
:rtype: (dict, :class:`~music21.meter.TimeSignature`, :class:`~music21.bar.Barline`, int)

**Return Value**

In short, it's ``parsed``, ``activeMeter``, ``nextMeasureLeft``, ``backupMeasureNum``.

- ``'parsed'`` is a dictionary where the keys are the values in ``allPartNs`` and the values are
    a list of all the :class:`Measure` objects in that part, as found in this <section> or
    <score>.
- ``'activeMeter'`` is the :class:`~music21.meter.TimeSignature` in effect at the end of this
    <section> or <score>.
- ``'nextMeasureLeft'`` is the value that should be
    assigned to the :attr:`leftBarline` attribute
    of the first :class:`Measure` found in the next <section>. This will almost always be None.
- ``'backupMeasureNum'`` is equal to the ``backupMeasureNum`` argument plus the number of
    <measure> elements found in this <score> or <section>.
rY   sectionmeasurescoreDefrt   r  r   )rP   rw  r   Nrh  r  ru   rp  rq  )rw  r  r  rP           )rF   r  rK   r  rs  r   rj  rx   r  rI   r   r4  rq  r^  rw   r  rD   r  r	  rM   sectionFromElementrr  r   r  r   r_  r)  rE   r*  )r5  	allPartNsrP   rw  r  r  scoreTag
sectionTag
measureTagscoreDefTagr  ru   parsedinNextThingr.  measureResultr~  	eachThinglocalResultallPartObjectr  	to_insertrJ  localParsedeachListr7  	theInstrIeachInsertions                               r1   sectionScoreCorer  |  s   N H87#J87#JHH%KHH%K ''YeYF'"+,)Qb5)K,MM#&%**@!.x9:D;FHM #!,U!3I!%(//9= "4%'E"".7?7PM%(4u$$]5%9: # },"/"="&LL(-hCK!,-?!@mU-@-@AA"/K )) 4HAuAv$1	 %-]$;	&--i8 !5 "A #K'#.u#5#<#<#>#E*11': $? #
 LL(||C ,28HOOQG!'5+>+>??&-S 1299'B  R !!"7">">|T"RS<<'J\' /!1%K'GK7G $/#4#4#6x u%#H $I,5k%6H,I(=%mZ5J5JKK'4H()I!	 -J   84'.y9#+ &gv}}==1<U1C 'sM B 2D! $, *,K& ) $,u,,W5 $,) 5M((2W $7Z \\!44##$;$B$B8<<QUQYQY$Z[[ 'd AAm (,s   P$P)c           	     H    [         R                  S5        [        U UUUUUS9$ )a  
<section> Segment of music data.

In MEI 2013: pg.432 (446 in PDF) (MEI.shared module)

.. note:: The parameters and return values are exactly the same for :func:`sectionFromElement`
    and :func:`sectionScoreCore`, so refer to the latter function's documentation for more
    information.

**Attributes/Elements Implemented:**

**Attributes Ignored:**

**Attributes/Elements in Testing:**

- @label
- contained <measure>, <scoreDef>, <staffDef>, <section>

**Attributes not Implemented:**

- att.common (@n, @xml:base) (att.id (@xml:id))
- att.declaring (@decls)
- att.facsimile (@facs)
- att.typed (@type, @subtype)
- att.pointing (@xlink:actuate, @xlink:role, @xlink:show, @target, @targettype, @xlink:title)
- att.section.vis (@restart)
- att.section.anl (att.common.anl (@copyof, @corresp, @next, @prev, @sameas, @synch)
                                  (att.alignment (@when)))

**Contained Elements not Implemented:**

- MEI.critapp: app
- MEI.edittrans: add choice corr damage del gap handShift orig reg
                 restore sic subst supplied unclear
- MEI.shared: annot ending expansion pb sb section staff
- MEI.text: div
- MEI.usersymbols: anchoredText curve line symbol
z*** processing a <section>r  )rD   rE   r  )r5  r  rw  r  r  rP   s         r1   r  r  C  s2    N 89D%&(3,;-=? ?r0   c                   [         R                  S5        [        U 5      n[        XUS9S   n[         R                  S5        [	        [        U5      5       Vs/ s H  n[        R                  " 5       PM     nn[        U5       H,  u  pgSXV   l	        X7    H  nXV   R                  U5        M     M.     [        R                  " U5      nUR                  [        U5      5        U$ s  snf )a  
<score> Full score view of the musical content.

In MEI 2013: pg.430 (444 in PDF) (MEI.shared module)

:param elem: The <score> element to process.
:type elem: :class:`~xml.etree.ElementTree.Element`
:param slurBundle: This :class:`SpannerBundle` holds the :class:`~music21.spanner.Slur` objects
    created during pre-processing. The slurs are attached to their respective :class:`Note` and
    :class:`Chord` objects as they are processed.
:type slurBundle: :class:`music21.spanner.SpannerBundle`
:returns: A completed :class:`~music21.stream.Score` object.

**Attributes/Elements Implemented:**

**Attributes Ignored:**

**Attributes/Elements in Testing:**

- contained <section>, <scoreDef>, and <staffDef>

**Attributes not Implemented:**

- att.common (@label, @n, @xml:base) (att.id (@xml:id))
- att.declaring (@decls)
- att.typed (@type, @subtype)
- att.score.anl (att.common.anl (@copyof, @corresp, @next, @prev, @sameas, @synch)
                                (att.alignment (@when)))

**Contained Elements not Implemented:**

- MEI.critapp: app
- MEI.edittrans: add choice corr damage del gap handShift orig
                 reg restore sic subst supplied unclear
- MEI.shared: annot ending pb sb
- MEI.text: div
- MEI.usersymbols: anchoredText curve line symbol
z*** processing a <score>rW  r   z*** making the ScoreF)rD   rE   r~   r  ranger  r   Partrq  atSoundingPitchrx   Scorer(  )	r5  rP   r  r  r  rb   r  r~  rJ  s	            r1   r_   r_   s  s    P 67
  %I d*EaHF
 23',S^'<='<!'<H=i(&+#}GKw' % )
 ||H%H OOD$% O >s   C'__main__)Nr  )rk   r  rh   z
str | Nonerg   z	str | intre   zpitch.Pitch)r  r   )rp   zfloat | int | Fractionro   rj   re   zduration.Duration)re   ztuple[str, ...])r   z!t.Literal['8', '15', '22'] | Noner   r  re   rj   )NN)r+  zlist[Element])r5  r   re   zkey.Key | key.KeySignaturerA   )r.   
__future__r   collectionsr   copyr   typingr  uuidr   xml.etree.ElementTreer   r   r	   r
   music21r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   TYPE_CHECKING	fractionsr   EnvironmentrD   r#  rF   r)  Music21Exceptionr&   r4   r7   r:   _TEST_FAILSrH   rL   _UNKNOWN_TAGr   ry   rP  _CANNOT_FIND_XMLIDrD  r	  r*  r  r  r=   rl   rr   r~   r   r   r   Accentr   r   Staccatissimor   SpiccatoDoitPlopFalloffDownBowUpBowHarmonicSnapPizzicatoStopped
OpenStringDoubleTongueOrganToeTripleTongue	OrganHeelr  r   rZ  r   r   r   r   r   r   r   r   rZ   r[   r\   r]   r^   r0  r6  rC  rO  rW  r^  rm  r{  r  ra   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r#  r%  r+  r  r  r>  r?  r=  rT  r\  rd  rm  r  r  r  r_   
_DOC_ORDERr*   mainTestr(   r0   r1   <module>r     s  bH # #    N N "                  ??"&&z2
 
4	1 hbMhbMhbMhdOhcNhjhhhh	 	|44 		L11 		55 		l33 	 d3 T >B L K L Y G H =< 
G G\  %!
%!%! %! 	%!R  #

 @+dXC Xc3 Xd XC XtT X4QV X%X!%uX.13X8<cXCGXNRTXX#X#SX*.X6:CXAEsXLPRVX  !s$dTX!DF 
 3SsQT\`VGHU^$kME=// ]33=//  ; ; M66	
 ]33 M.. M.. M11 ]22 ]00 M22 M77 M11 M44  !;!;  =11!" #0"<"<)33(55+88(55+88(55)66)66*77"/"<"<)66,99= F %$! !%G8<D	8E& ! &) *&6S]l#\L1=h>MB$ZX 	AAH	Z<<&[TK0 AHB ,:6:R"@F:~nb9xYx89x76t:%z+\Xv3l,4,m`2j$N`F18h] @`F=@/6"JBL "&taDBN-?`CP +
0 z r0   