diff --git a/README.md b/README.md index 243bc90..9feefbc 100644 --- a/README.md +++ b/README.md @@ -202,9 +202,12 @@ contract. from the first annotated performance onset through the first window that reaches the final onset. A window's statistic is the median absolute beat error, and a piece fails when any evaluated window exceeds the modality - threshold — 1.0 beat for audio, 0.5 for MIDI. + threshold — 1.0 musical beat for audio, 0.1 for MIDI. A musical beat groups + three denominator-note units in compound meter (6/8, 9/8, 12/8, 6/4, etc.) + and one elsewhere. The reference score's time signature is looked up at + each annotated onset, including changes within a piece and a window. - **Precision metric**: beat error (performance → score), pooled over the - pieces that method actually tracked. + pieces that method actually tracked, in denominator-note beats. - **Secondary precision metric**: ms error (score → performance), same pooling. - **Aggregation**: precision metrics are event-pooled across tracked pieces. - **Ranking**: tracking rate first, then median beat error. diff --git a/docs/eval-protocol.md b/docs/eval-protocol.md index a757bb5..43b867f 100644 --- a/docs/eval-protocol.md +++ b/docs/eval-protocol.md @@ -163,8 +163,25 @@ the threshold, and the piece counts as **lost** if any evaluated window fails. | Input | Threshold | | --- | --- | -| audio | 1.0 beat | -| MIDI | 0.5 beat | +| audio | 1.0 musical beat | +| MIDI | 0.1 musical beat | + +A musical beat contains three denominator-note units in compound time +signatures (numerators 6, 9, 12, and larger multiples of three), and one in +other meters. Simple triple meters such as 3/4 and 3/8 are not grouped. +At every reference onset, the absolute position error is divided by the factor +for the time signature at that reference score position **before** computing +the window median. This uses the follower's actual unfolded score, so meter +changes within a performance apply, even inside a single evaluation window. +The factor follows the reference position, not a potentially incorrect estimate. + +Thus the native-coordinate tolerance in a compound passage is 3.0 +denominator-note beats for audio and 0.3 for MIDI. The output paths, ground +truth, MeanAE, MedAE, standard deviations, and tolerance accuracies use +denominator-note units; only TR uses musical beats. Each run saves a +`meter_.json` alongside its full paths so the criterion can be reproduced. +Scores without a time signature use the parser's 4/4 default, recorded as +`assumed_time_signature` in that file. Accuracy metrics are reported over tracked pieces only. A piece that crashes or times out counts as lost. diff --git a/docs/index.html b/docs/index.html index 28262ef..a7fbc57 100644 --- a/docs/index.html +++ b/docs/index.html @@ -600,8 +600,11 @@

Tracked

The performance is walked in 30-second windows, one starting at every annotated onset. A piece counts as tracked unless the median beat error - in any window exceeds the tolerance — 0.5 beats for MIDI, 1.0 for - audio. A follower that loses the performer produces meaningless errors, + in any window exceeds the tolerance — 0.1 musical beat for MIDI, 1.0 for + audio. In compound meter, three denominator-note units form one musical + beat. The reference meter is applied at each onset, including changes + within a piece. Position-error summaries use denominator-note units. + A follower that loses the performer produces meaningless errors, so accuracy is only reported over the pieces it held onto.

@@ -869,21 +872,23 @@

Submitting

const { W, H } = plotSize(width, 6.4, 120, 190); const PAD = { l: 52, r: 14, t: 14, b: 30 }; const xs = all.map((p) => p[0]); - const top = Math.max(0.5, ...all.map((p) => p[1])); + // tr_tolerance steps at every meter change. Details without a tracking + // criterion are drawn against a flat denominator-note threshold. + const nativeThreshold = detail.input_type === "audio" ? 1.0 : 0.5; + const tolerance = piece.tr_tolerance || (piece.tracking_criterion ? [] : + [[Math.min(...xs), nativeThreshold], [Math.max(...xs), nativeThreshold]]); + const top = Math.max(0.5, ...all.map((p) => p[1]), ...tolerance.map((p) => p[1])); const { sx, sy, grid, labels } = svgAxes( W, H, PAD, [Math.min(...xs), Math.max(...xs)], [0, top], - detail.axes.x, "|beat error|", (v) => v.toFixed(v < 1 ? 2 : v < 10 ? 1 : 0) + detail.axes.x, "|error| (denominator-note beats)", (v) => v.toFixed(v < 1 ? 2 : v < 10 ? 1 : 0) ); - // The tracking verdict is decided against this line: 0.5 beats for MIDI, - // 1.0 for audio, as a median over each 30-second segment. - const threshold = detail.input_type === "audio" ? 1.0 : 0.5; - const rule = threshold <= top - ? ` - tracking threshold ${threshold}` - : ""; + const tolerancePath = tolerance.map(([t, v], i) => i + ? `H${sx(t).toFixed(1)}V${sy(v).toFixed(1)}` + : `M${sx(t).toFixed(1)},${sy(v).toFixed(1)}`).join(" "); + const rule = tolerance.length ? ` + TR tolerance before window median` : ""; // Without `err` the series is rebuilt from the decimated paths: close, but // a hold followed by a jump can still show as a spike the metrics never saw. const approximate = [piece, other].some((p) => p && !(p.err && p.err.length)); diff --git a/matchmaker_eval/eval.py b/matchmaker_eval/eval.py index 9d6a65f..a5d33eb 100644 --- a/matchmaker_eval/eval.py +++ b/matchmaker_eval/eval.py @@ -34,7 +34,9 @@ AudioEvalConfig, save_debug_results, ) -from matchmaker_eval.verify_tracking import check_tracking, plot_tracking +from matchmaker_eval.verify_tracking import ( + TRACKING_THRESHOLDS, check_tracking, plot_tracking, musical_beat_factors, score_meter_map, +) # --------------------------------------------------------------------------- # Evaluation against ground truth (post-processing of a completed Matchmaker run) @@ -313,10 +315,21 @@ def run_score_following( gt_for_check = np.column_stack( [perf_annotations[:min_len], score_annots_for_gt[:min_len]] ) - tracking = check_tracking(wp_for_check, gt_for_check) + meter = score_meter_map(mm.score_part) + factors = musical_beat_factors(gt_for_check[:, 1], meter) + threshold = TRACKING_THRESHOLDS[mm.input_type] + tracking = check_tracking( + wp_for_check, gt_for_check, threshold=threshold, beat_factors=factors + ) results["tracked"] = tracking["tracked"] results["max_deviation"] = tracking["max_deviation"] results["n_failed_segments"] = tracking["n_failed"] + results["tracking_criterion"] = { + key: tracking[key] for key in ("error_unit", "threshold", "window_duration") + } + if save_dir is not None and run_name: + meter_path = Path(save_dir) / f"meter_{run_name}.json" + meter_path.write_text(json.dumps(meter, indent=2) + "\n") if save_plots and save_dir is not None and run_name: plot_tracking( @@ -324,6 +337,8 @@ def run_score_following( gt_for_check, title=f"{config.method} #{run_name}", save_path=Path(save_dir) / f"tracking_{run_name}.png", + threshold=threshold, + beat_factors=factors, ) except Exception: pass diff --git a/matchmaker_eval/export_details.py b/matchmaker_eval/export_details.py index d24a959..e6acf6e 100644 --- a/matchmaker_eval/export_details.py +++ b/matchmaker_eval/export_details.py @@ -63,6 +63,7 @@ #: ``data_sha256`` names the bytes a piece was scored with (see provenance.py): #: provenance, not a measurement. It is published beside the identity fields. PIECE_IDENTITY = ( + "tracking_criterion", "index", "piece_id", "dataset", @@ -182,6 +183,8 @@ def export(run_dir: Path, include_paths: bool = True) -> dict: } for key in ordered_metrics(piece): row[key] = piece[key] + if "tracking_criterion" in piece: + row["tracking_criterion"] = piece["tracking_criterion"] if piece.get("error"): row["error"] = piece["error"] @@ -192,6 +195,16 @@ def export(run_dir: Path, include_paths: bool = True) -> dict: row["wp"] = decimate(wp) row["gt"] = decimate(gt) row["err"] = decimate_peaks(error_series(wp, gt)) + meter_path = run_dir / f"meter_{index}.json" + if meter_path.exists() and len(gt) and piece.get("tracking_criterion"): + from matchmaker_eval.verify_tracking import musical_beat_factors + meter = json.loads(meter_path.read_text()) + factors = musical_beat_factors(gt[:, 1], meter) + changes = np.flatnonzero(np.r_[True, factors[1:] != factors[:-1]]) + keep = np.unique(np.r_[changes, len(gt) - 1]) + threshold = piece["tracking_criterion"]["threshold"] + row["tr_tolerance"] = np.column_stack([gt[keep, 0], threshold * factors[keep]]).tolist() + row["meter"] = meter detail_pieces.append(row) return { @@ -226,7 +239,7 @@ def export(run_dir: Path, include_paths: bool = True) -> dict: #: Per-piece fields built from the run's wp_/gt_ files rather than its metrics. -PATH_FIELDS = ("wp", "gt", "err") +PATH_FIELDS = ("wp", "gt", "err", "tr_tolerance", "meter") def has_path_files(run_dir: Path) -> bool: diff --git a/matchmaker_eval/merge_shards.py b/matchmaker_eval/merge_shards.py index 8f9cd5b..75e502b 100644 --- a/matchmaker_eval/merge_shards.py +++ b/matchmaker_eval/merge_shards.py @@ -101,6 +101,9 @@ def merge(root: Path, output: Path) -> dict: source = shard_dir / f"{prefix}_{index}.tsv" if source.exists(): shutil.copy2(source, output / source.name) + meter_path = shard_dir / f"meter_{index}.json" + if meter_path.exists(): + shutil.copy2(meter_path, output / meter_path.name) failures.extend(record.get("failures", [])) pieces.sort(key=lambda p: p["index"]) diff --git a/matchmaker_eval/run_submission.py b/matchmaker_eval/run_submission.py index 8c1e67b..482d667 100644 --- a/matchmaker_eval/run_submission.py +++ b/matchmaker_eval/run_submission.py @@ -47,7 +47,9 @@ from eval import run_evaluation from utils import TOLERANCES_IN_BEATS, dataset_summaries, pooled_summaries -from verify_tracking import check_tracking, plot_tracking +from verify_tracking import ( + TRACKING_THRESHOLDS, check_tracking, musical_beat_factors, plot_tracking, score_meter_map, +) from matchmaker import Matchmaker from matchmaker.base import OnlineAlignment @@ -91,7 +93,7 @@ #: Tracking verdict thresholds, per input type. A piece counts as "tracked" #: unless some 30-second onset-wise window's median beat error exceeds the #: threshold. MIDI is held to a tighter bound than audio. -TRACKING_THRESHOLD = {"audio": 1.0, "midi": 0.5} +TRACKING_THRESHOLD = TRACKING_THRESHOLDS SEGMENT_DURATION = 30.0 DEFAULT_RESULTS_DIR = REPO_ROOT / "results" / "submissions" @@ -271,15 +273,22 @@ def run_piece( # alignment_path row 0 is already absolute performance seconds. wp_sec = np.stack([wp[0].astype(float), wp[1].astype(float)]).T threshold = TRACKING_THRESHOLD[input_type] + meter = score_meter_map(mm.score_part) + factors = musical_beat_factors(gt[:, 1], meter) + (run_dir / f"meter_{index}.json").write_text(json.dumps(meter, indent=2) + "\n") tracking = check_tracking( wp_sec, gt, segment_duration=SEGMENT_DURATION, threshold=threshold, + beat_factors=factors, ) metrics["tracked"] = bool(tracking["tracked"]) metrics["max_deviation"] = float(tracking["max_deviation"]) metrics["n_failed_segments"] = int(tracking["n_failed"]) + metrics["tracking_criterion"] = { + key: tracking[key] for key in ("error_unit", "threshold", "window_duration") + } if save_plots: plot_tracking( @@ -289,6 +298,7 @@ def run_piece( save_path=run_dir / f"tracking_{index}.png", segment_duration=SEGMENT_DURATION, threshold=threshold, + beat_factors=factors, ) # Whether this piece actually got a measured tempo. False both when the @@ -335,7 +345,7 @@ def fold_file_label(fold) -> str: #: the rerun would otherwise be scored on the previous run's path — and the #: progress count in run_references.py would read 146/146 from the first #: second. metrics.json stays until the run replaces it. -PIECE_OUTPUTS = ("wp_*.tsv", "gt_*.tsv", "tracking_*.png", "[0-9]*.json") +PIECE_OUTPUTS = ("wp_*.tsv", "gt_*.tsv", "meter_*.json", "tracking_*.png", "[0-9]*.json") def clear_piece_outputs(run_dir: Path) -> int: diff --git a/matchmaker_eval/test_symbolic.py b/matchmaker_eval/test_symbolic.py index 0620f2b..ca5e7ce 100644 --- a/matchmaker_eval/test_symbolic.py +++ b/matchmaker_eval/test_symbolic.py @@ -41,7 +41,9 @@ save_config, save_results_to_csv, ) -from matchmaker_eval.verify_tracking import check_tracking, plot_tracking +from matchmaker_eval.verify_tracking import ( + TRACKING_THRESHOLDS, check_tracking, plot_tracking, musical_beat_factors, score_meter_map, +) from tabulate import tabulate import wandb @@ -51,7 +53,7 @@ sys.setrecursionlimit(10000) -TRACKING_THRESHOLD = 0.5 # beats +TRACKING_THRESHOLD = TRACKING_THRESHOLDS["midi"] # musical beats WORKING_DIR = Path(__file__).parent.parent #: Resolved through MATCHMAKER_DATA_DIR rather than a hardcoded home @@ -168,11 +170,14 @@ def run_tests_and_eval_by_dataset( gt = np.column_stack([ps, sb]) wp_T = wp.T if wp.shape[0] == 2 else wp + meter = score_meter_map(mm.score_part) + factors = musical_beat_factors(gt[:, 1], meter) tracking = check_tracking( wp_T, gt, segment_duration=30, threshold=TRACKING_THRESHOLD, + beat_factors=factors, ) nested = run_evaluation( @@ -188,11 +193,15 @@ def run_tests_and_eval_by_dataset( nested["tracked"] = tracking["tracked"] nested["max_deviation"] = float(tracking["max_deviation"]) nested["n_failed_segments"] = int(tracking["n_failed"]) + nested["tracking_criterion"] = { + key: tracking[key] for key in ("error_unit", "threshold", "window_duration") + } piece_result = nested.copy() # Save WP/GT — column order: perf_sec, score_beat if run_dir is not None: + (run_dir / f"meter_{i}.json").write_text(json.dumps(meter, indent=2) + "\n") np.savetxt( run_dir / f"wp_{i}.tsv", wp_T, @@ -218,6 +227,7 @@ def run_tests_and_eval_by_dataset( title=f"{method} #{i}", save_path=run_dir / f"tracking_{i}.png", threshold=TRACKING_THRESHOLD, + beat_factors=factors, ) status = "TRACKED" if tracking["tracked"] else "FAILED" diff --git a/matchmaker_eval/verify_tracking.py b/matchmaker_eval/verify_tracking.py index 948f570..31b5b3b 100644 --- a/matchmaker_eval/verify_tracking.py +++ b/matchmaker_eval/verify_tracking.py @@ -1,12 +1,15 @@ """ Check if a tracker followed the score throughout a piece. -Evaluates in the score domain, in beat unit. At every annotated onset it +Evaluates in the score domain. At every annotated onset it looks up the last score position emitted at or before that time, then computes the median absolute beat error in a forward window starting at each unique annotated performance onset. The window slides onset-wise until one first reaches the final annotation. A piece fails when any window median exceeds the -selected beat tolerance. +selected beat tolerance. Benchmark callers supply ``beat_factors`` from the +reference score: errors are divided by three in compound-meter passages and +by one elsewhere, before the window median is taken. Without the factors, +errors stay in denominator-note beats. Input: wp.tsv Warping path (tab-separated) @@ -25,11 +28,85 @@ import matplotlib.pyplot as plt import numpy as np from matchmaker.utils.eval import ONSET_WINDOW_DURATION, onset_wise_windows +from partitura.score import TimeSignature BEAT_ERROR_THRESHOLD = 1.0 # threshold for window median beat error (beats) SEGMENT_DURATION = ONSET_WINDOW_DURATION # shared window duration (seconds) +TRACKING_THRESHOLDS = {"audio": 1.0, "midi": 0.1} +TRACKING_ERROR_UNIT = "musical_beat" +POSITION_ERROR_UNIT = "denominator_note" + + +def denominator_notes_per_beat(numerator: int) -> int: + """Three in compound meters (6, 9, 12, ...); one in other meters.""" + if numerator <= 0 or int(numerator) != numerator: + raise ValueError("time-signature numerator must be a positive integer") + return 3 if numerator >= 6 and numerator % 3 == 0 else 1 + + +def score_meter_map(part) -> dict: + """Serializable meter changes in the follower's score-beat coordinates. + + ``part`` must be the native, denominator-note score part passed to the + follower. Do not call ``use_musical_beat()`` on it: that would also change + its note array and the algorithm's behavior, rather than just evaluation. + A score without time signatures follows Partitura's 4/4 default, explicitly + recorded in the map instead of being mistaken for annotated meter. + """ + if getattr(part, "_use_musical_beat", False): + raise ValueError("TR expects score positions in denominator-note beats") + signatures = list(part.iter_all(TimeSignature)) + changes = [] + for ts in sorted(signatures, key=lambda ts: ts.start.t): + if ts.beat_type <= 0: + raise ValueError("time-signature denominator must be positive") + change = { + "start_score_beat": float(part.beat_map(ts.start.t)), + "numerator": int(ts.beats), + "denominator": int(ts.beat_type), + "denominator_notes_per_beat": denominator_notes_per_beat(ts.beats), + } + if changes and change["start_score_beat"] == changes[-1]["start_score_beat"]: + if change != changes[-1]: + raise ValueError("conflicting time signatures at one score position") + continue + changes.append(change) + if not changes: + changes = [{"start_score_beat": 0.0, "numerator": 4, "denominator": 4, + "denominator_notes_per_beat": 1}] + return { + "schema": 1, + "position_unit": POSITION_ERROR_UNIT, + "tracking_error_unit": TRACKING_ERROR_UNIT, + "assumed_time_signature": not bool(signatures), + "changes": changes, + } + + +def musical_beat_factors(score_positions, meter: dict) -> np.ndarray: + """The reference meter's factor at each position, right-inclusive at changes. + + Positions need not increase: the same lookup also applies when a performed + repeat returns to an earlier score position. Pickups before the first + explicit signature use that first signature. + """ + positions = np.asarray(score_positions, dtype=float) + if not np.all(np.isfinite(positions)): + raise ValueError("ground-truth score positions must be finite") + if meter.get("position_unit") != POSITION_ERROR_UNIT: + raise ValueError("meter map must use denominator-note score positions") + changes = meter["changes"] + starts = np.asarray([r["start_score_beat"] for r in changes], dtype=float) + factors = np.asarray([r["denominator_notes_per_beat"] for r in changes], dtype=float) + if (len(starts) == 0 or not np.all(np.isfinite(starts)) + or np.any(np.diff(starts) <= 0) or not np.all(np.isin(factors, [1., 3.]))): + raise ValueError("meter map must have ordered, finite changes and factors 1 or 3") + indices = np.maximum(np.searchsorted(starts, positions, side="right") - 1, 0) + return factors[indices] + + def _onset_wise_window_profile( times: np.ndarray, errors: np.ndarray, @@ -66,6 +143,8 @@ def check_tracking( gt: np.ndarray, segment_duration: float = SEGMENT_DURATION, threshold: float = BEAT_ERROR_THRESHOLD, + *, + beat_factors: np.ndarray = None, ) -> dict: """ Check tracking quality using an onset-wise sliding-window median. @@ -80,14 +159,29 @@ def check_tracking( gt : (M, 2) array — col 0: perf time (seconds), col 1: score position (beats) segment_duration : float — window duration W in seconds (default: 30) threshold : float — maximum median absolute beat error theta (default: 1.0) + beat_factors : (M,) array, optional + Denominator notes per musical beat at each GT score position. The + benchmark supplies this even for simple meter; without it, errors + remain in denominator-note units. Returns ------- dict with: windows, mean_onsets_per_window, worst_window, max_deviation, tracked, reason """ + if not np.isfinite(threshold) or threshold < 0: + raise ValueError("threshold must be finite and non-negative") + if beat_factors is not None: + beat_factors = np.asarray(beat_factors, dtype=float) + if (beat_factors.shape != (len(gt),) or not np.all(np.isfinite(beat_factors)) + or np.any(beat_factors <= 0)): + raise ValueError("beat_factors must contain one positive finite factor per GT onset") + unit = "musical_beat" if beat_factors is not None else "denominator_note" + criterion = {"error_unit": unit, "threshold": float(threshold), + "window_duration": float(segment_duration)} if wp.size == 0 or gt.size == 0: return { + **criterion, "windows": [], "n_windows": 0, "mean_onsets_per_window": 0.0, @@ -123,6 +217,8 @@ def check_tracking( errors_all = np.abs(predicted_score - gt_score) # beats errors_all[~valid] = np.inf # no causal estimate at an annotation + if beat_factors is not None: + errors_all = errors_all / beat_factors windows = _onset_wise_window_profile( gt_perf, errors_all, segment_duration, threshold @@ -148,6 +244,7 @@ def check_tracking( ) return { + **criterion, "windows": windows, "n_windows": len(windows), "mean_onsets_per_window": float( @@ -182,6 +279,8 @@ def plot_tracking( save_path: Path = None, segment_duration: float = SEGMENT_DURATION, threshold: float = BEAT_ERROR_THRESHOLD, + *, + beat_factors: np.ndarray = None, ): """Plot the alignment path and onset-wise window median-error profile.""" result = check_tracking( @@ -189,6 +288,7 @@ def plot_tracking( gt, segment_duration=segment_duration, threshold=threshold, + beat_factors=beat_factors, ) windows = result["windows"] worst_window = result["worst_window"] @@ -251,7 +351,7 @@ def plot_tracking( color="green" if tracked else "red", fontweight="bold", ) - ax1.set_ylabel("Score position") + ax1.set_ylabel("Score position (denominator-note beats)") ax1.set_xlabel("Performance time (s)") ax1.legend(loc="upper left") @@ -263,7 +363,8 @@ def plot_tracking( threshold, color="red", ls="--", lw=1.5, label=f"threshold={threshold:.1f}b" ) ax2.axhline(0, color="black", lw=0.5) - ax2.set_ylabel("Sliding median |beat error|") + beat_label = "musical beats" if beat_factors is not None else "denominator-note beats" + ax2.set_ylabel(f"Sliding median error ({beat_label})") yl = max(threshold * 2, max_dev * 1.3) if max_dev > 0 else threshold * 2 ax2.set_ylim(0, yl) ax2.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x:.1f}b")) @@ -332,6 +433,10 @@ def main(): ) parser.add_argument("--wp", type=Path, required=True, help="Warping path TSV") parser.add_argument("--gt", type=Path, required=True, help="Ground truth TSV") + parser.add_argument( + "--meter", type=Path, default=None, + help="Saved meter_.json from the benchmark; applies musical-beat TR", + ) parser.add_argument( "--save", type=Path, default=None, help="Save plot to file (default: show)" ) @@ -349,14 +454,19 @@ def main(): ) args = parser.parse_args() - wp = np.loadtxt(args.wp, delimiter="\t", skiprows=1) - gt = np.loadtxt(args.gt, delimiter="\t", skiprows=1) + wp = np.loadtxt(args.wp, delimiter="\t", skiprows=1, ndmin=2) + gt = np.loadtxt(args.gt, delimiter="\t", skiprows=1, ndmin=2) + factors = None + if args.meter is not None: + import json + factors = musical_beat_factors(gt[:, 1], json.loads(args.meter.read_text())) result = check_tracking( wp, gt, segment_duration=args.window_duration, threshold=args.threshold, + beat_factors=factors, ) title = _auto_title(args.wp) @@ -386,6 +496,7 @@ def main(): save_path=args.save, segment_duration=args.window_duration, threshold=args.threshold, + beat_factors=factors, ) diff --git a/tests/test_merge_shards.py b/tests/test_merge_shards.py index 7fe2d53..8d9ba14 100644 --- a/tests/test_merge_shards.py +++ b/tests/test_merge_shards.py @@ -84,6 +84,17 @@ def test_a_short_merge_stays_partial(self, tmp_path): merged = merge(root, tmp_path / "out") assert merged["partial"] is True + def test_the_meter_and_tracking_criterion_are_kept(self, tmp_path): + criterion = {"error_unit": "musical_beat", "threshold": 0.1, "window_duration": 30.0} + meter = {"position_unit": "denominator_note", "changes": []} + record = shard_record(0, fold_size=1) + record["pieces"][0]["tracking_criterion"] = criterion + root = write_shards(tmp_path / "shards", [record]) + (root / "shard-0" / "meter_0.json").write_text(json.dumps(meter)) + merged = merge(root, tmp_path / "out") + assert merged["pieces"][0]["tracking_criterion"] == criterion + assert json.loads((tmp_path / "out" / "meter_0.json").read_text()) == meter + class TestMergeRejectsMismatchedShards: @pytest.mark.parametrize("key,value", [ diff --git a/tests/test_musical_beats.py b/tests/test_musical_beats.py new file mode 100644 index 0000000..db8a93a --- /dev/null +++ b/tests/test_musical_beats.py @@ -0,0 +1,54 @@ +"""TR divides position errors by the reference meter's musical-beat factor.""" + +import numpy as np +import pytest +from partitura.score import Note, Part, TimeSignature + +from matchmaker_eval.verify_tracking import check_tracking, musical_beat_factors, score_meter_map + + +def score(signatures=((0, 6, 8), (12, 4, 4))): + """6/8 for six denominator-note beats, then 4/4.""" + part = Part("P1", quarter_duration=4) + for start, numerator, denominator in signatures: + part.add(TimeSignature(numerator, denominator), start=start) + part.add(Note("C", 4, id="n0"), start=0, end=4) + part.add(Note("D", 4, id="n1"), start=12, end=16) + part.add(Note("E", 4, id="n2"), start=24, end=28) + return part + + +def tracked(wp, gt, part, threshold=1.0): + factors = musical_beat_factors(gt[:, 1], score_meter_map(part)) + return check_tracking(wp, gt, threshold=threshold, beat_factors=factors) + + +def test_factor_follows_the_meter_at_each_position(): + meter = score_meter_map(score()) + # A pickup uses the first meter; a return to an earlier position uses its meter again. + assert musical_beat_factors([-1, 0, 5.99, 6, 10, 2], meter).tolist() == [3, 3, 3, 1, 1, 3] + + +@pytest.mark.parametrize("numerator,denominator,expected", [ + (6, 8, True), (9, 8, True), (12, 16, True), (3, 4, False), (3, 8, False), +]) +def test_only_compound_meters_group_three_beats(numerator, denominator, expected): + gt = np.array([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]) + wp = gt + [0.0, 2.0] + assert tracked(wp, gt, score(((0, numerator, denominator),)))["tracked"] is expected + + +def test_a_meter_change_inside_a_window_applies_per_onset(): + gt = np.array([[0.0, 5.0], [1.0, 5.5], [2.0, 6.0]]) + wp = gt + np.array([[0, 2.4], [0, 2.4], [0, 1.5]]) + # 2.4 / 3 = 0.8 for the two 6/8 onsets, 1.5 for the 4/4 onset: median 0.8. + result = tracked(wp, gt, score()) + assert result["tracked"] + assert result["worst_window"]["deviation"] == pytest.approx(0.8) + + +def test_the_factor_comes_from_the_ground_truth_position(): + gt = np.array([[0.0, 6.1], [1.0, 6.2], [2.0, 6.3]]) + wp = gt - [0.0, 2.0] + # The estimates fall back in 6/8, but the reference is already in 4/4. + assert not tracked(wp, gt, score())["tracked"]