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,FinalizeMixinParent type:
BeatChild type:
NoteChord is a sequence of one or more
XMLNote’s which occur at the same time in aXMLMeasureof aXMLPart.- Parameters:
midis –
Midi, Midi.value, [Midi, Midi.value], 0 or [0] for a rest.quarter_duration – int, float, Fraction,
QuarterDurationfor 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: T) T
TreemethodCheck 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
XMLDirectionTypeto a private dictionary_xml_direction_typeswith placement keys:belowandabove. This dictionary is used during the finalization to addXMLDirectionobjects toXMLMeasurebefore thisChordSee also
- Parameters:
direction_type – Permitted direction types are found in
XML_DIRECTION_TYPE_CLASSESandXML_DIRECTION_TYPE_AND_OTHER_NOTATIONSplacement –
None,below,above
- 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.Dynamicsobjects to chord’s private dictionary_xml_direction_typesSee also
- 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 orGraceChordobject to the private dictionary_grace_chordswith two position kyesbeforeandafter. The midis or grace chords will be positioned inMeasurebefore or after thisChordA
GraceChordor aChordwithquarter_duration0can be added directly to aBeattoo.- Parameters:
midis_or_grace_chord –
Midi’s orGraceChordtype –
typevalue of theGraceChordto be created ifmidis_or_grace_chordis a list of midis. It specifices the not type of the grace note. For permitted values see:XMLTypeposition –
None,before,after.positionvalue of themusicscore.chord.GraceChordto be created ifmidis_or_grace_chordis a list of midis.
Caution
midis_or_grace_chordis of typeGraceChord, usemusicscore.chord.GraceChord.typefor setting its note type andmusicscore.chord.GraceChord.positionfor setting its position instead of using type and position arguments.
- add_lyric(text: Any | XMLLyric, **kwargs) XMLLyric[source]
This method is used to add
XMLLyricto chord’s private_xml_lyricslist. This list is used to add lyrics the firstNoteobject of chord`s notes during finalization.
- add_midi(midi: float | int | Midi) Midi[source]
This method adds a new
Midito the chord and sorts its midis afterwards.
- 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.Noteobjects which are to be or are already created.- Parameters:
type –
startorstop- Returns:
None
- add_wedge(wedge: XMLWedge | str, placement: str = 'below') XMLWedge[source]
This method is used to add one or more
XMLWedgeobjects to chord’s private dictionary_xml_direction_typesSee also
- add_words(words: XMLWords | str, placement: str = 'above', **kwargs) XMLWords[source]
This method is used to add one or more
XMLWordsobjects to chord’s private dictionary_xml_direction_typesSee also
- Parameters:
- Returns:
added
XMLWords- Exception:
- 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
XMLElementobject 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 firstNoteobject 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.
placement –
None,above,below. If this value is set and x does not accept placement an error is raised.parent_type –
None, ``articulation,technical,ornament,notation,direction_type. IfNonethe 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
XMLElementto a list of elements to be added toXMLMeasureduring finalization after adding thisChord’sNote’s to it.- Param:
XMLElementto be added afterXMLNotes’s toXMLMeasure- Returns:
added
XMLElement
- classmethod create_tree_from_list(tree_list_representation: list[list[Any]], represented_attribute_names: list[str]) T
- filter_nodes(key: Callable[[T], Any], return_value: Any) list[T]
Treemethod>>> root.filter_nodes(lambda node: node.get_level(), 2) [grandchild1, grandchild2, grandchild3]
- 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
Beatexists.Ancestors
_update_divisions()is called to updateXMLMeasure’sXMLDivisionsattribute.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]
MusicTreemethodThis method can be used for
ScoreandPart,Measure,StaffandVoice.- Returns:
a flat list of all beats.
- Return type:
List[
Beat]
- get_brackets() List[XMLBracket][source]
Get
XMLBracketobjects associated with thisChordSee also
- Returns:
list of
XMLBracket
- get_children() list[T]
Treemethod- Returns:
list of added children.
- get_children_of_type(type_: type) list[T]
Treemethod- Returns:
list of added children of type.d
- Return type:
list[
Tree]
- get_chords() List[Chord]
MusicTreemethodThis method can be used for
ScoreandPart,MeasureandStaff,VoiceandBeat- Returns:
a flat list of all chords.
- Return type:
List[
Chord]
- get_distance(reference: T | None = None) int
>>> root.get_distance() 0 >>> greatgrandchild1.get_distance() 3 >>> greatgrandchild1.get_distance(child2) 2
- get_farthest_leaf() T
>>> root.get_farthest_leaf() greatgrandchild1
- get_grace_chords(position: str = 'before') List[GraceChord][source]
Get
GraceChordobjects associated with thisChord- Parameters:
position –
before,after- Returns:
list of positioned
GraceChord
- get_layer(level: int, key: Callable[[T], Any] | None = None) Any
Treemethod- 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[[T], Any] | None = None) list[Union[Any, list[Any]]]
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
>>> root.get_leaves() [child1, [[greatgrandchild1, greatgrandchild2], grandchild2], child3, [grandchild3]]
- get_level() int
Tree- Returns:
0forroot,1, 2 etc.for each layer of children- Return type:
nonnegative int
>>> root.get_level() 0 >>> child1.get_level() 1 >>> grandchild1.get_level() 2 >>> greatgrandchild1.get_level() 3
- 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_number_of_layers() int
>>> root.get_number_of_layers() 3
- get_parent() T | None
Treemethod- Returns:
parent.
Noneforroot.- Return type:
Tree
- get_position_in_tree() str
Treemethod- 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
>>> print(root.get_tree_representation(key=lambda node: node.get_position_in_tree())) └── 0 ├── 1 ├── 2 │ ├── 2.1 │ │ ├── 2.1.1 │ │ └── 2.1.2 │ └── 2.2 ├── 3 └── 4 └── 4.1
- get_reversed_path_to_root() list[T]
Treemethod- Returns:
path from self upwards through all ancestors up to the
root.
>>> greatgrandchild1.get_reversed_path_to_root() [greatgrandchild1, grandchild1, child2, root]
- get_root() T
Treemethod- Returns:
root(upmost node of a tree which has no parent)- Return type:
Tree
>>> greatgrandchild1.get_root() == root True >>> child4.get_root() == root True >>> root.get_root() == root True
- get_self_with_key(key: Callable[[T], Any] | None = None) Any
- get_slurs() List[XMLSlur][source]
Get
XMLSlurobjects associated with thisChordSee also
- Returns:
list of
XMLSlur
- get_tree_representation(key: Callable[[T], Any] | None = None, space: int = 3) str
Treemethod- Parameters:
key – An optional callable if
Nonestring(node) is called.- Returns:
a representation of all nodes as string in tree form.
>>> print(root.get_tree_representation()) └── root ├── child1 ├── child2 │ ├── grandchild1 │ │ ├── greatgrandchild1 │ │ └── greatgrandchild2 │ └── grandchild2 ├── child3 └── child4 └── grandchild3
- get_wedges() List[XMLWedge][source]
Get
XMLWedgeobjects associated with thisChordSee also
- Returns:
list of
XMLWedge
- get_words() List[XMLWords][source]
Get
XMLWordsobjects associated with thisChordSee also
- 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
ChordSee also
- 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:
Trueif pitches of self and other chord has the same pitch parameters and accidental values elseFalse
- iterate_leaves() Iterator[T]
Treemethod- Returns:
A generator iterating over all leaves.
- remove(child: T) None
TreemethodChild’s parent will be set to
Noneand child will be removed from list of children.- Parameters:
child –
- Returns:
None
- replace_child(old: T, new: T, index: int = 0) None
Treemethod- Parameters:
old – child or function
new – child
index – index of old child in the list of its appearances
- Returns:
None
- to_string(*args, **kwargs)
FinalizeMixinmethodIt triggers
finalize()first before calling parent’sxml_object.to_string()method. If no xml_object exists (it means there is no direct MusicXML equavalent of this class) aClassHasNoMusicXMLEquivalentErroris thrown.
- traverse() Iterator[T]
TreemethodTraverse all tree nodes.
- Returns:
generator
- property all_midis_are_tied_to_next: bool
- Returns:
Trueif the propertyis_tied_to_nextof all midi children of Chord are returnTrue, otherwiseFalse
- property all_midis_are_tied_to_previous: bool
- Returns:
Trueif the propertyis_tied_to_previousof all midi children of Chord are returnTrue, otherwiseFalse
- property arpeggio: str
Set and get
arpeggiovalue. Permitted values areNone,normal,up,down,none- After finalizing:
noneadds anXMLNonArpeggiatechild to eachNote’sXMLNotationsnormaladds anXMLArpeggiatechild to eachNote’sXMLNotationsupadds anXMLArpeggiatechild with directionupto eachNote’sXMLNotationsdownadds anXMLArpeggiatechild with directiondownto eachNote’sXMLNotations
- property beams
A dictionary like: {1:’continue’, 2:’begin’}. Keys are beam numbers. Default is {}.
_update_chord_beamssets a beam only if beam is not None and beam is not set manually.
- property broken_beam
If true the beam will be broken at this position
- property content: Any
- default_show_accidental_signs = 'modern'
- property is_first_child: bool
- property is_last_child: bool
>>> t = TestTree('root') >>> for node in t.traverse(): ... if node.name in ['root', 'child4', 'grandchild2', 'grandchild3', 'greatgrandchild1']: ... assert node.is_last_child ... else: ... assert not node.is_last_child
- property is_leaf: bool
Treeproperty- Returns:
Trueif self has no children.Falseif self has one or more children.- Return type:
bool
- property is_rest: bool
- Returns:
Trueif Chord represents a rest,Falseif otherwise.- Return type:
bool
- property is_root: bool
Treeproperty- Returns:
Trueif self has no parent, elseFalse.- 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 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: T | None
Treeproperty- Returns:
next sibling.
Noneif this is the last current child of the parent.- Return type:
Tree
- property notes: List[Note]
- Returns:
musicscore.chord.get_childrenwhich are of typemusicscore.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:
- property previous: T | None
Treeproperty- Returns:
previous sibling.
Noneif 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,fractions.Fraction,QuarterDuration
- property show_accidental_signs: str
MusicTreepropertyIf show_accidental_signs is set to None the first get_quantized of ancestors which is
FalseorTruewill be returned.If
show_accidental_signsis set to None it will be converted todefault_show_accidental_signsPossible show_accidental_signs are: None, ‘modern’, ‘traditional’
- Type:
Optional[str]
- Return type:
str
- 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.QuarterDuration0returnsNone. :param val: [‘1024th’, ‘512th’, ‘256th’, ‘128th’, ‘64th’, ‘32nd’, ‘16th’, ‘eighth’, ‘quarter’, ‘half’, ‘whole’, ‘breve’, ‘long’, ‘maxima’]
- property up: T | None
Treeproperty- Returns:
- Return type:
Tree
- 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
Chordduring finalization.
- property xml_direction_types: Dict
- Returns:
dict of xml direction types to be added to this
Chordduring finalization.
- property xml_lyrics: List[XMLLyric]
- Returns:
list of xml lyrics to be added to this
Chordduring 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
Chordduring finalization.
- class musicscore.chord.GraceChord(midis: List[float | int] | List[Midi] | float | int | Midi, *, type=None, position='before', **kwargs)[source]
Bases:
ChordSee also
Chordfor inherited methods and properties- property position
Set and get position (
before,after) of thisGraceChord. It is relevant if it would be added to aChord.
- property quarter_duration: QuarterDuration
Set and get the duration measured in quarters.
Setting value can be of types
int,float,fractions.Fraction,QuarterDuration
- class musicscore.chord.Rest(quarter_duration, display_step=None, display_octave=None, measure=None, **kwargs)[source]
Bases:
ChordSee also
Chordfor 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
Beatexists.Ancestors
_update_divisions()is called to updateXMLMeasure’sXMLDivisionsattribute.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
XMLDisplayOctavechild ofXMLRest. Permitted areNoneand positive int
- property display_step
Set and get
XMLDisplayStepchild ofXMLRest. Permitted values areNone,A,B,C,D,E,F,G
- property measure
Set or get measure attribute of
XMLRest. Permitted values areNone,yesandno. Ifyes, 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.