Created
June 1, 2023 11:15
-
-
Save clbarnes/2d91b14eba62220ba8081985add550bd to your computer and use it in GitHub Desktop.
Update networkx v1 node_link_data to v2+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Transform between networkx v1 and v2+ node_link_data format. | |
""" | |
def node_link_data_1_2( | |
data: dict, *, source="source", target="target", name="id", key="key", link="links" | |
): | |
"""Update the node_link_data in-place for compatibility with networkx v2+. | |
Between networkx 1 and 2, the node_link_data format changed: | |
specifically, the edges' source and target attributes now refer | |
to the node IDs, not their index in the node list. | |
CATMAID produces data compatible with networkx 1. | |
Parameters | |
---------- | |
data : dict | |
Networkx 1-like node_link_data. | |
Must use default keys for source, target, name, key, link. | |
""" | |
nodes = data["nodes"] | |
for e in data[link]: | |
for k in [source, target]: | |
e[k] = nodes[e[k]][name] | |
def node_link_data_2_1( | |
data: dict, *, source="source", target="target", name="id", key="key", link="links" | |
): | |
"""Roll back the node_link_data in-place for compatibility with networkx v1. | |
Between networkx 1 and 2, the node_link_data format changed: | |
specifically, the edges' source and target attributes now refer | |
to the node IDs, not their index in the node list. | |
Parameters | |
---------- | |
data : dict | |
Networkx 2+-like node_link_data. | |
""" | |
name_to_idx = {n[name]: idx for idx, n in enumerate(data["nodes"])} | |
for e in data[link]: | |
for k in [source, target]: | |
e[k] = name_to_idx[e[k]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment