예제 #1
0
def output_sequence_ly(sequence):
    notes = []
    for pitch in sequence:
        duration = abjad.Duration(1, 4)
        note = abjad.Note(pitch, duration)
        notes.append(note)

    staff = abjad.Staff(notes)
    score = abjad.Score([staff])
    lilypond_file = abjad.LilyPondFile.new(score,
                                           global_staff_size=20,
                                           default_paper_size=('letter',
                                                               'portrait'))
    lilypond_file.header_block.title = abjad.Markup(
        "Dissonant Counterpoint Pitch Sequence")
    #abjad.show(staff, pdf_file_path="dca_ps.pdf")

    pdf_file = "imgs/dca_ps.pdf"
    png_file1 = "imgs/dca_ps.png"
    png_file2 = "imgs/dca_ps0.png"
    abjad.persist(score).as_pdf(pdf_file)
    image = convert_image.get_abjad_output(pdf_file,
                                           png_file1,
                                           multiple_pages=True)
    display(Image(png_file2))
예제 #2
0
    def _save_lilypond_file_as_svg(self, lilypond_file):
        import abjad
        from sasha import sasha_configuration

        output_filepath = self._build_path()
        output_directory, output_filename = os.path.split(output_filepath)
        if not os.path.exists(output_directory):
            os.makedirs(output_directory)

        lilypond_path = self._path_to_lilypond_path(output_filepath)
        lilypond_directory, _ = os.path.split(lilypond_path)
        if not os.path.exists(lilypond_directory):
            os.makedirs(lilypond_directory)

        suffixless_filepath, _ = os.path.splitext(output_filepath)
        preview_filepath = '{}.preview.{}'.format(
            suffixless_filepath, self.file_suffix)

        abjad.persist(lilypond_file).as_ly(lilypond_path)
        command = '{} -dbackend=svg -dpreview -dno-point-and-click -o {} {}'
        command = command.format(
            sasha_configuration.get_binary('lilypond'),
            suffixless_filepath,
            lilypond_path,
            )
        out, err = Executable()._exec(command)
        if out or err:
            print(out)
            print(err)

        os.remove(output_filepath)
        os.rename(preview_filepath, output_filepath)
예제 #3
0
def output_clangs_ly(clangs):
    notes = []
    for clang in clangs:
        for pitch in clang:
            if pitch == "rest":
                notes.append(abjad.Rest('r8'))
            else:
                duration = abjad.Duration(1, 8)
                note = abjad.Note(pitch, duration)
                notes.append(note)

    staff = abjad.Staff(notes)

    score = abjad.Score([staff])
    lilypond_file = abjad.LilyPondFile.new(score,
                                           global_staff_size=20,
                                           default_paper_size=('letter',
                                                               'portrait'))
    lilypond_file.header_block.title = abjad.Markup(
        "Dissonant Counterpoint Example Piece")
    #abjad.show(staff, pdf_file_path="dca_ps.pdf")

    pdf_file = "imgs/dca_piece.pdf"
    png_file = "imgs/dca_piece.png"
    png_stem = png_file[:-4]
    abjad.persist(score).as_pdf(pdf_file)
    total_pngs = convert_image.get_abjad_output(pdf_file,
                                                png_file,
                                                multiple_pages=True)
    for i in range(total_pngs):
        png_file = png_stem + str(i) + ".png"
        print(png_file)
        display(Image(png_file))
예제 #4
0
    def converteToPdf(self, filename):
        # this function will use special lib ans converte markuped array to really Notes notation, then it saves it
        # as pdf
        for note in self.data:
            norm, time = self.abj_duration(note[1])
            if norm:
                if note[0] < 0:
                    self.notes.append(
                        abjad.Rest(
                            abjad.Note(note[0] - BASE_NOTE,
                                       abjad.Duration(time, MIN_NOTE))))
                else:
                    self.notes.append(
                        abjad.Note(note[0] - BASE_NOTE,
                                   abjad.Duration(time, MIN_NOTE)))
            else:
                # beg_tie = len(notes)
                if note[0] < 0:
                    for t in time:
                        self.notes.append(
                            abjad.Rest(
                                abjad.Note(note[0] - BASE_NOTE,
                                           abjad.Duration(t, MIN_NOTE))))
                        # abjad.attach(tie,notes[len(notes)-1])

                else:
                    tie = abjad.Tie()
                    for t in time:
                        self.notes.append(
                            abjad.Note(note[0] - BASE_NOTE,
                                       abjad.Duration(t, MIN_NOTE)))
                        abjad.attach(tie, self.notes[len(self.notes) - 1])
                    del tie
        abjad.persist(self.notes).as_pdf(''.join([PATH_TO_PDF, filename]))
        return filename
예제 #5
0
def keep_ly(data, data_name):
    path = os.path.join(
        os.environ.get('ARCHIPEL'), 
        'etc', 
        'ly', 
        data_name + '.ly',
        )
    abjad.persist(data).as_ly(path)
예제 #6
0
def keep_pdf(data, data_name):
    path = os.path.join(
        os.environ.get('ARCHIPEL'), 
        'etc', 
        'pdf', 
        data_name + '.pdf',
        )
    abjad.persist(data).as_pdf(path)
    os.system('open %s' % path)
def test_systemtools_PersistenceManager_as_ly_02():
    r'''Agent abjad.persists LilyPond file when LilyPond file already exists.
    '''

    note = abjad.Note("c'4")
    with abjad.FilesystemState(remove=[ly_path]):
        result = abjad.persist(note).as_ly(ly_path)
        assert isinstance(result, tuple)
        assert os.path.isfile(ly_path)
        abjad.persist(note).as_ly(ly_path)
        assert os.path.isfile(ly_path)
예제 #8
0
def test_systemtools_PersistenceManager_as_pdf_02():
    r'''Agent abjad.persists PDF file when equivalent PDF file already exists.
    '''

    note = abjad.Note("c'4")
    with abjad.FilesystemState(remove=paths):
        result = abjad.persist(note).as_pdf(pdf_path)
        assert os.path.isfile(pdf_path)
        assert isinstance(result, tuple)
        os.remove(ly_path)
        abjad.persist(note).as_pdf(pdf_path)
        assert os.path.isfile(pdf_path)
예제 #9
0
def test_PersistenceManager_as_ly_02():
    """
    Agent abjad.persists LilyPond file when LilyPond file already exists.
    """

    note = abjad.Note("c'4")
    with abjad.FilesystemState(remove=[ly_path]):
        result = abjad.persist(note).as_ly(ly_path)
        assert isinstance(result, tuple)
        assert os.path.isfile(ly_path)
        abjad.persist(note).as_ly(ly_path)
        assert os.path.isfile(ly_path)
예제 #10
0
def test_PersistenceManager_as_pdf_02():
    """
    Persists PDF file when equivalent PDF file already exists.
    """

    note = abjad.Note("c'4")
    with abjad.FilesystemState(remove=paths):
        result = abjad.persist(note).as_pdf(pdf_path)
        assert os.path.isfile(pdf_path)
        assert isinstance(result, tuple)
        os.remove(ly_path)
        abjad.persist(note).as_pdf(pdf_path)
        assert os.path.isfile(pdf_path)
예제 #11
0
def test_IOManager_save_last_ly_as_01():

    abjad_output_directory = abjad.abjad_configuration.abjad_output_directory
    lilypond_files = [
        x for x in os.listdir(abjad_output_directory) if x.endswith(".ly")
    ]
    if not lilypond_files:
        note = abjad.Note("c'4")
        abjad.persist(note).as_ly()

    abjad.IOManager.save_last_ly_as("tmp_foo.ly")
    assert os.path.exists("tmp_foo.ly")

    os.remove("tmp_foo.ly")
    assert not os.path.exists("tmp_foo.ly")
예제 #12
0
 def __call__(self, argument):
     if not hasattr(argument, "__illustrate__"):
         raise TypeError("Cannot illustrate {!r}".format(type(argument)))
     if not abjad.IOManager.find_executable("lilypond"):
         raise RuntimeError("Cannot find LilyPond.")
     if not abjad.IOManager.find_executable("convert"):
         raise RuntimeError("Cannot find ImageMagick.")
     with tempfile.TemporaryDirectory() as temporary_directory:
         temporary_directory = pathlib.Path(temporary_directory)
         temporary_file_path = temporary_directory / "output.png"
         png_paths, _, _, success = abjad.persist(argument).as_png(
             str(temporary_file_path))
         pngs = []
         if not success:
             raise RuntimeError("Rendering failed")
         if not png_paths:
             raise FileNotFoundError("LilyPond PNG output not found.")
         for png_path in png_paths:
             exit_code = self._run_imagemagick(png_path)
             if exit_code:
                 message = "ImageMagick failed: {}".format(exit_code)
                 raise RuntimeError(message)
             with open(str(png_path), "rb") as file_pointer:
                 file_contents = file_pointer.read()
                 pngs.append(file_contents)
     for png in pngs:
         IPython.core.display.display_png(png, raw=True)
예제 #13
0
def play(argument):
    r"""
    Plays ``argument``.

    ..  container:: example

        >>> note = abjad.Note("c'4")
        >>> abjad.play(note) # doctest: +SKIP

    Makes MIDI file.

    Appends ``.mid`` filename extension under Windows.

    Appends ``.midi`` filename extension under other operating systems.

    Opens MIDI file.

    Returns none.
    """
    import abjad
    from abjad import abjad_configuration
    assert hasattr(argument, '__illustrate__')
    result = abjad.persist(argument).as_midi()
    midi_file_path, abjad_formatting_time, lilypond_rendering_time = result
    midi_player = abjad_configuration['midi_player']
    abjad.IOManager.open_file(midi_file_path, midi_player)
예제 #14
0
def test_PersistenceManager_as_pdf_01():
    """
    Persists PDF file when no PDF file exists.
    """

    note = abjad.Note("c'4")
    with abjad.FilesystemState(remove=paths):
        result = abjad.persist(note).as_pdf(pdf_path)
        assert os.path.isfile(pdf_path)
        assert isinstance(result, tuple)
예제 #15
0
def test_PersistenceManager_as_pdf_01():
    """
    Persists PDF file when no PDF file exists.
    """

    note = abjad.Note("c'4")
    with abjad.FilesystemState(remove=paths):
        result = abjad.persist(note).as_pdf(pdf_path)
        assert os.path.isfile(pdf_path)
        assert isinstance(result, tuple)
def test_PersistenceManager_as_ly_01():
    """
    Agent abjad.persists LilyPond file when no LilyPond file exists.
    """

    note = abjad.Note("c'4")
    with abjad.FilesystemState(remove=[ly_path]):
        result = abjad.persist(note).as_ly(ly_path)
        assert os.path.isfile(ly_path)
        assert isinstance(result, tuple)
예제 #17
0
 def render(self, score, pdf=False, midi=False, render_all=True, filename=None, preview=False):
   """TODO: experiment with as_module...! http://abjad.mbrsi.org/api/tools/agenttools/PersistenceAgent.html"""
   self.filename=filename
   self.file_lily = self.filename_new("ly", filename=self.filename)
   if self._verbose:
     self.log_info("rendering {}".format(self.file_lily));
   if pdf or render_all:
     self.file_pdf = self.filename_new("pdf", filename=self.filename);
     if self._verbose: 
       self.log_info("rendering {}".format(self.file_pdf));
     abjad.persist(score).as_pdf(self.file_pdf);
     if preview:
         try: 
           call([self.pdf_viewer, self.file_pdf]);
         except Exception as e:
           self.log_warn("Couldn't call {}".format(self.pdf_viewer));
   if midi or render_all:
     self.file_midi = self.filename_new("midi", filename=filename);
     if self._verbose:
       self.log_info("rendering {}".format(self.file_midi));
     abjad.persist(score).as_midi(self.file_midi);
예제 #18
0
 def _render_illustration(self):
     score_file = self._lilypond_file
     directory = self.current_directory
     pdf_path = f"{directory}/illustration.pdf"
     ly_path = f"{directory}/illustration.ly"
     path = pathlib.Path("illustration.pdf")
     if path.exists():
         print(f"Removing {pdf_path} ...")
         path.unlink()
     print(f"Persisting {pdf_path} ...")
     result = abjad.persist(score_file).as_pdf(pdf_path, strict=79)
     if path.exists():
         print(f"Opening {pdf_path} ...")
         os.system(f"open {pdf_path}")
예제 #19
0
 def __call__(self, argument):
     if not abjad.IOManager.find_executable("lilypond"):
         raise RuntimeError("Cannot find LilyPond.")
     if not abjad.IOManager.find_executable("convert"):
         raise RuntimeError("Cannot find ImageMagick.")
     if not hasattr(argument, "__illustrate__"):
         raise TypeError("Cannot play {!r}".format(type(argument)))
     has_vorbis = self._check_for_vorbis()
     with tempfile.TemporaryDirectory() as temporary_directory:
         temporary_directory = pathlib.Path(temporary_directory)
         midi_file_path = temporary_directory / "out.midi"
         midi_file_path, _, _, success = abjad.persist(argument).as_midi(
             str(midi_file_path))
         if not success:
             raise RuntimeError("Rendering failed")
         if has_vorbis:
             audio_file_path = temporary_directory / "out.ogg"
         else:
             audio_file_path = temporary_directory / "out.aif"
         encoded_audio = self._get_audio_as_base64(midi_file_path,
                                                   audio_file_path,
                                                   has_vorbis)
     if encoded_audio is not None:
         self._display_audio_tag(encoded_audio, has_vorbis)
예제 #20
0
import abjad
import abjadext.rmakers
import os
from trio_score import materials
from trio_score.tools import SegmentMaker


segment_maker = SegmentMaker(
    time_signatures=[(3, 4), (4, 4), (7, 8), (4, 4)] * 2,
    cello_pitches=materials.my_pitches,
    cello_rhythm_maker=materials.my_fast_rhythm_maker,
    cello_seed=1,
    viola_pitches=materials.my_pitches.rotate(2, stravinsky=True),
    viola_rhythm_maker=materials.my_slow_rhythm_maker,
    viola_seed=1,
    violin_pitches=materials.my_pitches.retrograde().transpose(12),
    violin_rhythm_maker=abjadext.rmakers.EvenDivisionRhythmMaker(
        denominators=[16],
        ),
    )


if __name__ == '__main__':
    lilypond_file, _ = segment_maker()
    illustration_path = os.path.join(
        os.path.dirname(__file__),
        'illustration.pdf',
        )
    abjad.persist(lilypond_file).as_pdf(illustration_path)
    abjad.system.IOManager.open_file(illustration_path)
예제 #21
0
            [
                'surge',
                'segments',
                segment_name,
                'make_part'
            ]
        )
        module = importlib.import_module(module_path)
        # make score
        print("Making segment ...")
        segment = module.make_part(part_name, number_of_stages, ruler)

        # create LilyPond file
        with abjad.systemtools.Timer() as timer:
            print("Making Lilypond file ... ")
            abjad.persist(segment).as_ly(part_ly_path)
            seconds = int(timer.elapsed_time)
            time = str(datetime.timedelta(seconds=seconds))
            print(time)
            print("...Done")

        # create PDF
        with abjad.systemtools.Timer() as timer:
            print("Running Lilypond ... ")
            abjad.systemtools.IOManager.run_lilypond(part_ly_path)
            seconds = int(timer.elapsed_time)
            time = str(datetime.timedelta(seconds=seconds))
            print(time)
            print("...Done")

        # print time elapsed
예제 #22
0
abjad.SegmentMaker.comment_measure_numbers(score)
time_2 = time.time()
###################
directory = pathlib.Path(__file__).parent
print("directory")
print(directory)
pdf_path = f"{directory}/illustration.pdf"
print("path")
print(pdf_path)
path = pathlib.Path("illustration.pdf")
if path.exists():
    print(f"Removing {pdf_path} ...")
    path.unlink()
time_3 = time.time()
print(f"Persisting {pdf_path} ...")
result = abjad.persist(score_file).as_pdf(pdf_path)  # or ly
print(result[0])
print(result[1])
print(result[2])
success = result[3]
if success is False:
    print("LilyPond failed!")
time_4 = time.time()
abjad_time = time_4 - time_3
print(f"Total time: {abjad_time} seconds")
if path.exists():
    print(f"Opening {pdf_path} ...")
    os.system(f"open {pdf_path}")
score_lines = open(f"{directory}/illustration.ly").readlines()
build_path = (directory / ".." / ".." / "Build/score").resolve()
open(f"{build_path}/Segment_I.ly", "w").writelines(score_lines[15:-1])
예제 #23
0
                )
        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)

    try:
        segment = ide.Path(__file__).parent
        segment.write_metadata_py(maker.metadata)
    except:
        traceback.print_exc()
        sys.exit(1)

    try:
        segment = ide.Path(__file__).parent
        midi = segment / 'segment.midi'
        with abjad.Timer() as timer:
            abjad.persist(lilypond_file).as_midi(midi, remove_ly=True)
        count = int(timer.elapsed_time)
        counter = abjad.String('second').pluralize(count)
        message = f'LilyPond runtime {{count}} {{counter}} ...'
        print(message)
    except:
        traceback.print_exc()
        sys.exit(1)

    sys.exit(0)
예제 #24
0
# -*- encoding: utf-8 -*-
import os
import abjad
import abjadext.rmakers

my_droning_rhythm_maker = abjadext.rmakers.NoteRhythmMaker(
    tie_specifier=abjadext.rmakers.TieSpecifier(
        tie_across_divisions=[True, False], ), )

if __name__ == '__main__':
    illustration_path = os.path.join(
        os.path.dirname(__file__),
        'illustration.pdf',
    )
    abjad.persist(my_droning_rhythm_maker).as_pdf(illustration_path)
    abjad.system.IOManager.open_file(illustration_path)
        'surge',
        'segments',
        segment_name,
        'make_score'
    ]
)
module = importlib.import_module(module_path)

# make score
print("Making segment ...")
segment = module.make_conductor_part(number_of_stages)

# create LilyPond file
with abjad.systemtools.Timer() as timer:
    print("Making Lilypond file ... ")
    abjad.persist(segment).as_ly(score_ly_path)
    seconds = int(timer.elapsed_time)
    time = str(datetime.timedelta(seconds=seconds))
    print(time)
    print("...Done")

# create PDF
with abjad.systemtools.Timer() as timer:
    print("Running Lilypond ... ")
    abjad.systemtools.IOManager.run_lilypond(score_ly_path)
    seconds = int(timer.elapsed_time)
    time = str(datetime.timedelta(seconds=seconds))
    print(time)
    print("...Done")

# print time elapsed
예제 #26
0
                __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)
        message = f'LilyPond runtime {count} {counter} ...'
        print(message)
    except:
        traceback.print_exc()
        sys.exit(1)

    sys.exit(0)
예제 #27
0
# -*- encoding: utf-8 -*-
import os
import abjad


my_slow_rhythm_maker = abjad.rhythmmakertools.EvenDivisionRhythmMaker(
    denominators=[4, 8, 2],
    extra_counts_per_division=[0, 1],
    tie_specifier=abjad.rhythmmakertools.TieSpecifier(
        tie_across_divisions=True,
        ),
    )


if __name__ == '__main__':
    illustration_path = os.path.join(
        os.path.dirname(__file__),
        'illustration.pdf',
        )
    abjad.persist(my_slow_rhythm_maker).as_pdf(illustration_path)
    abjad.systemtools.IOManager.open_file(illustration_path)
예제 #28
0
     total_time = int(timer.elapsed_time)
     identifier = abjad.stringtools.pluralize('second', total_time)
     message = message.format(total_time, identifier)
     print(message)
 try:
     current_directory = os.path.dirname(__file__)
     ly_path = os.path.join(
         current_directory,
         'illustration.ly',
         )
     pdf_path = os.path.join(
         current_directory,
         'illustration.pdf',
         )
     output_paths = (ly_path, pdf_path)
     with abjad.systemtools.Timer() as timer:
         abjad.persist(lilypond_file).as_pdf(pdf_path)
     message = 'LilyPond runtime {} {} ...'
     total_time = int(timer.elapsed_time)
     identifier = abjad.stringtools.pluralize('second', total_time)
     message = message.format(total_time, identifier)
     print(message)
     for output_path in output_paths:
         message = 'writing {} ...'
         path = ide.tools.idetools.AbjadIDE._trim_path(output_path)
         message = message.format(path)
         print(message)
 except:
     traceback.print_exc()
     sys.exit(1)
 sys.exit(0)
예제 #29
0
def show(argument, return_timing=False, **keywords):
    r"""
    Shows ``argument``.

    ..  container:: example

        Shows note:

        >>> note = abjad.Note("c'4")
        >>> abjad.show(note) # doctest: +SKIP

        ..  docs::

            >>> abjad.f(note)
            c'4

    ..  container:: example

        Shows staff:

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

        ..  docs::

            >>> abjad.f(staff)
            \new Staff
            {
                c'4
                d'4
                e'4
                f'4
            }

    Makes LilyPond input files and output PDF.

    Writes LilyPond input file and output PDF to Abjad output directory.

    Opens output PDF.

    Returns none when ``return_timing`` is false.

    Returns pair of ``abjad_formatting_time`` and ``lilypond_rendering_time``
    when ``return_timing`` is true.
    """
    import abjad

    if not hasattr(argument, "__illustrate__"):
        message = "must have __illustrate__ method: {!r}."
        message = message.format(argument)
        raise Exception(message)
    result = abjad.persist(argument).as_pdf(**keywords)
    pdf_file_path = result[0]
    abjad_formatting_time = result[1]
    lilypond_rendering_time = result[2]
    success = result[3]
    if success:
        abjad.IOManager.open_file(pdf_file_path)
    else:
        with open(abjad.abjad_configuration.lilypond_log_file_path, "r") as fp:
            print(fp.read())
    if return_timing:
        return abjad_formatting_time, lilypond_rendering_time
예제 #30
0
        if getattr(item, "name", None) in block_names:
            lilypond_file.items.remove(item)
    block = abjad.Block(name="midi")
    lilypond_file.items.append(block)
    for item in lilypond_file.items[:]:
        if getattr(item, "name", None) == "header":
            lilypond_file.items.remove(item)
    abjad.f(lilypond_file)

    try:
        segment_directory = ide.Path(__file__).parent
        score_directory = segment_directory.contents
        stem = f"{{score_directory.name}}-{{segment_directory.name}}-clicktrack"
        midi = stem + ".midi"
    except:
        traceback.print_exc()
        sys.exit(1)

    try:
        with abjad.Timer() as timer:
            abjad.persist(lilypond_file).as_midi(midi, remove_ly=True)
        count = int(timer.elapsed_time)
        counter = abjad.String("second").pluralize(count)
        message = f"LilyPond runtime {{count}} {{counter}} ..."
        print(message)
    except:
        traceback.print_exc()
        sys.exit(1)

    sys.exit(0)
예제 #31
0
selection = stack(time_signatures_two)

skips_two = [abjad.Skip((1, 1)) for signature_two in time_signatures_two]

for skip_two, signature_two in zip(skips_two, time_signatures_two):
    skip.multiplier = abjad.Multiplier(signature.pair)
    abjad.attach(signature_two, skip_two)

ts_staff_2 = abjad.Staff(skips_two,
                         lilypond_type="TimeSignatureContext",
                         name="globalcontext")

staff_two = abjad.Staff(selection, name="staffname")

pitches_two = [
    abjad.NumberedPitch(x) + (2.5)
    for x in range(len(abjad.select(staff).logical_ties(pitched=True)))
]
zipped_two = zip(pitches_two,
                 abjad.select(staff_two).logical_ties(pitched=True))
for pitch_two, tie_two in zipped_two:
    for leaf_two in abjad.select(tie).leaves():
        leaf_two.written_pitch = pitch_two

scoretwo = abjad.Score([ts_staff_2, staff_two])

file = abjad.LilyPondFile.new(
    score, includes=[r"\Users\Matthew\mason\mason\lilypond\stylesheet.ily"])
abjad.persist(file).as_pdf(
    r"\Users\Matthew\mason\mason\playground\parabolicpitches.pdf")
예제 #32
0
# -*- encoding: utf-8 -*-
import os
import abjad


my_pitches = abjad.pitchtools.PitchSegment(
    [
        -5, 0, 1, 4, -5, -4, 2, 3, 0, 3, 0, 3,
        ],
    )


if __name__ == '__main__':
    illustration_path = os.path.join(
        os.path.dirname(__file__),
        'illustration.pdf',
        )
    abjad.persist(my_pitches).as_pdf(illustration_path)
    abjad.systemtools.IOManager.open_file(illustration_path)
예제 #33
0
# -*- encoding: utf-8 -*-
import os
import abjad
import abjadext.rmakers


my_droning_rhythm_maker = abjadext.rmakers.NoteRhythmMaker(
    tie_specifier=abjadext.rmakers.TieSpecifier(
        tie_across_divisions=[True, False],
        ),
    )


if __name__ == '__main__':
    illustration_path = os.path.join(
        os.path.dirname(__file__),
        'illustration.pdf',
        )
    abjad.persist(my_droning_rhythm_maker).as_pdf(illustration_path)
    abjad.system.IOManager.open_file(illustration_path)
예제 #34
0
        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:
                first_page_number, _, _ = result
                line = r"\paper {{ first-page-number = #"
                line += str(first_page_number)
                line += " }}"
                line = abjad.LilyPondFormatManager.tag(
                    [line], tag="__make_segment_pdf__")[0]
                lilypond_file.items.insert(0, line)
        result = abjad.persist(lilypond_file).as_ly(illustration_ly, strict=79)
        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)

    try:
        if "Global_Skips" in lilypond_file:
            context = lilypond_file["Global_Skips"]
            measure_count = len(context)
            counter = abjad.String("measure").pluralize(measure_count)
예제 #35
0
            os.remove(score_ly_path)
        if os.access(score_pdf_path, os.F_OK):
            os.remove(score_pdf_path)

# import segment module
module_path = ".".join(['surge', 'segments', segment_name, 'make_score'])
module = importlib.import_module(module_path)

# make score
print("Making segment ...")
segment = module.make_conductor_part(number_of_stages)

# create LilyPond file
with abjad.systemtools.Timer() as timer:
    print("Making Lilypond file ... ")
    abjad.persist(segment).as_ly(score_ly_path)
    seconds = int(timer.elapsed_time)
    time = str(datetime.timedelta(seconds=seconds))
    print(time)
    print("...Done")

# create PDF
with abjad.systemtools.Timer() as timer:
    print("Running Lilypond ... ")
    abjad.systemtools.IOManager.run_lilypond(score_ly_path)
    seconds = int(timer.elapsed_time)
    time = str(datetime.timedelta(seconds=seconds))
    print(time)
    print("...Done")

# print time elapsed
예제 #36
0
                __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)
        message = f'LilyPond runtime {count} {counter} ...'
        print(message)
    except:
        traceback.print_exc()
        sys.exit(1)

    sys.exit(0)
예제 #37
0
    includes=['first_stylesheet.ily'],
)
# Comment measure numbers
abjad.SegmentMaker.comment_measure_numbers(score)
###################

#print(format(score_file))
directory = '/Users/evansdsg2/spectralism_paper/harmony'
pdf_path = f'{directory}/chord_paper_edition.pdf'
path = pathlib.Path('chord_paper_edition.pdf')
if path.exists():
    print(f'Removing {pdf_path} ...')
    path.unlink()
time_1 = time.time()
print(f'Persisting {pdf_path} ...')
result = abjad.persist(score_file).as_pdf(pdf_path)
print(result[0])
print(result[1])
print(result[2])
success = result[3]
if success is False:
    print('LilyPond failed!')
time_2 = time.time()
total_time = time_2 - time_1
print(f'Total time: {total_time} seconds')
if path.exists():
    print(f'Opening {pdf_path} ...')
    os.system(f'open {pdf_path}')

# abjad.show(score)
예제 #38
0
파일: test.py 프로젝트: gsy/gmajor
    abjad.setting(measure).auto_beaming = False
    for beam_start, beam_end in beams:
        beam = abjad.Beam()
        abjad.attach(beam, measure[beam_start:beam_end])

    measures.append(measure)

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

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

for x in abjad.persist(staff).as_midi():
    x
    print(x)

# abjad.show(staff)
output = abjad.persist(staff).as_ly()
out_file = output[0]
command = "lilypond -dpreview -dbackend=svg {}".format(out_file)
print(command)

# duration = abjad.Duration(1, 4)
# rests = [abjad.Rest(abjad.Duration(1, 4)), abjad.Rest(abjad.Duration(2, 4))]

# notes = [
#     abjad.Note(16, abjad.Duration(1, 8)),
#     abjad.Note("e4", abjad.Duration(1, 8)),
예제 #39
0
            os.remove(part_ly_path)
        if os.access(part_pdf_path, os.F_OK):
            os.remove(part_pdf_path)

        # import segment module
        module_path = ".".join(
            ['surge', 'segments', segment_name, 'make_part'])
        module = importlib.import_module(module_path)
        # make score
        print("Making segment ...")
        segment = module.make_part(part_name, number_of_stages, ruler)

        # create LilyPond file
        with abjad.systemtools.Timer() as timer:
            print("Making Lilypond file ... ")
            abjad.persist(segment).as_ly(part_ly_path)
            seconds = int(timer.elapsed_time)
            time = str(datetime.timedelta(seconds=seconds))
            print(time)
            print("...Done")

        # create PDF
        with abjad.systemtools.Timer() as timer:
            print("Running Lilypond ... ")
            abjad.systemtools.IOManager.run_lilypond(part_ly_path)
            seconds = int(timer.elapsed_time)
            time = str(datetime.timedelta(seconds=seconds))
            print(time)
            print("...Done")

        # print time elapsed
예제 #40
0
                __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)
        message = f'LilyPond runtime {count} {counter} ...'
        print(message)
    except:
        traceback.print_exc()
        sys.exit(1)

    sys.exit(0)
예제 #41
0
        identifier = stringtools.pluralize('second', total_time)
        message = message.format(total_time, identifier)
        print(message)
    try:
        current_directory = os.path.dirname(__file__)
        ly_path = os.path.join(
            current_directory,
            'illustration.ly',
            )
        pdf_path = os.path.join(
            current_directory,
            'illustration.pdf',
            )
        output_paths = (ly_path, pdf_path)
        with systemtools.Timer() as timer:
            persist(lilypond_file).as_pdf(pdf_path)
        message = 'LilyPond runtime {} {} ...'
        total_time = int(timer.elapsed_time)
        identifier = stringtools.pluralize('second', total_time)
        message = message.format(total_time, identifier)
        print(message)
        for output_path in output_paths:
            message = 'writing {} ...'
            path = idetools.AbjadIDE._trim_path(output_path)
            message = message.format(path)
            print(message)
    except:
        traceback.print_exc()
        sys.exit(1)
    sys.exit(0)
예제 #42
0
# -*- encoding: utf-8 -*-
import os
import abjad
import abjadext.rmakers


my_slow_rhythm_maker = abjadext.rmakers.EvenDivisionRhythmMaker(
    denominators=[4, 8, 2],
    extra_counts_per_division=[0, 1],
    tie_specifier=abjadext.rmakers.TieSpecifier(
        tie_across_divisions=True,
        ),
    )


if __name__ == '__main__':
    illustration_path = os.path.join(
        os.path.dirname(__file__),
        'illustration.pdf',
        )
    abjad.persist(my_slow_rhythm_maker).as_pdf(illustration_path)
    abjad.system.IOManager.open_file(illustration_path)
예제 #43
0
import abjad

staff = abjad.Staff("c'4 d'4 e'4 d'4 f'4")
manager = abjad.persist(staff)
print(manager)
for x in abjad.persist(staff).as_midi():
    x
    print(x)
예제 #44
0
selection = selection1 + selection1_3 + selection1_6 + selection1_9 + selection2 + selection3 + selection4 + selection5 + selection6 + selection7 + selection8 + selection9
staff = abjad.Staff(selection, name="staffname")
abjad.attach(abjad.Clef("bass"), abjad.select(staff).leaf(0))

pitches = []
ties = abjad.select(staff).logical_ties(pitched=True)
for i in range(len(ties)):
    multiplied_val = i * 0.5
    sin_val = math.sin((2 * math.sin(i * math.sin(1.1))))
    added_val = multiplied_val + sin_val
    if 16 < added_val:
        added_val -= 10
    if 20 < i:
        added_val -= 5
    if 30 < i:
        added_val = math.sin(added_val * math.sin(i * -0.5)) + (0.1 * i)
    pitch = abjad.NumberedPitch(added_val)
    pitch -= 16
    pitches.append(pitch)

zipped = zip(pitches, abjad.select(staff).logical_ties(pitched=True))
for pitch, tie in zipped:
    for leaf in abjad.select(tie).leaves():
        leaf.written_pitch = pitch
score = abjad.Score([ts_staff, staff])

file = abjad.LilyPondFile.new(
    score, includes=[r"\Users\Matthew\mason\mason\lilypond\stylesheet.ily"])
abjad.persist(file).as_pdf(
    r"\Users\Matthew\mason\mason\playground\crashcourse.pdf")
예제 #45
0
                __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)
        message = f"LilyPond runtime {count} {counter} ..."
        print(message)
    except:
        traceback.print_exc()
        sys.exit(1)

    sys.exit(0)
예제 #46
0
        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)

    try:
        if 'GlobalSkips' in lilypond_file:
            context = lilypond_file['GlobalSkips']
            measure_count = len(context)
            counter = abjad.String('measure').pluralize(measure_count)
예제 #47
0
# laisses vibrer
laissez_vibrer = abjad.LaissezVibrer()
abjad.attach(laissez_vibrer, chord_zero_electronics)

# tempo mark
mark = abjad.MetronomeMark(None, None, "Statico")
abjad.attach(mark, chord_zero_electronics)

# fermata
abjad.attach(abjad.Fermata("verylongfermata"), chord_zero_electronics)

# remove includes to collect segments
includes = ['../../stylesheets/stylesheet.ily']

segment_maker = SegmentMaker(
    time_signatures=time_signatures,
    chords_voice_one_elec=chord_zero_electronics,
    initial_rest_voice_one=rest_organ,
    initial_rest_voice_four=rest_organ_voice_four,
    includes=includes,
)

if __name__ == '__main__':
    lilypond_file, _ = segment_maker()
    illustration_path = os.path.join(
        os.path.dirname(__file__),
        'Illustration.pdf',
    )
    abjad.persist(lilypond_file).as_pdf(illustration_path)
    abjad.system.IOManager.open_file(illustration_path)
예제 #48
0
state2 = stack2.state
selection3 = stack([time_signatures[2]], previous_state=state1)
selection4 = stack2(time_signatures[3:], previous_state=state2)

selection = selection1 + selection2 + selection3 + selection4
staff = abjad.Staff(selection, name="staffname")
abjad.attach(abjad.Clef("bass"), abjad.select(staff).leaf(0))

pitches = []
ties = abjad.select(staff).logical_ties(pitched=True)
for eye in range(len(ties)):
    multiplied_val = eye * 0.25
    sin_val = math.sin(eye)
    added_val = multiplied_val + sin_val
    if 3 < added_val:
        added_val -= 4.5
    pitch = abjad.NumberedPitch(added_val)
    pitch -= 12
    pitches.append(pitch)

zipped = zip(pitches, abjad.select(staff).logical_ties(pitched=True))
for pitch, tie in zipped:
    for leaf in abjad.select(tie).leaves():
        leaf.written_pitch = pitch
score = abjad.Score([ts_staff, staff])

file = abjad.LilyPondFile.new(
    score, includes=[r"\Users\Matthew\mason\mason\lilypond\stylesheet.ily"])
abjad.persist(file).as_pdf(
    r"\Users\Matthew\mason\mason\playground\july_second.pdf")