### Install Partitura Source: https://context7.com/cpjku/partitura/llms.txt Install the Partitura package using pip. Optional extras can be installed for extended functionality. ```bash pip install partitura # Optional extras for audio synthesis, ML tokenizers, and MuseScore backend: pip install "partitura[all]" ``` -------------------------------- ### Install Partitura and Tutorial Modules Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Install the partitura package and clone the tutorial repository. This is necessary for accessing helper modules if running in Google Colab. ```python # Install partitura ! pip install partitura # To be able to access helper modules in the repo for this tutorial # (not necessary if the jupyter notebook is run locally instead of google colab) !git clone https://github.com/CPJKU/partitura_tutorial.git import warnings warnings.filterwarnings('ignore') import sys, os sys.path.insert(0, os.path.join(os.getcwd(), "partitura_tutorial", "content")) sys.path.insert(0,'/content/partitura_tutorial/content') ``` -------------------------------- ### Install Partitura via Pip Source: https://github.com/cpjku/partitura/blob/main/README.md Install the latest release of the Partitura package and its dependencies using pip. ```shell pip install partitura ``` -------------------------------- ### Load Music via MuseScore Backend Source: https://context7.com/cpjku/partitura/llms.txt Imports music files in any format supported by MuseScore (e.g., .mscz, .gp5) by utilizing a local MuseScore 3/4 installation. Requires MuseScore to be installed. ```python import partitura as pt # Requires MuseScore to be installed score = pt.load_via_musescore("my_piece.mscz") score_gp = pt.load_via_musescore("my_piece.gp5") part = score.parts[0] print(part.note_array()["pitch"][:5]) ``` -------------------------------- ### Pretty Print Part (Commented Out) Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb A commented-out example showing how to print a formatted representation of the part, useful for debugging. ```python # print(part.pretty()) ``` -------------------------------- ### Load via MuseScore Backend Source: https://context7.com/cpjku/partitura/llms.txt Import music files using a local MuseScore installation, supporting various formats. ```APIDOC ## pt.load_via_musescore ### Description Uses a local MuseScore 3/4 installation to import any format MuseScore supports (Guitar Pro, MuseData, Capella, etc.). ### Usage ```python import partitura as pt # Requires MuseScore to be installed score = pt.load_via_musescore("my_piece.mscz") score_gp = pt.load_via_musescore("my_piece.gp5") part = score.parts[0] print(part.note_array()["pitch"][:5]) ``` ``` -------------------------------- ### Save Score as MusicXML (Commented Out) Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb A commented-out example showing how to save the generated part as a MusicXML file, which is a standard format for music notation. ```python # pt.save_musicxml(p, "CatScore.xml") ``` -------------------------------- ### Save Score as MIDI (Commented Out) Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb A commented-out example demonstrating how to save the generated part as a MIDI file. `part_voice_assign_mode=2` is used for voice assignment. ```python # pt.save_score_midi(p, "CatPerformance.mid", part_voice_assign_mode=2) ``` -------------------------------- ### Generate Random Durations and Pitches Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Initializes a `Part` and generates random durations and pitches for a sequence of notes. This sets up the data for the 'Cats on Keyboards' example. ```python l = 200 p = pt.score.Part('CoK', 'Cat on Keyboard', quarter_duration=8) dur = np.random.randint(1,20, size=(4,l+1)) ons = np.cumsum(dur, axis = 1) pitch = np.row_stack((np.random.randint(20,40, size=(1,l+1)), np.random.randint(60,80, size=(1,l+1)), np.random.randint(40,60, size=(1,l+1)), np.random.randint(40,60, size=(1,l+1)) )) ``` -------------------------------- ### Display Selected Fields from Extended Note Array Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Select and display specific fields from an extended note array to examine the included information. This example shows the first 10 notes with their ID, pitch spelling, key signature, and time signature details. ```python print(extended_score_note_array[['id', 'step', 'alter', 'octave', 'ks_fifths', 'ks_mode', #'is_downbeat' ]][:10]) ``` -------------------------------- ### Add a New Note to a Part Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Create a new note object and add it to a Partitura 'Part' by specifying its start and end times in 'divs'. ```python a_new_note = pt.score.Note(id='n04', step='A', octave=4, voice=1) part.add(a_new_note, start=3, end=15) ``` -------------------------------- ### PerformedPart.note_array() Source: https://context7.com/cpjku/partitura/llms.txt Get a structured array of performed notes with onset and offset times in seconds. ```APIDOC ## PerformedPart.note_array() ### Description Returns a structured array for performed notes with onset/offset in seconds. ### Usage ```python import partitura as pt import numpy as np perf = pt.load_performance(pt.EXAMPLE_MIDI) ppart = perf[0] pna = ppart.note_array() print(pna.dtype.names) print(np.sort(pna["pitch"])) print(pna["onset_sec"]) print(pna["velocity"]) ``` ``` -------------------------------- ### Render Score Part to Image Source: https://github.com/cpjku/partitura/blob/main/README.md Render a score part to an image if LilyPond or MuseScore are installed. This command displays the visual representation of the musical part. ```python pt.render(part) ``` -------------------------------- ### Extract Note Information to Numpy Array Source: https://github.com/cpjku/partitura/blob/main/README.md Store the start time, end time, and MIDI pitch of notes in a numpy array. Times are in divisions units. ```python import numpy as np pianoroll = np.array([(n.start.t, n.end.t, n.midi_pitch) for n in part.notes]) print(pianoroll) ``` -------------------------------- ### Get Note Array from Part Object Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Loads a MusicXML score and extracts its note array. This is useful for analyzing score-level musical information. ```python # Note array from a score # Path to the MusicXML file score_fn = os.path.join(MUSICXML_DIR, 'Chopin_op38.musicxml') # Load the score into a `Part` object score_part = pt.load_musicxml(score_fn) # Get note array. score_note_array = score_part.note_array() ``` -------------------------------- ### Get Structured Numpy Note Array Source: https://context7.com/cpjku/partitura/llms.txt Retrieves a structured numpy array of notes with onset/duration in various time units, pitch, and voice. Can include additional fields like pitch spelling, key/time signatures, and metrical position. ```python import partitura as pt part = pt.load_score_as_part(pt.EXAMPLE_MUSICXML) # Basic note array na = part.note_array() # With extra fields na_full = part.note_array( include_pitch_spelling=True, # adds step, alter, octave include_key_signature=True, # adds ks_fifths, ks_mode include_time_signature=True, # adds ts_beats, ts_beat_type include_metrical_position=True,# adds is_downbeat, rel_onset_div, etc. include_grace_notes=True, ) print(na_full.dtype.names) # (..., 'step', 'alter', 'octave', 'ks_fifths', 'ks_mode', # 'ts_beats', 'ts_beat_type', ...) # Filter notes by voice import numpy as np voice1 = na[na["voice"] == 1] print(voice1["pitch"]) # [69] ``` -------------------------------- ### Get Note Array from PerformedPart Object Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Loads a MIDI performance and extracts its note array. This is useful for analyzing performance-level musical information, including timing and dynamics. ```python # Note array from a performance # Path to the MIDI file performance_fn = os.path.join(MIDI_DIR, 'Chopin_op38_p01.mid') # Loading the file to a PerformedPart performance_part = pt.load_performance_midi(performance_fn) # Get note array! performance_note_array = performance_part.note_array() ``` -------------------------------- ### Initialize Dataset Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Set up the dataset for the tutorial by initializing it. This involves defining directories for MusicXML, MIDI, and Match files. ```python # setup the dataset from load_data import init_dataset DATASET_DIR = init_dataset() MUSICXML_DIR = os.path.join(DATASET_DIR, 'musicxml') MIDI_DIR = os.path.join(DATASET_DIR, 'midi') MATCH_DIR = os.path.join(DATASET_DIR, 'match') ``` -------------------------------- ### Load and Print Part Object Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Load a MusicXML file into a Partitura 'Part' object and print its pretty representation. This demonstrates the basic structure of a score in Partitura. ```python path_to_musicxml = pt.EXAMPLE_MUSICXML part = pt.load_musicxml(path_to_musicxml)[0] print(part.pretty()) ``` -------------------------------- ### Compute Feature-Rich Note Arrays Source: https://context7.com/cpjku/partitura/llms.txt Uses `compute_note_array` for a consistent interface to `Part.note_array()` or `full_note_array` to get the maximum set of fields. ```python import partitura as pt from partitura.musicanalysis import compute_note_array, full_note_array score = pt.load_score(pt.EXAMPLE_MUSICXML) # Selective fields na = compute_note_array( score, include_pitch_spelling=True, include_key_signature=True, include_time_signature=True, ) # All available fields na_full = full_note_array(score) print(na_full.dtype.names) ``` -------------------------------- ### Get Matched Note Indices Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Retrieves indices for score and performance notes that have a direct match in the alignment. This is a prerequisite for comparing matched notes. ```python snote_array = score_part.note_array() pnote_array = performed_part.note_array() matched_note_idxs = pt.utils.music.get_matched_notes(snote_array, pnote_array, alignment) ``` -------------------------------- ### Clone Partitura Repository Source: https://github.com/cpjku/partitura/blob/main/CONTRIBUTING.md Clone the forked Partitura repository to your local machine and navigate into the project directory. ```shell git clone https://github.com/YourUsername/partitura.git cd partitura ``` -------------------------------- ### Load Performance from MIDI or Match File Source: https://context7.com/cpjku/partitura/llms.txt Load performed music data from MIDI or `.match` files into a `Performance` object. Onset and offset times are provided in seconds. The `note_array` for performance data includes fields like pitch, velocity, and timing. ```python import partitura as pt perf = pt.load_performance(pt.EXAMPLE_MIDI, default_bpm=120, first_note_at_zero=True) ppart = perf[0] # first PerformedPart # Access performed notes (timing in seconds) for note in ppart.notes[:3]: print(note["midi_pitch"], note["note_on"], note["note_off"]) # 69 0.0 2.0 # 72 1.0 2.0 # 76 1.0 2.0 # note_array for the performance pna = ppart.note_array() print(pna.dtype.names) # ('onset_sec', 'duration_sec', 'pitch', 'velocity', 'track', 'channel', 'id') ``` -------------------------------- ### Build and Save a Minimal Note Array Source: https://context7.com/cpjku/partitura/llms.txt Constructs a basic note array and converts it into a Score object, then saves it as a MusicXML file. Requires the note_array_to_score function. ```python import partitura as pt import numpy as np na = np.array( [(0.0, 1.0, 60, 1, "n0"), (1.0, 1.0, 62, 1, "n1"), (2.0, 2.0, 64, 1, "n2")], dtype=[("onset_beat", "f4"), ("duration_beat", "f4"), ("pitch", "i4"), ("voice", "i4"), ("id", "U8")], ) part = pt.note_array_to_score( note_array=na, key_sigs=[(0.0, "C", 8.0)], time_sigs=[(0.0, 4, 4, 8.0)], part_id="P1", part_name="Piano", ) print(part.pretty()) pt.save_musicxml(part, "reconstructed.musicxml") ``` -------------------------------- ### Print First 5 Notes from Performance Note Array Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Displays the first 5 notes from a performance's note array. This helps in verifying the extracted performance data, including timing and velocity. ```python print(performance_note_array[:5]) ``` -------------------------------- ### pt.save_wav Source: https://context7.com/cpjku/partitura/llms.txt Synthesizes a score or part to a WAV file using built-in additive synthesis. An optional `save_wav_fluidsynth` function is available if pyfluidsynth and a soundfont are installed. ```APIDOC ## `pt.save_wav` — Export score to WAV (additive synthesis) Synthesizes a score or part to a WAV file using built-in additive synthesis (no external dependencies). ```python import partitura as pt score = pt.load_score(pt.EXAMPLE_MUSICXML) pt.save_wav(score, "output.wav") # With FluidSynth (requires pyfluidsynth and a soundfont) # pt.save_wav_fluidsynth(score, "output_fs.wav", soundfont="path/to/font.sf2") ``` ``` -------------------------------- ### Import Core Partitura Libraries Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Import the essential libraries for working with Partitura, including glob for file searching, numpy for numerical operations, and matplotlib for plotting. ```python import glob import partitura as pt import numpy as np import matplotlib.pyplot as plt ``` -------------------------------- ### Import MusicXML Score Source: https://github.com/cpjku/partitura/blob/main/README.md Load a musical score from a MusicXML file. Ensure the partitura library is imported. ```python import partitura as pt my_xml_file = pt.EXAMPLE_MUSICXML score = pt.load_musicxml(my_xml_file) ``` -------------------------------- ### Save Score Part to MIDI and MusicXML Source: https://github.com/cpjku/partitura/blob/main/README.md Save a score part to a MIDI file or a MusicXML file using the pt.save_score_midi function. The example shows saving to MIDI. ```python # Save Score MIDI to file. pt.save_score_midi(part, 'mypart.mid') ``` -------------------------------- ### Load and Save MusicXML Files Source: https://context7.com/cpjku/partitura/llms.txt Demonstrates loading MusicXML files into a Score object and saving a Score object to MusicXML format. Handles compressed .mxl files and provides a shortcut for direct note array extraction. ```python import partitura as pt # Load (also handles .mxl compressed files) score = pt.load_musicxml(pt.EXAMPLE_MUSICXML, force_note_ids="keep") # Note array shortcut na = pt.musicxml_to_notearray(pt.EXAMPLE_MUSICXML) print(na["pitch"]) # Export with work metadata pt.save_musicxml(score, "with_meta.musicxml") ``` -------------------------------- ### Import Kern Score Source: https://github.com/cpjku/partitura/blob/main/README.md Load a musical score from a Kern file. The partitura library must be imported first. ```python import partitura as pt my_kern_file = pt.EXAMPLE_KERN score = pt.load_kern(my_kern_file) ``` -------------------------------- ### Get Note Array from Performed Part Source: https://context7.com/cpjku/partitura/llms.txt Retrieves a structured NumPy array for performed notes, containing onset and offset times in seconds, pitch, velocity, and other performance-specific details. Useful for analyzing performance data. ```python import partitura as pt import numpy as np perf = pt.load_performance(pt.EXAMPLE_MIDI) ppart = perf[0] pna = ppart.note_array() print(pna.dtype.names) print(np.sort(pna["pitch"])) print(pna["onset_sec"]) print(pna["velocity"]) ``` -------------------------------- ### Import Score from Any Format Source: https://github.com/cpjku/partitura/blob/main/README.md Import a musical score from any supported format (MusicXML, Kern, MEI) using a generic load function. The partitura library must be imported. ```python import partitura as pt any_score_format_path = pt.EXAMPLE_MUSICXML score = pt.load_score(any_score_format_path) ``` -------------------------------- ### Get Active Time Signature Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Retrieve the currently active time signature at a specific score position using the part's time signature map. This accounts for changes in time signature throughout the score. ```python part.time_signature_map(part.notes[0].end.t) ``` -------------------------------- ### Match File I/O Source: https://context7.com/cpjku/partitura/llms.txt Save and load score-performance alignments using the Vienna Matchfile format and Nakamura's alignment tools. ```APIDOC ## pt.save_match / pt.load_nakamuramatch / pt.load_nakamuracorresp ### Description Save score–performance alignments in the Vienna Matchfile format; load alignments from Nakamura's music alignment tool. ### Usage ```python import partitura as pt from partitura.io import load_match from partitura.io.importnakamura import load_nakamuramatch, load_nakamuracorresp # Save alignment perf, alignment, score = load_match("existing.match", create_score=True) pt.save_match( score=score, performance=perf, alignment=alignment, out="new_alignment.match", ) # Load Nakamura match/corresp files perf_nk, alignment_nk = load_nakamuramatch("Shi05_infer_match.txt") perf_nc, alignment_nc = load_nakamuracorresp("Shi05_infer_corresp.txt") print(alignment_nk[0]) ``` ``` -------------------------------- ### Load Score and Performance MIDI Files Source: https://context7.com/cpjku/partitura/llms.txt Provides separate loaders for score-structured MIDI (quantized onsets) and performance MIDI (onsets in seconds). Score MIDI returns a Score object, while Performance MIDI returns a Performance object. ```python import partitura as pt # Score MIDI: onsets are quantized; returns a Score score = pt.load_score_midi(pt.EXAMPLE_MIDI, assign_note_ids=True) print(score.parts[0].note_array()["onset_quarter"]) # Performance MIDI: onsets in seconds; returns a Performance perf = pt.load_performance_midi( pt.EXAMPLE_MIDI, default_bpm=120, merge_tracks=False, ) ppart = perf[0] print(ppart.notes[0]) ``` -------------------------------- ### Load Humdrum, MEI, and DCML Files Source: https://context7.com/cpjku/partitura/llms.txt Loads music data from Humdrum **kern, MEI, and DCML harmonic annotation files. DCML loader specifically returns a Score with Harmony objects. ```python import partitura as pt from partitura.io.importdcml import load_dcml # Humdrum **kern score_kern = pt.load_kern(pt.EXAMPLE_KERN) print(score_kern.parts[0].note_array()["pitch"]) # MEI score_mei = pt.load_mei(pt.EXAMPLE_MEI) # DCML harmonic annotations (returns a Score with Harmony objects) score_dcml = load_dcml("path/to/annotations.tsv") part = score_dcml.parts[0] print(part.harmony) ``` -------------------------------- ### Compute Note-Level Features with Partitura Source: https://context7.com/cpjku/partitura/llms.txt Use `make_note_features` to compute a matrix of named feature functions over notes. Pass 'all' to compute all available features. The `force_fixed_size` option ensures a consistent output shape for batch processing. ```python import partitura as pt from partitura.musicanalysis import make_note_features, list_note_feats_functions score = pt.load_score(pt.EXAMPLE_MUSICXML) # List available feature function names print(list_note_feats_functions()) # ['articulation_feature', 'duration_feature', 'fermata_feature', # 'grace_feature', 'loudness_direction_feature', 'metrical_feature', # 'ornament_feature', 'pitch_feature', 'slur_feature', 'staff_feature', # 'time_signature_feature', 'vertical_neighbor_feature', ...] # Compute selected features features, names = make_note_features( score, feature_functions=["pitch_feature", "metrical_feature", "duration_feature"], ) print(features.shape) # (3, ) print(names[:5]) # ['pitch_feature.pitch', 'pitch_feature.octave', ...] # Compute ALL features features_all, names_all = make_note_features(score, feature_functions="all") print(features_all.shape) # (num_notes, total_descriptors) # Fixed-size (safe for batching across pieces) features_fixed, names_fixed = make_note_features( score, feature_functions=["pitch_feature", "duration_feature"], force_fixed_size=True, ) ``` -------------------------------- ### Load and Print Score Pitches Source: https://context7.com/cpjku/partitura/llms.txt Loads a MusicXML score and prints the pitches of the first part. ```python score2 = pt.load_score("output.musicxml") print(score2.parts[0].note_array()["pitch"]) # [69 72 76] ``` -------------------------------- ### Load MusicXML Score Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Loads a MusicXML file into a Partitura Part object for analysis. Ensure the MUSICXML_DIR is correctly set. ```python score_fn = os.path.join(MUSICXML_DIR, 'Chopin_op10_no3.musicxml') score_part = pt.load_musicxml(score_fn)[0] ``` -------------------------------- ### MusicXML I/O Source: https://context7.com/cpjku/partitura/llms.txt Load and save music data in MusicXML format. Includes a shortcut to extract a note array directly. ```APIDOC ## pt.load_musicxml / pt.save_musicxml ### Description Direct MusicXML import/export with fine-grained control. `musicxml_to_notearray` is a shortcut to extract a note array without building a full `Part`. ### Usage ```python import partitura as pt # Load (also handles .mxl compressed files) score = pt.load_musicxml(pt.EXAMPLE_MUSICXML, force_note_ids="keep") # Note array shortcut na = pt.musicxml_to_notearray(pt.EXAMPLE_MUSICXML) print(na["pitch"]) # Export with work metadata pt.save_musicxml(score, "with_meta.musicxml") ``` ``` -------------------------------- ### Load Match File Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Loads a performance match file, which contains information about how a performance aligns with a score. This is useful for detailed performance analysis. ```python performed_part, alignment = pt.load_match(match_fn) ``` -------------------------------- ### Import MEI Score Source: https://github.com/cpjku/partitura/blob/main/README.md Load a musical score from an MEI file. Requires the partitura library to be imported. ```python import partitura as pt my_mei_file = pt.EXAMPLE_MEI score = pt.load_mei(my_mei_file) ``` -------------------------------- ### Print First 10 Notes from Score Note Array Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Displays the first 10 notes from a score's note array to inspect its contents. This helps in understanding the structure and data types of the extracted information. ```python # Lets see the first notes in this note array print(score_note_array[:10]) ``` -------------------------------- ### Save and Load Matchfile Alignments Source: https://context7.com/cpjku/partitura/llms.txt Saves score-performance alignments in the Vienna Matchfile format and loads alignments from Nakamura's music alignment tool. Includes loading alignment data with score creation. ```python import partitura as pt from partitura.io import load_match from partitura.io.importnakamura import load_nakamuramatch, load_nakamuracorresp # Save alignment perf, alignment, score = load_match("existing.match", create_score=True) pt.save_match( score=score, performance=perf, alignment=alignment, out="new_alignment.match", ) # Load Nakamura match/corresp files perf_nk, alignment_nk = load_nakamuramatch("Shi05_infer_match.txt") perf_nc, alignment_nc = load_nakamuracorresp("Shi05_infer_corresp.txt") print(alignment_nk[0]) ``` -------------------------------- ### Display First 10 Alignment Items Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Shows the first 10 entries of an alignment list. Each entry details the correspondence between score and performance notes (match, insertion, deletion, ornament). ```python alignment[:10] ``` -------------------------------- ### Load Score from Various Formats Source: https://context7.com/cpjku/partitura/llms.txt Use `pt.load_score` as a universal entry point to load scores from local files or URLs. It auto-detects formats like MusicXML, MIDI, MEI, and Humdrum Kern. Accessing parts and notes is demonstrated, including converting to a numpy note array. ```python import partitura as pt # Load the bundled example MusicXML score = pt.load_score(pt.EXAMPLE_MUSICXML) print(score) # Score(parts=[Part id="P1" name="Piano"]) print(score.parts) # [] # Load from a URL score_url = pt.load_score( "https://raw.githubusercontent.com/CPJKU/partitura/main/" "partitura/assets/score_example.musicxml" ) # Load a MIDI score score_midi = pt.load_score(pt.EXAMPLE_MIDI) # Load a Kern file score_kern = pt.load_score(pt.EXAMPLE_KERN) # Load a MEI file score_mei = pt.load_score(pt.EXAMPLE_MEI) # Access parts and notes part = score.parts[0] print(part.pretty()) # Pretty-print the timeline # note_array() returns a numpy structured array na = part.note_array() print(na.dtype.names) # ('onset_div', 'duration_div', 'onset_beat', 'duration_beat', # 'onset_quarter', 'duration_quarter', 'onset_sec', 'duration_sec', # 'pitch', 'voice', 'id', 'staff') print(na[['onset_beat', 'duration_beat', 'pitch']]) # [(0., 4., 69) (2., 2., 72) (2., 2., 76)] ``` -------------------------------- ### MIDI I/O Source: https://context7.com/cpjku/partitura/llms.txt Load MIDI files, distinguishing between score-structured MIDI and performance MIDI. ```APIDOC ## pt.load_score_midi / pt.load_performance_midi ### Description Separate loaders for score-structured MIDI (with quantization) and performance MIDI (timing in seconds). ### Usage ```python import partitura as pt # Score MIDI: onsets are quantized; returns a Score score = pt.load_score_midi(pt.EXAMPLE_MIDI, assign_note_ids=True) print(score.parts[0].note_array()["onset_quarter"]) # Performance MIDI: onsets in seconds; returns a Performance perf = pt.load_performance_midi( pt.EXAMPLE_MIDI, default_bpm=120, merge_tracks=False, ) ppart = perf[0] print(ppart.notes[0]) ``` ``` -------------------------------- ### pt.load_performance Source: https://context7.com/cpjku/partitura/llms.txt Loads a performed (expressive) recording from a MIDI file or a .match file. It returns a Performance object containing PerformedPart objects with timing in seconds. ```APIDOC ## pt.load_performance — Load a MIDI or match-file performance Loads a performed (expressive) recording from a MIDI file or a `.match` file as a `Performance` containing `PerformedPart` objects. Onset/offset times are in seconds. ### Usage ```python import partitura as pt perf = pt.load_performance(pt.EXAMPLE_MIDI, default_bpm=120, first_note_at_zero=True) ppart = perf[0] # first PerformedPart # Access performed notes (timing in seconds) for note in ppart.notes[:3]: print(note["midi_pitch"], note["note_on"], note["note_off"]) # 69 0.0 2.0 # 72 1.0 2.0 # 76 1.0 2.0 # note_array for the performance pna = ppart.note_array() print(pna.dtype.names) # ('onset_sec', 'duration_sec', 'pitch', 'velocity', 'track', 'channel', 'id') ``` ``` -------------------------------- ### Part object properties and methods Source: https://context7.com/cpjku/partitura/llms.txt The `Part` object provides a time-indexed timeline of musical elements. It offers map functions for time conversions and list properties for accessing elements like notes, measures, key signatures, and tempo directions. ```APIDOC ## `Part` object — Score timeline and element access A `Part` is a time-indexed timeline of all musical elements. It exposes map functions and list properties for every element type. ```python import partitura as pt import numpy as np part = pt.load_score_as_part(pt.EXAMPLE_MUSICXML) # Time maps: convert internal divisions to musical time units beat_map = part.beat_map # divisions → beats inv_beat_map = part.inv_beat_map # beats → divisions quarter_map = part.quarter_map # divisions → quarter notes notes = part.notes # all Note objects (incl. grace notes) tied = part.notes_tied # only non-tied / first of tie chain # Convert to pianoroll-style array pianoroll = np.array([(n.start.t, n.end.t, n.midi_pitch) for n in notes]) print(pianoroll) # [[ 69 72 76]] # Convert start times to beat positions print(beat_map(pianoroll[:, 0])) # [0. 2. 2.] print(beat_map(pianoroll[:, 1])) # [4. 4. 4.] # Other element lists print(part.measures) # [] print(part.key_sigs) # [] print(part.time_sigs) # [] print(part.dynamics) # loudness markings print(part.tempo_directions) # Map functions for structural elements ts_map = part.time_signature_map # time → (beats, beat_type, musical_beats) ks_map = part.key_signature_map # time → (fifths, mode) m_map = part.measure_map # time → (measure_start, measure_end) mn_map = part.measure_number_map # time → measure number print(ts_map(0)) # [4. 4. 4.] (4/4 time signature) print(ks_map(0)) # [0. 1.] (C major) ``` ``` -------------------------------- ### Load MIDI Performance Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Loads a MIDI file into a `PerformedPart` object. This object is a wrapper for MIDI data, providing access to notes and control changes. ```python path_to_midifile = pt.EXAMPLE_MIDI performedpart = pt.load_performance_midi(path_to_midifile)[0] ``` -------------------------------- ### Export Score to WAV using Additive Synthesis Source: https://context7.com/cpjku/partitura/llms.txt Synthesizes a score to a WAV file using built-in additive synthesis. For FluidSynth, use `save_wav_fluidsynth` (requires pyfluidsynth and a soundfont). ```python import partitura as pt score = pt.load_score(pt.EXAMPLE_MUSICXML) pt.save_wav(score, "output.wav") # With FluidSynth (requires pyfluidsynth and a soundfont) # pt.save_wav_fluidsynth(score, "output_fs.wav", soundfont="path/to/font.sf2") ``` -------------------------------- ### Access Part Time Maps and Element Lists Source: https://context7.com/cpjku/partitura/llms.txt Accesses time maps (divisions to beats, etc.) and lists of musical elements (notes, measures, key/time signatures) from a Part object. ```python import partitura as pt import numpy as np part = pt.load_score_as_part(pt.EXAMPLE_MUSICXML) # Time maps: convert internal divisions to musical time units beat_map = part.beat_map # divisions → beats inv_beat_map = part.inv_beat_map # beats → divisions quarter_map = part.quarter_map # divisions → quarter notes notes = part.notes # all Note objects (incl. grace notes) tied = part.notes_tied # only non-tied / first of tie chain # Convert to pianoroll-style array pianoroll = np.array([(n.start.t, n.end.t, n.midi_pitch) for n in notes]) print(pianoroll) # [[ 0 48 69] # [24 48 72] # [24 48 76]] # Convert start times to beat positions print(beat_map(pianoroll[:, 0])) # [0. 2. 2.] print(beat_map(pianoroll[:, 1])) # [4. 4. 4.] # Other element lists print(part.measures) # [] print(part.key_sigs) # [] print(part.time_sigs) # [] print(part.dynamics) # loudness markings print(part.tempo_directions) # Map functions for structural elements ts_map = part.time_signature_map # time → (beats, beat_type, musical_beats) ks_map = part.key_signature_map # time → (fifths, mode) m_map = part.measure_map # time → (measure_start, measure_end) mn_map = part.measure_number_map # time → measure number print(ts_map(0)) # [4. 4. 4.] (4/4 time signature) print(ks_map(0)) # [0. 1.] (C major) ``` -------------------------------- ### pt.render Source: https://context7.com/cpjku/partitura/llms.txt Renders one or more parts or part-groups to a PNG or PDF image. It supports MuseScore or LilyPond as the backend. The output can be displayed inline or saved to a file. ```APIDOC ## `pt.render` — Render score to image Renders one or more parts/part-groups to a PNG or PDF image using MuseScore or LilyPond as the backend. ```python import partitura as pt score = pt.load_score(pt.EXAMPLE_MUSICXML) part = score.parts[0] # Display inline (opens default viewer) pt.render(part) # Save to file pt.render(part, fmt="png", dpi=150, out="score_image.png") pt.render(part, fmt="pdf", out="score.pdf") ``` ``` -------------------------------- ### Load and Save Score MIDI in Partitura Source: https://github.com/cpjku/partitura/blob/main/docs/source/introduction.md Use these functions to load and save musical scores in MIDI format. Note that loading a MIDI performance as a score may not yield accurate results. ```python load_score_midi() save_score_midi() ``` ```python load_performance_midi() save_performance_midi() ``` -------------------------------- ### Reconstruct Score from Note Array in Partitura Source: https://context7.com/cpjku/partitura/llms.txt Convert a structured note array, where onsets and durations are in beat units, back into a `Part` object. This reconstructed `Part` includes measures, key signatures, and time signatures. ```python import partitura as pt from partitura.musicanicanalysis.note_array_to_score import note_array_to_score import numpy as np ``` -------------------------------- ### Part.note_array() Source: https://context7.com/cpjku/partitura/llms.txt Returns a structured NumPy array containing detailed information about each note, including onset, duration in various time units, pitch, voice, staff, and note ID. Additional fields like pitch spelling, key signature, time signature, metrical position, and grace notes can be included. ```APIDOC ## `Part.note_array()` — Structured numpy note array Returns a structured numpy array with onset/duration in multiple time units, pitch, voice, staff, and note ID. Additional fields can be included via keyword arguments. ```python import partitura as pt part = pt.load_score_as_part(pt.EXAMPLE_MUSICXML) # Basic note array na = part.note_array() # With extra fields na_full = part.note_array( include_pitch_spelling=True, # adds step, alter, octave include_key_signature=True, # adds ks_fifths, ks_mode include_time_signature=True, # adds ts_beats, ts_beat_type include_metrical_position=True,# adds is_downbeat, rel_onset_div, etc. include_grace_notes=True, ) print(na_full.dtype.names) # (..., 'step', 'alter', 'octave', 'ks_fifths', 'ks_mode', # 'ts_beats', 'ts_beat_type', ...) # Filter notes by voice import numpy as np voice1 = na[na["voice"] == 1] print(voice1["pitch"]) # [69] ``` ``` -------------------------------- ### Load Alignment from Match File Only Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Loads alignment information, including a Part and a PerformedPart, directly from a match file. This method is useful when the original score file is not available. ```python # path to the match match_fn = os.path.join(MATCH_DIR, 'Chopin_op10_no3_p01.match') # loading a match file performed_part, alignment, score_part = pt.load_match(match_fn, create_part=True) ``` -------------------------------- ### Generate Tempo Curves from Alignments Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Calculates tempo curves for multiple performances of the same piece by mapping score time to performance time using alignment data. Requires scipy and numpy. ```python matchfiles = glob.glob(os.path.join(MATCH_DIR, 'Chopin_op10_no3_p*.match')) matchfiles.sort() score_time = np.linspace(snote_array['onset_beat'].min(), snote_array['onset_beat'].max(), 100) score_time_ending = np.r_[ score_time, (snote_array['onset_beat'] + snote_array['duration_beat']).max() # last offset ] tempo_curves = np.zeros((len(matchfiles), len(score_time))) for i, matchfile in enumerate(matchfiles): performance, alignment = pt.load_match(matchfile) ppart = performance[0] _, stime_to_ptime_map = pt.musicanalysis.performance_codec.get_time_maps_from_alignment( ppart, score_part, alignment) performance_time = stime_to_ptime_map(score_time_ending) tempo_curves[i,:] = 60 * np.diff(score_time_ending) / np.diff(performance_time) ``` -------------------------------- ### Compute Performance Features with Partitura Source: https://context7.com/cpjku/partitura/llms.txt Generate expressive performance descriptors like timing, dynamics, and articulation by matching score and performance data. The output is a structured NumPy array with one row per matched note. ```python import partitura as pt from partitura.musicanicanalysis import make_performance_features from partitura.io import load_match perf, alignment, score = load_match("path/to/file.match", create_score=True) perf_features = make_performance_features( score=score, performance=perf, alignment=alignment, feature_functions=["articulation_feature", "dynamics_feature", "pedal_feature"], ) # Returns a structured numpy array with one row per matched note print(perf_features.dtype.names) # ('articulation_feature.articulation_log', 'dynamics_feature.velocity', ...) ``` -------------------------------- ### Plot Tempo Curves Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Visualizes the tempo curves of multiple performances and their average. This helps in comparing expressive timing variations. Requires matplotlib. ```python fig, ax = plt.subplots(1, figsize=(15, 8)) color = plt.cm.rainbow(np.linspace(0, 1, len(tempo_curves))) for i, tempo_curve in enumerate(tempo_curves): ax.plot(score_time, tempo_curve, label=f'pianist {i + 1:02d}', alpha=0.4, c=color[i]) ax.plot(score_time, tempo_curves.mean(0), label='average', c='black', linewidth=2) measure_times = score_part.beat_map([measure.start.t for measure in score_part.iter_all(pt.score.Measure)]) measure_times = measure_times[measure_times >= 0] ax.set_title('Chopin Op. 10 No. 3') ax.set_xlabel('Score time (beats)') ax.set_ylabel('Tempo (bpm)') ax.set_xticks(measure_times) plt.legend(frameon=False, bbox_to_anchor = (1.15, .9)) plt.grid(axis='x') plt.show() ``` -------------------------------- ### Iterate Over Generic Notes with Subclasses Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Iterate over all `GenericNote` instances, including subclasses like grace notes, within a specified time range (0 to 24 divs). ```python for note in part.iter_all(pt.score.GenericNote, include_subclasses=True, start=0, end=24): print(note) ``` -------------------------------- ### Render Score to Image Files Source: https://context7.com/cpjku/partitura/llms.txt Renders a score part to a PNG or PDF image using MuseScore or LilyPond. Can display inline or save to a file. ```python import partitura as pt score = pt.load_score(pt.EXAMPLE_MUSICXML) part = score.parts[0] # Display inline (opens default viewer) pt.render(part) # Save to file pt.render(part, fmt="png", dpi=150, out="score_image.png") pt.render(part, fmt="pdf", out="score.pdf") ``` -------------------------------- ### Create Custom Note Array with Accent Information Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Define a custom note array structure with fields like 'onset_beat', 'pitch', and 'accent'. This function iterates through notes in a part, populates the custom array, and marks notes with accent articulations. ```python # Path to the MusicXML file score_fn = os.path.join(MUSICXML_DIR, 'Chopin_op10_no3.musicxml') # Load the score into a `Part` object score_part = pt.load_musicxml(score_fn)[0] def get_accent_note_array(part): fields = [("onset_beat", "f4"), ("pitch", "i4"), ("accent", "i4")] # Get all notes in the part notes = part.notes_tied # Beat map (maps divs to score time in beats) beat_map = part.beat_map N = len(notes) note_array = np.zeros(N, dtype=fields) for i, n in enumerate(notes): # MIDI pitch note_array[i]['pitch'] = n.midi_pitch # Get the onset time in beats note_array[i]['onset_beat'] = beat_map(n.start.t) # Iterate over articulations in the note if n.articulations: for art in n.articulations: if art == 'accent': note_array[i]['accent'] = 1 return note_array accent_note_array = get_accent_note_array(score_part) ``` -------------------------------- ### Save Score to MusicXML and WAV Source: https://github.com/cpjku/partitura/blob/main/README.md Save a musical score to MusicXML format or as an audio file using additive synthesis. ```python pt.save_musicxml(part, 'mypart.musicxml') ``` ```python pt.save_wav(part, 'mypart.wav') ``` -------------------------------- ### Load MusicXML Score Source: https://github.com/cpjku/partitura/blob/main/README.md Load a MusicXML file included with the package into a partitura.Score object. This function supports multiple score formats. ```python import partitura as pt my_xml_file = pt.EXAMPLE_MUSICXML score = pt.load_score(my_xml_file) ``` -------------------------------- ### Estimate Musical Key with Partitura Source: https://context7.com/cpjku/partitura/llms.txt Estimate the global key of a score or note array using the Krumhansl–Schmuckler algorithm. Different key profiles can be specified, and the function can return a sorted list of key candidates. ```python import partitura as pt from partitura.musicanicanalysis import estimate_key from partitura.musicanicanalysis.key_identification import ks_kid score = pt.load_score(pt.EXAMPLE_MUSICXML) # From a Score or Part key = estimate_key(score, method="krumhansl", key_profiles="krumhansl_kessler") print(key) # e.g. 'Am' or 'C' # From a note array na = score.note_array() key2 = estimate_key(na, key_profiles="kostka_payne") print(key2) # 'C' # Get sorted list of key candidates key3, sorted_keys = ks_kid(na, return_sorted_keys=True) print(sorted_keys[:3]) # [('C', 'major', ...), ('Am', 'minor', ...), ...] ``` -------------------------------- ### Fetch and Update Develop Branch Source: https://github.com/cpjku/partitura/blob/main/CONTRIBUTING.md Fetch the latest changes from the upstream repository and update your local develop branch. ```shell git fetch upstream git checkout develop git pull ``` -------------------------------- ### pt.load_match Source: https://context7.com/cpjku/partitura/llms.txt Loads a score-performance alignment from a match file (Vienna4x22 format) and returns the performance, alignment list, and score as a 3-tuple. ```APIDOC ## pt.load_match — Load score–performance alignment from a match file Loads a match file (Vienna4x22 format) and returns aligned performance, score, and alignment list as a 3-tuple. ### Usage ```python import partitura as pt from partitura.io import load_match perf, alignment, score = load_match( "path/to/alignment.match", create_score=True, first_note_at_zero=True, ) # alignment is a list of dicts with keys: label, score_id, performance_id matched = [a for a in alignment if a["label"] == "match"] print(matched[0]) # {'label': 'match', 'score_id': 'n01', 'performance_id': 'n1'} ``` ``` -------------------------------- ### Load Score for Piano Roll Extraction Source: https://github.com/cpjku/partitura/blob/main/docs/source/Tutorial/notebook.ipynb Load a MusicXML score into a partitura `Part` object. This is a prerequisite step before extracting piano roll representations. ```python # TODO: change the example # Path to the MusicXML file score_fn = os.path.join(MUSICXML_DIR, 'Chopin_op10_no3.musicxml') # Load the score score_part = pt.load_musicxml(score_fn) ``` -------------------------------- ### pt.musicanalysis.make_note_features Source: https://context7.com/cpjku/partitura/llms.txt Computes a set of named feature functions over all notes and returns an N×M float array along with feature names. Feature functions can be selected by name or passed as callables. Pass "all" to compute every available feature. ```APIDOC ## `pt.musicanalysis.make_note_features` — Note-level feature matrix for ML Computes a set of named feature functions over all notes and returns an N×M float array along with feature names. Feature functions can be selected by name or passed as callables. Pass `"all"` to compute every available feature. ```python import partitura as pt from partitura.musicanalysis import make_note_features, list_note_feats_functions score = pt.load_score(pt.EXAMPLE_MUSICXML) # List available feature function names print(list_note_feats_functions()) # ['articulation_feature', 'duration_feature', 'fermata_feature', # 'grace_feature', 'loudness_direction_feature', 'metrical_feature', # 'ornament_feature', 'pitch_feature', 'slur_feature', 'staff_feature', # 'time_signature_feature', 'vertical_neighbor_feature', ...] # Compute selected features features, names = make_note_features( score, feature_functions=["pitch_feature", "metrical_feature", "duration_feature"], ) print(features.shape) # (3, ) print(names[:5]) # ['pitch_feature.pitch', 'pitch_feature.octave', ...] # Compute ALL features features_all, names_all = make_note_features(score, feature_functions="all") print(features_all.shape) # (num_notes, total_descriptors) # Fixed-size (safe for batching across pieces) features_fixed, names_fixed = make_note_features( score, feature_functions=["pitch_feature", "duration_feature"], force_fixed_size=True, ) ``` ```