Skip to content

Describing a network

An edge list says who is tied to whom. Learn how the app turns it into a network, what density, clustering, assortativity and centrality measure, and how to read the map, the matrix and the degree curve.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Set up a network from an edge list, with an optional node table
  • Read size, density, separate parts, clustering and assortativity
  • Tell degree, betweenness, closeness, eigenvector centrality and PageRank apart
  • Keep node results as a dataset of their own
01

From rows to ties

Read

Most tables have one row per thing. An edge listEdge listA table with one row per tie: the two nodes it joins and, optionally, a weight or a time. has one row per tie: the two nodes it joins, and maybe a weight. A second table, the node tableNode tableAn optional second table with one row per node: its id, a label and attributes, joined to the network by id., can add one row per node with a label and attributes.

Before any measure runs, the app reads the edge list once. It drops rows with a missing end, merges repeated edges (adding their weights), leaves self-loops out, and puts the nodes in a fixed order. Python and R read the same result, so both describe the same network.

02

The karate club

Explore

In the 1970s Wayne Zachary recorded the friendships among 34 members of a university karate club. A quarrel split the club in two. The edge list has 78 friendships, each weighted by the number of settings in which the pair met.

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.

The map places tied members close together. Only the distances between dots mean something; the axes don't.

03

Make a guess

Predict

Predict first

There are 34 members and 78 friendships. What share of all possible pairs are friends (the density)?

Make your guess between 0 and 1 share of pairs, then reveal.

Reveal

The density is 0.139: 78 of 561 possible pairs. Real networks are sparse, and the bigger they get, the sparser.

04

Friends of friends

Checkpoint

TransitivityTransitivityShare of connected triples (A–B–C) that close into a triangle: how often a friend of a friend is a friend. is the share of "A knows B, B knows C" chains that close into a triangle. In the club it's 0.256. The average local clustering is 0.571.

Degree assortativityDegree assortativityCorrelation between the degrees at the two ends of each edge: positive when hubs link to hubs, negative when hubs link to small nodes. asks whether well-connected members befriend each other. In the unweighted club it's −0.476: the two leaders' many friends are mostly members with few ties.

Check yourself

A network's degree assortativity is −0.48. What does that say?

Show the answer

Answer: b

Assortativity is a correlation between the degrees at the two ends of each edge. Negative values mean hubs connect to small nodes, as in a club organized around two leaders.

05

Who is central?

In the app
Network description (size, degrees, clustering, centrality)Recorded · Python and R agreeRecorded 2026-11-25 · 231 values compared
R

A undirected network of 34 nodes and 78 edges (density 0.139); 1 part(s), the largest with 34 nodes.

Nodes
34
Edges
78
Density
0.1390
Separate parts
1
Transitivity
0.2557
Degree assortativity
−0.4756

Plots

Network mapWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromclubNodeDegreeToWeightxy
0Mr. Hi01614−0.3181−0.2545
0Mr. Hi1922−0.2233−0.0757
0Mr. Hi10333−0.5988−0.5538
0Mr. Hi11141−0.7684−0.3116
0Mr. Hi12253−0.5555−0.3153
0Mr. Hi13592−0.0383−0.1016
0Officer1421120.65630.2455
0Officer1521250.5571−0.0469
0Mr. Hi162142−0.5525−1
0Mr. Hi172233−0.5518−0.1334
0Officer1822520.69510.1440
0Mr. Hi193283−0.12180.0626
0Mr. Hi210293−0.01840.0461
0Officer2023030.64960.0363
0Mr. Hi212312−0.5239−0.0045
0Officer2223220.64640.3546
1Officer235550.33250.4993
1Officer24391−0.05040.6329
1Officer2531120.11080.6623
1Officer2621260.62030.5661
1Officer2741420.12930.4353
1Officer2832330.14940.2290
1Officer2942420.50850.4495
1Mr. Hi36314−0.2882−0.1638
2Officer3042830.2164−0.0296
2Officer3162930.01650.2593
4Officer32122330.40040.1628
5Officer33171230.32490.2115
5Mr. Hi43233−0.4335−0.5876
5Mr. Hi54273−0.5362−0.7094
6Mr. Hi64263−0.4075−0.7379
6Mr. Hi74272−0.1466−0.2632
7Mr. Hi852630.1237−0.0736
7Officer92274−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.

Degree distributionDo a few nodes hold most of the ties (a heavy tail), or are degrees much alike?
View data
Degree kDegreeShare of nodes with degree ≥ k
1Degree1
2Degree0.9706
3Degree0.6471
4Degree0.4706
5Degree0.2941
6Degree0.2059
9Degree0.1471
10Degree0.1176
12Degree0.0882
16Degree0.0588
17Degree0.0294
Adjacency matrixWhich nodes link to which, and do groups form blocks of dense ties?
View data
ColumnclubNodeOrderRowWeight
1Mr. Hi0004
2Mr. Hi11202
3Mr. Hi10103
4Mr. Hi112301
5Mr. Hi12503
9Mr. Hi133202
11Officer142902
12Officer153005
14Mr. Hi163102
23Mr. Hi17203
25Officer181102
28Mr. Hi192803
29Mr. Hi2403
30Officer20803
31Mr. Hi21902
32Officer221402
5Officer23315
9Officer242711
11Officer252612
12Officer262516
14Officer271612
23Officer282013
24Officer292212
31Mr. Hi32414
28Officer301723
29Officer311823
23Officer322143
12Officer33653
23Mr. Hi4753
27Mr. Hi51053
26Mr. Hi61363
27Mr. Hi71562
26Mr. Hi81973
27Officer93374
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.

Most central nodes (by PageRank)

NodeclubDegreePageRankEigenvectorClusteringBetweennessCloseness
33Officer170.09700.36410.11030.30410.5500
0Mr. Hi160.08850.31240.15000.43760.5690
32Officer120.07590.33230.19700.14520.5156
2Mr. Hi100.06280.36060.24440.14370.5593
1Mr. Hi90.05740.30180.33330.05390.4853
31Officer60.04200.20950.20000.13830.5410
23Officer50.04110.21800.40000.01760.3929
3Mr. Hi60.03720.19860.66670.01190.4648
5Mr. Hi40.03380.06740.50000.03000.3837
13Mr. Hi50.03350.24050.60000.04590.5156
8Mr. Hi50.03340.24700.50000.05590.5156
6Mr. Hi40.03150.06640.50000.03000.3837
25Officer30.02870.12260.33330.00380.3750
29Officer40.02830.13580.66670.00290.3837
27Officer40.02720.14770.16670.02230.4583
7Mr. Hi40.02650.1784100.4400
30Officer40.02300.15830.50000.01440.4583
10Mr. Hi30.02070.04580.66670.00060.3793
4Mr. Hi30.02050.05570.66670.00060.3793
16Mr. Hi20.01680.0185100.2845
24Officer30.01660.05100.33330.00220.3750
15Officer20.01640.1131100.3708
26Officer20.01520.0586100.3626
28Officer30.01450.08610.33330.00180.4521
19Mr. Hi30.01310.07340.33330.03250.5000

Network checks

CheckCount
Edge rows78
Edge rows left out (missing source, target or weight)0
Self-loops0
Repeated edges merged0
Isolated nodes0
Separate parts1
Node table rows34
Node table rows left out0
Nodes not in the node table0
Node table nodes with no edges0
The exact R script · R R version 4.5.1 (2025-06-13)
# Network description (size, degrees, clustering, centrality)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.network 1.0.0 · spec 2393515369599210
# 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)

# %% Network
# The app read the edge list once and wrote the network next to this run (graph/ in the output folder):
# nodes in a fixed order, the edges, and the simple network (self-loops left out, repeated edges merged with
# their weights added). Python and R read the same files, so both describe the same network.
out_dir <- "target/academy-parity/run-8142/describe.network/karate_club/out-r"
g <- cs_graph_read(out_dir)
warnings <- g$warnings
weighted <- TRUE && isTRUE(g$weighted)
damping <- 0.85
max_path_nodes <- as.integer(5000)
seed <- 42
MAP_NODES <- 2000  # largest network drawn as a map
MATRIX_NODES <- 300  # largest network drawn as a matrix
PER_NODE <- 200  # per-node values go into the result for networks up to this size
if (weighted) {
  bad <- sum(as.numeric(g$edges[["w"]]) <= 0)
  if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = "contexts", requirement = "positive for weighted measures (or turn off Use weights)", count = bad)
}
n <- g$n
m <- length(g$si)
meta <- g$meta

# %% Measures
# Degrees, density, reciprocity, clustering and assortativity, then one breadth-first search per node for
# betweenness, closeness and distances (Brandes 2001), then eigenvector centrality and PageRank by power
# iteration. Definitions follow networkx; the twins are codesplashr R/graph_describe.R and codesplash.
deg <- cs_graph_degrees(g)
cl <- cs_graph_clustering(g)
pa <- cs_graph_paths(g, max_path_nodes)
ev <- cs_graph_eigenvector(g, weighted)
pr <- cs_graph_pagerank(g, damping, weighted)
comp <- cs_graph_components(g)
if (!ev$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = "Eigenvector centrality"))
if (!pr$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = "PageRank"))
if (is.null(pa)) {
  warnings <- c(warnings, sprintf("Betweenness, closeness and distances were skipped: the network has more than %d nodes.", max_path_nodes))
}

nn <- function(x) if (is.finite(x)) as.numeric(x) else NULL

degree <- deg$degree
centralization <- NULL
if (!isTRUE(g$directed) && n > 2) centralization <- sum(as.numeric(max(degree) - degree)) / ((n - 1) * (n - 2))
values <- list(
  n_nodes = n,
  n_edges = m,
  n_edge_rows = as.integer(meta$n_edges),
  density = nn(cs_graph_density(g)),
  mean_degree = mean(as.numeric(degree)),
  median_degree = stats::median(as.numeric(degree)),
  max_degree = max(degree),
  max_in_degree = if (isTRUE(g$directed)) max(deg$in_degree) else NULL,
  max_out_degree = if (isTRUE(g$directed)) max(deg$out_degree) else NULL,
  reciprocity = if (isTRUE(g$directed)) nn(cs_graph_reciprocity(g)) else NULL,
  components = as.integer(meta$components),
  largest_component = as.integer(meta$largest_component),
  largest_share = as.integer(meta$largest_component) / n,
  isolates = as.integer(meta$isolates),
  self_loops = as.integer(meta$self_loops),
  duplicate_edges = as.integer(meta$duplicate_edges),
  triangles = cl$triangles,
  transitivity = cl$transitivity,
  avg_clustering = cl$average,
  assortativity = nn(cs_graph_assortativity(g)),
  degree_centralization = centralization,
  avg_path_length = if (!is.null(pa)) nn(pa$avg_path_length) else NULL,
  diameter = if (!is.null(pa)) nn(pa$diameter) else NULL,
  max_betweenness = if (!is.null(pa)) max(pa$betweenness) else NULL,
  max_closeness = if (!is.null(pa)) max(pa$closeness) else NULL,
  max_eigenvector = max(ev$x),
  max_pagerank = max(pr$x)
)
if (n <= PER_NODE) {
  for (k in seq_len(n)) {
    node <- g$node_id[k]
    values[[sprintf("degree[%s]", node)]] <- degree[k]
    if (isTRUE(g$directed)) {
      values[[sprintf("in_degree[%s]", node)]] <- deg$in_degree[k]
      values[[sprintf("out_degree[%s]", node)]] <- deg$out_degree[k]
    }
    values[[sprintf("clustering[%s]", node)]] <- cl$local[k]
    if (!is.null(pa)) {
      values[[sprintf("betweenness[%s]", node)]] <- pa$betweenness[k]
      values[[sprintf("closeness[%s]", node)]] <- pa$closeness[k]
    }
    values[[sprintf("eigenvector[%s]", node)]] <- ev$x[k]
    values[[sprintf("pagerank[%s]", node)]] <- pr$x[k]
  }
}

# %% Node table
# One row per node (node_id first); the app can save it as a dataset ("Save node table as dataset").
label <- if (!is.null(g$label)) g$nodes[[g$label]] else NULL
xy <- if (n <= MAP_NODES) cs_graph_layout_fr(g, seed) else NULL
cols <- list()
if (!is.null(label)) cols[[g$label]] <- label
cols$component <- comp + 1L
cols$degree <- degree
if (isTRUE(g$directed)) {
  cols$in_degree <- deg$in_degree
  cols$out_degree <- deg$out_degree
}
if (isTRUE(g$weighted)) {
  if (isTRUE(g$directed)) {
    cols$in_strength <- deg$in_strength
    cols$out_strength <- deg$out_strength
  } else {
    cols$strength <- deg$strength
  }
}
cols$clustering <- cl$local
if (!is.null(pa)) {
  cols$betweenness <- pa$betweenness
  cols$closeness <- pa$closeness
}
cols$eigenvector <- ev$x
cols$pagerank <- pr$x
if (!is.null(xy)) {
  cols$map_x <- xy$x
  cols$map_y <- xy$y
}
artifact <- cs_graph_write_nodes(out_dir, g, cols)

# %% Tables
ord <- head(order(-pr$x, seq_len(n)), 25L)
node_cols <- list(list(key = "node", label = "Node"))
if (!is.null(label)) node_cols[[length(node_cols) + 1L]] <- list(key = "label", label = g$label)
node_cols <- c(node_cols, list(
  list(key = "degree", label = "Degree", type = "integer"), list(key = "pagerank", label = "PageRank", type = "number"),
  list(key = "eigenvector", label = "Eigenvector", type = "number"), list(key = "clustering", label = "Clustering", type = "number")
))
if (!is.null(pa)) {
  node_cols <- c(node_cols, list(list(key = "betweenness", label = "Betweenness", type = "number"), list(key = "closeness", label = "Closeness", type = "number")))
}
rows <- lapply(ord, function(k) {
  r <- list(node = g$node_id[k], degree = degree[k], pagerank = pr$x[k], eigenvector = ev$x[k], clustering = cl$local[k])
  if (!is.null(label)) r$label <- if (is.na(label[k])) NULL else as.character(label[k])
  if (!is.null(pa)) {
    r$betweenness <- pa$betweenness[k]
    r$closeness <- pa$closeness[k]
  }
  r
})
checks <- list(
  list("Edge rows", as.integer(meta$input_rows)),
  list("Edge rows left out (missing source, target or weight)", as.integer(meta$dropped_rows)),
  list("Self-loops", as.integer(meta$self_loops)),
  list("Repeated edges merged", as.integer(meta$duplicate_edges)),
  list("Isolated nodes", as.integer(meta$isolates)),
  list("Separate parts", as.integer(meta$components))
)
nt <- meta$node_table
if (!is.null(nt)) {
  checks <- c(checks, list(
    list("Node table rows", as.integer(nt$rows)), list("Node table rows left out", as.integer(nt$dropped_rows)),
    list("Nodes not in the node table", as.integer(nt$missing_ids)), list("Node table nodes with no edges", as.integer(nt$extra_ids))
  ))
}
tables <- list(
  list(key = "top_nodes", title = "Most central nodes (by PageRank)", columns = node_cols, rows = rows),
  list(key = "checks", title = "Network checks", columns = list(list(key = "check", label = "Check"), list(key = "count", label = "Count", type = "integer")),
       rows = lapply(checks, function(x) list(check = x[[1]], count = x[[2]])))
)

# %% Charts
# Node and edge columns share one chart table: shorter columns end in empty cells.
padded <- function(v, rows) c(v, rep(NA, rows - length(v)))
group <- if (!is.null(label)) ifelse(is.na(label), "(missing)", as.character(label)) else paste("part", comp + 1L)
group_title <- if (!is.null(label)) g$label else "Part"
charts <- list()
if (!is.null(xy)) {
  show <- min(m, 20000L)
  keep <- seq_len(show)
  rows_map <- max(n, show)
  charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Network map", list(
    x = cs_col("x", padded(xy$x, rows_map), "numeric"),
    y = cs_col("y", padded(xy$y, rows_map), "numeric"),
    node = cs_col("Node", padded(g$node_id, rows_map), "categorical"),
    size = cs_col("Degree", padded(degree, rows_map), "numeric"),
    group = cs_col(group_title, padded(group, rows_map), "categorical"),
    from = cs_col("From", padded(g$si[keep], rows_map), "numeric"),
    to = cs_col("To", padded(g$sj[keep], rows_map), "numeric"),
    weight = if (isTRUE(g$weighted)) cs_col("Weight", padded(g$sw[keep], rows_map), "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", "Network map", list(), note = sprintf("The map is drawn for networks up to %d nodes; this one has %d.", MAP_NODES, n))
}
if (isTRUE(g$directed)) {
  ci <- cs_graph_degree_ccdf(deg$in_degree)
  co <- cs_graph_degree_ccdf(deg$out_degree)
  ks <- c(ci$k, co$k)
  ps <- c(ci$p, co$p)
  series <- c(rep("In-degree", length(ci$k)), rep("Out-degree", length(co$k)))
  series_levels <- c("In-degree", "Out-degree")
} else {
  ca <- cs_graph_degree_ccdf(degree)
  ks <- ca$k
  ps <- ca$p
  series <- rep("Degree", length(ca$k))
  series_levels <- "Degree"
}
charts[[length(charts) + 1L]] <- cs_chart("degrees", "degree-ccdf", "Degree distribution", list(
  degree = cs_col("Degree k", ks, "numeric"),
  share = cs_col("Share of nodes with degree ≥ k", ps, "numeric"),
  series = cs_col("Degree", series, "categorical", levels = series_levels)
))
if (n <= MATRIX_NODES) {
  morder <- order(group == "(missing)", group, -degree, seq_len(n), method = "radix") - 1L
  rows_mx <- max(n, m)
  charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix", list(
    row = cs_col("Row", padded(g$si, rows_mx), "numeric"),
    col = cs_col("Column", padded(g$sj, rows_mx), "numeric"),
    value = cs_col(if (isTRUE(g$weighted)) "Weight" else "Edge", padded(g$sw, rows_mx), "numeric"),
    node = cs_col("Node", padded(g$node_id, rows_mx), "categorical"),
    group = cs_col(group_title, padded(group, rows_mx), "categorical"),
    order = cs_col("Order", padded(morder, rows_mx), "numeric")
  ), controls = list(directed = isTRUE(g$directed)))
}

# %% Result
kind <- if (isTRUE(g$directed)) "directed" else "undirected"
dens <- if (is.null(values$density)) "undefined" else sprintf("%.3f", values$density)
summary <- sprintf("A %s network of %d nodes and %d edges (density %s); %d part(s), the largest with %d nodes.",
                   kind, n, m, dens, values$components, values$largest_component)
cs_publish(list(
  title = "Network description (size, degrees, clustering, centrality)",
  engine = cs_engine_info("jsonlite", "nanoparquet"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "n_nodes", label = "Nodes", value = n, format = "integer"),
    list(key = "n_edges", label = "Edges", value = m, format = "integer"),
    list(key = "density", label = "Density", value = values$density),
    list(key = "components", label = "Separate parts", value = values$components, format = "integer"),
    list(key = "transitivity", label = "Transitivity", value = values$transitivity),
    list(key = "assortativity", label = "Degree assortativity", value = values$assortativity)
  ),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(artifact)
))
Python

A undirected network of 34 nodes and 78 edges (density 0.139); 1 part(s), the largest with 34 nodes.

Nodes
34
Edges
78
Density
0.1390
Separate parts
1
Transitivity
0.2557
Degree assortativity
−0.4756

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

Most central nodes (by PageRank)

NodeclubDegreePageRankEigenvectorClusteringBetweennessCloseness
33Officer170.09700.36410.11030.30410.5500
0Mr. Hi160.08850.31240.15000.43760.5690
32Officer120.07590.33230.19700.14520.5156
2Mr. Hi100.06280.36060.24440.14370.5593
1Mr. Hi90.05740.30180.33330.05390.4853
31Officer60.04200.20950.20000.13830.5410
23Officer50.04110.21800.40000.01760.3929
3Mr. Hi60.03720.19860.66670.01190.4648
5Mr. Hi40.03380.06740.50000.03000.3837
13Mr. Hi50.03350.24050.60000.04590.5156
8Mr. Hi50.03340.24700.50000.05590.5156
6Mr. Hi40.03150.06640.50000.03000.3837
25Officer30.02870.12260.33330.00380.3750
29Officer40.02830.13580.66670.00290.3837
27Officer40.02720.14770.16670.02230.4583
7Mr. Hi40.02650.1784100.4400
30Officer40.02300.15830.50000.01440.4583
10Mr. Hi30.02070.04580.66670.00060.3793
4Mr. Hi30.02050.05570.66670.00060.3793
16Mr. Hi20.01680.0185100.2845
24Officer30.01660.05100.33330.00220.3750
15Officer20.01640.1131100.3708
26Officer20.01520.0586100.3626
28Officer30.01450.08610.33330.00180.4521
19Mr. Hi30.01310.07340.33330.03250.5000

Network checks

CheckCount
Edge rows78
Edge rows left out (missing source, target or weight)0
Self-loops0
Repeated edges merged0
Isolated nodes0
Separate parts1
Node table rows34
Node table rows left out0
Nodes not in the node table0
Node table nodes with no edges0
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Network description (size, degrees, clustering, centrality)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.network 1.0.0 · spec 2393515369599210
# 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 codesplash as cs
from codesplash import graph as cg
from codesplash.graph import describe as gd
from codesplash.graph import layout as gl

# %% Network
# The app read the edge list once and wrote the network next to this run (graph/ in the output folder):
# nodes in a fixed order, the edges, and the simple network (self-loops left out, repeated edges merged with
# their weights added). Python and R read the same files, so both describe the same network.
out_dir = "target/academy-parity/run-8142/describe.network/karate_club/out-python"
g = cg.read(out_dir)
warnings = list(g.warnings)
weighted = True and g.weighted
damping = 0.85
max_path_nodes = int(5000)
seed = 42
MAP_NODES = 2000  # largest network drawn as a map
MATRIX_NODES = 300  # largest network drawn as a matrix
PER_NODE = 200  # per-node values go into the result for networks up to this size
if weighted:
    bad = int((g.edges["w"].to_numpy(dtype=float) <= 0).sum())
    if bad:
        cs.cs_error("CS_E_INVALID_VALUES", column="contexts", requirement="positive for weighted measures (or turn off Use weights)", count=bad)
n = g.n
m = len(g.si)
meta = g.meta

# %% Measures
# Degrees, density, reciprocity, clustering and assortativity, then one breadth-first search per node for
# betweenness, closeness and distances (Brandes 2001), then eigenvector centrality and PageRank by power
# iteration. Definitions follow networkx; the twins are codesplash.graph.describe and codesplashr.
deg = gd.degrees(g)
cl = gd.clustering(g)
pa = gd.paths(g, max_path_nodes)
ev = gd.eigenvector(g, weighted)
pr = gd.pagerank(g, damping, weighted)
comp = gd.components(g)
if not ev["converged"]:
    warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what="Eigenvector centrality"))
if not pr["converged"]:
    warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what="PageRank"))
if pa is None:
    warnings.append(f"Betweenness, closeness and distances were skipped: the network has more than {max_path_nodes} nodes.")


def nn(x):
    """A finite number, or None."""
    x = float(x)
    return x if np.isfinite(x) else None


degree = deg["degree"]
centralization = None
if not g.directed and n > 2:
    centralization = float((degree.max() - degree).sum()) / ((n - 1) * (n - 2))
values = {
    "n_nodes": n,
    "n_edges": m,
    "n_edge_rows": int(meta["n_edges"]),
    "density": nn(gd.density(g)),
    "mean_degree": float(degree.mean()),
    "median_degree": float(np.median(degree)),
    "max_degree": int(degree.max()),
    "max_in_degree": int(deg["in_degree"].max()) if g.directed else None,
    "max_out_degree": int(deg["out_degree"].max()) if g.directed else None,
    "reciprocity": nn(gd.reciprocity(g)) if g.directed else None,
    "components": int(meta["components"]),
    "largest_component": int(meta["largest_component"]),
    "largest_share": int(meta["largest_component"]) / n,
    "isolates": int(meta["isolates"]),
    "self_loops": int(meta["self_loops"]),
    "duplicate_edges": int(meta["duplicate_edges"]),
    "triangles": cl["triangles"],
    "transitivity": cl["transitivity"],
    "avg_clustering": cl["average"],
    "assortativity": nn(gd.assortativity(g)),
    "degree_centralization": centralization,
    "avg_path_length": nn(pa["avg_path_length"]) if pa else None,
    "diameter": nn(pa["diameter"]) if pa else None,
    "max_betweenness": float(pa["betweenness"].max()) if pa else None,
    "max_closeness": float(pa["closeness"].max()) if pa else None,
    "max_eigenvector": float(ev["x"].max()),
    "max_pagerank": float(pr["x"].max()),
}
if n <= PER_NODE:
    for k, node in enumerate(g.node_id):
        values[f"degree[{node}]"] = int(degree[k])
        if g.directed:
            values[f"in_degree[{node}]"] = int(deg["in_degree"][k])
            values[f"out_degree[{node}]"] = int(deg["out_degree"][k])
        values[f"clustering[{node}]"] = float(cl["local"][k])
        if pa:
            values[f"betweenness[{node}]"] = float(pa["betweenness"][k])
            values[f"closeness[{node}]"] = float(pa["closeness"][k])
        values[f"eigenvector[{node}]"] = float(ev["x"][k])
        values[f"pagerank[{node}]"] = float(pr["x"][k])

# %% Node table
# One row per node (node_id first); the app can save it as a dataset ("Save node table as dataset").
label = g.nodes[g.label].astype(object).where(g.nodes[g.label].notna(), None).tolist() if g.label else None
xy = gl.fruchterman_reingold(g, seed) if n <= MAP_NODES else None
cols = {}
if label is not None:
    cols[g.label] = label
cols["component"] = comp + 1
cols["degree"] = degree
if g.directed:
    cols["in_degree"] = deg["in_degree"]
    cols["out_degree"] = deg["out_degree"]
if g.weighted:
    if g.directed:
        cols["in_strength"] = deg["in_strength"]
        cols["out_strength"] = deg["out_strength"]
    else:
        cols["strength"] = deg["strength"]
cols["clustering"] = cl["local"]
if pa:
    cols["betweenness"] = pa["betweenness"]
    cols["closeness"] = pa["closeness"]
cols["eigenvector"] = ev["x"]
cols["pagerank"] = pr["x"]
if xy is not None:
    cols["map_x"], cols["map_y"] = xy
artifact = cg.write_nodes(out_dir, g, cols)

# %% Tables
order = np.lexsort((np.arange(n), -pr["x"]))[:25]
node_cols = [{"key": "node", "label": "Node"}]
if label is not None:
    node_cols.append({"key": "label", "label": g.label})
node_cols += [{"key": "degree", "label": "Degree", "type": "integer"}, {"key": "pagerank", "label": "PageRank", "type": "number"},
              {"key": "eigenvector", "label": "Eigenvector", "type": "number"}, {"key": "clustering", "label": "Clustering", "type": "number"}]
if pa:
    node_cols += [{"key": "betweenness", "label": "Betweenness", "type": "number"}, {"key": "closeness", "label": "Closeness", "type": "number"}]
rows = []
for k in order.tolist():
    r = {"node": g.node_id[k], "degree": int(degree[k]), "pagerank": float(pr["x"][k]), "eigenvector": float(ev["x"][k]), "clustering": float(cl["local"][k])}
    if label is not None:
        r["label"] = None if label[k] is None else str(label[k])
    if pa:
        r["betweenness"] = float(pa["betweenness"][k])
        r["closeness"] = float(pa["closeness"][k])
    rows.append(r)
checks = [
    ("Edge rows", int(meta["input_rows"])),
    ("Edge rows left out (missing source, target or weight)", int(meta["dropped_rows"])),
    ("Self-loops", int(meta["self_loops"])),
    ("Repeated edges merged", int(meta["duplicate_edges"])),
    ("Isolated nodes", int(meta["isolates"])),
    ("Separate parts", int(meta["components"])),
]
nt = meta.get("node_table")
if nt:
    checks += [("Node table rows", int(nt["rows"])), ("Node table rows left out", int(nt["dropped_rows"])),
               ("Nodes not in the node table", int(nt["missing_ids"])), ("Node table nodes with no edges", int(nt["extra_ids"]))]
tables = [
    {"key": "top_nodes", "title": "Most central nodes (by PageRank)", "columns": node_cols, "rows": rows},
    {"key": "checks", "title": "Network checks", "columns": [{"key": "check", "label": "Check"}, {"key": "count", "label": "Count", "type": "integer"}],
     "rows": [{"check": c, "count": k} for c, k in checks]},
]

# %% Charts
def padded(values, rows):
    """Node and edge columns share one chart table: shorter columns end in empty cells."""
    vals = list(values.tolist() if hasattr(values, "tolist") else values)
    return vals + [None] * (rows - len(vals))


group = [("(missing)" if v is None else str(v)) for v in label] if label is not None else [f"part {c + 1}" for c in comp]
group_title = g.label if label is not None else "Part"
charts = []
if xy is not None:
    show = min(m, 20000)
    rows_map = max(n, show)
    charts.append(cs.chart("map", "network-graph", "Network map", {
        "x": cs.col("x", padded(xy[0], rows_map), "numeric"),
        "y": cs.col("y", padded(xy[1], rows_map), "numeric"),
        "node": cs.col("Node", padded(g.node_id, rows_map), "categorical"),
        "size": cs.col("Degree", padded(degree, rows_map), "numeric"),
        "group": cs.col(group_title, padded(group, rows_map), "categorical"),
        "from": cs.col("From", padded(g.si[:show], rows_map), "numeric"),
        "to": cs.col("To", padded(g.sj[:show], rows_map), "numeric"),
        "weight": cs.col("Weight", padded(g.sw[:show], rows_map), "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", "Network map", {}, note=f"The map is drawn for networks up to {MAP_NODES} nodes; this one has {n}."))
if g.directed:
    k_in, p_in = gd.degree_ccdf(deg["in_degree"])
    k_out, p_out = gd.degree_ccdf(deg["out_degree"])
    ks, ps, series = list(k_in) + list(k_out), list(p_in) + list(p_out), ["In-degree"] * len(k_in) + ["Out-degree"] * len(k_out)
    series_levels = ["In-degree", "Out-degree"]
else:
    k_all, p_all = gd.degree_ccdf(degree)
    ks, ps, series, series_levels = list(k_all), list(p_all), ["Degree"] * len(k_all), ["Degree"]
charts.append(cs.chart("degrees", "degree-ccdf", "Degree distribution", {
    "degree": cs.col("Degree k", ks, "numeric"),
    "share": cs.col("Share of nodes with degree ≥ k", ps, "numeric"),
    "series": cs.col("Degree", series, "categorical", series_levels),
}))
if n <= MATRIX_NODES:
    morder = sorted(range(n), key=lambda k: (group[k] == "(missing)", group[k], -int(degree[k]), k))
    rows_mx = max(n, m)
    charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix", {
        "row": cs.col("Row", padded(g.si, rows_mx), "numeric"),
        "col": cs.col("Column", padded(g.sj, rows_mx), "numeric"),
        "value": cs.col("Weight" if g.weighted else "Edge", padded(g.sw, rows_mx), "numeric"),
        "node": cs.col("Node", padded(g.node_id, rows_mx), "categorical"),
        "group": cs.col(group_title, padded(group, rows_mx), "categorical"),
        "order": cs.col("Order", padded(morder, rows_mx), "numeric"),
    }, controls={"directed": g.directed}))

# %% Result
kind = "directed" if g.directed else "undirected"
dens = "undefined" if values["density"] is None else f"{values['density']:.3f}"
summary = f"A {kind} network of {n} nodes and {m} edges (density {dens}); {values['components']} part(s), the largest with {values['largest_component']} nodes."
cs.publish({
    "title": "Network description (size, degrees, clustering, centrality)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "n_nodes", "label": "Nodes", "value": n, "format": "integer"},
        {"key": "n_edges", "label": "Edges", "value": m, "format": "integer"},
        {"key": "density", "label": "Density", "value": values["density"]},
        {"key": "components", "label": "Separate parts", "value": values["components"], "format": "integer"},
        {"key": "transitivity", "label": "Transitivity", "value": values["transitivity"]},
        {"key": "assortativity", "label": "Degree assortativity", "value": values["assortativity"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [artifact],
})

Each centrality answers a different question:

  • Degree: how many ties a node has.
  • BetweennessBetweenness centralityShare of shortest paths between other pairs that pass through a node (0 to 1): high for brokers between groups.: how many shortest paths between others pass through it. Brokers between groups score high.
  • Closeness: how few steps it takes to reach everyone else.
  • Eigenvector and PageRankPageRankShare of time a random walker spends at a node, following edges or jumping anywhere; sums to 1 over all nodes.: a node matters when its neighbors matter.

Check yourself

A member has only four friends but the highest betweenness in the club. What's the most likely reason?

Show the answer

Answer: b

Betweenness counts shortest paths through a node, in steps, not weights. A broker between two groups can have few ties and still hold the network together.

06

Blocks and hubs

Explore
Adjacency matrixWhich nodes link to which, and do groups form blocks of dense ties?
View data
fromtomessagespersondepartment
045Fin-1Finance
057Fin-2Finance
076Fin-3Finance
0115Fin-4Finance
0206Fin-5Finance
138Fin-6Finance
141Fin-7Finance
157Fin-8Finance
1139Ope-1Operations
233Ope-2Operations
243Ope-3Operations
263Ope-4Operations
276Ope-5Operations
2151Ope-6Operations
357Ope-7Operations
452Ope-8Operations
4124Res-1Research
4175Res-2Research
4216Res-3Research
574Res-4Research
684Res-5Research
7117Res-6Research
7159Res-7Research
8111Res-8Research
8128——
8137——
8141——
9118——
9123——
9146——
10141——
11159——
13159——
14153——
16201——
17193——
17226——
17232——
18193——
18205——
18212——
18224——
18239——
19234——
20221——
21226——
22232——

Sorted by group, tightly knit groups show as dark blocks on the diagonal. Ties between groups sit off it.

Degree distribution (CCDF)Do a few nodes hold most of the ties (a heavy tail), or are degrees much alike?
View data
degree kshare of nodes with degree ≥ kdegree
10.8600In-degree
20.6450In-degree
30.5175In-degree
40.4300In-degree
50.3525In-degree
60.3000In-degree
70.2625In-degree
80.2225In-degree
90.2050In-degree
100.1800In-degree
110.1575In-degree
120.1400In-degree
130.1200In-degree
140.1025In-degree
150.0975In-degree
160.0900In-degree
170.0850In-degree
180.0750In-degree
190.0700In-degree
200.0650In-degree
210.0550In-degree
230.0475In-degree
250.0450In-degree
260.0425In-degree
270.0350In-degree
280.0325In-degree
290.0275In-degree
310.0250In-degree
340.0225In-degree
360.0200In-degree
380.0175In-degree
430.0150In-degree
640.0125In-degree
650.0075In-degree
670.0050In-degree
700.0025In-degree
10.9500Out-degree
20.9025Out-degree
30.7675Out-degree
40.5875Out-degree
50.3700Out-degree
60.2125Out-degree
70.1100Out-degree
80.0425Out-degree
90.0125Out-degree

The degree curve shows the share of nodes with at least k ties. On log–log axes a long, slowly falling tail means a few hubs hold many ties.

07

Checks and node tables

Checkpoint

A test network of three teams has a self-loop, a repeated edge, a row with no target, and a node table that misses one person and adds one with no ties. The card's Network checks table counts each, and the warnings say what was done: 1 isolated node, 1 self-loop left out, 1 repeated edge merged.

Check yourself

Why does the app save node results as a new dataset instead of adding them as columns to the edge list?

Show the answer

Answer: b

Node measures belong to nodes. Save node table as dataset keeps one row per node, ready to join to the node table or chart.

08

Do it on your own data

In the app

Open Discover → Networks and choose a dataset with one row per tie. When two columns are named like an edge list (From and To, source and target, sender and receiver), the method opens with them bound. Add a node table under Node table in the setup.

Python
from codesplash import graph as cg
from codesplash.graph import describe as gd

g = cg.read("out")                     # the app writes out/graph/ next to the run
print(gd.density(g), gd.clustering(g)["transitivity"], gd.assortativity(g))
print(gd.pagerank(g, 0.85)["x"][:5])   # one value per node, in g.node_id order
R
library(codesplashr)
g <- cs_graph_read("out")
c(cs_graph_density(g), cs_graph_clustering(g)$transitivity, cs_graph_assortativity(g))
head(cs_graph_pagerank(g, 0.85)$x)
09

Recap

Recap
  • An edge list has one row per tie; the app checks it once and both engines read the same network.
  • Density, separate parts, clustering and assortativity describe the whole network; centralities rank the nodes.
  • Betweenness and closeness count steps; eigenvector centrality and PageRank can use weights.
  • Node results become a dataset of their own, never columns of the edge list.

Concepts in this lesson