Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# Changes

## Version 0.5.1

### Fixed

- `AudioStream` file input with `wait=True` supplies each audio block at its playback time on a separate thread, so slow processing no longer drifts the input timing.

### Changed

- Faster forward step for the pitch HMM followers (`"pthmm"`, `"hmm"`).
- Read the Docs builds take the version from the installed package.

## Version 0.5.0

### Added
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ Default method: `"pthmm"`
| `"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) |
| `"dannenberg"` | Dynamic-programming score follower by Bloch and Dannenberg (1985) |
| `"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) |
Expand Down
1 change: 0 additions & 1 deletion docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
pymatchmaker
myst-parser>=3.0.1
sphinx>=7.4.7
sphinx-rtd-theme>=3.0.2
8 changes: 3 additions & 5 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,12 @@

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import sys

sys.path.insert(0, os.path.abspath(".."))
import importlib.metadata

project = "pymatchmaker"
copyright = "2024, matchmaker development team"
author = "matchmaker development team"
release = "0.5.0"
release = importlib.metadata.version("pymatchmaker")

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
Expand All @@ -25,6 +22,7 @@
"sphinx.ext.todo",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
"sphinx.ext.napoleon",
"sphinx.ext.viewcode",
"myst_parser",
]
Expand Down
15 changes: 2 additions & 13 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
.. pymatchmaker documentation master file, created by
sphinx-quickstart on Tue Dec 3 17:52:36 2024.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.

Welcome to Matchmaker's Documentation!
======================================

.. include:: ../../README.md
:parser: myst_parser.sphinx_
:start-after: # Matchmaker
:end-before: ## Setup

.. toctree::
:maxdepth: 0
:caption: Contents

introduction
install
usage
configurations
Expand All @@ -35,10 +31,3 @@ Indices and tables
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

Acknowledgements
----------------
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).
7 changes: 0 additions & 7 deletions docs/source/introduction.rst

This file was deleted.

22 changes: 18 additions & 4 deletions docs/source/modules/matchmaker.dp.rst
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
matchmaker.dp
=============

.. autoclass:: matchmaker.dp.oltw_dixon.OnlineTimeWarpingDixon
:members: run
.. autoclass:: matchmaker.dp.OnlineTimeWarpingDixonFrame
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.dp.oltw_arzt.OnlineTimeWarpingArzt
:members: run
.. autoclass:: matchmaker.dp.OnlineTimeWarpingDixonEvent
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.dp.OnlineTimeWarpingArztFrame
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.dp.OnlineTimeWarpingArztEvent
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.dp.OnlineTimeWarpingArztMultiFold
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.dp.DPDannenberg
:show-inheritance:
:special-members: __init__
25 changes: 22 additions & 3 deletions docs/source/modules/matchmaker.prob.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
matchmaker.prob
=======================
===============

.. autoclass:: matchmaker.prob.hmm.PitchIOIHMM
:members: run
.. autoclass:: matchmaker.prob.PitchHMM
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.prob.PitchIOIHMM
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.prob.OuterProductHMM
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.prob.AudioOuterProductHMM
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.prob.particle_filter_korzeniowski.ParticleFilterKorzeniowski
:show-inheritance:
:special-members: __init__

.. autoclass:: matchmaker.prob.skf.SwitchingKalmanFilterFollower
:show-inheritance:
:special-members: __init__
10 changes: 10 additions & 0 deletions docs/source/modules/matchmaker.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,13 @@ matchmaker
:members: run
:show-inheritance:
:special-members: __init__

Every score follower implements the ``OnlineAlignment`` interface.

.. autoclass:: matchmaker.base.OnlineAlignment
:members: step, run, get_current_position
:special-members: __call__

.. autoclass:: matchmaker.external.OnlineParangonarAlignment
:show-inheritance:
:special-members: __init__
2 changes: 1 addition & 1 deletion matchmaker/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
try:
__version__ = version("pymatchmaker")
except PackageNotFoundError: # pragma: no cover
__version__ = "0.5.0"
__version__ = "0.5.1"

ASSETS_DIR = Path(__file__).parent / "assets"

Expand Down
69 changes: 53 additions & 16 deletions matchmaker/io/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""

import queue
import threading
import time
from types import TracebackType
from typing import Dict, Optional, Tuple, Type, Union
Expand Down Expand Up @@ -52,6 +53,10 @@ class AudioStream(Stream):
Name or index of the audio device to be used. Ignored
if ``file_path`` is given.

wait : bool
For file input, supply each complete audio block at its playback time
on a separate thread. Processing can lag behind but input is not dropped.

Notes
-----
Frame caching: each call to ``_process_feature`` prepends
Expand Down Expand Up @@ -301,25 +306,57 @@ def run_offline(self) -> None:
audio_y = np.concatenate(
(audio_y, np.zeros(self.hop_length - remainder, dtype=np.float32))
)
trimmed_audio = audio_y
time_interval = self.hop_length / float(sr)
# Do not stop early on digital silence (all-zeros tails).
while trimmed_audio.size > 0:
self.input_index += 1
self.last_data_received = time.time()
target_audio = trimmed_audio[: self.hop_length]
self._process_feature(target_audio, self.last_data_received)
trimmed_audio = trimmed_audio[self.hop_length :]
feeder = None
stop_feeder = threading.Event()
if self.wait:
data_queue = queue.Queue()
feeder = threading.Thread(
target=self._enqueue_audio, args=(audio_y, data_queue, stop_feeder)
)
feeder.start()
blocks = iter(data_queue.get, None)
else:
blocks = (
(audio_y[start : start + self.hop_length], time.time())
for start in range(0, len(audio_y), self.hop_length)
)

if not self.stream_start.is_set():
try:
for target_audio, received_time in blocks:
if not self.listen:
break
self.input_index += 1
self.last_data_received = received_time
self._process_feature(target_audio, received_time)
self.stream_start.set()
finally:
stop_feeder.set()
if feeder is not None:
feeder.join()
self.queue.put(STREAM_END)
self.stream_start.set()
self.stop_listening()

if self.wait:
elapsed_time = time.time() - self.last_data_received
time.sleep(max(time_interval - elapsed_time, 0))

self.queue.put(STREAM_END)
self.stop_listening()
def _enqueue_audio(self, audio_y, data_queue, stop_event) -> None:
"""Supply raw blocks at their end times, independently of processing."""
self._playback_start = time.perf_counter()
try:
for start in range(0, len(audio_y), self.hop_length):
end = start + self.hop_length
deadline = self._playback_start + end / float(self.target_sr)
# Absolute deadlines prevent accumulated sleep/processing drift.
# A block is not available until all its samples have arrived.
while True:
remaining = deadline - time.perf_counter()
if remaining <= 0:
break
if stop_event.wait(remaining):
return
if stop_event.is_set():
return
data_queue.put((audio_y[start:end], time.time()))
finally:
data_queue.put(None)

def run_online(self) -> None:
"""Process audio in real-time from input device.
Expand Down
58 changes: 49 additions & 9 deletions matchmaker/prob/hmm.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,7 @@ def _build_hmm_modules(
# observation model
observation_model = BernoulliPitchObservationModel(
pitch_profiles=pitch_profiles,
inserted_states=inserted_states,
)

if inserted_states:
Expand Down Expand Up @@ -932,9 +933,12 @@ class BernoulliPitchObservationModel(ObservationModel):
Pre-computed pitch profiles, for each separate possible pitch
in the MIDI range. Used in calculating the pitch observation
probabilities.
inserted_states : bool, optional
If True, odd states share one uniform profile, evaluated once.
Default is False.
"""

def __init__(self, pitch_profiles: NDArrayFloat):
def __init__(self, pitch_profiles: NDArrayFloat, inserted_states: bool = False):
"""
The initialization method.

Expand All @@ -944,16 +948,23 @@ def __init__(self, pitch_profiles: NDArrayFloat):
he pre-computed pitch profiles, for each separate possible pitch
in the MIDI range. Used in calculating the pitch observation
probabilities.
inserted_states : bool, optional
If True, odd states share one uniform profile, evaluated once.
Default is False.
"""
super().__init__(use_log_probabilities=False)
# Store the parameters of the object:
self.pitch_profiles = pitch_profiles
self.inserted_states = inserted_states

def __call__(self, observation: NDArrayFloat) -> NDArrayFloat:
return compute_bernoulli_pitch_probabilities(
pitch_obs=observation,
pitch_profiles=self.pitch_profiles,
)
if not self.inserted_states or len(self.pitch_profiles) < 2:
return compute_bernoulli_pitch_probabilities(observation, self.pitch_profiles)
# inserted states (odd indices) share one uniform profile: evaluate it once
obs_prob = np.empty(len(self.pitch_profiles))
obs_prob[0::2] = compute_bernoulli_pitch_probabilities(observation, self.pitch_profiles[0::2])
obs_prob[1::2] = compute_bernoulli_pitch_probabilities(observation, self.pitch_profiles[1:2])[0]
return obs_prob


class GaussianAudioPitchObservationModel(ObservationModel):
Expand Down Expand Up @@ -1536,6 +1547,15 @@ def __init__(
**kwargs,
)

# Rightmost non-zero transition column per row; the cumulative max bounds row slices.
self._last_col = None
if isinstance(self.transition_model, ConstantTransitionModel):
self.transition_model.use_log_probabilities = False
T = self.transition_model.transition_probabilities
self._last_col = np.maximum.accumulate(
len(T) - 1 - np.argmax(T[:, ::-1] != 0, axis=1)
)

def step(self, features) -> None:
perf_time = self.current_perf_time
ioi_obs = (
Expand All @@ -1545,10 +1565,30 @@ def step(self, features) -> None:
)
self._prev_perf_time = perf_time

current_state = self.forward_algorithm_step(
observation=(features, ioi_obs, self.tempo_model.beat_period),
log_probabilities=False,
)
observation = (features, ioi_obs, self.tempo_model.beat_period)
fv = self.forward_variable

# The first step uses the initial distribution; other transition models use the original path.
if self._last_col is None or fv is None:
current_state = self.forward_algorithm_step(
observation=observation, log_probabilities=False
)
else:
self.transition_model.use_log_probabilities = False
self.observation_model.use_log_probabilities = False
prior = np.zeros_like(fv)
nz = np.flatnonzero(fv)
if nz.size:
lo, hi = nz[0], nz[-1] + 1
m = self._last_col[hi - 1] + 1

# Restrict T.T @ fv to reached states; this slice form keeps the product BLAS-friendly.
prior[:m] = fv[lo:hi] @ self.transition_model.transition_probabilities[lo:hi, :m]
fv = self.observation_model(observation) * prior
fv /= max(fv.sum(), 1e-6)
self.forward_variable = fv
current_state = np.argmax(fv)

self.input_index += 1

prev_index = self.current_index
Expand Down
7 changes: 4 additions & 3 deletions matchmaker/prob/skf.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,10 @@ class SwitchingKalmanFilterFollower(OnlineAlignment):
Each hypothesis is a tuple (k, a) where k is the chord index and a is
the age (number of frames the current chord has lasted). Each hypothesis
carries:
- prob : float, filtered probability p(k_n, a_n | y^n_1)
- mu_t : float, Kalman-filtered tempo mean E[t_k | ...]
- var_t: float, Kalman-filtered tempo variance Var[t_k | ...]

- prob : float, filtered probability p(k_n, a_n | y^n_1)
- mu_t : float, Kalman-filtered tempo mean E[t_k | ...]
- var_t: float, Kalman-filtered tempo variance Var[t_k | ...]

Parameters
----------
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "pymatchmaker"
version = "0.5.0"
version = "0.5.1"
description = "A package for real-time music alignment"
readme = "README.md"
requires-python = ">=3.10,<3.14"
Expand Down
Loading