File size: 19,165 Bytes
5980447
1
2
{"repo": "networkx/networkx", "pull_number": 2272, "instance_id": "networkx__networkx-2272", "issue_numbers": "", "base_commit": "91d3de2ce319c60f8217c08b2e6831ee6ee45284", "patch": "diff --git a/examples/drawing/atlas.py b/examples/drawing/atlas.py\n--- a/examples/drawing/atlas.py\n+++ b/examples/drawing/atlas.py\n@@ -64,11 +64,11 @@ def iso(G1, glist):\n         from networkx.drawing.nx_agraph import graphviz_layout\n     except ImportError:\n         try:\n-            import pydotplus\n+            import pydot\n             from networkx.drawing.nx_pydot import graphviz_layout\n         except ImportError:\n             raise ImportError(\"This example needs Graphviz and either \"\n-                              \"PyGraphviz or PyDotPlus\")\n+                              \"PyGraphviz or pydot\")\n \n     import matplotlib.pyplot as plt\n     plt.figure(1, figsize=(8, 8))\ndiff --git a/examples/drawing/circular_tree.py b/examples/drawing/circular_tree.py\n--- a/examples/drawing/circular_tree.py\n+++ b/examples/drawing/circular_tree.py\n@@ -6,11 +6,11 @@\n     from networkx.drawing.nx_agraph import graphviz_layout\n except ImportError:\n     try:\n-        import pydotplus\n+        import pydot\n         from networkx.drawing.nx_pydot import graphviz_layout\n     except ImportError:\n         raise ImportError(\"This example needs Graphviz and either \"\n-                          \"PyGraphviz or PyDotPlus\")\n+                          \"PyGraphviz or pydot\")\n \n G = nx.balanced_tree(3, 5)\n pos = graphviz_layout(G, prog='twopi', args='')\ndiff --git a/examples/drawing/giant_component.py b/examples/drawing/giant_component.py\n--- a/examples/drawing/giant_component.py\n+++ b/examples/drawing/giant_component.py\n@@ -27,11 +27,11 @@\n     layout = graphviz_layout\n except ImportError:\n     try:\n-        import pydotplus\n+        import pydot\n         from networkx.drawing.nx_pydot import graphviz_layout\n         layout = graphviz_layout\n     except ImportError:\n-        print(\"PyGraphviz and PyDotPlus not found;\\n\"\n+        print(\"PyGraphviz and pydot not found;\\n\"\n               \"drawing with spring layout;\\n\"\n               \"will be slow.\")\n         layout = nx.spring_layout\ndiff --git a/examples/drawing/lanl_routes.py b/examples/drawing/lanl_routes.py\n--- a/examples/drawing/lanl_routes.py\n+++ b/examples/drawing/lanl_routes.py\n@@ -2,7 +2,7 @@\n \"\"\"\n Routes to LANL from 186 sites on the Internet.\n \n-This uses Graphviz for layout so you need PyGraphviz or PyDotPlus.\n+This uses Graphviz for layout so you need PyGraphviz or pydot.\n \n \"\"\"\n # Author: Aric Hagberg (hagberg@lanl.gov)\n@@ -50,11 +50,11 @@ def lanl_graph():\n         from networkx.drawing.nx_agraph import graphviz_layout\n     except ImportError:\n         try:\n-            import pydotplus\n+            import pydot\n             from networkx.drawing.nx_pydot import graphviz_layout\n         except ImportError:\n             raise ImportError(\"This example needs Graphviz and either \"\n-                              \"PyGraphviz or PyDotPlus\")\n+                              \"PyGraphviz or pydot\")\n \n     G=lanl_graph()\n \ndiff --git a/examples/graph/atlas.py b/examples/graph/atlas.py\n--- a/examples/graph/atlas.py\n+++ b/examples/graph/atlas.py\n@@ -64,11 +64,11 @@ def iso(G1, glist):\n         from networkx.drawing.nx_agraph import graphviz_layout\n     except ImportError:\n         try:\n-            import pydotplus\n+            import pydot\n             from networkx.drawing.nx_pydot import graphviz_layout\n         except ImportError:\n             raise ImportError(\"This example needs Graphviz and either \"\n-                              \"PyGraphviz or PyDotPlus\")\n+                              \"PyGraphviz or pydot\")\n \n     import matplotlib.pyplot as plt\n     plt.figure(1, figsize=(8, 8))\ndiff --git a/examples/pygraphviz/write_dotfile.py b/examples/pygraphviz/write_dotfile.py\n--- a/examples/pygraphviz/write_dotfile.py\n+++ b/examples/pygraphviz/write_dotfile.py\n@@ -2,7 +2,7 @@\n \"\"\"\n Write a dot file from a networkx graph for further processing with graphviz.\n \n-You need to have either pygraphviz or pydotplus for this example.\n+You need to have either pygraphviz or pydot for this example.\n \n See http://networkx.github.io/documentation/latest/reference/drawing.html\n for more info.\n@@ -28,12 +28,12 @@\n     print(\"using package pygraphviz\")\n except ImportError:\n     try:\n-        import pydotplus\n+        import pydot\n         from networkx.drawing.nx_pydot import write_dot\n-        print(\"using package pydotplus\")\n+        print(\"using package pydot\")\n     except ImportError:\n         print()\n-        print(\"Both pygraphviz and pydotplus were not found \")\n+        print(\"Both pygraphviz and pydot were not found \")\n         print(\"see http://networkx.github.io/documentation\"\n               \"/latest/reference/drawing.html for info\")\n         print()\ndiff --git a/networkx/drawing/nx_pydot.py b/networkx/drawing/nx_pydot.py\n--- a/networkx/drawing/nx_pydot.py\n+++ b/networkx/drawing/nx_pydot.py\n@@ -3,14 +3,14 @@\n Pydot\n *****\n \n-Import and export NetworkX graphs in Graphviz dot format using pydotplus.\n+Import and export NetworkX graphs in Graphviz dot format using pydot.\n \n Either this module or nx_agraph can be used to interface with graphviz.\n \n See Also\n --------\n-PyDotPlus: https://github.com/carlos-jenkins/pydotplus\n-Graphviz:          http://www.research.att.com/sw/tools/graphviz/\n+pydot:         https://github.com/erocarrera/pydot\n+Graphviz:      http://www.research.att.com/sw/tools/graphviz/\n DOT Language:  http://www.graphviz.org/doc/info/lang.html\n \"\"\"\n # Author: Aric Hagberg (aric.hagberg@gmail.com)\n@@ -19,20 +19,30 @@\n #    Aric Hagberg <hagberg@lanl.gov>\n #    Dan Schult <dschult@colgate.edu>\n #    Pieter Swart <swart@lanl.gov>\n+#    Cecil Curry <leycec@gmail.com>\n #    All rights reserved.\n #    BSD license.\n-import importlib\n+from locale import getpreferredencoding\n from networkx.utils import open_file, make_str\n+from pkg_resources import parse_version\n import networkx as nx\n \n __all__ = ['write_dot', 'read_dot', 'graphviz_layout', 'pydot_layout',\n            'to_pydot', 'from_pydot']\n \n+# Minimum required version of pydot, which broke backwards API compatibility in\n+# non-trivial ways and is thus a hard NetworkX requirement. Note that, although\n+# pydot 1.2.0 was the first to do so, pydot 1.2.3 resolves a critical long-\n+# standing Python 2.x issue required for sane NetworkX operation. See also:\n+#     https://github.com/erocarrera/pydot/blob/master/ChangeLog\n+PYDOT_VERSION_MIN = '1.2.3'\n+\n # 2.x/3.x compatibility\n try:\n     basestring\n except NameError:\n     basestring = str\n+    unicode = str\n \n @open_file(1, mode='w')\n def write_dot(G, path):\n@@ -46,25 +56,35 @@ def write_dot(G, path):\n \n @open_file(0, mode='r')\n def read_dot(path):\n-    \"\"\"Return a NetworkX MultiGraph or MultiDiGraph from a dot file on path.\n+    \"\"\"Return a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the\n+    dot file with the passed path.\n+\n+    If this file contains multiple graphs, only the first such graph is\n+    returned. All graphs _except_ the first are silently ignored.\n \n     Parameters\n     ----------\n-    path : filename or file handle\n+    path : str or file\n+        Filename or file handle.\n \n     Returns\n     -------\n-    G : NetworkX multigraph\n-        A MultiGraph or MultiDiGraph.\n+    G : MultiGraph or MultiDiGraph\n+        A :class:`MultiGraph` or :class:`MultiDiGraph`.\n \n     Notes\n     -----\n-    Use G = nx.Graph(read_dot(path)) to return a Graph instead of a MultiGraph.\n+    Use `G = nx.Graph(read_dot(path))` to return a :class:`Graph` instead of a\n+    :class:`MultiGraph`.\n     \"\"\"\n-    import pydotplus\n+    pydot = _import_pydot()\n     data = path.read()\n-    P = pydotplus.graph_from_dot_data(data)\n-    return from_pydot(P)\n+\n+    # List of one or more \"pydot.Dot\" instances deserialized from this file.\n+    P_list = pydot.graph_from_dot_data(data)\n+\n+    # Convert only the first such instance into a NetworkX graph.\n+    return from_pydot(P_list[0])\n \n def from_pydot(P):\n     \"\"\"Return a NetworkX graph from a Pydot graph.\n@@ -86,7 +106,7 @@ def from_pydot(P):\n     >>> G = nx.nx_pydot.from_pydot(A) # return MultiGraph\n \n     # make a Graph instead of MultiGraph\n-    >>> G = nx.Graph(nx.nx_pydot.from_pydot(A)) \n+    >>> G = nx.Graph(nx.nx_pydot.from_pydot(A))\n \n     \"\"\"\n     if P.get_strict(None): # pydot bug: get_strict() shouldn't take argument\n@@ -172,7 +192,8 @@ def to_pydot(N, strict=True):\n     -----\n \n     \"\"\"\n-    import pydotplus\n+    pydot = _import_pydot()\n+\n     # set Graphviz graph type\n     if N.is_directed():\n         graph_type='digraph'\n@@ -183,10 +204,10 @@ def to_pydot(N, strict=True):\n     name = N.name\n     graph_defaults=N.graph.get('graph',{})\n     if name is '':\n-        P = pydotplus.Dot('', graph_type=graph_type, strict=strict,\n+        P = pydot.Dot('', graph_type=graph_type, strict=strict,\n                       **graph_defaults)\n     else:\n-        P = pydotplus.Dot('\"%s\"'%name, graph_type=graph_type, strict=strict,\n+        P = pydot.Dot('\"%s\"'%name, graph_type=graph_type, strict=strict,\n                       **graph_defaults)\n     try:\n         P.set_node_defaults(**N.graph['node'])\n@@ -199,20 +220,20 @@ def to_pydot(N, strict=True):\n \n     for n,nodedata in N.nodes(data=True):\n         str_nodedata=dict((k,make_str(v)) for k,v in nodedata.items())\n-        p=pydotplus.Node(make_str(n),**str_nodedata)\n+        p=pydot.Node(make_str(n),**str_nodedata)\n         P.add_node(p)\n \n     if N.is_multigraph():\n         for u,v,key,edgedata in N.edges(data=True,keys=True):\n             str_edgedata=dict((k,make_str(v)) for k,v in edgedata.items() if k != 'key')\n-            edge=pydotplus.Edge(make_str(u), make_str(v),\n+            edge=pydot.Edge(make_str(u), make_str(v),\n                     key=make_str(key), **str_edgedata)\n             P.add_edge(edge)\n \n     else:\n         for u,v,edgedata in N.edges(data=True):\n             str_edgedata=dict((k,make_str(v)) for k,v in edgedata.items())\n-            edge=pydotplus.Edge(make_str(u),make_str(v),**str_edgedata)\n+            edge=pydot.Edge(make_str(u),make_str(v),**str_edgedata)\n             P.add_edge(edge)\n     return P\n \n@@ -248,10 +269,25 @@ def graphviz_layout(G,prog='neato',root=None, **kwds):\n     return pydot_layout(G=G,prog=prog,root=root,**kwds)\n \n \n-def pydot_layout(G,prog='neato',root=None, **kwds):\n-    \"\"\"Create node positions using Pydot and Graphviz.\n+#FIXME: Document the \"root\" parameter.\n+#FIXME: Why does this function accept a variadic dictionary of keyword arguments\n+#(i.e., \"**kwds\") but fail to do anything with those arguments? This is probably\n+#wrong, as unrecognized keyword arguments will be silently ignored.\n+def pydot_layout(G, prog='neato', root=None, **kwds):\n+    \"\"\"Create node positions using :mod:`pydot` and Graphviz.\n \n-    Returns a dictionary of positions keyed by node.\n+    Parameters\n+    --------\n+    G : Graph\n+        NetworkX graph to be laid out.\n+    prog : optional[str]\n+        Basename of the GraphViz command with which to layout this graph.\n+        Defaults to `neato`, the default GraphViz command for undirected graphs.\n+\n+    Returns\n+    --------\n+    dict\n+        Dictionary of positions keyed by node.\n \n     Examples\n     --------\n@@ -259,12 +295,17 @@ def pydot_layout(G,prog='neato',root=None, **kwds):\n     >>> pos = nx.nx_pydot.pydot_layout(G)\n     >>> pos = nx.nx_pydot.pydot_layout(G, prog='dot')\n     \"\"\"\n-    import pydotplus\n+    pydot = _import_pydot()\n     P=to_pydot(G)\n-    if root is not None :\n+    if root is not None:\n         P.set(\"root\",make_str(root))\n \n-    D=P.create_dot(prog=prog)\n+    # List of low-level bytes comprising a string in the dot language converted\n+    # from the passed graph with the passed external GraphViz command.\n+    D_bytes = P.create_dot(prog=prog)\n+\n+    # Unique string decoded from these bytes with the preferred locale encoding.\n+    D = unicode(D_bytes, encoding=getpreferredencoding())\n \n     if D==\"\":  # no data returned\n         print(\"Graphviz layout with %s failed\"%(prog))\n@@ -275,11 +316,16 @@ def pydot_layout(G,prog='neato',root=None, **kwds):\n         print(\"And then run %s on file.dot\"%(prog))\n         return\n \n-    Q=pydotplus.graph_from_dot_data(D)\n+    # List of one or more \"pydot.Dot\" instances deserialized from this string.\n+    Q_list = pydot.graph_from_dot_data(D)\n+    assert len(Q_list) == 1\n+\n+    # The first and only such instance, as guaranteed by the above assertion.\n+    Q = Q_list[0]\n \n     node_pos={}\n     for n in G.nodes():\n-        pydot_node = pydotplus.Node(make_str(n)).get_name()\n+        pydot_node = pydot.Node(make_str(n)).get_name()\n         node=Q.get_node(pydot_node)\n \n         if isinstance(node,list):\n@@ -290,10 +336,39 @@ def pydot_layout(G,prog='neato',root=None, **kwds):\n             node_pos[n]=(float(xx),float(yy))\n     return node_pos\n \n+def _import_pydot():\n+    '''\n+    Import and return the `pydot` module if the currently installed version of\n+    this module satisfies NetworkX requirements _or_ raise an exception.\n+\n+    Returns\n+    --------\n+    :mod:`pydot`\n+        Imported `pydot` module object.\n+\n+    Raises\n+    --------\n+    ImportError\n+        If the `pydot` module is either unimportable _or_ importable but of\n+        insufficient version.\n+    '''\n+\n+    import pydot\n+\n+    # If the currently installed version of pydot is older than this minimum,\n+    # raise an exception. The pkg_resources.parse_version() function bundled\n+    # with setuptools is commonly regarded to be the most robust means of\n+    # comparing version strings. (Your mileage may vary.)\n+    if parse_version(pydot.__version__) < parse_version(PYDOT_VERSION_MIN):\n+        raise ImportError(\n+            'pydot %s < %s' % (pydot.__version__, PYDOT_VERSION_MIN))\n+\n+    return pydot\n+\n # fixture for nose tests\n def setup_module(module):\n     from nose import SkipTest\n     try:\n-        import pydotplus\n+        return _import_pydot()\n     except ImportError:\n-        raise SkipTest(\"pydotplus not available\")\n+        raise SkipTest(\"pydot not available\")\n", "test_patch": "diff --git a/networkx/drawing/tests/test_pydot.py b/networkx/drawing/tests/test_pydot.py\n--- a/networkx/drawing/tests/test_pydot.py\n+++ b/networkx/drawing/tests/test_pydot.py\n@@ -1,8 +1,7 @@\n \"\"\"Unit tests for pydot drawing functions.\"\"\"\n-import os\n+import sys\n import tempfile\n-from nose import SkipTest\n-from nose.tools import assert_true\n+from nose.tools import assert_equal, assert_is_instance, assert_true\n import networkx as nx\n from networkx.testing import assert_graphs_equal\n \n@@ -10,37 +9,83 @@\n class TestPydot(object):\n     @classmethod\n     def setupClass(cls):\n-        global pydotplus\n-        try:\n-            import pydotplus\n-        except ImportError:\n-            raise SkipTest('pydotplus not available.')\n+        '''\n+        Fixture defining the `pydot` global to be the `pydot` module if both\n+        importable and of sufficient version _or_ skipping this test.\n+        '''\n+        global pydot\n+        pydot = nx.nx_pydot.setup_module(sys.modules[__name__])\n+        assert pydot is not None\n \n-    def pydot_checks(self, G):\n+    def pydot_checks(self, G, prog):\n+        '''\n+        Validate :mod:`pydot`-based usage of the passed NetworkX graph with the\n+        passed basename of an external GraphViz command (e.g., `dot`, `neato`).\n+        '''\n+\n+        # Set the name of this graph to... \"G\". Failing to do so will\n+        # subsequently trip an assertion expecting this name.\n+        G.graph['name'] = 'G'\n+\n+        # Add arbitrary nodes and edges to the passed empty graph.\n         G.add_edges_from([('A','B'),('A','C'),('B','C'),('A','D')])\n         G.add_node('E')\n+\n+        # Validate layout of this graph with the passed GraphViz command.\n+        graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog)\n+        assert_is_instance(graph_layout, dict)\n+\n+        # Convert this graph into a \"pydot.Dot\" instance.\n         P = nx.nx_pydot.to_pydot(G)\n+\n+        # Convert this \"pydot.Dot\" instance back into a graph of the same type.\n         G2 = G.__class__(nx.nx_pydot.from_pydot(P))\n+\n+        # Validate the original and resulting graphs to be the same.\n         assert_graphs_equal(G, G2)\n \n+        # Serialize this \"pydot.Dot\" instance to a temporary file in dot format.\n         fname = tempfile.mktemp()\n         assert_true(P.write_raw(fname))\n-        Pin = pydotplus.graph_from_dot_file(fname)\n \n+        # Deserialize a list of new \"pydot.Dot\" instances back from this file.\n+        Pin_list = pydot.graph_from_dot_file(path=fname, encoding='utf-8')\n+\n+        # Validate this file to contain only one graph.\n+        assert_equal(len(Pin_list), 1)\n+\n+        # The single \"pydot.Dot\" instance deserialized from this file.\n+        Pin = Pin_list[0]\n+\n+        # Sorted list of all nodes in the original \"pydot.Dot\" instance.\n         n1 = sorted([p.get_name() for p in P.get_node_list()])\n+\n+        # Sorted list of all nodes in the deserialized \"pydot.Dot\" instance.\n         n2 = sorted([p.get_name() for p in Pin.get_node_list()])\n-        assert_true(n1 == n2)\n \n-        e1 = [(e.get_source(),e.get_destination()) for e in P.get_edge_list()]\n-        e2 = [(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()]\n-        assert_true(sorted(e1) == sorted(e2))\n+        # Validate these instances to contain the same nodes.\n+        assert_equal(n1, n2)\n+\n+        # Sorted list of all edges in the original \"pydot.Dot\" instance.\n+        e1 = sorted([\n+            (e.get_source(), e.get_destination()) for e in P.get_edge_list()])\n \n+        # Sorted list of all edges in the original \"pydot.Dot\" instance.\n+        e2 = sorted([\n+            (e.get_source(), e.get_destination()) for e in Pin.get_edge_list()])\n+\n+        # Validate these instances to contain the same edges.\n+        assert_equal(e1, e2)\n+\n+        # Deserialize a new graph of the same type back from this file.\n         Hin = nx.nx_pydot.read_dot(fname)\n         Hin = G.__class__(Hin)\n+\n+        # Validate the original and resulting graphs to be the same.\n         assert_graphs_equal(G, Hin)\n \n     def testUndirected(self):\n-        self.pydot_checks(nx.Graph())\n+        self.pydot_checks(nx.Graph(), prog='neato')\n \n     def testDirected(self):\n-        self.pydot_checks(nx.DiGraph())\n+        self.pydot_checks(nx.DiGraph(), prog='dot')\n", "problem_statement": "", "hints_text": "", "created_at": "2016-10-05T07:12:58Z"}