Skip to content

Commit

Permalink
utilities: add converters to/from networkx graph and dependency dict
Browse files Browse the repository at this point in the history
- dependency_dict_to_networkx_digraph
- networkx_graph_to_dependency_dict
  • Loading branch information
kmantel committed Dec 7, 2023
1 parent ab34a99 commit a699df4
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion src/graph_scheduler/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
import weakref
from typing import Dict, Hashable, Set

import networkx as nx

__all__ = ['disable_debug_logging', 'enable_debug_logging']
__all__ = [
'dependency_dict_to_networkx_digraph', 'disable_debug_logging',
'enable_debug_logging', 'networkx_graph_to_dependency_dict',
]


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -146,3 +150,37 @@ def disable_debug_logging(level: int = logging.WARNING):
f'Restoring root logger level to {logging.getLevelName(level)}'
)
root_logger.setLevel(level)


def dependency_dict_to_networkx_digraph(graph: typing_graph_dependency_dict) -> nx.DiGraph:
"""
Converts a graph in dependency dict form to a networkx DiGraph
Args:
graph: a graph in dependency dict form
Returns:
networkx.DiGraph
"""
return nx.DiGraph(graph).reverse()


def networkx_graph_to_dependency_dict(graph: nx.Graph) -> typing_graph_dependency_dict:
"""
Converts a networkx Graph to a graph in dependency dict form
Args:
graph: a networkx.Graph
Returns:
a graph in dependency dict form
"""
res_graph = {}
for sender, receivers in graph.adj.items():
if sender not in res_graph:
res_graph[sender] = set()
for rec in receivers:
if rec not in res_graph:
res_graph[rec] = set()
res_graph[rec].add(sender)
return res_graph

0 comments on commit a699df4

Please sign in to comment.