11from __future__ import annotations
22
33from abc import ABC , abstractmethod
4+ import os
45import sys
56import warnings
67import numpy as np
78import matplotlib .pyplot as plt
89import copy
910from collections .abc import Iterable , Iterator
1011import tempfile
11- import subprocess
1212import webbrowser
13- from typing import Any , Callable , ClassVar , overload
13+ from typing import IO , Any , Callable , ClassVar , overload
1414from numpy .typing import ArrayLike , NDArray
1515
1616from spatialmath .base .graphics import axes_logic
@@ -1444,17 +1444,153 @@ def highlight_vertex(
14441444 vertex .x , vertex .y , "o" , color = color , markersize = 12 * scale , alpha = alpha
14451445 )
14461446
1447- def dotfile (self , filename : str | Any | None = None , direction : str | None = None ) -> None :
1447+ def export (
1448+ self ,
1449+ filename : str | os .PathLike | IO | None = None ,
1450+ format : str | None = None , # pylint: disable=redefined-builtin
1451+ ** options : Any ,
1452+ ) -> str | None :
1453+ """
1454+ Export the graph as text or as a rendered image
1455+
1456+ :param filename: destination path or open file, defaults to None
1457+ :type filename: str, path-like or file object, optional
1458+ :param format: ``"dot"``, ``"mermaid"``, ``"graphml"``, ``"elk"`` or an
1459+ image format ``"svg"``, ``"pdf"``, ``"png"`` ..., inferred from
1460+ the extension of ``filename`` if not given
1461+ :type format: str, optional
1462+ :param options: format specific options, see below
1463+ :raises ValueError: the format is unknown or cannot be inferred, or an
1464+ image format is requested without a ``filename``
1465+ :raises TypeError: an option is not valid for the format
1466+ :raises RuntimeError: an image format is requested and GraphViz is not
1467+ installed, or fails
1468+ :return: the text if ``filename`` is None, otherwise None
1469+ :rtype: str or None
1470+
1471+ .. list-table::
1472+ :header-rows: 1
1473+
1474+ * - ``format``
1475+ - extensions
1476+ - positions
1477+ - options
1478+ * - ``"dot"``
1479+ - ``.dot`` ``.gv``
1480+ - ``pos="x,y!"``
1481+ - ``direction``, ``colorcomponents``, ``costs``
1482+ * - ``"mermaid"``
1483+ - ``.mmd`` ``.mermaid``
1484+ - no
1485+ - ``direction``, ``colorcomponents``, ``costs``, ``fence``
1486+ * - ``"graphml"``
1487+ - ``.graphml``
1488+ - ``x``, ``y``, ``coord``
1489+ - none
1490+ * - ``"elk"``
1491+ - ``.elk.json`` ``.elk``
1492+ - ``x``, ``y``
1493+ - ``size``, ``layout_options``
1494+ * - ``"svg"`` ``"pdf"`` ``"png"`` ...
1495+ - the same
1496+ - yes, via ``neato``
1497+ - ``engine``, ``direction``, ``colorcomponents``, ``costs``
1498+
1499+ The text formats need nothing beyond the standard library. The image
1500+ formats run the GraphViz ``dot`` or ``neato`` executable.
1501+
1502+ .. runblock:: pycon
1503+
1504+ >>> from pgraph import UGraph
1505+ >>> g = UGraph()
1506+ >>> v1 = g.add_vertex(coord=[0,0], name='v1')
1507+ >>> v2 = g.add_vertex(coord=[1,1], name='v2')
1508+ >>> g.add_edge(v1, v2, cost=2)
1509+ >>> print(g.export(format="mermaid", direction="LR"))
1510+
1511+ .. note::
1512+
1513+ - Output is reproducible: vertices are written in creation order
1514+ and edges in the order of their vertices, not in set order.
1515+ - A file object passed as ``filename`` is written but not closed.
1516+ A path is opened, and closed even if writing fails.
1517+ - Names are escaped for each format, and Mermaid, GraphML and ELK
1518+ use generated ids so any vertex name is valid.
1519+
1520+ .. rubric:: For graphs with parallel edges or loops
1521+
1522+ Every edge is written, each with its own cost, so parallel edges give
1523+ repeated lines (DOT, Mermaid) or distinct ``id`` elements (GraphML,
1524+ ELK). A self-loop is written once, as an edge from a vertex to itself.
1525+
1526+ :seealso: :meth:`dotfile` :meth:`showgraph` :mod:`pgraph.exporters`
1527+ """
1528+ from . import exporters
1529+
1530+ if format is None :
1531+ format = exporters .format_from_filename (filename )
1532+ if format is None :
1533+ raise ValueError (
1534+ "cannot infer the export format, give format= or a filename "
1535+ f"with a known extension; formats: { exporters .formats ()} "
1536+ )
1537+ format = format .lower ()
1538+
1539+ if format in exporters .RENDER_FORMATS :
1540+ if filename is None :
1541+ raise ValueError (f"format { format !r} is an image and needs a filename" )
1542+ image = exporters .render (self , format , ** options )
1543+ if isinstance (filename , (str , os .PathLike )):
1544+ with open (filename , "wb" ) as f :
1545+ f .write (image )
1546+ else :
1547+ try :
1548+ filename .write (image )
1549+ except TypeError : # a text mode file, fine for svg and ps
1550+ if not exporters .RENDER_FORMATS [format ]:
1551+ raise
1552+ filename .write (image .decode ("utf-8" ))
1553+ return None
1554+
1555+ try :
1556+ func = exporters ._TEXT [format ]
1557+ except KeyError :
1558+ raise ValueError (
1559+ f"unknown export format { format !r} , expected one of "
1560+ f"{ exporters .formats ()} "
1561+ ) from None
1562+ text = func (self , ** options )
1563+
1564+ if filename is None :
1565+ return text
1566+ if isinstance (filename , (str , os .PathLike )):
1567+ with open (filename , "w" , encoding = "utf-8" ) as f :
1568+ f .write (text )
1569+ else :
1570+ filename .write (text )
1571+ return None
1572+
1573+ def dotfile (
1574+ self ,
1575+ filename : str | os .PathLike | IO | None = None ,
1576+ direction : str | None = None ,
1577+ ) -> None :
14481578 """
14491579 Export graph as a GraphViz dot file
14501580
14511581 :param filename: filename to save graph to, defaults to None
1452- :type filename: str, optional
1582+ :type filename: str, path-like or file object, optional
1583+ :param direction: layout direction, eg. ``"LR"``, defaults to None
1584+ :type direction: str, optional
14531585
14541586 ``g.dotfile()`` creates the specified file which contains the `GraphViz
14551587 <https://graphviz.org>`_ code to represent the embedded graph. By default
14561588 output is to the console.
14571589
1590+ This is :meth:`export` with ``format="dot"`` and edge costs left
1591+ unlabelled, as it has always been. Use :meth:`export` for other
1592+ formats or for edge labels.
1593+
14581594 .. note::
14591595
14601596 - The graph is undirected if it is a subclass of ``UGraph``
@@ -1477,76 +1613,44 @@ def dotfile(self, filename: str | Any | None = None, direction: str | None = Non
14771613 >>> g.add_edge(v1, v2)
14781614 >>> g.dotfile()
14791615
1480- :seealso: :func :`showgraph`
1616+ :seealso: :meth:`export` :meth :`showgraph`
14811617 """
1618+ from . import exporters
14821619
1620+ text = exporters .dot (self , direction = direction , costs = False )
14831621 if filename is None :
1484- f = sys .stdout
1485- elif isinstance (filename , str ):
1486- f = open (filename , "w" )
1487- else :
1488- f = filename
1489-
1490- if isinstance (self , DGraph ):
1491- print ("digraph {" , file = f )
1622+ sys .stdout .write (text )
1623+ elif isinstance (filename , (str , os .PathLike )):
1624+ with open (filename , "w" , encoding = "utf-8" ) as f :
1625+ f .write (text )
14921626 else :
1493- print ( "graph {" , file = f )
1627+ filename . write ( text )
14941628
1495- if direction is not None :
1496- print (f"rankdir = { direction } " , file = f )
1497-
1498- # add the vertices including name and position
1499- for vertex in self :
1500- if vertex .coord is None :
1501- print (' "{:s}"' .format (vertex .name ), file = f )
1502- else :
1503- print (
1504- ' "{:s}" [pos="{:.5g},{:.5g}"]' .format (
1505- vertex .name , vertex .coord [0 ], vertex .coord [1 ]
1506- ),
1507- file = f ,
1508- )
1509- print (file = f )
1510- # add the edges
1511- for e in self .edges ():
1512- assert e .v1 is not None and e .v2 is not None
1513- if isinstance (self , DGraph ):
1514- print (' "{:s}" -> "{:s}"' .format (e .v1 .name , e .v2 .name ), file = f )
1515- else :
1516- print (' "{:s}" -- "{:s}"' .format (e .v1 .name , e .v2 .name ), file = f )
1517-
1518- print ("}" , file = f )
1519-
1520- if isinstance (filename , str ):
1521- f .close () # noqa
1522-
1523- def showgraph (self , ** kwargs : Any ) -> None :
1629+ def showgraph (self , display : bool = True , ** options : Any ) -> str | None :
15241630 """
15251631 Display graph in a browser tab
15261632
1527- :param kwargs: arguments passed to :meth:`dotfile`
1528-
1529- ``g.showgraph()`` renders and displays the graph in a browser tab. The
1530- graph is exported in `GraphViz <https://graphviz.org>`_ format, rendered to
1531- PDF using ``dot`` and then displayed in a browser tab.
1532-
1533- :seealso: :func:`dotfile`
1534- """
1535- # create the temporary dotfile
1536- dotfile = tempfile .TemporaryFile (mode = "w" )
1537- self .dotfile (dotfile , ** kwargs )
1538-
1539- # rewind the dot file, create PDF file in the filesystem, run dot
1540- dotfile .seek (0 )
1541- pdffile = tempfile .NamedTemporaryFile (suffix = ".pdf" , delete = False )
1542- result = subprocess .run ("dot -Tpdf" , shell = True , stdin = dotfile , stdout = pdffile )
1543-
1544- if result .returncode == 0 :
1545- # dot ran happily
1546- # open the PDF file in browser (hopefully portable), then cleanup
1547- webbrowser .open (f"file://{ pdffile .name } " )
1548- # time.sleep(1)
1549- # os.remove(pdffile.name)
1633+ :param display: open the rendered PDF in a browser tab, defaults to True
1634+ :param options: ``engine``, ``direction``, ``colorcomponents`` and
1635+ ``costs``, passed to :meth:`export`
1636+ :raises RuntimeError: GraphViz is not installed, or fails
1637+ :return: path of the rendered PDF if ``display`` is False, else None
1638+ :rtype: str or None
1639+
1640+ ``g.showgraph()`` renders the graph to PDF with `GraphViz
1641+ <https://graphviz.org>`_ and displays it in a browser tab. With
1642+ ``display=False`` the PDF is rendered but not opened and its path is
1643+ returned, which is useful for tests and notebooks.
1644+
1645+ :seealso: :meth:`export` :meth:`dotfile`
1646+ """
1647+ pdf = tempfile .NamedTemporaryFile (suffix = ".pdf" , delete = False )
1648+ pdf .close ()
1649+ self .export (pdf .name , format = "pdf" , ** options )
1650+ if display :
1651+ webbrowser .open (f"file://{ pdf .name } " )
1652+ return None
1653+ return pdf .name
15501654
15511655 def iscyclic (self ) -> bool :
15521656 """
0 commit comments