Skip to content

Classes Representing Basic Score Elements

basics

Basic Symbolic Music Representation Classes

from amads.core import *

Note: amads.core includes amads.core.basics, amads.core.distribution and amads.core.timemap.

Overview

The basic hierarchy of a score is described here.

Author: Roger B. Dannenberg

Constructor Details

The safe way to construct a score is to fully specify onsets for every Event. These onsets are absolute and will not be adjusted provided that the parent onset is also specified.

However, for convenience and to support simple constructs such as

Chord(Note(pitch=60), Note(pitch=64)),

onsets are optional and default to None. To make this simple example work:

  • Concurrences (Score, Part, and Chord) replace unspecified (None) onsets in their immediate content with the parent's onset (or 0 if it is None).

  • Sequences (Staff, Measure) replace unspecified (None) onsets in their immediate content starting with the parent's onset (or 0 if None) for the first event and the offset of the previous Event for subsequent events.

  • To handle the construction of nested Events, when an unspecified (None) onset of an EventGroup is replaced, the entire subtree of its content is shifted by the same amount. E.g. if a Chord is constructed with Notes with unspecified onsets, the Notes onsets will initially be replaced with zeros. Then, if the Chord onset is unspecified (None) and the Chord is passed in the content of a Measure and the Chord onset is replaced with 1.0, then the Notes are shifted to 1.0. If the Measure is then passed in the content of a Staff, the Measure and all its content might be shifted again.


Event

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

A superclass for Note, Rest, EventGroup, and anything happening in time.

Parameters:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • onset (float | None) –

    The onset (start) time. This can be an “idealized” time for a symbolic score or an actual “real” time from a performance. Default is None.

  • duration (float) –

    The duration of the event in quarters or seconds. This can be zero for objects such as key signatures or time signatures.

Attributes:

  • parent (Optional[Event]) –

    The containing object or None.

  • _onset (float | None) –

    The onset (start) time.

  • duration (float) –

    The duration of the event in quarters or seconds.

  • info (Optional[Dict]) –

    Additional attribute/value information.

Source code in amads/core/basics.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def __init__(self, parent: Optional["EventGroup"],
             onset: Optional[float], duration: float):
    """
    Initialize an Event instance.

    """
    self.parent = None  # set below when inserted into parent
    self._onset = onset
    self.duration = duration
    self.info = None

    if parent:
        assert isinstance(parent, EventGroup)
        parent.insert(self)
    else:
        self.parent = None

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.

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.

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

__repr__

__repr__() -> str

All Event subclasses inherit this to use str().

Thus, a list of Events is printed using their str methods

Source code in amads/core/basics.py
120
121
122
123
124
125
def __repr__(self) -> str:
    """All Event subclasses inherit this to use str().

    Thus, a list of Events is printed using their __str__ methods
    """
    return str(self)

_event_times

_event_times(dur: bool = True) -> str

produce onset and duration string for str

Source code in amads/core/basics.py
135
136
137
138
139
140
141
def _event_times(self, dur: bool = True) -> str:
    """produce onset and duration string for __str__
    """
    duration = self.duration
    if duration is not None:
        duration = f"{self.duration:0.3f}"
    return f"{self._event_onset()}, duration={duration}"

time_shift

time_shift(increment: float) -> Event

Change the onset by an increment.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

Returns:

  • Event

    The object. This method modifies the Event.

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

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).

    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
243
244
245
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
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

_quantize

_quantize(divisions: int) -> Event

Modify onset and offset to a multiple of divisions per quarter note.

This method modifies the Event in place. It also handles tied notes.

E.g., use divisions=4 for sixteenth notes. If a Note tied to or from other notes quantizes to a zero duration, reduce the chain of tied notes to eliminate zero-length notes. See Collection.quantize for additional details.

self.onset and self.duration must be non-None.

Parameters:

  • divisions (int) –

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

Returns:

  • Event

    self, after quantization.

Source code in amads/core/basics.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def _quantize(self, divisions: int) -> "Event":
    """Modify onset and offset to a multiple of divisions per quarter note.

    This method modifies the Event in place. It also handles tied notes.

    E.g., use divisions=4 for sixteenth notes. If a
    Note tied to or from other notes quantizes to a zero
    duration, reduce the chain of tied notes to eliminate
    zero-length notes. See Collection.quantize for
    additional details.

    self.onset and self.duration must be non-None.

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

    Returns
    -------
    Event
        self, after quantization.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot quantize Event with None onset or duration")
    self.onset = round(self.onset * divisions) / divisions
    quantized_offset = round(self.offset * divisions) / divisions

    # tied note cases: Given any two tied notes where the first has a
    # quantized duration of zero, we want to eliminate the first one
    # because it is almost certainly at the end of a measure and ties
    # to the "real" note at the start of the next measure. In the
    # special case where the tied-to note quantizes to a zero duration,
    # we still want it to appear at the beginning of the measure, and
    # our convention is to set its duration to one quantum as long as
    # the original string of tied notes had a non-zero duration.
    # (Zero duration is preserved however for cases like meta-events
    # and grace notes which have zero duration before quantization.)
    #     Otherwise, if there are two tied notes and the first has a
    # non-zero and the second has zero quantized duration, we assume
    # that the note extended just barely across the bar line and we
    # eliminate the second note.
    #     Note that since we cannot look back to see if we are at the
    # end of a tie, we need to look forward using Note.tie.

    if (self.duration == 0 and
        (not isinstance(self, Note) or self.tie == None)):
        return self  # do not change duration if it is originally zero

    while isinstance(self, Note) and self.tie:  # check tied-to note:
        tie = self.tie  # the note our tie connects to
        onset = round(tie.onset * divisions) / divisions  # type: ignore
        offset = round(tie.offset * divisions) / divisions  # type: ignore
        duration = offset - onset  # quantized duration
        # if we tie from non-zero quantized duration to zero quantized
        # duration, eliminate the tied-to note
        if (quantized_offset - self.onset > 0 and   # type: ignore
            duration == 0):                         # type: ignore
            self.tie = tie.tie  # in case tie continues
            # remove tied_to note from its parent
            if tie.parent:
                tie.parent.remove(tie)
            # print("removed tied-to note", tied_to,
            #       "because duration quantized to zero")
        elif quantized_offset - self.onset == 0:    # type: ignore
            # remove self from its parent; prefer tied_to note
            # before removing, transfer duration from self to
            # tied_to to avoid strange case where the tied group
            # originally had a non-zero duration so we want the
            # tied_to duration to be non-zero:
            tie.duration += self.duration
            if self.parent:
                self.parent.remove(self)
            # tied_to will be revisited and quantized so no more work here
            return self
        else:  # both notes have non-zero durations
            break

    # now that potential ties are handled, set the duration of self
    if self.duration != 0:  # only modify non-zero durations
        self.duration = quantized_offset - self.onset  # type: ignore
        if self.duration == 0:  # do not allow duration to become zero:
            self.duration = 1 / divisions 
    # else: original zero duration remains zero after quantization
    return self

_convert_to_seconds

_convert_to_seconds(time_map: TimeMap) -> None

Convert the event's duration and onset to seconds.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def _convert_to_seconds(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to seconds.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot convert Event with None onset or duration")
    onset_time = time_map.quarter_to_time(self.onset)       # type: ignore
    offset_time = time_map.quarter_to_time(self.offset)     # type: ignore
    self.onset = onset_time
    self.duration = offset_time - onset_time

_convert_to_quarters

_convert_to_quarters(time_map: TimeMap) -> None

Convert the event's duration and onset to quarters.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def _convert_to_quarters(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to quarters.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot convert Event with None onset or duration")
    onset_quarters = time_map.time_to_quarter(self.onset)
    offset_quarters = time_map.time_to_quarter(self.offset)
    self.onset = onset_quarters
    self.duration = offset_quarters - onset_quarters

Note

Note(
    parent: Optional[EventGroup] = None,
    onset: Optional[float] = None,
    duration: float = 1.0,
    pitch: Union[Pitch, int, float, str, None] = 60,
    dynamic: Union[int, str, None] = None,
    lyric: Optional[str] = None,
)

Bases: Event

Note represents a musical note.

A Note is normally an element of a Measure in a full score, and an element of a Part in a flat score.

Parameters:

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

    The containing object or None.

  • onset (float, default: None ) –

    The onset (start) time. If None (default) is specified, a default onset will be calculated when the Note is inserted into an EventGroup.

  • duration (float, default: 1.0 ) –

    The duration of the note in quarters or seconds.

  • pitch (Union[Pitch, int, float], default: 60 ) –

    A Pitch object or an integer MIDI key number that will be converted to a Pitch object. The default (60) represents middle C.

  • dynamic (Optional[Union[int, str]], default: None ) –

    Dynamic level (integer MIDI velocity or arbitrary string).

  • lyric (Optional[str], default: None ) –

    Lyric text.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (Optional[float]) –

    The onset (start) time. None represents an unspecified onset.

  • duration (float) –

    The duration of the note in quarters or seconds. See the property tied_duration for the duration of an entire group if the note is the first of a tied group of notes.

  • pitch (Pitch | None) –

    The pitch of the note. Unpitched notes have a pitch of None.

  • dynamic (Optional[Union[int, str]]) –

    Dynamic level (integer MIDI velocity or arbitrary string).

  • lyric (Optional[str]) –

    Lyric text.

  • tie (Optional[Note]) –

    The note that this note is tied to, if any.

Source code in amads/core/basics.py
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def __init__(self,
             parent: Optional["EventGroup"] = None,
             onset: Optional[float] = None,
             duration: float = 1.0,
             pitch: Union["Pitch", int, float, str, None] = 60,
             dynamic: Union[int, str, None] = None,
             lyric: Optional[str] = None):
    super().__init__(parent, onset, float(duration))
    if isinstance(pitch, (int, float, str)):
        pitch = Pitch(pitch)
    self.pitch = pitch
    self.dynamic = dynamic
    self.lyric = lyric
    self.tie = None

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.

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.

measure property

measure: Optional[Measure]

Retrieve the Measure containing this event

Returns:

  • Optional[Measure]

    The Measure containing this event or None if not found.

tied_duration property

tied_duration: Union[float, int]

Retrieve the duration of the note in quarters or seconds.

If the note is the first note of a sequence of tied notes, return the duration of the entire sequence. However, if there are preceding notes tied to this note, they will not be considered part of the tied sequence. If you want to avoid processing notes that are tied to from earlier notes, you should either use merge_tied_notes() to eliminate them, or follow the tie links and add tied-to notes to a set as you traverse the score so you can ignore them when they are encountered. In some cases, notes can be tied across staves, in which case it might require two passes to (1) find all tied-to notes, and then (2) enumerate the rest of them. merge_tied_notes() handles this case properly.

Returns:

  • float

    The duration of the note and those it is tied to directly or indirectly, in quarters or seconds. The sum of durations is returned without checking whether notes are contiguous.

tied_offset property

tied_offset: float

Retrieve the offset (stop) time of a note or tied group of notes.

If the note is the first note of a sequence of tied notes, return the offset of the entire sequence. However, if there are preceding notes tied to this note, they will not be considered part of the tied sequence.

Returns:

  • float

    The global offset (stop) time of the note and those it is tied to.

step property

step: str

Retrieve the name of the pitch without accidental, e.g., "G".

If the note is unpitched (pitch is None), return the empty string.

name_with_octave property

name_with_octave: str

Retrieve the name of the pitch with octave, e.g., A4 or Bb3.

If the note is unpitched (pitch is None), return the empty string.

pitch_class property writable

pitch_class: int

Retrieve the pitch class of the note, e.g., 0, 1, 2, ..., 11.

If the note is unpitched (pitch is None), raise ValueError.

octave property writable

octave: int

Retrieve the octave number of the note.

The note name is based on key_num - alt, e.g., C4 has octave 4 while B#3 has octave 3. See also Pitch.register.

If the note is unpitched (pitch is None), raise ValueError.

If the note is unpitched (pitch is None), raise ValueError.

Returns:

  • int

    The octave number of the note.

key_num property

key_num: float | int

Retrieve the MIDI key number of the note, e.g., C4 = 60.

If the note is unpitched (pitch is None), raise ValueError.

Returns:

  • int

    The MIDI key number of the note.

Functions

__repr__

__repr__() -> str

All Event subclasses inherit this to use str().

Thus, a list of Events is printed using their str methods

Source code in amads/core/basics.py
120
121
122
123
124
125
def __repr__(self) -> str:
    """All Event subclasses inherit this to use str().

    Thus, a list of Events is printed using their __str__ methods
    """
    return str(self)

_event_times

_event_times(dur: bool = True) -> str

produce onset and duration string for str

Source code in amads/core/basics.py
135
136
137
138
139
140
141
def _event_times(self, dur: bool = True) -> str:
    """produce onset and duration string for __str__
    """
    duration = self.duration
    if duration is not None:
        duration = f"{self.duration:0.3f}"
    return f"{self._event_onset()}, duration={duration}"

time_shift

time_shift(increment: float) -> Event

Change the onset by an increment.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

Returns:

  • Event

    The object. This method modifies the Event.

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

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).

    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
243
244
245
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
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

_quantize

_quantize(divisions: int) -> Event

Modify onset and offset to a multiple of divisions per quarter note.

This method modifies the Event in place. It also handles tied notes.

E.g., use divisions=4 for sixteenth notes. If a Note tied to or from other notes quantizes to a zero duration, reduce the chain of tied notes to eliminate zero-length notes. See Collection.quantize for additional details.

self.onset and self.duration must be non-None.

Parameters:

  • divisions (int) –

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

Returns:

  • Event

    self, after quantization.

Source code in amads/core/basics.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def _quantize(self, divisions: int) -> "Event":
    """Modify onset and offset to a multiple of divisions per quarter note.

    This method modifies the Event in place. It also handles tied notes.

    E.g., use divisions=4 for sixteenth notes. If a
    Note tied to or from other notes quantizes to a zero
    duration, reduce the chain of tied notes to eliminate
    zero-length notes. See Collection.quantize for
    additional details.

    self.onset and self.duration must be non-None.

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

    Returns
    -------
    Event
        self, after quantization.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot quantize Event with None onset or duration")
    self.onset = round(self.onset * divisions) / divisions
    quantized_offset = round(self.offset * divisions) / divisions

    # tied note cases: Given any two tied notes where the first has a
    # quantized duration of zero, we want to eliminate the first one
    # because it is almost certainly at the end of a measure and ties
    # to the "real" note at the start of the next measure. In the
    # special case where the tied-to note quantizes to a zero duration,
    # we still want it to appear at the beginning of the measure, and
    # our convention is to set its duration to one quantum as long as
    # the original string of tied notes had a non-zero duration.
    # (Zero duration is preserved however for cases like meta-events
    # and grace notes which have zero duration before quantization.)
    #     Otherwise, if there are two tied notes and the first has a
    # non-zero and the second has zero quantized duration, we assume
    # that the note extended just barely across the bar line and we
    # eliminate the second note.
    #     Note that since we cannot look back to see if we are at the
    # end of a tie, we need to look forward using Note.tie.

    if (self.duration == 0 and
        (not isinstance(self, Note) or self.tie == None)):
        return self  # do not change duration if it is originally zero

    while isinstance(self, Note) and self.tie:  # check tied-to note:
        tie = self.tie  # the note our tie connects to
        onset = round(tie.onset * divisions) / divisions  # type: ignore
        offset = round(tie.offset * divisions) / divisions  # type: ignore
        duration = offset - onset  # quantized duration
        # if we tie from non-zero quantized duration to zero quantized
        # duration, eliminate the tied-to note
        if (quantized_offset - self.onset > 0 and   # type: ignore
            duration == 0):                         # type: ignore
            self.tie = tie.tie  # in case tie continues
            # remove tied_to note from its parent
            if tie.parent:
                tie.parent.remove(tie)
            # print("removed tied-to note", tied_to,
            #       "because duration quantized to zero")
        elif quantized_offset - self.onset == 0:    # type: ignore
            # remove self from its parent; prefer tied_to note
            # before removing, transfer duration from self to
            # tied_to to avoid strange case where the tied group
            # originally had a non-zero duration so we want the
            # tied_to duration to be non-zero:
            tie.duration += self.duration
            if self.parent:
                self.parent.remove(self)
            # tied_to will be revisited and quantized so no more work here
            return self
        else:  # both notes have non-zero durations
            break

    # now that potential ties are handled, set the duration of self
    if self.duration != 0:  # only modify non-zero durations
        self.duration = quantized_offset - self.onset  # type: ignore
        if self.duration == 0:  # do not allow duration to become zero:
            self.duration = 1 / divisions 
    # else: original zero duration remains zero after quantization
    return self

_convert_to_seconds

_convert_to_seconds(time_map: TimeMap) -> None

Convert the event's duration and onset to seconds.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def _convert_to_seconds(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to seconds.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot convert Event with None onset or duration")
    onset_time = time_map.quarter_to_time(self.onset)       # type: ignore
    offset_time = time_map.quarter_to_time(self.offset)     # type: ignore
    self.onset = onset_time
    self.duration = offset_time - onset_time

_convert_to_quarters

_convert_to_quarters(time_map: TimeMap) -> None

Convert the event's duration and onset to quarters.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def _convert_to_quarters(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to quarters.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot convert Event with None onset or duration")
    onset_quarters = time_map.time_to_quarter(self.onset)
    offset_quarters = time_map.time_to_quarter(self.offset)
    self.onset = onset_quarters
    self.duration = offset_quarters - onset_quarters

__deepcopy__

__deepcopy__(memo: dict) -> Note

Return a (mostly) deep copy of the Note instance.

Except the pitch is shallow copied to avoid copying the entire Pitch object, which is considered immutable.

Parameters:

  • memo (dict) –

    A dictionary to keep track of already copied objects.

Returns:

  • Note

    A deep copy of the Note instance with a shallow copy of the pitch.

Source code in amads/core/basics.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
def __deepcopy__(self, memo: dict) -> "Note":
    """Return a (mostly) deep copy of the Note instance.

    Except the pitch is shallow copied to avoid copying
    the entire Pitch object, which is considered immutable.

    Parameters
    ----------
    memo : dict
        A dictionary to keep track of already copied objects.

    Returns
    -------
    Note
        A deep copy of the Note instance with a shallow copy of the pitch.
    """
    cls = self.__class__
    result = cls.__new__(cls)
    memo[id(self)] = result

    # Iterate up the superclass chain and copy __slots__ at each level
    # If there is a __dict__, it will be in a __slots__ and will be deep
    # copied, so all attributes in __dict__ will be copied. If there is
    # multiple inheritance with duplicated slots, this will copy the
    # duplicated slot two (or more) times, but it should get the right
    # result.
    for base in cls.__mro__:
        if hasattr(base, '__slots__'):
            for slot in base.__slots__:
                if slot == "pitch":
                    result.pitch = self.pitch
                else:
                    setattr(result, slot,
                            copy.deepcopy(getattr(self, slot), memo))

    return result

enharmonic

enharmonic() -> Pitch

Return a Pitch representing the enharmonic.

The enharmonic Pitch's alt will be zero or have the opposite sign such that alt is minimized. E.g., the enharmonic of C-double-flat is A-sharp (not B-flat). If alt is zero, return a Pitch with alt of +1 or -1 if possible. Otherwise, return a Pitch with alt of -2.

If the note is unpitched (pitch is None), raise ValueError.

If the note is unpitched (pitch is None), raise ValueError.

Returns:

  • Pitch

    A Pitch object representing the enharmonic equivalent of the note.

Source code in amads/core/basics.py
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
def enharmonic(self) -> "Pitch":
    """Return a `Pitch` representing the enharmonic.

    The enharmonic `Pitch`'s `alt` will be zero or have the opposite
    sign such that `alt` is minimized. E.g., the enharmonic of
    C-double-flat is A-sharp (not B-flat). If `alt` is zero, return
    a Pitch with alt of +1 or -1 if possible. Otherwise, return a
    Pitch with alt of -2.

    If the note is unpitched (pitch is None), raise ValueError.

    If the note is unpitched (pitch is None), raise ValueError.

    Returns
    -------
    Pitch
        A Pitch object representing the enharmonic equivalent of the note.
    """
    if self.pitch is None:
        raise ValueError("Unpitched note has no enharmonic equivalent.")
    return self.pitch.enharmonic()

upper_enharmonic

upper_enharmonic() -> Pitch

Return a valid enharmonic Pitch with alt decreased, e.g., C#->Db.

It follows that the alt is decreased by 1 or 2, e.g., C### (with alt = +3) becomes D# (with alt = +1).

If the note is unpitched (pitch is None), raise ValueError.

If the note is unpitched (pitch is None), raise ValueError.

Returns:

  • Pitch

    A Pitch object representing the upper enharmonic equivalent of the note.

Source code in amads/core/basics.py
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
def upper_enharmonic(self) -> "Pitch":
    """Return a valid enharmonic Pitch with alt decreased, e.g., C#->Db.

    It follows that the alt is decreased by 1 or 2, e.g., C###
    (with `alt` = +3) becomes D# (with `alt` = +1).

    If the note is unpitched (pitch is None), raise ValueError.

    If the note is unpitched (pitch is None), raise ValueError.

    Returns
    -------
    Pitch
        A Pitch object representing the upper enharmonic
        equivalent of the note.
    """
    if self.pitch is None:
        raise ValueError(
                  "Unpitched note has no upper enharmonic equivalent.")
    return self.pitch.upper_enharmonic()

lower_enharmonic

lower_enharmonic() -> Pitch

Return a valid enharmonic Pitch with alt increased, e.g., Db->C#.

It follows that the alt is increased by 1 or 2, e.g., D# (with alt = +1) becomes C### (with alt = +3).

If the note is unpitched (pitch is None), raise ValueError.

If the note is unpitched (pitch is None), raise ValueError.

Returns:

  • Pitch

    A Pitch object representing the lower enharmonic equivalent of the note.

Source code in amads/core/basics.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
def lower_enharmonic(self) -> "Pitch":
    """Return a valid enharmonic Pitch with alt increased, e.g., Db->C#.

    It follows that the alt is increased by 1 or 2, e.g., D#
    (with `alt` = +1) becomes C### (with `alt` = +3).

    If the note is unpitched (pitch is None), raise ValueError.

    If the note is unpitched (pitch is None), raise ValueError.

    Returns
    -------
    Pitch
        A Pitch object representing the lower enharmonic
        equivalent of the note.
    """
    if self.pitch is None:
        raise ValueError(
                  "Unpitched note has no lower enharmonic equivalent.")
    return self.pitch.lower_enharmonic()

simplest_enharmonic

simplest_enharmonic(sharp_or_flat: Optional[str] = 'default') -> Pitch

Return a valid Pitch with the simplest enharmonic representation.

(See [simplest_enharmonic] [amads.core.pitch.Pitch.simplest_enharmonic].)

Parameters:

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

    This is only relevant if the pitch needs an alteration, otherwise it is unused. The value can be "sharp" (use sharps), "flat" (use flats), and otherwise use the same enharmonic choice as the Pitch constructor.

Exceptions

If the note is unpitched (pitch is None), raise ValueError.

Returns:

  • Pitch

    A Pitch object representing the enharmonic equivalent.

Source code in amads/core/basics.py
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
def simplest_enharmonic(self, 
        sharp_or_flat: Optional[str] = "default") -> "Pitch":
    """Return a valid Pitch with the simplest enharmonic representation.

    (See [simplest_enharmonic]
     [amads.core.pitch.Pitch.simplest_enharmonic].)

    Parameters
    ----------
    sharp_or_flat: str
        This is only relevant if the pitch needs an alteration, otherwise
        it is unused. The value can be "sharp" (use sharps), "flat" (use
        flats), and otherwise use the same enharmonic choice as the Pitch
        constructor.

    Exceptions
    ----------
    If the note is unpitched (pitch is None), raise ValueError.

    Returns
    -------
    Pitch
        A Pitch object representing the enharmonic equivalent.
    """
    if self.pitch is None:
        raise ValueError(
                  "Unpitched note has no simplest enharmonic equivalent.")
    return self.pitch.simplest_enharmonic(sharp_or_flat)

Rest

Rest(
    parent: Optional[EventGroup] = None,
    onset: Optional[float] = None,
    duration: float = 1,
)

Bases: Event

Rest represents a musical rest.

A Rest is normally an element of a Measure.

Parameters:

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

    The containing object or None.

  • onset (float, default: None ) –

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

  • duration (float, default: 1 ) –

    The duration of the rest in quarters or seconds.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (float) –

    The onset (start) time. None represents an unspecified onset.

  • duration (float) –

    The duration of the rest in quarters or seconds.

Source code in amads/core/basics.py
575
576
577
def __init__(self, parent: Optional["EventGroup"] = None,
             onset: Optional[float] = None, duration: float = 1):
    super().__init__(parent, onset, duration)

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.

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.

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

__repr__

__repr__() -> str

All Event subclasses inherit this to use str().

Thus, a list of Events is printed using their str methods

Source code in amads/core/basics.py
120
121
122
123
124
125
def __repr__(self) -> str:
    """All Event subclasses inherit this to use str().

    Thus, a list of Events is printed using their __str__ methods
    """
    return str(self)

_event_times

_event_times(dur: bool = True) -> str

produce onset and duration string for str

Source code in amads/core/basics.py
135
136
137
138
139
140
141
def _event_times(self, dur: bool = True) -> str:
    """produce onset and duration string for __str__
    """
    duration = self.duration
    if duration is not None:
        duration = f"{self.duration:0.3f}"
    return f"{self._event_onset()}, duration={duration}"

time_shift

time_shift(increment: float) -> Event

Change the onset by an increment.

Parameters:

  • increment (float) –

    The time increment (in quarters or seconds).

Returns:

  • Event

    The object. This method modifies the Event.

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

    Parameters
    ----------
    increment : float
        The time increment (in quarters or seconds).

    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
243
244
245
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
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

_quantize

_quantize(divisions: int) -> Event

Modify onset and offset to a multiple of divisions per quarter note.

This method modifies the Event in place. It also handles tied notes.

E.g., use divisions=4 for sixteenth notes. If a Note tied to or from other notes quantizes to a zero duration, reduce the chain of tied notes to eliminate zero-length notes. See Collection.quantize for additional details.

self.onset and self.duration must be non-None.

Parameters:

  • divisions (int) –

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

Returns:

  • Event

    self, after quantization.

Source code in amads/core/basics.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def _quantize(self, divisions: int) -> "Event":
    """Modify onset and offset to a multiple of divisions per quarter note.

    This method modifies the Event in place. It also handles tied notes.

    E.g., use divisions=4 for sixteenth notes. If a
    Note tied to or from other notes quantizes to a zero
    duration, reduce the chain of tied notes to eliminate
    zero-length notes. See Collection.quantize for
    additional details.

    self.onset and self.duration must be non-None.

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

    Returns
    -------
    Event
        self, after quantization.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot quantize Event with None onset or duration")
    self.onset = round(self.onset * divisions) / divisions
    quantized_offset = round(self.offset * divisions) / divisions

    # tied note cases: Given any two tied notes where the first has a
    # quantized duration of zero, we want to eliminate the first one
    # because it is almost certainly at the end of a measure and ties
    # to the "real" note at the start of the next measure. In the
    # special case where the tied-to note quantizes to a zero duration,
    # we still want it to appear at the beginning of the measure, and
    # our convention is to set its duration to one quantum as long as
    # the original string of tied notes had a non-zero duration.
    # (Zero duration is preserved however for cases like meta-events
    # and grace notes which have zero duration before quantization.)
    #     Otherwise, if there are two tied notes and the first has a
    # non-zero and the second has zero quantized duration, we assume
    # that the note extended just barely across the bar line and we
    # eliminate the second note.
    #     Note that since we cannot look back to see if we are at the
    # end of a tie, we need to look forward using Note.tie.

    if (self.duration == 0 and
        (not isinstance(self, Note) or self.tie == None)):
        return self  # do not change duration if it is originally zero

    while isinstance(self, Note) and self.tie:  # check tied-to note:
        tie = self.tie  # the note our tie connects to
        onset = round(tie.onset * divisions) / divisions  # type: ignore
        offset = round(tie.offset * divisions) / divisions  # type: ignore
        duration = offset - onset  # quantized duration
        # if we tie from non-zero quantized duration to zero quantized
        # duration, eliminate the tied-to note
        if (quantized_offset - self.onset > 0 and   # type: ignore
            duration == 0):                         # type: ignore
            self.tie = tie.tie  # in case tie continues
            # remove tied_to note from its parent
            if tie.parent:
                tie.parent.remove(tie)
            # print("removed tied-to note", tied_to,
            #       "because duration quantized to zero")
        elif quantized_offset - self.onset == 0:    # type: ignore
            # remove self from its parent; prefer tied_to note
            # before removing, transfer duration from self to
            # tied_to to avoid strange case where the tied group
            # originally had a non-zero duration so we want the
            # tied_to duration to be non-zero:
            tie.duration += self.duration
            if self.parent:
                self.parent.remove(self)
            # tied_to will be revisited and quantized so no more work here
            return self
        else:  # both notes have non-zero durations
            break

    # now that potential ties are handled, set the duration of self
    if self.duration != 0:  # only modify non-zero durations
        self.duration = quantized_offset - self.onset  # type: ignore
        if self.duration == 0:  # do not allow duration to become zero:
            self.duration = 1 / divisions 
    # else: original zero duration remains zero after quantization
    return self

_convert_to_seconds

_convert_to_seconds(time_map: TimeMap) -> None

Convert the event's duration and onset to seconds.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def _convert_to_seconds(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to seconds.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot convert Event with None onset or duration")
    onset_time = time_map.quarter_to_time(self.onset)       # type: ignore
    offset_time = time_map.quarter_to_time(self.offset)     # type: ignore
    self.onset = onset_time
    self.duration = offset_time - onset_time

_convert_to_quarters

_convert_to_quarters(time_map: TimeMap) -> None

Convert the event's duration and onset to quarters.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def _convert_to_quarters(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to quarters.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    if self._onset is None or self.duration is None:
        raise ValueError(
            "Cannot convert Event with None onset or duration")
    onset_quarters = time_map.time_to_quarter(self.onset)
    offset_quarters = time_map.time_to_quarter(self.offset)
    self.onset = onset_quarters
    self.duration = offset_quarters - onset_quarters

Measure

Measure(
    *args: Event,
    parent: Optional[EventGroup] = None,
    onset: Optional[float] = None,
    duration: float = 4,
    number: Optional[str] = None
)

Bases: Sequence

A Measure models a musical measure (bar).

A Measure can contain many object types including Note, Rest, Chord, and (in theory) custom Events. Measures are elements of a Staff.

See Constructor Details.

Parameters:

  • *args (Event, default: () ) –

    A variable number of Event objects to be added to the group.

  • 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: 4 ) –

    The duration in quarters or seconds. Must be passed as a keyword parameter due to *args.

  • number (Optional[str], default: None ) –

    A string representing the measure number. 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. 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 Measure.

  • number (Optional[str]) –

    A string representing the measure number if any.

Source code in amads/core/basics.py
2758
2759
2760
2761
2762
def __init__(self, *args: Event, parent: Optional[EventGroup] = None,
             onset: Optional[float] = None, duration: float = 4,
             number: Optional[str] = None):
    super().__init__(parent, onset, duration, list(args))
    self.number = number

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.

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.

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

__repr__

__repr__() -> str

All Event subclasses inherit this to use str().

Thus, a list of Events is printed using their str methods

Source code in amads/core/basics.py
120
121
122
123
124
125
def __repr__(self) -> str:
    """All Event subclasses inherit this to use str().

    Thus, a list of Events is printed using their __str__ methods
    """
    return str(self)

_event_times

_event_times(dur: bool = True) -> str

produce onset and duration string for str

Source code in amads/core/basics.py
135
136
137
138
139
140
141
def _event_times(self, dur: bool = True) -> str:
    """produce onset and duration string for __str__
    """
    duration = self.duration
    if duration is not None:
        duration = f"{self.duration:0.3f}"
    return f"{self._event_onset()}, duration={duration}"

time_shift

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

Change the onset by an increment, affecting all content.

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.

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
def time_shift(self, increment: float,
               content_only: bool = False) -> "EventGroup":
    """
    Change the onset by an increment, affecting all content.

    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`.
    """
    if not content_only:
        self._onset += increment  # type: ignore (onset is now number)
    for elem in self.content:
        elem.time_shift(increment)
    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
243
244
245
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
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

_quantize

_quantize(divisions: int) -> EventGroup

"Since _quantize is called recursively on children, this method is needed to redirect EventGroup._quantize to quantize

Source code in amads/core/basics.py
2025
2026
2027
2028
2029
def _quantize(self, divisions: int) -> "EventGroup":
    """"Since `_quantize` is called recursively on children, this method is
    needed to redirect `EventGroup._quantize` to `quantize`
    """
    return self.quantize(divisions)

_convert_to_seconds

_convert_to_seconds(time_map: TimeMap) -> None

Convert the event's duration and onset to seconds using the provided TimeMap. Convert content as well.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
def _convert_to_seconds(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to seconds using the
    provided TimeMap. Convert content as well.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    super()._convert_to_seconds(time_map)
    for elem in self.content:
        elem._convert_to_seconds(time_map)

_convert_to_quarters

_convert_to_quarters(time_map: TimeMap) -> None

Convert the event's duration and onset to quarters using the provided TimeMap. Convert content as well.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
def _convert_to_quarters(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to quarters using the
    provided TimeMap. Convert content as well.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    onset_quarters = time_map.time_to_quarter(self.onset)
    offset_quarters = time_map.time_to_quarter(self.onset + self.duration)
    self.onset = onset_quarters
    self.duration = offset_quarters - onset_quarters
    for elem in self.content:
        elem._convert_to_quarters(time_map)

_find_copied_version

_find_copied_version(
    original_note: Note, exclude: Note
) -> Optional[Note]

Find the copied version of a note in self.

Parameters:

  • original_note (Note) –

    The note that was copied

Source code in amads/core/basics.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
def _find_copied_version(self, original_note: Note,
                         exclude: Note) -> Optional[Note]:
    """Find the copied version of a note in self.

    Parameters
    ----------
    original_note: Note
        The note that was copied
    """
    for note in self.find_all(Note):
        note = cast(Note, note)
        if (note != exclude and note.onset == original_note.onset and
            note.pitch == original_note.pitch and
            note.duration == original_note.duration):
            return note
    return None

_add_slice_children

_add_slice_children(
    source: EventGroup,
    start: float,
    end: float,
    mode: str,
    truncate: str,
    min_duration: float,
) -> tuple[float, float]

Helper method for slice to populate the content of self. Assumes that source is a component of a flat score and that self is a Sequence with no content.

Returns:

  • float

    The minimum onset of the content added to self.

Source code in amads/core/basics.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
def _add_slice_children(self, source: "EventGroup", start: float,
        end: float, mode: str, truncate: str,
        min_duration: float) -> tuple[float, float]:
    """Helper method for slice to populate the content of self.
    Assumes that source is a component of a flat score and that self
    is a Sequence with no content.

    Returns
    -------
    float
        The minimum onset of the content added to self.
    """
    # Begin by finding all content to be included. Since score is flat,
    # source can only be a Score, a Part, or a Staff. So if a component is
    # not a Note, we copy all children (Parts or Staffs) into content
    # and recurse to add a slice of *their* content.
    min_onset = float("inf")
    max_offset = float("-inf")
    content = source.content
    if len(content) == 0:
        return min_onset, max_offset
    if not isinstance(content[0], Note):
        for elem in content:
            if isinstance(elem, EventGroup):
                elem_copy = elem.insert_emptycopy_into(self)
                e_min, e_max = elem._add_slice_children(elem_copy, start,
                                       end, mode, truncate, min_duration)
                min_onset = min(min_onset, e_min)
                max_offset = max(max_offset, e_max)
        return min_onset, max_offset

    assert(isinstance(source, Sequence))  # content is a list of Notes

    for elem in content:
        copied = None
        if mode == "onsets":
            if elem.onset >= start and elem.onset < end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "overlaps":
            if elem.onset < end and elem.offset > start:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "offsets":
            if elem.offset > start and elem.offset <= end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "strict":
            if elem.onset >= start and elem.offset <= end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        else:
            raise ValueError(f"invalid mode {mode} for slice")
        if copied:
            min_onset = min(min_onset, copied.onset)
            max_offset = max(max_offset, copied.offset)

    if truncate == "keep":
        return min_onset, max_offset
    if truncate in ["truncate", "beginning"]:
        # if we are truncating notes that start before start, we can save
        # some time by only looking at elements where onset < start
        j = len(content)
        for i, elem in enumerate(content):
            if elem.onset > start:
                j = i
                break  # now j indexes the first element with onset > start
        min_onset = source._truncate_note_beginnings(content[0 : j], start)
    if truncate in ["truncate", "dur", "duration", "end", "ending"]:
        # any note can end after end, so we have to look at all of them:
        max_offset = source._truncate_note_endings(content, end)

    # now remove any notes that are too short after truncation:
    if min_duration > 0:
        min_onset = float("inf")
        max_offset = float("-inf")
        filtered = []
        for elem in content:
            if elem.duration >= min_duration:
                filtered.append(elem)
                min_onset = min(min_onset, elem.onset)
                max_offset = max(max_offset, elem.offset)
        source.content = filtered
    return min_onset, max_offset

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

_copy_parents

_copy_parents(start: float, end: float) -> EventGroup

Helper method for slice to populate the ancestors of self in result.

This method is called by slice to populate the ancestors of self in the result Score. The ancestors are populated with empty copies of the original ancestors.

Returns:

  • EventGroup

    A copy of self with ancestors copied up to the Score.

Raises:

  • ValueError

    If self is not part of a Score.

Source code in amads/core/basics.py
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
def _copy_parents(self, start: float, end: float) -> "EventGroup":
    """Helper method for slice to populate the ancestors of self in result.

    This method is called by `slice` to populate the ancestors of self in
    the result Score. The ancestors are populated with empty copies of the
    original ancestors.

    Returns
    -------
    EventGroup
        A copy of self with ancestors copied up to the Score.

    Raises
    ------
    ValueError
        If self is not part of a Score.
    """
    # Algorithm: recursively populate ancestors from self up to score.
    if self is None:
        raise ValueError("slice can only be called on Sequences that are "
                         "part of a Score")
    elif isinstance(self, Score):  # base case: self is a Score
        return self # return copy of self
    else:  # copy parent & up; return copy of self inserted into parent copy
        parent = cast(EventGroup, self.parent)._copy_parents(start, end)
        parent.onset = start
        parent.offset = end
        # insert copy of self into parent copy:
        return self.insert_emptycopy_into(parent)

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
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
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
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
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)

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
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
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_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
1778
1779
1780
1781
1782
1783
1784
1785
1786
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
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
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
1804
1805
1806
1807
1808
1809
1810
1811
1812
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
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
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)

Source code in amads/core/basics.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
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)
    """
    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
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
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

_leaf_elements

_leaf_elements() -> list[Event]

Return a list of all leaf elements in this EventGroup.

Source code in amads/core/basics.py
1893
1894
1895
1896
1897
1898
1899
1900
1901
def _leaf_elements(self) -> list[Event]:
    """Return a list of all leaf elements in this EventGroup."""
    result = []
    for elem in self.content:
        if isinstance(elem, EventGroup):
            result.extend(elem._leaf_elements())
        else:
            result.append(elem)
    return result

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
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
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
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 = 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
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
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)

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
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
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
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

_add_measure_children

_add_measure_children(
    source: EventGroup,
    start: float,
    end: float,
    start_time: float,
    end_time: float,
) -> tuple[float, float]

Helper method for to populate the content with selected measures. Assumes that self is a component of a full score and that this Staff (self) has no content yet.

Since only measures within start and end are copied, the copied measures and other content all have onsets and offsets within copy range and do not need to be adjusted.

Assumes that notes crossing measure boundaries are tied and that ties to notes outside the copied measures should be broken, truncating the copied note to the measure boundary.

Returns:

  • tuple[float, float]

    The minimum onset and maximum offset of the content added to self.

Source code in amads/core/basics.py
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
def _add_measure_children(self, source: "EventGroup", start: float,
                          end: float, start_time: float,
                          end_time: float) -> tuple[float, float]:
    """Helper method for to populate the content with
    selected measures. Assumes that self is a component of a full score and
    that this Staff (self) has no content yet.

    Since only measures within start and end are copied, the copied
    measures and other content all have onsets and offsets within
    copy range and do not need to be adjusted.

    Assumes that notes crossing measure boundaries are tied and that
    ties to notes outside the copied measures should be broken, truncating
    the copied note to the measure boundary.

    Returns
    -------
    tuple[float, float]
        The minimum onset and maximum offset of the content added to self.
    """
    # Assume that whatever EventGroup(s) contain measures, they will *only*
    # contain measures, so we can check content[0] to find the measure
    # level. Recursively copy the structure from this level down to the
    # measure level whether or not any measures are encountered.
    #     Also assume any level with measures is well formed with all
    # measures contiguous, in order, starting at zero, and with durations
    # in compliance with time signatures.
    min_onset = float("inf")
    max_offset = float("-inf")
    if len(source.content) == 0:
        return min_onset, max_offset
    if isinstance(source.content[0], Measure):
        # find and copy the measures that are in the range
        start = round(start)
        end = round(end)
        for i, elem in enumerate(source.content):
            assert isinstance(elem, Measure), \
                   "expected Measures at this level"
            if i >= start and i < end:
                min_onset = min(min_onset, elem.onset)
                max_offset = max(max_offset, elem.offset)
                _ = elem.insert_copy_into(self)  # copy elem into self
        # if copied content has tied notes, the links will still refer
        # to the original notes, so we need to update the ties to
        # refer to the copied notes in self. If a tied-to note is outside
        # the copied content, we set the copied note's tie to None to
        # truncate the note.
        for note in self.find_all(Note):
            if note.tie is not None: # note is copied, but it still
                # references the original note. So pass original note
                # to find_copied_version and update note.tie. There is
                # a (theoretical?) possibility of two identical and tied 
                # grace notes with the same pitch and (zero) duration,
                # so we exclude note from the search for the copied
                # note to avoid creating a tie from note to itself.
                note.tie = self._find_copied_version(note.tie, note)
        return min_onset, max_offset
    # we are not at the measure level, copy all content and recurse:
    for elem in source.content:
        if isinstance(elem, EventGroup):
            elem_copy = elem.insert_emptycopy_into(self)
            elem_copy.onset = max(elem_copy.onset, start_time)
            elem_copy.offset = min(elem_copy.offset, end_time)
            e_min, e_max = elem_copy._add_measure_children(elem, start,
                                             end, start_time, end_time)
            min_onset = min(min_onset, e_min)
            max_offset = max(max_offset, e_max)
    return min_onset, max_offset

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
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
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
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
2305
2306
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
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 = self._add_slice_children(self, result,
                                              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

_truncate_note_beginnings

_truncate_note_beginnings(notes: list[Note], start: float) -> float

Helper method for slice to truncate an element according to the specified mode. Makes a copy of the element (with no parent) and applies the truncate method to the copy. This algorithm clips the beginning and ending in separate operations, which might result in extra copies. If very short tied notes are created, they are removed.

Returns:

  • float

    The minimum onset of the elements

Source code in amads/core/basics.py
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
def _truncate_note_beginnings(self, notes: list[Note],
                              start: float) -> float:
    """Helper method for slice to truncate an element according to the
    specified mode. Makes a copy of the element (with no parent) and
    applies the truncate method to the copy.  This algorithm clips the
    beginning and ending in separate operations, which might result in
    extra copies. If very short tied notes are created, they are removed.

    Returns
    -------
    float
        The minimum onset of the elements
    """
    min_onset = float("inf")
    for elem in notes:
        if elem.onset < start:
            elem.duration -= start - elem.onset
            elem.onset = start
        min_onset = min(min_onset, elem.onset)
    return min_onset

_is_well_formed

_is_well_formed() -> bool

Test if Measure conforms to strict hierarchy of: Measure-(Note or Rest or Chord) and Chord-Note

Returns:

  • bool

    True if the Measure conforms to normal hierarchy.

Source code in amads/core/basics.py
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
def _is_well_formed(self) -> bool:
    """Test if Measure conforms to strict hierarchy of:
    Measure-(Note or Rest or Chord) and Chord-Note

    Returns
    -------
    bool
        True if the Measure conforms to normal hierarchy.
    """
    for item in self.content:
        # Measure can (in theory) contain many object types, so we can
        # only rule out things that are outside of the strict hierarchy:
        if isinstance(item, (Score, Part, Staff, Measure)):
            return False
        if isinstance(item, Chord) and not item._is_well_formed():
            return False
    return True

time_signature

time_signature() -> TimeSignature

Retrieve the time signature that applies to this measure.

Returns:

  • TimeSignature

    The time signature from the score corresponding to the time of this measure.

Raises:

  • ValueError

    If there is no Score or no onset time.

Source code in amads/core/basics.py
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
def time_signature(self) -> TimeSignature:
    """Retrieve the time signature that applies to this measure.

    Returns
    -------
    TimeSignature
        The time signature from the score corresponding to the
        time of this measure.

    Raises
    ------
    ValueError
        If there is no Score or no onset time.
    """
    score = self.score
    if score is None:
        raise ValueError("Measure has no Score")
    else:  # find time sig at onset + a little to avoid rounding error:
        q = self.onset
        if self.score.units_are_seconds:
            q = self.score.time_map.seconds_to_quarters(self.onset)
        # use a small offset in case there is a time signature change
        # near the measure boundary, but a little bit late due to rounding:
        return score._find_time_signature(q + 0.002)

Staff

Staff(
    *args: Event,
    parent: Optional[EventGroup] = None,
    onset: Optional[float] = 0,
    duration: Optional[float] = None,
    number: Optional[int] = None
)

Bases: Sequence

A Staff models a musical staff.

This can also model one channel of a standard MIDI file track. A Staff normally contains Measure objects and is an element of a Part.

See Constructor Details.

Parameters:

  • *args (Optional[Event], default: () ) –

    A variable number of Event objects to be added to the group.

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

    The containing object or None.

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

    The onset (start) time. If unknown (None), it will be set when this Staff 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.

  • number (Optional[int], default: None ) –

    The staff number. Normally, a Staff is given an integer number where 1 is the top staff of the part, 2 is the 2nd, etc. Must be passed as a keyword parameter due to *args.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (float) –

    The onset (start) time.

  • duration (float) –

    The duration in quarters or seconds.

  • content (list[Event]) –

    Elements contained within this collection.

  • number (Optional[int]) –

    The staff number. Normally a Staff is given an integer number where 1 is the top staff of the part, 2 is the 2nd, etc.

Source code in amads/core/basics.py
4086
4087
4088
4089
4090
4091
4092
def __init__(self, *args: Event,
             parent: Optional[EventGroup] = None,
             onset: Optional[float] = 0,
             duration: Optional[float] = None,
             number: Optional[int] = None):
    super().__init__(parent, onset, duration, list(args))
    self.number = number

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.

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.

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

__repr__

__repr__() -> str

All Event subclasses inherit this to use str().

Thus, a list of Events is printed using their str methods

Source code in amads/core/basics.py
120
121
122
123
124
125
def __repr__(self) -> str:
    """All Event subclasses inherit this to use str().

    Thus, a list of Events is printed using their __str__ methods
    """
    return str(self)

_event_times

_event_times(dur: bool = True) -> str

produce onset and duration string for str

Source code in amads/core/basics.py
135
136
137
138
139
140
141
def _event_times(self, dur: bool = True) -> str:
    """produce onset and duration string for __str__
    """
    duration = self.duration
    if duration is not None:
        duration = f"{self.duration:0.3f}"
    return f"{self._event_onset()}, duration={duration}"

time_shift

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

Change the onset by an increment, affecting all content.

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.

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
def time_shift(self, increment: float,
               content_only: bool = False) -> "EventGroup":
    """
    Change the onset by an increment, affecting all content.

    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`.
    """
    if not content_only:
        self._onset += increment  # type: ignore (onset is now number)
    for elem in self.content:
        elem.time_shift(increment)
    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
243
244
245
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
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

_quantize

_quantize(divisions: int) -> EventGroup

"Since _quantize is called recursively on children, this method is needed to redirect EventGroup._quantize to quantize

Source code in amads/core/basics.py
2025
2026
2027
2028
2029
def _quantize(self, divisions: int) -> "EventGroup":
    """"Since `_quantize` is called recursively on children, this method is
    needed to redirect `EventGroup._quantize` to `quantize`
    """
    return self.quantize(divisions)

_convert_to_seconds

_convert_to_seconds(time_map: TimeMap) -> None

Convert the event's duration and onset to seconds using the provided TimeMap. Convert content as well.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
def _convert_to_seconds(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to seconds using the
    provided TimeMap. Convert content as well.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    super()._convert_to_seconds(time_map)
    for elem in self.content:
        elem._convert_to_seconds(time_map)

_convert_to_quarters

_convert_to_quarters(time_map: TimeMap) -> None

Convert the event's duration and onset to quarters using the provided TimeMap. Convert content as well.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
def _convert_to_quarters(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to quarters using the
    provided TimeMap. Convert content as well.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    onset_quarters = time_map.time_to_quarter(self.onset)
    offset_quarters = time_map.time_to_quarter(self.onset + self.duration)
    self.onset = onset_quarters
    self.duration = offset_quarters - onset_quarters
    for elem in self.content:
        elem._convert_to_quarters(time_map)

_find_copied_version

_find_copied_version(
    original_note: Note, exclude: Note
) -> Optional[Note]

Find the copied version of a note in self.

Parameters:

  • original_note (Note) –

    The note that was copied

Source code in amads/core/basics.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
def _find_copied_version(self, original_note: Note,
                         exclude: Note) -> Optional[Note]:
    """Find the copied version of a note in self.

    Parameters
    ----------
    original_note: Note
        The note that was copied
    """
    for note in self.find_all(Note):
        note = cast(Note, note)
        if (note != exclude and note.onset == original_note.onset and
            note.pitch == original_note.pitch and
            note.duration == original_note.duration):
            return note
    return None

_add_slice_children

_add_slice_children(
    source: EventGroup,
    start: float,
    end: float,
    mode: str,
    truncate: str,
    min_duration: float,
) -> tuple[float, float]

Helper method for slice to populate the content of self. Assumes that source is a component of a flat score and that self is a Sequence with no content.

Returns:

  • float

    The minimum onset of the content added to self.

Source code in amads/core/basics.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
def _add_slice_children(self, source: "EventGroup", start: float,
        end: float, mode: str, truncate: str,
        min_duration: float) -> tuple[float, float]:
    """Helper method for slice to populate the content of self.
    Assumes that source is a component of a flat score and that self
    is a Sequence with no content.

    Returns
    -------
    float
        The minimum onset of the content added to self.
    """
    # Begin by finding all content to be included. Since score is flat,
    # source can only be a Score, a Part, or a Staff. So if a component is
    # not a Note, we copy all children (Parts or Staffs) into content
    # and recurse to add a slice of *their* content.
    min_onset = float("inf")
    max_offset = float("-inf")
    content = source.content
    if len(content) == 0:
        return min_onset, max_offset
    if not isinstance(content[0], Note):
        for elem in content:
            if isinstance(elem, EventGroup):
                elem_copy = elem.insert_emptycopy_into(self)
                e_min, e_max = elem._add_slice_children(elem_copy, start,
                                       end, mode, truncate, min_duration)
                min_onset = min(min_onset, e_min)
                max_offset = max(max_offset, e_max)
        return min_onset, max_offset

    assert(isinstance(source, Sequence))  # content is a list of Notes

    for elem in content:
        copied = None
        if mode == "onsets":
            if elem.onset >= start and elem.onset < end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "overlaps":
            if elem.onset < end and elem.offset > start:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "offsets":
            if elem.offset > start and elem.offset <= end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "strict":
            if elem.onset >= start and elem.offset <= end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        else:
            raise ValueError(f"invalid mode {mode} for slice")
        if copied:
            min_onset = min(min_onset, copied.onset)
            max_offset = max(max_offset, copied.offset)

    if truncate == "keep":
        return min_onset, max_offset
    if truncate in ["truncate", "beginning"]:
        # if we are truncating notes that start before start, we can save
        # some time by only looking at elements where onset < start
        j = len(content)
        for i, elem in enumerate(content):
            if elem.onset > start:
                j = i
                break  # now j indexes the first element with onset > start
        min_onset = source._truncate_note_beginnings(content[0 : j], start)
    if truncate in ["truncate", "dur", "duration", "end", "ending"]:
        # any note can end after end, so we have to look at all of them:
        max_offset = source._truncate_note_endings(content, end)

    # now remove any notes that are too short after truncation:
    if min_duration > 0:
        min_onset = float("inf")
        max_offset = float("-inf")
        filtered = []
        for elem in content:
            if elem.duration >= min_duration:
                filtered.append(elem)
                min_onset = min(min_onset, elem.onset)
                max_offset = max(max_offset, elem.offset)
        source.content = filtered
    return min_onset, max_offset

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

_copy_parents

_copy_parents(start: float, end: float) -> EventGroup

Helper method for slice to populate the ancestors of self in result.

This method is called by slice to populate the ancestors of self in the result Score. The ancestors are populated with empty copies of the original ancestors.

Returns:

  • EventGroup

    A copy of self with ancestors copied up to the Score.

Raises:

  • ValueError

    If self is not part of a Score.

Source code in amads/core/basics.py
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
def _copy_parents(self, start: float, end: float) -> "EventGroup":
    """Helper method for slice to populate the ancestors of self in result.

    This method is called by `slice` to populate the ancestors of self in
    the result Score. The ancestors are populated with empty copies of the
    original ancestors.

    Returns
    -------
    EventGroup
        A copy of self with ancestors copied up to the Score.

    Raises
    ------
    ValueError
        If self is not part of a Score.
    """
    # Algorithm: recursively populate ancestors from self up to score.
    if self is None:
        raise ValueError("slice can only be called on Sequences that are "
                         "part of a Score")
    elif isinstance(self, Score):  # base case: self is a Score
        return self # return copy of self
    else:  # copy parent & up; return copy of self inserted into parent copy
        parent = cast(EventGroup, self.parent)._copy_parents(start, end)
        parent.onset = start
        parent.offset = end
        # insert copy of self into parent copy:
        return self.insert_emptycopy_into(parent)

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
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
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
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
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)

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
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
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_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
1778
1779
1780
1781
1782
1783
1784
1785
1786
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
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
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
1804
1805
1806
1807
1808
1809
1810
1811
1812
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
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
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)

Source code in amads/core/basics.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
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)
    """
    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
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
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

_leaf_elements

_leaf_elements() -> list[Event]

Return a list of all leaf elements in this EventGroup.

Source code in amads/core/basics.py
1893
1894
1895
1896
1897
1898
1899
1900
1901
def _leaf_elements(self) -> list[Event]:
    """Return a list of all leaf elements in this EventGroup."""
    result = []
    for elem in self.content:
        if isinstance(elem, EventGroup):
            result.extend(elem._leaf_elements())
        else:
            result.append(elem)
    return result

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
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
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
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 = 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
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
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)

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
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
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
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

_add_measure_children

_add_measure_children(
    source: EventGroup,
    start: float,
    end: float,
    start_time: float,
    end_time: float,
) -> tuple[float, float]

Helper method for to populate the content with selected measures. Assumes that self is a component of a full score and that this Staff (self) has no content yet.

Since only measures within start and end are copied, the copied measures and other content all have onsets and offsets within copy range and do not need to be adjusted.

Assumes that notes crossing measure boundaries are tied and that ties to notes outside the copied measures should be broken, truncating the copied note to the measure boundary.

Returns:

  • tuple[float, float]

    The minimum onset and maximum offset of the content added to self.

Source code in amads/core/basics.py
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
def _add_measure_children(self, source: "EventGroup", start: float,
                          end: float, start_time: float,
                          end_time: float) -> tuple[float, float]:
    """Helper method for to populate the content with
    selected measures. Assumes that self is a component of a full score and
    that this Staff (self) has no content yet.

    Since only measures within start and end are copied, the copied
    measures and other content all have onsets and offsets within
    copy range and do not need to be adjusted.

    Assumes that notes crossing measure boundaries are tied and that
    ties to notes outside the copied measures should be broken, truncating
    the copied note to the measure boundary.

    Returns
    -------
    tuple[float, float]
        The minimum onset and maximum offset of the content added to self.
    """
    # Assume that whatever EventGroup(s) contain measures, they will *only*
    # contain measures, so we can check content[0] to find the measure
    # level. Recursively copy the structure from this level down to the
    # measure level whether or not any measures are encountered.
    #     Also assume any level with measures is well formed with all
    # measures contiguous, in order, starting at zero, and with durations
    # in compliance with time signatures.
    min_onset = float("inf")
    max_offset = float("-inf")
    if len(source.content) == 0:
        return min_onset, max_offset
    if isinstance(source.content[0], Measure):
        # find and copy the measures that are in the range
        start = round(start)
        end = round(end)
        for i, elem in enumerate(source.content):
            assert isinstance(elem, Measure), \
                   "expected Measures at this level"
            if i >= start and i < end:
                min_onset = min(min_onset, elem.onset)
                max_offset = max(max_offset, elem.offset)
                _ = elem.insert_copy_into(self)  # copy elem into self
        # if copied content has tied notes, the links will still refer
        # to the original notes, so we need to update the ties to
        # refer to the copied notes in self. If a tied-to note is outside
        # the copied content, we set the copied note's tie to None to
        # truncate the note.
        for note in self.find_all(Note):
            if note.tie is not None: # note is copied, but it still
                # references the original note. So pass original note
                # to find_copied_version and update note.tie. There is
                # a (theoretical?) possibility of two identical and tied 
                # grace notes with the same pitch and (zero) duration,
                # so we exclude note from the search for the copied
                # note to avoid creating a tie from note to itself.
                note.tie = self._find_copied_version(note.tie, note)
        return min_onset, max_offset
    # we are not at the measure level, copy all content and recurse:
    for elem in source.content:
        if isinstance(elem, EventGroup):
            elem_copy = elem.insert_emptycopy_into(self)
            elem_copy.onset = max(elem_copy.onset, start_time)
            elem_copy.offset = min(elem_copy.offset, end_time)
            e_min, e_max = elem_copy._add_measure_children(elem, start,
                                             end, start_time, end_time)
            min_onset = min(min_onset, e_min)
            max_offset = max(max_offset, e_max)
    return min_onset, max_offset

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
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
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
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
2305
2306
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
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 = self._add_slice_children(self, result,
                                              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

_truncate_note_beginnings

_truncate_note_beginnings(notes: list[Note], start: float) -> float

Helper method for slice to truncate an element according to the specified mode. Makes a copy of the element (with no parent) and applies the truncate method to the copy. This algorithm clips the beginning and ending in separate operations, which might result in extra copies. If very short tied notes are created, they are removed.

Returns:

  • float

    The minimum onset of the elements

Source code in amads/core/basics.py
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
def _truncate_note_beginnings(self, notes: list[Note],
                              start: float) -> float:
    """Helper method for slice to truncate an element according to the
    specified mode. Makes a copy of the element (with no parent) and
    applies the truncate method to the copy.  This algorithm clips the
    beginning and ending in separate operations, which might result in
    extra copies. If very short tied notes are created, they are removed.

    Returns
    -------
    float
        The minimum onset of the elements
    """
    min_onset = float("inf")
    for elem in notes:
        if elem.onset < start:
            elem.duration -= start - elem.onset
            elem.onset = start
        min_onset = min(min_onset, elem.onset)
    return min_onset

_is_well_formed

_is_well_formed()

Test if Staff is well-formed, conforming to a strict hierarchy of: Staff-Measure-(Note or Rest or Chord) and Chord-Note)

Source code in amads/core/basics.py
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
def _is_well_formed(self):
    """Test if Staff is well-formed, conforming to a strict hierarchy of:
    Staff-Measure-(Note or Rest or Chord) and Chord-Note)
    """
    for measure in self.content:
        # Staff can (in theory) contain many objects such as key signature
        # or time signature. We only rule out types that are
        # outside-of-hierarchy:
        if isinstance(measure, (Score, Part, Staff, Note, Rest, Chord)):
            return False
        if isinstance(measure, Measure) and not measure._is_well_formed():
            return False
    return True

remove_measures

remove_measures() -> Staff

Modify Staff by removing all Measures.

Notes are “lifted” from Measures to become direct content of this Staff. There is no special handling for notes tied to or from another Staff, so normally this method should be used only on a Staff where ties have been merged (see merge_tied_notes()). This method is normally called from remove_measures() in Part, which insures that this Staff is not shared, so it is safe to modify it. If called directly, the caller, to avoid unintended side effects, must ensure that this Staff is not shared data. Only Note and KeySignature objects are copied from Measures to the Staff. All other objects are removed.

Returns:

  • Staff

    A Staff with all Measures removed.

Source code in amads/core/basics.py
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
def remove_measures(self) -> "Staff":
    """Modify Staff by removing all Measures.

    Notes are “lifted” from Measures to become direct content of this
    Staff. There is no special handling for notes tied to or from another
    Staff, so normally this method should be used only on a Staff where
    ties have been merged (see `merge_tied_notes()`).
    This method is normally called from `remove_measures()` in Part,
    which insures that this Staff is not shared, so it is safe to
    modify it. If called directly, the caller, to avoid unintended
    side effects, must ensure that this Staff is not shared data.
    Only Note and KeySignature objects are copied from Measures
    to the Staff. All other objects are removed.

    Returns
    -------
    Staff
        A Staff with all Measures removed.
    """
    new_content = []
    for measure in self.content:
        if isinstance(measure, Measure):
            for event in measure.content:
                if isinstance(event, (Note, KeySignature)):
                    new_content.append(event)
                # else ignore the event
        else:  # non-Measure objects are simply copied
            new_content.append(measure)
    self.content = new_content
    return self

Part

Part(
    *args: Event,
    parent: Optional[Score] = None,
    onset: float = 0.0,
    duration: Optional[float] = None,
    number: Optional[str] = None,
    instrument: Optional[str] = None,
    flat: bool = False
)

Bases: EventGroup

A Part models a staff or staff group such as a grand staff.

For that reason, a Part contains one or more Staff objects. It should not contain any other object types. Parts are normally elements of a Score. Note that in a flat score, a Part is a collection of Notes, not Staffs, and it should be organized more sequentially than concurrently, so the default assignment of onset times may not be appropriate.

See Constructor Details.

Part is an EventGroup rather than a Sequence or Concurrence because in flat scores, it acts like a Sequence of notes, but in full scores, it is like a Concurrence of Staff objects.

Parameters:

  • *args (Optional[Event], default: () ) –

    A variable number of Event objects to be added to the group. parent : Optional[EventGroup] The containing object or None. Must be passed as a keyword parameter due to *args.

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

    The onset (start) time. If unknown (None), it will be set when this Part 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.

  • number (Optional[str], default: None ) –

    A string representing the part number.

  • instrument (Optional[str], default: None ) –

    A string representing the instrument name.

  • flat (bool, default: False ) –

    If true, content in *args with onset None are modified to start at the offset of the previous note (or at onset if this is the first Event in *args, or at 0.0 if onset is unspecified). Otherwise, this is assumed to be a Part in a full score, *args is assumed to contain Staffs, and their default onset times are given onset by onset (or 0.0 if onset is unspecified). This must be passed as a keyword argument due to *args.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (float) –

    The onset (start) time.

  • duration (float) –

    The duration in quarters or seconds.

  • content (list[Event]) –

    Elements contained within this collection.

  • number (Union[str, None]) –

    A string representing the part number (if any). E.g., "22a".

  • instrument (Union[str, None]) –

    A string representing the instrument name (if any).

Notes
Standard MIDI File tracks often have text instrument names in
type 4 meta events. These are stored in the `instrument` attribute.
Tracks often contain events for a single MIDI channel and a single
“program” that is another representation of “instrument.” In fact,
the `pretty_midi` library considers MIDI program to be a property
of the track rather than a timed event within the track (many
sequencers use this model as well). Therefore, if there is a
single MIDI program in a track (or an AMADS Part), the program
number (int) is stored in `info` using the key `"midi_program"`.
Source code in amads/core/basics.py
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
def __init__(self, *args: Event,
             parent: Optional[Score] = None,
             onset: float = 0.0,
             duration: Optional[float] = None,
             number: Optional[str] = None,
             instrument: Optional[str] = None,
             flat: bool = False):
    content = list(args)
    if flat:  # adjust onsets to form a sequence (must be done before
        prev_onset : float = 0.0  # onset of previous note
        prev_offset : float = 0.0  # offset of previous note
        if not onset is None:
            prev_onset = onset
            prev_offset = onset
        for elem in content:
            if elem.parent and elem.parent != self:
                raise ValueError("Event already has a parent")
            elem.parent = self  # type: ignore
            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
        packed_args = []
    super().__init__(parent, onset, duration, content)
    self.number = number
    self.instrument = instrument

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.

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.

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

__repr__

__repr__() -> str

All Event subclasses inherit this to use str().

Thus, a list of Events is printed using their str methods

Source code in amads/core/basics.py
120
121
122
123
124
125
def __repr__(self) -> str:
    """All Event subclasses inherit this to use str().

    Thus, a list of Events is printed using their __str__ methods
    """
    return str(self)

_event_times

_event_times(dur: bool = True) -> str

produce onset and duration string for str

Source code in amads/core/basics.py
135
136
137
138
139
140
141
def _event_times(self, dur: bool = True) -> str:
    """produce onset and duration string for __str__
    """
    duration = self.duration
    if duration is not None:
        duration = f"{self.duration:0.3f}"
    return f"{self._event_onset()}, duration={duration}"

time_shift

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

Change the onset by an increment, affecting all content.

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.

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
def time_shift(self, increment: float,
               content_only: bool = False) -> "EventGroup":
    """
    Change the onset by an increment, affecting all content.

    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`.
    """
    if not content_only:
        self._onset += increment  # type: ignore (onset is now number)
    for elem in self.content:
        elem.time_shift(increment)
    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
243
244
245
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
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

_quantize

_quantize(divisions: int) -> EventGroup

"Since _quantize is called recursively on children, this method is needed to redirect EventGroup._quantize to quantize

Source code in amads/core/basics.py
2025
2026
2027
2028
2029
def _quantize(self, divisions: int) -> "EventGroup":
    """"Since `_quantize` is called recursively on children, this method is
    needed to redirect `EventGroup._quantize` to `quantize`
    """
    return self.quantize(divisions)

_convert_to_seconds

_convert_to_seconds(time_map: TimeMap) -> None

Convert the event's duration and onset to seconds using the provided TimeMap. Convert content as well.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
def _convert_to_seconds(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to seconds using the
    provided TimeMap. Convert content as well.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    super()._convert_to_seconds(time_map)
    for elem in self.content:
        elem._convert_to_seconds(time_map)

_convert_to_quarters

_convert_to_quarters(time_map: TimeMap) -> None

Convert the event's duration and onset to quarters using the provided TimeMap. Convert content as well.

Parameters:

  • time_map (TimeMap) –

    The TimeMap object used for conversion.

Source code in amads/core/basics.py
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
def _convert_to_quarters(self, time_map: TimeMap) -> None:
    """Convert the event's duration and onset to quarters using the
    provided TimeMap. Convert content as well.

    Parameters
    ----------
    time_map : TimeMap
        The TimeMap object used for conversion.
    """
    onset_quarters = time_map.time_to_quarter(self.onset)
    offset_quarters = time_map.time_to_quarter(self.onset + self.duration)
    self.onset = onset_quarters
    self.duration = offset_quarters - onset_quarters
    for elem in self.content:
        elem._convert_to_quarters(time_map)

_find_copied_version

_find_copied_version(
    original_note: Note, exclude: Note
) -> Optional[Note]

Find the copied version of a note in self.

Parameters:

  • original_note (Note) –

    The note that was copied

Source code in amads/core/basics.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
def _find_copied_version(self, original_note: Note,
                         exclude: Note) -> Optional[Note]:
    """Find the copied version of a note in self.

    Parameters
    ----------
    original_note: Note
        The note that was copied
    """
    for note in self.find_all(Note):
        note = cast(Note, note)
        if (note != exclude and note.onset == original_note.onset and
            note.pitch == original_note.pitch and
            note.duration == original_note.duration):
            return note
    return None

_add_slice_children

_add_slice_children(
    source: EventGroup,
    start: float,
    end: float,
    mode: str,
    truncate: str,
    min_duration: float,
) -> tuple[float, float]

Helper method for slice to populate the content of self. Assumes that source is a component of a flat score and that self is a Sequence with no content.

Returns:

  • float

    The minimum onset of the content added to self.

Source code in amads/core/basics.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
def _add_slice_children(self, source: "EventGroup", start: float,
        end: float, mode: str, truncate: str,
        min_duration: float) -> tuple[float, float]:
    """Helper method for slice to populate the content of self.
    Assumes that source is a component of a flat score and that self
    is a Sequence with no content.

    Returns
    -------
    float
        The minimum onset of the content added to self.
    """
    # Begin by finding all content to be included. Since score is flat,
    # source can only be a Score, a Part, or a Staff. So if a component is
    # not a Note, we copy all children (Parts or Staffs) into content
    # and recurse to add a slice of *their* content.
    min_onset = float("inf")
    max_offset = float("-inf")
    content = source.content
    if len(content) == 0:
        return min_onset, max_offset
    if not isinstance(content[0], Note):
        for elem in content:
            if isinstance(elem, EventGroup):
                elem_copy = elem.insert_emptycopy_into(self)
                e_min, e_max = elem._add_slice_children(elem_copy, start,
                                       end, mode, truncate, min_duration)
                min_onset = min(min_onset, e_min)
                max_offset = max(max_offset, e_max)
        return min_onset, max_offset

    assert(isinstance(source, Sequence))  # content is a list of Notes

    for elem in content:
        copied = None
        if mode == "onsets":
            if elem.onset >= start and elem.onset < end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "overlaps":
            if elem.onset < end and elem.offset > start:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "offsets":
            if elem.offset > start and elem.offset <= end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        elif mode == "strict":
            if elem.onset >= start and elem.offset <= end:
                copied = elem.insert_copy_into(self)  # copy elem into self
        else:
            raise ValueError(f"invalid mode {mode} for slice")
        if copied:
            min_onset = min(min_onset, copied.onset)
            max_offset = max(max_offset, copied.offset)

    if truncate == "keep":
        return min_onset, max_offset
    if truncate in ["truncate", "beginning"]:
        # if we are truncating notes that start before start, we can save
        # some time by only looking at elements where onset < start
        j = len(content)
        for i, elem in enumerate(content):
            if elem.onset > start:
                j = i
                break  # now j indexes the first element with onset > start
        min_onset = source._truncate_note_beginnings(content[0 : j], start)
    if truncate in ["truncate", "dur", "duration", "end", "ending"]:
        # any note can end after end, so we have to look at all of them:
        max_offset = source._truncate_note_endings(content, end)

    # now remove any notes that are too short after truncation:
    if min_duration > 0:
        min_onset = float("inf")
        max_offset = float("-inf")
        filtered = []
        for elem in content:
            if elem.duration >= min_duration:
                filtered.append(elem)
                min_onset = min(min_onset, elem.onset)
                max_offset = max(max_offset, elem.offset)
        source.content = filtered
    return min_onset, max_offset

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

_copy_parents

_copy_parents(start: float, end: float) -> EventGroup

Helper method for slice to populate the ancestors of self in result.

This method is called by slice to populate the ancestors of self in the result Score. The ancestors are populated with empty copies of the original ancestors.

Returns:

  • EventGroup

    A copy of self with ancestors copied up to the Score.

Raises:

  • ValueError

    If self is not part of a Score.

Source code in amads/core/basics.py
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
def _copy_parents(self, start: float, end: float) -> "EventGroup":
    """Helper method for slice to populate the ancestors of self in result.

    This method is called by `slice` to populate the ancestors of self in
    the result Score. The ancestors are populated with empty copies of the
    original ancestors.

    Returns
    -------
    EventGroup
        A copy of self with ancestors copied up to the Score.

    Raises
    ------
    ValueError
        If self is not part of a Score.
    """
    # Algorithm: recursively populate ancestors from self up to score.
    if self is None:
        raise ValueError("slice can only be called on Sequences that are "
                         "part of a Score")
    elif isinstance(self, Score):  # base case: self is a Score
        return self # return copy of self
    else:  # copy parent & up; return copy of self inserted into parent copy
        parent = cast(EventGroup, self.parent)._copy_parents(start, end)
        parent.onset = start
        parent.offset = end
        # insert copy of self into parent copy:
        return self.insert_emptycopy_into(parent)

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
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
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
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
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)

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
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
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_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
1778
1779
1780
1781
1782
1783
1784
1785
1786
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
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
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
1804
1805
1806
1807
1808
1809
1810
1811
1812
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
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
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)

Source code in amads/core/basics.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
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)
    """
    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
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
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

_leaf_elements

_leaf_elements() -> list[Event]

Return a list of all leaf elements in this EventGroup.

Source code in amads/core/basics.py
1893
1894
1895
1896
1897
1898
1899
1900
1901
def _leaf_elements(self) -> list[Event]:
    """Return a list of all leaf elements in this EventGroup."""
    result = []
    for elem in self.content:
        if isinstance(elem, EventGroup):
            result.extend(elem._leaf_elements())
        else:
            result.append(elem)
    return result

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
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
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
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
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
2019
2020
2021
2022
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
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
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
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

_add_measure_children

_add_measure_children(
    source: EventGroup,
    start: float,
    end: float,
    start_time: float,
    end_time: float,
) -> tuple[float, float]

Helper method for to populate the content with selected measures. Assumes that self is a component of a full score and that this Staff (self) has no content yet.

Since only measures within start and end are copied, the copied measures and other content all have onsets and offsets within copy range and do not need to be adjusted.

Assumes that notes crossing measure boundaries are tied and that ties to notes outside the copied measures should be broken, truncating the copied note to the measure boundary.

Returns:

  • tuple[float, float]

    The minimum onset and maximum offset of the content added to self.

Source code in amads/core/basics.py
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
def _add_measure_children(self, source: "EventGroup", start: float,
                          end: float, start_time: float,
                          end_time: float) -> tuple[float, float]:
    """Helper method for to populate the content with
    selected measures. Assumes that self is a component of a full score and
    that this Staff (self) has no content yet.

    Since only measures within start and end are copied, the copied
    measures and other content all have onsets and offsets within
    copy range and do not need to be adjusted.

    Assumes that notes crossing measure boundaries are tied and that
    ties to notes outside the copied measures should be broken, truncating
    the copied note to the measure boundary.

    Returns
    -------
    tuple[float, float]
        The minimum onset and maximum offset of the content added to self.
    """
    # Assume that whatever EventGroup(s) contain measures, they will *only*
    # contain measures, so we can check content[0] to find the measure
    # level. Recursively copy the structure from this level down to the
    # measure level whether or not any measures are encountered.
    #     Also assume any level with measures is well formed with all
    # measures contiguous, in order, starting at zero, and with durations
    # in compliance with time signatures.
    min_onset = float("inf")
    max_offset = float("-inf")
    if len(source.content) == 0:
        return min_onset, max_offset
    if isinstance(source.content[0], Measure):
        # find and copy the measures that are in the range
        start = round(start)
        end = round(end)
        for i, elem in enumerate(source.content):
            assert isinstance(elem, Measure), \
                   "expected Measures at this level"
            if i >= start and i < end:
                min_onset = min(min_onset, elem.onset)
                max_offset = max(max_offset, elem.offset)
                _ = elem.insert_copy_into(self)  # copy elem into self
        # if copied content has tied notes, the links will still refer
        # to the original notes, so we need to update the ties to
        # refer to the copied notes in self. If a tied-to note is outside
        # the copied content, we set the copied note's tie to None to
        # truncate the note.
        for note in self.find_all(Note):
            if note.tie is not None: # note is copied, but it still
                # references the original note. So pass original note
                # to find_copied_version and update note.tie. There is
                # a (theoretical?) possibility of two identical and tied 
                # grace notes with the same pitch and (zero) duration,
                # so we exclude note from the search for the copied
                # note to avoid creating a tie from note to itself.
                note.tie = self._find_copied_version(note.tie, note)
        return min_onset, max_offset
    # we are not at the measure level, copy all content and recurse:
    for elem in source.content:
        if isinstance(elem, EventGroup):
            elem_copy = elem.insert_emptycopy_into(self)
            elem_copy.onset = max(elem_copy.onset, start_time)
            elem_copy.offset = min(elem_copy.offset, end_time)
            e_min, e_max = elem_copy._add_measure_children(elem, start,
                                             end, start_time, end_time)
            min_onset = min(min_onset, e_min)
            max_offset = max(max_offset, e_max)
    return min_onset, max_offset

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
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
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
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
2305
2306
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
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 = self._add_slice_children(self, result,
                                              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

is_well_formed_full_part

is_well_formed_full_part()

Test if Part is measured and well-formed.

Part must conform to a strict hierarchy of: Part-Staff-Measure-(Note or Rest or Chord) and Chord-Note.

Source code in amads/core/basics.py
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
def is_well_formed_full_part(self):
    """Test if Part is measured and well-formed.

    Part must conform to a strict hierarchy of:
    Part-Staff-Measure-(Note or Rest or Chord) and Chord-Note.
    """
    for staff in self.content:  # type: ignore (Part contains Staffs)
        staff : Staff
        # only Staffs are expected, but things outside of the hierarchy
        # are allowed, so we only rule out violations of the hierarchy:
        if isinstance(staff, (Score, Part, Measure, Note, Rest, Chord)):
            return False
        if isinstance(staff, Staff) and not staff._is_well_formed():
            return False
    return True

flatten

flatten(in_place=False)

Build a flat Part where content will consist of notes only.

Parameters:

  • in_place (bool, default: False ) –

    If in_place=True, assume Part already has no ties and can be modified. Otherwise, return a new Part where deep copies of tied notes are merged.

Returns:

  • Part

    a new part that has been flattened

Source code in amads/core/basics.py
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
def flatten(self, in_place=False):
    """Build a flat Part where content will consist of notes only.

    Parameters
    ----------
    in_place : bool
        If in_place=True, assume Part already has no ties and can be
        modified. Otherwise, return a new Part where deep copies of
        tied notes are merged.

    Returns
    -------
    Part
        a new part that has been flattened
    """
    part = self if in_place else self.merge_tied_notes()
    notes : List[Note] \
          = part.list_all(Note)  # type: ignore (Notes < Events)
    for note in notes:
        note.parent = part
    notes.sort(key=lambda x: (x.onset, x.pitch))
    part.content = notes  # type: ignore (List[Note] < List[Event])
    return part

is_flat

is_flat()

Test if Part is flat (contains only notes without ties).

Returns:

  • bool

    True iff the Part is flat

Source code in amads/core/basics.py
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
def is_flat(self):
    """Test if Part is flat (contains only notes without ties).

    Returns
    -------
    bool
        True iff the Part is flat
    """
    for note in self.content:
        # only Notes without ties are expected, but things outside of
        # the hierarchy are allowed, so we only rule out violations of
        # the hierarchy:
        if isinstance(note, (Score, Part, Staff, Measure, Rest, Chord)):
            return False
        if isinstance(note, Note) and note.tie is not None:
            return False
    return True

remove_measures

remove_measures(score: Optional[Score], has_ties: bool = True) -> Part

Return a Part with all Measures removed.

Preserves Staffs in the hierarchy. Notes are “lifted” from Measures to become direct content of their Staff. Uses merge_tied_notes() to copy this Part unless has_ties is False, in which case there must be no tied notes and this Part is modified. (Note: it is harmless for has_ties to be True even if there are no ties. This will simply copy the Part before removing measures.)

Parameters:

  • score (Union[Score, None]) –

    The Score instance (if any) to which the new Part will be added.

  • has_ties (bool, default: True ) –

    If False, assume this is a copy we are free to modify, there are tied notes, and this Part is already contained by score. If True, this Part will be copied into score.

Returns:

  • Part

    A Part with all Measures removed.

Source code in amads/core/basics.py
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
def remove_measures(self, score: Optional["Score"],
                    has_ties: bool = True) -> "Part":
    """Return a Part with all Measures removed.

    Preserves Staffs in the hierarchy. Notes are “lifted” from Measures
    to become direct content of their Staff. Uses `merge_tied_notes()`
    to copy this Part unless `has_ties` is False, in which case
    there must be no tied notes and this Part is modified. (Note: it is
    harmless for `has_ties` to be True even if there are no ties. This
    will simply copy the Part before removing measures.)

    Parameters
    ----------
    score : Union[Score, None]
        The Score instance (if any) to which the new Part will be added.
    has_ties : bool
        If False, assume this is a copy we are free to modify,
        there are tied notes, and this Part is already contained
        by `score`. If True, this Part will be copied into `score`.

    Returns
    -------
    Part
        A Part with all Measures removed.
    """
    part : Part = (self.merge_tied_notes(score) 
                   if has_ties else self)  # type: ignore
    for staff in part.content:
        if isinstance(staff, Staff):
            staff.remove_measures()
    return part

calc_differences

calc_differences(what: List[str]) -> List[Note]

Calculate inter-onset intervals (IOIs), IOI-ratios and intervals.

This method modifies the Part in place, calculating several differences between notes. Onset differences (IOIs) are the time differences between a Note's onset and the onset of the previous Note in the same Part (regardless of Staff). The IOI of the first Note in the Part is set to None. The IOI values are computed when what contains "ioi" or "ioi_ratio" and stored as "ioi" in the Note's info dictionary.

The IOI-ratio of a Note is the ratio of its IOI to the IOI of the previous Note. The IOI-ratios of the first two Notes are set to None. The IOI-ratio values are computed when what contains "ioi_ratio" and stored as "ioi_ratio" in the Note's info dictionary.

The pitch interval of a Note is the difference in semitones between its pitch and the pitch of the previous Note in the same Part. The interval of the first Note in the Part is set to None. The interval values are computed when what contains "interval" and stored as "interval" in the Note's info dictionary.

Note that this method assumes that the Part has no concurrent Notes (IOI == 0) and no ties. In either case, a ValueError is raised.

Parameters:

  • what (list of str) –

    A list of strings indicating what differences to compute. Valid strings are: 'ioi' (for inter-onset intervals), 'ioi_ratio' (for ratio of successive IOIs), and 'interval' (for pitch intervals in semitones).

Raises:

  • ValueError

    If there are tied notes or concurrent notes in the Part or if what does not contain any of "ioi", "ioi_ratio" or "interval".

Returns:

  • List[Note]

    The sorted list of Notes with calculated IOIs and IOI-ratios.

Source code in amads/core/basics.py
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
def calc_differences(self, what: List[str]) -> List[Note]:
    """Calculate inter-onset intervals (IOIs), IOI-ratios and intervals.

    This method modifies the Part in place, calculating several
    differences between notes. Onset differences (IOIs) are the
    time differences between a Note's onset and the onset of the
    previous Note in the same Part (regardless of Staff). The IOI
    of the first Note in the Part is set to None. The IOI values
    are computed when `what` contains "ioi" or "ioi_ratio" and
    stored as `"ioi"` in the Note's `info` dictionary.

    The IOI-ratio of a Note is the ratio of its IOI to the IOI of
    the previous Note. The IOI-ratios of the first two Notes are set
    to None. The IOI-ratio values are computed when `what` contains
    "ioi_ratio" and stored as `"ioi_ratio"` in the Note's `info`
    dictionary.

    The pitch interval of a Note is the difference in semitones between
    its pitch and the pitch of the previous Note in the same Part. The
    interval of the first Note in the Part is set to None. The interval
    values are computed when `what` contains "interval" and stored
    as `"interval"` in the Note's `info` dictionary.

    Note that this method assumes that the Part has no concurrent
    Notes (IOI == 0) and no ties. In either case, a ValueError is raised.

    Parameters
    ----------
    what : list of str
        A list of strings indicating what differences to compute.
        Valid strings are: 'ioi' (for inter-onset intervals),
        'ioi_ratio' (for ratio of successive IOIs), and
        'interval' (for pitch intervals in semitones).

    Raises
    ------
    ValueError
        If there are tied notes or concurrent notes in the Part or if
        `what` does not contain any of "ioi", "ioi_ratio" or "interval".

    Returns
    -------
    List[Note]
        The sorted list of Notes with calculated IOIs and IOI-ratios.
    """
    # this will raise an exception if there are ties:
    notes : List[Note] = self.get_sorted_notes(has_ties=False)
    do_ioi = "ioi" in what or "ioi_ratio" in what
    do_interval = "interval" in what
    do_ioi_ratio = "ioi_ratio" in what
    if not (do_ioi or do_interval or do_ioi_ratio):
        raise ValueError(
                "what must contain 'ioi', 'ioi_ratio' or 'interval'")
    if len(notes) == 0:
        return []  # nothing to do
    else:
        if do_ioi:
            notes[0].set("ioi", None)
        if do_ioi_ratio:
            notes[0].set("ioi_ratio", None)
        if do_interval:
            notes[0].set("interval", None)

    prev_ioi : Optional[float] = None
    prev_note : Note = notes[0]
    for note in notes[1 : ]:
        if do_ioi:
            ioi = note.onset - prev_note.onset
            if ioi <= 0:
                raise ValueError(
                        "Part is not monophonic; cannot compute IOIs")
            note.set("ioi", ioi)
        if do_ioi_ratio:
            if prev_ioi is None:
                note.set("ioi_ratio", None)
            else:  # ignore typing because ioi is bound earlier:
                note.set("ioi_ratio", ioi / prev_ioi)  # type: ignore
            prev_ioi = ioi  # type: ignore (ioi is bound if do_ioi) 
        if do_interval:
            note.set("interval", note.key_num - prev_note.key_num)
        prev_note = note
    return notes

Score

Score(
    *args: Event,
    onset: Optional[float] = 0,
    duration: Optional[float] = None,
    time_map: Optional[TimeMap] = None,
    time_signatures: Optional[List[TimeSignature]] = None
)

Bases: Concurrence

A Score (abstract class) represents a musical work.

Normally, a Score contains Part objects, all with onsets zero, and has no parent.

See Constructor Details.

Additional properties may be assigned, e.g., 'title', 'source_file', 'composer', etc. (See set.)

Parameters:

  • *args (Event, default: () ) –

    A variable number of Event objects to be added to the group.

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

    The onset (start) time. If unknown (None), onset will be set when the score is added to a parent, but normally, Scores do not have parents, so the default onset is 0. You can override this using 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.

  • time_map (TimeMap, default: None ) –

    A map from quarters to seconds (or seconds to quarters). Must be passed as a keyword parameter due to *args.

Attributes:

  • parent (Optional[EventGroup]) –

    The containing object or None.

  • _onset (float) –

    The onset (start) time.

  • duration (float) –

    The duration in quarters or seconds.

  • content (list[Event]) –

    Elements contained within this collection.

  • time_map (TimeMap) –

    A map from quarters to seconds (or seconds to quarters).

  • time_signatures (list[TimeSignature]) –

    A list of all time signature changes

  • _units_are_seconds (bool) –

    True if the units are seconds, False if the units are quarters.

Source code in amads/core/basics.py
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
def __init__(self, *args: Event,
             onset: Optional[float] = 0,
             duration: Optional[float] = None,
             time_map: Optional["TimeMap"] = None,
             time_signatures: Optional[List[TimeSignature]] = None):
    super().__init__(None, onset, duration, list(args))  # parent is None
    self.time_map = time_map if time_map else TimeMap()
    self.time_signatures = (
            time_signatures if time_signatures else [TimeSignature(0)])
    self._units_are_seconds = False

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).

offset property writable

offset: float

Retrieve the global offset (stop) time.

Returns:

  • float

    The global offset (stop) time.

measure property

measure: Optional[Measure]

Retrieve the Measure containing this event

Returns:

  • Optional[Measure]

    The Measure containing this event or None if not found.

units_are_quarters property

units_are_quarters: bool

True if the units are in quarters, False if in seconds.

units_are_seconds property

units_are_seconds: bool

True if the units are in seconds, False if in quarters.

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
144
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
171
172
173
174
175
176
177
178
179
180
181
182
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
243
244
245
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
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
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
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
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
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
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
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
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
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
1767
1768
1769
1770
1771
1772
1773
1774
1775
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
1778
1779
1780
1781
1782
1783
1784
1785
1786
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
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
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
1804
1805
1806
1807
1808
1809
1810
1811
1812
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
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
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)

Source code in amads/core/basics.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
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)
    """
    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
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
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
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
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
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
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
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
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
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
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
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
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

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
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
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
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
2305
2306
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
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 = self._add_slice_children(self, result,
                                              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

from_melody classmethod

from_melody(
    pitches: list[Union[Pitch, int, float, str]],
    durations: Union[float, list[float]] = 1.0,
    iois: Optional[Union[float, list[float]]] = None,
    onsets: Optional[list[float]] = None,
    ties: Optional[list[bool]] = None,
) -> Score

Create a Score from a melody specified by pitches and timing.

Parameters:

  • pitches (list of int or list of Pitch) –

    MIDI note numbers or Pitch objects for each note.

  • durations (float or list of float, default: 1.0 ) –

    Durations in quarters for each note. If a scalar value, it will be repeated for all notes.

  • iois (float or list of float or None Inter-onset, default: None ) –

    intervals between successive notes. If a scalar value, it will be repeated for all notes. If not provided and onsets is None, takes values from the durations argument, assuming that notes are placed sequentially without overlap.

  • onsets (list of float or None, default: None ) –

    Start times. Cannot be used together with iois. If both are None, defaults to using durations as IOIs.

  • ties (list of bool or None, default: None ) –

    If provided, a list of booleans indicating whether each note is tied to the next note. The last note's tie value is ignored. If None, no ties are created.

Returns:

  • Score

    A new (flat) Score object containing the melody. If pitches is empty, returns a score with an empty part.

Examples:

Create a simple C major scale with default timing (sequential quarter notes):

>>> score = Score.from_melody([60, 62, 64, 65, 67, 69, 71, 72])
>>> notes = score.content[0].content
>>> len(notes)  # number of notes in first part
8
>>> notes[0].key_num
60
>>> score.duration  # last note ends at t=8
8.0

Create three notes with varying durations:

>>> score = Score.from_melody(
...     pitches=[60, 62, 64],  # C4, D4, E4
...     durations=[0.5, 1.0, 2.0],
... )
>>> score.duration  # last note ends at t=3.5
3.5

Create three notes with custom IOIs:

>>> score = Score.from_melody(
...     pitches=[60, 62, 64],  # C4, D4, E4
...     durations=1.0,  # quarter notes
...     iois=2.0,  # 2 beats between each note onset
... )
>>> score.duration  # last note ends at t=5
5.0

Create three notes with explicit onsets:

>>> score = Score.from_melody(
...     pitches=[60, 62, 64],  # C4, D4, E4
...     durations=1.0,  # quarter notes
...     onsets=[0.0, 2.0, 4.0],  # onset times 2 beats apart
... )
>>> score.duration  # last note ends at t=5
5.0
Source code in amads/core/basics.py
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
@classmethod
def from_melody(cls,
                pitches: list[Union[Pitch, int, float, str]],
                durations: Union[float, list[float]] = 1.0,
                iois: Optional[Union[float, list[float]]] = None,
                onsets: Optional[list[float]] = None,
                ties: Optional[list[bool]] = None) -> "Score":
    """Create a Score from a melody specified by pitches and timing.

    Parameters
    ----------
    pitches : list of int or list of Pitch
        MIDI note numbers or Pitch objects for each note.
    durations : float or list of float
        Durations in quarters for each note. If a scalar value,
        it will be repeated for all notes.
    iois : float or list of float or None Inter-onset
        intervals between successive notes. If a scalar value,
        it will be repeated for all notes. If not provided and
        onsets is None, takes values from the durations argument,
        assuming that notes are placed sequentially without overlap.
    onsets : list of float or None
        Start times. Cannot be used together with iois.
        If both are None, defaults to using durations as IOIs.
    ties : list of bool or None
        If provided, a list of booleans indicating whether each
        note is tied to the next note. The last note's tie value
        is ignored. If None, no ties are created.

    Returns
    -------
    Score
        A new (flat) Score object containing the melody. If pitches
        is empty, returns a score with an empty part.

    Examples
    --------
    Create a simple C major scale with default timing (sequential quarter notes):

    >>> score = Score.from_melody([60, 62, 64, 65, 67, 69, 71, 72])
    >>> notes = score.content[0].content
    >>> len(notes)  # number of notes in first part
    8
    >>> notes[0].key_num
    60
    >>> score.duration  # last note ends at t=8
    8.0

    Create three notes with varying durations:

    >>> score = Score.from_melody(
    ...     pitches=[60, 62, 64],  # C4, D4, E4
    ...     durations=[0.5, 1.0, 2.0],
    ... )
    >>> score.duration  # last note ends at t=3.5
    3.5

    Create three notes with custom IOIs:

    >>> score = Score.from_melody(
    ...     pitches=[60, 62, 64],  # C4, D4, E4
    ...     durations=1.0,  # quarter notes
    ...     iois=2.0,  # 2 beats between each note onset
    ... )
    >>> score.duration  # last note ends at t=5
    5.0

    Create three notes with explicit onsets:

    >>> score = Score.from_melody(
    ...     pitches=[60, 62, 64],  # C4, D4, E4
    ...     durations=1.0,  # quarter notes
    ...     onsets=[0.0, 2.0, 4.0],  # onset times 2 beats apart
    ... )
    >>> score.duration  # last note ends at t=5
    5.0
    """
    if len(pitches) == 0:
        return cls._from_melody(pitches=[], onsets=[], durations=[], ties=None)

    if iois is not None and onsets is not None:
        raise ValueError("Cannot specify both iois and onsets")

    # Convert scalar durations to list
    if isinstance(durations, (int, float)):
        durations = [float(durations)] * len(pitches)

    # If onsets are provided, use them directly
    if onsets is not None:
        if len(onsets) != len(pitches):
            raise ValueError("onsets list must have same length as pitches")
        onsets = [float(d) for d in onsets]

    # Otherwise convert IOIs to onsets
    else:  # onsets is Nonex
        onsets = [0.0]
        # If no IOIs provided, use durations as default IOIs
        if iois is None:
            iois = durations[:-1]  # last duration not needed for IOIs
        # Convert scalar IOIs to list
        elif isinstance(iois, (int, float)):
            iois = [float(iois)] * (len(pitches) - 1)

        # Validate IOIs length
        if len(iois) != len(pitches) - 1:
            raise ValueError("iois list must have length len(pitches) - 1")

        # Convert IOIs to onsets
        onsets = [0.0]  # first note onsets at 0
        current_time = 0.0
        for ioi in iois:
            current_time += float(ioi)
            onsets.append(current_time)

    if not (len(pitches) == len(onsets) == len(durations)):
        raise ValueError("All input lists must have the same length")

    return cls._from_melody(pitches, onsets, durations, ties)

copy

copy()

Make a deep copy.

This is equivalent to EventGroup.insert_copy_into, and provided because scores do not normally have a parent and there is nothing to "copy into."

Returns:

  • Score

    a copy of the score.

Source code in amads/core/basics.py
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
def copy(self):
    """Make a deep copy.

    This is equivalent to [EventGroup.insert_copy_into](
        basics_more.md#amads.core.basics.EventGroup.insert_emptycopy_into),
    and provided
    because scores do not normally have a parent and there is nothing
    to "copy into."

    Returns
    -------
    Score
        a copy of the score.
    """
    return self.insert_copy_into(None)

emptycopy

emptycopy()

Copy score without content.

See insert_emptycopy_into.

Since a Score does not normally have a parent, it is normal for the parent to be None, so emptycopy() is provided to make code more readable.

Returns:

  • Score

    a copy of the score with no content

Source code in amads/core/basics.py
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
def emptycopy(self):
    """Copy score without content.

    See [insert_emptycopy_into](
         basics_more.md#amads.core.basics.EventGroup.insert_emptycopy_into).

    Since a Score does not normally have a parent, it is normal for the
    parent to be None, so `emptycopy()` is provided to make code more
    readable.

    Returns
    -------
    Score
        a copy of the score with no content
    """
    return self.insert_emptycopy_into(None)

append_time_signature

append_time_signature(time_signature: TimeSignature) -> None

Append a time signature change to the score.

If there is already a time signature at the given time, it is replaced.

Parameters:

  • time_signature (TimeSignature) –

    The time signature to append.

Source code in amads/core/basics.py
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
def append_time_signature(self, time_signature: TimeSignature) -> None:
    """Append a time signature change to the score.

    If there is already a time signature at the given time, it is
    replaced.

    Parameters
    ----------
    time_signature : TimeSignature
        The time signature to append.
    """
    # Remove any existing time signature at the same time
    if isclose(self.time_signatures[-1].quarters, time_signature.quarters,
               abs_tol=0.003):
        self.time_signatures.pop()
    self.time_signatures.append(time_signature)

calc_differences

calc_differences(what: List[str]) -> List[List[Note]]

Calculate inter-onset intervals (IOIs), IOI-ratios and intervals.

This method is a convenience function that calls Part.calc_differences() on each Part of the Score. Since this method requires that Notes have no ties and are not concurrent (IOI == 0), the Score will normally be flat, which means only one Part.

Parameters:

  • what (list of str) –

    A list of strings indicating what differences to compute. Valid strings are: 'ioi' (for inter-onset intervals), 'ioi_ratio' (for ratio of successive IOIs), and 'interval' (for pitch intervals in semitones).

Returns:

  • list of List[Note]

    A list of Notes from each Part with the requested difference properties set.

Source code in amads/core/basics.py
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
def calc_differences(self, what: List[str]) -> List[List[Note]]:
    """Calculate inter-onset intervals (IOIs), IOI-ratios and intervals.

    This method is a convenience function that calls Part.calc_differences()
    on each Part of the Score. Since this method requires that Notes have
    no ties and are not concurrent (IOI == 0), the Score will normally be
    flat, which means only one Part.

    Parameters
    ----------
    what : list of str
        A list of strings indicating what differences to compute.
        Valid strings are: 'ioi' (for inter-onset intervals),
        'ioi_ratio' (for ratio of successive IOIs), and
        'interval' (for pitch intervals in semitones).

    Returns
    -------
    list of List[Note]
        A list of Notes from each Part with the requested difference
        properties set.
    """
    notes: List[List[Note]] = []
    parts: Generator = self.find_all(Part)
    for part in parts:
        part_notes = part.calc_differences(what)
        notes.append(part_notes)
    return notes

convert_to_seconds

convert_to_seconds() -> None

Convert the score to represent time in seconds.

This function modifies Score without making a copy.

Source code in amads/core/basics.py
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
def convert_to_seconds(self) -> None:
    """Convert the score to represent time in seconds.

    This function modifies Score without making a copy.
    """
    if self.units_are_seconds:
        return
    # time_signatures are always in units of quarters
    # for ts in self.time_signatures:
    #     ts.quarters = self.time_map.quarter_to_time(ts.quarters)
    super()._convert_to_seconds(self.time_map)
    self._units_are_seconds = True   # set the flag

convert_to_quarters

convert_to_quarters() -> None

Convert the score to represent time in quarters.

This function modifies Score without making a copy.

Source code in amads/core/basics.py
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
def convert_to_quarters(self) -> None:
    """Convert the score to represent time in quarters.

    This function modifies Score without making a copy.
    """
    if not self.units_are_seconds:
        return
    # time_signatures are always in units of quarters
    # for ts in self.time_signatures:
    #     ts.quarters = self.time_map.time_to_quarter(ts.quarters)
    super()._convert_to_quarters(self.time_map)
    self._units_are_seconds = False   # clear the flag

collapse_parts

collapse_parts(part=None, staff=None, has_ties=True)

Merge the notes of selected Parts and Staffs.

This function is used to extract only selected parts or staffs from a Score and return the data as a flat Score (only one part containing only Notes, with ties merged).

The flatten() method is similar and generally preferred. Use this collapse_parts() only if you want to select an individual Staff (e.g., only the left hand when left and right appear as two staffs) or when you only want to process one Part and avoid the cost of flattening all Parts with flatten().

If you are calling this method to extract notes separately for each Staff, it may do extra work. It might save some computation by performing a one-time

score = score.merge_tied_notes()

and calling this method with the parameter has_ties=False. If has_ties is False, it is assumed without checking that each part.has_ties() is False, allowing this method to skip calls to part.merge_tied_notes() for each selected part.

Parameters:

  • part (Union[int, str, list[int], None], default: None ) –

    If part is not None, only notes from the selected part are included:

    1. part may be an integer to match a part number (number is an attribute of Part), or
    2. part may be a string to match a part instrument, or
    3. part may be a list with an index, e.g., [3] will select the 4th part (because indexing is zero-based).
  • staff (Union[int, List[int], None], default: None ) –

    If staff is given, only the notes from selected staves are included. Note that staff selection requires part selection. Thus, if staff is given without part, an Exception is raised. Also, if staff is given and this is a flat score (no staves), an Exception is raised. Staff selection works as follows:

    1. staff may be an integer to match a staff number, or
    2. staff may be a list with an index, e.g., [1] will select the 2nd staff.
  • has_ties (bool, default: True ) –

    Indicates the possibility of tied notes, which must be merged as part of flattening. If the parts are flat already, setting has_ties=False will save some computation.

Raises:

  • ValueError

    A ValueError is raised if:

    • staff is given without a part specification
    • staff is given and this is a flat score (no staves)
Note

The use of lists like [1] for part and staff index notation is not ideal, but parts can be assigned a designated number that is not the same as the index, so we need a way to select by designated number, e.g., 1, and by index, e.g., [1]. Initially, I used tuples, but they are error prone. E.g., part=(0) means part=0, so you would have to write collapse_parts(part=((0))). With [n] notation, you write collapse_parts(part=[0]) to indicate an index. This is prettier and less prone to error.

Source code in amads/core/basics.py
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
def collapse_parts(self, part=None, staff=None, has_ties=True):
    """Merge the notes of selected Parts and Staffs.

    This function is used to extract only selected parts or staffs
    from a Score and return the data as a flat Score (only
    one part containing only Notes, with ties merged).

    The `flatten()` method is similar and generally preferred. Use
    this `collapse_parts()` only if you want to select an individual
    Staff (e.g., only the left hand when left and right appear as
    two staffs) or when you only want to process one Part and avoid
    the cost of flattening *all* Parts with `flatten()`.

    If you are calling this method to extract notes separately for each
    Staff, it may do extra work. It might save some computation by
    performing a one-time

        score = score.merge_tied_notes()

    and calling this method with the parameter has_ties=False. 
    If has_ties is False, it is assumed without checking that
    each part.has_ties() is False, allowing this method to skip
    calls to part.merge_tied_notes() for each selected part.

    Parameters
    ----------
    part : Union[int, str, list[int], None]
        If part is not None, only notes from the selected part are
        included:

        1. part may be an integer to match a part number (`number` is an
              attribute of `Part`), or
        2. part may be a string to match a part instrument, or
        3. part may be a list with an index, e.g., [3] will select the 4th
              part (because indexing is zero-based).
    staff : Union[int, List[int], None]
        If staff is given, only the notes from selected staves are
        included. Note that staff selection requires part selection.
        Thus, if staff is given without part, an Exception is raised.
        Also, if staff is given and this is a flat score (no staves),
        an Exception is raised.
        Staff selection works as follows:

        1. staff may be an integer to match a staff number, or
        2. staff may be a list with an index, e.g., [1] will select
             the 2nd staff.
    has_ties : bool
        Indicates the possibility of tied notes, which must be merged
        as part of flattening. If the parts are flat already,
        setting has_ties=False will save some computation.

    Raises
    ------
    ValueError
        A ValueError is raised if:

        - staff is given without a part specification
        - staff is given and this is a flat score (no staves)

    Note
    ----
    The use of lists like [1] for part and staff index notation
    is not ideal, but parts can be assigned a designated number that
    is not the same as the index, so we need a way to select by
    designated number, e.g., 1, and by index, e.g., [1]. Initially, I
    used tuples, but they are error prone. E.g., part=(0) means part=0,
    so you would have to write collapse_parts(part=((0))). With [n]
    notation, you write collapse_parts(part=[0]) to indicate an index.
    This is prettier and less prone to error.
    """

    # Algorithm: Since we might be selecting individual Staffs and
    # Parts, we want to do selection first, then copy to avoid
    # modifying the source Score (self).
    content = []  # collect selected Parts/Staffs here
    score : Score = self.emptycopy()  # type: ignore
    parts : Generator = self.find_all(Part)
    for i, p in enumerate(parts):
        if (part is None
            or (isinstance(part, int) and part == p.number)
            or (isinstance(part, str) and part == p.instrument)
            or (isinstance(part, list) and part[0] == i)):
            # merging tied notes takes place at the Part level because
            # notes can be tied across Staffs.
            if has_ties:
                # put parts into score copy to allow onset computation
                # later, we will merge notes and remove these parts
                p = p.merge_tied_notes(score)

            if staff is None:  # no staff selection, use whole Part
                content.append(p)
            else:  # must find Notes in selected Staffs
                staffs = p.find_all(Staff)
                for i, s in enumerate(staffs):
                    if (staff is None
                        or (isinstance(staff, int) and staff == s.number)
                        or (isinstance(staff, list) and staff[0] == i)):
                        content.append(s)
    # now content is a list of Parts or Staffs to merge
    notes = []
    for part_or_staff in content:  # works with both Part and Score:
        notes += part_or_staff.list_all(Note)
    new_part = Part(parent=score)
    if not has_ties:
        # because we avoided merging ties in parts, notes still belong
        # to the original score (self), so we need to copy them:
        copies = []  # copy all notes to here
        for note in notes:
            # rather than a possibly expensive insert into new_part, we
            # use sort (below) to construct the content of new_part.
            copies.append(note.insert_copy_into(new_part))
        notes = copies
    # notes can be modified, so reuse them in the new_part:
    for note in notes:
        note.parent = new_part
    notes.sort(key=lambda x: (x.onset, x.pitch))
    new_part.content = notes
    # remove all the parts that we merged, leaving only new_part
    score.content = [new_part]
    return score

flatten

flatten(collapse=False)

Deep copy notes in a score to a flat score.

A flat score consists of only Parts containing Notes (ties are merged).

See collapse_parts to select specific Parts or Staffs and flatten them.

Parameters:

  • collapse (bool, default: False ) –

    If collapse is True, multiple parts are collapsed into a single part, and notes are ordered according to onset times. The resulting score contains one or more Parts, each containing only Notes.

Source code in amads/core/basics.py
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
def flatten(self, collapse=False):
    """Deep copy notes in a score to a flat score.

    A flat score consists of only Parts containing Notes
    (ties are merged).

    See [collapse_parts][amads.core.basics.Score.collapse_parts]
    to select specific Parts or Staffs and flatten them.

    Parameters
    ----------
    collapse : bool
        If collapse is True, multiple parts are collapsed into a single
        part, and notes are ordered according to onset times. The resulting
        score contains one or more Parts, each containing only Notes.
    """
    # make a deep copy of the score, merging tied notes in the process.
    score : Score = self.merge_tied_notes()  # type: ignore
    # it is now safe to modify score because it has been copied
    if collapse:  # similar to Part.flatten() but we have to sort and
        # do some other extra work to put all notes into score
        # first, see if all parts have the same instrument. If so, we
        # will set instrument in the collapsed part. Otherwise, the
        # collapsed part will not have an instrument name.
        instrument = None
        instr_state = None
        for part in score.content:
            if isinstance(part, Part):
                if instr_state is None:  # capture first instrument name
                    instrument = part.instrument
                    instr_state = "set"
                elif instrument != part.instrument:
                    instr_state = "multiple"
                    instrument = None  # multiple instrument names found
                else:  # this part.instrument is consistent
                    pass

        new_part = Part(parent=score, onset=score.onset,
                        instrument=instrument)
        notes : list[Note] = score.list_all(Note)  # type: ignore
        score.content = [new_part]  # remove all other parts and events
        for note in notes:
            note.parent = new_part
        # notes with equal onset times are sorted in pitch from high to low
        notes.sort(key=lambda x: (x.onset, x.pitch))

        new_part.content = notes  # type: ignore (List[Note] < List[Event])

        # set the Part duration so it ends at the max offset of all Parts:
        offset = max((part.offset for part in self.find_all(Part)),
                     default=0)
        new_part.duration = offset - score.onset

    else:  # flatten each part separately
        for part in score.find_all(Part):
            part.flatten(in_place=True)  # type: ignore (part is a Part)
    return score

is_flat

is_flat()

Test if Score is flat.

a flat Score conforms to strict hierarchy of: Score-Part-Note with no tied notes.

Returns:

  • bool

    True iff the score is flat.

Source code in amads/core/basics.py
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
def is_flat(self):
    """Test if Score is flat.

    a flat Score conforms to strict hierarchy of:
    Score-Part-Note with no tied notes.

    Returns
    -------
    bool
        True iff the score is flat.
    """
    for part in self.content:
        # only Parts are expected, but things outside of the hierarchy
        # are allowed, so we only rule out violations of the hierarchy:
        if isinstance(part, (Score, Staff, Measure, Note, Rest, Chord)):
            return False
        if isinstance(part, Part) and not part.is_flat():
            return False
    return True

is_flat_and_collapsed

is_flat_and_collapsed()

Determine if score has been flattened into one part

Returns:

  • bool

    True iff the score is flat and has one part.

Source code in amads/core/basics.py
3418
3419
3420
3421
3422
3423
3424
3425
3426
def is_flat_and_collapsed(self):
    """Determine if score has been flattened into one part

    Returns
    -------
    bool
        True iff the score is flat and has one part.
    """
    return self.part_count() == 1 and self.is_flat()

is_well_formed_full_score

is_well_formed_full_score() -> bool

Test if Score is a well-formed full score.

A well-formed full score is measured and conforms to a strict hierarchy of: Score-Part-Staff-Measure-(Note or Rest or Chord) and Chord-Note.

Returns:

  • bool

    True iff the Score is a well-formed full Score.

Source code in amads/core/basics.py
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
def is_well_formed_full_score(self) -> bool:
    """Test if Score is a well-formed full score.

    A well-formed full score is measured and conforms to a strict
    hierarchy of: Score-Part-Staff-Measure-(Note or Rest or Chord)
    and Chord-Note.

    Returns
    -------
    bool
        True iff the Score is a well-formed full Score.
    """
    for part in self.content:
        # only Parts are expected, but things outside of the hierarchy
        # are allowed, so we only rule out violations of the hierarchy:
        if isinstance(part, (Score, Staff, Measure, Note, Rest, Chord)):
            return False
        if isinstance(part, Part) and not part.is_well_formed_full_part():
            return False
    return True

note_containers

note_containers()

Returns a list of non-empty note containers.

For full (measured) Scores, these are the Staff objects. For flat Scores, these are the Part objects. This is mainly useful for extracting note sequences where each part or staff represents a separate sequence. This method will retrieve either parts or staffs, whichever applies. This implementation also handles a mix of Parts with and without Staffs, returning a list of whichever is the direct parent of a list of Notes.

Returns:

  • list(EventGroup)

    list of (recursively) contained EventGroups that contain Notes

Source code in amads/core/basics.py
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
def note_containers(self):
    """Returns a list of non-empty note containers.

    For full (measured) Scores, these are the Staff objects.
    For flat Scores, these are the Part objects. This is mainly
    useful for extracting note sequences where each part or staff
    represents a separate sequence. This method will retrieve
    either parts or staffs, whichever applies. This implementation
    also handles a mix of Parts with and without Staffs, returning
    a list of whichever is the direct parent of a list of Notes.

    Returns
    -------
    list(EventGroup)
        list of (recursively) contained EventGroups that contain Notes
    """
    containers = []
    # start with parts, which are common to both measured scores and
    # flat scores. If the Part has a Staff, the Staffs are the
    # containers we want. If the Part has a Note, the Part itself is
    # the container. Other event classes can exist and are ignored.
    for part in self.find_all(Part):  # type: ignore (Part is an Event)
        part : Part
        for event in part.content:
            if isinstance(event, Staff):
                containers += part.list_all(Staff)
                break
            elif isinstance(event, Note):
                containers.append(part)
                break
        # if part was empty, it is not added to containers
    return containers

pack

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

Adjust onsets to pack events in the entire Score.

This method modifies the Score in place, adjusting onsets so that events occur sequentially without gaps. By default, self is assumed to be a full score containing Parts with Staffs and Measures, so all contained Parts are concurrent, starting at onset, and Parts are also packed, making all Staffs start concurrently.

If the Score is flat (Parts contain only Notes), set sequential to True, which overrides the packing of Parts, making their content sequential (Notes) instead of concurrent (Staffs).

Note that the direct content of this Score starts concurrently at onset in either case. Pack is recursive, but it makes content concurrent in Concurrences like Chords and sequential is Sequences like Staffs and Measures.

Parameters:

  • onset (float, default: 0.0 ) –

    The onset time for the Score after packing.

  • sequential (bool, default: False ) –

    If true, Parts are conconcurrently started at onset, but each Part is packed sequentially, so that the first event in each Part starts at onset, and subsequent events start at the offset of the previous event. Use False for full scores (with Parts and Staffs) and True for flat scores (with Parts containing only Notes).

Returns:

  • Score

    The modified Score instance itself.

Source code in amads/core/basics.py
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
def pack(self, onset: float = 0.0, sequential: bool = False) -> float:
    """Adjust onsets to pack events in the entire Score.

    This method modifies the Score in place, adjusting onsets
    so that events occur sequentially without gaps. By default,
    self is assumed to be a full score containing Parts with Staffs
    and Measures, so all contained Parts are concurrent, starting
    at `onset`, and Parts are also packed, making all Staffs start
    concurrently.

    If the Score is flat (Parts contain only Notes), set `sequential`
    to True, which overrides the packing of Parts, making their
    content sequential (Notes) instead of concurrent (Staffs).

    Note that the direct content of this Score starts concurrently
    at `onset` in either case. Pack is recursive, but it makes
    content concurrent in Concurrences like Chords and sequential
    is Sequences like Staffs and Measures.

    Parameters
    ----------
    onset : float
        The onset time for the Score after packing.
    sequential : bool
        If true, Parts are conconcurrently started at `onset`, but
        each Part is packed sequentially, so that the first event
        in each Part starts at `onset`, and subsequent events
        start at the offset of the previous event. Use False for
        full scores (with Parts and Staffs) and True for flat scores
        (with Parts containing only Notes).
    Returns
    -------
    Score
        The modified Score instance itself.
    """
    dur = 0.0
    for part in self.content:  # type: ignore (score contains Parts)
        part.onset = onset
        if isinstance(part, Part):
            dur = max(dur, part.pack(onset, sequential))
        # anything but Part follows default packing behavior:
        elif isinstance(part, EventGroup):
            dur = max(dur, part.pack(onset))
        else:
            dur = max(dur, part.duration)
    self.duration = dur
    return dur

part_count

part_count()

How many parts are in this score?

Returns:

  • int

    The number of parts in this score.

Source code in amads/core/basics.py
3534
3535
3536
3537
3538
3539
3540
3541
3542
def part_count(self):
    """How many parts are in this score?

    Returns
    -------
    int
        The number of parts in this score.
    """
    return len(self.list_all(Part))

parts_are_monophonic

parts_are_monophonic() -> bool

Determine if each part of a musical score is monophonic.

A monophonic part has no overlapping notes (e.g., chords).

Returns:

  • bool

    True if each part is monophonic, False otherwise.

Source code in amads/core/basics.py
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
def parts_are_monophonic(self) -> bool:
    """
    Determine if each part of a musical score is monophonic.

    A monophonic part has no overlapping notes (e.g., chords).

    Returns
    -------
    bool
        True if each part is monophonic, False otherwise.
    """
    for part in self.find_all(Part):
        part = cast(Part, part)
        if not part.ismonophonic():
            return False
    return True

remove_measures

remove_measures() -> Score

Create a new Score with all Measures removed.

Preserves Staffs in the hierarchy. Notes are "lifted" from Measures to become direct content of their Staff. The result satisfies neither is_flat() nor is_well_formed_full_score(), but it could be useful in preserving a separation between staves. See also collapse_parts, which can be used to extract individual staves from a score. The result will have ties merged. (If you want to preserve ties and access the notes in a Staff, consider using find_all(Staff), and then for each staff, find_all(Note), but note that ties can cross between staves.)

Returns:

  • Score

    A new Score instance with all Measures removed.

Source code in amads/core/basics.py
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
def remove_measures(self) -> "Score":
    """Create a new Score with all Measures removed.

    Preserves Staffs in the hierarchy. Notes are "lifted" from Measures
    to become direct content of their Staff. The result satisfies neither
    `is_flat()` nor `is_well_formed_full_score()`, but it could be useful
    in preserving a separation between staves. See also `collapse_parts`,
    which can be used to extract individual staves from a score. The result
    will have ties merged. (If you want to preserve ties and access the
    notes in a Staff, consider using find_all(Staff), and then for each staff,
    find_all(Note), but note that ties can cross between staves.)

    Returns
    -------
    Score
        A new Score instance with all Measures removed.
    """
    score : Score = self.emptycopy()  # type: ignore
    for part in self.content:  # type: ignore (score contains Parts)
        if isinstance(part, Part):
            # puts a copy of Part with merged_notes into score and
            # then removes measures from each staff:
            part.remove_measures(score)
        else:  # non-Part objects are simply copied
            part.insert_copy_into(score)
    return score

show

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

Print the Score information.

Parameters:

  • indent (int, default: 0 ) –

    The indentation level for display.

Returns:

  • Score

    The Score instance itself.

Source code in amads/core/basics.py
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
def show(self, indent: int = 0,
         file: Optional[TextIO] = None) -> "Score":
    """Print the Score information.

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

    Returns
    -------
    Score
        The Score instance itself.
    """

    print(" " * indent, self, sep="", file=file)
    self.time_map.show(indent + 4, file=file)

    print(" " * indent, "    time_signatures [", sep="", end="") 
    need_blank = ""
    col = indent + 21
    for ts in self.time_signatures:
        tss = str(ts)
        if len(tss) + col > 79:
            print("\n", " " * (indent + 20), end="")
            col = indent + 21
        print(need_blank, tss, sep="", end="")
        col += len(tss)
        need_blank = " "
    print("]")  # newline after time signatures

    for elem in self.content:
        elem.show(indent + 4, file=file)  # type: ignore
        # type ignore because (all Events have show())
    return self

time_shift

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

Change the onset by an increment, affecting all content.

This is tricky for scores because they have a time_map (tempo specification). If units_are_quarters, time_shift means insert initial quarters at the initial tempo, and shift all tempo changes by increment quarters. If increment is negative, it is assumed that all Events are at or after -increment, so they will shifted to positive times. Quarters are simply removed from the beginning, shifting all time signatures and tempo changes by increment quarters.

If units_are_seconds, we insert increment seconds at the initial tempo (positive increment), or we remove the first -increment seconds (negative increment) but converting increment to quarters and converting this Score to units_are_quarters.

If content_only is true, the time_map and time_signatures are left in place along with the placement of EventGroups including this Score, Parts, Staffs, Measures, and even Chords, but their Event content (Notes, Rests, KeySignatures, Clefs) are shifted. This probably only makes sense for flattened scores without Measures and Chords since Events could be shifted outside of their container boundaries.

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:

  • Score

    The object. This method modifies the Score.

Source code in amads/core/basics.py
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
def time_shift(self, increment: float,
               content_only: bool = False) -> "Score":
    """
    Change the onset by an increment, affecting all content.

    This is tricky for scores because they have a time_map (tempo
    specification). If units_are_quarters, time_shift means insert
    initial quarters at the initial tempo, and shift all tempo
    changes by increment quarters. If increment is negative, it is
    assumed that all Events are at or after -increment, so they will
    shifted to positive times. Quarters are simply removed from the
    beginning, shifting all time signatures and tempo changes by
    increment quarters.

    If units_are_seconds, we insert increment seconds at the initial
    tempo (positive increment), or we remove the first -increment
    seconds (negative increment) but converting increment to quarters
    and converting this Score to units_are_quarters.

    If content_only is true, the time_map and time_signatures are
    left in place along with the placement of EventGroups including
    this Score, Parts, Staffs, Measures, and even Chords, but their
    Event content (Notes, Rests, KeySignatures, Clefs) are shifted.
    This probably only makes sense for flattened scores without
    Measures and Chords since Events could be shifted outside of
    their container boundaries.

    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
    -------
    Score
        The object. This method modifies the `Score`.
    """
    original_units_are_seconds = self.units_are_seconds
    if original_units_are_seconds:
        if increment >= 0:
            increment = self.time_map.time_to_quarter(increment)
        else:
            increment = -self.time_map.time_to_quarter(-increment)
        self.convert_to_quarters()
    self._timesignatures_shift(increment)
    self.time_map._time_shift(increment)
    super().time_shift(increment, content_only)
    if original_units_are_seconds:
        self.convert_to_seconds()
    return self