Skip to content

CDiscover · discover.communities

Network communities

Which groups of nodes are linked more tightly to each other than to the rest of the network?

Finds communities: groups of nodes with many links inside and few between them. Leiden (the default) and Louvain maximize modularity or the constant Potts model, and Leiden keeps every community in one piece; label propagation lets each node copy the label most of its neighbors carry; Markov clustering (MCL) follows random walks, which stay trapped inside dense groups; Infomap finds the modules that describe a random walker's path most briefly (the map equation) and can follow edge directions. Without an edge list, each row links to its nearest neighbors in the chosen columns and the communities are groups of rows. Visit orders and random choices come from the shared random stream, so Python and R find the same communities.

Experimental Python and R agree to 6 decimals Seeded Also called community detection, network communities, graph clustering…

A real result

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

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

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Leiden karategraph_karate · source: member_a · target: member_b
  • Louvain karate weightedgraph_karate · source: member_a · target: member_b · weight: contexts
  • Leiden cpm blocksgraph_blocks_edges · source: from · target: to · weight: strength
  • Leiden resolution blocksgraph_blocks_edges · source: from · target: to
  • Label propagation blocksgraph_blocks_edges · source: from · target: to · weight: strength
  • Mcl karategraph_karate · source: member_a · target: member_b
  • Infomap directedgraph_directed · source: follower · target: followed
  • Infomap blocksgraph_blocks_edges · source: from · target: to · weight: strength

In the guides

Where it sits in the decision guides

  • Structure: independent, hierarchical / grouped, temporal / spatial, networked · DS & ML Decision Guide · Key data characteristics — what influences method choice
  • Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels

What you need

From (source)categorical / numeric · 0–1 column
One end of each edge: a person, page or station id. Leave empty to link rows to their nearest neighbors instead.
To (target)categorical / numeric · 0–1 column
The other end of each edge.
Edge weightnumeric · 0–1 column
Optional strength of each edge (positive numbers). Repeated edges add up; without it every edge counts 1.
Row featuresnumeric / categorical / boolean · 0–200 columns
Without an edge list: the columns that define each row's nearest neighbors. Categories enter as 0/1 indicator columns.
Known groupscategorical / boolean · 0–1 column
Row mode only: groups to compare with the communities (adjusted Rand index, NMI); never used to find them. In a network, use the node table's label.
Row labelscategorical / numeric · 0–1 column
Row mode only: names shown on the chart points.

Choices you make

model

Algorithmdefault leiden

Leiden is the safe default; Louvain is the classic; Infomap reads flow and direction; MCL and label propagation need no resolution.

  • Leiden(default) — Moves nodes, refines each community so it stays in one piece, then merges (Traag, Waltman & van Eck 2019).
  • Louvain — Moves nodes to the neighboring community that raises modularity most, then merges communities and repeats (Blondel et al. 2008). A community can end up in pieces.
  • Label propagation — Each node takes the label most of its neighbors carry (by weight) until nothing changes (Raghavan et al. 2007; Chinese Whispers).
  • Markov clustering (MCL) — Alternates spreading a random walk and sharpening it; walks stay inside dense groups (van Dongen 2000). Inflation sets how fine the groups are.
  • Infomap — The modules that let you describe a random walker's path in the fewest bits (the map equation; Rosvall & Bergstrom 2008). Follows directions when edges have them.
Quality functiondefault modularity

What the algorithm maximizes.

  • Modularity(default) — Links inside communities minus the number expected from the nodes' degrees alone (Newman 2006). Can't see communities smaller than about √(2 × edges).
  • Constant Potts model — Links inside communities minus the resolution times the number of node pairs: communities denser than the resolution (Traag et al. 2011). No size limit.
Resolution (γ)default —

Higher values give more, smaller communities. For the Potts model it is the edge density a community must exceed.

Inflationdefault 2

MCL's sharpening power: higher values give more, smaller clusters. 2 is the usual start; sparse networks often need 1.4–1.6.

Trialsdefault 5

Infomap searches this many times from different random orders and keeps the shortest description.

Edges have a directiondefault off

On: Infomap follows the direction of each edge (with teleportation, as PageRank does). The other algorithms treat every edge as two-way.

Neighbors per rowdefault 15

Row mode only: each row links to this many nearest rows (weight ½ per side, so mutual neighbors weigh 1).

options

Compare settingsdefault off

Also runs Leiden or Louvain at ¼, ½, 2 and 4 times the resolution, or MCL at other inflations, and shows how many communities each finds.

Node tabledefault —

Optional table with one row per node: its label column is compared with the communities (adjusted Rand index, NMI).

preprocess

Scale numbersdefault standard

Row mode only: standardize numbers so each counts equally in distances; turn off only when columns already share one unit.

  • Standardize (population SD)(default) — Rescales each number to mean 0 and SD 1 so every column counts equally in distances; the safe choice.
  • No scaling — Keeps raw values, so wide-ranging columns dominate distances; pick it only when columns share one unit.
Missing valuesdefault drop

Row mode only: rows with missing values are left out, or filled with the column median (categories get none).

  • Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
  • Fill with the median (categories → none) — Fills numeric gaps with the median and leaves category gaps as no category; keeps every row, at some cost to the shape.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Communities aren't unique

    Many different partitions score almost the same. Read the communities as one good answer; check how stable they are with other seeds and settings.

  • Modularity's resolution limit

    Modularity merges communities smaller than about the square root of twice the number of edges; raise the resolution or use the Potts model to see them.

  • Communities in one piece

    Leiden guarantees every community is connected; Louvain, label propagation and MCL can return a community in several pieces, which the table flags.

What it reports

mode
Splitting a network into groups of nodes with many links inside each group and few between groups.
algorithm_label
Splitting a network into groups of nodes with many links inside each group and few between groups.
n_nodes
Splitting a network into groups of nodes with many links inside each group and few between groups.
n_edges
Splitting a network into groups of nodes with many links inside each group and few between groups.
k
Splitting a network into groups of nodes with many links inside each group and few between groups.
modularity
The share of link weight inside communities minus the share expected if links fell at random given each node's degree.
coverage
The share of the network's edge weight that falls inside communities; 1 means no link crosses between them.
conductance
A community's outgoing link weight divided by the smaller of its own and the rest's total degree: lower is more separate.
n_disconnected
Moves each node to the neighboring community that raises modularity most, then merges communities into nodes and repeats.
largest_share
Splitting a network into groups of nodes with many links inside each group and few between groups.
singletons
Splitting a network into groups of nodes with many links inside each group and few between groups.

Per group, level or term: size[<community>], resolution, quality, levels, iterations, sweeps, converged, attractors, codelength, codelength_one, n_neighbors, n_labeled, ari, ami, nmi, silhouette, calinski_harabasz, davies_bouldin, sweep_setting[<i>], sweep_k[<i>], sweep_modularity[<i>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses numpy, pandas, scipy, codesplash; R uses nanoparquet, Matrix, codesplashr.

Default traps between the two languages

  • Both engines run the same written-out twins (codesplash.ml.communities ↔ codesplashr R/ml_communities.R) on the host's canonical node order: neighbors in index order, weights added in the same sequence, visit orders and Leiden's refinement draws from the shared Wichmann–Hill stream, and a move must beat staying by a small tolerance, so both engines take the same moves and return the same communities.
  • MCL multiplies sparse matrices (scipy.sparse ↔ Matrix), which add products in a different order; the limit matrices agree to rounding and give the same clusters.
  • Reference packages (igraph, leidenalg, networkx, Infomap) use other random generators and search refinements, so their partitions can differ while reaching similar modularity or codelength (P2/P3 against them).
Python

The exact script CodeSplash ran for example “Leiden karate” · 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)
R

The exact script CodeSplash ran for example “Leiden karate” · 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)

Sources

  • Newman MEJ (2006). Modularity and community structure in networks. PNAS 103:8577–8582.
  • Blondel VD, Guillaume J-L, Lambiotte R, Lefebvre E (2008). Fast unfolding of communities in large networks. J Stat Mech P10008.
  • Traag VA, Waltman L, van Eck NJ (2019). From Louvain to Leiden: guaranteeing well-connected communities. Scientific Reports 9:5233.
  • Traag VA, Van Dooren P, Nesterov Y (2011). Narrow scope for resolution-limit-free community detection. Phys Rev E 84:016114.
  • Raghavan UN, Albert R, Kumara S (2007). Near linear time algorithm to detect community structures in large-scale networks. Phys Rev E 76:036106.
  • Biemann C (2006). Chinese Whispers: an efficient graph clustering algorithm. TextGraphs workshop, HLT-NAACL, 73–80.
  • van Dongen S (2000). Graph clustering by flow simulation. PhD thesis, University of Utrecht.
  • Rosvall M, Bergstrom CT (2008). Maps of random walks on complex networks reveal community structure. PNAS 105:1118–1123.
  • Lambiotte R, Rosvall M (2012). Ranking and clustering of nodes in networks with smart teleportation. Phys Rev E 85:056107.
  • Fortunato S, Barthélemy M (2007). Resolution limit in community detection. PNAS 104:36–41.
  • Levine JH et al. (2015). Data-driven phenotypic dissection of AML reveals progenitor-like cells that correlate with prognosis. Cell 162:184–197 (PhenoGraph: communities of a kNN graph).

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