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
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__
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
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
130 changes: 130 additions & 0 deletions tests/test_io_audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,3 +309,133 @@ def test_process_frame(self):
(np.zeros(self.stream.hop_length, dtype=np.float32), original_data)
)
self.assertTrue(np.all(proc_output == expected_output))


class TestPacedFileInput(unittest.TestCase):
def test_absolute_block_end_deadlines(self):
import queue
from types import SimpleNamespace

clock = [100.0]
arrivals = []

class StopEvent:
def wait(self, duration):
# Simulate a scheduler that oversleeps each deadline by 3 ms.
clock[0] += duration + 0.003
return False

def is_set(self):
return False

class InputQueue(queue.Queue):
def _put(self, item):
if item is not None:
arrivals.append(clock[0])
super()._put(item)

stream = SimpleNamespace(hop_length=20, target_sr=1000)
source = np.arange(100, dtype=np.float32)
q = InputQueue()
with patch.object(time, "perf_counter", side_effect=lambda: clock[0]):
AudioStream._enqueue_audio(stream, source, q, StopEvent())
np.testing.assert_allclose(
np.asarray(arrivals) - 100, np.arange(1, 6) * 0.02 + 0.003
)
np.testing.assert_array_equal(
np.concatenate([q.get()[0] for _ in range(5)]), source
)
self.assertIsNone(q.get_nowait())

def test_feeder_can_be_cancelled(self):
import queue
import threading
from types import SimpleNamespace

stopped = threading.Event()
stopped.set()
q = queue.Queue()
AudioStream._enqueue_audio(
SimpleNamespace(hop_length=20, target_sr=1000), np.ones(100), q, stopped
)
self.assertIsNone(q.get_nowait())
self.assertTrue(q.empty())

def test_paced_and_fast_inputs_produce_identical_features(self):
from matchmaker.io.stream import STREAM_END

# Includes a silent tail and an incomplete final block.
source = np.r_[np.arange(27, dtype=np.float32), np.zeros(18)]
results = []
with patch.object(
AudioStream,
"_preload_audio",
lambda stream: setattr(stream, "_preloaded_audio", source.copy()),
):
for wait in (False, True):
stream = AudioStream(
processor=DummyProcessor(),
file_path="unused.wav",
sample_rate=1000,
target_sr=1000,
hop_length=10,
wait=wait,
)
stream.run_offline()
frames = []
while True:
item = stream.queue.get_nowait()
if item is STREAM_END:
break
frames.append(item)
self.assertEqual(stream.input_index, 5)
self.assertTrue(stream.stream_start.is_set())
self.assertFalse(stream.listen)
results.append(frames)
self.assertEqual(len(results[0]), 4)
self.assertEqual(len(results[1]), 4)
for fast, paced in zip(*results):
np.testing.assert_array_equal(fast[0], paced[0])
self.assertEqual(fast[1], paced[1])

def test_processor_error_stops_feeder(self):
from matchmaker.io.stream import STREAM_END

def fail(item):
raise ValueError("synthetic processor failure")

with patch.object(
AudioStream,
"_preload_audio",
lambda stream: setattr(stream, "_preloaded_audio", np.ones(10000)),
):
stream = AudioStream(
processor=fail,
file_path="unused.wav",
sample_rate=1000,
target_sr=1000,
hop_length=10,
wait=True,
)
started = time.perf_counter()
with self.assertRaisesRegex(ValueError, "synthetic processor failure"):
stream.run_offline()
self.assertLess(time.perf_counter() - started, 1)
self.assertFalse(stream.listen)
self.assertTrue(stream.stream_start.is_set())
self.assertIs(stream.queue.get_nowait(), STREAM_END)

def test_empty_input_unblocks_consumer(self):
from matchmaker.io.stream import STREAM_END

with patch.object(
AudioStream,
"_preload_audio",
lambda stream: setattr(stream, "_preloaded_audio", np.array([])),
):
stream = AudioStream(
processor=DummyProcessor(), file_path="unused.wav", wait=True
)
stream.run_offline()
self.assertTrue(stream.stream_start.is_set())
self.assertIs(stream.queue.get_nowait(), STREAM_END)
Loading