use crate::matrix::kmeans::kmeans_centroids_seeded;
use crate::matrix::traits::MatOps;
use nalgebra::{DMatrix, DVector, DVectorView};
use rand::rngs::SmallRng;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rayon::prelude::*;
const MAX_CLUSTER_ROUNDS: usize = 20;
const BLOCK_FRAC: f64 = 0.05;
const EPS_CLUSTER: f64 = 1e-5;
const EPS_HARMONY: f64 = 1e-4;
const WINDOW: usize = 3;
const KMEANS_STARTS: u64 = 10;
const KMEANS_ROUNDS: usize = 25;
const MIN_PAR_CELLS: usize = 256;
const SUM_CHUNK: usize = 1 << 14;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HarmonyArgs {
pub theta: f64,
pub sigma: f64,
pub lambda: f64,
pub n_clusters: Option<usize>,
pub max_rounds: usize,
}
impl Default for HarmonyArgs {
fn default() -> Self {
Self {
theta: 2.0,
sigma: 0.1,
lambda: 1.0,
n_clusters: None,
max_rounds: 10,
}
}
}
impl HarmonyArgs {
pub fn validate(&self) -> anyhow::Result<()> {
anyhow::ensure!(self.theta >= 0.0, "theta must be at least 0");
anyhow::ensure!(self.sigma > 0.0, "sigma must be positive");
anyhow::ensure!(self.lambda > 0.0, "lambda must be positive");
anyhow::ensure!(self.max_rounds >= 1, "max_rounds must be at least 1");
anyhow::ensure!(self.n_clusters != Some(0), "n_clusters must be at least 1");
Ok(())
}
}
fn correct(
z: &DMatrix<f64>,
zt: &DMatrix<f64>,
r: &DMatrix<f64>,
cells: &[Vec<usize>],
lambda: f64,
) -> DMatrix<f64> {
let (n_clusters, d, n_batches) = (r.nrows(), z.nrows(), cells.len());
let r_b: Vec<DMatrix<f64>> = cells.iter().map(|c| r.select_columns(c)).collect();
let m_b: Vec<DMatrix<f64>> = cells
.iter()
.zip(&r_b)
.map(|(c, rb)| rb * zt.select_rows(c))
.collect();
let o = DMatrix::from_columns(&r_b.iter().map(|rb| rb.column_sum()).collect::<Vec<_>>());
let mut w_b = vec![DMatrix::<f64>::zeros(n_clusters, d); n_batches];
for k in 0..n_clusters {
let mut a = DMatrix::<f64>::zeros(n_batches + 1, n_batches + 1);
let mut rhs = DMatrix::<f64>::zeros(n_batches + 1, d);
for (b, mb) in m_b.iter().enumerate() {
let (okb, j) = (o[(k, b)], b + 1);
a[(0, 0)] += okb;
a[(0, j)] = okb;
a[(j, 0)] = okb;
a[(j, j)] = okb + lambda;
let row = mb.row(k);
rhs.set_row(j, &row);
let mut r0 = rhs.row_mut(0);
r0 += &row;
}
let Some(w) = a.lu().solve(&rhs) else {
continue;
};
for (b, wb) in w_b.iter_mut().enumerate() {
wb.set_row(k, &w.row(b + 1));
}
}
let mut out = z.clone();
for ((c, rb), wb) in cells.iter().zip(&r_b).zip(&w_b) {
let delta = wb.tr_mul(rb);
for (t, &i) in c.iter().enumerate() {
let mut col = out.column_mut(i);
col -= delta.column(t);
}
}
out
}
fn soft_assign(dist: DVectorView<f64>, sigma: f64, log_w: impl Fn(usize) -> f64, out: &mut [f64]) {
for (k, v) in out.iter_mut().enumerate() {
*v = -dist[k] / sigma + log_w(k);
}
let max = out.iter().copied().fold(f64::NEG_INFINITY, f64::max);
out.iter_mut().for_each(|v| *v = (*v - max).exp());
let total: f64 = out.iter().sum();
out.iter_mut().for_each(|v| *v /= total);
}
fn initial_centroids(z_cos: &DMatrix<f64>, k: usize, seed: u64) -> DMatrix<f64> {
let rows = z_cos.transpose().map(|v| v as f32);
let cols = z_cos.map(|v| v as f32);
let starts = if k > 1 { KMEANS_STARTS } else { 1 };
let (_, cents) = (0..starts)
.map(|s| {
let (cents, labels) =
kmeans_centroids_seeded(&rows, k, KMEANS_ROUNDS, seed.wrapping_add(s));
let cents_t = cents.transpose();
let per_cell: Vec<f64> = labels
.par_iter()
.enumerate()
.map(|(i, &l)| {
let sq: f32 = cols
.column(i)
.iter()
.zip(cents_t.column(l).iter())
.map(|(a, b)| (a - b) * (a - b))
.sum();
sq as f64
})
.collect();
let inertia: f64 = per_cell.iter().sum();
(inertia, cents)
})
.min_by(|a, b| a.0.total_cmp(&b.0))
.expect("at least one k-means start");
let mut y = cents.transpose().map(|v| v as f64);
y.normalize_columns_inplace();
y
}
struct Clustering<'a> {
batch: &'a [usize],
args: &'a HarmonyArgs,
pr_b: Vec<f64>,
y: DMatrix<f64>,
r: DMatrix<f64>,
o: DMatrix<f64>,
mass: DVector<f64>,
objectives: Vec<f64>,
rng: SmallRng,
}
impl Clustering<'_> {
fn distances(&self, z_cos: &DMatrix<f64>, dist: &mut DMatrix<f64>) {
self.y.tr_mul_to(z_cos, dist);
dist.as_mut_slice()
.par_iter_mut()
.for_each(|c| *c = 2.0 * (1.0 - *c));
}
fn log_ratio(&self) -> DMatrix<f64> {
DMatrix::from_fn(self.o.nrows(), self.o.ncols(), |k, b| {
((self.o[(k, b)] + 1.0) / (self.mass[k] * self.pr_b[b] + 1.0)).ln()
})
}
fn tally(&mut self, i: usize, sign: f64) {
let b = self.batch[i];
for k in 0..self.r.nrows() {
let v = sign * self.r[(k, i)];
self.o[(k, b)] += v;
self.mass[k] += v;
}
}
fn objective(&self, dist: &DMatrix<f64>) -> f64 {
let HarmonyArgs { sigma, theta, .. } = *self.args;
let partial: Vec<f64> = self
.r
.as_slice()
.par_chunks(SUM_CHUNK)
.zip(dist.as_slice().par_chunks(SUM_CHUNK))
.map(|(r, d)| {
r.iter()
.zip(d)
.filter(|(&r, _)| r > 0.0)
.map(|(&r, &d)| r * d + sigma * r * r.ln())
.sum()
})
.collect();
let fit: f64 = partial.iter().sum();
let diversity: f64 = self
.o
.iter()
.zip(self.log_ratio().iter())
.map(|(o, l)| o * l)
.sum();
fit + sigma * theta * diversity
}
fn update_r(&mut self, dist: &DMatrix<f64>) {
let n = self.batch.len();
let HarmonyArgs { sigma, theta, .. } = *self.args;
let mut order: Vec<usize> = (0..n).collect();
order.shuffle(&mut self.rng);
let block = ((n as f64 * BLOCK_FRAC).ceil() as usize).max(1);
let k = self.r.nrows();
let mut buf = vec![0.0; k * block];
for cells in order.chunks(block) {
cells.iter().for_each(|&i| self.tally(i, -1.0));
let lr = self.log_ratio();
let batch = self.batch;
let buf = &mut buf[..k * cells.len()];
buf.par_chunks_mut(k)
.with_min_len(MIN_PAR_CELLS)
.zip(cells.par_iter())
.for_each(|(out, &i)| {
soft_assign(dist.column(i), sigma, |j| -theta * lr[(j, batch[i])], out)
});
for (out, &i) in buf.chunks(k).zip(cells) {
self.r.column_mut(i).copy_from_slice(out);
self.tally(i, 1.0);
}
}
}
fn cluster(&mut self, z_cos: &DMatrix<f64>, dist: &mut DMatrix<f64>) {
let z_cos_t = z_cos.transpose();
for round in 0..MAX_CLUSTER_ROUNDS {
self.y = (&self.r * &z_cos_t).transpose();
self.y.normalize_columns_inplace();
self.distances(z_cos, dist);
let dist = &*dist;
self.update_r(dist);
self.objectives.push(self.objective(dist));
if round > WINDOW && self.settled() {
break;
}
}
}
fn settled(&self) -> bool {
let m = self.objectives.len();
let old: f64 = self.objectives[m - 1 - WINDOW..m - 1].iter().sum();
let new: f64 = self.objectives[m - WINDOW..].iter().sum();
(old - new).abs() < EPS_CLUSTER * old.abs()
}
}
pub fn harmonize(
x: &DMatrix<f32>,
batch: &[usize],
p: &HarmonyArgs,
seed: u64,
) -> anyhow::Result<DMatrix<f32>> {
p.validate()?;
let n = x.nrows();
anyhow::ensure!(n > 0, "no cells");
anyhow::ensure!(
x.iter().all(|v| v.is_finite()),
"non-finite embedding entry"
);
anyhow::ensure!(
batch.len() == n,
"{} batch labels for {n} cells",
batch.len()
);
let mut labels = batch.to_vec();
labels.sort_unstable();
labels.dedup();
let batch: Vec<usize> = batch
.iter()
.map(|b| labels.binary_search(b).expect("label listed"))
.collect();
let n_batches = labels.len();
let mut cells = vec![Vec::new(); n_batches];
for (i, &b) in batch.iter().enumerate() {
cells[b].push(i);
}
let pr_b: Vec<f64> = cells.iter().map(|c| c.len() as f64 / n as f64).collect();
let k = match p.n_clusters {
Some(k) => {
anyhow::ensure!(k <= n, "{k} clusters for {n} cells");
k
}
None => ((n as f64 / 30.0).round() as usize).clamp(1, 100.min(n)),
};
let zt = x.map(|v| v as f64);
let z = zt.transpose();
let mut z_cos = z.normalize_columns();
let mut c = Clustering {
batch: &batch,
args: p,
pr_b,
y: initial_centroids(&z_cos, k, seed),
r: DMatrix::zeros(k, n),
o: DMatrix::zeros(k, n_batches),
mass: DVector::zeros(k),
objectives: Vec::new(),
rng: SmallRng::seed_from_u64(seed),
};
let mut dist = DMatrix::zeros(k, n);
c.distances(&z_cos, &mut dist);
c.r.as_mut_slice()
.par_chunks_mut(k)
.enumerate()
.for_each(|(i, out)| soft_assign(dist.column(i), p.sigma, |_| 0.0, out));
(0..n).for_each(|i| c.tally(i, 1.0));
c.objectives.push(c.objective(&dist));
let mut round = 0;
let z_hat = loop {
let old = *c.objectives.last().expect("an objective per round");
c.cluster(&z_cos, &mut dist);
let z_hat = correct(&z, &zt, &c.r, &cells, p.lambda);
round += 1;
let new = *c.objectives.last().expect("an objective per round");
if round == p.max_rounds || old - new < EPS_HARMONY * old.abs() {
break z_hat;
}
z_cos = z_hat;
z_cos.normalize_columns_inplace();
};
Ok(DMatrix::from_fn(n, z_hat.nrows(), |i, c| {
z_hat[(c, i)] as f32
}))
}
#[cfg(test)]
mod tests;