Skip to content

Classses Representing Basic Score Elements

from amads.core import *

Note: importing amads.core imports amads.core.basics, amads.core.distribution and amads.core.timemap.

Clef

Clef(
    parent: Optional[EventGroup] = None,
    onset: float = 0.0,
    clef: str = "treble",
    parameters: Optional[tuple[str, int, int]] = None,
)

Bases: Event

Clef is a zero-duration Event with clef information.

All valid clefs are named. For any clef name, you can retrieve descriptive information using the get_symbol, get_staff_line and get_octave methods. These uniquely define the mapping between note name and staff position.

Clef names are in _clef_info.keys() and based on Music21, which has these clefs (and a couple of others). For a more complete list (but how would we read them?), see https://github.com/Chorale-Corpus/Goudimel_C#clefs.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    The containing object or None.

  • onset (float, default: 0.0 ) –

    The onset (start) time. An initial value of None might be assigned when the Clef is inserted into an EventGroup.

  • clef (str, default: 'treble' ) –

    The clef name, one of "treble", "bass", "alto", "tenor", "percussion", "treble8vb" (Other clefs may be added later.)

  • parameters (Optionoal[tuple[str, int, int]], default: None ) –

    If clef is "constructed", parameters must contain a tuple giving the clef symbol ("F", "G", or "C"), the staff line as the clef position (1 through 5), and the octave shift, e.g., 1 for "8va", -1 for "8vb", 0 for the normal octave (F3, G4, C4).

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (float) –

    The onset (start) time.

  • duration (float) –

    Always zero for this subclass.

  • clef (str) –

    The clef name, one of "treble", "alto", "tenor", "bass", "treble8va", "treble8vb", "percussion". For uncommon clefs, see _clef_info in source code for a complete list.

Source code in amads/core/clef.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __init__(
    self,
    parent: Optional["EventGroup"] = None,
    onset: float = 0.0,
    clef: str = "treble",
    parameters: Optional[tuple[str, int, int]] = None,
):
    super().__init__(parent, onset, 0)
    if clef not in self._clef_info and clef != "constructed":
        raise ValueError(f"Invalid clef: {clef}")
    self.clef = clef
    if clef == "constructed":
        if parameters is None:
            raise ValueError("Must provide parameters for constructed clef")
        self.set("clef_info", parameters)

Attributes

onset property writable

onset: float

Retrieve the onset (start) time.

If the onset is None, raise an exception. (Events can have None onset times, but they must be set before retrieval. onsets that are None are automatically set when the Event is added to an EventGroup.)

Returns:

  • float | None

    The onset (start) time.

Raises:

  • ValueError

    If the onset time is not set (None).

units_are_seconds property

units_are_seconds: bool

Check if the times are in seconds.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in seconds. If not in a score, False is returned.

units_are_quarters property

units_are_quarters: bool

Check if the times are in quarters.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in quarters. If not in a score, False is returned.

offset property writable

offset: float

Retrieve the global offset (stop) time.

Returns:

  • float

    The global offset (stop) time.

part property

part: Optional[Part]

Retrieve the Part containing this event.

Returns:

  • Optional[Part]

    The Part containing this event or None if not found.

score property

score: Optional[Score]

Retrieve the Score containing this event, or self if it is a score.

Returns:

  • Optional[Score]

    The Score containing this event or None if not found.

staff property

staff: Optional[Staff]

Retrieve the Staff containing this event

Returns:

  • Optional[Staff]

    The Staff containing this event or None if not found.

measure property

measure: Optional[Measure]

Retrieve the Measure containing this event

Returns:

  • Optional[Measure]

    The Measure containing this event or None if not found.

Functions

set

set(property: str, value: Any) -> Event

Set a named property on this Event.

Every event can be extended with additional properties. Although Python objects are already extensible with new attributes, new attributes that are not set in __init__ confuse type checkers and other tools, so every Event has an info attribute as a dictionary where additional, application-specific information can be stored. The info attribute is None to save space until the first property is set, so you should use set and get methods and avoid writing event.info[property].

Parameters:

  • property (str) –

    The name of the property to set.

  • value (Any) –

    The value to assign to the property.

Returns:

  • Event

    returns this object (self)

Examples:

>>> note = Note()
>>> note.get("color", "no color")
'no color'
>>> _ = note.set("color", "red").set("harmonicity", 0.2)
>>> (note.has("color"), note.has("shape"))
(True, False)
>>> (note.get("color"), note.get("harmonicity"))
('red', 0.2)
Source code in amads/core/basics.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def set(self, property : str, value : Any) -> "Event":
    """Set a named property on this Event.

    Every event can be extended with additional properties. Although
    Python objects are already extensible with new attributes, new
    attributes that are not set in `__init__` confuse type checkers
    and other tools, so every `Event` has an `info` attribute as a
    dictionary where additional, application-specific information can
    be stored. The `info` attribute is `None` to save space until the
    first property is set, so you should use `set` and `get` methods
    and avoid writing `event.info[property]`.

    Parameters
    ----------
    property : str
        The name of the property to set.
    value : Any
        The value to assign to the property.

    Returns
    -------
    Event
        returns this object (self)

    Examples
    --------
    >>> note = Note()
    >>> note.get("color", "no color")
    'no color'
    >>> _ = note.set("color", "red").set("harmonicity", 0.2)
    >>> (note.has("color"), note.has("shape"))
    (True, False)
    >>> (note.get("color"), note.get("harmonicity"))
    ('red', 0.2)
    """
    if self.info is None:
        self.info = {}
    self.info[property] = value
    return self

get

get(property: str, default: Any = None) -> Any

Get the value of a property from this Event.

See set for more details.

Parameters:

  • property (str.) –

    The name of the property to get.

  • default (Any, default: None ) –

    The default value to return if the property is not found.

Returns:

  • Any

    The value of the specified property.

Source code in amads/core/basics.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def get(self, property : str, default : Any = None) -> Any:
    """Get the value of a property from this Event.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str.
        The name of the property to get.
    default : Any
        The default value to return if the property is not found.

    Returns
    -------
    Any
        The value of the specified property.
    """
    if self.info is None:
        return default
    return self.info.get(property, default)

has

has(property) -> bool

Check if the Event has a specific property.

See set for more details.

Parameters:

  • property (str) –

    The name of the property to check.

Returns:

  • bool

    True if the property exists, False otherwise.

Source code in amads/core/basics.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def has(self, property) -> bool:
    """Check if the Event has a specific property.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str
        The name of the property to check.

    Returns
    -------
    bool
        True if the property exists, False otherwise.
    """
    return (self.info is not None) and (property in self.info)

time_shift

time_shift(increment: float, content_only=False) -> Event

Change the onset by an increment.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

  • content_only (bool, default: False ) –

    This parameter is ignored. (See EventGroup.time_shift)

Returns:

  • Event

    The object. This method modifies the Event.

Source code in amads/core/basics.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def time_shift(self, increment: float, content_only=False) -> "Event":
    """
    Change the onset by an increment.

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).
    content_only : bool, optional
        This parameter is ignored. (See EventGroup.time_shift)
    Returns
    -------
    Event
        The object. This method modifies the `Event`.
    """
    self._onset += increment  # type: ignore
    return self

insert_copy_into

insert_copy_into(parent: Optional[EventGroup] = None) -> Event

Make a (mostly) deep copy of the Event and add to a new parent.

Pitch objects are considered immutable and are shared rather than copied.

Parameters:

  • parent (Optional(EventGroup), default: None ) –

    The copied Event will be a child of parent if not None. The parent is modified by this operation.

Returns:

  • Event

    A deep copy (except for parent and pitch) of the Event instance.

Source code in amads/core/basics.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def insert_copy_into(self,
                     parent: Optional["EventGroup"] = None) -> "Event":
    """
    Make a (mostly) deep copy of the `Event` and add to a new `parent`.

    `Pitch` objects are considered immutable and are shared rather
    than copied.

    Parameters
    ----------
    parent : Optional(EventGroup)
        The copied `Event` will be a child of `parent` if not `None`.
        The parent is modified by this operation.

    Returns
    -------
    Event
        A deep copy (except for parent and pitch) of the Event instance.
    """
    # remove link to parent to break link going up the tree
    # preventing deep copy from copying the entire tree
    original_parent = self.parent
    self.parent = None
    c = copy.deepcopy(self)  # deep copy of this event down to leaf nodes
    self.parent = original_parent  # restore link to parent
    if parent:
        parent.insert(c)
    return c

get_symbol classmethod

get_symbol(clef_name: str) -> str

retrieve the symbol used for the clef

Values are "G" for G clef, "C" for C clef, "F" for F clef, and "P" for percussion clef. The G clef position is that of pitch G4, the C clef position is that of C4, and the F clef position is that of F3, subject to alteration by octave transposition.

Parameters:

  • clef_name (str) –

    The clef name.

Returns:

  • str

    The clef symbol, one of "G", "C", "F", "P" (see above).

Raises:

  • ValueError

    If the clef_name is not a known clef.

Source code in amads/core/clef.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@classmethod
def get_symbol(cls, clef_name: str) -> str:
    """retrieve the symbol used for the clef

    Values are "G" for G clef, "C" for C clef, "F" for F clef, and
    "P" for percussion clef. The G clef position is that of pitch G4,
    the C clef position is that of C4, and the F clef position is
    that of F3, subject to alteration by octave transposition.

    Parameters
    ----------
    clef_name: str
        The clef name.

    Returns
    -------
    str
        The clef symbol, one of "G", "C", "F", "P" (see above).

    Raises
    ------
    ValueError
        If the `clef_name` is not a known clef.
    """
    info = cls._clef_info.get(clef_name)
    if not info:
        raise ValueError(f"Unknown clef name {clef_name}")
    return info[0]

get_staff_line classmethod

get_staff_line(clef_name: str) -> int

retrieve the staff line where the clef is placed

Staff lines are numbered 1 through 5, with 1 being the bottom line.

Parameters:

  • clef_name (str) –

    The clef name.

Returns:

  • int

    The staff line (1 through 5) of the clef symbol.

Raises:

  • ValueError

    If the clef_name is not a known clef.

Source code in amads/core/clef.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
@classmethod
def get_staff_line(cls, clef_name: str) -> int:
    """retrieve the staff line where the clef is placed

    Staff lines are numbered 1 through 5, with 1 being the
    bottom line.

    Parameters
    ----------
    clef_name: str
        The clef name.

    Returns
    -------
    int
        The staff line (1 through 5) of the clef symbol.

    Raises
    ------
    ValueError
        If the `clef_name` is not a known clef.
    """
    info = cls._clef_info.get(clef_name)
    if not info:
        raise ValueError(f"Unknown clef name {clef_name}")
    return info[1]

get_octave classmethod

get_octave(clef_name: str) -> int

retrieve the octave transposition for the clef

An octave transposition of 1 means the staff line with the clef symbol represents an octave higher than the nominal pitch of the clef symbol (one of G4, C4, F3). I.e., notes on the staff are transposed up one octave.

Parameters:

  • clef_name (str) –

    The clef name.

Returns:

  • int

    The octave transposition applied to the clef symbol, in the range -2 to +2.

Raises:

  • ValueError

    If the clef_name is not a known clef.

Source code in amads/core/clef.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@classmethod
def get_octave(cls, clef_name: str) -> int:
    """retrieve the octave transposition for the clef

    An octave transposition of 1 means the staff line with the clef
    symbol represents an octave higher than the nominal pitch of the
    clef symbol (one of G4, C4, F3). I.e., notes on the staff are
    transposed up one octave.

    Parameters
    ----------
    clef_name: str
        The clef name.

    Returns
    -------
    int
        The octave transposition applied to the clef symbol, in the
        range -2 to +2.

    Raises
    ------
    ValueError
        If the `clef_name` is not a known clef.
    """
    info = cls._clef_info.get(clef_name)
    if not info:
        raise ValueError(f"Unknown clef name {clef_name}")
    return info[2]

show

show(indent: int = 0, file: Optional[TextIO] = None) -> Clef

Display the Clef information.

Parameters:

  • indent (int, default: 0 ) –

    The indentation level for display.

Returns:

  • Clef

    The Clef instance itself.

Source code in amads/core/clef.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def show(self, indent: int = 0, file: Optional[TextIO] = None) -> "Clef":
    """Display the Clef information.

    Parameters
    ----------
    indent : int
        The indentation level for display.

    Returns
    -------
    Clef
        The Clef instance itself.
    """
    print(" " * indent, self, sep="", file=file)
    return self

KeySignature

KeySignature(
    parent: Optional[EventGroup] = None,
    onset: float = 0.0,
    key_sig: int = 0,
)

Bases: Event

KeySignature is a zero-duration Event with key signature information.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    The containing object or None.

  • onset (float, default: 0.0 ) –

    The onset (start) time. An initial value of None might be assigned when the KeySignature is inserted into an EventGroup.

  • key_sig (int, default: 0 ) –

    An integer representing the number of sharps (if positive) and flats (if negative), e.g., -3 for Eb major or C minor.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (float) –

    The onset (start) time.

  • duration (float) –

    Always zero for this subclass.

  • key_sig (int) –

    An integer representing the number of sharps and flats.

Source code in amads/core/basics.py
1207
1208
1209
1210
def __init__(self, parent: Optional["EventGroup"] = None,
             onset: float = 0.0, key_sig: int = 0):
    super().__init__(parent=parent, onset=onset, duration=0)
    self.key_sig = key_sig

Attributes

onset property writable

onset: float

Retrieve the onset (start) time.

If the onset is None, raise an exception. (Events can have None onset times, but they must be set before retrieval. onsets that are None are automatically set when the Event is added to an EventGroup.)

Returns:

  • float | None

    The onset (start) time.

Raises:

  • ValueError

    If the onset time is not set (None).

units_are_seconds property

units_are_seconds: bool

Check if the times are in seconds.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in seconds. If not in a score, False is returned.

units_are_quarters property

units_are_quarters: bool

Check if the times are in quarters.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in quarters. If not in a score, False is returned.

offset property writable

offset: float

Retrieve the global offset (stop) time.

Returns:

  • float

    The global offset (stop) time.

part property

part: Optional[Part]

Retrieve the Part containing this event.

Returns:

  • Optional[Part]

    The Part containing this event or None if not found.

score property

score: Optional[Score]

Retrieve the Score containing this event, or self if it is a score.

Returns:

  • Optional[Score]

    The Score containing this event or None if not found.

staff property

staff: Optional[Staff]

Retrieve the Staff containing this event

Returns:

  • Optional[Staff]

    The Staff containing this event or None if not found.

measure property

measure: Optional[Measure]

Retrieve the Measure containing this event

Returns:

  • Optional[Measure]

    The Measure containing this event or None if not found.

Functions

set

set(property: str, value: Any) -> Event

Set a named property on this Event.

Every event can be extended with additional properties. Although Python objects are already extensible with new attributes, new attributes that are not set in __init__ confuse type checkers and other tools, so every Event has an info attribute as a dictionary where additional, application-specific information can be stored. The info attribute is None to save space until the first property is set, so you should use set and get methods and avoid writing event.info[property].

Parameters:

  • property (str) –

    The name of the property to set.

  • value (Any) –

    The value to assign to the property.

Returns:

  • Event

    returns this object (self)

Examples:

>>> note = Note()
>>> note.get("color", "no color")
'no color'
>>> _ = note.set("color", "red").set("harmonicity", 0.2)
>>> (note.has("color"), note.has("shape"))
(True, False)
>>> (note.get("color"), note.get("harmonicity"))
('red', 0.2)
Source code in amads/core/basics.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def set(self, property : str, value : Any) -> "Event":
    """Set a named property on this Event.

    Every event can be extended with additional properties. Although
    Python objects are already extensible with new attributes, new
    attributes that are not set in `__init__` confuse type checkers
    and other tools, so every `Event` has an `info` attribute as a
    dictionary where additional, application-specific information can
    be stored. The `info` attribute is `None` to save space until the
    first property is set, so you should use `set` and `get` methods
    and avoid writing `event.info[property]`.

    Parameters
    ----------
    property : str
        The name of the property to set.
    value : Any
        The value to assign to the property.

    Returns
    -------
    Event
        returns this object (self)

    Examples
    --------
    >>> note = Note()
    >>> note.get("color", "no color")
    'no color'
    >>> _ = note.set("color", "red").set("harmonicity", 0.2)
    >>> (note.has("color"), note.has("shape"))
    (True, False)
    >>> (note.get("color"), note.get("harmonicity"))
    ('red', 0.2)
    """
    if self.info is None:
        self.info = {}
    self.info[property] = value
    return self

get

get(property: str, default: Any = None) -> Any

Get the value of a property from this Event.

See set for more details.

Parameters:

  • property (str.) –

    The name of the property to get.

  • default (Any, default: None ) –

    The default value to return if the property is not found.

Returns:

  • Any

    The value of the specified property.

Source code in amads/core/basics.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def get(self, property : str, default : Any = None) -> Any:
    """Get the value of a property from this Event.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str.
        The name of the property to get.
    default : Any
        The default value to return if the property is not found.

    Returns
    -------
    Any
        The value of the specified property.
    """
    if self.info is None:
        return default
    return self.info.get(property, default)

has

has(property) -> bool

Check if the Event has a specific property.

See set for more details.

Parameters:

  • property (str) –

    The name of the property to check.

Returns:

  • bool

    True if the property exists, False otherwise.

Source code in amads/core/basics.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def has(self, property) -> bool:
    """Check if the Event has a specific property.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str
        The name of the property to check.

    Returns
    -------
    bool
        True if the property exists, False otherwise.
    """
    return (self.info is not None) and (property in self.info)

time_shift

time_shift(increment: float, content_only=False) -> Event

Change the onset by an increment.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

  • content_only (bool, default: False ) –

    This parameter is ignored. (See EventGroup.time_shift)

Returns:

  • Event

    The object. This method modifies the Event.

Source code in amads/core/basics.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def time_shift(self, increment: float, content_only=False) -> "Event":
    """
    Change the onset by an increment.

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).
    content_only : bool, optional
        This parameter is ignored. (See EventGroup.time_shift)
    Returns
    -------
    Event
        The object. This method modifies the `Event`.
    """
    self._onset += increment  # type: ignore
    return self

insert_copy_into

insert_copy_into(parent: Optional[EventGroup] = None) -> Event

Make a (mostly) deep copy of the Event and add to a new parent.

Pitch objects are considered immutable and are shared rather than copied.

Parameters:

  • parent (Optional(EventGroup), default: None ) –

    The copied Event will be a child of parent if not None. The parent is modified by this operation.

Returns:

  • Event

    A deep copy (except for parent and pitch) of the Event instance.

Source code in amads/core/basics.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def insert_copy_into(self,
                     parent: Optional["EventGroup"] = None) -> "Event":
    """
    Make a (mostly) deep copy of the `Event` and add to a new `parent`.

    `Pitch` objects are considered immutable and are shared rather
    than copied.

    Parameters
    ----------
    parent : Optional(EventGroup)
        The copied `Event` will be a child of `parent` if not `None`.
        The parent is modified by this operation.

    Returns
    -------
    Event
        A deep copy (except for parent and pitch) of the Event instance.
    """
    # remove link to parent to break link going up the tree
    # preventing deep copy from copying the entire tree
    original_parent = self.parent
    self.parent = None
    c = copy.deepcopy(self)  # deep copy of this event down to leaf nodes
    self.parent = original_parent  # restore link to parent
    if parent:
        parent.insert(c)
    return c

show

show(indent: int = 0, file: Optional[TextIO] = None) -> KeySignature

Display the KeySignature information.

Parameters:

  • indent (int, default: 0 ) –

    The indentation level for display.

Returns:

Source code in amads/core/basics.py
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
def show(self, indent: int = 0,
         file: Optional[TextIO] = None) -> "KeySignature":
    """Display the KeySignature information.

    Parameters
    ----------
    indent : int
        The indentation level for display.

    Returns
    -------
    KeySignature
        The KeySignature instance itself.
    """
    print(" " * indent, self, sep="", file=file)
    return self

EventGroup

EventGroup(
    parent: Optional[EventGroup],
    onset: Optional[float],
    duration: Optional[float],
    content: Optional[list[Event]],
)

Bases: Event

A collection of Event objects. (An abstract class.)

Use one of the subclasses: Score, Part, Staff, Measure or Chord.

Normally, you create any EventGroup (Chord, Measure, Staff, Part, Score) with no content, then add content. You can add content in bulk by simply setting the content attribute to a list of Events whose parent attributes have been set to the EventGroup. You can also add one event at a time, by calling the EventGroup's insert method. (This will change the event parent from None to the group.) It is recommended to specify all onsets and durations explicitly, including the onset of the group itself.

Alternatively, you can provide content when the group is constructed. Chord, Measure, Staff, Part, and Score all have *args parameters so that you can write something like:

Score(Part(Staff(Measure(Note(...), Note(...)),
Measure(Note(...), Note(...)))))

In this case, it is recommended that you leave the onsets of content and chord unknown (None, the default). Then, as each event or group becomes content for a parent, the onsets will be set automatically, organizing events sequentially (in Measures and Staves) or concurrently (in Chords, Parts, Scores).

The use of unknown (None) onsets is offered as a convenience for simple cases. The main risk is that onsets are considered to be relative to the group onset if the group onset is not known. E.g. if onsets are specified within the content of an EventGroup (Chord, Measure, Staff, Part, Score) but the group onset is unknown (None), and then you assign (or a parent assigns) an onset value to the group, the content onsets (even “known” ones) will all be shifted by the assigned onset. This happens only when changing an onset from None to a number. Subsequent changes to the group onset will not adjust the content onsets, which are considered absolute times once the group onset is known.

EventGroup is subclassed to form Concurrence and Sequence. A Concurrence defaults to placing all events at onset 0, while Sequence defaults to placing events sequentially such that event inter-onset intervals are their durations. The EventGroup behaves like Concurrence, so the Concurrence implementation is minimal, while the Sequence needs several methods to override EventGroup behavior to support sequential behavior.

Parameters:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • onset (float | None) –

    The onset (start) time.

  • duration (Optional[float]) –

    The duration in quarters or seconds.

  • content (Optional[list]) –

    A list of Event objects to be added to the group. The parent of each Event is set to this EventGroup, and it is an error if any Event already has a parent.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (Optional[float]) –

    The onset (start) time.

  • duration (float) –

    The duration in quarters or seconds.

  • content (list[Event]) –

    Elements contained within this collection.

Source code in amads/core/basics.py
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
def __init__(self, parent: Optional["EventGroup"],
             onset: Optional[float], duration: Optional[float],
             content: Optional[list[Event]]):
    # pass 0 for duration because Event constructor wants a number,
    # but we will set duration later based on duration parameter or
    # based on content if duration is None:
    super().__init__(parent=parent, onset=onset, duration=0)
    if content is None:
        content = []
    # member_onset is the default onset for children
    member_onset = 0 if onset is None else onset
    prev_onset = member_onset
    for elem in content:  # check and set parents
        if elem.parent and elem.parent != self:
            raise ValueError("Event already has a (different) parent")
        elem.parent = self  # type: ignore
        if elem._onset is None:
            elem.onset = member_onset
        elif elem._onset < prev_onset:
            raise ValueError("content is not in onset time order")
        # # Rounding can cause notes to get re-ordered when they should
        # # be simultaneous. This finds notes that are within 1 usec and
        # # overwrites the onsets after the first note so they are all
        # # equal. Then get_sorted_notes() will sort these by pitch:
        # elif elem._onset < prev_onset + 1.0e-6:
        #     elem._onset = prev_onset
        else:
            prev_onset = elem._onset

    if duration is None:  # compute duration from content
        max_offset = 0
        for elem in content:
            max_offset = max(max_offset, elem.offset)
        duration = max_offset
        if onset:
            duration = max_offset - onset
    self.duration = duration  # type: ignore (duration is now number)
    self.content = content

Attributes

units_are_seconds property

units_are_seconds: bool

Check if the times are in seconds.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in seconds. If not in a score, False is returned.

units_are_quarters property

units_are_quarters: bool

Check if the times are in quarters.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in quarters. If not in a score, False is returned.

offset property writable

offset: float

Retrieve the global offset (stop) time.

Returns:

  • float

    The global offset (stop) time.

part property

part: Optional[Part]

Retrieve the Part containing this event.

Returns:

  • Optional[Part]

    The Part containing this event or None if not found.

score property

score: Optional[Score]

Retrieve the Score containing this event, or self if it is a score.

Returns:

  • Optional[Score]

    The Score containing this event or None if not found.

staff property

staff: Optional[Staff]

Retrieve the Staff containing this event

Returns:

  • Optional[Staff]

    The Staff containing this event or None if not found.

measure property

measure: Optional[Measure]

Retrieve the Measure containing this event

Returns:

  • Optional[Measure]

    The Measure containing this event or None if not found.

onset property writable

onset: float

Retrieve the onset (start) time.

If the onset is None, raise an exception. (Events can have None onset times, but they must be set before retrieval. onsets that are None are automatically set when the Event is added to an EventGroup.)

Returns:

  • float

    The onset (start) time.

Raises:

  • ValueError

    If the onset time is not set (None).

Functions

set

set(property: str, value: Any) -> Event

Set a named property on this Event.

Every event can be extended with additional properties. Although Python objects are already extensible with new attributes, new attributes that are not set in __init__ confuse type checkers and other tools, so every Event has an info attribute as a dictionary where additional, application-specific information can be stored. The info attribute is None to save space until the first property is set, so you should use set and get methods and avoid writing event.info[property].

Parameters:

  • property (str) –

    The name of the property to set.

  • value (Any) –

    The value to assign to the property.

Returns:

  • Event

    returns this object (self)

Examples:

>>> note = Note()
>>> note.get("color", "no color")
'no color'
>>> _ = note.set("color", "red").set("harmonicity", 0.2)
>>> (note.has("color"), note.has("shape"))
(True, False)
>>> (note.get("color"), note.get("harmonicity"))
('red', 0.2)
Source code in amads/core/basics.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def set(self, property : str, value : Any) -> "Event":
    """Set a named property on this Event.

    Every event can be extended with additional properties. Although
    Python objects are already extensible with new attributes, new
    attributes that are not set in `__init__` confuse type checkers
    and other tools, so every `Event` has an `info` attribute as a
    dictionary where additional, application-specific information can
    be stored. The `info` attribute is `None` to save space until the
    first property is set, so you should use `set` and `get` methods
    and avoid writing `event.info[property]`.

    Parameters
    ----------
    property : str
        The name of the property to set.
    value : Any
        The value to assign to the property.

    Returns
    -------
    Event
        returns this object (self)

    Examples
    --------
    >>> note = Note()
    >>> note.get("color", "no color")
    'no color'
    >>> _ = note.set("color", "red").set("harmonicity", 0.2)
    >>> (note.has("color"), note.has("shape"))
    (True, False)
    >>> (note.get("color"), note.get("harmonicity"))
    ('red', 0.2)
    """
    if self.info is None:
        self.info = {}
    self.info[property] = value
    return self

get

get(property: str, default: Any = None) -> Any

Get the value of a property from this Event.

See set for more details.

Parameters:

  • property (str.) –

    The name of the property to get.

  • default (Any, default: None ) –

    The default value to return if the property is not found.

Returns:

  • Any

    The value of the specified property.

Source code in amads/core/basics.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def get(self, property : str, default : Any = None) -> Any:
    """Get the value of a property from this Event.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str.
        The name of the property to get.
    default : Any
        The default value to return if the property is not found.

    Returns
    -------
    Any
        The value of the specified property.
    """
    if self.info is None:
        return default
    return self.info.get(property, default)

has

has(property) -> bool

Check if the Event has a specific property.

See set for more details.

Parameters:

  • property (str) –

    The name of the property to check.

Returns:

  • bool

    True if the property exists, False otherwise.

Source code in amads/core/basics.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def has(self, property) -> bool:
    """Check if the Event has a specific property.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str
        The name of the property to check.

    Returns
    -------
    bool
        True if the property exists, False otherwise.
    """
    return (self.info is not None) and (property in self.info)

insert_copy_into

insert_copy_into(parent: Optional[EventGroup] = None) -> Event

Make a (mostly) deep copy of the Event and add to a new parent.

Pitch objects are considered immutable and are shared rather than copied.

Parameters:

  • parent (Optional(EventGroup), default: None ) –

    The copied Event will be a child of parent if not None. The parent is modified by this operation.

Returns:

  • Event

    A deep copy (except for parent and pitch) of the Event instance.

Source code in amads/core/basics.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def insert_copy_into(self,
                     parent: Optional["EventGroup"] = None) -> "Event":
    """
    Make a (mostly) deep copy of the `Event` and add to a new `parent`.

    `Pitch` objects are considered immutable and are shared rather
    than copied.

    Parameters
    ----------
    parent : Optional(EventGroup)
        The copied `Event` will be a child of `parent` if not `None`.
        The parent is modified by this operation.

    Returns
    -------
    Event
        A deep copy (except for parent and pitch) of the Event instance.
    """
    # remove link to parent to break link going up the tree
    # preventing deep copy from copying the entire tree
    original_parent = self.parent
    self.parent = None
    c = copy.deepcopy(self)  # deep copy of this event down to leaf nodes
    self.parent = original_parent  # restore link to parent
    if parent:
        parent.insert(c)
    return c

ismonophonic

ismonophonic() -> bool

Determine if content is monophonic (non-overlapping notes).

A monophonic list of notes has no overlapping notes (e.g., chords). Serves as a helper function for ismonophonic and parts_are_monophonic.

Returns:

  • bool

    True if the list of notes is monophonic, False otherwise.

Source code in amads/core/basics.py
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
def ismonophonic(self) -> bool:
    """
    Determine if content is monophonic (non-overlapping notes).

    A monophonic list of notes has no overlapping notes (e.g., chords).
    Serves as a helper function for `ismonophonic` and
    `parts_are_monophonic`.

    Returns
    -------
    bool
        True if the list of notes is monophonic, False otherwise.
    """
    prev = None
    notes = self.list_all(Note)
    # Sort the notes by start time
    notes.sort(key=lambda note: note.onset)
    # Check for overlaps
    for note in notes:
        if prev:
            # 0.01 is to prevent precision errors when comparing floats
            if note.onset - prev.offset < -0.01:
                return False
        prev = note
    return True

time_shift

time_shift(increment: float, content_only: bool = False) -> EventGroup

Change the onset by an increment, affecting all content.

If content_only is true, preserves EventGroup times (Score, Part, Staff, but not Chord or Measure) and shifts only the content (recursively). Otherwise, shifts this container and all content by the increment. Container onsets (recursively) are not allowed to become negative, so the onset time is set to zero if the increment would make it negative. However, even if the onset is is not shifted by increment, time_shift is still applied recursively to the content, and non-EventGroup events (e.g., Notes) are allowed to have negative onsets, even if this may not be well-defined for all AMADS operations.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

  • content_only (bool, default: False ) –

    If true, preserves this container's time and shifts only the content.

Returns:

  • Event

    The object. This method modifies the EventGroup.

Raises:

  • ValueError

    If the EventGroup has an unknown (None) onset and content_only is false.

Source code in amads/core/basics.py
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
def time_shift(self, increment: float,
               content_only: bool = False) -> "EventGroup":
    """
    Change the onset by an increment, affecting all content.

    If content_only is true, preserves EventGroup times (Score, Part,
    Staff, but *not* Chord or Measure) and shifts only the content
    (recursively). Otherwise, shifts this container and all content by the
    increment. Container onsets (recursively) are not allowed to become
    negative, so the onset time is set to zero if the increment would
    make it negative. However, even if the onset is is not shifted by
    increment, time_shift is still applied recursively to the content,
    and non-EventGroup events (e.g., Notes) are allowed to have negative
    onsets, even if this may not be well-defined for all AMADS operations.

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).
    content_only: bool
        If true, preserves this container's time and shifts only
        the content.

    Returns
    -------
    Event
        The object. This method modifies the `EventGroup`.

    Raises
    ------
    ValueError
        If the EventGroup has an unknown (None) onset and
        content_only is false.
    """
    # note that Chord and Measures are special cases
    if not content_only or isinstance(self, (Chord, Measure)):
        if self._onset is None:
            raise ValueError(
                    "Cannot shift time of EventGroup with unknown onset")
        self._onset = max(0.0, self._onset + increment)
    for elem in self.content:
        elem.time_shift(increment, content_only)
    return self

insert_emptycopy_into

insert_emptycopy_into(
    parent: Optional[EventGroup] = None,
) -> EventGroup

Create a deep copy of the EventGroup except for content.

A new parent is provided as an argument and the copy is inserted into this parent. This method is useful for copying an EventGroup without copying its content. See also insert_copy_into to copy an EventGroup with its content into a new parent.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    The new parent to insert the copied Event into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with the new parent (if any) and no content.

Source code in amads/core/basics.py
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
def insert_emptycopy_into(self, 
            parent: Optional["EventGroup"] = None) -> "EventGroup":
    """Create a deep copy of the EventGroup except for content.

    A new parent is provided as an argument and the copy is inserted
    into this parent. This method is  useful for copying an
    EventGroup without copying its content.  See also
    [insert_copy_into][amads.core.basics.Event.insert_copy_into] to
    copy an EventGroup *with* its content into a new parent.

    Parameters
    ----------
    parent : Optional[EventGroup]
        The new parent to insert the copied Event into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with the new parent
        (if any) and no content.
    """
    # rather than customize __deepcopy__, we "hide" the content to avoid
    # copying it. Then we restore it after copying and fix parent.
    original_content = self.content
    self.content = []
    c = self.insert_copy_into(parent)
    self.content = original_content
    return c  #type: ignore (c will always be an EventGroup)

expand_chords

expand_chords(parent: Optional[EventGroup] = None) -> EventGroup

Replace chords with the multiple notes they contain.

Returns a deep copy with no parent unless parent is provided. Normally, you will call score.expand_chords() which returns a deep copy of Score with notes moved from each chord to the copy of the chord's parent (a Measure or a Part). The parent parameter is primarily for internal use when expand_chords is called recursively on score content.

Parameters:

  • parent (EventGroup, default: None ) –

    The new parent to insert the copied EventGroup into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with all Chord instances expanded.

Source code in amads/core/basics.py
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
def expand_chords(self,
                  parent: Optional["EventGroup"] = None) -> "EventGroup":
    """Replace chords with the multiple notes they contain.

    Returns a deep copy with no parent unless parent is provided.
    Normally, you will call `score.expand_chords()` which returns a deep
    copy of Score with notes moved from each chord to the copy of the
    chord's parent (a Measure or a Part). The parent parameter is 
    primarily for internal use when `expand_chords` is called recursively
    on score content.

    Parameters
    ----------
    parent : EventGroup
        The new parent to insert the copied EventGroup into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with all
        Chord instances expanded.
    """
    group = self.insert_emptycopy_into(parent)
    for item in self.content:
        if isinstance(item, Chord):
            for note in item.content:  # expand chord
                note.insert_copy_into(group)
        if isinstance(item, EventGroup):
            item.expand_chords(group)  # recursion for deep copy/expand
        else:
            item.insert_copy_into(group)  # deep copy non-EventGroup
    return group

find_all

find_all(elem_type: Type[Event]) -> Generator[Event, None, None]

Find all instances of a specific type within the EventGroup.

Assumes that objects of type elem_type are not nested within other objects of the same type. (The first elem_type encountered in a depth-first enumeration is returned without looking at any children in its content).

Parameters:

  • elem_type (Type[Event]) –

    The type of event to search for.

Yields:

  • Event

    Instances of the specified type found within the EventGroup.

Source code in amads/core/basics.py
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
def find_all(self, elem_type: Type[Event]) -> Generator[Event, None, None]:
    """Find all instances of a specific type within the EventGroup.

    Assumes that objects of type `elem_type` are not nested within
    other objects of the same type. (The first `elem_type` encountered
    in a depth-first enumeration is returned without looking at any
    children in its `content`).

    Parameters
    ----------
    elem_type : Type[Event]
        The type of event to search for.

    Yields
    -------
    Event
        Instances of the specified type found within the EventGroup.
    """
    # Algorithm: depth-first enumeration of EventGroup content.
    # If elem_types are nested, only the top-level elem_type is
    # returned since it is found first, and the content is not
    # searched. This makes it efficient, e.g., to search for
    # Parts in a Score without enumerating all Notes within.
    for elem in self.content:
        if isinstance(elem, elem_type):
            yield elem
        elif isinstance(elem, EventGroup):
            yield from elem.find_all(elem_type)

get_sorted_notes

get_sorted_notes(has_ties: bool = True) -> List[Note]

Return a list of sorted notes with merged ties.

This should generally be called on Parts and Scores since in all other EventGroups, Events are in time order and Notes retrieved with find_all() or list_all() are in time order. However, get_sorted_notes also sorts notes into increasing pitch (keynum) where note onsets are equal.

Parameters:

  • has_ties (bool, default: True ) –

    If True (default), copy the score, merge the ties, and return a list of these merged copies. If False, assume there are no ties and return a list of original notes.

Raises:

  • ValueError

    If has_ties is False, but a tie is encountered.

Returns:

  • list(Note)

    a list of sorted notes with merged ties

Source code in amads/core/basics.py
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
def get_sorted_notes(self, has_ties: bool = True) -> List[Note]:
    """Return a list of sorted notes with merged ties.

    This should generally be called on Parts and Scores since
    in all other EventGroups, Events are in time order and
    Notes retrieved with `find_all()` or `list_all()` are in
    time order. However, `get_sorted_notes` *also* sorts notes
    into increasing pitch (`keynum`) where note onsets are equal.

    Parameters
    ----------
    has_ties: bool
        If True (default), copy the score, merge the ties, and
        return a list of these merged copies. If False, assume
        there are no ties and return a list of original notes.

    Raises
    ------
    ValueError
        If has_ties is False, but a tie is encountered.

    Returns
    -------
    list(Note)
        a list of sorted notes with merged ties
    """
    if has_ties:
        # after flatten, score will have one Part with all Notes:
        return self.flatten(collapse=True).content[0].content  # type: ignore
    else:
        notes : List[Note] = cast(List[Note], self.list_all(Note))
        for note in notes:
            if note.tie is not None:
                raise ValueError(
                        "tie found by get_sorted_notes with has_ties=False")
        notes.sort(key=lambda x: (x.onset, x.pitch))
        return notes

has_instanceof

has_instanceof(the_class: Type[Event]) -> bool

Test if EventGroup contains any instances of the_class.

Parameters:

  • the_class (Type[Event]) –

    The class type to check for.

Returns:

  • bool

    True iff the EventGroup contains an instance of the_class.

Source code in amads/core/basics.py
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
def has_instanceof(self, the_class: Type[Event]) -> bool:
    """Test if EventGroup contains any instances of `the_class`.

    Parameters
    ----------
    the_class : Type[Event]
        The class type to check for.

    Returns
    -------
    bool
        True iff the EventGroup contains an instance of the_class.
    """
    instances = self.find_all(the_class)
    # if there are no instances (of the_class), next will return "empty":
    return next(instances, "empty") != "empty"

has_rests

has_rests() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Rest objects.

Returns:

  • bool

    True iff the EventGroup contains any Rest objects.

Source code in amads/core/basics.py
1787
1788
1789
1790
1791
1792
1793
1794
1795
def has_rests(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any `Rest` objects.

    Returns
    -------
    bool
        True iff the EventGroup contains any Rest objects.
    """
    return self.has_instanceof(Rest)

has_chords

has_chords() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Chord objects.

Returns:

  • bool

    True iff the EventGroup contains any Chord objects.

Source code in amads/core/basics.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
def has_chords(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any Chord objects.

    Returns
    -------
    bool
        True iff the EventGroup contains any Chord objects.
    """
    return self.has_instanceof(Chord)

has_ties

has_ties() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any tied notes.

Returns:

  • bool

    True iff the EventGroup contains any tied notes.

Source code in amads/core/basics.py
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
def has_ties(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any tied notes.

    Returns
    -------
    bool
        True iff the EventGroup contains any tied notes.
    """
    notes = self.find_all(Note)
    for note in notes:
        if note.tie:
            return True
    return False

has_measures

has_measures() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Measures.

Returns:

  • bool

    True iff the EventGroup contains any Measure objects.

Source code in amads/core/basics.py
1824
1825
1826
1827
1828
1829
1830
1831
1832
def has_measures(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any Measures.

    Returns
    -------
    bool
        True iff the EventGroup contains any Measure objects.
    """
    return self.has_instanceof(Measure)

inherit_duration

inherit_duration() -> EventGroup

Set the duration of this EventGroup according to maximum offset.

The duration is set to the maximum offset (end) time of the children. If the EventGroup is empty, the duration is set to 0. This method modifies this EventGroup instance.

Returns:

  • EventGroup

    The EventGroup instance (self) with updated duration.

Source code in amads/core/basics.py
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
def inherit_duration(self) -> "EventGroup":
    """Set the duration of this EventGroup according to maximum offset.

    The `duration` is set to the maximum offset (end) time of the
    children. If the EventGroup is empty, the duration is set to 0.
    This method modifies this `EventGroup` instance.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with updated duration.
    """
    onset = 0 if self._onset == None else self._onset
    max_offset = onset
    for elem in self.content:
        max_offset = max(max_offset, elem.offset)
    self.duration = max_offset - onset

    return self

insert

insert(event: Event) -> EventGroup

Insert an event.

Sets the parent of event to this EventGroup and makes event be a member of this EventGroup.content. No changes are made to event.onset or self.duration. Insert event in content just before the first element with a greater onset. The method modifies this object (self).

Parameters:

  • event (Event) –

    The event to be inserted.

Returns:

  • EventGroup

    The EventGroup instance (self) with the event inserted.

Raises:

  • ValueError

    If event._onset is None (it must be a number)

Caution Regarding Zero-Duration Event Order

If you have note N with non-zero duration and, at the same time, a grace note G with zero duration, the notes will be ordered according to when they are inserted. So if you insert N and then G, then N will be placed before G. See io.pt_import.py, where this case is dealt with.

Source code in amads/core/basics.py
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
def insert(self, event: Event) -> "EventGroup":
    """Insert an event.

    Sets the `parent` of `event` to this `EventGroup` and makes `event`
    be a member of this `EventGroup.content`. No changes are made to
    `event.onset` or `self.duration`. Insert `event` in `content` just
    before the first element with a greater onset. The method modifies
    this object (self).

    Parameters
    ----------
    event : Event
        The event to be inserted.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with the event inserted.

    Raises
    ------
    ValueError
        If event._onset is None (it must be a number)

    Caution Regarding Zero-Duration Event Order
    -------------------------------------------
    If you have note N with non-zero duration and, at the same
    time, a grace note G with zero duration, the notes will be
    ordered according to when they are inserted. So if you insert
    N and then G, then N will be placed *before* G. See
    io.pt_import.py, where this case is dealt with.
    """

    assert not event.parent
    if event._onset is None:  # must be a number
        raise ValueError(f"event's _onset attribute must be a number")
    atend = self.last()
    if atend and event.onset < atend.onset:
        # search in reverse from end
        i = len(self.content) - 2
        while i >= 0 and self.content[i].onset > event.onset:
            i -= 1
        # now i is either -1 or content[i] <= event.onset, so
        # insert event at content[i+1]
        self.content.insert(i + 1, event)
    else:  # simply append at the end of content:
        self.content.append(event)
    event.parent = self
    return self

last

last() -> Optional[Event]

Retrieve the last event in the content list.

Because the content list is sorted by onset, the returned Event is simply the last element of content, but not necessarily the event with the greatest offset.

Returns:

  • Optional[Event]

    The last event in the content list or None if the list is empty.

Source code in amads/core/basics.py
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
def last(self) -> Optional[Event]:
    """Retrieve the last event in the content list.

    Because the `content` list is sorted by `onset`, the returned
    `Event` is simply the last element of `content`, but not
    necessarily the event with the greatest *`offset`*.

    Returns
    -------
    Optional[Event]
        The last event in the content list or None if the list is empty.
    """
    return self.content[-1] if len(self.content) > 0 else None

list_all

list_all(elem_type: Type[Event]) -> list[Event]

Find all instances of a specific type within the EventGroup.

Assumes that objects of type elem_type are not nested within other objects of the same type. See also find_all, which returns a generator instead of a list.

Parameters:

  • elem_type (Type[Event]) –

    The type of event to search for.

Returns:

  • list[Event]

    A list of all instances of the specified type found within the EventGroup.

Source code in amads/core/basics.py
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
def list_all(self, elem_type: Type[Event]) -> list[Event]:
    """Find all instances of a specific type within the EventGroup.

    Assumes that objects of type `elem_type` are not nested within
    other objects of the same type.  See also
    [find_all][amads.core.basics.EventGroup.find_all], which returns
    a generator instead of a list.

    Parameters
    ----------
    elem_type : Type[Event]
        The type of event to search for.

    Returns
    -------
    list[Event]
        A list of all instances of the specified type found
        within the EventGroup.
    """
    return list(self.find_all(elem_type))

merge_tied_notes

merge_tied_notes(
    parent: Optional[EventGroup] = None, ignore: list[Note] = []
) -> EventGroup

Create a new EventGroup with tied notes replaced by single notes.

If ties cross staffs, the replacement is placed in the staff of the first note in the tied sequence. Insert the new EventGroup into parent.

Ordinarily, this method is called on a Score with no parameters. The parameters are used when Score.merge_tied_notes() calls this method recursively on EventGroups within the Score such as Parts and Staffs.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    Where to insert the result.

  • ignore (list[Note], default: [] ) –

    This parameter is used internally. Caller should not use this parameter.

Returns:

  • EventGroup

    A copy with tied notes replaced by equivalent single notes.

Source code in amads/core/basics.py
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
def merge_tied_notes(self, parent: Optional["EventGroup"] = None,
                     ignore: list[Note] = []) -> "EventGroup":
    """Create a new `EventGroup` with tied notes replaced by single notes.

    If ties cross staffs, the replacement is placed in the staff of the
    first note in the tied sequence. Insert the new `EventGroup` into
    `parent`.

    Ordinarily, this method is called on a Score with no parameters. The
    parameters are used when `Score.merge_tied_notes()` calls this method
    recursively on `EventGroup`s within the Score such as `Part`s and
    `Staff`s.

    Parameters
    ----------
    parent: Optional(EventGroup)
        Where to insert the result.

    ignore: Optional(list[Note])
        This parameter is used internally. Caller should not use
        this parameter.

    Returns
    -------
    EventGroup
        A copy with tied notes replaced by equivalent single notes.
    """
    # Algorithm: Find all notes, removing tied notes and updating
    # duration when ties are found. These tied notes are added to
    # ignore so they can be skipped when they are encountered.

    group = self.insert_emptycopy_into(parent)
    for event in self.content:
        if isinstance(event, Note):
            if event in ignore:  # do not copy tied notes into group;
                if event.tie:
                    ignore.append(event.tie)  # add tied note to ignore
                # We will not see this note again, so
                # we can also remove it from ignore. Removal is expensive
                # but it could be worse for ignore to grow large when there
                # are many ties since we have to search it entirely once
                # per note. An alternate representation might be a set to
                # make searching fast.
                ignore.remove(event)
            else:
                if event.tie:
                    tied_note = event.tie  # save the tied-to note
                    event.tie = None  # block the copy
                    ignore.append(tied_note)
                    # copy note into group:
                    event_copy = event.insert_copy_into(group)
                    event.tie = tied_note  # restore original event
                    # this is subtle: event.tied_duration (a property) will
                    # sum up durations of all the tied notes. Since
                    # event_copy is not tied, the sum of durations is
                    # stored on that one event_copy:
                    event_copy.duration = event.tied_duration
                else:  # put the untied note into group
                    event.insert_copy_into(group)
        elif isinstance(event, EventGroup):
            event.merge_tied_notes(group, ignore)
        else:
            event.insert_copy_into(group)  # simply copy to new parent
    return group

pack

pack(onset: float = 0.0, sequential: bool = False) -> float

Adjust the content to onsets starting with the onset parameter.

By default onsets are set to onset and the duration of self is set to the maximum duration of the content. pack() works recursively on elements that are EventGroups. Setting sequential to True implements sequential packing, where events are placed one after another.

Parameters:

  • onset (float, default: 0.0 ) –

    The onset (start) time for this object.

Returns:

  • float

    duration of self

Source code in amads/core/basics.py
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
def pack(self, onset: float = 0.0, sequential : bool = False) -> float:
    """Adjust the content to onsets starting with the onset parameter.

    By default onsets are set to `onset` and the duration of self is set to
    the maximum duration of the content. pack() works recursively on
    elements that are EventGroups. Setting sequential to True implements
    sequential packing, where events are placed one after another.

    Parameters
    ----------
    onset : float
        The onset (start) time for this object.

    Returns
    -------
    float
        duration of self
    """
    self.onset = onset
    self.duration = 0
    for elem in self.content:
        elem.onset = onset
        if isinstance(elem, EventGroup):   # either Sequence or Concurrence
            elem.duration = elem.pack(onset)  #type: ignore
        if sequential:
            onset += elem.duration
        else:
            self.duration = max(self.duration, elem.duration)
    if sequential:
        self.duration = onset - self.onset
    return self.duration

quantize

quantize(divisions: int) -> EventGroup

Align onsets and durations to a rhythmic grid.

Assumes time units are quarters. (See Score.convert_to_quarters.)

Modify all times and durations to a multiple of divisions per quarter note, e.g., 4 for sixteenth notes. Onsets and offsets are moved to the nearest quantized time. Any resulting duration change is less than one quantum, but not necessarily less than 0.5 quantum, since the onset and offset can round in opposite directions by up to 0.5 quantum each. Any non-zero duration that would quantize to zero duration gets a duration of one quantum since zero duration is almost certainly going to cause notation and visualization problems.

Special cases for zero duration:

  1. If the original duration is zero as in metadata or possibly grace notes, we preserve that.
  2. If a tied note duration quantizes to zero, we remove the tied note entirely provided some other note in the tied sequence has non-zero duration. If all tied notes quantize to zero, we keep the first one and set its duration to one quantum.

This method modifies this EventGroup and all its content in place.

Note that there is no way to specify "sixteenths or eighth triplets" because 6 would not allow sixteenths and 12 would admit sixteenth triplets. Using tuples as in Music21, e.g., (4, 3) for this problem creates another problem: if quantization is to time points 1/4, 1/3, then the difference is 1/12 or a thirty-second triplet. If the quantization is applied to durations, then you could have 1/4 + 1/3 = 7/12, and the remaining duration in a single beat would be 5/12, which is not expressible as sixteenths, eighth triplets or any tied combination.

Parameters:

  • divisions (int) –

    The number of divisions per quarter note, e.g., 4 for sixteenths, to control quantization.

Returns:

  • EventGroup

    The EventGroup instance (self) with (modified in place) quantized times.

Source code in amads/core/basics.py
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
def quantize(self, divisions: int) -> "EventGroup":
    """Align onsets and durations to a rhythmic grid.

    Assumes time units are quarters. (See [Score.convert_to_quarters](
            basics.md#amads.core.basics.Score.convert_to_quarters).)

    Modify all times and durations to a multiple of divisions
    per quarter note, e.g., 4 for sixteenth notes. Onsets and offsets
    are moved to the nearest quantized time. Any resulting duration
    change is less than one quantum, but not necessarily less than
    0.5 quantum, since the onset and offset can round in opposite
    directions by up to 0.5 quantum each. Any non-zero duration that would
    quantize to zero duration gets a duration of one quantum since
    zero duration is almost certainly going to cause notation and
    visualization problems.

    Special cases for zero duration:

    1. If the original duration is zero as in metadata or possibly
           grace notes, we preserve that.
    2. If a tied note duration quantizes to zero, we remove the
           tied note entirely provided some other note in the tied
           sequence has non-zero duration. If all tied notes quantize
           to zero, we keep the first one and set its duration to
           one quantum.

    This method modifies this EventGroup and all its content in place.

    Note that there is no way to specify "sixteenths or eighth triplets"
    because 6 would not allow sixteenths and 12 would admit sixteenth
    triplets. Using tuples as in Music21, e.g., (4, 3) for this problem
    creates another problem: if quantization is to time points 1/4, 1/3,
    then the difference is 1/12 or a thirty-second triplet. If the
    quantization is applied to durations, then you could have 1/4 + 1/3
    = 7/12, and the remaining duration in a single beat would be 5/12,
    which is not expressible as sixteenths, eighth triplets or any tied
    combination.

    Parameters
    ----------
    divisions : int
        The number of divisions per quarter note, e.g., 4 for
        sixteenths, to control quantization.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with (modified in place) 
        quantized times.
    """

    super()._quantize(divisions)
    # iterating through content is tricky because we may delete a
    # Note, shifting the content:
    i = 0
    while i < len(self.content):
        event = self.content[i]
        event._quantize(divisions)
        if event == self.content[i]:
            i += 1
        # otherwise, we deleted event so the next event to
        # quantize is at index i; don't incremenet i
    return self

remove

remove(element: Event) -> EventGroup

Remove an element from the content list.

The method modifies this object (self).

Parameters:

  • element (Event) –

    The event to be removed.

Returns:

  • EventGroup

    The EventGroup instance (self) with the element removed. The returned value is not a copy.

Source code in amads/core/basics.py
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
def remove(self, element: Event) -> "EventGroup":
    """Remove an element from the content list. 

    The method modifies this object (self).

    Parameters
    ----------
    element : Event
        The event to be removed.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with the element removed.
        The returned value is not a copy.
    """
    self.content.remove(element)
    element.parent = None
    return self

remove_rests

remove_rests(parent: Union[EventGroup, None] = None) -> EventGroup

Remove all Rest objects from content.

Returns a deep copy with no parent unless parent is provided.

Parameters:

  • parent (EventGroup, default: None ) –

    The new parent to insert the copied Event into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with all Rest objects removed.

Source code in amads/core/basics.py
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
def remove_rests(self, parent: Union["EventGroup", 
                                     None] = None) -> "EventGroup":
    """Remove all Rest objects from content.

    Returns a deep copy with no parent unless parent is provided.

    Parameters
    ----------
    parent : EventGroup
        The new parent to insert the copied Event into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with all Rest
        objects removed.
    """
    # implementation detail: when called without argument, remove_rests
    # makes a deep copy of the subtree and returns the copy without a
    # parent. remove_rests calls itself recursively *with* a parameter
    # indicating that the subtree copy should be inserted into a
    # parent which is the new copy at the next level up. Of course,
    # we check for and ignore Rests so they are never copied.
    group = self.insert_emptycopy_into(parent)
    for item in self.content:
        if isinstance(item, Rest):
            continue  # skip the Rests while making deep copy
        if isinstance(item, EventGroup):
            item.remove_rests(group)  # recursion for deep copy
        else:
            item.insert_copy_into(group)  # deep copy non-EventGroup
    return group

show

show(indent: int = 0, file: Optional[TextIO] = None) -> EventGroup

Print the EventGroup information.

Parameters:

  • indent (int, default: 0 ) –

    The indentation level for display.

Returns:

Source code in amads/core/basics.py
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
def show(self, indent: int = 0,
        file: Optional[TextIO] = None) -> "EventGroup":
    """Print the EventGroup information.

    Parameters
    ----------
    indent : int
        The indentation level for display.

    Returns
    -------
    EventGroup
        The EventGroup instance itself.
    """
    print(" " * indent, self, sep="", file=file)
    for elem in self.content:
        elem.show(indent + 4, file=file)  # type: ignore (show exists)
    return self

measure_times

measure_times(n: int) -> tuple[float, float]

Return the start and end times of measure n.

Parameters:

  • n (int) –

    The 0-based measure number.

Returns:

  • tuple(float, float)

    A tuple containing the start and end times of measure n. Measure 0 is the first measure. Units are the same as the score's time units.

Raises:

  • ValueError

    If there is no measure with number n.

Source code in amads/core/basics.py
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
def measure_times(self, n: int) -> tuple[float, float]:
    """Return the start and end times of measure n.

    Parameters
    ----------
    n : int
        The 0-based measure number.

    Returns
    -------
    tuple(float, float)
        A tuple containing the start and end times of measure n.
        Measure 0 is the first measure.  Units are the same as the
        score's time units.

    Raises
    ------
    ValueError
        If there is no measure with number n.
    """
    # Algorithm: For each Staff, linear search for nth Measure, returning
    # the onset and offset of the first one found.
    for staff in self.find_all(Staff):
        staff = cast(Staff, staff)
        for i, measure in enumerate(staff.find_all(Measure)):
            if i == n:
                return (measure.onset, measure.offset)
    raise ValueError(f"measure {n} not found")

slice

slice(
    start: float,
    end: float,
    units: str = "quarters",
    mode: str = "onsets",
    truncate: str = "keep",
    shift: bool = False,
    min_duration: float = 0.05,
) -> EventGroup

Create a new Score containing the content between start and end.

Typically, this method is called on a Score to create a new Score, but it works on any Sequence as long as the sequence is part of a Score.

If self has Measures, units must be "measures" or "bars", the start and end parameters are interpreted as 0-based measure numbers, and the result will therefore contain whole measures. It is assumed that notes are tied across measure boundaries. The result will contain only the parts of tied notes that are within the specified measures, excluding measure numbered by end.

For any units besides "measures" or "bars", the score must be flat. Notes that extend beyond the start or end time are included in the result unless the truncate parameter specifies otherwise.

In principle, there is no reason to require a flat score for slicing by time, but there are many difficult edge cases to consider such as ties from within one chord to a note in another measure. Therefore, to slice by time or quarter, you must have a flattened score. Conversely, to slice a full score, you must slice by measure so that the result gives you whole measures, which are encoded into the full Score structure.

The entire result can be shifted to start at time 0 by setting the shift parameter to True. Unless truncate is "truncate" or "beginning", the result can include events that start before the start time, in which case shifting will only shift the earliest onset to 0, which means the shift amount depends upon the content. (Negative onsets are currently not allowed.)

The resulting Score, Part, and other content will have onset and offset times matching start and end, even if some content starts earlier or ends later.

Parameters:

  • start (float) –

    The start time of the slice, inclusive. If units is "measures" or "bars", start is a 0-based measure number of the first measure.

  • end (float) –

    The end time of the slice, exclusive. For measures, end is the 0-based measure number of the last measure plus one, so the last measure is end - 1.

  • units (str, default: 'quarters' ) –

    The time units for start and end. Valid values are "quarters", "s", "sec", "seconds", "measures", or "bars".

  • shift (bool, default: False ) –

    If true, shift the content in the result so that the result starts time 0.0. If false (default), the content in the result retains the same time values as in the original Score.

  • mode (Optional[str], default: 'onsets' ) –

    The slicing mode, ignored if units is "measures" or "bars". Valid values are:

    • "onsets" - include events that start within bounds (default)
    • "overlaps" - include events that overlap (either onset or offset) is within the bounds. An event ending is considered to overlap if its offset is greater than start.
    • "offsets" - include events that end within the bounds
    • "strict" - include only events that start at or after start and end at or before end. (End times that are exactly equal to end are considered to be within bounds, so this is inclusive of end time.)
  • truncate (str, default: 'keep' ) –

    How to handle events that partially overlap the bounds, ignored if units is "measures" or "bars". Valid values are:

    • "truncate" - truncate (clip) events that partially overlap the bounds. If the event onset is before start, the onset is increased to start (adjusting duration to maintain the offset time). Also, if the event offset is after end, the duration is decreased so that the offset time is end.
    • "keep" - no modification/truncation (default). Note that with the default mode="onsets", no event onsets will be earlier than start, but offsets may extend beyond end.
    • "end" or "ending" or "dur" or "duration" - truncate (clip) events that extend beyond end so that all offsets <= end.
    • "beginning" - events with onsets before start are moved to make their onsets equal to start, and their duration is adjusted to maintain the original offset.
  • min_duration (float, default: 0.05 ) –

    Events with duration less than min_duration (after any truncation is applied) are removed. Ignored if units is "measures" or "bars". If None or 0.0, no events are removed. The default is 0.05, independent of time units. Be careful with gracenotes that, when read from MusicXML, have zero duration.

Returns:

  • Score

    A new Score instance containing the content between start and end.

Raises:

  • ValueError

    If the Sequence is not part of a Score, or if invalid values are provided for the parameters.

Source code in amads/core/basics.py
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
def slice(self, start: float, end: float, units: str = "quarters",
          mode: str = "onsets", truncate: str = "keep", shift: bool = False,
          min_duration: float = 0.05) -> "EventGroup":
    """
    Create a new Score containing the content between start and end.

    Typically, this method is called on a Score to create a new Score,
    but it works on any Sequence as long as the sequence is part of a Score.

    If self has Measures, units must be "measures" or "bars", the start and
    end parameters are interpreted as 0-based measure numbers, and the
    result will therefore contain whole measures. It is assumed that notes
    are tied across measure boundaries. The result will contain only the
    parts of tied notes that are within the specified measures, excluding
    measure numbered by `end`.

    For any units besides "measures" or "bars", the score must be flat.
    Notes that extend beyond the start or end time are included in the
    result unless the `truncate` parameter specifies otherwise.

    In principle, there is no reason to require a flat score for slicing by
    time, but there are many difficult edge cases to consider such as ties
    from within one chord to a note in another measure. Therefore, to slice
    by time or quarter, you must have a flattened score. Conversely, to
    slice a full score, you must slice by measure so that the result gives
    you whole measures, which are encoded into the full Score structure.

    The entire result can be shifted to start at time 0 by setting the
    `shift` parameter to True.  Unless `truncate` is "truncate" or
    "beginning", the result can include events that start before the start
    time, in which case shifting will only shift the earliest onset to 0,
    which means the shift amount depends upon the content. (Negative onsets
    are currently not allowed.)

    The resulting Score, Part, and other content will have onset and offset
    times matching start and end, even if some content starts earlier or
    ends later.

    Parameters
    ----------
    start : float
        The start time of the slice, inclusive. If units is "measures" or
        "bars", start is a 0-based measure number of the first measure.
    end : float
        The end time of the slice, exclusive. For measures, end is the
        0-based measure number of the last measure plus one, so the last
        measure is end - 1.
    units : str
        The time units for start and end. Valid values are "quarters", "s",
        "sec", "seconds", "measures", or "bars".
    shift: bool
        If true, shift the content in the result so that the result starts
        time 0.0. If false (default), the content in the result retains
        the same time values as in the original Score.
    mode : Optional[str]
        The slicing mode, ignored if units is "measures" or "bars".
        Valid values are:

        - `"onsets"` - include events that start within bounds (default)
        - `"overlaps"` - include events that overlap (either onset or
            offset) is within the bounds. An event ending is considered
            to overlap if its offset is greater than start.
        - `"offsets"` - include events that end within the bounds
        - `"strict"` - include only events that start at or after start
            and end at or before end. (End times that are exactly equal
            to end are considered to be within bounds, so this is
            inclusive of end time.)

    truncate: Optional[str]
        How to handle events that partially overlap the bounds,
        ignored if units is "measures" or "bars". Valid values are:

        - `"truncate"` - truncate (clip) events that partially overlap
            the bounds. If the event onset is before start, the onset
            is increased to start (adjusting duration to maintain the
            offset time). Also, if the event offset is after end, the
            duration is decreased so that the offset time is end.
        - `"keep"` - no modification/truncation (default). Note that
            with the default mode="onsets", no event onsets will be
            earlier than start, but offsets may extend beyond end.
        - `"end"` or "ending" or "dur" or "duration" - truncate (clip)
            events that extend beyond end so that all offsets <= end.
        - `"beginning"` - events with onsets before start are moved to
            make their onsets equal to start, and their duration is
            adjusted to maintain the original offset.

    min_duration: Optional[float]
        Events with duration less than min_duration (after any truncation
        is applied) are removed.  Ignored if units is "measures" or "bars".
        If None or 0.0, no events are removed. The default is 0.05,
        independent of time units. Be careful with gracenotes that, when
        read from MusicXML, have zero duration.

    Returns
    -------
    Score
        A new Score instance containing the content between start and end.

    Raises
    ------
    ValueError
        If the Sequence is not part of a Score, or if invalid values are
        provided for the parameters.
    """
    score = self.score
    if score is None:
        raise ValueError("slice can only be called on a Sequence that is "
                         "part of a Score")
    if score.is_flat():
        if units in ("measures", "bars"):
            raise ValueError(f"units cannot be {units} for slicing a "
                             "flat score")
    else:
        if units not in ("measures", "bars"):
            raise ValueError(f"units must be measures or bars for slicing "
                "a score with Measures (or flatten the score before "
                "slicing)")

    if units in ("quarters", "measures", "bars"):
        score.convert_to_quarters()
    elif units in ("s", "sec", "seconds"):
        score.convert_to_seconds()
    else:
        raise ValueError('units must be "quarters", "measures, "'
                         '"bars", "s", "sec", or "seconds"')

    # Find start time and end time for slice. It may not be (start, end)
    # if units is measures or bars.
    if units in ("measures", "bars"):
        (start_time, end_time) = self.measure_times(int(start))
        if end != start:
            (_, end_time) = self.measure_times(int(end) - 1)
    else:
        start_time = start
        end_time = end

    # construct the parts of the tree above self and make an empty copy
    # of self to add the slice content.
    result = (score.emptycopy() if isinstance(self, Score)
              else self._copy_parents(start_time, end_time))
    result.onset = start_time  # result is an empty copy of self. Set the
    result.offset = end_time   # onset and offset to the slice bounds.
    if units in ("measures", "bars"):
        c_min, c_max = result._add_measure_children(self, start, end,
                                                    start_time, end_time)
        if c_min < start_time or c_max > end_time:
            raise ValueError("unexpectedly found content outside the "
                             "measure slice bounds")
        min_time = c_min
        max_time = c_max
    else:   
        min_time, max_time = result._add_slice_children(self, start_time,
                                  end_time, mode, truncate, min_duration)
    result._trim_map_and_signatures(min_time, max_time)
    if shift and min_time != float("inf") and min_time > 0:
        result.time_shift(-min_time)
    return result

Sequence

Sequence(
    parent: Optional[EventGroup],
    onset: Optional[float] = None,
    duration: Optional[float] = None,
    content: Optional[list[Event]] = None,
)

Bases: EventGroup

Sequence (abstract class) represents a temporal sequence of music events.

Parameters:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • onset (Optional[float], default: None ) –

    The onset (start) time. None means unknown, to be set when Sequence is added to a parent.

  • duration (Optional[float], default: None ) –

    The duration in quarters or seconds. (If duration is omitted or None, the duration is set so that self.offset ends at the max offset in content, or 0 if there is no content.)

  • content (Optional[list[Event]], default: None ) –

    A list of Event objects to be added to the group. Content events with onsets of None are set to the offset of the previous event in the sequence. The first event onset is the specified group onset, or zero if onset is None.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (Optional[float]) –

    The onset (start) time. None represents “unknown” and to be determined when this object is added to a parent.

  • duration (float) –

    The duration in quarters or seconds.

  • content (list[Event]) –

    Elements contained within this collection.

Source code in amads/core/basics.py
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
def __init__(self, parent: Optional[EventGroup],
             onset: Optional[float] = None,
             duration: Optional[float] = None,
             content: Optional[list[Event]] = None):
    # if onset is given, we need to set all content onsets to form a
    # sequence before running super().__init__()
    if content is None:
        content = []
    prev_onset : float = 0.0
    prev_offset : float = 0.0
    if not onset is None:
        prev_onset = onset
        prev_offset = onset
    for elem in content:
        # parent will be set in EventGroup's constructor
        if elem._onset is None:
             elem.onset = prev_offset
        elif elem.onset < prev_onset:
            raise ValueError("Event onsets are not in time order")
        prev_onset = elem.onset
        prev_offset = elem.offset
    # now that onset times are all set, we can run EventGroup's
    # constructor to set parents, duration, content
    super().__init__(parent, onset, duration, content)

Attributes

onset property writable

onset: float

Retrieve the onset (start) time.

If the onset is None, raise an exception. (Events can have None onset times, but they must be set before retrieval. onsets that are None are automatically set when the Event is added to an EventGroup.)

Returns:

  • float

    The onset (start) time.

Raises:

  • ValueError

    If the onset time is not set (None).

units_are_seconds property

units_are_seconds: bool

Check if the times are in seconds.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in seconds. If not in a score, False is returned.

units_are_quarters property

units_are_quarters: bool

Check if the times are in quarters.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in quarters. If not in a score, False is returned.

offset property writable

offset: float

Retrieve the global offset (stop) time.

Returns:

  • float

    The global offset (stop) time.

part property

part: Optional[Part]

Retrieve the Part containing this event.

Returns:

  • Optional[Part]

    The Part containing this event or None if not found.

score property

score: Optional[Score]

Retrieve the Score containing this event, or self if it is a score.

Returns:

  • Optional[Score]

    The Score containing this event or None if not found.

staff property

staff: Optional[Staff]

Retrieve the Staff containing this event

Returns:

  • Optional[Staff]

    The Staff containing this event or None if not found.

measure property

measure: Optional[Measure]

Retrieve the Measure containing this event

Returns:

  • Optional[Measure]

    The Measure containing this event or None if not found.

Functions

set

set(property: str, value: Any) -> Event

Set a named property on this Event.

Every event can be extended with additional properties. Although Python objects are already extensible with new attributes, new attributes that are not set in __init__ confuse type checkers and other tools, so every Event has an info attribute as a dictionary where additional, application-specific information can be stored. The info attribute is None to save space until the first property is set, so you should use set and get methods and avoid writing event.info[property].

Parameters:

  • property (str) –

    The name of the property to set.

  • value (Any) –

    The value to assign to the property.

Returns:

  • Event

    returns this object (self)

Examples:

>>> note = Note()
>>> note.get("color", "no color")
'no color'
>>> _ = note.set("color", "red").set("harmonicity", 0.2)
>>> (note.has("color"), note.has("shape"))
(True, False)
>>> (note.get("color"), note.get("harmonicity"))
('red', 0.2)
Source code in amads/core/basics.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def set(self, property : str, value : Any) -> "Event":
    """Set a named property on this Event.

    Every event can be extended with additional properties. Although
    Python objects are already extensible with new attributes, new
    attributes that are not set in `__init__` confuse type checkers
    and other tools, so every `Event` has an `info` attribute as a
    dictionary where additional, application-specific information can
    be stored. The `info` attribute is `None` to save space until the
    first property is set, so you should use `set` and `get` methods
    and avoid writing `event.info[property]`.

    Parameters
    ----------
    property : str
        The name of the property to set.
    value : Any
        The value to assign to the property.

    Returns
    -------
    Event
        returns this object (self)

    Examples
    --------
    >>> note = Note()
    >>> note.get("color", "no color")
    'no color'
    >>> _ = note.set("color", "red").set("harmonicity", 0.2)
    >>> (note.has("color"), note.has("shape"))
    (True, False)
    >>> (note.get("color"), note.get("harmonicity"))
    ('red', 0.2)
    """
    if self.info is None:
        self.info = {}
    self.info[property] = value
    return self

get

get(property: str, default: Any = None) -> Any

Get the value of a property from this Event.

See set for more details.

Parameters:

  • property (str.) –

    The name of the property to get.

  • default (Any, default: None ) –

    The default value to return if the property is not found.

Returns:

  • Any

    The value of the specified property.

Source code in amads/core/basics.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def get(self, property : str, default : Any = None) -> Any:
    """Get the value of a property from this Event.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str.
        The name of the property to get.
    default : Any
        The default value to return if the property is not found.

    Returns
    -------
    Any
        The value of the specified property.
    """
    if self.info is None:
        return default
    return self.info.get(property, default)

has

has(property) -> bool

Check if the Event has a specific property.

See set for more details.

Parameters:

  • property (str) –

    The name of the property to check.

Returns:

  • bool

    True if the property exists, False otherwise.

Source code in amads/core/basics.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def has(self, property) -> bool:
    """Check if the Event has a specific property.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str
        The name of the property to check.

    Returns
    -------
    bool
        True if the property exists, False otherwise.
    """
    return (self.info is not None) and (property in self.info)

time_shift

time_shift(increment: float, content_only: bool = False) -> EventGroup

Change the onset by an increment, affecting all content.

If content_only is true, preserves EventGroup times (Score, Part, Staff, but not Chord or Measure) and shifts only the content (recursively). Otherwise, shifts this container and all content by the increment. Container onsets (recursively) are not allowed to become negative, so the onset time is set to zero if the increment would make it negative. However, even if the onset is is not shifted by increment, time_shift is still applied recursively to the content, and non-EventGroup events (e.g., Notes) are allowed to have negative onsets, even if this may not be well-defined for all AMADS operations.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

  • content_only (bool, default: False ) –

    If true, preserves this container's time and shifts only the content.

Returns:

  • Event

    The object. This method modifies the EventGroup.

Raises:

  • ValueError

    If the EventGroup has an unknown (None) onset and content_only is false.

Source code in amads/core/basics.py
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
def time_shift(self, increment: float,
               content_only: bool = False) -> "EventGroup":
    """
    Change the onset by an increment, affecting all content.

    If content_only is true, preserves EventGroup times (Score, Part,
    Staff, but *not* Chord or Measure) and shifts only the content
    (recursively). Otherwise, shifts this container and all content by the
    increment. Container onsets (recursively) are not allowed to become
    negative, so the onset time is set to zero if the increment would
    make it negative. However, even if the onset is is not shifted by
    increment, time_shift is still applied recursively to the content,
    and non-EventGroup events (e.g., Notes) are allowed to have negative
    onsets, even if this may not be well-defined for all AMADS operations.

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).
    content_only: bool
        If true, preserves this container's time and shifts only
        the content.

    Returns
    -------
    Event
        The object. This method modifies the `EventGroup`.

    Raises
    ------
    ValueError
        If the EventGroup has an unknown (None) onset and
        content_only is false.
    """
    # note that Chord and Measures are special cases
    if not content_only or isinstance(self, (Chord, Measure)):
        if self._onset is None:
            raise ValueError(
                    "Cannot shift time of EventGroup with unknown onset")
        self._onset = max(0.0, self._onset + increment)
    for elem in self.content:
        elem.time_shift(increment, content_only)
    return self

insert_copy_into

insert_copy_into(parent: Optional[EventGroup] = None) -> Event

Make a (mostly) deep copy of the Event and add to a new parent.

Pitch objects are considered immutable and are shared rather than copied.

Parameters:

  • parent (Optional(EventGroup), default: None ) –

    The copied Event will be a child of parent if not None. The parent is modified by this operation.

Returns:

  • Event

    A deep copy (except for parent and pitch) of the Event instance.

Source code in amads/core/basics.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def insert_copy_into(self,
                     parent: Optional["EventGroup"] = None) -> "Event":
    """
    Make a (mostly) deep copy of the `Event` and add to a new `parent`.

    `Pitch` objects are considered immutable and are shared rather
    than copied.

    Parameters
    ----------
    parent : Optional(EventGroup)
        The copied `Event` will be a child of `parent` if not `None`.
        The parent is modified by this operation.

    Returns
    -------
    Event
        A deep copy (except for parent and pitch) of the Event instance.
    """
    # remove link to parent to break link going up the tree
    # preventing deep copy from copying the entire tree
    original_parent = self.parent
    self.parent = None
    c = copy.deepcopy(self)  # deep copy of this event down to leaf nodes
    self.parent = original_parent  # restore link to parent
    if parent:
        parent.insert(c)
    return c

ismonophonic

ismonophonic() -> bool

Determine if content is monophonic (non-overlapping notes).

A monophonic list of notes has no overlapping notes (e.g., chords). Serves as a helper function for ismonophonic and parts_are_monophonic.

Returns:

  • bool

    True if the list of notes is monophonic, False otherwise.

Source code in amads/core/basics.py
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
def ismonophonic(self) -> bool:
    """
    Determine if content is monophonic (non-overlapping notes).

    A monophonic list of notes has no overlapping notes (e.g., chords).
    Serves as a helper function for `ismonophonic` and
    `parts_are_monophonic`.

    Returns
    -------
    bool
        True if the list of notes is monophonic, False otherwise.
    """
    prev = None
    notes = self.list_all(Note)
    # Sort the notes by start time
    notes.sort(key=lambda note: note.onset)
    # Check for overlaps
    for note in notes:
        if prev:
            # 0.01 is to prevent precision errors when comparing floats
            if note.onset - prev.offset < -0.01:
                return False
        prev = note
    return True

insert_emptycopy_into

insert_emptycopy_into(
    parent: Optional[EventGroup] = None,
) -> EventGroup

Create a deep copy of the EventGroup except for content.

A new parent is provided as an argument and the copy is inserted into this parent. This method is useful for copying an EventGroup without copying its content. See also insert_copy_into to copy an EventGroup with its content into a new parent.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    The new parent to insert the copied Event into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with the new parent (if any) and no content.

Source code in amads/core/basics.py
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
def insert_emptycopy_into(self, 
            parent: Optional["EventGroup"] = None) -> "EventGroup":
    """Create a deep copy of the EventGroup except for content.

    A new parent is provided as an argument and the copy is inserted
    into this parent. This method is  useful for copying an
    EventGroup without copying its content.  See also
    [insert_copy_into][amads.core.basics.Event.insert_copy_into] to
    copy an EventGroup *with* its content into a new parent.

    Parameters
    ----------
    parent : Optional[EventGroup]
        The new parent to insert the copied Event into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with the new parent
        (if any) and no content.
    """
    # rather than customize __deepcopy__, we "hide" the content to avoid
    # copying it. Then we restore it after copying and fix parent.
    original_content = self.content
    self.content = []
    c = self.insert_copy_into(parent)
    self.content = original_content
    return c  #type: ignore (c will always be an EventGroup)

expand_chords

expand_chords(parent: Optional[EventGroup] = None) -> EventGroup

Replace chords with the multiple notes they contain.

Returns a deep copy with no parent unless parent is provided. Normally, you will call score.expand_chords() which returns a deep copy of Score with notes moved from each chord to the copy of the chord's parent (a Measure or a Part). The parent parameter is primarily for internal use when expand_chords is called recursively on score content.

Parameters:

  • parent (EventGroup, default: None ) –

    The new parent to insert the copied EventGroup into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with all Chord instances expanded.

Source code in amads/core/basics.py
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
def expand_chords(self,
                  parent: Optional["EventGroup"] = None) -> "EventGroup":
    """Replace chords with the multiple notes they contain.

    Returns a deep copy with no parent unless parent is provided.
    Normally, you will call `score.expand_chords()` which returns a deep
    copy of Score with notes moved from each chord to the copy of the
    chord's parent (a Measure or a Part). The parent parameter is 
    primarily for internal use when `expand_chords` is called recursively
    on score content.

    Parameters
    ----------
    parent : EventGroup
        The new parent to insert the copied EventGroup into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with all
        Chord instances expanded.
    """
    group = self.insert_emptycopy_into(parent)
    for item in self.content:
        if isinstance(item, Chord):
            for note in item.content:  # expand chord
                note.insert_copy_into(group)
        if isinstance(item, EventGroup):
            item.expand_chords(group)  # recursion for deep copy/expand
        else:
            item.insert_copy_into(group)  # deep copy non-EventGroup
    return group

find_all

find_all(elem_type: Type[Event]) -> Generator[Event, None, None]

Find all instances of a specific type within the EventGroup.

Assumes that objects of type elem_type are not nested within other objects of the same type. (The first elem_type encountered in a depth-first enumeration is returned without looking at any children in its content).

Parameters:

  • elem_type (Type[Event]) –

    The type of event to search for.

Yields:

  • Event

    Instances of the specified type found within the EventGroup.

Source code in amads/core/basics.py
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
def find_all(self, elem_type: Type[Event]) -> Generator[Event, None, None]:
    """Find all instances of a specific type within the EventGroup.

    Assumes that objects of type `elem_type` are not nested within
    other objects of the same type. (The first `elem_type` encountered
    in a depth-first enumeration is returned without looking at any
    children in its `content`).

    Parameters
    ----------
    elem_type : Type[Event]
        The type of event to search for.

    Yields
    -------
    Event
        Instances of the specified type found within the EventGroup.
    """
    # Algorithm: depth-first enumeration of EventGroup content.
    # If elem_types are nested, only the top-level elem_type is
    # returned since it is found first, and the content is not
    # searched. This makes it efficient, e.g., to search for
    # Parts in a Score without enumerating all Notes within.
    for elem in self.content:
        if isinstance(elem, elem_type):
            yield elem
        elif isinstance(elem, EventGroup):
            yield from elem.find_all(elem_type)

get_sorted_notes

get_sorted_notes(has_ties: bool = True) -> List[Note]

Return a list of sorted notes with merged ties.

This should generally be called on Parts and Scores since in all other EventGroups, Events are in time order and Notes retrieved with find_all() or list_all() are in time order. However, get_sorted_notes also sorts notes into increasing pitch (keynum) where note onsets are equal.

Parameters:

  • has_ties (bool, default: True ) –

    If True (default), copy the score, merge the ties, and return a list of these merged copies. If False, assume there are no ties and return a list of original notes.

Raises:

  • ValueError

    If has_ties is False, but a tie is encountered.

Returns:

  • list(Note)

    a list of sorted notes with merged ties

Source code in amads/core/basics.py
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
def get_sorted_notes(self, has_ties: bool = True) -> List[Note]:
    """Return a list of sorted notes with merged ties.

    This should generally be called on Parts and Scores since
    in all other EventGroups, Events are in time order and
    Notes retrieved with `find_all()` or `list_all()` are in
    time order. However, `get_sorted_notes` *also* sorts notes
    into increasing pitch (`keynum`) where note onsets are equal.

    Parameters
    ----------
    has_ties: bool
        If True (default), copy the score, merge the ties, and
        return a list of these merged copies. If False, assume
        there are no ties and return a list of original notes.

    Raises
    ------
    ValueError
        If has_ties is False, but a tie is encountered.

    Returns
    -------
    list(Note)
        a list of sorted notes with merged ties
    """
    if has_ties:
        # after flatten, score will have one Part with all Notes:
        return self.flatten(collapse=True).content[0].content  # type: ignore
    else:
        notes : List[Note] = cast(List[Note], self.list_all(Note))
        for note in notes:
            if note.tie is not None:
                raise ValueError(
                        "tie found by get_sorted_notes with has_ties=False")
        notes.sort(key=lambda x: (x.onset, x.pitch))
        return notes

has_instanceof

has_instanceof(the_class: Type[Event]) -> bool

Test if EventGroup contains any instances of the_class.

Parameters:

  • the_class (Type[Event]) –

    The class type to check for.

Returns:

  • bool

    True iff the EventGroup contains an instance of the_class.

Source code in amads/core/basics.py
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
def has_instanceof(self, the_class: Type[Event]) -> bool:
    """Test if EventGroup contains any instances of `the_class`.

    Parameters
    ----------
    the_class : Type[Event]
        The class type to check for.

    Returns
    -------
    bool
        True iff the EventGroup contains an instance of the_class.
    """
    instances = self.find_all(the_class)
    # if there are no instances (of the_class), next will return "empty":
    return next(instances, "empty") != "empty"

has_rests

has_rests() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Rest objects.

Returns:

  • bool

    True iff the EventGroup contains any Rest objects.

Source code in amads/core/basics.py
1787
1788
1789
1790
1791
1792
1793
1794
1795
def has_rests(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any `Rest` objects.

    Returns
    -------
    bool
        True iff the EventGroup contains any Rest objects.
    """
    return self.has_instanceof(Rest)

has_chords

has_chords() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Chord objects.

Returns:

  • bool

    True iff the EventGroup contains any Chord objects.

Source code in amads/core/basics.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
def has_chords(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any Chord objects.

    Returns
    -------
    bool
        True iff the EventGroup contains any Chord objects.
    """
    return self.has_instanceof(Chord)

has_ties

has_ties() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any tied notes.

Returns:

  • bool

    True iff the EventGroup contains any tied notes.

Source code in amads/core/basics.py
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
def has_ties(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any tied notes.

    Returns
    -------
    bool
        True iff the EventGroup contains any tied notes.
    """
    notes = self.find_all(Note)
    for note in notes:
        if note.tie:
            return True
    return False

has_measures

has_measures() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Measures.

Returns:

  • bool

    True iff the EventGroup contains any Measure objects.

Source code in amads/core/basics.py
1824
1825
1826
1827
1828
1829
1830
1831
1832
def has_measures(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any Measures.

    Returns
    -------
    bool
        True iff the EventGroup contains any Measure objects.
    """
    return self.has_instanceof(Measure)

inherit_duration

inherit_duration() -> EventGroup

Set the duration of this EventGroup according to maximum offset.

The duration is set to the maximum offset (end) time of the children. If the EventGroup is empty, the duration is set to 0. This method modifies this EventGroup instance.

Returns:

  • EventGroup

    The EventGroup instance (self) with updated duration.

Source code in amads/core/basics.py
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
def inherit_duration(self) -> "EventGroup":
    """Set the duration of this EventGroup according to maximum offset.

    The `duration` is set to the maximum offset (end) time of the
    children. If the EventGroup is empty, the duration is set to 0.
    This method modifies this `EventGroup` instance.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with updated duration.
    """
    onset = 0 if self._onset == None else self._onset
    max_offset = onset
    for elem in self.content:
        max_offset = max(max_offset, elem.offset)
    self.duration = max_offset - onset

    return self

insert

insert(event: Event) -> EventGroup

Insert an event.

Sets the parent of event to this EventGroup and makes event be a member of this EventGroup.content. No changes are made to event.onset or self.duration. Insert event in content just before the first element with a greater onset. The method modifies this object (self).

Parameters:

  • event (Event) –

    The event to be inserted.

Returns:

  • EventGroup

    The EventGroup instance (self) with the event inserted.

Raises:

  • ValueError

    If event._onset is None (it must be a number)

Caution Regarding Zero-Duration Event Order

If you have note N with non-zero duration and, at the same time, a grace note G with zero duration, the notes will be ordered according to when they are inserted. So if you insert N and then G, then N will be placed before G. See io.pt_import.py, where this case is dealt with.

Source code in amads/core/basics.py
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
def insert(self, event: Event) -> "EventGroup":
    """Insert an event.

    Sets the `parent` of `event` to this `EventGroup` and makes `event`
    be a member of this `EventGroup.content`. No changes are made to
    `event.onset` or `self.duration`. Insert `event` in `content` just
    before the first element with a greater onset. The method modifies
    this object (self).

    Parameters
    ----------
    event : Event
        The event to be inserted.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with the event inserted.

    Raises
    ------
    ValueError
        If event._onset is None (it must be a number)

    Caution Regarding Zero-Duration Event Order
    -------------------------------------------
    If you have note N with non-zero duration and, at the same
    time, a grace note G with zero duration, the notes will be
    ordered according to when they are inserted. So if you insert
    N and then G, then N will be placed *before* G. See
    io.pt_import.py, where this case is dealt with.
    """

    assert not event.parent
    if event._onset is None:  # must be a number
        raise ValueError(f"event's _onset attribute must be a number")
    atend = self.last()
    if atend and event.onset < atend.onset:
        # search in reverse from end
        i = len(self.content) - 2
        while i >= 0 and self.content[i].onset > event.onset:
            i -= 1
        # now i is either -1 or content[i] <= event.onset, so
        # insert event at content[i+1]
        self.content.insert(i + 1, event)
    else:  # simply append at the end of content:
        self.content.append(event)
    event.parent = self
    return self

last

last() -> Optional[Event]

Retrieve the last event in the content list.

Because the content list is sorted by onset, the returned Event is simply the last element of content, but not necessarily the event with the greatest offset.

Returns:

  • Optional[Event]

    The last event in the content list or None if the list is empty.

Source code in amads/core/basics.py
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
def last(self) -> Optional[Event]:
    """Retrieve the last event in the content list.

    Because the `content` list is sorted by `onset`, the returned
    `Event` is simply the last element of `content`, but not
    necessarily the event with the greatest *`offset`*.

    Returns
    -------
    Optional[Event]
        The last event in the content list or None if the list is empty.
    """
    return self.content[-1] if len(self.content) > 0 else None

list_all

list_all(elem_type: Type[Event]) -> list[Event]

Find all instances of a specific type within the EventGroup.

Assumes that objects of type elem_type are not nested within other objects of the same type. See also find_all, which returns a generator instead of a list.

Parameters:

  • elem_type (Type[Event]) –

    The type of event to search for.

Returns:

  • list[Event]

    A list of all instances of the specified type found within the EventGroup.

Source code in amads/core/basics.py
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
def list_all(self, elem_type: Type[Event]) -> list[Event]:
    """Find all instances of a specific type within the EventGroup.

    Assumes that objects of type `elem_type` are not nested within
    other objects of the same type.  See also
    [find_all][amads.core.basics.EventGroup.find_all], which returns
    a generator instead of a list.

    Parameters
    ----------
    elem_type : Type[Event]
        The type of event to search for.

    Returns
    -------
    list[Event]
        A list of all instances of the specified type found
        within the EventGroup.
    """
    return list(self.find_all(elem_type))

merge_tied_notes

merge_tied_notes(
    parent: Optional[EventGroup] = None, ignore: list[Note] = []
) -> EventGroup

Create a new EventGroup with tied notes replaced by single notes.

If ties cross staffs, the replacement is placed in the staff of the first note in the tied sequence. Insert the new EventGroup into parent.

Ordinarily, this method is called on a Score with no parameters. The parameters are used when Score.merge_tied_notes() calls this method recursively on EventGroups within the Score such as Parts and Staffs.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    Where to insert the result.

  • ignore (list[Note], default: [] ) –

    This parameter is used internally. Caller should not use this parameter.

Returns:

  • EventGroup

    A copy with tied notes replaced by equivalent single notes.

Source code in amads/core/basics.py
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
def merge_tied_notes(self, parent: Optional["EventGroup"] = None,
                     ignore: list[Note] = []) -> "EventGroup":
    """Create a new `EventGroup` with tied notes replaced by single notes.

    If ties cross staffs, the replacement is placed in the staff of the
    first note in the tied sequence. Insert the new `EventGroup` into
    `parent`.

    Ordinarily, this method is called on a Score with no parameters. The
    parameters are used when `Score.merge_tied_notes()` calls this method
    recursively on `EventGroup`s within the Score such as `Part`s and
    `Staff`s.

    Parameters
    ----------
    parent: Optional(EventGroup)
        Where to insert the result.

    ignore: Optional(list[Note])
        This parameter is used internally. Caller should not use
        this parameter.

    Returns
    -------
    EventGroup
        A copy with tied notes replaced by equivalent single notes.
    """
    # Algorithm: Find all notes, removing tied notes and updating
    # duration when ties are found. These tied notes are added to
    # ignore so they can be skipped when they are encountered.

    group = self.insert_emptycopy_into(parent)
    for event in self.content:
        if isinstance(event, Note):
            if event in ignore:  # do not copy tied notes into group;
                if event.tie:
                    ignore.append(event.tie)  # add tied note to ignore
                # We will not see this note again, so
                # we can also remove it from ignore. Removal is expensive
                # but it could be worse for ignore to grow large when there
                # are many ties since we have to search it entirely once
                # per note. An alternate representation might be a set to
                # make searching fast.
                ignore.remove(event)
            else:
                if event.tie:
                    tied_note = event.tie  # save the tied-to note
                    event.tie = None  # block the copy
                    ignore.append(tied_note)
                    # copy note into group:
                    event_copy = event.insert_copy_into(group)
                    event.tie = tied_note  # restore original event
                    # this is subtle: event.tied_duration (a property) will
                    # sum up durations of all the tied notes. Since
                    # event_copy is not tied, the sum of durations is
                    # stored on that one event_copy:
                    event_copy.duration = event.tied_duration
                else:  # put the untied note into group
                    event.insert_copy_into(group)
        elif isinstance(event, EventGroup):
            event.merge_tied_notes(group, ignore)
        else:
            event.insert_copy_into(group)  # simply copy to new parent
    return group

quantize

quantize(divisions: int) -> EventGroup

Align onsets and durations to a rhythmic grid.

Assumes time units are quarters. (See Score.convert_to_quarters.)

Modify all times and durations to a multiple of divisions per quarter note, e.g., 4 for sixteenth notes. Onsets and offsets are moved to the nearest quantized time. Any resulting duration change is less than one quantum, but not necessarily less than 0.5 quantum, since the onset and offset can round in opposite directions by up to 0.5 quantum each. Any non-zero duration that would quantize to zero duration gets a duration of one quantum since zero duration is almost certainly going to cause notation and visualization problems.

Special cases for zero duration:

  1. If the original duration is zero as in metadata or possibly grace notes, we preserve that.
  2. If a tied note duration quantizes to zero, we remove the tied note entirely provided some other note in the tied sequence has non-zero duration. If all tied notes quantize to zero, we keep the first one and set its duration to one quantum.

This method modifies this EventGroup and all its content in place.

Note that there is no way to specify "sixteenths or eighth triplets" because 6 would not allow sixteenths and 12 would admit sixteenth triplets. Using tuples as in Music21, e.g., (4, 3) for this problem creates another problem: if quantization is to time points 1/4, 1/3, then the difference is 1/12 or a thirty-second triplet. If the quantization is applied to durations, then you could have 1/4 + 1/3 = 7/12, and the remaining duration in a single beat would be 5/12, which is not expressible as sixteenths, eighth triplets or any tied combination.

Parameters:

  • divisions (int) –

    The number of divisions per quarter note, e.g., 4 for sixteenths, to control quantization.

Returns:

  • EventGroup

    The EventGroup instance (self) with (modified in place) quantized times.

Source code in amads/core/basics.py
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
def quantize(self, divisions: int) -> "EventGroup":
    """Align onsets and durations to a rhythmic grid.

    Assumes time units are quarters. (See [Score.convert_to_quarters](
            basics.md#amads.core.basics.Score.convert_to_quarters).)

    Modify all times and durations to a multiple of divisions
    per quarter note, e.g., 4 for sixteenth notes. Onsets and offsets
    are moved to the nearest quantized time. Any resulting duration
    change is less than one quantum, but not necessarily less than
    0.5 quantum, since the onset and offset can round in opposite
    directions by up to 0.5 quantum each. Any non-zero duration that would
    quantize to zero duration gets a duration of one quantum since
    zero duration is almost certainly going to cause notation and
    visualization problems.

    Special cases for zero duration:

    1. If the original duration is zero as in metadata or possibly
           grace notes, we preserve that.
    2. If a tied note duration quantizes to zero, we remove the
           tied note entirely provided some other note in the tied
           sequence has non-zero duration. If all tied notes quantize
           to zero, we keep the first one and set its duration to
           one quantum.

    This method modifies this EventGroup and all its content in place.

    Note that there is no way to specify "sixteenths or eighth triplets"
    because 6 would not allow sixteenths and 12 would admit sixteenth
    triplets. Using tuples as in Music21, e.g., (4, 3) for this problem
    creates another problem: if quantization is to time points 1/4, 1/3,
    then the difference is 1/12 or a thirty-second triplet. If the
    quantization is applied to durations, then you could have 1/4 + 1/3
    = 7/12, and the remaining duration in a single beat would be 5/12,
    which is not expressible as sixteenths, eighth triplets or any tied
    combination.

    Parameters
    ----------
    divisions : int
        The number of divisions per quarter note, e.g., 4 for
        sixteenths, to control quantization.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with (modified in place) 
        quantized times.
    """

    super()._quantize(divisions)
    # iterating through content is tricky because we may delete a
    # Note, shifting the content:
    i = 0
    while i < len(self.content):
        event = self.content[i]
        event._quantize(divisions)
        if event == self.content[i]:
            i += 1
        # otherwise, we deleted event so the next event to
        # quantize is at index i; don't incremenet i
    return self

remove

remove(element: Event) -> EventGroup

Remove an element from the content list.

The method modifies this object (self).

Parameters:

  • element (Event) –

    The event to be removed.

Returns:

  • EventGroup

    The EventGroup instance (self) with the element removed. The returned value is not a copy.

Source code in amads/core/basics.py
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
def remove(self, element: Event) -> "EventGroup":
    """Remove an element from the content list. 

    The method modifies this object (self).

    Parameters
    ----------
    element : Event
        The event to be removed.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with the element removed.
        The returned value is not a copy.
    """
    self.content.remove(element)
    element.parent = None
    return self

remove_rests

remove_rests(parent: Union[EventGroup, None] = None) -> EventGroup

Remove all Rest objects from content.

Returns a deep copy with no parent unless parent is provided.

Parameters:

  • parent (EventGroup, default: None ) –

    The new parent to insert the copied Event into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with all Rest objects removed.

Source code in amads/core/basics.py
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
def remove_rests(self, parent: Union["EventGroup", 
                                     None] = None) -> "EventGroup":
    """Remove all Rest objects from content.

    Returns a deep copy with no parent unless parent is provided.

    Parameters
    ----------
    parent : EventGroup
        The new parent to insert the copied Event into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with all Rest
        objects removed.
    """
    # implementation detail: when called without argument, remove_rests
    # makes a deep copy of the subtree and returns the copy without a
    # parent. remove_rests calls itself recursively *with* a parameter
    # indicating that the subtree copy should be inserted into a
    # parent which is the new copy at the next level up. Of course,
    # we check for and ignore Rests so they are never copied.
    group = self.insert_emptycopy_into(parent)
    for item in self.content:
        if isinstance(item, Rest):
            continue  # skip the Rests while making deep copy
        if isinstance(item, EventGroup):
            item.remove_rests(group)  # recursion for deep copy
        else:
            item.insert_copy_into(group)  # deep copy non-EventGroup
    return group

show

show(indent: int = 0, file: Optional[TextIO] = None) -> EventGroup

Print the EventGroup information.

Parameters:

  • indent (int, default: 0 ) –

    The indentation level for display.

Returns:

Source code in amads/core/basics.py
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
def show(self, indent: int = 0,
        file: Optional[TextIO] = None) -> "EventGroup":
    """Print the EventGroup information.

    Parameters
    ----------
    indent : int
        The indentation level for display.

    Returns
    -------
    EventGroup
        The EventGroup instance itself.
    """
    print(" " * indent, self, sep="", file=file)
    for elem in self.content:
        elem.show(indent + 4, file=file)  # type: ignore (show exists)
    return self

measure_times

measure_times(n: int) -> tuple[float, float]

Return the start and end times of measure n.

Parameters:

  • n (int) –

    The 0-based measure number.

Returns:

  • tuple(float, float)

    A tuple containing the start and end times of measure n. Measure 0 is the first measure. Units are the same as the score's time units.

Raises:

  • ValueError

    If there is no measure with number n.

Source code in amads/core/basics.py
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
def measure_times(self, n: int) -> tuple[float, float]:
    """Return the start and end times of measure n.

    Parameters
    ----------
    n : int
        The 0-based measure number.

    Returns
    -------
    tuple(float, float)
        A tuple containing the start and end times of measure n.
        Measure 0 is the first measure.  Units are the same as the
        score's time units.

    Raises
    ------
    ValueError
        If there is no measure with number n.
    """
    # Algorithm: For each Staff, linear search for nth Measure, returning
    # the onset and offset of the first one found.
    for staff in self.find_all(Staff):
        staff = cast(Staff, staff)
        for i, measure in enumerate(staff.find_all(Measure)):
            if i == n:
                return (measure.onset, measure.offset)
    raise ValueError(f"measure {n} not found")

slice

slice(
    start: float,
    end: float,
    units: str = "quarters",
    mode: str = "onsets",
    truncate: str = "keep",
    shift: bool = False,
    min_duration: float = 0.05,
) -> EventGroup

Create a new Score containing the content between start and end.

Typically, this method is called on a Score to create a new Score, but it works on any Sequence as long as the sequence is part of a Score.

If self has Measures, units must be "measures" or "bars", the start and end parameters are interpreted as 0-based measure numbers, and the result will therefore contain whole measures. It is assumed that notes are tied across measure boundaries. The result will contain only the parts of tied notes that are within the specified measures, excluding measure numbered by end.

For any units besides "measures" or "bars", the score must be flat. Notes that extend beyond the start or end time are included in the result unless the truncate parameter specifies otherwise.

In principle, there is no reason to require a flat score for slicing by time, but there are many difficult edge cases to consider such as ties from within one chord to a note in another measure. Therefore, to slice by time or quarter, you must have a flattened score. Conversely, to slice a full score, you must slice by measure so that the result gives you whole measures, which are encoded into the full Score structure.

The entire result can be shifted to start at time 0 by setting the shift parameter to True. Unless truncate is "truncate" or "beginning", the result can include events that start before the start time, in which case shifting will only shift the earliest onset to 0, which means the shift amount depends upon the content. (Negative onsets are currently not allowed.)

The resulting Score, Part, and other content will have onset and offset times matching start and end, even if some content starts earlier or ends later.

Parameters:

  • start (float) –

    The start time of the slice, inclusive. If units is "measures" or "bars", start is a 0-based measure number of the first measure.

  • end (float) –

    The end time of the slice, exclusive. For measures, end is the 0-based measure number of the last measure plus one, so the last measure is end - 1.

  • units (str, default: 'quarters' ) –

    The time units for start and end. Valid values are "quarters", "s", "sec", "seconds", "measures", or "bars".

  • shift (bool, default: False ) –

    If true, shift the content in the result so that the result starts time 0.0. If false (default), the content in the result retains the same time values as in the original Score.

  • mode (Optional[str], default: 'onsets' ) –

    The slicing mode, ignored if units is "measures" or "bars". Valid values are:

    • "onsets" - include events that start within bounds (default)
    • "overlaps" - include events that overlap (either onset or offset) is within the bounds. An event ending is considered to overlap if its offset is greater than start.
    • "offsets" - include events that end within the bounds
    • "strict" - include only events that start at or after start and end at or before end. (End times that are exactly equal to end are considered to be within bounds, so this is inclusive of end time.)
  • truncate (str, default: 'keep' ) –

    How to handle events that partially overlap the bounds, ignored if units is "measures" or "bars". Valid values are:

    • "truncate" - truncate (clip) events that partially overlap the bounds. If the event onset is before start, the onset is increased to start (adjusting duration to maintain the offset time). Also, if the event offset is after end, the duration is decreased so that the offset time is end.
    • "keep" - no modification/truncation (default). Note that with the default mode="onsets", no event onsets will be earlier than start, but offsets may extend beyond end.
    • "end" or "ending" or "dur" or "duration" - truncate (clip) events that extend beyond end so that all offsets <= end.
    • "beginning" - events with onsets before start are moved to make their onsets equal to start, and their duration is adjusted to maintain the original offset.
  • min_duration (float, default: 0.05 ) –

    Events with duration less than min_duration (after any truncation is applied) are removed. Ignored if units is "measures" or "bars". If None or 0.0, no events are removed. The default is 0.05, independent of time units. Be careful with gracenotes that, when read from MusicXML, have zero duration.

Returns:

  • Score

    A new Score instance containing the content between start and end.

Raises:

  • ValueError

    If the Sequence is not part of a Score, or if invalid values are provided for the parameters.

Source code in amads/core/basics.py
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
def slice(self, start: float, end: float, units: str = "quarters",
          mode: str = "onsets", truncate: str = "keep", shift: bool = False,
          min_duration: float = 0.05) -> "EventGroup":
    """
    Create a new Score containing the content between start and end.

    Typically, this method is called on a Score to create a new Score,
    but it works on any Sequence as long as the sequence is part of a Score.

    If self has Measures, units must be "measures" or "bars", the start and
    end parameters are interpreted as 0-based measure numbers, and the
    result will therefore contain whole measures. It is assumed that notes
    are tied across measure boundaries. The result will contain only the
    parts of tied notes that are within the specified measures, excluding
    measure numbered by `end`.

    For any units besides "measures" or "bars", the score must be flat.
    Notes that extend beyond the start or end time are included in the
    result unless the `truncate` parameter specifies otherwise.

    In principle, there is no reason to require a flat score for slicing by
    time, but there are many difficult edge cases to consider such as ties
    from within one chord to a note in another measure. Therefore, to slice
    by time or quarter, you must have a flattened score. Conversely, to
    slice a full score, you must slice by measure so that the result gives
    you whole measures, which are encoded into the full Score structure.

    The entire result can be shifted to start at time 0 by setting the
    `shift` parameter to True.  Unless `truncate` is "truncate" or
    "beginning", the result can include events that start before the start
    time, in which case shifting will only shift the earliest onset to 0,
    which means the shift amount depends upon the content. (Negative onsets
    are currently not allowed.)

    The resulting Score, Part, and other content will have onset and offset
    times matching start and end, even if some content starts earlier or
    ends later.

    Parameters
    ----------
    start : float
        The start time of the slice, inclusive. If units is "measures" or
        "bars", start is a 0-based measure number of the first measure.
    end : float
        The end time of the slice, exclusive. For measures, end is the
        0-based measure number of the last measure plus one, so the last
        measure is end - 1.
    units : str
        The time units for start and end. Valid values are "quarters", "s",
        "sec", "seconds", "measures", or "bars".
    shift: bool
        If true, shift the content in the result so that the result starts
        time 0.0. If false (default), the content in the result retains
        the same time values as in the original Score.
    mode : Optional[str]
        The slicing mode, ignored if units is "measures" or "bars".
        Valid values are:

        - `"onsets"` - include events that start within bounds (default)
        - `"overlaps"` - include events that overlap (either onset or
            offset) is within the bounds. An event ending is considered
            to overlap if its offset is greater than start.
        - `"offsets"` - include events that end within the bounds
        - `"strict"` - include only events that start at or after start
            and end at or before end. (End times that are exactly equal
            to end are considered to be within bounds, so this is
            inclusive of end time.)

    truncate: Optional[str]
        How to handle events that partially overlap the bounds,
        ignored if units is "measures" or "bars". Valid values are:

        - `"truncate"` - truncate (clip) events that partially overlap
            the bounds. If the event onset is before start, the onset
            is increased to start (adjusting duration to maintain the
            offset time). Also, if the event offset is after end, the
            duration is decreased so that the offset time is end.
        - `"keep"` - no modification/truncation (default). Note that
            with the default mode="onsets", no event onsets will be
            earlier than start, but offsets may extend beyond end.
        - `"end"` or "ending" or "dur" or "duration" - truncate (clip)
            events that extend beyond end so that all offsets <= end.
        - `"beginning"` - events with onsets before start are moved to
            make their onsets equal to start, and their duration is
            adjusted to maintain the original offset.

    min_duration: Optional[float]
        Events with duration less than min_duration (after any truncation
        is applied) are removed.  Ignored if units is "measures" or "bars".
        If None or 0.0, no events are removed. The default is 0.05,
        independent of time units. Be careful with gracenotes that, when
        read from MusicXML, have zero duration.

    Returns
    -------
    Score
        A new Score instance containing the content between start and end.

    Raises
    ------
    ValueError
        If the Sequence is not part of a Score, or if invalid values are
        provided for the parameters.
    """
    score = self.score
    if score is None:
        raise ValueError("slice can only be called on a Sequence that is "
                         "part of a Score")
    if score.is_flat():
        if units in ("measures", "bars"):
            raise ValueError(f"units cannot be {units} for slicing a "
                             "flat score")
    else:
        if units not in ("measures", "bars"):
            raise ValueError(f"units must be measures or bars for slicing "
                "a score with Measures (or flatten the score before "
                "slicing)")

    if units in ("quarters", "measures", "bars"):
        score.convert_to_quarters()
    elif units in ("s", "sec", "seconds"):
        score.convert_to_seconds()
    else:
        raise ValueError('units must be "quarters", "measures, "'
                         '"bars", "s", "sec", or "seconds"')

    # Find start time and end time for slice. It may not be (start, end)
    # if units is measures or bars.
    if units in ("measures", "bars"):
        (start_time, end_time) = self.measure_times(int(start))
        if end != start:
            (_, end_time) = self.measure_times(int(end) - 1)
    else:
        start_time = start
        end_time = end

    # construct the parts of the tree above self and make an empty copy
    # of self to add the slice content.
    result = (score.emptycopy() if isinstance(self, Score)
              else self._copy_parents(start_time, end_time))
    result.onset = start_time  # result is an empty copy of self. Set the
    result.offset = end_time   # onset and offset to the slice bounds.
    if units in ("measures", "bars"):
        c_min, c_max = result._add_measure_children(self, start, end,
                                                    start_time, end_time)
        if c_min < start_time or c_max > end_time:
            raise ValueError("unexpectedly found content outside the "
                             "measure slice bounds")
        min_time = c_min
        max_time = c_max
    else:   
        min_time, max_time = result._add_slice_children(self, start_time,
                                  end_time, mode, truncate, min_duration)
    result._trim_map_and_signatures(min_time, max_time)
    if shift and min_time != float("inf") and min_time > 0:
        result.time_shift(-min_time)
    return result

pack

pack(onset: float = 0.0, sequential: bool = True) -> float

Adjust the content to be sequential.

The resulting content will begin with the parameter onset (defaults to 0), and each other object will get an onset equal to the offset of the previous element. The duration of self is set to the offset of the last element. This method essentially arranges the content to eliminate gaps. pack() works recursively on elements that are EventGroups.

Be careful not to pack Measures (directly or through recursion) if the Measure's content durations do not add up to the intended quarters per measure.

To override the sequential behavior, set the sequential parameter to False. In that case, pack behaves like the Concurrence.pack() method.

The pack method alters self and its content in place.

Parameters:

  • onset (float, default: 0.0 ) –

    The onset (start) time for this object.

Returns:

  • float

    duration of self

Source code in amads/core/basics.py
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
def pack(self, onset: float = 0.0, sequential: bool = True) -> float:
    """Adjust the content to be sequential.

    The resulting content will begin with the parameter `onset`
    (defaults to 0), and each other object will get an onset equal
    to the offset of the previous element. The duration of self is
    set to the offset of the last element.  This method essentially
    arranges the content to eliminate gaps. pack() works recursively
    on elements that are `EventGroups`.

    Be careful not to pack `Measures` (directly or through
    recursion) if the Measure's content durations do not add up to
    the intended quarters per measure.

    To override the sequential behavior, set the `sequential` 
    parameter to False.  In that case, pack behaves like the
    `Concurrence.pack()` method.

    The pack method alters self and its content in place.

    Parameters
    ----------
    onset : float
        The onset (start) time for this object.

    Returns
    -------
    float
        duration of self
    """
    return super().pack(onset, sequential)

Concurrence

Concurrence(
    parent: Optional[EventGroup] = None,
    onset: Optional[float] = None,
    duration: Optional[float] = None,
    content: Optional[list[Event]] = None,
)

Bases: EventGroup

Concurrence (abstract class) represents a group of simultaneous children.

However, children can have a non-zero onset to represent events organized in time). Thus, the main distinction between Concurrence and Sequence is that a Sequence can be constructed with pack=True to force sequential timing of the content. Note that a Sequence can have overlapping or entirely simultaneous Events as well.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    The containing object or None.

  • onset (Optional[float], default: None ) –

    The onset (start) time. None means unknown, to be set when Sequence is added to a parent.

  • duration (Optional[float], default: None ) –

    The duration in quarters or seconds. (If duration is omitted or None, the duration is set so that self.offset ends at the max offset in content, or 0 if there is no content.)

  • content (Optional[list[Event]], default: None ) –

    A list of Event objects to be added to the group. Content events with onsets of None are set to the offset of the concurrence, or zero if onset is None.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (Optional[float]) –

    The onset (start) time. None represents "unknown" and to be determined when this object is added to a parent.

  • duration (float) –

    The duration in quarters or seconds.

  • content (list[Event]) –

    Elements contained within this collection.

Source code in amads/core/basics.py
2662
2663
2664
2665
2666
def __init__(self, parent: Optional["EventGroup"] = None,
             onset: Optional[float] = None,
             duration: Optional[float] = None,
             content: Optional[list[Event]] = None):
    super().__init__(parent, onset, duration, content)

Attributes

onset property writable

onset: float

Retrieve the onset (start) time.

If the onset is None, raise an exception. (Events can have None onset times, but they must be set before retrieval. onsets that are None are automatically set when the Event is added to an EventGroup.)

Returns:

  • float

    The onset (start) time.

Raises:

  • ValueError

    If the onset time is not set (None).

units_are_seconds property

units_are_seconds: bool

Check if the times are in seconds.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in seconds. If not in a score, False is returned.

units_are_quarters property

units_are_quarters: bool

Check if the times are in quarters.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in quarters. If not in a score, False is returned.

offset property writable

offset: float

Retrieve the global offset (stop) time.

Returns:

  • float

    The global offset (stop) time.

part property

part: Optional[Part]

Retrieve the Part containing this event.

Returns:

  • Optional[Part]

    The Part containing this event or None if not found.

score property

score: Optional[Score]

Retrieve the Score containing this event, or self if it is a score.

Returns:

  • Optional[Score]

    The Score containing this event or None if not found.

staff property

staff: Optional[Staff]

Retrieve the Staff containing this event

Returns:

  • Optional[Staff]

    The Staff containing this event or None if not found.

measure property

measure: Optional[Measure]

Retrieve the Measure containing this event

Returns:

  • Optional[Measure]

    The Measure containing this event or None if not found.

Functions

set

set(property: str, value: Any) -> Event

Set a named property on this Event.

Every event can be extended with additional properties. Although Python objects are already extensible with new attributes, new attributes that are not set in __init__ confuse type checkers and other tools, so every Event has an info attribute as a dictionary where additional, application-specific information can be stored. The info attribute is None to save space until the first property is set, so you should use set and get methods and avoid writing event.info[property].

Parameters:

  • property (str) –

    The name of the property to set.

  • value (Any) –

    The value to assign to the property.

Returns:

  • Event

    returns this object (self)

Examples:

>>> note = Note()
>>> note.get("color", "no color")
'no color'
>>> _ = note.set("color", "red").set("harmonicity", 0.2)
>>> (note.has("color"), note.has("shape"))
(True, False)
>>> (note.get("color"), note.get("harmonicity"))
('red', 0.2)
Source code in amads/core/basics.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def set(self, property : str, value : Any) -> "Event":
    """Set a named property on this Event.

    Every event can be extended with additional properties. Although
    Python objects are already extensible with new attributes, new
    attributes that are not set in `__init__` confuse type checkers
    and other tools, so every `Event` has an `info` attribute as a
    dictionary where additional, application-specific information can
    be stored. The `info` attribute is `None` to save space until the
    first property is set, so you should use `set` and `get` methods
    and avoid writing `event.info[property]`.

    Parameters
    ----------
    property : str
        The name of the property to set.
    value : Any
        The value to assign to the property.

    Returns
    -------
    Event
        returns this object (self)

    Examples
    --------
    >>> note = Note()
    >>> note.get("color", "no color")
    'no color'
    >>> _ = note.set("color", "red").set("harmonicity", 0.2)
    >>> (note.has("color"), note.has("shape"))
    (True, False)
    >>> (note.get("color"), note.get("harmonicity"))
    ('red', 0.2)
    """
    if self.info is None:
        self.info = {}
    self.info[property] = value
    return self

get

get(property: str, default: Any = None) -> Any

Get the value of a property from this Event.

See set for more details.

Parameters:

  • property (str.) –

    The name of the property to get.

  • default (Any, default: None ) –

    The default value to return if the property is not found.

Returns:

  • Any

    The value of the specified property.

Source code in amads/core/basics.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def get(self, property : str, default : Any = None) -> Any:
    """Get the value of a property from this Event.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str.
        The name of the property to get.
    default : Any
        The default value to return if the property is not found.

    Returns
    -------
    Any
        The value of the specified property.
    """
    if self.info is None:
        return default
    return self.info.get(property, default)

has

has(property) -> bool

Check if the Event has a specific property.

See set for more details.

Parameters:

  • property (str) –

    The name of the property to check.

Returns:

  • bool

    True if the property exists, False otherwise.

Source code in amads/core/basics.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def has(self, property) -> bool:
    """Check if the Event has a specific property.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str
        The name of the property to check.

    Returns
    -------
    bool
        True if the property exists, False otherwise.
    """
    return (self.info is not None) and (property in self.info)

time_shift

time_shift(increment: float, content_only: bool = False) -> EventGroup

Change the onset by an increment, affecting all content.

If content_only is true, preserves EventGroup times (Score, Part, Staff, but not Chord or Measure) and shifts only the content (recursively). Otherwise, shifts this container and all content by the increment. Container onsets (recursively) are not allowed to become negative, so the onset time is set to zero if the increment would make it negative. However, even if the onset is is not shifted by increment, time_shift is still applied recursively to the content, and non-EventGroup events (e.g., Notes) are allowed to have negative onsets, even if this may not be well-defined for all AMADS operations.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

  • content_only (bool, default: False ) –

    If true, preserves this container's time and shifts only the content.

Returns:

  • Event

    The object. This method modifies the EventGroup.

Raises:

  • ValueError

    If the EventGroup has an unknown (None) onset and content_only is false.

Source code in amads/core/basics.py
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
def time_shift(self, increment: float,
               content_only: bool = False) -> "EventGroup":
    """
    Change the onset by an increment, affecting all content.

    If content_only is true, preserves EventGroup times (Score, Part,
    Staff, but *not* Chord or Measure) and shifts only the content
    (recursively). Otherwise, shifts this container and all content by the
    increment. Container onsets (recursively) are not allowed to become
    negative, so the onset time is set to zero if the increment would
    make it negative. However, even if the onset is is not shifted by
    increment, time_shift is still applied recursively to the content,
    and non-EventGroup events (e.g., Notes) are allowed to have negative
    onsets, even if this may not be well-defined for all AMADS operations.

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).
    content_only: bool
        If true, preserves this container's time and shifts only
        the content.

    Returns
    -------
    Event
        The object. This method modifies the `EventGroup`.

    Raises
    ------
    ValueError
        If the EventGroup has an unknown (None) onset and
        content_only is false.
    """
    # note that Chord and Measures are special cases
    if not content_only or isinstance(self, (Chord, Measure)):
        if self._onset is None:
            raise ValueError(
                    "Cannot shift time of EventGroup with unknown onset")
        self._onset = max(0.0, self._onset + increment)
    for elem in self.content:
        elem.time_shift(increment, content_only)
    return self

insert_copy_into

insert_copy_into(parent: Optional[EventGroup] = None) -> Event

Make a (mostly) deep copy of the Event and add to a new parent.

Pitch objects are considered immutable and are shared rather than copied.

Parameters:

  • parent (Optional(EventGroup), default: None ) –

    The copied Event will be a child of parent if not None. The parent is modified by this operation.

Returns:

  • Event

    A deep copy (except for parent and pitch) of the Event instance.

Source code in amads/core/basics.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def insert_copy_into(self,
                     parent: Optional["EventGroup"] = None) -> "Event":
    """
    Make a (mostly) deep copy of the `Event` and add to a new `parent`.

    `Pitch` objects are considered immutable and are shared rather
    than copied.

    Parameters
    ----------
    parent : Optional(EventGroup)
        The copied `Event` will be a child of `parent` if not `None`.
        The parent is modified by this operation.

    Returns
    -------
    Event
        A deep copy (except for parent and pitch) of the Event instance.
    """
    # remove link to parent to break link going up the tree
    # preventing deep copy from copying the entire tree
    original_parent = self.parent
    self.parent = None
    c = copy.deepcopy(self)  # deep copy of this event down to leaf nodes
    self.parent = original_parent  # restore link to parent
    if parent:
        parent.insert(c)
    return c

ismonophonic

ismonophonic() -> bool

Determine if content is monophonic (non-overlapping notes).

A monophonic list of notes has no overlapping notes (e.g., chords). Serves as a helper function for ismonophonic and parts_are_monophonic.

Returns:

  • bool

    True if the list of notes is monophonic, False otherwise.

Source code in amads/core/basics.py
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
def ismonophonic(self) -> bool:
    """
    Determine if content is monophonic (non-overlapping notes).

    A monophonic list of notes has no overlapping notes (e.g., chords).
    Serves as a helper function for `ismonophonic` and
    `parts_are_monophonic`.

    Returns
    -------
    bool
        True if the list of notes is monophonic, False otherwise.
    """
    prev = None
    notes = self.list_all(Note)
    # Sort the notes by start time
    notes.sort(key=lambda note: note.onset)
    # Check for overlaps
    for note in notes:
        if prev:
            # 0.01 is to prevent precision errors when comparing floats
            if note.onset - prev.offset < -0.01:
                return False
        prev = note
    return True

insert_emptycopy_into

insert_emptycopy_into(
    parent: Optional[EventGroup] = None,
) -> EventGroup

Create a deep copy of the EventGroup except for content.

A new parent is provided as an argument and the copy is inserted into this parent. This method is useful for copying an EventGroup without copying its content. See also insert_copy_into to copy an EventGroup with its content into a new parent.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    The new parent to insert the copied Event into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with the new parent (if any) and no content.

Source code in amads/core/basics.py
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
def insert_emptycopy_into(self, 
            parent: Optional["EventGroup"] = None) -> "EventGroup":
    """Create a deep copy of the EventGroup except for content.

    A new parent is provided as an argument and the copy is inserted
    into this parent. This method is  useful for copying an
    EventGroup without copying its content.  See also
    [insert_copy_into][amads.core.basics.Event.insert_copy_into] to
    copy an EventGroup *with* its content into a new parent.

    Parameters
    ----------
    parent : Optional[EventGroup]
        The new parent to insert the copied Event into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with the new parent
        (if any) and no content.
    """
    # rather than customize __deepcopy__, we "hide" the content to avoid
    # copying it. Then we restore it after copying and fix parent.
    original_content = self.content
    self.content = []
    c = self.insert_copy_into(parent)
    self.content = original_content
    return c  #type: ignore (c will always be an EventGroup)

expand_chords

expand_chords(parent: Optional[EventGroup] = None) -> EventGroup

Replace chords with the multiple notes they contain.

Returns a deep copy with no parent unless parent is provided. Normally, you will call score.expand_chords() which returns a deep copy of Score with notes moved from each chord to the copy of the chord's parent (a Measure or a Part). The parent parameter is primarily for internal use when expand_chords is called recursively on score content.

Parameters:

  • parent (EventGroup, default: None ) –

    The new parent to insert the copied EventGroup into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with all Chord instances expanded.

Source code in amads/core/basics.py
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
def expand_chords(self,
                  parent: Optional["EventGroup"] = None) -> "EventGroup":
    """Replace chords with the multiple notes they contain.

    Returns a deep copy with no parent unless parent is provided.
    Normally, you will call `score.expand_chords()` which returns a deep
    copy of Score with notes moved from each chord to the copy of the
    chord's parent (a Measure or a Part). The parent parameter is 
    primarily for internal use when `expand_chords` is called recursively
    on score content.

    Parameters
    ----------
    parent : EventGroup
        The new parent to insert the copied EventGroup into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with all
        Chord instances expanded.
    """
    group = self.insert_emptycopy_into(parent)
    for item in self.content:
        if isinstance(item, Chord):
            for note in item.content:  # expand chord
                note.insert_copy_into(group)
        if isinstance(item, EventGroup):
            item.expand_chords(group)  # recursion for deep copy/expand
        else:
            item.insert_copy_into(group)  # deep copy non-EventGroup
    return group

find_all

find_all(elem_type: Type[Event]) -> Generator[Event, None, None]

Find all instances of a specific type within the EventGroup.

Assumes that objects of type elem_type are not nested within other objects of the same type. (The first elem_type encountered in a depth-first enumeration is returned without looking at any children in its content).

Parameters:

  • elem_type (Type[Event]) –

    The type of event to search for.

Yields:

  • Event

    Instances of the specified type found within the EventGroup.

Source code in amads/core/basics.py
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
def find_all(self, elem_type: Type[Event]) -> Generator[Event, None, None]:
    """Find all instances of a specific type within the EventGroup.

    Assumes that objects of type `elem_type` are not nested within
    other objects of the same type. (The first `elem_type` encountered
    in a depth-first enumeration is returned without looking at any
    children in its `content`).

    Parameters
    ----------
    elem_type : Type[Event]
        The type of event to search for.

    Yields
    -------
    Event
        Instances of the specified type found within the EventGroup.
    """
    # Algorithm: depth-first enumeration of EventGroup content.
    # If elem_types are nested, only the top-level elem_type is
    # returned since it is found first, and the content is not
    # searched. This makes it efficient, e.g., to search for
    # Parts in a Score without enumerating all Notes within.
    for elem in self.content:
        if isinstance(elem, elem_type):
            yield elem
        elif isinstance(elem, EventGroup):
            yield from elem.find_all(elem_type)

get_sorted_notes

get_sorted_notes(has_ties: bool = True) -> List[Note]

Return a list of sorted notes with merged ties.

This should generally be called on Parts and Scores since in all other EventGroups, Events are in time order and Notes retrieved with find_all() or list_all() are in time order. However, get_sorted_notes also sorts notes into increasing pitch (keynum) where note onsets are equal.

Parameters:

  • has_ties (bool, default: True ) –

    If True (default), copy the score, merge the ties, and return a list of these merged copies. If False, assume there are no ties and return a list of original notes.

Raises:

  • ValueError

    If has_ties is False, but a tie is encountered.

Returns:

  • list(Note)

    a list of sorted notes with merged ties

Source code in amads/core/basics.py
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
def get_sorted_notes(self, has_ties: bool = True) -> List[Note]:
    """Return a list of sorted notes with merged ties.

    This should generally be called on Parts and Scores since
    in all other EventGroups, Events are in time order and
    Notes retrieved with `find_all()` or `list_all()` are in
    time order. However, `get_sorted_notes` *also* sorts notes
    into increasing pitch (`keynum`) where note onsets are equal.

    Parameters
    ----------
    has_ties: bool
        If True (default), copy the score, merge the ties, and
        return a list of these merged copies. If False, assume
        there are no ties and return a list of original notes.

    Raises
    ------
    ValueError
        If has_ties is False, but a tie is encountered.

    Returns
    -------
    list(Note)
        a list of sorted notes with merged ties
    """
    if has_ties:
        # after flatten, score will have one Part with all Notes:
        return self.flatten(collapse=True).content[0].content  # type: ignore
    else:
        notes : List[Note] = cast(List[Note], self.list_all(Note))
        for note in notes:
            if note.tie is not None:
                raise ValueError(
                        "tie found by get_sorted_notes with has_ties=False")
        notes.sort(key=lambda x: (x.onset, x.pitch))
        return notes

has_instanceof

has_instanceof(the_class: Type[Event]) -> bool

Test if EventGroup contains any instances of the_class.

Parameters:

  • the_class (Type[Event]) –

    The class type to check for.

Returns:

  • bool

    True iff the EventGroup contains an instance of the_class.

Source code in amads/core/basics.py
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
def has_instanceof(self, the_class: Type[Event]) -> bool:
    """Test if EventGroup contains any instances of `the_class`.

    Parameters
    ----------
    the_class : Type[Event]
        The class type to check for.

    Returns
    -------
    bool
        True iff the EventGroup contains an instance of the_class.
    """
    instances = self.find_all(the_class)
    # if there are no instances (of the_class), next will return "empty":
    return next(instances, "empty") != "empty"

has_rests

has_rests() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Rest objects.

Returns:

  • bool

    True iff the EventGroup contains any Rest objects.

Source code in amads/core/basics.py
1787
1788
1789
1790
1791
1792
1793
1794
1795
def has_rests(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any `Rest` objects.

    Returns
    -------
    bool
        True iff the EventGroup contains any Rest objects.
    """
    return self.has_instanceof(Rest)

has_chords

has_chords() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Chord objects.

Returns:

  • bool

    True iff the EventGroup contains any Chord objects.

Source code in amads/core/basics.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
def has_chords(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any Chord objects.

    Returns
    -------
    bool
        True iff the EventGroup contains any Chord objects.
    """
    return self.has_instanceof(Chord)

has_ties

has_ties() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any tied notes.

Returns:

  • bool

    True iff the EventGroup contains any tied notes.

Source code in amads/core/basics.py
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
def has_ties(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any tied notes.

    Returns
    -------
    bool
        True iff the EventGroup contains any tied notes.
    """
    notes = self.find_all(Note)
    for note in notes:
        if note.tie:
            return True
    return False

has_measures

has_measures() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Measures.

Returns:

  • bool

    True iff the EventGroup contains any Measure objects.

Source code in amads/core/basics.py
1824
1825
1826
1827
1828
1829
1830
1831
1832
def has_measures(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any Measures.

    Returns
    -------
    bool
        True iff the EventGroup contains any Measure objects.
    """
    return self.has_instanceof(Measure)

inherit_duration

inherit_duration() -> EventGroup

Set the duration of this EventGroup according to maximum offset.

The duration is set to the maximum offset (end) time of the children. If the EventGroup is empty, the duration is set to 0. This method modifies this EventGroup instance.

Returns:

  • EventGroup

    The EventGroup instance (self) with updated duration.

Source code in amads/core/basics.py
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
def inherit_duration(self) -> "EventGroup":
    """Set the duration of this EventGroup according to maximum offset.

    The `duration` is set to the maximum offset (end) time of the
    children. If the EventGroup is empty, the duration is set to 0.
    This method modifies this `EventGroup` instance.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with updated duration.
    """
    onset = 0 if self._onset == None else self._onset
    max_offset = onset
    for elem in self.content:
        max_offset = max(max_offset, elem.offset)
    self.duration = max_offset - onset

    return self

insert

insert(event: Event) -> EventGroup

Insert an event.

Sets the parent of event to this EventGroup and makes event be a member of this EventGroup.content. No changes are made to event.onset or self.duration. Insert event in content just before the first element with a greater onset. The method modifies this object (self).

Parameters:

  • event (Event) –

    The event to be inserted.

Returns:

  • EventGroup

    The EventGroup instance (self) with the event inserted.

Raises:

  • ValueError

    If event._onset is None (it must be a number)

Caution Regarding Zero-Duration Event Order

If you have note N with non-zero duration and, at the same time, a grace note G with zero duration, the notes will be ordered according to when they are inserted. So if you insert N and then G, then N will be placed before G. See io.pt_import.py, where this case is dealt with.

Source code in amads/core/basics.py
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
def insert(self, event: Event) -> "EventGroup":
    """Insert an event.

    Sets the `parent` of `event` to this `EventGroup` and makes `event`
    be a member of this `EventGroup.content`. No changes are made to
    `event.onset` or `self.duration`. Insert `event` in `content` just
    before the first element with a greater onset. The method modifies
    this object (self).

    Parameters
    ----------
    event : Event
        The event to be inserted.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with the event inserted.

    Raises
    ------
    ValueError
        If event._onset is None (it must be a number)

    Caution Regarding Zero-Duration Event Order
    -------------------------------------------
    If you have note N with non-zero duration and, at the same
    time, a grace note G with zero duration, the notes will be
    ordered according to when they are inserted. So if you insert
    N and then G, then N will be placed *before* G. See
    io.pt_import.py, where this case is dealt with.
    """

    assert not event.parent
    if event._onset is None:  # must be a number
        raise ValueError(f"event's _onset attribute must be a number")
    atend = self.last()
    if atend and event.onset < atend.onset:
        # search in reverse from end
        i = len(self.content) - 2
        while i >= 0 and self.content[i].onset > event.onset:
            i -= 1
        # now i is either -1 or content[i] <= event.onset, so
        # insert event at content[i+1]
        self.content.insert(i + 1, event)
    else:  # simply append at the end of content:
        self.content.append(event)
    event.parent = self
    return self

last

last() -> Optional[Event]

Retrieve the last event in the content list.

Because the content list is sorted by onset, the returned Event is simply the last element of content, but not necessarily the event with the greatest offset.

Returns:

  • Optional[Event]

    The last event in the content list or None if the list is empty.

Source code in amads/core/basics.py
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
def last(self) -> Optional[Event]:
    """Retrieve the last event in the content list.

    Because the `content` list is sorted by `onset`, the returned
    `Event` is simply the last element of `content`, but not
    necessarily the event with the greatest *`offset`*.

    Returns
    -------
    Optional[Event]
        The last event in the content list or None if the list is empty.
    """
    return self.content[-1] if len(self.content) > 0 else None

list_all

list_all(elem_type: Type[Event]) -> list[Event]

Find all instances of a specific type within the EventGroup.

Assumes that objects of type elem_type are not nested within other objects of the same type. See also find_all, which returns a generator instead of a list.

Parameters:

  • elem_type (Type[Event]) –

    The type of event to search for.

Returns:

  • list[Event]

    A list of all instances of the specified type found within the EventGroup.

Source code in amads/core/basics.py
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
def list_all(self, elem_type: Type[Event]) -> list[Event]:
    """Find all instances of a specific type within the EventGroup.

    Assumes that objects of type `elem_type` are not nested within
    other objects of the same type.  See also
    [find_all][amads.core.basics.EventGroup.find_all], which returns
    a generator instead of a list.

    Parameters
    ----------
    elem_type : Type[Event]
        The type of event to search for.

    Returns
    -------
    list[Event]
        A list of all instances of the specified type found
        within the EventGroup.
    """
    return list(self.find_all(elem_type))

merge_tied_notes

merge_tied_notes(
    parent: Optional[EventGroup] = None, ignore: list[Note] = []
) -> EventGroup

Create a new EventGroup with tied notes replaced by single notes.

If ties cross staffs, the replacement is placed in the staff of the first note in the tied sequence. Insert the new EventGroup into parent.

Ordinarily, this method is called on a Score with no parameters. The parameters are used when Score.merge_tied_notes() calls this method recursively on EventGroups within the Score such as Parts and Staffs.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    Where to insert the result.

  • ignore (list[Note], default: [] ) –

    This parameter is used internally. Caller should not use this parameter.

Returns:

  • EventGroup

    A copy with tied notes replaced by equivalent single notes.

Source code in amads/core/basics.py
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
def merge_tied_notes(self, parent: Optional["EventGroup"] = None,
                     ignore: list[Note] = []) -> "EventGroup":
    """Create a new `EventGroup` with tied notes replaced by single notes.

    If ties cross staffs, the replacement is placed in the staff of the
    first note in the tied sequence. Insert the new `EventGroup` into
    `parent`.

    Ordinarily, this method is called on a Score with no parameters. The
    parameters are used when `Score.merge_tied_notes()` calls this method
    recursively on `EventGroup`s within the Score such as `Part`s and
    `Staff`s.

    Parameters
    ----------
    parent: Optional(EventGroup)
        Where to insert the result.

    ignore: Optional(list[Note])
        This parameter is used internally. Caller should not use
        this parameter.

    Returns
    -------
    EventGroup
        A copy with tied notes replaced by equivalent single notes.
    """
    # Algorithm: Find all notes, removing tied notes and updating
    # duration when ties are found. These tied notes are added to
    # ignore so they can be skipped when they are encountered.

    group = self.insert_emptycopy_into(parent)
    for event in self.content:
        if isinstance(event, Note):
            if event in ignore:  # do not copy tied notes into group;
                if event.tie:
                    ignore.append(event.tie)  # add tied note to ignore
                # We will not see this note again, so
                # we can also remove it from ignore. Removal is expensive
                # but it could be worse for ignore to grow large when there
                # are many ties since we have to search it entirely once
                # per note. An alternate representation might be a set to
                # make searching fast.
                ignore.remove(event)
            else:
                if event.tie:
                    tied_note = event.tie  # save the tied-to note
                    event.tie = None  # block the copy
                    ignore.append(tied_note)
                    # copy note into group:
                    event_copy = event.insert_copy_into(group)
                    event.tie = tied_note  # restore original event
                    # this is subtle: event.tied_duration (a property) will
                    # sum up durations of all the tied notes. Since
                    # event_copy is not tied, the sum of durations is
                    # stored on that one event_copy:
                    event_copy.duration = event.tied_duration
                else:  # put the untied note into group
                    event.insert_copy_into(group)
        elif isinstance(event, EventGroup):
            event.merge_tied_notes(group, ignore)
        else:
            event.insert_copy_into(group)  # simply copy to new parent
    return group

pack

pack(onset: float = 0.0, sequential: bool = False) -> float

Adjust the content to onsets starting with the onset parameter.

By default onsets are set to onset and the duration of self is set to the maximum duration of the content. pack() works recursively on elements that are EventGroups. Setting sequential to True implements sequential packing, where events are placed one after another.

Parameters:

  • onset (float, default: 0.0 ) –

    The onset (start) time for this object.

Returns:

  • float

    duration of self

Source code in amads/core/basics.py
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
def pack(self, onset: float = 0.0, sequential : bool = False) -> float:
    """Adjust the content to onsets starting with the onset parameter.

    By default onsets are set to `onset` and the duration of self is set to
    the maximum duration of the content. pack() works recursively on
    elements that are EventGroups. Setting sequential to True implements
    sequential packing, where events are placed one after another.

    Parameters
    ----------
    onset : float
        The onset (start) time for this object.

    Returns
    -------
    float
        duration of self
    """
    self.onset = onset
    self.duration = 0
    for elem in self.content:
        elem.onset = onset
        if isinstance(elem, EventGroup):   # either Sequence or Concurrence
            elem.duration = elem.pack(onset)  #type: ignore
        if sequential:
            onset += elem.duration
        else:
            self.duration = max(self.duration, elem.duration)
    if sequential:
        self.duration = onset - self.onset
    return self.duration

quantize

quantize(divisions: int) -> EventGroup

Align onsets and durations to a rhythmic grid.

Assumes time units are quarters. (See Score.convert_to_quarters.)

Modify all times and durations to a multiple of divisions per quarter note, e.g., 4 for sixteenth notes. Onsets and offsets are moved to the nearest quantized time. Any resulting duration change is less than one quantum, but not necessarily less than 0.5 quantum, since the onset and offset can round in opposite directions by up to 0.5 quantum each. Any non-zero duration that would quantize to zero duration gets a duration of one quantum since zero duration is almost certainly going to cause notation and visualization problems.

Special cases for zero duration:

  1. If the original duration is zero as in metadata or possibly grace notes, we preserve that.
  2. If a tied note duration quantizes to zero, we remove the tied note entirely provided some other note in the tied sequence has non-zero duration. If all tied notes quantize to zero, we keep the first one and set its duration to one quantum.

This method modifies this EventGroup and all its content in place.

Note that there is no way to specify "sixteenths or eighth triplets" because 6 would not allow sixteenths and 12 would admit sixteenth triplets. Using tuples as in Music21, e.g., (4, 3) for this problem creates another problem: if quantization is to time points 1/4, 1/3, then the difference is 1/12 or a thirty-second triplet. If the quantization is applied to durations, then you could have 1/4 + 1/3 = 7/12, and the remaining duration in a single beat would be 5/12, which is not expressible as sixteenths, eighth triplets or any tied combination.

Parameters:

  • divisions (int) –

    The number of divisions per quarter note, e.g., 4 for sixteenths, to control quantization.

Returns:

  • EventGroup

    The EventGroup instance (self) with (modified in place) quantized times.

Source code in amads/core/basics.py
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
def quantize(self, divisions: int) -> "EventGroup":
    """Align onsets and durations to a rhythmic grid.

    Assumes time units are quarters. (See [Score.convert_to_quarters](
            basics.md#amads.core.basics.Score.convert_to_quarters).)

    Modify all times and durations to a multiple of divisions
    per quarter note, e.g., 4 for sixteenth notes. Onsets and offsets
    are moved to the nearest quantized time. Any resulting duration
    change is less than one quantum, but not necessarily less than
    0.5 quantum, since the onset and offset can round in opposite
    directions by up to 0.5 quantum each. Any non-zero duration that would
    quantize to zero duration gets a duration of one quantum since
    zero duration is almost certainly going to cause notation and
    visualization problems.

    Special cases for zero duration:

    1. If the original duration is zero as in metadata or possibly
           grace notes, we preserve that.
    2. If a tied note duration quantizes to zero, we remove the
           tied note entirely provided some other note in the tied
           sequence has non-zero duration. If all tied notes quantize
           to zero, we keep the first one and set its duration to
           one quantum.

    This method modifies this EventGroup and all its content in place.

    Note that there is no way to specify "sixteenths or eighth triplets"
    because 6 would not allow sixteenths and 12 would admit sixteenth
    triplets. Using tuples as in Music21, e.g., (4, 3) for this problem
    creates another problem: if quantization is to time points 1/4, 1/3,
    then the difference is 1/12 or a thirty-second triplet. If the
    quantization is applied to durations, then you could have 1/4 + 1/3
    = 7/12, and the remaining duration in a single beat would be 5/12,
    which is not expressible as sixteenths, eighth triplets or any tied
    combination.

    Parameters
    ----------
    divisions : int
        The number of divisions per quarter note, e.g., 4 for
        sixteenths, to control quantization.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with (modified in place) 
        quantized times.
    """

    super()._quantize(divisions)
    # iterating through content is tricky because we may delete a
    # Note, shifting the content:
    i = 0
    while i < len(self.content):
        event = self.content[i]
        event._quantize(divisions)
        if event == self.content[i]:
            i += 1
        # otherwise, we deleted event so the next event to
        # quantize is at index i; don't incremenet i
    return self

remove

remove(element: Event) -> EventGroup

Remove an element from the content list.

The method modifies this object (self).

Parameters:

  • element (Event) –

    The event to be removed.

Returns:

  • EventGroup

    The EventGroup instance (self) with the element removed. The returned value is not a copy.

Source code in amads/core/basics.py
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
def remove(self, element: Event) -> "EventGroup":
    """Remove an element from the content list. 

    The method modifies this object (self).

    Parameters
    ----------
    element : Event
        The event to be removed.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with the element removed.
        The returned value is not a copy.
    """
    self.content.remove(element)
    element.parent = None
    return self

remove_rests

remove_rests(parent: Union[EventGroup, None] = None) -> EventGroup

Remove all Rest objects from content.

Returns a deep copy with no parent unless parent is provided.

Parameters:

  • parent (EventGroup, default: None ) –

    The new parent to insert the copied Event into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with all Rest objects removed.

Source code in amads/core/basics.py
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
def remove_rests(self, parent: Union["EventGroup", 
                                     None] = None) -> "EventGroup":
    """Remove all Rest objects from content.

    Returns a deep copy with no parent unless parent is provided.

    Parameters
    ----------
    parent : EventGroup
        The new parent to insert the copied Event into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with all Rest
        objects removed.
    """
    # implementation detail: when called without argument, remove_rests
    # makes a deep copy of the subtree and returns the copy without a
    # parent. remove_rests calls itself recursively *with* a parameter
    # indicating that the subtree copy should be inserted into a
    # parent which is the new copy at the next level up. Of course,
    # we check for and ignore Rests so they are never copied.
    group = self.insert_emptycopy_into(parent)
    for item in self.content:
        if isinstance(item, Rest):
            continue  # skip the Rests while making deep copy
        if isinstance(item, EventGroup):
            item.remove_rests(group)  # recursion for deep copy
        else:
            item.insert_copy_into(group)  # deep copy non-EventGroup
    return group

show

show(indent: int = 0, file: Optional[TextIO] = None) -> EventGroup

Print the EventGroup information.

Parameters:

  • indent (int, default: 0 ) –

    The indentation level for display.

Returns:

Source code in amads/core/basics.py
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
def show(self, indent: int = 0,
        file: Optional[TextIO] = None) -> "EventGroup":
    """Print the EventGroup information.

    Parameters
    ----------
    indent : int
        The indentation level for display.

    Returns
    -------
    EventGroup
        The EventGroup instance itself.
    """
    print(" " * indent, self, sep="", file=file)
    for elem in self.content:
        elem.show(indent + 4, file=file)  # type: ignore (show exists)
    return self

measure_times

measure_times(n: int) -> tuple[float, float]

Return the start and end times of measure n.

Parameters:

  • n (int) –

    The 0-based measure number.

Returns:

  • tuple(float, float)

    A tuple containing the start and end times of measure n. Measure 0 is the first measure. Units are the same as the score's time units.

Raises:

  • ValueError

    If there is no measure with number n.

Source code in amads/core/basics.py
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
def measure_times(self, n: int) -> tuple[float, float]:
    """Return the start and end times of measure n.

    Parameters
    ----------
    n : int
        The 0-based measure number.

    Returns
    -------
    tuple(float, float)
        A tuple containing the start and end times of measure n.
        Measure 0 is the first measure.  Units are the same as the
        score's time units.

    Raises
    ------
    ValueError
        If there is no measure with number n.
    """
    # Algorithm: For each Staff, linear search for nth Measure, returning
    # the onset and offset of the first one found.
    for staff in self.find_all(Staff):
        staff = cast(Staff, staff)
        for i, measure in enumerate(staff.find_all(Measure)):
            if i == n:
                return (measure.onset, measure.offset)
    raise ValueError(f"measure {n} not found")

slice

slice(
    start: float,
    end: float,
    units: str = "quarters",
    mode: str = "onsets",
    truncate: str = "keep",
    shift: bool = False,
    min_duration: float = 0.05,
) -> EventGroup

Create a new Score containing the content between start and end.

Typically, this method is called on a Score to create a new Score, but it works on any Sequence as long as the sequence is part of a Score.

If self has Measures, units must be "measures" or "bars", the start and end parameters are interpreted as 0-based measure numbers, and the result will therefore contain whole measures. It is assumed that notes are tied across measure boundaries. The result will contain only the parts of tied notes that are within the specified measures, excluding measure numbered by end.

For any units besides "measures" or "bars", the score must be flat. Notes that extend beyond the start or end time are included in the result unless the truncate parameter specifies otherwise.

In principle, there is no reason to require a flat score for slicing by time, but there are many difficult edge cases to consider such as ties from within one chord to a note in another measure. Therefore, to slice by time or quarter, you must have a flattened score. Conversely, to slice a full score, you must slice by measure so that the result gives you whole measures, which are encoded into the full Score structure.

The entire result can be shifted to start at time 0 by setting the shift parameter to True. Unless truncate is "truncate" or "beginning", the result can include events that start before the start time, in which case shifting will only shift the earliest onset to 0, which means the shift amount depends upon the content. (Negative onsets are currently not allowed.)

The resulting Score, Part, and other content will have onset and offset times matching start and end, even if some content starts earlier or ends later.

Parameters:

  • start (float) –

    The start time of the slice, inclusive. If units is "measures" or "bars", start is a 0-based measure number of the first measure.

  • end (float) –

    The end time of the slice, exclusive. For measures, end is the 0-based measure number of the last measure plus one, so the last measure is end - 1.

  • units (str, default: 'quarters' ) –

    The time units for start and end. Valid values are "quarters", "s", "sec", "seconds", "measures", or "bars".

  • shift (bool, default: False ) –

    If true, shift the content in the result so that the result starts time 0.0. If false (default), the content in the result retains the same time values as in the original Score.

  • mode (Optional[str], default: 'onsets' ) –

    The slicing mode, ignored if units is "measures" or "bars". Valid values are:

    • "onsets" - include events that start within bounds (default)
    • "overlaps" - include events that overlap (either onset or offset) is within the bounds. An event ending is considered to overlap if its offset is greater than start.
    • "offsets" - include events that end within the bounds
    • "strict" - include only events that start at or after start and end at or before end. (End times that are exactly equal to end are considered to be within bounds, so this is inclusive of end time.)
  • truncate (str, default: 'keep' ) –

    How to handle events that partially overlap the bounds, ignored if units is "measures" or "bars". Valid values are:

    • "truncate" - truncate (clip) events that partially overlap the bounds. If the event onset is before start, the onset is increased to start (adjusting duration to maintain the offset time). Also, if the event offset is after end, the duration is decreased so that the offset time is end.
    • "keep" - no modification/truncation (default). Note that with the default mode="onsets", no event onsets will be earlier than start, but offsets may extend beyond end.
    • "end" or "ending" or "dur" or "duration" - truncate (clip) events that extend beyond end so that all offsets <= end.
    • "beginning" - events with onsets before start are moved to make their onsets equal to start, and their duration is adjusted to maintain the original offset.
  • min_duration (float, default: 0.05 ) –

    Events with duration less than min_duration (after any truncation is applied) are removed. Ignored if units is "measures" or "bars". If None or 0.0, no events are removed. The default is 0.05, independent of time units. Be careful with gracenotes that, when read from MusicXML, have zero duration.

Returns:

  • Score

    A new Score instance containing the content between start and end.

Raises:

  • ValueError

    If the Sequence is not part of a Score, or if invalid values are provided for the parameters.

Source code in amads/core/basics.py
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
def slice(self, start: float, end: float, units: str = "quarters",
          mode: str = "onsets", truncate: str = "keep", shift: bool = False,
          min_duration: float = 0.05) -> "EventGroup":
    """
    Create a new Score containing the content between start and end.

    Typically, this method is called on a Score to create a new Score,
    but it works on any Sequence as long as the sequence is part of a Score.

    If self has Measures, units must be "measures" or "bars", the start and
    end parameters are interpreted as 0-based measure numbers, and the
    result will therefore contain whole measures. It is assumed that notes
    are tied across measure boundaries. The result will contain only the
    parts of tied notes that are within the specified measures, excluding
    measure numbered by `end`.

    For any units besides "measures" or "bars", the score must be flat.
    Notes that extend beyond the start or end time are included in the
    result unless the `truncate` parameter specifies otherwise.

    In principle, there is no reason to require a flat score for slicing by
    time, but there are many difficult edge cases to consider such as ties
    from within one chord to a note in another measure. Therefore, to slice
    by time or quarter, you must have a flattened score. Conversely, to
    slice a full score, you must slice by measure so that the result gives
    you whole measures, which are encoded into the full Score structure.

    The entire result can be shifted to start at time 0 by setting the
    `shift` parameter to True.  Unless `truncate` is "truncate" or
    "beginning", the result can include events that start before the start
    time, in which case shifting will only shift the earliest onset to 0,
    which means the shift amount depends upon the content. (Negative onsets
    are currently not allowed.)

    The resulting Score, Part, and other content will have onset and offset
    times matching start and end, even if some content starts earlier or
    ends later.

    Parameters
    ----------
    start : float
        The start time of the slice, inclusive. If units is "measures" or
        "bars", start is a 0-based measure number of the first measure.
    end : float
        The end time of the slice, exclusive. For measures, end is the
        0-based measure number of the last measure plus one, so the last
        measure is end - 1.
    units : str
        The time units for start and end. Valid values are "quarters", "s",
        "sec", "seconds", "measures", or "bars".
    shift: bool
        If true, shift the content in the result so that the result starts
        time 0.0. If false (default), the content in the result retains
        the same time values as in the original Score.
    mode : Optional[str]
        The slicing mode, ignored if units is "measures" or "bars".
        Valid values are:

        - `"onsets"` - include events that start within bounds (default)
        - `"overlaps"` - include events that overlap (either onset or
            offset) is within the bounds. An event ending is considered
            to overlap if its offset is greater than start.
        - `"offsets"` - include events that end within the bounds
        - `"strict"` - include only events that start at or after start
            and end at or before end. (End times that are exactly equal
            to end are considered to be within bounds, so this is
            inclusive of end time.)

    truncate: Optional[str]
        How to handle events that partially overlap the bounds,
        ignored if units is "measures" or "bars". Valid values are:

        - `"truncate"` - truncate (clip) events that partially overlap
            the bounds. If the event onset is before start, the onset
            is increased to start (adjusting duration to maintain the
            offset time). Also, if the event offset is after end, the
            duration is decreased so that the offset time is end.
        - `"keep"` - no modification/truncation (default). Note that
            with the default mode="onsets", no event onsets will be
            earlier than start, but offsets may extend beyond end.
        - `"end"` or "ending" or "dur" or "duration" - truncate (clip)
            events that extend beyond end so that all offsets <= end.
        - `"beginning"` - events with onsets before start are moved to
            make their onsets equal to start, and their duration is
            adjusted to maintain the original offset.

    min_duration: Optional[float]
        Events with duration less than min_duration (after any truncation
        is applied) are removed.  Ignored if units is "measures" or "bars".
        If None or 0.0, no events are removed. The default is 0.05,
        independent of time units. Be careful with gracenotes that, when
        read from MusicXML, have zero duration.

    Returns
    -------
    Score
        A new Score instance containing the content between start and end.

    Raises
    ------
    ValueError
        If the Sequence is not part of a Score, or if invalid values are
        provided for the parameters.
    """
    score = self.score
    if score is None:
        raise ValueError("slice can only be called on a Sequence that is "
                         "part of a Score")
    if score.is_flat():
        if units in ("measures", "bars"):
            raise ValueError(f"units cannot be {units} for slicing a "
                             "flat score")
    else:
        if units not in ("measures", "bars"):
            raise ValueError(f"units must be measures or bars for slicing "
                "a score with Measures (or flatten the score before "
                "slicing)")

    if units in ("quarters", "measures", "bars"):
        score.convert_to_quarters()
    elif units in ("s", "sec", "seconds"):
        score.convert_to_seconds()
    else:
        raise ValueError('units must be "quarters", "measures, "'
                         '"bars", "s", "sec", or "seconds"')

    # Find start time and end time for slice. It may not be (start, end)
    # if units is measures or bars.
    if units in ("measures", "bars"):
        (start_time, end_time) = self.measure_times(int(start))
        if end != start:
            (_, end_time) = self.measure_times(int(end) - 1)
    else:
        start_time = start
        end_time = end

    # construct the parts of the tree above self and make an empty copy
    # of self to add the slice content.
    result = (score.emptycopy() if isinstance(self, Score)
              else self._copy_parents(start_time, end_time))
    result.onset = start_time  # result is an empty copy of self. Set the
    result.offset = end_time   # onset and offset to the slice bounds.
    if units in ("measures", "bars"):
        c_min, c_max = result._add_measure_children(self, start, end,
                                                    start_time, end_time)
        if c_min < start_time or c_max > end_time:
            raise ValueError("unexpectedly found content outside the "
                             "measure slice bounds")
        min_time = c_min
        max_time = c_max
    else:   
        min_time, max_time = result._add_slice_children(self, start_time,
                                  end_time, mode, truncate, min_duration)
    result._trim_map_and_signatures(min_time, max_time)
    if shift and min_time != float("inf") and min_time > 0:
        result.time_shift(-min_time)
    return result

Chord

Chord(
    *args: Event,
    parent: Optional[EventGroup] = None,
    onset: Optional[float] = None,
    duration: Optional[float] = None
)

Bases: Concurrence

A collection of notes played together.

Typically, chords represent notes that would share a stem, and note start times and durations match the start time and duration of the chord, but none of this is enforced. The order of notes is arbitrary.

Normally, a Chord is a member of a Measure. There is no requirement that simultaneous or overlapping notes be grouped into Chords, so the Chord class is merely an optional element of music structure representation.

See Constructor Details.

Representation note: An alternative representation would be to subclass Note and allow a list of pitches, which has the advantage of enforcing the shared onsets and durations. However, there can be ties connected differently to each note within the Chord, thus we use a Concurrence with Note objects as elements. Each Note.tie can be None (no tie) or tie to a Note in another Chord or Measure.

Parameters:

  • *args (Event, default: () ) –

    The Event objects to be added to the group. Content events with onsets of None are set to the onset of the chord, or zero if onset is None.

  • parent (Optional[EventGroup], default: None ) –

    The containing object or None. Must be passed as a keyword parameter due to *args.

  • onset (Optional[float], default: None ) –

    The onset (start) time. None means unknown, to be set when Sequence is added to a parent. Must be passed as a keyword parameter due to *args.

  • duration (Optional[float], default: None ) –

    The duration in quarters or seconds. (If duration is omitted or None, the duration is set so that self.offset ends at the max offset of args, or 0 if there is no content.) Must be passed as a keyword parameter due to *args.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (Optional[float]) –

    The onset (start) time.

  • duration (float) –

    The duration in quarters or seconds.

  • content (list[Event]) –

    Elements contained within this collection.

Source code in amads/core/basics.py
2724
2725
2726
2727
2728
def __init__(self, *args: Event,
             parent: Optional[EventGroup] = None,
             onset: Optional[float] = None,
             duration: Optional[float] = None):
    super().__init__(parent, onset, duration, list(args))

Attributes

onset property writable

onset: float

Retrieve the onset (start) time.

If the onset is None, raise an exception. (Events can have None onset times, but they must be set before retrieval. onsets that are None are automatically set when the Event is added to an EventGroup.)

Returns:

  • float

    The onset (start) time.

Raises:

  • ValueError

    If the onset time is not set (None).

units_are_seconds property

units_are_seconds: bool

Check if the times are in seconds.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in seconds. If not in a score, False is returned.

units_are_quarters property

units_are_quarters: bool

Check if the times are in quarters.

This event must be in a Score (where _units_are_seconds is stored).

Returns:

  • bool

    True iff the event's times are in quarters. If not in a score, False is returned.

offset property writable

offset: float

Retrieve the global offset (stop) time.

Returns:

  • float

    The global offset (stop) time.

part property

part: Optional[Part]

Retrieve the Part containing this event.

Returns:

  • Optional[Part]

    The Part containing this event or None if not found.

score property

score: Optional[Score]

Retrieve the Score containing this event, or self if it is a score.

Returns:

  • Optional[Score]

    The Score containing this event or None if not found.

staff property

staff: Optional[Staff]

Retrieve the Staff containing this event

Returns:

  • Optional[Staff]

    The Staff containing this event or None if not found.

measure property

measure: Optional[Measure]

Retrieve the Measure containing this event

Returns:

  • Optional[Measure]

    The Measure containing this event or None if not found.

Functions

set

set(property: str, value: Any) -> Event

Set a named property on this Event.

Every event can be extended with additional properties. Although Python objects are already extensible with new attributes, new attributes that are not set in __init__ confuse type checkers and other tools, so every Event has an info attribute as a dictionary where additional, application-specific information can be stored. The info attribute is None to save space until the first property is set, so you should use set and get methods and avoid writing event.info[property].

Parameters:

  • property (str) –

    The name of the property to set.

  • value (Any) –

    The value to assign to the property.

Returns:

  • Event

    returns this object (self)

Examples:

>>> note = Note()
>>> note.get("color", "no color")
'no color'
>>> _ = note.set("color", "red").set("harmonicity", 0.2)
>>> (note.has("color"), note.has("shape"))
(True, False)
>>> (note.get("color"), note.get("harmonicity"))
('red', 0.2)
Source code in amads/core/basics.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def set(self, property : str, value : Any) -> "Event":
    """Set a named property on this Event.

    Every event can be extended with additional properties. Although
    Python objects are already extensible with new attributes, new
    attributes that are not set in `__init__` confuse type checkers
    and other tools, so every `Event` has an `info` attribute as a
    dictionary where additional, application-specific information can
    be stored. The `info` attribute is `None` to save space until the
    first property is set, so you should use `set` and `get` methods
    and avoid writing `event.info[property]`.

    Parameters
    ----------
    property : str
        The name of the property to set.
    value : Any
        The value to assign to the property.

    Returns
    -------
    Event
        returns this object (self)

    Examples
    --------
    >>> note = Note()
    >>> note.get("color", "no color")
    'no color'
    >>> _ = note.set("color", "red").set("harmonicity", 0.2)
    >>> (note.has("color"), note.has("shape"))
    (True, False)
    >>> (note.get("color"), note.get("harmonicity"))
    ('red', 0.2)
    """
    if self.info is None:
        self.info = {}
    self.info[property] = value
    return self

get

get(property: str, default: Any = None) -> Any

Get the value of a property from this Event.

See set for more details.

Parameters:

  • property (str.) –

    The name of the property to get.

  • default (Any, default: None ) –

    The default value to return if the property is not found.

Returns:

  • Any

    The value of the specified property.

Source code in amads/core/basics.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def get(self, property : str, default : Any = None) -> Any:
    """Get the value of a property from this Event.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str.
        The name of the property to get.
    default : Any
        The default value to return if the property is not found.

    Returns
    -------
    Any
        The value of the specified property.
    """
    if self.info is None:
        return default
    return self.info.get(property, default)

has

has(property) -> bool

Check if the Event has a specific property.

See set for more details.

Parameters:

  • property (str) –

    The name of the property to check.

Returns:

  • bool

    True if the property exists, False otherwise.

Source code in amads/core/basics.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def has(self, property) -> bool:
    """Check if the Event has a specific property.

    See [set][amads.core.basics.Event.set] for more details.

    Parameters
    ----------
    property : str
        The name of the property to check.

    Returns
    -------
    bool
        True if the property exists, False otherwise.
    """
    return (self.info is not None) and (property in self.info)

time_shift

time_shift(increment: float, content_only: bool = False) -> EventGroup

Change the onset by an increment, affecting all content.

If content_only is true, preserves EventGroup times (Score, Part, Staff, but not Chord or Measure) and shifts only the content (recursively). Otherwise, shifts this container and all content by the increment. Container onsets (recursively) are not allowed to become negative, so the onset time is set to zero if the increment would make it negative. However, even if the onset is is not shifted by increment, time_shift is still applied recursively to the content, and non-EventGroup events (e.g., Notes) are allowed to have negative onsets, even if this may not be well-defined for all AMADS operations.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

  • content_only (bool, default: False ) –

    If true, preserves this container's time and shifts only the content.

Returns:

  • Event

    The object. This method modifies the EventGroup.

Raises:

  • ValueError

    If the EventGroup has an unknown (None) onset and content_only is false.

Source code in amads/core/basics.py
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
def time_shift(self, increment: float,
               content_only: bool = False) -> "EventGroup":
    """
    Change the onset by an increment, affecting all content.

    If content_only is true, preserves EventGroup times (Score, Part,
    Staff, but *not* Chord or Measure) and shifts only the content
    (recursively). Otherwise, shifts this container and all content by the
    increment. Container onsets (recursively) are not allowed to become
    negative, so the onset time is set to zero if the increment would
    make it negative. However, even if the onset is is not shifted by
    increment, time_shift is still applied recursively to the content,
    and non-EventGroup events (e.g., Notes) are allowed to have negative
    onsets, even if this may not be well-defined for all AMADS operations.

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).
    content_only: bool
        If true, preserves this container's time and shifts only
        the content.

    Returns
    -------
    Event
        The object. This method modifies the `EventGroup`.

    Raises
    ------
    ValueError
        If the EventGroup has an unknown (None) onset and
        content_only is false.
    """
    # note that Chord and Measures are special cases
    if not content_only or isinstance(self, (Chord, Measure)):
        if self._onset is None:
            raise ValueError(
                    "Cannot shift time of EventGroup with unknown onset")
        self._onset = max(0.0, self._onset + increment)
    for elem in self.content:
        elem.time_shift(increment, content_only)
    return self

insert_copy_into

insert_copy_into(parent: Optional[EventGroup] = None) -> Event

Make a (mostly) deep copy of the Event and add to a new parent.

Pitch objects are considered immutable and are shared rather than copied.

Parameters:

  • parent (Optional(EventGroup), default: None ) –

    The copied Event will be a child of parent if not None. The parent is modified by this operation.

Returns:

  • Event

    A deep copy (except for parent and pitch) of the Event instance.

Source code in amads/core/basics.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def insert_copy_into(self,
                     parent: Optional["EventGroup"] = None) -> "Event":
    """
    Make a (mostly) deep copy of the `Event` and add to a new `parent`.

    `Pitch` objects are considered immutable and are shared rather
    than copied.

    Parameters
    ----------
    parent : Optional(EventGroup)
        The copied `Event` will be a child of `parent` if not `None`.
        The parent is modified by this operation.

    Returns
    -------
    Event
        A deep copy (except for parent and pitch) of the Event instance.
    """
    # remove link to parent to break link going up the tree
    # preventing deep copy from copying the entire tree
    original_parent = self.parent
    self.parent = None
    c = copy.deepcopy(self)  # deep copy of this event down to leaf nodes
    self.parent = original_parent  # restore link to parent
    if parent:
        parent.insert(c)
    return c

ismonophonic

ismonophonic() -> bool

Determine if content is monophonic (non-overlapping notes).

A monophonic list of notes has no overlapping notes (e.g., chords). Serves as a helper function for ismonophonic and parts_are_monophonic.

Returns:

  • bool

    True if the list of notes is monophonic, False otherwise.

Source code in amads/core/basics.py
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
def ismonophonic(self) -> bool:
    """
    Determine if content is monophonic (non-overlapping notes).

    A monophonic list of notes has no overlapping notes (e.g., chords).
    Serves as a helper function for `ismonophonic` and
    `parts_are_monophonic`.

    Returns
    -------
    bool
        True if the list of notes is monophonic, False otherwise.
    """
    prev = None
    notes = self.list_all(Note)
    # Sort the notes by start time
    notes.sort(key=lambda note: note.onset)
    # Check for overlaps
    for note in notes:
        if prev:
            # 0.01 is to prevent precision errors when comparing floats
            if note.onset - prev.offset < -0.01:
                return False
        prev = note
    return True

insert_emptycopy_into

insert_emptycopy_into(
    parent: Optional[EventGroup] = None,
) -> EventGroup

Create a deep copy of the EventGroup except for content.

A new parent is provided as an argument and the copy is inserted into this parent. This method is useful for copying an EventGroup without copying its content. See also insert_copy_into to copy an EventGroup with its content into a new parent.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    The new parent to insert the copied Event into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with the new parent (if any) and no content.

Source code in amads/core/basics.py
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
def insert_emptycopy_into(self, 
            parent: Optional["EventGroup"] = None) -> "EventGroup":
    """Create a deep copy of the EventGroup except for content.

    A new parent is provided as an argument and the copy is inserted
    into this parent. This method is  useful for copying an
    EventGroup without copying its content.  See also
    [insert_copy_into][amads.core.basics.Event.insert_copy_into] to
    copy an EventGroup *with* its content into a new parent.

    Parameters
    ----------
    parent : Optional[EventGroup]
        The new parent to insert the copied Event into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with the new parent
        (if any) and no content.
    """
    # rather than customize __deepcopy__, we "hide" the content to avoid
    # copying it. Then we restore it after copying and fix parent.
    original_content = self.content
    self.content = []
    c = self.insert_copy_into(parent)
    self.content = original_content
    return c  #type: ignore (c will always be an EventGroup)

expand_chords

expand_chords(parent: Optional[EventGroup] = None) -> EventGroup

Replace chords with the multiple notes they contain.

Returns a deep copy with no parent unless parent is provided. Normally, you will call score.expand_chords() which returns a deep copy of Score with notes moved from each chord to the copy of the chord's parent (a Measure or a Part). The parent parameter is primarily for internal use when expand_chords is called recursively on score content.

Parameters:

  • parent (EventGroup, default: None ) –

    The new parent to insert the copied EventGroup into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with all Chord instances expanded.

Source code in amads/core/basics.py
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
def expand_chords(self,
                  parent: Optional["EventGroup"] = None) -> "EventGroup":
    """Replace chords with the multiple notes they contain.

    Returns a deep copy with no parent unless parent is provided.
    Normally, you will call `score.expand_chords()` which returns a deep
    copy of Score with notes moved from each chord to the copy of the
    chord's parent (a Measure or a Part). The parent parameter is 
    primarily for internal use when `expand_chords` is called recursively
    on score content.

    Parameters
    ----------
    parent : EventGroup
        The new parent to insert the copied EventGroup into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with all
        Chord instances expanded.
    """
    group = self.insert_emptycopy_into(parent)
    for item in self.content:
        if isinstance(item, Chord):
            for note in item.content:  # expand chord
                note.insert_copy_into(group)
        if isinstance(item, EventGroup):
            item.expand_chords(group)  # recursion for deep copy/expand
        else:
            item.insert_copy_into(group)  # deep copy non-EventGroup
    return group

find_all

find_all(elem_type: Type[Event]) -> Generator[Event, None, None]

Find all instances of a specific type within the EventGroup.

Assumes that objects of type elem_type are not nested within other objects of the same type. (The first elem_type encountered in a depth-first enumeration is returned without looking at any children in its content).

Parameters:

  • elem_type (Type[Event]) –

    The type of event to search for.

Yields:

  • Event

    Instances of the specified type found within the EventGroup.

Source code in amads/core/basics.py
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
def find_all(self, elem_type: Type[Event]) -> Generator[Event, None, None]:
    """Find all instances of a specific type within the EventGroup.

    Assumes that objects of type `elem_type` are not nested within
    other objects of the same type. (The first `elem_type` encountered
    in a depth-first enumeration is returned without looking at any
    children in its `content`).

    Parameters
    ----------
    elem_type : Type[Event]
        The type of event to search for.

    Yields
    -------
    Event
        Instances of the specified type found within the EventGroup.
    """
    # Algorithm: depth-first enumeration of EventGroup content.
    # If elem_types are nested, only the top-level elem_type is
    # returned since it is found first, and the content is not
    # searched. This makes it efficient, e.g., to search for
    # Parts in a Score without enumerating all Notes within.
    for elem in self.content:
        if isinstance(elem, elem_type):
            yield elem
        elif isinstance(elem, EventGroup):
            yield from elem.find_all(elem_type)

get_sorted_notes

get_sorted_notes(has_ties: bool = True) -> List[Note]

Return a list of sorted notes with merged ties.

This should generally be called on Parts and Scores since in all other EventGroups, Events are in time order and Notes retrieved with find_all() or list_all() are in time order. However, get_sorted_notes also sorts notes into increasing pitch (keynum) where note onsets are equal.

Parameters:

  • has_ties (bool, default: True ) –

    If True (default), copy the score, merge the ties, and return a list of these merged copies. If False, assume there are no ties and return a list of original notes.

Raises:

  • ValueError

    If has_ties is False, but a tie is encountered.

Returns:

  • list(Note)

    a list of sorted notes with merged ties

Source code in amads/core/basics.py
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
def get_sorted_notes(self, has_ties: bool = True) -> List[Note]:
    """Return a list of sorted notes with merged ties.

    This should generally be called on Parts and Scores since
    in all other EventGroups, Events are in time order and
    Notes retrieved with `find_all()` or `list_all()` are in
    time order. However, `get_sorted_notes` *also* sorts notes
    into increasing pitch (`keynum`) where note onsets are equal.

    Parameters
    ----------
    has_ties: bool
        If True (default), copy the score, merge the ties, and
        return a list of these merged copies. If False, assume
        there are no ties and return a list of original notes.

    Raises
    ------
    ValueError
        If has_ties is False, but a tie is encountered.

    Returns
    -------
    list(Note)
        a list of sorted notes with merged ties
    """
    if has_ties:
        # after flatten, score will have one Part with all Notes:
        return self.flatten(collapse=True).content[0].content  # type: ignore
    else:
        notes : List[Note] = cast(List[Note], self.list_all(Note))
        for note in notes:
            if note.tie is not None:
                raise ValueError(
                        "tie found by get_sorted_notes with has_ties=False")
        notes.sort(key=lambda x: (x.onset, x.pitch))
        return notes

has_instanceof

has_instanceof(the_class: Type[Event]) -> bool

Test if EventGroup contains any instances of the_class.

Parameters:

  • the_class (Type[Event]) –

    The class type to check for.

Returns:

  • bool

    True iff the EventGroup contains an instance of the_class.

Source code in amads/core/basics.py
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
def has_instanceof(self, the_class: Type[Event]) -> bool:
    """Test if EventGroup contains any instances of `the_class`.

    Parameters
    ----------
    the_class : Type[Event]
        The class type to check for.

    Returns
    -------
    bool
        True iff the EventGroup contains an instance of the_class.
    """
    instances = self.find_all(the_class)
    # if there are no instances (of the_class), next will return "empty":
    return next(instances, "empty") != "empty"

has_rests

has_rests() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Rest objects.

Returns:

  • bool

    True iff the EventGroup contains any Rest objects.

Source code in amads/core/basics.py
1787
1788
1789
1790
1791
1792
1793
1794
1795
def has_rests(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any `Rest` objects.

    Returns
    -------
    bool
        True iff the EventGroup contains any Rest objects.
    """
    return self.has_instanceof(Rest)

has_chords

has_chords() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Chord objects.

Returns:

  • bool

    True iff the EventGroup contains any Chord objects.

Source code in amads/core/basics.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
def has_chords(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any Chord objects.

    Returns
    -------
    bool
        True iff the EventGroup contains any Chord objects.
    """
    return self.has_instanceof(Chord)

has_ties

has_ties() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any tied notes.

Returns:

  • bool

    True iff the EventGroup contains any tied notes.

Source code in amads/core/basics.py
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
def has_ties(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any tied notes.

    Returns
    -------
    bool
        True iff the EventGroup contains any tied notes.
    """
    notes = self.find_all(Note)
    for note in notes:
        if note.tie:
            return True
    return False

has_measures

has_measures() -> bool

Test if EventGroup (e.g., Score, Part, ...) has any Measures.

Returns:

  • bool

    True iff the EventGroup contains any Measure objects.

Source code in amads/core/basics.py
1824
1825
1826
1827
1828
1829
1830
1831
1832
def has_measures(self) -> bool:
    """Test if EventGroup (e.g., Score, Part, ...) has any Measures.

    Returns
    -------
    bool
        True iff the EventGroup contains any Measure objects.
    """
    return self.has_instanceof(Measure)

inherit_duration

inherit_duration() -> EventGroup

Set the duration of this EventGroup according to maximum offset.

The duration is set to the maximum offset (end) time of the children. If the EventGroup is empty, the duration is set to 0. This method modifies this EventGroup instance.

Returns:

  • EventGroup

    The EventGroup instance (self) with updated duration.

Source code in amads/core/basics.py
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
def inherit_duration(self) -> "EventGroup":
    """Set the duration of this EventGroup according to maximum offset.

    The `duration` is set to the maximum offset (end) time of the
    children. If the EventGroup is empty, the duration is set to 0.
    This method modifies this `EventGroup` instance.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with updated duration.
    """
    onset = 0 if self._onset == None else self._onset
    max_offset = onset
    for elem in self.content:
        max_offset = max(max_offset, elem.offset)
    self.duration = max_offset - onset

    return self

insert

insert(event: Event) -> EventGroup

Insert an event.

Sets the parent of event to this EventGroup and makes event be a member of this EventGroup.content. No changes are made to event.onset or self.duration. Insert event in content just before the first element with a greater onset. The method modifies this object (self).

Parameters:

  • event (Event) –

    The event to be inserted.

Returns:

  • EventGroup

    The EventGroup instance (self) with the event inserted.

Raises:

  • ValueError

    If event._onset is None (it must be a number)

Caution Regarding Zero-Duration Event Order

If you have note N with non-zero duration and, at the same time, a grace note G with zero duration, the notes will be ordered according to when they are inserted. So if you insert N and then G, then N will be placed before G. See io.pt_import.py, where this case is dealt with.

Source code in amads/core/basics.py
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
def insert(self, event: Event) -> "EventGroup":
    """Insert an event.

    Sets the `parent` of `event` to this `EventGroup` and makes `event`
    be a member of this `EventGroup.content`. No changes are made to
    `event.onset` or `self.duration`. Insert `event` in `content` just
    before the first element with a greater onset. The method modifies
    this object (self).

    Parameters
    ----------
    event : Event
        The event to be inserted.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with the event inserted.

    Raises
    ------
    ValueError
        If event._onset is None (it must be a number)

    Caution Regarding Zero-Duration Event Order
    -------------------------------------------
    If you have note N with non-zero duration and, at the same
    time, a grace note G with zero duration, the notes will be
    ordered according to when they are inserted. So if you insert
    N and then G, then N will be placed *before* G. See
    io.pt_import.py, where this case is dealt with.
    """

    assert not event.parent
    if event._onset is None:  # must be a number
        raise ValueError(f"event's _onset attribute must be a number")
    atend = self.last()
    if atend and event.onset < atend.onset:
        # search in reverse from end
        i = len(self.content) - 2
        while i >= 0 and self.content[i].onset > event.onset:
            i -= 1
        # now i is either -1 or content[i] <= event.onset, so
        # insert event at content[i+1]
        self.content.insert(i + 1, event)
    else:  # simply append at the end of content:
        self.content.append(event)
    event.parent = self
    return self

last

last() -> Optional[Event]

Retrieve the last event in the content list.

Because the content list is sorted by onset, the returned Event is simply the last element of content, but not necessarily the event with the greatest offset.

Returns:

  • Optional[Event]

    The last event in the content list or None if the list is empty.

Source code in amads/core/basics.py
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
def last(self) -> Optional[Event]:
    """Retrieve the last event in the content list.

    Because the `content` list is sorted by `onset`, the returned
    `Event` is simply the last element of `content`, but not
    necessarily the event with the greatest *`offset`*.

    Returns
    -------
    Optional[Event]
        The last event in the content list or None if the list is empty.
    """
    return self.content[-1] if len(self.content) > 0 else None

list_all

list_all(elem_type: Type[Event]) -> list[Event]

Find all instances of a specific type within the EventGroup.

Assumes that objects of type elem_type are not nested within other objects of the same type. See also find_all, which returns a generator instead of a list.

Parameters:

  • elem_type (Type[Event]) –

    The type of event to search for.

Returns:

  • list[Event]

    A list of all instances of the specified type found within the EventGroup.

Source code in amads/core/basics.py
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
def list_all(self, elem_type: Type[Event]) -> list[Event]:
    """Find all instances of a specific type within the EventGroup.

    Assumes that objects of type `elem_type` are not nested within
    other objects of the same type.  See also
    [find_all][amads.core.basics.EventGroup.find_all], which returns
    a generator instead of a list.

    Parameters
    ----------
    elem_type : Type[Event]
        The type of event to search for.

    Returns
    -------
    list[Event]
        A list of all instances of the specified type found
        within the EventGroup.
    """
    return list(self.find_all(elem_type))

merge_tied_notes

merge_tied_notes(
    parent: Optional[EventGroup] = None, ignore: list[Note] = []
) -> EventGroup

Create a new EventGroup with tied notes replaced by single notes.

If ties cross staffs, the replacement is placed in the staff of the first note in the tied sequence. Insert the new EventGroup into parent.

Ordinarily, this method is called on a Score with no parameters. The parameters are used when Score.merge_tied_notes() calls this method recursively on EventGroups within the Score such as Parts and Staffs.

Parameters:

  • parent (Optional[EventGroup], default: None ) –

    Where to insert the result.

  • ignore (list[Note], default: [] ) –

    This parameter is used internally. Caller should not use this parameter.

Returns:

  • EventGroup

    A copy with tied notes replaced by equivalent single notes.

Source code in amads/core/basics.py
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
def merge_tied_notes(self, parent: Optional["EventGroup"] = None,
                     ignore: list[Note] = []) -> "EventGroup":
    """Create a new `EventGroup` with tied notes replaced by single notes.

    If ties cross staffs, the replacement is placed in the staff of the
    first note in the tied sequence. Insert the new `EventGroup` into
    `parent`.

    Ordinarily, this method is called on a Score with no parameters. The
    parameters are used when `Score.merge_tied_notes()` calls this method
    recursively on `EventGroup`s within the Score such as `Part`s and
    `Staff`s.

    Parameters
    ----------
    parent: Optional(EventGroup)
        Where to insert the result.

    ignore: Optional(list[Note])
        This parameter is used internally. Caller should not use
        this parameter.

    Returns
    -------
    EventGroup
        A copy with tied notes replaced by equivalent single notes.
    """
    # Algorithm: Find all notes, removing tied notes and updating
    # duration when ties are found. These tied notes are added to
    # ignore so they can be skipped when they are encountered.

    group = self.insert_emptycopy_into(parent)
    for event in self.content:
        if isinstance(event, Note):
            if event in ignore:  # do not copy tied notes into group;
                if event.tie:
                    ignore.append(event.tie)  # add tied note to ignore
                # We will not see this note again, so
                # we can also remove it from ignore. Removal is expensive
                # but it could be worse for ignore to grow large when there
                # are many ties since we have to search it entirely once
                # per note. An alternate representation might be a set to
                # make searching fast.
                ignore.remove(event)
            else:
                if event.tie:
                    tied_note = event.tie  # save the tied-to note
                    event.tie = None  # block the copy
                    ignore.append(tied_note)
                    # copy note into group:
                    event_copy = event.insert_copy_into(group)
                    event.tie = tied_note  # restore original event
                    # this is subtle: event.tied_duration (a property) will
                    # sum up durations of all the tied notes. Since
                    # event_copy is not tied, the sum of durations is
                    # stored on that one event_copy:
                    event_copy.duration = event.tied_duration
                else:  # put the untied note into group
                    event.insert_copy_into(group)
        elif isinstance(event, EventGroup):
            event.merge_tied_notes(group, ignore)
        else:
            event.insert_copy_into(group)  # simply copy to new parent
    return group

pack

pack(onset: float = 0.0, sequential: bool = False) -> float

Adjust the content to onsets starting with the onset parameter.

By default onsets are set to onset and the duration of self is set to the maximum duration of the content. pack() works recursively on elements that are EventGroups. Setting sequential to True implements sequential packing, where events are placed one after another.

Parameters:

  • onset (float, default: 0.0 ) –

    The onset (start) time for this object.

Returns:

  • float

    duration of self

Source code in amads/core/basics.py
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
def pack(self, onset: float = 0.0, sequential : bool = False) -> float:
    """Adjust the content to onsets starting with the onset parameter.

    By default onsets are set to `onset` and the duration of self is set to
    the maximum duration of the content. pack() works recursively on
    elements that are EventGroups. Setting sequential to True implements
    sequential packing, where events are placed one after another.

    Parameters
    ----------
    onset : float
        The onset (start) time for this object.

    Returns
    -------
    float
        duration of self
    """
    self.onset = onset
    self.duration = 0
    for elem in self.content:
        elem.onset = onset
        if isinstance(elem, EventGroup):   # either Sequence or Concurrence
            elem.duration = elem.pack(onset)  #type: ignore
        if sequential:
            onset += elem.duration
        else:
            self.duration = max(self.duration, elem.duration)
    if sequential:
        self.duration = onset - self.onset
    return self.duration

quantize

quantize(divisions: int) -> EventGroup

Align onsets and durations to a rhythmic grid.

Assumes time units are quarters. (See Score.convert_to_quarters.)

Modify all times and durations to a multiple of divisions per quarter note, e.g., 4 for sixteenth notes. Onsets and offsets are moved to the nearest quantized time. Any resulting duration change is less than one quantum, but not necessarily less than 0.5 quantum, since the onset and offset can round in opposite directions by up to 0.5 quantum each. Any non-zero duration that would quantize to zero duration gets a duration of one quantum since zero duration is almost certainly going to cause notation and visualization problems.

Special cases for zero duration:

  1. If the original duration is zero as in metadata or possibly grace notes, we preserve that.
  2. If a tied note duration quantizes to zero, we remove the tied note entirely provided some other note in the tied sequence has non-zero duration. If all tied notes quantize to zero, we keep the first one and set its duration to one quantum.

This method modifies this EventGroup and all its content in place.

Note that there is no way to specify "sixteenths or eighth triplets" because 6 would not allow sixteenths and 12 would admit sixteenth triplets. Using tuples as in Music21, e.g., (4, 3) for this problem creates another problem: if quantization is to time points 1/4, 1/3, then the difference is 1/12 or a thirty-second triplet. If the quantization is applied to durations, then you could have 1/4 + 1/3 = 7/12, and the remaining duration in a single beat would be 5/12, which is not expressible as sixteenths, eighth triplets or any tied combination.

Parameters:

  • divisions (int) –

    The number of divisions per quarter note, e.g., 4 for sixteenths, to control quantization.

Returns:

  • EventGroup

    The EventGroup instance (self) with (modified in place) quantized times.

Source code in amads/core/basics.py
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
def quantize(self, divisions: int) -> "EventGroup":
    """Align onsets and durations to a rhythmic grid.

    Assumes time units are quarters. (See [Score.convert_to_quarters](
            basics.md#amads.core.basics.Score.convert_to_quarters).)

    Modify all times and durations to a multiple of divisions
    per quarter note, e.g., 4 for sixteenth notes. Onsets and offsets
    are moved to the nearest quantized time. Any resulting duration
    change is less than one quantum, but not necessarily less than
    0.5 quantum, since the onset and offset can round in opposite
    directions by up to 0.5 quantum each. Any non-zero duration that would
    quantize to zero duration gets a duration of one quantum since
    zero duration is almost certainly going to cause notation and
    visualization problems.

    Special cases for zero duration:

    1. If the original duration is zero as in metadata or possibly
           grace notes, we preserve that.
    2. If a tied note duration quantizes to zero, we remove the
           tied note entirely provided some other note in the tied
           sequence has non-zero duration. If all tied notes quantize
           to zero, we keep the first one and set its duration to
           one quantum.

    This method modifies this EventGroup and all its content in place.

    Note that there is no way to specify "sixteenths or eighth triplets"
    because 6 would not allow sixteenths and 12 would admit sixteenth
    triplets. Using tuples as in Music21, e.g., (4, 3) for this problem
    creates another problem: if quantization is to time points 1/4, 1/3,
    then the difference is 1/12 or a thirty-second triplet. If the
    quantization is applied to durations, then you could have 1/4 + 1/3
    = 7/12, and the remaining duration in a single beat would be 5/12,
    which is not expressible as sixteenths, eighth triplets or any tied
    combination.

    Parameters
    ----------
    divisions : int
        The number of divisions per quarter note, e.g., 4 for
        sixteenths, to control quantization.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with (modified in place) 
        quantized times.
    """

    super()._quantize(divisions)
    # iterating through content is tricky because we may delete a
    # Note, shifting the content:
    i = 0
    while i < len(self.content):
        event = self.content[i]
        event._quantize(divisions)
        if event == self.content[i]:
            i += 1
        # otherwise, we deleted event so the next event to
        # quantize is at index i; don't incremenet i
    return self

remove

remove(element: Event) -> EventGroup

Remove an element from the content list.

The method modifies this object (self).

Parameters:

  • element (Event) –

    The event to be removed.

Returns:

  • EventGroup

    The EventGroup instance (self) with the element removed. The returned value is not a copy.

Source code in amads/core/basics.py
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
def remove(self, element: Event) -> "EventGroup":
    """Remove an element from the content list. 

    The method modifies this object (self).

    Parameters
    ----------
    element : Event
        The event to be removed.

    Returns
    -------
    EventGroup
        The EventGroup instance (self) with the element removed.
        The returned value is not a copy.
    """
    self.content.remove(element)
    element.parent = None
    return self

remove_rests

remove_rests(parent: Union[EventGroup, None] = None) -> EventGroup

Remove all Rest objects from content.

Returns a deep copy with no parent unless parent is provided.

Parameters:

  • parent (EventGroup, default: None ) –

    The new parent to insert the copied Event into.

Returns:

  • EventGroup

    A deep copy of the EventGroup instance with all Rest objects removed.

Source code in amads/core/basics.py
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
def remove_rests(self, parent: Union["EventGroup", 
                                     None] = None) -> "EventGroup":
    """Remove all Rest objects from content.

    Returns a deep copy with no parent unless parent is provided.

    Parameters
    ----------
    parent : EventGroup
        The new parent to insert the copied Event into.

    Returns
    -------
    EventGroup
        A deep copy of the EventGroup instance with all Rest
        objects removed.
    """
    # implementation detail: when called without argument, remove_rests
    # makes a deep copy of the subtree and returns the copy without a
    # parent. remove_rests calls itself recursively *with* a parameter
    # indicating that the subtree copy should be inserted into a
    # parent which is the new copy at the next level up. Of course,
    # we check for and ignore Rests so they are never copied.
    group = self.insert_emptycopy_into(parent)
    for item in self.content:
        if isinstance(item, Rest):
            continue  # skip the Rests while making deep copy
        if isinstance(item, EventGroup):
            item.remove_rests(group)  # recursion for deep copy
        else:
            item.insert_copy_into(group)  # deep copy non-EventGroup
    return group

show

show(indent: int = 0, file: Optional[TextIO] = None) -> EventGroup

Print the EventGroup information.

Parameters:

  • indent (int, default: 0 ) –

    The indentation level for display.

Returns:

Source code in amads/core/basics.py
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
def show(self, indent: int = 0,
        file: Optional[TextIO] = None) -> "EventGroup":
    """Print the EventGroup information.

    Parameters
    ----------
    indent : int
        The indentation level for display.

    Returns
    -------
    EventGroup
        The EventGroup instance itself.
    """
    print(" " * indent, self, sep="", file=file)
    for elem in self.content:
        elem.show(indent + 4, file=file)  # type: ignore (show exists)
    return self

measure_times

measure_times(n: int) -> tuple[float, float]

Return the start and end times of measure n.

Parameters:

  • n (int) –

    The 0-based measure number.

Returns:

  • tuple(float, float)

    A tuple containing the start and end times of measure n. Measure 0 is the first measure. Units are the same as the score's time units.

Raises:

  • ValueError

    If there is no measure with number n.

Source code in amads/core/basics.py
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
def measure_times(self, n: int) -> tuple[float, float]:
    """Return the start and end times of measure n.

    Parameters
    ----------
    n : int
        The 0-based measure number.

    Returns
    -------
    tuple(float, float)
        A tuple containing the start and end times of measure n.
        Measure 0 is the first measure.  Units are the same as the
        score's time units.

    Raises
    ------
    ValueError
        If there is no measure with number n.
    """
    # Algorithm: For each Staff, linear search for nth Measure, returning
    # the onset and offset of the first one found.
    for staff in self.find_all(Staff):
        staff = cast(Staff, staff)
        for i, measure in enumerate(staff.find_all(Measure)):
            if i == n:
                return (measure.onset, measure.offset)
    raise ValueError(f"measure {n} not found")

slice

slice(
    start: float,
    end: float,
    units: str = "quarters",
    mode: str = "onsets",
    truncate: str = "keep",
    shift: bool = False,
    min_duration: float = 0.05,
) -> EventGroup

Create a new Score containing the content between start and end.

Typically, this method is called on a Score to create a new Score, but it works on any Sequence as long as the sequence is part of a Score.

If self has Measures, units must be "measures" or "bars", the start and end parameters are interpreted as 0-based measure numbers, and the result will therefore contain whole measures. It is assumed that notes are tied across measure boundaries. The result will contain only the parts of tied notes that are within the specified measures, excluding measure numbered by end.

For any units besides "measures" or "bars", the score must be flat. Notes that extend beyond the start or end time are included in the result unless the truncate parameter specifies otherwise.

In principle, there is no reason to require a flat score for slicing by time, but there are many difficult edge cases to consider such as ties from within one chord to a note in another measure. Therefore, to slice by time or quarter, you must have a flattened score. Conversely, to slice a full score, you must slice by measure so that the result gives you whole measures, which are encoded into the full Score structure.

The entire result can be shifted to start at time 0 by setting the shift parameter to True. Unless truncate is "truncate" or "beginning", the result can include events that start before the start time, in which case shifting will only shift the earliest onset to 0, which means the shift amount depends upon the content. (Negative onsets are currently not allowed.)

The resulting Score, Part, and other content will have onset and offset times matching start and end, even if some content starts earlier or ends later.

Parameters:

  • start (float) –

    The start time of the slice, inclusive. If units is "measures" or "bars", start is a 0-based measure number of the first measure.

  • end (float) –

    The end time of the slice, exclusive. For measures, end is the 0-based measure number of the last measure plus one, so the last measure is end - 1.

  • units (str, default: 'quarters' ) –

    The time units for start and end. Valid values are "quarters", "s", "sec", "seconds", "measures", or "bars".

  • shift (bool, default: False ) –

    If true, shift the content in the result so that the result starts time 0.0. If false (default), the content in the result retains the same time values as in the original Score.

  • mode (Optional[str], default: 'onsets' ) –

    The slicing mode, ignored if units is "measures" or "bars". Valid values are:

    • "onsets" - include events that start within bounds (default)
    • "overlaps" - include events that overlap (either onset or offset) is within the bounds. An event ending is considered to overlap if its offset is greater than start.
    • "offsets" - include events that end within the bounds
    • "strict" - include only events that start at or after start and end at or before end. (End times that are exactly equal to end are considered to be within bounds, so this is inclusive of end time.)
  • truncate (str, default: 'keep' ) –

    How to handle events that partially overlap the bounds, ignored if units is "measures" or "bars". Valid values are:

    • "truncate" - truncate (clip) events that partially overlap the bounds. If the event onset is before start, the onset is increased to start (adjusting duration to maintain the offset time). Also, if the event offset is after end, the duration is decreased so that the offset time is end.
    • "keep" - no modification/truncation (default). Note that with the default mode="onsets", no event onsets will be earlier than start, but offsets may extend beyond end.
    • "end" or "ending" or "dur" or "duration" - truncate (clip) events that extend beyond end so that all offsets <= end.
    • "beginning" - events with onsets before start are moved to make their onsets equal to start, and their duration is adjusted to maintain the original offset.
  • min_duration (float, default: 0.05 ) –

    Events with duration less than min_duration (after any truncation is applied) are removed. Ignored if units is "measures" or "bars". If None or 0.0, no events are removed. The default is 0.05, independent of time units. Be careful with gracenotes that, when read from MusicXML, have zero duration.

Returns:

  • Score

    A new Score instance containing the content between start and end.

Raises:

  • ValueError

    If the Sequence is not part of a Score, or if invalid values are provided for the parameters.

Source code in amads/core/basics.py
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
def slice(self, start: float, end: float, units: str = "quarters",
          mode: str = "onsets", truncate: str = "keep", shift: bool = False,
          min_duration: float = 0.05) -> "EventGroup":
    """
    Create a new Score containing the content between start and end.

    Typically, this method is called on a Score to create a new Score,
    but it works on any Sequence as long as the sequence is part of a Score.

    If self has Measures, units must be "measures" or "bars", the start and
    end parameters are interpreted as 0-based measure numbers, and the
    result will therefore contain whole measures. It is assumed that notes
    are tied across measure boundaries. The result will contain only the
    parts of tied notes that are within the specified measures, excluding
    measure numbered by `end`.

    For any units besides "measures" or "bars", the score must be flat.
    Notes that extend beyond the start or end time are included in the
    result unless the `truncate` parameter specifies otherwise.

    In principle, there is no reason to require a flat score for slicing by
    time, but there are many difficult edge cases to consider such as ties
    from within one chord to a note in another measure. Therefore, to slice
    by time or quarter, you must have a flattened score. Conversely, to
    slice a full score, you must slice by measure so that the result gives
    you whole measures, which are encoded into the full Score structure.

    The entire result can be shifted to start at time 0 by setting the
    `shift` parameter to True.  Unless `truncate` is "truncate" or
    "beginning", the result can include events that start before the start
    time, in which case shifting will only shift the earliest onset to 0,
    which means the shift amount depends upon the content. (Negative onsets
    are currently not allowed.)

    The resulting Score, Part, and other content will have onset and offset
    times matching start and end, even if some content starts earlier or
    ends later.

    Parameters
    ----------
    start : float
        The start time of the slice, inclusive. If units is "measures" or
        "bars", start is a 0-based measure number of the first measure.
    end : float
        The end time of the slice, exclusive. For measures, end is the
        0-based measure number of the last measure plus one, so the last
        measure is end - 1.
    units : str
        The time units for start and end. Valid values are "quarters", "s",
        "sec", "seconds", "measures", or "bars".
    shift: bool
        If true, shift the content in the result so that the result starts
        time 0.0. If false (default), the content in the result retains
        the same time values as in the original Score.
    mode : Optional[str]
        The slicing mode, ignored if units is "measures" or "bars".
        Valid values are:

        - `"onsets"` - include events that start within bounds (default)
        - `"overlaps"` - include events that overlap (either onset or
            offset) is within the bounds. An event ending is considered
            to overlap if its offset is greater than start.
        - `"offsets"` - include events that end within the bounds
        - `"strict"` - include only events that start at or after start
            and end at or before end. (End times that are exactly equal
            to end are considered to be within bounds, so this is
            inclusive of end time.)

    truncate: Optional[str]
        How to handle events that partially overlap the bounds,
        ignored if units is "measures" or "bars". Valid values are:

        - `"truncate"` - truncate (clip) events that partially overlap
            the bounds. If the event onset is before start, the onset
            is increased to start (adjusting duration to maintain the
            offset time). Also, if the event offset is after end, the
            duration is decreased so that the offset time is end.
        - `"keep"` - no modification/truncation (default). Note that
            with the default mode="onsets", no event onsets will be
            earlier than start, but offsets may extend beyond end.
        - `"end"` or "ending" or "dur" or "duration" - truncate (clip)
            events that extend beyond end so that all offsets <= end.
        - `"beginning"` - events with onsets before start are moved to
            make their onsets equal to start, and their duration is
            adjusted to maintain the original offset.

    min_duration: Optional[float]
        Events with duration less than min_duration (after any truncation
        is applied) are removed.  Ignored if units is "measures" or "bars".
        If None or 0.0, no events are removed. The default is 0.05,
        independent of time units. Be careful with gracenotes that, when
        read from MusicXML, have zero duration.

    Returns
    -------
    Score
        A new Score instance containing the content between start and end.

    Raises
    ------
    ValueError
        If the Sequence is not part of a Score, or if invalid values are
        provided for the parameters.
    """
    score = self.score
    if score is None:
        raise ValueError("slice can only be called on a Sequence that is "
                         "part of a Score")
    if score.is_flat():
        if units in ("measures", "bars"):
            raise ValueError(f"units cannot be {units} for slicing a "
                             "flat score")
    else:
        if units not in ("measures", "bars"):
            raise ValueError(f"units must be measures or bars for slicing "
                "a score with Measures (or flatten the score before "
                "slicing)")

    if units in ("quarters", "measures", "bars"):
        score.convert_to_quarters()
    elif units in ("s", "sec", "seconds"):
        score.convert_to_seconds()
    else:
        raise ValueError('units must be "quarters", "measures, "'
                         '"bars", "s", "sec", or "seconds"')

    # Find start time and end time for slice. It may not be (start, end)
    # if units is measures or bars.
    if units in ("measures", "bars"):
        (start_time, end_time) = self.measure_times(int(start))
        if end != start:
            (_, end_time) = self.measure_times(int(end) - 1)
    else:
        start_time = start
        end_time = end

    # construct the parts of the tree above self and make an empty copy
    # of self to add the slice content.
    result = (score.emptycopy() if isinstance(self, Score)
              else self._copy_parents(start_time, end_time))
    result.onset = start_time  # result is an empty copy of self. Set the
    result.offset = end_time   # onset and offset to the slice bounds.
    if units in ("measures", "bars"):
        c_min, c_max = result._add_measure_children(self, start, end,
                                                    start_time, end_time)
        if c_min < start_time or c_max > end_time:
            raise ValueError("unexpectedly found content outside the "
                             "measure slice bounds")
        min_time = c_min
        max_time = c_max
    else:   
        min_time, max_time = result._add_slice_children(self, start_time,
                                  end_time, mode, truncate, min_duration)
    result._trim_map_and_signatures(min_time, max_time)
    if shift and min_time != float("inf") and min_time > 0:
        result.time_shift(-min_time)
    return result

TimeMap

TimeMap(qpm=100.0)

Implement the time_map attribute of Score class.

Every Score has a time_map attribute whose value is a TimeMap that maintains a mapping between time in seconds and beats in quarters. A TimeMap encodes the information in a MIDI File tempo track as well as tempo information from a Music XML score.

This class holds a list representing tempo changes as a list of (time, quarter) pairs, which you can think of as tempo changes. More mathematically, they are breakpoints in a piece-wise linear function that maps from time to quarter or from quarter to time.

Since tempo is not continuous, the tempo at a breakpoint is defined to be the tempo just after the breakpoint.

The time map is defined from time changes[0].time to infinity, and from quarter changes[0].quarter to infinity. The first breakpoint should correspond to Score.onset.Before the first breakpoint, the time map is defined to have a slope of 1 quarter per second (i.e., 60 qpm). After the last breakpoint, the time map is defined to have a slope of last_tempo quarters per second.

Parameters:

  • qpm (float, default: 100.0 ) –

    Initial tempo in quarters per minute (default is 100.0).

Attributes:

  • changes (list of MapQuarter) –

    List of (time, quarter) breakpoints for piece-wise linear mapping.

  • last_tempo (float) –

    Final quarters per second (qps) for extrapolatation.

Examples:

>>> tm = TimeMap(qpm=120)
>>> tm.append_change(4.0, 60.0)  # change to 60 qpm at quarter 4
>>> tm.quarter_to_time(5.0)
3.0
>>> tm.time_to_quarter(3.0)
5.0
Source code in amads/core/timemap.py
113
114
115
def __init__(self, qpm=100.0):
    self.changes = [MapQuarter(0.0, 0.0)]  # initial quarter
    self.last_tempo = qpm / 60.0  # 100 qpm default

Functions

show

show(indent: int = 0, file=sys.stdout) -> None

Print a summary of this time map.

Parameters:

  • indent (int, default: 0 ) –

    Number of spaces to indent (default is 0).

  • file (TextIO, default: stdout ) –

    The file to print to (default is sys.stdout).

Returns:

  • None
Source code in amads/core/timemap.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def show(self, indent: int = 0, file=sys.stdout) -> None:
    """Print a summary of this time map.

    Parameters
    ----------
    indent : int, optional
        Number of spaces to indent (default is 0).
    file : TextIO, optional
        The file to print to (default is sys.stdout).

    Returns
    -------
    None
    """
    print(" " * indent, "time_map: [", sep="", end="", file=file)
    col = indent + 11
    need_blank = ""
    for i, mb in enumerate(self.changes):
        tempo = self.get_tempo_at(i)
        mbs = f"({mb.quarter:.2f}, {mb.time:.3f}s, {tempo:.3f}qpm)"
        if len(mbs) + col > 79:
            print("\n", " " * (indent + 10), end="", file=file)
            col = indent + 11
        print(need_blank, mbs, sep="", end="", file=file)
        col += len(mbs)
        need_blank = " "
    print("]", file=file)

deep_copy

deep_copy() -> TimeMap

Make a full copy of this time map.

Returns:

  • TimeMap

    A deep copy of this TimeMap instance.

Source code in amads/core/timemap.py
145
146
147
148
149
150
151
152
153
154
155
156
def deep_copy(self) -> "TimeMap":
    """Make a full copy of this time map.

    Returns
    -------
    TimeMap
        A deep copy of this TimeMap instance.
    """
    newtm = TimeMap(qpm=self.last_tempo * 60)
    for i in self.changes[1:]:
        newtm.changes.append(i.copy())
    return newtm

append_change

append_change(quarter: float, tempo: float) -> None

Append a tempo change at a given quarter.

Append a MapQuarter specifying a change to tempo at quarter. quarter must be at least as great as last MapQuarter's quarter. You cannot insert a tempo change before the end of the TimeMap. The tempo will hold forever beginning at quarter unless you call append_change again to change the tempo somewhere beyond quarter.

Parameters:

  • quarter (float) –

    The quarter measured in quarters where the tempo changes

  • tempo (float) –

    The new tempo at quarter measured in quarters per minute. Typically, this is the same as beats per minute (BPM), but only when a beat lasts one quarter.

Returns:

  • None
Source code in amads/core/timemap.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def append_change(self, quarter: float, tempo: float) -> None:
    """Append a tempo change at a given quarter.

    Append a `MapQuarter` specifying a change to tempo at quarter.
    quarter must be at least as great as last MapQuarter's quarter.
    You cannot insert a tempo change before the end of the TimeMap.
    The `tempo` will hold forever beginning at `quarter` unless you call
    `append_change` again to change the tempo somewhere beyond
    `quarter`.

    Parameters
    ----------
    quarter: float
        The quarter measured in quarters where the tempo changes
    tempo: float
        The new tempo at quarter measured in quarters per minute.
        Typically, this is the same as beats per minute (BPM),
        but only when a beat lasts one quarter.

    Returns
    -------
    None
    """
    last_quarter = self.changes[-1].quarter  # get the last quarter
    assert quarter >= last_quarter
    if quarter > last_quarter:
        self.changes.append(
            MapQuarter(self.quarter_to_time(quarter), quarter)
        )
    self.last_tempo = tempo / 60.0  # from qpm to qps

get_time_at

get_time_at(index: int) -> float

Get the time in seconds at a given index in the changes list.

Parameters:

  • index (int) –

    The index in the changes list.

Returns:

  • float

    The time in seconds at the specified index.

Source code in amads/core/timemap.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def get_time_at(self, index: int) -> float:
    """Get the time in seconds at a given index in the changes list.

    Parameters
    ----------
    index : int
        The index in the changes list.

    Returns
    -------
    float
        The time in seconds at the specified index.
    """
    return self.changes[index].time

get_tempo_at

get_tempo_at(index: int) -> float

Get the tempo at a given index in the changes list.

The tempo changes at each breakpoint. This method returns the tempo in QPM just after the breakpoint at the specified index.

Parameters:

  • index (int) –

    The index in the changes list.

Returns:

  • float

    The tempo in quarters per minute immediately after the specified index.

  • The tempo at entry i is the tempo in effect JUST BEFORE entry i,

Parameters:

  • index (int) –

    The index in the changes list.

Returns:

  • float

    The tempo in quarters per minute (qpm) just after entry i.

Source code in amads/core/timemap.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def get_tempo_at(self, index: int) -> float:
    """Get the tempo at a given index in the changes list.

    The tempo changes at each breakpoint. This method returns
    the tempo in QPM just after the breakpoint at the specified
    index.

    Parameters
    ----------
    index : int
        The index in the changes list.

    Returns
    -------
    float
        The tempo in quarters per minute immediately after
        the specified index.

    The tempo at entry i is the tempo in effect JUST BEFORE entry i,

    Parameters
    ----------
    index : int
        The index in the changes list.

    Returns
    -------
    float
        The tempo in quarters per minute (qpm) just after entry i.
    """
    # two cases here: (1) we're at or beyond the last entry, so
    #   use last_tempo or extrapolate, OR
    #   (2) there's only one entry, so use last_tempo or
    #   return the default tempo
    if index < 0:
        raise ValueError("Index must be non-negative")
    if index >= len(self.changes) - 1:
        # special case: quarter >= last (time, quarter) pair
        # so extrapolate using last_tempo if it is there
        return self.last_tempo * 60.0
    mb0 = self.changes[index]
    mb1 = self.changes[index + 1]
    time_dif = mb1.time - mb0.time
    quarter_dif = mb1.quarter - mb0.quarter
    return quarter_dif * 60.0 / time_dif

quarter_to_time

quarter_to_time(quarter: float) -> float

Convert time in quarters to time to seconds.

When score time units are quarters, it is recommended to covert everything to seconds using score.convert_to_seconds(). This is much faster than calling this method for every event.

If there is a particular reason to convert the time of one event, you can write something like note.score.timemap.quarter_to_time(note.onset).

Parameters:

  • quarter (float) –

    A score position in quarters.

Returns:

  • float

    The time in seconds corresponding to quarter.

Source code in amads/core/timemap.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def quarter_to_time(self, quarter: float) -> float:
    """Convert time in quarters to time to seconds.

    When score time units are quarters, it is recommended to covert
    *everything* to seconds using `score.convert_to_seconds()`. This
    is much faster than calling this method for every event.

    If there is a particular reason to convert the time of one event,
    you can write something like
        `note.score.timemap.quarter_to_time(note.onset)`.

    Parameters
    ----------
    quarter: float
        A score position in quarters.

    Returns
    -------
    float
        The time in seconds corresponding to `quarter`.
    """
    if quarter <= 0:  # there is no negative time or tempo before 0
        return quarter  # so just pretend like tempo is 60 qpm
    i = self._quarter_to_insert_index(quarter)
    return self.changes[i - 1].time + (
        quarter - self.changes[i - 1].quarter
    ) * 60.0 / self.get_tempo_at(i - 1)

quarter_to_tempo

quarter_to_tempo(quarter: float) -> float

Get the tempo in qpm at a given quarter.

Parameters:

  • quarter (float) –

    A score position in changes.

Returns:

  • float

    The tempo at quarter. If there is a tempo change here, returns the tempo on the right (after the change).

Source code in amads/core/timemap.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def quarter_to_tempo(self, quarter: float) -> float:
    """Get the tempo in qpm at a given quarter.

    Parameters
    ----------
    quarter: float
        A score position in changes.

    Returns
    -------
    float
        The tempo at `quarter`. If there is a tempo change here,
        returns the tempo on the right (after the change).
    """
    return self.get_tempo_at(self._quarter_to_insert_index(quarter) - 1)

time_stretch

time_stretch(factor: float) -> TimeMap

Scale all tempos to increase times in seconds by a factor.

Parameters:

  • factor (float) –

    The scaling factor for timing.

Returns:

  • TimeMap

    The object. This method modifies the TimeMap.

Source code in amads/core/timemap.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def time_stretch(self, factor: float) -> "TimeMap":
    """
    Scale all tempos to increase times in seconds by a factor.

    Parameters
    ----------
    factor : float
        The scaling factor for timing.

    Returns
    -------
    TimeMap
        The object. This method modifies the `TimeMap`.
    """
    for change in self.changes:
        change.time *= factor
    self.last_tempo /= factor
    return self

time_to_quarter

time_to_quarter(time: float) -> float

Convert time in seconds to quarter position.

When score time units are seconds, it is recommended to covert everything to quarters using score.convert_to_quarters(). This is much faster than calling this method for every event.

If there is a particular reason to convert the time of one event, you can write something like note.score.timemap.time_to_quarter(note.onset).

Parameters:

  • time (float) –

    A score time in seconds.

Returns:

  • float

    The score position in changes corresponding to time.

Source code in amads/core/timemap.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def time_to_quarter(self, time: float) -> float:
    """Convert time in seconds to quarter position.

    When score time units are seconds, it is recommended to covert
    *everything* to quarters using `score.convert_to_quarters()`. This
    is much faster than calling this method for every event.

    If there is a particular reason to convert the time of one event,
    you can write something like
        `note.score.timemap.time_to_quarter(note.onset)`.

    Parameters
    ----------
    time: float
        A score time in seconds.

    Returns
    -------
    float
        The score position in changes corresponding to `time`.
    """
    if time <= self.changes[0].time:
        return self.changes[0].quarter + time - self.changes[0].time
    i = self._time_to_insert_index(time)
    return (
        self.changes[i - 1].quarter
        + (time - self.changes[i - 1].time)
        * self.get_tempo_at(i - 1)
        / 60.0
    )

time_to_tempo

time_to_tempo(time: float) -> float

Get the tempo in qpm at a given time (in seconds).

Parameters:

  • time (float) –

    A score time in seconds.

Returns:

  • float

    The tempo at time. If there is a tempo change here, use the tempo on the right (aftr the change).

Source code in amads/core/timemap.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def time_to_tempo(self, time: float) -> float:
    """Get the tempo in qpm at a given time (in seconds).

    Parameters
    ----------
    time: float
        A score time in seconds.

    Returns
    -------
    float
        The tempo at `time`. If there is a tempo change here,
        use the tempo on the right (aftr the change).
    """
    return self.get_tempo_at(self._time_to_insert_index(time) - 1)

trim

trim(start: float, end: float) -> None

Trim the time map to a specified range, given in seconds.

Source code in amads/core/timemap.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
def trim(self, start: float, end: float) -> None:
    """Trim the time map to a specified range, given in seconds."""

    i = 0  # index into changes
    initial_quarter = self.time_to_quarter(start)
    final_bpm = self.time_to_tempo(end)

    while i < len(self.changes) and self.changes[i].time < start:
        i = i + 1
    # now i is index into changes of the first breakpoint at or after start
    # if breakpoint at i is after start, insert a breakpoint at start
    if i < len(self.changes) and (self.changes[i].time > start + 0.001):
        if i > 0:
            self.changes[i - 1].time = start
            self.changes[i - 1].quarter = initial_quarter
            i = i - 1  # will copy from i to 0
        else:
            self.changes.insert(0, MapQuarter(start, initial_quarter))
            i = 0  # no copy needed since first breakpoint is now at 0
    # else changes[i].time is within 0.001 of start, so copy from i to 0
    # now figure out where is last breakpoint before end
    j = i
    while j < len(self.changes) and self.changes[j].time < end:
        j = j + 1
    self.changes = self.changes[i:j]  # copy from i to j
    self.last_tempo = final_bpm / 60.0

MapQuarter

MapQuarter(time: float, quarter: float)

Represents a (time, quarter) pair in a piece-wise linear mapping.

Parameters:

  • time (float) –

    The time in seconds.

  • quarter (float) –

    The corresponding quarter note position.

Attributes:

  • time (float) –

    The time in seconds.

  • quarter (float) –

    The corresponding quarter note position.

Methods:

  • copy

    Return a copy of the MapQuarter instance.

Source code in amads/core/timemap.py
47
48
49
def __init__(self, time: float, quarter: float):
    self.time = time
    self.quarter = quarter

Functions

copy

copy() -> MapQuarter

return a copy of this MapQuarter

Returns:

  • MapQuarter

    A copy of this MapQuarter instance.

Source code in amads/core/timemap.py
51
52
53
54
55
56
57
58
59
def copy(self) -> "MapQuarter":
    """return a copy of this MapQuarter

    Returns
    -------
    MapQuarter
        A copy of this MapQuarter instance.
    """
    return MapQuarter(self.time, self.quarter)