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 name attributes 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:

dict

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:

dict[int, (float, float, str)]

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:

list[str]

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:

str

point_in_polygon(x, y, polygon)

Ray casting algorithm for testing if a point is inside a polygon.

Parameters:
  • x (float) – X coordinate (longitude).

  • y (float) – Y coordinate (latitude).

  • polygon (list[tuple[float, float]]) – Polygon vertices as (lon, lat) tuples.

Returns:

True if the point lies inside the polygon, False otherwise.

Return type:

bool

polygon_to_path(coords)

Convert an iterable of polygon coordinates into an SVG path string.

Parameters:

coords (iterable[tuple[float, float]]) – Polygon coordinates as (lon, lat) tuples.

Returns:

SVG path string.

Return type:

str

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:

networkx.Graph

svg_path_to_coordinates(svg_path)

Parse an SVG path string and return a list of coordinates as (lon, lat) tuples.

Parameters:

svg_path (str) – SVG path data string.

Returns:

Sequence of (lon, lat) coordinates. The Y axis is inverted to map SVG screen coordinates to geographic latitude.

Return type:

list[tuple[float, float]]

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

Float that pretty-prints with two decimal places for JSON dumps.

class TopoGenerator

Bases: object

Base class for topology generators.

Subclasses should implement generate_topo to return a NetworkX node-link format dictionary. Node positions are expected in pos as (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:

dict

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_topo and 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 pos as (lon, lat) tuples.

main(topo_names)

CLI entry point to generate and save multiple topology sets.

Parameters:

topo_names (list[str]) – A list whose first element selects the provider/group, e.g., ‘gabriel’, ‘sndlib’, ‘topozoo’, ‘backbone’, ‘caida’. Remaining behavior is specialized per provider in this function body.

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:

dict[(object, object), list]

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:

dict[(object, object), list]

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:

dict[object, set], dict[object, int]

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:

dict[object, list], dict[object, int]

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.

Parameters:

list_of_values (list[float]) – List of values.

Returns:

Calculated Gini coefficient.

Return type:

float

haversine(src, dst)

Calculate the great-circle distance between two points on a sphere given their longitudes and latitudes.

Parameters:
  • src ((float, float)) – coordinates (lon0, lat0)

  • dst ((float, float)) – coordinates (lon1, lat1)

Returns:

Distance in kilometers.

Return type:

float

minmax(pos)

Find min and max in node positions dictionary.

Parameters:

pos (dict) – Node positions dictionary.

Returns:

Found max_x, max_y, min_x, min_y positions.

Return type:

(float, float, float, float)

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.

Parameters:
  • stats (dict) – Dictionary of path statistics between (src, dst) node pairs.

  • filename (str | None, default None) – Output file path without extension. If None, prints to stdout.

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:

dict[(object, object), list]

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:

dict[(object, object), list]

topo_stats(g, ps=None)

Calculate topology properties statistics.

Parameters:
  • g (networkx.Graph) – Network graph.

  • ps (dict | None, default None) – Dictionary of path statistics between (src, dst) node pairs.

Returns:

Dictionary of topology properties.

Return type:

dict[str, int | float]

topo_stats_print(stats, name, filename=None)

Print topology statistics in a LaTeX format.

Parameters:
  • stats (dict) – Dictionary of topology properties.

  • name (str) – Topology name.

  • filename (str | None, default None) – Output file path without extension. If None, prints to stdout.

write_gml(g, path)

Write a NetworkX graph to a GML format file.

Parameters:

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

Topology that adds b bridges per switch, each with k hosts.

Parameters:
  • b (int, default 1) – Number of bridges to attach to each switch.

  • k (int, default 1) – Number of hosts to attach to each bridge.

build(b=1, k=1, **params)

Attach b bridges per switch and k hosts per bridge.

class AutoHostTopo(*args: Any, **kwargs: Any)

Bases: Topo

Topology that adds k hosts per switch.

Parameters:

k (int, default 1) – Number of hosts to attach to each switch.

build(k=1, **params)

Attach k hosts to every switch in the topology.

class Demands

Bases: dict

Dictionary 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:
  • k (tuple[str, str]) – Pair (src, dst) of node identifiers.

  • default (float, default 0.0) – Default demand if the pair is not present.

  • sym (bool, default False) – If True, return demand for (dst, src) when (src, dst) is missing.

  • norm (bool, default False) – If True, normalize the returned demand by the maximum demand value to [0.0, 1.0].

Returns:

Demand value between the pair of nodes.

Return type:

float

property maximum

Maximum demand value in the dictionary.

Returns:

Maximum demand value, or 0.0 if the dictionary is empty.

Return type:

float

class JSONTopo(*args: Any, **kwargs: Any)

Bases: Topo

Mininet Topo built from a NetworkX node-link dictionary.

Expects topo_json class attribute to be set to a node-link dictionary with keys: graph, nodes, and edges.

build(*args, **params)

Build the topology using the topo_json node-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 TopoClsDict

Bases: dict

Lazy map from repository keys to generated Mininet Topo classes.

class TopoNamedClsDict

Bases: dict

Lazy map from repository keys to Mininet Topo classes using node names.

make_topo_class_from_json(name, topo)

Dynamically construct a Mininet Topo subclass from a node-link dictionary.

Parameters:
  • name (str) – Topology key or descriptive name.

  • topo (dict) – NetworkX node-link dictionary.

Returns:

A Topo subclass with name and topo_json attributes set.

Return type:

type