ly.musicxml package

Module contents

MusicXML functionality.

This subpackage is created to convert LilyPond text to MusicXML with the help of the tree structure created by ly.music. But it is constructed in such a way that you can use some of the submodules for generic MusicXML creation and manipulation.

ly.musicxml.writer()[source]

Convert LilyPond text to MusicXML

Example:

import ly.musicxml
e = ly.musicxml.writer()
e.parse_text(lilypond_text)
xml = e.musicxml()
xml.write(filename)         # or: xml.tostring()
# xml.tree is the ElementTree xml tree.

Submodules

ly.musicxml.create_musicxml module

Uses xml.etree to create a Music XML document.

Example:

musxml = create_musicxml.CreateMusicXML()
musxml.create_part()
musxml.create_measure(divs=1)
musxml.new_note('C', 4, 'whole', 4)
xml = musxml.musicxml()
xml.write(filename)
class ly.musicxml.create_musicxml.CreateMusicXML[source]

Creates the XML nodes according to the Music XML standard.

add_accidental(alter, caut=False, parenth=False)[source]

Create accidental.

add_articulations()[source]

Common function for creating all types of articulations.

add_backup(duration)[source]
add_barline(bl_type, repeat=None)[source]
add_beam(nr, beam_type)[source]

Add beam.

add_chord()[source]
add_clef(sign, line, nr=0, oct_ch=0)[source]
add_creator(creator, name)[source]

Add creator to score info.

add_direction(pos=u'above')[source]
add_dirwords(words)[source]

Add words in direction, e. g. a tempo mark.

add_div_duration(divdur)[source]

Create new duration

add_divisions(div)[source]
add_dot()[source]

Create a dot

add_duration_type(durtype)[source]

Create new type

add_dynamic_dashes(text)[source]

Add dynamics dashes.

add_dynamic_mark(dyn)[source]

Add specified dynamic mark.

add_dynamic_text(text)[source]

Add dynamic text.

add_dynamic_wedge(wedge_type)[source]

Add dynamic wedge/hairpin.

add_fingering(finger_nr)[source]
add_gliss(linetype, endtype, nr)[source]
add_grace(slash)[source]

Create grace node

add_key(key, mode)[source]
add_lyric(txt, syll, nr, ext=False)[source]

Add lyric element.

add_metron_dir(unit, beats, dots)[source]
add_mordent()[source]
add_named_artic(artic)[source]

Add articulation with specified name.

add_named_notation(notate)[source]

Fermata, etc.

add_notations()[source]
add_octave_shift(plac, octdir, size)[source]

Add octave shift.

add_ornaments()[source]
add_pitch(step, alter, octave)[source]

Create new pitch.

add_prall()[source]
add_rest()[source]

Create rest.

add_rest_w_pos(step, octave)[source]

Create rest with display position.

add_rights(rights)[source]

Add rights to score info.

add_skip(duration, forward=True)[source]
add_slur(nr, sl_type)[source]

Add slur.

add_sound_dir(midi_tempo)[source]
add_staff(staff)[source]
add_staves(staves)[source]
add_technical()[source]
add_tie(tie_type)[source]

Create node tie (used for sound of tie)

add_tied(tie_type)[source]

Create node tied (used for notation of tie)

add_time(timesign)[source]
add_time_modify(fraction)[source]

Create time modification

add_tremolo(trem_type, lines)[source]
add_trill()[source]
add_tuplet_type(nr, ttype, actnr=0, acttype=u'', normnr=0, normtype=u'')[source]

Create tuplet with type attribute

add_turn()[source]
add_unpitched(step, octave)[source]

Create unpitched.

add_voice(voice)[source]
add_wavyline(end_type)[source]
adjust_time_modify(timemod_node, fraction)[source]

Adjust existing time-modification node.

change_div_duration(newdura)[source]

Set new duration when tuplet

create_bar_attr()[source]

Create node attributes

create_measure(**bar_attrs)[source]

Create new measure

create_new_node(parentnode, nodename, txt)[source]

The Music XML language is extensive. This function can be used to create a non basic node not covered elsewhere in this script.

TODO: add attributes

create_note()[source]

Create new note.

create_part(name=u'unnamed', abbr=False, midi=False)[source]

Create a new part

create_partgroup(gr_type, num, name=None, abbr=None, symbol=None)[source]

Create a new part group.

create_score_info(tag, info, attr={})[source]

Create score info.

create_tempo(words, metronome, sound, dots)[source]
create_title(title)[source]

Create score title.

get_time_modify()[source]

Check if time-modification node already exists.

musicxml(prettyprint=True)[source]
new_adv_ornament(ornament, args)[source]

Add more complex ornament.

new_articulation(artic)[source]

Add specified articulation.

new_bar_attr(clef=0, mustime=0, key=None, mode=0, divs=0)[source]

Create all bar attributes set.

new_note(step, octave, durtype, divdur, alter=0, acc_token=0, voice=1, dot=0, chord=0, grace=(0, 0))[source]

Create all nodes needed for a normal note.

new_rest(duration, durtype, pos, dot, voice)[source]

Create all nodes needed for a rest.

new_simple_ornament(ornament)[source]

Add specified ornament.

new_unpitched_note(step, octave, durtype, divdur, voice=1, dot=0, chord=0, grace=(0, 0))[source]

Create all nodes needed for an unpitched note.

tie_note(tie_type)[source]
tuplet_note(fraction, bs, ttype, nr, divs, atyp=u'', ntyp=u'')[source]

Convert current note to tuplet

class ly.musicxml.create_musicxml.MusicXML(tree)[source]

Bases: object

Represent a generated MusicXML tree.

indent(indent=u' ')[source]

Add indent and linebreaks to the created XML tree.

tostring(encoding=u'UTF-8')[source]

Output etree as a XML document.

write(file, encoding=u'UTF-8', doctype=True)[source]

Write XML to a file (file obj or filename).

ly.musicxml.create_musicxml.get_tag_index(node, tag)[source]

Return the (first) index of tag in node.

If tag is not found, -1 is returned.

ly.musicxml.ly2xml_mediator module

The information of the parsed source is organised into an object structure with help of the classes in ly.musicxml.xml_objs.

class ly.musicxml.ly2xml_mediator.Mediator[source]

Help class that acts as mediator between the ly source parser and the XML creating modules.

add_snippet(snippet_name)[source]

Adds snippet to previous barlist. A snippet can be shorter than a full bar, so this can also mean continuing a previous bar.

add_staff_id(staff_id)[source]
add_to_bar(obj)[source]
calc_tupl_den(tfraction, length)[source]

Calculate the tuplet denominator from fraction and duration of tuplet.

change_group_bracket(system_start)[source]
change_to_tuplet(tfraction, ttype, nr, length=None)[source]

Change the current note into a tuplet note.

change_tuplet_type(index, newtype)[source]
check_current_note(rel=False, rest=False, is_unpitched=False)[source]

Perform checks common for all new notes and rests.

check_divs()[source]

The new duration is checked against current divisions

check_duration(rest)[source]

Check the duration for the current note.

check_lyrics(voice_id)[source]

Check the finished lyrics section and merge it into the referenced voice.

check_name(name, nr=1)[source]
check_part()[source]

Adds the latest active section to the part.

check_score()[source]

Check score

If no part were created, place first variable (fallback) as part.

Apply the latest global section.

check_simultan()[source]

Check done after simultanoues (<< >>) section.

check_voices()[source]

Checks active sections. The two latest created are merged. Also checks for empty sections.

check_voices_by_nr()[source]

Used for snippets. Merges all active snippets created after the stored voice number.

chord_end()[source]

Actions when chord is parsed.

clear_chord()[source]
close_group()[source]
copy_barnote_basics(bar_note)[source]

Create a copy of a xml_objs.BarNote.

copy_prev_chord(duration)[source]
create_barline(bl)[source]
create_barnote_from_note(note)[source]

Create a xml_objs.BarNote from ly.music.items.Note.

create_unpitched(unpitched)[source]

Create a xml_objs.Unpitched from ly.music.items.Unpitched.

do_action_onnext(note)[source]

Perform the stored action on the next note.

duration_from_tokens(tokens)[source]

Calculate dots and multibar rests from tokens.

end_gliss(note, line)[source]
get_first_var()[source]
get_part_by_id(pid, partholder=None)[source]
get_var_byname(name)[source]
new_articulation(art_token)[source]

An articulation, fingering, string number, or other symbol.

Grouped as articulations, ornaments, technical and others.

new_bar(fill_prev=True)[source]
new_chord(note, duration=None, rel=False, chord_base=True)[source]
new_chord_grace(slash=0)[source]
new_chordbase(note, duration, rel=False)[source]
new_chordnote(note, rel)[source]
new_clef(clefname)[source]
new_duration_token(token, tokens)[source]
new_dynamics(dynamics)[source]
new_gliss(line=None)[source]
new_grace(slash=0)[source]
new_group()[source]
new_header_assignment(name, value)[source]

Distributing header information.

new_iso_dura(note, rel=False, is_unpitched=False)[source]

Isolated durations in music sequences.

An isolated duration in LilyPond is rendered as a normal note but the pitch information is missing and has to be filled in by some other means, usually by the previous pitch. (RhythmicStaff is an exception since it ignores specified pitches anyway).

new_key(key_name, mode)[source]
new_lyric_nr(num)[source]
new_lyric_section(name, voice_id)[source]
new_lyrics_item(item)[source]
new_lyrics_text(txt)[source]
new_note(note, rel=False, is_unpitched=False)[source]
new_ottava(octdiff)[source]
new_part(pid=None, to_part=None, piano=False)[source]
new_repeat(rep)[source]
new_rest(rest)[source]
new_section(name, glob=False)[source]
new_snippet(name)[source]
new_tempo(unit, dur_tokens, tempo, string)[source]
new_time(num, den, numeric=False)[source]
new_trill_spanner(end=None)[source]
note2rest()[source]

Note used as rest position transformed to rest.

part_not_empty()[source]
revert_voicenr()[source]
scale_rest(multp)[source]

create multiple whole bar rests

sections = None

default and initial values

set_by_property(prprty, value, group=False)[source]

Generic setter for different properties.

set_groupabbr(abbr)[source]
set_groupname(name)[source]
set_octave(relative)[source]

Set octave by getting the octave of an absolute note + 3.

set_ottava(note, plac, octdir, size)[source]
set_partabbr(abbr)[source]
set_partmidi(midi)[source]
set_partname(name)[source]
set_relative(note)[source]
set_slur(nr, slur_type)[source]

Set the slur start or stop for the current note.

set_staffnr(staffnr, staff_id=None)[source]
set_tremolo(trem_type=u'single', duration=0, repeats=0)[source]
set_tuplspan_dur(token=None, tokens=None, fraction=None)[source]

Catch duration set by the tupletSpannerDuration property.

Set the fraction directly or calculate it from tokens.

set_voicenr(command=None, add=False, nr=0, piano=0)[source]
tie_to_next()[source]
unset_tuplspan_dur()[source]

Reset tuplet duration sum and tuplet spanner duration.

ly.musicxml.ly2xml_mediator.artic_token2xml_name(art_token)[source]

From Articulations in ly.music.items. Grouped as articulations, ornaments and others.

To add an articulation look up the name or abbreviation in LilyPond and the corresponding node name in musicXML. Add it to the python dictionary below.

ly.musicxml.ly2xml_mediator.calc_trem_dur(repeats, base_scaling, duration)[source]

Calculate tremolo duration from number of repeats and initial duration.

ly.musicxml.ly2xml_mediator.clefname2clef(clefname)[source]

To add a clef look up the clef name in LilyPond and the corresponding definition in musicXML. Add it to the python dictionary below.

ly.musicxml.ly2xml_mediator.durval2type(durval)[source]

Convert LilyPond duration to MusicXML duration type.

ly.musicxml.ly2xml_mediator.getNoteName(index)[source]
ly.musicxml.ly2xml_mediator.get_fifths(key, mode)[source]
ly.musicxml.ly2xml_mediator.get_group_symbol(lily_sys_start)[source]
ly.musicxml.ly2xml_mediator.get_line_style(style)[source]
ly.musicxml.ly2xml_mediator.get_mult(num, den)[source]
ly.musicxml.ly2xml_mediator.get_voice(c)[source]
ly.musicxml.ly2xml_mediator.get_xml_alter(alter)[source]

Convert alter to the specified format, i e int if it’s int and float otherwise. Also multiply with 2.

ly.musicxml.lymus2musxml module

Using the tree structure from ly.music to initiate the conversion to MusicXML.

Uses functions similar to ly.music.items.Document.iter_music() to iter through the node tree. But information about where a node branch ends is also added. During the iteration the information needed for the conversion is captured.

class ly.musicxml.lymus2musxml.End(node)[source]

Extra class that gives information about the end of Container elements in the node list.

class ly.musicxml.lymus2musxml.ParseSource[source]

creates the XML-file from the source code according to the Music XML standard

Articulation(art)[source]

An articulation, fingering, string number, or other symbol.

Assignment(a)[source]

Variables should already have been substituted so this need only cover other types of assignments.

Beam(beam)[source]
Change(change)[source]

A change music expression. Changes the staff number.

Chord(chord)[source]
ChordMode(chordmode)[source]

A chordmode or chords expression.

Clef(clef)[source]

Clef clef

Command(command)[source]

bar, rest etc

Context(context)[source]

context

DrumMode(drummode)[source]

A drummode or drums expression.

If the shorthand form drums is found, DrumStaff is implicit.

DrumNote(drumnote)[source]

A note in DrumMode.

Duration(duration)[source]

A written duration

Dynamic(dynamic)[source]

Any dynamic symbol.

End(end)[source]
FigureMode(figmode)[source]

A figuremode or figures expression.

Grace(grace)[source]
KeySignature(key)[source]
LyricItem(lyrics_item)[source]

Another lyric item (skip, extender, hyphen or tie).

LyricMode(lyricmode)[source]

A lyricmode, lyrics or addlyrics expression.

LyricText(lyrics_text)[source]

A lyric text (word, markup or string), with a Duration.

LyricsTo(lyrics_to)[source]

A lyricsto expression.

MusicList(musicList)[source]
Note(note)[source]

notename, e.g. c, cis, a bes …

NoteMode(notemode)[source]

A notemode or notes expression.

Number(number)[source]
Override(override)[source]

An override command.

PathItem(item)[source]

An item in the path of an override or revert command.

PhrasingSlur(phrslur)[source]

A ( or ).

PipeSymbol(barcheck)[source]

PipeSymbol = |

Postfix(postfix)[source]
Q(q)[source]
Relative(relative)[source]

A relative music expression.

Repeat(repeat)[source]
Rest(rest)[source]

rest, r or R. Note: NOT by command, i.e. rest

Scaler(scaler)[source]

times tuplet scaleDurations

Scheme(scheme)[source]

A Scheme expression inside LilyPond.

SchemeItem(item)[source]

Any scheme token.

SchemeQuote(quote)[source]

A ‘ in scheme.

Set(cont_set)[source]

A set command.

Skip(skip)[source]

invisible rest/spacer rest (s or command skip)

Slur(slur)[source]

Slur, ‘(‘ = start, ‘)’ = stop.

String(string)[source]
Tempo(tempo)[source]

Tempo direction, e g ‘4 = 80’

Tie(tie)[source]

tie ~

TimeSignature(timeSign)[source]
Tremolo(tremolo)[source]

A tremolo item “:”.

Unpitched(unpitched)[source]

A note without pitch, just a standalone duration.

UserCommand(usercommand)[source]

Music variables are substituted so this must be something else.

VoiceSeparator(voice_sep)[source]
With(cont_with)[source]

A with … construct.

check_context(context, context_id=None, token=u'')[source]

Check context and do appropriate action (e.g. create new part).

check_note(note)[source]

Generic check for all notes, both pitched and unpitched.

check_tuplet()[source]

Generic tuplet check.

find_score_sub(doc)[source]

Find substitute for scorenode. Takes first music node that isn’t an assignment.

gen_med_caller(func_name, *args)[source]

Call any function in the mediator object.

get_previous_node(node)[source]

Returns the nodes previous node or false if the node is first in its branch.

get_score(node)[source]

Returns (first) Score node or false if no Score is found.

iter_header(tree)[source]

Iter only over header nodes.

iter_score(scorenode, doc)[source]

Iter over score.

Similarly to items.Document.iter_music user commands are substituted.

Furthermore repeat unfold expressions are unfolded.

look_ahead(node, find_node)[source]

Looks ahead in a container node and returns True if the search is successful.

look_behind(node, find_node)[source]

Looks behind on the parent node(s) and returns True if the search is successful.

musicxml(prettyprint=True)[source]
parse_document(ly_doc, relative_first_pitch_absolute=False)[source]

Parse the LilyPond source specified as a ly.document document.

If relative_first_pitch_absolute is set to True, the first pitch in a
elative expression without startpitch is considered to be absolute
(LilyPond 2.18+ behaviour).
parse_nodes(nodes)[source]

Work through all nodes by calling the function with the same name as the nodes class.

parse_text(ly_text, filename=None)[source]

Parse the LilyPond source specified as text.

If you specify a filename, it can be used to resolve include commands correctly.

parse_tree(mustree)[source]

Parse the LilyPond source as a ly.music node tree.

simple_node_gen(node)[source]

Unlike iter_score are the subnodes yielded without substitution.

unfold_repeat(repeat_node, repeat_count, doc)[source]

Iter over node which represent a repeat unfold expression and do the unfolding directly.

ly.musicxml.xml_objs module

Classes that holds information about a musical score, suitable for converting to musicXML.

When the score structure is built, it can easily be used to create a musicXML.

Example:

from ly.musicxml import create_musicxml, xml_objs

musxml = create_musicxml.CreateMusicXML()

score = xml_objs.Score()
part = xml_objs.ScorePart()
score.partlist.append(part)
bar = xml_objs.Bar()
part.barlist.append(bar)
ba = xml_objs.BarAttr()
ba.set_time([4,4])
bar.obj_list.append(ba)
c = xml_objs.BarNote('c', 0, 0, (1,1))
c.set_octave(4)
c.set_durtype(1)
bar.obj_list.append(c)

xml_objs.IterateXmlObjs(score, musxml, 1)
xml = musxml.musicxml()
xml.write(filename)
class ly.musicxml.xml_objs.Bar[source]

Representing the bar/measure. Contains also information about how complete it is.

add(obj)[source]
create_backup()[source]

Calculate and create backup object.

has_music()[source]

Check if bar contains music.

inject_voice(new_voice, override=False)[source]

Adding new voice to bar. Omitting double or conflicting bar attributes as long as override is false. Omitting also bars with only skips.

is_skip(obj_list=None)[source]

Check if bar has nothing but skips.

class ly.musicxml.xml_objs.BarAttr[source]

object that keep track of bar attributes, e.g. time sign, clef, key etc

has_attr()[source]
merge_attr(barattr, override=False)[source]

Merge in attributes (from another bar). Existing attributes will only be replaced when override is set to true.

set_barline(bl)[source]
set_clef(clef)[source]
set_key(muskey, mode)[source]
set_tempo(unit=0, unittype=u'', beats=0, dots=0, text=u'')[source]
set_time(fractlist, numeric=True)[source]
class ly.musicxml.xml_objs.BarBackup(duration)[source]

Object that stores duration for backup

class ly.musicxml.xml_objs.BarMus(duration, voice=1)[source]

Common class for notes and rests.

add_dot()[source]
add_other_notation(other)[source]
has_attr()[source]
set_dynamics_dashes(sign, before=True)[source]
set_dynamics_mark(sign, before=True)[source]
set_dynamics_text(sign, before=True)[source]
set_dynamics_wedge(sign, before=True)[source]
set_oct_shift(plac, octdir, size)[source]
set_staff(staff)[source]
set_tuplet(fraction, ttype, nr, acttype=u'', normtype=u'')[source]
class ly.musicxml.xml_objs.BarNote(pitch_note, alter, accidental, duration, voice=1)[source]

Bases: ly.musicxml.xml_objs.BarMus

object to keep track of note parameters

add_adv_ornament(ornament, end_type=u'start')[source]
add_articulation(art_name)[source]
add_fingering(finger_nr)[source]
add_lyric(lyric_list)[source]
add_ornament(ornament)[source]
change_lyric_nr(index, nr)[source]
change_lyric_syll(index, syll)[source]
set_duration(duration, durtype=u'')[source]
set_durtype(durtype)[source]
set_gliss(line, endtype=u'start', nr=1)[source]
set_grace(slash)[source]
set_octave(octave)[source]
set_slur(nr, slur_type)[source]
set_tie(tie_type)[source]
set_tremolo(trem_type, duration=False)[source]
class ly.musicxml.xml_objs.BarRest(duration, voice=1, show_type=True, skip=False, pos=0)[source]

Bases: ly.musicxml.xml_objs.BarMus

object to keep track of different rests and skips

set_duration(duration, durtype=u'')[source]
set_durtype(durtype)[source]
class ly.musicxml.xml_objs.Dynamics(sign, before=True)[source]

Stores information about dynamics.

class ly.musicxml.xml_objs.DynamicsDashes(sign, before=True)[source]

Bases: ly.musicxml.xml_objs.Dynamics

Dynamics dashes.

class ly.musicxml.xml_objs.DynamicsMark(sign, before=True)[source]

Bases: ly.musicxml.xml_objs.Dynamics

A dynamics mark.

class ly.musicxml.xml_objs.DynamicsText(sign, before=True)[source]

Bases: ly.musicxml.xml_objs.Dynamics

A dynamics text.

class ly.musicxml.xml_objs.DynamicsWedge(sign, before=True)[source]

Bases: ly.musicxml.xml_objs.Dynamics

A dynamics wedge/hairpin.

class ly.musicxml.xml_objs.IterateXmlObjs(score, musxml, div)[source]

A ly.musicxml.xml_objs.Score object is iterated and the Music XML node tree is constructed.

after_note(obj)[source]

Xml-nodes after note.

before_note(obj)[source]

Xml-nodes before note.

count_duration(base_scaling, divs)[source]
gener_xml_mus(obj)[source]

Nodes generic for both notes and rests.

iterate_bar(bar)[source]

The objects in the bar are output to the xml-file.

iterate_part(part)[source]

The part is iterated.

iterate_partgroup(group)[source]

Loop through a group, recursively if nested.

new_xml_bar_attr(obj)[source]

Create bar attribute xml-nodes.

new_xml_note(obj)[source]

Create note specific xml-nodes.

new_xml_rest(obj)[source]

Create rest specific xml-nodes.

class ly.musicxml.xml_objs.LyricsSection(name, voice_id)[source]

Bases: ly.musicxml.xml_objs.ScoreSection

Holds the lyrics information. Will eventually be merged to the corresponding note in the section set by the voice id.

class ly.musicxml.xml_objs.OctaveShift(plac, octdir, size)[source]

Class for octave shifts.

class ly.musicxml.xml_objs.Score[source]

Object that keep track of a whole score.

debug_score(attr=[])[source]

Loop through score and print all elements for debugging purposes.

Additionally print element attributes by adding them to the argument ‘attr’ list.

is_empty()[source]

Check if score is empty.

merge_globally(section, override=False)[source]

Merge section to all parts.

class ly.musicxml.xml_objs.ScorePart(staves=0, part_id=None, to_part=None, name=u'')[source]

Bases: ly.musicxml.xml_objs.ScoreSection

object to keep track of part

extract_global_to_section(name)[source]

Extract only elements that is relevant for the score globally into a given section.

merge_part_to_part()[source]

Merge the part with the one indicated.

set_first_bar(divisions)[source]
class ly.musicxml.xml_objs.ScorePartGroup(num, bracket)[source]

Object to keep track of part group.

merge_voice(voice, override=False)[source]

Merge in a ScoreSection into all parts.

set_bracket(bracket)[source]
class ly.musicxml.xml_objs.ScoreSection(name, glob=False)[source]

object to keep track of music section

merge_lyrics(lyrics)[source]

Merge in lyrics in music section.

merge_voice(voice, override=False)[source]

Merge in other ScoreSection.

class ly.musicxml.xml_objs.Slur(nr, slurtype)[source]

Stores information about slur.

class ly.musicxml.xml_objs.Snippet(name, merge_into)[source]

Bases: ly.musicxml.xml_objs.ScoreSection

Short section intended to be merged. Holds reference to the barlist to be merged into.

class ly.musicxml.xml_objs.TempoDir(unit, unittype, beats, dots, text)[source]

Object that stores tempo direction information

set_midi_tempo(unit, beats, dots)[source]
class ly.musicxml.xml_objs.Tuplet(fraction, ttype, nr, acttype, normtype)[source]

Stores information about tuplet.

class ly.musicxml.xml_objs.Unpitched(duration, step=None, voice=1)[source]

Bases: ly.musicxml.xml_objs.BarNote

Object to keep track of unpitched notes.

ly.musicxml.xml_objs.convert_barl(bl)[source]
ly.musicxml.xml_objs.dur2lines(dur)[source]