def _replace(self, old_leaf, new_leaf):
        after_grace = abjad.inspect(old_leaf).get_after_grace_container()
        if after_grace is not None:
            old_after_grace = after_grace
            grace_notes = list(iterate(old_after_grace).by_leaf())
            detach(scoretools.GraceContainer, old_leaf)

        indicator_expressions = abjad.inspect(old_leaf).get_indicators(unwrap=False)
        #for indicator_expression in indicator_expressions:
        #    detach(indicator, old_leaf)

        timespan = old_leaf._timespan
        start_offset = old_leaf._start_offset
        stop_offset = old_leaf._stop_offset
        logical_measure_number = old_leaf._logical_measure_number
        mutate(old_leaf).replace(new_leaf)
        new_leaf._timespan = timespan
        new_leaf._start_offset = start_offset
        new_leaf._stop_offset = stop_offset
        new_leaf._logical_measure_number = logical_measure_number

        if after_grace is not None:
            new_after_grace = scoretools.AfterGraceContainer(grace_notes)
            attach(new_after_grace, new_leaf)

        for indicator_expression in indicator_expressions:
            attach(indicator_expression, new_leaf)
Пример #2
0
def test_Rest___init___12():
    """
    Initialize multiple rests from spanned notes.
    """

    voice = abjad.Voice("c'8 ( d'8 e'8 f'8 )")
    for note in voice:
        rest = abjad.Rest(note)
        abjad.mutate(note).replace(rest)

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
            r8
            (
            r8
            r8
            r8
            )
        }
        """
    )

    assert abjad.inspect(voice).wellformed()
Пример #3
0
    def _replace(self, old_leaf, new_leaf):
        grace_containers = inspect_(old_leaf).get_grace_containers('after')
        if grace_containers:
            old_grace_container = grace_containers[0]
            grace_notes = list(iterate(old_grace_container).by_leaf())
            detach(scoretools.GraceContainer, old_leaf)

        indicator_expressions = inspect_(old_leaf).get_indicators(unwrap=False)
        #for indicator_expression in indicator_expressions:
        #    detach(indicator, old_leaf)

        timespan = old_leaf._timespan
        start_offset = old_leaf._start_offset
        stop_offset = old_leaf._stop_offset
        logical_measure_number = old_leaf._logical_measure_number
        mutate(old_leaf).replace(new_leaf)
        new_leaf._timespan = timespan
        new_leaf._start_offset = start_offset
        new_leaf._stop_offset = stop_offset
        new_leaf._logical_measure_number = logical_measure_number

        if grace_containers:
            new_grace_container = scoretools.GraceContainer(
                grace_notes,
                kind='after',
                )
            attach(new_grace_container, new_leaf)

        for indicator_expression in indicator_expressions:
            attach(indicator_expression, new_leaf)
Пример #4
0
def test_Mutation_swap_02():
    """
    Moves parentage, children from container to empty voice.
    """

    voice = abjad.Voice("{ c'8 d'8 } { e'8 f'8 } { g'8 a'8 }")
    leaves = abjad.select(voice).leaves()
    voice.name = "foo"
    abjad.beam(leaves)

    assert format(voice) == abjad.String.normalize(
        r"""
        \context Voice = "foo"
        {
            {
                c'8
                [
                d'8
            }
            {
                e'8
                f'8
            }
            {
                g'8
                a'8
                ]
            }
        }
        """
    )

    new_voice = abjad.Voice()
    new_voice.name = "foo"
    abjad.mutate(voice[1:2]).swap(new_voice)

    assert format(voice) == abjad.String.normalize(
        r"""
        \context Voice = "foo"
        {
            {
                c'8
                [
                d'8
            }
            \context Voice = "foo"
            {
                e'8
                f'8
            }
            {
                g'8
                a'8
                ]
            }
        }
        """
    )

    assert abjad.inspect(voice).wellformed()
Пример #5
0
    def music(self, **kwargs):
        my_music = self.container_type()
        if self.line:

            # TO DO... this won't let holds overlap the silence... consider re-implementing to allow that
            self.add_silence(my_music, self.line.silence_counts, self.line.silence_ly)

            # TO DO... update to support multiple indices
            pitch = self.line.pitch_segments.get_pitch_numbers()[self.indices[0]]

            my_rhythms = self.get_rhythm_selection()
            # TO DO... consider using transpose instead of setting written pitch for each note?
            logical_ties = abjad.select(my_rhythms).by_logical_tie(pitched=True)
            for i, logical_tie in enumerate(logical_ties):
                for note in logical_tie:
                    note.written_pitch = pitch
            my_music.extend(my_rhythms)
            # TO DO... this would make more sense on the Pitches class... but won't work with PitchSegment, so keeping here for now
            if self.pitch_respell == "sharps":
                abjad.mutate(my_music).pitch_respell_with_sharps()
            elif self.pitch_respell == "flats":
                abjad.mutate(my_music).pitch_respell_with_flats()

            # TO DO... ditto as above
            self.add_silence(my_music, self.line.silence_post_counts, self.line.silence_post_ly)

        else:
            print("WARNING: tried to create hold with no line referenced")
        return my_music
Пример #6
0
def test_Mutation_swap_07():
    """
    Moves parentage, children from one container to another.
    """

    measure = abjad.Container("c'8 d'8 e'8 f'8")

    assert format(measure) == abjad.String.normalize(
        r"""
        {
            c'8
            d'8
            e'8
            f'8
        }
        """
    )

    new_measure = abjad.Container()
    abjad.mutate(measure).swap(new_measure)

    assert format(new_measure) == abjad.String.normalize(
        r"""
        {
            c'8
            d'8
            e'8
            f'8
        }
        """
    )

    assert abjad.inspect(new_measure).wellformed()
Пример #7
0
def test_Mutation_swap_06():
    """
    Trying to move parentage, children from components that are not
    parent-contiguous raises exception.
    """

    voice = abjad.Voice("{ c'8 d'8 } { e'8 f'8 } { g'8 a'8 }")
    leaves = abjad.select(voice).leaves()
    abjad.beam(leaves)

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
            {
                c'8
                [
                d'8
            }
            {
                e'8
                f'8
            }
            {
                g'8
                a'8
                ]
            }
        }
        """
    )

    tuplet = abjad.Tuplet((2, 3), [])
    with pytest.raises(Exception):
        abjad.mutate([voice[0], voice[2]]).swap(tuplet)
Пример #8
0
    def __call__(self, container, imbrication_token):
        r'''Calls imbrication specifier on `container`.

        Returns new container.
        '''
        container = copy.deepcopy(container)
        imbrication_token = abjad.sequence(imbrication_token)
        imbrication_token = imbrication_token.flatten()
        cursor = baca.tools.Cursor(
            imbrication_token,
            singletons=True,
            suppress_exception=True,
            )
        pitch_number = cursor.next()
        logical_ties = abjad.iterate(container).by_logical_tie(pitched=True)
        for logical_tie in logical_ties:
            if logical_tie.head.written_pitch.pitch_number == pitch_number:
                pitch_number = cursor.next()
                if self.truncate_ties:
                    for note in logical_tie[1:]:
                        duration = note.written_duration
                        skip = abjad.Skip(duration)
                        abjad.mutate(note).replace([skip])
            else:
                for note in logical_tie:
                    duration = note.written_duration
                    skip = abjad.Skip(duration)
                    abjad.mutate(note).replace([skip])
        self._apply_specifiers(container)
        return container
Пример #9
0
def test_Mutation_scale_03():
    """
    Scales leaves by tuplet-generating multiplier.
    """

    voice = abjad.Voice("c'8 d'8 e'8 f'8")
    abjad.mutate(voice).scale(abjad.Multiplier(4, 3))

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
            \tweak edge-height #'(0.7 . 0)
            \times 2/3 {
                c'4
            }
            \tweak edge-height #'(0.7 . 0)
            \times 2/3 {
                d'4
            }
            \tweak edge-height #'(0.7 . 0)
            \times 2/3 {
                e'4
            }
            \tweak edge-height #'(0.7 . 0)
            \times 2/3 {
                f'4
            }
        }
        """
    )

    assert abjad.inspect(voice).wellformed()
Пример #10
0
def test_Mutation_scale_02():
    """
    Scales leaves by tie-generating multiplier.
    """

    voice = abjad.Voice("c'8 d'8 e'8 f'8")
    abjad.mutate(voice).scale(abjad.Multiplier(5, 4))

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
            c'8
            ~
            c'32
            d'8
            ~
            d'32
            e'8
            ~
            e'32
            f'8
            ~
            f'32
        }
        """
    )

    assert abjad.inspect(voice).wellformed()
Пример #11
0
def add_string_music_to_score(score):
    """
    Adds string music to score.
    """
    # generate some pitch and rhythm information
    pitch_contour_reservoir = create_pitch_contour_reservoir()
    shadowed_contour_reservoir = shadow_pitch_contour_reservoir(
        pitch_contour_reservoir
    )
    durated_reservoir = durate_pitch_contour_reservoir(
        shadowed_contour_reservoir
    )
    # add six dotted-whole notes and the durated contours to each string voice
    for name, descents in durated_reservoir.items():
        instrument_voice = score["%s Voice" % name]
        instrument_voice.extend("R1. R1. R1. R1. R1. R1.")
        for descent in descents:
            instrument_voice.extend(descent)
    # apply instrument-specific edits
    edit_first_violin_voice(score, durated_reservoir)
    edit_second_violin_voice(score, durated_reservoir)
    edit_viola_voice(score, durated_reservoir)
    edit_cello_voice(score, durated_reservoir)
    edit_bass_voice(score, durated_reservoir)
    # chop all string parts into 6/4 measures
    strings_staff_group = score["Strings Staff Group"]
    with abjad.ForbidUpdate(score):
        for voice in abjad.iterate(strings_staff_group).components(
            abjad.Voice
        ):
            shards = abjad.mutate(voice[:]).split([(6, 4)], cyclic=True)
            for shard in shards:
                container = abjad.Container()
                abjad.mutate(shard).wrap(container)
Пример #12
0
 def __call__(
     self,
     logical_tie,
     pitch_range=None,
     ):
     assert isinstance(logical_tie, selectiontools.LogicalTie), logical_tie
     if isinstance(self.chord_expr, pitchtools.IntervalSegment):
         pitches = self._get_pitches_from_intervals(
             logical_tie.head.written_pitch,
             pitch_range,
             logical_tie,
             )
     else:
         pitches = self.chord_expr
     if len(pitches) == 2:
         interval = pitches[0] - pitches[1]
         if interval.quality_string in ('augmented', 'diminished'):
             chord = scoretools.Chord(pitches, 1)
             mutate(chord).respell_with_sharps()
             pitches = chord.written_pitches
             interval = pitches[0] - pitches[1]
         if interval.quality_string in ('augmented', 'diminished'):
             chord = scoretools.Chord(pitches, 1)
             mutate(chord).respell_with_flats()
             pitches = chord.written_pitches
     for i, leaf in enumerate(logical_tie):
         chord = scoretools.Chord(leaf)
         chord.written_pitches = pitches
         self._replace(leaf, chord)
         if not i and self.arpeggio_direction is not None:
             arpeggio = indicatortools.Arpeggio(self.arpeggio_direction)
             attach(arpeggio, chord)
Пример #13
0
 def clean_up_rhythm(self, music, time_signature_pairs):
     # THIS IS HOW WE CLEAN UP THE RHYTHM
     shards = abjad.mutate(music[:]).split(time_signature_pairs)
     for i, shard in enumerate(shards):
         measure = abjad.Measure(time_signature_pairs[i])
         abjad.mutate(shard).wrap(measure)
     return music
Пример #14
0
def test_Mutation_fuse_05():
    """
    Fuses leaves with differing LilyPond multipliers.
    """

    staff = abjad.Staff([abjad.Skip((1, 1)), abjad.Skip((1, 1))])
    staff[0].multiplier = (1, 16)
    staff[1].multiplier = (5, 16)

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            s1 * 1/16
            s1 * 5/16
        }
        """
    ), print(format(staff))

    assert abjad.inspect(staff).duration() == abjad.Duration(3, 8)

    abjad.mutate(staff[:]).fuse()

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            s1 * 3/8
        }
        """
    )

    assert abjad.inspect(staff).duration() == abjad.Duration(3, 8)
    assert abjad.inspect(staff).wellformed()
Пример #15
0
def test_Mutation_swap_03():
    """
    Moves parentage, children from container to empty tuplet.
    """

    voice = abjad.Voice("{ c'8 d'8 } { e'8 f'8 } { g'8 a'8 }")
    leaves = abjad.select(voice).leaves()
    abjad.beam(leaves)

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
            {
                c'8
                [
                d'8
            }
            {
                e'8
                f'8
            }
            {
                g'8
                a'8
                ]
            }
        }
        """
    )

    tuplet = abjad.Tuplet((3, 4), [])
    abjad.mutate(voice[1:2]).swap(tuplet)

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
            {
                c'8
                [
                d'8
            }
            \tweak text #tuplet-number::calc-fraction-text
            \times 3/4 {
                e'8
                f'8
            }
            {
                g'8
                a'8
                ]
            }
        }
        """
    )

    assert abjad.inspect(voice).wellformed()
Пример #16
0
def test_Mutation_fuse_07():
    """
    Fuses tuplets with same multiplier in score.
    """

    tuplet_1 = abjad.Tuplet((2, 3), "c'8 d'8 e'8")
    abjad.beam(tuplet_1[:])
    tuplet_2 = abjad.Tuplet((2, 3), "c'16 d'16 e'16")
    abjad.slur(tuplet_2[:])
    voice = abjad.Voice([tuplet_1, tuplet_2])

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
            \times 2/3 {
                c'8
                [
                d'8
                e'8
                ]
            }
            \times 2/3 {
                c'16
                (
                d'16
                e'16
                )
            }
        }
        """
    ), print(format(voice))

    tuplets = voice[:]
    abjad.mutate(tuplets).fuse()

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
            \times 2/3 {
                c'8
                [
                d'8
                e'8
                ]
                c'16
                (
                d'16
                e'16
                )
            }
        }
        """
    ), print(format(voice))

    assert abjad.inspect(voice).wellformed()
Пример #17
0
def scale_and_chop_staff(voice_number, staff, time_signature):
    # Scales a staff's durations by a factor and then chops & ties everything at 3/4 measure boundaries.
    scale_factor = 2 ** voice_number
    copy = abjad.mutate(staff).copy()
    for leaf in copy:
        leaf.written_pitch -= voice_number * 12
    abjad.mutate(copy).scale(abjad.Multiplier(scale_factor, 1))
    abjad.mutate(copy[:]).split([time_signature], cyclic=True)
    return copy
Пример #18
0
def test_Mutation_fuse_09():
    """
    Tuplets must carry same multiplier.
    """

    tuplet_1 = abjad.Tuplet((2, 3), "c'8 d'8 e'8")
    tuplet_2 = abjad.Tuplet((4, 5), "c'8 d'8 e'8 f'8 g'8")
    tuplets = abjad.select([tuplet_1, tuplet_2])

    with pytest.raises(Exception):
        abjad.mutate(tuplets).fuse()
Пример #19
0
def test_Mutation_replace_01():
    """
    Moves parentage from two old notes to five new notes.

    Equivalent to staff[1:3] = new_notes.
    """

    staff = abjad.Staff("c'8 d'8 e'8 f'8")
    abjad.beam(staff[:2])
    abjad.beam(staff[2:])
    abjad.hairpin("< !", staff[:])

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            c'8
            \<
            [
            d'8
            ]
            e'8
            [
            f'8
            \!
            ]
        }
        """
    ), print(format(staff))

    old_notes = staff[1:3]
    new_notes = 5 * abjad.Note("c''16")
    abjad.mutate(old_notes).replace(new_notes)

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            c'8
            \<
            [
            c''16
            c''16
            c''16
            c''16
            c''16
            f'8
            \!
            ]
        }
        """
    ), print(format(staff))

    assert abjad.inspect(staff).wellformed()
Пример #20
0
 def _flatten_trivial_tuplets(self, voice):
     for tuplet in abjad.iterate(voice).by_class(abjad.Tuplet):
         if len(tuplet) is 1:
             if isinstance(tuplet[0], (abjad.Rest, abjad.Skip)):
                 pitch = None
             else:
                 pitch = 0
             duration = tuplet.multiplied_duration
             maker = abjad.LeafMaker()
             leaf = maker(pitch, duration)
             abjad.mutate([tuplet]).replace(leaf)
Пример #21
0
def test_Mutation_swap_04():
    """
    Trying to move parentage, children to noncontainer raises exception.
    """

    voice = abjad.Voice("{ c'8 d'8 } { e'8 f'8 }")
    leaves = abjad.select(voice).leaves()
    abjad.beam(leaves)

    note = abjad.Note("c'4")
    with pytest.raises(Exception):
        abjad.mutate(voice[1:2]).swap(note)
Пример #22
0
 def _clean_up_rhythm(self, music, time_signature_pairs):
     """
     Clean up rhythms in ``music`` via ``time_signature_pairs``.
     """
     shards = abjad.mutate(music[:]).split(time_signature_pairs)
     for i, shard in enumerate(shards):
         time_signature_pair = time_signature_pairs[i]
         measure = abjad.Measure(time_signature_pair)
         assert abjad.inspect(shard).duration() == abjad.Duration(
             time_signature_pair)
         abjad.mutate(shard).wrap(measure)
     return music
Пример #23
0
def test_Mutation_swap_05():
    """
    Trying to move parentage, children from nonempty container to nonempty
    container raises exception.
    """

    voice = abjad.Voice("{ c'8 d'8 } { e'8 f'8 }")
    leaves = abjad.select(voice).leaves()
    abjad.beam(leaves)

    tuplet = abjad.Tuplet((2, 3), "c'8 d'8 e'8")
    with pytest.raises(Exception):
        abjad.mutate(voice[1:2]).swap(tuplet)
Пример #24
0
    def replace_multimeasure_rests(self, music):
        """
        TO DO EVENTUALLY... probably some more elegant way to do this, but for now this works
        """
        if self.time_signature:
            measure_length = abjad.Duration(self.time_signature)
        else:
            # if no time signature specified, then this gets the pair for the duration of the first measure:
            measure_length = sum([abjad.Duration(i) for i in self.metrical_durations[0]])

        leaves = abjad.select(music).by_leaf()
        rest_measures = 0
        measure_duration_tally = abjad.Duration(0)
        
        measure_has_only_rests = True # assume innocent until proven guilty
        measure_rests_to_replace = []
        rests_to_replace = []

        leaves_length = len(leaves)
        # print(music)
        for i,l in enumerate(leaves):
            
            measure_duration_tally += l.written_duration
            
            if isinstance(l, abjad.Rest) and measure_has_only_rests:
                measure_rests_to_replace.append(l)
            else:
                measure_has_only_rests = False

            if measure_duration_tally==measure_length:
                # if we're at the end of the line or this measure has notes, then maybe we need to add multimeasure rest beforehand
                # and then go and set rests_length back to 0
                if measure_has_only_rests:
                    rests_to_replace += measure_rests_to_replace
                    rest_measures += 1
                if i==leaves_length-1 or not measure_has_only_rests:
                    # then, add multimeasure rest, if > 0
                    if rest_measures > 0:
                        # print("MUTATE TO ADD REST %s/%s * %s" % (measure_length.pair[0], measure_length.pair[1], rest_measures) )
                        my_multimeasure_rests = abjad.Container("R1 * %s/%s * %s" % (measure_length.pair[0], measure_length.pair[1], rest_measures))
                        abjad.mutate(rests_to_replace).replace(my_multimeasure_rests)
                    rests_to_replace = []
                    rest_measures = 0

                # this measure is done, so set duration tally back to 0,
                # assume all rests in measure, and set rests in measure list back to empty
                # (all for the following measure):
                measure_duration_tally = abjad.Duration(0)
                measure_has_only_rests = True
                measure_rests_to_replace = []
Пример #25
0
def test_Mutation_extract_03():
    """
    Extracts container.
    """

    staff = abjad.Staff()
    staff.append(abjad.Container("c'8 d'8"))
    staff.append(abjad.Container("e'8 f'8"))
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves)

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            {
                c'8
                [
                d'8
            }
            {
                e'8
                f'8
                ]
            }
        }
        """
    ), print(format(staff))

    container = staff[0]
    abjad.mutate(container).extract()

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            c'8
            [
            d'8
            {
                e'8
                f'8
                ]
            }
        }
        """
    ), print(format(staff))

    assert not container
    assert abjad.inspect(staff).wellformed()
    def _construct_fingering_tablature(
        self,
        logical_tie,
        fingering,
        previous_fingering
    ):
        # create 'chords' at particular staff positions

        staff_positions = [4, 7, 11, 14]
        if self._hand == 'left':
            staff_positions.append(17)

        finger_names = ['thumb', 'index', 'middle', 'ring', 'pinky']
        finger_names.reverse()

        for i, leaf in enumerate(logical_tie):
            chord = abjad.Chord(staff_positions, leaf.written_duration)
            abjad.mutate(leaf).replace(chord)
            if i == 0:
                # first leaf
                for j, note_head in enumerate(chord.note_heads):
                    finger_name = finger_names[j]
                    current_keys = None

                    if finger_name in fingering.keys.keys():
                        current_keys = fingering.keys[finger_name]

                    previous_keys = None

                    if previous_fingering is not None:
                        previous_keys = previous_fingering.keys[finger_name]

                    if current_keys is not None:
                        # continuation: hide note head
                        if previous_keys == current_keys:
                            note_head.tweak.stencil = \
                                abjad.Scheme('point-stencil')
                        # new left_hand: set note head to markup
                        else:
                            markup = self._make_note_head_markup(current_keys)
                            if markup is not None:
                                note_head.tweak.stencil = \
                                    'ly:text-interface::print'
                                note_head.tweak.text = markup
                    else:
                        note_head.tweak.stencil = abjad.Scheme('point-stencil')
            else:
                # non-first leaf
                for note_head in chord.note_heads:
                    note_head.tweak.stencil = abjad.Scheme('point-stencil')
Пример #27
0
def test_Mutation_split_15():
    """
    Splits voice at negative index.
    """

    staff = abjad.Staff([abjad.Voice("c'8 d'8 e'8 f'8")])
    voice = staff[0]

    result = abjad.mutate([voice]).split([abjad.Duration(1, 4)])

    left = result[0][0]
    right = result[1][0]

    assert format(left) == abjad.String.normalize(
        r"""
        \new Voice
        {
            c'8
            d'8
        }
        """
    ), print(format(left))

    assert format(right) == abjad.String.normalize(
        r"""
        \new Voice
        {
            e'8
            f'8
        }
        """
    ), print(format(right))

    assert format(voice) == abjad.String.normalize(
        r"""
        \new Voice
        {
        }
        """
    ), print(format(voice))

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            \new Voice
            {
                c'8
                d'8
            }
            \new Voice
            {
                e'8
                f'8
            }
        }
        """
    ), print(format(staff))

    assert abjad.inspect(staff).wellformed()
Пример #28
0
def test_Mutation_split_20():
    """
    Splits leaf at non-assignable, non-power-of-two offset.
    """

    staff = abjad.Staff("c'4")

    notes = staff[:1]
    result = abjad.mutate(notes).split([abjad.Duration(5, 24)])

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            \times 2/3 {
                c'4
                ~
                c'16
                ~
                c'16
            }
        }
        """
    ), print(format(staff))

    assert abjad.inspect(staff).wellformed()
Пример #29
0
def edit_viola_voice(score, durated_reservoir):
    """
    Edits viola voice.
    """
    voice = score["Viola Voice"]
    descents = durated_reservoir["Viola"]
    for leaf in descents[-1]:
        articulation = abjad.Articulation("accent")
        abjad.attach(articulation, leaf)
        articulation = abjad.Articulation("tenuto")
        abjad.attach(articulation, leaf)
    last_descent = abjad.Selection(descents[-1])
    copied_descent = abjad.mutate(last_descent).copy()
    for leaf in copied_descent:
        if leaf.written_duration == abjad.Duration(4, 4):
            leaf.written_duration = abjad.Duration(8, 4)
        else:
            leaf.written_duration = abjad.Duration(4, 4)
    voice.extend(copied_descent)
    bridge = abjad.Note("e1")
    articulation = abjad.Articulation("tenuto")
    abjad.attach(articulation, bridge)
    articulation = abjad.Articulation("accent")
    abjad.attach(articulation, bridge)
    voice.append(bridge)
    final_sustain_rhythm = [(6, 4)] * 21 + [(1, 2)]
    maker = abjad.NoteMaker()
    final_sustain_notes = maker(["e"], final_sustain_rhythm)
    articulation = abjad.Articulation("accent")
    abjad.attach(articulation, final_sustain_notes[0])
    articulation = abjad.Articulation("tenuto")
    abjad.attach(articulation, final_sustain_notes[0])
    voice.extend(final_sustain_notes)
    abjad.tie(final_sustain_notes)
    voice.extend("r4 r2.")
Пример #30
0
def edit_cello_voice(score, durated_reservoir):
    """
    Edits cello voice.
    """
    voice = score["Cello Voice"]
    descents = durated_reservoir["Cello"]
    logical_tie = abjad.inspect(voice[-1]).logical_tie()
    for leaf in logical_tie.leaves:
        parent = abjad.inspect(leaf).parentage().parent
        index = parent.index(leaf)
        parent[index] = abjad.Chord(["e,", "a,"], leaf.written_duration)
    selection = voice[-len(descents[-1]) :]
    unison_descent = abjad.mutate(selection).copy()
    voice.extend(unison_descent)
    for chord in unison_descent:
        index = abjad.inspect(chord).parentage().parent.index(chord)
        parent[index] = abjad.Note(
            chord.written_pitches[1], chord.written_duration
        )
        articulation = abjad.Articulation("accent")
        abjad.attach(articulation, parent[index])
        articulation = abjad.Articulation("tenuto")
        abjad.attach(articulation, parent[index])
    voice.extend("a,1. ~ a,2")
    voice.extend("b,1 ~ b,1. ~ b,1.")
    voice.extend("a,1. ~ a,1. ~ a,1. ~ a,1. ~ a,1. ~ a,2")
    voice.extend("r4 r2.")
def test_rhythmmakertools_BeamSpecifier_beam_each_division_01():
    r'''Beam each cell with a multipart beam spanner.
    '''

    talea = rhythmmakertools.Talea(
        counts=[1, 1, 1, -1, 2, 2],
        denominator=32,
        )

    rhythm_maker = rhythmmakertools.TaleaRhythmMaker(
        talea=talea,
        extra_counts_per_division=[3, 4],
        )

    divisions = [(2, 16), (5, 16)]
    selections = rhythm_maker(divisions)

    maker = abjad.MeasureMaker()
    measures = maker(divisions)
    staff = abjad.Staff(measures)
    abjad.mutate(staff).replace_measure_contents(selections)
    score = abjad.Score([staff])
    abjad.setting(score).autoBeaming = False

    assert format(staff) == abjad.String.normalize(
        r'''
        \new Staff
        {
            {   % measure
                \time 2/16
                \times 4/7 {
                    c'32
                    [
                    c'32
                    c'32
                    ]
                    r32
                    c'16
                    [
                    c'32
                    ~
                    ]
                }
            }   % measure
            {   % measure
                \time 5/16
                \tweak text #tuplet-number::calc-fraction-text
                \times 5/7 {
                    c'32
                    [
                    c'32
                    c'32
                    c'32
                    ]
                    r32
                    c'16
                    [
                    c'16
                    c'32
                    c'32
                    c'32
                    ]
                    r32
                    c'32
                }
            }   % measure
        }
        '''
        )
Пример #32
0
        # We know the voice name of each timespan because a) the timespan
        # list is in a dictionary, associated with that voice name and b)
        # each timespan's annotation is a MusicSpecifier instance which
        # knows the name of the voice the timespan should be used for.
        # This double-reference to the voice is redundant here, but in a
        # different implementation we could put *all* the timespans into
        # one timespan list, split them, whatever, and still know which
        # voice they belong to because their annotation records that
        # information.
        durations = [timespan.duration for timespan in grouper]
        container = make_container(music_maker, durations)
        voice = score[voice_name]
        voice.append(container[:])

print("Adding Beam Staff ...")
voice_1_copy = abjad.mutate(score["Voice 1"]).copy()
score["Voice 5"].extend([voice_1_copy[:]])

voice_3_copy = abjad.mutate(score["Voice 3"]).copy()
score["Voice 6"].extend([voice_3_copy[:]])

print("Splitting and rewriting ...")

# split and rewite meters
for voice in abjad.iterate(score["Staff Group 1"]).components(abjad.Voice):
    for i, shard in enumerate(abjad.mutate(voice[:]).split(time_signatures)):
        time_signature = time_signatures[i]
        abjad.mutate(shard).rewrite_meter(time_signature)

for voice in abjad.iterate(score["Staff Group 2"]).components(abjad.Voice):
    for i, shard in enumerate(abjad.mutate(voice[:]).split(time_signatures)):
Пример #33
0
def test_Mutation_split_11():
    """
    Splits container in score.
    """

    staff = abjad.Staff([abjad.Container("c'8 d'8 e'8 f'8")])
    voice = staff[0]
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves)

    result = abjad.mutate([voice]).split([abjad.Duration(1, 4)])

    left = result[0][0]
    right = result[1][0]

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                c'8
                [
                d'8
            }
            {
                e'8
                f'8
                ]
            }
        }
        """), print(format(staff))

    assert format(left) == abjad.String.normalize(r"""
        {
            c'8
            [
            d'8
        }
        """), print(format(left))

    assert format(right) == abjad.String.normalize(r"""
        {
            e'8
            f'8
            ]
        }
        """), print(format(right))

    assert format(voice) == abjad.String.normalize(r"""
        {
        }
        """), print(format(voice))

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                c'8
                [
                d'8
            }
            {
                e'8
                f'8
                ]
            }
        }
        """), print(format(staff))

    assert abjad.inspect(staff).wellformed()
Пример #34
0
def fix_meter(score):
    for staff in score:
        abjad.mutate(staff[:]).split(durations=[(4,4)], cyclic=True)
Пример #35
0
def fill_with_rests(
    container: abjad.Container,
    *,
    disable_rewrite_meter: bool = False,
    prettify_rewrite_meter: bool = True,
    boundary_depth: Optional[int] = None,
    maximum_dot_count: Optional[int] = None,
    rewrite_tuplets: bool = True,
    extract_trivial_tuplets: bool = True,
    fuse_across_groups_of_beats: bool = True,
    fuse_quadruple_meter: bool = True,
    fuse_triple_meter: bool = True,
    split_quadruple_meter: bool = True,
) -> None:
    r"""Mutates an input container (of type |abjad.Container| or child class)
    in place and has no return value; this function fills a container with
    rests in order to make it full.

    Basic usage:
        Returns the missing duration of the last measure of any container or
        child class. If no time signature is encountered, it uses LilyPond's
        convention and considers the container as in 4/4.

        >>> container1 = abjad.Container(r"c'4 d'4 e'4 f'4")
        >>> container2 = abjad.Container(r"c'4 d'4 e'4")
        >>> container3 = abjad.Container(r"c'4 d'4 e'4 f'4 | c'4")
        >>> container4 = abjad.Container(r"c'4 d'4 e'4 f'4 | c'4 d'4 e'4 f'4")
        >>> auxjad.mutate(container1).fill_with_rests()
        >>> auxjad.mutate(container2).fill_with_rests()
        >>> auxjad.mutate(container3).fill_with_rests()
        >>> auxjad.mutate(container4).fill_with_rests()
        >>> abjad.f(container1)
        {
            c'4
            d'4
            e'4
            f'4
        }

        .. figure:: ../_images/fill_with_rests-up297scg6t.png

        >>> abjad.f(container2)
        {
            c'4
            d'4
            e'4
            r4
        }

        .. figure:: ../_images/fill_with_rests-azrrw0z0buw.png

        >>> abjad.f(container3)
        {
            c'4
            d'4
            e'4
            f'4
            c'4
            r2.
        }

        .. figure:: ../_images/fill_with_rests-jtyw5ikc0k.png

        >>> abjad.f(container4)
        {
            c'4
            d'4
            e'4
            f'4
            c'4
            d'4
            e'4
            f'4
        }

        .. figure:: ../_images/fill_with_rests-xjkm2vzjfpr.png

    .. note::

        Auxjad automatically adds this function as an extension method to
        |abjad.mutate()|. It can thus be used from either
        :func:`auxjad.mutate()` or |abjad.mutate()|. Therefore, the two lines
        below are equivalent:

        >>> auxjad.mutate(staff).fill_with_rests()
        >>> abjad.mutate(staff).fill_with_rests()

    Time signature changes:
        Handles any time signatures as well as changes of time signature.

        >>> staff1 = abjad.Staff(r"\time 4/4 c'4 d'4 e'4 f'4 g'")
        >>> staff2 = abjad.Staff(r"\time 3/4 a2. \time 2/4 c'4")
        >>> staff3 = abjad.Staff(r"\time 5/4 g1 ~ g4 \time 4/4 af'2")
        >>> auxjad.mutate(staff1).fill_with_rests()
        >>> auxjad.mutate(staff2).fill_with_rests()
        >>> auxjad.mutate(staff3).fill_with_rests()
        >>> abjad.f(staff1)
        {
            \time 4/4
            c'4
            d'4
            e'4
            f'4
            g'4
            r2.
        }

        .. figure:: ../_images/fill_with_rests-7zydps2jsb.png

        >>> abjad.f(staff2)
        {
            \time 3/4
            a2.
            \time 2/4
            c'4
            r4
        }

        .. figure:: ../_images/fill_with_rests-1lphcrl5pnr.png

        >>> abjad.f(staff3)
        {
            \time 5/4
            g1
            ~
            g4
            \time 4/4
            af'2
            r2
        }

        .. figure:: ../_images/fill_with_rests-e00jvx986r.png

    .. note::

        When using |abjad.Container|'s, all time signatures in the output will
        be commented out with ``%%%.`` This is because Abjad only applies time
        signatures to containers that belong to a |abjad.Staff|. The present
        function works with either |abjad.Container| and |abjad.Staff|.

        >>> container = abjad.Container(r"\time 3/4 c'4 d'4 e'4")
        >>> abjad.f(container)
        {
            %%% \time 3/4 %%%
            c'4
            d'4
            e'4
        }

        .. figure:: ../_images/fill_with_rests-b0qflg50qfn.png

        >>> staff = abjad.Staff([container])
        >>> abjad.f(container)
        {
            \time 3/4
            c'4
            d'4
            e'4
        }

        .. figure:: ../_images/fill_with_rests-qtaswjiecg.png

    Partial time signatures:
        Correctly handles partial time signatures.

        >>> staff = abjad.Staff(r"c'4 d'4 e'4 f'4 g'4")
        >>> time_signature = abjad.TimeSignature((3, 4), partial=(1, 4))
        >>> abjad.attach(time_signature, staff[0])
        >>> auxjad.mutate(staff).fill_with_rests()
        >>> abjad.f(staff)
        {
            \partial 4
            \time 3/4
            c'4
            d'4
            e'4
            f'4
            g'4
            r2
        }

        .. figure:: ../_images/fill_with_rests-9smva9ajdi.png

    ``disable_rewrite_meter``:
        By default, this class applies the |abjad.mutate().rewrite_meter()|
        mutation to the last measure when rests are added.

        >>> staff = abjad.Staff(r"\time 4/4 c'8 d'4 e'4")
        >>> auxjad.mutate(staff).fill_with_rests()
        >>> abjad.f(staff)
        \new Staff
        {
            \time 4/4
            c'8
            d'4
            e'8
            ~
            e'8
            r4.
        }

        .. figure:: ../_images/fill_with_rests-n83nmnfh92c.png

        Call this function with the optional keyword argument
        ``disable_rewrite_meter`` set to ``True`` in order to disable this
        behaviour.

        >>> staff = abjad.Staff(r"\time 4/4 c'8 d'4 e'4")
        >>> auxjad.mutate(staff, disable_rewrite_meter=True).fill_with_rests()
        >>> abjad.f(staff)
        \new Staff
        {
            \time 4/4
            c'8
            d'4
            e'4
            r4.
        }

        .. figure:: ../_images/fill_with_rests-9rg2i4n1vhr.png

    .. note::

        This function also accepts the arguments ``boundary_depth``,
        ``maximum_dot_count``, and ``rewrite_tuplets``, which are passed on to
        |abjad.mutate().rewrite_meter()|, and ``fuse_across_groups_of_beats``,
        ``fuse_quadruple_meter``, ``fuse_triple_meter``,
        ``extract_trivial_tuplets``,  and ``split_quadruple_meter``, which are
        passed on to |auxjad.mutate().prettify_rewrite_meter()| (the latter can
        be disabled by setting ``prettify_rewrite_meter`` to ``False``). See
        the documentation of those functions for more details on these
        arguments.

    .. error::

        If a container is malformed, i.e. it has an underfilled measure before
        a time signature change, the function raises a :exc:`ValueError`
        exception.

        >>> container = abjad.Container(r"\time 5/4 g''1 \time 4/4 f'4")
        >>> auxjad.mutate(container).fill_with_rests()
        ValueError: 'container' is malformed, with an underfull measure
        preceding a time signature change

    .. warning::

        The input container must be a contiguous logical voice. When dealing
        with a container with multiple subcontainers (e.g. a score containing
        multiple staves), the best approach is to cycle through these
        subcontainers, applying this function to them individually.
    """
    if not isinstance(container, abjad.Container):
        raise TypeError("argument must be 'abjad.Container' or child class")
    if not abjad.select(container).leaves().are_contiguous_logical_voice():
        raise ValueError("argument must be contiguous logical voice")
    try:
        if not inspect(container[:]).selection_is_full():
            underfull_rests = abjad.LeafMaker()(
                None,
                inspect(container[:]).underfull_duration(),
            )
            container.extend(underfull_rests)
        else:
            return
    except ValueError as err:
        raise ValueError("'container' is malformed, with an underfull measure "
                         "preceding a time signature change") from err
    if not disable_rewrite_meter:
        time_signatures = inspect(container).extract_time_signatures(
            do_not_use_none=True, )
        measures = abjad.select(container[:]).group_by_measure()
        abjad.mutate(measures[-1]).rewrite_meter(
            time_signatures[-1],
            boundary_depth=boundary_depth,
            maximum_dot_count=maximum_dot_count,
            rewrite_tuplets=rewrite_tuplets,
        )
        if prettify_rewrite_meter:
            measures = abjad.select(container[:]).group_by_measure()
            prettify_rewrite_meter_function(
                measures[-1],
                time_signatures[-1],
                extract_trivial_tuplets=extract_trivial_tuplets,
                fuse_across_groups_of_beats=fuse_across_groups_of_beats,
                fuse_quadruple_meter=fuse_quadruple_meter,
                fuse_triple_meter=fuse_triple_meter,
                split_quadruple_meter=split_quadruple_meter,
            )
Пример #36
0
 def _split_by_durations(
     self,
     durations,
     cyclic=False,
     fracture_spanners=False,
     tie_split_notes=True,
     repeat_ties=False,
 ):
     import abjad
     durations = [abjad.Duration(_) for _ in durations]
     durations = abjad.sequence(durations)
     leaf_duration = abjad.inspect(self).get_duration()
     if cyclic:
         durations = durations.repeat_to_weight(leaf_duration)
     if sum(durations) < leaf_duration:
         last_duration = leaf_duration - sum(durations)
         durations = list(durations)
         durations.append(last_duration)
         durations = abjad.sequence(durations)
     durations = durations.truncate(weight=leaf_duration)
     result_selections = []
     # detach grace containers
     grace_container = self._detach_grace_container()
     after_grace_container = self._detach_after_grace_container()
     leaf_prolation = abjad.inspect(self).get_parentage().prolation
     for duration in durations:
         new_leaf = copy.copy(self)
         preprolated_duration = duration / leaf_prolation
         selection = new_leaf._set_duration(
             preprolated_duration,
             repeat_ties=repeat_ties,
         )
         result_selections.append(selection)
     result_components = abjad.sequence(result_selections).flatten(depth=-1)
     result_components = abjad.select(result_components)
     result_leaves = abjad.select(result_components).leaves()
     assert all(isinstance(_, abjad.Selection) for _ in result_selections)
     assert all(isinstance(_, abjad.Component) for _ in result_components)
     assert result_leaves.are_leaves()
     if abjad.inspect(self).has_spanner(abjad.Tie):
         for leaf in result_leaves:
             abjad.detach(abjad.Tie, leaf)
     # strip result leaves of indicators (other than multipliers)
     for leaf in result_leaves:
         multiplier = abjad.inspect(leaf).get_indicator(abjad.Multiplier)
         abjad.detach(object, leaf)
         abjad.attach(multiplier, leaf)
     # replace leaf with flattened result
     selection = abjad.select(self)
     parent, start, stop = selection._get_parent_and_start_stop_indices()
     if parent:
         parent.__setitem__(slice(start, stop + 1), result_components)
     else:
         selection._give_dominant_spanners(result_components)
         selection._withdraw_from_crossing_spanners()
     # fracture spanners
     if fracture_spanners:
         first_selection = result_selections[0]
         for spanner in abjad.inspect(first_selection[-1]).get_spanners():
             index = spanner._index(first_selection[-1])
             spanner._fracture(index, direction=abjad.Right)
         last_selection = result_selections[-1]
         for spanner in abjad.inspect(last_selection[0]).get_spanners():
             index = spanner._index(last_selection[0])
             spanner._fracture(index, direction=abjad.Left)
         for middle_selection in result_selections[1:-1]:
             spanners = abjad.inspect(middle_selection[0]).get_spanners()
             for spanner in spanners:
                 index = spanner._index(middle_selection[0])
                 spanner._fracture(index, direction=abjad.Left)
             spanners = abjad.inspect(middle_selection[-1]).get_spanners()
             for spanner in spanners:
                 index = spanner._index(middle_selection[-1])
                 spanner._fracture(index, direction=abjad.Right)
     # move indicators
     first_result_leaf = result_leaves[0]
     last_result_leaf = result_leaves[-1]
     for indicator in abjad.inspect(self).get_indicators():
         if isinstance(indicator, abjad.Multiplier):
             continue
         abjad.detach(indicator, self)
         direction = getattr(indicator, '_time_orientation', abjad.Left)
         if direction == abjad.Left:
             abjad.attach(indicator, first_result_leaf)
         elif direction == abjad.Right:
             abjad.attach(indicator, last_result_leaf)
         else:
             raise ValueError(direction)
     # move grace containers
     if grace_container is not None:
         container = grace_container[0]
         assert isinstance(container, abjad.GraceContainer), repr(container)
         abjad.attach(container, first_result_leaf)
     if after_grace_container is not None:
         container = after_grace_container[0]
         prototype = abjad.AfterGraceContainer
         assert isinstance(container, prototype), repr(container)
         abjad.attach(container, last_result_leaf)
     if isinstance(result_components[0], abjad.Tuplet):
         abjad.mutate(result_components).fuse()
     # tie split notes
     if isinstance(self, (abjad.Note, abjad.Chord)) and tie_split_notes:
         result_leaves._attach_tie_spanner_to_leaves(
             repeat_ties=repeat_ties, )
     assert isinstance(result_selections, list), repr(result_selections)
     assert all(isinstance(_, abjad.Selection) for _ in result_selections)
     return result_selections
Пример #37
0
def sustain_notes(
    container: abjad.Container,
    *,
    sustain_multimeasure_rests: bool = True,
    rewrite_meter: bool = True,
) -> None:
    r"""Mutates an input container (of type |abjad.Container| or child class)
    in place and has no return value; this function will sustain all pitched
    leaves until the next pitched leaf, thus replacing all rests in between
    them.

    Basic usage:
        Simply call the function on a container.

        >>> staff = abjad.Staff(r"c'16 r8. d'16 r8. e'16 r8. f'16 r8.")
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            r8.
            d'16
            r8.
            e'16
            r8.
            f'16
            r8.
        }

        .. figure:: ../_images/sustain_notes-w1e1pmruyce.png

        >>> auxjad.mutate(staff).sustain_notes()
        >>> abjad.f(staff)
        \new Staff
        {
            c'4
            d'4
            e'4
            f'4
        }

        .. figure:: ../_images/sustain_notes-ythfpvkrvue.png

    .. note::

        Auxjad automatically adds this function as an extension method to
        |abjad.mutate()|. It can thus be used from either
        :func:`auxjad.mutate()` or |abjad.mutate()|. Therefore, the two lines
        below are equivalent:

        >>> auxjad.mutate(staff).close_containers()
        >>> abjad.mutate(staff).close_containers()

    Leaves with same pitch:
        Leaves are sustained until the next pitched leaf, even if the pitch is
        the same.

        >>> staff = abjad.Staff(r"c'16 r8. c'16 r8. c'16 r8. c'16 r8.")
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            r8.
            c'16
            r8.
            c'16
            r8.
            c'16
            r8.
        }

        .. figure:: ../_images/sustain_notes-oliqicqqw7q.png

        >>> auxjad.mutate(staff).sustain_notes()
        >>> abjad.f(staff)
        \new Staff
        {
            c'4
            c'4
            c'4
            c'4
        }

        .. figure:: ../_images/sustain_notes-3alcbmhc2jt.png

    Consecutive leaves with the same pitch:
        Consecutive pitched leaves with a same pitch will not be tied.

        >>> staff = abjad.Staff(
        ...     r"<c' e'>16 r8. <c' e'>4 <c' e'>4 <c' e'>16 r8."
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            <c' e'>16
            r8.
            <c' e'>4
            <c' e'>4
            <c' e'>16
            r8.
        }

        .. figure:: ../_images/sustain_notes-ek4ujjintt8.png

        >>> auxjad.mutate(staff).sustain_notes()
        >>> abjad.f(staff)
        \new Staff
        {
            <c' e'>4
            <c' e'>4
            <c' e'>4
            <c' e'>4
        }

        .. figure:: ../_images/sustain_notes-f7au6hojq99.png

    Tuplets:
        This function handles tuplets.

        >>> staff = abjad.Staff(
        ...     r"\times 2/3 {c'4 d'4 r4} r8 e'8 \times 2/3 {f'8 r4}"
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \times 2/3 {
                c'4
                d'4
                r4
            }
            r8
            e'8
            \times 2/3 {
                f'8
                r4
            }
        }

        .. figure:: ../_images/sustain_notes-nsjvhnyrkea.png

        >>> auxjad.mutate(staff).sustain_notes()
        >>> abjad.f(staff)
        \new Staff
        {
            \times 2/3 {
                c'4
                d'2
                ~
            }
            d'8
            e'8
            f'4
        }

        .. figure:: ../_images/sustain_notes-26l9hob8wko.png

    Complex example:
        This function can handle containers with a mixture of notes, chords,
        and rests, as well as tuplets.

        >>> staff = abjad.Staff(r"c'16 r8. d'16 r8. r8 r32 <e' g'>32 r16 r4 "
        ...                     r"\times 2/3 {r4 f'4 r4} r4 g'8 r8 a'4 ~ "
        ...                     r"a'16 r8. b'4 c''8 r8 "
        ...                     r"r4. d''8 \times 4/5 {r8 d''2}"
        ...                     )
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            r8.
            d'16
            r8.
            r8
            r32
            <e' g'>32
            r16
            r4
            \times 2/3 {
                r4
                f'4
                r4
            }
            r4
            g'8
            r8
            a'4
            ~
            a'16
            r8.
            b'4
            c''8
            r8
            r4.
            d''8
            \times 4/5 {
                r8
                d''2
            }
        }

        .. figure:: ../_images/sustain_notes-cpw7dvpegge.png

        >>> auxjad.mutate(staff).sustain_notes()
        >>> abjad.f(staff)
        \new Staff
        {
            c'4
            d'4
            ~
            d'8
            ~
            d'32
            <e' g'>16.
            ~
            <e' g'>4
            ~
            \times 2/3 {
                <e' g'>4
                f'2
                ~
            }
            f'4
            g'4
            a'2
            b'4
            c''4
            ~
            c''4.
            d''8
            ~
            \times 4/5 {
                d''8
                d''2
            }
        }

        .. figure:: ../_images/sustain_notes-z8t2jwxsvar.png

    Multi-measure rests:
        This mutation also handles multi-measure rests, including ones with
        non-assignable durations:

        >>> staff = abjad.Staff(r"r4 c'16 r8. d'16 r4.. "
        ...                     r"R1"
        ...                     r"r4 e'4 r2"
        ...                     r"\time 5/8 r8 f'4 r4"
        ...                     r"R1 * 5/8 "
        ...                     r"r8 g'8 a'8 r4"
        ...                     )
        >>> abjad.f(staff)
        \new Staff
        {
            r4
            c'16
            r8.
            d'16
            r4..
            R1
            r4
            e'4
            r2
            \time 5/8
            r8
            f'4
            r4
            R1 * 5/8
            r8
            g'8
            a'8
            r4
        }

        .. figure:: ../_images/sustain_notes-mJOOARIUAp.png

        >>> auxjad.mutate(staff).sustain_notes()
        >>> abjad.f(staff)
        \new Staff
        {
            r4
            c'4
            d'2
            ~
            d'1
            ~
            d'4
            e'2.
            ~
            \time 5/8
            e'8
            f'2
            ~
            f'4.
            ~
            f'4
            f'8
            g'4
            a'4
        }

        .. figure:: ../_images/sustain_notes-iLTiWERSvO.png

    ``sustain_multimeasure_rests``:
        By default, notes are tied across multi-measure rests.

        >>> staff = abjad.Staff(r"r4 c'16 r8. d'16 r4.. "
        ...                     r"R1"
        ...                     r"r4 e'4 r2"
        ...                     r"\time 5/8 r8 f'4 r4"
        ...                     r"R1 * 5/8 "
        ...                     r"r8 g'8 a'8 r4"
        ...                     )
        >>> abjad.f(staff)
        \new Staff
        {
            r4
            c'16
            r8.
            d'16
            r4..
            R1
            r4
            e'4
            r2
            \time 5/8
            r8
            f'4
            r4
            R1 * 5/8
            r8
            g'8
            a'8
            r4
        }

        .. figure:: ../_images/sustain_notes-P2CLdKi6Cs.png

        To disable sustaining across those, set ``sustain_multimeasure_rests``
        to  ``False``:

        >>> auxjad.mutate(staff).sustain_notes(sustain_multimeasure_rests=True)
        >>> abjad.f(staff)
        \new Staff
        {
            r4
            c'4
            d'2
            R1
            r4
            e'2.
            ~
            \time 5/8
            e'8
            f'2
            R1 * 5/8
            r8
            g'8
            a'4.
        }

        .. figure:: ../_images/sustain_notes-9WeilArLex.png

    ``rewrite_meter``:
        By default, |auxjad.mutate().auto_rewrite_meter()| is summoned after
        notes are sustained.

        >>> staff = abjad.Staff(r"r4 c'16 r8. d'16 r4.. "
        ...                     r"R1"
        ...                     r"r4 e'4 r2"
        ...                     r"\time 5/8 r8 f'4 r4"
        ...                     r"R1 * 5/8 "
        ...                     r"r8 g'8 a'8 r4"
        ...                     )
        >>> abjad.f(staff)
        \new Staff
        {
            r4
            c'16
            r8.
            d'16
            r4..
            R1
            r4
            e'4
            r2
            \time 5/8
            r8
            f'4
            r4
            R1 * 5/8
            r8
            g'8
            a'8
            r4
        }

        .. figure:: ../_images/sustain_notes-P2CLdKi6Cs.png

        To disable this behaviour, set ``rewrite_meter`` to ``False``:

        >>> auxjad.mutate(staff).sustain_notes(rewrite_meter=False)
        >>> abjad.f(staff)
        \new Staff
        {
            r4
            c'16
            ~
            c'8.
            d'16
            ~
            d'4..
            ~
            d'1
            ~
            d'4
            e'4
            ~
            e'2
            ~
            \time 5/8
            e'8
            f'4
            ~
            f'4
            ~
            f'2
            ~
            f'8
            f'8
            g'8
            ~
            a'8
            a'4
        }

        .. figure:: ../_images/sustain_notes-9WeilArLex.png

    .. warning::

        The input container must be a contiguous logical voice. When dealing
        with a container with multiple subcontainers (e.g. a score containing
        multiple staves), the best approach is to cycle through these
        subcontainers, applying this function to them individually.
    """
    if not isinstance(container, abjad.Container):
        raise TypeError("argument must be 'abjad.Container' or child class")
    if not abjad.select(container).leaves().are_contiguous_logical_voice():
        raise ValueError("argument must be contiguous logical voice")
    if not isinstance(sustain_multimeasure_rests, bool):
        raise TypeError("'sustain_multimeasure_rests' must be 'bool'")
    if not isinstance(rewrite_meter, bool):
        raise TypeError("'rewrite_meter' must be 'bool'")
    leaves = abjad.select(container).leaves()
    pitch = None
    pitches = None
    for index, leaf in enumerate(leaves):
        if isinstance(leaf, (abjad.Rest, abjad.MultimeasureRest)):
            if isinstance(leaf, abjad.MultimeasureRest):
                if not sustain_multimeasure_rests:
                    pitch = None
                    pitches = None
                    continue
                duration = abjad.inspect(leaf).duration()
            else:
                duration = leaf.written_duration
            if pitch is not None:
                replacement_leaf = abjad.LeafMaker()(pitch, duration)
            elif pitches is not None:
                replacement_leaf = abjad.LeafMaker()([pitches], [duration])
            if pitch is not None or pitches is not None:
                for indicator in abjad.inspect(leaf).indicators():
                    abjad.attach(
                        indicator,
                        abjad.select(replacement_leaf).leaf(0),
                    )
                abjad.mutate(leaf).replace(replacement_leaf)
                previous_leaf = abjad.select(container).leaves()[index - 1]
                if abjad.inspect(previous_leaf).indicator(abjad.Tie) is None:
                    if not isinstance(previous_leaf, abjad.MultimeasureRest):
                        abjad.attach(abjad.Tie(), previous_leaf)
        elif isinstance(leaf, abjad.Note):
            pitch = leaf.written_pitch
            pitches = None
        elif isinstance(leaf, abjad.Chord):
            pitch = None
            pitches = [pitch for pitch in leaf.written_pitches]
    # rewriting meter
    if rewrite_meter:
        auto_rewrite_meter(container)
Пример #38
0
 def fix_meter_at_measure_boundaries(self, chop_duration):
     for staff in self.skeleton:
         abjad.mutate(staff[:]).split(durations=[chop_duration], cyclic=True)
Пример #39
0
def enforce_time_signature(
    container: abjad.Container,
    time_signatures: Union[abjad.TimeSignature, tuple, list, ],
    *,
    cyclic: bool = False,
    fill_with_rests: bool = True,
    close_container: bool = False,
    disable_rewrite_meter: bool = False,
    prettify_rewrite_meter: bool = True,
    boundary_depth: Optional[int] = None,
    maximum_dot_count: Optional[int] = None,
    rewrite_tuplets: bool = True,
    extract_trivial_tuplets: bool = True,
    fuse_across_groups_of_beats: bool = True,
    fuse_quadruple_meter: bool = True,
    fuse_triple_meter: bool = True,
    split_quadruple_meter: bool = True,
) -> None:
    r"""Mutates an input container (of type |abjad.Container| or child class)
    in place and has no return value; this function applies a time signature
    (or a :obj:`list` of time signatures) to the input container.

    Basic usage:
        The function mutates a container in place, applying a time signature
        to it.

        >>> staff = abjad.Staff(r"c'1 d'1")
        >>> abjad.f(staff)
        \new Staff
        {
            c'1
            d'1
        }

        .. figure:: ../_images/enforce_time_signature-9bf9zmnm19k.png

        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     abjad.TimeSignature((2, 4))
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \time 2/4
            c'2
            ~
            c'2
            d'2
            ~
            d'2
        }

        .. figure:: ../_images/enforce_time_signature-kerf9uos62i.png

    .. note::

        Auxjad automatically adds this function as an extension method to
        |abjad.mutate()|. It can thus be used from either
        :func:`auxjad.mutate()` or |abjad.mutate()|. Therefore, the two lines
        below are equivalent:

        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     abjad.TimeSignature((2, 4))
        ... )
        >>> abjad.mutate(staff).enforce_time_signature(
        ...     abjad.TimeSignature((2, 4))
        ... )

    Single value for second positional argument:
        The second positional argument can take either |abjad.TimeSignature|
        or a :obj:`tuple` for a single time signature (for multiple time
        signatures, use a :obj:`list` as shown further below). By default,
        rests will be appended to the end of the staff if necessary.

        >>> staff = abjad.Staff(r"c'1 d'1")
        >>> abjad.f(staff)
        \new Staff
        {
            c'1
            d'1
        }

        .. figure:: ../_images/enforce_time_signature-218f65bsco3.png

        >>> auxjad.mutate(staff).enforce_time_signature((3, 4))
        >>> abjad.f(staff)
        \new Staff
        {
            \time 3/4
            c'2.
            ~
            c'4
            d'2
            ~
            d'2
            r4
        }

        .. figure:: ../_images/enforce_time_signature-u4p457k6ib7.png

    ``close_container``:
        Set the optional keyword argument ``close_container`` to ``True`` in
        order to adjust the last measure's time signature instead of filling it
        with rests.

        >>> staff = abjad.Staff(r"c'1 d'1 e'1 f'1")
        >>> abjad.f(staff)
        \new Staff
        {
            c'1
            d'1
            e'1
            f'1
        }

        .. figure:: ../_images/enforce_time_signature-tn1l53yimir.png

        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     abjad.TimeSignature((3, 4)),
        ...     close_container=True,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \time 3/4
            c'2.
            ~
            c'4
            d'2
            ~
            d'2
            e'4
            ~
            e'2.
            f'2.
            ~
            \time 1/4
            f'4
        }

        .. figure:: ../_images/enforce_time_signature-1uhp08fqlpl.png

    ``fill_with_rests``:
        Alternatively, to leave the last measure as it is input (i.e. not
        filling it with rests nor adjusting the time signature), set the
        optional keyword argument ``fill_with_rests`` to ``False`` (default
        value is ``True``).

        >>> staff = abjad.Staff(r"c'1 d'1 e'1 f'1")
        >>> abjad.f(staff)
        \new Staff
        {
            c'1
            d'1
            e'1
            f'1
        }

        .. figure:: ../_images/enforce_time_signature-bit2y19hncr.png

        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     abjad.TimeSignature((3, 4)),
        ...     fill_with_rests=False,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \time 3/4
            c'2.
            ~
            c'4
            d'2
            ~
            d'2
            e'4
            ~
            e'2.
            f'2.
            ~
            f'4
        }

        .. figure:: ../_images/enforce_time_signature-xo7fpeqsoek.png

    Multiple values for second positional argument:
        The second argument can also take a :obj:`list` of
        |abjad.TimeSignature| or :obj:`tuple`.

        >>> staff = abjad.Staff(r"c'1 d'1")
        >>> abjad.f(staff)
        \new Staff
        {
            c'1
            d'1
        }

        .. figure:: ../_images/enforce_time_signature-rl1csjn9osl.png

        >>> time_signatures = [abjad.TimeSignature((3, 4)),
        ...                    abjad.TimeSignature((5, 4)),
        ...                    ]
        >>> auxjad.mutate(staff).enforce_time_signature(time_signatures)
        >>> abjad.f(staff)
        \new Staff
        {
            \time 3/4
            c'2.
            ~
            \time 5/4
            c'4
            d'1
        }

        .. figure:: ../_images/enforce_time_signature-tqqrqi34bu.png

    Repeated time signatures:
        Consecutive identical time signatures are omitted. Also note that time
        signatures can also be represented as a :obj:`list` of :obj:`tuple`'s.

        >>> staff = abjad.Staff(r"c'1 d'1 e'1 f'1")
        >>> abjad.f(staff)
        \new Staff
        {
            c'1
            d'1
            e'1
            f'1
        }

        .. figure:: ../_images/enforce_time_signature-vn9ngz2k6cd.png

        >>> time_signatures = [(2, 4),
        ...                    (2, 4),
        ...                    (4, 4),
        ...                    ]
        >>> auxjad.mutate(staff).enforce_time_signature(time_signatures)
        >>> abjad.f(staff)
        \new Staff
        {
            \time 2/4
            c'2
            ~
            c'2
            \time 4/4
            d'1
            e'1
            f'1
        }

        .. figure:: ../_images/enforce_time_signature-nj2c90o0pe.png

        Alternatively, use ``None`` to indicate repeated time signatures:

        >>> staff = abjad.Staff(r"c'1 d'1 e'1 f'1")
        >>> abjad.f(staff)
        \new Staff
        {
            c'1
            d'1
            e'1
            f'1
        }

        .. figure:: ../_images/enforce_time_signature-2og5ld8bkxe.png

        >>> time_signatures = [(2, 4),
        ...                    None,
        ...                    None,
        ...                    (3, 4),
        ...                    None,
        ...                    (4, 4),
        ...                    ]
        >>> auxjad.mutate(staff).enforce_time_signature(time_signatures)
        >>> abjad.f(staff)
        \new Staff
        {
            \time 2/4
            c'2
            ~
            c'2
            d'2
            ~
            \time 3/4
            d'2
            e'4
            ~
            e'2.
            \time 4/4
            f'1
        }

        .. figure:: ../_images/enforce_time_signature-3s9h7p1k05x.png

    ``cyclic``:
        To cycle through the :obj:`list` of time signatures until the container
        is exhausted, set the optional keyword argument ``cyclic`` to ``True``.

        >>> staff = abjad.Staff(r"c'1 d'1 e'1 f'1")
        >>> abjad.f(staff)
        \new Staff
        {
            c'1
            d'1
            e'1
            f'1
        }

        .. figure:: ../_images/enforce_time_signature-vl1bwp21saq.png

        >>> time_signatures = [abjad.TimeSignature((3, 8)),
        ...                    abjad.TimeSignature((2, 8)),
        ...                    ]
        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     time_signatures,
        ...     cyclic=True,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \time 3/8
            c'4.
            ~
            \time 2/8
            c'4
            ~
            \time 3/8
            c'4.
            \time 2/8
            d'4
            ~
            \time 3/8
            d'4.
            ~
            \time 2/8
            d'4
            ~
            \time 3/8
            d'8
            e'4
            ~
            \time 2/8
            e'4
            ~
            \time 3/8
            e'4.
            ~
            \time 2/8
            e'8
            f'8
            ~
            \time 3/8
            f'4.
            ~
            \time 2/8
            f'4
            ~
            \time 3/8
            f'4
            r8
        }

        .. figure:: ../_images/enforce_time_signature-9mq64erlth6.png

    ``disable_rewrite_meter``:
        By default, this function applies the mutation
        |abjad.mutate().rewrite_meter()| to its output.

        >>> staff = abjad.Staff(r"c'1 ~ c'4 r8 d'4. e'4")
        >>> time_signatures = [abjad.TimeSignature((5, 4)),
        ...                    abjad.TimeSignature((3, 4)),
        ...                    ]
        >>> auxjad.mutate(staff).enforce_time_signature(time_signatures)
        >>> abjad.f(staff)
        \new Staff
        {
            \time 5/4
            c'2.
            ~
            c'2
            \time 3/4
            r8
            d'4.
            e'4
        }

        .. figure:: ../_images/enforce_time_signature-xsjbr0vnev9.png

        To disable this, set the keyword argument ``disable_rewrite_meter`` to
        ``True``.

        >>> staff = abjad.Staff(r"c'1 ~ c'4 r8 d'4. e'4")
        >>> time_signatures = [abjad.TimeSignature((5, 4)),
        ...                    abjad.TimeSignature((3, 4)),
        ...                    ]
        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     time_signatures,
        ...     disable_rewrite_meter=True,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \time 5/4
            c'1
            ~
            c'4
            \time 3/4
            r8
            d'4.
            e'4
        }

        .. figure:: ../_images/enforce_time_signature-ezjnpwjd3xu.png

    Tuplets:
        The function handles tuplets, even if they must be split.

        >>> staff = abjad.Staff(r"\times 2/3 {c'2 d'2 e'2} f'1")
        >>> abjad.f(staff)
        \new Staff
        {
            \times 2/3 {
                c'2
                d'2
                e'2
            }
            f'1
        }

        .. figure:: ../_images/enforce_time_signature-v4ndqpmqjk.png

        >>> time_signatures = [abjad.TimeSignature((2, 4)),
        ...                    abjad.TimeSignature((3, 4)),
        ...                    ]
        >>> auxjad.mutate(staff).enforce_time_signature(time_signatures)
        >>> abjad.f(staff)
        \new Staff
        {
            \times 2/3 {
                \time 2/4
                c'2
                d'4
                ~
            }
            \times 2/3 {
                \time 3/4
                d'4
                e'2
            }
            f'4
            ~
            f'2.
        }

        .. figure:: ../_images/enforce_time_signature-5jdoukq2rkd.png

    Time signatures in the input container:
        Note that any time signatures in the input container will be ignored.

        >>> staff = abjad.Staff(r"\time 3/4 c'2. d'2. e'2. f'2.")
        >>> abjad.f(staff)
        \new Staff
        {
            \time 3/4
            c'2.
            d'2.
            e'2.
            f'2.
        }

        .. figure:: ../_images/enforce_time_signature-bnnz1hov5bu.png

        >>> time_signatures = [abjad.TimeSignature((5, 8)),
        ...                    abjad.TimeSignature((1, 16)),
        ...                    abjad.TimeSignature((2, 4)),
        ...                    ]
        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     time_signatures,
        ...     cyclic=True,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \time 5/8
            c'4.
            ~
            c'4
            ~
            \time 1/16
            c'16
            ~
            \time 2/4
            c'16
            d'4..
            ~
            \time 5/8
            d'4
            ~
            d'16
            e'16
            ~
            e'4
            ~
            \time 1/16
            e'16
            ~
            \time 2/4
            e'4.
            f'8
            ~
            \time 5/8
            f'4.
            ~
            f'4
        }

        .. figure:: ../_images/enforce_time_signature-2l289r8sdzl.png

    Tweaking |abjad.mutate().rewrite_meter()|:
        This function uses the default logical tie splitting algorithm from
        |abjad.mutate().rewrite_meter()|.

        >>> staff = abjad.Staff(r"c'4. d'8 e'2")
        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     abjad.TimeSignature((4, 4)),
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \time 4/4
            c'4.
            d'8
            e'2
        }

        .. figure:: ../_images/enforce_time_signature-bykbobzx47.png

        Set ``boundary_depth`` to a different number to change its behaviour.

        >>> staff = abjad.Staff(r"c'4. d'8 e'2")
        >>> auxjad.mutate(staff).enforce_time_signature(
        ...     abjad.TimeSignature((4, 4)),
        ...     boundary_depth=1,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \time 4/4
            c'4
            ~
            c'8
            d'8
            e'2
        }

        .. figure:: ../_images/enforce_time_signature-wljhgmjh9c.png

        Other arguments available for tweaking the output of
        |abjad.mutate().rewrite_meter()| are ``maximum_dot_count`` and
        ``rewrite_tuplets``, which work exactly as the identically named
        arguments of |abjad.mutate().rewrite_meter()|.

        This function also accepts the arguments
        ``fuse_across_groups_of_beats``, ``fuse_quadruple_meter``,
        ``fuse_triple_meter``, ``extract_trivial_tuplets``, and
        ``split_quadruple_meter``, which are passed on to
        |auxjad.mutate().prettify_rewrite_meter()| (the latter can be disabled
        by setting ``prettify_rewrite_meter`` to ``False``). See the
        documentation of this function for more details on these arguments.

    .. note::

        When using |abjad.Container|'s, all time signatures in the output will
        be commented out with ``%%%.`` This is because Abjad only applies time
        signatures to containers that belong to a |abjad.Staff|. The present
        function works with either |abjad.Container| and |abjad.Staff|.

        >>> container = abjad.Container(r"\time 3/4 c'4 d'4 e'4")
        >>> abjad.f(container)
        {
            %%% \time 3/4 %%%
            c'4
            d'4
            e'4
        }

        .. figure:: ../_images/enforce_time_signature-ntl3jgbi7j.png

        >>> staff = abjad.Staff([container])
        >>> abjad.f(container)
        {
            \time 3/4
            c'4
            d'4
            e'4
        }

        .. figure:: ../_images/enforce_time_signature-y5sjtx3j0v.png

    .. warning::

        The input container must be a contiguous logical voice. When dealing
        with a container with multiple subcontainers (e.g. a score containing
        multiple staves), the best approach is to cycle through these
        subcontainers, applying this function to them individually.
    """
    if not isinstance(container, abjad.Container):
        raise TypeError("first argument must be 'abjad.Container' or "
                        "child class")
    if not abjad.select(container).leaves().are_contiguous_logical_voice():
        raise ValueError("first argument must be contiguous logical voice")
    if isinstance(time_signatures, list):
        time_signatures_ = time_signatures[:]
    else:
        time_signatures_ = [time_signatures]
    if time_signatures_[0] is None:
        raise ValueError("first element of the input list must not be 'None'")
    # converting all elements to abjad.TimeSignature
    for index, time_signature in enumerate(time_signatures_):
        if time_signature is None:
            previous_ts_duration = time_signatures_[index - 1].pair
            time_signatures_[index] = abjad.TimeSignature(previous_ts_duration)
        elif not isinstance(time_signature, abjad.TimeSignature):
            time_signatures_[index] = abjad.TimeSignature(time_signature)
    partial_time_signature = None
    if time_signatures_[0].partial is not None:
        partial_time_signature = time_signatures_[0]
        time_signatures_[0] = abjad.TimeSignature(
            partial_time_signature.duration)
        partial_element = abjad.TimeSignature(partial_time_signature.partial)
        time_signatures_.insert(0, partial_element)
    if not isinstance(cyclic, bool):
        raise TypeError("'cyclic' must be 'bool'")
    if not isinstance(fill_with_rests, bool):
        raise TypeError("'fill_with_rests' must be 'bool'")
    if not isinstance(close_container, bool):
        raise TypeError("'close_container' must be 'bool'")
    if not isinstance(disable_rewrite_meter, bool):
        raise TypeError("'disable_rewrite_meter' must be 'bool'")
    if boundary_depth is not None:
        if not isinstance(boundary_depth, int):
            raise TypeError("'boundary_depth' must be 'int'")
    if maximum_dot_count is not None:
        if not isinstance(maximum_dot_count, int):
            raise TypeError("'maximum_dot_count' must be 'int'")
    if not isinstance(rewrite_tuplets, bool):
        raise TypeError("'rewrite_tuplets' must be 'bool'")
    if not isinstance(split_quadruple_meter, bool):
        raise TypeError("'split_quadruple_meter' must be 'bool'")
    # remove all time signatures from container
    for leaf in abjad.select(container).leaves():
        if abjad.inspect(leaf).indicators(abjad.TimeSignature):
            abjad.detach(abjad.TimeSignature, leaf)
    # slice container at the places where time signatures change
    durations = [
        time_signature.duration for time_signature in time_signatures_
    ]
    if not cyclic:
        while sum(durations) < abjad.inspect(container).duration():
            durations.append(durations[-1])
    abjad.mutate(container[:]).split(durations, cyclic=cyclic)
    # attach new time signatures
    previous_ts = None
    index = 0
    duration = abjad.Duration(0)
    previous_ts_duration = abjad.Duration(0)
    for leaf in abjad.select(container).leaves():
        if duration == previous_ts_duration:
            duration = abjad.Duration(0)
            previous_ts_duration = durations[index]
            if partial_time_signature is not None and index in (0, 1):
                ts = partial_time_signature
            else:
                ts = time_signatures_[index]
            if ts != previous_ts:
                abjad.attach(ts, leaf)
            previous_ts = ts
            index += 1
            if index == len(time_signatures_):
                if cyclic:
                    index = 0
                else:
                    break
        duration += abjad.inspect(leaf).duration()
    # filling with rests or closing container
    if close_container:
        close_container_function(container)
    elif fill_with_rests:
        fill_with_rests_function(
            container,
            disable_rewrite_meter=disable_rewrite_meter,
        )
    # rewrite meter
    if not disable_rewrite_meter:
        measures = abjad.select(container[:]).group_by_measure()
        if cyclic:
            pattern = time_signatures_[:]
            while len(time_signatures_) < len(measures):
                time_signatures_ += pattern[:]
        else:
            while len(time_signatures_) < len(measures):
                time_signatures_.append(time_signatures_[-1])
        auto_rewrite_meter(
            container,
            meter_list=time_signatures_,
            boundary_depth=boundary_depth,
            maximum_dot_count=maximum_dot_count,
            rewrite_tuplets=rewrite_tuplets,
            prettify_rewrite_meter=prettify_rewrite_meter,
            extract_trivial_tuplets=extract_trivial_tuplets,
            fuse_across_groups_of_beats=fuse_across_groups_of_beats,
            fuse_quadruple_meter=fuse_quadruple_meter,
            fuse_triple_meter=fuse_triple_meter,
            split_quadruple_meter=split_quadruple_meter,
        )
Пример #40
0
def test_Mutation_split_13():
    """
    Splits cyclically.
    """

    voice = abjad.Voice([abjad.Container("c'8 d'8 e'8 f'8 g'8 a'8 b'8 c''8")])
    leaves = abjad.select(voice).leaves()
    abjad.beam(leaves)
    abjad.slur(leaves)

    assert format(voice) == abjad.String.normalize(r"""
        \new Voice
        {
            {
                c'8
                [
                (
                d'8
                e'8
                f'8
                g'8
                a'8
                b'8
                c''8
                )
                ]
            }
        }
        """), print(format(voice))

    note = voice[0]
    result = abjad.mutate(note).split(
        [abjad.Duration(1, 8), abjad.Duration(3, 8)], cyclic=True)

    assert format(voice) == abjad.String.normalize(r"""
        \new Voice
        {
            {
                c'8
                [
                (
            }
            {
                d'8
                e'8
                f'8
            }
            {
                g'8
            }
            {
                a'8
                b'8
                c''8
                )
                ]
            }
        }
        """), print(format(voice))

    assert abjad.inspect(voice).wellformed()
Пример #41
0
def test_Mutation_split_02():
    """
    Cyclically splits consecutive notes in score.
    """

    staff = abjad.Staff(r"abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 |")
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves[:2])
    abjad.beam(leaves[-2:])
    abjad.slur(leaves)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'8
                [
                (
                d'8
                ]
            }
            {
                \time 2/8
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    result = abjad.mutate(leaves).split([abjad.Duration(3, 32)], cyclic=True)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'16.
                [
                (
                ~
                c'32
                d'16
                ~
                d'16
                ]
            }
            {
                \time 2/8
                e'32
                [
                ~
                e'16.
                f'16.
                ~
                f'32
                )
                ]
            }
        }
        """), print(format(staff))

    assert abjad.inspect(staff).wellformed()
    assert len(result) == 6
Пример #42
0
        # knows the name of the voice the timespan should be used for.
        # This double-reference to the voice is redundant here, but in a
        # different implementation we could put *all* the timespans into
        # one timespan list, split them, whatever, and still know which
        # voice they belong to because their annotation records that
        # information.
        durations = [timespan.duration for timespan in grouper]
        container = make_container(music_maker, durations)
        voice = score[voice_name]
        voice.append(container)

print("Splitting and rewriting ...")

# split and rewite meters
for voice in abjad.iterate(score["Staff Group 1"]).components(abjad.Voice):
    for i, shard in enumerate(abjad.mutate(voice[:]).split(time_signatures)):
        time_signature = time_signatures[i]
        abjad.mutate(shard).rewrite_meter(time_signature)

print("Beaming runs ...")

for voice in abjad.select(score).components(abjad.Voice):
    for run in abjad.select(voice).runs():
        if 1 < len(run):
            # use a beam_specifier to remove beam indicators from run
            specifier = abjadext.rmakers.BeamSpecifier(
                beam_each_division=False)
            specifier(run)
            # then attach new indicators at the 0 and -1 of run
            abjad.attach(abjad.StartBeam(), run[0])
            abjad.attach(abjad.StopBeam(), run[-1])
Пример #43
0
def test_Mutation_copy_07():

    staff = abjad.Staff("abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 |"
                        "| 2/8 g'8 a'8 || 2/8 b'8 c''8 |")
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves)
    abjad.slur(leaves)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'8
                [
                (
                d'8
            }
            {
                \time 2/8
                e'8
                f'8
            }
            {
                \time 2/8
                g'8
                a'8
            }
            {
                \time 2/8
                b'8
                c''8
                )
                ]
            }
        }
        """), print(format(staff))

    result = abjad.mutate(staff[-2:]).copy()
    new_staff = abjad.Staff(result)

    assert format(new_staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                g'8
                a'8
            }
            {
                \time 2/8
                b'8
                c''8
                )
                ]
            }
        }
        """), print(format(new_staff))

    assert abjad.inspect(staff).wellformed()
    assert abjad.inspect(new_staff).wellformed()
Пример #44
0
def auto_rewrite_meter(
    container: abjad.Container,
    meter_list: Optional[list[Union[abjad.Meter,
                                    abjad.TimeSignature, ]]] = None,
    *,
    prettify_rewrite_meter: bool = True,
    extract_trivial_tuplets: bool = True,
    fuse_across_groups_of_beats: bool = True,
    fuse_quadruple_meter: bool = True,
    fuse_triple_meter: bool = True,
    boundary_depth: Optional[int] = None,
    maximum_dot_count: Optional[int] = None,
    rewrite_tuplets: bool = True,
    merge_partial_tuplets: bool = True,
    split_quadruple_meter: bool = True,
) -> None:
    r"""Mutates an input container (of type |abjad.Container| or child class)
    in place and has no return value; this function takes every measure of a
    container, detects its time signature, and apply both
    |abjad.mutate().rewrite_meter()| and
    |auxjad.mutate().prettify_rewrite_meter()| to it.

    Basic usage:
        For this example, the following container will be mutated:

        >>> staff = abjad.Staff(r"c'16 d'8 e'16 f'8 g'4 a'4 b'8 "
        ...                     r"c'16 d'4. e'16 f'8 g'4 a'16 b'16")
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            d'8
            e'16
            f'8
            g'4
            a'4
            b'8
            c'16
            d'4.
            e'16
            f'8
            g'4
            a'16
            b'16
        }

        .. figure:: ../_images/auto_rewrite_meter-xyx2wh7ufer.png

        Abjad's |abjad.mutate().rewrite_meter()| mutates an |abjad.Selection|
        of a measure, improving its notation.

        >>> for measure in abjad.select(staff[:]).group_by_measure():
        ...     abjad.mutate(measure).rewrite_meter(abjad.Meter((4, 4)))
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            d'16
            ~
            d'16
            e'16
            f'8
            g'8
            ~
            g'8
            a'8
            ~
            a'8
            b'8
            c'16
            d'8.
            ~
            d'8.
            e'16
            f'8
            g'8
            ~
            g'8
            a'16
            b'16
        }

        .. figure:: ../_images/auto_rewrite_meter-7fn2uj2xupb.png

        This function mutates an |abjad.Container| (or child class),
        identifying the implied meters of each measure and applying both
        |abjad.mutate().rewrite_meter()| and
        |auxjad.mutate().prettify_rewrite_meter()| to it. See the documentation
        of the latter for a detailed explanation of what it does.

        Applying |auxjad.mutate().auto_rewrite_meter()| to the same initial
        container shown in the first figure above outputs:

        >>> staff = abjad.Staff(r"c'16 d'8 e'16 f'8 g'4 a'4 b'8 "
        ...                     r"c'16 d'4. e'16 f'8 g'4 a'16 b'16")
        >>> auxjad.mutate(staff).auto_rewrite_meter()
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            d'8
            e'16
            f'8
            g'8
            ~
            g'8
            a'4
            b'8
            c'16
            d'8.
            ~
            d'8.
            e'16
            f'8
            g'4
            a'16
            b'16
        }

        .. figure:: ../_images/auto_rewrite_meter-ahdaggaiqbc.png

    .. note::

        Auxjad automatically adds this function as an extension method to
        |abjad.mutate()|. It can thus be used from either
        :func:`auxjad.mutate()` or |abjad.mutate()|. Therefore, the two lines
        below are equivalent:

        >>> auxjad.mutate(staff).auto_rewrite_meter()
        >>> abjad.mutate(staff).auto_rewrite_meter()

    Time signature changes:
        It automatically handles time signature changes.

        >>> staff = abjad.Staff(r"c'16 d'8 e'16 f'8 g'4 a'4 b'8 "
        ...                     r"\time 6/8 b'4 c''4 r4 ")
        >>> auxjad.mutate(staff).auto_rewrite_meter()
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            d'8
            e'16
            f'8
            g'8
            ~
            g'8
            a'4
            b'8
            \time 6/8
            b'4
            c''8
            ~
            c''8
            r4
        }

        .. figure:: ../_images/auto_rewrite_meter-08sckfp19vil.png

    ``prettify_rewrite_meter``:
        By default, this function invokes both |abjad.mutate().rewrite_meter()|
        and |auxjad.mutate().prettify_rewrite_meter()|.

        >>> staff = abjad.Staff(r"c'16 d'8 e'16 f'8 g'4 a'4 b'8 "
        ...                     r"c'16 d'8 e'16 f'8 g'4 a'4 b'8")
        >>> auxjad.mutate(staff).auto_rewrite_meter()
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            d'8
            e'16
            f'8
            g'8
            ~
            g'8
            a'4
            b'8
            c'16
            d'8
            e'16
            f'8
            g'8
            ~
            g'8
            a'4
            b'8
        }

        .. figure:: ../_images/auto_rewrite_meter-vbytyszlkng.png

        Set ``prettify_rewrite_meter`` to ``False`` to not invoke
        |auxjad.mutate().prettify_rewrite_meter()|.

        >>> staff = abjad.Staff(r"c'16 d'8 e'16 f'8 g'4 a'4 b'8 "
        ...                     r"c'16 d'4. e'16 f'8 g'4 a'16 b'16")
        >>> auxjad.mutate(staff).auto_rewrite_meter(
        ...     prettify_rewrite_meter=False,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            c'16
            d'16
            ~
            d'16
            e'16
            f'8
            g'8
            ~
            g'8
            a'8
            ~
            a'8
            b'8
            c'16
            d'8.
            ~
            d'8.
            e'16
            f'8
            g'8
            ~
            g'8
            a'16
            b'16
        }

        .. figure:: ../_images/auto_rewrite_meter-64wse58hvko.png

    ``meter_list``:
        When no ``meter_list`` is supplied, this function detects the time
        signature of each measure and uses those when rewritting it:

        >>> staff = abjad.Staff(r"\time 7/4 c'8 d'4 e'4 f'4 g'4 a'4 b'4 c''8 "
        ...                     r"\time 5/4 d''8 e''4 f''4 g''4 a''4 b''8")
        >>> auxjad.mutate(staff).auto_rewrite_meter()
        >>> abjad.f(staff)
        \new Staff
        {
            \time 7/4
            c'8
            d'4
            e'4
            f'8
            ~
            f'8
            g'4
            a'8
            ~
            a'8
            b'4
            c''8
            \time 5/4
            d''8
            e''4
            f''4
            g''8
            ~
            g''8
            a''4
            b''8
        }

        .. figure:: ../_images/auto_rewrite_meter-l4xnpevp3z.png

        To use a custom list of meters (one for each measure), set
        ``meter_list`` to a :obj:`list` of |abjad.Meter|'s or
        |abjad.TimeSignature|'s.

        >>> staff = abjad.Staff(r"\time 7/4 c'8 d'4 e'4 f'4 g'4 a'4 b'4 c''8 "
        ...                     r"\time 5/4 d''8 e''4 f''4 g''4 a''4 b''8")
        >>> meter_list = [abjad.Meter((7, 4), increase_monotonic=True),
        ...               abjad.Meter((5, 4), increase_monotonic=True),
        ...               ]
        >>> auxjad.mutate(staff).auto_rewrite_meter(meter_list=meter_list)
        >>> abjad.f(staff)
        \new Staff
        {
            \time 7/4
            c'8
            d'4
            e'8
            ~
            e'8
            f'4
            g'8
            ~
            g'8
            a'4
            b'4
            c''8
            \time 5/4
            d''8
            e''4
            f''8
            ~
            f''8
            g''4
            a''4
            b''8
        }

        .. figure:: ../_images/auto_rewrite_meter-uqif4i8tqxk.png

    Number of measures:
        This function handles a container with any number of measures and any
        number of time signature changes:

        >>> staff = abjad.Staff(
        ...     r"\time 3/4 c'8 d'4 e'4 f'8 "
        ...     r"\time 5/8 g'4 a'4 r8 "
        ...     r"\time 6/8 b'4 c''4 r4 "
        ...     r"\time 4/4 d''8 e''4 f''8 g''16 a''4 r8."
        ... )
        >>> auxjad.mutate(staff).auto_rewrite_meter()
        >>> abjad.f(staff)
        \new Staff
        {
            \time 3/4
            c'8
            d'4
            e'4
            f'8
            \time 5/8
            g'4
            a'8
            ~
            a'8
            r8
            \time 6/8
            b'4
            c''8
            ~
            c''8
            r4
            \time 4/4
            d''8
            e''4
            f''8
            g''16
            a''8.
            ~
            a''16
            r8.
        }

        .. figure:: ../_images/auto_rewrite_meter-hkhtqnqita.png

    ``extract_trivial_tuplets``:
        By default, tuplets filled with rests or tied notes or chords are
        extracted:

        >>> staff = abjad.Staff(
        ...     r"\times 2/3 {c'4 ~ c'8} \times 2/3 {d'8 r4} "
        ...     r"\times 2/3 {r8 r8 r8} \times 2/3 {<e' g'>8 ~ <e' g'>4}"
        ... )
        >>> auxjad.mutate(staff).auto_rewrite_meter()
        >>> abjad.f(staff)
        \new Staff
        {
            c'4
            \times 2/3 {
                d'8
                r4
            }
            r4
            <e' g'>4
        }

        .. figure:: ../_images/auto_rewrite_meter-nq6t6qwka7a.png

        Set ``extract_trivial_tuplets`` to ``False`` to disable this behaviour.

        >>> staff = abjad.Staff(
        ...     r"\times 2/3 {c'4 ~ c'8} \times 2/3 {d'8 r4} "
        ...     r"\times 2/3 {r8 r8 r8} \times 2/3 {<e' g'>8 ~ <e' g'>4}"
        ... )
        >>> auxjad.mutate(staff).auto_rewrite_meter(
        ...     extract_trivial_tuplets=False,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \times 2/3 {
                c'4.
            }
            \times 2/3 {
                d'8
                r4
            }
            \times 2/3 {
                r4.
            }
            \times 2/3 {
                <e' g'>4.
            }
        }

        .. figure:: ../_images/auto_rewrite_meter-ssnsui7o9cc.png

    ``merge_partial_tuplets``:
        By default, consecutive partial tuplets with the same ratio that sum up
        to an assignable duration will be merged together:

        >>> staff = abjad.Staff(r"\times 2/3 {c'2 d'1}"
        ...                     r"\times 2/3 {e'2} \times 2/3 {f'1}"
        ...                     )
        >>> auxjad.mutate(staff).auto_rewrite_meter()
        >>> abjad.f(staff)
        \new Staff
        {
            \times 2/3 {
                c'2
                d'1
            }
            \times 2/3 {
                e'2
                f'1
            }
        }

        .. figure:: ../_images/auto_rewrite_meter-ty72t5wvc1.png

        Set ``merge_partial_tuplets`` to ``False`` to disable this behaviour.

        >>> staff = abjad.Staff(r"\times 2/3 {c'2 d'1}"
        ...                     r"\times 2/3 {e'2} \times 2/3 {f'1}"
        ...                     )
        >>> auxjad.mutate(staff).auto_rewrite_meter(
        ...     merge_partial_tuplets=False,
        ... )
        >>> abjad.f(staff)
        \new Staff
        {
            \times 2/3 {
                c'2
                d'1
            }
            \tweak edge-height #'(0.7 . 0)
            \times 2/3 {
                e'2
            }
            \tweak edge-height #'(0.7 . 0)
            \times 2/3 {
                f'1
            }
        }

        .. figure:: ../_images/auto_rewrite_meter-4rouf819bjb.png

    .. note::

        This function also accepts the arguments ``boundary_depth``,
        ``maximum_dot_count``, and ``rewrite_tuplets``, which are passed on to
        |abjad.mutate().rewrite_meter()|, and ``fuse_across_groups_of_beats``,
        ``fuse_quadruple_meter``, ``fuse_triple_meter``, and
        ``split_quadruple_meter``, which are passed on to
        |auxjad.mutate().prettify_rewrite_meter()|. ``merge_partial_tuplets``
        is used to invoke |auxjad.mutate().merge_partial_tuplets()| See the
        documentation of these functions for more details on these arguments.

    .. warning::

        Setting ``boundary_depth`` to a value equal to or larger than ``1``
        will automatically disable ``fuse_across_groups_of_beats``,
        ``fuse_quadruple_meter``, and ``fuse_triple_meter``, regardless of
        their values. This is because when any of those arguments is ``True``,
        |auxjad.mutate().prettify_rewrite_meter()| will fuse across beats,
        which goes against the purpose of using ``boundary_depth``. Compare the
        results below. In the first case, simply applying
        |auxjad.mutate().prettify_rewrite_meter()| with no arguments results in
        some logical ties being tied across beats.

        >>> staff = abjad.Staff(r"\time 4/4 c'4. d'4. e'4 f'8 g'4 a'4 b'4.")
        >>> meter = abjad.Meter((4, 4))
        >>> for measure in abjad.select(staff[:]).group_by_measure():
        ...     abjad.mutate(measure).rewrite_meter(meter, boundary_depth=1)
        >>> for measure in abjad.select(staff[:]).group_by_measure():
        ...     auxjad.mutate(measure).prettify_rewrite_meter(meter)
        >>> abjad.f(staff)
        \new Staff
        {
            \time 4/4
            c'4
            ~
            c'8
            d'8
            ~
            d'4
            e'4
            f'8
            g'4
            a'8
            ~
            a'8
            b'8
            ~
            b'4
        }

        .. figure:: ../_images/auto_rewrite_meter-cf09ysj16fo.png

        By automatically setting all ``fuse_across_groups_of_beats``,
        ``fuse_quadruple_meter``, and  ``fuse_triple_meter` to ``False`` when
        ``boundary_depth`` is equal to or larger than ``1``, this function will
        not fuse those leaves against the required boundary depth.

        >>> staff = abjad.Staff(r"\time 4/4 c'4. d'4. e'4 f'8 g'4 a'4 b'4.")
        >>> auxjad.mutate(staff).auto_rewrite_meter(boundary_depth=1)
        >>> abjad.f(staff)
        \new Staff
        {
            \time 4/4
            c'4
            ~
            c'8
            d'8
            ~
            d'4
            e'4
            f'8
            g'8
            ~
            g'8
            a'8
            ~
            a'8
            b'8
            ~
            b'4
        }

        .. figure:: ../_images/auto_rewrite_meter-mm9xvmaqwfj.png
    """
    if not isinstance(container, abjad.Container):
        raise TypeError("first positional argument must be 'abjad.Container' "
                        "or child class")
    if meter_list is not None:
        if not isinstance(meter_list, list):
            raise TypeError("'meter_list' must be a 'list' of 'abjad.Meter' "
                            "or 'abjad.TimeSignature'")
        else:
            for meter in meter_list:
                if not isinstance(meter, (abjad.Meter, abjad.TimeSignature)):
                    raise TypeError("elements of 'meter_list' must be "
                                    "'abjad.Meter' or 'abjad.TimeSignature'")
                if isinstance(meter, abjad.TimeSignature):
                    meter = abjad.Meter(meter.pair)
    if not isinstance(prettify_rewrite_meter, bool):
        raise TypeError("'prettify_rewrite_meter' must be 'bool'")
    if not isinstance(fuse_across_groups_of_beats, bool):
        raise TypeError("'fuse_across_groups_of_beats' must be 'bool'")
    if not isinstance(fuse_quadruple_meter, bool):
        raise TypeError("'fuse_quadruple_meter' must be 'bool'")
    if not isinstance(fuse_triple_meter, bool):
        raise TypeError("'fuse_triple_meter' must be 'bool'")
    if boundary_depth is not None:
        if not isinstance(boundary_depth, int):
            raise TypeError("'boundary_depth' must be 'int'")
    if maximum_dot_count is not None:
        if not isinstance(maximum_dot_count, int):
            raise TypeError("'maximum_dot_count' must be 'int'")
    if not isinstance(rewrite_tuplets, bool):
        raise TypeError("'rewrite_tuplets' must be 'bool'")
    if not isinstance(merge_partial_tuplets, bool):
        raise TypeError("'merge_partial_tuplets' must be 'bool'")
    if not isinstance(split_quadruple_meter, bool):
        raise TypeError("'split_quadruple_meter' must be 'bool'")

    if merge_partial_tuplets:
        merge_partial_tuplets_function(container[:])
    if extract_trivial_tuplets:
        extract_trivial_tuplets_function(container[:])

    if meter_list is None:
        time_signatures = inspect(container).extract_time_signatures(
            do_not_use_none=True, )
        meter_list = [abjad.Meter(ts.pair) for ts in time_signatures]
    measures = abjad.select(container[:]).group_by_measure()
    for meter, measure in zip(meter_list, measures):
        if isinstance(measure[0], abjad.MultimeasureRest):
            continue
        abjad.mutate(measure).rewrite_meter(
            meter,
            boundary_depth=boundary_depth,
            maximum_dot_count=maximum_dot_count,
            rewrite_tuplets=rewrite_tuplets,
        )
    if prettify_rewrite_meter:
        measures = abjad.select(container[:]).group_by_measure()
        for meter, measure in zip(meter_list, measures):
            if boundary_depth is None or boundary_depth < 1:
                prettify_rewrite_meter_function(
                    measure,
                    meter,
                    fuse_across_groups_of_beats=fuse_across_groups_of_beats,
                    fuse_quadruple_meter=fuse_quadruple_meter,
                    fuse_triple_meter=fuse_triple_meter,
                    extract_trivial_tuplets=False,
                    split_quadruple_meter=split_quadruple_meter,
                )
            else:
                prettify_rewrite_meter_function(
                    measure,
                    meter,
                    fuse_across_groups_of_beats=False,
                    fuse_quadruple_meter=False,
                    fuse_triple_meter=False,
                    extract_trivial_tuplets=False,
                    split_quadruple_meter=False,
                )
Пример #45
0
    leaf_duration = talea[talea_index]
    if leaf_duration > 0:
        pitch = abjad.NamedPitch("c'")
    else:
        pitch = None
    leaf_duration = abs(leaf_duration)
    if (leaf_duration + current_duration) > total_duration:
        leaf_duration = total_duration - current_duration
    current_leaves = abjad.LeafMaker()([pitch], [leaf_duration])
    all_leaves.extend(current_leaves)
    current_duration += leaf_duration
    talea_index += 1

music = abjad.Container(all_leaves)

shards = abjad.mutate(music[:]).split(time_signature_pairs)
for i, shard in enumerate(shards):
    measure = abjad.Measure(time_signature_pairs[i])
    abjad.mutate(shard).wrap(measure)

# pitches = abjad.CyclicTuple(["d'", "a''", "gs'", "fs'"])
# pitches = abjad.CyclicTuple(["c'", "c''"])
# pitches = abjad.CyclicTuple([0, 2, 4, 5, 7, 9, 11, 12])

pitches = abjad.CyclicTuple([0, 3, 7, 12, 7, 3])
logical_ties = abjad.iterate(music).logical_ties(pitched=True)
for i, logical_tie in enumerate(logical_ties):
    pitch = pitches[i]
    for note in logical_tie:
        note.written_pitch = pitch
def test_Container___setitem___08():
    r"""
    Replaces note in one score with container from another score.
    """

    notes = [
        abjad.Note("c'8"),
        abjad.Note("d'8"),
        abjad.Note("e'8"),
        abjad.Note("f'8"),
        abjad.Note("g'8"),
        abjad.Note("a'8"),
        abjad.Note("b'8"),
    ]
    voice_1 = abjad.Voice(notes[:3])
    abjad.beam(voice_1[:])

    assert format(voice_1) == abjad.String.normalize(r"""
        \new Voice
        {
            c'8
            [
            d'8
            e'8
            ]
        }
        """), print(format(voice_1))

    voice_2 = abjad.Voice(notes[3:])
    abjad.mutate(voice_2[1:3]).wrap(abjad.Container())
    leaves = abjad.select(voice_2).leaves()
    leaves = abjad.select(voice_2[1]).leaves()
    abjad.slur(leaves)

    assert format(voice_2) == abjad.String.normalize(r"""
        \new Voice
        {
            f'8
            {
                g'8
                (
                a'8
                )
            }
            b'8
        }
        """), print(format(voice_2))

    voice_1[1] = voice_2[1]

    assert format(voice_1) == abjad.String.normalize(r"""
        \new Voice
        {
            c'8
            [
            {
                g'8
                (
                a'8
                )
            }
            e'8
            ]
        }
        """), print(format(voice_1))

    assert abjad.inspect(voice_1).wellformed()

    assert format(voice_2) == abjad.String.normalize(r"""
        \new Voice
        {
            f'8
            b'8
        }
        """), print(format(voice_2))

    assert abjad.inspect(voice_2).wellformed()
Пример #47
0
divisions = [(4, 8)] * 7
measures = rhythm(divisions)
voz = abjad.Voice(
    measures)  # NEED TO PUT IN A CONTAINER TO SEPARATE WELL THE LOGICAL TIES
logical_ties = abjad.select(voz).leaves().logical_ties(pitched=True)
logical_ties

voz_time = abjad.Voice("s2 s2 s2 s2 s2 s2 s2 s2 s2 s2 s2 s2 s2 s2 s4 s1")
abjad.Staff(voz, voz_time)

time_signatures = []
for item in divisions:
    time_signatures.append(abjad.TimeSignature(item))

abjad.attach(time_signatures[0])
abjad.mutate(measures[:]).split(divisions, cyclic=True)

abjad.show(measures)
selector = abjad.select(measures).leaves()
selector
select = selector.group_by_measure()
for time, measure in zip(time_signatures, measures):
    abjad.mutate(measure).rewrite_meter(
        time,
        maximum_dot_count=2,
    )

score = organi.ScoreTemplate()
score = score()
this = score['Piano_Staff'][0][1]
this.append("c,,4")
Пример #48
0
def test_Mutation_split_05():
    """
    Cyclically splits measure in score.
    """

    staff = abjad.Staff(r"abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 |")
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves[:2])
    abjad.beam(leaves[-2:])
    abjad.slur(leaves)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'8
                [
                (
                d'8
                ]
            }
            {
                \time 2/8
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    measures = staff[:1]
    result = abjad.mutate(measures).split([abjad.Duration(1, 16)], cyclic=True)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'16
                [
                (
                ~
            }
            {
                c'16
            }
            {
                d'16
                ~
            }
            {
                d'16
                ]
            }
            {
                \time 2/8
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    assert abjad.inspect(staff).wellformed()
    assert len(result) == 4
Пример #49
0
def test_Mutation_split_03():
    """
    Cyclically splits note in score.
    """

    staff = abjad.Staff(r"abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 |")
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves[:2])
    abjad.beam(leaves[-2:])
    abjad.slur(leaves)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'8
                [
                (
                d'8
                ]
            }
            {
                \time 2/8
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    notes = staff[0][1:]
    result = abjad.mutate(notes).split([abjad.Duration(1, 32)], cyclic=True)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'8
                [
                (
                d'32
                ~
                d'32
                ~
                d'32
                ~
                d'32
                ]
            }
            {
                \time 2/8
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    assert abjad.inspect(staff).wellformed()
    assert len(result) == 4
Пример #50
0
def merge_rests(time_signature, staff):
    for shard in abj.mutate(staff[:]).split([time_signature], cyclic=True):
        abj.mutate(shard).rewrite_meter(time_signature)
Пример #51
0
def post_process_voice_two(voice_two, score):
    # REGISTER TRANSPOSITION
    abjad.mutate(voice_two).transpose(-12)

    # registers
    abjad.attach(abjad.LilyPondLiteral(r"\override TextScript.outside-staff-priority = #'1100"), voice_two[0])
    register_one = abjad.Markup(
        r"""\scale #'(0.5 . 0.5)
          \column{

            \line{
          \draw-circle #1.1 #0.3 ##t
          \draw-circle #1.1 #0.3 ##f
            }
           \line{
          \draw-circle #1.1 #0.3 ##t
          \draw-circle #1.1 #0.3 ##t
            }
           \line{
          \draw-circle #1.1 #0.3 ##f
          \draw-circle #1.1 #0.3 ##t
            }
           \line{
          \draw-circle #1.1 #0.3 ##f
          \draw-circle #1.1 #0.3 ##f
            }
          }""", direction=abjad.Up)
    abjad.attach(register_one, voice_two[0])

    # metronome mark I
    abjad.attach(
        abjad.MetronomeMark((1, 8), (64, 72), "Lento"), voice_two[0])


    # rehearsal mark
    markI = abjad.RehearsalMark(number=4)
    abjad.attach(markI, voice_two[0])
    scheme = abjad.Scheme("format-mark-box-alphabet")
    abjad.setting(score).markFormatter = scheme
    
    # numbered leaves
    selection = abjad.select(voice_two).leaves()
    for i, leaf in enumerate(selection):
        # abjad.attach(abjad.Markup(i), leaf)
        pass

     # slurs
    start_slur = abjad.StartSlur()
    start_slur_down = abjad.StartSlur(direction=abjad.Down)
    stop_slur = abjad.StopSlur()

    abjad.attach(start_slur, voice_two[6])
    abjad.attach(stop_slur, voice_two[8])

    abjad.attach(abjad.LilyPondLiteral(
        r"""
        \shape #'((0 . 0) (0 . 0) (-1.5 . -3) (0 . -8)) Slur
        """), voice_two[16])
    abjad.attach(start_slur, voice_two[16])
    abjad.attach(stop_slur, voice_two[17])

    abjad.attach(start_slur, voice_two[23])
    abjad.attach(stop_slur, voice_two[25])

    abjad.attach(start_slur, voice_two[26])
    abjad.attach(stop_slur, voice_two[27])

    abjad.attach(start_slur, voice_two[34])
    abjad.attach(stop_slur, voice_two[37])

    abjad.attach(start_slur, voice_two[39])
    abjad.attach(stop_slur, voice_two[40])

    abjad.attach(start_slur, voice_two[43])
    abjad.attach(stop_slur, voice_two[45])

    abjad.attach(abjad.Clef("treble"), voice_two[0])

    # accelerando mark
    accel_text_span = abjad.LilyPondLiteral(
        r'\once \override TextSpanner.bound-details.left.text = "accelerando poco a poco"' + " " +
        r"\once \override TextSpanner.style = #'dashed-line"
        )
    start_accel = abjad.LilyPondLiteral(r"\startTextSpan")
    abjad.attach(accel_text_span, voice_two[-20])
    abjad.attach(start_accel, voice_two[-20])
    stop_accel_text_span = abjad.StopTextSpan(command=r"\stopTextSpan")
    abjad.attach(stop_accel_text_span, voice_two[-1])

    # voice_two.append(abjad.Container(
    #     r"""cs'''2
    #         (
    #         g''8
    #         )
    #         r8
    #         r8
    #         fs'''4
    #         ~
    #         (
    #         fs'''4
    #         g'''8
    #         )
    #     """
    #     ))
    
    voice_two[-1].written_pitch = "af''"
    abjad.attach(abjad.Tie(), voice_two[-1])

    return voice_two
Пример #52
0
def test_Mutation_split_01():
    """
    Cyclically splits note in score.
    """

    staff = abjad.Staff()
    staff.append(abjad.Container("c'8 d'8"))
    staff.append(abjad.Container("e'8 f'8"))
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves[:2])
    abjad.beam(leaves[-2:])
    abjad.slur(leaves)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                c'8
                [
                (
                d'8
                ]
            }
            {
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    notes = staff[0][1:2]
    result = abjad.mutate(notes).split([abjad.Duration(3, 64)], cyclic=True)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                c'8
                [
                (
                d'32.
                ~
                d'32.
                ~
                d'32
                ]
            }
            {
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    assert abjad.inspect(staff).wellformed()
    assert len(result) == 3
def test_Container___setitem___20():
    r"""
    You can use setitem to empty the contents of a container.
    """

    staff = abjad.Staff("c'8 d'8 [ e'8 ] f'8")
    inner_container = abjad.Container()
    abjad.mutate(staff[1:3]).wrap(inner_container)
    outer_container = abjad.Container()
    abjad.mutate(inner_container).wrap(outer_container)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            c'8
            {
                {
                    d'8
                    [
                    e'8
                    ]
                }
            }
            f'8
        }
        """), print(format(staff))

    # sets contents of outer container to nothing
    outer_container[:] = []

    # outer container is empty and remains in score
    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            c'8
            {
            }
            f'8
        }
        """), print(format(staff))

    assert format(inner_container) == abjad.String.normalize(r"""
        {
            d'8
            [
            e'8
            ]
        }
        """), print(format(inner_container))

    # ALTERNATIVE: use del(container)
    staff = abjad.Staff("c'8 d'8 [ e'8 ] f'8")
    inner_container = abjad.Container()
    abjad.mutate(staff[1:3]).wrap(inner_container)
    outer_container = abjad.Container()
    abjad.mutate(inner_container).wrap(outer_container)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            c'8
            {
                {
                    d'8
                    [
                    e'8
                    ]
                }
            }
            f'8
        }
        """), print(format(staff))

    # deletes outer container
    del outer_container[:]

    # outer container is empty and remains in score (as before)
    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            c'8
            {
            }
            f'8
        }
        """), print(format(staff))

    # inner container leaves are still spanned
    assert format(inner_container) == abjad.String.normalize(r"""
        {
            d'8
            [
            e'8
            ]
        }
        """), print(format(inner_container))
Пример #54
0
def test_Mutation_split_11():
    """
    Force-splits consecutive measures in score.
    """

    staff = abjad.Staff(r"abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 |")
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves[:2])
    abjad.beam(leaves[-2:])
    abjad.slur(leaves)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'8
                [
                (
                d'8
                ]
            }
            {
                \time 2/8
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    measures = staff[:]
    result = abjad.mutate(measures).split(
        [abjad.Duration(1, 32),
         abjad.Duration(3, 32),
         abjad.Duration(5, 32)],
        cyclic=False,
        tie_split_notes=False,
    )

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'32
                [
                (
            }
            {
                c'16.
            }
            {
                d'8
                ]
            }
            {
                \time 2/8
                e'32
                [
            }
            {
                e'16.
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    assert abjad.inspect(staff).wellformed()
    assert len(result) == 4
Пример #55
0
 def contents(self) -> abjad.Container:
     r'The |abjad.Container| to be shuffled.'
     return abjad.mutate(self._contents).copy()
Пример #56
0
def test_scoretools_Mutation_fuse_18():
    r'''Fusing measures with power-of-two denominators
    to measures without power-of-two denominators.
    With change in number of note-heads because of non-power-of-two multiplier.
    '''

    measure_1 = abjad.Measure((9, 80), [])
    measure_1.implicit_scaling = True
    measure_1.extend(9 * abjad.Note("c'64"))
    measure_2 = abjad.Measure((2, 16), [])
    measure_2.implicit_scaling = True
    measure_2.extend(2 * abjad.Note("c'16"))
    staff = abjad.Staff([measure_1, measure_2])

    assert format(staff) == abjad.String.normalize(r'''
        \new Staff
        {
            {   % measure
                \time 9/80
                \scaleDurations #'(4 . 5) {
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                }
            }   % measure
            {   % measure
                \time 2/16
                c'16
                c'16
            }   % measure
        }
        ''')

    new = abjad.mutate(staff[:]).fuse()

    assert format(staff) == abjad.String.normalize(r'''
        \new Staff
        {
            {   % measure
                \time 19/80
                \scaleDurations #'(4 . 5) {
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'64
                    c'16
                    ~
                    c'64
                    c'16
                    ~
                    c'64
                }
            }   % measure
        }
        ''')

    assert abjad.inspect(staff).is_well_formed()
Пример #57
0
        # knows the name of the voice the timespan should be used for.
        # This double-reference to the voice is redundant here, but in a
        # different implementation we could put *all* the timespans into
        # one timespan list, split them, whatever, and still know which
        # voice they belong to because their annotation records that
        # information.
        durations = [timespan.duration for timespan in grouper]
        container = make_container(rhythm_maker, durations)
        voice = score[voice_name]
        voice.append(container)

print('Splitting and rewriting ...')

# split and rewite meters
for voice in abjad.iterate(score['Staff Group']).components(abjad.Voice):
    for i, shard in enumerate(abjad.mutate(voice[:]).split(time_signatures)):
        time_signature = time_signatures[i]
        abjad.mutate(shard).rewrite_meter(time_signature)

print('Beautifying score ...')
# cutaway score
for staff in abjad.iterate(score['Staff Group']).components(abjad.Staff):
    for selection in abjad.select(staff).components(
            abjad.Rest).group_by_contiguity():
        start_command = abjad.LilyPondLiteral(
            r'\stopStaff \once \override Staff.StaffSymbol.line-count = #1 \startStaff',
            format_slot='before',
        )
        stop_command = abjad.LilyPondLiteral(
            r'\stopStaff \startStaff',
            format_slot='after',
Пример #58
0
 def current_window(self) -> abjad.Selection:
     r'Read-only property, returns the previously output selection.'
     current_window = abjad.mutate(self._current_window).copy()
     if self._omit_time_signatures:
         self._remove_all_time_signatures(current_window)
     return current_window
Пример #59
0
def test_Mutation_split_12():
    """
    Splits tuplet in score.
    """

    tuplet = abjad.Tuplet((4, 5), "c'8 c'8 c'8 c'8 c'8")
    voice = abjad.Voice([tuplet])
    staff = abjad.Staff([voice])
    abjad.beam(tuplet[:])

    result = abjad.mutate([tuplet]).split([abjad.Duration(1, 5)])

    left = result[0][0]
    right = result[1][0]

    assert format(left) == abjad.String.normalize(r"""
        \tweak edge-height #'(0.7 . 0)
        \times 4/5 {
            c'8
            [
            c'8
        }
        """), print(format(left))

    assert format(right) == abjad.String.normalize(r"""
        \tweak edge-height #'(0.7 . 0)
        \times 4/5 {
            c'8
            c'8
            c'8
            ]
        }
        """), print(format(right))

    assert format(tuplet) == abjad.String.normalize(r"""
        \times 4/5 {
        }
        """), print(format(tuplet))

    assert format(voice) == abjad.String.normalize(r"""
        \new Voice
        {
            \tweak edge-height #'(0.7 . 0)
            \times 4/5 {
                c'8
                [
                c'8
            }
            \tweak edge-height #'(0.7 . 0)
            \times 4/5 {
                c'8
                c'8
                c'8
                ]
            }
        }
        """), print(format(voice))

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            \new Voice
            {
                \tweak edge-height #'(0.7 . 0)
                \times 4/5 {
                    c'8
                    [
                    c'8
                }
                \tweak edge-height #'(0.7 . 0)
                \times 4/5 {
                    c'8
                    c'8
                    c'8
                    ]
                }
            }
        }
        """), print(format(staff))

    assert abjad.inspect(staff).wellformed()
Пример #60
0
def test_Mutation_split_03():
    """
    Cyclically splits containers in score.
    """

    staff = abjad.Staff(r"abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 |")
    leaves = abjad.select(staff).leaves()
    abjad.beam(leaves[:2])
    abjad.beam(leaves[-2:])
    abjad.slur(leaves)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'8
                [
                (
                d'8
                ]
            }
            {
                \time 2/8
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    measures = staff[:1]
    result = abjad.mutate(measures).split([abjad.Duration(3, 32)],
                                          cyclic=True,
                                          tie_split_notes=False)

    assert format(staff) == abjad.String.normalize(r"""
        \new Staff
        {
            {
                \time 2/8
                c'16.
                [
                (
            }
            {
                c'32
                d'16
            }
            {
                d'16
                ]
            }
            {
                \time 2/8
                e'8
                [
                f'8
                )
                ]
            }
        }
        """), print(format(staff))

    assert abjad.inspect(staff).wellformed()