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.Tag("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 tag(self, argument): import abjad if argument is not None: tag = abjad.Tag(argument) else: tag = None self._tag = tag
def write_time_signatures(self, time_signatures): r"""Write time signatures.""" site = "muda.Material.write_time_signatures()" tag = abjad.Tag(site) print(str(tag)) # select skips to attach TIME SIGNATURES if isinstance(time_signatures[0], abjad.TimeSignature): in_time_signatures = [_.pair for _ in time_signatures] else: in_time_signatures = time_signatures result = abjad.select.leaves(self.container) result = abjad.select.partition_by_durations( result, in_time_signatures, cyclic=False, fill=abjad.Exact, in_seconds=False, overhang=True, ) for time_sig, selection in zip(in_time_signatures, result): abjad.attach( abjad.TimeSignature(time_sig), abjad.select.leaf(selection, 0), tag=tag, )
def make_skips(score, time_signatures): site = "muda.functions.MakeSkips()" 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)) score["Global_Context"].append(skip) # select skips to attach TIME SIGNATURES for i, element in enumerate(in_time_signatures): previous_element = time_signatures[i - 1] if i > 0 else None current_element = element # if current_element != previous_element: a = in_time_signatures.index(current_element) abjad.attach(time_signatures_abjad[a], score["Global_Context"][i], tag=tag)
def skeleton( argument: typing.Union[str, abjad.Selection], *, do_not_check_total_duration: bool = None, tag: typing.Optional[abjad.Tag] = abjad.Tag("baca.skeleton()"), ) -> RhythmCommand: """ Makes rhythm command from ``string`` and attaches NOT_YET_PITCHED indicators to music. """ if isinstance(argument, str): string = f"{{ {argument} }}" container = abjad.parse(string) selection = abjad.mutate.eject_contents(container) elif isinstance(argument, abjad.Selection): selection = argument else: message = "baca.skeleton() accepts string or selection," message += " not {repr(argument)}." raise TypeError(message) if tag is not None: tag_selection(selection, tag) return RhythmCommand( selection, annotation_spanner_color="#darkcyan", annotation_spanner_text="baca.skeleton() =|", attach_not_yet_pitched=True, do_not_check_total_duration=do_not_check_total_duration, )
def music( argument: typing.Union[str, abjad.Selection], *, do_not_check_total_duration: bool = None, tag: typing.Optional[abjad.Tag] = abjad.Tag("baca.music()"), ) -> RhythmCommand: """ Makes rhythm command from string or selection ``argument``. """ if isinstance(argument, str): string = f"{{ {argument} }}" container = abjad.parse(string) selection = abjad.mutate.eject_contents(container) elif isinstance(argument, abjad.Selection): selection = argument else: message = "baca.music() accepts string or selection," message += f" not {repr(argument)}." raise TypeError(message) if tag is not None: tag_selection(selection, tag) return RhythmCommand( selection, annotation_spanner_color="#darkcyan", annotation_spanner_text="baca.music() =|", do_not_check_total_duration=do_not_check_total_duration, )
def glissando_rhythm(rotate=0): return baca.rhythm( rmakers.talea(abjad.sequence.rotate([5, 1, 2, 1], n=rotate), 8), rmakers.beam(), rmakers.extract_trivial(), rmakers.rewrite_meter(), tag=abjad.Tag("animales.glissando_rhythm()"), )
def _make_mm_rests(self): print("Making MM rests ...") for voice in abjad.iterate( self.score_template["Staff Group"]).components( abjad.Staff # was Voice ): leaves = abjad.select(voice).leaves(grace=False) shards = abjad.mutate.split(leaves, self.time_signatures) for shard in shards[:-1]: if not all(isinstance(leaf, abjad.Rest) for leaf in shard): continue indicators = abjad.get.indicators(shard[0]) multiplier = abjad.get.duration(shard) / 2 invisible_rest = abjad.Rest(1, multiplier=(multiplier)) rest_literal = abjad.LilyPondLiteral( r"\once \override Rest.transparent = ##t", "before") abjad.attach(rest_literal, invisible_rest, tag=abjad.Tag("applying invisibility")) for indicator in indicators: abjad.attach(indicator, invisible_rest, tag=abjad.Tag("applying indicators")) multimeasure_rest = abjad.MultimeasureRest( 1, multiplier=(multiplier)) start_command = abjad.LilyPondLiteral( r"\stopStaff \once \override Staff.StaffSymbol.line-count = #1 \startStaff", format_slot="before", ) stop_command = abjad.LilyPondLiteral(r"\stopStaff \startStaff", format_slot="after") if self.cutaway is True: abjad.attach(start_command, invisible_rest, tag=abjad.Tag("applying cutaway")) abjad.attach( stop_command, multimeasure_rest, tag=abjad.Tag("applying cutaway"), ) both_rests = [invisible_rest, multimeasure_rest] abjad.mutate.replace(shard, both_rests[:]) else: both_rests = [invisible_rest, multimeasure_rest] abjad.mutate.replace(shard, both_rests[:])
def _make_global_context(self): print("Making global context ...") for time_signature in self.time_signatures: skip = abjad.Skip(1, multiplier=(time_signature)) abjad.attach(time_signature, skip, tag=abjad.Tag("scaling time signatures")) self.score_template["Global Context"].append(skip)
def __init__(self): """Todo.""" site = "muda.Score()" tag = abjad.Tag(site) self.score = abjad.Score(name="Score", tag=tag) self.score.append( abjad.Staff(lilypond_type="TimeSignatureContext", name="Global_Context")) print(str(tag))
def clb_rhythm( section: str, member: int, counts: typing.Sequence[abjad.IntegerSequence], wrap: int, ): if section in ("First.Violin", "Second.Violin", "Viola"): assert member in range(1, 18 + 1), repr(member) elif section == "Cello": assert member in range(1, 14 + 1), repr(member) elif section == "Contrabass": assert member in range(1, 6 + 1), repr(member) else: assert ValueError(section) section_to_offset = { "First.Violin": 0, "Second.Violin": 18, "Viola": 36, "Cello": 54, "Contrabass": 68, } total_players = 74 index = section_to_offset[section] + member - 1 counts_ = baca.sequence.helianthate(counts, -1, -1) counts_ = abjad.sequence.flatten(counts_) counts_ = abjad.sequence.repeat_to_weight(counts_, total_players * wrap) shards = abjad.sequence.split(counts_, [wrap], cyclic=True, overhang=abjad.Exact) assert len(shards) == total_players assert abjad.sequence.weight(shards) == abjad.sequence.weight(counts_) counts_ = shards[index] extra_counts = None if index % 9 in [2, 3, 6, 7]: extra_counts = [-1] def preprocessor(divisions): result = baca.sequence.fuse(divisions) result = baca.sequence.quarters(result) return result return baca.rhythm( rmakers.talea(counts_, 16, extra_counts=extra_counts), rmakers.beam(), rmakers.rewrite_rest_filled(), rmakers.trivialize(), rmakers.force_diminution(), rmakers.extract_trivial(), rmakers.rewrite_meter(), preprocessor=preprocessor, tag=abjad.Tag("animales.clb_rhythm()"), )
def downbeat_attack(count=1, denominator=8): return baca.rhythm( rmakers.talea([count], denominator), rmakers.force_rest(baca.selectors.lts((1, None)), ), rmakers.beam(), rmakers.rewrite_rest_filled(), rmakers.extract_trivial(), rmakers.rewrite_meter(), tag=abjad.Tag("animales.downbeat_attack()"), )
def tag(self) -> abjad.Tag: """ Gets tag. """ # TODO: replace self.get_tag() functionality words = [str(_) for _ in self.tags] string = ":".join(words) tag = abjad.Tag(string) assert isinstance(tag, abjad.Tag) return tag
def get_tag(self, leaf: abjad.Leaf = None) -> typing.Optional[abjad.Tag]: """ Gets tag for ``leaf``. """ tags = self.tags[:] if self.tag_measure_number: start_offset = abjad.get.timespan(leaf).start_offset measure_number = self.runtime["offset_to_measure_number"].get( start_offset) if getattr(self, "after", None) is True: measure_number += 1 if measure_number is not None: tag = abjad.Tag(f"MEASURE_{measure_number}") tags.append(tag) if tags: words = [str(_) for _ in tags] string = ":".join(words) tag = abjad.Tag(string) return tag # TODO: return empty tag (instead of none) return None
def append(self, context): r"""Add ``muda.Instrument.ready_staff`` to the score. >>> my_inst = muda.Instrument( ... abjad_instrument = abjad.Piano(), ... name = "Piano", ... staff_count = 2, ... voice_count = [2, 1],) muda.score.Instrument() Piano creating Staff: Piano_Staff_1 creating Staff: Piano_Staff_2 creating Voice: Piano_Voice_1 creating Voice: Piano_Voice_2 creating Voice: Piano_Voice_3 >>> my_score.append([my_inst]) muda.Score.append() Piano >>> print(abjad.lilypond(my_score.score) ... ) \context Score = "Score" << \context TimeSignatureContext = "Global_Context" { } \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.append()" tag = abjad.Tag(site) if isinstance(context, list): for inst in context: print(str(tag), str(inst.name)) self.score.append(inst.ready_staff) else: self.score.append(context)
def site(frame, prefix, *, n=None) -> abjad.Tag: """ Makes site from ``frame``. .. todo:: Determine prefix dynamically. """ frame_info = inspect.getframeinfo(frame) if n is None: string = f"{prefix}.{frame_info.function}()" else: string = f"{prefix}.{frame_info.function}({n})" return abjad.Tag(string)
def margin_markup(key, alert=None, context="Staff", selector=baca.selectors.leaf(0)): margin_markup = margin_markups[key] command = baca.margin_markup( margin_markup, alert=alert, context=context, selector=selector, ) command_ = baca.not_parts(command) command_ = baca.tag(abjad.Tag("ANIMALES"), command_) return command_
def _initialize_tags(self, tags): tags_ = [] for tag in tags or []: if tag in (None, ""): continue elif isinstance(tag, str): for word in tag.split(":"): tag_ = abjad.Tag(word) tags_.append(tag_) elif isinstance(tag, abjad.Tag): tags_.append(tag) else: raise TypeError(tag) assert all(isinstance(_, abjad.Tag) for _ in tags_) self._tags = tags_
def __init__(self, abjad_instrument, name, staff_count, voice_count, lyrics_target=None): """Initializer.""" site = "muda.score.Instrument()" self.tag = abjad.Tag(site) print(str(self.tag), name) self.abjad_instrument = abjad_instrument self.name = name self.staff_count = staff_count self.voice_count = voice_count self.lyrics_target = lyrics_target self.__call__()
def _make_global_context(self): site = "abjad.ScoreTemplate._make_global_context()" tag = abjad.Tag(site) global_rests = abjad.Context( lilypond_type="GlobalRests", name="Global_Rests", tag=tag, ) global_skips = abjad.Context( lilypond_type="GlobalSkips", name="Global_Skips", tag=tag, ) global_context = abjad.Context( [global_rests, global_skips], lilypond_type="GlobalContext", simultaneous=True, name="Global_Context", tag=tag, ) return global_context
def tag( tags: typing.Union[abjad.Tag, typing.List[abjad.Tag]], command: CommandTyping, *, deactivate: bool = None, tag_measure_number: bool = None, ) -> CommandTyping: """ Appends each tag in ``tags`` to ``command``. Sorts ``command`` tags. Acts in place. """ if isinstance(tags, abjad.Tag): tags = [tags] if not isinstance(tags, list): message = "tags must be tag or list of tags" message += f" (not {tags!r})." raise Exception(message) assert all(isinstance(_, abjad.Tag) for _ in tags), repr(tags) assert Command._validate_tags(tags), repr(tags) if not isinstance(command, (Command, Suite)): raise Exception("can only tag command or suite.") if isinstance(command, Suite): for command_ in command.commands: tag( tags, command_, deactivate=deactivate, tag_measure_number=tag_measure_number, ) else: assert isinstance(command, Command), repr(command) assert command._tags is not None try: tags.sort() except TypeError: pass tags_ = [abjad.Tag(_) for _ in tags] # TODO: maybe use abjad.new() here? command._tags.extend(tags_) command._deactivate = deactivate command._tag_measure_number = tag_measure_number return command
def __call__(self, voice, *, tag: abjad.Tag = abjad.Tag()) -> None: assert isinstance(voice, abjad.Voice), repr(voice) staff = abjad.get.parentage(voice).parent assert isinstance(staff, abjad.Staff), repr(staff) time_signature_voice = staff["TimeSignatureVoice"] assert isinstance(time_signature_voice, abjad.Voice) meters, preferred_meters = [], [] for skip in time_signature_voice: time_signature = abjad.get.indicator(skip, abjad.TimeSignature) meter = abjad.Meter(time_signature) meters.append(meter) durations = [abjad.Duration(_) for _ in meters] reference_meters = self.reference_meters or () command = rmakers.SplitMeasuresCommand() non_tuplets = [] for component in voice: if isinstance(component, abjad.Tuplet): new_dur = abjad.get.duration(component) new_mult = abjad.Multiplier(new_dur) new_skip = abjad.Skip((1, 1), multiplier=new_mult) non_tuplets.append(new_skip) else: non_tuplets.append(component) command(non_tuplets, durations=durations) selections = abjad.select.group_by_measure(voice[:]) for meter, selection in zip(meters, selections): for reference_meter in reference_meters: if str(reference_meter) == str(meter): meter = reference_meter break preferred_meters.append(meter) nontupletted_leaves = [] for leaf in abjad.iterate.leaves(selection): if not abjad.get.parentage(leaf).count(abjad.Tuplet): nontupletted_leaves.append(leaf) rmakers.unbeam()(nontupletted_leaves) abjad.Meter.rewrite_meter( selection, meter, boundary_depth=self.boundary_depth, rewrite_tuplets=False, )
def make_skips(self, argument): r"""Write skips and time signatures to Context.""" site = "muda.Material.make_skips()" tag = abjad.Tag(site) print(str(tag)) if isinstance(argument, list or abjad.TimeSignature): time_signatures_abjad = [] if isinstance(argument[0], abjad.TimeSignature): time_signatures_abjad = argument elif isinstance(argument, list): in_time_signatures = argument 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.container.append(skip) else: self.container.extend(argument)
def brass_manifest_rhythm(part): assert part in range(1, 12 + 1), repr(part) counts, delay, extra_counts = { 1: ([8, 8, -2], 9, [0, 0, 0, 1]), 2: ([8, 8, -2], 13, [0, 1, 0, 0]), 3: ([8, 8, -2], None, [0, 0, 1, 0]), 4: ([8, 8, -2], 4, [1, 0, 0, 0]), 5: ([7, 7, -2], 6, [0, 0, 0, 1]), 6: ([7, 7, -2], 10, [0, 1, 0, 0]), 7: ([7, 7, -2], None, [0, 0, 1, 0]), 8: ([7, 7, -2], 4, [1, 0, 0, 0]), 9: ([6, 6, 6, -2], 9, [0, 0, 0, 1]), 10: ([6, 6, 6, -2], 13, [0, 1, 0, 0]), 11: ([6, 6, 6, -2], None, [0, 0, 1, 0]), 12: ([6, 6, 6, -2], 4, [1, 0, 0, 0]), }[part] if delay is None: preamble = () else: preamble = [-delay] def preprocessor(divisions): result = baca.sequence.fuse(divisions) result = baca.sequence.quarters(divisions) return result return baca.rhythm( rmakers.talea(counts, 8, extra_counts=extra_counts, preamble=preamble), rmakers.beam(), rmakers.rewrite_rest_filled(), rmakers.trivialize(), rmakers.extract_trivial(), rmakers.rewrite_meter(), preprocessor=preprocessor, persist="brass_manifest_rhythm", tag=abjad.Tag("animales.brass_manifest_rhythm()"), )
def pennant_rhythm(extra_counts=None, silences=None): commands = [] if silences is not None: specifier = rmakers.force_rest(baca.selectors.tuplets(silences), ) commands.append(specifier) def preprocessor(divisions): result = baca.sequence.fuse(divisions) result = baca.sequence.quarters(divisions) return result return baca.rhythm( rmakers.talea([1], 16, extra_counts=extra_counts), *commands, rmakers.beam(), rmakers.rewrite_rest_filled(), rmakers.force_diminution(), rmakers.trivialize(), rmakers.extract_trivial(), rmakers.rewrite_meter(), preprocessor=preprocessor, tag=abjad.Tag("animales.pennant_rhythm()"), )
def _call(self, argument=None): """ Calls command on ``argument``. """ if argument is None: return if self.start_indicator is None and self.stop_indicator is None: return if self.selector: argument = self.selector(argument) if self.start_indicator is not None: start_indicator = self.start_indicator if self.detach_first: for leaf in abjad.iterate(argument).leaves(grace=False): abjad.detach(type(start_indicator), leaf) self._apply_tweaks(start_indicator, self.tweaks) first_leaf = abjad.select(argument).leaf(0) if self.left_broken: self._attach_indicator( start_indicator, first_leaf, deactivate=self.deactivate, tag=abjad.Tag( "baca.SpannerIndicatorCommand._call(1)").append( ide.tags.SPANNER_START).append( ide.tags.LEFT_BROKEN), ) else: self._attach_indicator( start_indicator, first_leaf, deactivate=self.deactivate, tag=abjad.Tag( "baca.SpannerIndicatorCommand._call(2)").append( ide.tags.SPANNER_START), ) if self.stop_indicator is not None: stop_indicator = self.stop_indicator if self.detach_first: for leaf in abjad.iterate(argument).leaves(grace=False): abjad.detach(type(stop_indicator), leaf) final_leaf = abjad.select(argument).leaf(-1) if self.right_broken: self._attach_indicator( stop_indicator, final_leaf, deactivate=self.deactivate, tag=abjad.Tag( "baca.SpannerIndicatorCommand._call(3)").append( ide.tags.SPANNER_STOP).append( ide.tags.RIGHT_BROKEN), ) else: self._attach_indicator( stop_indicator, final_leaf, deactivate=self.deactivate, tag=abjad.Tag( "baca.SpannerIndicatorCommand._call(4)").append( ide.tags.SPANNER_STOP), )
import abjad import abjadext.rmakers as rmakers import muda durations_general = [(4, 4)] * 32 rmaker_afluteA = rmakers.stack( rmakers.talea([4, -2, 1], 8), rmakers.extract_trivial(), # counts # denominator tag=abjad.Tag("Mat_A"), ) rmaker_afluteB = rmakers.stack( rmakers.talea([1], 8, extra_counts=[1]), rmakers.beam(), rmakers.extract_trivial(), # counts # denominator # rmakers.rewrite_meter(), tag=abjad.Tag("Mat_B"), ) rest_maker = rmakers.stack(rmakers.note(), rmakers.force_rest(abjad.select()), tag=abjad.Tag("Rests")) rmaker_bclarinetA = rmakers.stack( rmakers.talea([-4, 2], 8), # counts # denominator rmakers.beam(), rmakers.extract_trivial(), tag=abjad.Tag("Mat_A"), ) rmaker_bclarinetB = rmakers.stack(
instruments=library.instruments, margin_markups=library.margin_markups, metronome_marks=library.metronome_marks, time_signatures=time_signatures, voice_abbreviations=library.voice_abbreviations(), voice_names=voice_names, ) commands( "Global_Skips", baca.rehearsal_mark( "W", baca.selectors.skip(1 - 1), abjad.tweak( (0, 6), tag=abjad.Tag("+TABLOID_SCORE"), ).extra_offset, ), ) # brass library.assign_brass_sforzando_parts(commands) library.brass_sforzando(commands, 1) # strings library.battuti(commands, [[1, -55], [1, -17], [1, -17]]) if __name__ == "__main__": metadata, persist, score, timing = baca.build.interpret_segment(
print(message) if layout_time_signatures != time_signatures: message = " Music time signatures still do not match" message += " layout time signatures ..." print(message) except: traceback.print_exc() sys.exit(1) try: if getattr(maker, "do_not_externalize", False) is not True: illustration_ly.extern(realign=79) illustration_ily = illustration_ly.with_suffix(".ily") assert illustration_ily.is_file() not_topmost = abjad.Job( deactivate=(abjad.Tag("NOT_TOPMOST"), "not topmost"), path=segment_directory, title="deactivating NOT_TOPMOST ...", ) for message in not_topmost(): print(" " + message) lilypond_log_file_path = illustration_ily.parent / ".log" with abjad.Timer() as timer: print(" Running LilyPond ...") abjad.IOManager.run_lilypond( illustration_ly, lilypond_log_file_path=lilypond_log_file_path) lilypond_log_file_path.remove_lilypond_warnings( crescendo_too_small=True, decrescendo_too_small=True, overwriting_glissando=True, )
def harp_exchange_rhythm(this_part, *commands, silence_first=False): part_to_pattern = dict([ (0, abjad.index([0, 30], period=36)), (1, abjad.index([0, 12, 16, 28, 32], period=48)), (2, abjad.index([0, 30], period=36)), (3, abjad.index([0, 12, 16, 28, 32], period=48)), ]) part_to_indices = {} for part in part_to_pattern: part_to_indices[part] = [] harp_indices = [] part = 0 pattern = part_to_pattern[part] index = 0 while True: if index % pattern.period in pattern.indices: part_to_indices[part].append(index) harp_indices.append((index, part)) degrees = [] for indices in part_to_indices.values(): talea = abjad.math.difference_series(indices) degree = baca.sequence.degree_of_rotational_symmetry(talea) degrees.append(degree) if all(1 < _ for _ in degrees): break part = (part + 1) % len(part_to_pattern) pattern = part_to_pattern[part] index += 1 if 999 < index: break part_to_preamble = {} part_to_counts = {} for part, indices in part_to_indices.items(): offset = indices[0] preamble = [] if offset != 0: preamble.append(offset) part_to_preamble[part] = preamble counts = abjad.math.difference_series(indices) period = baca.sequence.period_of_rotation(counts) counts = counts[:period] part_to_counts[part] = counts preamble = part_to_preamble[this_part] counts = [] for count in part_to_counts[this_part]: counts.append(2) rest = -(count - 2) counts.append(rest) silence_first_specifier = [] if silence_first is True: specifier = rmakers.force_rest(baca.selectors.lt(0)) silence_first_specifier.append(specifier) def preprocessor(divisions): result = baca.sequence.fuse(divisions) result = baca.sequence.quarters(result) return result return baca.rhythm( rmakers.talea(counts, 16, extra_counts=[2], preamble=preamble), *commands, rmakers.cache_state(), *silence_first_specifier, rmakers.beam(), rmakers.trivialize(), rmakers.extract_trivial(), rmakers.rewrite_meter(), rmakers.force_repeat_tie(), preprocessor=preprocessor, persist="harp_exchange_rhythm", tag=abjad.Tag("animales.harp_exchange_rhythm()"), )