def __call__(
     self,
     logical_tie,
     seed=0,
     ):
     assert isinstance(logical_tie, selectiontools.LogicalTie)
     if self.counts is None:
         return
     previous_leaf = logical_tie.head._get_leaf(-1)
     if previous_leaf is None:
         return
     silence_prototype = (
         abjad.Rest,
         abjad.MultimeasureRest,
         abjad.Skip,
         )
     if self.only_if_preceded_by_silence:
         if not isinstance(previous_leaf, silence_prototype):
             return
     if self.only_if_preceded_by_nonsilence:
         if isinstance(previous_leaf, silence_prototype):
             return
     grace_count = self.counts[seed]
     if not grace_count:
         return
     leaf_to_attach_to = previous_leaf
     leaves = []
     notes = abjad.LeafMaker()([0], [(1, 16)] * grace_count)
     leaves.extend(notes)
     assert len(leaves)
     grace_container = scoretools.AfterGraceContainer(leaves)
     abjad.override(grace_container).flag.stroke_style = \
         schemetools.Scheme('grace', force_quotes=True)
     abjad.override(grace_container).script.font_size = 0.5
     abjad.attach(grace_container, leaf_to_attach_to)
def test_lilypondparsertools_LilyPondParser__functions__transpose_01():

    pitches = ["e'", "gs'", "b'", "e''"]
    maker = abjad.NoteMaker()
    target = abjad.Staff(maker(pitches, (1, 4)))
    key_signature = abjad.KeySignature('e', 'major')
    abjad.attach(key_signature, target[0])

    assert format(target) == abjad.String.normalize(
        r"""
        \new Staff
        {
            \key e \major
            e'4
            gs'4
            b'4
            e''4
        }
        """
        )

    string = r"\transpose d e \relative c' \new Staff { \key d \major d4 fs a d }"
    parser = abjad.lilypondparsertools.LilyPondParser()
    result = parser(string)
    assert format(target) == format(result) and target is not result
def test_lilypondparsertools_LilyPondParser__functions__transpose_02():

    pitches = ["ef'", "f'", "g'", "bf'"]
    maker = abjad.NoteMaker()
    target = abjad.Staff(maker(pitches, (1, 4)))
    key_signature = abjad.KeySignature('ef', 'major')
    abjad.attach(key_signature, target[0])

    assert format(target) == abjad.String.normalize(
        r"""
        \new Staff
        {
            \key ef \major
            ef'4
            f'4
            g'4
            bf'4
        }
        """
        )

    string = r"\transpose a c' \relative c' \new Staff { \key c \major c4 d e g }"
    parser = abjad.lilypondparsertools.LilyPondParser()
    result = parser(string)
    assert format(target) == format(result) and target is not result
Exemplo n.º 4
0
def add_tempo(thing, duration=None, bpm_range=None):
    if not duration:
        duration = Config.tempo_duration
    if not bpm_range:
        bpm_range = Config.tempo_bpm_range
    tempo = Tempo(duration, bpm_range)
    attach(tempo, thing)
def test_LilyPondGrobNameManager___setattr___13():
    """
    Override LilyPond abjad.MetronomeMark grob.
    """

    staff = abjad.Staff("c'8 d'8 e'8 f'8")
    score = abjad.Score([staff])
    tempo = abjad.MetronomeMark(abjad.Duration(1, 4), 58)
    abjad.attach(tempo, staff[0])
    abjad.override(score).metronome_mark.color = "red"

    assert format(score) == abjad.String.normalize(
        r"""
        \new Score
        \with
        {
            \override MetronomeMark.color = #red
        }
        <<
            \new Staff
            {
                \tempo 4=58
                c'8
                d'8
                e'8
                f'8
            }
        >>
        """
    )

    assert abjad.inspect(score).wellformed()
Exemplo n.º 6
0
    def __call__(self, expr):
        r'''Calls specifier on `expr`.

        Returns none.
        '''
        if self.dynamic is None:
            return
        #print(expr)
        selector = self._get_selector()
        #print(selector)
        selections = selector(expr)
        #print(selections)
        for selection in selections:
            if isinstance(self.dynamic, abjad.spannertools.Hairpin):
                hairpin = abjad.new(self.dynamic)
                leaves = list(abjad.iterate(selection).by_leaf())
                if hairpin._attachment_test_all(leaves):
                    abjad.attach(hairpin, leaves)
            elif isinstance(self.dynamic, (str, abjad.indicatortools.Dynamic)):
                dynamic = abjad.indicatortools.Dynamic(self.dynamic)
                abjad.attach(dynamic, selection[0])
            else:
                message = 'invalid dynamic: {!r}.'
                message = message.format(self.dynamic)
                raise Exception(message)
Exemplo n.º 7
0
def test_Staff_time_signature_01():
    """
    Force time signature on nonempty staff.
    """

    staff = abjad.Staff(abjad.Note("c'4") * 8)
    time_signature = abjad.TimeSignature((2, 4))
    abjad.attach(time_signature, staff[0])

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            \time 2/4
            c'4
            c'4
            c'4
            c'4
            c'4
            c'4
            c'4
            c'4
        }
        """
    )
Exemplo n.º 8
0
Arquivo: part.py Projeto: Abjad/abjad
def apply_bowing_marks(score):
    """
    Applies bowing marks to score.
    """
    # apply alternating upbow and downbow for first two sounding bars
    # of the first violin
    for measure in score["First Violin Voice"][6:8]:
        for i, chord in enumerate(
            abjad.iterate(measure).components(abjad.Chord)
        ):
            if i % 2 == 0:
                articulation = abjad.Articulation("downbow")
                abjad.attach(articulation, chord)
            else:
                articulation = abjad.Articulation("upbow")
                abjad.attach(articulation, chord)

    # create and apply rebowing markup
    rebow_markup = abjad.Markup.concat(
        [
            abjad.Markup.musicglyph("scripts.downbow"),
            abjad.Markup.hspace(1),
            abjad.Markup.musicglyph("scripts.upbow"),
        ]
    )
    markup = copy.copy(rebow_markup)
    abjad.attach(markup, score["First Violin Voice"][64][0])
    markup = copy.copy(rebow_markup)
    abjad.attach(markup, score["Second Violin Voice"][75][0])
    markup = copy.copy(rebow_markup)
    abjad.attach(markup, score["Viola Voice"][86][0])
Exemplo n.º 9
0
Arquivo: part.py Projeto: Abjad/abjad
def apply_page_breaks(score):
    """
    Applies page breaks to score.
    """
    bell_voice = score["Bell Voice"]
    measure_indices = [
        5,
        10,
        15,
        20,
        25,
        30,
        35,
        40,
        45,
        50,
        55,
        60,
        65,
        72,
        79,
        86,
        93,
        100,
    ]
    for measure_index in measure_indices:
        command = abjad.LilyPondLiteral(r"\break", "after")
        abjad.attach(command, bell_voice[measure_index])
Exemplo n.º 10
0
Arquivo: part.py Projeto: Abjad/abjad
def add_bell_music_to_score(score):
    """
    Adds bell music to score.
    """

    def make_bell_phrase():
        phrase = []
        for _ in range(3):
            measure = abjad.Container("r2. a'2.")
            abjad.attach(abjad.TimeSignature((6, 4)), measure[0])
            abjad.attach(abjad.LaissezVibrer(), measure[-1])
            phrase.append(measure)
            phrase.append(abjad.Container("R1."))
        for _ in range(2):
            phrase.append(abjad.Container("R1."))
        return phrase

    bell_voice = score["Bell Voice"]
    for _ in range(11):
        bell_voice.extend(make_bell_phrase())
    for _ in range(19):
        bell_voice.append(abjad.Container("R1."))
    measure = abjad.Container(r"a'1.")
    abjad.attach(abjad.LaissezVibrer(), measure[-1])
    bell_voice.append(measure)
Exemplo n.º 11
0
Arquivo: part.py Projeto: Abjad/abjad
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.")
Exemplo n.º 12
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]).get_logical_tie()
    for leaf in logical_tie.leaves:
        parent = abjad.inspect(leaf).get_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).get_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 _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)
Exemplo n.º 14
0
def add_new_spacing_section(meter_voice, start_measure_number, new_moment,
    revert_measure_number = None):

    normal_spacing_duration = abjad.schemetools.SchemeMoment(1, 96)
    if revert_measure_number is None:
        revert_measure_number = start_measure_number + 1

    #measure = measuretools.get_one_indexed_measure_number_in_expr(
    #    meter_voice, start_measure_number)
    measures = list(abjad.iterate(meter_voice).by_class(abjad.Measure))

    start_measure_index = start_measure_number - 1
    measure = measures[start_measure_index]
    command = abjad.LilyPondCommand('newSpacingSection', 'before')
    abjad.attach(command, measure)
    moment = abjad.schemetools.SchemeMoment(new_moment)
    #measure.set.score.proportional_notation_duration = moment
    abjad.set_(measure).score.proportional_notation_duration = moment

    #measure = measuretools.get_one_indexed_measure_number_in_expr(
    #    meter_voice, revert_measure_number)
    revert_measure_index = revert_measure_number - 1
    measure = measures[revert_measure_index]

    command = abjad.LilyPondCommand('newSpacingSection', 'before')
    abjad.attach(command, measure)
    abjad.set_(measure).score.proportional_notation_duration = \
        normal_spacing_duration
Exemplo n.º 15
0
def test_Note___copy___04():
    """
    Copy note with grace container.
    """

    note_1 = abjad.Note("c'4")
    grace_container_1 = abjad.AfterGraceContainer([abjad.Note("d'32")])
    abjad.attach(grace_container_1, note_1)

    assert format(note_1) == abjad.String.normalize(
        r"""
        \afterGrace
        c'4
        {
            d'32
        }
        """
    )

    note_2 = copy.copy(note_1)
    grace_container_2 = abjad.inspect(note_2).after_grace_container()

    assert format(note_2) == abjad.String.normalize(
        r"""
        \afterGrace
        c'4
        {
            d'32
        }
        """
    )

    assert note_1 is not note_2
    assert grace_container_1 is not grace_container_2
    assert isinstance(grace_container_1, abjad.AfterGraceContainer)
Exemplo n.º 16
0
Arquivo: part.py Projeto: Abjad/abjad
def apply_rehearsal_marks(score):
    """
    Applies rehearsal marks to score.
    """
    bell_voice = score["Bell Voice"]
    measure_indices = [
        6,
        12,
        18,
        24,
        30,
        36,
        42,
        48,
        54,
        60,
        66,
        72,
        78,
        84,
        90,
        96,
        102,
    ]
    for measure_index in measure_indices:
        command = abjad.LilyPondLiteral(r"\mark \default", "before")
        abjad.attach(command, bell_voice[measure_index])
Exemplo n.º 17
0
def test_Note___copy___05():
    """
    Deepcopy orphan note.
    """

    note = abjad.Note("c'4")
    articulation = abjad.Articulation("staccato")
    abjad.attach(articulation, note)
    grace = abjad.GraceContainer("d'16")
    abjad.attach(grace, note)
    abjad.override(note).note_head.color = "red"

    assert format(note) == abjad.String.normalize(
        r"""
        \grace {
            d'16
        }
        \once \override NoteHead.color = #red
        c'4
        - \staccato
        """
    )

    new_note = copy.deepcopy(note)

    assert not new_note is note
    assert format(new_note) == format(note)
Exemplo n.º 18
0
    def __call__(self, logical_ties):
        r"""Calls trill specifier.

        Returns none.
        """
        if isinstance(logical_ties[0], abjad.scoretools.Leaf):
            logical_ties = [abjad.selectiontools.LogicalTie(_) for _ in logical_ties]
        for logical_tie in logical_ties:
            written_duration = abjad.durationtools.Duration(0)
            for note in logical_tie:
                written_duration += note.written_duration
            if self.minimum_written_duration is not None:
                if written_duration < self.minimum_written_duration:
                    continue
            if self.maximum_written_duration is not None:
                if self.maximum_written_duration <= written_duration:
                    continue
            spanner = abjad.spannertools.TrillSpanner(
                interval=self.interval, is_harmonic=self.is_harmonic, pitch=self.pitch
            )
            leaves = []
            for note in logical_tie:
                leaves.append(note)
            skip_spanner = False
            for leaf in leaves:
                if self._has_forbidden_annotation(leaf):
                    skip_spanner = True
                    break
            if skip_spanner:
                continue
            next_leaf = abjad.inspect_(leaves[-1]).get_leaf(1)
            if next_leaf is not None:
                leaves.append(next_leaf)
            if 1 < len(leaves):
                abjad.attach(spanner, leaves)
Exemplo n.º 19
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)
def test_LilyPondParser__indicators__TimeSignature_01():

    target = abjad.Score([abjad.Staff([abjad.Note(0, 1)])])
    time_signature = abjad.TimeSignature((8, 8))
    abjad.attach(time_signature, target[0][0])

    assert format(target) == abjad.String.normalize(
        r"""
        \new Score
        <<
            \new Staff
            {
                \time 8/8
                c'1
            }
        >>
        """
    )

    parser = abjad.parser.LilyPondParser()
    result = parser(format(target))
    assert format(target) == format(result) and target is not result
    leaves = abjad.select(result).leaves()
    leaf = leaves[0]
    time_signatures = abjad.inspect(leaf).indicators(abjad.TimeSignature)
    assert len(time_signatures) == 1
Exemplo n.º 21
0
    def __call__(self, stage_token):
        r'''Calls acciaccatura specifier on `stage_token`.

        Returns grace container together with new stage token.
        '''
        assert isinstance(stage_token, list), repr(stage_token)
        stage_length = len(stage_token)
        lmr_specifier = self._get_lmr_specifier()
        stage_parts = lmr_specifier(stage_token)
        stage_parts = [_ for _ in stage_parts if _]
        stage_token = [_[-1] for _ in stage_parts]
        durations = self._get_durations()
        grace_containers = []
        for stage_part in stage_parts:
            if len(stage_part) <= 1:
                grace_containers.append(None)
                continue
            grace_token = list(stage_part[:-1])
            grace_leaves = abjad.scoretools.make_leaves(
                grace_token,
                durations,
                )
            grace_container = abjad.scoretools.GraceContainer(
                grace_leaves,
                kind='acciaccatura',
                )
            if 1 < len(grace_container):
                abjad.attach(abjad.spannertools.Beam(), grace_container[:])
            grace_containers.append(grace_container)
        assert len(grace_containers) == len(stage_token)
        return grace_containers, stage_token
Exemplo n.º 22
0
def main():
  score = abjad.Score([]);
  measures = 50;
  beats = 4 * measures
  
  tempo = abjad.Tempo(abjad.Duration(1, 4), 240)
  abjad.attach(tempo, score)
  
  chord1 = Chord(C, name="major_major7");
  chord2 = Chord(G, name="major_minor7");
  part1 = []
  for i in xrange(0,beats):
    if i % 3:
      part1.append(choose_random_note_in_range(chord2.notes_all))
    else:
      part1.append(choose_random_note_in_range(chord1.notes_all))
  score = add_to_score(part1,score)

  part2 = []
  for i in xrange(0,beats):
    if i % 3:
      part2.append(choose_random_note_in_range(chord2.notes_all))
    else:
      part2.append(choose_random_note_in_range(chord1.notes_all))
  score = add_to_score(part2,score)

  abjad_renderer = RendererAbjad(clean=True, verbose=True)
  abjad_renderer.render(score, preview=False)
  audio_renderer = RendererAudioFluidsynth();  
  file_audio = audio_renderer.render(abjad_renderer.file_midi)
  audio_player = AudioPlayer();
  audio_player.play(file_audio)
 def _attach_tag(self, label, context):
     label = abjad.String(label).to_dash_case()
     tag = indicatortools.LilyPondCommand(
         name="tag #'{}".format(label),
         format_slot='before',
         )
     attach(tag, context)
Exemplo n.º 24
0
def test_Inspection_indicators_02():

    staff = abjad.Staff("c'8 d'8 e'8 f'8")
    abjad.slur(staff[:])
    comment = abjad.LilyPondComment("beginning of note content")
    abjad.attach(comment, staff[0])
    command = abjad.LilyPondLiteral(r"\slurDotted")
    abjad.attach(command, staff[0])

    assert format(staff) == abjad.String.normalize(
        r"""
        \new Staff
        {
            % beginning of note content
            \slurDotted
            c'8
            (
            d'8
            e'8
            f'8
            )
        }
        """
    ), format(staff)

    items = abjad.inspect(staff[0]).indicators()
    assert comment in items
    assert command in items
    assert len(items) == 3
def test_LilyPondParser__functions__grace_01():

    target = abjad.Container(
        [abjad.Note("c'4"), abjad.Note("d'4"), abjad.Note("e'2")]
    )

    grace = abjad.GraceContainer([abjad.Note("g''16"), abjad.Note("fs''16")])

    abjad.attach(grace, target[2])

    assert format(target) == abjad.String.normalize(
        r"""
        {
            c'4
            d'4
            \grace {
                g''16
                fs''16
            }
            e'2
        }
        """
    )

    string = r"{ c'4 d'4 \grace { g''16 fs''16} e'2 }"
    parser = abjad.parser.LilyPondParser()
    result = parser(string)
    assert format(target) == format(result) and target is not result
Exemplo n.º 26
0
def test_Inspection_indicators_04():

    staff = abjad.Staff("c'8 d'8 e'8 f'8")
    comment_1 = abjad.LilyPondComment("comment 1")
    abjad.attach(comment_1, staff[0])
    comment_2 = abjad.LilyPondComment("comment 2")
    abjad.attach(comment_2, staff[0])

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

    indicators = abjad.inspect(staff[0]).indicators(abjad.LilyPondComment)
    assert comment_1 in indicators
    assert comment_2 in indicators
    assert len(indicators) == 2
Exemplo n.º 27
0
 def __call__(self, music, name=None):
     leaves = list(iterate(music).by_leaf())
     weights = []
     weighted_pitches = []
     for leaf in leaves:
         weight = float(inspect_(leaf).get_duration())
         if isinstance(leaf, scoretools.Note):
             pitch = float(leaf.written_pitch)
             weighted_pitch = pitch * weight
             weights.append(weight)
             weighted_pitches.append(weighted_pitch)
         elif isinstance(leaf, scoretools.Chord):
             for pitch in leaf.written_pitches:
                 pitch = float(pitch)
                 weighted_pitch = pitch * weight
                 weighted_pitches.append(weighted_pitch)
                 weights.append(weight)
     sum_of_weights = sum(weights)
     sum_of_weighted_pitches = sum(weighted_pitches)
     weighted_average = sum_of_weighted_pitches / sum_of_weights
     #print(music, weighted_average)
     clef = inspect_(leaves[0]).get_effective(indicatortools.Clef)
     octavation_spanner = None
     if clef == indicatortools.Clef('treble'):
         if int(pitchtools.NamedPitch('C6')) <= int(weighted_average):
             octavation_spanner = spannertools.OctavationSpanner()
     elif clef == indicatortools.Clef('bass'):
         pass
     if octavation_spanner is not None:
         attach(octavation_spanner, music)
 def __call__(self, music, name=None):
     import consort
     leaves = list(iterate(music).by_leaf())
     weights = []
     weighted_pitches = []
     for leaf in leaves:
         weight = float(inspect(leaf).get_duration())
         if isinstance(leaf, abjad.Note):
             pitch = float(leaf.written_pitch)
             weighted_pitch = pitch * weight
             weights.append(weight)
             weighted_pitches.append(weighted_pitch)
         elif isinstance(leaf, abjad.Chord):
             for pitch in leaf.written_pitches:
                 pitch = float(pitch)
                 weighted_pitch = pitch * weight
                 weighted_pitches.append(weighted_pitch)
                 weights.append(weight)
     sum_of_weights = sum(weights)
     sum_of_weighted_pitches = sum(weighted_pitches)
     weighted_average = sum_of_weighted_pitches / sum_of_weights
     if weighted_average < 0:
         clef_spanner = consort.ClefSpanner('bass')
     else:
         clef_spanner = consort.ClefSpanner('treble')
     attach(clef_spanner, music, name=name)
 def _make_staff(
     self,
     name,
     clef,
     abbreviation=None,
     context_name=None,
     instrument=None,
     tag=None,
     voices=None,
     ):
     name = name.title()
     staff_name = '{} Staff'.format(name)
     context_name = context_name or staff_name
     context_name = context_name.replace(' ', '')
     abbreviation = abbreviation or name
     abbreviation = abjad.String(abbreviation).to_snake_case()
     voices = voices or [self._make_voice(name, abbreviation=abbreviation)]
     staff = abjad.Staff(
         voices,
         context_name=context_name,
         name=staff_name
         )
     if not isinstance(clef, indicatortools.Clef):
         clef = indicatortools.Clef(clef)
     attach(clef, staff)
     if tag:
         self._attach_tag(tag, staff)
     if instrument:
         assert isinstance(instrument, instrumenttools.Instrument)
         attach(instrument, staff)
     return staff
Exemplo n.º 30
0
def test_Inspection_indicators_01():

    staff = abjad.Staff("c'8 d'8 e'8 f'8")
    abjad.slur(staff[:])
    command_1 = abjad.LilyPondLiteral(r"\slurDotted")
    abjad.attach(command_1, staff[0])
    command_2 = abjad.LilyPondLiteral(r"\slurUp")
    abjad.attach(command_2, staff[0])

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

    indicators = abjad.inspect(staff[0]).indicators(abjad.LilyPondLiteral)
    assert command_1 in indicators
    assert command_2 in indicators
    assert len(indicators) == 2
Exemplo n.º 31
0
 def attach(self, leaf: abjad.Chord, novent) -> None:
     abjad.attach(
         abjad.LilyPondLiteral("\\snappizzicato",
                               format_slot="absolute_after"), leaf)
Exemplo n.º 32
0
 def attach(self, leaf: abjad.Chord, novent) -> None:
     markup = abjad.Markup(self.abjad.markup, direction="up").tiny()
     abjad.attach(markup, leaf)
Exemplo n.º 33
0
        ],
        lilypond_type='PianoStaff',
        name='Staff Group',
    )
])

# Teach each of the staves how to draw analysis brackets

for staff in score['Staff Group']:
    staff.consists_commands.append('Horizontal_bracket_engraver')

# Add skips and time signatures to the global context

for time_signature in time_signatures:
    skip = abjad.Skip(1, multiplier=(time_signature))
    abjad.attach(time_signature, skip)
    score['Global Context'].append(skip)

# Define a helper function that takes a rhythm maker and some durations and
# outputs a container. This helper function also adds LilyPond analysis
# brackets to make it clearer where the phrase and sub-phrase boundaries are.

print('Making containers ...')


def make_container(rhythm_maker, durations):
    selections = rhythm_maker(durations)
    container = abjad.Container(selections)
    # # Add analysis brackets so we can see the phrasing graphically
    # start_indicator = abjad.LilyPondLiteral('\startGroup', format_slot='after')
    # stop_indicator = abjad.LilyPondLiteral('\stopGroup', format_slot='after')
Exemplo n.º 34
0
def apply_expressive_marks(score):
    """
    Applies expressive marks to score.
    """
    voice = score['First Violin Voice']
    markup = abjad.Markup(r'\left-column { div. \line { con sord. } }',
                          direction=abjad.Up)
    abjad.attach(markup, voice[6][1])
    markup = abjad.Markup('sim.', direction=abjad.Up)
    abjad.attach(markup, voice[8][0])
    markup = abjad.Markup('uniti', direction=abjad.Up)
    abjad.attach(markup, voice[58][3])
    markup = abjad.Markup('div.', direction=abjad.Up)
    abjad.attach(markup, voice[59][0])
    markup = abjad.Markup('uniti', direction=abjad.Up)
    abjad.attach(markup, voice[63][3])

    voice = score['Second Violin Voice']
    markup = abjad.Markup('div.', direction=abjad.Up)
    abjad.attach(markup, voice[7][0])
    markup = abjad.Markup('uniti', direction=abjad.Up)
    abjad.attach(markup, voice[66][1])
    markup = abjad.Markup('div.', direction=abjad.Up)
    abjad.attach(markup, voice[67][0])
    markup = abjad.Markup('uniti', direction=abjad.Up)
    abjad.attach(markup, voice[74][0])

    voice = score['Viola Voice']
    markup = abjad.Markup('sole', direction=abjad.Up)
    abjad.attach(markup, voice[8][0])

    voice = score['Cello Voice']
    markup = abjad.Markup('div.', direction=abjad.Up)
    abjad.attach(markup, voice[10][0])
    markup = abjad.Markup('uniti', direction=abjad.Up)
    abjad.attach(markup, voice[74][0])
    markup = abjad.Markup('uniti', direction=abjad.Up)
    abjad.attach(markup, voice[84][1])
    markup = abjad.Markup(r'\italic { espr. }', direction=abjad.Down)
    abjad.attach(markup, voice[86][0])
    markup = abjad.Markup(r'\italic { molto espr. }', direction=abjad.Down)
    abjad.attach(markup, voice[88][1])

    voice = score['Bass Voice']
    markup = abjad.Markup('div.', direction=abjad.Up)
    abjad.attach(markup, voice[14][0])
    markup = abjad.Markup(r'\italic { espr. }', direction=abjad.Down)
    abjad.attach(markup, voice[86][0])
    abjad.mutate(voice[88][:]).split(
        [abjad.Duration(1, 1), abjad.Duration(1, 2)])
    markup = abjad.Markup(r'\italic { molto espr. }', direction=abjad.Down)
    abjad.attach(markup, voice[88][1])
    markup = abjad.Markup('uniti', direction=abjad.Up)
    abjad.attach(markup, voice[99][1])

    strings_staff_group = score['Strings Staff Group']
    for voice in abjad.iterate(strings_staff_group).components(abjad.Voice):
        markup = abjad.Markup(r'\italic { (non dim.) }', direction=abjad.Down)
        abjad.attach(markup, voice[102][0])
Exemplo n.º 35
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.')
Exemplo n.º 36
0
    [[1,6],4], [[7,5],1], [[1,6],2], [[7,5],1], [[1,6],2], [[2,7],2],
    [[6,3],2], [[5,2],3], [[6,3],1], [[5,2],4], [[6,3],1], [[5,2],2]
]

pitches = {1:"e''",2:"d''",3:"c''",4:"b'",5:"a'",6:"g'",7:"f'",8:"e'",9:"d'",10:"c'"}

QUAVER = abjad.Duration(1,8)
CROTCHET = 2*QUAVER

staff = abjad.Staff()
for (interval, length) in hymn:
    for i in range(length):
        staff.append(abjad.Note(pitches[interval[1]], CROTCHET))
        if interval[1] in (1,2):
            low_note = abjad.NoteHead(pitches[interval[1]+7])
            abjad.tweak(low_note).font_size = -3
            chord = abjad.Chord([], CROTCHET)
            chord.note_heads.extend([staff[-1].note_head, low_note])
            staff[-1] = chord

abjad.attach(abjad.TimeSignature((18, 4)), staff[0])
abjad.attach(abjad.TimeSignature((9, 4)), staff[18])
abjad.attach(abjad.TimeSignature((10, 4)), staff[27])
abjad.attach(abjad.TimeSignature((10, 4)), staff[37])
abjad.attach(abjad.TimeSignature((12, 4)), staff[47])
abjad.attach(abjad.TimeSignature((13, 4)), staff[59])

score = abjad.Score([staff])
score.add_final_bar_line()
abjad.show(score)
Exemplo n.º 37
0
def make_bartok_score():
    score = Score([])
    piano_staff = StaffGroup([], context_name='PianoStaff')
    upper_staff = Staff([])
    lower_staff = Staff([])
    piano_staff.append(upper_staff)
    piano_staff.append(lower_staff)
    score.append(piano_staff)
    upper_measures = []
    upper_measures.append(Measure((2, 4), []))
    upper_measures.append(Measure((3, 4), []))
    upper_measures.append(Measure((2, 4), []))
    upper_measures.append(Measure((2, 4), []))
    upper_measures.append(Measure((2, 4), []))
    lower_measures = copy.deepcopy(upper_measures)
    upper_staff.extend(upper_measures)
    lower_staff.extend(lower_measures)
    upper_measures[0].extend("a'8 g'8 f'8 e'8")
    upper_measures[1].extend("d'4 g'8 f'8 e'8 d'8")
    upper_measures[2].extend("c'8 d'16 e'16 f'8 e'8")
    upper_measures[3].append("d'2")
    upper_measures[4].append("d'2")
    lower_measures[0].extend("b4 d'8 c'8")
    lower_measures[1].extend("b8 a8 af4 c'8 bf8")
    lower_measures[2].extend("a8 g8 fs8 g16 a16")
    upper_voice = Voice("b2", name='upper voice')
    command = indicatortools.LilyPondCommand('voiceOne')
    attach(command, upper_voice)
    lower_voice = Voice("b4 a4", name='lower voice')
    command = indicatortools.LilyPondCommand('voiceTwo')
    attach(command, lower_voice)
    lower_measures[3].extend([upper_voice, lower_voice])
    lower_measures[3].is_simultaneous = True
    upper_voice = Voice("b2", name='upper voice')
    command = indicatortools.LilyPondCommand('voiceOne')
    attach(command, upper_voice)
    lower_voice = Voice("g2", name='lower voice')
    command = indicatortools.LilyPondCommand('voiceTwo')
    attach(command, lower_voice)
    lower_measures[4].extend([upper_voice, lower_voice])
    lower_measures[4].is_simultaneous = True
    clef = Clef('bass')
    attach(clef, lower_staff)
    dynamic = Dynamic('pp')
    attach(dynamic, upper_measures[0][0])
    dynamic = Dynamic('mp')
    attach(dynamic, upper_measures[1][1])
    dynamic = Dynamic('pp')
    attach(dynamic, lower_measures[0][1])
    dynamic = Dynamic('mp')
    attach(dynamic, lower_measures[1][3])
    score.add_final_bar_line()
    selector = select().by_leaf(flatten=True)
    upper_leaves = selector(upper_staff)
    lower_leaves = selector(lower_staff)
    beam = Beam()
    attach(beam, upper_leaves[:4])
    beam = Beam()
    attach(beam, lower_leaves[1:5])
    beam = Beam()
    attach(beam, lower_leaves[6:10])
    slur = Slur()
    attach(slur, upper_leaves[:5])
    slur = Slur()
    attach(slur, upper_leaves[5:])
    slur = Slur()
    attach(slur, lower_leaves[1:6])
    crescendo = Crescendo()
    attach(crescendo, upper_leaves[-7:-2])
    decrescendo = Decrescendo()
    attach(decrescendo, upper_leaves[-2:])
    markup = Markup('ritard.')
    text_spanner = spannertools.TextSpanner()
    override(text_spanner).text_spanner.bound_details__left__text = markup
    attach(text_spanner, upper_leaves[-7:])
    tie = Tie()
    attach(tie, upper_leaves[-2:])
    note_1 = lower_staff[-2]['upper voice'][0]
    note_2 = lower_staff[-1]['upper voice'][0]
    notes = [note_1, note_2]
    tie = Tie()
    attach(tie, notes)
    return score
Exemplo n.º 38
0
                        lilypond_type="Staff"),
        ],
        name="Staff Group 1",
    ),
])

# Teach each of the staves how to draw analysis brackets

# for staff in score['Staff Group']:
#     staff.consists_commands.append('Horizontal_bracket_engraver')

# Add skips and time signatures to the global context

for time_signature in time_signatures:
    skip = abjad.Skip(1, multiplier=(time_signature))
    abjad.attach(time_signature, skip)
    score["Global Context"].append(skip)

# Define a helper function that takes a rhythm maker and some durations and
# outputs a container. This helper function also adds LilyPond analysis
# brackets to make it clearer where the phrase and sub-phrase boundaries are.

print("Making containers ...")


def make_container(music_maker, durations):
    selections = music_maker(durations)
    container = abjad.Container([])
    container.extend(selections)
    # # Add analysis brackets so we can see the phrasing graphically
    # start_indicator = abjad.LilyPondLiteral('\startGroup', format_slot='after')
Exemplo n.º 39
0
 def attach_last_leaf(self, leaf: abjad.Chord, novent) -> None:
     abjad.attach(abjad.LilyPondLiteral("\\endParenthesis"), leaf)
     self.attach(leaf, novent)
Exemplo n.º 40
0
 def attach_middle_leaf(self, leaf: abjad.Chord, novent) -> None:
     abjad.attach(abjad.LilyPondLiteral("\\once \\tiny"), leaf)
Exemplo n.º 41
0
 def _attach_grace_not_style(leaf) -> None:
     abjad.attach(
         abjad.LilyPondLiteral(
             '\\once \\override Flag.stroke-style = #"grace"'),
         leaf,
     )
Exemplo n.º 42
0
def _show_transforms():
    voice = abjad.Voice(name="Voice")
    staff = abjad.Staff([voice], name="Staff")
    score = abjad.Score([staff], name="Score")
    segments, names = library.silver_start()
    _add_segments_to_voice(voice, "start", segments, names, do_not_page_break=True)
    segments, names = library.silver_transform_1()
    _add_segments_to_voice(
        voice, "transform 1", segments, names, do_not_page_break=True
    )
    segments, names = library.silver_transform_2()
    _add_segments_to_voice(voice, "transform 2", segments, names)
    segments, names = library.silver_transform_3()
    _add_segments_to_voice(voice, "transform 3", segments, names)
    segments, names = library.silver_transform_4()
    _add_segments_to_voice(voice, "transform 4", segments, names)
    segments, names = library.silver_transform_5()
    _add_segments_to_voice(voice, "transform 5", segments, names)
    segments, names = library.silver_transform_6()
    _add_segments_to_voice(voice, "transform 6", segments, names)
    segments, names = library.silver_transform_7()
    _add_segments_to_voice(voice, "transform 7", segments, names)

    leaf = abjad.select.leaf(score, 0)
    time_signature = abjad.TimeSignature((1, 8))
    abjad.attach(time_signature, leaf)
    literal = abjad.LilyPondLiteral("#(set-accidental-style 'forget)")
    abjad.attach(literal, leaf)
    preamble = r"""#(set-default-paper-size "letter")
    #(set-global-staff-size 14)

    \paper
    {
      bottom-margin = 15
      evenFooterMarkup = \markup \fill-line { "Mráz (silver transforms)" }
      indent = 0
      oddFooterMarkup = \evenFooterMarkup
      ragged-last = ##t
      ragged-last-bottom = ##t
      ragged-right = ##t
      top-margin = 20
      left-margin = 15
      print-page-number = ##f
      system-system-spacing.padding = 12
      tagline = ##f
    }

    \layout
    {
      \context
      {
        \Voice
        \remove Forbid_line_break_engraver
        \consists Horizontal_bracket_engraver
      }
      \context
      {
        \Score
        \remove Bar_number_engraver
        \override BarLine.transparent = ##t
        \override Flag.stencil = ##f
        \override HorizontalBracket.bracket-flare = #'(0 . 0)
        \override HorizontalBracket.staff-padding = 5
        \override HorizontalBracket.thickness = 2
        \override HorizontalBracketText.bracket = ##f
        \override HorizontalBracketText.padding = 1.5
        \override NonMusicalPaperColumn.line-break-permission = ##f
        \override Rest.transparent = ##t
        \override SpacingSpanner.strict-note-spacing = ##t
        \override SpacingSpanner.uniform-stretching = ##t
        \override SpanBar.transparent = ##t
        \override Stem.stencil = ##f
        \override TimeSignature.stencil = ##f
        autoBeaming = ##f
        proportionalNotationDuration = #(ly:make-moment 1 16)
      }
    }"""
    preamble = _trim_block_string(preamble)
    lilypond_file = abjad.LilyPondFile([preamble, score])
    name = "show/transforms"
    print(f"Writing {name} ...")
    abjad.persist.as_pdf(lilypond_file, name)
Exemplo n.º 43
0
    def __call__(self) -> abjad.Score:
        """
        Calls score template.
        """
        # GLOBAL CONTEXT
        global_context = abjad.Voice(name="Global_Context")
        global_context_ii = abjad.Voice(name="Global_Context_II")
        global_context_iii = abjad.Voice(name="Global_Context_III")

        # RH STAFF
        rh_voice_one = abjad.Voice(name="RH_Voice_One")
        # command = abjad.LilyPondLiteral(r"\voiceOne")
        # abjad.attach(command, rh_voice_one)
        # abjad.override(rh_voice_one).stem.direction = abjad.Up
        # abjad.override(rh_voice_one).tie.direction = abjad.Up
        rh_voice_two = abjad.Voice(name="RH_Voice_Two")
        # command = abjad.LilyPondLiteral(r"\voiceTwo")
        # abjad.attach(command, rh_voice_two)
        # abjad.override(rh_voice_two).stem.direction = abjad.Down
        # abjad.override(rh_voice_two).tie.direction = abjad.Down
        rh_voice_three = abjad.Voice(name="RH_Voice_Three")
        # command = abjad.LilyPondLiteral(r"\voiceThree")
        # abjad.attach(command, rh_voice_three)
        # abjad.override(rh_voice_three).stem.direction = abjad.Down
        # abjad.override(rh_voice_three).tie.direction = abjad.Down
        rh_staff = abjad.Staff(
            [global_context, rh_voice_one, rh_voice_two, rh_voice_three],
            name="RH_Staff")
        rh_staff.simultaneous = True

        # LH STAFF
        lh_voice_one = abjad.Voice(name="LH_Voice_Four")
        lh_voice_two = abjad.Voice(name="LH_Voice_Five")
        lh_staff = abjad.Staff([global_context_ii, lh_voice_one, lh_voice_two],
                               name="LH_Staff")
        lh_staff.simultaneous = True

        # ORGAN STAFF
        piano_group = abjad.StaffGroup(
            [rh_staff, lh_staff],
            lilypond_type="PianoStaff",
            name="Piano_Staff",
        )
        abjad.annotate(piano_group, "default_instrument", abjad.Piano())
        instrumentName_piano = abjad.LilyPondLiteral(
            r"\set PianoStaff.instrumentName = \markup{Organ}")
        abjad.attach(instrumentName_piano, piano_group)

        # ELECTRONICS
        # ELECTRONICS RH STAFF
        voice_one_elec = abjad.Voice(name="RH_Voice_One_Electronics")
        electronics = abjad.Staff([global_context_iii, voice_one_elec],
                                  name="Electronics_Staff")
        electronics.simultaneous = True

        abjad.annotate(electronics, "default_instrument", abjad.Piano())
        instrumentName_electronics = abjad.LilyPondLiteral(
            r"\set Staff.instrumentName = \markup{Electronics}")
        abjad.attach(instrumentName_electronics, electronics)

        # SCORE
        score = abjad.Score(
            [piano_group, electronics],
            name="Score",
        )
        # abjad.override(score).script.padding = 1.1
        # abjad.override(score).spacing_spanner.strict_grace_spacing = True
        # abjad.override(score).spacing_spanner.strict_note_spacing = True
        # abjad.override(score).spacing_spanner.uniform_stretching = True
        # abjad.override(score).stem.length = 8
        # abjad.override(score).text_script.outside_staff_padding = 1
        # abjad.override(score).tuplet_bracket.bracket_visibility = True
        # abjad.override(score).tuplet_bracket.minimum_length = 3
        # abjad.override(score).tuplet_bracket.outside_staff_padding = 1.5
        # abjad.override(score).tuplet_bracket.padding = 1.5
        # abjad.override(score).tuplet_bracket.springs_and_rods = \
        #     abjad.scheme.Scheme('ly:spanner::set-spacing-rods', verbatim=True)
        # abjad.override(score).tuplet_bracket.staff_padding = 2.25
        # abjad.override(score).tuplet_number.text = \
        #     abjad.scheme.Scheme(
        #         'tuplet-number::calc-fraction-text', verbatim=True)
        # abjad.setting(score).proportional_notation_duration = \
        #     abjad.scheme.SchemeMoment((1, 24))
        # abjad.setting(score).tuplet_full_length = True

        return score
Exemplo n.º 44
0
    def make_skips(self, time_signatures, attach=()):
        r"""Write skips and time signatures to "Global_Context".

        >>> my_score.make_skips([(4, 4), (5, 4)])
        muda.Score.make_skips()
        >>> print(abjad.lilypond(my_score.score))
        \context Score = "Score"
        <<
            \context TimeSignatureContext = "Global_Context"
            {
                \time 4/4
                s1 * 1
                \time 5/4
                s1 * 5/4
            }
            \context PianoStaff = "Piano_StaffGroup"
            <<
                \context Staff = "Piano_Staff_1"
                <<
                    \context Voice = "Piano_Voice_1"
                    {
                    }
                    \context Voice = "Piano_Voice_2"
                    {
                    }
                >>
                \context Staff = "Piano_Staff_2"
                <<
                    \context Voice = "Piano_Voice_3"
                    {
                    }
                >>
            >>
        >>
        """
        site = "muda.Score.make_skips()"
        tag = abjad.Tag(site)
        print(str(tag))

        if isinstance(time_signatures[0], abjad.TimeSignature):
            time_signatures_abjad = time_signatures
            in_time_signatures = [_.pair for _ in time_signatures]
        else:
            in_time_signatures = time_signatures
            time_signatures_abjad = [
                abjad.TimeSignature(_) for _ in in_time_signatures
            ]

        for time_sig in time_signatures_abjad:
            skip = abjad.Skip(1, multiplier=(time_sig.pair))
            self.score["Global_Context"].append(skip)

        # select skips to attach TIME SIGNATURES
        for i, item in enumerate(in_time_signatures):
            a = in_time_signatures.index(item)
            abjad.attach(time_signatures_abjad[a],
                         self.score["Global_Context"][i],
                         tag=tag)

        def attach(argument, select):
            selection = select(self.score["Global_Context"])
            if isinstance(selection, abjad.Leaf):
                abjad.attach(argument, selection)
            else:
                for skip_ in selection:
                    abjad.attach(argument, skip_)
Exemplo n.º 45
0
    def __illustrate__(self):
        r"""
        Illustrates pitch range.

        ..  container:: example

            >>> pitch_range = abjad.PitchRange('[C3, C7]')
            >>> abjad.show(pitch_range) # doctest: +SKIP

            ..  docs::

                >>> lilypond_file = pitch_range.__illustrate__()
                >>> abjad.f(lilypond_file[abjad.Score])
                \new Score
                \with
                {
                    \override BarLine.stencil = ##f
                    \override Glissando.thickness = #2
                    \override SpanBar.stencil = ##f
                    \override TimeSignature.stencil = ##f
                }
                <<
                    \new PianoStaff
                    <<
                        \context Staff = "Treble Staff"
                        {
                            \clef "treble"
                            s1 * 1/4
                            s1 * 1/4
                        }
                        \context Staff = "Bass Staff"
                        {
                            \clef "bass"
                            c1 * 1/4
                            \glissando
                            \change Staff = "Treble Staff"
                            c''''1 * 1/4
                        }
                    >>
                >>

        Returns LilyPond file.
        """
        import abjad
        start_pitch_clef = abjad.Clef.from_selection(self.start_pitch)
        stop_pitch_clef = abjad.Clef.from_selection(self.stop_pitch)
        start_note = abjad.Note(self.start_pitch, 1)
        stop_note = abjad.Note(self.stop_pitch, 1)
        glissando = abjad.Glissando()
        if start_pitch_clef == stop_pitch_clef:
            if start_pitch_clef == abjad.Clef('bass'):
                bass_staff = abjad.Staff()
                abjad.attach(abjad.Clef('bass'), bass_staff)
                bass_staff.extend([start_note, stop_note])
                bass_leaves = abjad.select(bass_staff).leaves()
                abjad.attach(glissando, bass_leaves)
                score = abjad.Score([bass_staff])
            else:
                treble_staff = abjad.Staff()
                abjad.attach(abjad.Clef('treble'), treble_staff)
                treble_staff.extend([start_note, stop_note])
                treble_leaves = abjad.select(treble_staff).leaves()
                abjad.attach(glissando, treble_leaves)
                score = abjad.Score([treble_staff])
        else:
            result = abjad.Score.make_piano_score()
            score, treble_staff, bass_staff = result
            bass_staff.extend([start_note, stop_note])
            treble_staff.extend(abjad.Skip(1) * 2)
            bass_leaves = abjad.select(bass_staff).leaves()
            abjad.attach(glissando, bass_leaves)
            abjad.attach(abjad.StaffChange(treble_staff), bass_staff[1])
            abjad.attach(abjad.Clef('treble'), treble_staff[0])
            abjad.attach(abjad.Clef('bass'), bass_staff[0])
        for leaf in abjad.iterate(score).leaves():
            abjad.attach(abjad.Multiplier(1, 4), leaf)
        abjad.override(score).bar_line.stencil = False
        abjad.override(score).span_bar.stencil = False
        abjad.override(score).glissando.thickness = 2
        abjad.override(score).time_signature.stencil = False
        lilypond_file = abjad.LilyPondFile.new(score)
        return lilypond_file
Exemplo n.º 46
0
    def write_materials(self, materials_list):
        r"""Write materials to voices. (TODO)

        >>> material_01 = muda.Material("Piano_Voice_1")
        >>> material_01.silence_and_rhythm_maker(
        ...     maker=rmakers.stack(
        ...             rmakers.talea([1, -3, 1], 16),
        ...             rmakers.extract_trivial(),
        ...             rmakers.beam()),
        ...     annotated_divisions=[
        ...             muda.AnnotatedDuration((1, 4)),
        ...             muda.AnnotatedDuration((2, 4), annotation="Rest"),
        ...             muda.AnnotatedDuration((1, 4)),
        ...             muda.AnnotatedDuration((2, 4), annotation="Rest"),
        ...             muda.AnnotatedDuration((3, 4)),]
        ... )
        >>> material_01.write_pitches(["d'"])

        >>> material_02 = muda.Material("Piano_Voice_3")
        >>> material_02.silence_and_rhythm_maker(
        ...     maker=rmakers.stack(
        ...         rmakers.talea([-1, 1, 1, 1], 16),
        ...         rmakers.extract_trivial(),
        ...         rmakers.beam(),
        ...         ),
        ...     annotated_divisions=[
        ...         muda.AnnotatedDuration((3, 8)),
        ...         muda.AnnotatedDuration((3, 8), annotation="Rest"),
        ...         muda.AnnotatedDuration((3, 8)),
        ...         muda.AnnotatedDuration((3, 8), annotation="Rest"),
        ...         muda.AnnotatedDuration((4, 8)),
        ...         muda.AnnotatedDuration((2, 8)),
        ...         ]
        ...     )

        >>> material_list = [material_01, material_02]
        >>> my_score.write_materials(material_list)
        >>> my_score.rewrite_meter(my_divisions)
        rewriting meter: Piano_Voice_1
        rewriting meter: Piano_Voice_3
        <Score-"Score"<<2>>>
        >>> print(abjad.lilypond(my_score.score))
        \context Score = "Score"
        <<
            \context TimeSignatureContext = "Global_Context"
            {
                \time 4/4
                s1 * 1
                \time 5/4
                s1 * 5/4
            }
            \context PianoStaff = "Piano_StaffGroup"
            <<
                \context Staff = "Piano_Staff_1"
                <<
                    \context Voice = "Piano_Voice_1"
                    {
                        d'16
                        r8.
                        r4
                        r4
                        d'16
                        r8.
                        r2
                        d'16
                        r8.
                        d'16
                        d'16
                        r8
                        r16
                        d'16
                        d'16
                        r16
                    }
                    \context Voice = "Piano_Voice_2"
                    {
                    }
                >>
                \context Staff = "Piano_Staff_2"
                <<
                    \context Voice = "Piano_Voice_3"
                    {
                        r16
                        c'16
                        c'16
                        c'16
                        r16
                        c'16
                        r8
                        r4
                        r16
                        c'16
                        c'16
                        c'16
                        r16
                        c'16
                        r4.
                        r16
                        c'16
                        c'16
                        c'16
                        r16
                        c'16
                        c'16
                        c'16
                        r16
                        c'16
                        c'16
                        c'16
                   }
                >>
            >>
        >>


        .. lily::
            :noedge:
            :audio:

            \version "2.20.0"

            \context Score = "Score"
            <<
                \context TimeSignatureContext = "Global_Context"
                {
                    \time 4/4
                    s1 * 1
                    \time 5/4
                    s1 * 5/4
                }
                \context PianoStaff = "Piano_StaffGroup"
                <<
                    \context Staff = "Piano_Staff_1"
                    <<
                        \context Voice = "Piano_Voice_1"
                        {
                            d'16
                            r8.
                            r4
                            r4
                            d'16
                            r8.
                            r2
                            d'16
                            r8.
                            d'16
                            d'16
                            r8
                            r16
                            d'16
                            d'16
                            r16
                        }
                        \context Voice = "Piano_Voice_2"
                        {
                        }
                    >>
                    \context Staff = "Piano_Staff_2"
                    <<
                        \context Voice = "Piano_Voice_3"
                        {
                            r16
                            c'16
                            c'16
                            c'16
                            r16
                            c'16
                            r8
                            r4
                            r16
                            c'16
                            c'16
                            c'16
                            r16
                            c'16
                            r4.
                            r16
                            c'16
                            c'16
                            c'16
                            r16
                            c'16
                            c'16
                            c'16
                            r16
                            c'16
                            c'16
                            c'16
                                                 }
                    >>
                >>
            >>

        """
        for material in materials_list:
            if material.lyrics is not None:
                lit = abjad.LilyPondLiteral(r'\lyricsto "' + material.target +
                                            r'" { \lyricmode {' +
                                            material.lyrics + "}}")
                abjad.attach(lit, self.score[material.name])
            else:
                self.score[material.name].extend(material.container)
Exemplo n.º 47
0
def apply_dynamics(score):
    """
    Applies dynamics to score.
    """

    voice = score['Bell Voice']
    dynamic = abjad.Dynamic('ppp')
    abjad.attach(dynamic, voice[0][1])
    dynamic = abjad.Dynamic('pp')
    abjad.attach(dynamic, voice[8][1])
    dynamic = abjad.Dynamic('p')
    abjad.attach(dynamic, voice[18][1])
    dynamic = abjad.Dynamic('mp')
    abjad.attach(dynamic, voice[26][1])
    dynamic = abjad.Dynamic('mf')
    abjad.attach(dynamic, voice[34][1])
    dynamic = abjad.Dynamic('f')
    abjad.attach(dynamic, voice[42][1])
    dynamic = abjad.Dynamic('ff')
    abjad.attach(dynamic, voice[52][1])
    dynamic = abjad.Dynamic('fff')
    abjad.attach(dynamic, voice[60][1])
    dynamic = abjad.Dynamic('ff')
    abjad.attach(dynamic, voice[68][1])
    dynamic = abjad.Dynamic('f')
    abjad.attach(dynamic, voice[76][1])
    dynamic = abjad.Dynamic('mf')
    abjad.attach(dynamic, voice[84][1])
    dynamic = abjad.Dynamic('pp')
    abjad.attach(dynamic, voice[-1][0])

    voice = score['First Violin Voice']
    dynamic = abjad.Dynamic('ppp')
    abjad.attach(dynamic, voice[6][1])
    dynamic = abjad.Dynamic('pp')
    abjad.attach(dynamic, voice[15][0])
    dynamic = abjad.Dynamic('p')
    abjad.attach(dynamic, voice[22][3])
    dynamic = abjad.Dynamic('mp')
    abjad.attach(dynamic, voice[31][0])
    dynamic = abjad.Dynamic('mf')
    abjad.attach(dynamic, voice[38][3])
    dynamic = abjad.Dynamic('f')
    abjad.attach(dynamic, voice[47][0])
    dynamic = abjad.Dynamic('ff')
    abjad.attach(dynamic, voice[55][2])
    dynamic = abjad.Dynamic('fff')
    abjad.attach(dynamic, voice[62][2])

    voice = score['Second Violin Voice']
    dynamic = abjad.Dynamic('pp')
    abjad.attach(dynamic, voice[7][0])
    dynamic = abjad.Dynamic('p')
    abjad.attach(dynamic, voice[12][0])
    dynamic = abjad.Dynamic('p')
    abjad.attach(dynamic, voice[16][0])
    dynamic = abjad.Dynamic('mp')
    abjad.attach(dynamic, voice[25][1])
    dynamic = abjad.Dynamic('mf')
    abjad.attach(dynamic, voice[34][1])
    dynamic = abjad.Dynamic('f')
    abjad.attach(dynamic, voice[44][1])
    dynamic = abjad.Dynamic('ff')
    abjad.attach(dynamic, voice[54][0])
    dynamic = abjad.Dynamic('fff')
    abjad.attach(dynamic, voice[62][1])

    voice = score['Viola Voice']
    dynamic = abjad.Dynamic('p')
    abjad.attach(dynamic, voice[8][0])
    dynamic = abjad.Dynamic('mp')
    abjad.attach(dynamic, voice[19][1])
    dynamic = abjad.Dynamic('mf')
    abjad.attach(dynamic, voice[30][0])
    dynamic = abjad.Dynamic('f')
    abjad.attach(dynamic, voice[36][0])
    dynamic = abjad.Dynamic('f')
    abjad.attach(dynamic, voice[42][0])
    dynamic = abjad.Dynamic('ff')
    abjad.attach(dynamic, voice[52][0])
    dynamic = abjad.Dynamic('fff')
    abjad.attach(dynamic, voice[62][0])

    voice = score['Cello Voice']
    dynamic = abjad.Dynamic('p')
    abjad.attach(dynamic, voice[10][0])
    dynamic = abjad.Dynamic('mp')
    abjad.attach(dynamic, voice[21][0])
    dynamic = abjad.Dynamic('mf')
    abjad.attach(dynamic, voice[31][0])
    dynamic = abjad.Dynamic('f')
    abjad.attach(dynamic, voice[43][0])
    dynamic = abjad.Dynamic('ff')
    abjad.attach(dynamic, voice[52][1])
    dynamic = abjad.Dynamic('fff')
    abjad.attach(dynamic, voice[62][0])

    voice = score['Bass Voice']
    dynamic = abjad.Dynamic('mp')
    abjad.attach(dynamic, voice[14][0])
    dynamic = abjad.Dynamic('mf')
    abjad.attach(dynamic, voice[27][0])
    dynamic = abjad.Dynamic('f')
    abjad.attach(dynamic, voice[39][0])
    dynamic = abjad.Dynamic('ff')
    abjad.attach(dynamic, voice[51][0])
    dynamic = abjad.Dynamic('fff')
    abjad.attach(dynamic, voice[62][0])
Exemplo n.º 48
0
def test_CrossFader_20():
    random.seed(87144)
    fade_out_container = abjad.Container(r"b'8 c''8 e''2 g''4")
    fade_in_container = abjad.Container(r"\times 2/3 {e'2 d'2 c'2}")
    fader = auxjad.CrossFader(fade_out_container, fade_in_container)
    selection_a, selection_b = fader.output_all()
    literal_voice_one = abjad.LilyPondLiteral(r'\voiceOne')
    literal_voice_two = abjad.LilyPondLiteral(r'\voiceTwo')
    abjad.attach(literal_voice_one, selection_a[0])
    abjad.attach(literal_voice_two, selection_b[0])
    staff = abjad.Staff(
        [abjad.Voice(selection_a), abjad.Voice(selection_b)],
        simultaneous=True,
    )
    assert abjad.lilypond(staff) == abjad.String.normalize(
        r"""
        \new Staff
        <<
            \new Voice
            {
                \time 4/4
                \voiceOne
                b'8
                c''8
                e''2
                g''4
                b'8
                c''8
                e''2
                r4
                b'8
                c''8
                e''2
                r4
                b'8
                c''8
                e''2
                r4
                b'8
                c''8
                e''2
                r4
                b'8
                c''8
                r2.
                b'8
                r2..
                R1
            }
            \new Voice
            {
                \time 4/4
                \voiceTwo
                R1
                R1
                \times 2/3
                {
                    r1
                    c'2
                }
                \times 2/3
                {
                    e'2
                    r2
                    c'2
                }
                \times 2/3
                {
                    e'2
                    d'2
                    c'2
                }
                \times 2/3
                {
                    e'2
                    d'2
                    c'2
                }
                \times 2/3
                {
                    e'2
                    d'2
                    c'2
                }
                \times 2/3
                {
                    e'2
                    d'2
                    c'2
                }
            }
        >>
        """
    )
Exemplo n.º 49
0
def configure_score(score):
    """
    Configures score.
    """
    # configure bell staff
    bell_staff = score['Bell Staff']
    leaf = abjad.inspect(bell_staff).leaf(0)
    clef = abjad.Clef('treble')
    abjad.attach(clef, leaf)
    bells = abjad.Instrument(
        name='Campana in La',
        short_name='Camp.',
        pitch_range='[C4, C6]',
    )
    abjad.attach(bells, leaf)
    mark = abjad.MetronomeMark((1, 4), (112, 120))
    abjad.attach(mark, leaf)
    #time_signature = abjad.TimeSignature((6, 4))
    #abjad.attach(time_signature, leaf)
    # configure first violin staff
    first_violin_staff = score['First Violin Staff']
    leaf = abjad.inspect(first_violin_staff).leaf(0)
    clef = abjad.Clef('treble')
    abjad.attach(clef, leaf)
    violin = abjad.Violin(
        markup=abjad.Markup('Violin I'),
        short_markup=abjad.Markup('Vl. I'),
    )
    abjad.attach(violin, leaf)
    # configure second violin staff
    second_violin_staff = score['Second Violin Staff']
    leaf = abjad.inspect(second_violin_staff).leaf(0)
    clef = abjad.Clef('treble')
    abjad.attach(clef, leaf)
    violin = abjad.Violin(
        markup=abjad.Markup('Violin II'),
        short_markup=abjad.Markup('Vl. II'),
    )
    abjad.attach(violin, leaf)
    # configure viola staff
    leaf = abjad.inspect(score['Viola Staff']).leaf(0)
    clef = abjad.Clef('alto')
    abjad.attach(clef, leaf)
    viola = abjad.Viola()
    abjad.attach(viola, leaf)
    # configure cello staff
    leaf = abjad.inspect(score['Cello Staff']).leaf(0)
    clef = abjad.Clef('bass')
    abjad.attach(clef, leaf)
    cello = abjad.Cello()
    abjad.attach(cello, leaf)
    # configure bass staff
    leaf = abjad.inspect(score['Bass Staff']).leaf(0)
    clef = abjad.Clef('bass')
    abjad.attach(clef, leaf)
    contrabass = abjad.Contrabass(short_markup=abjad.Markup('Cb.'), )
    abjad.attach(contrabass, leaf)
    # configure score
    vector = abjad.SpacingVector(0, 0, 8, 0)
    abjad.override(score).vertical_axis_group.staff_staff_spacing = vector
    abjad.override(score).staff_grouper.staff_staff_spacing = vector
    abjad.override(score).staff_symbol.thickness = 0.5
    scheme = abjad.Scheme('format-mark-box-numbers')
    abjad.setting(score).mark_formatter = scheme
Exemplo n.º 50
0
 def attach(self, leaf: abjad.Chord, novent) -> None:
     # for head in leaf.note_heads:
     #     abjad.tweak(head).color = "red"
     abjad.attach(abjad.Markup("\\teeny \\circle 1", direction="up"), leaf)
Exemplo n.º 51
0
import abjad

def tie():
    """
    Makes a tie on a single leaf.
    """
    return abjad.LilyPondLiteral("~", "after")

if __name__ == '__main__':
    voice = r"c'4 d'2 f'4 f'2 e'2"
    staff = abjad.Staff(voice)
    abjad.attach(tie(), staff[2])
    abjad.f(staff)

Exemplo n.º 52
0
 def attach(self, leaf: abjad.Chord, novent) -> None:
     abjad.attach(
         abjad.StemTremolo(32 * (2**leaf.written_duration.flag_count)),
         leaf)
Exemplo n.º 53
0
def make_bartok_score():
    score = abjad.Score()
    piano_staff = abjad.StaffGroup([], lilypond_type='PianoStaff')
    upper_staff = abjad.Staff([])
    lower_staff = abjad.Staff([])
    piano_staff.append(upper_staff)
    piano_staff.append(lower_staff)
    score.append(piano_staff)
    upper_measures = []
    upper_measures.append(abjad.Measure((2, 4), []))
    upper_measures.append(abjad.Measure((3, 4), []))
    upper_measures.append(abjad.Measure((2, 4), []))
    upper_measures.append(abjad.Measure((2, 4), []))
    upper_measures.append(abjad.Measure((2, 4), []))
    lower_measures = copy.deepcopy(upper_measures)
    upper_staff.extend(upper_measures)
    lower_staff.extend(lower_measures)
    upper_measures[0].extend("a'8 g'8 f'8 e'8")
    upper_measures[1].extend("d'4 g'8 f'8 e'8 d'8")
    upper_measures[2].extend("c'8 d'16 e'16 f'8 e'8")
    upper_measures[3].append("d'2")
    upper_measures[4].append("d'2")
    lower_measures[0].extend("b4 d'8 c'8")
    lower_measures[1].extend("b8 a8 af4 c'8 bf8")
    lower_measures[2].extend("a8 g8 fs8 g16 a16")
    upper_voice = abjad.Voice("b2", name='upper voice')
    command = abjad.LilyPondCommand('voiceOne')
    abjad.attach(command, upper_voice)
    lower_voice = abjad.Voice("b4 a4", name='lower voice')
    command = abjad.LilyPondCommand('voiceTwo')
    abjad.attach(command, lower_voice)
    lower_measures[3].extend([upper_voice, lower_voice])
    lower_measures[3].is_simultaneous = True
    upper_voice = abjad.Voice("b2", name='upper voice')
    command = abjad.LilyPondCommand('voiceOne')
    abjad.attach(command, upper_voice)
    lower_voice = abjad.Voice("g2", name='lower voice')
    command = abjad.LilyPondCommand('voiceTwo')
    abjad.attach(command, lower_voice)
    lower_measures[4].extend([upper_voice, lower_voice])
    lower_measures[4].is_simultaneous = True
    clef = abjad.Clef('bass')
    leaf = abjad.inspect(lower_staff).get_leaf(0)
    abjad.attach(clef, leaf)
    dynamic = abjad.Dynamic('pp')
    abjad.attach(dynamic, upper_measures[0][0])
    dynamic = abjad.Dynamic('mp')
    abjad.attach(dynamic, upper_measures[1][1])
    dynamic = abjad.Dynamic('pp')
    abjad.attach(dynamic, lower_measures[0][1])
    dynamic = abjad.Dynamic('mp')
    abjad.attach(dynamic, lower_measures[1][3])
    score.add_final_bar_line()
    abjad.selector = abjad.select().leaves()
    upper_leaves = abjad.selector(upper_staff)
    lower_leaves = abjad.selector(lower_staff)
    beam = abjad.Beam()
    abjad.attach(beam, upper_leaves[:4])
    beam = abjad.Beam()
    abjad.attach(beam, lower_leaves[1:5])
    beam = abjad.Beam()
    abjad.attach(beam, lower_leaves[6:10])
    slur = abjad.Slur()
    abjad.attach(slur, upper_leaves[:5])
    slur = abjad.Slur()
    abjad.attach(slur, upper_leaves[5:])
    slur = abjad.Slur()
    abjad.attach(slur, lower_leaves[1:6])
    crescendo = abjad.Hairpin('<')
    abjad.attach(crescendo, upper_leaves[-7:-2])
    diminuendo = abjad.Hairpin('>')
    abjad.attach(diminuendo, upper_leaves[-2:])
    markup = abjad.Markup('ritard.')
    text_spanner = abjad.TextSpanner()
    abjad.override(text_spanner).text_spanner.bound_details__left__text = markup
    abjad.attach(text_spanner, upper_leaves[-7:])
    tie = abjad.Tie()
    abjad.attach(tie, upper_leaves[-2:])
    note_1 = lower_staff[-2]['upper voice'][0]
    note_2 = lower_staff[-1]['upper voice'][0]
    notes = abjad.select([note_1, note_2])
    abjad.attach(abjad.Tie(), notes)
    return score
Exemplo n.º 54
0
 def attach(self, leaf: abjad.Chord, novent) -> None:
     abjad.attach(self._markup, leaf)
Exemplo n.º 55
0
def make_desordre_cell(pitches):
    """
    Makes a Désordre cell.
    """

    notes = [abjad.Note(pitch, (1, 8)) for pitch in pitches]
    notes = abjad.Selection(notes)
    abjad.beam(notes)
    abjad.slur(notes)
    clef = abjad.Dynamic('f')
    abjad.attach(clef, notes[0])
    dynamic = abjad.Dynamic('p')
    abjad.attach(dynamic, notes[1])

    # make the lower voice
    lower_voice = abjad.Voice(notes)
    lower_voice.name = 'RH Lower Voice'
    command = abjad.LilyPondLiteral(r'\voiceTwo')
    abjad.attach(command, lower_voice)
    n = int(math.ceil(len(pitches) / 2.))
    chord = abjad.Chord([pitches[0], pitches[0] + 12], (n, 8))
    articulation = abjad.Articulation('>')
    abjad.attach(articulation, chord)

    # make the upper voice
    upper_voice = abjad.Voice([chord])
    upper_voice.name = 'RH Upper Voice'
    command = abjad.LilyPondLiteral(r'\voiceOne')
    abjad.attach(command, upper_voice)

    # combine them together
    container = abjad.Container([lower_voice, upper_voice])
    container.is_simultaneous = True

    # make all 1/8 beats breakable
    leaves = abjad.select(lower_voice).leaves()
    for leaf in leaves[:-1]:
        bar_line = abjad.BarLine('')
        abjad.attach(bar_line, leaf)

    return container
Exemplo n.º 56
0
def rests_to_multimeasure_rest(
    selection: abjad.Selection,
    *,
    ignore_clefs: bool = False,
    ignore_dynamics: bool = False,
) -> None:
    r"""Mutates an input |abjad.Selection| in place and has no return value;
    this function looks for measures filled with regular rests and converts
    them into an |abjad.MultimeasureRest|.

    Basic usage:
        Converts any measure filled with regular rests into a measure with a
        single multi-measure rest.

        >>> container = abjad.Container(r"\time 3/4 r2.")
        >>> abjad.show(container)

        ..  docs::

            {
                \time 3/4
                r2.
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-VIj5iWyLCG.png

        >>> auxjad.mutate.rests_to_multimeasure_rest(container[:])
        >>> abjad.show(container)

        ..  docs::

            {
                \time 3/4
                R1 * 3/4
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-uvebc7ft1zo.png

    ..  note::

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

        >>> auxjad.mutate.rests_to_multimeasure_rest(staff[:])
        >>> abjad.mutate.rests_to_multimeasure_rest(staff[:])

    Multiple rests:
        Works with measures with multiple regular rests.

        >>> container = abjad.Container(r"r2 r8.. r32 r16 r8 r16")
        >>> abjad.show(container)

        ..  docs::

            {
                r2
                r8..
                r32
                r16
                r8
                r16
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-jk4m1wzsyfa.png

        >>> auxjad.mutate.rests_to_multimeasure_rest(container[:])
        >>> abjad.show(container)

        ..  docs::

            {
                R1
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-z8u0cs3fzdi.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.show(container)

        ..  docs::

            {
                %%% \time 3/4 %%%
                c'4
                d'4
                e'4
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-qtq55xbkkts.png

        >>> staff = abjad.Staff([container])
        >>> abjad.show(container)

        ..  docs::

            {
                \time 3/4
                c'4
                d'4
                e'4
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-9hceg93vrmv.png

    Time signature changes:
        Works with selections from containers with multiple time signatures as
        well as notes.

        >>> container = abjad.Staff(
        ...     r"\time 3/4 r2. | "
        ...     "\time 6/8 r2. | "
        ...     "\time 5/4 c'1 ~ c'4 | r1 r4"
        ... )
        >>> abjad.show(container)

        ..  docs::

            \new Staff
            {
                \time 3/4
                r2.
                \time 6/8
                r2.
                \time 5/4
                c'1
                ~
                c'4
                r1
                r4
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-oQfFRihzEY.png

        >>> auxjad.mutate.rests_to_multimeasure_rest(container[:])
        >>> abjad.show(container)

        ..  docs::

            \new Staff
            {
                \time 3/4
                R1 * 3/4
                \time 6/8
                R1 * 3/4
                \time 5/4
                c'1
                ~
                c'4
                R1 * 5/4
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-a9sqdcznoq.png

    Tuplets:
        Works with containers with tuplets.

        >>> container = abjad.Container(r"\times 2/3 {r2 r2 r2}")
        >>> abjad.show(container)

        ..  docs::

            {
                \times 2/3
                {
                    r2
                    r2
                    r2
                }
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-480a9zqvk2a.png

        >>> auxjad.mutate.rests_to_multimeasure_rest(container[:])
        >>> abjad.show(container)

        ..  docs::

            {
                R1
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-r5yg3a3f97q.png

        It also works with containers with tuplets within tuplets.

        >>> container = abjad.Container(
        ...     r"r2 \times 2/3 {r2 r4} \times 4/5 {r2. \times 2/3 {r2 r4}}"
        ... )
        >>> abjad.show(container)

        ..  docs::

            {
                r2
                \times 2/3
                {
                    r2
                    r4
                }
                \times 4/5
                {
                    r2.
                    \times 2/3
                    {
                        r2
                        r4
                    }
                }
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-codydc205jw.png

        >>> auxjad.mutate.rests_to_multimeasure_rest(container[:])
        >>> abjad.show(container)

        ..  docs::

            {
                R1
                R1
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-f647t5j3jgw.png

    ``ignore_clefs``
        By default, the last clef of an empty measure is preserved when
        replacing it with a multi-measure rest:

        >>> staff = abjad.Staff(
        ...     r"\clef bass r4 r4 \times 2/3 {r4 r8} r4 "
        ...     r"\time 3/4 \clef treble r2. "
        ...     r"\time 5/4 r2 \clef bass r2."
        ... )
        >>> abjad.show(staff)

        ..  docs::

            \new Staff
            {
                \clef "bass"
                r4
                r4
                \times 2/3
                {
                    r4
                    r8
                }
                r4
                \time 3/4
                \clef "treble"
                r2.
                \time 5/4
                r2
                \clef "bass"
                r2.
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-6GMRGmYkEQ.png

        >>> abjad.mutate.rests_to_multimeasure_rest(staff[:])
        >>> abjad.show(staff)

        ..  docs::

            \new Staff
            {
                \clef "bass"
                R1
                \time 3/4
                \clef "treble"
                R1 * 3/4
                \time 5/4
                \clef "bass"
                R1 * 5/4
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-UnL6ZoFoDC.png

        Invoke the mutation with ``ignore_clefs`` set to ``True`` to disable
        this behaviour and ignore all clefs:

        >>> staff = abjad.Staff(
        ...     r"\clef bass r4 r4 \times 2/3 {r4 r8} r4 "
        ...     r"\time 3/4 \clef treble r2. "
        ...     r"\time 5/4 r2 \clef bass r2."
        ... )
        >>> abjad.mutate.rests_to_multimeasure_rest(
        ...     staff[:],
        ...     ignore_clefs=True,
        ... )
        >>> abjad.show(staff)

        ..  docs::

            \new Staff
            {
                R1
                \time 3/4
                R1 * 3/4
                \time 5/4
                R1 * 5/4
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-KGRZJ8fvQF.png

    ``ignore_dynamics``
        By default, the last dynamic or hairpin of an empty measure is
        preserved when replacing it with a multi-measure rest:

        >>> staff = abjad.Staff(r"c'1\p\< r2\! r2 d'1\f\> r2 r2\ppp")
        >>> abjad.show(staff)

        ..  docs::

            \new Staff
            {
                c'1
                \p
                \<
                r2
                \!
                r2
                d'1
                \f
                \>
                r2
                r2
                \ppp
            }


        ..  figure:: ../_images/rests_to_multimeasure_rest-J9T5UY8r9w.png

        >>> abjad.mutate.rests_to_multimeasure_rest(staff[:])
        >>> abjad.show(staff)

        ..  docs::

            \new Staff
            {
                c'1
                \p
                \<
                R1
                \!
                d'1
                \f
                \>
                R1
                \ppp
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-77r9QeaZBA.png

        Invoke the mutation with ``ignore_dynamics`` set to ``True`` to disable
        this behaviour and ignore all dynamics and hairpins:

        >>> staff = abjad.Staff(r"c'1\p\< r2\! r2 d'1\f\> r2 r2\ppp")
        >>> abjad.mutate.rests_to_multimeasure_rest(
        ...     staff[:],
        ...     ignore_dynamics=True,
        ... )
        >>> abjad.show(staff)

        ..  docs::

            \new Staff
            {
                c'1
                \p
                \<
                R1
                d'1
                \f
                \>
                R1
            }

        ..  figure:: ../_images/rests_to_multimeasure_rest-3UhZukx9Pw.png

        ..  warning::

            Note that dynamics are only ignored when converting rests to
            multi-measure rests. All other dynamics are preserved in the score.
            This can result in problems displaying dynamics when one or more
            unterminated hairpins is present. In the example above, the last
            note's hairpin is unterminated and, because of that, LilyPond
            ignores all dynamics in that staff:

            >>> staff = abjad.Staff(r"c'1\p\< r2\! r2 d'1\f\> r2 r2\ppp")
            >>> abjad.mutate.rests_to_multimeasure_rest(
            ...     staff[:],
            ...     ignore_dynamics=True,
            ... )
            >>> string = abjad.lilypond(staff)
            >>> print(string)
            \new Staff
            {
                c'1
                \p
                \<
                R1
                d'1
                \f
                \>
                R1
            }

    ..  warning::

        The input selection 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(selection, abjad.Selection):
        raise TypeError("argument must be 'abjad.Selection'")
    if not selection.leaves().are_contiguous_logical_voice():
        raise ValueError("argument must be contiguous logical voice")
    if not isinstance(ignore_clefs, bool):
        raise TypeError("'ignore_clefs' must be 'bool'")
    if not isinstance(ignore_dynamics, bool):
        raise TypeError("'ignore_dynamics' must be 'bool'")

    measures = selection.group_by_measure()
    effective_time_signature = abjad.TimeSignature((4, 4))
    indicators_tuple = (
        abjad.BarLine,
        abjad.Fermata,
        abjad.KeySignature,
        abjad.LilyPondLiteral,
        abjad.MetronomeMark,
        abjad.RehearsalMark,
        abjad.Repeat,
        abjad.StaffChange,
        abjad.StartMarkup,
        abjad.StartTextSpan,
        abjad.StopTextSpan,
    )

    for measure in measures:
        head = abjad.select(measure).leaf(0)
        time_signature = abjad.get.indicator(head, abjad.TimeSignature)
        if time_signature is not None:
            effective_time_signature = time_signature
        if all([isinstance(leaf, abjad.Rest) for leaf in measure.leaves()]):
            if not ignore_clefs:
                for leaf in measure.leaves()[::-1]:
                    clef = abjad.get.indicator(leaf, abjad.Clef)
                    if clef is not None:
                        break
            if not ignore_dynamics:
                for leaf in measure.leaves()[::-1]:
                    dynamics = abjad.get.indicator(leaf, (
                        abjad.Dynamic,
                        abjad.StartHairpin,
                        abjad.StopHairpin,
                    ))
                    if dynamics is not None:
                        break
            duration = abjad.get.duration(measure)
            if duration == effective_time_signature.duration:
                if duration == 1:
                    multiplier = None
                else:
                    multiplier = abjad.Multiplier(duration)
                multimeasure_rest = abjad.MultimeasureRest(
                    (4, 4),
                    multiplier=multiplier,
                )
                if time_signature is not None:
                    abjad.attach(time_signature, multimeasure_rest)
                if not ignore_clefs and clef is not None:
                    abjad.attach(clef, multimeasure_rest)
                if not ignore_dynamics and dynamics is not None:
                    abjad.attach(dynamics, multimeasure_rest)
                for indicator in abjad.get.indicators(head):
                    if isinstance(indicator, indicators_tuple):
                        abjad.attach(indicator, multimeasure_rest)
                abjad.mutate.replace(measure, multimeasure_rest)
Exemplo n.º 57
0
def _add_moment_to_voice(voice, moment_number, moment_namespace):
    stage_names = ("stage_1", "stage_2", "stage_3", "stage_4", "stage_5", "stage_6")
    all_leaves_in_moment = []
    segments_ = (abjad.PitchClassSegment, abjad.PitchSegment)
    for stage_name in stage_names:
        stage_namespace = getattr(moment_namespace, stage_name, None)
        if stage_namespace is None:
            continue
        for part_name in ("rh", "lh"):
            part_namespace = getattr(stage_namespace, part_name, None)
            if part_namespace is None:
                continue
            for item_number, item in enumerate(part_namespace, start=1):
                if isinstance(item, list):
                    all_leaves = []
                    for subitem_number, subitem in enumerate(item, start=1):
                        if isinstance(subitem, segments_):
                            leaves = [abjad.Note(_.number, (1, 8)) for _ in subitem]
                            abjad.horizontal_bracket(leaves)
                        else:
                            assert isinstance(subitem, set | frozenset)
                            numbers = [_.number for _ in subitem]
                            chord = abjad.Chord(numbers, (1, 8))
                            leaves = [chord]
                        markup = abjad.Markup(rf"\markup {subitem_number}")
                        bundle = abjad.bundle(
                            markup,
                            r"- \tweak color #blue",
                            r"- \tweak staff-padding 3",
                        )
                        abjad.attach(bundle, leaves[0], direction=abjad.UP)
                        all_leaves.extend(leaves)
                    abjad.horizontal_bracket(all_leaves)
                    part = part_name[0].upper()
                    stage_number = stage_name[-1]
                    string = f"{moment_number}.{stage_number}.{part}.{item_number}"
                    markup = abjad.Markup(rf'\markup "{string}"')
                    bundle = abjad.bundle(
                        markup,
                        r"- \tweak color #red",
                        r"- \tweak staff-padding 6",
                    )
                    abjad.attach(bundle, all_leaves[0], direction=abjad.UP)
                elif isinstance(item, segments_):
                    all_leaves = [abjad.Note(_.number, (1, 8)) for _ in item]
                    abjad.horizontal_bracket(all_leaves)
                    part = part_name[0].upper()
                    stage_number = stage_name[-1]
                    string = f"{moment_number}.{stage_number}.{part}.{item_number}"
                    markup = abjad.Markup(rf'\markup "{string}"')
                    bundle = abjad.bundle(
                        markup,
                        r"- \tweak color #red",
                        r"- \tweak staff-padding 6",
                    )
                    abjad.attach(bundle, all_leaves[0], direction=abjad.UP)
                elif isinstance(item, set | frozenset):
                    numbers = [_.number for _ in item]
                    chord = abjad.Chord(numbers, (1, 8))
                    all_leaves = [chord]
                    abjad.horizontal_bracket(all_leaves)
                    part = part_name[0].upper()
                    stage_number = stage_name[-1]
                    string = f"{moment_number}.{stage_number}.{part}.{item_number}"
                    markup = abjad.Markup(rf'\markup "{string}"')
                    bundle = abjad.bundle(
                        markup,
                        r"- \tweak color #red",
                        r"- \tweak staff-padding 6",
                    )
                    abjad.attach(bundle, all_leaves[0], direction=abjad.UP)
                else:
                    raise Exception(item)
                voice.extend(all_leaves)
                all_leaves_in_moment.extend(all_leaves)
    for i, leaf in enumerate(all_leaves_in_moment):
        if i % 30 == 29:
            literal = abjad.LilyPondLiteral(r"\break", site="after")
            abjad.attach(literal, leaf)
    literal = abjad.LilyPondLiteral(r"\pageBreak", site="after")
    abjad.attach(literal, voice[-1])
Exemplo n.º 58
0
def _add_segments_to_voice(voice, label, segments, names, do_not_page_break=False):
    pairs = zip(segments, names)
    leaves = []
    for i, pair in enumerate(pairs):
        segment, name = pair
        notes = [abjad.Note(_.number, (1, 8)) for _ in segment]
        abjad.horizontal_bracket(notes)
        name = rf'\markup "{name}"'
        abjad.override(notes[0]).HorizontalBracketText.text = name
        voice.extend(notes)
        skip = abjad.Skip("s8")
        voice.append(skip)
        number = i + 1
        markup = abjad.Markup(rf"\markup {number}")
        bundle = abjad.bundle(markup, r"- \tweak staff-padding 2")
        abjad.attach(bundle, notes[0], direction=abjad.UP)
        if i == 0:
            string = rf'\markup \bold \with-color #red "{label}"'
            markup = abjad.Markup(string)
            bundle = abjad.bundle(markup, r"- \tweak staff-padding 6")
            abjad.attach(bundle, notes[0], direction=abjad.UP)
        if i == len(segments) - 1:
            literal = abjad.LilyPondLiteral(r"\break", site="after")
            abjad.attach(literal, voice[-1])
        leaves.extend(notes)
        leaves.append(skip)
    for i, leaf in enumerate(leaves):
        if i % 30 == 29:
            literal = abjad.LilyPondLiteral(r"\break", site="after")
            abjad.attach(literal, leaf)
    if not do_not_page_break:
        literal = abjad.LilyPondLiteral(r"\pageBreak")
        abjad.attach(literal, leaves[0])
    bar_line = abjad.BarLine("||")
    abjad.attach(bar_line, leaves[-1])
    literal = abjad.LilyPondLiteral(
        r"\once \override Score.BarLine.transparent = ##f", site="after"
    )
    abjad.attach(literal, leaves[-1])
Exemplo n.º 59
0
 def attach(self, leaf: abjad.Chord, novent) -> None:
     abjad.attach(self.abjad, leaf)
Exemplo n.º 60
0
Arquivo: test.py Projeto: gsy/gmajor
            _parsed_duration = parse_duration(_duration_type, _dot_count)
            notes.append(Rest(abjad.Duration(_parsed_duration)))
        else:
            print(_note.tag)

        _ties = note.findall('tie')
        for _tie in _ties:
            if _tie.attrib['type'] == 'start':
                tie_start = len(notes) - 1 if len(notes) > 1 else 0
            elif _tie.attrib['type'] == 'stop':
                tie_end = len(notes)
                ties.append((tie_start, tie_end))

    measure = Measure(TimeSignature((4, 4)), notes)
    for tie_start, tie_stop in ties:
        abjad.attach(abjad.Tie(), measure[tie_start:tie_stop])

    abjad.setting(measure).auto_beaming = False
    for beam_start, beam_end in beams:
        beam = abjad.Beam()
        abjad.attach(beam, measure[beam_start:beam_end])

    measures.append(measure)

clef = abjad.Clef('treble_8')
abjad.attach(clef, measures[0][0])

staff = abjad.Staff(measures)
# staff = abjad.Staff(measures, lilypond_type='TabStaff')
# show(staff)