moral.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. r"""Function for computing the moral graph of a directed graph."""
  2. import itertools
  3. import networkx as nx
  4. from networkx.utils import not_implemented_for
  5. __all__ = ["moral_graph"]
  6. @not_implemented_for("undirected")
  7. @nx._dispatchable(returns_graph=True)
  8. def moral_graph(G):
  9. r"""Return the Moral Graph
  10. Returns the moralized graph of a given directed graph.
  11. Parameters
  12. ----------
  13. G : NetworkX graph
  14. Directed graph
  15. Returns
  16. -------
  17. H : NetworkX graph
  18. The undirected moralized graph of G
  19. Raises
  20. ------
  21. NetworkXNotImplemented
  22. If `G` is undirected.
  23. Examples
  24. --------
  25. >>> G = nx.DiGraph([(1, 2), (2, 3), (2, 5), (3, 4), (4, 3)])
  26. >>> G_moral = nx.moral_graph(G)
  27. >>> G_moral.edges()
  28. EdgeView([(1, 2), (2, 3), (2, 5), (2, 4), (3, 4)])
  29. Notes
  30. -----
  31. A moral graph is an undirected graph H = (V, E) generated from a
  32. directed Graph, where if a node has more than one parent node, edges
  33. between these parent nodes are inserted and all directed edges become
  34. undirected.
  35. https://en.wikipedia.org/wiki/Moral_graph
  36. References
  37. ----------
  38. .. [1] Wray L. Buntine. 1995. Chain graphs for learning.
  39. In Proceedings of the Eleventh conference on Uncertainty
  40. in artificial intelligence (UAI'95)
  41. """
  42. H = G.to_undirected()
  43. for preds in G.pred.values():
  44. predecessors_combinations = itertools.combinations(preds, r=2)
  45. H.add_edges_from(predecessors_combinations)
  46. return H