diff --git a/README.md b/README.md index 4ec581c..9c54713 100644 --- a/README.md +++ b/README.md @@ -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) | diff --git a/docs/requirements.txt b/docs/requirements.txt index d985367..9115d0f 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,4 +1,3 @@ -pymatchmaker myst-parser>=3.0.1 sphinx>=7.4.7 sphinx-rtd-theme>=3.0.2 diff --git a/docs/source/conf.py b/docs/source/conf.py index 24f7d5c..e86f084 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -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 @@ -25,6 +22,7 @@ "sphinx.ext.todo", "sphinx.ext.coverage", "sphinx.ext.mathjax", + "sphinx.ext.napoleon", "sphinx.ext.viewcode", "myst_parser", ] diff --git a/docs/source/index.rst b/docs/source/index.rst index e8930ca..2b5e87d 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -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 @@ -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). diff --git a/docs/source/introduction.rst b/docs/source/introduction.rst deleted file mode 100644 index 40b1792..0000000 --- a/docs/source/introduction.rst +++ /dev/null @@ -1,7 +0,0 @@ -Introduction -============ - -.. include:: ../../README.md - :parser: myst_parser.sphinx_ - :start-after: # Matchmaker - :end-before: ## Setup diff --git a/docs/source/modules/matchmaker.dp.rst b/docs/source/modules/matchmaker.dp.rst index 2b91fd2..75aa9c6 100644 --- a/docs/source/modules/matchmaker.dp.rst +++ b/docs/source/modules/matchmaker.dp.rst @@ -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__ diff --git a/docs/source/modules/matchmaker.prob.rst b/docs/source/modules/matchmaker.prob.rst index ddd378c..94cae4f 100644 --- a/docs/source/modules/matchmaker.prob.rst +++ b/docs/source/modules/matchmaker.prob.rst @@ -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__ diff --git a/docs/source/modules/matchmaker.rst b/docs/source/modules/matchmaker.rst index 12ab8b3..7894f7c 100644 --- a/docs/source/modules/matchmaker.rst +++ b/docs/source/modules/matchmaker.rst @@ -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__ diff --git a/matchmaker/io/audio.py b/matchmaker/io/audio.py index 7ca444f..d69b19b 100644 --- a/matchmaker/io/audio.py +++ b/matchmaker/io/audio.py @@ -5,6 +5,7 @@ """ import queue +import threading import time from types import TracebackType from typing import Dict, Optional, Tuple, Type, Union @@ -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 @@ -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. diff --git a/matchmaker/prob/skf.py b/matchmaker/prob/skf.py index c9ef791..8ccbb53 100644 --- a/matchmaker/prob/skf.py +++ b/matchmaker/prob/skf.py @@ -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 ---------- diff --git a/tests/test_io_audio.py b/tests/test_io_audio.py index b6e86e2..79d6a80 100644 --- a/tests/test_io_audio.py +++ b/tests/test_io_audio.py @@ -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)