Skip to content

CDiscover · discover.bicluster

Biclustering (rows × columns)

Which groups of rows share a pattern over a group of columns, when no grouping fits all columns at once?

Finds blocks of the table: a set of rows that behave alike on a set of columns, while differing elsewhere. Cheng–Church looks for coherent submatrices one at a time (each row and column then shifts by its own amount, so the mean squared residue is small) and may let blocks overlap; spectral co-clustering puts every row and column in one of k blocks of large values; spectral biclustering finds a checkerboard of row groups × column groups. Rows can belong to several biclusters (Cheng–Church), so saving writes the first bicluster of each row plus one flag per bicluster.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called biclustering, co-clustering, Cheng–Church…

A real result

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

Biclustering (rows × columns)Recorded · Python and R agreeRecorded 2026-11-21 · 21 values compared
R

3 biclusters in 60 rows × 12 columns covering 37% of the rows; mean squared residue 0.00923.

Biclusters
3
Rows covered
36.7%
Mean squared residue
0.0092

Plots

Biclusters in the tableWhich subsets of rows share a pattern on a subset of columns?
View data
BiclusterColumnRowValue (standardized)
-1x1r011.166
-1x2r01−0.1202
-1x3r010.2679
-1x4r010.6042
-1x5r01−0.9826
-1x6r010.0277
-1x7r010.4645
-1x8r01−0.0677
-1x9r012.850
-1x10r010.2368
-1x11r01−0.4948
-1x12r01−0.1775
-1x1r020.0436
-1x2r02−1.401
-1x3r02−0.6471
-1x4r02−0.3771
-1x5r020.8307
-1x6r02−0.0856
-1x7r020.6873
-1x8r021.283
-1x9r020.9333
-1x10r02−1.728
-1x11r02−0.5257
-1x12r02−1.081
2x1r030.8580
2x2r03−0.5201
2x3r030.0291
2x4r030.3487
2x5r030.0055
-1x6r03−0.5167
-1x7r03−1.908
-1x8r03−0.4464
-1x9r031.701
-1x10r030.1065
-1x11r03−0.3729
-1x12r031.107
2x1r041.781
2x2r040.4723
2x3r040.8519
2x4r041.131
2x5r041.343
-1x6r041.051
-1x7r040.7797
-1x8r04−0.9918
-1x9r040.0180
-1x10r041.769
-1x11r04−0.1224
-1x12r040.1363
-1x1r051.355
-1x2r05−0.0224
-1x3r050.4606
-1x4r050.7913
-1x5r051.000
-1x6r05−1.513
-1x7r05−1.417
-1x8r05−1.134
-1x9r050.6560
-1x10r052.149
-1x11r050.8723
-1x12r05−0.1323

First 60 of 720 rows.

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1104x7, x8, x9, x100.0027−0.3418
285x1, x2, x3, x4, x50.01120.0863
344x4, x6, x9, x110.01380.1289
Python

3 biclusters in 60 rows × 12 columns covering 37% of the rows; mean squared residue 0.00923.

Biclusters
3
Rows covered
36.7%
Mean squared residue
0.0092

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

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1104x7, x8, x9, x100.0027−0.3418
285x1, x2, x3, x4, x50.01120.0863
344x4, x6, x9, x110.01380.1289

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 cheng churchclu4_bicluster · features: x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12 · id: id
  • Planted cheng church rawclu4_bicluster · features: x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12
  • Shifted cheng church rawclu4_bicluster · features: s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12
  • Blocks coclusterclu4_cocluster · features: w1, w2, w3, w4, w5, w6, w7, w8, w9 · id: id
  • Checker bistochasticclu4_checker · features: v1, v2, v3, v4, v5, v6, v7, v8
  • Checker logclu4_checker · features: v1, v2, v3, v4, v5, v6, v7, v8
  • Cocluster needs nonnegativeclu4_bicluster · features: x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12
  • Degenerate constantclu4_bicluster · features: x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12 · id: id

In the guides

Where it sits in the decision guides

  • Biclustering (row and column groups together) · DS & ML Decision Guide · Discover — find structure without labels
  • Discover: cluster quality (silhouette, ARI); coherence (topics); stability and interpretability · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Columnsnumeric · 2–500 columns
The table's numeric columns; biclusters pick rows and some of these columns (rows with a missing value are left out).
Row labelscategorical / numeric · 0–1 column
Optional: names the rows in the heatmap.

Choices you make

model

Algorithmdefault cheng_church

Which kind of block to look for.

  • Cheng–Church (coherent blocks)(default) — Rows that move in parallel over some columns (additive pattern); blocks can overlap; any numbers.
  • Spectral co-clustering — Every row and column in one of k blocks of large values (Dhillon 2001); non-negative data such as counts.
  • Spectral biclustering (checkerboard) — Row groups × column groups with their own levels (Kluger et al. 2003); positive data.
Biclustersdefault 3

Cheng–Church: the most blocks to look for (it can stop earlier). Co-clustering: the number of blocks.

Residue thresholddefault 0.02

δ as a share of the whole table's mean squared residue: smaller asks for tighter, smaller blocks; raise it for larger, looser ones.

Scale columnsdefault standard

Whether columns are put on one scale before looking for coherent blocks.

  • Standardize(default) — Each column to mean 0 and SD 1 (population SD), so no column dominates the residue.
  • Keep as they are — For columns already in one unit.
Row groupsdefault 3

Row groups in the checkerboard.

Column groupsdefault 3

Column groups in the checkerboard.

Normalizationdefault bistochastic

How row and column effects are removed before the singular vectors are taken.

  • Bistochastic(default) — Repeated row and column scaling until every row and column sum is alike (scikit-learn's default).
  • Scale once — One row and column scaling.
  • Log interaction — Logs with row and column means removed; every value must be positive.

Advanced

Multiple-deletion factordefault 1.2

Along a dimension with 100 or more members, drop every row or column whose residue exceeds α × the current mean (Cheng & Church used 1.2).

Singular vectorsdefault 6

Singular vectors computed before the best ones are chosen.

Vectors keptdefault 3

Singular vectors that look most piecewise-constant; rows and columns are clustered on these.

k-means startsdefault 10

k-means++ starts in the spectral methods; the best is kept.

What it reports

n
Rows and columns of the table searched for biclusters, after rows with a missing value are left out.
p
Rows and columns of the table searched for biclusters, after rows with a missing value are left out.
k
A set of rows that behave alike on a set of columns — a block of the table — while differing on the other columns.
rows_covered
Share of rows (or of cells) that fall in at least one bicluster; the rest belong to no block.
cells_covered
Share of rows (or of cells) that fall in at least one bicluster; the rest belong to no block.
msr_mean
Average squared misfit of a block to rows and columns that each shift by their own amount; 0 = a perfectly additive block.
delta
Cheng–Church keeps shrinking a block until its mean squared residue is at most δ; here δ = a share of the whole table's residue.
membership_check
A one-number summary of which rows and columns each bicluster holds, used to compare runs and engines.
iterations
Rounds of row and column scaling before the checkerboard's singular vectors; bistochastic repeats until sums stop changing.

Per group, level or term: n_rows[<bicluster>], n_cols[<bicluster>], msr[<bicluster>], mean[<bicluster>]

Python and R

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

Default traps between the two languages

  • Both engines run the same written-out Cheng–Church steps, singular value decompositions and Lloyd k-means from k-means++ starts on the shared stream; the masking values for Cheng–Church come from the same stream. Singular vectors may come back with opposite signs, which k-means does not see. scikit-learn's spectral methods start k-means from their own random numbers, so their block numbering (not the blocks) can differ.
Python

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

# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec 31b304c79ce1b41c
# Dataset: clu4_bicluster (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import cluster_bicluster as cb
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng

# %% Data
FEATURES = ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12"]
ROW_ID = "id"  # row labels for the heatmap
SEED = 42
ALGORITHM = "cheng_church"
df = pd.read_parquet("tests/parity/fixtures/clu4_bicluster.parquet", columns=list(dict.fromkeys(FEATURES + ([ROW_ID] if ROW_ID else []))))
n_input = len(df)
cs.check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, FEATURES)
warnings = []
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), 4, "Biclustering")
X = csembed.numeric_matrix(df, FEATURES, rows)
n, p = X.shape
if np.all(np.ptp(X, axis=0) == 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
out = csml.out_dir("target/academy-parity/run-85263/discover.bicluster/planted_cheng_church/out-python")
rng = Rng(SEED)
delta = None
iterations = None


def need_nonnegative(strict: bool) -> None:
    bad = (X <= 0) if strict else (X < 0)
    for j, f in enumerate(FEATURES):
        if np.any(bad[:, j]):
            cs.cs_error("CS_E_INVALID_VALUES", column=f, requirement="positive" if strict else "zero or more", count=int(np.sum(bad[:, j])))
    if np.any(X.sum(axis=1) <= 0):
        cs.cs_error("CS_E_INVALID_VALUES", column="Row totals", requirement="positive", count=int(np.sum(X.sum(axis=1) <= 0)))
    if np.any(X.sum(axis=0) <= 0):
        cs.cs_error("CS_E_INVALID_VALUES", column="Column totals", requirement="positive", count=int(np.sum(X.sum(axis=0) <= 0)))


# %% Biclusters
if ALGORITHM == "cheng_church":
    A = X.copy()
    if "standard" == "standard":
        flat = np.ptp(A, axis=0) == 0
        sd = A.std(axis=0, ddof=0)
        sd[flat] = 1.0
        A = (A - A.mean(axis=0)) / sd
        A[:, flat] = 0.0  # constant columns exactly 0 in both engines
    h_full = cb.msr(A, np.ones(n, dtype=bool), np.ones(p, dtype=bool))
    if h_full <= 0:
        cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
    delta = float(0.02) * h_full
    biclusters = cb.cheng_church(A, 3, delta, float(1.2), rng)
    if not biclusters:
        warnings.append("No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
elif ALGORITHM == "cocluster":
    need_nonnegative(strict=False)
    K = 3
    n_sv = 1 + int(np.ceil(np.log2(K))) if K > 1 else 1
    if K < 2 or n_sv > min(n, p) or K > n:
        cs.cs_error("CS_E_INVALID_OPTION", option="Biclusters", allowed=f"between 2 and {min(n, 2 ** (min(n, p) - 1))} for this table", value=K)
    A = X
    rl, cl = cb.cocluster(A, K, rng, 10)
    biclusters = [(rl == b, cl == b) for b in range(K)]
else:
    METHOD = "bistochastic"
    need_nonnegative(strict=(METHOD == "log"))
    NR, NC = 3, 3
    NCOMP, NBEST = 6, 3
    if NCOMP > min(n, p):
        cs.cs_error("CS_E_INVALID_OPTION", option="Singular vectors", allowed=f"at most {min(n, p)} for this table", value=NCOMP)
    usable = NCOMP - (0 if METHOD == "log" else 1)
    if NBEST > usable:
        cs.cs_error("CS_E_INVALID_OPTION", option="Vectors kept", allowed=f"at most {usable} with {NCOMP} singular vectors", value=NBEST)
    if NR > n or NC > p:
        cs.cs_error("CS_E_INVALID_OPTION", option="Row groups" if NR > n else "Column groups", allowed=f"at most {n if NR > n else p}", value=NR if NR > n else NC)
    A = X
    rl, cl, iterations = cb.checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
    biclusters = [(rl == r, cl == c) for r in range(NR) for c in range(NC)]

# %% Summaries
k = len(biclusters)
summ = cb.summarize(A, biclusters)
values = {
    "n": n, "p": p, "k": k, "delta": delta, "iterations": iterations,
    "membership_check": cb.membership_checksum(biclusters, n, p),
}
covered_rows = np.zeros(n, dtype=bool)
covered_cells = np.zeros((n, p), dtype=bool)
for I, J in biclusters:
    covered_rows |= I
    covered_cells[np.ix_(I, J)] = True
values["rows_covered"] = float(np.mean(covered_rows))
values["cells_covered"] = float(np.mean(covered_cells))
msrs = [s["msr"] for s in summ if s["msr"] == s["msr"]]
values["msr_mean"] = float(np.mean(msrs)) if msrs else None
for b, s in enumerate(summ, start=1):
    values[f"n_rows[{b}]"] = s["n_rows"]
    values[f"n_cols[{b}]"] = s["n_cols"]
    values[f"msr[{b}]"] = s["msr"]
    values[f"mean[{b}]"] = s["mean"]
tables = [{
    "key": "biclusters",
    "title": "Biclusters",
    "columns": [
        {"key": "bicluster", "label": "Bicluster", "type": "integer"},
        {"key": "rows", "label": "Rows", "type": "integer"},
        {"key": "cols", "label": "Columns", "type": "integer"},
        {"key": "columns", "label": "Which columns", "type": "string"},
        {"key": "msr", "label": "Mean squared residue", "type": "number"},
        {"key": "mean", "label": "Mean value", "type": "number"},
    ],
    "rows": [
        {"bicluster": b, "rows": s["n_rows"], "cols": s["n_cols"],
         "columns": ", ".join([FEATURES[j] for j in np.flatnonzero(J)][:12]) + (" …" if int(J.sum()) > 12 else ""),
         "msr": s["msr"], "mean": s["mean"]}
        for b, ((I, J), s) in enumerate(zip(biclusters, summ), start=1)
    ],
}]

# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first = np.full(n, -1, dtype=np.int64)
flags = {}
for b, (I, J) in enumerate(biclusters, start=1):
    first[(first == -1) & I] = b
    flags[f"in_{b}"] = I.copy()
path = csc.write_labels(out, rows, first, **flags)
bpath = os.path.join(out, "biclusters.json")
with open(bpath, "w", encoding="utf-8") as fh:
    json.dump({"k": k, "rows": [[int(rows[i]) for i in np.flatnonzero(I)] for I, _ in biclusters],
               "cols": [[FEATURES[j] for j in np.flatnonzero(J)] for _, J in biclusters]}, fh)

# %% Heatmap
charts = []
if p <= 120 and k > 0:
    show = np.arange(n) if n <= 400 else np.flatnonzero(covered_rows)[csc.even_sample(int(covered_rows.sum()), 400)]
    if ROW_ID:
        names = cc.label_text(df[ROW_ID].iloc[rows].tolist())
        names = np.array(["" if v is None else v for v in names], dtype=object)
        if len(set(names.tolist())) < n:
            names = np.array([f"{v} #{i + 1}" for i, v in enumerate(names)], dtype=object)
    else:
        names = np.array([f"row {int(r) + 1}" for r in rows], dtype=object)
    cell_b = np.full((n, p), -1, dtype=np.int64)
    for b, (I, J) in enumerate(biclusters, start=1):
        sub = np.ix_(I, J)
        blk = cell_b[sub]
        blk[blk == -1] = b
        cell_b[sub] = blk
    rr = [int(i) for i in show for _ in range(p)]
    jj = [j for _ in show for j in range(p)]
    charts.append(cs.chart(
        "heatmap", "bicluster-heatmap", "Biclusters in the table",
        {
            "row": cs.col("Row", [names[i] for i in rr], "categorical", levels=[names[i] for i in show]),
            "column": cs.col("Column", [FEATURES[j] for j in jj], "categorical", levels=FEATURES),
            "value": cs.col("Value (standardized)" if ALGORITHM == "cheng_church" and "standard" == "standard" else "Value",
                            [float(A[i, j]) for i, j in zip(rr, jj)], "numeric"),
            "bicluster": cs.col("Bicluster", [str(cell_b[i, j]) for i, j in zip(rr, jj)], "categorical",
                                levels=[str(b) for b in range(1, k + 1)] + ["-1"]) if k <= 29 else None,
        },
        note=None if len(show) == n else f"{len(show):,} of {n:,} rows shown (rows in a bicluster, evenly sampled).",
    ))

# %% Result
cs.publish({
    "title": "Biclustering (rows × columns)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": (f"{k} bicluster{'s' if k != 1 else ''} in {n:,} rows × {p} columns covering {values['rows_covered'] * 100:.0f}% of the rows"
                + (f"; mean squared residue {values['msr_mean']:.3g}." if values["msr_mean"] is not None else ".")),
    "statistics": [
        {"key": "k", "label": "Biclusters", "value": k, "format": "integer"},
        {"key": "rows_covered", "label": "Rows covered", "value": values["rows_covered"], "format": "percent"},
        {"key": "msr_mean", "label": "Mean squared residue", "value": values["msr_mean"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}, {"key": "biclusters", "path": bpath, "format": "json"}],
    "model": {"kind": "bicluster", "features": FEATURES, "params": {
        "algorithm": "cheng_church",
        "k": 3,
        "delta_share": 0.02,
        "alpha": 1.2,
        "scale": "standard",
        "n_row_clusters": 3,
        "n_col_clusters": 3,
        "normalize": "bistochastic",
        "n_components": 6,
        "n_best": 3,
        "n_init": 10,
    }},
})
R

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

# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec 31b304c79ce1b41c
# Dataset: clu4_bicluster (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12")
ROW_ID <- "id"  # row labels for the heatmap
SEED <- 42
ALGORITHM <- "cheng_church"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_bicluster.parquet", col_select = unique(c(FEATURES, ROW_ID))))
n_input <- nrow(df)
cs_check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, FEATURES)
warnings <- list()
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), 4, "Biclustering")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
dimnames(X) <- NULL
n <- nrow(X)
p <- ncol(X)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
out <- cs_ml_out_dir("target/academy-parity/run-85263/discover.bicluster/planted_cheng_church/out-r")
rng <- cs_rng(SEED)
delta <- NULL
iterations <- NULL

need_nonnegative <- function(strict) {
  bad <- if (strict) X <= 0 else X < 0
  for (j in seq_along(FEATURES)) {
    if (any(bad[, j])) cs_error("CS_E_INVALID_VALUES", column = FEATURES[j], requirement = if (strict) "positive" else "zero or more", count = sum(bad[, j]))
  }
  if (any(rowSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Row totals", requirement = "positive", count = sum(rowSums(X) <= 0))
  if (any(colSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Column totals", requirement = "positive", count = sum(colSums(X) <= 0))
}

# %% Biclusters
if (ALGORITHM == "cheng_church") {
  A <- X
  if ("standard" == "standard") {
    flat <- apply(A, 2, function(v) max(v) - min(v)) == 0
    sd0 <- apply(A, 2, function(v) sqrt(mean((v - mean(v))^2)))
    sd0[flat] <- 1
    A <- sweep(sweep(A, 2, colMeans(A)), 2, sd0, "/")
    A[, flat] <- 0  # constant columns exactly 0 in both engines
  }
  h_full <- cs_ml_bicluster_msr(A, rep(TRUE, n), rep(TRUE, p))
  if (h_full <= 0) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
  delta <- as.numeric(0.02) * h_full
  found <- cs_ml_bicluster_cheng_church(A, 3, delta, as.numeric(1.2), rng)
  biclusters <- found
  if (!length(biclusters)) warnings <- c(warnings, "No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
} else if (ALGORITHM == "cocluster") {
  need_nonnegative(FALSE)
  K <- 3
  n_sv <- if (K > 1) 1 + ceiling(log2(K)) else 1
  if (K < 2 || n_sv > min(n, p) || K > n) {
    cs_error("CS_E_INVALID_OPTION", option = "Biclusters", allowed = sprintf("between 2 and %d for this table", as.integer(min(n, 2^(min(n, p) - 1)))), value = K)
  }
  A <- X
  co <- cs_ml_bicluster_cocluster(A, K, rng, 10)
  biclusters <- lapply(seq_len(K) - 1L, function(b) list(I = co$rows == b, J = co$cols == b))
} else {
  METHOD <- "bistochastic"
  need_nonnegative(METHOD == "log")
  NR <- 3
  NC <- 3
  NCOMP <- 6
  NBEST <- 3
  if (NCOMP > min(n, p)) cs_error("CS_E_INVALID_OPTION", option = "Singular vectors", allowed = sprintf("at most %d for this table", min(n, p)), value = NCOMP)
  usable <- NCOMP - (if (METHOD == "log") 0 else 1)
  if (NBEST > usable) cs_error("CS_E_INVALID_OPTION", option = "Vectors kept", allowed = sprintf("at most %d with %d singular vectors", usable, NCOMP), value = NBEST)
  if (NR > n || NC > p) {
    cs_error("CS_E_INVALID_OPTION", option = if (NR > n) "Row groups" else "Column groups", allowed = sprintf("at most %d", if (NR > n) n else p), value = if (NR > n) NR else NC)
  }
  A <- X
  ch <- cs_ml_bicluster_checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
  iterations <- ch$iterations
  biclusters <- list()
  for (r in seq_len(NR) - 1L) for (cc in seq_len(NC) - 1L) biclusters[[length(biclusters) + 1L]] <- list(I = ch$rows == r, J = ch$cols == cc)
}

# %% Summaries
k <- length(biclusters)
summ <- cs_ml_bicluster_summary(A, biclusters)
values <- list(n = n, p = p, k = k)
values["delta"] <- list(delta)
values["iterations"] <- list(iterations)
values$membership_check <- cs_ml_bicluster_checksum(biclusters)
covered_rows <- rep(FALSE, n)
covered_cells <- matrix(FALSE, n, p)
for (b in biclusters) {
  covered_rows <- covered_rows | b$I
  covered_cells[b$I, b$J] <- TRUE
}
values$rows_covered <- mean(covered_rows)
values$cells_covered <- mean(covered_cells)
msrs <- vapply(summ, function(s) s$msr, numeric(1))
msrs <- msrs[!is.nan(msrs)]
values["msr_mean"] <- list(if (length(msrs)) mean(msrs) else NULL)
for (b in seq_along(summ)) {
  values[[sprintf("n_rows[%d]", b)]] <- summ[[b]]$n_rows
  values[[sprintf("n_cols[%d]", b)]] <- summ[[b]]$n_cols
  values[[sprintf("msr[%d]", b)]] <- summ[[b]]$msr
  values[[sprintf("mean[%d]", b)]] <- summ[[b]]$mean
}
tables <- list(list(
  key = "biclusters", title = "Biclusters",
  columns = list(
    list(key = "bicluster", label = "Bicluster", type = "integer"),
    list(key = "rows", label = "Rows", type = "integer"),
    list(key = "cols", label = "Columns", type = "integer"),
    list(key = "columns", label = "Which columns", type = "string"),
    list(key = "msr", label = "Mean squared residue", type = "number"),
    list(key = "mean", label = "Mean value", type = "number")
  ),
  rows = lapply(seq_along(biclusters), function(b) {
    J <- biclusters[[b]]$J
    nm <- FEATURES[which(J)]
    list(bicluster = b, rows = summ[[b]]$n_rows, cols = summ[[b]]$n_cols,
         columns = paste0(paste(utils::head(nm, 12), collapse = ", "), if (sum(J) > 12) " …" else ""),
         msr = summ[[b]]$msr, mean = summ[[b]]$mean)
  })
))

# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first <- rep(-1L, n)
flags <- list()
for (b in seq_along(biclusters)) {
  I <- biclusters[[b]]$I
  first[first == -1L & I] <- b
  flags[[sprintf("in_%d", b)]] <- I
}
path <- do.call(cs_ml_write_labels, c(list(out, rows, first), flags))
bpath <- file.path(out, "biclusters.json")
bj <- list(k = k,
           rows = lapply(biclusters, function(b) I(as.integer(rows[which(b$I)]))),
           cols = lapply(biclusters, function(b) I(FEATURES[which(b$J)])))
writeLines(as.character(jsonlite::toJSON(bj, auto_unbox = TRUE)), bpath, useBytes = TRUE)

# %% Heatmap
charts <- list()
if (p <= 120 && k > 0) {
  show <- if (n <= 400) seq_len(n) else which(covered_rows)[cs_ml_even_sample(sum(covered_rows), 400) + 1L]
  if (!is.null(ROW_ID)) {
    names <- cs_ml_label_text(df[[ROW_ID]][rows + 1L])
    names[is.na(names)] <- ""
    if (length(unique(names)) < n) names <- sprintf("%s #%d", names, seq_len(n))
  } else {
    names <- sprintf("row %d", rows + 1L)
  }
  cell_b <- matrix(-1L, n, p)
  for (b in seq_along(biclusters)) {
    I <- biclusters[[b]]$I
    J <- biclusters[[b]]$J
    blk <- cell_b[I, J, drop = FALSE]
    blk[blk == -1L] <- b
    cell_b[I, J] <- blk
  }
  rr <- rep(show, each = p)
  jj <- rep(seq_len(p), times = length(show))
  vlabel <- if (ALGORITHM == "cheng_church" && "standard" == "standard") "Value (standardized)" else "Value"
  roles <- list(
    row = cs_col("Row", names[rr], "categorical", levels = names[show]),
    column = cs_col("Column", FEATURES[jj], "categorical", levels = FEATURES),
    value = cs_col(vlabel, A[cbind(rr, jj)], "numeric")
  )
  if (k <= 29) roles$bicluster <- cs_col("Bicluster", as.character(cell_b[cbind(rr, jj)]), "categorical", levels = c(as.character(seq_len(k)), "-1"))
  charts[[1]] <- cs_chart("heatmap", "bicluster-heatmap", "Biclusters in the table", roles,
                          note = if (length(show) == n) NULL else sprintf("%s of %s rows shown (rows in a bicluster, evenly sampled).", format(length(show), big.mark = ","), format(n, big.mark = ",")))
}

# %% Result
cs_publish(list(
  title = "Biclustering (rows × columns)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = n,
  summary = paste0(sprintf("%d bicluster%s in %s rows × %d columns covering %.0f%% of the rows", k, if (k != 1) "s" else "", format(n, big.mark = ","), p, values$rows_covered * 100),
                   if (!is.null(values$msr_mean)) sprintf("; mean squared residue %s.", format(signif(values$msr_mean, 3))) else "."),
  statistics = list(list(key = "k", label = "Biclusters", value = k, format = "integer"),
                    list(key = "rows_covered", label = "Rows covered", value = values$rows_covered, format = "percent"),
                    list(key = "msr_mean", label = "Mean squared residue", value = values$msr_mean)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet"), list(key = "biclusters", path = bpath, format = "json")),
  model = list(kind = "bicluster", features = I(FEATURES), params = list(
    algorithm = "cheng_church",
    k = 3,
    delta_share = 0.02,
    alpha = 1.2,
    scale = "standard",
    n_row_clusters = 3,
    n_col_clusters = 3,
    normalize = "bistochastic",
    n_components = 6,
    n_best = 3,
    n_init = 10
  ))
))

Sources

  • Cheng Y, Church GM (2000). Biclustering of expression data. Proceedings of ISMB 2000, 93–103.
  • Dhillon IS (2001). Co-clustering documents and words using bipartite spectral graph partitioning. KDD 2001, 269–274.
  • Kluger Y, Basri R, Chang JT, Gerstein M (2003). Spectral biclustering of microarray data: coclustering genes and conditions. Genome Research 13:703–716.
  • Madeira SC, Oliveira AL (2004). Biclustering algorithms for biological data analysis: a survey. IEEE/ACM TCBB 1:24–45.

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