Separating sounds and scoring the result
Split a recording into component tracks with NMF on its spectrogram, then score separated signals against the true sources with SI-SDR, its improvement over the mixture, and BSS Eval's SDR, SIR and SAR.
What runs in CodeSplash
- Separate sounds with NMF Experimental
- Source separation metrics (SI-SDR, SDR, SIR, SAR) Verified in Python and R
You will be able to
- Explain how NMF on a spectrogram, soft masks and the inverse STFT give tracks that add up to the original
- Say when NMF separation works and when it fails
- Read SI-SDR and SI-SDRi, and tell them from plain SNR
- Explain why separated signals are matched to sources before scoring (PIT), and what SIR and SAR add
Parts that add up
ReadNon-negative matrix factorization writes a table of non-negative numbers as a sum of a few parts. A magnitude spectrogramSpectrogramA picture of sound: time across, frequency up, brightness for level; tones are lines, noise is a wash, clicks are vertical stripes. is such a table: frames by frequencies, all non-negative.
NMF splits it into templates (what each part's spectrum looks like) and activations (how strongly each part is on in each frame). A hum is one template that's always on; a drum is another that switches on and off.
From parts to tracks
In the appEach part gets a soft mask: its share of the model in every time–frequency cell. The masks add up to 1, so cutting the original spectrogram with them and turning each piece back into sound gives tracks that add back up to the original. That's NMF separationNMF separationSplitting a recording by factorizing its spectrogram into templates and activations, then masking the original into one track each..
4 files split into 2 components each; mean NMF relative error 0.397.
- Files separated
- 4
- Mean NMF relative error
- 0.3968
- Largest gap, tracks vs original
- 8.882e-16
Assumptions
- Files decode — Every file processed was decoded.
- Sounds differ in spectrum — The NMF model leaves 39.7% of the spectrogram unexplained on average; listen to the tracks to judge the split.
- Components are unnamed — Components are ordered by their total activation, loudest first.
Components by file
| File | Component | Share of energy | Template centroid (Hz) | Template peak (Hz) |
|---|---|---|---|---|
| tone_a.wav | 1 | 0.7871 | 484.06 | 437.50 |
| tone_a.wav | 2 | 0.2129 | 441.31 | 437.50 |
| tone_b.wav | 1 | 0.9115 | 1590.58 | 656.25 |
| tone_b.wav | 2 | 0.0885 | 1153.48 | 640.63 |
| noise_a.wav | 1 | 0.5168 | 729.15 | 31.250 |
| noise_a.wav | 2 | 0.4832 | 695.62 | 0 |
| chirp_loud.wav | 1 | 0.5564 | 1336.44 | 1968.75 |
| chirp_loud.wav | 2 | 0.4436 | 1502.20 | 1,375 |
Fit by file
| File | NMF relative error | Tracks vs original (relative gap) |
|---|---|---|
| tone_a.wav | 0.1371 | 6.716e-16 |
| tone_b.wav | 0.0842 | 8.882e-16 |
| noise_a.wav | 0.4402 | 6.301e-16 |
| chirp_loud.wav | 0.9257 | 6.918e-16 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Separate sounds with NMF
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.separate_nmf 1.0.0 · spec d4e4ebaf0ce6f7aa
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud1_clips.parquet", col_select = c("path")))
n_input <- nrow(df)
df[["path"]] <- factor(df[["path"]], levels = sort(unique(df[["path"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("path")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("path")) # infinite values stop the run (registry/errors.yaml)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.separate_nmf/two_components/out-r", df,
"tests/parity/fixtures/aud1_clips.parquet")
media_ids <- cs_media_ids(media, df)
if (is.null(media$root) || !nzchar(media$root)) {
media$root <- dirname(normalizePath("tests/parity/fixtures/aud1_clips.parquet", mustWork = FALSE)) # relative paths start next to the data file
}
# %% Settings
PATH <- "path"
SR <- as.numeric(media$transform$sample_rate)
K <- 2; ITER <- 60; N_FFT <- 1024; HOP <- 256
POWER <- as.numeric("1")
MAX_FILES <- 4
SEED <- 42
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.separate_nmf/two_components/out-r")
TRACKS <- file.path(out, "tracks")
dir.create(TRACKS, showWarnings = FALSE, recursive = TRUE)
# %% Separate each file: NMF on the spectrogram, soft masks, inverse STFT
status <- cs_media_status(media, media_ids)
paths <- as.character(df[[PATH]])
rows <- list(); files <- list(); bad <- list(); first <- NULL
for (i in seq_along(media_ids)) {
if (length(files) >= MAX_FILES) break
x <- NULL
if (is.na(status[i])) x <- tryCatch(as.numeric(cs_media_audio(media, media_ids[i])[[1]]), cs_error = function(e) NULL)
name <- basename(paths[i])
if (is.null(x)) {
bad[[length(bad) + 1]] <- list(file = name, path = paths[i])
next
}
r <- cs_audio_nmf_separate(x, SR, K, N_FFT, HOP, ITER, SEED, POWER)
energy <- rowSums(r$tracks^2)
total <- sum(energy)
xn <- sqrt(sum(x^2))
gap <- if (xn > 0) sqrt(sum((colSums(r$tracks) - x)^2)) / xn else 0
stem <- paste0(sprintf("%03d_", length(files) + 1), substr(gsub("[^A-Za-z0-9_-]", "_", tools::file_path_sans_ext(name)), 1, 60))
for (k in seq_len(K)) {
wav <- file.path(TRACKS, sprintf("%s_c%d.wav", stem, k))
cs_audio_write_wav(wav, r$tracks[k, ], SR)
rows[[length(rows) + 1]] <- list(file = name, media_id = media_ids[i], component = k,
energy_share = if (total > 0) energy[k] / total else NULL,
centroid_hz = sum(r$freqs * r$templates[k, ]),
peak_hz = r$freqs[which.max(r$templates[k, ])],
track = wav)
}
files[[length(files) + 1]] <- list(file = name, rel_error = r$rel_error, sum_error = gap)
if (is.null(first)) first <- list(name = name, x = x, r = r)
}
if (!length(files)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an audio file that exists and can be decoded", count = length(bad))
if (length(bad)) warnings <- c(warnings, sprintf("%d listed files could not be read and were skipped.", length(bad)))
# %% Artifacts: one WAV per file and component, and a table of the components
art <- data.frame(
file = vapply(rows, function(r) r$file, ""), media_id = vapply(rows, function(r) r$media_id, ""),
component = vapply(rows, function(r) as.integer(r$component), 0L),
energy_share = vapply(rows, function(r) if (is.null(r$energy_share)) NA_real_ else r$energy_share, 0),
centroid_hz = vapply(rows, function(r) r$centroid_hz, 0), peak_hz = vapply(rows, function(r) r$peak_hz, 0),
track = vapply(rows, function(r) r$track, ""), stringsAsFactors = FALSE
)
art_path <- file.path(out, "components.parquet")
nanoparquet::write_parquet(art, art_path)
# %% Result
rel <- vapply(files, function(f) f$rel_error, 0)
values <- list(n_rows = length(media_ids), n_files = length(files) + length(bad), n_separated = length(files), n_components = K,
rel_error_mean = mean(rel), rel_error_max = max(rel), sum_error_max = max(vapply(files, function(f) f$sum_error, 0)))
for (k in seq_len(K)) {
sh <- art$energy_share[art$component == k & !is.na(art$energy_share)]
if (length(sh)) values[[sprintf("energy_share[%d]", k)]] <- mean(sh)
values[[sprintf("centroid_hz[%d]", k)]] <- mean(art$centroid_hz[art$component == k])
}
top <- rows[seq_len(min(200, length(rows)))]
tables <- list(
list(key = "components", title = "Components by file",
columns = list(list(key = "file", label = "File"), list(key = "component", label = "Component", type = "integer"),
list(key = "energy_share", label = "Share of energy", type = "number"), list(key = "centroid_hz", label = "Template centroid (Hz)", type = "number"),
list(key = "peak_hz", label = "Template peak (Hz)", type = "number")),
rows = lapply(top, function(r) list(file = r$file, media_id = r$media_id, component = r$component, energy_share = r$energy_share, centroid_hz = r$centroid_hz, peak_hz = r$peak_hz))),
list(key = "fit", title = "Fit by file",
columns = list(list(key = "file", label = "File"), list(key = "rel_error", label = "NMF relative error", type = "number"),
list(key = "sum_error", label = "Tracks vs original (relative gap)", type = "number")),
rows = files[seq_len(min(200, length(files)))])
)
if (length(bad)) {
tables[[3]] <- list(key = "unreadable", title = "Files that could not be read", columns = list(list(key = "file", label = "File"), list(key = "path", label = "Path")),
rows = bad[seq_len(min(50, length(bad)))])
}
labels <- sprintf("Component %d", seq_len(K))
charts <- list(cs_chart("energy", "cleveland-dot", "Share of energy by component", list(
category = cs_col("Component", labels[art$component], "categorical", labels),
value = cs_col("Share of energy", art$energy_share, "numeric")
), note = "Mean over the separated files; components are ordered loudest first."))
x <- first$x; r <- first$r
seg <- as.integer(min(length(x), 10 * SR))
S <- Mod(cs_audio_stft(x[seq_len(seg)], N_FFT, HOP))
D <- cs_audio_power_to_db(S^2, "max", 1e-10, 80)
T <- cs_audio_frame_times(ncol(D), SR, HOP)
F <- cs_audio_fft_frequencies(SR, N_FFT)
charts[[2]] <- cs_chart("spectrogram", "spectrogram", paste0("Spectrogram: ", first$name), list(
x = cs_col("Time (s)", rep(T, each = length(F)), "numeric"),
y = cs_col("Frequency (Hz)", rep(F, length(T)), "numeric"),
z = cs_col("Level (dB re max)", as.vector(D), "numeric")
), controls = list(scale = "linear"), note = sprintf("Hann frames of %d samples every %d at %d Hz; the first 10 s.", N_FFT, HOP, as.integer(SR)))
t0 <- numeric(0); t1 <- numeric(0); lo <- numeric(0); hi <- numeric(0); rm <- numeric(0); trk <- character(0)
sigs <- c(list(Original = x), stats::setNames(lapply(seq_len(K), function(k) r$tracks[k, ]), labels))
for (label in names(sigs)) {
e <- cs_audio_envelope(sigs[[label]], SR, 600)
t0 <- c(t0, e$start); t1 <- c(t1, e$end); lo <- c(lo, e$min); hi <- c(hi, e$max); rm <- c(rm, e$rms); trk <- c(trk, rep(label, length(e$min)))
}
charts[[3]] <- cs_chart("tracks", "waveform", paste0("Original and separated tracks: ", first$name), list(
time = cs_col("Time (s)", t0, "numeric"), end = cs_col("End (s)", t1, "numeric"),
min = cs_col("Min", lo, "numeric"), max = cs_col("Max", hi, "numeric"), rms = cs_col("RMS", rm, "numeric"),
track = cs_col("Track", trk, "categorical", c("Original", labels))
))
assumptions <- list(
list(key = "decoded", label = "Files decode", status = if (length(bad)) "warn" else "pass",
detail = if (length(bad)) sprintf("%d files could not be read and were skipped.", length(bad)) else "Every file processed was decoded."),
list(key = "different_spectra", label = "Sounds differ in spectrum", status = "info",
detail = sprintf("The NMF model leaves %.1f%% of the spectrogram unexplained on average; listen to the tracks to judge the split.", 100 * values$rel_error_mean)),
list(key = "component_order", label = "Components are unnamed", status = "info", detail = "Components are ordered by their total activation, loudest first.")
)
cs_publish(list(
title = "Separate sounds with NMF",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(files),
summary = sprintf("%d files split into %d components each; mean NMF relative error %.3f.", length(files), K, values$rel_error_mean),
statistics = list(
list(key = "n_separated", label = "Files separated", value = length(files)),
list(key = "rel_error_mean", label = "Mean NMF relative error", value = values$rel_error_mean),
list(key = "sum_error_max", label = "Largest gap, tracks vs original", value = values$sum_error_max)
),
tables = tables,
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "components", path = art_path, format = "parquet"), list(key = "audio_tracks", path = TRACKS, format = "folder"))
))
4 files split into 2 components each; mean NMF relative error 0.397.
- Files separated
- 4
- Mean NMF relative error
- 0.3968
- Largest gap, tracks vs original
- 1.969e-16
Assumptions
- Files decode — Every file processed was decoded.
- Sounds differ in spectrum — The NMF model leaves 39.7% of the spectrogram unexplained on average; listen to the tracks to judge the split.
- Components are unnamed — Components are ordered by their total activation, loudest first.
Components by file
| File | Component | Share of energy | Template centroid (Hz) | Template peak (Hz) |
|---|---|---|---|---|
| tone_a.wav | 1 | 0.7871 | 484.06 | 437.50 |
| tone_a.wav | 2 | 0.2129 | 441.31 | 437.50 |
| tone_b.wav | 1 | 0.9115 | 1590.58 | 656.25 |
| tone_b.wav | 2 | 0.0885 | 1153.48 | 640.63 |
| noise_a.wav | 1 | 0.5168 | 729.15 | 31.250 |
| noise_a.wav | 2 | 0.4832 | 695.62 | 0 |
| chirp_loud.wav | 1 | 0.5564 | 1336.44 | 1968.75 |
| chirp_loud.wav | 2 | 0.4436 | 1502.20 | 1,375 |
Fit by file
| File | NMF relative error | Tracks vs original (relative gap) |
|---|---|---|
| tone_a.wav | 0.1371 | 1.808e-16 |
| tone_b.wav | 0.0842 | 1.969e-16 |
| noise_a.wav | 0.4402 | 1.842e-16 |
| chirp_loud.wav | 0.9257 | 1.953e-16 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Separate sounds with NMF
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.separate_nmf 1.0.0 · spec d4e4ebaf0ce6f7aa
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import describe as ad
from codesplash.audio import dsp
from codesplash.audio import separate as asep
from codesplash.errors import CsError
# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_clips.parquet", columns=["path"])
n_input = len(df)
df["path"] = pd.Categorical(df["path"], categories=sorted(df["path"].dropna().unique()))
df = df.dropna(subset=["path"]) # listwise deletion over the analysis columns
df["path"] = df["path"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["path"]) # infinite values stop the run (registry/errors.yaml)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.separate_nmf/two_components/out-python", df, "tests/parity/fixtures/aud1_clips.parquet")
media_ids = cs_media.ids_of(media, df)
if not media.get("root"):
media["root"] = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud1_clips.parquet")) # relative paths start next to the data file
# %% Settings
PATH = "path"
SR = float(media["transform"]["sample_rate"])
K, ITER, N_FFT, HOP = 2, 60, 1024, 256
POWER = float("1")
MAX_FILES = 4
SEED = 42
out = csml.out_dir("target/academy-parity/run-8142/audio.separate_nmf/two_components/out-python")
TRACKS = os.path.join(out, "tracks")
os.makedirs(TRACKS, exist_ok=True)
# %% Separate each file: NMF on the spectrogram, soft masks, inverse STFT
status = cs_media.status(media, media_ids)
paths = df[PATH].astype(str).tolist()
rows, files, bad, first = [], [], [], None
for i, mid in enumerate(media_ids):
if len(files) >= MAX_FILES:
break
x = None
if status[i] is None:
try:
x = np.asarray(cs_media.audio(media, [mid])[0], dtype=np.float64)
except CsError:
x = None
name = os.path.basename(paths[i])
if x is None:
bad.append({"file": name, "path": paths[i]})
continue
r = asep.nmf_separate(x, SR, K, N_FFT, HOP, ITER, SEED, POWER)
energy = np.sum(r["tracks"] ** 2, axis=1)
total = float(np.sum(energy))
xn = float(np.linalg.norm(x))
gap = float(np.linalg.norm(np.sum(r["tracks"], axis=0) - x)) / xn if xn > 0 else 0.0
stem = f"{len(files) + 1:03d}_" + "".join(ch if (ch.isascii() and ch.isalnum()) or ch in "-_" else "_" for ch in os.path.splitext(name)[0])[:60]
for k in range(K):
wav = os.path.join(TRACKS, f"{stem}_c{k + 1}.wav")
asep.write_wav(wav, r["tracks"][k], int(SR))
rows.append({"file": name, "media_id": mid, "component": k + 1,
"energy_share": float(energy[k] / total) if total > 0 else None,
"centroid_hz": float(np.sum(r["freqs"] * r["templates"][k])),
"peak_hz": float(r["freqs"][int(np.argmax(r["templates"][k]))]),
"track": wav})
files.append({"file": name, "rel_error": r["rel_error"], "sum_error": gap})
if first is None:
first = (name, x, r)
if not files:
cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an audio file that exists and can be decoded", count=len(bad))
warnings = list(warnings)
if bad:
warnings.append(f"{len(bad)} listed files could not be read and were skipped.")
# %% Artifacts: one WAV per file and component, and a table of the components
art = pd.DataFrame(rows, columns=["file", "media_id", "component", "energy_share", "centroid_hz", "peak_hz", "track"])
for c in ("file", "media_id", "track"):
art[c] = art[c].astype("string")
art["component"] = art["component"].astype("int64")
art["energy_share"] = pd.to_numeric(art["energy_share"], errors="coerce").astype("float64")
art_path = os.path.join(out, "components.parquet")
art.to_parquet(art_path, index=False)
# %% Result
values = {"n_rows": len(media_ids), "n_files": len(files) + len(bad), "n_separated": len(files), "n_components": K,
"rel_error_mean": float(np.mean([f["rel_error"] for f in files])), "rel_error_max": float(np.max([f["rel_error"] for f in files])),
"sum_error_max": float(np.max([f["sum_error"] for f in files]))}
for k in range(1, K + 1):
sh = [r["energy_share"] for r in rows if r["component"] == k and r["energy_share"] is not None]
if sh:
values[f"energy_share[{k}]"] = float(np.mean(sh))
values[f"centroid_hz[{k}]"] = float(np.mean([r["centroid_hz"] for r in rows if r["component"] == k]))
tables = [
{"key": "components", "title": "Components by file",
"columns": [{"key": "file", "label": "File"}, {"key": "component", "label": "Component", "type": "integer"},
{"key": "energy_share", "label": "Share of energy", "type": "number"}, {"key": "centroid_hz", "label": "Template centroid (Hz)", "type": "number"},
{"key": "peak_hz", "label": "Template peak (Hz)", "type": "number"}],
"rows": [{k: r[k] for k in ("file", "media_id", "component", "energy_share", "centroid_hz", "peak_hz")} for r in rows[:200]]},
{"key": "fit", "title": "Fit by file",
"columns": [{"key": "file", "label": "File"}, {"key": "rel_error", "label": "NMF relative error", "type": "number"},
{"key": "sum_error", "label": "Tracks vs original (relative gap)", "type": "number"}], "rows": files[:200]},
]
if bad:
tables.append({"key": "unreadable", "title": "Files that could not be read", "columns": [{"key": "file", "label": "File"}, {"key": "path", "label": "Path"}], "rows": bad[:50]})
name, x, r = first
labels = [f"Component {k + 1}" for k in range(K)]
charts = [cs.chart("energy", "cleveland-dot", "Share of energy by component", {
"category": cs.col("Component", [labels[r_["component"] - 1] for r_ in rows], "categorical", labels),
"value": cs.col("Share of energy", [r_["energy_share"] for r_ in rows], "numeric"),
}, note="Mean over the separated files; components are ordered loudest first.")]
seg = int(min(len(x), 10 * SR))
S = np.abs(dsp.stft(x[:seg], N_FFT, HOP))
D = dsp.power_to_db(S**2, "max", 1e-10, 80.0)
T = dsp.frame_times(D.shape[1], SR, HOP)
F = dsp.fft_frequencies(SR, N_FFT)
charts.append(cs.chart("spectrogram", "spectrogram", f"Spectrogram: {name}", {
"x": cs.col("Time (s)", np.repeat(T, len(F)), "numeric"),
"y": cs.col("Frequency (Hz)", np.tile(F, len(T)), "numeric"),
"z": cs.col("Level (dB re max)", D.T.ravel(), "numeric"),
}, controls={"scale": "linear"}, note=f"Hann frames of {N_FFT} samples every {HOP} at {int(SR)} Hz; the first 10 s."))
t0, t1, lo, hi, rm, trk = [], [], [], [], [], []
for label, sig in [("Original", x)] + [(labels[k], r["tracks"][k]) for k in range(K)]:
e = ad.envelope(sig, SR, 600)
t0 += e["start"]; t1 += e["end"]; lo += e["min"]; hi += e["max"]; rm += e["rms"]; trk += [label] * len(e["min"])
charts.append(cs.chart("tracks", "waveform", f"Original and separated tracks: {name}", {
"time": cs.col("Time (s)", t0, "numeric"), "end": cs.col("End (s)", t1, "numeric"),
"min": cs.col("Min", lo, "numeric"), "max": cs.col("Max", hi, "numeric"), "rms": cs.col("RMS", rm, "numeric"),
"track": cs.col("Track", trk, "categorical", ["Original"] + labels),
}))
assumptions = [
{"key": "decoded", "label": "Files decode", "status": "warn" if bad else "pass",
"detail": f"{len(bad)} files could not be read and were skipped." if bad else "Every file processed was decoded."},
{"key": "different_spectra", "label": "Sounds differ in spectrum", "status": "info",
"detail": f"The NMF model leaves {values['rel_error_mean']:.1%} of the spectrogram unexplained on average; listen to the tracks to judge the split."},
{"key": "component_order", "label": "Components are unnamed", "status": "info", "detail": "Components are ordered by their total activation, loudest first."},
]
cs.publish({
"title": "Separate sounds with NMF",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": len(files),
"summary": f"{len(files)} files split into {K} components each; mean NMF relative error {values['rel_error_mean']:.3f}.",
"statistics": [
{"key": "n_separated", "label": "Files separated", "value": len(files)},
{"key": "rel_error_mean", "label": "Mean NMF relative error", "value": values["rel_error_mean"]},
{"key": "sum_error_max", "label": "Largest gap, tracks vs original", "value": values["sum_error_max"]},
],
"tables": tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "components", "path": art_path, "format": "parquet"}, {"key": "audio_tracks", "path": TRACKS, "format": "folder"}],
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
The four files were split into two components each. Added together, the tracks differ from the originals by at most 8.88e-16 of their size (tracks versus originalTracks versus originalHow far the separated tracks, added together, are from the original, relative to its size; near 0 when the masks cover it.), which is rounding.
The NMF relative errorNMF relative errorHow much of the spectrogram the NMF model leaves unexplained, as a share of its size; lower means the components fit better. is 0.397 on average: the share of the spectrogram the two parts leave unexplained. It is highest for the clipped chirp: its pitch keeps sweeping, so no fixed template fits it for long.
Check yourself
Which recording will NMF separation handle best?
Show the answer
Answer: a
NMF splits sounds by their spectra. A hum and a voice occupy different frequencies, so their templates differ. Two similar voices or two instruments on one note share frequencies, and the masks can't tell them apart.
Check yourself
After separation, component 1 is the loudest track in every file. Does that mean component 1 is the same sound in every file?
Show the answer
Answer: b
Every file gets its own factorization, ordered loudest first. Listen to the tracks (they're saved with the run) to decide which is which.
Scoring a separation
CheckpointWhen the true sources are known (a test mix you made yourself, or a benchmark), the separation can be scored. The standard score is SI-SDRSI-SDR (scale-invariant signal-to-distortion ratio)How close a separated signal is to the true source in dB, ignoring its overall volume; higher is better, 0 dB means as much error as signal.: scale the true source to fit the estimate, and compare what fits with what's left, in dB. It ignores the estimate's overall volume, which a separator can't know.
Mean SI-SDR 8.1 dB over 2 clip(s) and 3 source(s).
- Mean SI-SDR (dB)
- 8.081
- Mean SI-SDRi (dB)
- 11.413
- Mean SDR (dB)
- 9.581
- Mean SIR (dB)
- 10.972
- Mean SAR (dB)
- 15.629
- Mean SNR (dB)
- 8.620
Plots
Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture.
View data
| True source | Signal | SI-SDR (dB) |
|---|---|---|
| s1 | Mixture | 0.2224 |
| s1 | Separated | 11.103 |
| s2 | Mixture | −5.643 |
| s2 | Separated | 6.031 |
| s3 | Mixture | −4.643 |
| s3 | Separated | 6.833 |
| s1 | Mixture | 1.127 |
| s1 | Separated | 11.966 |
| s2 | Mixture | −6.423 |
| s2 | Separated | 5.388 |
| s3 | Mixture | −4.630 |
| s3 | Separated | 7.167 |
SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added.
View data
| True source | Metric | dB |
|---|---|---|
| s1 | SDR | 12.628 |
| s1 | SIR | 14.130 |
| s1 | SAR | 18.132 |
| s2 | SDR | 7.940 |
| s2 | SIR | 9.386 |
| s2 | SAR | 13.894 |
| s3 | SDR | 8.236 |
| s3 | SIR | 9.613 |
| s3 | SAR | 14.344 |
| s1 | SDR | 13.368 |
| s1 | SIR | 15.032 |
| s1 | SAR | 18.475 |
| s2 | SDR | 6.653 |
| s2 | SIR | 7.731 |
| s2 | SAR | 13.910 |
| s3 | SDR | 8.662 |
| s3 | SIR | 9.939 |
| s3 | SAR | 15.019 |
Assumptions
- Signals are aligned in time — Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR.
- No silent sources — Every true source varies in every clip.
- One estimate per source — 3 separated signals for 3 true sources; matching reordered them in 1 of 2 clips.
Scores by clip and source
| Clip | True source | Matched estimate | SI-SDR (dB) | SI-SDRi (dB) | Mixture SI-SDR (dB) | SDR (dB) | SIR (dB) | SAR (dB) | SNR (dB) |
|---|---|---|---|---|---|---|---|---|---|
| a | s1 | est1 | 11.103 | 10.881 | 0.2224 | 12.628 | 14.130 | 18.132 | 11.124 |
| a | s2 | est2 | 6.031 | 11.674 | −5.643 | 7.940 | 9.386 | 13.894 | 6.997 |
| a | s3 | est3 | 6.833 | 11.477 | −4.643 | 8.236 | 9.613 | 14.344 | 7.580 |
| b | s1 | est3 | 11.966 | 10.840 | 1.127 | 13.368 | 15.032 | 18.475 | 11.685 |
| b | s2 | est1 | 5.388 | 11.810 | −6.423 | 6.653 | 7.731 | 13.910 | 6.477 |
| b | s3 | est2 | 7.167 | 11.796 | −4.630 | 8.662 | 9.939 | 15.019 | 7.856 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Source separation metrics (SI-SDR, SDR, SIR, SAR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.separation 1.0.1 · spec 56f2d5c067a8ae81
# Dataset: aud1_separation (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud1_separation.parquet", col_select = c("s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip")))
n_input <- nrow(df)
df[["clip"]] <- factor(df[["clip"]], levels = sort(unique(df[["clip"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip")) # infinite values stop the run (registry/errors.yaml)
# %% Signals: one column per true source and per separated signal, samples in row order
REFS <- c("s1", "s2", "s3")
ESTS <- c("est1", "est2", "est3")
MIX <- "mix"
CLIP <- "clip"
PERMUTE <- TRUE
ZERO_MEAN <- TRUE
BSS <- TRUE
FLEN <- 512
if (length(ESTS) != length(REFS)) {
cs_error("CS_E_INVALID_OPTION", option = "Separated signals", allowed = paste0(length(REFS), " columns, one per true source"), value = length(ESTS))
}
clips <- if (is.null(CLIP)) list(`all rows` = df) else split(df, df[[CLIP]], drop = TRUE)
# %% Scores per clip: permutation-invariant matching on SI-SDR, then SI-SDRi and BSS Eval
rows <- list()
n_permuted <- 0L
for (name in names(clips)) {
g <- clips[[name]]
R <- t(as.matrix(g[REFS])); storage.mode(R) <- "double"
E <- t(as.matrix(g[ESTS])); storage.mode(E) <- "double"
for (i in seq_along(REFS)) {
s <- if (ZERO_MEAN) R[i, ] - mean(R[i, ]) else R[i, ]
if (sum(s * s) == 0) cs_error("CS_E_UNDEFINED", what = "SI-SDR", reason = paste0("the true source ", REFS[i], " is silent in clip ", name))
}
m <- if (!is.null(MIX)) as.numeric(g[[MIX]]) else NULL
r <- cs_sep_evaluate(R, E, m, zero_mean = ZERO_MEAN, bss = BSS, flen = FLEN, permute = PERMUTE)
if (any(r$perm != seq_along(REFS))) n_permuted <- n_permuted + 1L
for (i in seq_along(REFS)) {
rows[[length(rows) + 1]] <- list(
clip = name, source = REFS[i], estimate = ESTS[r$perm[i]], samples = ncol(R),
si_sdr = r$si_sdr[i],
si_sdri = if (!is.null(m)) r$si_sdri[i] else NULL,
mixture_si_sdr = if (!is.null(m)) r$mixture_si_sdr[i] else NULL,
sdr = if (BSS) r$sdr[i] else NULL,
sir = if (BSS) r$sir[i] else NULL,
sar = if (BSS) r$sar[i] else NULL,
snr = r$snr[i]
)
}
}
mean_of <- function(key, source = NULL) {
v <- unlist(lapply(rows, function(x) if (!is.null(x[[key]]) && (is.null(source) || x$source == source)) x[[key]] else NULL))
if (length(v)) mean(v) else NULL
}
si <- vapply(rows, function(x) x$si_sdr, 0)
values <- list(
n_clips = length(clips), n_sources = length(REFS), n_samples = nrow(df),
si_sdr_mean = mean_of("si_sdr"), si_sdr_median = stats::median(si), si_sdr_min = min(si),
si_sdri_mean = mean_of("si_sdri"), mixture_si_sdr_mean = mean_of("mixture_si_sdr"),
sdr_mean = mean_of("sdr"), sir_mean = mean_of("sir"), sar_mean = mean_of("sar"), snr_mean = mean_of("snr"),
n_permuted = n_permuted, filter_length = if (BSS) FLEN else NULL
)
for (c in REFS) {
for (key in c("si_sdr", "si_sdri", "sdr", "sir", "sar", "snr")) {
v <- mean_of(key, c)
if (!is.null(v)) values[[sprintf("%s[%s]", key, c)]] <- v
}
}
# %% Artifact: one row per clip and source
out <- cs_ml_out_dir("target/academy-parity/run-8142/evaluate.separation/three_sources_mixture/out-r")
num_or_na <- function(key) vapply(rows, function(x) if (is.null(x[[key]])) NA_real_ else as.numeric(x[[key]]), 0)
art <- data.frame(
clip = vapply(rows, function(x) x$clip, ""), source = vapply(rows, function(x) x$source, ""),
estimate = vapply(rows, function(x) x$estimate, ""), samples = vapply(rows, function(x) as.integer(x$samples), 0L),
si_sdr = num_or_na("si_sdr"), si_sdri = num_or_na("si_sdri"), mixture_si_sdr = num_or_na("mixture_si_sdr"),
sdr = num_or_na("sdr"), sir = num_or_na("sir"), sar = num_or_na("sar"), snr = num_or_na("snr"),
stringsAsFactors = FALSE
)
nanoparquet::write_parquet(art, file.path(out, "separation.parquet"))
# %% Result
cols <- list(list(key = "clip", label = "Clip"), list(key = "source", label = "True source"), list(key = "estimate", label = "Matched estimate"),
list(key = "si_sdr", label = "SI-SDR (dB)", type = "number"))
if (!is.null(MIX)) cols <- c(cols, list(list(key = "si_sdri", label = "SI-SDRi (dB)", type = "number"), list(key = "mixture_si_sdr", label = "Mixture SI-SDR (dB)", type = "number")))
if (BSS) cols <- c(cols, list(list(key = "sdr", label = "SDR (dB)", type = "number"), list(key = "sir", label = "SIR (dB)", type = "number"), list(key = "sar", label = "SAR (dB)", type = "number")))
cols <- c(cols, list(list(key = "snr", label = "SNR (dB)", type = "number")))
keys <- vapply(cols, function(c) c$key, "")
table_rows <- lapply(rows[seq_len(min(500, length(rows)))], function(x) stats::setNames(lapply(keys, function(k) x[[k]]), keys))
tables <- list(list(key = "scores", title = "Scores by clip and source", columns = cols, rows = table_rows))
fin <- function(v) if (is.finite(v)) v else NA_real_
kind <- character(0); src <- character(0); val <- numeric(0)
for (x in rows) {
if (!is.null(MIX)) { kind <- c(kind, "Mixture"); src <- c(src, x$source); val <- c(val, fin(x$mixture_si_sdr)) }
kind <- c(kind, "Separated"); src <- c(src, x$source); val <- c(val, fin(x$si_sdr))
}
charts <- list(cs_chart("si_sdr", "cleveland-dot", paste0("SI-SDR by source", if (!is.null(MIX)) ": mixture and separated" else ""), list(
category = cs_col("True source", src, "categorical", REFS),
value = cs_col("SI-SDR (dB)", val, "numeric"),
group = cs_col("Signal", kind, "categorical", if (!is.null(MIX)) c("Mixture", "Separated") else c("Separated"))
), note = if (!is.null(MIX)) "Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture." else "Mean over clips; higher is better."))
if (BSS) {
metric <- character(0); msrc <- character(0); mval <- numeric(0)
for (x in rows) {
for (pair in list(c("sdr", "SDR"), c("sir", "SIR"), c("sar", "SAR"))) {
metric <- c(metric, pair[2]); msrc <- c(msrc, x$source); mval <- c(mval, fin(x[[pair[1]]]))
}
}
charts[[2]] <- cs_chart("bss_eval", "cleveland-dot", "BSS Eval by source", list(
category = cs_col("True source", msrc, "categorical", REFS),
value = cs_col("dB", mval, "numeric"),
group = cs_col("Metric", metric, "categorical", c("SDR", "SIR", "SAR"))
), note = "SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added.")
}
assumptions <- list(
list(key = "aligned", label = "Signals are aligned in time", status = "info",
detail = "Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR."),
list(key = "silent_reference", label = "No silent sources", status = "pass", detail = "Every true source varies in every clip."),
list(key = "same_count", label = "One estimate per source", status = "pass",
detail = paste0(length(ESTS), " separated signals for ", length(REFS), " true sources",
if (PERMUTE) sprintf("; matching reordered them in %d of %d clips.", n_permuted, length(clips)) else ", paired in column order."))
)
stats_list <- list(list(key = "si_sdr_mean", label = "Mean SI-SDR (dB)", value = values$si_sdr_mean))
if (!is.null(MIX)) stats_list[[length(stats_list) + 1]] <- list(key = "si_sdri_mean", label = "Mean SI-SDRi (dB)", value = values$si_sdri_mean)
if (BSS) {
stats_list <- c(stats_list, list(list(key = "sdr_mean", label = "Mean SDR (dB)", value = values$sdr_mean),
list(key = "sir_mean", label = "Mean SIR (dB)", value = values$sir_mean),
list(key = "sar_mean", label = "Mean SAR (dB)", value = values$sar_mean)))
}
stats_list[[length(stats_list) + 1]] <- list(key = "snr_mean", label = "Mean SNR (dB)", value = values$snr_mean)
cs_publish(list(
title = "Source separation metrics (SI-SDR, SDR, SIR, SAR)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = nrow(df),
summary = sprintf("Mean SI-SDR %.1f dB over %d clip(s) and %d source(s).", values$si_sdr_mean, length(clips), length(REFS)),
statistics = stats_list,
tables = tables,
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "separation", path = file.path(out, "separation.parquet"), format = "parquet"))
))
Mean SI-SDR 8.1 dB over 2 clip(s) and 3 source(s).
- Mean SI-SDR (dB)
- 8.081
- Mean SI-SDRi (dB)
- 11.413
- Mean SDR (dB)
- 9.581
- Mean SIR (dB)
- 10.972
- Mean SAR (dB)
- 15.629
- Mean SNR (dB)
- 8.620
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Signals are aligned in time — Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR.
- No silent sources — Every true source varies in every clip.
- One estimate per source — 3 separated signals for 3 true sources; matching reordered them in 1 of 2 clips.
Scores by clip and source
| Clip | True source | Matched estimate | SI-SDR (dB) | SI-SDRi (dB) | Mixture SI-SDR (dB) | SDR (dB) | SIR (dB) | SAR (dB) | SNR (dB) |
|---|---|---|---|---|---|---|---|---|---|
| a | s1 | est1 | 11.103 | 10.881 | 0.2224 | 12.628 | 14.130 | 18.132 | 11.124 |
| a | s2 | est2 | 6.031 | 11.674 | −5.643 | 7.940 | 9.386 | 13.894 | 6.997 |
| a | s3 | est3 | 6.833 | 11.477 | −4.643 | 8.236 | 9.613 | 14.344 | 7.580 |
| b | s1 | est3 | 11.966 | 10.840 | 1.127 | 13.368 | 15.032 | 18.475 | 11.685 |
| b | s2 | est1 | 5.388 | 11.810 | −6.423 | 6.653 | 7.731 | 13.910 | 6.477 |
| b | s3 | est2 | 7.167 | 11.796 | −4.630 | 8.662 | 9.939 | 15.019 | 7.856 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Source separation metrics (SI-SDR, SDR, SIR, SAR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.separation 1.0.1 · spec 56f2d5c067a8ae81
# Dataset: aud1_separation (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import separation as sep
# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_separation.parquet", columns=["s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip"])
n_input = len(df)
df["clip"] = pd.Categorical(df["clip"], categories=sorted(df["clip"].dropna().unique()))
df = df.dropna(subset=["s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip"]) # listwise deletion over the analysis columns
df["clip"] = df["clip"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["s1", "s2", "s3", "est1", "est2", "est3", "mix", "clip"]) # infinite values stop the run (registry/errors.yaml)
# %% Signals: one column per true source and per separated signal, samples in row order
REFS = ["s1", "s2", "s3"]
ESTS = ["est1", "est2", "est3"]
MIX = "mix"
CLIP = "clip"
PERMUTE = True
ZERO_MEAN = True
BSS = True
FLEN = 512
if len(ESTS) != len(REFS):
cs.cs_error("CS_E_INVALID_OPTION", option="Separated signals", allowed=f"{len(REFS)} columns, one per true source", value=len(ESTS))
clips = [("all rows", df)] if CLIP is None else [(str(k), g) for k, g in df.groupby(CLIP, observed=True, sort=True)]
# %% Scores per clip: permutation-invariant matching on SI-SDR, then SI-SDRi and BSS Eval
rows = []
n_permuted = 0
for name, g in clips:
R = g[REFS].to_numpy(dtype=np.float64).T
E = g[ESTS].to_numpy(dtype=np.float64).T
for i, c in enumerate(REFS):
s = R[i] - np.mean(R[i]) if ZERO_MEAN else R[i]
if float(np.dot(s, s)) == 0.0:
cs.cs_error("CS_E_UNDEFINED", what="SI-SDR", reason=f"the true source {c} is silent in clip {name}")
m = g[MIX].to_numpy(dtype=np.float64) if MIX is not None else None
r = sep.evaluate(R, E, m, zero_mean=ZERO_MEAN, bss=BSS, flen=FLEN, permute=PERMUTE)
if any(int(r["perm"][i]) != i for i in range(len(REFS))):
n_permuted += 1
for i, c in enumerate(REFS):
rows.append({
"clip": name, "source": c, "estimate": ESTS[int(r["perm"][i])], "samples": int(R.shape[1]),
"si_sdr": float(r["si_sdr"][i]),
"si_sdri": float(r["si_sdri"][i]) if m is not None else None,
"mixture_si_sdr": float(r["mixture_si_sdr"][i]) if m is not None else None,
"sdr": float(r["sdr"][i]) if BSS else None,
"sir": float(r["sir"][i]) if BSS else None,
"sar": float(r["sar"][i]) if BSS else None,
"snr": float(r["snr"][i]),
})
def mean_of(key, source=None):
v = [x[key] for x in rows if x[key] is not None and (source is None or x["source"] == source)]
return float(np.mean(v)) if v else None
si = np.array([x["si_sdr"] for x in rows])
values = {
"n_clips": len(clips), "n_sources": len(REFS), "n_samples": len(df),
"si_sdr_mean": mean_of("si_sdr"), "si_sdr_median": float(np.median(si)), "si_sdr_min": float(np.min(si)),
"si_sdri_mean": mean_of("si_sdri"), "mixture_si_sdr_mean": mean_of("mixture_si_sdr"),
"sdr_mean": mean_of("sdr"), "sir_mean": mean_of("sir"), "sar_mean": mean_of("sar"), "snr_mean": mean_of("snr"),
"n_permuted": n_permuted, "filter_length": FLEN if BSS else None,
}
for c in REFS:
for key in ("si_sdr", "si_sdri", "sdr", "sir", "sar", "snr"):
v = mean_of(key, c)
if v is not None:
values[f"{key}[{c}]"] = v
# %% Artifact: one row per clip and source
out = csml.out_dir("target/academy-parity/run-8142/evaluate.separation/three_sources_mixture/out-python")
art = pd.DataFrame(rows, columns=["clip", "source", "estimate", "samples", "si_sdr", "si_sdri", "mixture_si_sdr", "sdr", "sir", "sar", "snr"])
for c in ("clip", "source", "estimate"):
art[c] = art[c].astype("string")
for c in ("si_sdri", "mixture_si_sdr", "sdr", "sir", "sar"):
art[c] = pd.to_numeric(art[c], errors="coerce").astype("float64")
art.to_parquet(os.path.join(out, "separation.parquet"), index=False)
# %% Result
cols = [{"key": "clip", "label": "Clip"}, {"key": "source", "label": "True source"}, {"key": "estimate", "label": "Matched estimate"},
{"key": "si_sdr", "label": "SI-SDR (dB)", "type": "number"}]
if MIX is not None:
cols += [{"key": "si_sdri", "label": "SI-SDRi (dB)", "type": "number"}, {"key": "mixture_si_sdr", "label": "Mixture SI-SDR (dB)", "type": "number"}]
if BSS:
cols += [{"key": "sdr", "label": "SDR (dB)", "type": "number"}, {"key": "sir", "label": "SIR (dB)", "type": "number"}, {"key": "sar", "label": "SAR (dB)", "type": "number"}]
cols += [{"key": "snr", "label": "SNR (dB)", "type": "number"}]
tables = [{"key": "scores", "title": "Scores by clip and source", "columns": cols, "rows": [{c["key"]: x[c["key"]] for c in cols} for x in rows[:500]]}]
kind, src, val = [], [], []
for x in rows:
if MIX is not None:
kind.append("Mixture"); src.append(x["source"]); val.append(x["mixture_si_sdr"])
kind.append("Separated"); src.append(x["source"]); val.append(x["si_sdr"])
charts = [cs.chart("si_sdr", "cleveland-dot", "SI-SDR by source" + (": mixture and separated" if MIX is not None else ""), {
"category": cs.col("True source", src, "categorical", REFS),
"value": cs.col("SI-SDR (dB)", [v if np.isfinite(v) else None for v in val], "numeric"),
"group": cs.col("Signal", kind, "categorical", ["Mixture", "Separated"] if MIX is not None else ["Separated"]),
}, note="Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture." if MIX is not None else "Mean over clips; higher is better.")]
if BSS:
metric, msrc, mval = [], [], []
for x in rows:
for key, label in (("sdr", "SDR"), ("sir", "SIR"), ("sar", "SAR")):
metric.append(label); msrc.append(x["source"]); mval.append(x[key] if np.isfinite(x[key]) else None)
charts.append(cs.chart("bss_eval", "cleveland-dot", "BSS Eval by source", {
"category": cs.col("True source", msrc, "categorical", REFS),
"value": cs.col("dB", mval, "numeric"),
"group": cs.col("Metric", metric, "categorical", ["SDR", "SIR", "SAR"]),
}, note="SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added."))
assumptions = [
{"key": "aligned", "label": "Signals are aligned in time", "status": "info",
"detail": "Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR."},
{"key": "silent_reference", "label": "No silent sources", "status": "pass", "detail": "Every true source varies in every clip."},
{"key": "same_count", "label": "One estimate per source", "status": "pass",
"detail": f"{len(ESTS)} separated signals for {len(REFS)} true sources" + (f"; matching reordered them in {n_permuted} of {len(clips)} clips." if PERMUTE else ", paired in column order.")},
]
cs.publish({
"title": "Source separation metrics (SI-SDR, SDR, SIR, SAR)",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(df),
"summary": f"Mean SI-SDR {values['si_sdr_mean']:.1f} dB over {len(clips)} clip(s) and {len(REFS)} source(s).",
"statistics": [s for s in [
{"key": "si_sdr_mean", "label": "Mean SI-SDR (dB)", "value": values["si_sdr_mean"]},
{"key": "si_sdri_mean", "label": "Mean SI-SDRi (dB)", "value": values["si_sdri_mean"]} if MIX is not None else None,
{"key": "sdr_mean", "label": "Mean SDR (dB)", "value": values["sdr_mean"]} if BSS else None,
{"key": "sir_mean", "label": "Mean SIR (dB)", "value": values["sir_mean"]} if BSS else None,
{"key": "sar_mean", "label": "Mean SAR (dB)", "value": values["sar_mean"]} if BSS else None,
{"key": "snr_mean", "label": "Mean SNR (dB)", "value": values["snr_mean"]},
] if s is not None],
"tables": tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "separation", "path": os.path.join(out, "separation.parquet"), "format": "parquet"}],
})
Over two clips with three sources each, the separated signals reach a mean SI-SDR of 8.08 dB. The mixture itself, compared with each source, scores −3.33 dB, so the improvementSI-SDR improvement (SI-SDRi)The separated signal's SI-SDR minus the mixture's: how much the separation helped compared with doing nothing. is 11.4 dB.
Check yourself
A separated voice is perfect except that it is half as loud as the true voice. What happens to SI-SDR and to plain SNR?
Show the answer
Answer: a
SI-SDR first rescales the reference to the estimate, so volume doesn't count. Plain SNR compares the signals as they are, so a correct but quieter estimate looks like a large error.
Which estimate is which?
ExploreA separator returns its outputs in no particular order. Permutation-invariant matchingPermutation-invariant matching (PIT)Pairing each separated signal with the true source it fits best, since a separator doesn't know which output is which source. pairs each estimate with the source it fits best before scoring. In the second test clip the estimate columns are rotated; matching put them back, so 1 clip was reordered.
Mean SI-SDR -5.1 dB over 2 clip(s) and 3 source(s).
- Mean SI-SDR (dB)
- −5.059
- Mean SNR (dB)
- 3.190
Plots
Mean over clips; higher is better.
View data
| True source | Signal | SI-SDR (dB) |
|---|---|---|
| s1 | Separated | 11.103 |
| s2 | Separated | 6.031 |
| s3 | Separated | 6.833 |
| s1 | Separated | −12.894 |
| s2 | Separated | −13.933 |
| s3 | Separated | −27.497 |
Assumptions
- Signals are aligned in time — Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR.
- No silent sources — Every true source varies in every clip.
- One estimate per source — 3 separated signals for 3 true sources, paired in column order.
Scores by clip and source
| Clip | True source | Matched estimate | SI-SDR (dB) | SNR (dB) |
|---|---|---|---|---|
| a | s1 | est1 | 11.103 | 11.124 |
| a | s2 | est2 | 6.031 | 6.997 |
| a | s3 | est3 | 6.833 | 7.580 |
| b | s1 | est1 | −12.894 | −0.1386 |
| b | s2 | est2 | −13.933 | −1.969 |
| b | s3 | est3 | −27.497 | −4.456 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Source separation metrics (SI-SDR, SDR, SIR, SAR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.separation 1.0.1 · spec d0fa779762d209de
# Dataset: aud1_separation (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud1_separation.parquet", col_select = c("s1", "s2", "s3", "est1", "est2", "est3", "clip")))
n_input <- nrow(df)
df[["clip"]] <- factor(df[["clip"]], levels = sort(unique(df[["clip"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("s1", "s2", "s3", "est1", "est2", "est3", "clip")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("s1", "s2", "s3", "est1", "est2", "est3", "clip")) # infinite values stop the run (registry/errors.yaml)
# %% Signals: one column per true source and per separated signal, samples in row order
REFS <- c("s1", "s2", "s3")
ESTS <- c("est1", "est2", "est3")
MIX <- NULL
CLIP <- "clip"
PERMUTE <- FALSE
ZERO_MEAN <- TRUE
BSS <- FALSE
FLEN <- 512
if (length(ESTS) != length(REFS)) {
cs_error("CS_E_INVALID_OPTION", option = "Separated signals", allowed = paste0(length(REFS), " columns, one per true source"), value = length(ESTS))
}
clips <- if (is.null(CLIP)) list(`all rows` = df) else split(df, df[[CLIP]], drop = TRUE)
# %% Scores per clip: permutation-invariant matching on SI-SDR, then SI-SDRi and BSS Eval
rows <- list()
n_permuted <- 0L
for (name in names(clips)) {
g <- clips[[name]]
R <- t(as.matrix(g[REFS])); storage.mode(R) <- "double"
E <- t(as.matrix(g[ESTS])); storage.mode(E) <- "double"
for (i in seq_along(REFS)) {
s <- if (ZERO_MEAN) R[i, ] - mean(R[i, ]) else R[i, ]
if (sum(s * s) == 0) cs_error("CS_E_UNDEFINED", what = "SI-SDR", reason = paste0("the true source ", REFS[i], " is silent in clip ", name))
}
m <- if (!is.null(MIX)) as.numeric(g[[MIX]]) else NULL
r <- cs_sep_evaluate(R, E, m, zero_mean = ZERO_MEAN, bss = BSS, flen = FLEN, permute = PERMUTE)
if (any(r$perm != seq_along(REFS))) n_permuted <- n_permuted + 1L
for (i in seq_along(REFS)) {
rows[[length(rows) + 1]] <- list(
clip = name, source = REFS[i], estimate = ESTS[r$perm[i]], samples = ncol(R),
si_sdr = r$si_sdr[i],
si_sdri = if (!is.null(m)) r$si_sdri[i] else NULL,
mixture_si_sdr = if (!is.null(m)) r$mixture_si_sdr[i] else NULL,
sdr = if (BSS) r$sdr[i] else NULL,
sir = if (BSS) r$sir[i] else NULL,
sar = if (BSS) r$sar[i] else NULL,
snr = r$snr[i]
)
}
}
mean_of <- function(key, source = NULL) {
v <- unlist(lapply(rows, function(x) if (!is.null(x[[key]]) && (is.null(source) || x$source == source)) x[[key]] else NULL))
if (length(v)) mean(v) else NULL
}
si <- vapply(rows, function(x) x$si_sdr, 0)
values <- list(
n_clips = length(clips), n_sources = length(REFS), n_samples = nrow(df),
si_sdr_mean = mean_of("si_sdr"), si_sdr_median = stats::median(si), si_sdr_min = min(si),
si_sdri_mean = mean_of("si_sdri"), mixture_si_sdr_mean = mean_of("mixture_si_sdr"),
sdr_mean = mean_of("sdr"), sir_mean = mean_of("sir"), sar_mean = mean_of("sar"), snr_mean = mean_of("snr"),
n_permuted = n_permuted, filter_length = if (BSS) FLEN else NULL
)
for (c in REFS) {
for (key in c("si_sdr", "si_sdri", "sdr", "sir", "sar", "snr")) {
v <- mean_of(key, c)
if (!is.null(v)) values[[sprintf("%s[%s]", key, c)]] <- v
}
}
# %% Artifact: one row per clip and source
out <- cs_ml_out_dir("target/academy-parity/run-8142/evaluate.separation/column_order_no_matching/out-r")
num_or_na <- function(key) vapply(rows, function(x) if (is.null(x[[key]])) NA_real_ else as.numeric(x[[key]]), 0)
art <- data.frame(
clip = vapply(rows, function(x) x$clip, ""), source = vapply(rows, function(x) x$source, ""),
estimate = vapply(rows, function(x) x$estimate, ""), samples = vapply(rows, function(x) as.integer(x$samples), 0L),
si_sdr = num_or_na("si_sdr"), si_sdri = num_or_na("si_sdri"), mixture_si_sdr = num_or_na("mixture_si_sdr"),
sdr = num_or_na("sdr"), sir = num_or_na("sir"), sar = num_or_na("sar"), snr = num_or_na("snr"),
stringsAsFactors = FALSE
)
nanoparquet::write_parquet(art, file.path(out, "separation.parquet"))
# %% Result
cols <- list(list(key = "clip", label = "Clip"), list(key = "source", label = "True source"), list(key = "estimate", label = "Matched estimate"),
list(key = "si_sdr", label = "SI-SDR (dB)", type = "number"))
if (!is.null(MIX)) cols <- c(cols, list(list(key = "si_sdri", label = "SI-SDRi (dB)", type = "number"), list(key = "mixture_si_sdr", label = "Mixture SI-SDR (dB)", type = "number")))
if (BSS) cols <- c(cols, list(list(key = "sdr", label = "SDR (dB)", type = "number"), list(key = "sir", label = "SIR (dB)", type = "number"), list(key = "sar", label = "SAR (dB)", type = "number")))
cols <- c(cols, list(list(key = "snr", label = "SNR (dB)", type = "number")))
keys <- vapply(cols, function(c) c$key, "")
table_rows <- lapply(rows[seq_len(min(500, length(rows)))], function(x) stats::setNames(lapply(keys, function(k) x[[k]]), keys))
tables <- list(list(key = "scores", title = "Scores by clip and source", columns = cols, rows = table_rows))
fin <- function(v) if (is.finite(v)) v else NA_real_
kind <- character(0); src <- character(0); val <- numeric(0)
for (x in rows) {
if (!is.null(MIX)) { kind <- c(kind, "Mixture"); src <- c(src, x$source); val <- c(val, fin(x$mixture_si_sdr)) }
kind <- c(kind, "Separated"); src <- c(src, x$source); val <- c(val, fin(x$si_sdr))
}
charts <- list(cs_chart("si_sdr", "cleveland-dot", paste0("SI-SDR by source", if (!is.null(MIX)) ": mixture and separated" else ""), list(
category = cs_col("True source", src, "categorical", REFS),
value = cs_col("SI-SDR (dB)", val, "numeric"),
group = cs_col("Signal", kind, "categorical", if (!is.null(MIX)) c("Mixture", "Separated") else c("Separated"))
), note = if (!is.null(MIX)) "Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture." else "Mean over clips; higher is better."))
if (BSS) {
metric <- character(0); msrc <- character(0); mval <- numeric(0)
for (x in rows) {
for (pair in list(c("sdr", "SDR"), c("sir", "SIR"), c("sar", "SAR"))) {
metric <- c(metric, pair[2]); msrc <- c(msrc, x$source); mval <- c(mval, fin(x[[pair[1]]]))
}
}
charts[[2]] <- cs_chart("bss_eval", "cleveland-dot", "BSS Eval by source", list(
category = cs_col("True source", msrc, "categorical", REFS),
value = cs_col("dB", mval, "numeric"),
group = cs_col("Metric", metric, "categorical", c("SDR", "SIR", "SAR"))
), note = "SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added.")
}
assumptions <- list(
list(key = "aligned", label = "Signals are aligned in time", status = "info",
detail = "Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR."),
list(key = "silent_reference", label = "No silent sources", status = "pass", detail = "Every true source varies in every clip."),
list(key = "same_count", label = "One estimate per source", status = "pass",
detail = paste0(length(ESTS), " separated signals for ", length(REFS), " true sources",
if (PERMUTE) sprintf("; matching reordered them in %d of %d clips.", n_permuted, length(clips)) else ", paired in column order."))
)
stats_list <- list(list(key = "si_sdr_mean", label = "Mean SI-SDR (dB)", value = values$si_sdr_mean))
if (!is.null(MIX)) stats_list[[length(stats_list) + 1]] <- list(key = "si_sdri_mean", label = "Mean SI-SDRi (dB)", value = values$si_sdri_mean)
if (BSS) {
stats_list <- c(stats_list, list(list(key = "sdr_mean", label = "Mean SDR (dB)", value = values$sdr_mean),
list(key = "sir_mean", label = "Mean SIR (dB)", value = values$sir_mean),
list(key = "sar_mean", label = "Mean SAR (dB)", value = values$sar_mean)))
}
stats_list[[length(stats_list) + 1]] <- list(key = "snr_mean", label = "Mean SNR (dB)", value = values$snr_mean)
cs_publish(list(
title = "Source separation metrics (SI-SDR, SDR, SIR, SAR)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = nrow(df),
summary = sprintf("Mean SI-SDR %.1f dB over %d clip(s) and %d source(s).", values$si_sdr_mean, length(clips), length(REFS)),
statistics = stats_list,
tables = tables,
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "separation", path = file.path(out, "separation.parquet"), format = "parquet"))
))
Mean SI-SDR -5.1 dB over 2 clip(s) and 3 source(s).
- Mean SI-SDR (dB)
- −5.059
- Mean SNR (dB)
- 3.190
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Signals are aligned in time — Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR.
- No silent sources — Every true source varies in every clip.
- One estimate per source — 3 separated signals for 3 true sources, paired in column order.
Scores by clip and source
| Clip | True source | Matched estimate | SI-SDR (dB) | SNR (dB) |
|---|---|---|---|---|
| a | s1 | est1 | 11.103 | 11.124 |
| a | s2 | est2 | 6.031 | 6.997 |
| a | s3 | est3 | 6.833 | 7.580 |
| b | s1 | est1 | −12.894 | −0.1386 |
| b | s2 | est2 | −13.933 | −1.969 |
| b | s3 | est3 | −27.497 | −4.456 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Source separation metrics (SI-SDR, SDR, SIR, SAR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.separation 1.0.1 · spec d0fa779762d209de
# Dataset: aud1_separation (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import separation as sep
# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_separation.parquet", columns=["s1", "s2", "s3", "est1", "est2", "est3", "clip"])
n_input = len(df)
df["clip"] = pd.Categorical(df["clip"], categories=sorted(df["clip"].dropna().unique()))
df = df.dropna(subset=["s1", "s2", "s3", "est1", "est2", "est3", "clip"]) # listwise deletion over the analysis columns
df["clip"] = df["clip"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["s1", "s2", "s3", "est1", "est2", "est3", "clip"]) # infinite values stop the run (registry/errors.yaml)
# %% Signals: one column per true source and per separated signal, samples in row order
REFS = ["s1", "s2", "s3"]
ESTS = ["est1", "est2", "est3"]
MIX = None
CLIP = "clip"
PERMUTE = False
ZERO_MEAN = True
BSS = False
FLEN = 512
if len(ESTS) != len(REFS):
cs.cs_error("CS_E_INVALID_OPTION", option="Separated signals", allowed=f"{len(REFS)} columns, one per true source", value=len(ESTS))
clips = [("all rows", df)] if CLIP is None else [(str(k), g) for k, g in df.groupby(CLIP, observed=True, sort=True)]
# %% Scores per clip: permutation-invariant matching on SI-SDR, then SI-SDRi and BSS Eval
rows = []
n_permuted = 0
for name, g in clips:
R = g[REFS].to_numpy(dtype=np.float64).T
E = g[ESTS].to_numpy(dtype=np.float64).T
for i, c in enumerate(REFS):
s = R[i] - np.mean(R[i]) if ZERO_MEAN else R[i]
if float(np.dot(s, s)) == 0.0:
cs.cs_error("CS_E_UNDEFINED", what="SI-SDR", reason=f"the true source {c} is silent in clip {name}")
m = g[MIX].to_numpy(dtype=np.float64) if MIX is not None else None
r = sep.evaluate(R, E, m, zero_mean=ZERO_MEAN, bss=BSS, flen=FLEN, permute=PERMUTE)
if any(int(r["perm"][i]) != i for i in range(len(REFS))):
n_permuted += 1
for i, c in enumerate(REFS):
rows.append({
"clip": name, "source": c, "estimate": ESTS[int(r["perm"][i])], "samples": int(R.shape[1]),
"si_sdr": float(r["si_sdr"][i]),
"si_sdri": float(r["si_sdri"][i]) if m is not None else None,
"mixture_si_sdr": float(r["mixture_si_sdr"][i]) if m is not None else None,
"sdr": float(r["sdr"][i]) if BSS else None,
"sir": float(r["sir"][i]) if BSS else None,
"sar": float(r["sar"][i]) if BSS else None,
"snr": float(r["snr"][i]),
})
def mean_of(key, source=None):
v = [x[key] for x in rows if x[key] is not None and (source is None or x["source"] == source)]
return float(np.mean(v)) if v else None
si = np.array([x["si_sdr"] for x in rows])
values = {
"n_clips": len(clips), "n_sources": len(REFS), "n_samples": len(df),
"si_sdr_mean": mean_of("si_sdr"), "si_sdr_median": float(np.median(si)), "si_sdr_min": float(np.min(si)),
"si_sdri_mean": mean_of("si_sdri"), "mixture_si_sdr_mean": mean_of("mixture_si_sdr"),
"sdr_mean": mean_of("sdr"), "sir_mean": mean_of("sir"), "sar_mean": mean_of("sar"), "snr_mean": mean_of("snr"),
"n_permuted": n_permuted, "filter_length": FLEN if BSS else None,
}
for c in REFS:
for key in ("si_sdr", "si_sdri", "sdr", "sir", "sar", "snr"):
v = mean_of(key, c)
if v is not None:
values[f"{key}[{c}]"] = v
# %% Artifact: one row per clip and source
out = csml.out_dir("target/academy-parity/run-8142/evaluate.separation/column_order_no_matching/out-python")
art = pd.DataFrame(rows, columns=["clip", "source", "estimate", "samples", "si_sdr", "si_sdri", "mixture_si_sdr", "sdr", "sir", "sar", "snr"])
for c in ("clip", "source", "estimate"):
art[c] = art[c].astype("string")
for c in ("si_sdri", "mixture_si_sdr", "sdr", "sir", "sar"):
art[c] = pd.to_numeric(art[c], errors="coerce").astype("float64")
art.to_parquet(os.path.join(out, "separation.parquet"), index=False)
# %% Result
cols = [{"key": "clip", "label": "Clip"}, {"key": "source", "label": "True source"}, {"key": "estimate", "label": "Matched estimate"},
{"key": "si_sdr", "label": "SI-SDR (dB)", "type": "number"}]
if MIX is not None:
cols += [{"key": "si_sdri", "label": "SI-SDRi (dB)", "type": "number"}, {"key": "mixture_si_sdr", "label": "Mixture SI-SDR (dB)", "type": "number"}]
if BSS:
cols += [{"key": "sdr", "label": "SDR (dB)", "type": "number"}, {"key": "sir", "label": "SIR (dB)", "type": "number"}, {"key": "sar", "label": "SAR (dB)", "type": "number"}]
cols += [{"key": "snr", "label": "SNR (dB)", "type": "number"}]
tables = [{"key": "scores", "title": "Scores by clip and source", "columns": cols, "rows": [{c["key"]: x[c["key"]] for c in cols} for x in rows[:500]]}]
kind, src, val = [], [], []
for x in rows:
if MIX is not None:
kind.append("Mixture"); src.append(x["source"]); val.append(x["mixture_si_sdr"])
kind.append("Separated"); src.append(x["source"]); val.append(x["si_sdr"])
charts = [cs.chart("si_sdr", "cleveland-dot", "SI-SDR by source" + (": mixture and separated" if MIX is not None else ""), {
"category": cs.col("True source", src, "categorical", REFS),
"value": cs.col("SI-SDR (dB)", [v if np.isfinite(v) else None for v in val], "numeric"),
"group": cs.col("Signal", kind, "categorical", ["Mixture", "Separated"] if MIX is not None else ["Separated"]),
}, note="Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture." if MIX is not None else "Mean over clips; higher is better.")]
if BSS:
metric, msrc, mval = [], [], []
for x in rows:
for key, label in (("sdr", "SDR"), ("sir", "SIR"), ("sar", "SAR")):
metric.append(label); msrc.append(x["source"]); mval.append(x[key] if np.isfinite(x[key]) else None)
charts.append(cs.chart("bss_eval", "cleveland-dot", "BSS Eval by source", {
"category": cs.col("True source", msrc, "categorical", REFS),
"value": cs.col("dB", mval, "numeric"),
"group": cs.col("Metric", metric, "categorical", ["SDR", "SIR", "SAR"]),
}, note="SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added."))
assumptions = [
{"key": "aligned", "label": "Signals are aligned in time", "status": "info",
"detail": "Rows are read as samples in time order; a delay between a source and its estimate lowers SI-SDR."},
{"key": "silent_reference", "label": "No silent sources", "status": "pass", "detail": "Every true source varies in every clip."},
{"key": "same_count", "label": "One estimate per source", "status": "pass",
"detail": f"{len(ESTS)} separated signals for {len(REFS)} true sources" + (f"; matching reordered them in {n_permuted} of {len(clips)} clips." if PERMUTE else ", paired in column order.")},
]
cs.publish({
"title": "Source separation metrics (SI-SDR, SDR, SIR, SAR)",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(df),
"summary": f"Mean SI-SDR {values['si_sdr_mean']:.1f} dB over {len(clips)} clip(s) and {len(REFS)} source(s).",
"statistics": [s for s in [
{"key": "si_sdr_mean", "label": "Mean SI-SDR (dB)", "value": values["si_sdr_mean"]},
{"key": "si_sdri_mean", "label": "Mean SI-SDRi (dB)", "value": values["si_sdri_mean"]} if MIX is not None else None,
{"key": "sdr_mean", "label": "Mean SDR (dB)", "value": values["sdr_mean"]} if BSS else None,
{"key": "sir_mean", "label": "Mean SIR (dB)", "value": values["sir_mean"]} if BSS else None,
{"key": "sar_mean", "label": "Mean SAR (dB)", "value": values["sar_mean"]} if BSS else None,
{"key": "snr_mean", "label": "Mean SNR (dB)", "value": values["snr_mean"]},
] if s is not None],
"tables": tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "separation", "path": os.path.join(out, "separation.parquet"), "format": "parquet"}],
})
With matching off, the rotated clip is scored against the wrong sources and the mean SI-SDR falls to −5.06 dB.
Check yourself
Why must estimates be matched to sources before scoring a separation?
Show the answer
Answer: b
The order of a separator's outputs carries no meaning. Matching keeps the score about separation quality rather than output order.
Leakage or artifacts?
CheckpointBSS EvalBSS Eval (SDR, SIR, SAR)Splits a separation's error into leakage from other sources (SIR), added artifacts (SAR) and both together (SDR), in dB. splits the error further. SIR counts only leakage from the other sources, SAR only artifacts the separation added, and SDR both. Here SIR is 11.0 dB and SAR 15.6 dB, so leakage is the bigger problem.
View data
| country | life_expectancy | sex |
|---|---|---|
| Japan | 83.300 | Male |
| Japan | 85.300 | Female |
| Japan | 82.600 | Male |
| Japan | 89.100 | Female |
| Japan | 81.200 | Male |
| Japan | 89.100 | Female |
| Japan | 83.500 | Male |
| Japan | 85.700 | Female |
| Japan | 79.900 | Male |
| Japan | 87.400 | Female |
| Japan | 83.800 | Male |
| Japan | 89.500 | Female |
| Japan | 80.600 | Male |
| Japan | 86.500 | Female |
| Japan | 84.200 | Male |
| Japan | 87.600 | Female |
| Japan | 82.100 | Male |
| Japan | 87.600 | Female |
| Japan | 82.800 | Male |
| Japan | 88.500 | Female |
| Japan | 83.800 | Male |
| Japan | 87.400 | Female |
| Japan | 83.400 | Male |
| Japan | 86.300 | Female |
| Japan | 81.900 | Male |
| Japan | 86.700 | Female |
| Japan | 80.800 | Male |
| Japan | 87.100 | Female |
| Japan | 81.500 | Male |
| Japan | 86.700 | Female |
| Japan | 81.100 | Male |
| Japan | 86 | Female |
| Japan | 83.900 | Male |
| Japan | 87.900 | Female |
| Japan | 81.300 | Male |
| Japan | 87.200 | Female |
| Japan | 81.300 | Male |
| Japan | 85.200 | Female |
| Japan | 85.100 | Male |
| Japan | 85.500 | Female |
| Spain | 78 | Male |
| Spain | 86.200 | Female |
| Spain | 80.800 | Male |
| Spain | 86.400 | Female |
| Spain | 81.100 | Male |
| Spain | 85.200 | Female |
| Spain | 82 | Male |
| Spain | 85.500 | Female |
| Spain | 80.700 | Male |
| Spain | 86.700 | Female |
| Spain | 83 | Male |
| Spain | 86.700 | Female |
| Spain | 77.900 | Male |
| Spain | 85.800 | Female |
| Spain | 82.300 | Male |
| Spain | 85.700 | Female |
| Spain | 81.100 | Male |
| Spain | 89.200 | Female |
| Spain | 81.800 | Male |
| Spain | 87.400 | Female |
First 60 of 480 rows.
Check yourself
A separation has SIR 25 dB and SAR 6 dB. What does a listener most likely hear?
Show the answer
Answer: b
A high SIR means little leakage; a low SAR means the separation added artifacts of its own. Aggressive masks often trade one for the other.
Concepts in this lesson