Skip to content

ADescribe · audio.separate_nmf

Separate sounds with NMF

Can this recording be split into a few sounds that add up to it, and what does each one sound like?

Splits each audio file into a few component tracks that add back up to the original. The magnitude spectrogram is factorized by non-negative matrix factorization (the same solver as Discover's NMF) into spectral templates (what each sound's spectrum looks like) and activations (when each sound is on); soft masks then cut the original spectrogram into one track per component, which is turned back into audio. Works best when the sounds differ in pitch or timbre (a hum under speech, a drum under a melody) and poorly when they overlap in frequency. The tracks are saved as WAV files with the run, and can be added as an audio collection to listen to or measure. Identical in Python and R.

Experimental Python and R agree to 6 decimals Seeded Also called NMF source separation, audio source separation, unmix audio…

A real result

Example “Two components”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Separate sounds with NMFRecorded · Python and R agreeRecorded 2026-11-25 · 11 values compared
R

4 files split into 2 components each; mean NMF relative error 0.397.

Files separated
4
Mean NMF relative error
0.3968
Largest gap, tracks vs original
8.882e-16

Assumptions

  • Files decode — Every file processed was decoded.
  • Sounds differ in spectrum — The NMF model leaves 39.7% of the spectrogram unexplained on average; listen to the tracks to judge the split.
  • Components are unnamed — Components are ordered by their total activation, loudest first.

Components by file

FileComponentShare of energyTemplate centroid (Hz)Template peak (Hz)
tone_a.wav10.7871484.06437.50
tone_a.wav20.2129441.31437.50
tone_b.wav10.91151590.58656.25
tone_b.wav20.08851153.48640.63
noise_a.wav10.5168729.1531.250
noise_a.wav20.4832695.620
chirp_loud.wav10.55641336.441968.75
chirp_loud.wav20.44361502.201,375

Fit by file

FileNMF relative errorTracks vs original (relative gap)
tone_a.wav0.13716.716e-16
tone_b.wav0.08428.882e-16
noise_a.wav0.44026.301e-16
chirp_loud.wav0.92576.918e-16
Python

4 files split into 2 components each; mean NMF relative error 0.397.

Files separated
4
Mean NMF relative error
0.3968
Largest gap, tracks vs original
1.969e-16

Assumptions

  • Files decode — Every file processed was decoded.
  • Sounds differ in spectrum — The NMF model leaves 39.7% of the spectrogram unexplained on average; listen to the tracks to judge the split.
  • Components are unnamed — Components are ordered by their total activation, loudest first.

Components by file

FileComponentShare of energyTemplate centroid (Hz)Template peak (Hz)
tone_a.wav10.7871484.06437.50
tone_a.wav20.2129441.31437.50
tone_b.wav10.91151590.58656.25
tone_b.wav20.08851153.48640.63
noise_a.wav10.5168729.1531.250
noise_a.wav20.4832695.620
chirp_loud.wav10.55641336.441968.75
chirp_loud.wav20.44361502.201,375

Fit by file

FileNMF relative errorTracks vs original (relative gap)
tone_a.wav0.13711.808e-16
tone_b.wav0.08421.969e-16
noise_a.wav0.44021.842e-16
chirp_loud.wav0.92571.953e-16

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Two componentsaud1_clips · audio: path
  • Three components poweraud1_clips · audio: path
  • Degenerate all naaud1_clips · audio: path
  • Degenerate n1aud1_clips · audio: path
  • Degenerate n2aud1_clips · audio: path
  • Degenerate n3aud1_clips · audio: path

In the guides

Where it sits in the decision guides

  • Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels
  • Sequences, curves and signals (hidden Markov models, functional PCA, scattering) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Audio filecategorical · 1 column
A column of audio file paths; each file is separated on its own.

Choices you make

model

Componentsdefault 2

How many sounds to split each file into. Try the number of sources you expect, then one more for noise.

Factorizedefault 1

Which spectrogram NMF factorizes; the masks always split the original.

  • Magnitude(default) — The usual choice: closer to how loud each sound is, and more forgiving of overlap.
  • Power — Squared magnitudes: the loudest sound dominates the split more.

Advanced

Iterationsdefault 200

Multiplicative-update passes of NMF.

Frame length (samples)default 1024

Longer frames separate close pitches better but smear fast changes; 1024 at 16 kHz is 64 ms.

Frame step (samples)default 256

Samples between frames; a quarter of the frame length gives a perfect reconstruction.

Sample rate (Hz)default 16000

Files are resampled to this rate and mixed to mono first.

options

Files to separatedefault 20

Separate at most this many files (in table order); each writes one track per component.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Files decode

    Files that can't be decoded or are missing are listed and skipped.

  • Sounds differ in spectrum

    NMF splits sounds by their spectra; two sounds that share frequencies (two voices, overlapping instruments) end up mixed.

  • Components are unnamed

    Components are ordered by how much they sound (loudest first), not by what they are; listen to decide which is which.

What it reports

n_rows
Splitting a recording by factorizing its spectrogram into templates and activations, then masking the original into one track each.
n_files
Splitting a recording by factorizing its spectrogram into templates and activations, then masking the original into one track each.
n_separated
Splitting a recording by factorizing its spectrogram into templates and activations, then masking the original into one track each.
n_components
Splitting a recording by factorizing its spectrogram into templates and activations, then masking the original into one track each.
rel_error_mean
How much of the spectrogram the NMF model leaves unexplained, as a share of its size; lower means the components fit better.
rel_error_max
How much of the spectrogram the NMF model leaves unexplained, as a share of its size; lower means the components fit better.
sum_error_max
How far the separated tracks, added together, are from the original, relative to its size; near 0 when the masks cover it.

Per group, level or term: energy_share[<k>], centroid_hz[<k>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, pandas, scipy, codesplash; R uses nanoparquet, jsonlite, codesplashr.

Default traps between the two languages

  • Both engines run the same twins (codesplash.audio.separate ↔ codesplashr R/audio_separate.R) on the same decoded samples, and NMF is discover.nmf's multiplicative-update twin from the same shared random start; the iterations amplify FFT and matrix-product rounding slightly, hence P1.
Python

The exact script CodeSplash ran for example “Two components” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Separate sounds with NMF
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.separate_nmf 1.0.0 · spec d4e4ebaf0ce6f7aa
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import describe as ad
from codesplash.audio import dsp
from codesplash.audio import separate as asep
from codesplash.errors import CsError

# %% Data
df = pd.read_parquet("tests/parity/fixtures/aud1_clips.parquet", columns=["path"])
n_input = len(df)
df["path"] = pd.Categorical(df["path"], categories=sorted(df["path"].dropna().unique()))
df = df.dropna(subset=["path"])  # listwise deletion over the analysis columns
df["path"] = df["path"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["path"])  # infinite values stop the run (registry/errors.yaml)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.separate_nmf/two_components/out-python", df, "tests/parity/fixtures/aud1_clips.parquet")
media_ids = cs_media.ids_of(media, df)
if not media.get("root"):
    media["root"] = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud1_clips.parquet"))  # relative paths start next to the data file

# %% Settings
PATH = "path"
SR = float(media["transform"]["sample_rate"])
K, ITER, N_FFT, HOP = 2, 60, 1024, 256
POWER = float("1")
MAX_FILES = 4
SEED = 42
out = csml.out_dir("target/academy-parity/run-8142/audio.separate_nmf/two_components/out-python")
TRACKS = os.path.join(out, "tracks")
os.makedirs(TRACKS, exist_ok=True)

# %% Separate each file: NMF on the spectrogram, soft masks, inverse STFT
status = cs_media.status(media, media_ids)
paths = df[PATH].astype(str).tolist()
rows, files, bad, first = [], [], [], None
for i, mid in enumerate(media_ids):
    if len(files) >= MAX_FILES:
        break
    x = None
    if status[i] is None:
        try:
            x = np.asarray(cs_media.audio(media, [mid])[0], dtype=np.float64)
        except CsError:
            x = None
    name = os.path.basename(paths[i])
    if x is None:
        bad.append({"file": name, "path": paths[i]})
        continue
    r = asep.nmf_separate(x, SR, K, N_FFT, HOP, ITER, SEED, POWER)
    energy = np.sum(r["tracks"] ** 2, axis=1)
    total = float(np.sum(energy))
    xn = float(np.linalg.norm(x))
    gap = float(np.linalg.norm(np.sum(r["tracks"], axis=0) - x)) / xn if xn > 0 else 0.0
    stem = f"{len(files) + 1:03d}_" + "".join(ch if (ch.isascii() and ch.isalnum()) or ch in "-_" else "_" for ch in os.path.splitext(name)[0])[:60]
    for k in range(K):
        wav = os.path.join(TRACKS, f"{stem}_c{k + 1}.wav")
        asep.write_wav(wav, r["tracks"][k], int(SR))
        rows.append({"file": name, "media_id": mid, "component": k + 1,
                     "energy_share": float(energy[k] / total) if total > 0 else None,
                     "centroid_hz": float(np.sum(r["freqs"] * r["templates"][k])),
                     "peak_hz": float(r["freqs"][int(np.argmax(r["templates"][k]))]),
                     "track": wav})
    files.append({"file": name, "rel_error": r["rel_error"], "sum_error": gap})
    if first is None:
        first = (name, x, r)
if not files:
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an audio file that exists and can be decoded", count=len(bad))
warnings = list(warnings)
if bad:
    warnings.append(f"{len(bad)} listed files could not be read and were skipped.")

# %% Artifacts: one WAV per file and component, and a table of the components
art = pd.DataFrame(rows, columns=["file", "media_id", "component", "energy_share", "centroid_hz", "peak_hz", "track"])
for c in ("file", "media_id", "track"):
    art[c] = art[c].astype("string")
art["component"] = art["component"].astype("int64")
art["energy_share"] = pd.to_numeric(art["energy_share"], errors="coerce").astype("float64")
art_path = os.path.join(out, "components.parquet")
art.to_parquet(art_path, index=False)

# %% Result
values = {"n_rows": len(media_ids), "n_files": len(files) + len(bad), "n_separated": len(files), "n_components": K,
          "rel_error_mean": float(np.mean([f["rel_error"] for f in files])), "rel_error_max": float(np.max([f["rel_error"] for f in files])),
          "sum_error_max": float(np.max([f["sum_error"] for f in files]))}
for k in range(1, K + 1):
    sh = [r["energy_share"] for r in rows if r["component"] == k and r["energy_share"] is not None]
    if sh:
        values[f"energy_share[{k}]"] = float(np.mean(sh))
    values[f"centroid_hz[{k}]"] = float(np.mean([r["centroid_hz"] for r in rows if r["component"] == k]))
tables = [
    {"key": "components", "title": "Components by file",
     "columns": [{"key": "file", "label": "File"}, {"key": "component", "label": "Component", "type": "integer"},
                 {"key": "energy_share", "label": "Share of energy", "type": "number"}, {"key": "centroid_hz", "label": "Template centroid (Hz)", "type": "number"},
                 {"key": "peak_hz", "label": "Template peak (Hz)", "type": "number"}],
     "rows": [{k: r[k] for k in ("file", "media_id", "component", "energy_share", "centroid_hz", "peak_hz")} for r in rows[:200]]},
    {"key": "fit", "title": "Fit by file",
     "columns": [{"key": "file", "label": "File"}, {"key": "rel_error", "label": "NMF relative error", "type": "number"},
                 {"key": "sum_error", "label": "Tracks vs original (relative gap)", "type": "number"}], "rows": files[:200]},
]
if bad:
    tables.append({"key": "unreadable", "title": "Files that could not be read", "columns": [{"key": "file", "label": "File"}, {"key": "path", "label": "Path"}], "rows": bad[:50]})
name, x, r = first
labels = [f"Component {k + 1}" for k in range(K)]
charts = [cs.chart("energy", "cleveland-dot", "Share of energy by component", {
    "category": cs.col("Component", [labels[r_["component"] - 1] for r_ in rows], "categorical", labels),
    "value": cs.col("Share of energy", [r_["energy_share"] for r_ in rows], "numeric"),
}, note="Mean over the separated files; components are ordered loudest first.")]
seg = int(min(len(x), 10 * SR))
S = np.abs(dsp.stft(x[:seg], N_FFT, HOP))
D = dsp.power_to_db(S**2, "max", 1e-10, 80.0)
T = dsp.frame_times(D.shape[1], SR, HOP)
F = dsp.fft_frequencies(SR, N_FFT)
charts.append(cs.chart("spectrogram", "spectrogram", f"Spectrogram: {name}", {
    "x": cs.col("Time (s)", np.repeat(T, len(F)), "numeric"),
    "y": cs.col("Frequency (Hz)", np.tile(F, len(T)), "numeric"),
    "z": cs.col("Level (dB re max)", D.T.ravel(), "numeric"),
}, controls={"scale": "linear"}, note=f"Hann frames of {N_FFT} samples every {HOP} at {int(SR)} Hz; the first 10 s."))
t0, t1, lo, hi, rm, trk = [], [], [], [], [], []
for label, sig in [("Original", x)] + [(labels[k], r["tracks"][k]) for k in range(K)]:
    e = ad.envelope(sig, SR, 600)
    t0 += e["start"]; t1 += e["end"]; lo += e["min"]; hi += e["max"]; rm += e["rms"]; trk += [label] * len(e["min"])
charts.append(cs.chart("tracks", "waveform", f"Original and separated tracks: {name}", {
    "time": cs.col("Time (s)", t0, "numeric"), "end": cs.col("End (s)", t1, "numeric"),
    "min": cs.col("Min", lo, "numeric"), "max": cs.col("Max", hi, "numeric"), "rms": cs.col("RMS", rm, "numeric"),
    "track": cs.col("Track", trk, "categorical", ["Original"] + labels),
}))
assumptions = [
    {"key": "decoded", "label": "Files decode", "status": "warn" if bad else "pass",
     "detail": f"{len(bad)} files could not be read and were skipped." if bad else "Every file processed was decoded."},
    {"key": "different_spectra", "label": "Sounds differ in spectrum", "status": "info",
     "detail": f"The NMF model leaves {values['rel_error_mean']:.1%} of the spectrogram unexplained on average; listen to the tracks to judge the split."},
    {"key": "component_order", "label": "Components are unnamed", "status": "info", "detail": "Components are ordered by their total activation, loudest first."},
]
cs.publish({
    "title": "Separate sounds with NMF",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": len(files),
    "summary": f"{len(files)} files split into {K} components each; mean NMF relative error {values['rel_error_mean']:.3f}.",
    "statistics": [
        {"key": "n_separated", "label": "Files separated", "value": len(files)},
        {"key": "rel_error_mean", "label": "Mean NMF relative error", "value": values["rel_error_mean"]},
        {"key": "sum_error_max", "label": "Largest gap, tracks vs original", "value": values["sum_error_max"]},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "components", "path": art_path, "format": "parquet"}, {"key": "audio_tracks", "path": TRACKS, "format": "folder"}],
})
R

The exact script CodeSplash ran for example “Two components” · R version 4.5.1 (2025-06-13)

# Separate sounds with NMF
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.separate_nmf 1.0.0 · spec d4e4ebaf0ce6f7aa
# Dataset: aud1_clips (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud1_clips.parquet", col_select = c("path")))
n_input <- nrow(df)
df[["path"]] <- factor(df[["path"]], levels = sort(unique(df[["path"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("path")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("path"))  # infinite values stop the run (registry/errors.yaml)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":null,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.separate_nmf/two_components/out-r", df,
                        "tests/parity/fixtures/aud1_clips.parquet")
media_ids <- cs_media_ids(media, df)
if (is.null(media$root) || !nzchar(media$root)) {
  media$root <- dirname(normalizePath("tests/parity/fixtures/aud1_clips.parquet", mustWork = FALSE))  # relative paths start next to the data file
}

# %% Settings
PATH <- "path"
SR <- as.numeric(media$transform$sample_rate)
K <- 2; ITER <- 60; N_FFT <- 1024; HOP <- 256
POWER <- as.numeric("1")
MAX_FILES <- 4
SEED <- 42
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.separate_nmf/two_components/out-r")
TRACKS <- file.path(out, "tracks")
dir.create(TRACKS, showWarnings = FALSE, recursive = TRUE)

# %% Separate each file: NMF on the spectrogram, soft masks, inverse STFT
status <- cs_media_status(media, media_ids)
paths <- as.character(df[[PATH]])
rows <- list(); files <- list(); bad <- list(); first <- NULL
for (i in seq_along(media_ids)) {
  if (length(files) >= MAX_FILES) break
  x <- NULL
  if (is.na(status[i])) x <- tryCatch(as.numeric(cs_media_audio(media, media_ids[i])[[1]]), cs_error = function(e) NULL)
  name <- basename(paths[i])
  if (is.null(x)) {
    bad[[length(bad) + 1]] <- list(file = name, path = paths[i])
    next
  }
  r <- cs_audio_nmf_separate(x, SR, K, N_FFT, HOP, ITER, SEED, POWER)
  energy <- rowSums(r$tracks^2)
  total <- sum(energy)
  xn <- sqrt(sum(x^2))
  gap <- if (xn > 0) sqrt(sum((colSums(r$tracks) - x)^2)) / xn else 0
  stem <- paste0(sprintf("%03d_", length(files) + 1), substr(gsub("[^A-Za-z0-9_-]", "_", tools::file_path_sans_ext(name)), 1, 60))
  for (k in seq_len(K)) {
    wav <- file.path(TRACKS, sprintf("%s_c%d.wav", stem, k))
    cs_audio_write_wav(wav, r$tracks[k, ], SR)
    rows[[length(rows) + 1]] <- list(file = name, media_id = media_ids[i], component = k,
                                     energy_share = if (total > 0) energy[k] / total else NULL,
                                     centroid_hz = sum(r$freqs * r$templates[k, ]),
                                     peak_hz = r$freqs[which.max(r$templates[k, ])],
                                     track = wav)
  }
  files[[length(files) + 1]] <- list(file = name, rel_error = r$rel_error, sum_error = gap)
  if (is.null(first)) first <- list(name = name, x = x, r = r)
}
if (!length(files)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an audio file that exists and can be decoded", count = length(bad))
if (length(bad)) warnings <- c(warnings, sprintf("%d listed files could not be read and were skipped.", length(bad)))

# %% Artifacts: one WAV per file and component, and a table of the components
art <- data.frame(
  file = vapply(rows, function(r) r$file, ""), media_id = vapply(rows, function(r) r$media_id, ""),
  component = vapply(rows, function(r) as.integer(r$component), 0L),
  energy_share = vapply(rows, function(r) if (is.null(r$energy_share)) NA_real_ else r$energy_share, 0),
  centroid_hz = vapply(rows, function(r) r$centroid_hz, 0), peak_hz = vapply(rows, function(r) r$peak_hz, 0),
  track = vapply(rows, function(r) r$track, ""), stringsAsFactors = FALSE
)
art_path <- file.path(out, "components.parquet")
nanoparquet::write_parquet(art, art_path)

# %% Result
rel <- vapply(files, function(f) f$rel_error, 0)
values <- list(n_rows = length(media_ids), n_files = length(files) + length(bad), n_separated = length(files), n_components = K,
               rel_error_mean = mean(rel), rel_error_max = max(rel), sum_error_max = max(vapply(files, function(f) f$sum_error, 0)))
for (k in seq_len(K)) {
  sh <- art$energy_share[art$component == k & !is.na(art$energy_share)]
  if (length(sh)) values[[sprintf("energy_share[%d]", k)]] <- mean(sh)
  values[[sprintf("centroid_hz[%d]", k)]] <- mean(art$centroid_hz[art$component == k])
}
top <- rows[seq_len(min(200, length(rows)))]
tables <- list(
  list(key = "components", title = "Components by file",
       columns = list(list(key = "file", label = "File"), list(key = "component", label = "Component", type = "integer"),
                      list(key = "energy_share", label = "Share of energy", type = "number"), list(key = "centroid_hz", label = "Template centroid (Hz)", type = "number"),
                      list(key = "peak_hz", label = "Template peak (Hz)", type = "number")),
       rows = lapply(top, function(r) list(file = r$file, media_id = r$media_id, component = r$component, energy_share = r$energy_share, centroid_hz = r$centroid_hz, peak_hz = r$peak_hz))),
  list(key = "fit", title = "Fit by file",
       columns = list(list(key = "file", label = "File"), list(key = "rel_error", label = "NMF relative error", type = "number"),
                      list(key = "sum_error", label = "Tracks vs original (relative gap)", type = "number")),
       rows = files[seq_len(min(200, length(files)))])
)
if (length(bad)) {
  tables[[3]] <- list(key = "unreadable", title = "Files that could not be read", columns = list(list(key = "file", label = "File"), list(key = "path", label = "Path")),
                      rows = bad[seq_len(min(50, length(bad)))])
}
labels <- sprintf("Component %d", seq_len(K))
charts <- list(cs_chart("energy", "cleveland-dot", "Share of energy by component", list(
  category = cs_col("Component", labels[art$component], "categorical", labels),
  value = cs_col("Share of energy", art$energy_share, "numeric")
), note = "Mean over the separated files; components are ordered loudest first."))
x <- first$x; r <- first$r
seg <- as.integer(min(length(x), 10 * SR))
S <- Mod(cs_audio_stft(x[seq_len(seg)], N_FFT, HOP))
D <- cs_audio_power_to_db(S^2, "max", 1e-10, 80)
T <- cs_audio_frame_times(ncol(D), SR, HOP)
F <- cs_audio_fft_frequencies(SR, N_FFT)
charts[[2]] <- cs_chart("spectrogram", "spectrogram", paste0("Spectrogram: ", first$name), list(
  x = cs_col("Time (s)", rep(T, each = length(F)), "numeric"),
  y = cs_col("Frequency (Hz)", rep(F, length(T)), "numeric"),
  z = cs_col("Level (dB re max)", as.vector(D), "numeric")
), controls = list(scale = "linear"), note = sprintf("Hann frames of %d samples every %d at %d Hz; the first 10 s.", N_FFT, HOP, as.integer(SR)))
t0 <- numeric(0); t1 <- numeric(0); lo <- numeric(0); hi <- numeric(0); rm <- numeric(0); trk <- character(0)
sigs <- c(list(Original = x), stats::setNames(lapply(seq_len(K), function(k) r$tracks[k, ]), labels))
for (label in names(sigs)) {
  e <- cs_audio_envelope(sigs[[label]], SR, 600)
  t0 <- c(t0, e$start); t1 <- c(t1, e$end); lo <- c(lo, e$min); hi <- c(hi, e$max); rm <- c(rm, e$rms); trk <- c(trk, rep(label, length(e$min)))
}
charts[[3]] <- cs_chart("tracks", "waveform", paste0("Original and separated tracks: ", first$name), list(
  time = cs_col("Time (s)", t0, "numeric"), end = cs_col("End (s)", t1, "numeric"),
  min = cs_col("Min", lo, "numeric"), max = cs_col("Max", hi, "numeric"), rms = cs_col("RMS", rm, "numeric"),
  track = cs_col("Track", trk, "categorical", c("Original", labels))
))
assumptions <- list(
  list(key = "decoded", label = "Files decode", status = if (length(bad)) "warn" else "pass",
       detail = if (length(bad)) sprintf("%d files could not be read and were skipped.", length(bad)) else "Every file processed was decoded."),
  list(key = "different_spectra", label = "Sounds differ in spectrum", status = "info",
       detail = sprintf("The NMF model leaves %.1f%% of the spectrogram unexplained on average; listen to the tracks to judge the split.", 100 * values$rel_error_mean)),
  list(key = "component_order", label = "Components are unnamed", status = "info", detail = "Components are ordered by their total activation, loudest first.")
)
cs_publish(list(
  title = "Separate sounds with NMF",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(files),
  summary = sprintf("%d files split into %d components each; mean NMF relative error %.3f.", length(files), K, values$rel_error_mean),
  statistics = list(
    list(key = "n_separated", label = "Files separated", value = length(files)),
    list(key = "rel_error_mean", label = "Mean NMF relative error", value = values$rel_error_mean),
    list(key = "sum_error_max", label = "Largest gap, tracks vs original", value = values$sum_error_max)
  ),
  tables = tables,
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "components", path = art_path, format = "parquet"), list(key = "audio_tracks", path = TRACKS, format = "folder"))
))

Sources

  • Smaragdis P, Brown JC (2003). Non-negative matrix factorization for polyphonic music transcription. IEEE WASPAA 2003, 177–180.
  • Virtanen T (2007). Monaural sound source separation by nonnegative matrix factorization with temporal continuity and sparseness criteria. IEEE TASLP 15(3):1066–1074.
  • Lee DD, Seung HS (2001). Algorithms for non-negative matrix factorization. NIPS 13.

From the CodeSplash method registry · audio.separate_nmf v1.0.0.