Communities and blocks: who links with whom in a network
Find groups of densely linked nodes with Leiden, Louvain, label propagation, Markov clustering and Infomap, read modularity honestly, then fit a stochastic blockmodel to find blocks that link alike, such as a core and its periphery.
What runs in CodeSplash
- Network communities Experimental
- Stochastic blockmodel Experimental
You will be able to
- Find communities in an edge list and read modularity, coverage and conductance
- Explain why Leiden keeps communities in one piece and why the resolution matters
- Turn a table into a nearest-neighbor network and find communities of rows
- Fit a stochastic blockmodel and read its block matrix and the number of blocks ICL picks
A club that split in two
ReadIn the 1970s a university karate club split in two. Before the split, Wayne Zachary recorded who met whom outside the club: 34 members, 78 friendships. Can the friendships alone show the split?
Community detectionCommunity detectionSplitting a network into groups of nodes with many links inside each group and few between groups. looks for groups of nodes with many links inside and few between. The default algorithm, LeidenLeiden algorithmLouvain with a refinement step that splits each community into well-connected parts before merging, so none falls apart., moves nodes between communities to raise modularityModularityThe share of link weight inside communities minus the share expected if links fell at random given each node's degree., refines each community so it stays in one piece, then merges communities into single nodes and repeats.
Leiden found 4 communities among 34 nodes; 73% of the edge weight falls inside them (modularity 0.420).
- Communities
- 4
- Modularity
- 0.4198
- Edge weight inside
- 73.1%
Plots
View data
| From | Community | Node | Strength | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 2 | 0 | 16 | 1 | −0.3181 | −0.2545 |
| 0 | 2 | 1 | 9 | 2 | −0.2233 | −0.0757 |
| 0 | 4 | 10 | 3 | 3 | −0.5988 | −0.5538 |
| 0 | 2 | 11 | 1 | 4 | −0.7684 | −0.3116 |
| 0 | 2 | 12 | 2 | 5 | −0.5555 | −0.3153 |
| 0 | 2 | 13 | 5 | 9 | −0.0383 | −0.1016 |
| 0 | 1 | 14 | 2 | 11 | 0.6563 | 0.2455 |
| 0 | 1 | 15 | 2 | 12 | 0.5571 | −0.0469 |
| 0 | 4 | 16 | 2 | 14 | −0.5525 | −1 |
| 0 | 2 | 17 | 2 | 23 | −0.5518 | −0.1334 |
| 0 | 1 | 18 | 2 | 25 | 0.6951 | 0.1440 |
| 0 | 2 | 19 | 3 | 28 | −0.1218 | 0.0626 |
| 0 | 2 | 2 | 10 | 29 | −0.0184 | 0.0461 |
| 0 | 1 | 20 | 2 | 30 | 0.6496 | 0.0363 |
| 0 | 2 | 21 | 2 | 31 | −0.5239 | −0.0045 |
| 0 | 1 | 22 | 2 | 32 | 0.6464 | 0.3546 |
| 1 | 3 | 23 | 5 | 5 | 0.3325 | 0.4993 |
| 1 | 3 | 24 | 3 | 9 | −0.0504 | 0.6329 |
| 1 | 3 | 25 | 3 | 11 | 0.1108 | 0.6623 |
| 1 | 1 | 26 | 2 | 12 | 0.6203 | 0.5661 |
| 1 | 3 | 27 | 4 | 14 | 0.1293 | 0.4353 |
| 1 | 3 | 28 | 3 | 23 | 0.1494 | 0.2290 |
| 1 | 1 | 29 | 4 | 24 | 0.5085 | 0.4495 |
| 1 | 2 | 3 | 6 | 31 | −0.2882 | −0.1638 |
| 2 | 1 | 30 | 4 | 28 | 0.2164 | −0.0296 |
| 2 | 3 | 31 | 6 | 29 | 0.0165 | 0.2593 |
| 4 | 1 | 32 | 12 | 23 | 0.4004 | 0.1628 |
| 5 | 1 | 33 | 17 | 12 | 0.3249 | 0.2115 |
| 5 | 4 | 4 | 3 | 23 | −0.4335 | −0.5876 |
| 5 | 4 | 5 | 4 | 27 | −0.5362 | −0.7094 |
| 6 | 4 | 6 | 4 | 26 | −0.4075 | −0.7379 |
| 6 | 2 | 7 | 4 | 27 | −0.1466 | −0.2632 |
| 7 | 1 | 8 | 5 | 26 | 0.1237 | −0.0736 |
| 7 | 1 | 9 | 2 | 27 | −0.0040 | 0.3656 |
| 8 | — | — | — | 29 | — | — |
| 8 | — | — | — | 30 | — | — |
| 10 | — | — | — | 26 | — | — |
| 10 | — | — | — | 27 | — | — |
| 11 | — | — | — | 27 | — | — |
| 12 | — | — | — | 20 | — | — |
| 12 | — | — | — | 21 | — | — |
| 12 | — | — | — | 23 | — | — |
| 12 | — | — | — | 26 | — | — |
| 12 | — | — | — | 31 | — | — |
| 12 | — | — | — | 32 | — | — |
| 12 | — | — | — | 33 | — | — |
| 13 | — | — | — | 26 | — | — |
| 13 | — | — | — | 27 | — | — |
| 15 | — | — | — | 26 | — | — |
| 15 | — | — | — | 27 | — | — |
| 16 | — | — | — | 18 | — | — |
| 16 | — | — | — | 20 | — | — |
| 16 | — | — | — | 22 | — | — |
| 16 | — | — | — | 26 | — | — |
| 16 | — | — | — | 27 | — | — |
| 17 | — | — | — | 18 | — | — |
| 17 | — | — | — | 20 | — | — |
| 17 | — | — | — | 25 | — | — |
| 18 | — | — | — | 25 | — | — |
| 19 | — | — | — | 22 | — | — |
First 60 of 78 rows.
Nodes sorted by community: dense blocks on the diagonal are communities.
View data
| Column | Community | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 1 | 2 | 0 | 27 | 0 | 1 |
| 2 | 2 | 1 | 26 | 0 | 1 |
| 3 | 4 | 10 | 32 | 0 | 1 |
| 4 | 2 | 11 | 22 | 0 | 1 |
| 5 | 2 | 12 | 24 | 0 | 1 |
| 9 | 2 | 13 | 6 | 0 | 1 |
| 11 | 1 | 14 | 7 | 0 | 1 |
| 12 | 1 | 15 | 10 | 0 | 1 |
| 14 | 4 | 16 | 13 | 0 | 1 |
| 23 | 2 | 17 | 15 | 0 | 1 |
| 25 | 1 | 18 | 19 | 0 | 1 |
| 28 | 2 | 19 | 33 | 0 | 1 |
| 29 | 2 | 2 | 0 | 0 | 1 |
| 30 | 1 | 20 | 12 | 0 | 1 |
| 31 | 2 | 21 | 1 | 0 | 1 |
| 32 | 1 | 22 | 23 | 0 | 1 |
| 5 | 3 | 23 | 5 | 1 | 1 |
| 9 | 3 | 24 | 31 | 1 | 1 |
| 11 | 3 | 25 | 11 | 1 | 1 |
| 12 | 1 | 26 | 4 | 1 | 1 |
| 14 | 3 | 27 | 9 | 1 | 1 |
| 23 | 3 | 28 | 14 | 1 | 1 |
| 24 | 1 | 29 | 3 | 1 | 1 |
| 31 | 2 | 3 | 25 | 1 | 1 |
| 28 | 1 | 30 | 16 | 2 | 1 |
| 29 | 3 | 31 | 20 | 2 | 1 |
| 23 | 1 | 32 | 17 | 4 | 1 |
| 12 | 1 | 33 | 18 | 5 | 1 |
| 23 | 4 | 4 | 21 | 5 | 1 |
| 27 | 4 | 5 | 29 | 5 | 1 |
| 26 | 4 | 6 | 30 | 6 | 1 |
| 27 | 2 | 7 | 2 | 6 | 1 |
| 26 | 1 | 8 | 28 | 7 | 1 |
| 27 | 1 | 9 | 8 | 7 | 1 |
| 29 | — | — | — | 8 | 1 |
| 30 | — | — | — | 8 | 1 |
| 26 | — | — | — | 10 | 1 |
| 27 | — | — | — | 10 | 1 |
| 27 | — | — | — | 11 | 1 |
| 20 | — | — | — | 12 | 1 |
| 21 | — | — | — | 12 | 1 |
| 23 | — | — | — | 12 | 1 |
| 26 | — | — | — | 12 | 1 |
| 31 | — | — | — | 12 | 1 |
| 32 | — | — | — | 12 | 1 |
| 33 | — | — | — | 12 | 1 |
| 26 | — | — | — | 13 | 1 |
| 27 | — | — | — | 13 | 1 |
| 26 | — | — | — | 15 | 1 |
| 27 | — | — | — | 15 | 1 |
| 18 | — | — | — | 16 | 1 |
| 20 | — | — | — | 16 | 1 |
| 22 | — | — | — | 16 | 1 |
| 26 | — | — | — | 16 | 1 |
| 27 | — | — | — | 16 | 1 |
| 18 | — | — | — | 17 | 1 |
| 20 | — | — | — | 17 | 1 |
| 25 | — | — | — | 17 | 1 |
| 25 | — | — | — | 18 | 1 |
| 22 | — | — | — | 19 | 1 |
First 60 of 78 rows.
View data
| Community |
|---|
| 2 |
| 2 |
| 4 |
| 2 |
| 2 |
| 2 |
| 1 |
| 1 |
| 4 |
| 2 |
| 1 |
| 2 |
| 2 |
| 1 |
| 2 |
| 1 |
| 3 |
| 3 |
| 3 |
| 1 |
| 3 |
| 3 |
| 1 |
| 2 |
| 1 |
| 3 |
| 1 |
| 1 |
| 4 |
| 4 |
| 4 |
| 2 |
| 1 |
| 1 |
Communities
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 12 | 35.3% | 0.2500 | yes | 33, 32, 8 |
| 2 | 11 | 32.4% | 0.2333 | yes | 0, 2, 1 |
| 3 | 6 | 17.6% | 0.4167 | yes | 31, 23, 27 |
| 4 | 5 | 14.7% | 0.2500 | yes | 5, 6, 10 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec ab902ef908a98ec8
# Dataset: graph_karate (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ml_comm_*(): twin of codesplash.ml.communities
ALGO <- "leiden"
QUALITY <- "modularity"
RESOLUTION <- NULL
INFLATION <- 2
TRIALS <- 5L
DIRECTED <- FALSE
SWEEP <- FALSE
SEED <- 42
LABELS <- c(leiden = "Leiden", louvain = "Louvain", label_propagation = "Label propagation", mcl = "Markov clustering", infomap = "Infomap")
LIMITS <- list(infomap = c(10000, 100000), mcl = c(5000, 50000)) # (nodes, edges); the others 20,000 / 200,000
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.communities/leiden_karate/out-r")
warnings <- list()
values <- list(algorithm_label = LABELS[[ALGO]])
tables <- list()
charts <- list()
artifacts <- list()
# %% The network the host built (canonical node order, merged edges; cs_graph_read)
G <- cs_graph_read(out)
warnings <- c(warnings, as.list(G$warnings))
N <- G$n
pairs <- cs_graph_undirected_pairs(G)
g <- cs_ml_comm_graph(N, pairs$a + 1L, pairs$b + 1L, pairs$w) # direction set aside: every edge counts both ways
lim <- if (!is.null(LIMITS[[ALGO]])) LIMITS[[ALGO]] else c(20000, 200000)
if (N > lim[1] || length(pairs$a) > lim[2]) {
cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(pairs$a), max_nodes = lim[1], max_edges = lim[2])
}
if (N < 2 || g$m2 <= 0) cs_error("CS_E_UNDEFINED", what = "Communities", reason = "the network needs at least one edge between two different nodes")
if (isTRUE(G$directed) && !(ALGO == "infomap" && isTRUE(DIRECTED))) {
warnings <- c(warnings, sprintf("%s treats every edge as two-way, so the directions were set aside.", LABELS[[ALGO]]))
}
truth <- NULL
if (!is.null(G$label)) truth <- as.character(G$nodes[[G$label]])
values$mode <- "network"
values$n_nodes <- N
values$n_edges <- length(g$idx) %/% 2L
# %% Communities
if (ALGO %in% c("leiden", "louvain")) {
gamma <- if (!is.null(RESOLUTION)) as.numeric(RESOLUTION) else if (QUALITY == "cpm") (g$m2 / 2) / (N * (N - 1) / 2) else 1 # Potts default: the network's density
values$resolution <- gamma
}
find <- function(setting) {
rng <- cs_rng(SEED) # a fresh stream for every setting
if (ALGO == "leiden") return(cs_ml_comm_leiden(g, setting, QUALITY, rng))
if (ALGO == "louvain") return(cs_ml_comm_louvain(g, setting, QUALITY, rng))
if (ALGO == "label_propagation") return(cs_ml_comm_label_propagation(g, rng))
if (ALGO == "mcl") return(cs_ml_comm_mcl(g, setting))
fl <- if (isTRUE(G$directed) && isTRUE(DIRECTED)) cs_ml_comm_flow_directed(cs_ml_comm_dgraph(N, G$si + 1L, G$sj + 1L, G$sw)) else cs_ml_comm_flow_undirected(g)
cs_ml_comm_infomap(fl, rng, TRIALS)
}
setting <- if (ALGO %in% c("leiden", "louvain")) gamma else if (ALGO == "mcl") as.numeric(INFLATION) else NULL
res <- find(setting)
labels <- cs_ml_canonical(res$labels) # 1..k by size, ties by first node
k <- max(labels)
values$k <- k
if (!is.null(res$levels)) values$levels <- res$levels
if (!is.null(res$iterations)) values$iterations <- res$iterations
if (!is.null(res$sweeps)) values$sweeps <- res$sweeps
if (!is.null(res$converged)) {
values$converged <- isTRUE(res$converged)
if (!isTRUE(res$converged)) warnings <- c(warnings, sprintf("%s stopped at its iteration limit before every node settled.", LABELS[[ALGO]]))
}
if (!is.null(res$attractors)) values$attractors <- res$attractors
if (ALGO == "infomap") {
values$codelength <- res$codelength
values$codelength_one <- res$one_module
}
# %% Quality of the partition
values$modularity <- cs_ml_comm_modularity(g, labels, 1)
if (ALGO %in% c("leiden", "louvain")) {
values$quality <- if (QUALITY == "cpm") cs_ml_comm_cpm(g, labels, gamma) else cs_ml_comm_modularity(g, labels, gamma)
}
values$coverage <- cs_ml_comm_coverage(g, labels)
cond <- cs_ml_comm_conductance(g, labels)
finite <- cond[!is.nan(cond)]
if (length(finite)) values$conductance <- mean(finite) else values["conductance"] <- list(NULL)
conn <- cs_ml_comm_connected(g, labels)
values$n_disconnected <- sum(!conn)
if (values$n_disconnected > 0) warnings <- c(warnings, sprintf("%d of %d communities fall apart into separate pieces of the network.", values$n_disconnected, k))
sizes <- tabulate(labels, nbins = k)
for (c in seq_len(k)) values[[sprintf("size[%d]", c)]] <- sizes[c]
values$largest_share <- max(sizes) / N
values$singletons <- sum(sizes == 1)
if (!is.null(truth)) {
ok <- !is.na(truth)
values$n_labeled <- sum(ok)
if (sum(ok) >= 2) {
values$ari <- cs_ml_ari(truth[ok], labels[ok])
values$ami <- cs_ml_ami(truth[ok], labels[ok])
values$nmi <- cs_ml_nmi(truth[ok], labels[ok])
}
}
# %% Settings compared
if (isTRUE(SWEEP) && ALGO %in% c("leiden", "louvain", "mcl")) {
grid <- if (ALGO != "mcl") gamma * c(0.25, 0.5, 1, 2, 4) else c(1.4, 1.6, 2, 2.5, 3, 4)
srows <- list(); ks <- integer(0); qs <- numeric(0)
for (i in seq_along(grid)) {
lab_s <- cs_ml_canonical(find(grid[i])$labels)
ks[i] <- max(lab_s)
qs[i] <- cs_ml_comm_modularity(g, lab_s, 1)
values[[sprintf("sweep_setting[%d]", i)]] <- grid[i]
values[[sprintf("sweep_k[%d]", i)]] <- ks[i]
values[[sprintf("sweep_modularity[%d]", i)]] <- qs[i]
srows[[i]] <- list(setting = grid[i], k = ks[i], modularity = qs[i])
}
what <- if (ALGO == "mcl") "Inflation" else "Resolution"
tables[[length(tables) + 1L]] <- list(
key = "sweep", title = sprintf("Communities at other settings (%s)", tolower(what)),
columns = list(list(key = "setting", label = what, type = "number"), list(key = "k", label = "Communities", type = "integer"),
list(key = "modularity", label = "Modularity", type = "number")),
rows = srows
)
chosen <- abs(grid - setting) < 1e-12
charts[[length(charts) + 1L]] <- cs_chart(
"sweep", "elbow-plot", sprintf("Communities by %s", tolower(what)),
list(k = cs_col(what, c(grid, grid), "numeric"), score = cs_col("Value", c(ks, qs), "numeric"),
criterion = cs_col("Measure", c(rep("Communities", length(grid)), rep("Modularity", length(grid))), "categorical", c("Communities", "Modularity")),
chosen = cs_col("This run", c(chosen, chosen), "boolean")),
note = sprintf("The ringed point is this run's %s.", tolower(what))
)
}
# %% Communities table
crows <- list()
for (c in seq_len(k)) {
members <- which(labels == c)
top <- members[order(-g$k[members], members)][seq_len(min(3L, length(members)))]
crows[[c]] <- list(community = c, size = sizes[c], share = sizes[c] / N,
conductance = if (is.nan(cond[c])) NULL else cond[c], connected = conn[c],
examples = paste(G$node_id[top], collapse = ", "))
}
tables <- c(list(list(
key = "communities", title = "Communities",
columns = list(list(key = "community", label = "Community", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
list(key = "share", label = "Share", type = "percent"), list(key = "conductance", label = "Conductance", type = "number"),
list(key = "connected", label = "In one piece", type = "boolean"), list(key = "examples", label = "Best-connected nodes")),
rows = crows
)), tables)
# %% Results per node (or row) and charts
level_names <- as.character(seq_len(k))
artifacts[[length(artifacts) + 1L]] <- cs_graph_write_nodes(out, G, data.frame(community = as.integer(labels), strength = g$k))
MAP_NODES <- 2000; MATRIX_NODES <- 300
if (N <= MAP_NODES) {
xy <- cs_graph_layout_fr(G, SEED)
m <- length(G$si)
show <- min(m, 20000)
keep <- seq_len(show)
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(
x = cs_col("x", xy$x, "numeric"),
y = cs_col("y", xy$y, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
size = cs_col("Strength", g$k, "numeric"),
group = cs_col("Community", as.character(labels), "categorical", level_names),
from = cs_col("From", G$si[keep], "numeric"),
to = cs_col("To", G$sj[keep], "numeric"),
weight = if (isTRUE(G$weighted)) cs_col("Weight", G$sw[keep], "numeric") else NULL
), controls = list(directed = isTRUE(G$directed)), note = if (show == m) NULL else sprintf("%d of %d edges drawn.", show, m))
} else {
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(), note = sprintf("The map is drawn for networks up to %d nodes; this one has %d.", MAP_NODES, N))
}
if (N <= MATRIX_NODES) {
morder <- order(labels, -g$k, seq_len(N)) - 1L
charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by community", list(
row = cs_col("Row", G$si, "numeric"),
col = cs_col("Column", G$sj, "numeric"),
value = cs_col(if (isTRUE(G$weighted)) "Weight" else "Edge", G$sw, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
group = cs_col("Community", as.character(labels), "categorical", level_names),
order = cs_col("Order", morder, "numeric")
), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by community: dense blocks on the diagonal are communities.")
}
charts[[length(charts) + 1L]] <- cs_chart("sizes", "bar", "Community sizes", list(x = cs_col("Community", as.character(labels), "categorical", level_names)),
controls = list(top = 30))
# %% Result
what <- if (values$mode == "rows") "rows" else "nodes"
summary <- sprintf("%s found %d communit%s among %s %s; %.0f%% of the edge weight falls inside them (modularity %.3f).",
LABELS[[ALGO]], k, if (k == 1) "y" else "ies", format(N, big.mark = ","), what, 100 * values$coverage, values$modularity)
if (ALGO == "infomap") {
summary <- paste0(summary, sprintf(" The map describes the walk in %.3f bits per step, against %.3f with one module.", values$codelength, values$codelength_one))
}
publish <- list(
title = "Network communities",
engine = cs_engine_info("nanoparquet", "Matrix"),
n = N,
summary = summary,
statistics = list(list(key = "k", label = "Communities", value = k, format = "integer"),
list(key = "modularity", label = "Modularity", value = values$modularity),
list(key = "coverage", label = "Edge weight inside", value = values$coverage, format = "percent")),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = artifacts
)
cs_publish(publish)
Leiden found 4 communities among 34 nodes; 73% of the edge weight falls inside them (modularity 0.420).
- Communities
- 4
- Modularity
- 0.4198
- Edge weight inside
- 73.1%
To keep this page light, the plots are shown once, under the R tab.
Communities
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 12 | 35.3% | 0.2500 | yes | 33, 32, 8 |
| 2 | 11 | 32.4% | 0.2333 | yes | 0, 2, 1 |
| 3 | 6 | 17.6% | 0.4167 | yes | 31, 23, 27 |
| 4 | 5 | 14.7% | 0.2500 | yes | 5, 6, 10 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec ab902ef908a98ec8
# Dataset: graph_karate (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
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 communities as cm # twin of codesplashr R/ml_communities.R
from codesplash.stats.rng import Rng
ALGO = "leiden"
QUALITY = "modularity"
RESOLUTION = None
INFLATION = 2
TRIALS = 5
DIRECTED = False
SWEEP = False
SEED = 42
LABELS = {"leiden": "Leiden", "louvain": "Louvain", "label_propagation": "Label propagation", "mcl": "Markov clustering", "infomap": "Infomap"}
LIMITS = {"infomap": (10000, 100000), "mcl": (5000, 50000)} # (nodes, edges); the others 20,000 / 200,000
out = csml.out_dir("target/academy-parity/run-8142/discover.communities/leiden_karate/out-python")
warnings = []
values = {"algorithm_label": LABELS[ALGO]}
tables = []
charts = []
artifacts = []
# %% The network the host built (canonical node order, merged edges; codesplash.graph)
from codesplash import graph as cg
from codesplash.graph import layout as gl
G = cg.read(out)
warnings += list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G)
g = cm.undirected(N, a, b, w) # direction set aside: every edge counts both ways
max_nodes, max_edges = LIMITS.get(ALGO, (20000, 200000))
if N > max_nodes or len(a) > max_edges:
cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=max_nodes, max_edges=max_edges)
if N < 2 or g.m2 <= 0:
cs.cs_error("CS_E_UNDEFINED", what="Communities", reason="the network needs at least one edge between two different nodes")
if G.directed and not (ALGO == "infomap" and DIRECTED):
warnings.append(f"{LABELS[ALGO]} treats every edge as two-way, so the directions were set aside.")
truth = None
if G.label:
truth = np.array([None if pd.isna(v) else str(v) for v in G.nodes[G.label].tolist()], dtype=object) # None, NaN, pd.NA
values["mode"] = "network"
values["n_nodes"] = N
values["n_edges"] = g.n_edges
# %% Communities
if ALGO in ("leiden", "louvain"):
if RESOLUTION is not None:
gamma = float(RESOLUTION)
elif QUALITY == "cpm":
gamma = (g.m2 / 2.0) / (N * (N - 1) / 2.0) # the network's density (edge weight per pair of nodes)
else:
gamma = 1.0
values["resolution"] = gamma
def find(setting):
"""Communities for one setting (resolution or inflation), from a fresh stream → (labels, info)."""
rng = Rng(SEED)
if ALGO == "leiden":
r = cm.leiden(g, setting, QUALITY, rng)
elif ALGO == "louvain":
r = cm.louvain(g, setting, QUALITY, rng)
elif ALGO == "label_propagation":
r = cm.label_propagation(g, rng)
elif ALGO == "mcl":
r = cm.mcl(g, setting)
else:
fl = cm.flow_directed(cm.DGraph(N, G.si, G.sj, G.sw)) if (G.directed and DIRECTED) else cm.flow_undirected(g)
r = cm.infomap(fl, rng, TRIALS)
return r
setting = gamma if ALGO in ("leiden", "louvain") else (float(INFLATION) if ALGO == "mcl" else None)
res = find(setting)
labels = csc.canonical(np.asarray(res["labels"], dtype=np.int64)) # 1…k by size, ties by first node
lab0 = (labels - 1).tolist()
k = int(labels.max())
values["k"] = k
if "levels" in res:
values["levels"] = res["levels"]
if "iterations" in res:
values["iterations"] = res["iterations"]
if "sweeps" in res:
values["sweeps"] = res["sweeps"]
if "converged" in res:
values["converged"] = bool(res["converged"])
if not res["converged"]:
warnings.append(f"{LABELS[ALGO]} stopped at its iteration limit before every node settled.")
if "attractors" in res:
values["attractors"] = res["attractors"]
if ALGO == "infomap":
values["codelength"] = res["codelength"]
values["codelength_one"] = res["one_module"]
# %% Quality of the partition
values["modularity"] = cm.modularity(g, lab0, 1.0)
if ALGO in ("leiden", "louvain"):
values["quality"] = cm.cpm(g, lab0, gamma) if QUALITY == "cpm" else cm.modularity(g, lab0, gamma)
values["coverage"] = cm.coverage(g, lab0)
cond = cm.conductance(g, lab0)
finite = [c for c in cond if c == c]
values["conductance"] = float(np.mean(finite)) if finite else None
conn = cm.connected(g, lab0)
values["n_disconnected"] = int(sum(1 for x in conn if not x))
if values["n_disconnected"]:
warnings.append(f"{values['n_disconnected']} of {k} communities fall apart into separate pieces of the network.")
sizes = np.bincount(labels, minlength=k + 1)[1:]
for c in range(1, k + 1):
values[f"size[{c}]"] = int(sizes[c - 1])
values["largest_share"] = float(sizes.max() / N)
values["singletons"] = int(np.sum(sizes == 1))
if truth is not None:
ok = np.array([v is not None for v in truth])
values["n_labeled"] = int(ok.sum())
if ok.sum() >= 2:
tt = truth[ok].astype(str)
values["ari"] = csc.ari(tt, labels[ok])
values["ami"] = csc.ami(tt, labels[ok])
values["nmi"] = csc.nmi(tt, labels[ok])
# %% Settings compared
if SWEEP and ALGO in ("leiden", "louvain", "mcl"):
grid = [gamma * f for f in (0.25, 0.5, 1.0, 2.0, 4.0)] if ALGO != "mcl" else [1.4, 1.6, 2.0, 2.5, 3.0, 4.0]
srows = []
for i, s in enumerate(grid, start=1):
lab_s = csc.canonical(np.asarray(find(s)["labels"], dtype=np.int64))
ks = int(lab_s.max())
qs = cm.modularity(g, (lab_s - 1).tolist(), 1.0)
values[f"sweep_setting[{i}]"] = s
values[f"sweep_k[{i}]"] = ks
values[f"sweep_modularity[{i}]"] = qs
srows.append({"setting": s, "k": ks, "modularity": qs})
what = "Inflation" if ALGO == "mcl" else "Resolution"
tables.append({
"key": "sweep", "title": f"Communities at other settings ({what.lower()})",
"columns": [{"key": "setting", "label": what, "type": "number"}, {"key": "k", "label": "Communities", "type": "integer"},
{"key": "modularity", "label": "Modularity", "type": "number"}],
"rows": srows,
})
chosen = [abs(s - setting) < 1e-12 for s in grid]
charts.append(cs.chart(
"sweep", "elbow-plot", f"Communities by {what.lower()}",
{"k": cs.col(what, grid + grid, "numeric"), "score": cs.col("Value", [r["k"] for r in srows] + [r["modularity"] for r in srows], "numeric"),
"criterion": cs.col("Measure", ["Communities"] * len(grid) + ["Modularity"] * len(grid), "categorical", ["Communities", "Modularity"]),
"chosen": cs.col("This run", chosen + chosen, "boolean")},
note=f"The ringed point is this run's {what.lower()}.",
))
# %% Communities table
crows = []
for c in range(1, k + 1):
members = np.flatnonzero(labels == c)
top = sorted(members.tolist(), key=lambda v: (-g.k[v], v))[:3]
crows.append({"community": c, "size": int(sizes[c - 1]), "share": float(sizes[c - 1] / N),
"conductance": cond[c - 1] if cond[c - 1] == cond[c - 1] else None, "connected": bool(conn[c - 1]),
"examples": ", ".join(G.node_id[v] for v in top)})
tables.insert(0, {
"key": "communities", "title": "Communities",
"columns": [{"key": "community", "label": "Community", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
{"key": "share", "label": "Share", "type": "percent"}, {"key": "conductance", "label": "Conductance", "type": "number"},
{"key": "connected", "label": "In one piece", "type": "boolean"}, {"key": "examples", "label": "Best-connected nodes"}],
"rows": crows,
})
# %% Results per node (or row) and charts
level_names = [str(c) for c in range(1, k + 1)]
cols = {"community": labels.astype(np.int64), "strength": np.asarray(g.k, dtype=np.float64)}
artifacts.append(cg.write_nodes(out, G, cols))
MAP_NODES, MATRIX_NODES = 2000, 300
if N <= MAP_NODES:
xy = gl.fruchterman_reingold(G, SEED)
m = len(G.si)
show = min(m, 20000)
charts.append(cs.chart("map", "network-graph", "Communities in the network", {
"x": cs.col("x", xy[0], "numeric"),
"y": cs.col("y", xy[1], "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"size": cs.col("Strength", g.k, "numeric"),
"group": cs.col("Community", [str(c) for c in labels], "categorical", level_names),
"from": cs.col("From", G.si[:show], "numeric"),
"to": cs.col("To", G.sj[:show], "numeric"),
"weight": cs.col("Weight", G.sw[:show], "numeric") if G.weighted else None,
}, controls={"directed": G.directed}, note=None if show == m else f"{show} of {m} edges drawn."))
else:
charts.append(cs.chart("map", "network-graph", "Communities in the network", {}, note=f"The map is drawn for networks up to {MAP_NODES} nodes; this one has {N}."))
if N <= MATRIX_NODES:
morder = sorted(range(N), key=lambda v: (int(labels[v]), -g.k[v], v))
charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by community", {
"row": cs.col("Row", G.si, "numeric"),
"col": cs.col("Column", G.sj, "numeric"),
"value": cs.col("Weight" if G.weighted else "Edge", G.sw, "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"group": cs.col("Community", [str(c) for c in labels], "categorical", level_names),
"order": cs.col("Order", morder, "numeric"),
}, controls={"directed": G.directed}, note="Nodes sorted by community: dense blocks on the diagonal are communities."))
charts.append(cs.chart("sizes", "bar", "Community sizes", {"x": cs.col("Community", [str(c) for c in labels], "categorical", level_names)},
controls={"top": 30}))
# %% Result
what = "rows" if values["mode"] == "rows" else "nodes"
summary = (f"{LABELS[ALGO]} found {k} communit{'y' if k == 1 else 'ies'} among {N:,} {what}; "
f"{values['coverage']:.0%} of the edge weight falls inside them (modularity {values['modularity']:.3f}).")
if ALGO == "infomap":
summary += f" The map describes the walk in {values['codelength']:.3f} bits per step, against {values['codelength_one']:.3f} with one module."
publish = {
"title": "Network communities",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": N,
"summary": summary,
"statistics": [
{"key": "k", "label": "Communities", "value": k, "format": "integer"},
{"key": "modularity", "label": "Modularity", "value": values["modularity"]},
{"key": "coverage", "label": "Edge weight inside", "value": values["coverage"], "format": "percent"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": artifacts,
}
cs.publish(publish)
Leiden finds 4 communities with modularity 0.420, the highest this network allows. Against the clubs members joined, the adjusted Rand index is 0.46: each club splits in two, but few communities mix the clubs.
View data
| x | y | person | degree | team | from | to |
|---|---|---|---|---|---|---|
| 0.9470 | 0.0170 | Des-1 | 4 | Design | 0 | 1 |
| 0.8260 | 0.1750 | Des-2 | 5 | Design | 0 | 7 |
| 0.6950 | 0.2280 | Des-3 | 6 | Design | 0 | 8 |
| 0.4920 | 0.3110 | Des-4 | 6 | Design | 0 | 11 |
| 0.3860 | 0.1840 | Des-5 | 4 | Design | 1 | 2 |
| 0.2960 | −0.0400 | Des-6 | 2 | Design | 1 | 4 |
| 0.4430 | −0.1380 | Des-7 | 3 | Design | 1 | 8 |
| 0.5310 | −0.2670 | Des-8 | 4 | Design | 1 | 28 |
| 0.7340 | −0.2650 | Des-9 | 4 | Design | 2 | 3 |
| 0.8550 | −0.2200 | Des-10 | 4 | Design | 2 | 6 |
| −0.0770 | 0.5650 | Eng-1 | 4 | Engineering | 2 | 8 |
| −0.1470 | 0.6850 | Eng-2 | 5 | Engineering | 2 | 9 |
| −0.2300 | 0.8190 | Eng-3 | 2 | Engineering | 2 | 11 |
| −0.4100 | 0.7720 | Eng-4 | 5 | Engineering | 3 | 4 |
| −0.5010 | 0.6470 | Eng-5 | 3 | Engineering | 3 | 5 |
| −0.5550 | 0.5100 | Eng-6 | 3 | Engineering | 3 | 7 |
| −0.5230 | 0.4220 | Eng-7 | 3 | Engineering | 3 | 24 |
| −0.3910 | 0.2320 | Eng-8 | 4 | Engineering | 3 | 29 |
| −0.1720 | 0.2530 | Eng-9 | 6 | Engineering | 4 | 9 |
| −0.0340 | 0.3630 | Eng-10 | 5 | Engineering | 4 | 22 |
| 0.0220 | −0.5120 | Sal-1 | 6 | Sales | 5 | 7 |
| −0.0140 | −0.3800 | Sal-2 | 1 | Sales | 6 | 7 |
| −0.2370 | −0.2210 | Sal-3 | 3 | Sales | 6 | 9 |
| −0.3810 | −0.2810 | Sal-4 | 6 | Sales | 8 | 9 |
| −0.5410 | −0.3290 | Sal-5 | 7 | Sales | 10 | 11 |
| −0.5700 | −0.5090 | Sal-6 | 4 | Sales | 10 | 13 |
| −0.5450 | −0.7170 | Sal-7 | 3 | Sales | 10 | 18 |
| −0.4070 | −0.7670 | Sal-8 | 5 | Sales | 10 | 19 |
| −0.2460 | −0.7870 | Sal-9 | 5 | Sales | 11 | 13 |
| −0.1000 | −0.6820 | Sal-10 | 6 | Sales | 11 | 16 |
| — | — | — | — | — | 12 | 14 |
| — | — | — | — | — | 12 | 16 |
| — | — | — | — | — | 13 | 15 |
| — | — | — | — | — | 13 | 17 |
| — | — | — | — | — | 13 | 24 |
| — | — | — | — | — | 14 | 17 |
| — | — | — | — | — | 14 | 18 |
| — | — | — | — | — | 15 | 18 |
| — | — | — | — | — | 15 | 19 |
| — | — | — | — | — | 16 | 18 |
| — | — | — | — | — | 17 | 18 |
| — | — | — | — | — | 17 | 19 |
| — | — | — | — | — | 18 | 19 |
| — | — | — | — | — | 19 | 28 |
| — | — | — | — | — | 20 | 23 |
| — | — | — | — | — | 20 | 25 |
| — | — | — | — | — | 20 | 26 |
| — | — | — | — | — | 20 | 27 |
| — | — | — | — | — | 20 | 28 |
| — | — | — | — | — | 20 | 29 |
| — | — | — | — | — | 21 | 24 |
| — | — | — | — | — | 22 | 27 |
| — | — | — | — | — | 22 | 28 |
| — | — | — | — | — | 23 | 24 |
| — | — | — | — | — | 23 | 25 |
| — | — | — | — | — | 23 | 26 |
| — | — | — | — | — | 23 | 27 |
| — | — | — | — | — | 23 | 28 |
| — | — | — | — | — | 24 | 25 |
| — | — | — | — | — | 24 | 27 |
First 60 of 64 rows.
Reading modularity honestly
ReadModularity compares the share of links inside communities with the share expected if links fell at random, given each node's degree. Use it to compare partitions of the same network:
- it can't see communities smaller than about (the resolution limitResolution limitModularity merges communities smaller than about √(2 × edges); a resolution above 1 splits them, below 1 merges more.); a resolution above 1 splits more, below 1 merges more;
- a random network without communities still reaches a sizable modularity, so a high value doesn't prove real groups.
The weighted version counts how many contexts each pair of members shared. Louvain, Leiden's predecessor, with the settings sweep:
Louvain found 4 communities among 34 nodes; 78% of the edge weight falls inside them (modularity 0.444).
- Communities
- 4
- Modularity
- 0.4439
- Edge weight inside
- 77.9%
Plots
The ringed point is this run's resolution.
View data
| This run | Measure | Resolution | Value |
|---|---|---|---|
| false | Communities | 0.2500 | 2 |
| false | Communities | 0.5000 | 2 |
| true | Communities | 1 | 4 |
| false | Communities | 2 | 7 |
| false | Communities | 4 | 11 |
| false | Modularity | 0.2500 | 0.4036 |
| false | Modularity | 0.5000 | 0.4036 |
| true | Modularity | 1 | 0.4439 |
| false | Modularity | 2 | 0.3443 |
| false | Modularity | 4 | 0.2475 |
View data
| From | Community | Node | Strength | To | Weight | x | y |
|---|---|---|---|---|---|---|---|
| 0 | 2 | 0 | 42 | 1 | 4 | −0.3181 | −0.2545 |
| 0 | 2 | 1 | 29 | 2 | 2 | −0.2233 | −0.0757 |
| 0 | 3 | 10 | 8 | 3 | 3 | −0.5988 | −0.5538 |
| 0 | 2 | 11 | 3 | 4 | 1 | −0.7684 | −0.3116 |
| 0 | 2 | 12 | 4 | 5 | 3 | −0.5555 | −0.3153 |
| 0 | 2 | 13 | 17 | 9 | 2 | −0.0383 | −0.1016 |
| 0 | 1 | 14 | 5 | 11 | 2 | 0.6563 | 0.2455 |
| 0 | 1 | 15 | 7 | 12 | 5 | 0.5571 | −0.0469 |
| 0 | 3 | 16 | 6 | 14 | 2 | −0.5525 | −1 |
| 0 | 2 | 17 | 3 | 23 | 3 | −0.5518 | −0.1334 |
| 0 | 1 | 18 | 3 | 25 | 2 | 0.6951 | 0.1440 |
| 0 | 2 | 19 | 5 | 28 | 3 | −0.1218 | 0.0626 |
| 0 | 2 | 2 | 33 | 29 | 3 | −0.0184 | 0.0461 |
| 0 | 1 | 20 | 4 | 30 | 3 | 0.6496 | 0.0363 |
| 0 | 2 | 21 | 4 | 31 | 2 | −0.5239 | −0.0045 |
| 0 | 1 | 22 | 5 | 32 | 2 | 0.6464 | 0.3546 |
| 1 | 1 | 23 | 21 | 5 | 5 | 0.3325 | 0.4993 |
| 1 | 4 | 24 | 7 | 9 | 1 | −0.0504 | 0.6329 |
| 1 | 4 | 25 | 14 | 11 | 2 | 0.1108 | 0.6623 |
| 1 | 1 | 26 | 6 | 12 | 6 | 0.6203 | 0.5661 |
| 1 | 1 | 27 | 13 | 14 | 2 | 0.1293 | 0.4353 |
| 1 | 4 | 28 | 6 | 23 | 3 | 0.1494 | 0.2290 |
| 1 | 1 | 29 | 13 | 24 | 2 | 0.5085 | 0.4495 |
| 1 | 2 | 3 | 18 | 31 | 4 | −0.2882 | −0.1638 |
| 2 | 1 | 30 | 11 | 28 | 3 | 0.2164 | −0.0296 |
| 2 | 4 | 31 | 21 | 29 | 3 | 0.0165 | 0.2593 |
| 4 | 1 | 32 | 38 | 23 | 3 | 0.4004 | 0.1628 |
| 5 | 1 | 33 | 48 | 12 | 3 | 0.3249 | 0.2115 |
| 5 | 3 | 4 | 8 | 23 | 3 | −0.4335 | −0.5876 |
| 5 | 3 | 5 | 14 | 27 | 3 | −0.5362 | −0.7094 |
| 6 | 3 | 6 | 13 | 26 | 3 | −0.4075 | −0.7379 |
| 6 | 2 | 7 | 13 | 27 | 2 | −0.1466 | −0.2632 |
| 7 | 1 | 8 | 17 | 26 | 3 | 0.1237 | −0.0736 |
| 7 | 1 | 9 | 3 | 27 | 4 | −0.0040 | 0.3656 |
| 8 | — | — | — | 29 | 3 | — | — |
| 8 | — | — | — | 30 | 3 | — | — |
| 10 | — | — | — | 26 | 1 | — | — |
| 10 | — | — | — | 27 | 2 | — | — |
| 11 | — | — | — | 27 | 1 | — | — |
| 12 | — | — | — | 20 | 2 | — | — |
| 12 | — | — | — | 21 | 2 | — | — |
| 12 | — | — | — | 23 | 3 | — | — |
| 12 | — | — | — | 26 | 2 | — | — |
| 12 | — | — | — | 31 | 4 | — | — |
| 12 | — | — | — | 32 | 5 | — | — |
| 12 | — | — | — | 33 | 1 | — | — |
| 13 | — | — | — | 26 | 3 | — | — |
| 13 | — | — | — | 27 | 1 | — | — |
| 15 | — | — | — | 26 | 2 | — | — |
| 15 | — | — | — | 27 | 3 | — | — |
| 16 | — | — | — | 18 | 5 | — | — |
| 16 | — | — | — | 20 | 4 | — | — |
| 16 | — | — | — | 22 | 3 | — | — |
| 16 | — | — | — | 26 | 5 | — | — |
| 16 | — | — | — | 27 | 4 | — | — |
| 17 | — | — | — | 18 | 2 | — | — |
| 17 | — | — | — | 20 | 3 | — | — |
| 17 | — | — | — | 25 | 2 | — | — |
| 18 | — | — | — | 25 | 7 | — | — |
| 19 | — | — | — | 22 | 4 | — | — |
First 60 of 78 rows.
Nodes sorted by community: dense blocks on the diagonal are communities.
View data
| Column | Community | Node | Order | Row | Weight |
|---|---|---|---|---|---|
| 1 | 2 | 0 | 27 | 0 | 4 |
| 2 | 2 | 1 | 26 | 0 | 2 |
| 3 | 3 | 10 | 16 | 0 | 3 |
| 4 | 2 | 11 | 32 | 0 | 1 |
| 5 | 2 | 12 | 20 | 0 | 3 |
| 9 | 2 | 13 | 22 | 0 | 2 |
| 11 | 1 | 14 | 24 | 0 | 2 |
| 12 | 1 | 15 | 7 | 0 | 5 |
| 14 | 3 | 16 | 19 | 0 | 2 |
| 23 | 2 | 17 | 6 | 0 | 3 |
| 25 | 1 | 18 | 15 | 0 | 2 |
| 28 | 2 | 19 | 13 | 0 | 3 |
| 29 | 2 | 2 | 10 | 0 | 3 |
| 30 | 1 | 20 | 33 | 0 | 3 |
| 31 | 2 | 21 | 0 | 0 | 2 |
| 32 | 1 | 22 | 12 | 0 | 2 |
| 5 | 1 | 23 | 1 | 1 | 5 |
| 9 | 4 | 24 | 23 | 1 | 1 |
| 11 | 4 | 25 | 5 | 1 | 2 |
| 12 | 1 | 26 | 31 | 1 | 6 |
| 14 | 1 | 27 | 11 | 1 | 2 |
| 23 | 4 | 28 | 4 | 1 | 3 |
| 24 | 1 | 29 | 14 | 1 | 2 |
| 31 | 2 | 3 | 3 | 1 | 4 |
| 28 | 1 | 30 | 9 | 2 | 3 |
| 29 | 4 | 31 | 29 | 2 | 3 |
| 23 | 1 | 32 | 30 | 4 | 3 |
| 12 | 1 | 33 | 2 | 5 | 3 |
| 23 | 3 | 4 | 28 | 5 | 3 |
| 27 | 3 | 5 | 8 | 5 | 3 |
| 26 | 3 | 6 | 25 | 6 | 3 |
| 27 | 2 | 7 | 18 | 6 | 2 |
| 26 | 1 | 8 | 17 | 7 | 3 |
| 27 | 1 | 9 | 21 | 7 | 4 |
| 29 | — | — | — | 8 | 3 |
| 30 | — | — | — | 8 | 3 |
| 26 | — | — | — | 10 | 1 |
| 27 | — | — | — | 10 | 2 |
| 27 | — | — | — | 11 | 1 |
| 20 | — | — | — | 12 | 2 |
| 21 | — | — | — | 12 | 2 |
| 23 | — | — | — | 12 | 3 |
| 26 | — | — | — | 12 | 2 |
| 31 | — | — | — | 12 | 4 |
| 32 | — | — | — | 12 | 5 |
| 33 | — | — | — | 12 | 1 |
| 26 | — | — | — | 13 | 3 |
| 27 | — | — | — | 13 | 1 |
| 26 | — | — | — | 15 | 2 |
| 27 | — | — | — | 15 | 3 |
| 18 | — | — | — | 16 | 5 |
| 20 | — | — | — | 16 | 4 |
| 22 | — | — | — | 16 | 3 |
| 26 | — | — | — | 16 | 5 |
| 27 | — | — | — | 16 | 4 |
| 18 | — | — | — | 17 | 2 |
| 20 | — | — | — | 17 | 3 |
| 25 | — | — | — | 17 | 2 |
| 25 | — | — | — | 18 | 7 |
| 22 | — | — | — | 19 | 4 |
First 60 of 78 rows.
View data
| Community |
|---|
| 2 |
| 2 |
| 3 |
| 2 |
| 2 |
| 2 |
| 1 |
| 1 |
| 3 |
| 2 |
| 1 |
| 2 |
| 2 |
| 1 |
| 2 |
| 1 |
| 1 |
| 4 |
| 4 |
| 1 |
| 1 |
| 4 |
| 1 |
| 2 |
| 1 |
| 4 |
| 1 |
| 1 |
| 3 |
| 3 |
| 3 |
| 2 |
| 1 |
| 1 |
Communities
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 14 | 41.2% | 0.1856 | yes | 33, 32, 23 |
| 2 | 11 | 32.4% | 0.1930 | yes | 0, 2, 1 |
| 3 | 5 | 14.7% | 0.2245 | yes | 5, 6, 10 |
| 4 | 4 | 11.8% | 0.4583 | yes | 31, 25, 24 |
Communities at other settings (resolution)
| Resolution | Communities | Modularity |
|---|---|---|
| 0.2500 | 2 | 0.4036 |
| 0.5000 | 2 | 0.4036 |
| 1 | 4 | 0.4439 |
| 2 | 7 | 0.3443 |
| 4 | 11 | 0.2475 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec ac1d3322b978860b
# Dataset: graph_karate (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ml_comm_*(): twin of codesplash.ml.communities
ALGO <- "louvain"
QUALITY <- "modularity"
RESOLUTION <- NULL
INFLATION <- 2
TRIALS <- 5L
DIRECTED <- FALSE
SWEEP <- TRUE
SEED <- 42
LABELS <- c(leiden = "Leiden", louvain = "Louvain", label_propagation = "Label propagation", mcl = "Markov clustering", infomap = "Infomap")
LIMITS <- list(infomap = c(10000, 100000), mcl = c(5000, 50000)) # (nodes, edges); the others 20,000 / 200,000
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.communities/louvain_karate_weighted/out-r")
warnings <- list()
values <- list(algorithm_label = LABELS[[ALGO]])
tables <- list()
charts <- list()
artifacts <- list()
# %% The network the host built (canonical node order, merged edges; cs_graph_read)
G <- cs_graph_read(out)
warnings <- c(warnings, as.list(G$warnings))
N <- G$n
pairs <- cs_graph_undirected_pairs(G)
g <- cs_ml_comm_graph(N, pairs$a + 1L, pairs$b + 1L, pairs$w) # direction set aside: every edge counts both ways
lim <- if (!is.null(LIMITS[[ALGO]])) LIMITS[[ALGO]] else c(20000, 200000)
if (N > lim[1] || length(pairs$a) > lim[2]) {
cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(pairs$a), max_nodes = lim[1], max_edges = lim[2])
}
if (N < 2 || g$m2 <= 0) cs_error("CS_E_UNDEFINED", what = "Communities", reason = "the network needs at least one edge between two different nodes")
if (isTRUE(G$directed) && !(ALGO == "infomap" && isTRUE(DIRECTED))) {
warnings <- c(warnings, sprintf("%s treats every edge as two-way, so the directions were set aside.", LABELS[[ALGO]]))
}
truth <- NULL
if (!is.null(G$label)) truth <- as.character(G$nodes[[G$label]])
values$mode <- "network"
values$n_nodes <- N
values$n_edges <- length(g$idx) %/% 2L
# %% Communities
if (ALGO %in% c("leiden", "louvain")) {
gamma <- if (!is.null(RESOLUTION)) as.numeric(RESOLUTION) else if (QUALITY == "cpm") (g$m2 / 2) / (N * (N - 1) / 2) else 1 # Potts default: the network's density
values$resolution <- gamma
}
find <- function(setting) {
rng <- cs_rng(SEED) # a fresh stream for every setting
if (ALGO == "leiden") return(cs_ml_comm_leiden(g, setting, QUALITY, rng))
if (ALGO == "louvain") return(cs_ml_comm_louvain(g, setting, QUALITY, rng))
if (ALGO == "label_propagation") return(cs_ml_comm_label_propagation(g, rng))
if (ALGO == "mcl") return(cs_ml_comm_mcl(g, setting))
fl <- if (isTRUE(G$directed) && isTRUE(DIRECTED)) cs_ml_comm_flow_directed(cs_ml_comm_dgraph(N, G$si + 1L, G$sj + 1L, G$sw)) else cs_ml_comm_flow_undirected(g)
cs_ml_comm_infomap(fl, rng, TRIALS)
}
setting <- if (ALGO %in% c("leiden", "louvain")) gamma else if (ALGO == "mcl") as.numeric(INFLATION) else NULL
res <- find(setting)
labels <- cs_ml_canonical(res$labels) # 1..k by size, ties by first node
k <- max(labels)
values$k <- k
if (!is.null(res$levels)) values$levels <- res$levels
if (!is.null(res$iterations)) values$iterations <- res$iterations
if (!is.null(res$sweeps)) values$sweeps <- res$sweeps
if (!is.null(res$converged)) {
values$converged <- isTRUE(res$converged)
if (!isTRUE(res$converged)) warnings <- c(warnings, sprintf("%s stopped at its iteration limit before every node settled.", LABELS[[ALGO]]))
}
if (!is.null(res$attractors)) values$attractors <- res$attractors
if (ALGO == "infomap") {
values$codelength <- res$codelength
values$codelength_one <- res$one_module
}
# %% Quality of the partition
values$modularity <- cs_ml_comm_modularity(g, labels, 1)
if (ALGO %in% c("leiden", "louvain")) {
values$quality <- if (QUALITY == "cpm") cs_ml_comm_cpm(g, labels, gamma) else cs_ml_comm_modularity(g, labels, gamma)
}
values$coverage <- cs_ml_comm_coverage(g, labels)
cond <- cs_ml_comm_conductance(g, labels)
finite <- cond[!is.nan(cond)]
if (length(finite)) values$conductance <- mean(finite) else values["conductance"] <- list(NULL)
conn <- cs_ml_comm_connected(g, labels)
values$n_disconnected <- sum(!conn)
if (values$n_disconnected > 0) warnings <- c(warnings, sprintf("%d of %d communities fall apart into separate pieces of the network.", values$n_disconnected, k))
sizes <- tabulate(labels, nbins = k)
for (c in seq_len(k)) values[[sprintf("size[%d]", c)]] <- sizes[c]
values$largest_share <- max(sizes) / N
values$singletons <- sum(sizes == 1)
if (!is.null(truth)) {
ok <- !is.na(truth)
values$n_labeled <- sum(ok)
if (sum(ok) >= 2) {
values$ari <- cs_ml_ari(truth[ok], labels[ok])
values$ami <- cs_ml_ami(truth[ok], labels[ok])
values$nmi <- cs_ml_nmi(truth[ok], labels[ok])
}
}
# %% Settings compared
if (isTRUE(SWEEP) && ALGO %in% c("leiden", "louvain", "mcl")) {
grid <- if (ALGO != "mcl") gamma * c(0.25, 0.5, 1, 2, 4) else c(1.4, 1.6, 2, 2.5, 3, 4)
srows <- list(); ks <- integer(0); qs <- numeric(0)
for (i in seq_along(grid)) {
lab_s <- cs_ml_canonical(find(grid[i])$labels)
ks[i] <- max(lab_s)
qs[i] <- cs_ml_comm_modularity(g, lab_s, 1)
values[[sprintf("sweep_setting[%d]", i)]] <- grid[i]
values[[sprintf("sweep_k[%d]", i)]] <- ks[i]
values[[sprintf("sweep_modularity[%d]", i)]] <- qs[i]
srows[[i]] <- list(setting = grid[i], k = ks[i], modularity = qs[i])
}
what <- if (ALGO == "mcl") "Inflation" else "Resolution"
tables[[length(tables) + 1L]] <- list(
key = "sweep", title = sprintf("Communities at other settings (%s)", tolower(what)),
columns = list(list(key = "setting", label = what, type = "number"), list(key = "k", label = "Communities", type = "integer"),
list(key = "modularity", label = "Modularity", type = "number")),
rows = srows
)
chosen <- abs(grid - setting) < 1e-12
charts[[length(charts) + 1L]] <- cs_chart(
"sweep", "elbow-plot", sprintf("Communities by %s", tolower(what)),
list(k = cs_col(what, c(grid, grid), "numeric"), score = cs_col("Value", c(ks, qs), "numeric"),
criterion = cs_col("Measure", c(rep("Communities", length(grid)), rep("Modularity", length(grid))), "categorical", c("Communities", "Modularity")),
chosen = cs_col("This run", c(chosen, chosen), "boolean")),
note = sprintf("The ringed point is this run's %s.", tolower(what))
)
}
# %% Communities table
crows <- list()
for (c in seq_len(k)) {
members <- which(labels == c)
top <- members[order(-g$k[members], members)][seq_len(min(3L, length(members)))]
crows[[c]] <- list(community = c, size = sizes[c], share = sizes[c] / N,
conductance = if (is.nan(cond[c])) NULL else cond[c], connected = conn[c],
examples = paste(G$node_id[top], collapse = ", "))
}
tables <- c(list(list(
key = "communities", title = "Communities",
columns = list(list(key = "community", label = "Community", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
list(key = "share", label = "Share", type = "percent"), list(key = "conductance", label = "Conductance", type = "number"),
list(key = "connected", label = "In one piece", type = "boolean"), list(key = "examples", label = "Best-connected nodes")),
rows = crows
)), tables)
# %% Results per node (or row) and charts
level_names <- as.character(seq_len(k))
artifacts[[length(artifacts) + 1L]] <- cs_graph_write_nodes(out, G, data.frame(community = as.integer(labels), strength = g$k))
MAP_NODES <- 2000; MATRIX_NODES <- 300
if (N <= MAP_NODES) {
xy <- cs_graph_layout_fr(G, SEED)
m <- length(G$si)
show <- min(m, 20000)
keep <- seq_len(show)
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(
x = cs_col("x", xy$x, "numeric"),
y = cs_col("y", xy$y, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
size = cs_col("Strength", g$k, "numeric"),
group = cs_col("Community", as.character(labels), "categorical", level_names),
from = cs_col("From", G$si[keep], "numeric"),
to = cs_col("To", G$sj[keep], "numeric"),
weight = if (isTRUE(G$weighted)) cs_col("Weight", G$sw[keep], "numeric") else NULL
), controls = list(directed = isTRUE(G$directed)), note = if (show == m) NULL else sprintf("%d of %d edges drawn.", show, m))
} else {
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(), note = sprintf("The map is drawn for networks up to %d nodes; this one has %d.", MAP_NODES, N))
}
if (N <= MATRIX_NODES) {
morder <- order(labels, -g$k, seq_len(N)) - 1L
charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by community", list(
row = cs_col("Row", G$si, "numeric"),
col = cs_col("Column", G$sj, "numeric"),
value = cs_col(if (isTRUE(G$weighted)) "Weight" else "Edge", G$sw, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
group = cs_col("Community", as.character(labels), "categorical", level_names),
order = cs_col("Order", morder, "numeric")
), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by community: dense blocks on the diagonal are communities.")
}
charts[[length(charts) + 1L]] <- cs_chart("sizes", "bar", "Community sizes", list(x = cs_col("Community", as.character(labels), "categorical", level_names)),
controls = list(top = 30))
# %% Result
what <- if (values$mode == "rows") "rows" else "nodes"
summary <- sprintf("%s found %d communit%s among %s %s; %.0f%% of the edge weight falls inside them (modularity %.3f).",
LABELS[[ALGO]], k, if (k == 1) "y" else "ies", format(N, big.mark = ","), what, 100 * values$coverage, values$modularity)
if (ALGO == "infomap") {
summary <- paste0(summary, sprintf(" The map describes the walk in %.3f bits per step, against %.3f with one module.", values$codelength, values$codelength_one))
}
publish <- list(
title = "Network communities",
engine = cs_engine_info("nanoparquet", "Matrix"),
n = N,
summary = summary,
statistics = list(list(key = "k", label = "Communities", value = k, format = "integer"),
list(key = "modularity", label = "Modularity", value = values$modularity),
list(key = "coverage", label = "Edge weight inside", value = values$coverage, format = "percent")),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = artifacts
)
cs_publish(publish)
Louvain found 4 communities among 34 nodes; 78% of the edge weight falls inside them (modularity 0.444).
- Communities
- 4
- Modularity
- 0.4439
- Edge weight inside
- 77.9%
To keep this page light, the plots are shown once, under the R tab.
Communities
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 14 | 41.2% | 0.1856 | yes | 33, 32, 23 |
| 2 | 11 | 32.4% | 0.1930 | yes | 0, 2, 1 |
| 3 | 5 | 14.7% | 0.2245 | yes | 5, 6, 10 |
| 4 | 4 | 11.8% | 0.4583 | yes | 31, 25, 24 |
Communities at other settings (resolution)
| Resolution | Communities | Modularity |
|---|---|---|
| 0.2500 | 2 | 0.4036 |
| 0.5000 | 2 | 0.4036 |
| 1 | 4 | 0.4439 |
| 2 | 7 | 0.3443 |
| 4 | 11 | 0.2475 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec ac1d3322b978860b
# Dataset: graph_karate (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
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 communities as cm # twin of codesplashr R/ml_communities.R
from codesplash.stats.rng import Rng
ALGO = "louvain"
QUALITY = "modularity"
RESOLUTION = None
INFLATION = 2
TRIALS = 5
DIRECTED = False
SWEEP = True
SEED = 42
LABELS = {"leiden": "Leiden", "louvain": "Louvain", "label_propagation": "Label propagation", "mcl": "Markov clustering", "infomap": "Infomap"}
LIMITS = {"infomap": (10000, 100000), "mcl": (5000, 50000)} # (nodes, edges); the others 20,000 / 200,000
out = csml.out_dir("target/academy-parity/run-8142/discover.communities/louvain_karate_weighted/out-python")
warnings = []
values = {"algorithm_label": LABELS[ALGO]}
tables = []
charts = []
artifacts = []
# %% The network the host built (canonical node order, merged edges; codesplash.graph)
from codesplash import graph as cg
from codesplash.graph import layout as gl
G = cg.read(out)
warnings += list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G)
g = cm.undirected(N, a, b, w) # direction set aside: every edge counts both ways
max_nodes, max_edges = LIMITS.get(ALGO, (20000, 200000))
if N > max_nodes or len(a) > max_edges:
cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=max_nodes, max_edges=max_edges)
if N < 2 or g.m2 <= 0:
cs.cs_error("CS_E_UNDEFINED", what="Communities", reason="the network needs at least one edge between two different nodes")
if G.directed and not (ALGO == "infomap" and DIRECTED):
warnings.append(f"{LABELS[ALGO]} treats every edge as two-way, so the directions were set aside.")
truth = None
if G.label:
truth = np.array([None if pd.isna(v) else str(v) for v in G.nodes[G.label].tolist()], dtype=object) # None, NaN, pd.NA
values["mode"] = "network"
values["n_nodes"] = N
values["n_edges"] = g.n_edges
# %% Communities
if ALGO in ("leiden", "louvain"):
if RESOLUTION is not None:
gamma = float(RESOLUTION)
elif QUALITY == "cpm":
gamma = (g.m2 / 2.0) / (N * (N - 1) / 2.0) # the network's density (edge weight per pair of nodes)
else:
gamma = 1.0
values["resolution"] = gamma
def find(setting):
"""Communities for one setting (resolution or inflation), from a fresh stream → (labels, info)."""
rng = Rng(SEED)
if ALGO == "leiden":
r = cm.leiden(g, setting, QUALITY, rng)
elif ALGO == "louvain":
r = cm.louvain(g, setting, QUALITY, rng)
elif ALGO == "label_propagation":
r = cm.label_propagation(g, rng)
elif ALGO == "mcl":
r = cm.mcl(g, setting)
else:
fl = cm.flow_directed(cm.DGraph(N, G.si, G.sj, G.sw)) if (G.directed and DIRECTED) else cm.flow_undirected(g)
r = cm.infomap(fl, rng, TRIALS)
return r
setting = gamma if ALGO in ("leiden", "louvain") else (float(INFLATION) if ALGO == "mcl" else None)
res = find(setting)
labels = csc.canonical(np.asarray(res["labels"], dtype=np.int64)) # 1…k by size, ties by first node
lab0 = (labels - 1).tolist()
k = int(labels.max())
values["k"] = k
if "levels" in res:
values["levels"] = res["levels"]
if "iterations" in res:
values["iterations"] = res["iterations"]
if "sweeps" in res:
values["sweeps"] = res["sweeps"]
if "converged" in res:
values["converged"] = bool(res["converged"])
if not res["converged"]:
warnings.append(f"{LABELS[ALGO]} stopped at its iteration limit before every node settled.")
if "attractors" in res:
values["attractors"] = res["attractors"]
if ALGO == "infomap":
values["codelength"] = res["codelength"]
values["codelength_one"] = res["one_module"]
# %% Quality of the partition
values["modularity"] = cm.modularity(g, lab0, 1.0)
if ALGO in ("leiden", "louvain"):
values["quality"] = cm.cpm(g, lab0, gamma) if QUALITY == "cpm" else cm.modularity(g, lab0, gamma)
values["coverage"] = cm.coverage(g, lab0)
cond = cm.conductance(g, lab0)
finite = [c for c in cond if c == c]
values["conductance"] = float(np.mean(finite)) if finite else None
conn = cm.connected(g, lab0)
values["n_disconnected"] = int(sum(1 for x in conn if not x))
if values["n_disconnected"]:
warnings.append(f"{values['n_disconnected']} of {k} communities fall apart into separate pieces of the network.")
sizes = np.bincount(labels, minlength=k + 1)[1:]
for c in range(1, k + 1):
values[f"size[{c}]"] = int(sizes[c - 1])
values["largest_share"] = float(sizes.max() / N)
values["singletons"] = int(np.sum(sizes == 1))
if truth is not None:
ok = np.array([v is not None for v in truth])
values["n_labeled"] = int(ok.sum())
if ok.sum() >= 2:
tt = truth[ok].astype(str)
values["ari"] = csc.ari(tt, labels[ok])
values["ami"] = csc.ami(tt, labels[ok])
values["nmi"] = csc.nmi(tt, labels[ok])
# %% Settings compared
if SWEEP and ALGO in ("leiden", "louvain", "mcl"):
grid = [gamma * f for f in (0.25, 0.5, 1.0, 2.0, 4.0)] if ALGO != "mcl" else [1.4, 1.6, 2.0, 2.5, 3.0, 4.0]
srows = []
for i, s in enumerate(grid, start=1):
lab_s = csc.canonical(np.asarray(find(s)["labels"], dtype=np.int64))
ks = int(lab_s.max())
qs = cm.modularity(g, (lab_s - 1).tolist(), 1.0)
values[f"sweep_setting[{i}]"] = s
values[f"sweep_k[{i}]"] = ks
values[f"sweep_modularity[{i}]"] = qs
srows.append({"setting": s, "k": ks, "modularity": qs})
what = "Inflation" if ALGO == "mcl" else "Resolution"
tables.append({
"key": "sweep", "title": f"Communities at other settings ({what.lower()})",
"columns": [{"key": "setting", "label": what, "type": "number"}, {"key": "k", "label": "Communities", "type": "integer"},
{"key": "modularity", "label": "Modularity", "type": "number"}],
"rows": srows,
})
chosen = [abs(s - setting) < 1e-12 for s in grid]
charts.append(cs.chart(
"sweep", "elbow-plot", f"Communities by {what.lower()}",
{"k": cs.col(what, grid + grid, "numeric"), "score": cs.col("Value", [r["k"] for r in srows] + [r["modularity"] for r in srows], "numeric"),
"criterion": cs.col("Measure", ["Communities"] * len(grid) + ["Modularity"] * len(grid), "categorical", ["Communities", "Modularity"]),
"chosen": cs.col("This run", chosen + chosen, "boolean")},
note=f"The ringed point is this run's {what.lower()}.",
))
# %% Communities table
crows = []
for c in range(1, k + 1):
members = np.flatnonzero(labels == c)
top = sorted(members.tolist(), key=lambda v: (-g.k[v], v))[:3]
crows.append({"community": c, "size": int(sizes[c - 1]), "share": float(sizes[c - 1] / N),
"conductance": cond[c - 1] if cond[c - 1] == cond[c - 1] else None, "connected": bool(conn[c - 1]),
"examples": ", ".join(G.node_id[v] for v in top)})
tables.insert(0, {
"key": "communities", "title": "Communities",
"columns": [{"key": "community", "label": "Community", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
{"key": "share", "label": "Share", "type": "percent"}, {"key": "conductance", "label": "Conductance", "type": "number"},
{"key": "connected", "label": "In one piece", "type": "boolean"}, {"key": "examples", "label": "Best-connected nodes"}],
"rows": crows,
})
# %% Results per node (or row) and charts
level_names = [str(c) for c in range(1, k + 1)]
cols = {"community": labels.astype(np.int64), "strength": np.asarray(g.k, dtype=np.float64)}
artifacts.append(cg.write_nodes(out, G, cols))
MAP_NODES, MATRIX_NODES = 2000, 300
if N <= MAP_NODES:
xy = gl.fruchterman_reingold(G, SEED)
m = len(G.si)
show = min(m, 20000)
charts.append(cs.chart("map", "network-graph", "Communities in the network", {
"x": cs.col("x", xy[0], "numeric"),
"y": cs.col("y", xy[1], "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"size": cs.col("Strength", g.k, "numeric"),
"group": cs.col("Community", [str(c) for c in labels], "categorical", level_names),
"from": cs.col("From", G.si[:show], "numeric"),
"to": cs.col("To", G.sj[:show], "numeric"),
"weight": cs.col("Weight", G.sw[:show], "numeric") if G.weighted else None,
}, controls={"directed": G.directed}, note=None if show == m else f"{show} of {m} edges drawn."))
else:
charts.append(cs.chart("map", "network-graph", "Communities in the network", {}, note=f"The map is drawn for networks up to {MAP_NODES} nodes; this one has {N}."))
if N <= MATRIX_NODES:
morder = sorted(range(N), key=lambda v: (int(labels[v]), -g.k[v], v))
charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by community", {
"row": cs.col("Row", G.si, "numeric"),
"col": cs.col("Column", G.sj, "numeric"),
"value": cs.col("Weight" if G.weighted else "Edge", G.sw, "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"group": cs.col("Community", [str(c) for c in labels], "categorical", level_names),
"order": cs.col("Order", morder, "numeric"),
}, controls={"directed": G.directed}, note="Nodes sorted by community: dense blocks on the diagonal are communities."))
charts.append(cs.chart("sizes", "bar", "Community sizes", {"x": cs.col("Community", [str(c) for c in labels], "categorical", level_names)},
controls={"top": 30}))
# %% Result
what = "rows" if values["mode"] == "rows" else "nodes"
summary = (f"{LABELS[ALGO]} found {k} communit{'y' if k == 1 else 'ies'} among {N:,} {what}; "
f"{values['coverage']:.0%} of the edge weight falls inside them (modularity {values['modularity']:.3f}).")
if ALGO == "infomap":
summary += f" The map describes the walk in {values['codelength']:.3f} bits per step, against {values['codelength_one']:.3f} with one module."
publish = {
"title": "Network communities",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": N,
"summary": summary,
"statistics": [
{"key": "k", "label": "Communities", "value": k, "format": "integer"},
{"key": "modularity", "label": "Modularity", "value": values["modularity"]},
{"key": "coverage", "label": "Edge weight inside", "value": values["coverage"], "format": "percent"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": artifacts,
}
cs.publish(publish)
View data
| number of clusters k | score | criterion | recommended |
|---|---|---|---|
| 2 | 1009.44 | within-cluster SS | false |
| 2 | 0.4790 | silhouette | false |
| 2 | 1.406 | gap statistic | false |
| 3 | 604.67 | within-cluster SS | false |
| 3 | 0.5390 | silhouette | false |
| 3 | 1.667 | gap statistic | false |
| 4 | 266.55 | within-cluster SS | true |
| 4 | 0.5690 | silhouette | true |
| 4 | 1.883 | gap statistic | true |
| 5 | 212.94 | within-cluster SS | false |
| 5 | 0.5610 | silhouette | false |
| 5 | 1.900 | gap statistic | false |
| 6 | 172.92 | within-cluster SS | false |
| 6 | 0.4890 | silhouette | false |
| 6 | 1.880 | gap statistic | false |
| 7 | 158.52 | within-cluster SS | false |
| 7 | 0.4350 | silhouette | false |
| 7 | 1.844 | gap statistic | false |
| 8 | 143.15 | within-cluster SS | false |
| 8 | 0.3800 | silhouette | false |
| 8 | 1.835 | gap statistic | false |
| 9 | 125.91 | within-cluster SS | false |
| 9 | 0.3080 | silhouette | false |
| 9 | 1.793 | gap statistic | false |
Other ways to find communities
Read- Label propagationLabel propagationEvery node starts with its own label and repeatedly takes the label most of its neighbors carry, until nothing changes.: each node takes the label most of its neighbors carry. Fast, no resolution, but weak communities can merge into one.
- Markov clusteringMarkov clusteringAlternately spreads a random walk (expansion) and sharpens it (inflation); walks end trapped in dense groups, the clusters.: random walks spread out (expansion) and are sharpened (inflation) until they stay trapped in dense groups.
Markov clustering found 2 communities among 34 nodes; 87% of the edge weight falls inside them (modularity 0.371).
- Communities
- 2
- Modularity
- 0.3715
- Edge weight inside
- 87.2%
Plots
The ringed point is this run's inflation.
View data
| This run | Measure | Inflation | Value |
|---|---|---|---|
| false | Communities | 1.400 | 1 |
| false | Communities | 1.600 | 2 |
| false | Communities | 2 | 2 |
| false | Communities | 2.500 | 3 |
| false | Communities | 3 | 4 |
| false | Communities | 4 | 6 |
| false | Modularity | 1.400 | 0 |
| false | Modularity | 1.600 | 0.3715 |
| false | Modularity | 2 | 0.3600 |
| false | Modularity | 2.500 | 0.3728 |
| false | Modularity | 3 | 0.3586 |
| false | Modularity | 4 | 0.3632 |
View data
| From | Community | Node | Strength | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 2 | 0 | 16 | 1 | −0.3181 | −0.2545 |
| 0 | 2 | 1 | 9 | 2 | −0.2233 | −0.0757 |
| 0 | 2 | 10 | 3 | 3 | −0.5988 | −0.5538 |
| 0 | 2 | 11 | 1 | 4 | −0.7684 | −0.3116 |
| 0 | 2 | 12 | 2 | 5 | −0.5555 | −0.3153 |
| 0 | 2 | 13 | 5 | 9 | −0.0383 | −0.1016 |
| 0 | 1 | 14 | 2 | 11 | 0.6563 | 0.2455 |
| 0 | 1 | 15 | 2 | 12 | 0.5571 | −0.0469 |
| 0 | 2 | 16 | 2 | 14 | −0.5525 | −1 |
| 0 | 2 | 17 | 2 | 23 | −0.5518 | −0.1334 |
| 0 | 1 | 18 | 2 | 25 | 0.6951 | 0.1440 |
| 0 | 2 | 19 | 3 | 28 | −0.1218 | 0.0626 |
| 0 | 2 | 2 | 10 | 29 | −0.0184 | 0.0461 |
| 0 | 1 | 20 | 2 | 30 | 0.6496 | 0.0363 |
| 0 | 2 | 21 | 2 | 31 | −0.5239 | −0.0045 |
| 0 | 1 | 22 | 2 | 32 | 0.6464 | 0.3546 |
| 1 | 1 | 23 | 5 | 5 | 0.3325 | 0.4993 |
| 1 | 1 | 24 | 3 | 9 | −0.0504 | 0.6329 |
| 1 | 1 | 25 | 3 | 11 | 0.1108 | 0.6623 |
| 1 | 1 | 26 | 2 | 12 | 0.6203 | 0.5661 |
| 1 | 1 | 27 | 4 | 14 | 0.1293 | 0.4353 |
| 1 | 1 | 28 | 3 | 23 | 0.1494 | 0.2290 |
| 1 | 1 | 29 | 4 | 24 | 0.5085 | 0.4495 |
| 1 | 2 | 3 | 6 | 31 | −0.2882 | −0.1638 |
| 2 | 1 | 30 | 4 | 28 | 0.2164 | −0.0296 |
| 2 | 1 | 31 | 6 | 29 | 0.0165 | 0.2593 |
| 4 | 1 | 32 | 12 | 23 | 0.4004 | 0.1628 |
| 5 | 1 | 33 | 17 | 12 | 0.3249 | 0.2115 |
| 5 | 2 | 4 | 3 | 23 | −0.4335 | −0.5876 |
| 5 | 2 | 5 | 4 | 27 | −0.5362 | −0.7094 |
| 6 | 2 | 6 | 4 | 26 | −0.4075 | −0.7379 |
| 6 | 2 | 7 | 4 | 27 | −0.1466 | −0.2632 |
| 7 | 1 | 8 | 5 | 26 | 0.1237 | −0.0736 |
| 7 | 1 | 9 | 2 | 27 | −0.0040 | 0.3656 |
| 8 | — | — | — | 29 | — | — |
| 8 | — | — | — | 30 | — | — |
| 10 | — | — | — | 26 | — | — |
| 10 | — | — | — | 27 | — | — |
| 11 | — | — | — | 27 | — | — |
| 12 | — | — | — | 20 | — | — |
| 12 | — | — | — | 21 | — | — |
| 12 | — | — | — | 23 | — | — |
| 12 | — | — | — | 26 | — | — |
| 12 | — | — | — | 31 | — | — |
| 12 | — | — | — | 32 | — | — |
| 12 | — | — | — | 33 | — | — |
| 13 | — | — | — | 26 | — | — |
| 13 | — | — | — | 27 | — | — |
| 15 | — | — | — | 26 | — | — |
| 15 | — | — | — | 27 | — | — |
| 16 | — | — | — | 18 | — | — |
| 16 | — | — | — | 20 | — | — |
| 16 | — | — | — | 22 | — | — |
| 16 | — | — | — | 26 | — | — |
| 16 | — | — | — | 27 | — | — |
| 17 | — | — | — | 18 | — | — |
| 17 | — | — | — | 20 | — | — |
| 17 | — | — | — | 25 | — | — |
| 18 | — | — | — | 25 | — | — |
| 19 | — | — | — | 22 | — | — |
First 60 of 78 rows.
Nodes sorted by community: dense blocks on the diagonal are communities.
View data
| Column | Community | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 1 | 2 | 0 | 27 | 0 | 1 |
| 2 | 2 | 1 | 26 | 0 | 1 |
| 3 | 2 | 10 | 25 | 0 | 1 |
| 4 | 2 | 11 | 16 | 0 | 1 |
| 5 | 2 | 12 | 32 | 0 | 1 |
| 9 | 2 | 13 | 20 | 0 | 1 |
| 11 | 1 | 14 | 22 | 0 | 1 |
| 12 | 1 | 15 | 24 | 0 | 1 |
| 14 | 2 | 16 | 17 | 0 | 1 |
| 23 | 2 | 17 | 18 | 0 | 1 |
| 25 | 1 | 18 | 21 | 0 | 1 |
| 28 | 2 | 19 | 6 | 0 | 1 |
| 29 | 2 | 2 | 7 | 0 | 1 |
| 30 | 1 | 20 | 10 | 0 | 1 |
| 31 | 2 | 21 | 13 | 0 | 1 |
| 32 | 1 | 22 | 15 | 0 | 1 |
| 5 | 1 | 23 | 19 | 1 | 1 |
| 9 | 1 | 24 | 33 | 1 | 1 |
| 11 | 1 | 25 | 0 | 1 | 1 |
| 12 | 1 | 26 | 12 | 1 | 1 |
| 14 | 1 | 27 | 1 | 1 | 1 |
| 23 | 1 | 28 | 23 | 1 | 1 |
| 24 | 1 | 29 | 5 | 1 | 1 |
| 31 | 2 | 3 | 29 | 1 | 1 |
| 28 | 1 | 30 | 30 | 2 | 1 |
| 29 | 1 | 31 | 31 | 2 | 1 |
| 23 | 1 | 32 | 2 | 4 | 1 |
| 12 | 1 | 33 | 11 | 5 | 1 |
| 23 | 2 | 4 | 28 | 5 | 1 |
| 27 | 2 | 5 | 4 | 5 | 1 |
| 26 | 2 | 6 | 8 | 6 | 1 |
| 27 | 2 | 7 | 9 | 6 | 1 |
| 26 | 1 | 8 | 14 | 7 | 1 |
| 27 | 1 | 9 | 3 | 7 | 1 |
| 29 | — | — | — | 8 | 1 |
| 30 | — | — | — | 8 | 1 |
| 26 | — | — | — | 10 | 1 |
| 27 | — | — | — | 10 | 1 |
| 27 | — | — | — | 11 | 1 |
| 20 | — | — | — | 12 | 1 |
| 21 | — | — | — | 12 | 1 |
| 23 | — | — | — | 12 | 1 |
| 26 | — | — | — | 12 | 1 |
| 31 | — | — | — | 12 | 1 |
| 32 | — | — | — | 12 | 1 |
| 33 | — | — | — | 12 | 1 |
| 26 | — | — | — | 13 | 1 |
| 27 | — | — | — | 13 | 1 |
| 26 | — | — | — | 15 | 1 |
| 27 | — | — | — | 15 | 1 |
| 18 | — | — | — | 16 | 1 |
| 20 | — | — | — | 16 | 1 |
| 22 | — | — | — | 16 | 1 |
| 26 | — | — | — | 16 | 1 |
| 27 | — | — | — | 16 | 1 |
| 18 | — | — | — | 17 | 1 |
| 20 | — | — | — | 17 | 1 |
| 25 | — | — | — | 17 | 1 |
| 25 | — | — | — | 18 | 1 |
| 22 | — | — | — | 19 | 1 |
First 60 of 78 rows.
View data
| Community |
|---|
| 2 |
| 2 |
| 2 |
| 2 |
| 2 |
| 2 |
| 1 |
| 1 |
| 2 |
| 2 |
| 1 |
| 2 |
| 2 |
| 1 |
| 2 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 2 |
| 1 |
| 1 |
| 1 |
| 1 |
| 2 |
| 2 |
| 2 |
| 2 |
| 1 |
| 1 |
Communities
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 18 | 52.9% | 0.1316 | yes | 33, 32, 31 |
| 2 | 16 | 47.1% | 0.1316 | yes | 0, 2, 1 |
Communities at other settings (inflation)
| Inflation | Communities | Modularity |
|---|---|---|
| 1.400 | 1 | 0 |
| 1.600 | 2 | 0.3715 |
| 2 | 2 | 0.3600 |
| 2.500 | 3 | 0.3728 |
| 3 | 4 | 0.3586 |
| 4 | 6 | 0.3632 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec 1fb93652fb211128
# Dataset: graph_karate (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ml_comm_*(): twin of codesplash.ml.communities
ALGO <- "mcl"
QUALITY <- "modularity"
RESOLUTION <- NULL
INFLATION <- 1.8
TRIALS <- 5L
DIRECTED <- FALSE
SWEEP <- TRUE
SEED <- 42
LABELS <- c(leiden = "Leiden", louvain = "Louvain", label_propagation = "Label propagation", mcl = "Markov clustering", infomap = "Infomap")
LIMITS <- list(infomap = c(10000, 100000), mcl = c(5000, 50000)) # (nodes, edges); the others 20,000 / 200,000
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.communities/mcl_karate/out-r")
warnings <- list()
values <- list(algorithm_label = LABELS[[ALGO]])
tables <- list()
charts <- list()
artifacts <- list()
# %% The network the host built (canonical node order, merged edges; cs_graph_read)
G <- cs_graph_read(out)
warnings <- c(warnings, as.list(G$warnings))
N <- G$n
pairs <- cs_graph_undirected_pairs(G)
g <- cs_ml_comm_graph(N, pairs$a + 1L, pairs$b + 1L, pairs$w) # direction set aside: every edge counts both ways
lim <- if (!is.null(LIMITS[[ALGO]])) LIMITS[[ALGO]] else c(20000, 200000)
if (N > lim[1] || length(pairs$a) > lim[2]) {
cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(pairs$a), max_nodes = lim[1], max_edges = lim[2])
}
if (N < 2 || g$m2 <= 0) cs_error("CS_E_UNDEFINED", what = "Communities", reason = "the network needs at least one edge between two different nodes")
if (isTRUE(G$directed) && !(ALGO == "infomap" && isTRUE(DIRECTED))) {
warnings <- c(warnings, sprintf("%s treats every edge as two-way, so the directions were set aside.", LABELS[[ALGO]]))
}
truth <- NULL
if (!is.null(G$label)) truth <- as.character(G$nodes[[G$label]])
values$mode <- "network"
values$n_nodes <- N
values$n_edges <- length(g$idx) %/% 2L
# %% Communities
if (ALGO %in% c("leiden", "louvain")) {
gamma <- if (!is.null(RESOLUTION)) as.numeric(RESOLUTION) else if (QUALITY == "cpm") (g$m2 / 2) / (N * (N - 1) / 2) else 1 # Potts default: the network's density
values$resolution <- gamma
}
find <- function(setting) {
rng <- cs_rng(SEED) # a fresh stream for every setting
if (ALGO == "leiden") return(cs_ml_comm_leiden(g, setting, QUALITY, rng))
if (ALGO == "louvain") return(cs_ml_comm_louvain(g, setting, QUALITY, rng))
if (ALGO == "label_propagation") return(cs_ml_comm_label_propagation(g, rng))
if (ALGO == "mcl") return(cs_ml_comm_mcl(g, setting))
fl <- if (isTRUE(G$directed) && isTRUE(DIRECTED)) cs_ml_comm_flow_directed(cs_ml_comm_dgraph(N, G$si + 1L, G$sj + 1L, G$sw)) else cs_ml_comm_flow_undirected(g)
cs_ml_comm_infomap(fl, rng, TRIALS)
}
setting <- if (ALGO %in% c("leiden", "louvain")) gamma else if (ALGO == "mcl") as.numeric(INFLATION) else NULL
res <- find(setting)
labels <- cs_ml_canonical(res$labels) # 1..k by size, ties by first node
k <- max(labels)
values$k <- k
if (!is.null(res$levels)) values$levels <- res$levels
if (!is.null(res$iterations)) values$iterations <- res$iterations
if (!is.null(res$sweeps)) values$sweeps <- res$sweeps
if (!is.null(res$converged)) {
values$converged <- isTRUE(res$converged)
if (!isTRUE(res$converged)) warnings <- c(warnings, sprintf("%s stopped at its iteration limit before every node settled.", LABELS[[ALGO]]))
}
if (!is.null(res$attractors)) values$attractors <- res$attractors
if (ALGO == "infomap") {
values$codelength <- res$codelength
values$codelength_one <- res$one_module
}
# %% Quality of the partition
values$modularity <- cs_ml_comm_modularity(g, labels, 1)
if (ALGO %in% c("leiden", "louvain")) {
values$quality <- if (QUALITY == "cpm") cs_ml_comm_cpm(g, labels, gamma) else cs_ml_comm_modularity(g, labels, gamma)
}
values$coverage <- cs_ml_comm_coverage(g, labels)
cond <- cs_ml_comm_conductance(g, labels)
finite <- cond[!is.nan(cond)]
if (length(finite)) values$conductance <- mean(finite) else values["conductance"] <- list(NULL)
conn <- cs_ml_comm_connected(g, labels)
values$n_disconnected <- sum(!conn)
if (values$n_disconnected > 0) warnings <- c(warnings, sprintf("%d of %d communities fall apart into separate pieces of the network.", values$n_disconnected, k))
sizes <- tabulate(labels, nbins = k)
for (c in seq_len(k)) values[[sprintf("size[%d]", c)]] <- sizes[c]
values$largest_share <- max(sizes) / N
values$singletons <- sum(sizes == 1)
if (!is.null(truth)) {
ok <- !is.na(truth)
values$n_labeled <- sum(ok)
if (sum(ok) >= 2) {
values$ari <- cs_ml_ari(truth[ok], labels[ok])
values$ami <- cs_ml_ami(truth[ok], labels[ok])
values$nmi <- cs_ml_nmi(truth[ok], labels[ok])
}
}
# %% Settings compared
if (isTRUE(SWEEP) && ALGO %in% c("leiden", "louvain", "mcl")) {
grid <- if (ALGO != "mcl") gamma * c(0.25, 0.5, 1, 2, 4) else c(1.4, 1.6, 2, 2.5, 3, 4)
srows <- list(); ks <- integer(0); qs <- numeric(0)
for (i in seq_along(grid)) {
lab_s <- cs_ml_canonical(find(grid[i])$labels)
ks[i] <- max(lab_s)
qs[i] <- cs_ml_comm_modularity(g, lab_s, 1)
values[[sprintf("sweep_setting[%d]", i)]] <- grid[i]
values[[sprintf("sweep_k[%d]", i)]] <- ks[i]
values[[sprintf("sweep_modularity[%d]", i)]] <- qs[i]
srows[[i]] <- list(setting = grid[i], k = ks[i], modularity = qs[i])
}
what <- if (ALGO == "mcl") "Inflation" else "Resolution"
tables[[length(tables) + 1L]] <- list(
key = "sweep", title = sprintf("Communities at other settings (%s)", tolower(what)),
columns = list(list(key = "setting", label = what, type = "number"), list(key = "k", label = "Communities", type = "integer"),
list(key = "modularity", label = "Modularity", type = "number")),
rows = srows
)
chosen <- abs(grid - setting) < 1e-12
charts[[length(charts) + 1L]] <- cs_chart(
"sweep", "elbow-plot", sprintf("Communities by %s", tolower(what)),
list(k = cs_col(what, c(grid, grid), "numeric"), score = cs_col("Value", c(ks, qs), "numeric"),
criterion = cs_col("Measure", c(rep("Communities", length(grid)), rep("Modularity", length(grid))), "categorical", c("Communities", "Modularity")),
chosen = cs_col("This run", c(chosen, chosen), "boolean")),
note = sprintf("The ringed point is this run's %s.", tolower(what))
)
}
# %% Communities table
crows <- list()
for (c in seq_len(k)) {
members <- which(labels == c)
top <- members[order(-g$k[members], members)][seq_len(min(3L, length(members)))]
crows[[c]] <- list(community = c, size = sizes[c], share = sizes[c] / N,
conductance = if (is.nan(cond[c])) NULL else cond[c], connected = conn[c],
examples = paste(G$node_id[top], collapse = ", "))
}
tables <- c(list(list(
key = "communities", title = "Communities",
columns = list(list(key = "community", label = "Community", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
list(key = "share", label = "Share", type = "percent"), list(key = "conductance", label = "Conductance", type = "number"),
list(key = "connected", label = "In one piece", type = "boolean"), list(key = "examples", label = "Best-connected nodes")),
rows = crows
)), tables)
# %% Results per node (or row) and charts
level_names <- as.character(seq_len(k))
artifacts[[length(artifacts) + 1L]] <- cs_graph_write_nodes(out, G, data.frame(community = as.integer(labels), strength = g$k))
MAP_NODES <- 2000; MATRIX_NODES <- 300
if (N <= MAP_NODES) {
xy <- cs_graph_layout_fr(G, SEED)
m <- length(G$si)
show <- min(m, 20000)
keep <- seq_len(show)
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(
x = cs_col("x", xy$x, "numeric"),
y = cs_col("y", xy$y, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
size = cs_col("Strength", g$k, "numeric"),
group = cs_col("Community", as.character(labels), "categorical", level_names),
from = cs_col("From", G$si[keep], "numeric"),
to = cs_col("To", G$sj[keep], "numeric"),
weight = if (isTRUE(G$weighted)) cs_col("Weight", G$sw[keep], "numeric") else NULL
), controls = list(directed = isTRUE(G$directed)), note = if (show == m) NULL else sprintf("%d of %d edges drawn.", show, m))
} else {
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(), note = sprintf("The map is drawn for networks up to %d nodes; this one has %d.", MAP_NODES, N))
}
if (N <= MATRIX_NODES) {
morder <- order(labels, -g$k, seq_len(N)) - 1L
charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by community", list(
row = cs_col("Row", G$si, "numeric"),
col = cs_col("Column", G$sj, "numeric"),
value = cs_col(if (isTRUE(G$weighted)) "Weight" else "Edge", G$sw, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
group = cs_col("Community", as.character(labels), "categorical", level_names),
order = cs_col("Order", morder, "numeric")
), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by community: dense blocks on the diagonal are communities.")
}
charts[[length(charts) + 1L]] <- cs_chart("sizes", "bar", "Community sizes", list(x = cs_col("Community", as.character(labels), "categorical", level_names)),
controls = list(top = 30))
# %% Result
what <- if (values$mode == "rows") "rows" else "nodes"
summary <- sprintf("%s found %d communit%s among %s %s; %.0f%% of the edge weight falls inside them (modularity %.3f).",
LABELS[[ALGO]], k, if (k == 1) "y" else "ies", format(N, big.mark = ","), what, 100 * values$coverage, values$modularity)
if (ALGO == "infomap") {
summary <- paste0(summary, sprintf(" The map describes the walk in %.3f bits per step, against %.3f with one module.", values$codelength, values$codelength_one))
}
publish <- list(
title = "Network communities",
engine = cs_engine_info("nanoparquet", "Matrix"),
n = N,
summary = summary,
statistics = list(list(key = "k", label = "Communities", value = k, format = "integer"),
list(key = "modularity", label = "Modularity", value = values$modularity),
list(key = "coverage", label = "Edge weight inside", value = values$coverage, format = "percent")),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = artifacts
)
cs_publish(publish)
Markov clustering found 2 communities among 34 nodes; 87% of the edge weight falls inside them (modularity 0.371).
- Communities
- 2
- Modularity
- 0.3715
- Edge weight inside
- 87.2%
To keep this page light, the plots are shown once, under the R tab.
Communities
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 18 | 52.9% | 0.1316 | yes | 33, 32, 31 |
| 2 | 16 | 47.1% | 0.1316 | yes | 0, 2, 1 |
Communities at other settings (inflation)
| Inflation | Communities | Modularity |
|---|---|---|
| 1.400 | 1 | 0 |
| 1.600 | 2 | 0.3715 |
| 2 | 2 | 0.3600 |
| 2.500 | 3 | 0.3728 |
| 3 | 4 | 0.3586 |
| 4 | 6 | 0.3632 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec 1fb93652fb211128
# Dataset: graph_karate (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
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 communities as cm # twin of codesplashr R/ml_communities.R
from codesplash.stats.rng import Rng
ALGO = "mcl"
QUALITY = "modularity"
RESOLUTION = None
INFLATION = 1.8
TRIALS = 5
DIRECTED = False
SWEEP = True
SEED = 42
LABELS = {"leiden": "Leiden", "louvain": "Louvain", "label_propagation": "Label propagation", "mcl": "Markov clustering", "infomap": "Infomap"}
LIMITS = {"infomap": (10000, 100000), "mcl": (5000, 50000)} # (nodes, edges); the others 20,000 / 200,000
out = csml.out_dir("target/academy-parity/run-8142/discover.communities/mcl_karate/out-python")
warnings = []
values = {"algorithm_label": LABELS[ALGO]}
tables = []
charts = []
artifacts = []
# %% The network the host built (canonical node order, merged edges; codesplash.graph)
from codesplash import graph as cg
from codesplash.graph import layout as gl
G = cg.read(out)
warnings += list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G)
g = cm.undirected(N, a, b, w) # direction set aside: every edge counts both ways
max_nodes, max_edges = LIMITS.get(ALGO, (20000, 200000))
if N > max_nodes or len(a) > max_edges:
cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=max_nodes, max_edges=max_edges)
if N < 2 or g.m2 <= 0:
cs.cs_error("CS_E_UNDEFINED", what="Communities", reason="the network needs at least one edge between two different nodes")
if G.directed and not (ALGO == "infomap" and DIRECTED):
warnings.append(f"{LABELS[ALGO]} treats every edge as two-way, so the directions were set aside.")
truth = None
if G.label:
truth = np.array([None if pd.isna(v) else str(v) for v in G.nodes[G.label].tolist()], dtype=object) # None, NaN, pd.NA
values["mode"] = "network"
values["n_nodes"] = N
values["n_edges"] = g.n_edges
# %% Communities
if ALGO in ("leiden", "louvain"):
if RESOLUTION is not None:
gamma = float(RESOLUTION)
elif QUALITY == "cpm":
gamma = (g.m2 / 2.0) / (N * (N - 1) / 2.0) # the network's density (edge weight per pair of nodes)
else:
gamma = 1.0
values["resolution"] = gamma
def find(setting):
"""Communities for one setting (resolution or inflation), from a fresh stream → (labels, info)."""
rng = Rng(SEED)
if ALGO == "leiden":
r = cm.leiden(g, setting, QUALITY, rng)
elif ALGO == "louvain":
r = cm.louvain(g, setting, QUALITY, rng)
elif ALGO == "label_propagation":
r = cm.label_propagation(g, rng)
elif ALGO == "mcl":
r = cm.mcl(g, setting)
else:
fl = cm.flow_directed(cm.DGraph(N, G.si, G.sj, G.sw)) if (G.directed and DIRECTED) else cm.flow_undirected(g)
r = cm.infomap(fl, rng, TRIALS)
return r
setting = gamma if ALGO in ("leiden", "louvain") else (float(INFLATION) if ALGO == "mcl" else None)
res = find(setting)
labels = csc.canonical(np.asarray(res["labels"], dtype=np.int64)) # 1…k by size, ties by first node
lab0 = (labels - 1).tolist()
k = int(labels.max())
values["k"] = k
if "levels" in res:
values["levels"] = res["levels"]
if "iterations" in res:
values["iterations"] = res["iterations"]
if "sweeps" in res:
values["sweeps"] = res["sweeps"]
if "converged" in res:
values["converged"] = bool(res["converged"])
if not res["converged"]:
warnings.append(f"{LABELS[ALGO]} stopped at its iteration limit before every node settled.")
if "attractors" in res:
values["attractors"] = res["attractors"]
if ALGO == "infomap":
values["codelength"] = res["codelength"]
values["codelength_one"] = res["one_module"]
# %% Quality of the partition
values["modularity"] = cm.modularity(g, lab0, 1.0)
if ALGO in ("leiden", "louvain"):
values["quality"] = cm.cpm(g, lab0, gamma) if QUALITY == "cpm" else cm.modularity(g, lab0, gamma)
values["coverage"] = cm.coverage(g, lab0)
cond = cm.conductance(g, lab0)
finite = [c for c in cond if c == c]
values["conductance"] = float(np.mean(finite)) if finite else None
conn = cm.connected(g, lab0)
values["n_disconnected"] = int(sum(1 for x in conn if not x))
if values["n_disconnected"]:
warnings.append(f"{values['n_disconnected']} of {k} communities fall apart into separate pieces of the network.")
sizes = np.bincount(labels, minlength=k + 1)[1:]
for c in range(1, k + 1):
values[f"size[{c}]"] = int(sizes[c - 1])
values["largest_share"] = float(sizes.max() / N)
values["singletons"] = int(np.sum(sizes == 1))
if truth is not None:
ok = np.array([v is not None for v in truth])
values["n_labeled"] = int(ok.sum())
if ok.sum() >= 2:
tt = truth[ok].astype(str)
values["ari"] = csc.ari(tt, labels[ok])
values["ami"] = csc.ami(tt, labels[ok])
values["nmi"] = csc.nmi(tt, labels[ok])
# %% Settings compared
if SWEEP and ALGO in ("leiden", "louvain", "mcl"):
grid = [gamma * f for f in (0.25, 0.5, 1.0, 2.0, 4.0)] if ALGO != "mcl" else [1.4, 1.6, 2.0, 2.5, 3.0, 4.0]
srows = []
for i, s in enumerate(grid, start=1):
lab_s = csc.canonical(np.asarray(find(s)["labels"], dtype=np.int64))
ks = int(lab_s.max())
qs = cm.modularity(g, (lab_s - 1).tolist(), 1.0)
values[f"sweep_setting[{i}]"] = s
values[f"sweep_k[{i}]"] = ks
values[f"sweep_modularity[{i}]"] = qs
srows.append({"setting": s, "k": ks, "modularity": qs})
what = "Inflation" if ALGO == "mcl" else "Resolution"
tables.append({
"key": "sweep", "title": f"Communities at other settings ({what.lower()})",
"columns": [{"key": "setting", "label": what, "type": "number"}, {"key": "k", "label": "Communities", "type": "integer"},
{"key": "modularity", "label": "Modularity", "type": "number"}],
"rows": srows,
})
chosen = [abs(s - setting) < 1e-12 for s in grid]
charts.append(cs.chart(
"sweep", "elbow-plot", f"Communities by {what.lower()}",
{"k": cs.col(what, grid + grid, "numeric"), "score": cs.col("Value", [r["k"] for r in srows] + [r["modularity"] for r in srows], "numeric"),
"criterion": cs.col("Measure", ["Communities"] * len(grid) + ["Modularity"] * len(grid), "categorical", ["Communities", "Modularity"]),
"chosen": cs.col("This run", chosen + chosen, "boolean")},
note=f"The ringed point is this run's {what.lower()}.",
))
# %% Communities table
crows = []
for c in range(1, k + 1):
members = np.flatnonzero(labels == c)
top = sorted(members.tolist(), key=lambda v: (-g.k[v], v))[:3]
crows.append({"community": c, "size": int(sizes[c - 1]), "share": float(sizes[c - 1] / N),
"conductance": cond[c - 1] if cond[c - 1] == cond[c - 1] else None, "connected": bool(conn[c - 1]),
"examples": ", ".join(G.node_id[v] for v in top)})
tables.insert(0, {
"key": "communities", "title": "Communities",
"columns": [{"key": "community", "label": "Community", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
{"key": "share", "label": "Share", "type": "percent"}, {"key": "conductance", "label": "Conductance", "type": "number"},
{"key": "connected", "label": "In one piece", "type": "boolean"}, {"key": "examples", "label": "Best-connected nodes"}],
"rows": crows,
})
# %% Results per node (or row) and charts
level_names = [str(c) for c in range(1, k + 1)]
cols = {"community": labels.astype(np.int64), "strength": np.asarray(g.k, dtype=np.float64)}
artifacts.append(cg.write_nodes(out, G, cols))
MAP_NODES, MATRIX_NODES = 2000, 300
if N <= MAP_NODES:
xy = gl.fruchterman_reingold(G, SEED)
m = len(G.si)
show = min(m, 20000)
charts.append(cs.chart("map", "network-graph", "Communities in the network", {
"x": cs.col("x", xy[0], "numeric"),
"y": cs.col("y", xy[1], "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"size": cs.col("Strength", g.k, "numeric"),
"group": cs.col("Community", [str(c) for c in labels], "categorical", level_names),
"from": cs.col("From", G.si[:show], "numeric"),
"to": cs.col("To", G.sj[:show], "numeric"),
"weight": cs.col("Weight", G.sw[:show], "numeric") if G.weighted else None,
}, controls={"directed": G.directed}, note=None if show == m else f"{show} of {m} edges drawn."))
else:
charts.append(cs.chart("map", "network-graph", "Communities in the network", {}, note=f"The map is drawn for networks up to {MAP_NODES} nodes; this one has {N}."))
if N <= MATRIX_NODES:
morder = sorted(range(N), key=lambda v: (int(labels[v]), -g.k[v], v))
charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by community", {
"row": cs.col("Row", G.si, "numeric"),
"col": cs.col("Column", G.sj, "numeric"),
"value": cs.col("Weight" if G.weighted else "Edge", G.sw, "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"group": cs.col("Community", [str(c) for c in labels], "categorical", level_names),
"order": cs.col("Order", morder, "numeric"),
}, controls={"directed": G.directed}, note="Nodes sorted by community: dense blocks on the diagonal are communities."))
charts.append(cs.chart("sizes", "bar", "Community sizes", {"x": cs.col("Community", [str(c) for c in labels], "categorical", level_names)},
controls={"top": 30}))
# %% Result
what = "rows" if values["mode"] == "rows" else "nodes"
summary = (f"{LABELS[ALGO]} found {k} communit{'y' if k == 1 else 'ies'} among {N:,} {what}; "
f"{values['coverage']:.0%} of the edge weight falls inside them (modularity {values['modularity']:.3f}).")
if ALGO == "infomap":
summary += f" The map describes the walk in {values['codelength']:.3f} bits per step, against {values['codelength_one']:.3f} with one module."
publish = {
"title": "Network communities",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": N,
"summary": summary,
"statistics": [
{"key": "k", "label": "Communities", "value": k, "format": "integer"},
{"key": "modularity", "label": "Modularity", "value": values["modularity"]},
{"key": "coverage", "label": "Edge weight inside", "value": values["coverage"], "format": "percent"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": artifacts,
}
cs.publish(publish)
With inflation a little below the usual 2, MCL splits the club into 2 clusters, close to the real split.
- InfomapMap equationThe bits per step needed to describe a random walker's path when nodes get short codes inside modules: Infomap minimizes it. reads a network as flow: it looks for the modules that let you describe a random walker's path in the fewest bits, and it can follow edge directions.
Infomap found 4 communities among 20 nodes; 61% of the edge weight falls inside them (modularity 0.331). The map describes the walk in 4.039 bits per step, against 4.231 with one module.
- Communities
- 4
- Modularity
- 0.3310
- Edge weight inside
- 61.0%
Plots
View data
| From | Community | Node | Strength | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 5 | 10 | 0.0748 | 0.8574 |
| 0 | 3 | 10 | 12 | 16 | −0.3189 | −0.5455 |
| 0 | 3 | 11 | 6 | 19 | 0.2678 | −0.6332 |
| 1 | 3 | 12 | 12 | 2 | −0.0469 | −0.3780 |
| 1 | 3 | 13 | 5 | 3 | −0.5093 | −0.1323 |
| 1 | 2 | 14 | 9 | 4 | −0.2271 | 0.2959 |
| 1 | 4 | 15 | 4 | 10 | 0.2773 | −0.8726 |
| 1 | 2 | 16 | 7 | 13 | 0.3697 | 0.1788 |
| 1 | 4 | 17 | 4 | 18 | 0.3894 | −0.1070 |
| 2 | 1 | 18 | 4 | 1 | −0.6092 | 0.4825 |
| 2 | 1 | 19 | 14 | 6 | −0.0312 | 0.0868 |
| 2 | 2 | 2 | 4 | 12 | −1 | 0.0103 |
| 3 | 2 | 20 | 9 | 1 | 0.6241 | 0.0458 |
| 3 | 3 | 3 | 7 | 2 | −0.7301 | −0.4961 |
| 3 | 4 | 4 | 9 | 4 | 0.5314 | −0.3702 |
| 3 | 2 | 5 | 6 | 7 | 0.8961 | 0.1924 |
| 3 | 1 | 6 | 9 | 10 | −0.1425 | 0.7120 |
| 3 | 2 | 7 | 7 | 13 | 0.4145 | 0.5555 |
| 3 | 1 | 8 | 8 | 14 | −0.2838 | −0.2194 |
| 4 | 1 | 9 | 13 | 1 | 0.0539 | 0.3368 |
| 4 | — | — | — | 3 | — | — |
| 5 | — | — | — | 7 | — | — |
| 5 | — | — | — | 8 | — | — |
| 5 | — | — | — | 11 | — | — |
| 5 | — | — | — | 17 | — | — |
| 6 | — | — | — | 14 | — | — |
| 6 | — | — | — | 18 | — | — |
| 7 | — | — | — | 5 | — | — |
| 7 | — | — | — | 12 | — | — |
| 7 | — | — | — | 15 | — | — |
| 7 | — | — | — | 19 | — | — |
| 8 | — | — | — | 12 | — | — |
| 8 | — | — | — | 14 | — | — |
| 9 | — | — | — | 5 | — | — |
| 9 | — | — | — | 16 | — | — |
| 10 | — | — | — | 1 | — | — |
| 10 | — | — | — | 3 | — | — |
| 10 | — | — | — | 5 | — | — |
| 10 | — | — | — | 14 | — | — |
| 10 | — | — | — | 16 | — | — |
| 10 | — | — | — | 18 | — | — |
| 10 | — | — | — | 19 | — | — |
| 11 | — | — | — | 5 | — | — |
| 11 | — | — | — | 13 | — | — |
| 12 | — | — | — | 2 | — | — |
| 12 | — | — | — | 15 | — | — |
| 12 | — | — | — | 17 | — | — |
| 12 | — | — | — | 19 | — | — |
| 13 | — | — | — | 1 | — | — |
| 13 | — | — | — | 3 | — | — |
| 13 | — | — | — | 11 | — | — |
| 13 | — | — | — | 18 | — | — |
| 14 | — | — | — | 3 | — | — |
| 14 | — | — | — | 6 | — | — |
| 14 | — | — | — | 8 | — | — |
| 14 | — | — | — | 10 | — | — |
| 15 | — | — | — | 7 | — | — |
| 15 | — | — | — | 12 | — | — |
| 15 | — | — | — | 14 | — | — |
| 15 | — | — | — | 17 | — | — |
First 60 of 77 rows.
Nodes sorted by community: dense blocks on the diagonal are communities.
View data
| Column | Community | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 10 | 1 | 1 | 10 | 0 | 1 |
| 16 | 3 | 10 | 19 | 0 | 1 |
| 19 | 3 | 11 | 16 | 0 | 1 |
| 2 | 3 | 12 | 18 | 1 | 1 |
| 3 | 3 | 13 | 0 | 1 | 1 |
| 4 | 2 | 14 | 9 | 1 | 1 |
| 10 | 4 | 15 | 5 | 1 | 1 |
| 13 | 2 | 16 | 12 | 1 | 1 |
| 18 | 4 | 17 | 7 | 1 | 1 |
| 1 | 1 | 18 | 17 | 2 | 1 |
| 6 | 1 | 19 | 15 | 2 | 1 |
| 12 | 2 | 2 | 11 | 2 | 1 |
| 1 | 2 | 20 | 1 | 3 | 1 |
| 2 | 3 | 3 | 3 | 3 | 1 |
| 4 | 4 | 4 | 13 | 3 | 1 |
| 7 | 2 | 5 | 2 | 3 | 1 |
| 10 | 1 | 6 | 4 | 3 | 1 |
| 13 | 2 | 7 | 14 | 3 | 1 |
| 14 | 1 | 8 | 6 | 3 | 1 |
| 1 | 1 | 9 | 8 | 4 | 1 |
| 3 | — | — | — | 4 | 1 |
| 7 | — | — | — | 5 | 1 |
| 8 | — | — | — | 5 | 1 |
| 11 | — | — | — | 5 | 1 |
| 17 | — | — | — | 5 | 1 |
| 14 | — | — | — | 6 | 1 |
| 18 | — | — | — | 6 | 1 |
| 5 | — | — | — | 7 | 1 |
| 12 | — | — | — | 7 | 1 |
| 15 | — | — | — | 7 | 1 |
| 19 | — | — | — | 7 | 1 |
| 12 | — | — | — | 8 | 1 |
| 14 | — | — | — | 8 | 1 |
| 5 | — | — | — | 9 | 1 |
| 16 | — | — | — | 9 | 1 |
| 1 | — | — | — | 10 | 1 |
| 3 | — | — | — | 10 | 1 |
| 5 | — | — | — | 10 | 1 |
| 14 | — | — | — | 10 | 1 |
| 16 | — | — | — | 10 | 1 |
| 18 | — | — | — | 10 | 1 |
| 19 | — | — | — | 10 | 1 |
| 5 | — | — | — | 11 | 1 |
| 13 | — | — | — | 11 | 1 |
| 2 | — | — | — | 12 | 1 |
| 15 | — | — | — | 12 | 1 |
| 17 | — | — | — | 12 | 1 |
| 19 | — | — | — | 12 | 1 |
| 1 | — | — | — | 13 | 1 |
| 3 | — | — | — | 13 | 1 |
| 11 | — | — | — | 13 | 1 |
| 18 | — | — | — | 13 | 1 |
| 3 | — | — | — | 14 | 1 |
| 6 | — | — | — | 14 | 1 |
| 8 | — | — | — | 14 | 1 |
| 10 | — | — | — | 14 | 1 |
| 7 | — | — | — | 15 | 1 |
| 12 | — | — | — | 15 | 1 |
| 14 | — | — | — | 15 | 1 |
| 17 | — | — | — | 15 | 1 |
First 60 of 77 rows.
View data
| Community |
|---|
| 1 |
| 3 |
| 3 |
| 3 |
| 3 |
| 2 |
| 4 |
| 2 |
| 4 |
| 1 |
| 1 |
| 2 |
| 2 |
| 3 |
| 4 |
| 2 |
| 1 |
| 2 |
| 1 |
| 1 |
Communities
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 6 | 30.0% | 0.3585 | yes | 19, 9, 6 |
| 2 | 6 | 30.0% | 0.3810 | yes | 14, 20, 16 |
| 3 | 5 | 25.0% | 0.3810 | yes | 10, 12, 3 |
| 4 | 3 | 15.0% | 0.5294 | yes | 4, 15, 17 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec 61481e0d4a6eaf7d
# Dataset: graph_directed (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ml_comm_*(): twin of codesplash.ml.communities
ALGO <- "infomap"
QUALITY <- "modularity"
RESOLUTION <- NULL
INFLATION <- 2
TRIALS <- 3L
DIRECTED <- TRUE
SWEEP <- FALSE
SEED <- 42
LABELS <- c(leiden = "Leiden", louvain = "Louvain", label_propagation = "Label propagation", mcl = "Markov clustering", infomap = "Infomap")
LIMITS <- list(infomap = c(10000, 100000), mcl = c(5000, 50000)) # (nodes, edges); the others 20,000 / 200,000
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.communities/infomap_directed/out-r")
warnings <- list()
values <- list(algorithm_label = LABELS[[ALGO]])
tables <- list()
charts <- list()
artifacts <- list()
# %% The network the host built (canonical node order, merged edges; cs_graph_read)
G <- cs_graph_read(out)
warnings <- c(warnings, as.list(G$warnings))
N <- G$n
pairs <- cs_graph_undirected_pairs(G)
g <- cs_ml_comm_graph(N, pairs$a + 1L, pairs$b + 1L, pairs$w) # direction set aside: every edge counts both ways
lim <- if (!is.null(LIMITS[[ALGO]])) LIMITS[[ALGO]] else c(20000, 200000)
if (N > lim[1] || length(pairs$a) > lim[2]) {
cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(pairs$a), max_nodes = lim[1], max_edges = lim[2])
}
if (N < 2 || g$m2 <= 0) cs_error("CS_E_UNDEFINED", what = "Communities", reason = "the network needs at least one edge between two different nodes")
if (isTRUE(G$directed) && !(ALGO == "infomap" && isTRUE(DIRECTED))) {
warnings <- c(warnings, sprintf("%s treats every edge as two-way, so the directions were set aside.", LABELS[[ALGO]]))
}
truth <- NULL
if (!is.null(G$label)) truth <- as.character(G$nodes[[G$label]])
values$mode <- "network"
values$n_nodes <- N
values$n_edges <- length(g$idx) %/% 2L
# %% Communities
if (ALGO %in% c("leiden", "louvain")) {
gamma <- if (!is.null(RESOLUTION)) as.numeric(RESOLUTION) else if (QUALITY == "cpm") (g$m2 / 2) / (N * (N - 1) / 2) else 1 # Potts default: the network's density
values$resolution <- gamma
}
find <- function(setting) {
rng <- cs_rng(SEED) # a fresh stream for every setting
if (ALGO == "leiden") return(cs_ml_comm_leiden(g, setting, QUALITY, rng))
if (ALGO == "louvain") return(cs_ml_comm_louvain(g, setting, QUALITY, rng))
if (ALGO == "label_propagation") return(cs_ml_comm_label_propagation(g, rng))
if (ALGO == "mcl") return(cs_ml_comm_mcl(g, setting))
fl <- if (isTRUE(G$directed) && isTRUE(DIRECTED)) cs_ml_comm_flow_directed(cs_ml_comm_dgraph(N, G$si + 1L, G$sj + 1L, G$sw)) else cs_ml_comm_flow_undirected(g)
cs_ml_comm_infomap(fl, rng, TRIALS)
}
setting <- if (ALGO %in% c("leiden", "louvain")) gamma else if (ALGO == "mcl") as.numeric(INFLATION) else NULL
res <- find(setting)
labels <- cs_ml_canonical(res$labels) # 1..k by size, ties by first node
k <- max(labels)
values$k <- k
if (!is.null(res$levels)) values$levels <- res$levels
if (!is.null(res$iterations)) values$iterations <- res$iterations
if (!is.null(res$sweeps)) values$sweeps <- res$sweeps
if (!is.null(res$converged)) {
values$converged <- isTRUE(res$converged)
if (!isTRUE(res$converged)) warnings <- c(warnings, sprintf("%s stopped at its iteration limit before every node settled.", LABELS[[ALGO]]))
}
if (!is.null(res$attractors)) values$attractors <- res$attractors
if (ALGO == "infomap") {
values$codelength <- res$codelength
values$codelength_one <- res$one_module
}
# %% Quality of the partition
values$modularity <- cs_ml_comm_modularity(g, labels, 1)
if (ALGO %in% c("leiden", "louvain")) {
values$quality <- if (QUALITY == "cpm") cs_ml_comm_cpm(g, labels, gamma) else cs_ml_comm_modularity(g, labels, gamma)
}
values$coverage <- cs_ml_comm_coverage(g, labels)
cond <- cs_ml_comm_conductance(g, labels)
finite <- cond[!is.nan(cond)]
if (length(finite)) values$conductance <- mean(finite) else values["conductance"] <- list(NULL)
conn <- cs_ml_comm_connected(g, labels)
values$n_disconnected <- sum(!conn)
if (values$n_disconnected > 0) warnings <- c(warnings, sprintf("%d of %d communities fall apart into separate pieces of the network.", values$n_disconnected, k))
sizes <- tabulate(labels, nbins = k)
for (c in seq_len(k)) values[[sprintf("size[%d]", c)]] <- sizes[c]
values$largest_share <- max(sizes) / N
values$singletons <- sum(sizes == 1)
if (!is.null(truth)) {
ok <- !is.na(truth)
values$n_labeled <- sum(ok)
if (sum(ok) >= 2) {
values$ari <- cs_ml_ari(truth[ok], labels[ok])
values$ami <- cs_ml_ami(truth[ok], labels[ok])
values$nmi <- cs_ml_nmi(truth[ok], labels[ok])
}
}
# %% Settings compared
if (isTRUE(SWEEP) && ALGO %in% c("leiden", "louvain", "mcl")) {
grid <- if (ALGO != "mcl") gamma * c(0.25, 0.5, 1, 2, 4) else c(1.4, 1.6, 2, 2.5, 3, 4)
srows <- list(); ks <- integer(0); qs <- numeric(0)
for (i in seq_along(grid)) {
lab_s <- cs_ml_canonical(find(grid[i])$labels)
ks[i] <- max(lab_s)
qs[i] <- cs_ml_comm_modularity(g, lab_s, 1)
values[[sprintf("sweep_setting[%d]", i)]] <- grid[i]
values[[sprintf("sweep_k[%d]", i)]] <- ks[i]
values[[sprintf("sweep_modularity[%d]", i)]] <- qs[i]
srows[[i]] <- list(setting = grid[i], k = ks[i], modularity = qs[i])
}
what <- if (ALGO == "mcl") "Inflation" else "Resolution"
tables[[length(tables) + 1L]] <- list(
key = "sweep", title = sprintf("Communities at other settings (%s)", tolower(what)),
columns = list(list(key = "setting", label = what, type = "number"), list(key = "k", label = "Communities", type = "integer"),
list(key = "modularity", label = "Modularity", type = "number")),
rows = srows
)
chosen <- abs(grid - setting) < 1e-12
charts[[length(charts) + 1L]] <- cs_chart(
"sweep", "elbow-plot", sprintf("Communities by %s", tolower(what)),
list(k = cs_col(what, c(grid, grid), "numeric"), score = cs_col("Value", c(ks, qs), "numeric"),
criterion = cs_col("Measure", c(rep("Communities", length(grid)), rep("Modularity", length(grid))), "categorical", c("Communities", "Modularity")),
chosen = cs_col("This run", c(chosen, chosen), "boolean")),
note = sprintf("The ringed point is this run's %s.", tolower(what))
)
}
# %% Communities table
crows <- list()
for (c in seq_len(k)) {
members <- which(labels == c)
top <- members[order(-g$k[members], members)][seq_len(min(3L, length(members)))]
crows[[c]] <- list(community = c, size = sizes[c], share = sizes[c] / N,
conductance = if (is.nan(cond[c])) NULL else cond[c], connected = conn[c],
examples = paste(G$node_id[top], collapse = ", "))
}
tables <- c(list(list(
key = "communities", title = "Communities",
columns = list(list(key = "community", label = "Community", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
list(key = "share", label = "Share", type = "percent"), list(key = "conductance", label = "Conductance", type = "number"),
list(key = "connected", label = "In one piece", type = "boolean"), list(key = "examples", label = "Best-connected nodes")),
rows = crows
)), tables)
# %% Results per node (or row) and charts
level_names <- as.character(seq_len(k))
artifacts[[length(artifacts) + 1L]] <- cs_graph_write_nodes(out, G, data.frame(community = as.integer(labels), strength = g$k))
MAP_NODES <- 2000; MATRIX_NODES <- 300
if (N <= MAP_NODES) {
xy <- cs_graph_layout_fr(G, SEED)
m <- length(G$si)
show <- min(m, 20000)
keep <- seq_len(show)
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(
x = cs_col("x", xy$x, "numeric"),
y = cs_col("y", xy$y, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
size = cs_col("Strength", g$k, "numeric"),
group = cs_col("Community", as.character(labels), "categorical", level_names),
from = cs_col("From", G$si[keep], "numeric"),
to = cs_col("To", G$sj[keep], "numeric"),
weight = if (isTRUE(G$weighted)) cs_col("Weight", G$sw[keep], "numeric") else NULL
), controls = list(directed = isTRUE(G$directed)), note = if (show == m) NULL else sprintf("%d of %d edges drawn.", show, m))
} else {
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(), note = sprintf("The map is drawn for networks up to %d nodes; this one has %d.", MAP_NODES, N))
}
if (N <= MATRIX_NODES) {
morder <- order(labels, -g$k, seq_len(N)) - 1L
charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by community", list(
row = cs_col("Row", G$si, "numeric"),
col = cs_col("Column", G$sj, "numeric"),
value = cs_col(if (isTRUE(G$weighted)) "Weight" else "Edge", G$sw, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
group = cs_col("Community", as.character(labels), "categorical", level_names),
order = cs_col("Order", morder, "numeric")
), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by community: dense blocks on the diagonal are communities.")
}
charts[[length(charts) + 1L]] <- cs_chart("sizes", "bar", "Community sizes", list(x = cs_col("Community", as.character(labels), "categorical", level_names)),
controls = list(top = 30))
# %% Result
what <- if (values$mode == "rows") "rows" else "nodes"
summary <- sprintf("%s found %d communit%s among %s %s; %.0f%% of the edge weight falls inside them (modularity %.3f).",
LABELS[[ALGO]], k, if (k == 1) "y" else "ies", format(N, big.mark = ","), what, 100 * values$coverage, values$modularity)
if (ALGO == "infomap") {
summary <- paste0(summary, sprintf(" The map describes the walk in %.3f bits per step, against %.3f with one module.", values$codelength, values$codelength_one))
}
publish <- list(
title = "Network communities",
engine = cs_engine_info("nanoparquet", "Matrix"),
n = N,
summary = summary,
statistics = list(list(key = "k", label = "Communities", value = k, format = "integer"),
list(key = "modularity", label = "Modularity", value = values$modularity),
list(key = "coverage", label = "Edge weight inside", value = values$coverage, format = "percent")),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = artifacts
)
cs_publish(publish)
Infomap found 4 communities among 20 nodes; 61% of the edge weight falls inside them (modularity 0.331). The map describes the walk in 4.039 bits per step, against 4.231 with one module.
- Communities
- 4
- Modularity
- 0.3310
- Edge weight inside
- 61.0%
To keep this page light, the plots are shown once, under the R tab.
Communities
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 6 | 30.0% | 0.3585 | yes | 19, 9, 6 |
| 2 | 6 | 30.0% | 0.3810 | yes | 14, 20, 16 |
| 3 | 5 | 25.0% | 0.3810 | yes | 10, 12, 3 |
| 4 | 3 | 15.0% | 0.5294 | yes | 4, 15, 17 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec 61481e0d4a6eaf7d
# Dataset: graph_directed (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
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 communities as cm # twin of codesplashr R/ml_communities.R
from codesplash.stats.rng import Rng
ALGO = "infomap"
QUALITY = "modularity"
RESOLUTION = None
INFLATION = 2
TRIALS = 3
DIRECTED = True
SWEEP = False
SEED = 42
LABELS = {"leiden": "Leiden", "louvain": "Louvain", "label_propagation": "Label propagation", "mcl": "Markov clustering", "infomap": "Infomap"}
LIMITS = {"infomap": (10000, 100000), "mcl": (5000, 50000)} # (nodes, edges); the others 20,000 / 200,000
out = csml.out_dir("target/academy-parity/run-8142/discover.communities/infomap_directed/out-python")
warnings = []
values = {"algorithm_label": LABELS[ALGO]}
tables = []
charts = []
artifacts = []
# %% The network the host built (canonical node order, merged edges; codesplash.graph)
from codesplash import graph as cg
from codesplash.graph import layout as gl
G = cg.read(out)
warnings += list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G)
g = cm.undirected(N, a, b, w) # direction set aside: every edge counts both ways
max_nodes, max_edges = LIMITS.get(ALGO, (20000, 200000))
if N > max_nodes or len(a) > max_edges:
cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=max_nodes, max_edges=max_edges)
if N < 2 or g.m2 <= 0:
cs.cs_error("CS_E_UNDEFINED", what="Communities", reason="the network needs at least one edge between two different nodes")
if G.directed and not (ALGO == "infomap" and DIRECTED):
warnings.append(f"{LABELS[ALGO]} treats every edge as two-way, so the directions were set aside.")
truth = None
if G.label:
truth = np.array([None if pd.isna(v) else str(v) for v in G.nodes[G.label].tolist()], dtype=object) # None, NaN, pd.NA
values["mode"] = "network"
values["n_nodes"] = N
values["n_edges"] = g.n_edges
# %% Communities
if ALGO in ("leiden", "louvain"):
if RESOLUTION is not None:
gamma = float(RESOLUTION)
elif QUALITY == "cpm":
gamma = (g.m2 / 2.0) / (N * (N - 1) / 2.0) # the network's density (edge weight per pair of nodes)
else:
gamma = 1.0
values["resolution"] = gamma
def find(setting):
"""Communities for one setting (resolution or inflation), from a fresh stream → (labels, info)."""
rng = Rng(SEED)
if ALGO == "leiden":
r = cm.leiden(g, setting, QUALITY, rng)
elif ALGO == "louvain":
r = cm.louvain(g, setting, QUALITY, rng)
elif ALGO == "label_propagation":
r = cm.label_propagation(g, rng)
elif ALGO == "mcl":
r = cm.mcl(g, setting)
else:
fl = cm.flow_directed(cm.DGraph(N, G.si, G.sj, G.sw)) if (G.directed and DIRECTED) else cm.flow_undirected(g)
r = cm.infomap(fl, rng, TRIALS)
return r
setting = gamma if ALGO in ("leiden", "louvain") else (float(INFLATION) if ALGO == "mcl" else None)
res = find(setting)
labels = csc.canonical(np.asarray(res["labels"], dtype=np.int64)) # 1…k by size, ties by first node
lab0 = (labels - 1).tolist()
k = int(labels.max())
values["k"] = k
if "levels" in res:
values["levels"] = res["levels"]
if "iterations" in res:
values["iterations"] = res["iterations"]
if "sweeps" in res:
values["sweeps"] = res["sweeps"]
if "converged" in res:
values["converged"] = bool(res["converged"])
if not res["converged"]:
warnings.append(f"{LABELS[ALGO]} stopped at its iteration limit before every node settled.")
if "attractors" in res:
values["attractors"] = res["attractors"]
if ALGO == "infomap":
values["codelength"] = res["codelength"]
values["codelength_one"] = res["one_module"]
# %% Quality of the partition
values["modularity"] = cm.modularity(g, lab0, 1.0)
if ALGO in ("leiden", "louvain"):
values["quality"] = cm.cpm(g, lab0, gamma) if QUALITY == "cpm" else cm.modularity(g, lab0, gamma)
values["coverage"] = cm.coverage(g, lab0)
cond = cm.conductance(g, lab0)
finite = [c for c in cond if c == c]
values["conductance"] = float(np.mean(finite)) if finite else None
conn = cm.connected(g, lab0)
values["n_disconnected"] = int(sum(1 for x in conn if not x))
if values["n_disconnected"]:
warnings.append(f"{values['n_disconnected']} of {k} communities fall apart into separate pieces of the network.")
sizes = np.bincount(labels, minlength=k + 1)[1:]
for c in range(1, k + 1):
values[f"size[{c}]"] = int(sizes[c - 1])
values["largest_share"] = float(sizes.max() / N)
values["singletons"] = int(np.sum(sizes == 1))
if truth is not None:
ok = np.array([v is not None for v in truth])
values["n_labeled"] = int(ok.sum())
if ok.sum() >= 2:
tt = truth[ok].astype(str)
values["ari"] = csc.ari(tt, labels[ok])
values["ami"] = csc.ami(tt, labels[ok])
values["nmi"] = csc.nmi(tt, labels[ok])
# %% Settings compared
if SWEEP and ALGO in ("leiden", "louvain", "mcl"):
grid = [gamma * f for f in (0.25, 0.5, 1.0, 2.0, 4.0)] if ALGO != "mcl" else [1.4, 1.6, 2.0, 2.5, 3.0, 4.0]
srows = []
for i, s in enumerate(grid, start=1):
lab_s = csc.canonical(np.asarray(find(s)["labels"], dtype=np.int64))
ks = int(lab_s.max())
qs = cm.modularity(g, (lab_s - 1).tolist(), 1.0)
values[f"sweep_setting[{i}]"] = s
values[f"sweep_k[{i}]"] = ks
values[f"sweep_modularity[{i}]"] = qs
srows.append({"setting": s, "k": ks, "modularity": qs})
what = "Inflation" if ALGO == "mcl" else "Resolution"
tables.append({
"key": "sweep", "title": f"Communities at other settings ({what.lower()})",
"columns": [{"key": "setting", "label": what, "type": "number"}, {"key": "k", "label": "Communities", "type": "integer"},
{"key": "modularity", "label": "Modularity", "type": "number"}],
"rows": srows,
})
chosen = [abs(s - setting) < 1e-12 for s in grid]
charts.append(cs.chart(
"sweep", "elbow-plot", f"Communities by {what.lower()}",
{"k": cs.col(what, grid + grid, "numeric"), "score": cs.col("Value", [r["k"] for r in srows] + [r["modularity"] for r in srows], "numeric"),
"criterion": cs.col("Measure", ["Communities"] * len(grid) + ["Modularity"] * len(grid), "categorical", ["Communities", "Modularity"]),
"chosen": cs.col("This run", chosen + chosen, "boolean")},
note=f"The ringed point is this run's {what.lower()}.",
))
# %% Communities table
crows = []
for c in range(1, k + 1):
members = np.flatnonzero(labels == c)
top = sorted(members.tolist(), key=lambda v: (-g.k[v], v))[:3]
crows.append({"community": c, "size": int(sizes[c - 1]), "share": float(sizes[c - 1] / N),
"conductance": cond[c - 1] if cond[c - 1] == cond[c - 1] else None, "connected": bool(conn[c - 1]),
"examples": ", ".join(G.node_id[v] for v in top)})
tables.insert(0, {
"key": "communities", "title": "Communities",
"columns": [{"key": "community", "label": "Community", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
{"key": "share", "label": "Share", "type": "percent"}, {"key": "conductance", "label": "Conductance", "type": "number"},
{"key": "connected", "label": "In one piece", "type": "boolean"}, {"key": "examples", "label": "Best-connected nodes"}],
"rows": crows,
})
# %% Results per node (or row) and charts
level_names = [str(c) for c in range(1, k + 1)]
cols = {"community": labels.astype(np.int64), "strength": np.asarray(g.k, dtype=np.float64)}
artifacts.append(cg.write_nodes(out, G, cols))
MAP_NODES, MATRIX_NODES = 2000, 300
if N <= MAP_NODES:
xy = gl.fruchterman_reingold(G, SEED)
m = len(G.si)
show = min(m, 20000)
charts.append(cs.chart("map", "network-graph", "Communities in the network", {
"x": cs.col("x", xy[0], "numeric"),
"y": cs.col("y", xy[1], "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"size": cs.col("Strength", g.k, "numeric"),
"group": cs.col("Community", [str(c) for c in labels], "categorical", level_names),
"from": cs.col("From", G.si[:show], "numeric"),
"to": cs.col("To", G.sj[:show], "numeric"),
"weight": cs.col("Weight", G.sw[:show], "numeric") if G.weighted else None,
}, controls={"directed": G.directed}, note=None if show == m else f"{show} of {m} edges drawn."))
else:
charts.append(cs.chart("map", "network-graph", "Communities in the network", {}, note=f"The map is drawn for networks up to {MAP_NODES} nodes; this one has {N}."))
if N <= MATRIX_NODES:
morder = sorted(range(N), key=lambda v: (int(labels[v]), -g.k[v], v))
charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by community", {
"row": cs.col("Row", G.si, "numeric"),
"col": cs.col("Column", G.sj, "numeric"),
"value": cs.col("Weight" if G.weighted else "Edge", G.sw, "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"group": cs.col("Community", [str(c) for c in labels], "categorical", level_names),
"order": cs.col("Order", morder, "numeric"),
}, controls={"directed": G.directed}, note="Nodes sorted by community: dense blocks on the diagonal are communities."))
charts.append(cs.chart("sizes", "bar", "Community sizes", {"x": cs.col("Community", [str(c) for c in labels], "categorical", level_names)},
controls={"top": 30}))
# %% Result
what = "rows" if values["mode"] == "rows" else "nodes"
summary = (f"{LABELS[ALGO]} found {k} communit{'y' if k == 1 else 'ies'} among {N:,} {what}; "
f"{values['coverage']:.0%} of the edge weight falls inside them (modularity {values['modularity']:.3f}).")
if ALGO == "infomap":
summary += f" The map describes the walk in {values['codelength']:.3f} bits per step, against {values['codelength_one']:.3f} with one module."
publish = {
"title": "Network communities",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": N,
"summary": summary,
"statistics": [
{"key": "k", "label": "Communities", "value": k, "format": "integer"},
{"key": "modularity", "label": "Modularity", "value": values["modularity"]},
{"key": "coverage", "label": "Edge weight inside", "value": values["coverage"], "format": "percent"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": artifacts,
}
cs.publish(publish)
On 20 accounts that follow each other, the modules cut the description from 4.23 bits per step (one module) to 4.04.
Communities of rows
ReadWithout an edge list, the method links each row to its nearest rows in the chosen columns (a nearest-neighbor graphNearest-neighbor graphLinks each row to its k closest rows in the chosen columns, turning a table into a network whose communities are row groups.) and finds communities of rows, the idea behind PhenoGraph in single-cell biology. The labels line up with the rows, so you can save them to the dataset.
Louvain found 6 communities among 150 rows; 84% of the edge weight falls inside them (modularity 0.654).
- Communities
- 6
- Modularity
- 0.6539
- Edge weight inside
- 83.5%
Plots
View data
| Community | PC1 (73%) | PC2 (23%) |
|---|---|---|
| 1 | −2.265 | 0.4800 |
| 5 | −2.081 | −0.6741 |
| 5 | −2.364 | −0.3419 |
| 5 | −2.299 | −0.5974 |
| 1 | −2.390 | 0.6468 |
| 1 | −2.076 | 1.489 |
| 1 | −2.444 | 0.0476 |
| 1 | −2.233 | 0.2231 |
| 5 | −2.335 | −1.115 |
| 5 | −2.184 | −0.4690 |
| 1 | −2.166 | 1.044 |
| 1 | −2.326 | 0.1331 |
| 5 | −2.218 | −0.7287 |
| 5 | −2.633 | −0.9615 |
| 1 | −2.199 | 1.860 |
| 1 | −2.262 | 2.686 |
| 1 | −2.208 | 1.484 |
| 1 | −2.190 | 0.4888 |
| 1 | −1.899 | 1.405 |
| 1 | −2.343 | 1.128 |
| 1 | −1.914 | 0.4089 |
| 1 | −2.207 | 0.9241 |
| 1 | −2.774 | 0.4583 |
| 1 | −1.819 | 0.0856 |
| 1 | −2.227 | 0.1373 |
| 5 | −1.952 | −0.6256 |
| 1 | −2.051 | 0.2422 |
| 1 | −2.169 | 0.5271 |
| 1 | −2.140 | 0.3132 |
| 5 | −2.265 | −0.3377 |
| 5 | −2.140 | −0.5045 |
| 1 | −1.832 | 0.4237 |
| 1 | −2.615 | 1.794 |
| 1 | −2.446 | 2.151 |
| 5 | −2.110 | −0.4602 |
| 5 | −2.208 | −0.2061 |
| 1 | −2.045 | 0.6616 |
| 1 | −2.527 | 0.5923 |
| 5 | −2.430 | −0.9042 |
| 1 | −2.170 | 0.2689 |
| 1 | −2.286 | 0.4417 |
| 5 | −1.858 | −2.337 |
| 5 | −2.554 | −0.4791 |
| 1 | −1.964 | 0.4723 |
| 1 | −2.137 | 1.142 |
| 5 | −2.070 | −0.7111 |
| 1 | −2.385 | 1.120 |
| 5 | −2.394 | −0.3862 |
| 1 | −2.229 | 0.9980 |
| 1 | −2.204 | 0.0092 |
| 2 | 1.102 | 0.8630 |
| 2 | 0.7313 | 0.5946 |
| 2 | 1.241 | 0.6163 |
| 4 | 0.4075 | −1.754 |
| 2 | 1.075 | −0.2084 |
| 2 | 0.3887 | −0.5933 |
| 2 | 0.7465 | 0.7730 |
| 4 | −0.4873 | −1.852 |
| 2 | 0.9279 | 0.0322 |
| 4 | 0.0114 | −1.034 |
First 60 of 150 rows.
View data
| Community |
|---|
| 1 |
| 5 |
| 5 |
| 5 |
| 1 |
| 1 |
| 1 |
| 1 |
| 5 |
| 5 |
| 1 |
| 1 |
| 5 |
| 5 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 5 |
| 1 |
| 1 |
| 1 |
| 5 |
| 5 |
| 1 |
| 1 |
| 1 |
| 5 |
| 5 |
| 1 |
| 1 |
| 5 |
| 1 |
| 1 |
| 5 |
| 5 |
| 1 |
| 1 |
| 5 |
| 1 |
| 5 |
| 1 |
| 1 |
| 2 |
| 2 |
| 2 |
| 4 |
| 2 |
| 2 |
| 2 |
| 4 |
| 2 |
| 4 |
First 60 of 150 rows.
Communities
| Community | Rows | Share | Conductance | In one piece | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 33 | 22.0% | 0.0462 | yes | 5.170 | 3.630 | 1.494 | 0.2727 |
| 2 | 32 | 21.3% | 0.2455 | yes | 6.156 | 2.991 | 4.513 | 1.456 |
| 3 | 30 | 20.0% | 0.1306 | yes | 6.947 | 3.147 | 5.827 | 2.143 |
| 4 | 21 | 14.0% | 0.1860 | yes | 5.543 | 2.443 | 3.948 | 1.200 |
| 5 | 17 | 11.3% | 0.1000 | yes | 4.688 | 3.035 | 1.400 | 0.1941 |
| 6 | 17 | 11.3% | 0.3441 | yes | 6.141 | 2.694 | 5.206 | 1.853 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec a00e338c5837f052
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ml_comm_*(): twin of codesplash.ml.communities
ALGO <- "louvain"
QUALITY <- "modularity"
RESOLUTION <- NULL
INFLATION <- 2
TRIALS <- 5L
DIRECTED <- FALSE
SWEEP <- FALSE
SEED <- 42
LABELS <- c(leiden = "Leiden", louvain = "Louvain", label_propagation = "Label propagation", mcl = "Markov clustering", infomap = "Infomap")
LIMITS <- list(infomap = c(10000, 100000), mcl = c(5000, 50000)) # (nodes, edges); the others 20,000 / 200,000
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.communities/knn_iris_louvain/out-r")
warnings <- list()
values <- list(algorithm_label = LABELS[[ALGO]])
tables <- list()
charts <- list()
artifacts <- list()
# %% Rows linked to their nearest neighbors (a k-nearest-neighbor graph)
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species" # known groups (comparison only)
ROW_ID <- NULL
KINDS <- list(
sepal_length = "numeric",
sepal_width = "numeric",
petal_length = "numeric",
petal_width = "numeric"
)
LEVELS <- list(
)
if (!length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Input", allowed = "an edge list (From and To) or row features", value = "neither")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
cs_check_finite_columns(frame, FEATURES[vapply(FEATURES, function(f) identical(KINDS[[f]], "numeric"), logical(1))]) # ±Inf stops with CS_E_NOT_FINITE in both engines
if (length(rows) < n_input) {
warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
N <- length(rows)
if (N < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "Communities on a nearest-neighbor graph", min = 3, n = N)
if (N > 10000) cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = N * 15, max_nodes = 10000, max_edges = 200000)
if (!any(apply(X, 2, function(v) max(v) - min(v)) > 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
K_NN <- min(15, N - 1)
g <- cs_ml_comm_knn_graph(X, K_NN)
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
values$mode <- "rows"
values$n_neighbors <- K_NN
values$n_nodes <- N
values$n_edges <- length(g$idx) %/% 2L
# %% Communities
if (ALGO %in% c("leiden", "louvain")) {
gamma <- if (!is.null(RESOLUTION)) as.numeric(RESOLUTION) else if (QUALITY == "cpm") (g$m2 / 2) / (N * (N - 1) / 2) else 1 # Potts default: the network's density
values$resolution <- gamma
}
find <- function(setting) {
rng <- cs_rng(SEED) # a fresh stream for every setting
if (ALGO == "leiden") return(cs_ml_comm_leiden(g, setting, QUALITY, rng))
if (ALGO == "louvain") return(cs_ml_comm_louvain(g, setting, QUALITY, rng))
if (ALGO == "label_propagation") return(cs_ml_comm_label_propagation(g, rng))
if (ALGO == "mcl") return(cs_ml_comm_mcl(g, setting))
fl <- cs_ml_comm_flow_undirected(g)
cs_ml_comm_infomap(fl, rng, TRIALS)
}
setting <- if (ALGO %in% c("leiden", "louvain")) gamma else if (ALGO == "mcl") as.numeric(INFLATION) else NULL
res <- find(setting)
labels <- cs_ml_canonical(res$labels) # 1..k by size, ties by first node
k <- max(labels)
values$k <- k
if (!is.null(res$levels)) values$levels <- res$levels
if (!is.null(res$iterations)) values$iterations <- res$iterations
if (!is.null(res$sweeps)) values$sweeps <- res$sweeps
if (!is.null(res$converged)) {
values$converged <- isTRUE(res$converged)
if (!isTRUE(res$converged)) warnings <- c(warnings, sprintf("%s stopped at its iteration limit before every node settled.", LABELS[[ALGO]]))
}
if (!is.null(res$attractors)) values$attractors <- res$attractors
if (ALGO == "infomap") {
values$codelength <- res$codelength
values$codelength_one <- res$one_module
}
# %% Quality of the partition
values$modularity <- cs_ml_comm_modularity(g, labels, 1)
if (ALGO %in% c("leiden", "louvain")) {
values$quality <- if (QUALITY == "cpm") cs_ml_comm_cpm(g, labels, gamma) else cs_ml_comm_modularity(g, labels, gamma)
}
values$coverage <- cs_ml_comm_coverage(g, labels)
cond <- cs_ml_comm_conductance(g, labels)
finite <- cond[!is.nan(cond)]
if (length(finite)) values$conductance <- mean(finite) else values["conductance"] <- list(NULL)
conn <- cs_ml_comm_connected(g, labels)
values$n_disconnected <- sum(!conn)
if (values$n_disconnected > 0) warnings <- c(warnings, sprintf("%d of %d communities fall apart into separate pieces of the network.", values$n_disconnected, k))
sizes <- tabulate(labels, nbins = k)
for (c in seq_len(k)) values[[sprintf("size[%d]", c)]] <- sizes[c]
values$largest_share <- max(sizes) / N
values$singletons <- sum(sizes == 1)
check <- cs_ml_cluster_validation(X, labels, truth, cap = 3000, seed = SEED)
check$.widths <- NULL
values <- c(values, check)
# %% Settings compared
if (isTRUE(SWEEP) && ALGO %in% c("leiden", "louvain", "mcl")) {
grid <- if (ALGO != "mcl") gamma * c(0.25, 0.5, 1, 2, 4) else c(1.4, 1.6, 2, 2.5, 3, 4)
srows <- list(); ks <- integer(0); qs <- numeric(0)
for (i in seq_along(grid)) {
lab_s <- cs_ml_canonical(find(grid[i])$labels)
ks[i] <- max(lab_s)
qs[i] <- cs_ml_comm_modularity(g, lab_s, 1)
values[[sprintf("sweep_setting[%d]", i)]] <- grid[i]
values[[sprintf("sweep_k[%d]", i)]] <- ks[i]
values[[sprintf("sweep_modularity[%d]", i)]] <- qs[i]
srows[[i]] <- list(setting = grid[i], k = ks[i], modularity = qs[i])
}
what <- if (ALGO == "mcl") "Inflation" else "Resolution"
tables[[length(tables) + 1L]] <- list(
key = "sweep", title = sprintf("Communities at other settings (%s)", tolower(what)),
columns = list(list(key = "setting", label = what, type = "number"), list(key = "k", label = "Communities", type = "integer"),
list(key = "modularity", label = "Modularity", type = "number")),
rows = srows
)
chosen <- abs(grid - setting) < 1e-12
charts[[length(charts) + 1L]] <- cs_chart(
"sweep", "elbow-plot", sprintf("Communities by %s", tolower(what)),
list(k = cs_col(what, c(grid, grid), "numeric"), score = cs_col("Value", c(ks, qs), "numeric"),
criterion = cs_col("Measure", c(rep("Communities", length(grid)), rep("Modularity", length(grid))), "categorical", c("Communities", "Modularity")),
chosen = cs_col("This run", c(chosen, chosen), "boolean")),
note = sprintf("The ringed point is this run's %s.", tolower(what))
)
}
# %% Communities table
crows <- list()
num_f <- FEATURES[vapply(FEATURES, function(f) identical(KINDS[[f]], "numeric"), logical(1))]
for (c in seq_len(k)) {
member <- labels == c
row <- list(community = c, size = sizes[c], share = sizes[c] / N,
conductance = if (is.nan(cond[c])) NULL else cond[c], connected = conn[c])
for (f in num_f) row[[f]] <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
crows[[c]] <- row
}
tables <- c(list(list(
key = "communities", title = "Communities",
columns = c(list(list(key = "community", label = "Community", type = "integer"), list(key = "size", label = "Rows", type = "integer"),
list(key = "share", label = "Share", type = "percent"), list(key = "conductance", label = "Conductance", type = "number"),
list(key = "connected", label = "In one piece", type = "boolean")),
lapply(num_f, function(f) list(key = f, label = f, type = "number"))),
rows = crows
)), tables)
# %% Results per node (or row) and charts
level_names <- as.character(seq_len(k))
artifacts[[length(artifacts) + 1L]] <- list(key = "labels", path = cs_ml_write_labels(out, rows, labels), format = "parquet")
pr <- cs_ml_project2(X, NULL, names_)
show <- cs_ml_even_sample(N)
charts[[length(charts) + 1L]] <- cs_chart(
"clusters", "cluster-scatter", "Communities",
list(x = cs_col(pr$labels[1], pr$P[show + 1L, 1], "numeric"), y = cs_col(pr$labels[2], pr$P[show + 1L, 2], "numeric"),
cluster = cs_col("Community", as.character(labels[show + 1L]), "categorical", levels = level_names),
label = if (!is.null(ROW_ID)) cs_col("Row", as.character(frame[[ROW_ID]])[show + 1L], "categorical") else NULL),
note = if (length(show) == N) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(N, big.mark = ","))
)
charts[[length(charts) + 1L]] <- cs_chart("sizes", "bar", "Community sizes", list(x = cs_col("Community", as.character(labels), "categorical", level_names)),
controls = list(top = 30))
# %% Result
what <- if (values$mode == "rows") "rows" else "nodes"
summary <- sprintf("%s found %d communit%s among %s %s; %.0f%% of the edge weight falls inside them (modularity %.3f).",
LABELS[[ALGO]], k, if (k == 1) "y" else "ies", format(N, big.mark = ","), what, 100 * values$coverage, values$modularity)
if (ALGO == "infomap") {
summary <- paste0(summary, sprintf(" The map describes the walk in %.3f bits per step, against %.3f with one module.", values$codelength, values$codelength_one))
}
publish <- list(
title = "Network communities",
engine = cs_engine_info("nanoparquet", "Matrix"),
n = N,
summary = summary,
statistics = list(list(key = "k", label = "Communities", value = k, format = "integer"),
list(key = "modularity", label = "Modularity", value = values$modularity),
list(key = "coverage", label = "Edge weight inside", value = values$coverage, format = "percent")),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = artifacts
)
publish$model <- list(kind = "clusterer", features = I(names_), params = list(
algorithm = "louvain",
quality = "modularity",
resolution = NULL,
inflation = 2,
trials = 5,
directed = FALSE,
n_neighbors = 15,
sweep = FALSE,
nodes = NULL,
scale = "standard",
missing = "drop"
))
cs_publish(publish)
Louvain found 6 communities among 150 rows; 84% of the edge weight falls inside them (modularity 0.654).
- Communities
- 6
- Modularity
- 0.6539
- Edge weight inside
- 83.5%
To keep this page light, the plots are shown once, under the R tab.
Communities
| Community | Rows | Share | Conductance | In one piece | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 33 | 22.0% | 0.0462 | yes | 5.170 | 3.630 | 1.494 | 0.2727 |
| 2 | 32 | 21.3% | 0.2455 | yes | 6.156 | 2.991 | 4.513 | 1.456 |
| 3 | 30 | 20.0% | 0.1306 | yes | 6.947 | 3.147 | 5.827 | 2.143 |
| 4 | 21 | 14.0% | 0.1860 | yes | 5.543 | 2.443 | 3.948 | 1.200 |
| 5 | 17 | 11.3% | 0.1000 | yes | 4.688 | 3.035 | 1.400 | 0.1941 |
| 6 | 17 | 11.3% | 0.3441 | yes | 6.141 | 2.694 | 5.206 | 1.853 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec a00e338c5837f052
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
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 communities as cm # twin of codesplashr R/ml_communities.R
from codesplash.stats.rng import Rng
ALGO = "louvain"
QUALITY = "modularity"
RESOLUTION = None
INFLATION = 2
TRIALS = 5
DIRECTED = False
SWEEP = False
SEED = 42
LABELS = {"leiden": "Leiden", "louvain": "Louvain", "label_propagation": "Label propagation", "mcl": "Markov clustering", "infomap": "Infomap"}
LIMITS = {"infomap": (10000, 100000), "mcl": (5000, 50000)} # (nodes, edges); the others 20,000 / 200,000
out = csml.out_dir("target/academy-parity/run-8142/discover.communities/knn_iris_louvain/out-python")
warnings = []
values = {"algorithm_label": LABELS[ALGO]}
tables = []
charts = []
artifacts = []
# %% Rows linked to their nearest neighbors (a k-nearest-neighbor graph)
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species" # known groups (comparison only)
ROW_ID = None
KINDS = {
"sepal_length": "numeric",
"sepal_width": "numeric",
"petal_length": "numeric",
"petal_width": "numeric",
}
LEVELS = {
}
if not FEATURES:
cs.cs_error("CS_E_INVALID_OPTION", option="Input", allowed="an edge list (From and To) or row features", value="neither")
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
cs.check_finite_columns(frame, [f for f in FEATURES if KINDS[f] == "numeric"]) # ±Inf stops with CS_E_NOT_FINITE in both engines
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
N = len(rows)
if N < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Communities on a nearest-neighbor graph", min=3, n=N)
if N > 10000:
cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=N * 15, max_nodes=10000, max_edges=200000)
if not np.any(np.ptp(X, axis=0) > 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
K_NN = min(15, N - 1)
g = cm.knn_graph(X, K_NN)
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
values["mode"] = "rows"
values["n_neighbors"] = K_NN
values["n_nodes"] = N
values["n_edges"] = g.n_edges
# %% Communities
if ALGO in ("leiden", "louvain"):
if RESOLUTION is not None:
gamma = float(RESOLUTION)
elif QUALITY == "cpm":
gamma = (g.m2 / 2.0) / (N * (N - 1) / 2.0) # the network's density (edge weight per pair of nodes)
else:
gamma = 1.0
values["resolution"] = gamma
def find(setting):
"""Communities for one setting (resolution or inflation), from a fresh stream → (labels, info)."""
rng = Rng(SEED)
if ALGO == "leiden":
r = cm.leiden(g, setting, QUALITY, rng)
elif ALGO == "louvain":
r = cm.louvain(g, setting, QUALITY, rng)
elif ALGO == "label_propagation":
r = cm.label_propagation(g, rng)
elif ALGO == "mcl":
r = cm.mcl(g, setting)
else:
fl = cm.flow_undirected(g)
r = cm.infomap(fl, rng, TRIALS)
return r
setting = gamma if ALGO in ("leiden", "louvain") else (float(INFLATION) if ALGO == "mcl" else None)
res = find(setting)
labels = csc.canonical(np.asarray(res["labels"], dtype=np.int64)) # 1…k by size, ties by first node
lab0 = (labels - 1).tolist()
k = int(labels.max())
values["k"] = k
if "levels" in res:
values["levels"] = res["levels"]
if "iterations" in res:
values["iterations"] = res["iterations"]
if "sweeps" in res:
values["sweeps"] = res["sweeps"]
if "converged" in res:
values["converged"] = bool(res["converged"])
if not res["converged"]:
warnings.append(f"{LABELS[ALGO]} stopped at its iteration limit before every node settled.")
if "attractors" in res:
values["attractors"] = res["attractors"]
if ALGO == "infomap":
values["codelength"] = res["codelength"]
values["codelength_one"] = res["one_module"]
# %% Quality of the partition
values["modularity"] = cm.modularity(g, lab0, 1.0)
if ALGO in ("leiden", "louvain"):
values["quality"] = cm.cpm(g, lab0, gamma) if QUALITY == "cpm" else cm.modularity(g, lab0, gamma)
values["coverage"] = cm.coverage(g, lab0)
cond = cm.conductance(g, lab0)
finite = [c for c in cond if c == c]
values["conductance"] = float(np.mean(finite)) if finite else None
conn = cm.connected(g, lab0)
values["n_disconnected"] = int(sum(1 for x in conn if not x))
if values["n_disconnected"]:
warnings.append(f"{values['n_disconnected']} of {k} communities fall apart into separate pieces of the network.")
sizes = np.bincount(labels, minlength=k + 1)[1:]
for c in range(1, k + 1):
values[f"size[{c}]"] = int(sizes[c - 1])
values["largest_share"] = float(sizes.max() / N)
values["singletons"] = int(np.sum(sizes == 1))
check = csc.validation(X, labels, truth, cap=3000, seed=SEED)
check.pop("_widths")
values.update(check)
# %% Settings compared
if SWEEP and ALGO in ("leiden", "louvain", "mcl"):
grid = [gamma * f for f in (0.25, 0.5, 1.0, 2.0, 4.0)] if ALGO != "mcl" else [1.4, 1.6, 2.0, 2.5, 3.0, 4.0]
srows = []
for i, s in enumerate(grid, start=1):
lab_s = csc.canonical(np.asarray(find(s)["labels"], dtype=np.int64))
ks = int(lab_s.max())
qs = cm.modularity(g, (lab_s - 1).tolist(), 1.0)
values[f"sweep_setting[{i}]"] = s
values[f"sweep_k[{i}]"] = ks
values[f"sweep_modularity[{i}]"] = qs
srows.append({"setting": s, "k": ks, "modularity": qs})
what = "Inflation" if ALGO == "mcl" else "Resolution"
tables.append({
"key": "sweep", "title": f"Communities at other settings ({what.lower()})",
"columns": [{"key": "setting", "label": what, "type": "number"}, {"key": "k", "label": "Communities", "type": "integer"},
{"key": "modularity", "label": "Modularity", "type": "number"}],
"rows": srows,
})
chosen = [abs(s - setting) < 1e-12 for s in grid]
charts.append(cs.chart(
"sweep", "elbow-plot", f"Communities by {what.lower()}",
{"k": cs.col(what, grid + grid, "numeric"), "score": cs.col("Value", [r["k"] for r in srows] + [r["modularity"] for r in srows], "numeric"),
"criterion": cs.col("Measure", ["Communities"] * len(grid) + ["Modularity"] * len(grid), "categorical", ["Communities", "Modularity"]),
"chosen": cs.col("This run", chosen + chosen, "boolean")},
note=f"The ringed point is this run's {what.lower()}.",
))
# %% Communities table
crows = []
for c in range(1, k + 1):
member = labels == c
row = {"community": c, "size": int(sizes[c - 1]), "share": float(sizes[c - 1] / N),
"conductance": cond[c - 1] if cond[c - 1] == cond[c - 1] else None, "connected": bool(conn[c - 1])}
for f in FEATURES:
if KINDS[f] == "numeric":
row[f] = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
crows.append(row)
tables.insert(0, {
"key": "communities", "title": "Communities",
"columns": [{"key": "community", "label": "Community", "type": "integer"}, {"key": "size", "label": "Rows", "type": "integer"},
{"key": "share", "label": "Share", "type": "percent"}, {"key": "conductance", "label": "Conductance", "type": "number"},
{"key": "connected", "label": "In one piece", "type": "boolean"}]
+ [{"key": f, "label": f, "type": "number"} for f in FEATURES if KINDS[f] == "numeric"],
"rows": crows,
})
# %% Results per node (or row) and charts
level_names = [str(c) for c in range(1, k + 1)]
artifacts.append({"key": "labels", "path": csc.write_labels(out, rows, labels), "format": "parquet"})
P, _, axes = csc.project2(X, None, names)
show = csc.even_sample(N)
charts.append(cs.chart(
"clusters", "cluster-scatter", "Communities",
{
"x": cs.col(axes[0], list(P[show, 0]), "numeric"),
"y": cs.col(axes[1], list(P[show, 1]), "numeric"),
"cluster": cs.col("Community", [str(c) for c in labels[show]], "categorical", levels=level_names),
"label": cs.col("Row", [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]], "categorical") if ROW_ID else None,
},
note=None if len(show) == N else f"{len(show):,} of {N:,} rows shown.",
))
charts.append(cs.chart("sizes", "bar", "Community sizes", {"x": cs.col("Community", [str(c) for c in labels], "categorical", level_names)},
controls={"top": 30}))
# %% Result
what = "rows" if values["mode"] == "rows" else "nodes"
summary = (f"{LABELS[ALGO]} found {k} communit{'y' if k == 1 else 'ies'} among {N:,} {what}; "
f"{values['coverage']:.0%} of the edge weight falls inside them (modularity {values['modularity']:.3f}).")
if ALGO == "infomap":
summary += f" The map describes the walk in {values['codelength']:.3f} bits per step, against {values['codelength_one']:.3f} with one module."
publish = {
"title": "Network communities",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": N,
"summary": summary,
"statistics": [
{"key": "k", "label": "Communities", "value": k, "format": "integer"},
{"key": "modularity", "label": "Modularity", "value": values["modularity"]},
{"key": "coverage", "label": "Edge weight inside", "value": values["coverage"], "format": "percent"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": artifacts,
}
publish["model"] = {"kind": "clusterer", "features": names, "params": {
"algorithm": "louvain",
"quality": "modularity",
"resolution": None,
"inflation": 2,
"trials": 5,
"directed": False,
"n_neighbors": 15,
"sweep": False,
"nodes": None,
"scale": "standard",
"missing": "drop",
}}
cs.publish(publish)
Blocks that link alike
ReadCommunities are only one shape a network can have. A stochastic blockmodelStochastic blockmodelA network model where each node sits in one block and the chance of a link depends only on the two nodes' blocks. puts every node in a block and lets the chance of a link depend only on the two blocks. Its block matrixBlock matrixThe link probability (or degree-scaled rate) between every pair of blocks; a heavy diagonal means communities. says what the blocks are: a heavy diagonal means communities; a dense core block linked to a sparse periphery means core and periphery; an empty diagonal means two sides that only link across.
The stochastic blockmodel puts 49 nodes in 2 blocks (chosen by BIC); the average node sits in its block with probability 1.000.
- Blocks
- 2
- ICL
- −348.54
- Mean certainty
- 1.0000
Plots
View data
| With block | Block | Link probability |
|---|---|---|
| Block 1 | Block 1 | 0.0121 |
| Block 2 | Block 1 | 0.3154 |
| Block 1 | Block 2 | 0.3154 |
| Block 2 | Block 2 | 0.8444 |
Higher is better; BIC chose 2 blocks.
View data
| Best | Criterion | Blocks | Criterion |
|---|---|---|---|
| false | ICL | 1 | −489.40 |
| true | ICL | 2 | −348.54 |
| false | ICL | 3 | −376.59 |
| false | ICL | 4 | −380.27 |
| false | BIC | 1 | −489.40 |
| true | BIC | 2 | −348.54 |
| false | BIC | 3 | −359.65 |
| false | BIC | 4 | −376.32 |
Nodes sorted by block: each tile of the matrix is one pair of blocks.
View data
| Column | Block | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 1 | 2 | c01 | 30 | 0 | 1 |
| 2 | 2 | c02 | 43 | 0 | 1 |
| 3 | 2 | c03 | 22 | 0 | 1 |
| 4 | 2 | c04 | 23 | 0 | 1 |
| 5 | 2 | c05 | 31 | 0 | 1 |
| 6 | 2 | c06 | 12 | 0 | 1 |
| 7 | 2 | c07 | 25 | 0 | 1 |
| 8 | 2 | c08 | 32 | 0 | 1 |
| 9 | 2 | c09 | 40 | 0 | 1 |
| 10 | 2 | c10 | 45 | 0 | 1 |
| 12 | 1 | p01 | 46 | 0 | 1 |
| 14 | 1 | p02 | 47 | 0 | 1 |
| 15 | 1 | p03 | 48 | 0 | 1 |
| 16 | 1 | p04 | 17 | 0 | 1 |
| 17 | 1 | p05 | 18 | 0 | 1 |
| 19 | 1 | p06 | 24 | 0 | 1 |
| 23 | 1 | p08 | 26 | 0 | 1 |
| 25 | 1 | p09 | 33 | 0 | 1 |
| 30 | 1 | p10 | 35 | 0 | 1 |
| 31 | 1 | p11 | 44 | 0 | 1 |
| 32 | 1 | p12 | 10 | 0 | 1 |
| 33 | 1 | p13 | 11 | 0 | 1 |
| 34 | 1 | p14 | 14 | 0 | 1 |
| 35 | 1 | p15 | 16 | 0 | 1 |
| 36 | 1 | p16 | 19 | 0 | 1 |
| 39 | 1 | p17 | 21 | 0 | 1 |
| 47 | 1 | p18 | 41 | 0 | 1 |
| 2 | 1 | p19 | 15 | 1 | 1 |
| 3 | 1 | p20 | 20 | 1 | 1 |
| 4 | 1 | p21 | 27 | 1 | 1 |
| 5 | 1 | p22 | 34 | 1 | 1 |
| 6 | 1 | p23 | 38 | 1 | 1 |
| 8 | 1 | p24 | 39 | 1 | 1 |
| 9 | 1 | p25 | 42 | 1 | 1 |
| 11 | 1 | p26 | 13 | 1 | 1 |
| 18 | 1 | p27 | 28 | 1 | 1 |
| 19 | 1 | p28 | 29 | 1 | 1 |
| 21 | 1 | p29 | 36 | 1 | 1 |
| 22 | 1 | p30 | 37 | 1 | 1 |
| 25 | 1 | p31 | 0 | 1 | 1 |
| 32 | 1 | p32 | 1 | 1 | 1 |
| 40 | 1 | p33 | 5 | 1 | 1 |
| 41 | 1 | p34 | 2 | 1 | 1 |
| 42 | 1 | p35 | 4 | 1 | 1 |
| 43 | 1 | p36 | 9 | 1 | 1 |
| 45 | 1 | p37 | 7 | 1 | 1 |
| 46 | 1 | p38 | 3 | 1 | 1 |
| 48 | 1 | p39 | 6 | 1 | 1 |
| 4 | 1 | p40 | 8 | 2 | 1 |
| 5 | — | — | — | 2 | 1 |
| 6 | — | — | — | 2 | 1 |
| 7 | — | — | — | 2 | 1 |
| 8 | — | — | — | 2 | 1 |
| 11 | — | — | — | 2 | 1 |
| 12 | — | — | — | 2 | 1 |
| 13 | — | — | — | 2 | 1 |
| 14 | — | — | — | 2 | 1 |
| 17 | — | — | — | 2 | 1 |
| 23 | — | — | — | 2 | 1 |
| 24 | — | — | — | 2 | 1 |
First 60 of 170 rows.
View data
| From | Block | Node | Degree | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 2 | c01 | 27 | 1 | 0.0647 | 0.2206 |
| 0 | 2 | c02 | 22 | 2 | −0.0703 | −0.0522 |
| 0 | 2 | c03 | 21 | 3 | 0.0556 | −0.2756 |
| 0 | 2 | c04 | 17 | 4 | 0.0011 | 0.1048 |
| 0 | 2 | c05 | 21 | 5 | −0.2148 | −0.0705 |
| 0 | 2 | c06 | 22 | 6 | 0.0092 | −0.1142 |
| 0 | 2 | c07 | 16 | 7 | 0.1814 | 0.0672 |
| 0 | 2 | c08 | 19 | 8 | 0.2416 | −0.1651 |
| 0 | 2 | c09 | 14 | 9 | −0.0366 | −0.1490 |
| 0 | 2 | c10 | 20 | 10 | −0.2293 | 0.1655 |
| 0 | 1 | p01 | 3 | 12 | −0.3715 | 0.6393 |
| 0 | 1 | p02 | 3 | 14 | −0.4997 | −0.1871 |
| 0 | 1 | p03 | 5 | 15 | 0.1987 | −0.2454 |
| 0 | 1 | p04 | 1 | 16 | 0.1736 | −1 |
| 0 | 1 | p05 | 3 | 17 | 0.1100 | −0.4102 |
| 0 | 1 | p06 | 2 | 19 | 0.4894 | 0.5501 |
| 0 | 1 | p08 | 3 | 23 | −0.5082 | 0.3244 |
| 0 | 1 | p09 | 4 | 25 | 0.5402 | −0.0508 |
| 0 | 1 | p10 | 4 | 30 | 0.4464 | 0.0612 |
| 0 | 1 | p11 | 3 | 31 | 0.0994 | 0.5200 |
| 0 | 1 | p12 | 2 | 32 | −0.3263 | −0.4763 |
| 0 | 1 | p13 | 3 | 33 | −0.4702 | −0.3604 |
| 0 | 1 | p14 | 6 | 34 | 0.1060 | −0.0352 |
| 0 | 1 | p15 | 6 | 35 | 0.2189 | 0.1485 |
| 0 | 1 | p16 | 4 | 36 | −0.3539 | −0.0189 |
| 0 | 1 | p17 | 5 | 39 | −0.1623 | 0.3314 |
| 0 | 1 | p18 | 4 | 47 | 0.1637 | −0.5505 |
| 1 | 1 | p19 | 2 | 2 | −0.1921 | 0.6509 |
| 1 | 1 | p20 | 1 | 3 | −0.9067 | −0.2940 |
| 1 | 1 | p21 | 1 | 4 | −0.8718 | 0.4965 |
| 1 | 1 | p22 | 8 | 5 | −0.0443 | 0.0333 |
| 1 | 1 | p23 | 6 | 6 | −0.2952 | 0.1515 |
| 1 | 1 | p24 | 5 | 8 | 0.3638 | 0.2121 |
| 1 | 1 | p25 | 4 | 9 | −0.4595 | 0.1276 |
| 1 | 1 | p26 | 2 | 11 | 0.5505 | 0.2952 |
| 1 | 1 | p27 | 4 | 18 | 0.3660 | −0.1414 |
| 1 | 1 | p28 | 1 | 19 | 0.3536 | 0.8868 |
| 1 | 1 | p29 | 1 | 21 | 0.8376 | −0.5543 |
| 1 | 1 | p30 | 2 | 22 | 0.7614 | −0.1230 |
| 1 | 1 | p31 | 2 | 25 | −0.1585 | 0.8464 |
| 1 | 1 | p32 | 5 | 32 | −0.3514 | 0.4490 |
| 1 | 1 | p33 | 3 | 40 | −0.1077 | −0.5990 |
| 1 | 1 | p34 | 2 | 41 | 0.2435 | −0.6710 |
| 1 | 1 | p35 | 7 | 42 | −0.0037 | 0.3144 |
| 1 | 1 | p36 | 4 | 43 | 0.3518 | −0.3309 |
| 1 | 1 | p37 | 5 | 45 | −0.1879 | −0.3302 |
| 1 | 1 | p38 | 5 | 46 | −0.0777 | −0.3903 |
| 1 | 1 | p39 | 5 | 48 | 0.2471 | 0.2456 |
| 2 | 1 | p40 | 5 | 4 | −0.2757 | −0.2468 |
| 2 | — | — | — | 5 | — | — |
| 2 | — | — | — | 6 | — | — |
| 2 | — | — | — | 7 | — | — |
| 2 | — | — | — | 8 | — | — |
| 2 | — | — | — | 11 | — | — |
| 2 | — | — | — | 12 | — | — |
| 2 | — | — | — | 13 | — | — |
| 2 | — | — | — | 14 | — | — |
| 2 | — | — | — | 17 | — | — |
| 2 | — | — | — | 23 | — | — |
| 2 | — | — | — | 24 | — | — |
First 60 of 170 rows.
Blocks
| Block | Nodes | Model share | Link probability within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 39 | 79.6% | 0.0121 | 1.0000 | p22, p35, p14 |
| 2 | 10 | 20.4% | 0.8444 | 1.0000 | c01, c02, c06 |
Link probability between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.0121 | 0.3154 |
| Block 2 | 0.3154 | 0.8444 |
Number of blocks
| Blocks | ICL | BIC | Lower bound |
|---|---|---|---|
| 1 | −489.40 | −489.40 | −485.87 |
| 2 | −348.54 | −348.54 | −335.99 |
| 3 | −376.59 | −359.65 | −334.55 |
| 4 | −380.27 | −376.32 | −335.13 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Stochastic blockmodel
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sbm 1.0.0 · spec be4cf769b2dd9671
# Dataset: grf2_coreper_edges (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ml_sbm_*(): twin of codesplash.ml.sbm
MODEL <- "bernoulli"
BLOCKS <- NULL
MAX_BLOCKS <- 4
CRITERION <- "bic"
STARTS <- 3L
SEED <- 42
MODEL_LABELS <- c(bernoulli = "stochastic blockmodel", poisson_dc = "degree-corrected blockmodel")
CRITERION_LABELS <- c(icl = "ICL", bic = "BIC")
# %% The network the host built (canonical node order, merged edges; cs_graph_read)
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.sbm/coreper_bic/out-r")
G <- cs_graph_read(out)
warnings <- as.list(G$warnings)
N <- G$n
pairs <- cs_graph_undirected_pairs(G) # direction set aside; repeated edges add up
a <- pairs$a; b <- pairs$b; w <- pairs$w
if (N > 2000 || length(a) > 200000) cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(a), max_nodes = 2000, max_edges = 200000)
if (N < 3 || length(a) == 0) cs_error("CS_E_UNDEFINED", what = "A stochastic blockmodel", reason = "it needs at least 3 nodes and one edge between two different nodes")
if (any(w < 0)) cs_error("CS_E_INVALID_VALUES", column = if (!is.null(G$meta$weight)) G$meta$weight else "Edge count", requirement = "zero or more", count = sum(w < 0))
if (isTRUE(G$directed)) warnings <- c(warnings, "The blockmodel treats every edge as two-way, so the directions were set aside.")
A <- matrix(0, N, N)
if (MODEL == "bernoulli") {
A[cbind(a + 1L, b + 1L)] <- 1
if (isTRUE(G$weighted)) warnings <- c(warnings, "The plain blockmodel reads whether two nodes are linked, so edge weights were set aside.")
} else {
A[cbind(a + 1L, b + 1L)] <- w # link counts (1 per edge row without a weight column)
}
A[cbind(b + 1L, a + 1L)] <- A[cbind(a + 1L, b + 1L)]
values <- list(n_nodes = N, n_edges = length(a), density = length(a) / (N * (N - 1) / 2),
model_label = MODEL_LABELS[[MODEL]], criterion_label = if (is.null(BLOCKS)) CRITERION_LABELS[[CRITERION]] else "you")
# %% Fit: variational EM from k-means++ / Lloyd starts on the rows of A (shared stream)
rng <- cs_rng(SEED)
if (is.null(BLOCKS)) {
q_max <- max(1, min(MAX_BLOCKS, N - 1))
sel <- cs_ml_sbm_select(A, q_max, MODEL, rng, STARTS, CRITERION)
Q <- sel$best
fits <- sel$fits
best <- fits[[Q]]
} else {
Q <- as.integer(BLOCKS)
if (Q > N - 1) cs_error("CS_E_INVALID_OPTION", option = "Blocks", allowed = sprintf("at most %d for %d nodes", N - 1, N), value = Q)
best <- cs_ml_sbm_fit(A, Q, MODEL, rng, STARTS)
fits <- NULL
}
cn <- cs_ml_sbm_canonical(best$tau, best$alpha, best$rate)
lab <- cn$labels; tau <- cn$tau; alpha <- cn$alpha; rate <- cn$rate
block <- lab + 1L # 1..Q by size, ties by first node
values$blocks <- Q
values$icl <- best$icl; values$bic <- best$bic; values$loglik <- best$loglik
values$elbo <- best$J
values$converged <- isTRUE(best$converged)
if (!isTRUE(best$converged)) warnings <- c(warnings, "Variational EM stopped at its iteration limit before the lower bound settled.")
certainty <- apply(tau, 1, max)
values$certainty <- mean(certainty)
sizes <- tabulate(block, nbins = Q)
edges <- matrix(0, Q, Q)
for (e in seq_along(a)) {
p <- min(lab[a[e] + 1L], lab[b[e] + 1L]) + 1L; q <- max(lab[a[e] + 1L], lab[b[e] + 1L]) + 1L
edges[p, q] <- edges[p, q] + if (MODEL == "bernoulli") 1 else w[e]
}
for (q in seq_len(Q)) {
values[[sprintf("size[%d]", q)]] <- sizes[q]
values[[sprintf("share[%d]", q)]] <- alpha[q]
for (l in q:Q) {
values[[sprintf("rate[%d,%d]", q, l)]] <- rate[q, l]
values[[sprintf("edges[%d,%d]", q, l)]] <- edges[q, l]
}
}
if (!is.null(fits)) {
for (i in seq_along(fits)) {
values[[sprintf("icl[%d]", i)]] <- fits[[i]]$icl
values[[sprintf("bic[%d]", i)]] <- fits[[i]]$bic
}
}
if (!is.null(G$label)) {
truth <- as.character(G$nodes[[G$label]])
ok <- !is.na(truth)
values$n_labeled <- sum(ok)
if (sum(ok) >= 2) {
values$ari <- cs_ml_ari(truth[ok], block[ok])
values$ami <- cs_ml_ami(truth[ok], block[ok])
values$nmi <- cs_ml_nmi(truth[ok], block[ok])
}
}
# %% Tables
rate_label <- if (MODEL == "bernoulli") "Link probability" else "Rate per degree pair (λ)"
deg <- rowSums(A)
brows <- list()
for (q in seq_len(Q)) {
members <- which(block == q)
top <- members[order(-deg[members], members)][seq_len(min(3L, length(members)))]
brows[[q]] <- list(block = q, size = sizes[q], share = alpha[q], within = rate[q, q],
certainty = if (length(members)) mean(certainty[members]) else NULL,
examples = paste(G$node_id[top], collapse = ", "))
}
tables <- list(list(
key = "blocks", title = "Blocks",
columns = list(list(key = "block", label = "Block", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
list(key = "share", label = "Model share", type = "percent"), list(key = "within", label = sprintf("%s within", rate_label), type = "number"),
list(key = "certainty", label = "Mean certainty", type = "number"), list(key = "examples", label = "Best-connected nodes")),
rows = brows
))
mrows <- lapply(seq_len(Q), function(q) {
row <- list(block = sprintf("Block %d", q))
for (l in seq_len(Q)) row[[sprintf("b%d", l)]] <- rate[q, l]
row
})
tables[[2]] <- list(
key = "block_matrix", title = sprintf("%s between blocks", rate_label),
columns = c(list(list(key = "block", label = "Block")), lapply(seq_len(Q), function(l) list(key = sprintf("b%d", l), label = sprintf("Block %d", l), type = "number"))),
rows = mrows
)
if (!is.null(fits)) {
tables[[3]] <- list(
key = "selection", title = "Number of blocks",
columns = list(list(key = "blocks", label = "Blocks", type = "integer"), list(key = "icl", label = "ICL", type = "number"),
list(key = "bic", label = "BIC", type = "number"), list(key = "elbo", label = "Lower bound", type = "number")),
rows = lapply(seq_along(fits), function(i) list(blocks = i, icl = fits[[i]]$icl, bic = fits[[i]]$bic, elbo = fits[[i]]$J))
)
}
# %% Node table and charts
artifacts <- list(cs_graph_write_nodes(out, G, data.frame(block = as.integer(block), certainty = certainty, degree = deg)))
names_ <- sprintf("Block %d", seq_len(Q))
level_names <- as.character(seq_len(Q))
charts <- list()
charts[[1]] <- cs_chart("block_matrix", "matrix-heatmap", sprintf("%s between blocks", rate_label), list(
row = cs_col("Block", rep(names_, each = Q), "categorical", names_),
col = cs_col("With block", rep(names_, times = Q), "categorical", names_),
value = cs_col(rate_label, as.vector(t(rate)), "numeric")
), controls = list(scale = "sequential"))
if (!is.null(fits) && length(fits) > 1) {
qs <- seq_along(fits)
icl <- vapply(fits, function(f) f$icl, numeric(1))
bic <- vapply(fits, function(f) f$bic, numeric(1))
charts[[length(charts) + 1L]] <- cs_chart("selection", "elbow-plot", "Choosing the number of blocks", list(
k = cs_col("Blocks", c(qs, qs), "numeric"),
score = cs_col("Criterion", c(icl, bic), "numeric"),
criterion = cs_col("Criterion", c(rep("ICL", length(qs)), rep("BIC", length(qs))), "categorical", c("ICL", "BIC")),
chosen = cs_col("Best", c(qs == which.max(icl), qs == which.max(bic)), "boolean")
), note = sprintf("Higher is better; %s chose %d block%s.", CRITERION_LABELS[[CRITERION]], Q, if (Q != 1) "s" else ""))
}
if (N <= 300) {
morder <- order(block, -deg, seq_len(N)) - 1L
charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by block", list(
row = cs_col("Row", G$si, "numeric"),
col = cs_col("Column", G$sj, "numeric"),
value = cs_col(if (isTRUE(G$weighted)) "Weight" else "Edge", G$sw, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
group = cs_col("Block", as.character(block), "categorical", level_names),
order = cs_col("Order", morder, "numeric")
), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by block: each tile of the matrix is one pair of blocks.")
}
if (N <= 2000) {
xy <- cs_graph_layout_fr(G, SEED)
m <- length(G$si)
show <- min(m, 20000)
keep <- seq_len(show)
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Blocks in the network", list(
x = cs_col("x", xy$x, "numeric"),
y = cs_col("y", xy$y, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
size = cs_col("Degree", deg, "numeric"),
group = cs_col("Block", as.character(block), "categorical", level_names),
from = cs_col("From", G$si[keep], "numeric"),
to = cs_col("To", G$sj[keep], "numeric"),
weight = if (isTRUE(G$weighted)) cs_col("Weight", G$sw[keep], "numeric") else NULL
), controls = list(directed = isTRUE(G$directed)), note = if (show == m) NULL else sprintf("%d of %d edges drawn.", show, m))
}
# %% Result
how <- if (is.null(BLOCKS)) sprintf("chosen by %s", CRITERION_LABELS[[CRITERION]]) else "as set"
summary <- sprintf("The %s puts %s nodes in %d block%s (%s); the average node sits in its block with probability %.3f.",
MODEL_LABELS[[MODEL]], format(N, big.mark = ","), Q, if (Q != 1) "s" else "", how, values$certainty)
cs_publish(list(
title = "Stochastic blockmodel",
engine = cs_engine_info("nanoparquet"),
n = N,
summary = summary,
statistics = list(list(key = "blocks", label = "Blocks", value = Q, format = "integer"),
list(key = "icl", label = "ICL", value = values$icl),
list(key = "certainty", label = "Mean certainty", value = values$certainty)),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = artifacts
))
The stochastic blockmodel puts 49 nodes in 2 blocks (chosen by BIC); the average node sits in its block with probability 1.000.
- Blocks
- 2
- ICL
- −348.54
- Mean certainty
- 1.0000
To keep this page light, the plots are shown once, under the R tab.
Blocks
| Block | Nodes | Model share | Link probability within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 39 | 79.6% | 0.0121 | 1.0000 | p22, p35, p14 |
| 2 | 10 | 20.4% | 0.8444 | 1.0000 | c01, c02, c06 |
Link probability between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.0121 | 0.3154 |
| Block 2 | 0.3154 | 0.8444 |
Number of blocks
| Blocks | ICL | BIC | Lower bound |
|---|---|---|---|
| 1 | −489.40 | −489.40 | −485.87 |
| 2 | −348.54 | −348.54 | −335.99 |
| 3 | −376.59 | −359.65 | −334.55 |
| 4 | −380.27 | −376.32 | −335.13 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Stochastic blockmodel
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sbm 1.0.0 · spec be4cf769b2dd9671
# Dataset: grf2_coreper_edges (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import graph as cg
from codesplash import ml as csml
from codesplash.graph import layout as gl
from codesplash.ml import cluster as csc
from codesplash.ml import sbm # twin of codesplashr R/ml_sbm.R
from codesplash.stats.rng import Rng
MODEL = "bernoulli"
BLOCKS = None
MAX_BLOCKS = 4
CRITERION = "bic"
STARTS = 3
SEED = 42
MODEL_LABELS = {"bernoulli": "stochastic blockmodel", "poisson_dc": "degree-corrected blockmodel"}
CRITERION_LABELS = {"icl": "ICL", "bic": "BIC"}
# %% The network the host built (canonical node order, merged edges; codesplash.graph)
out = csml.out_dir("target/academy-parity/run-8142/discover.sbm/coreper_bic/out-python")
G = cg.read(out)
warnings = list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G) # direction set aside; repeated edges add up
if N > 2000 or len(a) > 200000:
cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=2000, max_edges=200000)
if N < 3 or len(a) == 0:
cs.cs_error("CS_E_UNDEFINED", what="A stochastic blockmodel", reason="it needs at least 3 nodes and one edge between two different nodes")
if np.any(w < 0):
cs.cs_error("CS_E_INVALID_VALUES", column=G.meta.get("weight") or "Edge count", requirement="zero or more", count=int(np.sum(w < 0)))
if G.directed:
warnings.append("The blockmodel treats every edge as two-way, so the directions were set aside.")
A = np.zeros((N, N))
if MODEL == "bernoulli":
A[a, b] = 1.0
if G.weighted:
warnings.append("The plain blockmodel reads whether two nodes are linked, so edge weights were set aside.")
else:
A[a, b] = w # link counts (1 per edge row without a weight column)
A[b, a] = A[a, b]
values = {"n_nodes": N, "n_edges": int(len(a)), "density": float(len(a) / (N * (N - 1) / 2.0)),
"model_label": MODEL_LABELS[MODEL], "criterion_label": CRITERION_LABELS[CRITERION] if BLOCKS is None else "you"}
# %% Fit: variational EM from k-means++ / Lloyd starts on the rows of A (shared stream)
rng = Rng(SEED)
if BLOCKS is None:
q_max = max(1, min(MAX_BLOCKS, N - 1))
sel = sbm.select(A, q_max, MODEL, rng, STARTS, CRITERION)
Q = sel["best"]
fits = sel["fits"]
best = fits[Q - 1]
else:
Q = int(BLOCKS)
if Q > N - 1:
cs.cs_error("CS_E_INVALID_OPTION", option="Blocks", allowed=f"at most {N - 1} for {N} nodes", value=Q)
best = sbm.fit(A, Q, MODEL, rng, STARTS)
fits = None
lab, tau, alpha, rate = sbm.canonical(best["tau"], best["alpha"], best["rate"])
block = lab + 1 # 1…Q by size, ties by first node
values["blocks"] = Q
for key in ("icl", "bic", "loglik"):
values[key] = best[key]
values["elbo"] = best["J"]
values["converged"] = bool(best["converged"])
if not best["converged"]:
warnings.append("Variational EM stopped at its iteration limit before the lower bound settled.")
certainty = tau.max(axis=1)
values["certainty"] = float(np.mean(certainty))
sizes = np.bincount(lab, minlength=Q)
edges = np.zeros((Q, Q))
for i, j, x in zip(a.tolist(), b.tolist(), w.tolist()):
p, q = min(lab[i], lab[j]), max(lab[i], lab[j])
edges[p, q] += 1.0 if MODEL == "bernoulli" else x
for q in range(Q):
values[f"size[{q + 1}]"] = int(sizes[q])
values[f"share[{q + 1}]"] = float(alpha[q])
for l in range(q, Q):
values[f"rate[{q + 1},{l + 1}]"] = float(rate[q, l])
values[f"edges[{q + 1},{l + 1}]"] = float(edges[q, l])
if fits is not None:
for i, f in enumerate(fits, start=1):
values[f"icl[{i}]"] = f["icl"]
values[f"bic[{i}]"] = f["bic"]
if G.label:
truth = np.array([None if pd.isna(v) else str(v) for v in G.nodes[G.label].tolist()], dtype=object) # None, NaN, pd.NA
ok = np.array([v is not None for v in truth])
values["n_labeled"] = int(ok.sum())
if ok.sum() >= 2:
tt = truth[ok].astype(str)
values["ari"] = csc.ari(tt, block[ok])
values["ami"] = csc.ami(tt, block[ok])
values["nmi"] = csc.nmi(tt, block[ok])
# %% Tables
rate_label = "Link probability" if MODEL == "bernoulli" else "Rate per degree pair (λ)"
deg = A.sum(axis=1)
brows = []
for q in range(Q):
members = np.flatnonzero(lab == q)
top = sorted(members.tolist(), key=lambda v: (-deg[v], v))[:3]
brows.append({"block": q + 1, "size": int(sizes[q]), "share": float(alpha[q]), "within": float(rate[q, q]),
"certainty": float(np.mean(certainty[members])) if len(members) else None,
"examples": ", ".join(G.node_id[v] for v in top)})
tables = [{
"key": "blocks", "title": "Blocks",
"columns": [{"key": "block", "label": "Block", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
{"key": "share", "label": "Model share", "type": "percent"}, {"key": "within", "label": f"{rate_label} within", "type": "number"},
{"key": "certainty", "label": "Mean certainty", "type": "number"}, {"key": "examples", "label": "Best-connected nodes"}],
"rows": brows,
}]
mrows = []
for q in range(Q):
row = {"block": f"Block {q + 1}"}
for l in range(Q):
row[f"b{l + 1}"] = float(rate[q, l])
mrows.append(row)
tables.append({
"key": "block_matrix", "title": f"{rate_label} between blocks",
"columns": [{"key": "block", "label": "Block"}] + [{"key": f"b{l + 1}", "label": f"Block {l + 1}", "type": "number"} for l in range(Q)],
"rows": mrows,
})
if fits is not None:
tables.append({
"key": "selection", "title": "Number of blocks",
"columns": [{"key": "blocks", "label": "Blocks", "type": "integer"}, {"key": "icl", "label": "ICL", "type": "number"},
{"key": "bic", "label": "BIC", "type": "number"}, {"key": "elbo", "label": "Lower bound", "type": "number"}],
"rows": [{"blocks": i, "icl": f["icl"], "bic": f["bic"], "elbo": f["J"]} for i, f in enumerate(fits, start=1)],
})
# %% Node table and charts
artifacts = [cg.write_nodes(out, G, {"block": block.astype(np.int64), "certainty": certainty, "degree": deg})]
names = [f"Block {q + 1}" for q in range(Q)]
level_names = [str(q + 1) for q in range(Q)]
charts = []
cells_r, cells_c, cells_v = [], [], []
for q in range(Q):
for l in range(Q):
cells_r.append(names[q])
cells_c.append(names[l])
cells_v.append(float(rate[q, l]))
charts.append(cs.chart("block_matrix", "matrix-heatmap", f"{rate_label} between blocks", {
"row": cs.col("Block", cells_r, "categorical", names),
"col": cs.col("With block", cells_c, "categorical", names),
"value": cs.col(rate_label, cells_v, "numeric"),
}, controls={"scale": "sequential"}))
if fits is not None and len(fits) > 1:
qs = list(range(1, len(fits) + 1))
icl = [f["icl"] for f in fits]
bic = [f["bic"] for f in fits]
charts.append(cs.chart("selection", "elbow-plot", "Choosing the number of blocks", {
"k": cs.col("Blocks", qs + qs, "numeric"),
"score": cs.col("Criterion", icl + bic, "numeric"),
"criterion": cs.col("Criterion", ["ICL"] * len(qs) + ["BIC"] * len(qs), "categorical", ["ICL", "BIC"]),
"chosen": cs.col("Best", [q == 1 + int(np.argmax(icl)) for q in qs] + [q == 1 + int(np.argmax(bic)) for q in qs], "boolean"),
}, note=f"Higher is better; {CRITERION_LABELS[CRITERION]} chose {Q} block{'s' if Q != 1 else ''}."))
if N <= 300:
morder = sorted(range(N), key=lambda v: (int(block[v]), -deg[v], v))
charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by block", {
"row": cs.col("Row", G.si, "numeric"),
"col": cs.col("Column", G.sj, "numeric"),
"value": cs.col("Weight" if G.weighted else "Edge", G.sw, "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"group": cs.col("Block", [str(q) for q in block], "categorical", level_names),
"order": cs.col("Order", morder, "numeric"),
}, controls={"directed": G.directed}, note="Nodes sorted by block: each tile of the matrix is one pair of blocks."))
if N <= 2000:
xy = gl.fruchterman_reingold(G, SEED)
m = len(G.si)
show = min(m, 20000)
charts.append(cs.chart("map", "network-graph", "Blocks in the network", {
"x": cs.col("x", xy[0], "numeric"),
"y": cs.col("y", xy[1], "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"size": cs.col("Degree", deg, "numeric"),
"group": cs.col("Block", [str(q) for q in block], "categorical", level_names),
"from": cs.col("From", G.si[:show], "numeric"),
"to": cs.col("To", G.sj[:show], "numeric"),
"weight": cs.col("Weight", G.sw[:show], "numeric") if G.weighted else None,
}, controls={"directed": G.directed}, note=None if show == m else f"{show} of {m} edges drawn."))
# %% Result
how = f"chosen by {CRITERION_LABELS[CRITERION]}" if BLOCKS is None else "as set"
summary = (f"The {MODEL_LABELS[MODEL]} puts {N:,} nodes in {Q} block{'s' if Q != 1 else ''} ({how}); "
f"the average node sits in its block with probability {values['certainty']:.3f}.")
cs.publish({
"title": "Stochastic blockmodel",
"engine": cs.engine_info("numpy", "pandas", "scikit-learn"),
"n": N,
"summary": summary,
"statistics": [
{"key": "blocks", "label": "Blocks", "value": Q, "format": "integer"},
{"key": "icl", "label": "ICL", "value": values["icl"]},
{"key": "certainty", "label": "Mean certainty", "value": values["certainty"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": artifacts,
})
View data
| variable | with | r |
|---|---|---|
| age | age | 1 |
| age | BMI | 0.1207 |
| age | systolic BP | 0.1471 |
| age | cholesterol | 0.1467 |
| age | glucose | 0.1912 |
| age | activity | −0.1247 |
| BMI | age | 0.1207 |
| BMI | BMI | 1 |
| BMI | systolic BP | 0.3132 |
| BMI | cholesterol | 0.3194 |
| BMI | glucose | 0.3629 |
| BMI | activity | −0.1770 |
| systolic BP | age | 0.1471 |
| systolic BP | BMI | 0.3132 |
| systolic BP | systolic BP | 1 |
| systolic BP | cholesterol | 0.4537 |
| systolic BP | glucose | 0.5647 |
| systolic BP | activity | −0.3672 |
| cholesterol | age | 0.1467 |
| cholesterol | BMI | 0.3194 |
| cholesterol | systolic BP | 0.4537 |
| cholesterol | cholesterol | 1 |
| cholesterol | glucose | 0.6006 |
| cholesterol | activity | −0.3861 |
| glucose | age | 0.1912 |
| glucose | BMI | 0.3629 |
| glucose | systolic BP | 0.5647 |
| glucose | cholesterol | 0.6006 |
| glucose | glucose | 1 |
| glucose | activity | −0.4105 |
| activity | age | −0.1247 |
| activity | BMI | −0.1770 |
| activity | systolic BP | −0.3672 |
| activity | cholesterol | −0.3861 |
| activity | glucose | −0.4105 |
| activity | activity | 1 |
The plain model tends to give hubs a block of their own. The degree-corrected modelDegree-corrected blockmodelA blockmodel whose link counts scale with both nodes' degrees, so hubs share a block with nodes that link to the same places. scales each pair's link rate by both nodes' degrees, so blocks group nodes by whom they link to, not how many. On the karate club with two blocks, it recovers the split almost exactly (adjusted Rand index 0.88).
The degree-corrected blockmodel puts 34 nodes in 2 blocks (as set); the average node sits in its block with probability 0.964.
- Blocks
- 2
- ICL
- −198.48
- Mean certainty
- 0.9636
Plots
View data
| With block | Block | Rate per degree pair (λ) |
|---|---|---|
| Block 1 | Block 1 | 0.0121 |
| Block 2 | Block 1 | 0.0018 |
| Block 1 | Block 2 | 0.0018 |
| Block 2 | Block 2 | 0.0123 |
Nodes sorted by block: each tile of the matrix is one pair of blocks.
View data
| Column | Block | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 1 | 2 | 0 | 27 | 0 | 1 |
| 2 | 2 | 1 | 26 | 0 | 1 |
| 3 | 2 | 10 | 25 | 0 | 1 |
| 4 | 2 | 11 | 16 | 0 | 1 |
| 5 | 2 | 12 | 32 | 0 | 1 |
| 9 | 2 | 13 | 20 | 0 | 1 |
| 11 | 1 | 14 | 22 | 0 | 1 |
| 12 | 1 | 15 | 24 | 0 | 1 |
| 14 | 2 | 16 | 17 | 0 | 1 |
| 23 | 2 | 17 | 18 | 0 | 1 |
| 25 | 1 | 18 | 21 | 0 | 1 |
| 28 | 2 | 19 | 6 | 0 | 1 |
| 29 | 2 | 2 | 7 | 0 | 1 |
| 30 | 1 | 20 | 10 | 0 | 1 |
| 31 | 2 | 21 | 13 | 0 | 1 |
| 32 | 1 | 22 | 15 | 0 | 1 |
| 5 | 1 | 23 | 19 | 1 | 1 |
| 9 | 1 | 24 | 33 | 1 | 1 |
| 11 | 1 | 25 | 0 | 1 | 1 |
| 12 | 1 | 26 | 12 | 1 | 1 |
| 14 | 1 | 27 | 1 | 1 | 1 |
| 23 | 1 | 28 | 23 | 1 | 1 |
| 24 | 1 | 29 | 5 | 1 | 1 |
| 31 | 2 | 3 | 29 | 1 | 1 |
| 28 | 1 | 30 | 30 | 2 | 1 |
| 29 | 1 | 31 | 31 | 2 | 1 |
| 23 | 1 | 32 | 2 | 4 | 1 |
| 12 | 1 | 33 | 11 | 5 | 1 |
| 23 | 2 | 4 | 28 | 5 | 1 |
| 27 | 2 | 5 | 4 | 5 | 1 |
| 26 | 2 | 6 | 8 | 6 | 1 |
| 27 | 2 | 7 | 9 | 6 | 1 |
| 26 | 1 | 8 | 14 | 7 | 1 |
| 27 | 1 | 9 | 3 | 7 | 1 |
| 29 | — | — | — | 8 | 1 |
| 30 | — | — | — | 8 | 1 |
| 26 | — | — | — | 10 | 1 |
| 27 | — | — | — | 10 | 1 |
| 27 | — | — | — | 11 | 1 |
| 20 | — | — | — | 12 | 1 |
| 21 | — | — | — | 12 | 1 |
| 23 | — | — | — | 12 | 1 |
| 26 | — | — | — | 12 | 1 |
| 31 | — | — | — | 12 | 1 |
| 32 | — | — | — | 12 | 1 |
| 33 | — | — | — | 12 | 1 |
| 26 | — | — | — | 13 | 1 |
| 27 | — | — | — | 13 | 1 |
| 26 | — | — | — | 15 | 1 |
| 27 | — | — | — | 15 | 1 |
| 18 | — | — | — | 16 | 1 |
| 20 | — | — | — | 16 | 1 |
| 22 | — | — | — | 16 | 1 |
| 26 | — | — | — | 16 | 1 |
| 27 | — | — | — | 16 | 1 |
| 18 | — | — | — | 17 | 1 |
| 20 | — | — | — | 17 | 1 |
| 25 | — | — | — | 17 | 1 |
| 25 | — | — | — | 18 | 1 |
| 22 | — | — | — | 19 | 1 |
First 60 of 78 rows.
View data
| From | Block | Node | Degree | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 2 | 0 | 16 | 1 | −0.3181 | −0.2545 |
| 0 | 2 | 1 | 9 | 2 | −0.2233 | −0.0757 |
| 0 | 2 | 10 | 3 | 3 | −0.5988 | −0.5538 |
| 0 | 2 | 11 | 1 | 4 | −0.7684 | −0.3116 |
| 0 | 2 | 12 | 2 | 5 | −0.5555 | −0.3153 |
| 0 | 2 | 13 | 5 | 9 | −0.0383 | −0.1016 |
| 0 | 1 | 14 | 2 | 11 | 0.6563 | 0.2455 |
| 0 | 1 | 15 | 2 | 12 | 0.5571 | −0.0469 |
| 0 | 2 | 16 | 2 | 14 | −0.5525 | −1 |
| 0 | 2 | 17 | 2 | 23 | −0.5518 | −0.1334 |
| 0 | 1 | 18 | 2 | 25 | 0.6951 | 0.1440 |
| 0 | 2 | 19 | 3 | 28 | −0.1218 | 0.0626 |
| 0 | 2 | 2 | 10 | 29 | −0.0184 | 0.0461 |
| 0 | 1 | 20 | 2 | 30 | 0.6496 | 0.0363 |
| 0 | 2 | 21 | 2 | 31 | −0.5239 | −0.0045 |
| 0 | 1 | 22 | 2 | 32 | 0.6464 | 0.3546 |
| 1 | 1 | 23 | 5 | 5 | 0.3325 | 0.4993 |
| 1 | 1 | 24 | 3 | 9 | −0.0504 | 0.6329 |
| 1 | 1 | 25 | 3 | 11 | 0.1108 | 0.6623 |
| 1 | 1 | 26 | 2 | 12 | 0.6203 | 0.5661 |
| 1 | 1 | 27 | 4 | 14 | 0.1293 | 0.4353 |
| 1 | 1 | 28 | 3 | 23 | 0.1494 | 0.2290 |
| 1 | 1 | 29 | 4 | 24 | 0.5085 | 0.4495 |
| 1 | 2 | 3 | 6 | 31 | −0.2882 | −0.1638 |
| 2 | 1 | 30 | 4 | 28 | 0.2164 | −0.0296 |
| 2 | 1 | 31 | 6 | 29 | 0.0165 | 0.2593 |
| 4 | 1 | 32 | 12 | 23 | 0.4004 | 0.1628 |
| 5 | 1 | 33 | 17 | 12 | 0.3249 | 0.2115 |
| 5 | 2 | 4 | 3 | 23 | −0.4335 | −0.5876 |
| 5 | 2 | 5 | 4 | 27 | −0.5362 | −0.7094 |
| 6 | 2 | 6 | 4 | 26 | −0.4075 | −0.7379 |
| 6 | 2 | 7 | 4 | 27 | −0.1466 | −0.2632 |
| 7 | 1 | 8 | 5 | 26 | 0.1237 | −0.0736 |
| 7 | 1 | 9 | 2 | 27 | −0.0040 | 0.3656 |
| 8 | — | — | — | 29 | — | — |
| 8 | — | — | — | 30 | — | — |
| 10 | — | — | — | 26 | — | — |
| 10 | — | — | — | 27 | — | — |
| 11 | — | — | — | 27 | — | — |
| 12 | — | — | — | 20 | — | — |
| 12 | — | — | — | 21 | — | — |
| 12 | — | — | — | 23 | — | — |
| 12 | — | — | — | 26 | — | — |
| 12 | — | — | — | 31 | — | — |
| 12 | — | — | — | 32 | — | — |
| 12 | — | — | — | 33 | — | — |
| 13 | — | — | — | 26 | — | — |
| 13 | — | — | — | 27 | — | — |
| 15 | — | — | — | 26 | — | — |
| 15 | — | — | — | 27 | — | — |
| 16 | — | — | — | 18 | — | — |
| 16 | — | — | — | 20 | — | — |
| 16 | — | — | — | 22 | — | — |
| 16 | — | — | — | 26 | — | — |
| 16 | — | — | — | 27 | — | — |
| 17 | — | — | — | 18 | — | — |
| 17 | — | — | — | 20 | — | — |
| 17 | — | — | — | 25 | — | — |
| 18 | — | — | — | 25 | — | — |
| 19 | — | — | — | 22 | — | — |
First 60 of 78 rows.
Blocks
| Block | Nodes | Model share | Rate per degree pair (λ) within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 18 | 51.6% | 0.0121 | 0.9527 | 33, 32, 31 |
| 2 | 16 | 48.4% | 0.0123 | 0.9759 | 0, 2, 1 |
Rate per degree pair (λ) between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.0121 | 0.0018 |
| Block 2 | 0.0018 | 0.0123 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Stochastic blockmodel
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sbm 1.0.0 · spec 6194fdf6c90dc39b
# Dataset: graph_karate (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ml_sbm_*(): twin of codesplash.ml.sbm
MODEL <- "poisson_dc"
BLOCKS <- 2
MAX_BLOCKS <- 6
CRITERION <- "icl"
STARTS <- 5L
SEED <- 42
MODEL_LABELS <- c(bernoulli = "stochastic blockmodel", poisson_dc = "degree-corrected blockmodel")
CRITERION_LABELS <- c(icl = "ICL", bic = "BIC")
# %% The network the host built (canonical node order, merged edges; cs_graph_read)
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.sbm/karate_dc/out-r")
G <- cs_graph_read(out)
warnings <- as.list(G$warnings)
N <- G$n
pairs <- cs_graph_undirected_pairs(G) # direction set aside; repeated edges add up
a <- pairs$a; b <- pairs$b; w <- pairs$w
if (N > 2000 || length(a) > 200000) cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(a), max_nodes = 2000, max_edges = 200000)
if (N < 3 || length(a) == 0) cs_error("CS_E_UNDEFINED", what = "A stochastic blockmodel", reason = "it needs at least 3 nodes and one edge between two different nodes")
if (any(w < 0)) cs_error("CS_E_INVALID_VALUES", column = if (!is.null(G$meta$weight)) G$meta$weight else "Edge count", requirement = "zero or more", count = sum(w < 0))
if (isTRUE(G$directed)) warnings <- c(warnings, "The blockmodel treats every edge as two-way, so the directions were set aside.")
A <- matrix(0, N, N)
if (MODEL == "bernoulli") {
A[cbind(a + 1L, b + 1L)] <- 1
if (isTRUE(G$weighted)) warnings <- c(warnings, "The plain blockmodel reads whether two nodes are linked, so edge weights were set aside.")
} else {
A[cbind(a + 1L, b + 1L)] <- w # link counts (1 per edge row without a weight column)
}
A[cbind(b + 1L, a + 1L)] <- A[cbind(a + 1L, b + 1L)]
values <- list(n_nodes = N, n_edges = length(a), density = length(a) / (N * (N - 1) / 2),
model_label = MODEL_LABELS[[MODEL]], criterion_label = if (is.null(BLOCKS)) CRITERION_LABELS[[CRITERION]] else "you")
# %% Fit: variational EM from k-means++ / Lloyd starts on the rows of A (shared stream)
rng <- cs_rng(SEED)
if (is.null(BLOCKS)) {
q_max <- max(1, min(MAX_BLOCKS, N - 1))
sel <- cs_ml_sbm_select(A, q_max, MODEL, rng, STARTS, CRITERION)
Q <- sel$best
fits <- sel$fits
best <- fits[[Q]]
} else {
Q <- as.integer(BLOCKS)
if (Q > N - 1) cs_error("CS_E_INVALID_OPTION", option = "Blocks", allowed = sprintf("at most %d for %d nodes", N - 1, N), value = Q)
best <- cs_ml_sbm_fit(A, Q, MODEL, rng, STARTS)
fits <- NULL
}
cn <- cs_ml_sbm_canonical(best$tau, best$alpha, best$rate)
lab <- cn$labels; tau <- cn$tau; alpha <- cn$alpha; rate <- cn$rate
block <- lab + 1L # 1..Q by size, ties by first node
values$blocks <- Q
values$icl <- best$icl; values$bic <- best$bic; values$loglik <- best$loglik
values$elbo <- best$J
values$converged <- isTRUE(best$converged)
if (!isTRUE(best$converged)) warnings <- c(warnings, "Variational EM stopped at its iteration limit before the lower bound settled.")
certainty <- apply(tau, 1, max)
values$certainty <- mean(certainty)
sizes <- tabulate(block, nbins = Q)
edges <- matrix(0, Q, Q)
for (e in seq_along(a)) {
p <- min(lab[a[e] + 1L], lab[b[e] + 1L]) + 1L; q <- max(lab[a[e] + 1L], lab[b[e] + 1L]) + 1L
edges[p, q] <- edges[p, q] + if (MODEL == "bernoulli") 1 else w[e]
}
for (q in seq_len(Q)) {
values[[sprintf("size[%d]", q)]] <- sizes[q]
values[[sprintf("share[%d]", q)]] <- alpha[q]
for (l in q:Q) {
values[[sprintf("rate[%d,%d]", q, l)]] <- rate[q, l]
values[[sprintf("edges[%d,%d]", q, l)]] <- edges[q, l]
}
}
if (!is.null(fits)) {
for (i in seq_along(fits)) {
values[[sprintf("icl[%d]", i)]] <- fits[[i]]$icl
values[[sprintf("bic[%d]", i)]] <- fits[[i]]$bic
}
}
if (!is.null(G$label)) {
truth <- as.character(G$nodes[[G$label]])
ok <- !is.na(truth)
values$n_labeled <- sum(ok)
if (sum(ok) >= 2) {
values$ari <- cs_ml_ari(truth[ok], block[ok])
values$ami <- cs_ml_ami(truth[ok], block[ok])
values$nmi <- cs_ml_nmi(truth[ok], block[ok])
}
}
# %% Tables
rate_label <- if (MODEL == "bernoulli") "Link probability" else "Rate per degree pair (λ)"
deg <- rowSums(A)
brows <- list()
for (q in seq_len(Q)) {
members <- which(block == q)
top <- members[order(-deg[members], members)][seq_len(min(3L, length(members)))]
brows[[q]] <- list(block = q, size = sizes[q], share = alpha[q], within = rate[q, q],
certainty = if (length(members)) mean(certainty[members]) else NULL,
examples = paste(G$node_id[top], collapse = ", "))
}
tables <- list(list(
key = "blocks", title = "Blocks",
columns = list(list(key = "block", label = "Block", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
list(key = "share", label = "Model share", type = "percent"), list(key = "within", label = sprintf("%s within", rate_label), type = "number"),
list(key = "certainty", label = "Mean certainty", type = "number"), list(key = "examples", label = "Best-connected nodes")),
rows = brows
))
mrows <- lapply(seq_len(Q), function(q) {
row <- list(block = sprintf("Block %d", q))
for (l in seq_len(Q)) row[[sprintf("b%d", l)]] <- rate[q, l]
row
})
tables[[2]] <- list(
key = "block_matrix", title = sprintf("%s between blocks", rate_label),
columns = c(list(list(key = "block", label = "Block")), lapply(seq_len(Q), function(l) list(key = sprintf("b%d", l), label = sprintf("Block %d", l), type = "number"))),
rows = mrows
)
if (!is.null(fits)) {
tables[[3]] <- list(
key = "selection", title = "Number of blocks",
columns = list(list(key = "blocks", label = "Blocks", type = "integer"), list(key = "icl", label = "ICL", type = "number"),
list(key = "bic", label = "BIC", type = "number"), list(key = "elbo", label = "Lower bound", type = "number")),
rows = lapply(seq_along(fits), function(i) list(blocks = i, icl = fits[[i]]$icl, bic = fits[[i]]$bic, elbo = fits[[i]]$J))
)
}
# %% Node table and charts
artifacts <- list(cs_graph_write_nodes(out, G, data.frame(block = as.integer(block), certainty = certainty, degree = deg)))
names_ <- sprintf("Block %d", seq_len(Q))
level_names <- as.character(seq_len(Q))
charts <- list()
charts[[1]] <- cs_chart("block_matrix", "matrix-heatmap", sprintf("%s between blocks", rate_label), list(
row = cs_col("Block", rep(names_, each = Q), "categorical", names_),
col = cs_col("With block", rep(names_, times = Q), "categorical", names_),
value = cs_col(rate_label, as.vector(t(rate)), "numeric")
), controls = list(scale = "sequential"))
if (!is.null(fits) && length(fits) > 1) {
qs <- seq_along(fits)
icl <- vapply(fits, function(f) f$icl, numeric(1))
bic <- vapply(fits, function(f) f$bic, numeric(1))
charts[[length(charts) + 1L]] <- cs_chart("selection", "elbow-plot", "Choosing the number of blocks", list(
k = cs_col("Blocks", c(qs, qs), "numeric"),
score = cs_col("Criterion", c(icl, bic), "numeric"),
criterion = cs_col("Criterion", c(rep("ICL", length(qs)), rep("BIC", length(qs))), "categorical", c("ICL", "BIC")),
chosen = cs_col("Best", c(qs == which.max(icl), qs == which.max(bic)), "boolean")
), note = sprintf("Higher is better; %s chose %d block%s.", CRITERION_LABELS[[CRITERION]], Q, if (Q != 1) "s" else ""))
}
if (N <= 300) {
morder <- order(block, -deg, seq_len(N)) - 1L
charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by block", list(
row = cs_col("Row", G$si, "numeric"),
col = cs_col("Column", G$sj, "numeric"),
value = cs_col(if (isTRUE(G$weighted)) "Weight" else "Edge", G$sw, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
group = cs_col("Block", as.character(block), "categorical", level_names),
order = cs_col("Order", morder, "numeric")
), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by block: each tile of the matrix is one pair of blocks.")
}
if (N <= 2000) {
xy <- cs_graph_layout_fr(G, SEED)
m <- length(G$si)
show <- min(m, 20000)
keep <- seq_len(show)
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Blocks in the network", list(
x = cs_col("x", xy$x, "numeric"),
y = cs_col("y", xy$y, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
size = cs_col("Degree", deg, "numeric"),
group = cs_col("Block", as.character(block), "categorical", level_names),
from = cs_col("From", G$si[keep], "numeric"),
to = cs_col("To", G$sj[keep], "numeric"),
weight = if (isTRUE(G$weighted)) cs_col("Weight", G$sw[keep], "numeric") else NULL
), controls = list(directed = isTRUE(G$directed)), note = if (show == m) NULL else sprintf("%d of %d edges drawn.", show, m))
}
# %% Result
how <- if (is.null(BLOCKS)) sprintf("chosen by %s", CRITERION_LABELS[[CRITERION]]) else "as set"
summary <- sprintf("The %s puts %s nodes in %d block%s (%s); the average node sits in its block with probability %.3f.",
MODEL_LABELS[[MODEL]], format(N, big.mark = ","), Q, if (Q != 1) "s" else "", how, values$certainty)
cs_publish(list(
title = "Stochastic blockmodel",
engine = cs_engine_info("nanoparquet"),
n = N,
summary = summary,
statistics = list(list(key = "blocks", label = "Blocks", value = Q, format = "integer"),
list(key = "icl", label = "ICL", value = values$icl),
list(key = "certainty", label = "Mean certainty", value = values$certainty)),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = artifacts
))
The degree-corrected blockmodel puts 34 nodes in 2 blocks (as set); the average node sits in its block with probability 0.964.
- Blocks
- 2
- ICL
- −198.48
- Mean certainty
- 0.9636
To keep this page light, the plots are shown once, under the R tab.
Blocks
| Block | Nodes | Model share | Rate per degree pair (λ) within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 18 | 51.6% | 0.0121 | 0.9527 | 33, 32, 31 |
| 2 | 16 | 48.4% | 0.0123 | 0.9759 | 0, 2, 1 |
Rate per degree pair (λ) between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.0121 | 0.0018 |
| Block 2 | 0.0018 | 0.0123 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Stochastic blockmodel
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sbm 1.0.0 · spec 6194fdf6c90dc39b
# Dataset: graph_karate (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import graph as cg
from codesplash import ml as csml
from codesplash.graph import layout as gl
from codesplash.ml import cluster as csc
from codesplash.ml import sbm # twin of codesplashr R/ml_sbm.R
from codesplash.stats.rng import Rng
MODEL = "poisson_dc"
BLOCKS = 2
MAX_BLOCKS = 6
CRITERION = "icl"
STARTS = 5
SEED = 42
MODEL_LABELS = {"bernoulli": "stochastic blockmodel", "poisson_dc": "degree-corrected blockmodel"}
CRITERION_LABELS = {"icl": "ICL", "bic": "BIC"}
# %% The network the host built (canonical node order, merged edges; codesplash.graph)
out = csml.out_dir("target/academy-parity/run-8142/discover.sbm/karate_dc/out-python")
G = cg.read(out)
warnings = list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G) # direction set aside; repeated edges add up
if N > 2000 or len(a) > 200000:
cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=2000, max_edges=200000)
if N < 3 or len(a) == 0:
cs.cs_error("CS_E_UNDEFINED", what="A stochastic blockmodel", reason="it needs at least 3 nodes and one edge between two different nodes")
if np.any(w < 0):
cs.cs_error("CS_E_INVALID_VALUES", column=G.meta.get("weight") or "Edge count", requirement="zero or more", count=int(np.sum(w < 0)))
if G.directed:
warnings.append("The blockmodel treats every edge as two-way, so the directions were set aside.")
A = np.zeros((N, N))
if MODEL == "bernoulli":
A[a, b] = 1.0
if G.weighted:
warnings.append("The plain blockmodel reads whether two nodes are linked, so edge weights were set aside.")
else:
A[a, b] = w # link counts (1 per edge row without a weight column)
A[b, a] = A[a, b]
values = {"n_nodes": N, "n_edges": int(len(a)), "density": float(len(a) / (N * (N - 1) / 2.0)),
"model_label": MODEL_LABELS[MODEL], "criterion_label": CRITERION_LABELS[CRITERION] if BLOCKS is None else "you"}
# %% Fit: variational EM from k-means++ / Lloyd starts on the rows of A (shared stream)
rng = Rng(SEED)
if BLOCKS is None:
q_max = max(1, min(MAX_BLOCKS, N - 1))
sel = sbm.select(A, q_max, MODEL, rng, STARTS, CRITERION)
Q = sel["best"]
fits = sel["fits"]
best = fits[Q - 1]
else:
Q = int(BLOCKS)
if Q > N - 1:
cs.cs_error("CS_E_INVALID_OPTION", option="Blocks", allowed=f"at most {N - 1} for {N} nodes", value=Q)
best = sbm.fit(A, Q, MODEL, rng, STARTS)
fits = None
lab, tau, alpha, rate = sbm.canonical(best["tau"], best["alpha"], best["rate"])
block = lab + 1 # 1…Q by size, ties by first node
values["blocks"] = Q
for key in ("icl", "bic", "loglik"):
values[key] = best[key]
values["elbo"] = best["J"]
values["converged"] = bool(best["converged"])
if not best["converged"]:
warnings.append("Variational EM stopped at its iteration limit before the lower bound settled.")
certainty = tau.max(axis=1)
values["certainty"] = float(np.mean(certainty))
sizes = np.bincount(lab, minlength=Q)
edges = np.zeros((Q, Q))
for i, j, x in zip(a.tolist(), b.tolist(), w.tolist()):
p, q = min(lab[i], lab[j]), max(lab[i], lab[j])
edges[p, q] += 1.0 if MODEL == "bernoulli" else x
for q in range(Q):
values[f"size[{q + 1}]"] = int(sizes[q])
values[f"share[{q + 1}]"] = float(alpha[q])
for l in range(q, Q):
values[f"rate[{q + 1},{l + 1}]"] = float(rate[q, l])
values[f"edges[{q + 1},{l + 1}]"] = float(edges[q, l])
if fits is not None:
for i, f in enumerate(fits, start=1):
values[f"icl[{i}]"] = f["icl"]
values[f"bic[{i}]"] = f["bic"]
if G.label:
truth = np.array([None if pd.isna(v) else str(v) for v in G.nodes[G.label].tolist()], dtype=object) # None, NaN, pd.NA
ok = np.array([v is not None for v in truth])
values["n_labeled"] = int(ok.sum())
if ok.sum() >= 2:
tt = truth[ok].astype(str)
values["ari"] = csc.ari(tt, block[ok])
values["ami"] = csc.ami(tt, block[ok])
values["nmi"] = csc.nmi(tt, block[ok])
# %% Tables
rate_label = "Link probability" if MODEL == "bernoulli" else "Rate per degree pair (λ)"
deg = A.sum(axis=1)
brows = []
for q in range(Q):
members = np.flatnonzero(lab == q)
top = sorted(members.tolist(), key=lambda v: (-deg[v], v))[:3]
brows.append({"block": q + 1, "size": int(sizes[q]), "share": float(alpha[q]), "within": float(rate[q, q]),
"certainty": float(np.mean(certainty[members])) if len(members) else None,
"examples": ", ".join(G.node_id[v] for v in top)})
tables = [{
"key": "blocks", "title": "Blocks",
"columns": [{"key": "block", "label": "Block", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
{"key": "share", "label": "Model share", "type": "percent"}, {"key": "within", "label": f"{rate_label} within", "type": "number"},
{"key": "certainty", "label": "Mean certainty", "type": "number"}, {"key": "examples", "label": "Best-connected nodes"}],
"rows": brows,
}]
mrows = []
for q in range(Q):
row = {"block": f"Block {q + 1}"}
for l in range(Q):
row[f"b{l + 1}"] = float(rate[q, l])
mrows.append(row)
tables.append({
"key": "block_matrix", "title": f"{rate_label} between blocks",
"columns": [{"key": "block", "label": "Block"}] + [{"key": f"b{l + 1}", "label": f"Block {l + 1}", "type": "number"} for l in range(Q)],
"rows": mrows,
})
if fits is not None:
tables.append({
"key": "selection", "title": "Number of blocks",
"columns": [{"key": "blocks", "label": "Blocks", "type": "integer"}, {"key": "icl", "label": "ICL", "type": "number"},
{"key": "bic", "label": "BIC", "type": "number"}, {"key": "elbo", "label": "Lower bound", "type": "number"}],
"rows": [{"blocks": i, "icl": f["icl"], "bic": f["bic"], "elbo": f["J"]} for i, f in enumerate(fits, start=1)],
})
# %% Node table and charts
artifacts = [cg.write_nodes(out, G, {"block": block.astype(np.int64), "certainty": certainty, "degree": deg})]
names = [f"Block {q + 1}" for q in range(Q)]
level_names = [str(q + 1) for q in range(Q)]
charts = []
cells_r, cells_c, cells_v = [], [], []
for q in range(Q):
for l in range(Q):
cells_r.append(names[q])
cells_c.append(names[l])
cells_v.append(float(rate[q, l]))
charts.append(cs.chart("block_matrix", "matrix-heatmap", f"{rate_label} between blocks", {
"row": cs.col("Block", cells_r, "categorical", names),
"col": cs.col("With block", cells_c, "categorical", names),
"value": cs.col(rate_label, cells_v, "numeric"),
}, controls={"scale": "sequential"}))
if fits is not None and len(fits) > 1:
qs = list(range(1, len(fits) + 1))
icl = [f["icl"] for f in fits]
bic = [f["bic"] for f in fits]
charts.append(cs.chart("selection", "elbow-plot", "Choosing the number of blocks", {
"k": cs.col("Blocks", qs + qs, "numeric"),
"score": cs.col("Criterion", icl + bic, "numeric"),
"criterion": cs.col("Criterion", ["ICL"] * len(qs) + ["BIC"] * len(qs), "categorical", ["ICL", "BIC"]),
"chosen": cs.col("Best", [q == 1 + int(np.argmax(icl)) for q in qs] + [q == 1 + int(np.argmax(bic)) for q in qs], "boolean"),
}, note=f"Higher is better; {CRITERION_LABELS[CRITERION]} chose {Q} block{'s' if Q != 1 else ''}."))
if N <= 300:
morder = sorted(range(N), key=lambda v: (int(block[v]), -deg[v], v))
charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by block", {
"row": cs.col("Row", G.si, "numeric"),
"col": cs.col("Column", G.sj, "numeric"),
"value": cs.col("Weight" if G.weighted else "Edge", G.sw, "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"group": cs.col("Block", [str(q) for q in block], "categorical", level_names),
"order": cs.col("Order", morder, "numeric"),
}, controls={"directed": G.directed}, note="Nodes sorted by block: each tile of the matrix is one pair of blocks."))
if N <= 2000:
xy = gl.fruchterman_reingold(G, SEED)
m = len(G.si)
show = min(m, 20000)
charts.append(cs.chart("map", "network-graph", "Blocks in the network", {
"x": cs.col("x", xy[0], "numeric"),
"y": cs.col("y", xy[1], "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"size": cs.col("Degree", deg, "numeric"),
"group": cs.col("Block", [str(q) for q in block], "categorical", level_names),
"from": cs.col("From", G.si[:show], "numeric"),
"to": cs.col("To", G.sj[:show], "numeric"),
"weight": cs.col("Weight", G.sw[:show], "numeric") if G.weighted else None,
}, controls={"directed": G.directed}, note=None if show == m else f"{show} of {m} edges drawn."))
# %% Result
how = f"chosen by {CRITERION_LABELS[CRITERION]}" if BLOCKS is None else "as set"
summary = (f"The {MODEL_LABELS[MODEL]} puts {N:,} nodes in {Q} block{'s' if Q != 1 else ''} ({how}); "
f"the average node sits in its block with probability {values['certainty']:.3f}.")
cs.publish({
"title": "Stochastic blockmodel",
"engine": cs.engine_info("numpy", "pandas", "scikit-learn"),
"n": N,
"summary": summary,
"statistics": [
{"key": "blocks", "label": "Blocks", "value": Q, "format": "integer"},
{"key": "icl", "label": "ICL", "value": values["icl"]},
{"key": "certainty", "label": "Mean certainty", "value": values["certainty"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": artifacts,
})
How many blocks?
ReadEach number of blocks is fitted from several starts by variational EM and scored by ICL: fit minus a penalty for the parameters (choosing the number of blocksChoosing the number of blocksEach number of blocks is fitted and scored by ICL or BIC (fit minus a penalty for parameters); the highest score wins.). On buyers and sellers in two markets, the degree-corrected model picks 4 blocks: buyers and sellers of each market.
The degree-corrected blockmodel puts 28 nodes in 4 blocks (chosen by ICL); the average node sits in its block with probability 0.991.
- Blocks
- 4
- ICL
- −226.22
- Mean certainty
- 0.9915
Plots
View data
| With block | Block | Rate per degree pair (λ) |
|---|---|---|
| Block 1 | Block 1 | 1.000e-10 |
| Block 2 | Block 1 | 1.000e-10 |
| Block 3 | Block 1 | 0.0028 |
| Block 4 | Block 1 | 0.0149 |
| Block 1 | Block 2 | 1.000e-10 |
| Block 2 | Block 2 | 1.000e-10 |
| Block 3 | Block 2 | 0.0164 |
| Block 4 | Block 2 | 1.000e-10 |
| Block 1 | Block 3 | 0.0028 |
| Block 2 | Block 3 | 0.0164 |
| Block 3 | Block 3 | 1.000e-10 |
| Block 4 | Block 3 | 1.000e-10 |
| Block 1 | Block 4 | 0.0149 |
| Block 2 | Block 4 | 1.000e-10 |
| Block 3 | Block 4 | 1.000e-10 |
| Block 4 | Block 4 | 1.000e-10 |
Higher is better; ICL chose 4 blocks.
View data
| Best | Criterion | Blocks | Criterion |
|---|---|---|---|
| false | ICL | 1 | −282.12 |
| false | ICL | 2 | −296.32 |
| false | ICL | 3 | −232.00 |
| true | ICL | 4 | −226.22 |
| false | BIC | 1 | −282.12 |
| false | BIC | 2 | −289.73 |
| false | BIC | 3 | −231.60 |
| true | BIC | 4 | −225.51 |
Nodes sorted by block: each tile of the matrix is one pair of blocks.
View data
| Column | Block | Node | Order | Row | Weight |
|---|---|---|---|---|---|
| 16 | 1 | b01 | 5 | 0 | 4 |
| 18 | 1 | b02 | 0 | 0 | 4 |
| 19 | 1 | b03 | 4 | 0 | 3 |
| 21 | 1 | b04 | 7 | 0 | 1 |
| 19 | 1 | b05 | 6 | 1 | 1 |
| 21 | 1 | b06 | 15 | 1 | 1 |
| 16 | 1 | b07 | 3 | 2 | 3 |
| 19 | 1 | b08 | 2 | 3 | 4 |
| 16 | 2 | b09 | 1 | 4 | 4 |
| 17 | 2 | b10 | 14 | 4 | 3 |
| 25 | 2 | b11 | 8 | 4 | 3 |
| 16 | 2 | b12 | 10 | 5 | 3 |
| 17 | 2 | b13 | 13 | 5 | 2 |
| 18 | 2 | b14 | 12 | 5 | 4 |
| 19 | 2 | b15 | 9 | 5 | 4 |
| 20 | 1 | b16 | 11 | 5 | 4 |
| 19 | 4 | s01 | 25 | 6 | 4 |
| 20 | 3 | s02 | 17 | 6 | 2 |
| 17 | 4 | s03 | 27 | 7 | 1 |
| 18 | 4 | s04 | 24 | 7 | 3 |
| 19 | 4 | s05 | 23 | 7 | 4 |
| 23 | 4 | s06 | 26 | 8 | 2 |
| 24 | 3 | s07 | 22 | 8 | 4 |
| 27 | 3 | s08 | 19 | 8 | 4 |
| 23 | 3 | s09 | 16 | 9 | 1 |
| 27 | 3 | s10 | 18 | 9 | 2 |
| 17 | 3 | s11 | 20 | 10 | 4 |
| 22 | 3 | s12 | 21 | 10 | 1 |
| 25 | — | — | — | 10 | 3 |
| 26 | — | — | — | 10 | 1 |
| 27 | — | — | — | 10 | 1 |
| 24 | — | — | — | 11 | 1 |
| 23 | — | — | — | 12 | 2 |
| 26 | — | — | — | 12 | 2 |
| 22 | — | — | — | 13 | 2 |
| 24 | — | — | — | 13 | 1 |
| 25 | — | — | — | 13 | 2 |
| 23 | — | — | — | 14 | 3 |
| 24 | — | — | — | 14 | 3 |
| 25 | — | — | — | 14 | 4 |
| 26 | — | — | — | 14 | 4 |
| 27 | — | — | — | 14 | 3 |
| 16 | — | — | — | 15 | 3 |
| 25 | — | — | — | 15 | 2 |
View data
| From | Block | Node | Degree | To | Weight | x | y |
|---|---|---|---|---|---|---|---|
| 0 | 1 | b01 | 12 | 16 | 4 | −0.5141 | 0.5202 |
| 0 | 1 | b02 | 2 | 18 | 4 | −0.5550 | 0.8667 |
| 0 | 1 | b03 | 3 | 19 | 3 | −0.6806 | 0.1090 |
| 0 | 1 | b04 | 4 | 21 | 1 | −0.3271 | 1 |
| 1 | 1 | b05 | 10 | 19 | 1 | −0.1663 | −0.0317 |
| 1 | 1 | b06 | 17 | 21 | 1 | −0.2197 | 0.4140 |
| 2 | 1 | b07 | 6 | 16 | 3 | −0.1103 | 0.8516 |
| 3 | 1 | b08 | 8 | 19 | 4 | −0.1378 | 0.4593 |
| 4 | 2 | b09 | 10 | 16 | 4 | 0.5225 | −0.6361 |
| 4 | 2 | b10 | 3 | 17 | 3 | 0.7887 | −0.4151 |
| 4 | 2 | b11 | 10 | 25 | 3 | 0.2320 | −0.2468 |
| 5 | 2 | b12 | 1 | 16 | 3 | 0.1282 | −0.9553 |
| 5 | 2 | b13 | 4 | 17 | 2 | 0.7217 | −0.6813 |
| 5 | 2 | b14 | 5 | 18 | 4 | 0.0579 | −0.5988 |
| 5 | 2 | b15 | 17 | 19 | 4 | 0.3433 | −0.5012 |
| 5 | 1 | b16 | 5 | 20 | 4 | −0.2847 | −0.1355 |
| 6 | 4 | s01 | 17 | 19 | 4 | −0.4036 | 0.1727 |
| 6 | 3 | s02 | 10 | 20 | 2 | −0.0183 | 0.1371 |
| 7 | 4 | s03 | 11 | 17 | 1 | −0.3423 | 0.5054 |
| 7 | 4 | s04 | 20 | 18 | 3 | −0.3150 | 0.7085 |
| 7 | 4 | s05 | 6 | 19 | 4 | −0.0693 | 0.6731 |
| 8 | 4 | s06 | 2 | 23 | 2 | −0.6938 | 0.7380 |
| 8 | 3 | s07 | 3 | 24 | 4 | 0.1112 | −0.4558 |
| 8 | 3 | s08 | 8 | 27 | 4 | 0.6550 | −0.5573 |
| 9 | 3 | s09 | 9 | 23 | 1 | 0.2690 | −0.7467 |
| 9 | 3 | s10 | 14 | 27 | 2 | 0.0094 | −0.3119 |
| 10 | 3 | s11 | 7 | 17 | 4 | 0.4764 | −0.4937 |
| 10 | 3 | s12 | 10 | 22 | 1 | 0.5227 | −0.3882 |
| 10 | — | — | — | 25 | 3 | — | — |
| 10 | — | — | — | 26 | 1 | — | — |
| 10 | — | — | — | 27 | 1 | — | — |
| 11 | — | — | — | 24 | 1 | — | — |
| 12 | — | — | — | 23 | 2 | — | — |
| 12 | — | — | — | 26 | 2 | — | — |
| 13 | — | — | — | 22 | 2 | — | — |
| 13 | — | — | — | 24 | 1 | — | — |
| 13 | — | — | — | 25 | 2 | — | — |
| 14 | — | — | — | 23 | 3 | — | — |
| 14 | — | — | — | 24 | 3 | — | — |
| 14 | — | — | — | 25 | 4 | — | — |
| 14 | — | — | — | 26 | 4 | — | — |
| 14 | — | — | — | 27 | 3 | — | — |
| 15 | — | — | — | 16 | 3 | — | — |
| 15 | — | — | — | 25 | 2 | — | — |
Blocks
| Block | Nodes | Model share | Rate per degree pair (λ) within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 9 | 32.8% | 1.000e-10 | 1.0000 | b06, b01, b05 |
| 2 | 7 | 24.3% | 1.000e-10 | 0.9725 | b15, b09, b11 |
| 3 | 7 | 25.2% | 1.000e-10 | 1.0000 | s10, s02, s12 |
| 4 | 5 | 17.7% | 1.000e-10 | 0.9907 | s04, s01, s03 |
Rate per degree pair (λ) between blocks
| Block | Block 1 | Block 2 | Block 3 | Block 4 |
|---|---|---|---|---|
| Block 1 | 1.000e-10 | 1.000e-10 | 0.0028 | 0.0149 |
| Block 2 | 1.000e-10 | 1.000e-10 | 0.0164 | 1.000e-10 |
| Block 3 | 0.0028 | 0.0164 | 1.000e-10 | 1.000e-10 |
| Block 4 | 0.0149 | 1.000e-10 | 1.000e-10 | 1.000e-10 |
Number of blocks
| Blocks | ICL | BIC | Lower bound |
|---|---|---|---|
| 1 | −282.12 | −282.12 | −279.16 |
| 2 | −296.32 | −289.73 | −279.16 |
| 3 | −232.00 | −231.60 | −210.46 |
| 4 | −226.22 | −225.51 | −190.83 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Stochastic blockmodel
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sbm 1.0.0 · spec 6d5b0165785bbb11
# Dataset: grf2_market_edges (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ml_sbm_*(): twin of codesplash.ml.sbm
MODEL <- "poisson_dc"
BLOCKS <- NULL
MAX_BLOCKS <- 4
CRITERION <- "icl"
STARTS <- 3L
SEED <- 42
MODEL_LABELS <- c(bernoulli = "stochastic blockmodel", poisson_dc = "degree-corrected blockmodel")
CRITERION_LABELS <- c(icl = "ICL", bic = "BIC")
# %% The network the host built (canonical node order, merged edges; cs_graph_read)
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.sbm/bipartite_dc_counts/out-r")
G <- cs_graph_read(out)
warnings <- as.list(G$warnings)
N <- G$n
pairs <- cs_graph_undirected_pairs(G) # direction set aside; repeated edges add up
a <- pairs$a; b <- pairs$b; w <- pairs$w
if (N > 2000 || length(a) > 200000) cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(a), max_nodes = 2000, max_edges = 200000)
if (N < 3 || length(a) == 0) cs_error("CS_E_UNDEFINED", what = "A stochastic blockmodel", reason = "it needs at least 3 nodes and one edge between two different nodes")
if (any(w < 0)) cs_error("CS_E_INVALID_VALUES", column = if (!is.null(G$meta$weight)) G$meta$weight else "Edge count", requirement = "zero or more", count = sum(w < 0))
if (isTRUE(G$directed)) warnings <- c(warnings, "The blockmodel treats every edge as two-way, so the directions were set aside.")
A <- matrix(0, N, N)
if (MODEL == "bernoulli") {
A[cbind(a + 1L, b + 1L)] <- 1
if (isTRUE(G$weighted)) warnings <- c(warnings, "The plain blockmodel reads whether two nodes are linked, so edge weights were set aside.")
} else {
A[cbind(a + 1L, b + 1L)] <- w # link counts (1 per edge row without a weight column)
}
A[cbind(b + 1L, a + 1L)] <- A[cbind(a + 1L, b + 1L)]
values <- list(n_nodes = N, n_edges = length(a), density = length(a) / (N * (N - 1) / 2),
model_label = MODEL_LABELS[[MODEL]], criterion_label = if (is.null(BLOCKS)) CRITERION_LABELS[[CRITERION]] else "you")
# %% Fit: variational EM from k-means++ / Lloyd starts on the rows of A (shared stream)
rng <- cs_rng(SEED)
if (is.null(BLOCKS)) {
q_max <- max(1, min(MAX_BLOCKS, N - 1))
sel <- cs_ml_sbm_select(A, q_max, MODEL, rng, STARTS, CRITERION)
Q <- sel$best
fits <- sel$fits
best <- fits[[Q]]
} else {
Q <- as.integer(BLOCKS)
if (Q > N - 1) cs_error("CS_E_INVALID_OPTION", option = "Blocks", allowed = sprintf("at most %d for %d nodes", N - 1, N), value = Q)
best <- cs_ml_sbm_fit(A, Q, MODEL, rng, STARTS)
fits <- NULL
}
cn <- cs_ml_sbm_canonical(best$tau, best$alpha, best$rate)
lab <- cn$labels; tau <- cn$tau; alpha <- cn$alpha; rate <- cn$rate
block <- lab + 1L # 1..Q by size, ties by first node
values$blocks <- Q
values$icl <- best$icl; values$bic <- best$bic; values$loglik <- best$loglik
values$elbo <- best$J
values$converged <- isTRUE(best$converged)
if (!isTRUE(best$converged)) warnings <- c(warnings, "Variational EM stopped at its iteration limit before the lower bound settled.")
certainty <- apply(tau, 1, max)
values$certainty <- mean(certainty)
sizes <- tabulate(block, nbins = Q)
edges <- matrix(0, Q, Q)
for (e in seq_along(a)) {
p <- min(lab[a[e] + 1L], lab[b[e] + 1L]) + 1L; q <- max(lab[a[e] + 1L], lab[b[e] + 1L]) + 1L
edges[p, q] <- edges[p, q] + if (MODEL == "bernoulli") 1 else w[e]
}
for (q in seq_len(Q)) {
values[[sprintf("size[%d]", q)]] <- sizes[q]
values[[sprintf("share[%d]", q)]] <- alpha[q]
for (l in q:Q) {
values[[sprintf("rate[%d,%d]", q, l)]] <- rate[q, l]
values[[sprintf("edges[%d,%d]", q, l)]] <- edges[q, l]
}
}
if (!is.null(fits)) {
for (i in seq_along(fits)) {
values[[sprintf("icl[%d]", i)]] <- fits[[i]]$icl
values[[sprintf("bic[%d]", i)]] <- fits[[i]]$bic
}
}
if (!is.null(G$label)) {
truth <- as.character(G$nodes[[G$label]])
ok <- !is.na(truth)
values$n_labeled <- sum(ok)
if (sum(ok) >= 2) {
values$ari <- cs_ml_ari(truth[ok], block[ok])
values$ami <- cs_ml_ami(truth[ok], block[ok])
values$nmi <- cs_ml_nmi(truth[ok], block[ok])
}
}
# %% Tables
rate_label <- if (MODEL == "bernoulli") "Link probability" else "Rate per degree pair (λ)"
deg <- rowSums(A)
brows <- list()
for (q in seq_len(Q)) {
members <- which(block == q)
top <- members[order(-deg[members], members)][seq_len(min(3L, length(members)))]
brows[[q]] <- list(block = q, size = sizes[q], share = alpha[q], within = rate[q, q],
certainty = if (length(members)) mean(certainty[members]) else NULL,
examples = paste(G$node_id[top], collapse = ", "))
}
tables <- list(list(
key = "blocks", title = "Blocks",
columns = list(list(key = "block", label = "Block", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
list(key = "share", label = "Model share", type = "percent"), list(key = "within", label = sprintf("%s within", rate_label), type = "number"),
list(key = "certainty", label = "Mean certainty", type = "number"), list(key = "examples", label = "Best-connected nodes")),
rows = brows
))
mrows <- lapply(seq_len(Q), function(q) {
row <- list(block = sprintf("Block %d", q))
for (l in seq_len(Q)) row[[sprintf("b%d", l)]] <- rate[q, l]
row
})
tables[[2]] <- list(
key = "block_matrix", title = sprintf("%s between blocks", rate_label),
columns = c(list(list(key = "block", label = "Block")), lapply(seq_len(Q), function(l) list(key = sprintf("b%d", l), label = sprintf("Block %d", l), type = "number"))),
rows = mrows
)
if (!is.null(fits)) {
tables[[3]] <- list(
key = "selection", title = "Number of blocks",
columns = list(list(key = "blocks", label = "Blocks", type = "integer"), list(key = "icl", label = "ICL", type = "number"),
list(key = "bic", label = "BIC", type = "number"), list(key = "elbo", label = "Lower bound", type = "number")),
rows = lapply(seq_along(fits), function(i) list(blocks = i, icl = fits[[i]]$icl, bic = fits[[i]]$bic, elbo = fits[[i]]$J))
)
}
# %% Node table and charts
artifacts <- list(cs_graph_write_nodes(out, G, data.frame(block = as.integer(block), certainty = certainty, degree = deg)))
names_ <- sprintf("Block %d", seq_len(Q))
level_names <- as.character(seq_len(Q))
charts <- list()
charts[[1]] <- cs_chart("block_matrix", "matrix-heatmap", sprintf("%s between blocks", rate_label), list(
row = cs_col("Block", rep(names_, each = Q), "categorical", names_),
col = cs_col("With block", rep(names_, times = Q), "categorical", names_),
value = cs_col(rate_label, as.vector(t(rate)), "numeric")
), controls = list(scale = "sequential"))
if (!is.null(fits) && length(fits) > 1) {
qs <- seq_along(fits)
icl <- vapply(fits, function(f) f$icl, numeric(1))
bic <- vapply(fits, function(f) f$bic, numeric(1))
charts[[length(charts) + 1L]] <- cs_chart("selection", "elbow-plot", "Choosing the number of blocks", list(
k = cs_col("Blocks", c(qs, qs), "numeric"),
score = cs_col("Criterion", c(icl, bic), "numeric"),
criterion = cs_col("Criterion", c(rep("ICL", length(qs)), rep("BIC", length(qs))), "categorical", c("ICL", "BIC")),
chosen = cs_col("Best", c(qs == which.max(icl), qs == which.max(bic)), "boolean")
), note = sprintf("Higher is better; %s chose %d block%s.", CRITERION_LABELS[[CRITERION]], Q, if (Q != 1) "s" else ""))
}
if (N <= 300) {
morder <- order(block, -deg, seq_len(N)) - 1L
charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by block", list(
row = cs_col("Row", G$si, "numeric"),
col = cs_col("Column", G$sj, "numeric"),
value = cs_col(if (isTRUE(G$weighted)) "Weight" else "Edge", G$sw, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
group = cs_col("Block", as.character(block), "categorical", level_names),
order = cs_col("Order", morder, "numeric")
), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by block: each tile of the matrix is one pair of blocks.")
}
if (N <= 2000) {
xy <- cs_graph_layout_fr(G, SEED)
m <- length(G$si)
show <- min(m, 20000)
keep <- seq_len(show)
charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Blocks in the network", list(
x = cs_col("x", xy$x, "numeric"),
y = cs_col("y", xy$y, "numeric"),
node = cs_col("Node", G$node_id, "categorical"),
size = cs_col("Degree", deg, "numeric"),
group = cs_col("Block", as.character(block), "categorical", level_names),
from = cs_col("From", G$si[keep], "numeric"),
to = cs_col("To", G$sj[keep], "numeric"),
weight = if (isTRUE(G$weighted)) cs_col("Weight", G$sw[keep], "numeric") else NULL
), controls = list(directed = isTRUE(G$directed)), note = if (show == m) NULL else sprintf("%d of %d edges drawn.", show, m))
}
# %% Result
how <- if (is.null(BLOCKS)) sprintf("chosen by %s", CRITERION_LABELS[[CRITERION]]) else "as set"
summary <- sprintf("The %s puts %s nodes in %d block%s (%s); the average node sits in its block with probability %.3f.",
MODEL_LABELS[[MODEL]], format(N, big.mark = ","), Q, if (Q != 1) "s" else "", how, values$certainty)
cs_publish(list(
title = "Stochastic blockmodel",
engine = cs_engine_info("nanoparquet"),
n = N,
summary = summary,
statistics = list(list(key = "blocks", label = "Blocks", value = Q, format = "integer"),
list(key = "icl", label = "ICL", value = values$icl),
list(key = "certainty", label = "Mean certainty", value = values$certainty)),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = artifacts
))
The degree-corrected blockmodel puts 28 nodes in 4 blocks (chosen by ICL); the average node sits in its block with probability 0.991.
- Blocks
- 4
- ICL
- −226.22
- Mean certainty
- 0.9915
To keep this page light, the plots are shown once, under the R tab.
Blocks
| Block | Nodes | Model share | Rate per degree pair (λ) within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 9 | 32.8% | 1.000e-10 | 1.0000 | b06, b01, b05 |
| 2 | 7 | 24.3% | 1.000e-10 | 0.9725 | b15, b09, b11 |
| 3 | 7 | 25.2% | 1.000e-10 | 1.0000 | s10, s02, s12 |
| 4 | 5 | 17.7% | 1.000e-10 | 0.9907 | s04, s01, s03 |
Rate per degree pair (λ) between blocks
| Block | Block 1 | Block 2 | Block 3 | Block 4 |
|---|---|---|---|---|
| Block 1 | 1.000e-10 | 1.000e-10 | 0.0028 | 0.0149 |
| Block 2 | 1.000e-10 | 1.000e-10 | 0.0164 | 1.000e-10 |
| Block 3 | 0.0028 | 0.0164 | 1.000e-10 | 1.000e-10 |
| Block 4 | 0.0149 | 1.000e-10 | 1.000e-10 | 1.000e-10 |
Number of blocks
| Blocks | ICL | BIC | Lower bound |
|---|---|---|---|
| 1 | −282.12 | −282.12 | −279.16 |
| 2 | −296.32 | −289.73 | −279.16 |
| 3 | −232.00 | −231.60 | −210.46 |
| 4 | −226.22 | −225.51 | −190.83 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Stochastic blockmodel
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sbm 1.0.0 · spec 6d5b0165785bbb11
# Dataset: grf2_market_edges (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import graph as cg
from codesplash import ml as csml
from codesplash.graph import layout as gl
from codesplash.ml import cluster as csc
from codesplash.ml import sbm # twin of codesplashr R/ml_sbm.R
from codesplash.stats.rng import Rng
MODEL = "poisson_dc"
BLOCKS = None
MAX_BLOCKS = 4
CRITERION = "icl"
STARTS = 3
SEED = 42
MODEL_LABELS = {"bernoulli": "stochastic blockmodel", "poisson_dc": "degree-corrected blockmodel"}
CRITERION_LABELS = {"icl": "ICL", "bic": "BIC"}
# %% The network the host built (canonical node order, merged edges; codesplash.graph)
out = csml.out_dir("target/academy-parity/run-8142/discover.sbm/bipartite_dc_counts/out-python")
G = cg.read(out)
warnings = list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G) # direction set aside; repeated edges add up
if N > 2000 or len(a) > 200000:
cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=2000, max_edges=200000)
if N < 3 or len(a) == 0:
cs.cs_error("CS_E_UNDEFINED", what="A stochastic blockmodel", reason="it needs at least 3 nodes and one edge between two different nodes")
if np.any(w < 0):
cs.cs_error("CS_E_INVALID_VALUES", column=G.meta.get("weight") or "Edge count", requirement="zero or more", count=int(np.sum(w < 0)))
if G.directed:
warnings.append("The blockmodel treats every edge as two-way, so the directions were set aside.")
A = np.zeros((N, N))
if MODEL == "bernoulli":
A[a, b] = 1.0
if G.weighted:
warnings.append("The plain blockmodel reads whether two nodes are linked, so edge weights were set aside.")
else:
A[a, b] = w # link counts (1 per edge row without a weight column)
A[b, a] = A[a, b]
values = {"n_nodes": N, "n_edges": int(len(a)), "density": float(len(a) / (N * (N - 1) / 2.0)),
"model_label": MODEL_LABELS[MODEL], "criterion_label": CRITERION_LABELS[CRITERION] if BLOCKS is None else "you"}
# %% Fit: variational EM from k-means++ / Lloyd starts on the rows of A (shared stream)
rng = Rng(SEED)
if BLOCKS is None:
q_max = max(1, min(MAX_BLOCKS, N - 1))
sel = sbm.select(A, q_max, MODEL, rng, STARTS, CRITERION)
Q = sel["best"]
fits = sel["fits"]
best = fits[Q - 1]
else:
Q = int(BLOCKS)
if Q > N - 1:
cs.cs_error("CS_E_INVALID_OPTION", option="Blocks", allowed=f"at most {N - 1} for {N} nodes", value=Q)
best = sbm.fit(A, Q, MODEL, rng, STARTS)
fits = None
lab, tau, alpha, rate = sbm.canonical(best["tau"], best["alpha"], best["rate"])
block = lab + 1 # 1…Q by size, ties by first node
values["blocks"] = Q
for key in ("icl", "bic", "loglik"):
values[key] = best[key]
values["elbo"] = best["J"]
values["converged"] = bool(best["converged"])
if not best["converged"]:
warnings.append("Variational EM stopped at its iteration limit before the lower bound settled.")
certainty = tau.max(axis=1)
values["certainty"] = float(np.mean(certainty))
sizes = np.bincount(lab, minlength=Q)
edges = np.zeros((Q, Q))
for i, j, x in zip(a.tolist(), b.tolist(), w.tolist()):
p, q = min(lab[i], lab[j]), max(lab[i], lab[j])
edges[p, q] += 1.0 if MODEL == "bernoulli" else x
for q in range(Q):
values[f"size[{q + 1}]"] = int(sizes[q])
values[f"share[{q + 1}]"] = float(alpha[q])
for l in range(q, Q):
values[f"rate[{q + 1},{l + 1}]"] = float(rate[q, l])
values[f"edges[{q + 1},{l + 1}]"] = float(edges[q, l])
if fits is not None:
for i, f in enumerate(fits, start=1):
values[f"icl[{i}]"] = f["icl"]
values[f"bic[{i}]"] = f["bic"]
if G.label:
truth = np.array([None if pd.isna(v) else str(v) for v in G.nodes[G.label].tolist()], dtype=object) # None, NaN, pd.NA
ok = np.array([v is not None for v in truth])
values["n_labeled"] = int(ok.sum())
if ok.sum() >= 2:
tt = truth[ok].astype(str)
values["ari"] = csc.ari(tt, block[ok])
values["ami"] = csc.ami(tt, block[ok])
values["nmi"] = csc.nmi(tt, block[ok])
# %% Tables
rate_label = "Link probability" if MODEL == "bernoulli" else "Rate per degree pair (λ)"
deg = A.sum(axis=1)
brows = []
for q in range(Q):
members = np.flatnonzero(lab == q)
top = sorted(members.tolist(), key=lambda v: (-deg[v], v))[:3]
brows.append({"block": q + 1, "size": int(sizes[q]), "share": float(alpha[q]), "within": float(rate[q, q]),
"certainty": float(np.mean(certainty[members])) if len(members) else None,
"examples": ", ".join(G.node_id[v] for v in top)})
tables = [{
"key": "blocks", "title": "Blocks",
"columns": [{"key": "block", "label": "Block", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
{"key": "share", "label": "Model share", "type": "percent"}, {"key": "within", "label": f"{rate_label} within", "type": "number"},
{"key": "certainty", "label": "Mean certainty", "type": "number"}, {"key": "examples", "label": "Best-connected nodes"}],
"rows": brows,
}]
mrows = []
for q in range(Q):
row = {"block": f"Block {q + 1}"}
for l in range(Q):
row[f"b{l + 1}"] = float(rate[q, l])
mrows.append(row)
tables.append({
"key": "block_matrix", "title": f"{rate_label} between blocks",
"columns": [{"key": "block", "label": "Block"}] + [{"key": f"b{l + 1}", "label": f"Block {l + 1}", "type": "number"} for l in range(Q)],
"rows": mrows,
})
if fits is not None:
tables.append({
"key": "selection", "title": "Number of blocks",
"columns": [{"key": "blocks", "label": "Blocks", "type": "integer"}, {"key": "icl", "label": "ICL", "type": "number"},
{"key": "bic", "label": "BIC", "type": "number"}, {"key": "elbo", "label": "Lower bound", "type": "number"}],
"rows": [{"blocks": i, "icl": f["icl"], "bic": f["bic"], "elbo": f["J"]} for i, f in enumerate(fits, start=1)],
})
# %% Node table and charts
artifacts = [cg.write_nodes(out, G, {"block": block.astype(np.int64), "certainty": certainty, "degree": deg})]
names = [f"Block {q + 1}" for q in range(Q)]
level_names = [str(q + 1) for q in range(Q)]
charts = []
cells_r, cells_c, cells_v = [], [], []
for q in range(Q):
for l in range(Q):
cells_r.append(names[q])
cells_c.append(names[l])
cells_v.append(float(rate[q, l]))
charts.append(cs.chart("block_matrix", "matrix-heatmap", f"{rate_label} between blocks", {
"row": cs.col("Block", cells_r, "categorical", names),
"col": cs.col("With block", cells_c, "categorical", names),
"value": cs.col(rate_label, cells_v, "numeric"),
}, controls={"scale": "sequential"}))
if fits is not None and len(fits) > 1:
qs = list(range(1, len(fits) + 1))
icl = [f["icl"] for f in fits]
bic = [f["bic"] for f in fits]
charts.append(cs.chart("selection", "elbow-plot", "Choosing the number of blocks", {
"k": cs.col("Blocks", qs + qs, "numeric"),
"score": cs.col("Criterion", icl + bic, "numeric"),
"criterion": cs.col("Criterion", ["ICL"] * len(qs) + ["BIC"] * len(qs), "categorical", ["ICL", "BIC"]),
"chosen": cs.col("Best", [q == 1 + int(np.argmax(icl)) for q in qs] + [q == 1 + int(np.argmax(bic)) for q in qs], "boolean"),
}, note=f"Higher is better; {CRITERION_LABELS[CRITERION]} chose {Q} block{'s' if Q != 1 else ''}."))
if N <= 300:
morder = sorted(range(N), key=lambda v: (int(block[v]), -deg[v], v))
charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by block", {
"row": cs.col("Row", G.si, "numeric"),
"col": cs.col("Column", G.sj, "numeric"),
"value": cs.col("Weight" if G.weighted else "Edge", G.sw, "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"group": cs.col("Block", [str(q) for q in block], "categorical", level_names),
"order": cs.col("Order", morder, "numeric"),
}, controls={"directed": G.directed}, note="Nodes sorted by block: each tile of the matrix is one pair of blocks."))
if N <= 2000:
xy = gl.fruchterman_reingold(G, SEED)
m = len(G.si)
show = min(m, 20000)
charts.append(cs.chart("map", "network-graph", "Blocks in the network", {
"x": cs.col("x", xy[0], "numeric"),
"y": cs.col("y", xy[1], "numeric"),
"node": cs.col("Node", G.node_id, "categorical"),
"size": cs.col("Degree", deg, "numeric"),
"group": cs.col("Block", [str(q) for q in block], "categorical", level_names),
"from": cs.col("From", G.si[:show], "numeric"),
"to": cs.col("To", G.sj[:show], "numeric"),
"weight": cs.col("Weight", G.sw[:show], "numeric") if G.weighted else None,
}, controls={"directed": G.directed}, note=None if show == m else f"{show} of {m} edges drawn."))
# %% Result
how = f"chosen by {CRITERION_LABELS[CRITERION]}" if BLOCKS is None else "as set"
summary = (f"The {MODEL_LABELS[MODEL]} puts {N:,} nodes in {Q} block{'s' if Q != 1 else ''} ({how}); "
f"the average node sits in its block with probability {values['certainty']:.3f}.")
cs.publish({
"title": "Stochastic blockmodel",
"engine": cs.engine_info("numpy", "pandas", "scikit-learn"),
"n": N,
"summary": summary,
"statistics": [
{"key": "blocks", "label": "Blocks", "value": Q, "format": "integer"},
{"key": "icl", "label": "ICL", "value": values["icl"]},
{"key": "certainty", "label": "Mean certainty", "value": values["certainty"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": artifacts,
})
Check your understanding
CheckpointCheck yourself
A partition of a network has modularity 0.42. What does that tell you?
Show the answer
Answer: b
Modularity compares the observed share of links inside communities with the share expected at random. Random networks reach sizable values too, so it compares partitions; it doesn't prove them.
Check yourself
Why is Leiden the default rather than Louvain?
Show the answer
Answer: b
Leiden refines each community into well-connected parts before merging, so no community falls apart. Both use the same quality functions and resolution.
Check yourself
Leiden with modularity merges two small groups you know are separate. What do you try?
Show the answer
Answer: b
Modularity's resolution limit merges small communities. A higher resolution splits them; the constant Potts model has no such limit.
Check yourself
You have a table without an edge list. How does the method still find communities?
Show the answer
Answer: b
Row mode builds a nearest-neighbor graph from the columns; its communities are groups of rows, saved back as row labels.
Check yourself
A two-block fit has link probabilities 0.80 within block 1, 0.30 between the blocks and 0.02 within block 2. What shape is this?
Show the answer
Answer: b
The core links densely to itself and often to the periphery, whose members rarely link to each other. Communities would show a heavy diagonal in both blocks.
Check yourself
In a plain blockmodel, the three busiest hubs end up in a block of their own. What changes with the degree-corrected model?
Show the answer
Answer: a
The degree-corrected model explains hubs' many links by their degree, so blocks reflect whom nodes link to rather than how many links they have.
Check yourself
You planted three groups in a network of 36 nodes, but ICL picks two blocks. What is the likely reason?
Show the answer
Answer: b
ICL subtracts a penalty that grows with the number of blocks; with few nodes and links, the extra block's gain in fit can be smaller than its penalty.
Concepts in this lesson