code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def parse_annotation(filename: str) -> Annotation: """Parse the annotation from the filename.""" annotation = { "emo_class": filename[1], "YouTube_ID": filename[3:14], "seg_id": filename.split("_")[-1][:-4], } return Annotation(time=0, annotation=annotation)
Parse the annotation from the filename.
parse_annotation
python
salu133445/muspy
muspy/datasets/emopia.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/emopia.py
MIT
def get_annotations( roman_numerals: List[RomanNumeral], resolution=DEFAULT_RESOLUTION ) -> List[Annotation]: """Return music21 RomanNumeral objects as Annotation objects.""" # Convert the list into a dictionary to remove duplicate items roman_numeral_dict = {rn.offset: rn for rn in roman_numerals if rn...
Return music21 RomanNumeral objects as Annotation objects.
get_annotations
python
salu133445/muspy
muspy/datasets/haydn.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/haydn.py
MIT
def download(self) -> "FolderDataset": """Download the source datasets. Returns ------- Object itself. """ # Maximum consecutive trials allowed to fail tolerance = 10 kinds = ["Classic", "New Tunes", "New Songs", "Children"] keys = ["h", "nt", "...
Download the source datasets. Returns ------- Object itself.
download
python
salu133445/muspy
muspy/datasets/hymnal.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/hymnal.py
MIT
def convert( self, root: Union[str, Path], kind: str = "json", n_jobs: int = 1, ignore_exceptions: bool = True, ) -> "MusicDataset": """Convert and save the Music objects. Parameters ---------- root : str or Path Root directory to ...
Convert and save the Music objects. Parameters ---------- root : str or Path Root directory to save the data. kind : {'json', 'yaml'}, default: 'json' File format to save the data. n_jobs : int, default: 1 Maximum number of concurrently runnin...
convert
python
salu133445/muspy
muspy/datasets/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/music21.py
MIT
def compute_md5(path: Union[str, Path], chunk_size: int): """Return the MD5 hash of a file, calculated chunk by chunk. Parameters ---------- path : str or Path Path to the file. chunk_size : int Chunk size used to calculate the MD5 hash. """ md5 = hashlib.md5() with ope...
Return the MD5 hash of a file, calculated chunk by chunk. Parameters ---------- path : str or Path Path to the file. chunk_size : int Chunk size used to calculate the MD5 hash.
compute_md5
python
salu133445/muspy
muspy/datasets/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/utils.py
MIT
def compute_sha256(path: Union[str, Path], chunk_size: int): """Return the MD5 checksum of a file, calculated chunk by chunk. Parameters ---------- path : str or Path Path to the file. chunk_size : int Chunk size used to calculate the MD5 checksum. """ sha256 = hashlib.sha2...
Return the MD5 checksum of a file, calculated chunk by chunk. Parameters ---------- path : str or Path Path to the file. chunk_size : int Chunk size used to calculate the MD5 checksum.
compute_sha256
python
salu133445/muspy
muspy/datasets/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/utils.py
MIT
def check_sha256( path: Union[str, Path], sha256: str, chunk_size: int = 1024 * 1024 ): """Check if the sha256 hash of a file matches the expected one. Parameters ---------- path : str or Path Path to the file. sha256 : str Expected sha256 hash of the file. chunk_size : int,...
Check if the sha256 hash of a file matches the expected one. Parameters ---------- path : str or Path Path to the file. sha256 : str Expected sha256 hash of the file. chunk_size : int, default: 2^20 Chunk size used to compute the sha256 hash.
check_sha256
python
salu133445/muspy
muspy/datasets/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/utils.py
MIT
def download_url( url: str, path: Union[str, Path], overwrite: bool = False, size: int = None, md5: str = None, sha256: str = None, verbose: bool = True, ): """Download a file from a URL. Parameters ---------- url : str URL to the file to download. path : str or ...
Download a file from a URL. Parameters ---------- url : str URL to the file to download. path : str or Path Path to save the downloaded file. overwrite : bool, default: False Whether to overwrite existing downloaded file. size : int, optional Expected size of the...
download_url
python
salu133445/muspy
muspy/datasets/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/utils.py
MIT
def extract_archive( path: Union[str, Path], root: Union[str, Path] = None, kind: str = None, cleanup: bool = False, verbose: bool = True, ): """Extract an archive in ZIP, TAR, TGZ, TXZ, GZ or XZ format. Parameters ---------- path : str or Path Path to the archive. root ...
Extract an archive in ZIP, TAR, TGZ, TXZ, GZ or XZ format. Parameters ---------- path : str or Path Path to the archive. root : str or Path, optional Root directory to save the extracted file. Defaults to the directory that contains the archive. kind : {'zip', 'tar', 'tgz', ...
extract_archive
python
salu133445/muspy
muspy/datasets/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/utils.py
MIT
def list_datasets(): """Return all supported dataset classes as a list. Returns ------- A list of all supported dataset classes. """ return [ EMOPIADataset, EssenFolkSongDatabase, HaydnOp20Dataset, HymnalDataset, HymnalTuneDataset, JSBChoralesDat...
Return all supported dataset classes as a list. Returns ------- A list of all supported dataset classes.
list_datasets
python
salu133445/muspy
muspy/datasets/wrapper.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/wrapper.py
MIT
def get_dataset(key: str) -> Type[Dataset]: """Return a certain dataset class by key. Parameters ---------- key : str Dataset key (case-insensitive). Returns ------- The corresponding dataset class. """ key = key.lower() if key == "emopia": return EMOPIADataset...
Return a certain dataset class by key. Parameters ---------- key : str Dataset key (case-insensitive). Returns ------- The corresponding dataset class.
get_dataset
python
salu133445/muspy
muspy/datasets/wrapper.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/wrapper.py
MIT
def read_abc_string( data_str: str, number: int = None, resolution=DEFAULT_RESOLUTION, ) -> Union[Music, List[Music]]: """Read ABC data into Music object(s) using music21 backend. Parameters ---------- data_str : str ABC data to parse. number : int, optional Reference number of ...
Read ABC data into Music object(s) using music21 backend. Parameters ---------- data_str : str ABC data to parse. number : int, optional Reference number of a specific tune to read (i.e., the 'X:' field). Defaults to read all tunes. resolution : int, default: `muspy.DEFAULT_...
read_abc_string
python
salu133445/muspy
muspy/inputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/abc.py
MIT
def read_abc( path: Union[str, Path], number: int = None, resolution=DEFAULT_RESOLUTION, ) -> Union[Music, List[Music]]: """Return an ABC file into Music object(s) using music21 backend. Parameters ---------- path : str or Path Path to the ABC file to read. number : int, optional ...
Return an ABC file into Music object(s) using music21 backend. Parameters ---------- path : str or Path Path to the ABC file to read. number : int, optional Reference number of a specific tune to read (i.e., the 'X:' field). Defaults to read all tunes. resolution : int, defa...
read_abc
python
salu133445/muspy
muspy/inputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/abc.py
MIT
def from_event_representation( array: ndarray, resolution: int = DEFAULT_RESOLUTION, program: int = 0, is_drum: bool = False, use_single_note_off_event: bool = False, use_end_of_sequence_event: bool = False, max_time_shift: int = 100, velocity_bins: int = 32, default_velocity: int = ...
Decode event-based representation into a Music object. Parameters ---------- array : ndarray Array in event-based representation to decode. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. program : int, default: 0 (Acoustic Grand Piano) ...
from_event_representation
python
salu133445/muspy
muspy/inputs/event.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/event.py
MIT
def load_json( path: Union[str, Path, TextIO], compressed: bool = None ) -> Music: """Load a JSON file into a Music object. Parameters ---------- path : str, Path or TextIO Path to the file or the file to load. compressed : bool, optional Whether the file is a compressed JSON fi...
Load a JSON file into a Music object. Parameters ---------- path : str, Path or TextIO Path to the file or the file to load. compressed : bool, optional Whether the file is a compressed JSON file (`.json.gz`). Has no effect when `path` is a file object. Defaults to infer from th...
load_json
python
salu133445/muspy
muspy/inputs/json.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/json.py
MIT
def from_mido(midi: MidiFile, duplicate_note_mode: str = "fifo") -> Music: """Return a mido MidiFile object as a Music object. Parameters ---------- midi : :class:`mido.MidiFile` Mido MidiFile object to convert. duplicate_note_mode : {'fifo', 'lifo', 'all'}, default: 'fifo' Policy f...
Return a mido MidiFile object as a Music object. Parameters ---------- midi : :class:`mido.MidiFile` Mido MidiFile object to convert. duplicate_note_mode : {'fifo', 'lifo', 'all'}, default: 'fifo' Policy for dealing with duplicate notes. When a note off message is presetned whil...
from_mido
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def read_midi_mido( path: Union[str, Path], duplicate_note_mode: str = "fifo" ) -> Music: """Read a MIDI file into a Music object using mido backend. Parameters ---------- path : str or Path Path to the MIDI file to read. duplicate_note_mode : {'fifo', 'lifo, 'all'}, default: 'fifo' ...
Read a MIDI file into a Music object using mido backend. Parameters ---------- path : str or Path Path to the MIDI file to read. duplicate_note_mode : {'fifo', 'lifo, 'all'}, default: 'fifo' Policy for dealing with duplicate notes. When a note off message is presetned while ther...
read_midi_mido
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def from_pretty_midi_key_signature( key_signature: PmKeySignature, ) -> KeySignature: """Return a pretty_midi KeySignature object as a KeySignature. Parameters ---------- key_signature : :class:`pretty_midi.KeySignature` pretty_midi KeySignature object to convert. Returns ------- ...
Return a pretty_midi KeySignature object as a KeySignature. Parameters ---------- key_signature : :class:`pretty_midi.KeySignature` pretty_midi KeySignature object to convert. Returns ------- :class:`muspy.KeySignature` Converted key signature. Note ---- The `time`...
from_pretty_midi_key_signature
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def from_pretty_midi_time_signature( time_signature: PmTimeSignature, ) -> TimeSignature: """Return a pretty_midi TimeSignature object as a TimeSignature. Parameters ---------- time_signature : :class:`pretty_midi.TimeSignature` pretty_midi TimeSignature object to convert. Returns ...
Return a pretty_midi TimeSignature object as a TimeSignature. Parameters ---------- time_signature : :class:`pretty_midi.TimeSignature` pretty_midi TimeSignature object to convert. Returns ------- :class:`muspy.TimeSignature` Converted time signature. Note ---- The...
from_pretty_midi_time_signature
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def from_pretty_midi_lyric(lyric: PmLyric) -> Lyric: """Return a pretty_midi Lyric object as a Lyric object. Parameters ---------- lyric : :class:`pretty_midi.Lyric` pretty_midi Lyric object to convert. Returns ------- :class:`muspy.Lyric` Converted lyric. Note ---...
Return a pretty_midi Lyric object as a Lyric object. Parameters ---------- lyric : :class:`pretty_midi.Lyric` pretty_midi Lyric object to convert. Returns ------- :class:`muspy.Lyric` Converted lyric. Note ---- The `time` attribute of the converted object will be o...
from_pretty_midi_lyric
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def from_pretty_midi_note(note: PmNote) -> Note: """Return pretty_midi Note object as a Note object. Parameters ---------- note : :class:`pretty_midi.Note` pretty_midi Note object to convert. Returns ------- :class:`muspy.Note` Converted note. Note ---- The `ti...
Return pretty_midi Note object as a Note object. Parameters ---------- note : :class:`pretty_midi.Note` pretty_midi Note object to convert. Returns ------- :class:`muspy.Note` Converted note. Note ---- The `time` and `duration` attributes of the converted object wi...
from_pretty_midi_note
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def from_pretty_midi_instrument(instrument: Instrument) -> Track: """Return a pretty_midi Instrument object as a Track object. Parameters ---------- instrument : :class:`pretty_midi.Instrument` pretty_midi Instrument object to convert. Returns ------- :class:`muspy.Track` C...
Return a pretty_midi Instrument object as a Track object. Parameters ---------- instrument : :class:`pretty_midi.Instrument` pretty_midi Instrument object to convert. Returns ------- :class:`muspy.Track` Converted track.
from_pretty_midi_instrument
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def from_pretty_midi(midi: PrettyMIDI, resolution: int = None) -> Music: """Return a pretty_midi PrettyMIDI object as a Music object. Parameters ---------- midi : :class:`pretty_midi.PrettyMIDI` PrettyMIDI object to convert. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) ...
Return a pretty_midi PrettyMIDI object as a Music object. Parameters ---------- midi : :class:`pretty_midi.PrettyMIDI` PrettyMIDI object to convert. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- :class:`muspy.Music` ...
from_pretty_midi
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def read_midi_pretty_midi(path: Union[str, Path]) -> Music: """Read a MIDI file into a Music object using pretty_midi backend. Parameters ---------- path : str or Path Path to the MIDI file to read. Returns ------- :class:`muspy.Music` Converted Music object. """ m...
Read a MIDI file into a Music object using pretty_midi backend. Parameters ---------- path : str or Path Path to the MIDI file to read. Returns ------- :class:`muspy.Music` Converted Music object.
read_midi_pretty_midi
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def read_midi( path: Union[str, Path], backend: str = "mido", duplicate_note_mode: str = "fifo", ) -> Music: """Read a MIDI file into a Music object. Parameters ---------- path : str or Path Path to the MIDI file to read. backend: {'mido', 'pretty_midi'}, default: 'mido' ...
Read a MIDI file into a Music object. Parameters ---------- path : str or Path Path to the MIDI file to read. backend: {'mido', 'pretty_midi'}, default: 'mido' Backend to use. duplicate_note_mode : {'fifo', 'lifo, 'all'}, default: 'fifo' Policy for dealing with duplicate not...
read_midi
python
salu133445/muspy
muspy/inputs/midi.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/midi.py
MIT
def _gcd(a: int, b: int) -> int: """Return greatest common divisor using Euclid's Algorithm. Code copied from https://stackoverflow.com/a/147539. """ while b: a, b = b, a % b return a
Return greatest common divisor using Euclid's Algorithm. Code copied from https://stackoverflow.com/a/147539.
_gcd
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def _get_text( element: Element, path: str, default: T = None, remove_newlines: bool = False, ) -> Union[str, T]: """Return the text of the first matching element.""" elem = element.find(path) if elem is not None and elem.text is not None: if remove_newlines: return " ".j...
Return the text of the first matching element.
_get_text
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def _get_required(element: Element, path: str) -> Element: """Return a required child element of an element. Raise a MuseScoreError if not found. """ elem = element.find(path) if elem is None: raise MuseScoreError( f"Element `{path}` is required for an '{element.tag}' element."...
Return a required child element of an element. Raise a MuseScoreError if not found.
_get_required
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def _get_required_attr(element: Element, attr: str) -> str: """Return a required attribute of an element. Raise a MuseScoreError if not found. """ attribute = element.get(attr) if attribute is None: raise MuseScoreError( f"Attribute '{attr}' is required for an '{element.tag}' e...
Return a required attribute of an element. Raise a MuseScoreError if not found.
_get_required_attr
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def _get_required_text( element: Element, path: str, remove_newlines: bool = False ) -> str: """Return a required text from a child element of an element. Raise a MuseScoreError otherwise. """ elem = _get_required(element, path) if elem.text is None: raise MuseScoreError( f...
Return a required text from a child element of an element. Raise a MuseScoreError otherwise.
_get_required_text
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_metronome_elem(elem: Element) -> Optional[float]: """Return a qpm value parsed from a metronome element.""" beat_unit = _get_text(elem, "beat-unit") if beat_unit is not None: per_minute = _get_text(elem, "per-minute") if per_minute is not None and beat_unit in NOTE_TYPE_MAP: ...
Return a qpm value parsed from a metronome element.
parse_metronome_elem
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_time_elem(elem: Element) -> Tuple[int, int]: """Return the numerator and denominator of a time element.""" # Numerator beats = _get_text(elem, "sigN") if beats is None: beats = _get_text(elem, "nom1") if beats is None: raise MuseScoreError( "Neither 'sigN' nor '...
Return the numerator and denominator of a time element.
parse_time_elem
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_key_elem(elem: Element) -> Tuple[int, str, int, str]: """Return the key parsed from a key element.""" mode = _get_text(elem, "mode") fifths_text = _get_text(elem, "accidental") # MuseScore 2.x and 3.x if fifths_text is None: fifths_text = _get_text(elem, "subtype") # MuseScore 1.x ...
Return the key parsed from a key element.
parse_key_elem
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_lyric_elem(elem: Element) -> str: """Return the lyric text parsed from a lyric element.""" text = _get_required_text(elem, "text") syllabic_elem = elem.find("syllabic") if syllabic_elem is not None: if syllabic_elem.text == "begin": text = f"{text} -" elif syllabic_...
Return the lyric text parsed from a lyric element.
parse_lyric_elem
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_marker_measure_map(elem: Element) -> Dict[str, int]: """Return a marker-measure map parsed from a staff element.""" # Initialize with a start marker markers: Dict[str, int] = {"start": 0} # Find all markers in all measures for i, measure_elem in enumerate(elem.findall("Measure")): ...
Return a marker-measure map parsed from a staff element.
parse_marker_measure_map
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_meta_staff_elem( staff_elem: Element, resolution: int, measure_indices: List[int], timeout: int = None, ) -> Tuple[ List[Tempo], List[KeySignature], List[TimeSignature], List[Barline], List[Beat], ]: """Return data parsed from a meta staff element. This function on...
Return data parsed from a meta staff element. This function only parses the tempos, key and time signatures. Use `parse_staff_elem` to parse the notes and lyrics.
parse_meta_staff_elem
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_staff_elem( staff_elem: Element, resolution: int, measure_indices: List[int], timeout: int = None, ) -> Tuple[List[Note], List[Lyric]]: """Return notes and lyrics parsed from a staff element. This function only parses the notes and lyrics. Use `parse_meta_staff_elem` to parse the ...
Return notes and lyrics parsed from a staff element. This function only parses the notes and lyrics. Use `parse_meta_staff_elem` to parse the tempos, key and time signatures.
parse_staff_elem
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_metadata(root: Element) -> Metadata: """Return a Metadata object parsed from a MuseScore file.""" # Creators and copyrights title = None creators = [] copyrights = [] # Iterate over meta tags for meta_tag in root.findall("Score/metaTag"): name = _get_required_attr(meta_tag...
Return a Metadata object parsed from a MuseScore file.
parse_metadata
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def _get_root(path: Union[str, Path], compressed: bool = None): """Return root of the element tree.""" if compressed is None: compressed = str(path).endswith(".mscz") if not compressed: tree = ET.parse(str(path)) return tree.getroot() # Find out the main MSCX file in the compre...
Return root of the element tree.
_get_root
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_part_elem_info( elem: Element, has_staff_id: bool = True ) -> Tuple[Optional[List[str]], OrderedDict]: """Return part information parsed from a score part element.""" part_info: OrderedDict = OrderedDict() # Staff IDs if has_staff_id: staff_ids = [ _get_required_attr(s...
Return part information parsed from a score part element.
parse_part_elem_info
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def read_musescore( path: Union[str, Path], resolution: int = None, compressed: bool = None, timeout: int = None, ) -> Music: """Read a MuseScore file into a Music object. Parameters ---------- path : str or Path Path to the MuseScore file to read. resolution : int, optional...
Read a MuseScore file into a Music object. Parameters ---------- path : str or Path Path to the MuseScore file to read. resolution : int, optional Time steps per quarter note. Defaults to the least common multiple of all divisions. compressed : bool, optional Whether...
read_musescore
python
salu133445/muspy
muspy/inputs/musescore.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musescore.py
MIT
def parse_metadata(stream: Stream) -> Union[Metadata, None]: """Return metadata parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. Returns ------- :class:`muspy.Metadata` Parsed metadata. """ if strea...
Return metadata parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. Returns ------- :class:`muspy.Metadata` Parsed metadata.
parse_metadata
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def parse_tempos( stream: Stream, resolution: int = DEFAULT_RESOLUTION ) -> List[Tempo]: """Return tempos parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) ...
Return tempos parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- list of :class:`muspy.Tempo` Par...
parse_tempos
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def parse_key_signatures( stream: Stream, resolution: int = DEFAULT_RESOLUTION ) -> List[KeySignature]: """Return key signatures parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. resolution : int, default: `muspy.DEFAULT_...
Return key signatures parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- list of :class:`muspy.KeySignatu...
parse_key_signatures
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def parse_time_signatures( stream: Stream, resolution: int = DEFAULT_RESOLUTION ) -> List[TimeSignature]: """Return time signatures parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. resolution : int, default: `muspy.DEFAU...
Return time signatures parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- list of :class:`muspy.TimeSigna...
parse_time_signatures
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def parse_barlines_and_beats( stream: Stream, time_signatures: List[TimeSignature], resolution: int = DEFAULT_RESOLUTION, ) -> Tuple[List[Barline], List[Beat]]: """Return barlines and beats parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` S...
Return barlines and beats parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. time_signatures : list of :class:`muspy.TimeSignature` Time signature objects. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) ...
parse_barlines_and_beats
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def parse_notes_and_chords( stream: Stream, resolution: int = DEFAULT_RESOLUTION ) -> Tuple[List[Note], List[Chord]]: """Return notes and chords parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. resolution : int, default:...
Return notes and chords parsed from a music21 Stream object. Parameters ---------- stream : `music21.stream.Stream` Stream object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- list of :class:`muspy.Note` ...
parse_notes_and_chords
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def parse_track(part: Part, resolution: int = DEFAULT_RESOLUTION) -> Track: """Return track parsed from a music21 Part object. Parameters ---------- part : `music21.stream.Part` Part object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter n...
Return track parsed from a music21 Part object. Parameters ---------- part : `music21.stream.Part` Part object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- :class:`muspy.Track` Parsed track.
parse_track
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def from_music21_part( part: Part, resolution: int = DEFAULT_RESOLUTION ) -> Union[Track, List[Track]]: """Return a music21 Part object as Track object(s). Parameters ---------- part : `music21.stream.Part` Part object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24)...
Return a music21 Part object as Track object(s). Parameters ---------- part : `music21.stream.Part` Part object to parse. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- :class:`muspy.Track` or list of :class:`muspy.Tr...
from_music21_part
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def from_music21_score( score: Score, resolution: int = DEFAULT_RESOLUTION ) -> Music: """Return a music21 Stream object as a Music object. Parameters ---------- score : `music21.stream.Score` Score object to convert. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Ti...
Return a music21 Stream object as a Music object. Parameters ---------- score : `music21.stream.Score` Score object to convert. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- :class:`muspy.Music` Converted Mus...
from_music21_score
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def from_music21_opus( opus: Opus, resolution: int = DEFAULT_RESOLUTION ) -> List[Music]: """Return a music21 Opus object as a list of Music objects. Parameters ---------- opus : `music21.stream.Opus` Opus object to convert. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) ...
Return a music21 Opus object as a list of Music objects. Parameters ---------- opus : `music21.stream.Opus` Opus object to convert. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- :class:`muspy.Music` Converted...
from_music21_opus
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def from_music21( stream: Stream, resolution: int = DEFAULT_RESOLUTION ) -> Union[Music, List[Music], Track, List[Track]]: """Return a music21 Stream object as Music or Track object(s). Parameters ---------- stream : `music21.stream.Stream` Stream object to convert. resolution : int, de...
Return a music21 Stream object as Music or Track object(s). Parameters ---------- stream : `music21.stream.Stream` Stream object to convert. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. Returns ------- :class:`muspy.Music` or :clas...
from_music21
python
salu133445/muspy
muspy/inputs/music21.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/music21.py
MIT
def _get_required(element: Element, path: str) -> Element: """Return a required element; raise ValueError if not found.""" elem = element.find(path) if elem is None: raise MusicXMLError( f"Element `{path}` is required for an '{element.tag}' element." ) return elem
Return a required element; raise ValueError if not found.
_get_required
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def _get_required_attr(element: Element, attr: str) -> str: """Return a required attribute; raise MusicXMLError if not found.""" attribute = element.get(attr) if attribute is None: raise MusicXMLError( f"Attribute '{attr}' is required for an '{element.tag}' element." ) return...
Return a required attribute; raise MusicXMLError if not found.
_get_required_attr
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def _get_required_text( element: Element, path: str, remove_newlines: bool = False ) -> str: """Return a required text; raise MusicXMLError if not found.""" elem = _get_required(element, path) if elem.text is None: raise MusicXMLError( f"Text content '{path}' of an element '{element....
Return a required text; raise MusicXMLError if not found.
_get_required_text
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def parse_pitch_elem(elem: Element) -> Tuple[int, str]: """Return the pitch and pitch_str of a pitch element.""" step = _get_required_text(elem, "step") octave = int(_get_required_text(elem, "octave")) alter = int(_get_text(elem, "alter", 0)) pitch = 12 * (octave + 1) + NOTE_MAP[step] + alter if...
Return the pitch and pitch_str of a pitch element.
parse_pitch_elem
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def parse_unpitched_elem(elem: Element) -> Tuple[int, str]: """Return the pitch and pitch_str of an unpitched element.""" step = _get_required_text(elem, "display-step") octave = int(_get_required_text(elem, "display-octave")) pitch = 12 * (octave + 1) + NOTE_MAP[step] pitch_str = step + str(octave)...
Return the pitch and pitch_str of an unpitched element.
parse_unpitched_elem
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def get_measure_ordering(elem: Element) -> List[int]: """Return a list of measure indices parsed from a part element. This function returns the ordering of measures, considering all repeats and jumps. """ # Measure indices measure_indices = [] # Repeats is_after_repeat = False las...
Return a list of measure indices parsed from a part element. This function returns the ordering of measures, considering all repeats and jumps.
get_measure_ordering
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def get_beats( downbeat_times: List[int], time_signatures: List[TimeSignature], resolution: int = DEFAULT_RESOLUTION, is_sorted: bool = False, ) -> List[Beat]: """Return beats given downbeat positions and time signatures. Parameters ---------- downbeat_times : sequence of int Po...
Return beats given downbeat positions and time signatures. Parameters ---------- downbeat_times : sequence of int Positions of the downbeats. time_signatures : sequence of :class:`muspy.TimeSignature` Time signature objects. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24)...
get_beats
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def parse_meta_part_elem( part_elem: Element, resolution: int, measure_indices: List[int] ) -> Tuple[ List[Tempo], List[KeySignature], List[TimeSignature], List[Barline], List[Beat], ]: """Return data parsed from a meta part element. This function only parses the tempos, key and time si...
Return data parsed from a meta part element. This function only parses the tempos, key and time signatures. Use `parse_part_elem` to parse the notes and lyrics.
parse_meta_part_elem
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def parse_part_elem( part_elem: Element, resolution: int, instrument_info: dict, measure_indices: List[int], ) -> Tuple[Dict[str, List[Note]], List[Lyric]]: """Return notes and lyrics parsed from a part element. This function only parses the notes and lyrics. Use `parse_meta_part_elem` to p...
Return notes and lyrics parsed from a part element. This function only parses the notes and lyrics. Use `parse_meta_part_elem` to parse the tempos, key and time signatures.
parse_part_elem
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def parse_metadata(root: Element) -> Metadata: """Return a Metadata object parsed from a MusicXML file.""" # Title is usually stored in movement-title. See # https://www.musicxml.com/tutorial/file-structure/score-header-entity/ title = _get_text(root, "movement-title", remove_newlines=True) if not t...
Return a Metadata object parsed from a MusicXML file.
parse_metadata
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def _get_root(path: Union[str, Path], compressed: bool = None): """Return the root of the element tree.""" if compressed is None: compressed = str(path).endswith(".mxl") if not compressed: tree = ET.parse(str(path)) return tree.getroot() # Find out the main MusicXML file in the...
Return the root of the element tree.
_get_root
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def read_musicxml( path: Union[str, Path], resolution: int = None, compressed: bool = None ) -> Music: """Read a MusicXML file into a Music object. Parameters ---------- path : str or Path Path to the MusicXML file to read. resolution : int, optional Time steps per quarter note....
Read a MusicXML file into a Music object. Parameters ---------- path : str or Path Path to the MusicXML file to read. resolution : int, optional Time steps per quarter note. Defaults to the least common multiple of all divisions. compressed : bool, optional Whether i...
read_musicxml
python
salu133445/muspy
muspy/inputs/musicxml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/musicxml.py
MIT
def from_note_representation( array: ndarray, resolution: int = DEFAULT_RESOLUTION, program: int = 0, is_drum: bool = False, use_start_end: bool = False, encode_velocity: bool = True, default_velocity: int = DEFAULT_VELOCITY, ) -> Music: """Decode note-based representation into a Music o...
Decode note-based representation into a Music object. Parameters ---------- array : ndarray Array in note-based representation to decode. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. program : int, default: 0 (Acoustic Grand Piano) ...
from_note_representation
python
salu133445/muspy
muspy/inputs/note.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/note.py
MIT
def from_pypianoroll_track( track: PypianorollTrack, default_velocity: int = DEFAULT_VELOCITY ) -> Track: """Return a Pypianoroll Track object as a Track object. Parameters ---------- track : :class:`pypianoroll.Track` Pypianoroll Track object to convert. default_velocity : int, default...
Return a Pypianoroll Track object as a Track object. Parameters ---------- track : :class:`pypianoroll.Track` Pypianoroll Track object to convert. default_velocity : int, default: `muspy.DEFAULT_VELOCITY` (64) Default velocity value to use when decoding. Returns ------- :cl...
from_pypianoroll_track
python
salu133445/muspy
muspy/inputs/pianoroll.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/pianoroll.py
MIT
def from_pypianoroll( multitrack: Multitrack, default_velocity: int = DEFAULT_VELOCITY ) -> Music: """Return a Pypianoroll Multitrack object as a Music object. Parameters ---------- multitrack : :class:`pypianoroll.Multitrack` Pypianoroll Multitrack object to convert. default_velocity :...
Return a Pypianoroll Multitrack object as a Music object. Parameters ---------- multitrack : :class:`pypianoroll.Multitrack` Pypianoroll Multitrack object to convert. default_velocity : int, default: `muspy.DEFAULT_VELOCITY` (64) Default velocity value to use when decoding. Returns...
from_pypianoroll
python
salu133445/muspy
muspy/inputs/pianoroll.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/pianoroll.py
MIT
def from_pianoroll_representation( array: ndarray, resolution: int = DEFAULT_RESOLUTION, program: int = 0, is_drum: bool = False, encode_velocity: bool = True, default_velocity: int = DEFAULT_VELOCITY, ) -> Music: """Decode piano-roll representation into a Music object. Parameters -...
Decode piano-roll representation into a Music object. Parameters ---------- array : ndarray Array in piano-roll representation to decode. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. program : int, default: 0 (Acoustic Grand Piano) ...
from_pianoroll_representation
python
salu133445/muspy
muspy/inputs/pianoroll.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/pianoroll.py
MIT
def from_pitch_representation( array: ndarray, resolution: int = DEFAULT_RESOLUTION, program: int = 0, is_drum: bool = False, use_hold_state: bool = False, default_velocity: int = DEFAULT_VELOCITY, ) -> Music: """Decode pitch-based representation into a Music object. Parameters ----...
Decode pitch-based representation into a Music object. Parameters ---------- array : ndarray Array in pitch-based representation to decode. resolution : int, default: `muspy.DEFAULT_RESOLUTION` (24) Time steps per quarter note. program : int, default: 0 (Acoustic Grand Piano) ...
from_pitch_representation
python
salu133445/muspy
muspy/inputs/pitch.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/pitch.py
MIT
def load(path: Union[str, Path, TextIO], kind: str = None, **kwargs) -> Music: """Load a JSON or a YAML file into a Music object. This is a wrapper function for :func:`muspy.load_json` and :func:`muspy.load_yaml`. Parameters ---------- path : str, Path or TextIO Path to the file or the...
Load a JSON or a YAML file into a Music object. This is a wrapper function for :func:`muspy.load_json` and :func:`muspy.load_yaml`. Parameters ---------- path : str, Path or TextIO Path to the file or the file to to load. kind : {'json', 'yaml'}, optional Format to save. Defaul...
load
python
salu133445/muspy
muspy/inputs/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/wrappers.py
MIT
def read( path: Union[str, Path], kind: str = None, **kwargs ) -> Union[Music, List[Music]]: """Read a MIDI/MusicXML/ABC file into a Music object. Parameters ---------- path : str or Path Path to the file to read. kind : {'midi', 'musicxml', 'abc'}, optional Format to save. Defa...
Read a MIDI/MusicXML/ABC file into a Music object. Parameters ---------- path : str or Path Path to the file to read. kind : {'midi', 'musicxml', 'abc'}, optional Format to save. Defaults to infer from the extension. **kwargs Keyword arguments to pass to :func:`muspy.read_mi...
read
python
salu133445/muspy
muspy/inputs/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/wrappers.py
MIT
def from_object( obj: Union[Stream, MidiFile, PrettyMIDI, Multitrack], **kwargs ) -> Union[Music, List[Music], Track, List[Track]]: """Return an outside object as a Music object. Parameters ---------- obj Object to convert. Supported objects are `music21.Stream`, :class:`mido.MidiTr...
Return an outside object as a Music object. Parameters ---------- obj Object to convert. Supported objects are `music21.Stream`, :class:`mido.MidiTrack`, :class:`pretty_midi.PrettyMIDI`, and :class:`pypianoroll.Multitrack` objects. **kwargs Keyword arguments to pass to :...
from_object
python
salu133445/muspy
muspy/inputs/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/wrappers.py
MIT
def from_representation(array: ndarray, kind: str, **kwargs) -> Music: """Update with the given representation. Parameters ---------- array : :class:`numpy.ndarray` Array in a supported representation. kind : str, {'pitch', 'pianoroll', 'event', 'note'} Data representation. **kw...
Update with the given representation. Parameters ---------- array : :class:`numpy.ndarray` Array in a supported representation. kind : str, {'pitch', 'pianoroll', 'event', 'note'} Data representation. **kwargs Keyword arguments to pass to :func:`muspy.from_pitch_repr...
from_representation
python
salu133445/muspy
muspy/inputs/wrappers.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/wrappers.py
MIT
def load_yaml( path: Union[str, Path, TextIO], compressed: bool = None ) -> Music: """Load a YAML file into a Music object. Parameters ---------- path : str, Path or TextIO Path to the file or the file to load. compressed : bool, optional Whether the file is a compressed YAML fi...
Load a YAML file into a Music object. Parameters ---------- path : str, Path or TextIO Path to the file or the file to load. compressed : bool, optional Whether the file is a compressed YAML file (`.yaml.gz`). Has no effect when `path` is a file object. Defaults to infer from th...
load_yaml
python
salu133445/muspy
muspy/inputs/yaml.py
https://github.com/salu133445/muspy/blob/master/muspy/inputs/yaml.py
MIT
def n_pitches_used(music: Music) -> int: """Return the number of unique pitches used. Drum tracks are ignored. Parameters ---------- music : :class:`muspy.Music` Music object to evaluate. Returns ------- int Number of unique pitch used. See Also -------- :...
Return the number of unique pitches used. Drum tracks are ignored. Parameters ---------- music : :class:`muspy.Music` Music object to evaluate. Returns ------- int Number of unique pitch used. See Also -------- :func:`muspy.n_pitch_class_used` : Comput...
n_pitches_used
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def n_pitch_classes_used(music: Music) -> int: """Return the number of unique pitch classes used. Drum tracks are ignored. Parameters ---------- music : :class:`muspy.Music` Music object to evaluate. Returns ------- int Number of unique pitch classes used. See Als...
Return the number of unique pitch classes used. Drum tracks are ignored. Parameters ---------- music : :class:`muspy.Music` Music object to evaluate. Returns ------- int Number of unique pitch classes used. See Also -------- :func:`muspy.n_pitches_used` : ...
n_pitch_classes_used
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def pitch_range(music: Music) -> int: """Return the pitch range. Drum tracks are ignored. Return zero if no note is found. Parameters ---------- music : :class:`muspy.Music` Music object to evaluate. Returns ------- int Pitch range. """ if not music.tracks: ...
Return the pitch range. Drum tracks are ignored. Return zero if no note is found. Parameters ---------- music : :class:`muspy.Music` Music object to evaluate. Returns ------- int Pitch range.
pitch_range
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def empty_measure_rate(music: Music, measure_resolution: int) -> float: r"""Return the ratio of empty measures. The empty-measure rate is defined as the ratio of the number of empty measures (where no note is played) to the total number of measures. Note that this metric only works for songs with a con...
Return the ratio of empty measures. The empty-measure rate is defined as the ratio of the number of empty measures (where no note is played) to the total number of measures. Note that this metric only works for songs with a constant time signature. Return NaN if song length is zero. This metric is ...
empty_measure_rate
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def polyphony(music: Music) -> float: r"""Return the average number of pitches being played concurrently. The polyphony is defined as the average number of pitches being played at the same time, evaluated only at time steps where at least one pitch is on. Drum tracks are ignored. Return NaN if no note ...
Return the average number of pitches being played concurrently. The polyphony is defined as the average number of pitches being played at the same time, evaluated only at time steps where at least one pitch is on. Drum tracks are ignored. Return NaN if no note is found. .. math:: polyphony...
polyphony
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def polyphony_rate(music: Music, threshold: int = 2) -> float: r"""Return the ratio of time steps where multiple pitches are on. The polyphony rate is defined as the ratio of the number of time steps where multiple pitches are on to the total number of time steps. Drum tracks are ignored. Return NaN if...
Return the ratio of time steps where multiple pitches are on. The polyphony rate is defined as the ratio of the number of time steps where multiple pitches are on to the total number of time steps. Drum tracks are ignored. Return NaN if song length is zero. This metric is used in [1], where it is calle...
polyphony_rate
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def _get_scale(root: int, mode: str) -> ndarray: """Return the scale mask for a specific root.""" if mode == "major": c_scale = np.array([1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1], bool) elif mode == "minor": c_scale = np.array([1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0], bool) else: raise Va...
Return the scale mask for a specific root.
_get_scale
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def pitch_in_scale_rate(music: Music, root: int, mode: str) -> float: r"""Return the ratio of pitches in a certain musical scale. The pitch-in-scale rate is defined as the ratio of the number of notes in a certain scale to the total number of notes. Drum tracks are ignored. Return NaN if no note is fou...
Return the ratio of pitches in a certain musical scale. The pitch-in-scale rate is defined as the ratio of the number of notes in a certain scale to the total number of notes. Drum tracks are ignored. Return NaN if no note is found. This metric is used in [1]. .. math:: pitch\_in\_scale\_r...
pitch_in_scale_rate
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def scale_consistency(music: Music) -> float: r"""Return the largest pitch-in-scale rate. The scale consistency is defined as the largest pitch-in-scale rate over all major and minor scales. Drum tracks are ignored. Return NaN if no note is found. This metric is used in [1]. .. math:: scal...
Return the largest pitch-in-scale rate. The scale consistency is defined as the largest pitch-in-scale rate over all major and minor scales. Drum tracks are ignored. Return NaN if no note is found. This metric is used in [1]. .. math:: scale\_consistency = \max_{root, mode}{ pitch\...
scale_consistency
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def _get_drum_pattern(res: int, meter: str) -> ndarray: """Return the drum pattern mask of a specific meter.""" drum_pattern = np.zeros(res, dtype=bool) drum_pattern[0] = 1 if meter == "duple": if res % 4 == 0: drum_pattern[:: (res // 4)] = 1 if res % 2 == 0: drum...
Return the drum pattern mask of a specific meter.
_get_drum_pattern
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def drum_in_pattern_rate(music: Music, meter: str) -> float: r"""Return the ratio of drum notes in a certain drum pattern. The drum-in-pattern rate is defined as the ratio of the number of notes in a certain scale to the total number of notes. Only drum tracks are considered. Return NaN if no drum note...
Return the ratio of drum notes in a certain drum pattern. The drum-in-pattern rate is defined as the ratio of the number of notes in a certain scale to the total number of notes. Only drum tracks are considered. Return NaN if no drum note is found. This metric is used in [1]. .. math:: dru...
drum_in_pattern_rate
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def drum_pattern_consistency(music: Music) -> float: r"""Return the largest drum-in-pattern rate. The drum pattern consistency is defined as the largest drum-in-pattern rate over duple and triple meters. Only drum tracks are considered. Return NaN if no drum note is found. .. math:: drum\_...
Return the largest drum-in-pattern rate. The drum pattern consistency is defined as the largest drum-in-pattern rate over duple and triple meters. Only drum tracks are considered. Return NaN if no drum note is found. .. math:: drum\_pattern\_consistency = \max_{meter}{ drum\_in\_pa...
drum_pattern_consistency
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def pitch_entropy(music: Music) -> float: r"""Return the entropy of the normalized note pitch histogram. The pitch entropy is defined as the Shannon entropy of the normalized note pitch histogram. Drum tracks are ignored. Return NaN if no note is found. .. math:: pitch\_entropy = -\sum_{i ...
Return the entropy of the normalized note pitch histogram. The pitch entropy is defined as the Shannon entropy of the normalized note pitch histogram. Drum tracks are ignored. Return NaN if no note is found. .. math:: pitch\_entropy = -\sum_{i = 0}^{127}{ P(pitch=i) \log_2 P(pitch=...
pitch_entropy
python
salu133445/muspy
muspy/metrics/metrics.py
https://github.com/salu133445/muspy/blob/master/muspy/metrics/metrics.py
MIT
def __eq__(self, other: "_ABCTrackElement"): """ Check if `other` represents the same set of musical data, possibly occuring in a different moment of music track """ try: temp_time = getattr(other.represented, "time") setattr( other.represe...
Check if `other` represents the same set of musical data, possibly occuring in a different moment of music track
__eq__
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def __lt__(self, other: "_ABCTrackElement"): """ Check if element should be written in ABC notation before `other`. """ if self.represented < other.represented: return True if ( getattr(self.represented, "time") == getattr(other.represented, "t...
Check if element should be written in ABC notation before `other`.
__lt__
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def __gt__(self, other: "_ABCTrackElement"): """ Check if element should be written in ABC notation after `other`. """ if self.represented > other.represented: return True if ( getattr(self.represented, "time") == getattr(other.represented, "ti...
Check if element should be written in ABC notation after `other`.
__gt__
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def generate_header(music: "Music") -> List[str]: """Generate ABC header from Music object. Parameters ---------- music : :class:`muspy.Music` Music object to generate ABC header. """ header_lines = ["X: 1"] # set filename as title if no other title title = music.metadata.title...
Generate ABC header from Music object. Parameters ---------- music : :class:`muspy.Music` Music object to generate ABC header.
generate_header
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def remove_consecutive_repeats(list: list): """ Creates a copy of `list` with consecutive repeats of values skipped. """ cleared = list[:1] for element in list[1:]: if element == cleared[-1]: continue cleared.append(element) return cleared
Creates a copy of `list` with consecutive repeats of values skipped.
remove_consecutive_repeats
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def _enclose(track: "list[_ABCBarline|_ABCNote]"): """ Ensure that `track` is enclosed by barlines in order to make it possible to mark repetitions involving either first or last bar of track. """ if len(track) > 0: if type(track[0]) != _ABCBarline: ...
Ensure that `track` is enclosed by barlines in order to make it possible to mark repetitions involving either first or last bar of track.
_enclose
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def _disassemble(self): """ Break track into sequences of notes and separating them barlines. Prepare a counter for number of occurences for each sequence of notes. """ last_barline_index = 0 enclosed = self._enclose(self.track) self._sections_borders = [enclosed[...
Break track into sequences of notes and separating them barlines. Prepare a counter for number of occurences for each sequence of notes.
_disassemble
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def _assemble(self): """ Reassemble track from sections and separating them barlines. Mark repetitions of sections based on corresponding counters. """ track = [self._sections_borders[0]] for occurences, section, closing_barline in zip( self._sections_occurenc...
Reassemble track from sections and separating them barlines. Mark repetitions of sections based on corresponding counters.
_assemble
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def _get_section(self, index: int, n: int): """ Get section of track starting with subsection at `index` and containing `n` next subsections. Barlines separating subsections are incorporated into retrieved section. """ section = [*self._sections[index]] for i in r...
Get section of track starting with subsection at `index` and containing `n` next subsections. Barlines separating subsections are incorporated into retrieved section.
_get_section
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def _find_repeat(self, repeat_length: int): """ Looks for the first repeat of given length in track Parameters ---------- repeat_length : int number of sections to include in repeat Returns ------- tuple[int, int] Index of section...
Looks for the first repeat of given length in track Parameters ---------- repeat_length : int number of sections to include in repeat Returns ------- tuple[int, int] Index of section that starts repeating fragment and number of ...
_find_repeat
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def _remove_repeat( self, index: int, repeat_length: int, repeat_count: int ): """ Replace a block of `repeat_count` repeats each containing `repeat_length` sections starting at 'index' with concatenated sections from original and mark its occurence count. """ ...
Replace a block of `repeat_count` repeats each containing `repeat_length` sections starting at 'index' with concatenated sections from original and mark its occurence count.
_remove_repeat
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def _compact(self): """ Detect consecutive repetitions of track sections. Remove repeated sections and mark occurence counts of originals. """ repeat_length = floor(len(self._sections) / 2) while repeat_length > 0: start, repeat_count = self._find_repeat(repea...
Detect consecutive repetitions of track sections. Remove repeated sections and mark occurence counts of originals.
_compact
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT
def compact(self): """ Detect repetitions in track contained by object. Mark repeats of sections of track on barlines enclosing them and remove repeated elements. """ if len(self.track) == 0: return self.track self._disassemble() self._compact(...
Detect repetitions in track contained by object. Mark repeats of sections of track on barlines enclosing them and remove repeated elements.
compact
python
salu133445/muspy
muspy/outputs/abc.py
https://github.com/salu133445/muspy/blob/master/muspy/outputs/abc.py
MIT