skm_tools.serialize =================== .. py:module:: skm_tools.serialize .. autoapi-nested-parse:: 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 --------- .. autoapisummary:: skm_tools.serialize.to_json_safe skm_tools.serialize.graph_to_dict skm_tools.serialize.graph_from_dict skm_tools.serialize.paths_to_dict Module Contents --------------- .. py:function:: 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)``. :param x: Value to convert. :type x: object :returns: A value that :func:`json.dumps` accepts. :rtype: object :raises ValueError: If two keys of a dict are the same as strings (e.g. ``1`` and ``"1"``). .. py:function:: graph_to_dict(g) A networkx graph as a JSON-safe dict. :param g: Any networkx graph type. :type g: networkx.Graph :returns: ``{"directed": bool, "multigraph": bool, "graph": {...}, "nodes": [{"id": ..., }, ...], "edges": [{"source": ..., "target": ..., ["key": ...,] }, ...]}``. Edge keys are only included for multigraphs. Attribute values are converted with :func:`to_json_safe`. Read back with :func:`graph_from_dict`. :rtype: 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. .. rubric:: Examples >>> import networkx as nx >>> g = nx.DiGraph([("A", "B", {"weight": 1})]) >>> graph_to_dict(g)["edges"] [{'source': 'A', 'target': 'B', 'weight': 1}] .. py:function:: graph_from_dict(data, create_using=None) Rebuild a networkx graph from :func:`graph_to_dict` output. :param data: As returned by :func:`graph_to_dict` (or read from its JSON). :type data: dict :param create_using: Graph class to create. Default: chosen from ``data["directed"]`` and ``data["multigraph"]``. :type create_using: networkx graph class, optional :returns: Attribute values come back as their JSON types (e.g. tuples become lists, sets become sorted lists). :rtype: networkx.Graph .. py:function:: paths_to_dict(paths, g=None, node_attrs=('display_label', ), edge_attrs=('interaction', )) Paths as JSON-safe data, optionally with node and edge attributes. :param paths: Paths as lists of nodes, e.g. from :func:`skm_tools.paths.get_paths`. :type paths: list of list :param g: The graph of the paths: to add the `node_attrs` of the nodes and the `edge_attrs` of each step. :type g: networkx.Graph, optional :param node_attrs: Node attributes to add (with `g`; default ``display_label``). :type node_attrs: iterable of str :param edge_attrs: Edge attributes to add (with `g`; default ``interaction``). :type edge_attrs: iterable of str :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. :rtype: dict .. rubric:: 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'}]]