Beispiel #1
0
    def __div__(self, *arguments):
        """
        Divides duration by ``arguments``.

        ..  container:: example

            >>> abjad.Duration(1) / abjad.NonreducedFraction(3, 3)
            NonreducedFraction(3, 3)


        >>> abjad.NonreducedFraction(3, 3) / abjad.Duration(1)
        NonreducedFraction(3, 3)

        Returns multiplier.
        """
        import abjad

        if len(arguments) == 1 and isinstance(arguments[0], type(self)):
            fraction = Fraction.__truediv__(self, *arguments)
            result = abjad.Multiplier(fraction)
        elif len(arguments) == 1 and isinstance(
            arguments[0], abjad.NonreducedFraction
        ):
            result = arguments[0].__rdiv__(self)
        else:
            result = type(self)(Fraction.__truediv__(self, *arguments))
        return result
Beispiel #2
0
    def test_3(self):
        # sf = SimpleFormat(durations=[Fraction(4) + Fraction(1, 2), Fraction(1, 2)])
        sf = SimpleFormat(quarter_durations=[
            Fraction(4, 1) +
            Fraction(5, 7), Fraction(5, 7)
        ])
        # sf = SimpleFormat(durations=[Fraction(4, 1) + Fraction(5, 7), Fraction(2, 7)])
        v = sf.to_stream_voice()
        v.add_to_score(self.score)

        self.score.finish()
        # print([chord.quarter_duration for chord in self.score.get_measure(2).get_part(1).chords])
        # print([chord.tie_types for chord in self.score.get_measure(2).get_part(1).chords])
        result_path = path + '_test_3'
        self.score.write(path=result_path)
    def test_1(self):
        self.score.add_measure(TreeMeasure(time=(5, 4)))
        sf = SimpleFormat(quarter_durations=[5])
        v = sf.to_stream_voice(1)
        v.add_to_score(self.score)

        self.score.finish()
        output = []
        for measure in self.score.get_children_by_type(TreeMeasure):
            for part in measure.get_children_by_type(TreePart):
                for beat in part.get_beats():
                    output.append([ch.quarter_duration for ch in beat.chords])

        result = [[Fraction(3, 1)], [], [], [Fraction(2, 1)], []]
        self.assertEqual(output, result)
Beispiel #4
0
    def __add__(self, *arguments):
        """
        Adds duration to ``arguments``.

        ..  container:: example

            Returns duration when ``arguments`` is a duration:

            >>> duration_1 = abjad.Duration(1, 2)
            >>> duration_2 = abjad.Duration(3, 2)
            >>> duration_1 + duration_2
            Duration(2, 1)

        ..  container:: example

            Returns nonreduced fraction when ``arguments`` is a nonreduced
            fraction:

            >>> duration = abjad.Duration(1, 2)
            >>> nonreduced_fraction = abjad.NonreducedFraction(3, 6)
            >>> duration + nonreduced_fraction
            NonreducedFraction(6, 6)

        Returns duration.
        """
        if len(arguments) == 1 and isinstance(
            arguments[0], mathtools.NonreducedFraction
        ):
            result = arguments[0].__radd__(self)
        else:
            result = type(self)(Fraction.__add__(self, *arguments))
        return result
Beispiel #5
0
    def __abs__(self, *arguments):
        """
        Gets absolute value of duration.

        Returns nonnegative duration.
        """
        return type(self)(Fraction.__abs__(self, *arguments))
Beispiel #6
0
    def test_4(self):
        cf_1 = ChordField(
            quarter_duration=10,
            midi_generator=ValueGenerator(cycle([60, 61, 64, 66])),
            long_ending_mode='self_extend',
            short_ending_mode='self_shrink'
        )
        cf_2 = ChordField(
            quarter_duration=3,
            midi_generator=ValueGenerator(cycle([72, 73, 74, 73, 72])),
            long_ending_mode='self_extend',
            short_ending_mode='self_shrink'
        )

        breathe_unit = Fraction(1, 5)
        breathe_breakpoints = (5 * breathe_unit, breathe_unit, 5 * breathe_unit)
        breathe_proportions = [2, 4, 1, 7, 2]

        breathe = Breathe(proportions=breathe_proportions,
                          quarter_duration=13,
                          breakpoints=breathe_breakpoints)
        cfg = ChordField(duration_generator=breathe.duration_generator)
        cfg.add_child(cf_1)
        cfg.add_child(cf_2)

        simple_format = SimpleFormat()
        simple_format.extend(cf_1.simple_format)
        simple_format.extend(cf_2.simple_format)

        self.score.set_time_signatures(ceil(simple_format.quarter_duration))
        simple_format.to_stream_voice().add_to_score(self.score)
        xml_path = path + 'test_4.xml'
        self.score.write(xml_path)
        self.assertCompareFiles(xml_path)
Beispiel #7
0
    def __ge__(self, argument):
        r'''Is true when duration is greater than or equal to `argument`.
        Otherwise false.

        Returns true or false.
        '''
        return Fraction.__ge__(self, argument)
Beispiel #8
0
    def __rpow__(self, *arguments):
        """
        Raises ``arguments`` to the power of duration.

        Returns new duration.
        """
        return type(self)(Fraction.__rpow__(self, *arguments))
Beispiel #9
0
    def __rsub__(self, *arguments):
        """
        Subtracts duration from ``arguments``.

        Returns new duration.
        """
        return type(self)(Fraction.__rsub__(self, *arguments))
Beispiel #10
0
    def __rtruediv__(self, *arguments):
        """
        Documentation required.

        Returns new duration.
        """
        return type(self)(Fraction.__rtruediv__(self, *arguments))
Beispiel #11
0
    def __rmul__(self, *arguments):
        """
        Multiplies ``arguments`` by duration.

        Returns new duration.
        """
        return type(self)(Fraction.__rmul__(self, *arguments))
Beispiel #12
0
    def __radd__(self, *arguments):
        """
        Adds ``arguments`` to duration.

        Returns new duration.
        """
        return type(self)(Fraction.__radd__(self, *arguments))
Beispiel #13
0
    def __rdiv__(self, *arguments):
        """
        Divides ``arguments`` by duration.

        Returns new duration.
        """
        return type(self)(Fraction.__rdiv__(self, *arguments))
Beispiel #14
0
    def __pos__(self, *arguments):
        """
        Get positive duration.

        Returns new duration.
        """
        return type(self)(Fraction.__pos__(self, *arguments))
Beispiel #15
0
    def __eq__(self, argument):
        r'''Is true when duration equals `argument`.
        Otherwise false.

        Returns true or false.
        '''
        return Fraction.__eq__(self, argument)
Beispiel #16
0
    def __mul__(self, *arguments):
        """
        Duration multiplied by ``arguments``.

        ..  container:: example

            Returns a new duration when ``arguments`` is a duration:

            >>> duration_1 = abjad.Duration(1, 2)
            >>> duration_2 = abjad.Duration(3, 2)
            >>> duration_1 * duration_2
            Duration(3, 4)

        ..  container:: example

            Returns nonreduced fraction when ``arguments`` is a nonreduced
            fraction:

            >>> duration = abjad.Duration(1, 2)
            >>> nonreduced_fraction = abjad.NonreducedFraction(3, 6)
            >>> duration * nonreduced_fraction
            NonreducedFraction(3, 12)

        Returns duration or nonreduced fraction.
        """
        if len(arguments) == 1 and isinstance(
            arguments[0], mathtools.NonreducedFraction
        ):
            result = arguments[0].__rmul__(self)
        else:
            result = type(self)(Fraction.__mul__(self, *arguments))
        return result
Beispiel #17
0
    def __neg__(self, *arguments):
        """
        Negates duration.

        Returns new duration.
        """
        return type(self)(Fraction.__neg__(self, *arguments))
Beispiel #18
0
    def __mod__(self, *arguments):
        """
        Modulus operator applied to duration.

        Returns duration.
        """
        return type(self)(Fraction.__mod__(self, *arguments))
Beispiel #19
0
    def __lt__(self, argument):
        """
        Is true when duration is less than ``argument``.

        Returns true or false.
        """
        return Fraction.__lt__(self, argument)
Beispiel #20
0
    def __gt__(self, argument):
        """
        Is true when duration is greater than ``argument``.

        Returns true or false.
        """
        return Fraction.__gt__(self, argument)
Beispiel #21
0
    def __rtruediv__(self, *arguments):
        """
        Documentation required.

        Returns new duration.
        """
        return type(self)(Fraction.__rtruediv__(self, *arguments))
Beispiel #22
0
    def __pow__(self, *arguments):
        """
        Raises duration to ``arguments`` power.

        Returns new duration.
        """
        return type(self)(Fraction.__pow__(self, *arguments))
Beispiel #23
0
    def __rsub__(self, *arguments):
        """
        Subtracts duration from ``arguments``.

        Returns new duration.
        """
        return type(self)(Fraction.__rsub__(self, *arguments))
Beispiel #24
0
    def __rmul__(self, *arguments):
        """
        Multiplies ``arguments`` by duration.

        Returns new duration.
        """
        return type(self)(Fraction.__rmul__(self, *arguments))
Beispiel #25
0
 def test_half_down(self):
     w = HalfWave(quarter_duration=10,
                  proportions=[7, 5, 3, 1],
                  duration_units=[
                      Fraction(1, 7),
                      Fraction(1, 6),
                      Fraction(1, 5),
                      Fraction(1, 4)
                  ],
                  min_midi=60,
                  max_midi=76,
                  direction='down',
                  show_last_note=True)
     w.simple_format.to_stream_voice().add_to_score(self.score)
     with self.file_path(path, 'half_down', 'xml') as xml_path:
         self.score.write(xml_path)
Beispiel #26
0
    def __eq__(self, argument):
        """
        Is true when duration equals ``argument``.

        Returns true or false.
        """
        return Fraction.__eq__(self, argument)
Beispiel #27
0
    def test_1(self):
        proportions = (1, 3, 1, 5, 1)
        breakpoints = (1, Fraction(1, 7), 1)
        quarter_durations = [8, 12]
        breathe = Breathe(proportions=proportions, breakpoints=breakpoints, quarter_duration=sum(quarter_durations),
                          quantize=1)
        breathe.midi_generator = ValueGenerator(cycle([71]))
        test_chord_field = ChordField(duration_generator=breathe.duration_generator.__deepcopy__())
        for i in range(len(quarter_durations)):
            quarter_duration = quarter_durations[i]
            midi = 60 + i
            test_chord_field.add_child(
                ChordField(midi_generator=ValueGenerator(cycle([midi])), long_ending_mode='self_extend',
                           short_ending_mode='self_shrink', quarter_duration=quarter_duration))

        test_chord_field_2 = ChordField(duration_generator=breathe.duration_generator.__deepcopy__())
        for i in range(len(quarter_durations)):
            quarter_duration = quarter_durations[i]
            midi = 72 + i
            test_chord_field_2.add_child(
                ChordField(midi_generator=ValueGenerator(cycle([midi])), long_ending_mode='cut',
                           short_ending_mode='add_rest', quarter_duration=quarter_duration))
        breathe.simple_format.to_stream_voice().add_to_score(score=self.score, part_number=1)
        test_chord_field.simple_format.to_stream_voice().add_to_score(score=self.score, part_number=2)

        simple_format = SimpleFormat()
        for child in test_chord_field_2.children:
            simple_format.extend(child.simple_format)

        simple_format.to_stream_voice().add_to_score(score=self.score, part_number=3)
        xml_path = path + '_test_1.xml'
        self.score.write(xml_path)
        self.assertCompareFiles(xml_path)
Beispiel #28
0
 def test_units(self):
     w = Wave(quarter_duration=13,
              field_proportions=[1, 1],
              show_last_note=True)
     w.rising_field.proportions = [5, 4, 3, 2, 1]
     w.rising_field.duration_units = [
         Fraction(1, 7),
         Fraction(1, 6),
         Fraction(1, 5),
         Fraction(1, 4)
     ]
     w.falling_field.proportions = [5, 4, 3, 2, 1]
     w.falling_field.duration_units = w.rising_field.duration_units
     w.simple_format.to_stream_voice().add_to_score(self.score)
     with self.file_path(path, 'units', 'xml') as xml_path:
         self.score.write(xml_path)
Beispiel #29
0
    def __rpow__(self, *arguments):
        """
        Raises ``arguments`` to the power of duration.

        Returns new duration.
        """
        return type(self)(Fraction.__rpow__(self, *arguments))
Beispiel #30
0
    def __add__(self, *arguments):
        """
        Adds duration to ``arguments``.

        ..  container:: example

            Returns duration when ``arguments`` is a duration:

            >>> duration_1 = abjad.Duration(1, 2)
            >>> duration_2 = abjad.Duration(3, 2)
            >>> duration_1 + duration_2
            Duration(2, 1)

        ..  container:: example

            Returns nonreduced fraction when ``arguments`` is a nonreduced
            fraction:

            >>> duration = abjad.Duration(1, 2)
            >>> nonreduced_fraction = abjad.NonreducedFraction(3, 6)
            >>> duration + nonreduced_fraction
            NonreducedFraction(6, 6)

        Returns duration.
        """
        if (
            len(arguments) == 1 and
            isinstance(arguments[0], mathtools.NonreducedFraction)
            ):
            result = arguments[0].__radd__(self)
        else:
            result = type(self)(Fraction.__add__(self, *arguments))
        return result
Beispiel #31
0
    def __radd__(self, *arguments):
        """
        Adds ``arguments`` to duration.

        Returns new duration.
        """
        return type(self)(Fraction.__radd__(self, *arguments))
Beispiel #32
0
    def __eq__(self, argument):
        """
        Is true when duration equals ``argument``.

        Returns true or false.
        """
        return Fraction.__eq__(self, argument)
Beispiel #33
0
    def __pos__(self, *arguments):
        """
        Get positive duration.

        Returns new duration.
        """
        return type(self)(Fraction.__pos__(self, *arguments))
Beispiel #34
0
    def __pow__(self, *arguments):
        """
        Raises duration to ``arguments`` power.

        Returns new duration.
        """
        return type(self)(Fraction.__pow__(self, *arguments))
Beispiel #35
0
    def __mul__(self, *arguments):
        """
        Duration multiplied by ``arguments``.

        ..  container:: example

            Returns a new duration when ``arguments`` is a duration:

            >>> duration_1 = abjad.Duration(1, 2)
            >>> duration_2 = abjad.Duration(3, 2)
            >>> duration_1 * duration_2
            Duration(3, 4)

        ..  container:: example

            Returns nonreduced fraction when ``arguments`` is a nonreduced
            fraction:

            >>> duration = abjad.Duration(1, 2)
            >>> nonreduced_fraction = abjad.NonreducedFraction(3, 6)
            >>> duration * nonreduced_fraction
            NonreducedFraction(3, 12)

        Returns duration or nonreduced fraction.
        """
        if (
            len(arguments) == 1 and
            isinstance(arguments[0], mathtools.NonreducedFraction)
            ):
            result = arguments[0].__rmul__(self)
        else:
            result = type(self)(Fraction.__mul__(self, *arguments))
        return result
Beispiel #36
0
    def __neg__(self, *arguments):
        """
        Negates duration.

        Returns new duration.
        """
        return type(self)(Fraction.__neg__(self, *arguments))
Beispiel #37
0
    def __lt__(self, argument):
        """
        Is true when duration is less than ``argument``.

        Returns true or false.
        """
        return Fraction.__lt__(self, argument)
Beispiel #38
0
    def __mod__(self, *arguments):
        """
        Modulus operator applied to duration.

        Returns duration.
        """
        return type(self)(Fraction.__mod__(self, *arguments))
Beispiel #39
0
    def __lt__(self, argument):
        r'''Is true when duration is less than `argument`.
        Otherwise false.

        Returns true or false.
        '''
        return Fraction.__lt__(self, argument)
Beispiel #40
0
    def __gt__(self, argument):
        """
        Is true when duration is greater than ``argument``.

        Returns true or false.
        """
        return Fraction.__gt__(self, argument)
Beispiel #41
0
    def __rdiv__(self, *arguments):
        """
        Divides ``arguments`` by duration.

        Returns new duration.
        """
        return type(self)(Fraction.__rdiv__(self, *arguments))
Beispiel #42
0
    def __abs__(self, *arguments):
        """
        Gets absolute value of duration.

        Returns nonnegative duration.
        """
        return type(self)(Fraction.__abs__(self, *arguments))
Beispiel #43
0
def _generate_simple_format():
    unit = Fraction(1, 2)
    quarter_durations = [x * unit for x in range(1, 8)]
    intervals = list(range(1, 7))
    midis = dToX(intervals, first_element=60)
    output = SimpleFormat(quarter_durations=quarter_durations, midis=midis)
    return output
Beispiel #44
0
def periodic_float_to_fraction(s: str) -> Fraction:
    """
    Convert a float with a periodic part to its fraction

    Args:
        s: the numer as string. Notate the periodic part 
           (for example 1/3=0.333...)
           as 0.(3, without repetitions. For example, 2.83333... as 2.8(3

    Returns:
        the fraction which results in the same periodic float

    Notation::

        12.3(17     2.3171717...
        123.45(67   123.45676767...

    """
    s2 = s.replace("(", "")
    x = float(s.replace("(", ""))
    numDecimals = len(s2.split(".")[1])
    lenPeriod = len(s.split("(")[1])
    factorA = 10 ** numDecimals
    factorB = 10 ** (numDecimals-lenPeriod)
    den = factorA - factorB
    num = int(x*factorA) - int(x*factorB)
    return Fraction(num, den)
Beispiel #45
0
def fraction_range(start: number_t, stop: number_t = None, step: number_t = None
                   ) -> Iterator[Fraction]:
    """ Like range, but yielding Fractions """
    if stop is None:
        stopF = asFraction(start)
        startF = Fraction(0)
    else:
        startF = asFraction(start)
        stopF = asFraction(stop)

    if step is None:
        step = Fraction(1)
    else:
        step = asFraction(step)
    while startF < stopF:
        yield startF
        startF += step
 def test_5(self):
     self.score.set_time_signatures(
         [Fraction(3, 2)])
     sf = SimpleFormat(quarter_durations=[0.666, 0.333, 0.5])
     xml_path = path + '_test_5.xml'
     sf.to_stream_voice().add_to_score(self.score)
     self.score.get_score_parts()[0].max_division = 1
     self.score.write(xml_path)
Beispiel #47
0
 def __new__(class_, *arguments):
     """
     Makes new duration.
     """
     if len(arguments) == 1:
         argument = arguments[0]
         if type(argument) is class_:
             return argument
         if isinstance(argument, mathtools.NonreducedFraction):
             return Fraction.__new__(class_, *argument.pair)
         try:
             return Fraction.__new__(class_, *argument)
         except (AttributeError, TypeError):
             pass
         try:
             return Fraction.__new__(class_, argument)
         except (AttributeError, TypeError):
             pass
         if (
             isinstance(argument, tuple)
             and len(argument) == 2
             and mathtools.is_integer_equivalent(argument[0])
             and mathtools.is_integer_equivalent(argument[1])
             and not argument[1] == 0
         ):
             return Fraction.__new__(
                 class_, int(argument[0]), int(argument[1])
             )
         try:
             return Fraction.__new__(class_, argument.duration)
         except AttributeError:
             pass
         if isinstance(argument, str) and "/" not in argument:
             result = Duration._initialize_from_lilypond_duration_string(
                 argument
             )
             return Fraction.__new__(class_, result)
         if (
             isinstance(argument, tuple)
             and len(argument) == 1
             and mathtools.is_integer_equivalent(argument[0])
         ):
             return Fraction.__new__(class_, int(argument[0]))
     else:
         try:
             return Fraction.__new__(class_, *arguments)
         except TypeError:
             pass
         if mathtools.all_are_integer_equivalent_numbers(arguments):
             return Fraction.__new__(class_, *[int(x) for x in arguments])
     raise ValueError(f"can not construct duration: {arguments!r}.")
Beispiel #48
0
    def _calculate_quarter_durations(self):
        if self.proportions:
            quarter_durations = [
                (Fraction(Fraction(p), Fraction(sum(self.proportions)))) * Fraction(self.quarter_duration) for p in
                self.proportions]

            if self.duration_units:
                quarter_durations = find_best_quantized_values(values=quarter_durations, units=self.duration_units,
                                                               check_sum=True)
            if self.direction == 'down':
                quarter_durations = quarter_durations[::-1]
            self._quarter_durations = quarter_durations
        if self.quarter_durations:
            self._duration_generator = ValueGenerator(iter(self.quarter_durations), duration=self.quarter_duration,
                                                      value_mode='duration')
        else:
            self._duration_generator = None
Beispiel #49
0
    def __divmod__(self, *arguments):
        """
        Equals the pair (duration // ``arguments``, duration % ``arguments``).

        Returns pair.
        """
        truncated, residue = Fraction.__divmod__(self, *arguments)
        truncated = type(self)(truncated)
        residue = type(self)(residue)
        return truncated, residue
Beispiel #50
0
    def __sub__(self, *arguments):
        """
        Subtracts ``arguments`` from duration.

        ..  container:: example

            >>> abjad.Duration(1, 2) - abjad.NonreducedFraction(2, 8)
            NonreducedFraction(2, 8)

            >>> abjad.NonreducedFraction(4, 8) - abjad.Duration(1, 4)
            NonreducedFraction(2, 8)

        Returns new duration.
        """
        if len(arguments) == 1 and isinstance(
            arguments[0], mathtools.NonreducedFraction
        ):
            return arguments[0].__rsub__(self)
        else:
            return type(self)(Fraction.__sub__(self, *arguments))
Beispiel #51
0
 def __rmod__(self, *arguments):
     """
     Documentation required.
     """
     return type(self)(Fraction.__rmod__(self, *arguments))