skm_tools.serialize

Convert networks and analysis results to JSON-safe Python data (dicts and lists).

The analysis functions return networkx objects; these helpers are the separate, explicit step for when plain data is needed (JSON files, web APIs, other languages).

Functions

to_json_safe(x)

Recursively convert a value to JSON-safe Python types.

graph_to_dict(g)

A networkx graph as a JSON-safe dict.

graph_from_dict(data[, create_using])

Rebuild a networkx graph from graph_to_dict() output.

paths_to_dict(paths[, g, node_attrs, edge_attrs])

Paths as JSON-safe data, optionally with node and edge attributes.

Module Contents

skm_tools.serialize.to_json_safe(x)

Recursively convert a value to JSON-safe Python types.

dict -> dict (keys as str), list/tuple/set -> list (sets sorted when possible), numpy scalars and arrays -> Python values and lists, NaN/inf and pandas’ NA/NaT -> None, and anything else that isn’t str/int/float/bool/None -> str(x).

Parameters:

x (object) – Value to convert.

Returns:

A value that json.dumps() accepts.

Return type:

object

Raises:

ValueError – If two keys of a dict are the same as strings (e.g. 1 and "1").

skm_tools.serialize.graph_to_dict(g)

A networkx graph as a JSON-safe dict.

Parameters:

g (networkx.Graph) – Any networkx graph type.

Returns:

{"directed": bool, "multigraph": bool, "graph": {...}, "nodes": [{"id": ..., <attributes>}, ...], "edges": [{"source": ..., "target": ..., ["key": ...,] <attributes>}, ...]}. Edge keys are only included for multigraphs. Attribute values are converted with to_json_safe(). Read back with graph_from_dict().

Return type:

dict

Raises:

ValueError – If a node id is not a string or an integer (e.g. a tuple, which JSON can’t keep), or an attribute has the name of a field of the format: id (nodes), source, target or key (edges). Rename such attributes first.

Examples

>>> import networkx as nx
>>> g = nx.DiGraph([("A", "B", {"weight": 1})])
>>> graph_to_dict(g)["edges"]
[{'source': 'A', 'target': 'B', 'weight': 1}]
skm_tools.serialize.graph_from_dict(data, create_using=None)

Rebuild a networkx graph from graph_to_dict() output.

Parameters:
  • data (dict) – As returned by graph_to_dict() (or read from its JSON).

  • create_using (networkx graph class, optional) – Graph class to create. Default: chosen from data["directed"] and data["multigraph"].

Returns:

Attribute values come back as their JSON types (e.g. tuples become lists, sets become sorted lists).

Return type:

networkx.Graph

skm_tools.serialize.paths_to_dict(paths, g=None, node_attrs=('display_label',), edge_attrs=('interaction',))

Paths as JSON-safe data, optionally with node and edge attributes.

Parameters:
  • paths (list of list) – Paths as lists of nodes, e.g. from skm_tools.paths.get_paths().

  • g (networkx.Graph, optional) – The graph of the paths: to add the node_attrs of the nodes and the edge_attrs of each step.

  • node_attrs (iterable of str) – Node attributes to add (with g; default display_label).

  • edge_attrs (iterable of str) – Edge attributes to add (with g; default interaction).

Returns:

{"paths": [[node, ...], ...], "lengths": [int, ...]}, where a path’s length is its number of edges. With g, also "nodes": {node: {attribute: value}} for the nodes on the paths, and "steps": per path, a list of {"source": u, "target": v, attribute: value} per edge. A step against the edge direction (paths from get_paths(..., directed=False)) has the attributes of the reverse edge, and "reversed": True. In a multigraph, an attribute’s value is the list of the values of the parallel edges.

Return type:

dict

Examples

>>> import networkx as nx
>>> g = nx.DiGraph([("A", "B", {"interaction": "positive-influence"})])
>>> paths_to_dict([["A", "B"]], g, node_attrs=())["steps"]
[[{'source': 'A', 'target': 'B', 'interaction': 'positive-influence'}]]