def check_manuals_ranges(score): manuals_voice_1 = score['Manuals Voice 1'] manuals_voice_2 = score['Manuals Voice 2'] rh_manual_range = abjad.pitchtools.PitchRange('[-20, 43]') lh_manual_range = abjad.pitchtools.PitchRange('[-32, 25]') lh_total = 0 lh_violations = 0 for note in abjad.iterate(manuals_voice_1).by_class(abjad.Note): lh_total += 1 if note not in lh_manual_range: lh_violations += 1 abjad.label(note).color_leaves('red') #message = '{} of {} lh pitches out of range.' #message = message.format(lh_violations, lh_total) #print(message) rh_total = 0 rh_violations = 0 for note in abjad.iterate(manuals_voice_2).by_class(abjad.Note): rh_total += 1 if note not in rh_manual_range: rh_violations += 1 #message = '{} of {} rh pitches out of range.' #message = message.format(rh_violations, rh_total) #print(message) if lh_violations or rh_violations: #message = 'pitches out of range!' #raise Exception(message) #print(message) pass
def test_scoretools_Iteration__depth_first_03(): r'''Duplicates-allowed depth-first search: nodes yield every time they are traversed. ''' # LEFT-TO-RIGHT # iterator = abjad.iterate(staff[2])._depth_first(unique=False, ) assert next(iterator) is staff[2] assert next(iterator) is staff[2][0] assert next(iterator) is staff[2][0][0] assert next(iterator) is staff[2][0] assert next(iterator) is staff[2][0][1] assert next(iterator) is staff[2][0] assert next(iterator) is staff[2] assert next(iterator) is staff[2][1] assert next(iterator) is staff[2][1][0] assert next(iterator) is staff[2][1] assert next(iterator) is staff[2][1][1] assert next(iterator) is staff[2][1] assert next(iterator) is staff[2] assert pytest.raises(StopIteration, 'next(iterator)') r''' abjad.Container(abjad.Voice(d'8, ef'8), abjad.Voice(e'8, f'8)) Voice(d'8, ef'8) d'8 Voice(d'8, ef'8) ef'8 Voice(d'8, ef'8) abjad.Container(abjad.Voice(d'8, ef'8), abjad.Voice(e'8, f'8)) Voice(e'8, f'8) e'8 Voice(e'8, f'8) f'8 Voice(e'8, f'8) abjad.Container(abjad.Voice(d'8, ef'8), abjad.Voice(e'8, f'8)) ''' # RIGHT-TO-LEFT # iterator = abjad.iterate(staff[2])._depth_first( direction=abjad.Right, unique=False, ) assert next(iterator) is staff[2] assert next(iterator) is staff[2][1] assert next(iterator) is staff[2][1][1] assert next(iterator) is staff[2][1] assert next(iterator) is staff[2][1][0] assert next(iterator) is staff[2][1] assert next(iterator) is staff[2] assert next(iterator) is staff[2][0] assert next(iterator) is staff[2][0][1] assert next(iterator) is staff[2][0] assert next(iterator) is staff[2][0][0] assert next(iterator) is staff[2][0] assert next(iterator) is staff[2] assert pytest.raises(StopIteration, 'next(iterator)') r'''
def comment_measure_numbers(score): """ Comments measure numbers in ``score``. """ import abjad offset_to_measure_number = {} for context in abjad.iterate(score).components(abjad.Context): if not context.simultaneous: break site = "abjad.SegmentMaker.comment_measure_numbers()" measures = abjad.select(context).leaves().group_by_measure() for i, measure in enumerate(measures): measure_number = i + 1 first_leaf = abjad.select(measure).leaf(0) start_offset = abjad.inspect(first_leaf).timespan().start_offset offset_to_measure_number[start_offset] = measure_number for leaf in abjad.iterate(score).leaves(): offset = abjad.inspect(leaf).timespan().start_offset measure_number = offset_to_measure_number.get(offset, None) if measure_number is None: continue context = abjad.inspect(leaf).parentage().get(abjad.Context) if context.name is None: string = ( f"% [{context.lilypond_type} measure {measure_number}]") else: string = f"% [{context.name} measure {measure_number}]" literal = abjad.LilyPondLiteral(string, "absolute_before") tag = abjad.Tag("COMMENT_MEASURE_NUMBERS").append(site) abjad.attach(literal, leaf, tag=tag)
def _handle_voice(self, voice, current_stage): # hide all noteheads if no fingerings.py if self._fingerings is None or self._fingerings[current_stage] is None: for note in abjad.iterate(voice).by_leaf(): self._hide_note_head(note) return # get logical ties and construct left_hand tablature previous_fingering = None for logical_tie in abjad.iterate(voice).by_logical_tie(): if logical_tie.is_pitched: fingering_index = WoodwindFingeringHandler._cycle_next( self._fingering_patterns, current_stage ) fingering = self._fingerings[current_stage][fingering_index] self._construct_fingering_tablature( logical_tie=logical_tie, fingering=fingering, previous_fingering=previous_fingering, ) previous_fingering = fingering else: previous_fingering = None
def test_scoretools_Iteration__depth_first_06(): r'''Uncapped and restricted depth-first search. ''' # LEFT-TO-RIGHT # iterator = abjad.iterate(staff[2])._depth_first( capped=False, forbid='simultaneous', ) assert next(iterator) is staff[2] assert next(iterator) is staff assert next(iterator) is staff[3] assert next(iterator) is staff[4] r''' abjad.Container(abjad.Voice(d'8, ef'8), abjad.Voice(e'8, f'8)) Staff{5} fs'8 iterator'8 ''' # RIGHT-TO-LEFT # iterator = abjad.iterate(staff[2])._depth_first( capped=False, direction=abjad.Right, forbid='simultaneous', ) assert next(iterator) is staff[2] assert next(iterator) is staff assert next(iterator) is staff[1] assert next(iterator) is staff[0] r'''
def comment_measure_numbers(score): """ Comments measure numbers in ``score``. """ import abjad offset_to_measure_number = {} for context in abjad.iterate(score).components(abjad.Context): if not context.is_simultaneous: break measures = abjad.select(context).leaves().group_by_measure() for i, measure in enumerate(measures): measure_number = i + 1 first_leaf = abjad.select(measure).leaf(0) start_offset = abjad.inspect(first_leaf).timespan().start_offset offset_to_measure_number[start_offset] = measure_number for leaf in abjad.iterate(score).leaves(): offset = abjad.inspect(leaf).timespan().start_offset measure_number = offset_to_measure_number.get(offset, None) if measure_number is None: continue context = abjad.inspect(leaf).parentage().get(abjad.Context) if context.name is None: string = ( f"% [{context.lilypond_type} measure {measure_number}]" ) else: string = f"% [{context.name} measure {measure_number}]" literal = abjad.LilyPondLiteral(string, "absolute_before") abjad.attach(literal, leaf, tag="COMMENT_MEASURE_NUMBERS")
def __call__(self, segment_maker): r'''Calls spacing specifier. Returns none. ''' score = segment_maker._score skip_context = score['Time Signature Context Skips'] leaves = abjad.iterate(score).by_leaf() minimum_leaf_durations_by_measure = \ self._get_minimum_leaf_durations_by_measure(skip_context, leaves) fermata_start_offsets = getattr( segment_maker, '_fermata_start_offsets', [], ) skips = abjad.iterate(skip_context).by_leaf(abjad.scoretools.Skip) for measure_index, skip in enumerate(skips): measure_timespan = abjad.inspect_(skip).get_timespan() if (self.fermata_measure_width is not None and measure_timespan.start_offset in fermata_start_offsets): duration = self.fermata_measure_width else: duration = minimum_leaf_durations_by_measure[measure_index] if self.minimum_width is not None: if self.minimum_width < duration: duration = self.minimum_width if self.multiplier is not None: duration = duration / self.multiplier command = abjad.indicatortools.LilyPondCommand('newSpacingSection') abjad.attach(command, skip) moment = abjad.schemetools.SchemeMoment(duration) abjad.set_(skip).score.proportional_notation_duration = moment
def _populate_time_signature_contexts(self): r""" Makes and inserts blank measures for time signature context and attaches tempo indicators. """ for staff in abjad.iterate(self._score).by_class(abjad.Context): # if staff.name is 'Separator': # measures = self._make_skip_filled_measures() # staff.extend(measures) if staff.context_name == 'TimeSignatureContext': if self._ruler: measures = self._make_repeated_note_measures() else: measures = self._make_skip_filled_measures() # attach Tempi for tempo in self.tempo_map: if tempo[0] < len(measures): abjad.attach(tempo[1], measures[tempo[0]][0]) # attach dummy first bar command leaves = abjad.iterate(measures).by_class(abjad.Leaf) leaves = list(leaves) first_leaf = leaves[0] dummy_first_bar_command = abjad.indicatortools.LilyPondCommand( 'bar ""' ) abjad.attach(dummy_first_bar_command, first_leaf) voice = abjad.Voice(measures) staff.append(voice)
def apply_pitches(containers, pitched_notes): pitch_index = 0 #leaves = abjad.iterate(containers).leaves() leaves = abjad.iterate(containers).leaves(grace_notes=False) for leaf_index, leaf in enumerate(leaves): if not isinstance(leaf, abjad.Note): continue if leaf_index == 603: pitch_index += 1 pitched_note = pitched_notes[pitch_index] written_pitch = pitched_note.written_pitch leaf.written_pitch = written_pitch if written_pitch == -1: abjad.label(leaf).color_leaves('green') pitch_index += 1 inspection = abjad.inspect(leaf) grace_container = inspection.grace_container() if not grace_container: continue for grace_container in [grace_container]: agent = abjad.iterate(grace_container) for note in agent.leaves(pitched=True): pitched_note = pitched_notes[pitch_index] written_pitch = pitched_note.written_pitch note.written_pitch = written_pitch pitch_index += 1
def test_scoretools_Iteration__depth_first_07(): r'''Restricted depth-first search with duplicates allowed. ''' # LEFT-TO-RIGHT iterator = abjad.iterate(staff)._depth_first( forbid='simultaneous', unique=False, ) assert next(iterator) is staff assert next(iterator) is staff[0] assert next(iterator) is staff assert next(iterator) is staff[1] assert next(iterator) is staff assert next(iterator) is staff[2] assert next(iterator) is staff assert next(iterator) is staff[3] assert next(iterator) is staff assert next(iterator) is staff[4] assert next(iterator) is staff assert pytest.raises(StopIteration, 'next(iterator)') r''' Staff{5} c'8 Staff{5} cs'8 Staff{5} abjad.Container(abjad.Voice(d'8, ef'8), abjad.Voice(e'8, f'8)) Staff{5} fs'8 Staff{5} iterator'8 Staff{5} ''' # RIGHT-TO-LEFT # iterator = abjad.iterate(staff)._depth_first( direction=abjad.Right, forbid='simultaneous', unique=False, ) assert next(iterator) is staff assert next(iterator) is staff[4] assert next(iterator) is staff assert next(iterator) is staff[3] assert next(iterator) is staff assert next(iterator) is staff[2] assert next(iterator) is staff assert next(iterator) is staff[1] assert next(iterator) is staff assert next(iterator) is staff[0] assert next(iterator) is staff assert pytest.raises(StopIteration, 'next(iterator)') r'''
def test_scoretools_VerticalMoment___hash___01(): r'''Vertical moments behave well when included in a set. ''' staff = abjad.Staff("c'8 d'8 e'8 f'8") vms = [] vms.extend(abjad.iterate(staff).vertical_moments()) vms.extend(abjad.iterate(staff).vertical_moments()) assert len(vms) == 8 assert len(set(vms)) == 4
def _iterate_logical_ties(voice): i = -1 count = len(list(abjad.iterate(voice).by_logical_tie())) for tie in abjad.iterate(voice).by_logical_tie(): start_moment = abjad.inspect( tie.head ).get_vertical_moment(voice) offset_start = float(start_moment.offset) offset_end = offset_start + float(tie.get_duration()) i += 1 yield tie, offset_start, offset_end, i, count
def test_scoretools_Iteration__depth_first_02(): r'''Uncapped depth-first search: uncapped iteration returns all elements above self._client ''' # LEFT-TO-RIGHT # iterator = abjad.iterate(staff[2])._depth_first(capped=False, ) assert next(iterator) is staff[2] assert next(iterator) is staff[2][0] assert next(iterator) is staff[2][0][0] assert next(iterator) is staff[2][0][1] assert next(iterator) is staff[2][1] assert next(iterator) is staff[2][1][0] assert next(iterator) is staff[2][1][1] assert next(iterator) is staff assert next(iterator) is staff[3] assert next(iterator) is staff[4] assert pytest.raises(StopIteration, 'next(iterator)') r''' abjad.Container(abjad.Voice(d'8, ef'8), abjad.Voice(e'8, f'8)) Voice(d'8, ef'8) d'8 ef'8 Voice(e'8, f'8) e'8 f'8 Staff{5} fs'8 iterator'8 ''' # RIGHT-TO-LEFT # iterator = abjad.iterate(staff[2])._depth_first( capped=False, direction=abjad.Right, ) assert next(iterator) is staff[2] assert next(iterator) is staff[2][1] assert next(iterator) is staff[2][1][1] assert next(iterator) is staff[2][1][0] assert next(iterator) is staff[2][0] assert next(iterator) is staff[2][0][1] assert next(iterator) is staff[2][0][0] assert next(iterator) is staff assert next(iterator) is staff[1] assert next(iterator) is staff[0] assert pytest.raises(StopIteration, 'next(iterator)') r'''
def test_make_measures_01(): t = abjad.Voice([abjad.Note(n, (1, 8)) for n in range(8)]) assert len(t) == 8 leaves_before = abjad.iterate(t).by_leaf() leaves_before = list(leaves_before) lidercfeny.etc.transforms.make_measures(t, [(n, 8) for n in (2, 2, 2, 2)]) assert len(t) == 4 leaves_after = abjad.iterate(t).by_leaf() leaves_after = list(leaves_after) assert leaves_before == leaves_after for x in t: assert isinstance(x, abjad.Measure) assert abjad.inspect_(x).get_duration() == abjad.Duration(2, 8)
def set_articulations(voice, articulations, *args, **kwargs): r"""Iterates leaves and sets articulations. """ leaves = abjad.iterate(voice).by_leaf() leaves = list(leaves) if len(args) == 0: start = 0 stop = len(leaves) elif len(args) == 1: start = stop = args elif len(args) == 2: start, stop = args else: raise ValueError leafSlice = leaves[start : stop + 1] if kwargs.has_key("exclude"): exclude = kwargs["exclude"] else: exclude = True for l in leafSlice: if instance(l, (Note, Chord)) or not exclude: if isinstance(articulations, str): l.articulations = [articulations] elif isinstance(articulations, list): l.articulations = articulations else: raise ValueError
def __illustrate__(self): score = self() time_signatures = [ (3, 4), (7, 8), (2, 4), (5, 16), (4, 4), (6, 8), (5, 4), (3, 8), (3, 4), (7, 8), (2, 4), (5, 16), ] for voice in iterate(score).by_class(abjad.Voice): for pair in time_signatures: rest = abjad.MultimeasureRest(1) attach(Multiplier(pair), rest) voice.append(rest) for pair in time_signatures: skip = abjad.Skip(1) attach(Multiplier(pair), skip) score['Time Signature Context'].append(skip) attach( abjad.TimeSignature(pair), skip, scope=abjad.Score, ) module = importlib.import_module(type(self).__module__) score_path = pathlib.Path(module.__file__).parent.parent stylesheet_path = score_path.joinpath('stylesheets', 'stylesheet.ily') stylesheet_path = stylesheet_path.resolve() lilypond_file = lilypondfiletools.LilyPondFile.new( score, includes=[str(stylesheet_path)], use_relative_includes=True, ) return lilypond_file
def _attach_rhythm_annotation_spanner(self, selection): from . import piecewise if not self.annotation_spanner_text and not self.frame: return leaves = [] for leaf in abjad.iterate(selection).leaves(): if abjad.get.parentage(leaf).get(abjad.OnBeatGraceContainer): continue leaves.append(leaf) container = abjad.get.before_grace_container(leaves[0]) if container is not None: leaves_ = abjad.select(container).leaves() leaves[0:0] = leaves_ container = abjad.get.after_grace_container(leaves[-1]) if container is not None: leaves_ = abjad.select(container).leaves() leaves.extend(leaves_) string = self.annotation_spanner_text if string is None: string = self._make_rhythm_annotation_string() color = self.annotation_spanner_color or "#darkyellow" command = piecewise.rhythm_annotation_spanner( string, abjad.tweak(color).color, abjad.tweak(8).staff_padding, leak_spanner_stop=True, selector=classes.select().leaves(), ) command(leaves)
def check_out_of_range_notes(self, argument=None): r'''Checks out-of-range notes. .. container:: example Out of range: >>> staff = abjad.Staff("c'8 r8 <d fs>8 r8") >>> violin = abjad.Violin() >>> abjad.attach(violin, staff[0]) >>> abjad.show(staff) # doctest: +SKIP .. docs:: >>> abjad.f(staff) \new Staff { \set Staff.instrumentName = \markup { Violin } \set Staff.shortInstrumentName = \markup { Vn. } c'8 r8 <d fs>8 r8 } >>> agent = abjad.inspect(staff) >>> print(agent.tabulate_wellformedness()) 0 / 0 beamed long notes 0 / 0 discontiguous spanners 0 / 5 duplicate ids 0 / 1 empty containers 0 / 0 misdurated measures 0 / 0 misfilled measures 0 / 0 mismatched enchained hairpins 0 / 0 mispitched ties 0 / 4 misrepresented flags 0 / 5 missing parents 0 / 0 nested measures 0 / 4 notes on wrong clef 1 / 2 out of range notes 0 / 0 overlapping beams 0 / 0 overlapping glissandi 0 / 0 overlapping hairpins 0 / 0 overlapping octavation spanners 0 / 0 overlapping ties 0 / 0 overlapping trill spanners 0 / 2 tied rests Returns true or false. ''' import abjad violators, total = [], set() for leaf in abjad.iterate(argument).leaves(pitched=True): total.add(leaf) instrument = abjad.inspect(leaf).get_effective(abjad.Instrument) if instrument is None: continue if leaf not in instrument.pitch_range: violators.append(leaf) return violators, len(total)
def check_beamed_long_notes(self, argument=None): r'''Checks beamed long notes. .. container:: example >>> staff = abjad.Staff("c'8 d' e' f'4.") >>> abjad.attach(abjad.Beam(), staff[:]) >>> manager = abjad.WellformednessManager() >>> violators, total = manager.check_beamed_long_notes(staff) >>> violators [Note("f'4.")] Returns pair. First item in pair is list of beamed long notes. Second item in pair is count of all long notes in `argument`. ''' import abjad violators, total = [], set() smart_beams = ( abjad.DuratedComplexBeam, abjad.MultipartBeam, ) for leaf in abjad.iterate(argument).leaves(): if leaf.written_duration < abjad.Duration(1, 4): continue total.add(leaf) beams = abjad.inspect(leaf).get_spanners(abjad.Beam) for beam in beams: if isinstance(beam, smart_beams): continue violators.append(leaf) return violators, len(total)
def _respell_tuplets(self, music): multiplier = abjad.Multiplier(3, 2) for tuplet in abjad.iterate(music).by_class(abjad.Tuplet): if tuplet.multiplier == multiplier: for note in tuplet: new_written_duration = multiplier * note.written_duration note.written_duration = new_written_duration
def _attach_leaf_index_markup(self, music): if not self.index_logical_ties: return logical_ties = abjad.iterate(music).by_logical_tie() for i, logical_tie in enumerate(logical_ties): markup = abjad.Markup(i) abjad.attach(markup, logical_tie.head)
def attach_glissandi(nucleus_voice): selections = [[]] leaves = abjad.iterate(nucleus_voice).leaves() for leaf_index, leaf in enumerate(leaves): if 641 <= leaf_index: leaf_index += 2 string = letter_maker.nuclei[leaf_index] if string == 0: glissando = False else: result = letter_maker.get_body_pitch_shape_glissando(string) pitch, shape, glissando = result if glissando: assert isinstance(leaf, abjad.Note), repr(leaf) selections[-1].append(leaf) elif not selections[-1] == []: selections.append([]) if selections[-1] == []: selections.pop() selections = [abjad.select(_) for _ in selections] for selection in selections: next_leaf = abjad.inspect(selection[-1]).leaf(1) if next_leaf is not None: selection = selection + [next_leaf] abjad.glissando(selection, allow_repeats=True) triples = abjad.sequence(selection).nwise(n=3) for left_note, middle_note, right_note in triples: if not (left_note.written_pitch == middle_note.written_pitch == right_note.written_pitch): continue abjad.override(middle_note).note_head.transparent = True grob_proxy = abjad.override(middle_note).glissando grob_proxy.bound_details__left__padding = -1.2
def _strip_ties_(self, divisions): import abjad if not self.strip_ties: return for division in divisions: for leaf in abjad.iterate(division).leaves(): abjad.detach(abjad.Tie, leaf)
def add_string_music_to_score(score): """ Adds string music to score. """ # generate some pitch and rhythm information pitch_contour_reservoir = create_pitch_contour_reservoir() shadowed_contour_reservoir = shadow_pitch_contour_reservoir( pitch_contour_reservoir ) durated_reservoir = durate_pitch_contour_reservoir( shadowed_contour_reservoir ) # add six dotted-whole notes and the durated contours to each string voice for name, descents in durated_reservoir.items(): instrument_voice = score["%s Voice" % name] instrument_voice.extend("R1. R1. R1. R1. R1. R1.") for descent in descents: instrument_voice.extend(descent) # apply instrument-specific edits edit_first_violin_voice(score, durated_reservoir) edit_second_violin_voice(score, durated_reservoir) edit_viola_voice(score, durated_reservoir) edit_cello_voice(score, durated_reservoir) edit_bass_voice(score, durated_reservoir) # chop all string parts into 6/4 measures strings_staff_group = score["Strings Staff Group"] with abjad.ForbidUpdate(score): for voice in abjad.iterate(strings_staff_group).components( abjad.Voice ): shards = abjad.mutate(voice[:]).split([(6, 4)], cyclic=True) for shard in shards: container = abjad.Container() abjad.mutate(shard).wrap(container)
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])
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
def cross_staves_down( voice, start, stop, bp, target, includes=[], excludes=[], topBeamPositions=None, bottomBeamPositions=None, ): r'''target is a reference to an actual Staff instance. TODO: run octavate at some time other than cross-determination time. ''' leaves = abjad.iterate(voice).by_leaf() leaves = list(leaves) for j, l in enumerate(leaves[start : stop + 1]): i = start + j if isinstance(l, Note): #if (bp <= l.safePitchNumber or i in includes) and i not in excludes: if ((bp <= lidercfeny.etc.transforms.get_lowest_pitch(l) or i in includes) and i not in excludes): l.staff = target else: octavate(l, base = (-4, 30))
def append_articulations(voice, articulations, *args, **kwargs): r'''Iterates leaves and append articulations. ''' leaves = abjad.iterate(voice).by_leaf() leaves = list(leaves) if len(args) == 0: start = 0 stop = len(leaves) elif len(args) == 1: start = stop = args elif len(args) == 2: start, stop = args else: raise ValueError leafSlice = leaves[start : stop + 1] if kwargs.has_key('exclude'): exclude = kwargs['exclude'] else: exclude = True for l in leaves: if isinstance(l, (Note, Chord)) or not exclude: if isinstance(articulations, str): l.articulations.append(articulations) elif isinstance(articulations, list): for articulation in articulations: l.articulations.extend(articulation) else: raise ValueError
def set_pitches_by_pitch_cycle(voice, start, stop, pcyc): leaves = abjad.iterate(voice).by_leaf() leaves = list(leaves) for j, l in enumerate(leaves[start : stop + 1]): i = j + start p = pcyc[j % len(pcyc)] l.pitch = p
def _replace(self, old_leaf, new_leaf): grace_containers = inspect_(old_leaf).get_grace_containers('after') if grace_containers: old_grace_container = grace_containers[0] grace_notes = list(iterate(old_grace_container).by_leaf()) detach(scoretools.GraceContainer, old_leaf) indicator_expressions = inspect_(old_leaf).get_indicators(unwrap=False) #for indicator_expression in indicator_expressions: # detach(indicator, old_leaf) timespan = old_leaf._timespan start_offset = old_leaf._start_offset stop_offset = old_leaf._stop_offset logical_measure_number = old_leaf._logical_measure_number mutate(old_leaf).replace(new_leaf) new_leaf._timespan = timespan new_leaf._start_offset = start_offset new_leaf._stop_offset = stop_offset new_leaf._logical_measure_number = logical_measure_number if grace_containers: new_grace_container = scoretools.GraceContainer( grace_notes, kind='after', ) attach(new_grace_container, new_leaf) for indicator_expression in indicator_expressions: attach(indicator_expression, new_leaf)
def add_final_bar_line( self, abbreviation='|.', to_each_voice=False, ): r""" Add final bar line to end of score. >>> staff = abjad.Staff("c'4 d'4 e'4 f'4") >>> score = abjad.Score([staff]) >>> abjad.show(score) # doctest: +SKIP .. docs:: >>> abjad.f(score) \new Score << \new Staff { c'4 d'4 e'4 f'4 } >> >>> bar_line = score.add_final_bar_line() >>> abjad.show(score) # doctest: +SKIP .. docs:: >>> abjad.f(score) \new Score << \new Staff { c'4 d'4 e'4 f'4 \bar "|." %! SCORE_1 } >> Set ``to_each_voice`` to true to make part extraction easier. Returns bar line. """ import abjad bar_line = abjad.BarLine(abbreviation) if not to_each_voice: last_leaf = abjad.inspect(self).leaf(-1) abjad.attach(bar_line, last_leaf, tag='SCORE_1') else: for voice in abjad.iterate(self).components(abjad.Voice): last_leaf = abjad.inspect(voice).leaf(-1) abjad.attach(bar_line, last_leaf, tag='SCORE_1') return bar_line
def rosatize(self): # transposing up an octave and add dynamic for Rosa Guitar Trio for staff in self.skeleton: first_leaf = abjad.inspect(staff).leaf(0) abjad.attach(abjad.Dynamic('pp'), first_leaf) for note in abjad.iterate(staff).components(prototype=abjad.Note): note.written_pitch += 12
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)
def applyCoverSpanner(voice, *args): leaves = abjad.iterate(voice).by_leaf() leaves = list(leaves) if len(args) == 1: i = args[0] leaves[i].formatter.right.append( r'^ \markup { \italic \fontsize #2 "coperta" }') elif len(args) == 2: start, stop = args leaves[start].formatter.before.extend([ r"\once \override TextSpanner #'bound-details #'left-broken " + r"#'X = #8", r"\once \override TextSpanner #'dash-fraction = #0.25", r"\once \override TextSpanner #'dash-period = #1", r"\once \override TextSpanner #'bound-details #'left " + \ r"""#'text = \markup { \italic \fontsize #2 "coperta " }""", r"\once \override TextSpanner #'bound-details #'left " + \ r"#'stencil-align-dir-y = #CENTER", r"\once \override TextSpanner #'bound-details #'right-broken " + r"#'text = ##f", r"\once \override TextSpanner #'bound-details #'right " + r"#'text = #(markup #:draw-line '(0 . -1))", r"\once \override TextSpanner #'staff-padding = #6", r"\once \override TextSpanner #'extra-offset = #'(0 . -2.5)" ]) leaves[start].formatter.right.append(r'\startTextSpan') leaves[stop].formatter.right.append(r'\stopTextSpan') else: raise ValueError('can not apply cover spanner.')
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])
def test_scoretools_Component__measure_number_02(): staff = abjad.Staff() staff.append(abjad.Measure((2, 4), "c'4 d'4")) staff.append(abjad.Measure((2, 4), "e'4 f'4")) staff.append(abjad.Measure((3, 4), "g'4 a'4 b'4")) staff.append(abjad.Measure((1, 4), "c''4")) staff._update_measure_numbers() assert staff._measure_number == 1 assert staff[0]._measure_number == 1 assert staff[1]._measure_number == 2 assert staff[2]._measure_number == 3 assert staff[3]._measure_number == 4 leaves = abjad.iterate(staff).leaves() leaves = list(leaves) assert leaves[0]._measure_number == 1 assert leaves[1]._measure_number == 1 assert leaves[2]._measure_number == 2 assert leaves[3]._measure_number == 2 assert leaves[4]._measure_number == 3 assert leaves[5]._measure_number == 3 assert leaves[6]._measure_number == 3 assert leaves[7]._measure_number == 4
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)
def transpose_from_written_pitch(argument): r""" Transposes notes and chords in `argument` from sounding pitch to written pitch. .. container:: example >>> staff = abjad.Staff("<c' e' g'>4 d'4 r4 e'4") >>> clarinet = abjad.ClarinetInBFlat() >>> abjad.attach(clarinet, staff[0]) >>> abjad.show(staff) # doctest: +SKIP .. docs:: >>> abjad.f(staff) \new Staff { \set Staff.instrumentName = \markup { "Clarinet in B-flat" } \set Staff.shortInstrumentName = \markup { "Cl. in B-flat" } <c' e' g'>4 d'4 r4 e'4 } >>> abjad.Instrument.transpose_from_written_pitch(staff) >>> abjad.show(staff) # doctest: +SKIP .. docs:: >>> abjad.f(staff) \new Staff { \set Staff.instrumentName = \markup { "Clarinet in B-flat" } \set Staff.shortInstrumentName = \markup { "Cl. in B-flat" } <bf d' f'>4 c'4 r4 d'4 } Returns none. """ import abjad for leaf in abjad.iterate(argument).leaves(pitched=True): instrument = abjad.inspect(leaf).get_effective(abjad.Instrument) if not instrument: continue sounding_pitch = instrument.middle_c_sounding_pitch interval = abjad.NamedPitch('C4') - sounding_pitch if isinstance(leaf, abjad.Note): written_pitch = leaf.written_pitch written_pitch = interval.transpose(written_pitch) leaf.written_pitch = written_pitch elif isinstance(leaf, abjad.Chord): pitches = [ interval.transpose(pitch) for pitch in leaf.written_pitches ] leaf.written_pitches = pitches
def _populate_time_signature_context(self): time_signature_context = self._score['Time Signature Context'] music_voice = self._score['Music Voice'] measure_durations = [] current_duration = abjad.Duration(0) ideal_measure_duration = abjad.Duration(4, 4) for component in music_voice: component_duration = abjad.inspect_(component).get_duration() candidate_duration = current_duration + component_duration if ideal_measure_duration < candidate_duration: if 0 < current_duration: measure_durations.append(current_duration) current_duration = component_duration else: current_duration = candidate_duration measure_durations.append(current_duration) measures = abjad.scoretools.make_spacer_skip_measures( measure_durations) time_signature_context.extend(measures) for measure in abjad.iterate(time_signature_context).by_class(abjad.Measure): time_signature = abjad.inspect_(measure).get_indicator(abjad.TimeSignature) if time_signature.denominator < 4: fraction = abjad.mathtools.NonreducedFraction( time_signature.pair) fraction = fraction.with_multiple_of_denominator(4) abjad.detach(time_signature, measure) new_time_signature = abjad.TimeSignature(fraction) abjad.attach(new_time_signature, measure)
def _tie_consecutive_notes_(self, divisions): import abjad if not self.tie_consecutive_notes: return leaves = list(abjad.iterate(divisions).leaves()) for leaf in leaves: abjad.detach(abjad.Tie, leaf) pairs = itertools.groupby(leaves, lambda _: _.__class__) def _get_pitches(component): if isinstance(component, abjad.Note): return component.written_pitch elif isinstance(component, abjad.Chord): return component.written_pitches else: raise TypeError(component) for class_, group in pairs: group = list(group) if not isinstance(group[0], (abjad.Note, abjad.Chord)): continue subpairs = itertools.groupby(group, lambda _: _get_pitches(_)) for pitches, subgroup in subpairs: subgroup = list(subgroup) if len(subgroup) == 1: continue tie = abjad.Tie() assert tie._attachment_test_all(subgroup) is True abjad.attach(tie, abjad.select(subgroup))
def check_empty_containers(self, argument=None): r""" Checks empty containers. .. container:: example >>> staff = abjad.Staff("c'4 d' e' f'") >>> staff.append(abjad.Container()) >>> abjad.f(staff) \new Staff { c'4 d'4 e'4 f'4 { } } >>> manager = abjad.WellformednessManager() >>> violators, total = manager.check_empty_containers(staff) >>> violators [Container()] Returns list of empty containers and count of all containers in ``argument``. """ import abjad violators, containers = [], set() for container in abjad.iterate(argument).components(abjad.Container): containers.add(container) if len(container) == 0: violators.append(container) return violators, len(containers)
def _compound_scope_to_logical_ties( self, compound_scope, include_rests=False, ): import huitzil timespan_map, timespans = [], [] for scope in compound_scope.simple_scopes: start_stage, stop_stage = scope.stages offsets = self._get_offsets(start_stage, stop_stage) timespan = abjad.timespantools.Timespan(*offsets) timespan_map.append((scope.voice_name, timespan)) timespans.append(timespan) compound_scope._timespan_map = timespan_map voice_names = [_[0] for _ in timespan_map] compound_scope._voice_names = tuple(voice_names) logical_ties = [] if include_rests: prototype = (abjad.Note, abjad.Chord, abjad.Rest) else: prototype = (abjad.Note, abjad.Chord) for note in abjad.iterate(self._score).by_timeline(prototype): if note in compound_scope: logical_tie = abjad.inspect_(note).get_logical_tie() if logical_tie.head is note: logical_ties.append(logical_tie) start_offset = min(_.start_offset for _ in timespans) stop_offset = max(_.stop_offset for _ in timespans) timespan = abjad.timespantools.Timespan(start_offset, stop_offset) return logical_ties, timespan
def __call__(self, argument): r'''Calls naive attack-point optimizer. Returns none. ''' import abjad for logical_tie in abjad.iterate(argument).logical_ties( grace_notes=False, reverse=True, ): sub_logical_ties = [] current_sub_logical_tie = [] for leaf in logical_tie: tempos = leaf._get_indicators(abjad.MetronomeMark) if tempos: if current_sub_logical_tie: current_sub_logical_tie = abjad.LogicalTie( current_sub_logical_tie) sub_logical_ties.append(current_sub_logical_tie) current_sub_logical_tie = [] current_sub_logical_tie.append(leaf) if current_sub_logical_tie: current_sub_logical_tie = abjad.LogicalTie( current_sub_logical_tie) sub_logical_ties.append(current_sub_logical_tie) for sub_logical_tie in sub_logical_ties: sub_logical_tie._fuse_leaves_by_immediate_parent()
def add_passaggi(self): self.last_passaggi_ornaments = [self.last_ornament_chosen] * 3 self.last_passaggi_voice = None # to implement: ornament a different voice each time moments = list(abjad.iterate(self.score).vertical_moments()) for moment_pair in zip(moments, moments[1:]): first_starts = moment_pair[0].start_notes next_starts = moment_pair[1].start_notes if len(self.score) == len(first_starts) == len(next_starts): if self.moment_contains_only_base_values(moment_pair[0]): adjacencies = [ Adjacency(moment_pair[0], moment_pair[1], i) for i in range(3) ] if False in [ 'P1' == a.melodic_interval.name for a in adjacencies ]: adjacencies = [ a for a in adjacencies if a.melodic_interval.name != 'P1' ] adjacencies = [a for a in adjacencies \ if not self.succeeds_imitation(a.from_note)] adjacency = self.choose_adjacency(adjacencies) if 2 <= len(adjacencies): adjacency = self.ensure_novel_staff_choice( adjacencies, adjacency) self.last_passaggi_voice = adjacency.staff_index self.add_passaggio_to_adjacency(adjacency) self.last_ornament_chosen = self.last_passaggi_ornaments[0]
def detach_grace_containers(containers, indices): #for i, leaf in enumerate(abjad.iterate(containers).leaves()): leaves = abjad.iterate(containers).leaves(grace_notes=False) for i, leaf in enumerate(leaves): if i not in indices: continue abjad.detach(abjad.GraceContainer, leaf)
def _get_previous_measure(self): import abjad if isinstance(self, abjad.Leaf): for parent in abjad.inspect(self).get_parentage( include_self=False): if isinstance(parent, abjad.Measure): return parent raise MissingMeasureError elif isinstance(self, abjad.Measure): return self._get_in_my_logical_voice(-1, prototype=abjad.Measure) elif isinstance(self, abjad.Container): contents = self._get_descendants_stopping_with() contents = [x for x in contents if isinstance(x, abjad.Measure)] if contents: return contents[0] raise MissingMeasureError elif isinstance(self, (list, tuple)): measure_generator = abjad.iterate(self).components( abjad.Measure, reverse=True, ) try: measure = next(measure_generator) return measure except StopIteration: raise MissingMeasureError else: message = 'unknown component: {!r}.' raise TypeError(message.format(self))
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 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])
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 add_string_music_to_score(score): """ Adds string music to score. """ # generate some pitch and rhythm information pitch_contour_reservoir = create_pitch_contour_reservoir() shadowed_contour_reservoir = shadow_pitch_contour_reservoir( pitch_contour_reservoir) durated_reservoir = durate_pitch_contour_reservoir( shadowed_contour_reservoir) # add six dotted-whole notes and the durated contours to each string voice for name, descents in durated_reservoir.items(): instrument_voice = score['%s Voice' % name] instrument_voice.extend("R1. R1. R1. R1. R1. R1.") for descent in descents: instrument_voice.extend(descent) # apply instrument-specific edits edit_first_violin_voice(score, durated_reservoir) edit_second_violin_voice(score, durated_reservoir) edit_viola_voice(score, durated_reservoir) edit_cello_voice(score, durated_reservoir) edit_bass_voice(score, durated_reservoir) # chop all string parts into 6/4 measures strings_staff_group = score['Strings Staff Group'] with abjad.ForbidUpdate(score): for voice in abjad.iterate(strings_staff_group).components( abjad.Voice): shards = abjad.mutate(voice[:]).split([(6, 4)], cyclic=True) for shard in shards: container = abjad.Container() abjad.mutate(shard).wrap(container)
def _apply_denominator(self, selections, divisions): import abjad if not self.denominator: return tuplets = list(abjad.iterate(selections).components(abjad.Tuplet)) if divisions is None: divisions = len(tuplets) * [None] assert len(selections) == len(divisions) assert len(tuplets) == len(divisions) denominator = self.denominator if isinstance(denominator, tuple): denominator = abjad.Duration(denominator) for tuplet, division in zip(tuplets, divisions): if denominator == 'divisions': tuplet.denominator = division.numerator elif isinstance(denominator, abjad.Duration): unit_duration = denominator assert unit_duration.numerator == 1 duration = abjad.inspect(tuplet).get_duration() denominator_ = unit_duration.denominator nonreduced_fraction = duration.with_denominator(denominator_) tuplet.denominator = nonreduced_fraction.numerator elif abjad.mathtools.is_positive_integer(denominator): tuplet.denominator = denominator else: message = f'invalid preferred denominator: {denominator!r}.' raise Exception(message)
def __call__(self, container, imbrication_token): r'''Calls imbrication specifier on `container`. Returns new container. ''' container = copy.deepcopy(container) imbrication_token = abjad.sequence(imbrication_token) imbrication_token = imbrication_token.flatten() cursor = baca.tools.Cursor( imbrication_token, singletons=True, suppress_exception=True, ) pitch_number = cursor.next() logical_ties = abjad.iterate(container).by_logical_tie(pitched=True) for logical_tie in logical_ties: if logical_tie.head.written_pitch.pitch_number == pitch_number: pitch_number = cursor.next() if self.truncate_ties: for note in logical_tie[1:]: duration = note.written_duration skip = abjad.Skip(duration) abjad.mutate(note).replace([skip]) else: for note in logical_tie: duration = note.written_duration skip = abjad.Skip(duration) abjad.mutate(note).replace([skip]) self._apply_specifiers(container) return container
def test_scoretools_Mutation_copy_07(): voice = abjad.Voice("abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 |" "| 2/8 g'8 a'8 || 2/8 b'8 c''8 |") leaves = abjad.select(voice).leaves() beam = abjad.Beam() abjad.attach(beam, leaves) slur = abjad.Slur() abjad.attach(slur, leaves) assert format(voice) == abjad.String.normalize(r''' \new Voice { { % measure \time 2/8 c'8 [ ( d'8 } % measure { % measure e'8 f'8 } % measure { % measure g'8 a'8 } % measure { % measure b'8 c''8 ] ) } % measure } ''') result = abjad.mutate(voice[-2:]).copy() new_voice = abjad.Voice(result) for component in abjad.iterate(new_voice).components(): abjad.detach(abjad.Spanner, component) assert format(new_voice) == abjad.String.normalize(r''' \new Voice { { % measure \time 2/8 g'8 a'8 } % measure { % measure b'8 c''8 } % measure } ''') assert abjad.inspect(voice).is_well_formed() assert abjad.inspect(new_voice).is_well_formed()
def transpose_from_sounding_pitch(argument): r'''Transpose notes and chords in `argument` from sounding pitch to written pitch: .. container:: example >>> staff = abjad.Staff("<c' e' g'>4 d'4 r4 e'4") >>> clarinet = abjad.ClarinetInBFlat() >>> abjad.attach(clarinet, staff[0]) >>> abjad.show(staff) # doctest: +SKIP .. docs:: >>> abjad.f(staff) \new Staff { \set Staff.instrumentName = \markup { "Clarinet in B-flat" } \set Staff.shortInstrumentName = \markup { "Cl. in B-flat" } <c' e' g'>4 d'4 r4 e'4 } >>> abjad.Instrument.transpose_from_sounding_pitch(staff) >>> abjad.show(staff) # doctest: +SKIP .. docs:: >>> abjad.f(staff) \new Staff { \set Staff.instrumentName = \markup { "Clarinet in B-flat" } \set Staff.shortInstrumentName = \markup { "Cl. in B-flat" } <d' fs' a'>4 e'4 r4 fs'4 } Returns none. ''' import abjad for leaf in abjad.iterate(argument).leaves(pitched=True): instrument = abjad.inspect(leaf).get_effective(abjad.Instrument) if not instrument: continue sounding_pitch = instrument.middle_c_sounding_pitch interval = abjad.NamedPitch('C4') - sounding_pitch interval *= -1 if isinstance(leaf, abjad.Note): pitch = leaf.written_pitch pitch = interval.transpose(pitch) leaf.written_pitch = pitch elif isinstance(leaf, abjad.Chord): pitches = [ interval.transpose(pitch) for pitch in leaf.written_pitches ] leaf.written_pitches = pitches
def fuse_moments(self): for staff in self.score: for pair in abjad.iterate(staff).leaf_pairs(): if self.resolution == pair[0].written_duration == pair[1].written_duration \ and pair[0].written_pitch == pair[1].written_pitch \ and 0 == abjad.inspect(pair[0]).vertical_moment().offset % (2 * self.resolution) \ and not self.contains_suspension(pair): abjad.mutate(pair).fuse()
def music_to_ratios(music): """Converts an Abjad selection to rhythmic ratios.""" ratios = [] for tie in abjad.iterate(music).by_logical_tie(): duration = abjad.inspect(tie).get_duration() fraction = fractions.Fraction(duration) ratios.append(fraction) return ratios
def apply_final_bar_lines(score): """ Applies final bar lines to score. """ for voice in abjad.iterate(score).components(abjad.Voice): bar_line = abjad.BarLine('|.') leaf = abjad.inspect(voice).leaf(-1) abjad.attach(bar_line, leaf)