moral.py 1.4 KB

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