๐ Quickstartยถ
Common tasks and minimal examples. Copy and run.
Tasksยถ
Create and query: ๐งฉ Core
Load and save: ๐พ Read & Write
Measures: ๐ Measures
Projections: ๐ Representations
Matrices: ๐งฎ Linear Algebra
Core classesยถ
hypergraphx.Hypergraph(undirected)hypergraphx.DirectedHypergraphhypergraphx.TemporalHypergraphhypergraphx.MultiplexHypergraph
Create a hypergraphยถ
import hypergraphx as hgx
hg = hgx.Hypergraph(edge_list=[(0, 1, 2), (2, 3)], weighted=True, weights=[1.0, 2.0])
hg.add_edge((3, 4), weight=1.5, metadata={"kind": "tri"})
print(hg)
Note
Hypergraphs are weighted by default. If you want an unweighted hypergraph, pass
weighted=False (unweighted graphs only accept weight=None or weight=1).
Directed / temporal / multiplexยถ
dh = hgx.DirectedHypergraph(edge_list=[((0, 1), (2,)), ((2,), (3,))])
th = hgx.TemporalHypergraph(edge_list=[(0, (0, 1)), (1, (1, 2))])
mx = hgx.MultiplexHypergraph(edge_list=[(0, 1), (1, 2)], edge_layer=["L1", "L2"])
# Directed in/out degrees
dh.in_degree(2)
dh.out_degree(2)
Common queriesยถ
hg.num_nodes()
hg.num_edges()
hg.get_edges()
hg.get_incident_edges(2)
hg.degree(2)
hg.get_edge_metadata((0, 1, 2))
Tip
For a smaller API surface, start with hypergraphx.core and hypergraphx.readwrite.
Common patternsยถ
# Build -> analyze -> save
hg = hgx.Hypergraph(edge_list=[(0, 1), (1, 2, 3)])
seq = degree_sequence(hg)
hgx.save_hypergraph(hg, "graph.json")
Conversionsยถ
# Drop direction, time, or layer information
dh = hgx.DirectedHypergraph(edge_list=[((0, 1), (2,))], weighted=True, weights=[2.0])
th = hgx.TemporalHypergraph(edge_list=[(0, (0, 1)), (1, (0, 1))], weighted=True, weights=[1.0, 2.0])
mx = hgx.MultiplexHypergraph(edge_list=[(0, 1), (0, 1)], edge_layer=["L1", "L2"], weighted=True, weights=[1.0, 2.0])
dh.to_hypergraph() # merges source/target, sums weights
th.to_hypergraph() # drops time, sums weights
mx.to_hypergraph() # drops layer, sums weights
Load and saveยถ
hgx.save_hypergraph(hg, "graph.json")
hg2 = hgx.load_hypergraph("graph.json")
# Prefer the compact HGX format for larger local files.
hgx.save_hypergraph(hg, "graph.hgx", fmt="pickle")
hg3 = hgx.load_hypergraph("graph.hgx")
Remote datasetsยถ
Hypergraphx can load datasets from the Hypergraphx-data catalog by name.
Remote datasets are downloaded and cached locally by default under
~/.cache/hypergraphx/datasets; set store=False to load without keeping
a local copy, or pass cache_dir=... to choose a different cache location.
import hypergraphx as hgx
# List catalog entries with tags/categories and basic sizes.
datasets = hgx.list_remote_datasets()
print(datasets[0]["name"], datasets[0]["tags"])
# Search without downloading hypergraphs.
biology = hgx.search_remote_datasets(
query="biology",
tags=["Undirected"],
)
# Inspect the full catalog metadata for one dataset.
info = hgx.get_remote_dataset_info("zoo")
print(info["description"], info["license"])
# Download and cache a dataset file without loading it.
path = hgx.download_remote_dataset("zoo")
H = hgx.load_hypergraph(path)
# Download multiple datasets and inspect per-dataset results.
results = hgx.download_remote_datasets(
["zoo", "contacts-hospital"],
continue_on_error=True,
)
for name, result in results.items():
print(name, result["status"], result["path"], result["error"])
# Load a dataset by name. The compact ``"hgx"`` format is the default.
H = hgx.load_hypergraph_from_server("zoo")
# Override the cache directory or force a fresh download.
H = hgx.load_hypergraph_from_server(
"zoo",
cache_dir="./hgx_datasets",
overwrite=True,
)
# Iterate lazily over matching remote datasets.
for H, info in hgx.iter_remote_hypergraphs(
["Undirected", "Temporal"],
include_metadata=True,
):
print(info["name"], H.num_nodes(), H.num_edges())
# Or iterate over an explicit list of dataset names.
for H in hgx.iter_remote_hypergraphs(names=["zoo", "Marvel"]):
print(H.num_nodes(), H.num_edges())
Note
The current dataset server may require verify_ssl=False because of its
certificate chain. This is the default for the remote dataset helpers. If the
server certificate is fixed, pass verify_ssl=True to enforce normal TLS
verification.
Projections and matricesยถ
from hypergraphx.linalg import adjacency_matrix
from hypergraphx.representations.projections import clique_projection
A = adjacency_matrix(hg)
G = clique_projection(hg)
Random generationยถ
Use random_hypergraph to sample a simple random hypergraph with exact
unique-edge counts by size. Requests that exceed the number of possible
combinations are rejected.
from hypergraphx.generation import random_hypergraph
hg_sample = random_hypergraph(10, {2: 20, 3: 10}, seed=0)
For dense requests, random_hypergraph switches from rejection sampling to
direct combination sampling to avoid slowdown near saturation. Tune this with
dense_threshold and max_tries_factor if needed.
Use configuration_model to randomize a hypergraph with a
configuration-model-style MCMC sampler.
from hypergraphx.generation import configuration_model
hg_rand = configuration_model(hg, n_steps=500, label="edge", seed=0)
The duplicate_output parameter controls how repeated sampled hyperedges are
handled:
"merge"(default): collapse duplicates into a simple hypergraph"count": return a weighted hypergraph whose edge weights equal sampled multiplicities"error": raise an error if repeated sampled hyperedges occur
hg_rand = configuration_model(hg, n_steps=500, duplicate_output="merge", seed=0)
hg_counts = configuration_model(hg, n_steps=500, duplicate_output="count", seed=0)
Measuresยถ
from hypergraphx.measures.degree import degree_sequence
from hypergraphx.measures.shortest_paths import calc_ho_shortest_paths
seq = degree_sequence(hg)
paths = calc_ho_shortest_paths(hg)
API mapยถ
Core classes:
hypergraphx.coreRead/write:
hypergraphx.readwriteMeasures:
hypergraphx.measuresRepresentations:
hypergraphx.representationsLinear algebra:
hypergraphx.linalgFilters:
hypergraphx.filtersMotifs:
hypergraphx.motifsDynamics:
hypergraphx.dynamicsCommunities:
hypergraphx.communitiesUtils:
hypergraphx.utils
Exceptionsยถ
All custom exceptions inherit from HypergraphxError. Most also inherit from
ValueError (ReadwriteError inherits from RuntimeError).
from hypergraphx import MissingNodeError
try:
hg.get_incident_edges("missing")
except MissingNodeError:
pass
Logging (optional)ยถ
Hypergraphx uses the standard logging module. To see info-level logs:
import logging
logging.basicConfig(level=logging.INFO)