Skip to content

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.

Applied ~15 min7 steps

What runs in CodeSplash

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

Read first

01

A club that split in two

Read

In 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.

Network communitiesRecorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

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

Communities in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromCommunityNodeStrengthToxy
020161−0.3181−0.2545
02192−0.2233−0.0757
041033−0.5988−0.5538
021114−0.7684−0.3116
021225−0.5555−0.3153
021359−0.0383−0.1016
01142110.65630.2455
01152120.5571−0.0469
0416214−0.5525−1
0217223−0.5518−0.1334
01182250.69510.1440
0219328−0.12180.0626
0221029−0.01840.0461
01202300.64960.0363
0221231−0.5239−0.0045
01222320.64640.3546
1323550.33250.4993
132439−0.05040.6329
13253110.11080.6623
11262120.62030.5661
13274140.12930.4353
13283230.14940.2290
11294240.50850.4495
123631−0.2882−0.1638
21304280.2164−0.0296
23316290.01650.2593
413212230.40040.1628
513317120.32490.2115
544323−0.4335−0.5876
545427−0.5362−0.7094
646426−0.4075−0.7379
627427−0.1466−0.2632
7185260.1237−0.0736
719227−0.00400.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.

Adjacency matrix by communityWhich nodes link to which, and do groups form blocks of dense ties?

Nodes sorted by community: dense blocks on the diagonal are communities.

View data
ColumnCommunityNodeOrderRowEdge
1202701
2212601
34103201
42112201
52122401
9213601
11114701
121151001
144161301
232171501
251181901
282193301
2922001
301201201
31221101
321222301
5323511
93243111
113251111
12126411
14327911
233281411
24129311
31232511
281301621
293312021
231321741
121331851
23442151
27452951
26463061
2727261
26182871
2719871
29———81
30———81
26———101
27———101
27———111
20———121
21———121
23———121
26———121
31———121
32———121
33———121
26———131
27———131
26———151
27———151
18———161
20———161
22———161
26———161
27———161
18———171
20———171
25———171
25———181
22———191

First 60 of 78 rows.

Community sizesHow often does each category occur?
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

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11235.3%0.2500yes33, 32, 8
21132.4%0.2333yes0, 2, 1
3617.6%0.4167yes31, 23, 27
4514.7%0.2500yes5, 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)
Python

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

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11235.3%0.2500yes33, 32, 8
21132.4%0.2333yes0, 2, 1
3617.6%0.4167yes31, 23, 27
4514.7%0.2500yes5, 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.

Network mapWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
xypersondegreeteamfromto
0.94700.0170Des-14Design01
0.82600.1750Des-25Design07
0.69500.2280Des-36Design08
0.49200.3110Des-46Design011
0.38600.1840Des-54Design12
0.2960−0.0400Des-62Design14
0.4430−0.1380Des-73Design18
0.5310−0.2670Des-84Design128
0.7340−0.2650Des-94Design23
0.8550−0.2200Des-104Design26
−0.07700.5650Eng-14Engineering28
−0.14700.6850Eng-25Engineering29
−0.23000.8190Eng-32Engineering211
−0.41000.7720Eng-45Engineering34
−0.50100.6470Eng-53Engineering35
−0.55500.5100Eng-63Engineering37
−0.52300.4220Eng-73Engineering324
−0.39100.2320Eng-84Engineering329
−0.17200.2530Eng-96Engineering49
−0.03400.3630Eng-105Engineering422
0.0220−0.5120Sal-16Sales57
−0.0140−0.3800Sal-21Sales67
−0.2370−0.2210Sal-33Sales69
−0.3810−0.2810Sal-46Sales89
−0.5410−0.3290Sal-57Sales1011
−0.5700−0.5090Sal-64Sales1013
−0.5450−0.7170Sal-73Sales1018
−0.4070−0.7670Sal-85Sales1019
−0.2460−0.7870Sal-95Sales1113
−0.1000−0.6820Sal-106Sales1116
—————1214
—————1216
—————1315
—————1317
—————1324
—————1417
—————1418
—————1518
—————1519
—————1618
—————1718
—————1719
—————1819
—————1928
—————2023
—————2025
—————2026
—————2027
—————2028
—————2029
—————2124
—————2227
—————2228
—————2324
—————2325
—————2326
—————2327
—————2328
—————2425
—————2427

First 60 of 64 rows.

02

Reading modularity honestly

Read

Modularity 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 2m\sqrt{2m} (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:

Network communitiesRecorded · Python and R agreeRecorded 2026-11-25 · 33 values compared
R

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

Communities by resolutionHow many clusters does the data support?

The ringed point is this run's resolution.

View data
This runMeasureResolutionValue
falseCommunities0.25002
falseCommunities0.50002
trueCommunities14
falseCommunities27
falseCommunities411
falseModularity0.25000.4036
falseModularity0.50000.4036
trueModularity10.4439
falseModularity20.3443
falseModularity40.2475
Communities in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromCommunityNodeStrengthToWeightxy
0204214−0.3181−0.2545
0212922−0.2233−0.0757
0310833−0.5988−0.5538
0211341−0.7684−0.3116
0212453−0.5555−0.3153
02131792−0.0383−0.1016
011451120.65630.2455
011571250.5571−0.0469
03166142−0.5525−1
02173233−0.5518−0.1334
011832520.69510.1440
02195283−0.12180.0626
02233293−0.01840.0461
012043030.64960.0363
02214312−0.5239−0.0045
012253220.64640.3546
112321550.33250.4993
1424791−0.05040.6329
1425141120.11080.6623
112661260.62030.5661
1127131420.12930.4353
142862330.14940.2290
1129132420.50850.4495
12318314−0.2882−0.1638
2130112830.2164−0.0296
2431212930.01650.2593
4132382330.40040.1628
5133481230.32490.2115
5348233−0.4335−0.5876
53514273−0.5362−0.7094
63613263−0.4075−0.7379
62713272−0.1466−0.2632
718172630.1237−0.0736
7193274−0.00400.3656
8———293——
8———303——
10———261——
10———272——
11———271——
12———202——
12———212——
12———233——
12———262——
12———314——
12———325——
12———331——
13———263——
13———271——
15———262——
15———273——
16———185——
16———204——
16———223——
16———265——
16———274——
17———182——
17———203——
17———252——
18———257——
19———224——

First 60 of 78 rows.

Adjacency matrix by communityWhich nodes link to which, and do groups form blocks of dense ties?

Nodes sorted by community: dense blocks on the diagonal are communities.

View data
ColumnCommunityNodeOrderRowWeight
1202704
2212602
33101603
42113201
52122003
92132202
111142402
12115705
143161902
23217603
251181502
282191303
29221003
301203303
31221002
321221202
5123115
94242311
11425512
121263116
141271112
23428413
241291412
3123314
28130923
294312923
231323043
12133253
23342853
2735853
26362563
27271862
26181773
27192174
29———83
30———83
26———101
27———102
27———111
20———122
21———122
23———123
26———122
31———124
32———125
33———121
26———133
27———131
26———152
27———153
18———165
20———164
22———163
26———165
27———164
18———172
20———173
25———172
25———187
22———194

First 60 of 78 rows.

Community sizesHow often does each category occur?
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

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11441.2%0.1856yes33, 32, 23
21132.4%0.1930yes0, 2, 1
3514.7%0.2245yes5, 6, 10
4411.8%0.4583yes31, 25, 24

Communities at other settings (resolution)

ResolutionCommunitiesModularity
0.250020.4036
0.500020.4036
140.4439
270.3443
4110.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)
Python

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

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11441.2%0.1856yes33, 32, 23
21132.4%0.1930yes0, 2, 1
3514.7%0.2245yes5, 6, 10
4411.8%0.4583yes31, 25, 24

Communities at other settings (resolution)

ResolutionCommunitiesModularity
0.250020.4036
0.500020.4036
140.4439
270.3443
4110.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)
Choosing kHow many clusters does the data support?
View data
number of clusters kscorecriterionrecommended
21009.44within-cluster SSfalse
20.4790silhouettefalse
21.406gap statisticfalse
3604.67within-cluster SSfalse
30.5390silhouettefalse
31.667gap statisticfalse
4266.55within-cluster SStrue
40.5690silhouettetrue
41.883gap statistictrue
5212.94within-cluster SSfalse
50.5610silhouettefalse
51.900gap statisticfalse
6172.92within-cluster SSfalse
60.4890silhouettefalse
61.880gap statisticfalse
7158.52within-cluster SSfalse
70.4350silhouettefalse
71.844gap statisticfalse
8143.15within-cluster SSfalse
80.3800silhouettefalse
81.835gap statisticfalse
9125.91within-cluster SSfalse
90.3080silhouettefalse
91.793gap statisticfalse
03

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.
Network communitiesRecorded · Python and R agreeRecorded 2026-11-25 · 34 values compared
R

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

Communities by inflationHow many clusters does the data support?

The ringed point is this run's inflation.

View data
This runMeasureInflationValue
falseCommunities1.4001
falseCommunities1.6002
falseCommunities22
falseCommunities2.5003
falseCommunities34
falseCommunities46
falseModularity1.4000
falseModularity1.6000.3715
falseModularity20.3600
falseModularity2.5000.3728
falseModularity30.3586
falseModularity40.3632
Communities in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromCommunityNodeStrengthToxy
020161−0.3181−0.2545
02192−0.2233−0.0757
021033−0.5988−0.5538
021114−0.7684−0.3116
021225−0.5555−0.3153
021359−0.0383−0.1016
01142110.65630.2455
01152120.5571−0.0469
0216214−0.5525−1
0217223−0.5518−0.1334
01182250.69510.1440
0219328−0.12180.0626
0221029−0.01840.0461
01202300.64960.0363
0221231−0.5239−0.0045
01222320.64640.3546
1123550.33250.4993
112439−0.05040.6329
11253110.11080.6623
11262120.62030.5661
11274140.12930.4353
11283230.14940.2290
11294240.50850.4495
123631−0.2882−0.1638
21304280.2164−0.0296
21316290.01650.2593
413212230.40040.1628
513317120.32490.2115
524323−0.4335−0.5876
525427−0.5362−0.7094
626426−0.4075−0.7379
627427−0.1466−0.2632
7185260.1237−0.0736
719227−0.00400.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.

Adjacency matrix by communityWhich nodes link to which, and do groups form blocks of dense ties?

Nodes sorted by community: dense blocks on the diagonal are communities.

View data
ColumnCommunityNodeOrderRowEdge
1202701
2212601
32102501
42111601
52123201
92132001
111142201
121152401
142161701
232171801
251182101
28219601
2922701
301201001
312211301
321221501
51231911
91243311
11125011
121261211
14127111
231282311
24129511
31232911
281303021
291313121
23132241
121331151
23242851
2725451
2626861
2727961
26181471
2719371
29———81
30———81
26———101
27———101
27———111
20———121
21———121
23———121
26———121
31———121
32———121
33———121
26———131
27———131
26———151
27———151
18———161
20———161
22———161
26———161
27———161
18———171
20———171
25———171
25———181
22———191

First 60 of 78 rows.

Community sizesHow often does each category occur?
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

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11852.9%0.1316yes33, 32, 31
21647.1%0.1316yes0, 2, 1

Communities at other settings (inflation)

InflationCommunitiesModularity
1.40010
1.60020.3715
220.3600
2.50030.3728
340.3586
460.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)
Python

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

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11852.9%0.1316yes33, 32, 31
21647.1%0.1316yes0, 2, 1

Communities at other settings (inflation)

InflationCommunitiesModularity
1.40010
1.60020.3715
220.3600
2.50030.3728
340.3586
460.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.
Network communitiesRecorded · Python and R agreeRecorded 2026-11-25 · 17 values compared
R

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

Communities in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromCommunityNodeStrengthToxy
0115100.07480.8574
03101216−0.3189−0.5455
03116190.2678−0.6332
1312122−0.0469−0.3780
131353−0.5093−0.1323
121494−0.22710.2959
14154100.2773−0.8726
12167130.36970.1788
14174180.3894−0.1070
211841−0.60920.4825
2119146−0.03120.0868
222412−10.0103
3220910.62410.0458
33372−0.7301−0.4961
344940.5314−0.3702
325670.89610.1924
316910−0.14250.7120
3277130.41450.5555
318814−0.2838−0.2194
4191310.05390.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.

Adjacency matrix by communityWhich nodes link to which, and do groups form blocks of dense ties?

Nodes sorted by community: dense blocks on the diagonal are communities.

View data
ColumnCommunityNodeOrderRowEdge
10111001
163101901
193111601
23121811
3313011
4214911
10415511
132161211
18417711
11181721
61191521
12221121
1220131
233331
4441331
725231
1016431
13271431
1418631
119841
3———41
7———51
8———51
11———51
17———51
14———61
18———61
5———71
12———71
15———71
19———71
12———81
14———81
5———91
16———91
1———101
3———101
5———101
14———101
16———101
18———101
19———101
5———111
13———111
2———121
15———121
17———121
19———121
1———131
3———131
11———131
18———131
3———141
6———141
8———141
10———141
7———151
12———151
14———151
17———151

First 60 of 77 rows.

Community sizesHow often does each category occur?
View data
Community
1
3
3
3
3
2
4
2
4
1
1
2
2
3
4
2
1
2
1
1

Communities

CommunityNodesShareConductanceIn one pieceBest-connected nodes
1630.0%0.3585yes19, 9, 6
2630.0%0.3810yes14, 20, 16
3525.0%0.3810yes10, 12, 3
4315.0%0.5294yes4, 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)
Python

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

CommunityNodesShareConductanceIn one pieceBest-connected nodes
1630.0%0.3585yes19, 9, 6
2630.0%0.3810yes14, 20, 16
3525.0%0.3810yes10, 12, 3
4315.0%0.5294yes4, 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.

04

Communities of rows

Read

Without 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.

Network communitiesRecorded · Python and R agreeRecorded 2026-11-25 · 27 values compared
R

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

CommunitiesWhich rows group together, and how well separated are the groups?
View data
CommunityPC1 (73%)PC2 (23%)
1−2.2650.4800
5−2.081−0.6741
5−2.364−0.3419
5−2.299−0.5974
1−2.3900.6468
1−2.0761.489
1−2.4440.0476
1−2.2330.2231
5−2.335−1.115
5−2.184−0.4690
1−2.1661.044
1−2.3260.1331
5−2.218−0.7287
5−2.633−0.9615
1−2.1991.860
1−2.2622.686
1−2.2081.484
1−2.1900.4888
1−1.8991.405
1−2.3431.128
1−1.9140.4089
1−2.2070.9241
1−2.7740.4583
1−1.8190.0856
1−2.2270.1373
5−1.952−0.6256
1−2.0510.2422
1−2.1690.5271
1−2.1400.3132
5−2.265−0.3377
5−2.140−0.5045
1−1.8320.4237
1−2.6151.794
1−2.4462.151
5−2.110−0.4602
5−2.208−0.2061
1−2.0450.6616
1−2.5270.5923
5−2.430−0.9042
1−2.1700.2689
1−2.2860.4417
5−1.858−2.337
5−2.554−0.4791
1−1.9640.4723
1−2.1371.142
5−2.070−0.7111
1−2.3851.120
5−2.394−0.3862
1−2.2290.9980
1−2.2040.0092
21.1020.8630
20.73130.5946
21.2410.6163
40.4075−1.754
21.075−0.2084
20.3887−0.5933
20.74650.7730
4−0.4873−1.852
20.92790.0322
40.0114−1.034

First 60 of 150 rows.

Community sizesHow often does each category occur?
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

CommunityRowsShareConductanceIn one piecesepal_lengthsepal_widthpetal_lengthpetal_width
13322.0%0.0462yes5.1703.6301.4940.2727
23221.3%0.2455yes6.1562.9914.5131.456
33020.0%0.1306yes6.9473.1475.8272.143
42114.0%0.1860yes5.5432.4433.9481.200
51711.3%0.1000yes4.6883.0351.4000.1941
61711.3%0.3441yes6.1412.6945.2061.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)
Python

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

CommunityRowsShareConductanceIn one piecesepal_lengthsepal_widthpetal_lengthpetal_width
13322.0%0.0462yes5.1703.6301.4940.2727
23221.3%0.2455yes6.1562.9914.5131.456
33020.0%0.1306yes6.9473.1475.8272.143
42114.0%0.1860yes5.5432.4433.9481.200
51711.3%0.1000yes4.6883.0351.4000.1941
61711.3%0.3441yes6.1412.6945.2061.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)
06

How many blocks?

Read

Each 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.

Stochastic blockmodelRecorded · Python and R agreeRecorded 2026-11-25 · 48 values compared
R

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

Rate per degree pair (λ) between blocksWhat do the values of a square or rectangular result matrix look like at a glance?
View data
With blockBlockRate per degree pair (λ)
Block 1Block 11.000e-10
Block 2Block 11.000e-10
Block 3Block 10.0028
Block 4Block 10.0149
Block 1Block 21.000e-10
Block 2Block 21.000e-10
Block 3Block 20.0164
Block 4Block 21.000e-10
Block 1Block 30.0028
Block 2Block 30.0164
Block 3Block 31.000e-10
Block 4Block 31.000e-10
Block 1Block 40.0149
Block 2Block 41.000e-10
Block 3Block 41.000e-10
Block 4Block 41.000e-10
Choosing the number of blocksHow many clusters does the data support?

Higher is better; ICL chose 4 blocks.

View data
BestCriterionBlocksCriterion
falseICL1−282.12
falseICL2−296.32
falseICL3−232.00
trueICL4−226.22
falseBIC1−282.12
falseBIC2−289.73
falseBIC3−231.60
trueBIC4−225.51
Adjacency matrix by blockWhich nodes link to which, and do groups form blocks of dense ties?

Nodes sorted by block: each tile of the matrix is one pair of blocks.

View data
ColumnBlockNodeOrderRowWeight
161b01504
181b02004
191b03403
211b04701
191b05611
211b061511
161b07323
191b08234
162b09144
172b101443
252b11843
162b121053
172b131352
182b141254
192b15954
201b161154
194s012564
203s021762
174s032771
184s042473
194s052374
234s062682
243s072284
273s081984
233s091691
273s101892
173s1120104
223s1221101
25———103
26———101
27———101
24———111
23———122
26———122
22———132
24———131
25———132
23———143
24———143
25———144
26———144
27———143
16———153
25———152
Blocks in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromBlockNodeDegreeToWeightxy
01b0112164−0.51410.5202
01b022184−0.55500.8667
01b033193−0.68060.1090
01b044211−0.32711
11b0510191−0.1663−0.0317
11b0617211−0.21970.4140
21b076163−0.11030.8516
31b088194−0.13780.4593
42b09101640.5225−0.6361
42b1031730.7887−0.4151
42b11102530.2320−0.2468
52b1211630.1282−0.9553
52b1341720.7217−0.6813
52b1451840.0579−0.5988
52b15171940.3433−0.5012
51b165204−0.2847−0.1355
64s0117194−0.40360.1727
63s0210202−0.01830.1371
74s0311171−0.34230.5054
74s0420183−0.31500.7085
74s056194−0.06930.6731
84s062232−0.69380.7380
83s0732440.1112−0.4558
83s0882740.6550−0.5573
93s0992310.2690−0.7467
93s10142720.0094−0.3119
103s1171740.4764−0.4937
103s12102210.5227−0.3882
10———253——
10———261——
10———271——
11———241——
12———232——
12———262——
13———222——
13———241——
13———252——
14———233——
14———243——
14———254——
14———264——
14———273——
15———163——
15———252——

Blocks

BlockNodesModel shareRate per degree pair (λ) withinMean certaintyBest-connected nodes
1932.8%1.000e-101.0000b06, b01, b05
2724.3%1.000e-100.9725b15, b09, b11
3725.2%1.000e-101.0000s10, s02, s12
4517.7%1.000e-100.9907s04, s01, s03

Rate per degree pair (λ) between blocks

BlockBlock 1Block 2Block 3Block 4
Block 11.000e-101.000e-100.00280.0149
Block 21.000e-101.000e-100.01641.000e-10
Block 30.00280.01641.000e-101.000e-10
Block 40.01491.000e-101.000e-101.000e-10

Number of blocks

BlocksICLBICLower 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
))
Python

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

BlockNodesModel shareRate per degree pair (λ) withinMean certaintyBest-connected nodes
1932.8%1.000e-101.0000b06, b01, b05
2724.3%1.000e-100.9725b15, b09, b11
3725.2%1.000e-101.0000s10, s02, s12
4517.7%1.000e-100.9907s04, s01, s03

Rate per degree pair (λ) between blocks

BlockBlock 1Block 2Block 3Block 4
Block 11.000e-101.000e-100.00280.0149
Block 21.000e-101.000e-100.01641.000e-10
Block 30.00280.01641.000e-101.000e-10
Block 40.01491.000e-101.000e-101.000e-10

Number of blocks

BlocksICLBICLower 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,
})
07

Check your understanding

Checkpoint

Check 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