Esempio n. 1
0
def test_mathtools_least_common_multiple_03():
    r'''Works with more than two positive integers.
    '''

    assert mathtools.least_common_multiple(2, 3, 4) == 12
    assert mathtools.least_common_multiple(2, 3, 4, 6, 12) == 12
    assert mathtools.least_common_multiple(2, 3, 4, 5, 6, 12) == 60
    def __add__(self, expr):
        r'''Adds `expr` to nonreduced fraction.

        ::

            >>> mathtools.NonreducedFraction(3, 3) + 1
            NonreducedFraction(6, 3)

        Returns nonreduced fraction.
        '''
        from abjad.tools import mathtools
        if isinstance(expr, int):
            numerator = self.numerator + expr * self.denominator
            return NonreducedFraction(numerator, self.denominator)
        elif hasattr(expr, 'denominator'):
            if self.denominator == expr.denominator:
                numerator = self.numerator + expr.numerator
                return NonreducedFraction(numerator, self.denominator)
            else:
                denominator = mathtools.least_common_multiple(
                    self.denominator, expr.denominator)
                self_multiplier = denominator // self.denominator
                expr_multiplier = denominator // expr.denominator
                self_numerator = self_multiplier * self.numerator
                expr_numerator = expr_multiplier * expr.numerator
                return NonreducedFraction(
                    self_numerator + expr_numerator, denominator)
        else:
            raise ValueError(expr)
def make_unordered_cells_sequence():

    result = []

    harmonic_walk = sequencetools.flatten_sequence(manifolds.etc.pitch.harmonic_walk)
    pitch_fields = manifolds.etc.pitch.pitch_fields
    timeslot_pitch_to_field_cell = \
        manifolds.etc.pitch._helpers.timeslot_pitch_to_field_cell

    len_walk = len(harmonic_walk)
    len_fields = len(pitch_fields)

    lcm = mathtools.least_common_multiple(len_walk, len_fields)

    assert lcm == 120

    harmonic_walk = sequencetools.repeat_list_to_length(harmonic_walk, lcm)

    for timeslot, pitch in enumerate(harmonic_walk):
        field_cell = timeslot_pitch_to_field_cell(timeslot, Pitch(pitch))
        result.append(field_cell)

    assert len(result) == 120
    assert len(sequencetools.flatten_sequence(result)) == 504

    return result
Esempio n. 4
0
 def _fraction_with_denominator(self, fraction, denominator):
     from abjad.tools import mathtools
     denominators = [denominator, fraction.denominator]
     denominator = mathtools.least_common_multiple(*denominators)
     result = self._from_pair(fraction)
     result = result.with_denominator(denominator)
     return result
Esempio n. 5
0
    def durations_to_nonreduced_fractions(durations):
        r'''Changes `durations` to nonreduced fractions sharing
        least common denominator.

        ..  container:: example

            **Example.** Changes durations to nonreduced fractions:

            ::

                >>> durations = [Duration(2, 4), 3, (5, 16)]
                >>> result = Duration.durations_to_nonreduced_fractions(durations)
                >>> for x in result:
                ...     x
                ...
                NonreducedFraction(8, 16)
                NonreducedFraction(48, 16)
                NonreducedFraction(5, 16)

        Returns new object of `durations` type.
        '''
        durations = [Duration(x) for x in durations]
        denominators = [duration.denominator for duration in durations]
        lcd = mathtools.least_common_multiple(*denominators)
        nonreduced_fractions = [
            mathtools.NonreducedFraction(x).with_denominator(lcd)
            for x in durations
        ]
        result = type(durations)(nonreduced_fractions)
        return result
Esempio n. 6
0
    def __add__(self, argument):
        r'''Adds `argument` to nonreduced fraction.

        ..  container:: example

            >>> abjad.NonreducedFraction(3, 3) + 1
            NonreducedFraction(6, 3)

            >>> 1 + abjad.NonreducedFraction(3, 3)
            NonreducedFraction(6, 3)

        Returns nonreduced fraction.
        '''
        from abjad.tools import mathtools
        if isinstance(argument, int):
            numerator = self.numerator + argument * self.denominator
            pair = (numerator, self.denominator)
            return self._from_pair(pair)
        if getattr(argument, 'denominator', 'foo') == 'foo':
            raise ValueError(argument)
        if self.denominator == argument.denominator:
            numerator = self.numerator + argument.numerator
            pair = (numerator, self.denominator)
            return self._from_pair(pair)
        else:
            denominators = [self.denominator, argument.denominator]
            denominator = mathtools.least_common_multiple(*denominators)
            self_multiplier = denominator // self.denominator
            argument_multiplier = denominator // argument.denominator
            self_numerator = self_multiplier * self.numerator
            argument_numerator = argument_multiplier * argument.numerator
            pair = (self_numerator + argument_numerator, denominator)
            return self._from_pair(pair)
Esempio n. 7
0
 def _fraction_with_denominator(self, fraction, denominator):
     from abjad.tools import mathtools
     denominators = [denominator, fraction.denominator]
     denominator = mathtools.least_common_multiple(*denominators)
     result = self._from_pair(fraction)
     result = result.with_denominator(denominator)
     return result
Esempio n. 8
0
    def durations_to_nonreduced_fractions(durations):
        r'''Change `durations` to nonreduced fractions sharing
        least common denominator.

        ::

            >>> durations = [Duration(2, 4), 3, (5, 16)]
            >>> result = Duration.durations_to_nonreduced_fractions(durations)
            >>> for x in result:
            ...     x
            ...
            NonreducedFraction(8, 16)
            NonreducedFraction(48, 16)
            NonreducedFraction(5, 16)

        Returns new object of `durations` type.
        '''
        durations = [Duration(x) for x in durations]
        denominators = [duration.denominator for duration in durations]
        lcd = mathtools.least_common_multiple(*denominators)
        nonreduced_fractions = [
            mathtools.NonreducedFraction(x).with_denominator(lcd)
            for x in durations
            ]
        result = type(durations)(nonreduced_fractions)
        return result
Esempio n. 9
0
    def __add__(self, expr):
        r'''Adds `expr` to nonreduced fraction.

        ::

            >>> mathtools.NonreducedFraction(3, 3) + 1
            NonreducedFraction(6, 3)

        Returns nonreduced fraction.
        '''
        from abjad.tools import mathtools
        if isinstance(expr, int):
            numerator = self.numerator + expr * self.denominator
            pair = (numerator, self.denominator)
            return self._from_pair(pair)
        elif hasattr(expr, 'denominator'):
            if self.denominator == expr.denominator:
                numerator = self.numerator + expr.numerator
                pair = (numerator, self.denominator)
                return self._from_pair(pair)
            else:
                denominators = [self.denominator, expr.denominator]
                denominator = mathtools.least_common_multiple(*denominators)
                self_multiplier = denominator // self.denominator
                expr_multiplier = denominator // expr.denominator
                self_numerator = self_multiplier * self.numerator
                expr_numerator = expr_multiplier * expr.numerator
                pair = (self_numerator + expr_numerator, denominator)
                return self._from_pair(pair)
        else:
            raise ValueError(expr)
Esempio n. 10
0
def test_mathtools_least_common_multiple_01():
    r'''Works with two positive integers.
    '''

    assert mathtools.least_common_multiple(4, 4) == 4
    assert mathtools.least_common_multiple(4, 5) == 20
    assert mathtools.least_common_multiple(4, 6) == 12
    assert mathtools.least_common_multiple(4, 7) == 28
    assert mathtools.least_common_multiple(4, 8) == 8
    assert mathtools.least_common_multiple(4, 9) == 36
    assert mathtools.least_common_multiple(4, 10) == 20
    assert mathtools.least_common_multiple(4, 11) == 44
Esempio n. 11
0
 def period(self):
     r'''Residue class expression period.
     '''
     rc_periods = []
     for rc in self.rcs:
         rc_periods.append(rc.modulo)
     if rc_periods:
         period = mathtools.least_common_multiple(*rc_periods)
     else:
         period = 1
     return period
Esempio n. 12
0
    def __add__(self, expr):
        r'''Adds `expr` to nonreduced fraction.

        ::

            >>> mathtools.NonreducedFraction(3, 3) + 1
            NonreducedFraction(6, 3)

        Adding two nonreduced fractions is fairly fast:

        ::

            >>> a = mathtools.NonreducedFraction(3, 6)
            >>> b = mathtools.NonreducedFraction(3, 12)
            >>> systemtools.IOManager.count_function_calls('a + b', globals())
            67

        Adding an integer is even faster:

        ::

            >>> systemtools.IOManager.count_function_calls('a + 10', globals())
            35

        Returns nonreduced fraction.
        '''
        from abjad.tools import mathtools
        if isinstance(expr, int):
            numerator = self.numerator + expr * self.denominator
            return NonreducedFraction(numerator, self.denominator)
        elif hasattr(expr, 'denominator'):
            if self.denominator == expr.denominator:
                numerator = self.numerator + expr.numerator
                return NonreducedFraction(numerator, self.denominator)
            else:
                denominator = mathtools.least_common_multiple(
                    self.denominator, expr.denominator)
                self_multiplier = denominator / self.denominator
                expr_multiplier = denominator / expr.denominator
                self_numerator = self_multiplier * self.numerator
                expr_numerator = expr_multiplier * expr.numerator
                return NonreducedFraction(
                    self_numerator + expr_numerator, denominator)
        else:
            raise ValueError(expr)
Esempio n. 13
0
 def _fraction_with_denominator(self, fraction, denominator):
     from abjad.tools import mathtools
     denominator = mathtools.least_common_multiple(denominator,
                                                   fraction.denominator)
     return NonreducedFraction(fraction).with_denominator(denominator)
Esempio n. 14
0
 def _fraction_with_denominator(self, fraction, denominator):
     from abjad.tools import durationtools
     from abjad.tools import mathtools
     denominator = mathtools.least_common_multiple(
         denominator, fraction.denominator)
     return NonreducedFraction(fraction).with_denominator(denominator)
Esempio n. 15
0
def make_tied_leaf(
    kind,
    duration,
    decrease_durations_monotonically=True,
    forbidden_written_duration=None,
    pitches=None,
    tie_parts=True,
    ):
    r'''Make tied `kind` with `duration`.

    ..  container:: example

        **Example 1.** Make note:

        ::

            >>> leaves = scoretools.make_tied_leaf(
            ...     Note,
            ...     Duration(1, 2),
            ...     pitches='C#5',
            ...     )
            >>> staff = Staff(leaves)
            >>> time_signature = TimeSignature((2, 4))
            >>> attach(time_signature, staff)
            >>> show(staff) # doctest: +SKIP

        ..  doctest::

            >>> print(format(staff))
            \new Staff {
                \time 2/4
                cs''2
            }

    ..  container:: example

        **Example 2.** Make note and forbid half notes:

        ::

            >>> leaves = scoretools.make_tied_leaf(
            ...     Note,
            ...     Duration(1, 2),
            ...     pitches='C#5',
            ...     forbidden_written_duration=Duration(1, 2),
            ...     )
            >>> staff = Staff(leaves)
            >>> time_signature = TimeSignature((2, 4))
            >>> attach(time_signature, staff)
            >>> show(staff) # doctest: +SKIP

        ..  doctest::

            >>> print(format(staff))
            \new Staff {
                \time 2/4
                cs''4 ~
                cs''4
            }

    ..  container:: example

        **Example 3.** Make tied note with half notes forbidden and
        durations decreasing monotonically:

        ::

            >>> leaves = scoretools.make_tied_leaf(
            ...     Note,
            ...     Duration(9, 8),
            ...     pitches='C#5',
            ...     forbidden_written_duration=Duration(1, 2),
            ...     decrease_durations_monotonically=True,
            ...     )
            >>> staff = Staff(leaves)
            >>> time_signature = TimeSignature((9, 8))
            >>> attach(time_signature, staff)
            >>> show(staff) # doctest: +SKIP

        ..  doctest::

            >>> print(format(staff))
            \new Staff {
                \time 9/8
                cs''4 ~
                cs''4 ~
                cs''4 ~
                cs''4 ~
                cs''8
            }

    ..  container:: example

        **Example 4.** Make tied note with half notes forbidden and
        durations increasing monotonically:

        ::

            >>> leaves = scoretools.make_tied_leaf(
            ...     Note,
            ...     Duration(9, 8),
            ...     pitches='C#5',
            ...     forbidden_written_duration=Duration(1, 2),
            ...     decrease_durations_monotonically=False,
            ...     )
            >>> staff = Staff(leaves)
            >>> time_signature = TimeSignature((9, 8))
            >>> attach(time_signature, staff)
            >>> show(staff) # doctest: +SKIP

        ..  doctest::

            >>> print(format(staff))
            \new Staff {
                \time 9/8
                cs''8 ~
                cs''4 ~
                cs''4 ~
                cs''4 ~
                cs''4
            }

    Returns selection of unincorporated leaves.
    '''
    from abjad.tools import scoretools
    from abjad.tools import spannertools

    # check input
    duration = durationtools.Duration(duration)
    if forbidden_written_duration is not None:
        forbidden_written_duration = \
            durationtools.Duration(forbidden_written_duration)
        assert forbidden_written_duration.is_assignable
        assert forbidden_written_duration.numerator == 1

    # find preferred numerator of written durations if necessary
    if forbidden_written_duration is not None and \
        forbidden_written_duration <= duration:
        denominators = [
            2 * forbidden_written_duration.denominator,
            duration.denominator,
            ]
        denominator = mathtools.least_common_multiple(*denominators)
        forbidden_written_duration = \
            mathtools.NonreducedFraction(forbidden_written_duration)
        forbidden_written_duration = \
            forbidden_written_duration.with_denominator(denominator)
        duration = mathtools.NonreducedFraction(duration)
        duration = duration.with_denominator(denominator)
        forbidden_numerator = forbidden_written_duration.numerator
        assert forbidden_numerator % 2 == 0
        preferred_numerator = forbidden_numerator / 2

    # make written duration numerators
    numerators = []
    parts = mathtools.partition_integer_into_canonic_parts(duration.numerator)
    if forbidden_written_duration is not None and \
        forbidden_written_duration <= duration:
        for part in parts:
            if forbidden_numerator <= part:
                better_parts = \
                    mathtools.partition_integer_into_parts_less_than_double(
                    part, preferred_numerator)
                numerators.extend(better_parts)
            else:
                numerators.append(part)
    else:
        numerators = parts

    # reverse numerators if necessary
    if not decrease_durations_monotonically:
        numerators = list(reversed(numerators))

    # make one leaf per written duration
    result = []
    for numerator in numerators:
        written_duration = \
            durationtools.Duration(numerator, duration.denominator)
        if not pitches is None:
            args = (pitches, written_duration)
        else:
            args = (written_duration, )
        result.append(kind(*args))

    # apply tie spanner if required
    if tie_parts and 1 < len(result):
        if not issubclass(kind, (scoretools.Rest, scoretools.Skip)):
            tie = spannertools.Tie()
            attach(tie, result)

    # return result
    result = selectiontools.Selection(result)
    return result
Esempio n. 16
0
def test_mathtools_least_common_multiple_02():
    r'''Works with one positive integer.
    '''

    assert mathtools.least_common_multiple(1) == 1
    assert mathtools.least_common_multiple(2) == 2
Esempio n. 17
0
    def period(self):
        r'''Gets period of compound pattern.

        ..  container:: example

            **Example 1.** Gets period of pattern that selects every fourth and
            fifth element:

            ::

                >>> pattern_1 = patterntools.Pattern([0], period=4)
                >>> pattern_2 = patterntools.Pattern([0], period=5)
                >>> pattern = pattern_1 | pattern_2

            ::

                >>> print(format(pattern))
                patterntools.CompoundPattern(
                    (
                        patterntools.Pattern(
                            indices=(0,),
                            period=4,
                            ),
                        patterntools.Pattern(
                            indices=(0,),
                            period=5,
                            ),
                        ),
                    operator='or',
                    )

            ::

                >>> pattern.period
                20

        ..  container:: example

            **Example 2.** Returns none when pattern contains acyclic parts:

            ::

                >>> pattern_1 = patterntools.Pattern([0], period=4)
                >>> pattern_2 = patterntools.Pattern([0])
                >>> pattern = pattern_1 | pattern_2

            ::

                >>> print(format(pattern))
                patterntools.CompoundPattern(
                    (
                        patterntools.Pattern(
                            indices=(0,),
                            period=4,
                            ),
                        patterntools.Pattern(
                            indices=(0,),
                            ),
                        ),
                    operator='or',
                    )

            ::

                >>> pattern.period is None
                True

        Returns positive integer.
        '''
        periods = [_.period for _ in self]
        if None not in periods:
            return mathtools.least_common_multiple(*periods)
Esempio n. 18
0
def make_tied_leaf(
    kind,
    duration,
    decrease_durations_monotonically=True,
    forbidden_written_duration=None,
    pitches=None,
    tie_parts=True,
):
    r'''Make tied `kind` with `duration`.

    ..  container:: example

        **Example 1.** Make note:

        ::

            >>> leaves = scoretools.make_tied_leaf(
            ...     Note,
            ...     Duration(1, 2),
            ...     pitches='C#5',
            ...     )
            >>> staff = Staff(leaves)
            >>> time_signature = TimeSignature((2, 4))
            >>> attach(time_signature, staff)
            >>> show(staff) # doctest: +SKIP

        ..  doctest::

            >>> print(format(staff))
            \new Staff {
                \time 2/4
                cs''2
            }

    ..  container:: example

        **Example 2.** Make note and forbid half notes:

        ::

            >>> leaves = scoretools.make_tied_leaf(
            ...     Note,
            ...     Duration(1, 2),
            ...     pitches='C#5',
            ...     forbidden_written_duration=Duration(1, 2),
            ...     )
            >>> staff = Staff(leaves)
            >>> time_signature = TimeSignature((2, 4))
            >>> attach(time_signature, staff)
            >>> show(staff) # doctest: +SKIP

        ..  doctest::

            >>> print(format(staff))
            \new Staff {
                \time 2/4
                cs''4 ~
                cs''4
            }

    ..  container:: example

        **Example 3.** Make tied note with half notes forbidden and
        durations decreasing monotonically:

        ::

            >>> leaves = scoretools.make_tied_leaf(
            ...     Note,
            ...     Duration(9, 8),
            ...     pitches='C#5',
            ...     forbidden_written_duration=Duration(1, 2),
            ...     decrease_durations_monotonically=True,
            ...     )
            >>> staff = Staff(leaves)
            >>> time_signature = TimeSignature((9, 8))
            >>> attach(time_signature, staff)
            >>> show(staff) # doctest: +SKIP

        ..  doctest::

            >>> print(format(staff))
            \new Staff {
                \time 9/8
                cs''4 ~
                cs''4 ~
                cs''4 ~
                cs''4 ~
                cs''8
            }

    ..  container:: example

        **Example 4.** Make tied note with half notes forbidden and
        durations increasing monotonically:

        ::

            >>> leaves = scoretools.make_tied_leaf(
            ...     Note,
            ...     Duration(9, 8),
            ...     pitches='C#5',
            ...     forbidden_written_duration=Duration(1, 2),
            ...     decrease_durations_monotonically=False,
            ...     )
            >>> staff = Staff(leaves)
            >>> time_signature = TimeSignature((9, 8))
            >>> attach(time_signature, staff)
            >>> show(staff) # doctest: +SKIP

        ..  doctest::

            >>> print(format(staff))
            \new Staff {
                \time 9/8
                cs''8 ~
                cs''4 ~
                cs''4 ~
                cs''4 ~
                cs''4
            }

    Returns selection of unincorporated leaves.
    '''
    from abjad.tools import scoretools
    from abjad.tools import spannertools

    # check input
    duration = durationtools.Duration(duration)
    if forbidden_written_duration is not None:
        forbidden_written_duration = \
            durationtools.Duration(forbidden_written_duration)
        assert forbidden_written_duration.is_assignable
        assert forbidden_written_duration.numerator == 1

    # find preferred numerator of written durations if necessary
    if forbidden_written_duration is not None and \
        forbidden_written_duration <= duration:
        denominators = [
            2 * forbidden_written_duration.denominator,
            duration.denominator,
        ]
        denominator = mathtools.least_common_multiple(*denominators)
        forbidden_written_duration = \
            mathtools.NonreducedFraction(forbidden_written_duration)
        forbidden_written_duration = \
            forbidden_written_duration.with_denominator(denominator)
        duration = mathtools.NonreducedFraction(duration)
        duration = duration.with_denominator(denominator)
        forbidden_numerator = forbidden_written_duration.numerator
        assert forbidden_numerator % 2 == 0
        preferred_numerator = forbidden_numerator / 2

    # make written duration numerators
    numerators = []
    parts = mathtools.partition_integer_into_canonic_parts(duration.numerator)
    if forbidden_written_duration is not None and \
        forbidden_written_duration <= duration:
        for part in parts:
            if forbidden_numerator <= part:
                better_parts = \
                    mathtools.partition_integer_into_parts_less_than_double(
                    part, preferred_numerator)
                numerators.extend(better_parts)
            else:
                numerators.append(part)
    else:
        numerators = parts

    # reverse numerators if necessary
    if not decrease_durations_monotonically:
        numerators = list(reversed(numerators))

    # make one leaf per written duration
    result = []
    for numerator in numerators:
        written_duration = \
            durationtools.Duration(numerator, duration.denominator)
        if not pitches is None:
            args = (pitches, written_duration)
        else:
            args = (written_duration, )
        result.append(kind(*args))

    # apply tie spanner if required
    if tie_parts and 1 < len(result):
        if not issubclass(kind, (scoretools.Rest, scoretools.Skip)):
            tie = spannertools.Tie()
            attach(tie, result)

    # return result
    result = selectiontools.Selection(result)
    return result
Esempio n. 19
0
    def period(self):
        r'''Gets period of compound pattern.

        ..  container:: example

            **Example 1.** Gets period of pattern that selects every fourth and
            fifth element:

            ::

                >>> pattern_1 = patterntools.Pattern([0], period=4)
                >>> pattern_2 = patterntools.Pattern([0], period=5)
                >>> pattern = pattern_1 | pattern_2

            ::

                >>> print(format(pattern))
                patterntools.CompoundPattern(
                    (
                        patterntools.Pattern(
                            indices=(0,),
                            period=4,
                            ),
                        patterntools.Pattern(
                            indices=(0,),
                            period=5,
                            ),
                        ),
                    operator='or',
                    )

            ::

                >>> pattern.period
                20

        ..  container:: example

            **Example 2.** Returns none when pattern contains acyclic parts:

            ::

                >>> pattern_1 = patterntools.Pattern([0], period=4)
                >>> pattern_2 = patterntools.Pattern([0])
                >>> pattern = pattern_1 | pattern_2

            ::

                >>> print(format(pattern))
                patterntools.CompoundPattern(
                    (
                        patterntools.Pattern(
                            indices=(0,),
                            period=4,
                            ),
                        patterntools.Pattern(
                            indices=(0,),
                            ),
                        ),
                    operator='or',
                    )

            ::

                >>> pattern.period is None
                True

        Returns positive integer.
        '''
        periods = [_.period for _ in self]
        if None not in periods:
            return mathtools.least_common_multiple(*periods)