Skip to content

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.

Advanced ~18 min10 steps

What runs in CodeSplash

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

Read first

01

Which output is which?

Read

A 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:

LPIT=min⁡π∈SK1K∑k=1Kℓ(s^k,sπ(k)).\mathcal{L}_{\text{PIT}} = \min_{\pi \in S_K} \frac{1}{K} \sum_{k=1}^{K} \ell\bigl(\hat s_k, s_{\pi(k)}\bigr).

Evaluation needs the same matching. With KK sources there are K!K! assignments: fine for 2 or 3, while larger KK 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…
02

SI-SDR

Read

The 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:

starget=⟨s^,s⟩∥s∥2 s,SI-SDR=10log⁡10∥starget∥2∥s^−starget∥2.s_{\text{target}} = \frac{\langle \hat s, s \rangle}{\lVert s \rVert^2}\, s, \qquad \text{SI-SDR} = 10 \log_{10} \frac{\lVert s_{\text{target}} \rVert^2}{\lVert \hat s - s_{\text{target}} \rVert^2}.

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.

03

The lab in code

Read

Two tones, outputs in the wrong order, each with a little leakage from the other source:

Python
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 nothing
R
si_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 nothing

Run 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.

  1. 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 with s1 and the second with s2, and store the mean of the two SI-SDRs in fixed.

    Show a solution
    Python
    def 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)) / 2
    R
    si_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
  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
    Python
    pit = max((si_sdr(est[0], s1) + si_sdr(est[1], s2)) / 2, (si_sdr(est[0], s2) + si_sdr(est[1], s1)) / 2)
    R
    pit <- max((si_sdr(est[[1]], s1) + si_sdr(est[[2]], s2)) / 2, (si_sdr(est[[1]], s2) + si_sdr(est[[2]], s1)) / 2)
  3. Is it really scale invariant?

    Multiply the better-matched estimate for s1 by 3 and score it again. Store True (R: TRUE) in scale_free if its SI-SDR changed by less than 1e-9 dB, else False.

    Show a solution
    Python
    scale_free = abs(si_sdr(3 * est[1], s1) - si_sdr(est[1], s1)) < 1e-9
    R
    scale_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.

04

Improvement over the mixture

Read

The 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?

2

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.

0.15

Share of the whole mix left in each output: the other sources bleeding through.

1.0

Scales every output. SI-SDR ignores the volume; SNR does not.

0.05

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.

SourcesOutputs, in the order returned1216.3−22.9−20.218.5Source 1Source 2Output 1Output 217.4 dBSI-SDR, best assignment−21.6 dBSI-SDR, fixed order16.6 dBSNR as scored

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.

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.

05

Order matters: in CodeSplash

Read
Source separation metrics (SI-SDR, SDR, SIR, SAR)Recorded · Python and R agreeRecorded 2026-11-25 · 20 values compared
R

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

SI-SDR by sourceHow do categories compare on one value — and across up to three groups?

Mean over clips; higher is better.

View data
True sourceSignalSI-SDR (dB)
s1Separated11.103
s2Separated6.031
s3Separated6.833
s1Separated−12.894
s2Separated−13.933
s3Separated−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

ClipTrue sourceMatched estimateSI-SDR (dB)SNR (dB)
as1est111.10311.124
as2est26.0316.997
as3est36.8337.580
bs1est1−12.894−0.1386
bs2est2−13.933−1.969
bs3est3−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"))
))
Python

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

ClipTrue sourceMatched estimateSI-SDR (dB)SNR (dB)
as1est111.10311.124
as2est26.0316.997
as3est36.8337.580
bs1est1−12.894−0.1386
bs2est2−13.933−1.969
bs3est3−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.

06

Matched, with the mixture

Read
Source separation metrics (SI-SDR, SDR, SIR, SAR)Recorded · Python and R agreeRecorded 2026-11-25 · 32 values compared
R

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

SI-SDR by source: mixture and separatedHow do categories compare on one value — and across up to three groups?

Mean over clips. The gap between the dots is SI-SDRi, the gain over the unseparated mixture.

View data
True sourceSignalSI-SDR (dB)
s1Mixture0.2224
s1Separated11.103
s2Mixture−5.643
s2Separated6.031
s3Mixture−4.643
s3Separated6.833
s1Mixture1.127
s1Separated11.966
s2Mixture−6.423
s2Separated5.388
s3Mixture−4.630
s3Separated7.167
BSS Eval by sourceHow do categories compare on one value — and across up to three groups?

SDR counts every error; SIR only leakage from the other sources; SAR only artifacts the separation added.

View data
True sourceMetricdB
s1SDR12.628
s1SIR14.130
s1SAR18.132
s2SDR7.940
s2SIR9.386
s2SAR13.894
s3SDR8.236
s3SIR9.613
s3SAR14.344
s1SDR13.368
s1SIR15.032
s1SAR18.475
s2SDR6.653
s2SIR7.731
s2SAR13.910
s3SDR8.662
s3SIR9.939
s3SAR15.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

ClipTrue sourceMatched estimateSI-SDR (dB)SI-SDRi (dB)Mixture SI-SDR (dB)SDR (dB)SIR (dB)SAR (dB)SNR (dB)
as1est111.10310.8810.222412.62814.13018.13211.124
as2est26.03111.674−5.6437.9409.38613.8946.997
as3est36.83311.477−4.6438.2369.61314.3447.580
bs1est311.96610.8401.12713.36815.03218.47511.685
bs2est15.38811.810−6.4236.6537.73113.9106.477
bs3est27.16711.796−4.6308.6629.93915.0197.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"))
))
Python

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

ClipTrue sourceMatched estimateSI-SDR (dB)SI-SDRi (dB)Mixture SI-SDR (dB)SDR (dB)SIR (dB)SAR (dB)SNR (dB)
as1est111.10310.8810.222412.62814.13018.13211.124
as2est26.03111.674−5.6437.9409.38613.8946.997
as3est36.83311.477−4.6438.2369.61314.3447.580
bs1est311.96610.8401.12713.36815.03218.47511.685
bs2est15.38811.810−6.4236.6537.73113.9106.477
bs3est27.16711.796−4.6308.6629.93915.0197.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.

07

When not to permute

Predict

Predict first

A music separator outputs vocals, drums, bass and other. Should you score it with permutation matching?

Yes: always take the best matchingNo: stems have fixed names, so score vocals against vocals
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.

08

Where it stands in CodeSplash

Read
EntryIn 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.

09

Check: PIT and SI-SDR

Checkpoint

Check 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

4!=244! = 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.

10

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