topohub
TopoHub Python package.
This package provides access to a repository of real-world and synthetic network topologies in NetworkX node-link format. Unless otherwise noted, node positions are stored as (longitude, latitude) tuples.
- get(key, use_names=False)
Load a topology from the embedded repository as a node-link dictionary.
- Parameters:
key (str) – Repository key in the form “group/name” (e.g., “gabriel/25/0”, “backbone/africa”, “topozoo/Abilene”, “sndlib/polska”).
use_names (bool, default False) – If True, replace integer node IDs with their
nameattributes in the returned structure. Not supported for topologies that contain unnamed or duplicate node names (e.g., some “backbone” or “caida”).
- Returns:
NetworkX node-link dictionary with keys:
graph,nodes,edges.- Return type:
- Raises:
KeyError – If the specified topology key cannot be found/read.
Examples
import networkx as nx import topohub # Obtain topology dicts from JSON files stored in the repository topo = topohub.get('gabriel/25/0') topo = topohub.get('backbone/africa') topo = topohub.get('topozoo/Abilene') topo = topohub.get('sndlib/polska') # Create NetworkX graph from node-link dict g = nx.node_link_graph(topo, edges='edges') # Access graph parameters print(g.graph['name']) print(g.graph['demands']) print(g.graph['stats']['avg_degree']) # By default, nodes are referred by their integer IDs # You can obtain node names through the `name` attribute print(g.nodes[0]['name']) print(g.nodes[10]['name']) # Obtain link length in kilometers between node 0 and 10 print(g.edges[0, 10]['dist']) # Obtain percentage utilization of the link between node 0 and 10 under ECMP routing in the forward direction print(g.edges[0, 10]['ecmp_fwd']['uni']) # You can also load a topology using node names instead of integer IDs as node identifiers # (this will not work for 'backbone' and 'caida' topologies which have unnamed or duplicated name nodes) topo = topohub.get('sndlib/polska', use_names=True) g = nx.node_link_graph(topo, edges='edges') print(g.graph['demands']) print(g.edges['Gdansk', 'Warsaw']['dist']) print(g.edges['Gdansk', 'Warsaw']['ecmp_fwd']['uni'])
topohub.geo
Geographic helpers and region filtering for TopoHub.
This module contains utilities for working with geographic shapes and maps, including SVG path parsing, polygon tests, map background generation, and GeoPandas-based filtering of nodes by countries/continents. Unless otherwise noted, positions use the (longitude, latitude) convention.
- filter_contiguous_us(world)
Extract GeoDataFrame rows representing the contiguous United States.
- Parameters:
world (geopandas.GeoDataFrame) – World dataset with polygon geometries.
- Returns:
GeoDataFrame containing polygons for the contiguous US only.
- Return type:
geopandas.GeoDataFrame
- filter_countries(world, include_countries=None, include_continents=None, exclude_countries=None, mainland_only=False)
Build a filtered GeoDataFrame for selected continents/countries.
- Parameters:
world (geopandas.GeoDataFrame) – World dataset with polygon geometries.
include_countries (list[str] | None) – Country names to include (match ‘NAME’ column). Special case: ‘US’ adds contiguous US polygons.
include_continents (list[str] | None) – Continent names to include (match ‘CONTINENT’ column). Special case: ‘EU’ adds mainland Europe.
exclude_countries (list[str] | None) – Country names to exclude.
mainland_only (bool, default False) – Reduce each country’s geometry to its mainland (the largest polygon).
- Returns:
Filtered set of polygons.
- Return type:
geopandas.GeoDataFrame
- filter_mainland_europe(world)
Extract mainland Europe polygons from the world dataset using a bounding box.
- Parameters:
world (geopandas.GeoDataFrame) – World dataset with polygon geometries.
- Returns:
GeoDataFrame containing mainland Europe polygons.
- Return type:
geopandas.GeoDataFrame
- filter_nodes_by_geo(nodes, include_countries=None, include_continents=None, exclude_countries=None, mainland_only=False)
Filter node ids by country/continent membership using GeoPandas names.
- Parameters:
nodes (dict[int, (float, float, str)]) – Mapping of node id to (lon, lat, city) floats for nodes to consider.
include_countries (list[str] | None) – List of country names to include (values must match the ‘NAME’ column in the world dataset).
include_continents (list[str] | None) – List of continent names to include (values must match the ‘CONTINENT’ column or special aliases like ‘EU’).
exclude_countries (list[str] | None) – List of country names to exclude.
mainland_only (bool, default False) – If True, restrict each country’s geometry to its mainland (largest polygon). Special-case for the US uses contiguous US polygons.
- Returns:
A shallow copy of the mapping limited to nodes located within the selected geographic regions.
- Return type:
- generate_map(include_continents=None, include_countries=None, exclude_countries=None, mainland_only=False, **kwargs)
Generate SVG path elements for map backgrounds of the selected regions.
- Parameters:
include_countries (list[str] | None) – Country names to include.
include_continents (list[str] | None) – Continent names to include.
exclude_countries (list[str] | None) – Country names to exclude.
mainland_only (bool, default False) – If True, reduce countries to their mainland polygons.
**kwargs (dict) – Additional options reserved for future use (currently unused).
- Returns:
SVG <path> element strings.
- Return type:
- geometry_to_path(geometry)
Convert a shapely geometry (Polygon or MultiPolygon) to an SVG path string.
- Parameters:
geometry (shapely.geometry.base.BaseGeometry) – Geometry to convert.
- Returns:
SVG path string.
- Return type:
- point_in_polygon(x, y, polygon)
Ray casting algorithm for testing if a point is inside a polygon.
- polygon_to_path(coords)
Convert an iterable of polygon coordinates into an SVG path string.
- remove_dead_ends(g)
Iterate and remove leaf nodes that are marked as seacable waypoints or have no edges.
- Parameters:
g (networkx.Graph) – Input graph.
- Returns:
Graph with selected dead-end nodes and incident edges removed.
- Return type:
- svg_path_to_coordinates(svg_path)
Parse an SVG path string and return a list of coordinates as (lon, lat) tuples.
topohub.generate
Topo generation CLI and helpers for TopoHub.
This module orchestrates generation and saving of topologies using provider generators. Unless otherwise noted, node positions are stored as (longitude, latitude) tuples.
- class RoundingFloat(x=0, /)
Bases:
floatFloat that pretty-prints with two decimal places for JSON dumps.
- class TopoGenerator
Bases:
objectBase class for topology generators.
Subclasses should implement
generate_topoto return a NetworkX node-link format dictionary. Node positions are expected inposas (lon, lat) tuples.- classmethod generate_topo(*args, **kwargs) dict
Generate a topology.
This base implementation returns an empty node-link structure and should be overridden by subclasses.
- Returns:
A dictionary compatible with
networkx.node_link_graph.- Return type:
- classmethod save_topo(*args, **kwargs) None
Generate, post-process, and save a topology to files.
- Parameters:
*args (tuple) – Positional arguments forwarded to
generate_topo.**kwargs (dict) – Keyword arguments forwarded to
generate_topoand processing flags.filename (str, optional (keyword-only)) – Basename of output files (without extension). Defaults to
mininet/topo_lib/<graph name>.with_plot (bool, optional) – If True, save an SVG rendering of the graph.
with_utilization (bool, optional) – If True, compute ECMP utilizations.
with_path_stats (bool, optional) – If True, compute disjoint path statistics.
with_topo_stats (bool, optional) – If True, compute and embed topology statistics in graph attributes.
scale (bool | float | None, optional) – Forwarded to
topohub.graph.save_topo_graph_svg.background (list[str] | None, optional) – SVG elements for background (e.g., map paths).
Notes
Nodes are expected to contain
posas (lon, lat) tuples.
topohub.graph
Graph utilities for TopoHub.
This module provides geographic distance functions, path computations, plotting (SVG/PDF), topology statistics, and GML export helpers. Coordinates for geographic functions follow the (longitude, latitude) convention.
- all_disjoint_paths(g, ff, node_filter=None)
Find all disjoint paths between all node pairs in a graph.
- Parameters:
g (networkx.Graph) – Network graph.
ff (callable) – Callable for computing the maximum flow among a pair of nodes.
node_filter (callable | None, default None) – Predicate on a node attribute dict; only nodes where predicate returns True are considered.
- Returns:
Dictionary of lists of disjoint paths between (src, dst) node pairs.
- Return type:
- all_disjoint_paths_scipy(g, ff)
Find all disjoint paths between all node pairs in a graph using SciPy.
- Parameters:
g (networkx.Graph) – Network graph.
ff (callable) – Callable for computing the maximum flow among a pair of nodes.
- Returns:
Dictionary of lists of disjoint paths between (src, dst) node pairs.
- Return type:
- all_shortest_nhops_all_targets(g, source, weight=None, limit=None)
Find all next hops from a source node to all other nodes.
- Parameters:
g (networkx.Graph) – Network graph.
source (object) – Source node.
weight (str | callable, default None) – Name of edge attribute or a callable returning edge weight.
limit (int, default None) – Limit the number of shortest paths to find.
- Returns:
Next hops and distances from the source node to all other nodes.
- Return type:
- all_shortest_paths_all_targets(g, source, weight=None, limit=None)
Find all shortest paths from a source node to all other nodes.
- Parameters:
g (networkx.Graph) – Network graph.
source (object) – Source node.
weight (str | callable, default None) – Name of edge attribute or a callable returning edge weight.
limit (int, default None) – Limit the number of shortest paths to find.
- Returns:
Paths and distances from the source node to all other nodes.
- Return type:
- calculate_utilization(g, node_filter=None)
Calculate link utilizations for ECMP shortest path routing and save them as edges properties.
- Parameters:
g (networkx.Graph) – Network graph.
node_filter (callable | None, default None) – Predicate on a node attribute dict; only nodes where predicate returns True are considered in uniform/degree demand modes.
- gini(list_of_values)
Calculate the Gini coefficient of a given list of values.
- haversine(src, dst)
Calculate the great-circle distance between two points on a sphere given their longitudes and latitudes.
- minmax(pos)
Find min and max in node positions dictionary.
- path_stats(g, node_filter=None)
Calculate statistics for paths between all node pairs.
- Parameters:
g (networkx.Graph) – Network graph.
node_filter (callable | None, default None) – Predicate on a node attribute dict; only nodes where predicate returns True are considered in demand generation and filtering.
- Returns:
Dictionary mapping (src, dst) to tuples: (adp_number, sdp_number, avg_adp_hops, avg_sdp_hops, avg_adp_length, avg_sdp_length, demand, src, dst).
- Return type:
dict[(object, object), (int, int, float, int, float, float, float, object, object)]
- path_stats_print(stats, filename=None)
Print statistics for paths between all node pairs in the CSV format.
- save_topo_graph_pdf(g, filename=None, plot_aspect=1.0)
Generate and save a topology graph as a PDF file using matplotlib.
- Parameters:
g (networkx.Graph) – Network graph.
filename (str | None, default None) – Output file path without extension. If None, defaults to ‘mininet/topo_lib/<graph name>’.
plot_aspect (float, default 1.0) – Plot aspect ratio.
- save_topo_graph_svg(g, filename=None, scale=None, background=None)
Generate and save a topology graph as an SVG file.
- Parameters:
g (networkx.Graph) – Network graph.
filename (str | None, default None) – Output file path without extension. If None, defaults to ‘mininet/topo_lib/<graph name>’.
scale (bool | float | None, default None) – If None or falsy, uses a scale factor of 1. If True, scales relative to the topology diameter (max span) divided by 250. If a number, uses that value as the scale factor directly.
background (list[str] | None, default None) – Optional list of SVG elements (e.g., path strings) to embed before the graph elements (useful for map backgrounds).
- shortest_disjoint_paths(g, ff, node_filter=None)
Find all shortest disjoint paths between all node pairs in a graph.
- Parameters:
g (networkx.Graph) – Network graph.
ff (callable) – Callable for computing the maximum flow among a pair of nodes.
node_filter (callable | None, default None) – Predicate on a node attribute dict; only nodes where predicate returns True are considered.
- Returns:
Dictionary of lists of disjoint paths between (src, dst) node pairs.
- Return type:
- shortest_disjoint_paths_slow(g)
Find all shortest disjoint paths between all node pairs in a graph.
- Parameters:
g (networkx.Graph) – Network graph.
- Returns:
Dictionary of lists of disjoint paths between (src, dst) node pairs.
- Return type:
- topo_stats(g, ps=None)
Calculate topology properties statistics.
- topo_stats_print(stats, name, filename=None)
Print topology statistics in a LaTeX format.
- write_gml(g, path)
Write a NetworkX graph to a GML format file.
- Parameters:
g (networkx.Graph) – Input NetworkX graph.
path (str) – Output file path.
topohub.mininet
Mininet helpers for TopoHub.
This module exposes utilities to obtain Mininet Topo classes directly
from TopoHub’s embedded repository. It also provides convenience topologies
that automatically attach hosts/bridges to each switch.
Notes
Topologies are loaded from node-link dictionaries returned by
topohub.get.Coordinates in the repository follow the (longitude, latitude) convention.
- class AutoHostBridgeTopo(*args: Any, **kwargs: Any)
Bases:
TopoTopology that adds
bbridges per switch, each withkhosts.- Parameters:
- build(b=1, k=1, **params)
Attach
bbridges per switch andkhosts per bridge.
- class AutoHostTopo(*args: Any, **kwargs: Any)
Bases:
TopoTopology that adds
khosts per switch.- Parameters:
k (int, default 1) – Number of hosts to attach to each switch.
- build(k=1, **params)
Attach
khosts to every switch in the topology.
- class Demands
Bases:
dictDictionary of traffic demands between node pairs with convenience helpers.
- get(k, default=0.0, sym=False, norm=False)
Return the demand value for (src, dst) node pair if specified in the dictionary, else default.
- Parameters:
- Returns:
Demand value between the pair of nodes.
- Return type:
- class JSONTopo(*args: Any, **kwargs: Any)
Bases:
TopoMininet Topo built from a NetworkX node-link dictionary.
Expects
topo_jsonclass attribute to be set to a node-link dictionary with keys:graph,nodes, andedges.- build(*args, **params)
Build the topology using the
topo_jsonnode-link dictionary.
- TOPO_CLS = {}
Use this dictionary to obtain topologies from the repository as Mininet Topo classes.
Example:
import mininet.net import topohub.mininet # Obtain Mininet Topo classes for topologies stored in the repository topo_cls = topohub.mininet.TOPO_CLS['gabriel/25/0'] topo_cls = topohub.mininet.TOPO_CLS['backbone/africa'] topo_cls = topohub.mininet.TOPO_CLS['topozoo/Abilene'] topo_cls = topohub.mininet.TOPO_CLS['sndlib/polska'] # Initialize Mininet Topo object topo = topo_cls() # Create Mininet Network using the selected topology net = mininet.net.Mininet(topo=topo) # Start the network and Mininet shell net.interact()
- TOPO_NAMED_CLS = {}
Use this dictionary to obtain topologies from the repository as Mininet Topo classes, using node names instead integer IDs as node identifiers.
(this will not work for ‘backbone’ category topologies which have unnamed or duplicated name nodes)
Example:
import mininet.net import topohub.mininet # Obtain Mininet Topo classes for topologies stored in the repository topo_cls = topohub.mininet.TOPO_NAMED_CLS['gabriel/25/0'] topo_cls = topohub.mininet.TOPO_NAMED_CLS['topozoo/Abilene'] topo_cls = topohub.mininet.TOPO_NAMED_CLS['sndlib/polska'] # Initialize Mininet Topo object topo = topo_cls() # Create Mininet Network using the selected topology net = mininet.net.Mininet(topo=topo) # Start the network and Mininet shell net.interact()
- class TopoNamedClsDict
Bases:
dictLazy map from repository keys to Mininet Topo classes using node names.
- make_topo_class_from_json(name, topo)
Dynamically construct a Mininet
Toposubclass from a node-link dictionary.