diff --git a/.github/workflows/pypi_publish.yml b/.github/workflows/pypi_publish.yml index 294a9dc..1d0161a 100644 --- a/.github/workflows/pypi_publish.yml +++ b/.github/workflows/pypi_publish.yml @@ -10,7 +10,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-latest, macos-latest] + os: [ubuntu-latest, macos-latest, windows-latest] steps: - uses: actions/checkout@v3 @@ -27,11 +27,11 @@ jobs: run: python -m cibuildwheel env: CIBW_BUILD: "cp310-* cp311-* cp312-* cp313-*" - CIBW_ARCHS: "x86_64" + CIBW_ARCHS_LINUX: "x86_64" CIBW_ARCHS_MACOS: "x86_64 arm64" - CIBW_BEFORE_BUILD: | - pip install --upgrade pip - pip install "numpy>=2.0,<3.0" "cython>=3.0.10,<4.0" + CIBW_ARCHS_WINDOWS: "AMD64" + # One line: on Windows this runs in cmd, which does not take a script. + CIBW_BEFORE_BUILD: pip install "numpy>=2.0,<3.0" "cython>=3.0.10,<4.0" CIBW_BUILD_VERBOSITY: 1 - name: Upload artifact @@ -40,9 +40,33 @@ jobs: name: wheels-${{ matrix.os }} path: ./wheelhouse/*.whl + # The source distribution, for platforms without a wheel (pip builds it + # there, which needs a C compiler). + build_sdist: + name: Build sdist + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: "3.12" + + - name: Build sdist + run: | + python -m pip install build + python -m build --sdist + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: sdist + path: ./dist/*.tar.gz + publish: if: github.event.release.prerelease == false - needs: build_wheels + needs: [build_wheels, build_sdist] runs-on: ubuntu-latest permissions: id-token: write @@ -50,7 +74,6 @@ jobs: - name: Download artifacts uses: actions/download-artifact@v4 with: - pattern: wheels-* path: dist merge-multiple: true diff --git a/.github/workflows/test_pypi_publish.yml b/.github/workflows/test_pypi_publish.yml index 5d78dc7..207ec30 100644 --- a/.github/workflows/test_pypi_publish.yml +++ b/.github/workflows/test_pypi_publish.yml @@ -10,7 +10,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-latest, macos-latest] + os: [ubuntu-latest, macos-latest, windows-latest] steps: - uses: actions/checkout@v3 @@ -27,11 +27,11 @@ jobs: run: python -m cibuildwheel env: CIBW_BUILD: "cp310-* cp311-* cp312-* cp313-*" - CIBW_ARCHS: "x86_64" + CIBW_ARCHS_LINUX: "x86_64" CIBW_ARCHS_MACOS: "x86_64 arm64" - CIBW_BEFORE_BUILD: | - pip install --upgrade pip - pip install "numpy>=2.0,<3.0" "cython>=3.0.10,<4.0" + CIBW_ARCHS_WINDOWS: "AMD64" + # One line: on Windows this runs in cmd, which does not take a script. + CIBW_BEFORE_BUILD: pip install "numpy>=2.0,<3.0" "cython>=3.0.10,<4.0" CIBW_BUILD_VERBOSITY: 1 - name: Upload artifact @@ -40,9 +40,33 @@ jobs: name: wheels-${{ matrix.os }} path: ./wheelhouse/*.whl + # The source distribution, for platforms without a wheel (pip builds it + # there, which needs a C compiler). + build_sdist: + name: Build sdist + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: "3.12" + + - name: Build sdist + run: | + python -m pip install build + python -m build --sdist + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: sdist + path: ./dist/*.tar.gz + publish: if: startsWith(github.ref, 'refs/tags/') - needs: build_wheels + needs: [build_wheels, build_sdist] runs-on: ubuntu-latest permissions: id-token: write @@ -50,7 +74,6 @@ jobs: - name: Download artifacts uses: actions/download-artifact@v4 with: - pattern: wheels-* path: dist merge-multiple: true diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index c1a54fa..0030612 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -10,10 +10,11 @@ jobs: strategy: fail-fast: false matrix: - platform: [ubuntu-latest, macos-latest] + platform: [ubuntu-latest, macos-latest, windows-latest] python-version: ["3.10", "3.11", "3.12", "3.13"] runs-on: ${{ matrix.platform }} + timeout-minutes: 30 steps: - uses: actions/checkout@v3 @@ -22,17 +23,34 @@ jobs: with: python-version: ${{ matrix.python-version }} + # A slow package mirror can stall apt for half an hour or more: retry + # dropped downloads, and fail after 10 minutes so the job can be re-run. + # No recommended packages: that skips qsynth, a Qt GUI for FluidSynth. + # libfluidsynth3 still pulls in a soundfont, though matchmaker synthesizes + # with partitura's bundled one. PyAudio is built by pip from + # portaudio19-dev, not taken from the system Python. - name: Install system dependencies (Ubuntu) if: matrix.platform == 'ubuntu-latest' + timeout-minutes: 10 run: | - sudo apt-get update - sudo apt-get install -y portaudio19-dev python3-pyaudio fluidsynth + sudo apt-get update -o Acquire::Retries=3 + sudo apt-get install -y --no-install-recommends -o Acquire::Retries=3 \ + portaudio19-dev fluidsynth - name: Install system dependencies (macOS) if: matrix.platform == 'macos-latest' + timeout-minutes: 10 run: | brew install portaudio fluidsynth + # PyAudio's Windows wheels bundle PortAudio, so only FluidSynth is needed. + - name: Install system dependencies (Windows) + if: matrix.platform == 'windows-latest' + timeout-minutes: 10 + run: | + choco install fluidsynth -y --no-progress + echo "C:\tools\fluidsynth\bin" >> $env:GITHUB_PATH + - name: Install dependencies run: | python -m pip install --upgrade pip diff --git a/CHANGES.md b/CHANGES.md index 453747f..98e27bc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,18 @@ # Changes +## Version 0.5.0 + +### Added + +- Bloch and Dannenberg's dynamic-programming follower for MIDI (`method="dannenberg"`). +- Windows wheels and a source distribution on PyPI. + +### Changed + +- SPARC resamples the position path at 3 kHz (`SPARC_SAMPLE_RATE`) instead of 50 Hz, so every audio frame interval (25, 30, 50, 62.5 Hz) spans a whole number of samples and closely spaced MIDI updates stay apart. `smoothness` values therefore differ from 0.4.0; pass `fs=50` to `compute_sparc` to reproduce them. +- SPARC windows are computed from the sparse speed of the held path and only the bins up to `fc`, giving the same values as before without a full FFT per window (a 5-minute piece takes seconds at 3 kHz instead of about a minute and a half). +- `arzt_multi_fold` builds only the first repeat unfoldings it uses instead of every repeat path, so scores with many repeats no longer stall. The hypotheses and their order are unchanged. + ## Version 0.4.0 New score followers, a method registry, and a standardized evaluation output. Not backwards compatible with 0.3. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..12e08ad --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +# Cython sources for building from the sdist. setuptools picks up the .pyx +# files from setup.py, but not the .pxd declarations next to them. +recursive-include matchmaker *.pyx *.pxd diff --git a/README.md b/README.md index b2432de..4ec581c 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,8 @@ Supports **simulation mode**: run online alignment against recorded audio or MID > ```bash > conda install -c conda-forge fluidsynth > ``` +> +> conda-forge has no Fluidsynth package for Windows; see [Installing Fluidsynth on Windows](#installing-fluidsynth-on-windows). ### Option 2: Live device support @@ -51,6 +53,8 @@ Adds [PyAudio](https://pypi.org/project/PyAudio/) and [python-rtmidi](https://py > ```bash > conda install -c conda-forge fluidsynth portaudio > ``` +> +> On Windows, the `pyaudio` wheels already include PortAudio, so only Fluidsynth is needed. ### Option 3: Development install (from source) @@ -65,31 +69,42 @@ cd matchmaker conda create -n matchmaker python=3.12 conda activate matchmaker -# Install system dependencies +# Install system dependencies (Linux and macOS; on Windows, see below) conda install -c conda-forge gcc=12.1.0 glib fluidsynth portaudio # Install matchmaker in editable mode with all dev dependencies (includes [devices]) pip install -e ".[dev]" ``` +On Windows, skip the system dependencies step: conda-forge has neither `gcc=12.1.0` nor Fluidsynth for Windows, and none of these packages are needed there. Instead, install the [Visual C++ build tools](#missing-visual-c-build-tools-on-windows) to compile the Cython extensions and [install Fluidsynth from its release ZIP](#installing-fluidsynth-on-windows). The rest of the steps are the same, in a conda environment or a plain `venv`. + > **Note:** `partitura` will download `MuseScore_General.sf3` (a free soundfont) on first use. This may take a moment. ### Known Setup Issues #### Missing Visual C++ build tools (on Windows) -Download `vs_BuildTools.exe` from and run: +Building from source (`pip install -e .`, or the sdist) fails with `Microsoft Visual C++ 14.0 or greater is required` if no C++ compiler is installed. Having Visual Studio installed is not enough; it also needs the C++ workload. Install the build tools with winget: + +```bash +winget install --id Microsoft.VisualStudio.2022.BuildTools --override "--quiet --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended" +``` + +Or download `vs_BuildTools.exe` from and run: ```bash vs_buildtools.exe --norestart --passive --downloadThenInstall --includeRecommended --add Microsoft.VisualStudio.Workload.NativeDesktop --add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Workload.MSBuildTools ``` -#### Issues with Fluidsynth and pyfluidsynth on Windows +#### Installing Fluidsynth on Windows + +Without Fluidsynth, `import fluidsynth` raises `ImportError("Couldn't find the FluidSynth library.")`. pyfluidsynth looks for `libfluidsynth-3.dll` in `C:\tools\fluidsynth\bin` and on `PATH`: -On Windows, pyfluidsynth expects `fluidsynth.exe` to be located in `C:\tools\bin` (some users report `C:\tools\fluidsynth\bin`): +1. Download the ZIP for your architecture (e.g. `fluidsynth-v2.6.1-win10-x64-cpp11.zip`) from . +2. Extract it and rename the extracted folder (e.g. `fluidsynth-v2.6.1-win10-x64-cpp11`) to `C:\tools\fluidsynth`, so that the DLL is at `C:\tools\fluidsynth\bin\libfluidsynth-3.dll`. Alternatively, put the folder anywhere and add its `bin` directory to `PATH`. +3. Check with `python -c "import fluidsynth"`. -1. Download the ZIP for your Windows version from -2. Extract the contents to `C:\tools` (or wherever pyfluidsynth expects the executable). +With [Chocolatey](https://chocolatey.org/), `choco install fluidsynth` installs it to `C:\tools\fluidsynth` as well. #### Using Fluidsynth installed from Homebrew on macOS @@ -362,7 +377,7 @@ Default method: `"arzt"` | Method | Description | |---|---| -| `"arzt"` | On-line time warping adapted from Brazier and Widmer (2020) | +| `"arzt"` | On-line time warping by Arzt et al. (2008), extending Dixon (2005) | | `"dixon"` | On-line time warping by Dixon (2005) | | `"outerhmm"` | Two-level HMM with repeats and skips by Nakamura et al. (2016) | | `"skf"` | Switching Kalman Filter with hidden tempo by Jiang and Raphael (2020) | @@ -376,16 +391,16 @@ Default method: `"pthmm"` | Method | Description | |---|---| -| `"arzt"` | On-line time warping adapted from Brazier and Widmer (2020) | +| `"arzt"` | On-line time warping by Arzt et al. (2008), extending Dixon (2005) | | `"dixon"` | On-line time warping by Dixon (2005) | -| `"outerhmm"` | Outer-product HMM score follower by Nakamura (2014) | +| `"outerhmm"` | Outer-product HMM score follower by Nakamura et al. (2014) | | `"hmm"` | HMM score follower by Cancino-Chacón et al. (2023) | | `"pthmm"` | Pitch-based HMM score follower | | `"pfkorz"` | Particle filter score follower by Korzeniowski et al. (2013) | -| `"SL_OLTW"` | Symbolic-level OLTW note matcher from [parangonar](https://github.com/sildater/parangonar) | -| `"SLT_OLTW"` | Symbolic-level OLTW note matcher with tempo, from parangonar | -| `"OTM"` | Online transformer note matcher from parangonar | -| `"OPTM"` | Online pure-transformer note matcher from parangonar | +| `"SL_OLTW"` | Symbolic-level OLTW note matcher from [parangonar](https://github.com/sildater/parangonar) (Peter et al., 2025) | +| `"SLT_OLTW"` | Symbolic-level OLTW note matcher with tempo, from parangonar (Peter et al., 2025) | +| `"OTM"` | Online transformer note matcher from parangonar (Peter, 2023) | +| `"OPTM"` | Online pure-transformer note matcher from parangonar (Peter, 2023) | The parangonar methods match one performed note at a time, so they always run event-based (no MIDI polling). @@ -404,7 +419,7 @@ Default processor: `"chroma"`. Some methods default to their own processor | `"cqt"` | Constant-Q transform | | `"mel"` | Mel-spectrogram | | `"lse"` | Log-spectral energy features used in Dixon (2005) | -| `"cqt_spectral_flux"` | CQT-based spectral flux used in Nakamura (2014) | +| `"cqt_spectral_flux"` | CQT-based spectral flux used in Nakamura et al. (2016) | | `"raw_spectrum"` | Raw power spectrum used in Jiang and Raphael (2020) | | `"korzeniowski"` | Spectral observations for the Korzeniowski et al. (2013) particle filter | @@ -475,7 +490,7 @@ If you find Matchmaker useful, we would appreciate if you could cite us! ## Acknowledgments -This work has been supported by the Austrian Science Fund (FWF), grant agreement PAT 8820923 ("*Rach3: A Computational Approach to Study Piano Rehearsals*"). Additionally, this work was supported by the National Research Foundation of Korea (NRF) grant funded by the Korea government (MSIT) (No. NRF-2023R1A2C3007605). +This work has been supported by the Austrian Science Fund (FWF), grant agreement PAT 8820923 (Rach3: A Computational Approach to Study Piano Rehearsals) and PIN 1347924 (AURA: Augmenting musical interaction via EVAs), as well as by the European Research Council (ERC) under the EU’s Horizon 2020 research & innovation programme, grant agreement No.101019375 (Whither Music?), and by the National Research Foundation of Korea (NRF) grant funded by the Korea government (MSIT) under Grant RS-2023-NR077289. ## License diff --git a/docs/source/conf.py b/docs/source/conf.py index 76e8655..24f7d5c 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -13,7 +13,7 @@ project = "pymatchmaker" copyright = "2024, matchmaker development team" author = "matchmaker development team" -release = "0.4.0" +release = "0.5.0" # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/matchmaker/__init__.py b/matchmaker/__init__.py index f48df23..a5feb7d 100644 --- a/matchmaker/__init__.py +++ b/matchmaker/__init__.py @@ -15,7 +15,7 @@ try: __version__ = version("pymatchmaker") except PackageNotFoundError: # pragma: no cover - __version__ = "0.4.0" + __version__ = "0.5.0" ASSETS_DIR = Path(__file__).parent / "assets" diff --git a/matchmaker/dp/__init__.py b/matchmaker/dp/__init__.py index c5ff815..a2e12ef 100644 --- a/matchmaker/dp/__init__.py +++ b/matchmaker/dp/__init__.py @@ -8,6 +8,7 @@ - Event: onset-level features (MIDI) """ +from .dannenberg import DPDannenberg from .oltw_arzt import ( OnlineTimeWarpingArzt, OnlineTimeWarpingArztEvent, diff --git a/matchmaker/dp/dannenberg.py b/matchmaker/dp/dannenberg.py new file mode 100644 index 0000000..84fcb9f --- /dev/null +++ b/matchmaker/dp/dannenberg.py @@ -0,0 +1,261 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +""" +Dannenberg 1985 dynamic-programming polyphonic score follower. + +Re-implementation of the dynamic grouping matcher from: + + Bloch, J. & Dannenberg, R.B. (1985). Real-Time Computer Accompaniment + of Keyboard Performances. Proc. ICMC, 279-289. + +The matcher processes MIDI note-ons individually through a DP matrix +whose rows are score compound events (cevts = pitch sets at each onset) +and whose columns are individual performance notes. The algorithm finds +the association that maximises a rating function penalising wrong and +missing notes (Sec. 3, 6). Epsilon and epsilon-fraction tests (Sec. 5) +group incoming notes into performance cevts for confidence checking. + +Classes: + DPDannenberg -- windowed DP matcher (event-level, MIDI only) +""" + +from typing import Any, List, Optional, Set + +import numpy as np +from numpy.typing import NDArray + +from matchmaker.base import OnlineAlignment +from matchmaker.io.queue import RECVQueue + + +class DPDannenberg(OnlineAlignment): + """Windowed DP matcher (Bloch & Dannenberg 1985, Sec. 6). + + Rows of the DP matrix are score compound events (one pitch set per + unique onset beat); columns are individual performance MIDI notes. + Each incoming note updates one column by considering three + predecessors -- same row (extend), diagonal (advance and match), and + vertical (skip note) -- choosing the one that maximises the rating. + + Parameters + ---------- + reference_features : list of set of int + MIDI pitch set for each score onset (one per ``score_positions`` + entry). + score_positions : np.ndarray + Beat position of each score onset. + queue : optional + Input queue for streaming. + c_m : float + Cost per missing score note when advancing past a score cevt + (Sec. 8, default 0.5). + c_e : float + Cost per extra performance note not in the current score cevt + (Sec. 8, default 0.0). + epsilon : float + Absolute time threshold (seconds) for grouping notes into the + same performance cevt (Sec. 5, default 0.090 s). + epsilon_fraction : float + Fraction of predicted next-cevt time for the relative grouping + test (Sec. 5, default 0.25). + window : int + Number of score cevts ahead of the current best match to + consider (default 50). + tempo : float + Initial tempo in BPM, used to seed the epsilon-fraction test + and position interpolation (default 120.0). + smoothing : float + Exponential smoothing coefficient for tempo tracking + (default 0.5). + """ + + score_cevts: List[Set[int]] + n_states: int + c_m: float + c_e: float + epsilon: float + epsilon_fraction: float + window: int + smoothing: float + + _values: NDArray[np.float64] + _used: List[Set[int]] + _prev_values: NDArray[np.float64] + _prev_used: List[Set[int]] + + _best_value: float + _best_row: int + + _prev_note_time: Optional[float] + + _beats_per_second: float + _anchor_beat: float + _anchor_time: float + _prev_match_time: Optional[float] + _prev_match_beat: Optional[float] + + def __init__( + self, + reference_features: List[Set[int]], + score_positions: NDArray[np.floating[Any]], + queue: Optional[RECVQueue] = None, + c_m: float = 0.5, + c_e: float = 0.0, + epsilon: float = 0.090, + epsilon_fraction: float = 0.25, + window: int = 50, + tempo: float = 120.0, + smoothing: float = 0.5, + **kwargs: Any, + ) -> None: + super().__init__( + reference_features=reference_features, + score_positions=score_positions, + queue=queue, + ) + self.score_cevts = reference_features + self.n_states = len(reference_features) + self.c_m = c_m + self.c_e = c_e + self.epsilon = epsilon + self.epsilon_fraction = epsilon_fraction + self.window = window + self.smoothing = smoothing + + # Initial column (before any performance note): matching must start + # at the first score cevt, so row r begins with the cost of missing + # every note in cevts 0..r-1 (rather than 0 everywhere, which would + # allow a wrong first note to lock onto any row in the window). + sizes = np.array([len(c) for c in reference_features], dtype=np.float64) + self._values = np.zeros(self.n_states, dtype=np.float64) + if self.n_states > 1: + self._values[1:] = -self.c_m * np.cumsum(sizes)[:-1] + self._used = [set() for _ in range(self.n_states)] + self._prev_values = self._values.copy() + self._prev_used = [set() for _ in range(self.n_states)] + + self._best_value = float("-inf") + self._best_row = 0 + + self._prev_note_time = None + + self._beats_per_second = tempo / 60.0 + self._anchor_beat = float(score_positions[0]) + self._anchor_time = 0.0 + self._prev_match_time = None + self._prev_match_beat = None + + def _is_new_cevt(self, note_time: float) -> bool: + """Epsilon and epsilon-fraction tests (Sec. 5, p. 283-284).""" + if self._prev_note_time is None: + return True + dt = note_time - self._prev_note_time + if dt > self.epsilon: + return True + if ( + self._beats_per_second > 0 + and self._best_row + 1 < self.n_states + ): + beat_gap = float( + self.score_positions[self._best_row + 1] + - self.score_positions[self._best_row] + ) + predicted_dt = beat_gap / self._beats_per_second + if predicted_dt > 0 and dt > self.epsilon_fraction * predicted_dt: + return True + return False + + def step(self, features: Any) -> None: + pitch = int(np.atleast_1d(features)[0]) + note_time = self.current_perf_time + + if self._is_new_cevt(note_time): + pass + self._prev_note_time = note_time + + lo = max(0, self._best_row - 10) + hi = min(self.n_states, self._best_row + self.window) + + # Shift columns: save current as previous (Sec. 6, p. 285). + for r in range(lo, hi): + self._prev_values[r] = self._values[r] + for r in range(lo, hi): + self._prev_used[r] = self._used[r].copy() + + # DP update: one column per performance note (Fig. 6-2, p. 285). + for r in range(lo, hi): + B = self.score_cevts[r] + + y_val = float(self._prev_values[r]) + y_used = self._prev_used[r] + + z_val = y_val + z_used = y_used.copy() + + if pitch not in B: + z_val -= self.c_e + + if pitch in B: + if pitch not in y_used: + z_val = y_val + 1 + z_used = y_used | {pitch} + + if r > lo: + A = self.score_cevts[r - 1] + w_val = float(self._prev_values[r - 1]) + w_used = self._prev_used[r - 1] + missing_in_A = len(A - w_used) + d = w_val + 1 - self.c_m * missing_in_A + if d > z_val: + z_val = d + z_used = {pitch} + + if r > lo: + A_skip = self.score_cevts[r - 1] + x_val = float(self._values[r - 1]) + x_used = self._used[r - 1] + missing_in_A_skip = len(A_skip - x_used) + v = x_val - self.c_m * missing_in_A_skip + if v >= z_val: + z_val = v + z_used = set() + + self._values[r] = z_val + self._used[r] = z_used + + best_r = lo + int(np.argmax(self._values[lo:hi])) + best_v = float(self._values[best_r]) + + if best_v > self._best_value: + self._best_value = best_v + self._best_row = best_r + self.current_index = best_r + + beat = float(self.score_positions[best_r]) + if self._prev_match_time is not None: + elapsed = note_time - self._prev_match_time + advanced = beat - self._prev_match_beat + if elapsed > 0.05 and 0 < advanced < 16: + rate = advanced / elapsed + self._beats_per_second = ( + self.smoothing * self._beats_per_second + + (1 - self.smoothing) * rate + ) + + self._anchor_beat = beat + self._anchor_time = note_time + self._prev_match_time = note_time + self._prev_match_beat = beat + + def get_current_position(self) -> float: + drift = self._beats_per_second * ( + self.current_perf_time - self._anchor_time + ) + pos = self._anchor_beat + drift + if self.current_index + 1 < self.n_states: + cap = float(self.score_positions[self.current_index + 1]) + pos = min(pos, cap) + return pos + + def is_still_following(self) -> bool: + return self.current_index < self.n_states - 1 diff --git a/matchmaker/dp/oltw_arzt.py b/matchmaker/dp/oltw_arzt.py index d309d21..ce2b19d 100644 --- a/matchmaker/dp/oltw_arzt.py +++ b/matchmaker/dp/oltw_arzt.py @@ -4,6 +4,16 @@ On-line Time Warping (OLTWArzt) OLTW with step-size constraint and adaptive window, based on: + Arzt et al. (2008) "Automatic Page Turning for Musicians via Real-Time + Machine Listening" +which extends: + Dixon (2005) "Live Tracking of Musical Performances Using On-Line Time + Warping" +The frame-level (audio) variant closely follows source code provided by +Andreas Arzt; the event-level (MIDI) variant is a reimplementation by the +matchmaker team for MIDI input. + +Optional extensions: Arzt & Widmer (2010) "Simple Tempo Models for Real-Time Music Tracking" Arzt & Widmer (2015) "Real-Time Music Tracking Using Multiple Performances as a Reference" diff --git a/matchmaker/dp/oltw_arzt_multi_fold.py b/matchmaker/dp/oltw_arzt_multi_fold.py index bd3b296..053c65d 100644 --- a/matchmaker/dp/oltw_arzt_multi_fold.py +++ b/matchmaker/dp/oltw_arzt_multi_fold.py @@ -15,7 +15,7 @@ is adapted from A. Arzt, G. Widmer and S. Dixon, "Automatic page turning for musicians via real-time machine listening", Proc. ECAI, 2008 (Strategy 3) - G. Widmer and A. Arzt, "Robust real-time music tracking", Proc. Vienna Talk, 2010. + A. Arzt and G. Widmer, "Robust real-time music tracking", Proc. Vienna Talk, 2010. The unfolded versions, the cost window and the switching margin are this implementation's own choices, not those papers'. """ @@ -48,6 +48,30 @@ from matchmaker.utils.misc import generate_score_audio, set_latency_stats +def _iter_first_unfolded_parts(part, limit=4): + """Yield the first variants in Partitura's traversal order, without enumerating the rest.""" + import itertools + + if limit < 1: + return + pt.score.add_segments(part) + segments = pt.score.get_segments(part) + initial = pt.score.Path(["A"], segments, no_repeats=False, all_repeats=False) + + def paths(path): + for destination in path.list_of_destinations_from_last_segment: + if destination == "END": + path.ended = True + yield path + else: + yield from paths( + path.make_copy_with_jump_to(destination, ignore_leap_info=True) + ) + + for path in itertools.islice(paths(initial), limit): + yield pt.score.new_part_from_path(path, part, update_ids=True) + + class OnlineTimeWarpingArztMultiFold(OnlineTimeWarpingArztFrame): """Multi-fold parallel OLTW tracker for folded scores with repeats. @@ -165,7 +189,6 @@ def __init__( def _build_hypotheses(self) -> None: """Enumerate distinct structural fold clones safely and initialize trackers.""" - import itertools import sys _prev_limit = sys.getrecursionlimit() @@ -190,8 +213,7 @@ def _build_hypotheses(self) -> None: # 3. Intermediate unfold variants (bounded to prevent combinatorial explosion) try: - gen = pt.score.iter_unfolded_parts(self.score_part, update_ids=True) - for c in itertools.islice(gen, 4): + for c in _iter_first_unfolded_parts(self.score_part, limit=4): clones.append(c) except Exception: pass diff --git a/matchmaker/methods.yaml b/matchmaker/methods.yaml index cb32522..3d9c8ee 100644 --- a/matchmaker/methods.yaml +++ b/matchmaker/methods.yaml @@ -347,6 +347,29 @@ methods: observation_type: midi num_particles: 500 + dannenberg: + class: matchmaker.dp:DPDannenberg + reference: score_cevts + event_based: true + args: + reference_features: {from: reference_features} + score_positions: {from: score_positions} + queue: {from: queue} + tempo: {from: tempo} + config_passthrough: + exclude: [piano_range, return_pitch_list] + processor_args: + return_pitch_list: true + piano_range: false + default_kwargs: + processor: pitch + c_m: 0.5 + c_e: 0.0 + epsilon: 0.090 + epsilon_fraction: 0.25 + window: 50 + smoothing: 0.5 + # --- parangonar trackers; all four differ only by the ``method`` string --- # # They read the live stream themselves rather than being fed frames, so diff --git a/matchmaker/prob/particle_filter_korzeniowski.py b/matchmaker/prob/particle_filter_korzeniowski.py index 36dcee5..db4f47f 100644 --- a/matchmaker/prob/particle_filter_korzeniowski.py +++ b/matchmaker/prob/particle_filter_korzeniowski.py @@ -18,6 +18,7 @@ HOP_SIZE = 1.0 / FRAME_RATE + class ParticleFilterKorzeniowski(OnlineAlignment): """ Particle Filter described in @@ -26,7 +27,7 @@ class ParticleFilterKorzeniowski(OnlineAlignment): "Tracking Rests and Tempo Changes: Improved Score Following with Particle Filters" - ISMIR 2014. + ICMC 2013. Parameters ---------- @@ -60,10 +61,7 @@ def __init__( self.observation_type = observation_type.lower() if self.observation_type not in ("audio", "midi"): - raise ValueError( - "observation_type must be " - "'audio' or 'midi'." - ) + raise ValueError("observation_type must be " "'audio' or 'midi'.") self.notated_tempo = notated_tempo self.hop_size = hop_size @@ -106,7 +104,6 @@ def __init__( # initial particle weights are uniform self.weights = np.ones(num_particles) / num_particles - # strictness of matching expected and observed notes, used in the midi feature likelihood computation. Lower is stricter. self.note_sigma = 0.2 @@ -162,41 +159,34 @@ def __init__( self.loudness_weight = 0.10 if self.observation_type == "audio" else 0.0 self.last_onset_time = np.full( - self.num_particles, - self.previous_time, - dtype=np.float64, - ) - - self.small_mvt = (notated_tempo/3) * hop_size / 60.0 - self.large_mvt = (notated_tempo*3) * hop_size / 60.0 + self.num_particles, + self.previous_time, + dtype=np.float64, + ) + + self.small_mvt = (notated_tempo / 3) * hop_size / 60.0 + self.large_mvt = (notated_tempo * 3) * hop_size / 60.0 self.notated_mvt = notated_tempo * hop_size / 60.0 @property def warping_path(self): return np.array(self._alignment_path).T - def is_still_following(self): return True - @staticmethod def gaussian(x, mu, sigma): - return ( - np.exp(-0.5 * ((x - mu) / sigma) ** 2) - / (sigma * np.sqrt(2 * np.pi)) - ) - + return np.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * np.sqrt(2 * np.pi)) @staticmethod def log2tempo_to_bpm(m): - return 2.0 ** m - + return 2.0**m @staticmethod def bpm_to_log2(bpm): return np.log2(bpm) - + def beat_index( self, beat: float, @@ -229,7 +219,7 @@ def beat_index( return before return after - + def moving_average_tempo( self, local_tempo, @@ -248,18 +238,20 @@ def moving_average_tempo( bpm_local = self.log2tempo_to_bpm(local_tempo) bpm_note = self.log2tempo_to_bpm(note_tempo) - # For the particles in bpm_note that are 2 times faster than the notated tempo, snap them just below notated tempo with some Gaussian noise, - # and for the particles that are 2 times slower than the notated tempo, snap them just above notated tempo with some Gaussian noise. + # For the particles in bpm_note that are 2 times faster than the notated tempo, snap them just below notated tempo with some Gaussian noise, + # and for the particles that are 2 times slower than the notated tempo, snap them just above notated tempo with some Gaussian noise. # This is to prevent the moving average from being skewed by extreme values from the phase gain. bpm_note = np.where( bpm_note > 2 * self.notated_tempo, - self.notated_tempo + self.rng.normal( + self.notated_tempo + + self.rng.normal( -5, 5, ), np.where( bpm_note < self.notated_tempo / 2, - self.notated_tempo + self.rng.normal( + self.notated_tempo + + self.rng.normal( 5, 5, ), @@ -279,7 +271,7 @@ def phase_error( ) -> np.ndarray: """ Compute the normalized timing error for particles - that crossed a score onset, using the expected interval + that crossed a score onset, using the expected interval from their tempo and the actual time since the last onset. Returns @@ -298,65 +290,46 @@ def phase_error( dtype=np.float64, ) - valid = ( - (onset_idx > 0) - & (onset_idx < len(self.score_positions)) - ) + valid = (onset_idx > 0) & (onset_idx < len(self.score_positions)) if not np.any(valid): return phase valid_onset_idx = onset_idx[valid] - delta_score_positions = np.clip(valid_onset_idx - deltas[crossed][valid], 0, len(self.score_positions) - 1) + delta_score_positions = np.clip( + valid_onset_idx - deltas[crossed][valid], 0, len(self.score_positions) - 1 + ) crossed_indices = np.flatnonzero(crossed) valid_particle_indices = crossed_indices[valid] delta_beats = ( self.score_positions[valid_onset_idx] - - - self.score_positions[delta_score_positions] + - self.score_positions[delta_score_positions] ) - bps = ( - 2.0 ** self.m[valid_particle_indices] - ) / 60.0 + bps = (2.0 ** self.m[valid_particle_indices]) / 60.0 - expected_interval = ( - delta_beats - / bps - ) + expected_interval = delta_beats / bps - actual_interval = ( - current_time - - - self.last_onset_time[valid_particle_indices] - ) - - phase[valid] = ( - actual_interval - - - expected_interval - ) / (expected_interval * 60) + actual_interval = current_time - self.last_onset_time[valid_particle_indices] + phase[valid] = (actual_interval - expected_interval) / (expected_interval * 60) self.last_onset_time[valid_particle_indices] = current_time return phase - - + def is_rest_position(self, beat): idx = self.beat_index(beat) return self.score_model.rest_mask[idx] - def spectral_template(self, idx): return self.score_model.templates[idx] - def nearest_onset(self, idx): return self.score_model.nearest_onsets[idx] - + def sample_note_tempo( self, local_tempo, @@ -378,10 +351,7 @@ def sample_note_tempo( n = len(local_tempo) - choose_fast = ( - self.rng.rand(n) - < self.weight_fast - ) + choose_fast = self.rng.rand(n) < self.weight_fast sigma = np.where( choose_fast, @@ -394,7 +364,7 @@ def sample_note_tempo( scale=sigma, size=n, ) - + def predict_position(self): """ Equation (5). @@ -405,11 +375,7 @@ def predict_position(self): bpm = self.log2tempo_to_bpm(self.m) - delta_beats = ( - bpm - * (self.current_perf_time - self.previous_time) - / 60.0 - ) + delta_beats = bpm * (self.current_perf_time - self.previous_time) / 60.0 delta_beats = np.where( delta_beats > self.large_mvt, @@ -418,7 +384,7 @@ def predict_position(self): delta_beats < self.small_mvt, self.small_mvt, delta_beats, - ) + ), ) previous = self.x.copy() @@ -432,7 +398,6 @@ def predict_position(self): ) return previous - def update_tempi(self, previous_positions): """ @@ -473,11 +438,8 @@ def update_tempi(self, previous_positions): self.m[crossed], ) - self.m[crossed] = self.sample_note_tempo( - self.l[crossed] - ) + self.m[crossed] = self.sample_note_tempo(self.l[crossed]) - def predict(self): """ State transition. @@ -504,20 +466,11 @@ def propagate_sound_state(self): recursively. """ - sounding = np.empty_like( - self.sound_prob - ) + sounding = np.empty_like(self.sound_prob) - resting = np.empty_like( - self.rest_prob - ) + resting = np.empty_like(self.rest_prob) - rest_mask = np.array( - [ - self.is_rest_position(x) - for x in self.x - ] - ) + rest_mask = np.array([self.is_rest_position(x) for x in self.x]) # sounding score positions @@ -526,16 +479,10 @@ def propagate_sound_state(self): resting[~rest_mask] = 0.0 # rests - sounding[rest_mask] = ( - 0.8 - * self.sound_prob[rest_mask] - ) + sounding[rest_mask] = 0.8 * self.sound_prob[rest_mask] resting[rest_mask] = ( - 0.2 - * self.sound_prob[rest_mask] - + - self.rest_prob[rest_mask] + 0.2 * self.sound_prob[rest_mask] + self.rest_prob[rest_mask] ) total = sounding + resting @@ -543,7 +490,7 @@ def propagate_sound_state(self): self.sound_prob = sounding / total self.rest_prob = resting / total - + def onset_probability( self, beat, @@ -557,12 +504,8 @@ def onset_probability( d = beat - onset - return np.exp( - -(d ** 2) - / - (2 * self.sigma_onset ** 2) - ) - + return np.exp(-(d**2) / (2 * self.sigma_onset**2)) + def estimate_position(self): """ MAP estimate. @@ -575,14 +518,10 @@ def estimate_position(self): int(0.20 * self.num_particles), ) - idx = np.argsort( - self.weights - )[-n:] + idx = np.argsort(self.weights)[-n:] + + return float(np.mean(self.x[idx])) - return float( - np.mean(self.x[idx]) - ) - def spectral_probability( self, spectrum, @@ -606,7 +545,7 @@ def spectral_probability( ) return max(0.0, corr) - + def note_probability( self, observed_notes, @@ -638,21 +577,10 @@ def note_probability( if precision + recall == 0: return 0.0 - similarity = ( - 2.0 - * precision - * recall - / (precision + recall) - ) + similarity = 2.0 * precision * recall / (precision + recall) + + return np.exp(-0.5 * ((1.0 - similarity) / self.note_sigma) ** 2) - return np.exp( - -0.5 - * ( - (1.0 - similarity) - / self.note_sigma - ) ** 2 - ) - def onset_observation_probability( self, onset_feature, @@ -668,26 +596,14 @@ def onset_observation_probability( k = 10.0 if onset_present: + return 0.5 * (1.0 + np.tanh(k * (onset_feature - 0.5))) - return 0.5 * ( - 1.0 + - np.tanh( - k * (onset_feature - 0.5) - ) - ) + return 0.5 * (1.0 + np.tanh(k * (0.5 - onset_feature))) - return 0.5 * ( - 1.0 + - np.tanh( - k * (0.5 - onset_feature) - ) - ) - else: observed_onset = len(onset_feature) > 0 if onset_present: - return ( self.onset_match_probability if observed_onset @@ -699,7 +615,7 @@ def onset_observation_probability( if observed_onset else self.onset_match_probability ) - + def feature_probability( self, feature, @@ -716,7 +632,6 @@ def feature_probability( """ if self.observation_type == "audio": - return self.spectral_probability( feature, beat, @@ -724,19 +639,14 @@ def feature_probability( ) elif self.observation_type == "midi": - return self.note_probability( feature, beat, idx, ) - raise ValueError( - f"Unknown observation type " - f"{self.observation_type}" - ) - - + raise ValueError(f"Unknown observation type " f"{self.observation_type}") + def onset_probability_feature( self, onset_feature, @@ -755,14 +665,15 @@ def onset_probability_feature( self.onset_observation_probability( onset_feature, True, - ) * p_onset - + - self.onset_observation_probability( + ) + * p_onset + + self.onset_observation_probability( onset_feature, False, - ) * p_no + ) + * p_no ) - + def loudness_probability( self, loudness, @@ -786,12 +697,8 @@ def loudness_probability( 8, ) - return ( - self.sound_prob[particle] * ps - + - self.rest_prob[particle] * pr - ) - + return self.sound_prob[particle] * ps + self.rest_prob[particle] * pr + def compute_weights( self, observation, @@ -817,21 +724,17 @@ def compute_weights( loudness = observation.loudness if self.observation_type == "audio": - feature = observation.spectrum onset = observation.onset else: - feature = observation.active_notes onset = observation.onset_notes for i in range(self.num_particles): - beat = self.x[i] idx = self.beat_index(beat) - # Feature likelihood pf = self.feature_probability( feature, @@ -852,7 +755,6 @@ def compute_weights( i, ) - likelihood[i] = np.exp( self.feature_weight * np.log(max(pf, 1e-300)) + self.onset_weight * np.log(max(po, 1e-300)) @@ -863,30 +765,21 @@ def compute_weights( self.weights += 1e-300 - self.weights /= np.sum( - self.weights - ) + self.weights /= np.sum(self.weights) def effective_sample_size(self): + return 1.0 / np.sum(self.weights**2) - return 1.0 / np.sum( - self.weights ** 2 - ) - def systematic_resample(self): """ Low-variance systematic resampling. """ positions = ( - self.rng.rand() - + - np.arange(self.num_particles) + self.rng.rand() + np.arange(self.num_particles) ) / self.num_particles - cumulative = np.cumsum( - self.weights - ) + cumulative = np.cumsum(self.weights) indices = np.searchsorted( cumulative, @@ -901,9 +794,7 @@ def systematic_resample(self): self.rest_prob = self.rest_prob[indices] self.last_onset_time = self.last_onset_time[indices] - self.weights.fill( - 1.0 / self.num_particles - ) + self.weights.fill(1.0 / self.num_particles) def step( self, @@ -950,24 +841,17 @@ def step( estimate = self.estimate_position() - if ( - self.effective_sample_size() - < - self.resample_threshold - ): - + if self.effective_sample_size() < self.resample_threshold: self.systematic_resample() self.previous_position = self.current_position self.current_position = estimate return estimate - - + def get_current_position(self): return self.current_position - def __call__( self, observation, @@ -991,15 +875,8 @@ def __call__( return float(beat) - def run( self, verbose=True, ): - - return ( - yield from - super().run( - verbose=verbose - ) - ) \ No newline at end of file + return (yield from super().run(verbose=verbose)) diff --git a/matchmaker/registry.py b/matchmaker/registry.py index c83c433..47eab2c 100644 --- a/matchmaker/registry.py +++ b/matchmaker/registry.py @@ -211,6 +211,17 @@ def _reference_korzeniowski(mm): return score_processor(mm.score_part) +@reference_builder("score_cevts") +def _reference_score_cevts(mm): + """Score compound events: one MIDI pitch set per unique onset beat.""" + na = mm.score_part.note_array() + onset_beats = np.unique(na["onset_beat"]) + return [ + set(na["pitch"][na["onset_beat"] == ob].tolist()) + for ob in onset_beats + ] + + # --------------------------------------------------------------------------- # Argument resolution # --------------------------------------------------------------------------- diff --git a/matchmaker/utils/eval.py b/matchmaker/utils/eval.py index 615d54b..33996f9 100644 --- a/matchmaker/utils/eval.py +++ b/matchmaker/utils/eval.py @@ -7,6 +7,10 @@ TOLERANCES_IN_BEATS = [0.05, 0.1, 0.3, 0.5, 1, 2] ONSET_WINDOW_DURATION = 30.0 +#: SPARC resamples the held position path at this rate. Every audio frame rate +#: matchmaker uses (25, 30, 50 and 62.5 Hz) divides it, so each frame interval +#: spans a whole number of samples, and closely spaced MIDI updates stay apart. +SPARC_SAMPLE_RATE = 3000.0 def transfer_positions( @@ -240,10 +244,102 @@ def spectral_arc_length( return float(-np.hypot(np.diff(frequencies) / span, np.diff(spectrum)).sum()) +def windowed_spectral_arc_lengths( + position: np.ndarray, + fs: float, + edges: list, + padlevel: int = 4, + fc: float = 10.0, + amp_th: float = 0.05, +) -> list: + """``spectral_arc_length`` of ``|np.gradient(position[left:right])|`` per window. + + Returns one ``(value, reason)`` per ``(left, right)`` in ``edges``, with + ``reason`` one of "ok", "stationary" or "undefined_band", and the same values + as slicing every window and calling ``spectral_arc_length``, without its cost + at high rates. A held position makes the speed zero except where a report + changes it, and SPARC reads only the bins up to ``fc``. So each window's + spectrum is kept as a running sum of its nonzero speed samples, evaluated at + those bins only, while the windows slide forward; ``np.gradient`` is + one-sided at a slice's ends, so the two edge samples are corrected per window. + + ``edges`` must not decrease in either bound, which holds for onset-wise + windows. ``position`` may be NaN before the first report, but not within a + window. + """ + position = np.asarray(position, dtype=float) + if len(position) < 2: + return [(None, "insufficient_samples")] * len(edges) + speed = np.nan_to_num(np.abs(np.gradient(position, 1.0 / fs)), nan=0.0) + nonzero = np.flatnonzero(speed) + results = [None] * len(edges) + groups = {} + for i, (left, right) in enumerate(edges): + if right - left < 2: + results[i] = (None, "insufficient_samples") + continue + n_fft = int(2 ** (np.ceil(np.log2(right - left)) + padlevel)) + groups.setdefault(n_fft, []).append(i) + + for n_fft, members in groups.items(): + frequencies = np.fft.rfftfreq(n_fft, d=1.0 / fs) + frequencies = frequencies[: np.flatnonzero(frequencies <= fc)[-1] + 1] + # At low rates nearly every speed sample is nonzero and the band up to + # fc is a large share of the spectrum: there, plain per-window FFTs + # are cheaper. Both routes give the same values. A complex exponential + # in the sliding loop costs about 20 FFT operations. + first_left, last_right = edges[members[0]][0], edges[members[-1]][1] + in_span = np.searchsorted(nonzero, last_right) - np.searchsorted(nonzero, first_left) + sliding_cost = 20 * 2 * (in_span + len(members)) * len(frequencies) + if len(members) * n_fft * np.log2(n_fft) < sliding_cost: + for i in members: + left, right = edges[i] + local_speed = np.abs(np.gradient(position[left:right], 1.0 / fs)) + value = spectral_arc_length(local_speed, fs, padlevel, fc, amp_th) + reason = "ok" if value is not None else ( + "undefined_band" if np.any(local_speed) else "stationary" + ) + results[i] = (value, reason) + continue + omega = -2j * np.pi * np.arange(len(frequencies)) / n_fft + spectrum = np.zeros(len(frequencies), dtype=complex) + low = high = 0 + for i in members: + left, right = edges[i] + while high < len(nonzero) and nonzero[high] < right: + spectrum += speed[nonzero[high]] * np.exp(omega * nonzero[high]) + high += 1 + while low < high and nonzero[low] < left: + spectrum -= speed[nonzero[low]] * np.exp(omega * nonzero[low]) + low += 1 + first = abs(position[left + 1] - position[left]) * fs + last = abs(position[right - 1] - position[right - 2]) * fs + inner = np.searchsorted(nonzero, right - 1) - np.searchsorted(nonzero, left + 1) + if inner == 0 and first == 0 and last == 0: + results[i] = (None, "stationary") + continue + local = ( + spectrum + + (first - speed[left]) * np.exp(omega * left) + + (last - speed[right - 1]) * np.exp(omega * (right - 1)) + ) + # The speed is nonnegative, so the DC bin is the spectrum's maximum. + magnitude = np.abs(local) / local[0].real + support = np.flatnonzero(magnitude >= amp_th) + if len(support) < 2: + results[i] = (None, "undefined_band") + continue + band = slice(support[0], support[-1] + 1) + span = frequencies[band][-1] - frequencies[band][0] + value = -np.hypot(np.diff(frequencies[band]) / span, np.diff(magnitude[band])).sum() + results[i] = (float(value), "ok") + return results + + def compute_sparc( score_beat: np.ndarray, perf_sec: np.ndarray, - fs: float = 50.0, + fs: float = SPARC_SAMPLE_RATE, fc: float = 10.0, padlevel: int = 4, *, @@ -254,9 +350,9 @@ def compute_sparc( ) -> Union[float, dict, None]: """Mean adaptive SPARC over GT onset-wise windows, without time weights. - Each window uses the full position trajectory resampled at ``fs``, holding - the last reported position between updates, rather than sampling positions - only at onsets. Stationary/undefined windows are omitted from the mean; an + Each window uses the full position trajectory resampled at ``fs`` (by + default ``SPARC_SAMPLE_RATE``), holding the last reported position between + updates, rather than sampling positions only at onsets. Stationary/undefined windows are omitted from the mean; an entirely undefined path returns None. Pass the same GT ``onset_times`` for every follower being compared, as @@ -284,7 +380,6 @@ def compute_sparc( ) diagnostics = [] values = [] - cached_windows = {} if windows and len(perf_sec) >= 2: times = np.arange(windows[0]["t0"], windows[-1]["t1"], 1.0 / fs) report_indices = np.searchsorted(perf_sec, times, side="right") - 1 @@ -293,24 +388,29 @@ def compute_sparc( positions[has_report] = score_beat[report_indices[has_report]] else: times, positions = np.array([]), np.array([]) - for window in windows: + # Sample range of each window the path covers; windows with the same range + # share one value. + keys = {} + for i, window in enumerate(windows): start, stop = window["t0"], window["t1"] - value, reason = None, "insufficient_samples" - if len(perf_sec) >= 2 and (start < perf_sec[0] or stop > perf_sec[-1]): - reason = "uncovered" - elif len(times): + if len(times) and not (start < perf_sec[0] or stop > perf_sec[-1]): left, right = np.searchsorted(times, [start, stop], side="left") - key = (int(left), int(right)) - if key not in cached_windows: - position = positions[left:right] - if len(position) >= 2: - speed = np.abs(np.gradient(position, 1.0 / fs)) - value = spectral_arc_length(speed, fs, padlevel, fc, amp_th) - reason = "stationary" if not np.any(speed) else "undefined_band" - if value is not None: - reason = "ok" - cached_windows[key] = value, reason - value, reason = cached_windows[key] + keys[i] = (int(left), int(right)) + unique = sorted(set(keys.values())) + computed = dict( + zip( + unique, + windowed_spectral_arc_lengths(positions, fs, unique, padlevel, fc, amp_th), + ) + ) + for i, window in enumerate(windows): + start, stop = window["t0"], window["t1"] + if i in keys: + value, reason = computed[keys[i]] + elif len(perf_sec) >= 2 and (start < perf_sec[0] or stop > perf_sec[-1]): + value, reason = None, "uncovered" + else: + value, reason = None, "insufficient_samples" diagnostics.append({"t0": start, "t1": stop, "sparc": value, "reason": reason}) if value is not None: values.append(value) diff --git a/pyproject.toml b/pyproject.toml index 642d2ee..4965cc6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pymatchmaker" -version = "0.4.0" +version = "0.5.0" description = "A package for real-time music alignment" readme = "README.md" requires-python = ">=3.10,<3.14" diff --git a/run_examples.py b/run_examples.py index bda7b6d..81b1f42 100644 --- a/run_examples.py +++ b/run_examples.py @@ -49,9 +49,9 @@ def evaluate(mm, match_file): def save_tsv(rows, path): - with open(path, "w") as f: + with open(path, "w", newline="") as f: f.write("perf_sec\tscore_beat\n") - csv.writer(f, delimiter="\t").writerows(rows) + csv.writer(f, delimiter="\t", lineterminator="\n").writerows(rows) def plot_alignment_path(perf_sec, score_beat, gt_perf, gt_score, save_path, run_name): diff --git a/tests/test_dannenberg.py b/tests/test_dannenberg.py new file mode 100644 index 0000000..3382dd1 --- /dev/null +++ b/tests/test_dannenberg.py @@ -0,0 +1,292 @@ +"""Tests for the Dannenberg 1985 DP score follower. + +Test scenario based on Figure 2.7 from: + + Bloch, J. & Dannenberg, R.B. (1985). Real-Time Computer Accompaniment + of Keyboard Performances. Proc. ICMC, 279-289. + +Score (three chords at beats 0, 1, 2): + A0 = {A3, G4, E4} = {57, 67, 64} + A1 = {G4} = {67} + A2 = {A3, B3, C4} = {57, 59, 60} + +Performance: the score notes played in order with ~30-50 ms spacing +within each chord, plus an extra D4 (62) inserted before the third +chord. +""" + +import unittest + +import numpy as np + +from matchmaker.dp.dannenberg import DPDannenberg + + +def _make_follower(**overrides): + """Build a DPDannenberg for the three-chord Figure 2.7 example.""" + score_cevts = [{57, 67, 64}, {67}, {57, 59, 60}] + score_positions = np.array([0.0, 1.0, 2.0]) + defaults = dict( + reference_features=score_cevts, + score_positions=score_positions, + tempo=120.0, + window=50, + c_m=0.5, + c_e=0.0, + epsilon=0.090, + epsilon_fraction=0.25, + smoothing=0.5, + ) + defaults.update(overrides) + return DPDannenberg(**defaults) + + +def _feed(follower, notes): + """Feed (pitch, time) pairs through __call__.""" + for pitch, t in notes: + follower(np.array([pitch]), t) + + +class TestDPDannenbergInit(unittest.TestCase): + def test_initial_column_penalises_skipped_cevts(self): + f = _make_follower() + np.testing.assert_allclose(f._values, [0.0, -1.5, -2.0]) + + def test_wrong_first_note_does_not_jump_to_end(self): + # Score C-D-E; performance starts with a wrong E. + f = _make_follower( + reference_features=[{60}, {62}, {64}], + score_positions=np.array([0.0, 1.0, 2.0]), + ) + _feed(f, [(64, 0.0)]) + self.assertTrue(f.is_still_following()) + + def test_state_dimensions(self): + f = _make_follower() + self.assertEqual(f.n_states, 3) + self.assertEqual(len(f._values), 3) + self.assertEqual(len(f._used), 3) + self.assertEqual(len(f._prev_values), 3) + self.assertEqual(len(f._prev_used), 3) + + def test_initial_position(self): + f = _make_follower() + self.assertEqual(f.current_index, 0) + self.assertAlmostEqual(f.get_current_position(), 0.0) + + def test_initial_tempo(self): + f = _make_follower(tempo=60.0) + self.assertAlmostEqual(f._beats_per_second, 1.0) + + def test_is_still_following_at_start(self): + f = _make_follower() + self.assertTrue(f.is_still_following()) + + +class TestDPDannenbergStep(unittest.TestCase): + """DP update logic using the three-chord example.""" + + def test_first_chord_all_notes_matched(self): + """All three notes of chord A0 should be matched.""" + f = _make_follower() + _feed(f, [ + (57, 0.00), # A3 + (67, 0.03), # G4 + (64, 0.05), # E4 + ]) + self.assertEqual(f.current_index, 0) + self.assertAlmostEqual(f._values[0], 3.0) + self.assertEqual(f._used[0], {57, 67, 64}) + + def test_advance_to_second_chord(self): + """After chord A0 is done, a G4 at a later time advances to A1.""" + f = _make_follower() + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + (67, 0.50), # G4 — matches A1 + ]) + self.assertEqual(f.current_index, 1) + + def test_extra_note_no_penalty_default_c_e(self): + """With c_e=0 an extra D4 does not decrease the best value.""" + f = _make_follower(c_e=0.0) + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + (67, 0.50), + ]) + val_before = f._best_value + _feed(f, [(62, 0.80)]) # D4 extra + self.assertGreaterEqual(f._best_value, val_before) + + def test_extra_note_with_c_e_penalty(self): + """With c_e > 0 an extra note not in B subtracts from z_val.""" + f = _make_follower(c_e=1.0) + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + (67, 0.50), + ]) + val_before = float(f._values[f.current_index]) + _feed(f, [(62, 0.80)]) # D4 extra — penalty applied + val_after = float(f._values[f.current_index]) + self.assertLess(val_after, val_before + 1) + + def test_full_performance_reaches_last_chord(self): + """Play all chords; the follower should reach A2.""" + f = _make_follower() + _feed(f, [ + (57, 0.00), # A0: A3 + (67, 0.03), # A0: G4 + (64, 0.05), # A0: E4 + (67, 0.50), # A1: G4 + (62, 0.80), # extra D4 + (57, 1.00), # A2: A3 + (59, 1.03), # A2: B3 + (60, 1.05), # A2: C4 + ]) + self.assertEqual(f.current_index, 2) + + def test_is_still_following_false_at_end(self): + """Once the last score event is matched, is_still_following is False.""" + f = _make_follower() + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + (67, 0.50), + (57, 1.00), + (59, 1.03), + (60, 1.05), + ]) + self.assertFalse(f.is_still_following()) + + def test_missing_note_c_m_penalty(self): + """c_m penalty reduces diagonal advance value for missing notes.""" + f_no = _make_follower(c_m=0.0) + f_hi = _make_follower(c_m=1.0) + notes = [ + (57, 0.00), + (67, 0.03), + (67, 0.50), + ] + _feed(f_no, notes) + _feed(f_hi, notes) + # With c_m=0 no penalty for the missing E4 in A0; with c_m=1 + # the advance to row 1 loses 1 point for the missing note. + self.assertGreater(f_no._values[1], f_hi._values[1]) + + +class TestDPDannenbergIsNewCevt(unittest.TestCase): + """Epsilon and epsilon-fraction grouping (Sec. 5).""" + + def test_first_note_is_always_new(self): + f = _make_follower() + self.assertTrue(f._is_new_cevt(0.0)) + + def test_note_within_epsilon_is_same_cevt(self): + f = _make_follower(epsilon=0.090) + f._prev_note_time = 0.0 + self.assertFalse(f._is_new_cevt(0.05)) + + def test_note_beyond_epsilon_is_new_cevt(self): + f = _make_follower(epsilon=0.090) + f._prev_note_time = 0.0 + self.assertTrue(f._is_new_cevt(0.10)) + + def test_epsilon_fraction_triggers_new_cevt(self): + f = _make_follower(epsilon=1.0, epsilon_fraction=0.1) + f._prev_note_time = 0.0 + f._beats_per_second = 2.0 + f._best_row = 0 + # beat_gap = 1.0, predicted_dt = 0.5, threshold = 0.05 + self.assertTrue(f._is_new_cevt(0.06)) + + def test_epsilon_fraction_no_trigger_when_close(self): + f = _make_follower(epsilon=1.0, epsilon_fraction=0.5) + f._prev_note_time = 0.0 + f._beats_per_second = 2.0 + f._best_row = 0 + # beat_gap = 1.0, predicted_dt = 0.5, threshold = 0.25 + self.assertFalse(f._is_new_cevt(0.20)) + + def test_epsilon_fraction_skipped_at_last_row(self): + f = _make_follower(epsilon=1.0, epsilon_fraction=0.01) + f._prev_note_time = 0.0 + f._best_row = 2 # last row + # No next row to compute beat_gap, so only epsilon matters. + self.assertFalse(f._is_new_cevt(0.5)) + + +class TestDPDannenbergGetCurrentPosition(unittest.TestCase): + def test_position_at_anchor(self): + f = _make_follower() + f._anchor_beat = 1.0 + f._anchor_time = 0.5 + f.current_perf_time = 0.5 + self.assertAlmostEqual(f.get_current_position(), 1.0) + + def test_position_interpolated(self): + f = _make_follower(tempo=120.0) + f._anchor_beat = 0.0 + f._anchor_time = 0.0 + f.current_perf_time = 0.25 + pos = f.get_current_position() + # 120 BPM = 2 beats/s, 0.25s drift = 0.5 beats + self.assertAlmostEqual(pos, 0.5) + + def test_position_capped_at_next_beat(self): + f = _make_follower(tempo=120.0) + f._anchor_beat = 0.0 + f._anchor_time = 0.0 + f.current_index = 0 + f.current_perf_time = 5.0 # way ahead + pos = f.get_current_position() + # Capped at score_positions[1] = 1.0 + self.assertAlmostEqual(pos, 1.0) + + def test_position_not_capped_at_last_state(self): + f = _make_follower(tempo=120.0) + f._anchor_beat = 2.0 + f._anchor_time = 1.0 + f.current_index = 2 # last state + f.current_perf_time = 1.5 + pos = f.get_current_position() + # No cap since current_index + 1 == n_states + self.assertAlmostEqual(pos, 3.0) + + +class TestDPDannenbergTempoTracking(unittest.TestCase): + def test_tempo_updates_on_advance(self): + f = _make_follower(tempo=120.0, smoothing=0.0) + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + ]) + initial_bps = f._beats_per_second + _feed(f, [(67, 1.00)]) # advance to beat 1.0 at time 1.0 + # With smoothing=0, the tempo is purely the new rate. + # beat advance = 1.0, time elapsed ~1.0 → rate ~ 1.0 + self.assertNotAlmostEqual(f._beats_per_second, initial_bps) + + def test_smoothing_blends_old_and_new(self): + f = _make_follower(tempo=120.0, smoothing=0.5) + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + ]) + _feed(f, [(67, 1.00)]) + # smoothing=0.5 blends: 0.5 * 2.0 + 0.5 * new_rate + bps = f._beats_per_second + self.assertGreater(bps, 0.5) + self.assertLess(bps, 3.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_io_audio.py b/tests/test_io_audio.py index 2fdedb9..b6e86e2 100644 --- a/tests/test_io_audio.py +++ b/tests/test_io_audio.py @@ -102,7 +102,15 @@ def test_stream_init(self, mock_stdout): ) self.assertTrue(isinstance(stream, AudioStream)) - self.assertTrue(stream.input_device_index == ad.device_index) + # Names are not unique on Windows, where each device is + # listed once per host API (MME, DirectSound, WASAPI, ...), + # so the name may resolve to another device of that name. + selected = [ + d + for d in audio_devices + if d.device_index == stream.input_device_index + ] + self.assertTrue(selected[0].name == ad.name) # Set audio device from index stream = AudioStream( diff --git a/tests/test_utils_eval_sparc.py b/tests/test_utils_eval_sparc.py index f07fd86..b088988 100644 --- a/tests/test_utils_eval_sparc.py +++ b/tests/test_utils_eval_sparc.py @@ -6,10 +6,12 @@ import numpy as np from matchmaker.utils.eval import ( + SPARC_SAMPLE_RATE, compute_sparc, evaluate_alignment, onset_wise_windows, spectral_arc_length, + windowed_spectral_arc_lengths, ) @@ -49,6 +51,45 @@ def test_stationary_speed_is_undefined(self): self.assertIsNone(spectral_arc_length(np.array([1.0]), fs=50)) +class TestWindowedSpectralArcLengths(unittest.TestCase): + def test_default_rate_spans_every_audio_frame_interval(self): + self.assertEqual(compute_sparc.__defaults__[0], SPARC_SAMPLE_RATE) + for frame_rate in (25, 30, 50, 62.5): + self.assertEqual(SPARC_SAMPLE_RATE % frame_rate, 0) + + def test_matches_slicing_each_window(self): + rng = np.random.default_rng(0) + for fs in (50.0, SPARC_SAMPLE_RATE): + # A held path: reports at irregular times, a stall, and a jump back. + times = np.arange(0.0, 40.0, 1.0 / fs) + reports = np.sort(rng.uniform(0.0, 40.0, 300)) + beats = np.cumsum(rng.uniform(-0.1, 0.5, 300)) + beats[100:140] = beats[100] + position = beats[np.clip(np.searchsorted(reports, times, side="right") - 1, 0, None)] + edges = [ + tuple(np.searchsorted(times, [w["t0"], w["t1"]])) + for w in onset_wise_windows(np.sort(rng.uniform(0.0, 40.0, 25))) + ] + for (left, right), (value, reason) in zip( + edges, windowed_spectral_arc_lengths(position, fs, edges) + ): + speed = np.abs(np.gradient(position[left:right], 1.0 / fs)) + expected = spectral_arc_length(speed, fs) + with self.subTest(fs=fs, left=left, right=right): + if expected is None: + self.assertIsNone(value) + else: + self.assertAlmostEqual(value, expected, places=9) + self.assertEqual(reason, "ok") + + def test_stationary_window(self): + position = np.r_[np.zeros(100), np.ones(100)] + self.assertEqual( + windowed_spectral_arc_lengths(position, 50.0, [(0, 100)]), + [(None, "stationary")], + ) + + class TestPathSparc(unittest.TestCase): def details(self, beats, times, onsets): return compute_sparc(beats, times, onset_times=onsets, return_details=True) @@ -60,8 +101,11 @@ def test_alignment_result_reports_rounded_smoothness(self): self.assertEqual(result["smoothness"], round(compute_sparc(beats, times), 4)) def test_short_constant_speed_is_evaluated(self): + # Sampled at the 50 Hz report rate, the held path is a constant speed. times = np.arange(0.0, 10.02, 0.02) - result = self.details(times, times, np.array([0.0, 5.0, 10.0])) + result = compute_sparc( + times, times, fs=50, onset_times=np.array([0.0, 5.0, 10.0]), return_details=True + ) self.assertIsNotNone(result["sparc"]) self.assertEqual(result["sparc_n_windows"], 1) self.assertEqual(result["sparc_n_valid_windows"], 1) diff --git a/tests/test_utils_symbolic.py b/tests/test_utils_symbolic.py index d4c3445..e73ab94 100644 --- a/tests/test_utils_symbolic.py +++ b/tests/test_utils_symbolic.py @@ -4,6 +4,7 @@ Tests for matchmaker/utils/partitura.py """ +import os import time import unittest from tempfile import NamedTemporaryFile @@ -81,7 +82,10 @@ def test_midi_messages_from_midi(self): """ Tests for `midi_messages_from_midi`. """ - tmp_file = NamedTemporaryFile(delete=True) + # Closed before writing: Windows can't reopen a file that is still open. + tmp_file = NamedTemporaryFile(suffix=".mid", delete=False) + tmp_file.close() + self.addCleanup(os.remove, tmp_file.name) perf = generate_random_performance_note_array( return_performance=True, ) @@ -103,8 +107,6 @@ def test_midi_messages_from_midi(self): self.assertTrue(np.all(np.diff(message_times) >= 0)) - tmp_file.close() - def test_framed_midi_messages_from_midi(self): """ Tests for `framed_midi_messages_from_midi` diff --git a/tests/utils.py b/tests/utils.py index b943e34..8c870da 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -5,6 +5,7 @@ """ import numbers +import os import tempfile import threading import wave @@ -319,8 +320,10 @@ def process_audio_offline( # TODO modify mock audio stream to handle # an input numpy array - # Create a temporary file and get its path - temp_file = tempfile.NamedTemporaryFile(delete=True, suffix=".wav") + # Create a temporary file and get its path. It is closed before + # writing, since Windows can't reopen a file that is still open. + temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav") + temp_file.close() file_path = temp_file.name save_wav_fluidsynth( @@ -343,7 +346,7 @@ def process_audio_offline( outputs = [item[0] for item in list(queue.queue)] if temp_file is not None: - temp_file.close() + os.remove(file_path) return outputs @@ -365,6 +368,7 @@ def generate_sine_wave( # Create a temporary file temp_file = tempfile.NamedTemporaryFile(suffix=".wav", delete=False) + temp_file.close() file_path = temp_file.name # Save the sine wave to a WAV file