musicscore.chord

class musicscore.chord.Chord(midis: List[float | int] | List[Midi] | float | int | Midi, quarter_duration: float | int | Fraction | QuarterDuration, **kwargs)[source]

Bases: MusicTree, QuarterDurationMixin, FinalizeMixin

Parent type: Beat

Child type: Note

Chord is a sequence of one or more XMLNote’s which occur at the same time in a XMLMeasure of a XMLPart.

Parameters:
  • midisMidi, Midi.value, [Midi, Midi.value], 0 or [0] for a rest.

  • quarter_duration – int, float, Fraction, QuarterDuration for duration counted in quarters (crotchets). 0 for grace note (or chord).

add_after_note_xml_objects(xml_element)[source]

Deprecated since version 2.0.2: This method is deprecated. Use add_xml_element_after_notes() instead.

add_child(child: Tree) Tree

Tree method

Check and add child to list of children. Child’s parent is set to self.

Parameters:

child

Returns:

child

Return type:

Tree

add_direction_type(direction_type: XMLElement, placement: str | None = None)[source]

Adds a XMLDirectionType to a private dictionary _xml_direction_types with placement keys: below and above. This dictionary is used during the finalization to add XMLDirection objects to XMLMeasure before this Chord

See also

add_x

Parameters:
Returns:

added direction_type

add_dynamics(dynamics: List[Dynamics] | List[str] | Dynamics | str, placement: str = 'below') List[Dynamics][source]

This method is used to add one or more musicscore.dynamics.Dynamics objects to chord’s private dictionary _xml_direction_types

Parameters:
  • dynamics – str, Dynamics of a list of Dynamics to be added to directions

  • placementabove or below

Returns:

List[Dynamics]

Exception:

AlreadyFinalizedError

add_grace_chord(midis_or_grace_chord: Midi | List[Midi] | int | float | List[float | int] | GraceChord, type: str | None = None, *, position: str | None = None)[source]

This method is used to add Midi’s or GraceChord object to the private dictionary _grace_chords with two position kyes before and after. The midis or grace chords will be positioned in Measure before or after this Chord

A GraceChord or a Chord with quarter_duration 0 can be added directly to a Beat too.

Parameters:
  • midis_or_grace_chordMidi’s or GraceChord

  • typetype value of the GraceChord to be created if midis_or_grace_chord is a list of midis. It specifices the not type of the grace note. For permitted values see: XMLType

  • positionNone, before, after. position value of the musicscore.chord.GraceChord to be created if midis_or_grace_chord is a list of midis.

Caution

midis_or_grace_chord is of type GraceChord, use musicscore.chord.GraceChord.type for setting its note type and musicscore.chord.GraceChord.position for setting its position instead of using type and position arguments.

add_lyric(text: Any | XMLLyric, **kwargs) XMLLyric[source]

This method is used to add XMLLyric to chord’s private _xml_lyrics list. This list is used to add lyrics the first Note object of chord`s notes during finalization.

Parameters:

text – if not of type XMLLyric a string conversion will be applied to text.

Parm kwargs:

passed on to XMLLyric if it has to be created.

Returns:

added XMLLyric

Exception:

AlreadyFinalizedError

add_midi(midi: float | int | Midi) Midi[source]

This method adds a new Midi to the chord and sorts its midis afterwards.

Param:

a Midi or a valid midi value.

Returns:

added Midi

Exception:

AlreadyFinalizedError

add_tie(type: str) None[source]

Chord’s tie list is used to add ties to or _update ties of all midis and consequently musicscore.note.Note objects which are to be or are already created.

Parameters:

typestart or stop

Returns:

None

add_wedge(wedge: XMLWedge | str, placement: str = 'below') XMLWedge[source]

This method is used to add one or more XMLWedge objects to chord’s private dictionary _xml_direction_types

Parameters:
  • wedge – str, XMLWedge to be added to directions

  • placementabove or below

Returns:

added XMLWedge

Exception:

AlreadyFinalizedError

add_words(words: XMLWords | str, placement: str = 'above', **kwargs) XMLWords[source]

This method is used to add one or more XMLWords objects to chord’s private dictionary _xml_direction_types

Parameters:
  • words – str, XMLWords to be added to directions

  • placementabove or below

  • kwargs – passed on to XMLWords if it has to be created.

Returns:

added XMLWords

Exception:

AlreadyFinalizedError

add_x(x: XMLAccent | XMLStrongAccent | XMLStaccato | XMLTenuto | XMLDetachedLegato | XMLStaccatissimo | XMLSpiccato | XMLScoop | XMLPlop | XMLDoit | XMLFalloff | XMLBreathMark | XMLCaesura | XMLStress | XMLUnstress | XMLUpBow | XMLDownBow | XMLHarmonic | XMLOpenString | XMLThumbPosition | XMLFingering | XMLPluck | XMLDoubleTongue | XMLTripleTongue | XMLStopped | XMLSnapPizzicato | XMLFret | XMLString | XMLHammerOn | XMLPullOff | XMLBend | XMLTap | XMLHeel | XMLToe | XMLFingernails | XMLHole | XMLArrow | XMLHandbell | XMLBrassBend | XMLFlip | XMLSmear | XMLOpen | XMLHalfMuted | XMLHarmonMute | XMLGolpe | XMLOtherTechnical | XMLDelayedInvertedTurn | XMLDelayedTurn | XMLHaydn | XMLInvertedMordent | XMLInvertedTurn | XMLInvertedVerticalTurn | XMLMordent | XMLOtherOrnament | XMLSchleifer | XMLShake | XMLTremolo | XMLTrillMark | XMLTurn | XMLVerticalTurn | XMLWavyLine | XMLF | XMLFf | XMLFff | XMLFfff | XMLFffff | XMLFfffff | XMLFp | XMLFz | XMLMf | XMLMp | XMLP | XMLPf | XMLPp | XMLPpp | XMLPppp | XMLPpppp | XMLPppppp | XMLRf | XMLRfz | XMLSf | XMLSffz | XMLSfp | XMLSfpp | XMLSfz | XMLSfzp | XMLArpeggiate | XMLFermata | XMLFootnote | XMLGlissando | XMLLevel | XMLNonArpeggiate | XMLOtherNotation | XMLSlide | XMLSlur | XMLAccidentalMark | XMLRehearsal | XMLSegno | XMLCoda | XMLWords | XMLSymbol | XMLWedge | XMLDashes | XMLBracket | XMLPedal | XMLMetronome | XMLOctaveShift | XMLHarpPedals | XMLDamp | XMLDampAll | XMLEyeglasses | XMLStringMute | XMLScordatura | XMLPrincipalVoice | XMLPercussion | XMLAccordionRegistration | XMLStaffDivide | XMLOtherDirection, *, placement: str = None, parent_type: str = None) XMLElement[source]

This method is used to add one XMLElement object to a chord’s private xml object lists (like _xml_articulations, xml_technicals etc.). These lists are used to add or update articulations, technicals etc. of the first Note object of chord`s notes which are to be or are already created. In case of direction types the object is added before the first note to the measure.

Parameters:
  • x – MusicXML articulation, technical, ornament, dynamics, other notations or direction type element.

  • placementNone, above, below. If this value is set and x does not accept placement an error is raised.

  • parent_typeNone, ``articulation, technical, ornament, notation, direction_type. If None the right parent type will be tried to determined. If x’s parent is ambivalent an error is raised.

Returns:

added x

Exception:

NotationException, ChordAddXPlacementException, ChordAddXException

add_xml_element_after_notes(xml_element: XMLElement) XMLElement[source]

This method adds an XMLElement to a list of elements to be added to XMLMeasure during finalization after adding this Chord’s Note’s to it.

Param:

XMLElement to be added after XMLNotes’s to XMLMeasure

Returns:

added XMLElement

check_number_of_beams()[source]
check_printed_duration()[source]
finalize()[source]

Finalize can be called only once. All necessary updates and xmlelement object creations will take place and the MusicTree object will be prepared for returning a musicxml snippet or a whole musicxml file.

  • Check if parent Beat exists.

  • Ancestors _update_divisions() is called to update XMLMeasure’s XMLDivisions attribute.

  • Following updates are triggered: _update_notes, _update_xml_chord, _update_notes_quarter_durations, _update_xml_lyrics, _update_ties, _update_xml_directions, _update_xml_metronome, _update_xml_articulations, _update_technicals, _update_xml_ornaments, _update_xml_dynamics, _update_xml_other_notations, _update_xml_notations_arpeggiate

get_beats() List[Beat]

MusicTree method

This method can be used for Score and Part, Measure, Staff and Voice.

Returns:

a flat list of all beats.

Return type:

List[Beat]

get_brackets() List[XMLBracket][source]

Get XMLBracket objects associated with this Chord

See also

get_x()

Returns:

list of XMLBracket

get_children() List[Tree]

Tree method

Returns:

list of added children.

Return type:

List[Tree]

get_children_of_type(type) List[Tree]

Tree method

Returns:

list of added children of type.

Return type:

List[Tree]

get_chords() List[Chord]

MusicTree method

This method can be used for Score and Part, Measure and Staff, Voice and Beat

Returns:

a flat list of all chords.

Return type:

List[Chord]

get_coordinates_in_tree() str

Tree method

Returns:

0 for root. 1, 2, … for layer 1. Other layers: x.y.z…. Example: 3.2.2 => third child of secod child of second child of the root.

Return type:

str

>>> class TestTree(Tree):
...   def _check_child_to_be_added(self, child):
...      return True
>>> root = TestTree()
>>> root.get_coordinates_in_tree()
'0'
>>> child1 = root.add_child(TestTree())
>>> child2 = root.add_child(TestTree())
>>> grandchild1 = child2.add_child(TestTree())
>>> grandchild2 = child2.add_child(TestTree())
>>> child1.get_coordinates_in_tree()
'1'
>>> child2.get_coordinates_in_tree()
'2'
>>> grandchild1.get_coordinates_in_tree()
'2.1'
>>> grandchild2.get_coordinates_in_tree()
'2.2'
get_grace_chords(position: str = 'before') List[GraceChord][source]

Get GraceChord objects associated with this Chord

Parameters:

positionbefore, after

Returns:

list of positioned GraceChord

get_indentation() str

Tree method

Returns:

indentation according to level (layer number). As default it is used for creating tabs in tree_representation

Return type:

str

get_layer(level: int, key: Callable | None = None) list

Tree method

Parameters:
  • level – layer number where 0 is the root.

  • key – An optional callable for each node in the layer.

Returns:

All nodes on this level. The leaves of branches which are shorter than the given level will be repeated on this and all following layers.

Return type:

list

get_leaves(key: Callable | None = None) list

Tree method

Parameters:

key – An optional callable to be called on each leaf.

Returns:

nested list of leaves or values of key(leaf) for each leaf

Return type:

nested list of Tree

get_next_in_part() Chord | None[source]

Get the next chord in part with same voice and staff number

Raises:

~:obj:~musicscore.exceptions.ChordHasNoParentPartError

get_parent() Tree

Tree method

Returns:

parent. None for root.

Return type:

Tree

get_parent_measure() Measure[source]
Returns:

parent Measure

get_root() Tree

Tree method

Returns:

root (upmost node of a tree which has no parent)

Return type:

Tree

get_slurs() List[XMLSlur][source]

Get XMLSlur objects associated with this Chord

See also

get_x()

Returns:

list of XMLSlur

get_staff_number() int | None[source]
Returns:

number of parent Staff

get_voice_number() int | None[source]
Returns:

number of parent Voice

get_wedges() List[XMLWedge][source]

Get XMLWedge objects associated with this Chord

See also

get_x()

Returns:

list of XMLWedge

get_words() List[XMLWords][source]

Get XMLWords objects associated with this Chord

See also

get_x()

Returns:

list of XMLWords

get_x(type: type) List[XMLAccent | XMLStrongAccent | XMLStaccato | XMLTenuto | XMLDetachedLegato | XMLStaccatissimo | XMLSpiccato | XMLScoop | XMLPlop | XMLDoit | XMLFalloff | XMLBreathMark | XMLCaesura | XMLStress | XMLUnstress | XMLUpBow | XMLDownBow | XMLHarmonic | XMLOpenString | XMLThumbPosition | XMLFingering | XMLPluck | XMLDoubleTongue | XMLTripleTongue | XMLStopped | XMLSnapPizzicato | XMLFret | XMLString | XMLHammerOn | XMLPullOff | XMLBend | XMLTap | XMLHeel | XMLToe | XMLFingernails | XMLHole | XMLArrow | XMLHandbell | XMLBrassBend | XMLFlip | XMLSmear | XMLOpen | XMLHalfMuted | XMLHarmonMute | XMLGolpe | XMLOtherTechnical | XMLDelayedInvertedTurn | XMLDelayedTurn | XMLHaydn | XMLInvertedMordent | XMLInvertedTurn | XMLInvertedVerticalTurn | XMLMordent | XMLOtherOrnament | XMLSchleifer | XMLShake | XMLTremolo | XMLTrillMark | XMLTurn | XMLVerticalTurn | XMLWavyLine | XMLF | XMLFf | XMLFff | XMLFfff | XMLFffff | XMLFfffff | XMLFp | XMLFz | XMLMf | XMLMp | XMLP | XMLPf | XMLPp | XMLPpp | XMLPppp | XMLPpppp | XMLPppppp | XMLRf | XMLRfz | XMLSf | XMLSffz | XMLSfp | XMLSfpp | XMLSfz | XMLSfzp | XMLArpeggiate | XMLFermata | XMLFootnote | XMLGlissando | XMLLevel | XMLNonArpeggiate | XMLOtherNotation | XMLSlide | XMLSlur | XMLAccidentalMark | XMLRehearsal | XMLSegno | XMLCoda | XMLWords | XMLSymbol | XMLWedge | XMLDashes | XMLBracket | XMLPedal | XMLMetronome | XMLOctaveShift | XMLHarpPedals | XMLDamp | XMLDampAll | XMLEyeglasses | XMLStringMute | XMLScordatura | XMLPrincipalVoice | XMLPercussion | XMLAccordionRegistration | XMLStaffDivide | XMLOtherDirection][source]

Get different direction_type, ornament, technical, articulation, dynamics or other notations objects objects associated with this Chord

See also

add_x()

Parameters:

type – type of XMLElement to look for.

has_same_pitches(other: Chord) bool[source]

Only for chords with pitches. Rest chords cannot use this method.

Parameters:

other – Other chord to which the comparison takes place

Returns:

True if pitches of self and other chord has the same pitch parameters and accidental values else False

iterate_leaves() Iterator[Tree]

Tree method

Returns:

A generator iterating over all leaves.

remove(child: Tree) None

Tree method

Child’s parent will be set to None and child will be removed from list of children.

Parameters:

child

Returns:

None

remove_children() None

Tree method

Calls remove() on all children.

Returns:

None

replace_child(old, new, index: int = 0) None

Tree method

Parameters:
  • old – child or function

  • new – child

  • index – index of old child in the list of its appearances

Returns:

None

reversed_path_to_root() Iterator[Tree]

Tree method

Returns:

path from self upwards through all ancestors up to the root.

set_beam(number, value)[source]
to_rest() None[source]

Set self.midis to [0]

Returns:

None

to_string(*args, **kwargs)

FinalizeMixin method

It triggers finalize() first before calling parent’s xml_object.to_string() method. If no xml_object exists (it means there is no direct MusicXML equavalent of this class) a ClassHasNoMusicXMLEquivalentError is thrown.

traverse() Iterator[Tree]

Tree method

Traverse all tree nodes.

Returns:

generator

tree_representation(key: Callable | None = None, tab: Callable | None = None) str

Tree method

Parameters:
  • key – An optional callable if None compact_repr property of each node is called.

  • tab – An optional callable if None get_indentation() method of each node is called.

Returns:

a representation of all nodes as string in tree form.

Return type:

str

property all_midis_are_tied_to_next: bool
Returns:

True if the property is_tied_to_next of all midi children of Chord are return True, otherwise False

property all_midis_are_tied_to_previous: bool
Returns:

True if the property is_tied_to_previous of all midi children of Chord are return True, otherwise False

property arpeggio: str

Set and get arpeggio value. Permitted values are None, normal, up, down, none

After finalizing:
property beams

A dictionary like: {1:’continue’, 2:’begin’}. Keys are beam numbers. Default is {}. _update_chord_beams sets a beam only if beam is not None and beam is not set manually.

property clef: Clef

Set or get Clef object to be added to Measure before this Chord

property compact_repr: str

Tree property

Returns:

compact representation of a node. Default is the string representation. This property is used as default in the tree_representation method and can be customized in subclasses to get the most appropriate representation.

Return type:

str

default_show_accidental_signs = 'modern'

Class attribute of MusicTree

property is_leaf: bool

Tree property

Returns:

True if self has no children. False if self has one or more children.

Return type:

bool

property is_rest: bool
Returns:

True if Chord represents a rest, False if otherwise.

Return type:

bool

property is_root: bool

Tree property

Returns:

True if self has no parent, else False.

Return type:

bool

property is_tied_to_next

Same as all_midis_are_tied_to_next

property is_tied_to_previous

Same as all_midis_are_tied_to_previous

property level: int

Tree property

Returns:

0 for root, 1, 2 etc. for each layer of children

Return type:

nonnegative int

>>> class TestTree(Tree):
...   def _check_child_to_be_added(self, child):
...      return True
>>> root = TestTree()
>>> root.level
0
>>> ch = root.add_child(TestTree()).add_child(TestTree()).add_child(TestTree())
>>> ch.level
3
property metronome

Get and set the Metronome object associated with this Chord

property midis: List[Midi]
Returns:

list of midis

>>> ch = Chord(quarter_duration=1, midis=60)
>>> [type(m) for m in ch.midis]
[<class 'musicscore.midi.Midi'>]
>>> [m.value for m in ch.midis]
[60]
>>> ch = Chord(quarter_duration=1,midis=[60, Midi(40)])
>>> [m.value for m in ch.midis]
[40, 60]
>>> Chord(quarter_duration=1, midis=[0, 60])
Traceback (most recent call last):
...
ValueError: Chord cannot accept a mixed list of midis of rests and pitches or a list of more than one rests.
property next: Tree | None

Tree property

Returns:

next sibling. None if this is the last current child of the parent.

Return type:

Tree

property notes: List[Note]
Returns:

musicscore.chord.get_children which are of type musicscore.note.Note.

Return type:

List[Note]

property number_of_beams: int | None
property number_of_dots: int

Set and get number of dots to be added to the notes. If not set manually ~:obj:musicscore.beat.Beat.finalize() will set it usually via calling ~:obj:~musicscore.quarterduration.QuarterDuration.get_number_of_dots().

property offset: QuarterDuration
Returns:

Offset in Chord’s parent Beat

Return type:

QuarterDuration

property previous: Tree | None

Tree property

Returns:

previous sibling. None if this is the first child of the parent.

Return type:

Tree

property quarter_duration: QuarterDuration

Set and get the duration measured in quarters.

Setting value can be of types int, float, quicktions.Fraction, QuarterDuration

property show_accidental_signs: str

MusicTree property

  • If show_accidental_signs is set to None the first get_quantized of ancestors which is False or True will be returned.

  • If show_accidental_signs is set to None it will be converted to default_show_accidental_signs

  • Possible show_accidental_signs are: None, ‘modern’, ‘traditional’

Type:

Optional[str]

Return type:

str

property tuplet: Tuplet | None
property type: str | None

Set and get `XMLNoteType.value_` associated with this chord. If not set manually ~:obj:musicscore.beat.Beat.finalize() will set it usually via calling ~:obj:~musicscore.quarterduration.QuarterDuration.get_type(). ~:obj:~musicscore.quarterduration.QuarterDuration 0 returns None. :param val: [‘1024th’, ‘512th’, ‘256th’, ‘128th’, ‘64th’, ‘32nd’, ‘16th’, ‘eighth’, ‘quarter’, ‘half’, ‘whole’, ‘breve’, ‘long’, ‘maxima’]

property up: Tree

Tree property

Returns:

get_parent()

Return type:

Tree

property voice_number: int
Returns:

Number of parent Voice

Return type:

positive int

property xml_articulations: List[XMLAccent | XMLStrongAccent | XMLStaccato | XMLTenuto | XMLDetachedLegato | XMLStaccatissimo | XMLSpiccato | XMLScoop | XMLPlop | XMLDoit | XMLFalloff | XMLBreathMark | XMLCaesura | XMLStress | XMLUnstress]
Returns:

list of xml articulations to be added to this Chord during finalization.

property xml_direction_types: Dict
Returns:

dict of xml direction types to be added to this Chord during finalization.

property xml_lyrics: List[XMLLyric]
Returns:

list of xml lyrics to be added to this Chord during finalization.

property xml_technicals: List[XMLUpBow | XMLDownBow | XMLHarmonic | XMLOpenString | XMLThumbPosition | XMLFingering | XMLPluck | XMLDoubleTongue | XMLTripleTongue | XMLStopped | XMLSnapPizzicato | XMLFret | XMLString | XMLHammerOn | XMLPullOff | XMLBend | XMLTap | XMLHeel | XMLToe | XMLFingernails | XMLHole | XMLArrow | XMLHandbell | XMLBrassBend | XMLFlip | XMLSmear | XMLOpen | XMLHalfMuted | XMLHarmonMute | XMLGolpe | XMLOtherTechnical]
Returns:

list of xml technicals to be added to this Chord during finalization.

class musicscore.chord.GraceChord(midis: List[float | int] | List[Midi] | float | int | Midi, *, type=None, position='before', **kwargs)[source]

Bases: Chord

See also

Chord for inherited methods and properties

add_grace_chord(midis_or_grace_chord, type=None, *, position=None)[source]
Exception:

GraceChordCannotHaveGraceNotesError

get_grace_chords(position='before')[source]
Exception:

GraceChordCannotHaveGraceNotesError

property position

Set and get position (before, after) of this GraceChord. It is relevant if it would be added to a Chord.

property quarter_duration: QuarterDuration

Set and get the duration measured in quarters.

Setting value can be of types int, float, quicktions.Fraction, QuarterDuration

class musicscore.chord.Rest(quarter_duration, display_step=None, display_octave=None, measure=None, **kwargs)[source]

Bases: Chord

See also

Chord for inherited methods and properties

finalize()[source]

Finalize can be called only once. All necessary updates and xmlelement object creations will take place and the MusicTree object will be prepared for returning a musicxml snippet or a whole musicxml file.

  • Check if parent Beat exists.

  • Ancestors _update_divisions() is called to update XMLMeasure’s XMLDivisions attribute.

  • Following updates are triggered: _update_notes, _update_xml_chord, _update_notes_quarter_durations, _update_xml_lyrics, _update_ties, _update_xml_directions, _update_xml_metronome, _update_xml_articulations, _update_technicals, _update_xml_ornaments, _update_xml_dynamics, _update_xml_other_notations, _update_xml_notations_arpeggiate

property display_octave

Set and get XMLDisplayOctave child of XMLRest. Permitted are None and positive int

property display_step

Set and get XMLDisplayStep child of XMLRest. Permitted values are None, A, B, C, D, E, F, G

property measure

Set or get measure attribute of XMLRest. Permitted values are None, yes and no. If yes, this indicates this is a complete measure rest.

property midis: List[Midi]
Returns:

list of midis

>>> ch = Chord(quarter_duration=1, midis=60)
>>> [type(m) for m in ch.midis]
[<class 'musicscore.midi.Midi'>]
>>> [m.value for m in ch.midis]
[60]
>>> ch = Chord(quarter_duration=1,midis=[60, Midi(40)])
>>> [m.value for m in ch.midis]
[40, 60]
>>> Chord(quarter_duration=1, midis=[0, 60])
Traceback (most recent call last):
...
ValueError: Chord cannot accept a mixed list of midis of rests and pitches or a list of more than one rests.