Hypergraph Analysis and Visualization in PythonThe hatvis toolbox

Chapter 2
Representations and interchange

A hypergraph can be stored, drawn, and computed with in many forms: as an incidence matrix, as a bipartite graph, as a graph of co-occurring vertices, as a graph of overlapping hyperedges, as a tensor, or as a file in one of several exchange formats. This chapter defines these representations in one notation, states which of them are lossless and what the others forget, introduces the variants of the basic model (weighted, fuzzy, directed, and temporal hypergraphs), and describes how hatvis reads, writes, and converts all of them. Every later chapter names the representation it works on, so this chapter is the reference for the rest of the book.

2.1 Problem and idea

The same family of groups admits very different encodings, and each encoding makes some questions easy and others impossible. The incidence matrix answers “which groups contain this vertex” with a row lookup and supports seriation, biclustering, and every linear-algebraic method; the bipartite graph makes a hypergraph accessible to graph drawing and to partitioning software; the graph of co-occurring vertices makes spectral clustering and diffusion straightforward; the graph of overlapping groups lets one walk from group to group; the adjacency tensor keeps every group as a single multilinear term. Figure 2.1 shows several of them for the small example of section 1.6.

The difficulty is that some of these encodings are not invertible. Two hypergraphs with the same clique expansion are indistinguishable to any method that uses only that expansion (fig. 1.1); two vertices with the same memberships are indistinguishable to any method that uses only the incidences; the line graph forgets which vertices produced an overlap. The idea of this chapter is to keep a single lossless object, the incidence matrix with its attributes, to compute every other representation from it on demand, and to state for each representation exactly what it forgets. A method whose answer differs between two hypergraphs that share a representation cannot be computed from that representation, and a method that uses a lossy representation must be read with its loss in mind.

Figure 2.1

Figure 2.1. Representations of the same hypergraph. The drawing (a), the incidence matrix (b), and the star expansion (c) are lossless: each can be converted into the others. The clique expansion (d) records only which pairs of vertices meet, with the number of shared hyperedges as weight (v1v2 meet twice); the line graph (e) records only which hyperedges overlap and by how much. Raising the overlap threshold to s = 2 (f) keeps only the pair e1e2, which share v1 and v2.

2.2 Theory

2.2.1 Hypergraphs and their variants

A hypergraph H = (V,E) consists of a finite vertex set V = {v1,…,vn} and a family E = (e1,…,em) of subsets of V , the hyperedges [16]. The word family matters: the same subset may occur more than once (a multi-hypergraph), and hyperedges may be empty. The size of a hyperedge is |e|, the degree of a vertex is the number of hyperedges that contain it, the rank and co-rank of H are the largest and smallest hyperedge sizes, and H is k-uniform when all hyperedges have size k; a graph is a 2-uniform hypergraph. A hypergraph is simple (a clutter, or Sperner family) when no hyperedge is contained in another; the maximal hyperedges of any hypergraph, its toplexes, form a simple hypergraph.

The incidence matrix B ∈ ℝn×m has bie = 1 if vi ∈e and 0 otherwise. Everything else can be added to this matrix without changing its shape:

Three further variants are needed in the applications. A directed hypergraph [33, 34] has hyperarcs e = (T(e),H(e)) with a tail set and a head set; it represents AND-type dependencies, such as an assembly step that needs all its inputs, a chemical reaction, a Horn clause, or an association rule X ⇒Y . It is stored as two incidence matrices Btail,Bhead of the same shape. A temporal hypergraph attaches a time stamp te to every hyperedge; its snapshots Ht = (V,{e : te = t}) and windows H[t0,t1) are ordinary hypergraphs (chapter 12). Finally the dual hypergraph H∗ exchanges the roles of vertices and hyperedges: its incidence matrix is BT, so the hyperedge of H∗ belonging to vi is the set of hyperedges of H that contain vi, and (H∗)∗ = H. The dual is lossless; every vertex-level method becomes a hyperedge-level method when applied to H∗, which is how hatvis computes most hyperedge centralities and similarities.

Two subhypergraphs are used constantly. The partial hypergraph on a subset F ⊆E keeps those hyperedges and all vertices; the induced subhypergraph on U ⊆V cuts every hyperedge to e ∩U. Restricting to a production line, to a time window, or to the hyperedges of one automation group are examples of the first; restricting to the resources of one cell is an example of the second.

2.2.2 Matrices derived from the incidence matrix

Two products of the incidence matrix with its transpose count overlaps:

C = BBT,c ij = |{e : vi,vj ∈e}|,K = BTB,k ef = |e ∩f|,
(2.1)

for a 0/1 matrix B. The co-occurrence matrix C has the degrees on its diagonal and the number of shared hyperedges off it; the intersection matrix K has the sizes on its diagonal and the overlaps off it. Both are the basis of the similarity measures of chapter 5, of the line graphs below, and of the pattern statistics of chapter 8.

The weighted adjacency of the clique expansion generalizes C:

aij = ∑ e∋vi,vjwec(e)(i≠j),c(e) ∈ {1, 1 |e|, 1 |e|−1 },
(2.2)

and aii = 0. With c(e) = 1 the weight counts the shared hyperedges (or sums their weights), so A = BWBT −Dv for a 0/1 incidence; with c(e) = 1∕|e| large groups contribute less per pair, the normalization underlying the Laplacian of Zhou et al. [35]; with c(e) = 1∕(|e|−1) every vertex receives exactly we in total from each of its hyperedges, so the weighted degree of the expansion equals the weighted hypergraph degree. Agarwal et al. [36] showed that many Laplacians proposed for hypergraph learning reduce to Laplacians of the clique or the star expansion with one of these weightings, which is why the choice of c(e) matters more than the name of the method.

2.2.3 Expansions and line graphs

The clique expansion (or 2-section, primal graph) [H]2 has the vertex set V and an edge between two vertices whenever they share a hyperedge, weighted by (2.2). The star expansion (incidence graph, Levi graph, or König representation) is the bipartite graph with vertex set V ∪E and an edge {vi,e} for every incidence bie≠0, weighted by bie [17]. It is lossless, and every graph algorithm that respects the bipartition (drawing in two layers, bipartite matching, bipartite community detection, minimum cuts that may separate a vertex from a hyperedge) applies to it directly.

Aksoy et al. [21] introduced a family of graphs that interpolate between “any contact” and “strong contact”. The s-line graph Ls(H) has the hyperedges of size at least s as its vertices and an edge between e and f whenever

|e ∩f|≥s,
(2.3)

with weight |e ∩f|= kef. For s = 1 it is the ordinary line graph (the intersection graph of the hyperedges); as s grows, only hyperedges with substantial overlap remain connected, and the components of Ls(H) split. The vertex version is the s-line graph of the dual: two vertices are adjacent when they share at least s hyperedges, i.e. when cij ≥s. A walk in Ls(H) is an s-walk of the hypergraph, a sequence of hyperedges in which consecutive ones share at least s vertices; distances, components, and centralities defined on s-walks are the subject of chapter 6. Figure 2.1(e) and (f) show L1 and L2 of the small example.

2.2.4 What is lost

Three kinds of loss occur.

Clique expansion. The clique expansion cannot distinguish a hyperedge from the set of all pairs inside it, nor a hyperedge from several smaller hyperedges that cover the same pairs (fig. 1.1). The cases in which it loses nothing essential are characterized by conformality. A hypergraph is conformal when every maximal clique of its clique expansion is contained in some hyperedge [16]. For a simple conformal hypergraph the maximal cliques of [H]2 are exactly the hyperedges, so H is recovered from [H]2 by listing its maximal cliques; for a conformal hypergraph that is not simple, the toplexes are recovered and the hyperedges contained in others are lost; for a non-conformal hypergraph some maximal clique of [H]2 (in fig. 1.1, the triangle {a,b,c} of the three pairs) is not a group at all, and the expansion suggests an interaction that never happened. Gilmore’s criterion gives a direct test: H is conformal if and only if for any three hyperedges e,f,g the set (e ∩f) ∪(f ∩g) ∪(e ∩g) is contained in some hyperedge [16]. hatvis tests conformality by enumerating the maximal cliques of the expansion (algorithm 2.1), which is fast for the sparse expansions met in practice.

Line graphs. The s-line graph keeps the overlaps but forgets the vertices that produced them: in fig. 2.1(e) one cannot tell which two vertices e1 and e2 share, or whether e3 meets them in the same vertex. A single line graph also forgets the hyperedges smaller than s. The family {Ls(H)}s≥1 together with the sizes carries much more information, and it is this family, not a single member, that the analysis of chapter 6 uses.

Incidences. Even the lossless incidence matrix cannot distinguish two vertices with identical rows, i.e. with the same memberships. Such vertices are equivalent: every method that is a function of B treats them identically, every similarity between them is maximal, and a similarity-based layout places them on top of each other. H.collapse_nodes() merges each class into one representative and records the class sizes, and H.collapse() merges identical hyperedges and adds their multiplicities to the weights. Both reductions are lossless for methods that take weights into account and simplify the drawings considerably.

Algorithm

2.2.5 Laplacians

Spectral methods (clustering, embedding, diffusion, consensus, label spreading) need a Laplacian, and the hypergraph literature offers several. With Dv = diag ⁡ (di) and De = diag ⁡ (|e|), hatvis provides

LZhou = I −Dv−1∕2BWD e−1BTD v−1∕2, (2.4) Lrw = I −Dv−1BWD e−1BT, (2.5) LBolla = Dv −BWDe−1BT, (2.6) Lclique = diag ⁡ (A1) −A,A from (2.2) with c(e) = 1. (2.7)

The normalized Laplacian (2.4) was introduced by Zhou, Huang, and Schölkopf [35]; (2.5) is its random-walk form, I −P with the transition matrix P of the walk that leaves a vertex through one of its hyperedges chosen with probability proportional to we and then moves to a uniformly chosen member of that hyperedge (section 6.2.4); (2.6) is the combinatorial Laplacian of Bolla [37]; and (2.7) is the Laplacian of the clique expansion weighted by the number of shared hyperedges, studied by Rodríguez [38].

All four are symmetric positive semidefinite (the random-walk form is similar to the normalized one) and have a zero eigenvalue for every connected component of the hypergraph, so the number of zero eigenvalues counts the components and the second smallest eigenvalue, the algebraic connectivity, is positive exactly when the hypergraph is connected. Their spectra nevertheless differ in a way that is worth knowing. Writing LZhou = I −XXT with X = Dv−1∕2BW1∕2De−1∕2 ∈ ℝn×m shows that its eigenvalues lie in [0,1] and that the matrix XXT has rank at most m, so at least n −m eigenvalues are exactly 1: when there are more vertices than hyperedges, a large part of the spectrum carries no structural information at all. The combinatorial Laplacians (2.6) and (2.7) have no such plateau, and their largest eigenvalues grow with the degrees. Agarwal et al. [36] discuss the equivalence of these operators with Laplacians of the expansions; Hayashi et al. [39] and Chitra and Raphael [40] generalize the random walk to edge-dependent vertex weights, and Lucas et al. [41] combine the Laplacians of the uniform layers into a multiorder Laplacian.

2.2.6 Tensors and layers

A k-uniform hypergraph is naturally a symmetric tensor of order k. The adjacency tensor of Cooper and Dutle [42] is

Ai1i2…ik = we (k −1)!if {vi1,…,vik}= e ∈E,0otherwise,
(2.8)

and the tensor–vector product

(Axk−1) i = ∑ e∋viwe ∏ vj∈e∖{vi}xj
(2.9)

is the building block of the tensor eigenvector centralities of section 6.2.5. The right-hand side of (2.9) is defined for any hypergraph, uniform or not, and hatvis evaluates it from the incidence lists without ever forming the nk entries of the tensor; the product over the other members is what makes these methods group-aware, since a vertex receives credit from a hyperedge only if all its co-members are important. HAT [18] builds its analysis on this representation, including the Laplacian tensor L = D −A, which hatvis also provides for small uniform hypergraphs.

A non-uniform hypergraph can be split into its uniform layers H(k) = (V,{e : |e|= k}), a multilayer view in which pairwise and higher-order interactions are kept apart. Its opposite is the simplicial closure, which adds every non-empty subset of every hyperedge and turns H into an abstract simplicial complex; it is exponential in the hyperedge size and is used here only to construct examples and to measure how far a hypergraph is from a simplicial complex (section 9.2.4).

In a nutshell: Representations

  • Lossless: incidence matrix B (with weights W, incidence values, and attribute tables), star expansion, dual H∗. hatvis stores B as a sparse matrix and computes every other form from it.
  • Lossy: clique expansion (recovers the toplexes only if H is conformal), s-line graphs (forget the vertices of the overlaps), any statistic of the incidences (cannot separate vertices with equal memberships).
  • Overlap counts: BBT (shared hyperedges) and BTB (shared vertices) underlie similarities, line graphs, and pattern statistics.
  • Laplacians: Zhou normalized and random walk (eigenvalues in [0,1], at least n −m equal to 1), Bolla, clique (Rodríguez); zero eigenvalues count components.
  • Tensors: adjacency tensor of uniform hypergraphs and the tensor–vector product (2.9), valid for any hypergraph.
  • Variants: multi-, weighted, fuzzy (α-cuts), directed (tail/head), temporal (snapshots, windows).

2.3 Interchange

A representation is only useful if the data can get into it. hatvis reads and writes five families of formats and converts directly to and from three Python packages; table 2.1 lists what each of them preserves.

Hypergraph Interchange Format. HIF [26] is a JSON schema agreed by maintainers of HyperNetX, XGI, Hypergraphx, HAT, and other packages. A HIF document has a list of incidences, each a record with an edge and a node identifier and optional weight, direction, and attrs; optional lists of nodes and edges carry their own weights and attributes; the field network-type distinguishes undirected and directed hypergraphs and abstract simplicial complexes. hatvis writes hyperedge weights to the edge records, incidence values to the incidence records, the attribute tables to attrs, and the tail/head sets of a directed hypergraph to the direction field, so a round trip through HIF gives back an identical object.

HyperGodot text format. HyperGodot [2] reads one hyperedge per line, the vertex labels separated by spaces, followed by optional tags such as #WEIGHT: 15 and #GROUP: H. The weight becomes the hyperedge weight; every other tag becomes a column of the hyperedge attribute table, which is how the comparative views of section 4.2.5 find their groups. Files written by hatvis open in HyperGodot unchanged.

Pattern-mining output. The SPMF library [43] writes frequent itemsets as lines 1 4 7 #SUP: 25 and association rules as 1 2 ==> 5 #SUP: 3 #CONF: 0.75. hatvis reads the first as a hypergraph whose hyperedges are the itemsets weighted by their support and the second as a directed hypergraph whose hyperarcs are the rules, so the output of any external miner can be visualized and analyzed with the methods of chapter 8.

Tables. Incidence data usually arrive as a long table with one row per membership (a person and a project, an item and a basket, a resource and an activity) or as a wide matrix in a spreadsheet. Hypergraph.from_dataframe reads the first, read_incidence_csv and read_incidence_excel the second; the house-of-quality matrix of section 5.2.6 was read from the Excel file of the HAT-VIS distribution in this way.

Python packages. The converters to_hypernetx/from_hypernetx, to_xgi/from_xgi, and to_hypergraphx/from_hypergraphx create the native objects of HyperNetX [20], XGI [22], and Hypergraphx [23] with the hyperedge weights as attributes, so a method that exists only in one of these packages can be applied to a hatvis hypergraph and its result brought back by label. The packages are optional dependencies and are imported only when a converter is called.

Table 2.1. Interchange formats and what they preserve in hatvis. “Labels” means hyperedge labels; vertex labels are preserved by all.
Format Labels Weights Incidence values Attributes Directed
HIF JSON yes yes yes yes yes
HyperGodot text generated yes no tags no
SPMF itemsets / rules generated support no confidence rules
CSV / Excel incidence yes column yes no no
HyperNetX / XGI yes yes no partly no
Hypergraphx no yes no no no

2.4 Using it in hatvis

Hypergraph(edges, *, nodes=None, weights=None, edge_labels=None, node_data=None, edge_data=None, name=None)

edges

a list of member lists (labelled e0, e1, …), a dictionary label -> members, or a dictionary label -> {vertex: value} for real-valued incidences.

nodes

vertex order; vertices listed here but in no hyperedge are kept as isolated vertices.

weights

hyperedge weights we (default 1).

node_data, edge_data

attribute tables indexed by the labels.

Constructors

Hypergraph.from_incidence(B, nodes, edges) (array, sparse matrix, or labelled data frame), Hypergraph.from_dataframe(df, node_col, edge_col, value_col), DirectedHypergraph(arcs), TemporalHypergraph(edges, times).

Access

incidence, nodes, edges, weights, members(e), memberships(v), edge_dict(), node_dict(), to_dataframe(), summary().

Transformations

dual(), restrict_nodes, restrict_edges, filter_edges(min_size, max_size, min_weight, predicate), alpha_cut(alpha), collapse(), collapse_nodes(), toplexes(), relabel, add_edges; all return new objects.

The representations of section 2.2 are plain functions of the hypergraph: clique_adjacency(H, weighting) and clique_expansion, star_expansion, line_graph(H, s) and s_line_graph(H, s, edges=False) for the vertex version, intersection_matrix, cooccurrence_matrix, laplacian(H, kind) with kind one of "normalized", "randomwalk", "bolla", "clique", adjacency_tensor, tensor_apply, uniform_layers, and simplicial_closure. The inverse direction is covered by from_cliques (maximal cliques of a graph), from_graph_edges (a graph as a 2-uniform hypergraph), and io.from_bipartite. The readers, writers, and converters of section 2.3 are in hatvis.io.

2.5 Examples

What the clique expansion forgets. The script of fig. 2.2 builds the two hypergraphs of fig. 1.1 and compares their representations.

H1 = hv.Hypergraph({"group": ["a", "b", "c"]}, name="one 3-way interaction") 
H2 = hv.Hypergraph({"ab": ["a", "b"], "bc": ["b", "c"], "ac": ["a", "c"]}, name="three pairwise interactions") 
G1, G2 = hv.clique_expansion(H1), hv.clique_expansion(H2) 
print("same clique expansion:", set(map(frozenset, G1.edges())) == set(map(frozenset, G2.edges()))) 
print("same star expansion:  ", nx.is_isomorphic(hv.star_expansion(H1), hv.star_expansion(H2))) 
print("conformal:", hv.problems.is_conformal(H1), hv.problems.is_conformal(H2))
   

The clique expansions are equal, the star expansions are not isomorphic, and the conformality test separates the two: the single group is conformal, the three pairs are not, because the maximal clique {a,b,c} of their common expansion is not contained in any of them.

Figure 2.2

Figure 2.2. What the clique expansion forgets. Top: one interaction of three vertices; bottom: three pairwise interactions. The clique expansions (middle) are identical; the star expansions (right) differ, with one hyperedge node of degree three in the first case and three of degree two in the second.

Open in ColabExample plot_02_projection_loss.py in the gallery

A production system seen through four graphs. The cyber-physical production example of HyperGodot [2] has fifteen entities (four workers, two robots, five materials, a simulation software, and three machines) and seven tasks, from the 3D design of a component to the final inspection. Figure 2.3 shows its clique expansion, star expansion, and two line graphs. The clique expansion is dense around the components C2 and C3, which take part in most tasks, and it hides which entities act together: the five members of the assembly task E5 form a 5-clique that is indistinguishable from five overlapping triangles. The star expansion shows the tasks explicitly, as square nodes, and reveals the chain from design (E1, E2) through machining and welding (E3, E4) to assembly, quality control, and inspection (E5–E7). The 1-line graph connects the tasks that share any entity. In the 2-line graph only the tasks that share at least two entities remain linked, and the process falls apart into three parts: the two design tasks E1 and E2, which share the component C1 and the simulation software; the CNC milling task E3, now isolated; and the four downstream tasks E4–E7. The three parts are connected to each other through single components only, which is exactly the kind of weak link that the s-walk analysis of chapter 6 is designed to expose.

Figure 2.3

Figure 2.3. Expansions and line graphs of the cyber-physical production example of HyperGodot: clique expansion (top left), star expansion with the seven tasks as squares (top right), 1-line graph (bottom left) and 2-line graph (bottom right) of the tasks. The edge widths of the line graphs are the overlap sizes |e ∩f|.

Open in ColabExample plot_03_expansions_and_spectra.py in the gallery

spectra = {kind: np.sort(np.linalg.eigvalsh(hv.laplacian(H, kind))) for kind in ("normalized", "bolla", "clique")} 
for kind, ev in spectra.items(): 
    print(f"{kind:>10}: zero eigenvalues = {np.sum(ev < 1e-9)}, largest = {ev[-1]:.3f}") 
print("algebraic connectivity:", round(hv.spectral.algebraic_connectivity(H), 4))
   

The three Laplacian spectra of fig. 2.4 each have exactly one zero eigenvalue, so the system is connected. The normalized Laplacian has its largest eigenvalue at 1 and a plateau of eight eigenvalues equal to 1, as predicted by the rank argument of section 2.2.5 (n −m = 15 −7 = 8); its algebraic connectivity is 0.1009. The combinatorial Laplacians have no plateau and much larger spectral radii (73.5 for Bolla’s and 314.0 for the clique Laplacian, which counts every shared task of every pair), but after normalization by the largest eigenvalue their shapes almost coincide. For clustering and embedding the normalized operator is usually preferable, because its eigenvalues are comparable across hypergraphs; for diffusion with a physical time scale the combinatorial ones are the natural choice (chapter 11).

Figure 2.4

Figure 2.4. Spectra of three Laplacians of the production example, each divided by its largest eigenvalue. The normalized Laplacian of Zhou et al. has eight eigenvalues equal to its maximum 1, because its non-trivial part has rank at most m = 7.

Interchange. The last script writes the production example to HIF and to the HyperGodot format, reads both back, and converts it to the three Python packages and back again.

io.write_hif(H, tmp / "cps.hif.json")              # shared by HyperNetX, XGI, Hypergraphx, HAT 
io.write_hypergodot(H, tmp / "cps.txt")             # "W1 C1 SW #WEIGHT: 15 #GROUP: H" 
print((tmp / "cps.txt").read_text().splitlines()[0]) 
back = io.read_hif(tmp / "cps.hif.json") 
print("HIF round trip identical:", back == H) 
print("HyperGodot round trip, same hyperedges:", io.read_hypergodot(tmp / "cps.txt").edge_sets() == H.edge_sets())
   

The HIF round trip returns an identical object, including the weights (processing times) and the task attributes; the HyperGodot file reproduces the hyperedges, weights, and groups, with the first line W1 C1 SW #WEIGHT: 15 #GROUP: H. The conversions to HyperNetX, XGI, and Hypergraphx and back return the same vertex sets. Figure 2.5 shows the degree and size distributions computed after the round trip: nine of the fifteen entities take part in a single task, and the component C3 in four; three tasks have three members, three have four, and the assembly has five.

Figure 2.5

Figure 2.5. Vertex degree (left) and hyperedge size (right) distributions of the production example after a round trip through HIF.

Open in ColabExample plot_04_interchange.py in the gallery

2.6 Further reading

Berge [16] treats conformality, the Helly property, and duality, and Bretto [17] the incidence graph and the 2-section. The s-walk framework and its line graphs are developed by Aksoy et al. [21]. Agarwal et al. [36] compare hypergraph Laplacians with those of the expansions, and Torres et al. [14] discuss the choice between graphs, hypergraphs, and simplicial complexes for a given system. Lee-Kwang and Lee [32] define fuzzy hypergraphs and their α-cuts; Gallo et al. [33] and Ausiello and Laura [34] cover directed hypergraphs. The HIF paper [26] describes the schema and its integration in the major packages.