Skip to content

CDiscover · discover.robust_pca

Robust PCA (cell outliers)

Which single cells don't fit the main pattern of the table?

Splits a numeric table into a low-rank part (the shared pattern) plus a sparse part (a few cells that break it), by principal component pursuit: minimize the nuclear norm of the low-rank part plus λ times the absolute size of the sparse part. Solved by Candès and colleagues' alternating directions method run to both primal and dual tolerance, identical in both engines. Cells whose sparse part is beyond a threshold are flagged with their value and the value the pattern expects; the low-rank part gives a map of the rows. It flags cells, not whole rows.

Verified in Python and R Python and R agree to 6 decimals Also called robust PCA, RPCA, principal component pursuit…

A real result

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

Robust PCA (cell outliers)Recorded · Python and R agreeRecorded 2026-11-21 · 38 values compared
R

Robust PCA split the data into a rank-3 part and a sparse part; 15 of 960 cells (1.6%) are flagged.

Low-rank part: rank
3
Flagged cells
15
Rows with a flagged cell
13

Plots

Low-rank part: variation by componentHow many components carry most of the variance?
View data
ComponentCumulativeShare of the low-rank part
10.64090.6409
20.99900.3581
310.0010
Flagged cells by variableHow often does each category occur?
View data
Variable
m7
m5
m6
m5
m3
m8
m1
m7
m4
m7
m5
m2
m2
m4
m7
Biplot of the low-rank part (LC1 × LC2)How do rows spread on the main components, and which variables drive each direction?

Loading arrows are rescaled to the score range.

View data
KindLabelLC1LC2
point−0.7602−1.207
point−1.268−1.359
point−1.2211.296
point0.41320.6085
point−0.71910.1055
point0.07303.376
point1.419−1.365
point−1.0141.045
point−2.6970.5859
point−1.438−0.1922
point−0.37920.0315
point2.4990.4489
point2.816−1.192
point0.67841.071
point−3.345−1.156
point0.72331.959
point3.072−1.039
point0.22221.615
point0.57830.4367
point4.752−1.475
point0.85473.544
point1.7810.8524
point0.9886−0.5187
point0.3578−0.6322
point−0.1366−0.1460
point−0.56902.226
point−3.6802.066
point3.102−2.976
point−1.6201.076
point−0.9975−0.0467
point3.4303.129
point−1.301−0.4393
point1.566−1.441
point2.494−0.5314
point−1.282−1.388
point−0.0822−0.9451
point−0.7235−0.5301
point0.3745−0.2345
point3.858−2.766
point2.440−1.008
point1.806−1.423
point0.29460.7111
point0.1773−2.442
point−1.038−2.088
point−4.860−0.6180
point−0.1745−0.4724
point−2.805−2.993
point0.19341.160
point−1.2922.082
point2.6650.6096
point−0.93581.994
point−2.314−1.440
point0.8071−1.222
point−4.393−0.7417
point1.709−2.261
point1.1551.419
point−0.19522.301
point3.9661.389
point−1.903−0.8208
point2.0570.3706

First 60 of 128 rows.

Flagged cells (sparse part beyond 2 scaled units)

RowVariableValueLow-rank fitSparse part
75m47.5400.72696.813
111m46.8320.67366.158
103m26.827−0.75717.584
99m27.5550.02387.531
19m57.9740.54217.432
19m65.648−0.49706.145
98m5−7.087−0.1626−6.925
31m58.9972.2656.732
77m78.6750.58768.087
42m38.7070.19398.513
72m1−6.3940.0434−6.438
9m7−7.063−0.1119−6.951
72m7−7.084−0.5234−6.561
115m75.609−0.54666.155
51m8−11.312−2.556−8.756

Flagged cells by variable

VariableFlagged cellsShare of rowsCenterScale
m110.8%0.24711.345
m221.7%0.08020.8986
m310.8%0.16451.752
m421.7%−0.01510.4654
m532.5%0.23881.199
m610.8%−0.23091.011
m743.3%−0.06891.617
m810.8%−0.59643.408

Loadings of the low-rank part

VariableLC1LC2
m10.44910.1197
m2−0.28520.4072
m30.4501−0.2007
m4−0.18940.5481
m50.45930.0342
m6−0.4223−0.1572
m7−0.1095−0.5254
m8−0.2779−0.4210
  • Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged.
Python

Robust PCA split the data into a rank-3 part and a sparse part; 15 of 960 cells (1.6%) are flagged.

Low-rank part: rank
3
Flagged cells
15
Rows with a flagged cell
13

To keep this page light, the plots are shown once, under the R tab.

Flagged cells (sparse part beyond 2 scaled units)

RowVariableValueLow-rank fitSparse part
75m47.5400.72696.813
111m46.8320.67366.158
103m26.827−0.75717.584
99m27.5550.02387.531
19m57.9740.54217.432
19m65.648−0.49706.145
98m5−7.087−0.1626−6.925
31m58.9972.2656.732
77m78.6750.58768.087
42m38.7070.19398.513
72m1−6.3940.0434−6.438
9m7−7.063−0.1119−6.951
72m7−7.084−0.5234−6.561
115m75.609−0.54666.155
51m8−11.312−2.556−8.756

Flagged cells by variable

VariableFlagged cellsShare of rowsCenterScale
m110.8%0.24711.345
m221.7%0.08020.8986
m310.8%0.16451.752
m421.7%−0.01510.4654
m532.5%0.23881.199
m610.8%−0.23091.011
m743.3%−0.06891.617
m810.8%−0.59643.408

Loadings of the low-rank part

VariableLC1LC2
m10.44910.1197
m2−0.28520.4072
m30.4501−0.2007
m4−0.18940.5481
m50.45930.0342
m6−0.4223−0.1572
m7−0.1095−0.5254
m8−0.2779−0.4210
  • Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Planted cellsrep1_lowrank · features: m1, m2, m3, m4, m5, m6, m7, m8
  • Usarrests standardml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Iris median penaltyml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins imputeml_penguins · features: bill_len, bill_dep, flipper_len, body_mass
  • Degenerate all narep1_lowrank · features: m1, m2, m3, m4, m5, m6, m7, m8
  • Degenerate empty after filterrep1_lowrank · features: m1, m2, m3, m4, m5, m6, m7, m8
  • Degenerate infrep1_lowrank · features: m1, m2, m3, m4, m5, m6, m7, m8
  • Degenerate n1rep1_lowrank · features: m1, m2, m3, m4, m5, m6, m7, m8

In the guides

Where it sits in the decision guides

  • Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Variablesnumeric · 2–500 columns
Numeric columns of the table to split into a shared pattern and odd cells.
Color points bycategorical / boolean · 0–1 column
Optional: shown on the biplot of the low-rank part only.

Choices you make

preprocess

Scale variablesdefault robust

Put columns on one scale first, so the flag threshold means the same in every column.

  • Median and MAD(default) — Centers on the median and divides by 1.4826 × MAD (the SD when the MAD is 0); odd cells don't distort the scale.
  • Mean and SD — Centers on the mean and divides by the SD; odd cells inflate the SD a little.
  • Median only — Centers on the median and keeps the units; use when every column shares one unit.
Missing valuesdefault listwise

Leave out rows with a missing value, or replace it with the column median.

  • Leave out rows with a missing value(default) — Leaves out rows with any missing value; the clean choice when few are missing.
  • Replace with the column median — Replaces gaps with the column median before the split; filled cells are never flagged as odd.

model

Sparsity penalty λdefault —

Larger λ keeps more in the low-rank part and flags fewer cells; empty uses the standard 1/√max(rows, columns).

Flag cells beyonddefault 2

A cell is flagged when its sparse part is larger than this, in scaled units (2 ≈ two robust SDs of its column).

Map dimensionsdefault 2

Principal components of the low-rank part kept for the map and the export.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_variables
How many independent units the analysis used; it sets precision and power.
rank
Splits a table into a low-rank pattern plus a sparse part holding the few cells that break it.
lambda
Splits a table into a low-rank pattern plus a sparse part holding the few cells that break it.
n_flagged
A cell whose sparse part is larger than the flag threshold, in scaled units: the pattern can't explain its value.
flagged_share
A cell whose sparse part is larger than the flag threshold, in scaled units: the pattern can't explain its value.
rows_flagged
A cell whose sparse part is larger than the flag threshold, in scaled units: the pattern can't explain its value.
sparse_share
Share of the scaled table's sum of squares that falls in the sparse part rather than the low-rank pattern.
n_components
Share of the low-rank part's variation held by each of its principal components.

Per group, level or term: flagged[<variable>], lowrank_prop[<k>], loading[<k>:<variable>], score_check[<k>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy; R uses codesplashr.

Default traps between the two languages

  • Both engines run the same ADMM twin (Candès et al. 2011, Algorithm 1: μ₀ = n·p / (4‖M‖₁), μ doubled or halved when the primal and dual residuals are more than 10 apart; stop when both are below 1e-9 of ‖M‖). Singular value thresholding is unique for distinct singular values, so LAPACK sign choices don't matter. An inexact ALM with fast-growing μ (Lin, Chen & Ma 2010) stops short of the optimum on noisy tables, so it isn't used.
Python

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

# Robust PCA (cell outliers)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_pca 1.0.0 · spec 63c7f51a131dcaad
# Dataset: rep1_lowrank (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.ml import embed as csembed
from codesplash.ml import rep_linear as rl

def chart_rows(n, cap=2000):
    return np.arange(n) if n <= cap else np.unique(np.linspace(0, n - 1, cap).round().astype(int))

# %% Data
FEATURES = ["m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8"]
LABEL = None
df = pd.read_parquet("tests/parity/fixtures/rep1_lowrank.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
cs.check_finite_columns(df, FEATURES)
rows = csembed.complete_rows(df, FEATURES)
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 3, "Robust PCA")
X = csembed.numeric_matrix(df, FEATURES, rows)

# %% Principal component pursuit (ADMM to primal and dual tolerance): low-rank part L + sparse part S = scaled data
Zs, center, scale = rl.robust_center_scale(X, "robust")
if not np.any(Zs != 0):
    cs.cs_error("CS_E_CONSTANT", column=FEATURES[0])
n, p = Zs.shape
LAM = None
lam = 1.0 / np.sqrt(max(n, p)) if LAM is None else float(LAM)
L, S, rank, iterations, converged = rl.robust_pca(Zs, lam)
if not converged:
    warnings.append("Principal component pursuit stopped after 10,000 iterations before reaching its tolerance; treat the split as approximate.")
FLAG = float(2)
flagged = np.abs(S) > FLAG
n_flagged = int(np.sum(flagged))
rows_flagged = int(np.sum(flagged.any(axis=1)))
total_ss = float(np.sum(Zs * Zs))
sparse_share = float(np.sum(S * S)) / total_ss

# low-rank part: its own principal axes give the map
U, sv, Vt = np.linalg.svd(L, full_matrices=False)
k = min(int(2), rank)
signs = csembed.canonical_signs(Vt[:k].T) if k else np.ones(0)
loadings = Vt[:k].T * signs
scores = U[:, :k] * sv[:k] * signs
lr_ss = float(np.sum(sv[:rank] ** 2))
lr_prop = sv[:rank] ** 2 / lr_ss if rank else np.zeros(0)
if rank == 0:
    warnings.append("The low-rank part is empty: λ is so small that the sparse part takes everything. Raise λ.")

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-93840/discover.robust_pca/planted_cells/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(k):
    emb[f"dim_{j + 1}"] = scores[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
fi, fj = np.nonzero(flagged)
size = np.abs(S[fi, fj])
order = np.lexsort((fj, fi, -size))  # largest sparse part first; ties by row, then column
fi, fj = fi[order], fj[order]
cells = pd.DataFrame({
    "row": rows[fi].astype(np.int64),
    "column": [FEATURES[j] for j in fj],
    "value": X[fi, fj],
    "fitted": L[fi, fj] * scale[fj] + center[fj],
    "sparse": S[fi, fj] * scale[fj],
})
cells.to_parquet(os.path.join(out, "cells.parquet"), index=False)

# %% Result
values = {
    "n": n,
    "n_variables": p,
    "rank": int(rank),
    "lambda": lam,
    "n_flagged": n_flagged,
    "flagged_share": n_flagged / (n * p),
    "rows_flagged": rows_flagged,
    "sparse_share": sparse_share,
    "n_components": k,
}
per_var = flagged.sum(axis=0)
for i, f in enumerate(FEATURES):
    values[f"flagged[{f}]"] = int(per_var[i])
for j in range(rank):
    values[f"lowrank_prop[{j + 1}]"] = float(lr_prop[j])
for j in range(k):
    values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
    for i, f in enumerate(FEATURES):
        values[f"loading[{j + 1}:{f}]"] = float(loadings[i, j])
top = min(len(cells), 50)
tables = [
    {
        "key": "cells",
        "title": f"Flagged cells (sparse part beyond {FLAG:g} scaled units){'' if top == len(cells) else f', largest {top} of {len(cells)}'}",
        "columns": [
            {"key": "row", "label": "Row", "type": "integer"},
            {"key": "variable", "label": "Variable"},
            {"key": "value", "label": "Value", "type": "number"},
            {"key": "fitted", "label": "Low-rank fit", "type": "number"},
            {"key": "sparse", "label": "Sparse part", "type": "number"},
        ],
        "rows": [
            {"row": int(cells["row"].iloc[i]) + 1, "variable": cells["column"].iloc[i], "value": float(cells["value"].iloc[i]),
             "fitted": float(cells["fitted"].iloc[i]), "sparse": float(cells["sparse"].iloc[i])}
            for i in range(top)
        ],
    },
    {
        "key": "variables",
        "title": "Flagged cells by variable",
        "columns": [
            {"key": "variable", "label": "Variable"},
            {"key": "flagged", "label": "Flagged cells", "type": "integer"},
            {"key": "share", "label": "Share of rows", "type": "percent"},
            {"key": "center", "label": "Center", "type": "number"},
            {"key": "scale", "label": "Scale", "type": "number"},
        ],
        "rows": [{"variable": f, "flagged": int(per_var[i]), "share": float(per_var[i]) / n, "center": float(center[i]), "scale": float(scale[i])} for i, f in enumerate(FEATURES)],
    },
]
if k:
    tables.append({
        "key": "loadings",
        "title": "Loadings of the low-rank part",
        "columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"lc{j + 1}", "label": f"LC{j + 1}", "type": "number"} for j in range(k)],
        "rows": [dict({"variable": f}, **{f"lc{j + 1}": loadings[i, j] for j in range(k)}) for i, f in enumerate(FEATURES)],
    })
charts = []
if rank:
    charts.append(cs.chart(
        "scree",
        "scree-plot",
        "Low-rank part: variation by component",
        {
            "component": cs.col("Component", list(range(1, rank + 1)), "numeric"),
            "variance": cs.col("Share of the low-rank part", lr_prop, "numeric"),
            "cumulative": cs.col("Cumulative", np.cumsum(lr_prop), "numeric"),
        },
    ))
if n_flagged:
    charts.append(cs.chart(
        "flagged",
        "bar",
        "Flagged cells by variable",
        {"x": cs.col("Variable", [FEATURES[j] for j in np.nonzero(flagged)[1]], "categorical", levels=FEATURES)},
    ))
if k >= 2:
    pick = chart_rows(n)
    lab = ["" if LABEL is None else str(v) for v in df.iloc[rows[pick]][LABEL]] if LABEL else [""] * len(pick)
    reach = np.max(np.abs(scores[pick, :2])) / max(np.max(np.abs(loadings[:, :2])), 1e-12) * 0.8
    charts.append(cs.chart(
        "biplot",
        "biplot",
        "Biplot of the low-rank part (LC1 × LC2)",
        {
            "x": cs.col("LC1", np.concatenate([scores[pick, 0], loadings[:, 0] * reach]), "numeric"),
            "y": cs.col("LC2", np.concatenate([scores[pick, 1], loadings[:, 1] * reach]), "numeric"),
            "kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * p, "categorical"),
            "label": cs.col(LABEL or "Label", lab + FEATURES, "categorical"),
        },
        note="Loading arrows are rescaled to the score range.",
    ))
cs.publish(
    {
        "title": "Robust PCA (cell outliers)",
        "engine": cs.engine_info("numpy", "pandas"),
        "n": n,
        "summary": f"Robust PCA split the data into a rank-{rank} part and a sparse part; {n_flagged} of {n * p} cells ({n_flagged / (n * p):.1%}) are flagged.",
        "statistics": [
            {"key": "rank", "label": "Low-rank part: rank", "value": int(rank), "format": "integer"},
            {"key": "n_flagged", "label": "Flagged cells", "value": n_flagged, "format": "integer"},
            {"key": "rows_flagged", "label": "Rows with a flagged cell", "value": rows_flagged, "format": "integer"},
        ],
        "notes": ["Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged."],
        "tables": tables,
        "charts": charts,
        "values": values,
        "warnings": warnings,
        "artifacts": [
            {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
            {"key": "cells", "path": os.path.join(out, "cells.parquet"), "format": "parquet"},
        ],
    }
)
R

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

# Robust PCA (cell outliers)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_pca 1.0.0 · spec 63c7f51a131dcaad
# Dataset: rep1_lowrank (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))

# %% Data
FEATURES <- c("m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8")
LABEL <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep1_lowrank.parquet", col_select = unique(c(FEATURES, LABEL))))
n_input <- nrow(df)
warnings <- list()
cs_check_finite_columns(df, FEATURES)
rows <- cs_ml_complete_rows(df, FEATURES)
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
}
cs_check_rows(length(rows), 3, "Robust PCA")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)

# %% Principal component pursuit (ADMM to primal and dual tolerance): low-rank part L + sparse part S = scaled data
rc <- cs_rep_robust_center_scale(X, "robust")
Zs <- rc$Z; center <- rc$center; scale <- rc$scale
if (!any(Zs != 0)) cs_error("CS_E_CONSTANT", column = FEATURES[1])
n <- nrow(Zs); p <- ncol(Zs)
LAM <- NULL
lam <- if (is.null(LAM)) 1 / sqrt(max(n, p)) else as.numeric(LAM)
fit <- cs_rep_robust_pca(Zs, lam)
L <- fit$L; S <- fit$S; rank <- fit$rank
if (!fit$converged) warnings <- c(warnings, "Principal component pursuit stopped after 10,000 iterations before reaching its tolerance; treat the split as approximate.")
FLAG <- as.numeric(2)
flagged <- abs(S) > FLAG
n_flagged <- sum(flagged)
rows_flagged <- sum(rowSums(flagged) > 0)
total_ss <- sum(Zs * Zs)
sparse_share <- sum(S * S) / total_ss

# low-rank part: its own principal axes give the map
sv <- svd(L)
k <- min(as.integer(2), rank)
if (k > 0) {
  signs <- cs_ml_canonical_signs(sv$v[, seq_len(k), drop = FALSE])
  loadings <- sweep(sv$v[, seq_len(k), drop = FALSE], 2, signs, "*")
  scores <- sweep(sv$u[, seq_len(k), drop = FALSE], 2, sv$d[seq_len(k)] * signs, "*")
} else {
  loadings <- matrix(0, p, 0); scores <- matrix(0, n, 0)
}
lr_ss <- sum(sv$d[seq_len(rank)]^2)
lr_prop <- if (rank > 0) sv$d[seq_len(rank)]^2 / lr_ss else numeric(0)
if (rank == 0) warnings <- c(warnings, "The low-rank part is empty: λ is so small that the sparse part takes everything. Raise λ.")

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-93840/discover.robust_pca/planted_cells/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(k)) emb[[paste0("dim_", j)]] <- scores[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
w <- which(flagged, arr.ind = TRUE)
fi <- unname(w[, 1]); fj <- unname(w[, 2])
ord <- order(-abs(S[cbind(fi, fj)]), fi, fj)  # largest sparse part first; ties by row, then column
fi <- fi[ord]; fj <- fj[ord]
cells <- data.frame(row = as.integer(rows[fi]), column = FEATURES[fj], value = X[cbind(fi, fj)],
                    fitted = L[cbind(fi, fj)] * scale[fj] + center[fj], sparse = S[cbind(fi, fj)] * scale[fj],
                    stringsAsFactors = FALSE)
nanoparquet::write_parquet(cells, file.path(out, "cells.parquet"))

# %% Result
values <- list(n = n, n_variables = p, rank = rank, lambda = lam, n_flagged = n_flagged,
               flagged_share = n_flagged / (n * p), rows_flagged = rows_flagged, sparse_share = sparse_share,
               n_components = k)
per_var <- colSums(flagged)
for (i in seq_along(FEATURES)) values[[sprintf("flagged[%s]", FEATURES[i])]] <- per_var[i]
for (j in seq_len(rank)) values[[sprintf("lowrank_prop[%d]", j)]] <- lr_prop[j]
for (j in seq_len(k)) {
  values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
  for (i in seq_along(FEATURES)) values[[sprintf("loading[%d:%s]", j, FEATURES[i])]] <- loadings[i, j]
}
top <- min(nrow(cells), 50L)
tables <- list(
  list(key = "cells",
       title = sprintf("Flagged cells (sparse part beyond %s scaled units)%s", format(FLAG), if (top == nrow(cells)) "" else sprintf(", largest %d of %d", top, nrow(cells))),
       columns = list(list(key = "row", label = "Row", type = "integer"),
                      list(key = "variable", label = "Variable"),
                      list(key = "value", label = "Value", type = "number"),
                      list(key = "fitted", label = "Low-rank fit", type = "number"),
                      list(key = "sparse", label = "Sparse part", type = "number")),
       rows = lapply(seq_len(top), function(i) list(row = cells$row[i] + 1L, variable = cells$column[i], value = cells$value[i],
                                                   fitted = cells$fitted[i], sparse = cells$sparse[i]))),
  list(key = "variables", title = "Flagged cells by variable",
       columns = list(list(key = "variable", label = "Variable"),
                      list(key = "flagged", label = "Flagged cells", type = "integer"),
                      list(key = "share", label = "Share of rows", type = "percent"),
                      list(key = "center", label = "Center", type = "number"),
                      list(key = "scale", label = "Scale", type = "number")),
       rows = lapply(seq_along(FEATURES), function(i) list(variable = FEATURES[i], flagged = per_var[[i]], share = per_var[[i]] / n,
                                                          center = center[i], scale = scale[i])))
)
if (k > 0) {
  tables[[3]] <- list(key = "loadings", title = "Loadings of the low-rank part",
                      columns = c(list(list(key = "variable", label = "Variable")),
                                  lapply(seq_len(k), function(j) list(key = paste0("lc", j), label = paste0("LC", j), type = "number"))),
                      rows = lapply(seq_along(FEATURES), function(i) {
                        r <- list(variable = FEATURES[i])
                        for (j in seq_len(k)) r[[paste0("lc", j)]] <- loadings[i, j]
                        r
                      }))
}
charts <- list()
if (rank > 0) {
  charts[[length(charts) + 1L]] <- cs_chart("scree", "scree-plot", "Low-rank part: variation by component", list(
    component = cs_col("Component", seq_len(rank), "numeric"),
    variance = cs_col("Share of the low-rank part", lr_prop, "numeric"),
    cumulative = cs_col("Cumulative", cumsum(lr_prop), "numeric")
  ))
}
if (n_flagged > 0) {
  wr <- which(flagged, arr.ind = TRUE)
  wr <- wr[order(wr[, 1], wr[, 2]), , drop = FALSE]  # row by row, like numpy's nonzero
  charts[[length(charts) + 1L]] <- cs_chart("flagged", "bar", "Flagged cells by variable", list(
    x = cs_col("Variable", FEATURES[wr[, 2]], "categorical", levels = FEATURES)
  ))
}
if (k >= 2) {
  pick <- chart_rows(n)
  lab <- if (!is.null(LABEL)) as.character(df[[LABEL]][rows[pick] + 1L]) else rep("", length(pick))
  lab[is.na(lab)] <- ""
  reach <- max(abs(scores[pick, 1:2])) / max(max(abs(loadings[, 1:2])), 1e-12) * 0.8
  charts[[length(charts) + 1L]] <- cs_chart("biplot", "biplot", "Biplot of the low-rank part (LC1 × LC2)", list(
    x = cs_col("LC1", c(scores[pick, 1], loadings[, 1] * reach), "numeric"),
    y = cs_col("LC2", c(scores[pick, 2], loadings[, 2] * reach), "numeric"),
    kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", p)), "categorical"),
    label = cs_col(if (is.null(LABEL)) "Label" else LABEL, c(lab, FEATURES), "categorical")
  ), note = "Loading arrows are rescaled to the score range.")
}
cs_publish(list(
  title = "Robust PCA (cell outliers)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = n,
  summary = sprintf("Robust PCA split the data into a rank-%d part and a sparse part; %d of %d cells (%.1f%%) are flagged.",
                    rank, n_flagged, n * p, 100 * n_flagged / (n * p)),
  statistics = list(list(key = "rank", label = "Low-rank part: rank", value = rank, format = "integer"),
                    list(key = "n_flagged", label = "Flagged cells", value = n_flagged, format = "integer"),
                    list(key = "rows_flagged", label = "Rows with a flagged cell", value = rows_flagged, format = "integer")),
  notes = list("Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged."),
  tables = tables,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
                   list(key = "cells", path = file.path(out, "cells.parquet"), format = "parquet"))
))

Sources

  • Candès EJ, Li X, Ma Y, Wright J (2011). Robust principal component analysis? J ACM 58(3):11.
  • Boyd S, Parikh N, Chu E, Peleato B, Eckstein J (2011). Distributed optimization and statistical learning via the alternating direction method of multipliers. Found Trends Mach Learn 3(1):1–122.

From the CodeSplash method registry · discover.robust_pca v1.0.0.