utils (module)

Utility helpers exposed by gradnet.utils. This page lists all public functions automatically from the module, so newly added public functions appear in the docs without manual edits.

gradnet.utils.random_seed(seed)[source]

Set random seed for reproducibility. Works with torch, numpy, and random.

gradnet.utils.laplacian(A)[source]

Compute the graph Laplacian from the adjacency matrix.

gradnet.utils.prune_edges(del_adj, *, threshold=None, target_edge_number=None, renorm=True)[source]

Prune edges in an adjacency-like tensor.

Use either a numeric threshold (keeps entries with abs(x) >= threshold) or specify target_edge_number to automatically determine a threshold that yields exactly that many unpruned entries. Exactly one of these must be provided.

If renorm is True, rescales the pruned tensor to match the original L1 norm. If all entries are pruned, returns an all-zero tensor.

gradnet.utils.to_networkx(gn, pruning_threshold=1e-08)[source]

Export the current adjacency to a NetworkX graph.

Edges with absolute weight below pruning_threshold are dropped. Supports both dense and sparse internal representations.

Parameters:

pruning_threshold (float) – Minimum absolute weight to keep an edge.

Returns:

A networkx.DiGraph if directed else a Graph.

Return type:

networkx.Graph | networkx.DiGraph

gradnet.utils.plot_adjacency_heatmap(gn, *, ax=None, title=None, xlabel='$j$', ylabel='$i$', cbar_label='$A_{ij}$', add_colorbar=True, cbar_kwargs=None, imshow_kwargs=None, plt_show=False)[source]

Plot an adjacency matrix as a heatmap.

  • If ax is None, creates a new figure and axes.

  • The colorbar attaches to ax.figure unless add_colorbar=False.

  • Accepts a GradNet-like object (callable with no args), a Torch tensor, or any array-like representing an adjacency.

gradnet.utils.plot_graph(gn, *, ax=None, pruning_threshold=1e-08, layout='spring', node_size=15.0, edgecolors='black', edge_width_scaling=1.0, draw_kwargs=None, add_colorbar=False, colorbar_label=None, plt_show=False)[source]

Draw the NetworkX representation of gn.

  • If ax is None, creates a new figure and axes.

  • Uses to_networkx and derives edge widths from weights.

  • layout can be a networkx.draw_* name or a callable.

  • If add_colorbar=True, adds a colorbar when node_color is array-like.

gradnet.utils.load_scalars(log_dir)[source]

Return shared steps and a dict of scalar series from Lightning logs.

The log_dir can be either a specific version directory (e.g., lightning_logs/gradnet/version_3) or the parent folder that contains multiple version_* subdirectories (e.g., lightning_logs/gradnet). This function prefers CSV logs when present and falls back to TensorBoard event files if available.

Returns (steps, series) where steps is a single list of integers (epoch/step) shared by all metrics, and series is a mapping {name: values} with values aligned to steps. Missing values are filled with nan.

Usage:
>>> steps, series = load_scalars('lightning_logs/gradnet')
>>> loss = series['loss']
Parameters:

log_dir – Path to a logger directory or its parent.

Returns:

tuple[list[int], dict[str, list[float]]]

gradnet.utils.animate_adjacency(checkpoints, *, output_path=None, fps=30, dpi=100, figsize=None, title_template='Checkpoint {index}: {name}', imshow_kwargs=None)[source]

Animate adjacency heatmaps for GradNet checkpoints named gn-periodic-*.ckpt.

gradnet.utils.positions_to_distance_matrix(positions, norm=2.0)[source]

Compute the pairwise distance matrix from node positions using a given norm.

gradnet.utils.regularization_loss(del_adj)[source]

Regularization loss for sparsifying the delta adjacency. Computes sum(log(abs(del_adj) + 1)) / N, where N is the last dimension size.