コード例 #1
0
    def make_lilypond_override_string(
        grob,
        attribute,
        value,
        context=None,
        once=False,
        ):
        r'''Makes Lilypond override string.

        Returns string.
        '''
        import abjad
        grob = abjad.String(grob).to_upper_camel_case()
        attribute = LilyPondFormatManager.format_lilypond_attribute(attribute)
        value = LilyPondFormatManager.format_lilypond_value(value)
        if context is not None:
            context = abjad.String(context).to_upper_camel_case()
            context += '.'
        else:
            context = ''
        if once is True:
            once = r'\once '
        else:
            once = ''
        result = r'{}\override {}{}.{} = {}'
        result = result.format(once, context, grob, attribute, value)
        return result
コード例 #2
0
    def _process_args(self, arguments):
        import abjad

        message = "Replacing {!r} with {!r} ..."
        message = message.format(arguments.old, arguments.new)
        print(message)
        skipped_dirs_patterns = self.skipped_directories
        skipped_dirs_patterns += arguments.without_dirs
        skipped_files_patterns = self.skipped_files + arguments.without_files
        if arguments.regex or (not arguments.regex
                               and arguments.whole_words_only):
            arguments.old = self._get_regex_search_callable(arguments)
            index, length = arguments.old("", 0)
            if 0 <= index:
                message = "regex pattern {!r} matches the empty string."
                message = message.format(arguments.old.pattern.pattern)
                raise ValueError(message)
        else:
            arguments.old = self._get_naive_search_callable(arguments)
        changed_file_count = 0
        changed_line_count = 0
        changed_item_count = 0
        for root, dirs, files in os.walk(arguments.path):
            dirs_to_remove = []
            for dir in dirs:
                for pattern in skipped_dirs_patterns:
                    if fnmatch.fnmatch(dir, pattern):
                        dirs_to_remove.append(dir)
                        break
            for dir in dirs_to_remove:
                dirs.remove(dir)
            for file in sorted(files):
                valid = True
                for pattern in skipped_files_patterns:
                    if fnmatch.fnmatch(file, pattern):
                        valid = False
                        break
                if not valid:
                    continue
                changed_lines, changed_items = self._process_file(
                    arguments, os.path.join(root, file))
                if changed_lines:
                    changed_file_count += 1
                    changed_line_count += changed_lines
                    changed_item_count += changed_items
        print()
        item_identifier = abjad.String("instance").pluralize(
            changed_item_count)
        line_identifier = abjad.String("line").pluralize(changed_line_count)
        file_identifier = abjad.String("file").pluralize(changed_file_count)
        message = "\tReplaced {} {} over {} {} in {} {}."
        message = message.format(
            changed_item_count,
            item_identifier,
            changed_line_count,
            line_identifier,
            changed_file_count,
            file_identifier,
        )
        print(message)
コード例 #3
0
    def _write_optimization_log(self):
        print("Writing optimization log ...\n")
        times = [
            self.pre_handlers_time + self.handlers_time +
            self.post_handlers_time
        ]
        segment_time = sum(times)
        with open(f"{self.current_directory}/.optimization", "a") as fp:

            segment_time = f"Segment runtime: {segment_time} "
            segment_time += abjad.String("second").pluralize(segment_time)

            pre_handlers_time = f" Pre-handlers runtime: {self.pre_handlers_time} "
            pre_handlers_time += abjad.String("second").pluralize(
                self.pre_handlers_time)

            handlers_time = f" Handlers runtime: {self.handlers_time} "
            handlers_time += abjad.String("second").pluralize(
                self.handlers_time)

            post_handlers_time = f" Post-handlers runtime: {self.post_handlers_time} "
            post_handlers_time += abjad.String("second").pluralize(
                self.post_handlers_time)

            lines = []
            lines.append("")
            lines.append("")
            lines.append(
                f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            lines.append(segment_time)
            lines.append(pre_handlers_time)
            lines.append(handlers_time)
            lines.append(post_handlers_time)
            string = "\n".join(lines)
            fp.write(string)
コード例 #4
0
    def from_expr(class_, argument):
        r'''Convenience constructor for enumerations.

        Returns new enumeration item.
        '''
        import abjad
        if isinstance(argument, class_):
            return argument
        elif isinstance(argument, int):
            return class_(argument)
        elif isinstance(argument, str):
            argument = argument.strip()
            argument = abjad.String(argument).to_snake_case()
            argument = argument.upper()
            try:
                return class_[argument]
            except KeyError:
                return class_[argument.replace('_', '')]
        elif argument is None:
            return class_(0)
        message = 'Cannot instantiate {} from {}.'.format(
            class_.__name__,
            argument,
        )
        raise ValueError(message)
コード例 #5
0
    def make_lilypond_revert_string(grob, attribute, context=None):
        r'''Makes LilyPond revert string.

        Returns string.
        '''
        import abjad
        grob = abjad.String(grob).to_upper_camel_case()
        attribute = LilyPondFormatManager.format_lilypond_attribute(attribute)
        attribute = attribute.split('.')[0]
        if context is not None:
            context = abjad.String(context).to_upper_camel_case()
            context += '.'
        else:
            context = ''
        result = r'\revert {}{}.{}'
        result = result.format(context, grob, attribute)
        return result
コード例 #6
0
 def _get_lilypond_format(self):
     import abjad
     command = self._name
     if command.startswith('#'):
         return command
     elif ' ' not in command:
         return self.prefix + abjad.String(command).to_lower_camel_case()
     else:
         return self.prefix + command
コード例 #7
0
ファイル: Instrument.py プロジェクト: tchiwinpiti/abjad
 def _initialize_default_name_markups(self):
     import abjad
     if self._name_markup is None:
         if self.name:
             string = self.name
             string = abjad.String(string).capitalize_start()
             markup = abjad.Markup(contents=string)
             self._name_markup = markup
         else:
             self._name_markup = None
     if self._short_name_markup is None:
         if self.short_name:
             string = self.short_name
             string = abjad.String(string).capitalize_start()
             markup = abjad.Markup(contents=string)
             self._short_name_markup = markup
         else:
             self._short_name_markup = None
コード例 #8
0
ファイル: Timer.py プロジェクト: tchiwinpiti/abjad
    def total_time_message(self):
        r'''Gets total time message.

        Truncated to the nearest second.

        Returns string.
        '''
        import abjad
        identifier = abjad.String('second').pluralize(int(self.elapsed_time))
        message = 'total time {} {} ...'
        message = message.format(int(self.elapsed_time), identifier)
        return message
コード例 #9
0
    def total_time_message(self):
        """
        Gets total time message.

        Truncated to the nearest second.

        Returns string.
        """
        import abjad

        identifier = abjad.String("second").pluralize(int(self.elapsed_time))
        message = "total time {} {} ..."
        message = message.format(int(self.elapsed_time), identifier)
        return message
コード例 #10
0
    def make_lilypond_tweak_string(attribute, value, grob=None):
        r'''Makes Lilypond \tweak string.

        Returns string.
        '''
        import abjad
        if grob is not None:
            grob = abjad.String(grob).to_upper_camel_case()
            grob += '.'
        else:
            grob = ''
        attribute = LilyPondFormatManager.format_lilypond_attribute(attribute)
        value = LilyPondFormatManager.format_lilypond_value(value)
        result = r'- \tweak {}{} {}'
        result = result.format(grob, attribute, value)
        return result
コード例 #11
0
ファイル: scoping.py プロジェクト: jgarte/baca
    def _to_indicator_stem(indicator) -> abjad.String:
        """
        Changes ``indicator`` to stem.

        ..  container:: example

            >>> baca.Command._to_indicator_stem(abjad.Clef("alto"))
            'CLEF'

            >>> baca.Command._to_indicator_stem(abjad.Clef("treble"))
            'CLEF'

            >>> baca.Command._to_indicator_stem(abjad.Dynamic("f"))
            'DYNAMIC'

            >>> baca.Command._to_indicator_stem(abjad.StartHairpin("<"))
            'DYNAMIC'

            >>> baca.Command._to_indicator_stem(abjad.Cello())
            'INSTRUMENT'

            >>> baca.Command._to_indicator_stem(abjad.Violin())
            'INSTRUMENT'

            >>> metronome_mark = abjad.MetronomeMark((1, 4), 58)
            >>> baca.Command._to_indicator_stem(metronome_mark)
            'METRONOME_MARK'

            >>> start_text_span = abjad.StartTextSpan()
            >>> baca.Command._to_indicator_stem(start_text_span)
            'TEXT_SPANNER'

            >>> stop_text_span = abjad.StopTextSpan()
            >>> baca.Command._to_indicator_stem(stop_text_span)
            'TEXT_SPANNER'

        """
        assert getattr(indicator, "persistent", False), repr(indicator)
        if isinstance(indicator, abjad.Instrument):
            stem = "INSTRUMENT"
        elif getattr(indicator, "parameter", None) == "TEMPO":
            stem = "METRONOME_MARK"
        elif hasattr(indicator, "parameter"):
            stem = indicator.parameter
        else:
            stem = type(indicator).__name__
        return abjad.String(stem).to_shout_case()
コード例 #12
0
        material = getattr(definition, directory.name)
    except ImportError:
        traceback.print_exc()
        sys.exit(1)

    try:
        with abjad.Timer() as timer:
            if getattr(definition, "__illustrate__", None):
                __illustrate__ = getattr(definition, "__illustrate__")
                lilypond_file = __illustrate__(material)
            elif hasattr(material, "__illustrate__"):
                lilypond_file = material.__illustrate__()
            else:
                print(f"No illustrate method ...")
        count = int(timer.elapsed_time)
        counter = abjad.String("second").pluralize(count)
        message = f"Abjad runtime {count} {counter} ..."
        print(message)
    except:
        traceback.print_exc()
        sys.exit(1)

    if lilypond_file is None:
        sys.exit(0)

    try:
        ly = directory / "illustration.ly"
        with abjad.Timer() as timer:
            abjad.persist(lilypond_file).as_ly(ly, strict=89)
        count = int(timer.elapsed_time)
        counter = abjad.String("second").pluralize(count)
コード例 #13
0
    def __getattr__(self, name):
        r'''Gets LilyPond name manager keyed to `name`.

        ..  container:: example

            >>> staff = abjad.Staff("c'4 d' e' f'")
            >>> abjad.override(staff).note_head.color = 'red'
            >>> abjad.show(staff) # doctest: +SKIP

            ..  docs::

                >>> abjad.f(staff)
                \new Staff
                \with
                {
                    \override NoteHead.color = #red
                }
                {
                    c'4
                    d'4
                    e'4
                    f'4
                }

        ..  container:: example

            Returns LilyPond name manager:

            >>> abjad.override(staff).note_head
            LilyPondNameManager(('color', 'red'))

        '''
        import abjad
        from abjad import ly
        from abjad.tools import lilypondnametools
        camel_name = abjad.String(name).to_upper_camel_case()
        if name.startswith('_'):
            try:
                return vars(self)[name]
            except KeyError:
                message = '{!r} object has no attribute: {!r}.'
                message = message.format(type(self).__name__, name)
                raise AttributeError(message)
        elif camel_name in ly.contexts:
            try:
                return vars(self)['_' + name]
            except KeyError:
                context = lilypondnametools.LilyPondGrobNameManager()
                vars(self)['_' + name] = context
                return context
        elif camel_name in ly.grob_interfaces:
            try:
                return vars(self)[name]
            except KeyError:
                vars(self)[name] = lilypondnametools.LilyPondNameManager()
                return vars(self)[name]
        else:
            try:
                return vars(self)[name]
            except KeyError:
                message = '{!r} object has no attribute: {!r}.'
                message = message.format(type(self).__name__, name)
                raise AttributeError(message)
コード例 #14
0
ファイル: __make_segment_pdf__.py プロジェクト: tuchang/abjad
                              scores=scores_directory)
 assert segment_directory.is_score_package_path(), repr(
     segment_directory)
 illustration_ly = segment_directory / "illustration.ly"
 print(" Running segment-maker ...")
 with abjad.Timer() as timer:
     lilypond_file = maker.run(
         metadata=metadata,
         persist=persist,
         previous_metadata=previous_metadata,
         previous_persist=previous_persist,
         segment_directory=segment_directory,
     )
 segment_maker_runtime = int(timer.elapsed_time)
 count = segment_maker_runtime
 counter = abjad.String("second").pluralize(count)
 message = f" Segment-maker runtime {{count}} {{counter}} ..."
 print(message)
 segment_maker_runtime = (count, counter)
 segment_directory.write_metadata_py(maker.metadata)
 segment_directory.write_metadata_py(maker.persist,
                                     file_name="__persist__.py",
                                     variable_name="persist")
 first_segment = segment_directory.segments.get_next_package()
 if segment_directory.name != first_segment.name:
     layout_ly = segment_directory / "layout.ly"
     if not layout_ly.is_file():
         message = f"{{layout_ly.trim()}} does not exit."
         raise Exception(message)
     result = layout_ly.get_preamble_page_count_overview()
     if result is not None:
コード例 #15
0
        assert isinstance(breaks, baca.BreakMeasureMap), repr(breaks)
    except ImportError:
        print(f'No breaks in {{maker.trim()}} ...')
        sys.exit(1)

    try:
        from {layout_module_name} import spacing
        prototype = baca.HorizontalSpacingSpecifier
        assert isinstance(spacing, prototype), repr(spacing)
    except ImportError:
        spacing = None

    try:
        buildspace_directory = maker.parent
        layout_py = buildspace_directory / '{layout_module_name}.py'
        document_name = abjad.String(buildspace_directory.name).to_shout_case()
    except:
        traceback.print_exc()
        sys.exit(1)

    try:
        if buildspace_directory.get_metadatum('parts_directory') is True:
            from {layout_module_name} import part_identifier
            assert abjad.String(part_identifier).is_shout_case()
            document_name = f'{{document_name}}_{{part_identifier}}'
    except ImportError:
        traceback.print_exc()
        sys.exit(1)

    try:
        if buildspace_directory.is_segment():
コード例 #16
0
            segment_directory,
            scores=scores_directory,
        )
        assert segment_directory.is_score_package_path(), repr(
            segment_directory)
        illustration_ly = segment_directory('illustration.ly')
        print(' Running segment-maker ...')
        with abjad.Timer() as timer:
            lilypond_file = maker.run(
                metadata=metadata,
                previous_metadata=previous_metadata,
                segment_directory=segment_directory,
            )
        segment_maker_runtime = int(timer.elapsed_time)
        count = segment_maker_runtime
        counter = abjad.String('second').pluralize(count)
        message = f' Segment-maker runtime {{count}} {{counter}} ...'
        print(message)
        segment_maker_runtime = (count, counter)
        segment_directory.write_metadata_py(maker.metadata)
        result = abjad.persist(lilypond_file).as_ly(illustration_ly, strict=89)
        abjad_format_time = int(result[1])
        count = abjad_format_time
        counter = abjad.String('second').pluralize(count)
        message = f' Abjad format time {{count}} {{counter}} ...'
        print(message)
        abjad_format_time = (count, counter)
    except:
        traceback.print_exc()
        sys.exit(1)
コード例 #17
0
ファイル: scoping.py プロジェクト: jgarte/baca
 def _remove_reapplied_wrappers(leaf, indicator):
     if not getattr(indicator, "persistent", False):
         return
     if getattr(indicator, "parameter", None) == "TEXT_SPANNER":
         return
     if abjad.get.timespan(leaf).start_offset != 0:
         return
     dynamic_prototype = (abjad.Dynamic, abjad.StartHairpin)
     tempo_prototype = (
         abjad.MetronomeMark,
         indicators.Accelerando,
         indicators.Ritardando,
     )
     if isinstance(indicator, abjad.Instrument):
         prototype = abjad.Instrument
     elif isinstance(indicator, dynamic_prototype):
         prototype = dynamic_prototype
     elif isinstance(indicator, tempo_prototype):
         prototype = tempo_prototype
     else:
         prototype = type(indicator)
     stem = Command._to_indicator_stem(indicator)
     assert stem in (
         "BAR_EXTENT",
         "BEAM",
         "CLEF",
         "DYNAMIC",
         "INSTRUMENT",
         "MARGIN_MARKUP",
         "METRONOME_MARK",
         "OTTAVA",
         "PEDAL",
         "PERSISTENT_OVERRIDE",
         "REPEAT_TIE",
         "SLUR",
         "STAFF_LINES",
         "TIE",
         "TRILL",
     ), repr(stem)
     reapplied_wrappers = []
     reapplied_indicators = []
     wrappers = list(abjad.get.wrappers(leaf))
     effective_wrapper = abjad.get.effective_wrapper(leaf, prototype)
     if effective_wrapper and effective_wrapper not in wrappers:
         component = effective_wrapper.component
         start_1 = abjad.get.timespan(leaf).start_offset
         start_2 = abjad.get.timespan(component).start_offset
         if start_1 == start_2:
             wrappers_ = abjad.get.wrappers(component)
             wrappers.extend(wrappers_)
     for wrapper in wrappers:
         if not wrapper.tag:
             continue
         is_reapplied_wrapper = False
         for word in abjad.Tag(wrapper.tag):
             if f"REAPPLIED_{stem}" in word or f"DEFAULT_{stem}" in word:
                 is_reapplied_wrapper = True
         if not is_reapplied_wrapper:
             continue
         reapplied_wrappers.append(wrapper)
         if isinstance(wrapper.indicator, prototype):
             reapplied_indicators.append(wrapper.indicator)
         abjad.detach(wrapper, wrapper.component)
     if reapplied_wrappers:
         count = len(reapplied_indicators)
         if count != 1:
             for reapplied_wrapper in reapplied_wrappers:
                 print(reapplied_wrapper)
             counter = abjad.String("indicator").pluralize(count)
             message = f"found {count} reapplied {counter};"
             message += " expecting 1.\n\n"
             raise Exception(message)
         return reapplied_indicators[0]
コード例 #18
0
ファイル: __make_material_pdf__.py プロジェクト: gsy/gmajor
        material = getattr(definition, directory.name)
    except ImportError:
        traceback.print_exc()
        sys.exit(1)

    try:
        with abjad.Timer() as timer:
            if getattr(definition, '__illustrate__', None):
                __illustrate__ = getattr(definition, '__illustrate__')
                lilypond_file = __illustrate__(material)
            elif hasattr(material, '__illustrate__'):
                lilypond_file = material.__illustrate__()
            else:
                print(f'No illustrate method ...')
        count = int(timer.elapsed_time)
        counter = abjad.String('second').pluralize(count)
        message = f'Abjad runtime {count} {counter} ...'
        print(message)
    except:
        traceback.print_exc()
        sys.exit(1)

    if lilypond_file is None:
        sys.exit(0)

    try:
        pdf = directory('illustration.pdf')
        with abjad.Timer() as timer:
            abjad.persist(lilypond_file).as_pdf(pdf, strict=89)
        count = int(timer.elapsed_time)
        counter = abjad.String('second').pluralize(count)