def post_process_voice_four(voice_four, score):
    # print(score['LH_Voice_Four'][-3:])
    del voice_four[-6:]
    voice_four[-2] = abjad.Chord("cs' fs'", (1, 4))
    voice_four[-1] = abjad.Chord("cs' fs'", (3, 4))
    abjad.attach(abjad.Tie(), voice_four[-3])
    abjad.attach(abjad.Tie(), voice_four[-2])
    abjad.attach(abjad.Tie(), voice_four[-1])
    voice_four.extend("<cs'~ fs'>8 cs'4 ~ cs'4.")

    # voice_four[-5].written_duration = (1, 2)
    # del voice_four[-5].note_heads[0]
    # del voice_four[-4].note_heads[0]
    # del voice_four[-3].note_heads[0]
    # del voice_four[-2].note_heads[0]
    # voice_four[-3].written_duration = (1, 8)
    # voice_four[-2].written_duration = (2, 4)
    # del voice_four[-1]
    # voice_four[-2].written_duration = (1, 4)
    # voice_four[-1].written_duration = (3, 8)

    clef_bass = abjad.Clef("bass")
    abjad.attach(clef_bass, voice_four[19])
    # final_chord = abjad.Chord("c e", (3, 4))
    # final_chord.written_pitches = voice_four[-1].written_pitches
    # voice_four.append(final_chord)
    # abjad.attach(abjad.Fermata(), voice_four[-1])

    # REGISTER TRANSPOSITION
    abjad.mutate(voice_four).transpose(-12)
    return voice_four
Пример #2
0
def custom_ties(music):
    tuplets = abjad.select(music).tuplets()
    for tuplet in tuplets:
        leaves = abjad.select(tuplet).leaves()
        for leaf in leaves:
            if not isinstance(leaf, abjad.Rest):
                pitch = [leaf.written_pitch]
                abjad.mutate(leaf).replace(
                    abjad.Chord(pitch, leaf.written_duration))

        leaves2 = abjad.select(tuplet).leaves()
        # print(leaves2)
        for leaf1, leaf2 in zip(leaves2, leaves2[1:]):
            if isinstance(leaf1, abjad.Chord):
                pitch1 = leaf1.written_pitches
                pitch2 = leaf2.written_pitches
                interval = abjad.NumberedPitch(
                    pitch2[0]) - abjad.NumberedPitch(pitch1[0])
                interval = abs(interval.number)
                if interval <= 10 and interval != 0:
                    leaf2.written_pitches = [pitch1[0], pitch2[0]]
    # TIES
    selection = abjad.select(music).leaves().logical_ties()
    # verify next leave to apply ties correctly
    for leave, next_leave in zip(selection, selection[1:]):
        if isinstance(leave[-1], abjad.Note) and isinstance(
                next_leave[0], abjad.Chord):
            # verify if there are same pitches in both leaves
            for item in next_leave[0].written_pitches:
                if item == leave[-1].written_pitch:
                    # print("note-chord tie:" + str(leave[-1]))
                    abjad.attach(abjad.Tie(), leave[-1])
        if isinstance(leave[-1], abjad.Note) and isinstance(
                next_leave[0], abjad.Note):
            if leave[-1].written_pitch == next_leave[0].written_pitch:
                # print("note-note tie:" + str(leave[-1]))
                abjad.attach(abjad.Tie(), leave[-1])
        # if leave is chord
        if isinstance(leave[-1], abjad.Chord) and isinstance(
                next_leave[0], abjad.Chord):
            # verify if there are same pitches in both leaves
            if set(leave[-1].written_pitches) & set(
                    next_leave[0].written_pitches):
                # print("chord-chord tie:" + str(leave[-1]))
                abjad.attach(abjad.Tie(), leave[-1])
        if isinstance(leave[-1], abjad.Chord) and isinstance(
                next_leave[0], abjad.Note):
            for item in leave[-1].written_pitches:
                # print("chord-note tie:" + str(leave[-1]))
                if item == next_leave[0].written_pitch:
                    abjad.attach(abjad.Tie(), leave[-1])
    tuplets = abjad.select(music).tuplets()

    for tuplet in tuplets:
        if tuplet.multiplier == 1:
            abjad.mutate(tuplet).extract()

    return music
Пример #3
0
 def _set_duration(self, new_duration, repeat_ties=False):
     import abjad
     new_duration = abjad.Duration(new_duration)
     # change LilyPond multiplier if leaf already has LilyPond multiplier
     if self._get_indicators(abjad.Multiplier):
         abjad.detach(abjad.Multiplier, self)
         multiplier = new_duration.__div__(self.written_duration)
         abjad.attach(multiplier, self)
         return abjad.select(self)
     # change written duration if new duration is assignable
     try:
         self.written_duration = new_duration
         return abjad.select(self)
     except AssignabilityError:
         pass
     # make new notes or tuplets if new duration is nonassignable
     maker = abjad.NoteMaker(repeat_ties=repeat_ties, )
     components = maker(0, new_duration)
     if isinstance(components[0], abjad.Leaf):
         tied_leaf_count = len(components) - 1
         tied_leaves = tied_leaf_count * self
         all_leaves = [self] + tied_leaves
         for leaf, component in zip(all_leaves, components):
             leaf.written_duration = component.written_duration
         self._splice(tied_leaves, grow_spanners=True)
         parentage = abjad.inspect(self).get_parentage()
         if not abjad.inspect(parentage).get_spanners(abjad.Tie):
             tie = abjad.Tie()
             if tie._attachment_test(self):
                 tie = abjad.Tie(repeat_ties=repeat_ties, )
                 abjad.attach(tie, all_leaves)
         return abjad.select(all_leaves)
     else:
         assert isinstance(components[0], abjad.Tuplet)
         tuplet = components[0]
         components = tuplet[:]
         tied_leaf_count = len(components) - 1
         tied_leaves = tied_leaf_count * self
         all_leaves = [self] + tied_leaves
         for leaf, component in zip(all_leaves, components):
             leaf.written_duration = component.written_duration
         self._splice(tied_leaves, grow_spanners=True)
         if not self._get_spanners(abjad.Tie):
             tie = abjad.Tie()
             if tie._attachment_test(self):
                 tie = abjad.Tie(repeat_ties=repeat_ties, )
                 abjad.attach(tie, all_leaves)
         multiplier = tuplet.multiplier
         tuplet = abjad.Tuplet(multiplier, [])
         abjad.mutate(all_leaves).wrap(tuplet)
         return abjad.select(tuplet)
def test_quantizationtools_QEventSequence_from_tempo_scaled_leaves_02():

    staff = abjad.Staff([])

    staff.append(abjad.Note(0, (1, 4)))
    staff.append(abjad.Rest((1, 4)))
    staff.append(abjad.Rest((1, 8)))
    staff.append(abjad.Note(1, (1, 8)))
    staff.append(abjad.Note(1, (1, 8)))
    staff.append(abjad.Note(2, (1, 8)))
    staff.append(abjad.Note(2, (1, 8)))
    staff.append(abjad.Note(3, (1, 8)))
    staff.append(abjad.Skip((1, 4)))
    staff.append(abjad.Rest((1, 4)))
    staff.append(abjad.Note(3, (1, 8)))
    staff.append(abjad.Chord([0, 1, 4], (1, 4)))

    tie = abjad.Tie()
    abjad.attach(tie, staff[3:5])
    tie = abjad.Tie()
    abjad.attach(tie, staff[5:7])

    tempo = abjad.MetronomeMark((1, 4), 58)
    abjad.attach(tempo, staff[0], context='Staff')
    tempo = abjad.MetronomeMark((1, 4), 77)
    abjad.attach(tempo, staff[9], context='Staff')

    leaves = abjad.select(staff).leaves()
    q_events = quantizationtools.QEventSequence.from_tempo_scaled_leaves(
        leaves)

    assert q_events == quantizationtools.QEventSequence(
        (quantizationtools.PitchedQEvent(abjad.Offset(0, 1),
                                         (abjad.NamedPitch("c'"), )),
         quantizationtools.SilentQEvent(abjad.Offset(30000, 29)),
         quantizationtools.PitchedQEvent(abjad.Offset(75000, 29),
                                         (abjad.NamedPitch("cs'"), )),
         quantizationtools.PitchedQEvent(abjad.Offset(105000, 29),
                                         (abjad.NamedPitch("d'"), )),
         quantizationtools.PitchedQEvent(abjad.Offset(135000, 29),
                                         (abjad.NamedPitch("ef'"), )),
         quantizationtools.SilentQEvent(abjad.Offset(150000, 29)),
         quantizationtools.PitchedQEvent(abjad.Offset(15600000, 2233),
                                         (abjad.NamedPitch("ef'"), )),
         quantizationtools.PitchedQEvent(abjad.Offset(16470000, 2233), (
             abjad.NamedPitch("c'"),
             abjad.NamedPitch("cs'"),
             abjad.NamedPitch("e'"),
         )), quantizationtools.TerminalQEvent(abjad.Offset(18210000, 2233))))
Пример #5
0
def tieitup(held_notes, staff):

    #print "tie held {0}".format(held_notes)

    # don't think i can tie before i add to staff b/c logical voice contiguity error
    # F*****G for now tie is just <yes or no> b/c we can't specify a partial tie

    if held_notes:

        #print "doing one"

        # previous note: last leaf of the previus tuplet
        # F*****G hardcoded assumes everything is a tuplet.
        # not_first_beat = len(staff[-1])!=0
        not_first_beat = len(staff[-1]) != 1
        # print not_first_beat
        # print len(staff)
        # print staff[-1][-1]
        # print 'no'
        last_prev = staff[-1 if not_first_beat else -2][
            -2 if not_first_beat else -1][-1]
        # last_prev = staff[-1 if not_first_beat else -2][-1 if not_first_beat else -1][-1]
        # print last_prev

        # current note: first leaf of the current tuplet
        firs_curr = staff[-1][-1][0]

        # tie them
        abj.attach(abj.Tie(), [last_prev, firs_curr])
Пример #6
0
 def _tie_consecutive_notes_(self, divisions):
     import abjad
     if not self.tie_consecutive_notes:
         return
     leaves = list(abjad.iterate(divisions).leaves())
     for leaf in leaves:
         abjad.detach(abjad.Tie, leaf)
     pairs = itertools.groupby(leaves, lambda _: _.__class__)
     def _get_pitches(component):
         if isinstance(component, abjad.Note):
             return component.written_pitch
         elif isinstance(component, abjad.Chord):
             return component.written_pitches
         else:
             raise TypeError(component)
     for class_, group in pairs:
         group = list(group)
         if not isinstance(group[0], (abjad.Note, abjad.Chord)):
             continue
         subpairs = itertools.groupby(group, lambda _: _get_pitches(_))
         for pitches, subgroup in subpairs:
             subgroup = list(subgroup)
             if len(subgroup) == 1:
                 continue
             tie = abjad.Tie()
             assert tie._attachment_test_all(subgroup) is True
             abjad.attach(tie, abjad.select(subgroup))
Пример #7
0
    def converteToPdf(self, filename):
        # this function will use special lib ans converte markuped array to really Notes notation, then it saves it
        # as pdf
        for note in self.data:
            norm, time = self.abj_duration(note[1])
            if norm:
                if note[0] < 0:
                    self.notes.append(
                        abjad.Rest(
                            abjad.Note(note[0] - BASE_NOTE,
                                       abjad.Duration(time, MIN_NOTE))))
                else:
                    self.notes.append(
                        abjad.Note(note[0] - BASE_NOTE,
                                   abjad.Duration(time, MIN_NOTE)))
            else:
                # beg_tie = len(notes)
                if note[0] < 0:
                    for t in time:
                        self.notes.append(
                            abjad.Rest(
                                abjad.Note(note[0] - BASE_NOTE,
                                           abjad.Duration(t, MIN_NOTE))))
                        # abjad.attach(tie,notes[len(notes)-1])

                else:
                    tie = abjad.Tie()
                    for t in time:
                        self.notes.append(
                            abjad.Note(note[0] - BASE_NOTE,
                                       abjad.Duration(t, MIN_NOTE)))
                        abjad.attach(tie, self.notes[len(self.notes) - 1])
                    del tie
        abjad.persist(self.notes).as_pdf(''.join([PATH_TO_PDF, filename]))
        return filename
Пример #8
0
def _notate_glissando(name: str) -> None:
    staff = abjad.Staff([
        abjad.Note("a'", 3 / 16),
        abjad.Note("a'", 1 / 16),
        abjad.Note("a'", 1 / 8),
        abjad.Note("a'", 1 / 8),
    ])

    abjad.attach(
        abjad.LilyPondLiteral("#(define afterGraceFraction (cons 15 16))"),
        staff[0])
    abjad.attach(
        abjad.LilyPondLiteral('\\override Flag.stroke-style = #"grace"'),
        staff[0],
    )

    for n in (0, 2):
        attachments._GlissandoAttachment._set_glissando_layout(
            staff[n + 1], minimum_length=3)
        abjad.attach(abjad.AfterGraceContainer([abjad.Note("f'", 1 / 8)]),
                     staff[n + 1])
        abjad.attach(abjad.Tie(), staff[n])
        abjad.attach(abjad.StartBeam(), staff[n])
        abjad.attach(abjad.StopBeam(), staff[n + 1])
        abjad.attach(abjad.GlissandoIndicator(), staff[n + 1])

    abjad.attach(lily.mk_no_time_signature(), staff[0])
    abjad.attach(abjad.TimeSignature((len(staff), 1)), staff[0])
    abjad.attach(abjad.Clef("treble"), staff[0])

    sco = abjad.Score([staff])
    lily.make_small_example(sco, name, ragged_last=True, ragged_right=True)
Пример #9
0
 def output_n(
     self,
     n: int,
     *,
     tie_identical_pitches: bool = False,
 ) -> abjad.Selection:
     r"""Goes through ``n`` iterations of the looping process and outputs a
     single |abjad.Selection|.
     """
     if not isinstance(n, int):
         raise TypeError("first positional argument must be 'int'")
     if n < 1:
         raise ValueError("first positional argument must be a positive "
                          "'int'")
     if not isinstance(tie_identical_pitches, bool):
         raise TypeError("'tie_identical_pitches' must be 'bool'")
     dummy_container = abjad.Container()
     for _ in range(n):
         if not tie_identical_pitches or len(dummy_container) == 0:
             dummy_container.append(self.__call__())
         else:
             new_window = self.__call__()
             leaf1 = abjad.select(new_window).leaf(0)
             leaf2 = abjad.select(dummy_container).leaf(-1)
             if get.leaves_are_tieable((leaf1, leaf2)):
                 abjad.attach(abjad.Tie(), dummy_container[-1])
             dummy_container.append(new_window)
     mutate.remove_repeated_time_signatures(dummy_container[:])
     mutate.reposition_dynamics(dummy_container[:])
     output = dummy_container[:]
     dummy_container[:] = []
     return output
Пример #10
0
 def output_all(
     self,
     *,
     tie_identical_pitches: bool = False,
 ) -> abjad.Selection:
     r"""Goes through the whole looping process and outputs a single
     |abjad.Selection|.
     """
     if not isinstance(tie_identical_pitches, bool):
         raise TypeError("'tie_identical_pitches' must be 'bool'")
     dummy_container = abjad.Container()
     while True:
         try:
             if not tie_identical_pitches or len(dummy_container) == 0:
                 dummy_container.append(self.__call__())
             else:
                 new_window = self.__call__()
                 leaf1 = abjad.select(new_window).leaf(0)
                 leaf2 = abjad.select(dummy_container).leaf(-1)
                 if get.leaves_are_tieable((leaf1, leaf2)):
                     abjad.attach(abjad.Tie(), dummy_container[-1])
                 dummy_container.append(new_window)
         except RuntimeError:
             break
     mutate.remove_repeated_time_signatures(dummy_container[:])
     mutate.reposition_dynamics(dummy_container[:])
     output = dummy_container[:]
     dummy_container[:] = []
     return output
Пример #11
0
 def recurse(node, tuplet_duration):
     basic_prolated_duration = \
         tuplet_duration / node._get_contents_duration()
     basic_written_duration = \
         basic_prolated_duration.equal_or_greater_power_of_two
     tuplet = abjad.Tuplet(1, [])
     for child in node.children:
         if isinstance(child, type(self)):
             tuplet.extend(
                 recurse(
                     child, child.preprolated_duration *
                     basic_written_duration))
         else:
             leaves = child(basic_written_duration)
             tuplet.extend(leaves)
             if 1 < len(leaves):
                 tie = abjad.Tie()
                 abjad.attach(tie, leaves)
     assert tuplet.multiplier == 1, repr(tuplet.multiplier)
     contents_duration = abjad.inspect(tuplet).duration()
     target_duration = tuplet_duration
     multiplier = target_duration / contents_duration
     tuplet.multiplier = multiplier
     if tuplet.multiplier == 1:
         return tuplet[:]
     return [tuplet]
Пример #12
0
Файл: part.py Проект: gsy/gmajor
def edit_second_violin_voice(score, durated_reservoir):
    """
    Edits second violin voice.
    """
    voice = score['Second Violin Voice']
    descents = durated_reservoir['Second Violin']
    last_descent = abjad.Selection(descents[-1])
    copied_descent = abjad.mutate(last_descent).copy()
    copied_descent = list(copied_descent)
    copied_descent[-1].written_duration = abjad.Duration(1, 1)
    copied_descent.append(abjad.Note('a2'))
    for leaf in copied_descent:
        articulation = abjad.Articulation('accent')
        abjad.attach(articulation, leaf)
        articulation = abjad.Articulation('tenuto')
        abjad.attach(articulation, leaf)
    voice.extend(copied_descent)
    final_sustain = []
    for _ in range(32):
        final_sustain.append(abjad.Note('a1.'))
    final_sustain.append(abjad.Note('a2'))
    final_sustain = abjad.Selection(final_sustain)
    articulation = abjad.Articulation('accent')
    abjad.attach(articulation, final_sustain[0])
    articulation = abjad.Articulation('tenuto')
    abjad.attach(articulation, final_sustain[0])
    voice.extend(final_sustain)
    tie = abjad.Tie()
    abjad.attach(tie, final_sustain)
    voice.extend('r4 r2.')
def test_lilypondparsertools_LilyPondParser__spanners__Tie_01():

    target = abjad.Container([abjad.Note(0, 1), abjad.Note(0, 1)])
    tie = abjad.Tie()
    abjad.attach(tie, target[:])
    parser = abjad.lilypondparsertools.LilyPondParser()
    result = parser(format(target))
    assert format(target) == format(result) and target is not result
def test_quantizationtools_QEventSequence_from_tempo_scaled_leaves_01():

    staff = abjad.Staff([])

    staff.append(abjad.Note(0, (1, 4)))
    staff.append(abjad.Rest((1, 4)))
    staff.append(abjad.Rest((1, 8)))
    staff.append(abjad.Note(1, (1, 8)))
    staff.append(abjad.Note(1, (1, 8)))
    staff.append(abjad.Note(2, (1, 8)))
    staff.append(abjad.Note(2, (1, 8)))
    staff.append(abjad.Note(3, (1, 8)))
    staff.append(abjad.Skip((1, 4)))
    staff.append(abjad.Rest((1, 4)))
    staff.append(abjad.Note(3, (1, 8)))
    staff.append(abjad.Chord([0, 1, 4], (1, 4)))

    tie = abjad.Tie()
    abjad.attach(tie, staff[3:5])
    tie = abjad.Tie()
    abjad.attach(tie, staff[5:7])

    tempo = abjad.MetronomeMark((1, 4), 55)

    leaves = abjad.select(staff).leaves()
    q_events = quantizationtools.QEventSequence.from_tempo_scaled_leaves(
        leaves, tempo)

    assert q_events == quantizationtools.QEventSequence(
        (quantizationtools.PitchedQEvent(abjad.Offset(0, 1),
                                         (abjad.NamedPitch("c'"), )),
         quantizationtools.SilentQEvent(abjad.Offset(12000, 11)),
         quantizationtools.PitchedQEvent(abjad.Offset(30000, 11),
                                         (abjad.NamedPitch("cs'"), )),
         quantizationtools.PitchedQEvent(abjad.Offset(42000, 11),
                                         (abjad.NamedPitch("d'"), )),
         quantizationtools.PitchedQEvent(abjad.Offset(54000, 11),
                                         (abjad.NamedPitch("ef'"), )),
         quantizationtools.SilentQEvent(abjad.Offset(60000, 11)),
         quantizationtools.PitchedQEvent(abjad.Offset(84000, 11),
                                         (abjad.NamedPitch("ef'"), )),
         quantizationtools.PitchedQEvent(abjad.Offset(90000, 11), (
             abjad.NamedPitch("c'"),
             abjad.NamedPitch("cs'"),
             abjad.NamedPitch("e'"),
         )), quantizationtools.TerminalQEvent(abjad.Offset(102000, 11))))
Пример #15
0
 def _add_or_remove_notes_to_achieve_written_duration(
         self, new_written_duration):
     import abjad
     new_written_duration = abjad.Duration(new_written_duration)
     maker = abjad.NoteMaker()
     if new_written_duration.is_assignable:
         self[0].written_duration = new_written_duration
         for leaf in self[1:]:
             parent = leaf._parent
             if parent:
                 index = parent.index(leaf)
                 del (parent[index])
         first = self[0]
         for spanner in first._get_spanners(abjad.Tie):
             spanner._sever_all_leaves()
         #detach(abjad.Tie, first)
     elif new_written_duration.has_power_of_two_denominator:
         durations = maker(0, [new_written_duration])
         for leaf, token in zip(self, durations):
             leaf.written_duration = token.written_duration
         if len(self) == len(durations):
             pass
         elif len(durations) < len(self):
             for leaf in self[len(durations):]:
                 parent = leaf._parent
                 if parent:
                     index = parent.index(leaf)
                     del (parent[index])
         elif len(self) < len(durations):
             for spanner in self[0]._get_spanners(abjad.Tie):
                 spanner._sever_all_leaves()
             #detach(abjad.Tie, self[0])
             difference = len(durations) - len(self)
             extra_leaves = self[0] * difference
             for extra_leaf in extra_leaves:
                 for spanner in extra_leaf._get_spanners():
                     spanner._remove(extra_leaf)
             extra_tokens = durations[len(self):]
             for leaf, token in zip(extra_leaves, extra_tokens):
                 leaf.written_duration = token.written_duration
             ties = self[-1]._get_spanners(abjad.Tie)
             if not ties:
                 tie = abjad.Tie()
                 if all(tie._attachment_test(_) for _ in self):
                     abjad.attach(tie, self.leaves)
             self[-1]._splice(extra_leaves, grow_spanners=True)
     else:
         durations = maker(0, new_written_duration)
         assert isinstance(durations[0], abjad.Tuplet)
         tuplet = durations[0]
         logical_tie = tuplet[0]._get_logical_tie()
         duration = logical_tie._get_preprolated_duration()
         self._add_or_remove_notes_to_achieve_written_duration(duration)
         multiplier = tuplet.multiplier
         tuplet = abjad.Tuplet(multiplier, [])
         abjad.mutate(self.leaves).wrap(tuplet)
     return self[0]._get_logical_tie()
Пример #16
0
    def _rewrite_meter_and_tie(self, music, time_signature_pairs):
        # I made this separate function because I needed
        # to rewrite meter before to attach ties :/
        time_signatures = []
        for item in time_signature_pairs:
            time_signatures.append(abjad.TimeSignature(item))
        abjad.mutate(music[:]).split(time_signature_pairs, cyclic=True)
        selector = abjad.select(music).leaves()
        measures = selector.group_by_measure()
        for time, measure in zip(time_signatures, measures):
            abjad.mutate(measure).rewrite_meter(time)

        # TIES
        selection = abjad.select(music).leaves().logical_ties()
        # verify next leave to apply ties correctly
        for leave, next_leave in zip(selection, selection[1:]):
            if isinstance(leave[-1], abjad.Note) and isinstance(
                    next_leave[0], abjad.Chord):
                # verify if there are same pitches in both leaves
                for item in next_leave[0].written_pitches:
                    if item == leave[-1].written_pitch:
                        # print("note-chord tie:" + str(leave[-1]))
                        abjad.attach(abjad.Tie(), leave[-1])
            if isinstance(leave[-1], abjad.Note) and isinstance(
                    next_leave[0], abjad.Note):
                if leave[-1].written_pitch == next_leave[0].written_pitch:
                    # print("note-note tie:" + str(leave[-1]))
                    abjad.attach(abjad.Tie(), leave[-1])
            # if leave is chord
            if isinstance(leave[-1], abjad.Chord) and isinstance(
                    next_leave[0], abjad.Chord):
                # verify if there are same pitches in both leaves
                if set(leave[-1].written_pitches) & set(
                        next_leave[0].written_pitches):
                    # print("chord-chord tie:" + str(leave[-1]))
                    abjad.attach(abjad.Tie(), leave[-1])
            if isinstance(leave[-1], abjad.Chord) and isinstance(
                    next_leave[0], abjad.Note):
                for item in leave[-1].written_pitches:
                    # print("chord-note tie:" + str(leave[-1]))
                    if item == next_leave[0].written_pitch:
                        abjad.attach(abjad.Tie(), leave[-1])
        return measures
Пример #17
0
def apply_rhythm(this_notes, spelled_rhythm, rhythm_strings,
                 notes_with_lily_features):

    #print 'notes_with_lily_features {0}'.format(notes_with_lily_features)

    lily_features = map(
        lambda n: filter(lambda f: f[0] == 'lily', n.features),
        notes_with_lily_features)[0] if notes_with_lily_features else []
    #print lily_features
    lily_features = map(lambda x: x[1], lily_features)
    #print lily_features
    lily_features = reduce(lambda x, y: x + y,
                           lily_features) if lily_features else ""
    #print 'lily_features {0}'.format(lily_features)
    subnotes = []

    for (num, base) in spelled_rhythm:
        for i in range(num):

            # F*****G (efficiency) this all happens for each num. can do it outside just once

            # empty => rest
            if this_notes == []:
                thisone = abj.Rest('r' + rhythm_strings(base) + '\mp')

            # one note
            elif len(this_notes) == 1:
                thisone = abj.Note(
                    mid_2_lil(this_notes[0].pitch) + rhythm_strings(base) +
                    lily_features)

            # chord
            else:
                thisone = abj.Chord(
                    "<" + reduce(lambda x, y: x + " " + y,
                                 [mid_2_lil(n.pitch) for n in this_notes]) +
                    ">" + rhythm_strings(base) + lily_features)

            # append to subnotes
            subnotes.append(thisone)

    # if more than one subnote then tie them all up
    # first count how many
    # then reach back into subnotes and tie themup
    # wait this shouldn't work... meaning it probs doesn't...

    how_many = sum([x for (x, y) in spelled_rhythm])

    #print how_many

    if how_many > 1:
        #print "tieing"
        abj.attach(abj.Tie(), subnotes[how_many * -1::])

    return subnotes
Пример #18
0
    def _rtm_maker(self, divisions, starting_index=0):
        rtm = self.rtm[starting_index:starting_index + len(divisions)]

        selections = []
        for rtm_string, division in zip(rtm, divisions):
            selection = self._rhythm_cell(division, rtm_string)
            selections.append(selection)
        for selection_ in selections[:-1]:
            if self.tie_across_divisions is True:
                last_leaf = abjad.select(selection_).leaves()[-1]
                abjad.attach(abjad.Tie(), last_leaf)
        return selections
def test_scoretools_Selection__attach_tie_spanner_to_leaf_pair_02():
    r'''Span left leaf with spanner and right leaf with spanner.
    '''

    voice = abjad.Voice("c'8 c'8 c'8 c'8")
    tie = abjad.Tie()
    abjad.attach(tie, voice[:2])
    tie = abjad.Tie()
    abjad.attach(tie, voice[2:])

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

    selector = abjad.select().leaves()
    leaves = selector(voice)
    leaves[1:3]._attach_tie_spanner_to_leaf_pair()

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

    assert abjad.inspect(voice).is_well_formed()
Пример #20
0
Файл: part.py Проект: gsy/gmajor
def edit_first_violin_voice(score, durated_reservoir):
    """
    Edits first violin voice.
    """
    voice = score['First Violin Voice']
    descents = durated_reservoir['First Violin']
    last_descent = abjad.Selection(descents[-1])
    copied_descent = abjad.mutate(last_descent).copy()
    voice.extend(copied_descent)
    final_sustain_rhythm = [(6, 4)] * 43 + [(1, 2)]
    maker = abjad.NoteMaker()
    final_sustain_notes = maker(["c'"], final_sustain_rhythm)
    voice.extend(final_sustain_notes)
    tie = abjad.Tie()
    abjad.attach(tie, final_sustain_notes)
    voice.extend('r4 r2.')
Пример #21
0
def test_scoretools_Leaf__split_by_durations_12():
    r'''Lone spanned leaf results in two spanned leaves.
    '''

    staff = abjad.Staff([abjad.Note("c'4")])
    tie = abjad.Tie()
    abjad.attach(tie, staff[:])
    halves = staff[0]._split_by_durations([abjad.Duration(1, 8)])

    assert len(staff) == 2
    for leaf in staff[:]:
        assert abjad.inspect(leaf).get_spanners() == [tie]
        prototype = (abjad.Tie, )
        assert abjad.inspect(leaf).get_spanner(prototype) is tie

    assert abjad.inspect(staff).is_well_formed()
Пример #22
0
 def _notate_leaves(
     self,
     grace_handler=None,
     voice=None,
 ):
     import abjad
     for leaf in abjad.iterate(voice).leaves():
         if leaf._has_indicator(dict):
             annotation = leaf._get_indicator(dict)
             q_events = annotation['q_events']
             pitches, grace_container = grace_handler(q_events)
             if not pitches:
                 new_leaf = abjad.Rest(leaf)
             elif 1 < len(pitches):
                 new_leaf = abjad.Chord(leaf)
                 new_leaf.written_pitches = pitches
             else:
                 new_leaf = abjad.Note(leaf)
                 new_leaf.written_pitch = pitches[0]
             if grace_container:
                 abjad.attach(grace_container, new_leaf)
             tie = abjad.Tie()
             if tie._attachment_test(new_leaf):
                 abjad.attach(tie, abjad.select(new_leaf))
             abjad.mutate(leaf).replace(new_leaf)
         else:
             previous_leaf = leaf._get_leaf(-1)
             if isinstance(previous_leaf, abjad.Rest):
                 new_leaf = type(previous_leaf)(leaf.written_duration, )
             elif isinstance(previous_leaf, abjad.Note):
                 new_leaf = type(previous_leaf)(
                     previous_leaf.written_pitch,
                     leaf.written_duration,
                 )
             else:
                 new_leaf = type(previous_leaf)(
                     previous_leaf.written_pitch,
                     leaf.written_duration,
                 )
             abjad.mutate(leaf).replace(new_leaf)
             tie = abjad.inspect(previous_leaf).get_spanner(abjad.Tie)
             if tie is not None:
                 tie._append(new_leaf)
         if leaf._has_indicator(abjad.MetronomeMark):
             tempo = leaf._get_indicator(abjad.MetronomeMark)
             abjad.detach(indicatortools.MetronomeMark, leaf)
             abjad.attach(tempo, new_leaf)
Пример #23
0
 def _tie_across_divisions_(self, divisions):
     import abjad
     if not self.tie_across_divisions:
         return
     if self.strip_ties:
         return
     if self.tie_consecutive_notes:
         return
     length = len(divisions)
     tie_across_divisions = self.tie_across_divisions
     if isinstance(tie_across_divisions, bool):
         tie_across_divisions = [tie_across_divisions]
     if not isinstance(tie_across_divisions, abjad.Pattern):
         tie_across_divisions = abjad.Pattern.from_vector(
             tie_across_divisions)
     pairs = abjad.sequence(divisions).nwise()
     rest_prototype = (abjad.Rest, abjad.MultimeasureRest)
     for i, pair in enumerate(pairs):
         if not tie_across_divisions.matches_index(i, length):
             continue
         division_one, division_two = pair
         leaf_one = next(abjad.iterate(division_one).leaves(reverse=True))
         leaf_two = next(abjad.iterate(division_two).leaves())
         leaves = [leaf_one, leaf_two]
         if isinstance(leaf_one, rest_prototype):
             continue
         if isinstance(leaf_two, rest_prototype):
             continue
         pitched_prototype = (abjad.Note, abjad.Chord)
         if not all(isinstance(_, pitched_prototype) for _ in leaves):
             continue
         logical_tie_one = abjad.inspect(leaf_one).get_logical_tie()
         logical_tie_two = abjad.inspect(leaf_two).get_logical_tie()
         if logical_tie_one == logical_tie_two:
             continue
         combined_logical_tie = logical_tie_one + logical_tie_two
         for leaf in combined_logical_tie:
             abjad.detach(abjad.Tie, leaf)
         tie = abjad.Tie(repeat=self.repeat_ties)
         tie._unconstrain_contiguity()
         if tie._attachment_test_all(combined_logical_tie) is True:
             try:
                 abjad.attach(tie, combined_logical_tie)
             except:
                 raise Exception(tie, combined_logical_tie)
         tie._constrain_contiguity()
Пример #24
0
def test_scoretools_Leaf__set_duration_02():
    r'''Change tied leaf to tied value.
    Duplicate ties are not created.
    '''

    voice = abjad.Voice("c'8 c'8 c'8 c'8")
    tie = abjad.Tie()
    abjad.attach(tie, voice[:2])
    beam = abjad.Beam()
    abjad.attach(beam, voice[:2])

    assert format(voice) == abjad.String.normalize(
        r'''
        \new Voice
        {
            c'8
            ~
            [
            c'8
            ]
            c'8
            c'8
        }
        '''
        )

    voice[1]._set_duration(abjad.Duration(5, 32))

    assert format(voice) == abjad.String.normalize(
        r'''
        \new Voice
        {
            c'8
            ~
            [
            c'8
            ~
            c'32
            ]
            c'8
            c'8
        }
        '''
        )

    assert abjad.inspect(voice).is_well_formed()
Пример #25
0
 def _make_music(self, divisions):
     import abjad
     from abjad.tools import rhythmmakertools
     selections = []
     duration_specifier = self._get_duration_specifier()
     tie_specifier = self._get_tie_specifier()
     tuplet_specifier = self._get_tuplet_specifier()
     leaf_maker = abjad.LeafMaker(
         decrease_monotonic=duration_specifier.decrease_monotonic,
         forbidden_duration=duration_specifier.forbidden_duration,
         diminution=tuplet_specifier.diminution,
         repeat_ties=tie_specifier.repeat_ties,
     )
     for division in divisions:
         if (duration_specifier.spell_metrically is True
                 or (duration_specifier.spell_metrically == 'unassignable'
                     and not abjad.mathtools.is_assignable_integer(
                         division.numerator))):
             meter = abjad.Meter(division)
             rhythm_tree_container = meter.root_node
             durations = [_.duration for _ in rhythm_tree_container]
         elif isinstance(duration_specifier.spell_metrically,
                         rhythmmakertools.PartitionTable):
             partition_table = duration_specifier.spell_metrically
             durations = partition_table.respell_division(division)
         else:
             durations = [division]
         selection = leaf_maker(pitches=0, durations=durations)
         if (1 < len(selection)
                 and not selection[0]._has_spanner(abjad.Tie)):
             tie = abjad.Tie(repeat=tie_specifier.repeat_ties)
             abjad.attach(tie, selection[:])
         selections.append(selection)
     selections = self._apply_burnish_specifier(selections)
     beam_specifier = self._get_beam_specifier()
     beam_specifier(selections)
     selections = self._apply_division_masks(selections)
     if duration_specifier.rewrite_meter:
         selections = duration_specifier._rewrite_meter_(
             selections,
             divisions,
             repeat_ties=tie_specifier.repeat_ties,
         )
     return selections
Пример #26
0
def test_scoretools_Leaf__split_by_durations_14():
    r'''Returns three leaves with two tied.

    Spanner is shared by all 3 leaves.
    '''

    staff = abjad.Staff([abjad.Note("c'4")])
    tie = abjad.Tie()
    abjad.attach(tie, staff[:])
    halves = staff[0]._split_by_durations([abjad.Duration(5, 32)])

    assert len(halves) == 2
    assert len(halves[0]) == 2
    assert len(halves[1]) == 1
    for l in staff:
        assert abjad.inspect(l).get_spanners() == [tie]
        assert abjad.inspect(l).get_spanner(abjad.Tie) is tie

    assert abjad.inspect(staff).is_well_formed()
Пример #27
0
 def convert_abjad_pitches_and_mu_rhythms2abjad_notes(
         self, harmonies: list, delays: list, grid) -> list:
     leading_pulses = grid.leading_pulses
     absolute_leading_pulses = tuple(
         itertools.accumulate([0] + list(leading_pulses)))
     converted_delays = grid.apply_delay(delays)
     absolute_delays = tuple(
         itertools.accumulate([0] + list(converted_delays)))
     # 1. generate notes
     notes = abjad.Measure(abjad.TimeSignature(grid.absolute_meter), [])
     resulting_durations = []
     for harmony, delay, start, end in zip(harmonies, converted_delays,
                                           absolute_delays,
                                           absolute_delays[1:]):
         subnotes = abjad.Voice()
         seperated_by_grid = Instrument.seperate_by_grid(
             delay, start, end, absolute_leading_pulses, leading_pulses,
             grid)
         assert sum(seperated_by_grid) == delay
         for d in seperated_by_grid:
             seperated_by_assignable = Instrument.seperate_by_assignablity(
                 d, grid)
             assert sum(seperated_by_assignable) == d
             for assignable in seperated_by_assignable:
                 resulting_durations.append(assignable)
                 if harmony:
                     chord = abjad.Chord(harmony,
                                         abjad.Duration(assignable))
                 else:
                     chord = abjad.Rest(abjad.Duration(assignable))
                 subnotes.append(chord)
         if len(subnotes) > 1 and len(harmony) > 0:
             abjad.attach(abjad.Tie(), subnotes[:])
         notes.extend(subnotes)
     assert sum(resulting_durations) == sum(converted_delays)
     voice = Instrument.mk_voice(notes)
     # 2. apply beams
     voice = Instrument.apply_beams(voice, resulting_durations,
                                    absolute_leading_pulses)
     return voice
Пример #28
0
def edit_viola_voice(score, durated_reservoir):
    r'''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)
    tie = abjad.Tie()
    abjad.attach(tie, final_sustain_notes)
    voice.extend('r4 r2.')
Пример #29
0
    def _apply_spanners(self, leaves):
        import abjad

        spanner_references = {
            abjad.Beam: None,
            abjad.Slur: None,
        }

        first_leaf = leaves[0]
        pairs = abjad.sequence(leaves).nwise(wrapped=True)
        for leaf, next_leaf in pairs:
            span_events = self._get_span_events(leaf)
            for current_class, directions in span_events.items():
                starting, stopping = [], []
                for direction in directions:
                    if direction is Left:
                        starting.append(Left)
                    else:
                        stopping.append(Right)

                # apply undirected events immediately,
                # and do not maintain a reference to them
                if current_class is abjad.Tie:
                    if next_leaf is first_leaf:
                        message = 'unterminated {} at {}.'
                        message = message.format(current_class.__name__, leaf)
                        raise Exception(message)
                    previous_tie = [
                        x for x in leaf._get_spanners()
                        if isinstance(x, abjad.Tie)
                    ]
                    if previous_tie:
                        previous_tie[0]._append(next_leaf)
                    else:
                        tie = abjad.Tie()
                        selection = abjad.select([leaf, next_leaf])
                        attach(tie, selection)

                elif current_class is abjad.Beam:
                    # A beam may begin and end on the same leaf
                    # but only one beam spanner may cover any given leaf,
                    # and starting events are processed before ending ones
                    for _ in starting:
                        if spanner_references[current_class] is not None:
                            message = 'already have beam.'
                            raise Exception(message)
                        else:
                            spanner_references[current_class] = current_class()
                    for _ in stopping:
                        if spanner_references[current_class] is not None:
                            spanner_references[current_class]._append(leaf)
                            spanner_references[current_class] = None

                elif current_class is spanners.Slur:
                    # Slurs process stop events before start events,
                    # they must contain more than one leaf,
                    # but they can stop on a leaf and start on the same leaf.
                    for _ in stopping:
                        if spanner_references[current_class] is not None:
                            spanner_references[current_class]._append(leaf)
                            spanner_references[current_class] = None
                        else:
                            message = 'can not end: {}.'
                            message = message.format(current_class.__name)
                            raise Exception(message)
                    for _ in starting:
                        if spanner_references[current_class] is None:
                            spanner_references[current_class] = current_class()
                        else:
                            message = 'already have: {}.'
                            message = message.format(current_class.__name)
                            raise Exception(message)

            # append leaf to all tracked spanners,
            for current_class, instance in spanner_references.items():
                if instance is not None:
                    instance._append(leaf)

        # check for unterminated spanners
        for current_class, instance in spanner_references.items():
            if instance is not None:
                message = 'unterminated {}.'
                message = message.format(current_class.__name__)
                raise Exception(message)
Пример #30
0
 def _notate_music(
     self,
     dummy_container: abjad.Container,
     start: int,
     end: int,
 ) -> None:
     r'Handles the notation aspects of the looping window.'
     window_size = self._window_size
     # passing on indicators from the head of an initial splitted leaf
     for index in range(start - 1, -1, -1):
         if abjad.inspect(dummy_container[index]).indicator(abjad.Tie):
             inspect_contents = abjad.inspect(dummy_container[index - 1])
             if index == 0 or not inspect_contents.indicator(abjad.Tie):
                 inspect_contents = abjad.inspect(dummy_container[index])
                 for indicator in inspect_contents.indicators():
                     inspector = abjad.inspect(dummy_container[start])
                     if (not isinstance(indicator,
                                        (abjad.TimeSignature, abjad.Tie))
                             and
                             inspector.indicator(type(indicator)) is None):
                         abjad.attach(indicator, dummy_container[start])
     # removing ties generated by the split mutation
     abjad.detach(abjad.Tie(), dummy_container[start - 1])
     abjad.detach(abjad.Tie(), dummy_container[end - 1])
     # handling initial dynamics and slurs
     start_head = abjad.select(dummy_container[start:]).logical_tie(0)[0]
     start_tail = abjad.select(dummy_container[start:]).logical_tie(0)[-1]
     if (abjad.inspect(start_head).indicator(abjad.StartSlur) is None and
             abjad.inspect(start_tail).indicator(abjad.StopSlur) is None):
         for leaf in dummy_container[start - 1::-1].leaves():
             if abjad.inspect(leaf).indicator(abjad.StartSlur) is not None:
                 abjad.attach(abjad.StartSlur(), start_head)
                 break
             elif abjad.inspect(leaf).indicator(abjad.StopSlur) is not None:
                 break
     if (abjad.inspect(start_head).indicator(abjad.Dynamic) is None
             and not isinstance(start_head, (
                 abjad.Rest,
                 abjad.MultimeasureRest,
             ))):
         for leaf in dummy_container[start - 1::-1].leaves():
             dynamic = abjad.inspect(leaf).indicator(abjad.Dynamic)
             if dynamic is not None:
                 abjad.attach(dynamic, start_head)
                 break
     # appending rests if necessary
     contents_dur = abjad.inspect(dummy_container[start:end]).duration()
     if contents_dur < window_size.duration:
         missing_dur = window_size.duration - contents_dur
         rests = abjad.LeafMaker()(None, missing_dur)
         dummy_container.extend(rests)
         end += len(rests)
     # transforming abjad.Selection -> abjad.Container for rewrite_meter
     dummy_container = abjad.Container(
         abjad.mutate(dummy_container[start:end]).copy())
     # rewriting meter
     if not self._disable_rewrite_meter:
         mutate(dummy_container).auto_rewrite_meter(
             meter_list=[abjad.TimeSignature(window_size)],
             boundary_depth=self._boundary_depth,
             maximum_dot_count=self._maximum_dot_count,
             rewrite_tuplets=self._rewrite_tuplets,
             prettify_rewrite_meter=self._prettify_rewrite_meter,
             extract_trivial_tuplets=self._extract_trivial_tuplets,
             fuse_across_groups_of_beats=self._fuse_across_groups_of_beats,
             fuse_quadruple_meter=self._fuse_quadruple_meter,
             fuse_triple_meter=self._fuse_triple_meter,
         )
     abjad.attach(
         abjad.TimeSignature(window_size),
         abjad.select(dummy_container).leaf(0),
     )
     mutate(dummy_container[:]).reposition_dynamics()
     mutate(dummy_container[:]).reposition_slurs()
     self._current_window = dummy_container[:]
     dummy_container[:] = []