Lab: scoring separation with PIT and SI-SDR
Audio lab B. Separated outputs come in no particular order: match them to sources, compute SI-SDR by hand, check that scale doesn't matter, and read the improvement over the mixture, in code and in CodeSplash.
What runs in CodeSplash
- AUD041Permutation invariant training (PIT) Runs in CodeSplash
- Source separation metrics (SI-SDR, SDR, SIR, SAR) Verified in Python and R
You will be able to
- Explain why anonymous separated outputs must be matched to sources before scoring
- Compute SI-SDR by hand with the centered convention, and show it ignores scale
- Read SI-SDR, its improvement over the mixture, and BSS Eval's SDR, SIR and SAR
- Use the permutation-invariant loss for training and the matching for evaluation
Which output is which?
ReadA separator for two speakers has two outputs, and nothing says which speaker comes out of which. During training, if the loss compared output 1 with speaker 1, a model that put speaker 1 on output 2 would be punished for a perfect answer. Permutation-invariant trainingPermutation-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. (PIT) scores every assignment of outputs to sources and keeps the best:
Evaluation needs the same matching. With sources there are assignments: fine for 2 or 3, while larger calls for an assignment solver.
Reference · AUD041 · Runs in CodeSplashPermutation invariant training (PIT)A supervised training principle resolving the arbitrary ordering of multiple predicted sources. It selects the reference assignment with smallest loss, allowing source-separation or speaker-activity models to learn…SI-SDR
ReadThe usual 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.. Center both signals, project the estimate onto the reference to get the best scaled copy, and compare that copy's energy with what's left over:
Turning the estimate up or down changes nothing, which is the point: a separator shouldn't be scored on loudness. A silent reference has no SI-SDR at all; say how silence is handled.
The lab in code
ReadTwo tones, outputs in the wrong order, each with a little leakage from the other source:
import itertools
import numpy as np
def si_sdr(est, ref):
est = est - est.mean(); ref = ref - ref.mean() # centered convention
target = (est @ ref) / (ref @ ref) * ref # best scaled copy of the reference
resid = est - target
return 10 * np.log10((target @ target) / (resid @ resid))
t = np.arange(4000) / 8000 # half a second at 8 kHz
sources = np.stack([np.sin(2 * np.pi * 220 * t), 0.7 * np.sin(2 * np.pi * 380 * t + 0.2)])
noise = 0.03 * np.cos(2 * np.pi * 710 * t)
estimates = np.stack([sources[1] + 0.1 * sources[0] + noise, # outputs in the "wrong" order,
sources[0] + 0.1 * sources[1] - noise]) # each with a little leakage
mixture = sources.sum(axis=0)
perms = list(itertools.permutations(range(2)))
costs = [np.mean((estimates - sources[list(p)]) ** 2) for p in perms]
best = perms[int(np.argmin(costs))]
print(best) # best matching
print([round(float(si_sdr(estimates[k], sources[k])), 1) for k in range(2)]) # by position
print([round(float(si_sdr(estimates[k], sources[best[k]])), 1) for k in range(2)]) # after matching
print([round(float(si_sdr(mixture, sources[best[k]])), 1) for k in range(2)]) # the mixture itself
print(round(float(si_sdr(3 * estimates[0], sources[best[0]])), 1)) # scaling changes nothingsi_sdr <- function(est, ref) {
est <- est - mean(est); ref <- ref - mean(ref) # centered convention
target <- sum(est * ref) / sum(ref * ref) * ref # best scaled copy of the reference
resid <- est - target
10 * log10(sum(target^2) / sum(resid^2))
}
t <- (0:3999) / 8000 # half a second at 8 kHz
sources <- rbind(sin(2 * pi * 220 * t), 0.7 * sin(2 * pi * 380 * t + 0.2))
noise <- 0.03 * cos(2 * pi * 710 * t)
estimates <- rbind(sources[2, ] + 0.1 * sources[1, ] + noise, # outputs in the "wrong" order,
sources[1, ] + 0.1 * sources[2, ] - noise) # each with a little leakage
mixture <- colSums(sources)
perms <- list(c(1, 2), c(2, 1))
costs <- sapply(perms, function(p) mean((estimates - sources[p, ])^2))
best <- perms[[which.min(costs)]]
print(best) # best matching
print(round(sapply(1:2, function(k) si_sdr(estimates[k, ], sources[k, ])), 1)) # by position
print(round(sapply(1:2, function(k) si_sdr(estimates[k, ], sources[best[k], ])), 1)) # after matching
print(round(sapply(1:2, function(k) si_sdr(mixture, sources[best[k], ])), 1)) # the mixture
print(round(si_sdr(3 * estimates[1, ], sources[best[1], ]), 1)) # scaling changes nothingRun it. By position both scores are strongly negative; after matching both are strongly positive. The last line equals the first matched score: tripling the output changed nothing.
Notebook exercise · ~12 min
Score a separation with SI-SDR and PIT
Compute scale-invariant SDR by hand, see a good separation score badly in the wrong order, and fix it with permutation-invariant scoring.
- SI-SDR in the order returned
Write
si_sdr(e, r): project the estimate onto the reference, target = (e·r / r·r) r, call the rest the error, and return 10 log10(‖target‖² / ‖error‖²). Pair the first estimate withs1and the second withs2, and store the mean of the two SI-SDRs infixed.Show a solution
Pythondef si_sdr(e, r): target = (e @ r) / (r @ r) * r return 10 * math.log10((target @ target) / ((e - target) @ (e - target))) fixed = (si_sdr(est[0], s1) + si_sdr(est[1], s2)) / 2Rsi_sdr <- function(e, r) { target <- sum(e * r) / sum(r * r) * r 10 * log10(sum(target^2) / sum((e - target)^2)) } fixed <- (si_sdr(est[[1]], s1) + si_sdr(est[[2]], s2)) / 2 - Permutation-invariant scoring
Score both pairings: (first, s1) with (second, s2), and (first, s2) with (second, s1). Store the better of the two mean SI-SDRs in
pit.Show a solution
Pythonpit = max((si_sdr(est[0], s1) + si_sdr(est[1], s2)) / 2, (si_sdr(est[0], s2) + si_sdr(est[1], s1)) / 2)Rpit <- max((si_sdr(est[[1]], s1) + si_sdr(est[[2]], s2)) / 2, (si_sdr(est[[1]], s2) + si_sdr(est[[2]], s1)) / 2) - Is it really scale invariant?
Multiply the better-matched estimate for
s1by 3 and score it again. StoreTrue(R:TRUE) inscale_freeif its SI-SDR changed by less than 1e-9 dB, elseFalse.Show a solution
Pythonscale_free = abs(si_sdr(3 * est[1], s1) - si_sdr(est[1], s1)) < 1e-9Rscale_free <- abs(si_sdr(3 * est[[2]], s1) - si_sdr(est[[2]], s1)) < 1e-9
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
Improvement over the mixture
ReadThe fourth line scores the unprocessed mixture against each source. The quieter source starts lower, because the louder one drowns it. That baseline matters: a separator that returns the mixture unchanged already gets those scores. SI-SDR improvementSI-SDR improvement (SI-SDRi)The separated signal's SI-SDR minus the mixture's: how much the separation helped compared with doing nothing. (SI-SDRi) subtracts the mixture's score, so it measures what separation added. Report both.
Don't swap in other numbers under the same name. Classical SDR from BSS Eval allows a short distortion filter, so it is more lenient than SI-SDR; plain SNR isn't scale-invariant. They aren't interchangeable.
DExplorable · Scoring separated sources: SI-SDR and permutation-invariant matching
How do you score a separator that returns the right voices in the wrong order?
A tone and a buzzy wave, plus a noise burst when there are three.
Output order
Separators don't know which output is which voice: here the outputs can come back rotated.
Share of the whole mix left in each output: the other sources bleeding through.
Scales every output. SI-SDR ignores the volume; SNR does not.
White noise the separator adds to each output.
Scoring
Match outputs to sources by trying every assignment (PIT), or score output k against source k.
Bars below zero are drawn flat; read their numbers. SI-SDR first rescales the source to fit the output, so the output's volume can't change it.
- Mean SI-SDR as scored (dB)
- 17.40
- Mean SI-SDR, best assignment (dB)
- 17.40
- Mean SI-SDR, fixed order (dB)
- −21.57
- Mean SNR as scored (dB)
- 16.62
- SI-SDR improvement over the mix (dB)
- 17.40
- Puzzle: With the best assignment, find settings where SNR and SI-SDR disagree by more than 6 dB.
PIT matches source 1 → output 2, source 2 → output 1: mean SI-SDR 17.4 dB (SNR 16.6 dB); against the raw mix that is a change of 17.4 dB. Best assignment 17.4 dB against fixed order −21.6 dB.
Order matters: in CodeSplash
ReadMean 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"}],
})
Source separation metrics scores separated signals against the true ones. With matching turned off, each estimate column is scored against the reference column in the same position: the mean SI-SDR is −5.1 dB.
Matched, with the mixture
ReadMean 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"}],
})
With matching on, the same estimates score 8.1 dB on average; 1 clip needed its outputs reordered. Given the mixture, the method also reports the mixture's own SI-SDR, −3.3 dB, and the improvement, 11.4 dB.
BSS Eval splits the error further: SIR (other sources leaking in) is 11.0 dB and SAR (artifacts) 15.6 dB, so leakage is the larger problem here.
When not to permute
PredictPredict first
A music separator outputs vocals, drums, bass and other. Should you score it with permutation matching?
Reveal
No. StemsMusic stemsFixed named music sources such as vocals, drums and bass. Outputs keep their names, so scoring needs no permutation search. have fixed identities. Permutation matching could pair a "vocals" output with the drum reference and hide a real error. Turn matching off and keep the column order meaningful.
Where it stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Permutation-invariant training (AUD041) | Runs in CodeSplash for scoring: Source separation metrics matches outputs to sources and reports SI-SDR, SI-SDRi, SDR, SIR and SAR. Training with the PIT loss is explained here |
The reference's PIT program is a component check, verified in Python and R.
Check: PIT and SI-SDR
CheckpointCheck yourself
Why does training a two-speaker separator need a permutation-invariant loss?
Show the answer
Answer: b
PIT scores every assignment and keeps the best, so the model is free to put either speaker on either output.
Check yourself
A separator has four anonymous outputs. How many assignments does exhaustive PIT check per example?
Show the answer
Answer: 24
. Beyond a handful of sources, an assignment solver replaces enumeration.
Check yourself
You double the volume of a separated output. What happens to its SI-SDR and its plain SNR?
Show the answer
Answer: a
SI-SDR compares the estimate with its best scaled copy of the reference, so overall gain cancels out. Plain SNR compares with the reference at its own scale.
Check yourself
System A scores 10 dB SI-SDR on mixtures whose own SI-SDR is 5 dB. System B scores 8 dB on mixtures at −4 dB. Which separated more?
Show the answer
Answer: b
SI-SDRi subtracts the mixture's own score. Easy test mixtures inflate SI-SDR; the improvement shows what the model added.
Recap
Recap- Anonymous outputs must be matched to sources: PIT for training, best matching for scoring.
- SI-SDR centers, projects onto the reference and ignores scale; silent references have no score.
- Report SI-SDRi beside SI-SDR; SDR, SIR, SAR and plain SNR are different numbers.
- Named stems keep their order. Source separation metrics runs all of this in CodeSplash.
Concepts in this lesson