
    3j                    V   d dl mZ d dlmZ d dlmZ d dlZd dlmZmZ d dl	Z	d dl
Z
d dlmZmZ d dlZd dlmZ d dlmZmZ erd d	lmZmZ g d
Zg dZedd Zded<   ded<   ded<   ded<   d0dZej6                  Zed1d       Z eg d      Zed2d       Z ed3d       Z d4dZ ej6                  fd5dZ!d6dZ"d7d8dZ#d9d:dZ$d;dZ%dZ&d<d Z'd=d!Z(d>d"Z)	 	 	 	 d?d#Z*	 d@	 	 	 dAd$Z+dBdCd%Z,dDd&Z-dEd'Z.d(d)dFd*Z/dGd+Z0dHdId,Z1i Z2 e3 e4e            D ]Z  Z5ee5   Z6e6jo                         Z8e5e2e6<   e5e2e8<   e5e2 e9e5       e1e5      z   <   ee5   Z:e:e6k7  sAe:jo                         Z;e5e2e:<   e5e2e;<   \ [5[6[8[:[; G d- d.ejx                        Z=e/e0gZ>e?d/k(  rd dlZ ej                  e=       yy)J    )annotations)Fraction)cacheN)isclosegcd)overloadTYPE_CHECKING)defaults)
OffsetQLInOffsetQL)Sequence
Collection)addFloatPrecisionapproximateGCDcontiguousListdecimalToTupletdotMultiplier	fromRomangroupContiguousIntegersmixedNumeralmusicOrdinalsnearestMultiplenumToIntOrFloatopFracordinalAbbreviationordinalsordinalsToNumbersroundToHalfIntegerstrTrimFloattoRomanunitBoundaryProportionunitNormalizeProportionweightedSelection)ZerothFirstSecondThirdFourthFifthSixthSeventhEighthNinthTenthEleventhTwelfth
Thirteenth
Fourteenth	Fifteenth	SixteenthSeventeenth
Eighteenth
Nineteenth	TwentiethzTwenty-firstzTwenty-secondUnison   Octave   zDouble-octave   zTriple-octave   c                    	 t        |       }t	        || d      r|S | dz   S # t        t        f$ r t        |       } t        |       }Y <w xY w)a  
    Given a number, return an integer if it is very close to an integer,
    otherwise, return a float.

    This routine is very important for conversion of
    :class:`~music21.pitch.Accidental` objects' `.alter`  attribute
    in musicXML must be 1 (not 1.0) for sharp and -1 (not -1.0) for flat,
    but allows for 0.5 for half-sharp.

    >>> common.numToIntOrFloat(1.0)
    1
    >>> common.numToIntOrFloat(1.00003)
    1.00003
    >>> common.numToIntOrFloat(1.5)
    1.5
    >>> common.numToIntOrFloat(2)
    2
    >>> common.numToIntOrFloat(-5)
    -5
    >>> common.numToIntOrFloat(1.0000000005)
    1
    >>> common.numToIntOrFloat(0.999999999)
    1

    >>> sharp = pitch.Accidental('sharp')
    >>> common.numToIntOrFloat(sharp.alter)
    1
    >>> halfFlat = pitch.Accidental('half-flat')
    >>> common.numToIntOrFloat(halfFlat.alter)
    -0.5

    Can also take in a string representing an int or float

    >>> common.numToIntOrFloat('1.0')
    1
    >>> common.numToIntOrFloat('1')
    1
    >>> common.numToIntOrFloat('1.25')
    1.25

    Others raise a ValueError

    >>> common.numToIntOrFloat('one')
    Traceback (most recent call last):
    ValueError: could not convert string to float: 'one'

    Fractions also become ints or floats

    >>> from fractions import Fraction
    >>> common.numToIntOrFloat(Fraction(1, 2))
    0.5
    >>> common.numToIntOrFloat(Fraction(4, 3))
    1.333333333...

    Note: Decimal objects are not supported.
    gư>abs_tol        )round
ValueError	TypeErrorfloatr   )valueintVals     G/DATA/.local/lib/python3.12/site-packages/music21/common/numberTools.pyr   r   H   sV    ru
 vud+3; 	" eus   " %A
	A
c                n   |t         k  r| |fS | }|}d\  }}}}	 | |z  }|||z  z   }	|	t         kD  rn|||||z  z   |	f\  }}}}|| ||z  z
  }} 3t         |z
  |z  }
||
|z  z   }||
|z  z   }|}|}t        ||z  ||z  z
        }||z  }t        ||z  ||z  z
        }||z  }||z  ||z  z
  }|dk\  r||fS ||fS )aW  
    Used in opFrac

    Copied from fractions.limit_denominator.  Their method
    requires creating three new Fraction instances to get one back.
    This doesn't create any call before Fraction.

    DENOM_LIMIT is hardcoded to defaults.limitOffsetDenominator for speed.

    returns a new n, d.

    >>> common.numberTools._preFracLimitDenominator(100001, 300001)
    (1, 3)

    >>> from fractions import Fraction
    >>> Fraction(100_000_000_001, 30_0000_000_001).limit_denominator(65535)
    Fraction(1, 3)
    >>> Fraction(100001, 300001).limit_denominator(65535)
    Fraction(1, 3)

    Timing differences are huge!

    t is timeit.timeit::

        t('Fraction(*common.numberTools._preFracLimitDenominator(*x.as_integer_ratio()))',
           setup='x = 1000001/3000001; from music21 import common; from fractions import Fraction',
           number=100000)
        1.0814228057861328

        t('Fraction(x).limit_denominator(65535)',
           setup='x = 1000001/3000001; from fractions import Fraction',
           number=100000)
        7.941488981246948

    Nothing changed in 2023, in fact, it's faster now with the cache, and even
    without the cache, it's still 4x faster.

    Proof of working:

    >>> import random
    >>> myWay = lambda x: Fraction(*common.numberTools._preFracLimitDenominator(
    ...     *x.as_integer_ratio()))
    >>> theirWay = lambda x: Fraction(x).limit_denominator(65535)

    >>> for _ in range(50):
    ...     x = random.random()
    ...     if myWay(x) != theirWay(x):
    ...         print(f'boo: {x}, {myWay(x)}, {theirWay(x)}')

    (n.b. -- nothing printed)
    )r   r:   r:   r   r   )DENOM_LIMITabs)ndnOrgdOrgp0q0p1q1aq2kbound1nbound1dbound2nbound2dbound1minusS_nbound1minusS_dbound2minusS_nbound2minusS_d
differences                       rI   _preFracLimitDenominatorra      s+   l 	K1vDDNBB
F!b&[Ra"fb0BB!a!e)1  
r	b A1r6kG1r6kGGG'D.TG^<=NG^N'D.TG^<=NG^N >1n~6UVJQ!!!!    )g      ?g      ?g      ?g      ?      ?g      ?      ?      ?      ?      ?       @      @      @      @c                     y N nums    rI   r   r          rb   c                     y rm   rn   ro   s    rI   r   r      rq   rb   c                z   | t         v r| dz   S t        |       }|t        u rW| j                         }|d   t        kD  r9t        t        |  }|j                  }||dz
  z  dk(  r|j                  |dz   z  S |S | S |t        u r| dz   S |t
        u r+| j                  }||dz
  z  dk(  r| j                  |dz   z  S | S | yt        | t              r| dz   S t        | t              rt        t        |             S t        | t
              r+| j                  }||dz
  z  dk(  r| j                  |dz   z  S | S t        d|        )a  
    opFrac -> optionally convert a number to a fraction or back.

    Important music21 function for working with offsets and quarterLengths

    Takes in a number and converts it to a Fraction with denominator
    less than limitDenominator if it is not binary expressible; otherwise return a float.
    Or if the Fraction can be converted back to a binary expressible
    float then do so.

    This function should be called often to ensure that values being passed around are floats
    and ints wherever possible and fractions where needed.

    The naming of this method violates music21's general rule of no abbreviations, but it
    is important to make it short enough so that no one will be afraid of calling it often.
    It also doesn't have a setting for maxDenominator so that it will expand in
    Code Completion easily. That is to say, this function has been set up to be used, so please
    use it.

    This is a performance-critical operation. Do not alter it in any way without running
    many timing tests.

    >>> from fractions import Fraction
    >>> defaults.limitOffsetDenominator
    65535
    >>> common.opFrac(3)
    3.0
    >>> common.opFrac(1/3)
    Fraction(1, 3)
    >>> common.opFrac(1/4)
    0.25
    >>> f = Fraction(1, 3)
    >>> common.opFrac(f + f + f)
    1.0
    >>> common.opFrac(0.99999999842)
    1.0
    >>> common.opFrac(0.123456789)
    Fraction(10, 81)
    >>> common.opFrac(0.000001)
    0.0

    Please check against None before calling, but None is changed to 0.0

    >>> common.opFrac(None)
    0.0

    * Changed in v9.3: opFrac(None) should not be called.  If it is called,
      it now returns 0.0.
    rB   r:   r   zCannot convert num: )_KNOWN_PASSEStyperF   as_integer_ratiorK   r   ra   _denominator
_numeratorint
isinstancer   denominator	numeratorrE   )rp   numTypeirf_outrN   s        rI   r   r      sc   t mSy 3iG% !!#a5;6;<E""AQU!''1s733 J	CSy	H	QKA>>QW--J	 
C	Sy	C	eCj!!	C	"OOQKA==AG,,J.se455rb   c                   t        | t              sOt        t        |       d      \  }}t        |      j	                  |      }|dk  r|dz  }d|z
  }n0|dk(  r+d}|dz
  }n#t        t        |             }| |z
  }|dk  r|dz  }|r&|rt        |       d| S t        t        |            S |dk7  rt        |      S t        d      S )a  
    Returns a string representing a mixedNumeral form of a number

    >>> common.mixedNumeral(1.333333)
    '1 1/3'
    >>> common.mixedNumeral(0.333333)
    '1/3'
    >>> common.mixedNumeral(-1.333333)
    '-1 1/3'
    >>> common.mixedNumeral(-0.333333)
    '-1/3'

    >>> common.mixedNumeral(0)
    '0'
    >>> common.mixedNumeral(-0)
    '0'

    Works with Fraction objects too

    >>> from fractions import Fraction
    >>> common.mixedNumeral(Fraction(31, 7))
    '4 3/7'
    >>> common.mixedNumeral(Fraction(1, 5))
    '1/5'
    >>> common.mixedNumeral(Fraction(-1, 5))
    '-1/5'
    >>> common.mixedNumeral(Fraction(-4, 5))
    '-4/5'
    >>> common.mixedNumeral(Fraction(-31, 7))
    '-4 3/7'

    Denominator is limited by default but can be changed.

    >>> common.mixedNumeral(2.0000001)
    '2'
    >>> common.mixedNumeral(2.0000001, limitDenominator=10000000)
    '2 1/10000000'
    rf   r:   rB   r    )rz   r   divmodrF   limit_denominatorry   str)exprlimitDenominatorquotient	remainderremainderFracs        rI   r   r   i  s    P dH%$U4[#6) +==>NOb=MH-M^H)A-MuT{#xa<RM(m_Am_55s8}%%A}%%q6Mrb   c                    t        | d      \  }}t        |      }|dk  rd}||z   S d|cxk  rdk  r
n nd}||z   S d}||z   S )a  
    Given a floating-point number, round to the nearest half-integer. Returns int or float

    >>> common.roundToHalfInteger(1.2)
    1
    >>> common.roundToHalfInteger(1.35)
    1.5
    >>> common.roundToHalfInteger(1.8)
    2
    >>> common.roundToHalfInteger(1.6234)
    1.5

    0.25 rounds up:

    >>> common.roundToHalfInteger(0.25)
    0.5

    as does 0.75

    >>> common.roundToHalfInteger(0.75)
    1

    unlike python round function, does the same for 1.25 and 1.75

    >>> common.roundToHalfInteger(1.25)
    1.5
    >>> common.roundToHalfInteger(1.75)
    2

    negative numbers however, round up on the boundaries

    >>> common.roundToHalfInteger(-0.26)
    -0.5
    >>> common.roundToHalfInteger(-0.25)
    0
    rf   rc   r   re   rd   r:   )r   ry   )rp   rH   floatVals      rI   r   r     sk    J c3'FH[F$
 H	 
	 D	  H Hrb   c                    t        | t              rt        |       } d}|D ]  }t        | ||      st	        |      c S  | S )a   
    Given a value that suggests a floating point fraction, like 0.33,
    return a Fraction or float that provides greater specification, such as Fraction(1, 3)

    >>> import fractions
    >>> common.addFloatPrecision(0.333)
    Fraction(1, 3)
    >>> common.addFloatPrecision(0.33)
    Fraction(1, 3)
    >>> common.addFloatPrecision(0.35) == fractions.Fraction(1, 3)
    False
    >>> common.addFloatPrecision(0.2) == 0.2
    True
    >>> common.addFloatPrecision(0.125)
    0.125
    >>> common.addFloatPrecision(1/7) == 1/7
    True
    )gUUUUUU?gUUUUUU?gUUUUUU?g?r@   )rz   r   rF   r   r   )xgrainvaluesvs       rI   r   r     sE    & !S!HF1a'!9  Hrb   c                    dt        |      z   dz   }|| z  }|j                  d      }t        |      }t        |dz
  |dz   d      D ]  }||   dk7  r n|dz
  } |d| }|S )aw  
    returns a string from a float that is at most maxNum of
    decimal digits long, but never less than 1.

    >>> common.strTrimFloat(42.3333333333)
    '42.3333'
    >>> common.strTrimFloat(42.3333333333, 2)
    '42.33'
    >>> common.strTrimFloat(6.66666666666666, 2)
    '6.67'
    >>> common.strTrimFloat(2.0)
    '2.0'
    >>> common.strTrimFloat(-5)
    '-5.0'
    z%.f.r:   r   0r   )r   indexlenrange)floatNummaxNumoffBuildStringoff
offDecimaloffLenr   s          rI   r   r     s|    " S[(3.N
8
#C3JXFvz:>26u:aZF	 7
 a-CJrb   c                l   | dk  rt        d|  ddz   d| z         t        j                  | |z        }|dz  }||z  }||dz   z  }|| cxk\  r|k\  rn nt        d| d	|       || cxk  r||z   k  r"n n|t        | |z
  d
      t        | |z
  d
      fS |t        || z
  d
      t        | |z
  d
      fS )a>  
    Given a positive value `n`, return the nearest multiple of the supplied `unit` as well as
    the absolute difference (error) to seven significant digits and the signed difference.

    >>> print(common.nearestMultiple(0.25, 0.25))
    (0.25, 0.0, 0.0)
    >>> print(common.nearestMultiple(0.35, 0.25))
    (0.25, 0.1..., 0.1...)
    >>> print(common.nearestMultiple(0.20, 0.25))
    (0.25, 0.05..., -0.05...)

    Note that this one also has an error of 0.1, but it's a positive error off of 0.5

    >>> print(common.nearestMultiple(0.4, 0.25))
    (0.5, 0.1..., -0.1...)

    >>> common.nearestMultiple(0.4, 0.25)[0]
    0.5
    >>> common.nearestMultiple(23404.001, 0.125)[0]
    23404.0
    >>> common.nearestMultiple(23404.134, 0.125)[0]
    23404.125

    Error is always positive, but signed difference can be negative.

    >>> common.nearestMultiple(23404 - 0.0625, 0.125)
    (23403.875, 0.0625, 0.0625)

    >>> common.nearestMultiple(0.001, 0.125)[0]
    0.0

    >>> from math import isclose
    >>> isclose(common.nearestMultiple(0.25, 1 / 3)[0], 0.33333333, abs_tol=1e-7)
    True
    >>> isclose(common.nearestMultiple(0.55, 1 / 3)[0], 0.66666666, abs_tol=1e-7)
    True
    >>> isclose(common.nearestMultiple(234.69, 1 / 3)[0], 234.6666666, abs_tol=1e-7)
    True
    >>> isclose(common.nearestMultiple(18.123, 1 / 6)[0], 18.16666666, abs_tol=1e-7)
    True

    >>> common.nearestMultiple(-0.5, 0.125)
    Traceback (most recent call last):
    ValueError: n (-0.5) is less than zero. Thus, cannot find the nearest
        multiple for a value less than the unit, 0.125
    r   zn (z) is less than zero. z3Thus, cannot find the nearest multiple for a value zless than the unit, rh   r:   z"cannot place n between multiples: z,    )rD   mathfloorrC   )rM   unitmulthalfUnitmatchLow	matchHighs         rI   r   r     s    ^ 	1u3qc!67PQ1$89 : 	: ::a$hDczHd{Hq!I 1!	!=hZr)UVV1-H,-q8|Q/q8|Q1GGG %	Aq15Y3JJJrb   )	rf   rg   g      ?g      ?g      ?g     ?g     ?g     ?g     ?c                @    | dk  r	t         |    S d| dz   z  dz
  d| z  z  S )a  
    dotMultiplier(dots) returns how long to multiply the note
    length of a note in order to get the note length with n dots

    Since dotMultiplier always returns a power of two in the denominator,
    the float will be exact.

    >>> from fractions import Fraction
    >>> Fraction(common.dotMultiplier(1))
    Fraction(3, 2)
    >>> Fraction(common.dotMultiplier(2))
    Fraction(7, 4)
    >>> Fraction(common.dotMultiplier(3))
    Fraction(15, 8)

    >>> common.dotMultiplier(0)
    1.0
    	      rf   )_DOT_LOOKUP)dotss    rI   r   r   `  s3    & ax4  4#:#%!t)44rb   c                n   d }d}| dk  rt        d      | dk  rd}d| z  } t        j                  |       \  }}| |z  } ||      \  }}|dk(  rt        d      ||z  }t	        t        |      t        |            }||z  }||z  }|du rt        |      t        |      fS t        |      t        |      fS )a  
    For simple decimals (usually > 1), a quick way to figure out the
    fraction in lowest terms that gives a valid tuplet.

    No it does not work really fast.  No it does not return tuplets with
    denominators over 100.  Too bad, math geeks.  This is real life.  :-)

    returns (numerator, denominator)

    >>> common.decimalToTuplet(1.5)
    (3, 2)
    >>> common.decimalToTuplet(1.25)
    (5, 4)

    If decNum is < 1, the denominator will be greater than the numerator:

    >>> common.decimalToTuplet(0.8)
    (4, 5)

    If decNum is <= 0, returns a ZeroDivisionError:

    >>> common.decimalToTuplet(-.02)
    Traceback (most recent call last):
    ZeroDivisionError: number must be greater than zero
    c                    t        dd      D ]A  }t        ||dz        D ]-  }t        | ||z  d      st        |      t        |      fc c S  C y)z#
        Utility function.
        r:     r   gHz>r@   )r   r   )r   r   ry   )inner_workingr   js      rI   findSimpleFractionz+decimalToTuplet.<locals>.findSimpleFraction  sQ     1d^E5%!),=!e)TBFCJ// - $ rb   Fr   z number must be greater than zeror:   TzNo such luck)ZeroDivisionErrorr   modfrD   r   ry   )	decNumr   flipNumeratorunused_remainder
multiplierworkingjyiymy_gcds	            rI   r   r   y  s    4 M{ BCCzV#'99V#4 jz!G!'*HR	Qw((*BR#b'"F	fB	fBBR!!BR!!rb   c                |    d}| D ]  }|dk  rt        d      ||z  } g }| D ]  }|j                  ||z          |S )a  
    Normalize values within the unit interval, where max is determined by the sum of the series.

    >>> common.unitNormalizeProportion([0, 3, 4])
    [0.0, 0.42857142857142855, 0.5714285714285714]
    >>> common.unitNormalizeProportion([1, 1, 1])
    [0.3333333..., 0.333333..., 0.333333...]

    Works fine with a mix of ints and floats:

    >>> common.unitNormalizeProportion([1.0, 1, 1.0])
    [0.3333333..., 0.333333..., 0.333333...]

    On 32-bit computers this number may be inexact even for small floats.
    On 64-bit it works fine.  This is the 32-bit output for this result.

        common.unitNormalizeProportion([0.2, 0.6, 0.2])
        [0.20000000000000001, 0.59999999999999998, 0.20000000000000001]

    Negative values should be shifted to positive region first:

    >>> common.unitNormalizeProportion([0, -2, -8])
    Traceback (most recent call last):
    ValueError: value members must be positive
    rB   zvalue members must be positive)rD   append)r   	summationr   r   s       rI   r"   r"     sU    4 Is7=>>Q	  DQ]$ Krb   c                    t        |       }g }d}t        t        |            D ]H  }|t        |      dz
  k7  r"|j                  ||||   z   f       |||   z  }6|j                  |df       J |S )aG  
    Take a series of parts with an implied sum, and create
    unit-interval boundaries proportional to the series components.

    >>> common.unitBoundaryProportion([1, 1, 2])
    [(0.0, 0.25), (0.25, 0.5), (0.5, 1.0)]
    >>> common.unitBoundaryProportion([9, 1, 1])
    [(0.0, 0.8...), (0.8..., 0.9...), (0.9..., 1.0)]
    rB   r:   rf   )r"   r   r   r   )seriesr   boundsr   r   s        rI   r!   r!     s{     #6*DFIs4y!CIM!MM9i$u+&=>?e$IMM9c*+ " Mrb   c                    | |       }nt        j                          }t        |      }d}t        |      D ]  \  }\  }}||cxk  r|k  sn | |   c S  | |   S )aV  
    Given a list of values and an equal-sized list of weights,
    return a randomly selected value using the weight.

    Example: sum -1 and 1 for 100 values; should be
    around 0 or at least between -50 and 50 (99.99999% of the time)

    >>> -50 < sum([common.weightedSelection([-1, 1], [1, 1]) for x in range(100)]) < 50
    True
    r   )randomr!   	enumerate)r   weightsrandomGeneratorq
boundariesr   lowhighs           rI   r#   r#     se     "MMO'0JE'
3{T!?d?%=  4 %=rb   c                "   t        t        |             }d}| D ])  }||z  }|t        |      z
  }t        |d|      s%|dz  }+ |t	        |       k(  r|S d}g }t               }	| D ]C  }
g }|D ])  }|
|z  }|j                  |       |	j                  |       + |j                  |       E g }|	D ]G  }d}|D ]  }|D ]  }t        |||      s|dz  }    |t	        |      k(  s7|j                  |       I |st        d      t        |      S )a  
    Given a list of values, find the lowest common divisor of floating point values.

    >>> common.approximateGCD([2.5, 10, 0.25])
    0.25
    >>> common.approximateGCD([2.5, 10])
    2.5
    >>> common.approximateGCD([2, 10])
    2.0
    >>> common.approximateGCD([1.5, 5, 2, 7])
    0.5
    >>> common.approximateGCD([2, 5, 10])
    1.0
    >>> common.approximateGCD([2, 5, 10, 0.25])
    0.25
    >>> common.strTrimFloat(common.approximateGCD([1/3, 2/3]))
    '0.3333'
    >>> common.strTrimFloat(common.approximateGCD([5/3, 2/3, 4]))
    '0.3333'
    >>> common.strTrimFloat(common.approximateGCD([5/3, 2/3, 5]))
    '0.3333'
    >>> common.strTrimFloat(common.approximateGCD([5/3, 2/3, 5/6, 3/6]))
    '0.1667'
    r   rB   r@   r:   )rf   rh   ri   rj   g      @rk   g      @g       @g      "@g      $@g      &@g      (@g      *@g      ,@g      .@g      0@zcannot find a common divisor)
rF   minry   r   r   setr   addrD   max)r   r   lowestcountr   x_adjustfloatingValuedivisors	divisionsuniqueDivisionsr   collrN   r   commonUniqueDivisionss                  rI   r   r     s>   2 3v;F Ev: 3x=0=#u5QJE  FH IeOA	AKKN"  	  D1a/QJE	   C	N"!((+  !788$%%rb   c                j    | d   }t        dt        |             D ]  }| |   }||dz   k7  r y|dz  } y)a  
    returns bool True or False if a list containing ints
    contains only contiguous (increasing) values

    requires the list to be sorted first

    >>> l = [3, 4, 5, 6]
    >>> common.contiguousList(l)
    True
    >>> l.append(8)
    >>> common.contiguousList(l)
    False

    Sorting matters

    >>> l.append(7)
    >>> common.contiguousList(l)
    False
    >>> common.contiguousList(sorted(l))
    True
    r   r:   FT)r   r   )inputListOrTuplecurrentMaxValr   newVals       rI   r   r   X  sN    , %Q'Mq#./0!%(]Q&&	 1
 rb   c                |   t        |       dk  r| gS g }g }| j                          d}|t        |       dz
  k  r| |   }|j                  |       | |dz      }||dz   k7  r|j                  |       g }|t        |       dz
  k(  r"|j                  |       |j                  |       |dz  }|t        |       dz
  k  r|S )a7  
    Given a list of integers, group contiguous values into sub lists

    >>> common.groupContiguousIntegers([3, 5, 6])
    [[3], [5, 6]]
    >>> common.groupContiguousIntegers([3, 4, 6])
    [[3, 4], [6]]
    >>> common.groupContiguousIntegers([3, 4, 6, 7])
    [[3, 4], [6, 7]]
    >>> common.groupContiguousIntegers([3, 4, 6, 7, 20])
    [[3, 4], [6, 7], [20]]
    >>> common.groupContiguousIntegers([3, 4, 5, 6, 7])
    [[3, 4, 5, 6, 7]]
    >>> common.groupContiguousIntegers([3])
    [[3]]
    >>> common.groupContiguousIntegers([3, 200])
    [[3], [200]]
    r:   r   r   )r   sortr   )srcpostgroupieeNexts         rI   r   r   w  s    & 3x1}uDEHHJ	A
s3x!|
FQAE
AE>KKEC1LLKK	Q s3x!|
" Krb   F)strictModernc                  | j                         }d}d}d}g }|D ]  }||vst        d|        t        t        |            D ]  }||   }||j	                  |         }		 ||j	                  ||dz               }
|
|	kD  r%|	|v r!|r|
|	dz  k\  rt        dd|  z         |	d	z  }	n|
|	kD  rt        d
|        |j                  |	        d}|D ]  }||z  }	 |S # t
        $ r Y .w xY w)a{  

    Convert a Roman numeral (upper or lower) to an int

    https://code.activestate.com/recipes/81611-roman-numerals/

    >>> common.fromRoman('ii')
    2
    >>> common.fromRoman('vii')
    7

    Works with both IIII and IV forms:

    >>> common.fromRoman('MCCCCLXXXIX')
    1489
    >>> common.fromRoman('MCDLXXXIX')
    1489

    Some people consider this an error, but you see it in medieval and ancient roman documents:

    >>> common.fromRoman('ic')
    99

    unless strictModern is True

    >>> common.fromRoman('ic', strictModern=True)
    Traceback (most recent call last):
    ValueError: input contains an invalid subtraction element (modern interpretation): ic

    But things like this are never seen, and thus cause an error:

    >>> common.fromRoman('vx')
    Traceback (most recent call last):
    ValueError: input contains an invalid subtraction element: vx
    )r:   
   d   )MDCLXVI)r     r   2   r      r:   z$value is not a valid roman numeral: r:   r   z.input contains an invalid subtraction element z(modern interpretation): r   z/input contains an invalid subtraction element: r   )upperrD   r   r   r   
IndexErrorr   )rp   r   
inputRomansubtractionValuesnumsintsplacescr   rG   	nextValuer   rM   s                rI   r   r     sE   H J$.D)DFD=CJ<PQQ  3z?#qMTZZ]#	TZZ
1q5(9:;I5 U.?%?I$;$H5cU;<= = U" EcUKM M
 	e' $( IQ	   		s   #AC	C)(C)c                $   t        | t              st        dt        |              d| cxk  rdk  st	        d       t	        d      d}d}d}t        t        |            D ])  }t        | ||   z        }|||   |z  z  }| ||   |z  z  } + |S )a  
    Convert a number from 1 to 3999 to a roman numeral

    >>> common.toRoman(2)
    'II'
    >>> common.toRoman(7)
    'VII'
    >>> common.toRoman(1999)
    'MCMXCIX'

    >>> common.toRoman('hi')
    Traceback (most recent call last):
    TypeError: expected integer, got <... 'str'>

    >>> common.toRoman(0)
    Traceback (most recent call last):
    ValueError: Argument must be between 1 and 3999
    zexpected integer, got r   i  z#Argument must be between 1 and 3999)r     r   i  r   Z   r   (   r   r   r      r:   )r   CMr   CDr   XCr   XLr   IXr   IVr    )rz   ry   rE   ru   rD   r   r   )rp   r   r   resultr   r   s         rI   r    r      s    & c30c<==s>T>>?? >??ADRDF3t9C$q'M"$q'E/!tAw  Mrb   c                    | dz  }|dv rd}n/| dz  }|dk(  rd}n"|dv rd}n|dk(  rd	}n|d
k(  rd}nt        d      |dk7  r|r|dz  }|S )z
    Return the ordinal abbreviations for integers

    >>> common.ordinalAbbreviation(3)
    'rd'
    >>> common.ordinalAbbreviation(255)
    'th'
    >>> common.ordinalAbbreviation(255, plural=True)
    'ths'
    r   )         thr   r:   st)r   r  r      r   r<   r   r   nd   rdzSomething really weirds)rD   )rG   pluralvalueHundredthsr   valueMods        rI   r   r     sx     ckO,&2:q=D..D]D]D566t|Krb   c                  (    e Zd ZdZd Zd Zd Zd Zy)Testz*
    Tests not requiring file output.
    c                     y rm   rn   selfs    rI   setUpz
Test.setUpH  s    rb   c                N    dD ]   \  }}| j                  |t        |             " y )N))r:   r   )r  III)r   r   )assertEqualr    )r  r   dsts      rI   testToRomanzTest.testToRomanK  s$    8HCS'#,/ 9rb   c                   | j                  t        d   d       | j                  t        d   d       | j                  t        d   d       | j                  t        d   d       | j                  t        d   d       | j                  t        d   d       | j                  t        d	   d       | j                  t        d
   d       | j                  t        d   d       | j                  t        d   d       y )Nunisonr:   r9   firstr%   1stoctaver<   r;   eighthr,   8th)r   r   r  s    rI   testOrdinalsToNumberszTest.testOrdinalsToNumbersO  s    *84a8*84a8*73Q7*73Q7*5115*84a8*84a8*84a8*84a8*5115rb   c                   t        d      D ]F  }d}t        d      D ]  }|t        ddgddg      z  } | j                  d|cxk  xr dk  nc        H t        d      D ]F  }d}t        d      D ]  }|t        ddgddg      z  } | j                  d|cxk  xr d	k  nc        H t        d      D ]F  }d}t        d      D ]  }|t        ddgddg      z  } | j                  d
|cxk  xr dk  nc        H t        d      D ]9  }d}t        d      D ]  }|t        ddgddg      z  } | j                  |d       ; y )Nr   r   r   r   r:   i   i'     r   )r   r#   
assertTruer   )r  r   r   r   unused_js        rI   testWeightedSelectionzTest.testWeightedSelection[  sJ   rAA4[&AwA77 ! OOD1NsN+  rAA4[&1vqz:: ! OOAKRK(  rAA4[&1v5z:: ! OOC1,,-  b	HA4[&1v1v66 ! Q" "rb   N)__name__
__module____qualname____doc__r  r"  r*  r0  rn   rb   rI   r  r  C  s    0
6!#rb   r  __main__)rG   r   returnzint | float)rM   ry   rN   ry   r6  tuple[int, int])rp   ry   r6  rF   )rp   float | Fractionr6  r8  )rp   r   r6  r   )r   znumbers.Real)rp   float | intr6  r9  )g{Gz?)r6  r8  )r  )r   rF   r   ry   r6  r   )rM   rF   r   rF   r6  ztuple[float, float, float])r   ry   r6  rF   )r   rF   r6  r7  )r   Sequence[int | float]r6  zlist[float])r   r:  r6  zlist[tuple[int | float, float]]rm   )r   	list[int]r   zlist[int | float]r6  ry   )g-C6?)r   z"Collection[int | float | Fraction]r   rF   r6  rF   )r6  bool)r   r;  r6  zlist[list[int]])rp   r   r6  ry   )rp   ry   r6  r   )F)rG   ry   r6  r   )A
__future__r   	fractionsr   	functoolsr   r   r   r   numbersr   typingr   r	   unittestmusic21r
   music21.common.typesr   r   collections.abcr   r   __all__r   r   r   limitOffsetDenominatorrK   ra   	frozensetrt   r   r   r   r   r   r   r   r   r   r"   r!   r#   r   r   r   r   r    r   r   r   r   ordinal_indexordinalNamelowerordinalNameLowerr   musicOrdinalNamemusicOrdinalNameLowerTestCaser  
_DOC_ORDERr1  mainTestrn   rb   rI   <module>rR     sd   #       *   540 a a #b #b BJ --Q" Q"p   
 
 
 
 
p6h #+"A"A?D-`<<CKL952;"|"J"4 '+./2:C&N>*\ ). DPB@  3x=)M=)K"((*%2k"*7&'Q^c-(+>}+MMN$]3;& 0 6 6 8.;*+3@/0 * 9#8 9#| !
 zGT rb   