a
    n}T                     @   s  d Z ddlmZmZ ddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZ ejdk  Zer~dZeZeZeZnd	Zeg d
Zeg dZeg dZeg dZdd ZdAddZG dd deZg dZe dej!Z"e dej!Z#e dej!Z$e dej!Z%e dej&ej!B Z'e dej&ej!B Z(dd Z)dd Z*d d! Z+d"d# Z,dBd%d&Z-dCd'd(Z.dDd)d*Z/d+d, Z0d-d. Z1G d/d0 d0e2Z3G d1d2 d2e4Z5G d3d4 d4e4Z6G d5d6 d6e3Z7G d7d8 d8e3Z8G d9d: d:e3Z9G d;d< d<e9Z:G d=d> d>e9Z;G d?d@ d@e9Z<dS )Ez
Graphviz's dot language Python interface.

This module provides with a full interface to create handle modify
and process graphs in Graphviz's dot language.
    )divisionprint_functionN)
itemgetter   )parser)   r   r        )TZDampingKURLZaspectZbbbgcolorcentercharsetZclusterrankcolorschemecommentZcompoundZconcentrateZdefaultdistZdimZdimenZdiredgeconstraintsZdpiepsilonZesep	fontcolorfontnameZ	fontnamesZfontpathfontsizeidlabel	labeljustlabellocZ	landscapeZlayersZlayersepZlayoutZlevelsZ	levelsgaplheightlplwidthmarginmaxiterZmclimitZmindistmodemodelZmosekZnodesep	nojustify	normalizeZnslimitZnslimit1ZorderingorientationZoutputorderoverlapZoverlap_scalingpackZpackmodepadZpageZpagedirZquadtreeZquantumZrankdirZranksepZratioZ
remincrossZrepulsiveforce
resolutionrootrotateZ
searchsizesep	showboxessizeZ	smoothingsortvZsplinesstartZ
stylesheettargetZ	truecolorZviewportZvoro_marginrank)=r   Z	arrowheadZ	arrowsizeZ	arrowtailcolorr   r   Z
constraintZdecoratedirZedgeURLZedgehrefZ
edgetargetZedgetooltipr   r   r   ZheadURLZheadclipZheadhrefZ	headlabelZheadportZ
headtargetZheadtooltipZhrefr   r   ZlabelURLZ
labelangleZlabeldistanceZ
labelfloatZlabelfontcolorZlabelfontnameZlabelfontsizeZ	labelhrefZlabeltargetZlabeltooltiplayerlenZlheadr   ZltailZminlenr    penwidthposZsameheadZsametailr*   styleZtailURLZtailclipZtailhrefZ	taillabelZtailportZ
tailtargetZtailtooltipr.   tooltipZweightr/   )+r   r0   r   r   Z
distortion	fillcolorZ	fixedsizer   r   r   groupheightr   imageZ
imagescaler   r   r2   r   r    r"   r4   peripheriesZpinr5   ZrectsZregularr'   ZsamplepointsshapeZ	shapefiler*   ZsidesZskewr,   r6   r.   r7   ZverticeswidthzZtexlblZtexmode)r
   r   r   r0   r   r8   r   r   r   r   r   r   r   r   r   r    Zpencolorr4   r<   r,   r6   r.   r7   c              	   C   s*   z| d  W n t tfy$   Y dS 0 dS )zCheck if obj is string.r	   FT)	TypeError
ValueErrorobj rD   W/var/www/viveiro_mudafortebrasil/venv/lib/python3.9/site-packages/pydotplus/graphviz.pyis_string_likes   s
    rF   w+c                 C   sD   t | rt| |}d}n$t| dr,| }d}nt| |}d}||fS )a  Obtain a proper file object.

    Parameters
    ----------
    fname : string, file object, file descriptor
        If a string or file descriptor, then we create a file object.
        If *fname*
        is a file object, then we do nothing and ignore the specified *mode*
        parameter.
    mode : str
        The mode of the file to be opened.

    Returns
    -------
    fobj : file object
        The file object.
    close : bool
        If *fname* was a string, then *close* will be *True* to signify that
        the file object should be closed after writing to it. Otherwise,
        *close* will be *False* signifying that the user, in essence, created
        the file object already and that subsequent operations should not
        close it.

    TwriteF)rF   openhasattrosfdopen)fnamer   fobjcloserD   rD   rE   get_fobj|   s    

rP   c                   @   sX   e Zd Zdd ZeeZe Z ZZe Z Z	 Z
Zdd Zdd Zdd Zd	d
 ZdS )
frozendictc                 C   s   t dd S )Nz A frozendict cannot be modified.)AttributeErrorrB   rD   rD   rE   _blocked_attribute   s    zfrozendict._blocked_attributec           
      O   s   t | }g }|D ]}t|t rt|}| D ]~\}}t|trN|||< q2t|t rft|||< q2t|tr2t }|D ](}	t|	t r|t|	 qz||	 qzt|||< q2|| q|| qt j	|g|R i | |S N)
dict__new__
isinstancecopyitemsrQ   listappendtuple__init__)
clsargskwnewZargs_argkvZv_elmrD   rD   rE   rV      s*    







zfrozendict.__new__c                 O   s   d S rT   rD   )selfr_   r`   rD   rD   rE   r]      s    zfrozendict.__init__c                 C   s>   z| j W S  ty8   ttt|   }| _ | Y S 0 d S rT   )Z_cached_hashrR   hashr\   sortedrY   )rf   hrD   rD   rE   __hash__   s
    zfrozendict.__hash__c                 C   s   dt |  S )Nzfrozendict(%s))rU   __repr__rf   rD   rD   rE   rk      s    zfrozendict.__repr__N)__name__
__module____qualname__rS   property__delitem____setitem__clearpoppopitem
setdefaultupdaterV   r]   rj   rk   rD   rD   rD   rE   rQ      s   rQ   )graphsubgraphdigraphnodeedgestrictz^[_a-zA-Z][a-zA-Z0-9_,]*$z*^[_a-zA-Z][a-zA-Z0-9_,:"]*[a-zA-Z0-9_,"]+$z	^[0-9,]+$z^([^:]*):([^:]*)$z^".*"$z^<.*>$c                 C   s   | t v rdS dd | D }|r6t| s6t| s6dS tttttfD ]}|| rD dS qDt| }|rt|	dpt|	dS dS )a  Checks whether a string is a dot language ID.

    It will check whether the string is solely composed
    by the characters allowed in an ID or not.
    If the string is one of the reserved keywords it will
    need quotes too but the user will need to add them
    manually.
    Fc                 S   s,   g | ]$}t |d ks t |dkrt |qS )   r   )ord).0crD   rD   rE   
<listcomp>   r   z needs_quotes.<locals>.<listcomp>Tr      )
dot_keywordsid_re_dbl_quotedmatch
id_re_htmlid_re_alpha_nums	id_re_numid_re_alpha_nums_with_portsid_re_with_portneeds_quotesr9   )scharsZtest_remrD   rD   rE   r      s    

r   c                 C   s~   | dkrdS t | tr&| du r"dS dS t | ts4| S | s<| S t| rzdddd	}| D ]\}}| ||} qXd
|  d
 S | S )Nr	   z""TTrueFalsez\"z\nz\r)"
r   )rW   bool
basestringr   rY   replace)r   r   abrD   rD   rE   quote_if_necessary  s     

r   c                 C   s
   t | S )zLoad graph as defined by data in DOT format.

    The data is assumed to be in DOT format. It will
    be parsed and a Dot class will be returned,
    representing the graph.
    )r   Zparse_dot_data)datarD   rD   rE   graph_from_dot_data&  s    r   c                 C   s"   t | d}| }|  t|S )zLoad graph as defined by a DOT file.

    The file is assumed to be in DOT format. It will
    be loaded, parsed and a Dot class will be returned,
    representing the graph.
    rb)rI   readrO   r   )pathfdr   rD   rD   rE   graph_from_dot_file1  s    
r   Fc                 C   s   |rt dd}n
t dd}| D ]p}t|d tr>||d  }n|t|d  }t|d trj||d  }n|t|d  }t||}|| q|S )a<  Creates a basic graph out of an edge list.

    The edge list has to be a list of tuples representing
    the nodes connected by the edge.
    The values can be anything: bool, int, float, str.

    If the graph is undirected by default, it is only
    calculated from one of the symmetric halves of the matrix.
    rz   
graph_typerx   r   r   )DotrW   strEdgeadd_edge)	edge_listnode_prefixdirectedrx   r|   srcdsterD   rD   rE   graph_from_edges@  s    

r   c           
      C   s   d}|rt dd}n
t dd}| D ]f}|sB| |}||d }nd}|}|d }|D ](}	|	rv|t|| ||  |d7 }qV|d7 }q"|S )zCreates a basic graph out of an adjacency matrix.

    The matrix has to be a list of rows of values
    representing an adjacency matrix.
    The values can be anything: bool, int, float, as long
    as they can evaluate to True or False.
    r   rz   r   rx   Nr   )r   indexr   r   )
matrixr   r   Z	node_origrx   rowskiprZ	node_destr   rD   rD   rE   graph_from_adjacency_matrixc  s,    	



r   c                 C   s   |rt dd}n
t dd}| D ]h}g }d}|D ]}|rD|||  |d7 }q.|  t|dkr|t|t|d  ||d   q|s|d |S )zCreates a basic graph out of an incidence matrix.

    The matrix has to be a list of rows of values
    representing an incidence matrix.
    The values can be anything: bool, int, float, as long
    as they can evaluate to True or False.
    rz   r   rx   r   r   r   T)r   r[   sortr3   r   r   absset_simplify)r   r   r   rx   r   nodesr   r{   rD   rD   rE   graph_from_incidence_matrix  s*    	



r   c                 C   s$  d}ddddddd}d}|   } | drF| drF| dd } d}tj| r| D ]}|| rjq\tjtj| |r|rdtj| | d ||< ntj| |||< d}q\tjtj| |d r\|rdtj| |d  d ||< ntj| |d ||< d}q\|r|S d	S d	S )
zUsed by find_graphviz

    path - single directory as a string

    If any of the executables are found, it will return a dictionary
    containing the program names as keys and their paths as values.

    Otherwise returns None
    Fr	   )dotZtwopiZneatoZcircoZfdpZsfdpr   r   Tz.exeN)	strip
startswithendswithrK   r   isdirkeysexistsjoin)r   successprogsZ
was_quotedZprgrD   rD   rE   __find_executables  s<    	 r   c               	      s  t jjdkr2d} d}d}d}d}zddl}|j}|j}|j}W n tyR   Y n0 z.ddl  fdd} fdd	} j	j
j}W n ty   Y n0 |dur2d}d
dg}|D ]}z`|| |d|}|dur||d}	|| |	sW qt j|	d}	t|	}
|
dur|
W   S W n ty(   Y q0  q2qdt jv rrt jd t jD ] }	t|	}
|
durP|
  S qPt jjdkrdt jv rt jt jd ddd}	nd}	t|	}
|
dur|
S dD ] }	t|	}
|
dur|
  S qdS )a}  Locate Graphviz's executables in the system.

    Tries three methods:

    First: Windows Registry (Windows only)
    This requires Mark Hammond's pywin32 is installed.

    Secondly: Search the path
    It will look for 'dot', 'twopi' and 'neato' in all the directories
    specified in the PATH environment variable.

    Thirdly: Default install location (Windows only)
    It will look for 'dot', 'twopi' and 'neato' in the default install
    location under the "Program Files" directory.

    It will return a dictionary containing the program names as keys
    and their paths as values.

    If this fails, it returns None.
    win32l       r   Nr   c              	      s,     d} jj| ||| | |jS )Nr   )c_uintwindlladvapi32ZRegOpenKeyExAbyrefvalue)keysubkeyoptZsamresultctypesrD   rE   RegOpenKeyEx  s
    
z#find_graphviz.<locals>.RegOpenKeyExc              
      sH     d}  d} d} jj| |d || | |jS )Nr   i   )r   create_string_bufferr   r   ZRegQueryValueExAr   r   )hkeyZ	valuenameZ	data_typeZdata_lenr   r   rD   rE   RegQueryValueEx  s    



z&find_graphviz.<locals>.RegQueryValueExzSOFTWARE\ATT\Graphvizz$SOFTWARE\AT&T Research Labs\GraphvizZInstallPathbinPATHZPROGRAMFILESZATTZGraphVizz!C:\Program Files\att\Graphviz\bin)z/usr/binz/usr/local/binz/opt/local/binz/opt/binz/sw/binz
/usr/sharez*/Applications/Graphviz.app/Contents/MacOS/)rK   sysplatformwin32apir   r   RegCloseKeyImportErrorr   r   r   r   r   r   	Exceptionenvironsplitpathsep)HKEY_LOCAL_MACHINEZKEY_QUERY_VALUEr   r   r   r   r   ZpotentialKeysZpotentialKeyr   r   rD   r   rE   find_graphviz  s|    







r   c                   @   sh   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )Commonz|Common information to several classes.

    Should not be directly used, several classes are derived from
    this one.
    c                 C   s   t  | j}|S rT   rX   obj_dict)rf   rU   rD   rD   rE   __getstate__  s    zCommon.__getstate__c                 C   s
   || _ d S rT   r   rf   staterD   rD   rE   __setstate__  s    zCommon.__setstate__c                 C   s   | j d |d}|du r| j d }|dv r0d}|  }|durL||}ndS t|ttfsd|g}|D ]"}|j d |d}|rh|  S qhn|S dS )z)Look for default attributes for this node
attributesNtype)ry   rz   Zclusterrx   )r   getget_parent_graphget_noderW   rZ   r\   )rf   attrattr_valZdefault_node_namegdefaultsdefaultrD   rD   rE   __get_attribute__  s"    

zCommon.__get_attribute__c                 C   s   || j d< d S Nparent_graphr   )rf   r   rD   rD   rE   set_parent_graph  s    zCommon.set_parent_graphc                 C   s   | j dd S r   r   r   rl   rD   rD   rE   r     s    zCommon.get_parent_graphc                 C   s   || j d |< dS )a  Set an attribute value by name.

        Given an attribute 'name' it will set its value to 'value'.
        There's always the possibility of using the methods:

            set_'name'(value)

        which are defined for all the existing attributes.
        r   Nr   )rf   namer   rD   rD   rE   set  s    z
Common.setc                 C   s   | j d |dS )zGet an attribute value by name.

        Given an attribute 'name' it will get its value.
        There's always the possibility of using the methods:

            get_'name'()

        which are defined for all the existing attributes.
        r   Nr   )rf   r   rD   rD   rE   r     s    z
Common.getc                 C   s
   | j d S )r	   r   r   rl   rD   rD   rE   get_attributes  s    zCommon.get_attributesc                 C   s   || j d< d S Nsequencer   rf   seqrD   rD   rE   set_sequence  s    zCommon.set_sequencec                 C   s
   | j d S r   r   rl   rD   rD   rE   get_sequence  s    zCommon.get_sequencec                    sF   |D ]<}  d| |f fdd	   d| |f fdd	 qd S )Nset_c                    s    j d || S )Nr   )r   rr   )xr   rl   rD   rE   <lambda>  r   z1Common.create_attribute_methods.<locals>.<lambda>get_c                    s
     | S rT   )r   )r   rl   rD   rE   r    r   )__setattr__)rf   Zobj_attributesr   rD   rl   rE   create_attribute_methods  s    zCommon.create_attribute_methodsN)rm   rn   ro   __doc__r   r   r   r   r   r   r   r   r  r  r  rD   rD   rD   rE   r     s   (r   c                   @   s    e Zd ZdZdd Zdd ZdS )Errorz"General error handling class.
    c                 C   s
   || _ d S rT   r   rf   r   rD   rD   rE   r]     s    zError.__init__c                 C   s   | j S rT   r  rl   rD   rD   rE   __str__  s    zError.__str__Nrm   rn   ro   r	  r]   r  rD   rD   rD   rE   r
    s   r
  c                   @   s    e Zd ZdZdd Zdd ZdS )InvocationExceptionz`
    To indicate that a ploblem occurred while running any of the GraphViz
    executables.
    c                 C   s
   || _ d S rT   r  r  rD   rD   rE   r]     s    zInvocationException.__init__c                 C   s   | j S rT   r  rl   rD   rD   rE   r    s    zInvocationException.__str__Nr  rD   rD   rD   rE   r  	  s   r  c                   @   sB   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dS )NodezA graph node.

    This class represents a graph's node with all its attributes.

    node(name, attribute=value, ...)

    name: node's name

    All the attributes defined in the Graphviz dot language should
    be supported.
    r	   Nc                 K   s   |d ur|| _ nt | _ t|| j d< d| j d< d | j d< d | j d< d | j d< d }t|tr|ds|d}|d	kr|d
 t|k r|d | ||d   }}t|ttfrt	|}t
|| j d< || j d< | t d S )Nr   r{   r   r   Zparent_node_listr   r   :r   r   r   port)r   rU   rW   r   r   findr3   longintr   r   r  NODE_ATTRIBUTES)rf   r   r   attrsr  idxrD   rD   rE   r]   "  s$    





zNode.__init__c                 C   s   || j d< dS )zSet the node's name.r   Nr   )rf   Z	node_namerD   rD   rE   set_nameG  s    zNode.set_namec                 C   s
   | j d S )zGet the node's name.r   r   rl   rD   rD   rE   get_nameL  s    zNode.get_namec                 C   s
   | j d S )zGet the node's port.r  r   rl   rD   rD   rE   get_portQ  s    zNode.get_portc                 C   sN   | j d dd }|s"|r"|g}n|d}|| d|| j d d< d S )Nr   r6   ,)r   r   r   r[   r   )rf   r6   ZstylesrD   rD   rE   	add_styleV  s    

zNode.add_stylec                 C   s   t | jd }t }t| jd  tddD ]2\}}|durV|d|t |f  q.|| q.|dv rzt|dkrzdS d	|}|r|d
| d 7 }|d S )zEReturns a string representation of the node in dot language.
        r   r   r   r   N%s=%s)rx   r{   r|   r	   ,  [];)	r   r   rZ   rh   rY   r   r[   r3   r   )rf   r{   Z	node_attrr   r   rD   rD   rE   	to_stringa  s    
zNode.to_string)r	   N)
rm   rn   ro   r	  r]   r  r  r  r  r$  rD   rD   rD   rE   r    s   
%r  c                   @   sJ   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dS )r   ax  A graph edge.

    This class represents a graph's edge with all its attributes.

    edge(src, dst, attribute=value, ...)

    src: source node's name
    dst: destination node's name

    All the attributes defined in the Graphviz dot language should
    be supported.

    Attributes can be set through the dynamically generated methods:

     set_[attribute name], i.e. set_label, set_fontname

    or directly by using the instance's special dictionary:

     Edge.obj_dict['attributes'][attribute name], i.e.

        edge_instance.obj_dict['attributes']['label']
        edge_instance.obj_dict['attributes']['fontname']

    r	   Nc                 K   s   t |ttfr|dkr|\}}|d ur.|| _n|t | _t|| jd< d| jd< d | jd< d | jd< d | jd< t |tr~| }t |tr| }t|t|f}|| jd< | t	 d S )	Nr	   r   r|   r   r   Zparent_edge_listr   points)
rW   rZ   r\   r   rU   r  r  r   r  EDGE_ATTRIBUTES)rf   r   r   r   r  r%  rD   rD   rE   r]     s"    






zEdge.__init__c                 C   s   | j d d S )zGet the edges source node name.r%  r   r   rl   rD   rD   rE   
get_source  s    zEdge.get_sourcec                 C   s   | j d d S )z%Get the edge's destination node name.r%  r   r   rl   rD   rD   rE   get_destination  s    zEdge.get_destinationc                 C   s   t t |  t |   S rT   )rg   r'  r(  rl   rD   rD   rE   rj     s    zEdge.__hash__c                 C   s   t |tstd|   dkrh|  | krB|  | ksb| |  kr| |  krdS n$|  | kr|  | krdS dS )a)  Compare two edges.

        If the parent graph is directed, arcs linking
        node A to B are considered equal and A->B != B->A

        If the parent graph is undirected, any edge
        connecting two nodes is equal to any other
        edge connecting the same nodes, A->B == B->A
        z,Can't compare and edge to a non-edge object.rx   TF)rW   r   r
  r   get_top_graph_typer'  r(  )rf   r|   rD   rD   rE   __eq__  s     
zEdge.__eq__c                 C   s   t |ts|S |dr&|dr&|S |d}|dkrX|d dkrX||d  dkrX|S |dkr|d | }||d d  }t|}|dt| 7 }|S |S )Nr   r  r   r   )rW   r   r   r   rfindr   )rf   Znode_strZnode_port_idxr   r   r{   rD   rD   rE   parse_node_ref  s     

zEdge.parse_node_refc                 C   s`  |  |  }|  |  }t|tr8t|d g}n t|ttfrRt	|g}n|g}| 
 r| 
  r| 
  dkr|d n
|d t|tr|t|d  n(t|ttfr|t	| n
|| t }t| jd  tddD ]4\}}|dur$|d	|t|f  q|| qd
|}|rR|d| d  d|d S )zEReturns a string representation of the edge in dot language.
        r   rz   z->z--r   r   r  Nr  r   r!  r"   r#  )r,  r'  r(  rW   rQ   Subgraphr$  r  r  r   r   r)  r[   rZ   rh   r   rY   r   r   r   )rf   r   r   r|   Z	edge_attrr   r   rD   rD   rE   r$    s>    






zEdge.to_string)r	   r	   N)rm   rn   ro   r	  r]   r'  r(  rj   r*  r,  r$  rD   rD   rD   rE   r     s   
! r   c                   @   s8  e Zd ZdZdNddZdd	 Zd
d Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ ZdOd0d1Zd2d3 Zd4d5 Zd6d7 Zd8d9 ZdPd:d;ZdQd<d=Zd>d? Z d@dA Z!dBdC Z"dDdE Z#dFdG Z$dHdI Z%dJdK Z&dLdM Z'dS )RGrapha8  Class representing a graph in Graphviz's dot language.

    This class implements the methods to work on a representation
    of a graph in Graphviz's dot language.

    graph(graph_name='G', graph_type='digraph',
        strict=False, suppress_disconnected=False, attribute=value, ...)

    graph_name:
        the graph's name
    graph_type:
        can be 'graph' or 'digraph'
    suppress_disconnected:
        defaults to False, which will remove from the
        graph any disconnected nodes.
    simplify:
        if True it will avoid displaying equal edges, i.e.
        only one edge between two nodes. removing the
        duplicated ones.

    All the attributes defined in the Graphviz dot language should
    be supported.

    Attributes can be set through the dynamically generated methods:

     set_[attribute name], i.e. set_size, set_fontname

    or using the instance's attributes:

     Graph.obj_dict['attributes'][attribute name], i.e.

        graph_instance.obj_dict['attributes']['label']
        graph_instance.obj_dict['attributes']['fontname']
    GNrz   Fc                 K   s   |d ur|| _ nt | _ t|| j d< |dvr:td| t|| j d< || j d< || j d< || j d< || j d< d	| j d
< t | j d< t | j d< t | j d< | |  | t d S )Nr   )rx   rz   zEInvalid type "%s". Accepted graph types are: graph, digraph, subgraphr   r   r}   suppress_disconnectedsimplifyr   current_child_sequencer   edges	subgraphs)r   rU   r
  r   r   r  GRAPH_ATTRIBUTES)rf   
graph_namer   r   r}   r1  r2  r  rD   rD   rE   r]   W  s*    





zGraph.__init__c                 C   s
   | j d S Nr   r   rl   rD   rD   rE   get_graph_typey  s    zGraph.get_graph_typec                 C   s&   | }|  }||krq|}q|jd S r8  )r   r   )rf   parentZparent_rD   rD   rE   r)  |  s    zGraph.get_top_graph_typec                 K   s   |  tdi | d S )Nrx   )rx   add_noder  rf   r  rD   rD   rE   set_graph_defaults  s    zGraph.set_graph_defaultsc                 K   s.   |  d}t|ttfr&dd |D S | S )Nrx   c                 S   s   g | ]}|  qS rD   r   r   r{   rD   rD   rE   r     r   z,Graph.get_graph_defaults.<locals>.<listcomp>r   rW   rZ   r\   r   rf   r  Zgraph_nodesrD   rD   rE   get_graph_defaults  s    
zGraph.get_graph_defaultsc                 K   s   |  tdi | d S )Nr{   )r{   r;  r=  rD   rD   rE   set_node_defaults  s    zGraph.set_node_defaultsc                 K   s.   |  d}t|ttfr&dd |D S | S )Nr{   c                 S   s   g | ]}|  qS rD   r?  r@  rD   rD   rE   r     r   z+Graph.get_node_defaults.<locals>.<listcomp>rA  rB  rD   rD   rE   get_node_defaults  s    
zGraph.get_node_defaultsc                 K   s   |  tdi | d S )Nr|   )r|   r;  r=  rD   rD   rE   set_edge_defaults  s    zGraph.set_edge_defaultsc                 K   s.   |  d}t|ttfr&dd |D S | S )Nr|   c                 S   s   g | ]}|  qS rD   r?  r@  rD   rD   rE   r     r   z+Graph.get_edge_defaults.<locals>.<listcomp>rA  rB  rD   rD   rE   get_edge_defaults  s    
zGraph.get_edge_defaultsc                 C   s   || j d< dS )zSet whether to simplify or not.

        If True it will avoid displaying equal edges, i.e.
        only one edge between two nodes. removing the
        duplicated ones.
        r2  Nr   )rf   r2  rD   rD   rE   r     s    zGraph.set_simplifyc                 C   s
   | j d S )z]Get whether to simplify or not.

        Refer to set_simplify for more information.
        r2  r   rl   rD   rD   rE   get_simplify  s    zGraph.get_simplifyc                 C   s   || j d< dS )z+Set the graph's type, 'graph' or 'digraph'.r   Nr   )rf   r   rD   rD   rE   set_type  s    zGraph.set_typec                 C   s
   | j d S )z+Get the graph's type, 'graph' or 'digraph'.r   r   rl   rD   rD   rE   get_type  s    zGraph.get_typec                 C   s   || j d< dS )zSet the graph's name.r   Nr   )rf   r7  rD   rD   rE   r    s    zGraph.set_namec                 C   s
   | j d S )zGet the graph's name.r   r   rl   rD   rD   rE   r    s    zGraph.get_namec                 C   s   || j d< dS )z]Set graph to 'strict' mode.

        This option is only valid for top level graphs.
        r}   Nr   rf   valrD   rD   rE   
set_strict  s    zGraph.set_strictc                 C   s
   | j d S )zjGet graph's 'strict' mode (True, False).

        This option is only valid for top level graphs.
        r}   r   rK  rD   rD   rE   
get_strict  s    zGraph.get_strictc                 C   s   || j d< dS )zSuppress disconnected nodes in the output graph.

        This option will skip nodes in the graph with no incoming or outgoing
        edges. This option works also for subgraphs and has effect only in the
        current graph/subgraph.
        r1  Nr   rK  rD   rD   rE   set_suppress_disconnected  s    zGraph.set_suppress_disconnectedc                 C   s
   | j d S )zoGet if suppress disconnected is set.

        Refer to set_suppress_disconnected for more information.
        r1  r   rK  rD   rD   rE   get_suppress_disconnected  s    zGraph.get_suppress_disconnectedc                 C   s    | j d }| j d  d7  < |S )Nr3  r   r   r   rD   rD   rE   get_next_sequence_number  s    
zGraph.get_next_sequence_numberc                 C   s   t |tstdt|| | }|sT|jg| jd | < || 	  n| jd |  
|j ||   dS )zxAdds a node object to the graph.

        It takes a node object as its only argument and returns
        None.
        z/add_node() received a non node class object: {}r   N)rW   r  r@   formatr   r   r  r   r   r   r[   r  rQ  )rf   Z
graph_noder{   rD   rD   rE   r<    s    
zGraph.add_nodec                 C   sf   t |tr| }|| jd v rb|durR|t| jd | k rR| jd | |= dS | jd |= dS dS )aP  Delete a node from the graph.

        Given a node's name all node(s) with that same name
        will be deleted if 'index' is not specified or set
        to None.
        If there are several nodes with that same name and
        'index' is given, only the node in that position
        will be deleted.

        'index' should be an integer specifying the position
        of the node to delete. If index is larger than the
        number of nodes with that name, no action is taken.

        If nodes are deleted it returns True. If no action
        is taken it returns False.
        r   NTF)rW   r  r  r   r3   )rf   r   r   rD   rD   rE   del_node  s    
zGraph.del_nodec                 C   s6   t  }|| jd v r2|dd | jd | D  |S )a  Retrieve a node from the graph.

        Given a node's name the corresponding Node
        instance will be returned.

        If one or more nodes exist with that name a list of
        Node instances is returned.
        An empty list is returned otherwise.
        r   c                 S   s   g | ]}t |d qS r   r  )r   r   rD   rD   rE   r   ?  s   z"Graph.get_node.<locals>.<listcomp>)rZ   r   extend)rf   r   r   rD   rD   rE   r   1  s    
zGraph.get_nodec                 C   s   |   S )zGet the list of Node instances.)get_node_listrl   rD   rD   rE   	get_nodesG  s    zGraph.get_nodesc                 C   s6   t  }| jd  D ]\}}|dd |D  q|S )z}Get the list of Node instances.

        This method returns the list of Node instances
        composing the graph.
        r   c                 S   s   g | ]}t |d qS rT  rU  r   Zobj_drD   rD   rE   r   V  s   z'Graph.get_node_list.<locals>.<listcomp>rZ   r   rY   rV  )rf   Z	node_objsr{   obj_dict_listrD   rD   rE   rW  L  s    

zGraph.get_node_listc                 C   s   t |tstdt|| | f}|| jd v rV| jd | }||j n|jg| jd |< |	| 
  ||   dS )zyAdds an edge object to the graph.

        It takes a edge object as its only argument and returns
        None.
        z/add_edge() received a non edge class object: {}r4  N)rW   r   r@   rR  r   r'  r(  r   r[   r  rQ  r   r   )rf   Z
graph_edgeedge_pointsr   rD   rD   rE   r   ^  s    
zGraph.add_edgec                 C   s   t |ttfr2|dur(t |ttfr(|}|\}}n
|| }}t |trN| }t |tr`| }||f| jd v r|dur|t| jd ||f k r| jd ||f |= dS | jd ||f= dS dS )aK  Delete an edge from the graph.

        Given an edge's (source, destination) node names all
        matching edges(s) will be deleted if 'index' is not
        specified or set to None.
        If there are several matching edges and 'index' is
        given, only the edge in that position will be deleted.

        'index' should be an integer specifying the position
        of the edge to delete. If index is larger than the
        number of matching edges, no action is taken.

        If edges are deleted it returns True. If no action
        is taken it returns False.
        Nr4  TF)	rW   rZ   r\   r  r  r  r  r   r3   )rf   src_or_listr   r   r   rD   rD   rE   del_edgew  s$    



zGraph.del_edgec                 C   s   t |ttfr0|du r0t|}|d |d f}n||f}||f}t }|| jd v sn|  dkr|| jd v r| jd || jd |d}|D ] }|t|d |d |d q|S )a7  Retrieved an edge from the graph.

        Given an edge's source and destination the corresponding
        Edge instance(s) will be returned.

        If one or more edges exist with that source and destination
        a list of Edge instances is returned.
        An empty list is returned otherwise.
        Nr   r   r4  rx   r   )rW   rZ   r\   r   r)  r   r[   r   )rf   r]  r   r\  Zedge_points_reverser   Zedges_obj_dictZedge_obj_dictrD   rD   rE   get_edge  s,    


zGraph.get_edgec                 C   s   |   S rT   )get_edge_listrl   rD   rD   rE   	get_edges  s    zGraph.get_edgesc                 C   s6   t  }| jd  D ]\}}|dd |D  q|S )z}Get the list of Edge instances.

        This method returns the list of Edge instances
        composing the graph.
        r4  c                 S   s   g | ]}t |d qS rT  )r   rY  rD   rD   rE   r     s   z'Graph.get_edge_list.<locals>.<listcomp>rZ  )rf   Z	edge_objsr|   r[  rD   rD   rE   r`    s    

zGraph.get_edge_listc                 C   s   t |ts&t |ts&tdt|| | jd v rX| jd |  }||j n|jg| jd | < |	| 
  ||   dS )zAdds an subgraph object to the graph.

        It takes a subgraph object as its only argument and returns
        None.
        z4add_subgraph() received a non subgraph class object:r5  N)rW   r.  Clusterr@   rR  r   r  r   r[   r  rQ  r   r   )rf   sgraphZsgraph_listrD   rD   rE   add_subgraph  s    
zGraph.add_subgraphc                 C   sB   t  }|| jd v r>| jd |}|D ]}|t|d q(|S )a'  Retrieved a subgraph from the graph.

        Given a subgraph's name the corresponding
        Subgraph instance will be returned.

        If one or more subgraphs exist with the same name, a list of
        Subgraph instances is returned.
        An empty list is returned otherwise.
        r5  r   )rZ   r   r   r[   r.  )rf   r   r   Zsgraphs_obj_dictr[  rD   rD   rE   get_subgraph  s    zGraph.get_subgraphc                 C   s   |   S rT   )get_subgraph_listrl   rD   rD   rE   get_subgraphs	  s    zGraph.get_subgraphsc                 C   s6   t  }| jd  D ]\}}|dd |D  q|S )z~Get the list of Subgraph instances.

        This method returns the list of Subgraph instances
        in the graph.
        r5  c                 S   s   g | ]}t |d qS rT  )r.  rY  rD   rD   rE   r     s   z+Graph.get_subgraph_list.<locals>.<listcomp>rZ  )rf   Zsgraph_objsrc  r[  rD   rD   rE   rf    s    

zGraph.get_subgraph_listc                 C   s   || j d< | j d  D ]}|D ]}||d< q q| j d  D ]}|D ]}||d< qFq>| j d  D ]}|D ]}t|d| qlqdd S )Nr   r   r4  r5  r   )r   valuesr/  r   )rf   r   obj_listrC   rD   rD   rE   r     s    
zGraph.set_parent_graphc                 C   s  t  }| jdddur8| |  kr8| jd r8|d | jd dkrrd| jv rf| jd rf|d q|d n|d	| jd
 | jd  t| jd  tddD ]<\}}|dur|d|t	|f  n
|| |d qt
 }t  }| jd  D ]}|| q|rHt tdd |D  \}}t
|t
| }}nt
 t
  }}t  }	| jd  D ]}|	| qjt  }
| jd  D ]}|
| qtdd ||	 |
 D }|D ]\}}|d
 dkr$t|d}| jddr| |vr| |vrq|| d  np|d
 dkrxt|d}| jddrZ||v rZq|| d  || nt|d}|| d  q|d d|S )zReturns a string representation of the graph in dot language.

        It will return the graph and all its subelements in string from.
        r}   Nzstrict r   r	   Zshow_keywordzsubgraph {
z{
z	{} {} {{
r   r   r   r  r  z;
r4  c                 S   s   g | ]}|d  qS )r%  rD   r   rC   rD   rD   rE   r   Z  r   z#Graph.to_string.<locals>.<listcomp>r   r5  c                 S   s   g | ]}|d  |fqS )r   rD   rj  rD   rD   rE   r   h  s   r{   r   r1  Fr   r|   r2  z}
)rZ   r   r   r   r[   rR  rh   rY   r   r   r   rh  rV  zipr  r  r$  r   addr.  r   )rf   rx   r   r   Z
edges_doneZedge_obj_dictsr   Zedge_src_setZedge_dst_setZnode_obj_dictsZsgraph_obj_dictsZsgri  r  rC   r{   r|   rc  rD   rD   rE   r$  .  s|    








zGraph.to_string)r0  Nrz   FFF)N)NN)N)(rm   rn   ro   r	  r]   r9  r)  r>  rC  rD  rE  rF  rG  r   rH  rI  rJ  r  r  rM  rN  rO  rP  rQ  r<  rS  r   rX  rW  r   r^  r_  ra  r`  rd  re  rg  rf  r   r$  rD   rD   rD   rE   r/  3  sN   $  
"
	



)
%r/  c                   @   s   e Zd ZdZdddZdS )r.  ah  Class representing a subgraph in Graphviz's dot language.

    This class implements the methods to work on a representation
    of a subgraph in Graphviz's dot language.

    subgraph(
        graph_name='subG', suppress_disconnected=False, attribute=value, ...
    )

    graph_name:
        the subgraph's name
    suppress_disconnected:
        defaults to false, which will remove from the
        subgraph any disconnected nodes.
    All the attributes defined in the Graphviz dot language should
    be supported.

    Attributes can be set through the dynamically generated methods:

     set_[attribute name], i.e. set_size, set_fontname

    or using the instance's attributes:

     Subgraph.obj_dict['attributes'][attribute name], i.e.

        subgraph_instance.obj_dict['attributes']['label']
        subgraph_instance.obj_dict['attributes']['fontname']
    r	   NFc                 K   s2   t j| f||||d| |d u r.d| jd< d S )Nr7  r   r1  r2  ry   r   )r/  r]   r   rf   r7  r   r1  r2  r  rD   rD   rE   r]     s    zSubgraph.__init__)r	   NFFrm   rn   ro   r	  r]   rD   rD   rD   rE   r.    s   !  r.  c                   @   s   e Zd ZdZdddZdS )rb  a  Class representing a cluster in Graphviz's dot language.

    This class implements the methods to work on a representation
    of a cluster in Graphviz's dot language.

    cluster(
        graph_name='subG', suppress_disconnected=False, attribute=value, ...
    )

    graph_name:
        the cluster's name (the string 'cluster' will be always prepended)
    suppress_disconnected:
        defaults to false, which will remove from the
        cluster any disconnected nodes.
    All the attributes defined in the Graphviz dot language should
    be supported.

    Attributes can be set through the dynamically generated methods:

     set_[attribute name], i.e. set_color, set_fontname

    or using the instance's attributes:

     Cluster.obj_dict['attributes'][attribute name], i.e.

        cluster_instance.obj_dict['attributes']['label']
        cluster_instance.obj_dict['attributes']['fontname']
    subGNFc                 K   sJ   t j| f||||d| |d u r<d| jd< d| | jd< | t d S )Nrm  ry   r   Zcluster_r   )r/  r]   r   r  CLUSTER_ATTRIBUTESrn  rD   rD   rE   r]     s    
zCluster.__init__)rp  NFFro  rD   rD   rD   rE   rb    s
      rb  c                   @   sT   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dddZ
dddZdS )r   zA container for handling a dot language file.

    This class implements methods to write and process
    a dot language file. It is a derived class of
    the base class 'Graph'.
    c                    s   t j g|R i | t  _d  _g d _d _ jD ]8} d| | jf fdd	  jd|  }d|_	q< jdg D ]8} d| | jf fd	d	  jd|  }d
|_	qd S )N)$ZcanonZcmapZcmapxZcmapx_npZdiar   ZfiggdZgd2ZgifZhpglimapZimap_npZismapZjpeZjpegZjpgZmifmpZpclZpdfZpicplainz	plain-extZpngpsZps2ZsvgZsvgzZvmlZvmlzZvrmlZvtxZwbmpZxdotZxlibr   Zcreate_c                    s    j | |dS N)rR  prog)create)frx  rl   rD   rE   r    r   zDot.__init__.<locals>.<lambda>zLRefer to the docstring accompanying the'create' method for more information.rawZwrite_c                    s    j | ||dS rw  )rH   )r   rz  rx  rl   rD   rE   r    s    zKRefer to the docstring accompanying the'write' method for more information.)
r/  r]   rZ   shape_filesr   formatsrx  r  __dict__r	  )rf   ZargslZargsdZfrmtrz  rD   rl   rE   r]     s.    

zDot.__init__c                 C   s   t  | jS rT   r   rl   rD   rD   rE   r     s    zDot.__getstate__c                 C   s
   || _ d S rT   r   r   rD   rD   rE   r     s    zDot.__setstate__c                 C   s4   t |tr| j| t |ttfr0| j| dS )a  Add the paths of the required image files.

        If the graph needs graphic objects to be used as shapes or otherwise
        those need to be in the same folder as the graph is going to be
        rendered from. Alternatively the absolute path to the files can be
        specified when including the graphics in the graph.

        The files in the location pointed to by the path(s) specified as
        arguments to this method will be copied to the same temporary location
        where the graph is going to be rendered.
        N)rW   r   r|  r[   rZ   r\   rV  )rf   Z
file_pathsrD   rD   rE   set_shape_files!  s    
zDot.set_shape_filesc                 C   s
   || _ dS )zSets the default program.

        Sets the default program in charge of processing
        the dot file into a graph.
        N)rx  )rf   rx  rD   rD   rE   set_prog4  s    zDot.set_progc                 C   s
   || _ dS )a  
        This method allows to manually specify the location of the GraphViz
        executables.

        The argument to this method should be a dictionary where the keys are
        as follows:

            {'dot': '', 'twopi': '', 'neato': '', 'circo': '', 'fdp': ''}

        and the values are the paths to the corresponding executable,
        including the name of the executable itself.
        N)r   )rf   pathsrD   rD   rE   set_graphviz_executables<  s    zDot.set_graphviz_executablesNr{  c                 C   s   |du r| j }t|d\}}z|dkr|  }t|tr^t|ts^zt|d}W n   Y n0 z"|  }trp|std}||}W n   tr|d}Y n0 |	| n|	| 
|| W |r|  n|r|  0 dS )a[  
        Given a filename 'path' it will open/create and truncate
        such file and write on it a representation of the graph
        defined by the dot object and in the format specified by
        'format'. 'path' can also be an open file-like object, such as
        a StringIO instance.

        The format 'raw' is used to dump the string representation
        of the Dot object, without further processing.
        The output can be processed by any of graphviz tools, defined
        in 'prog', which defaults to 'dot'
        Returns True or False according to the success of the write
        operation.

        There's also the preferred possibility of using:

            write_'format'(path, prog='program')

        which are automatically defined for all the supported formats.
        [write_ps(), write_gif(), write_dia(), ...]

        Nzw+br{  zutf-8T)rx  rP   r$  rW   r   unicodeget_charsetPY3encoderH   ry  rO   )rf   r   rx  rR  rN   rO   r   r   rD   rD   rE   rH   L  s8    




z	Dot.writerv  c              	   C   s`  |du r| j }t|ttfr4|d |dd  }}ng }| jdu r\t | _| jdu r\td|| jvrrtd| tj	| j| rtj
| j| std| j| t \}}t| | | tj|}| jD ]L}t|d}| }	|  ttj|tj|d}||	 |  q| j| d	| |g| }
tj|
|tjtjd
}|j}|j}t }| }|s|q|| qj|  t|}|jst }| }|sq|| q|  |rt|}tr|t jj!}|" }|dkrtd||f n|r(t#| | jD ]"}t$tj|tj| q.t$| |S )a!  Creates and returns a Postscript representation of the graph.

        create will write the graph to a temporary dot file and process
        it with the program given by 'prog' (which defaults to 'twopi'),
        reading the Postscript output and returning it as a string is the
        operation is successful.
        On failure None is returned.

        There's also the preferred possibility of using:

            create_'format'(prog='program')

        which are automatically defined for all the supported formats.
        [create_ps(), create_gif(), create_dia(), ...]

        If 'prog' is a list instead of a string the fist item is expected
        to be the program name, followed by any optional command-line
        arguments for it:

            ['twopi', '-Tdot', '-s10']
        Nr   r   z GraphViz's executables not foundz$GraphViz's executable "%s" not foundz9GraphViz's executable "{}" is not a file or doesn't existr   wbz-T)cwdstderrstdoutz6Program terminated with status: %d. stderr follows: %s)%rx  rW   rZ   r\   r   r   r  rK   r   r   isfilerR  tempfilemkstemprO   rH   dirnamer|  rI   r   r   basename
subprocessPopenPIPEr  r  r[   NULL_SEPclosedr  decoder   encodingwaitprintunlink)rf   rx  rR  r_   Ztmp_fdZtmp_nameZtmp_dirZimgrz  Zf_dataZcmdlinepr  r  Zstdout_outputr   Zstderr_outputstatusrD   rD   rE   ry    s    












 
z
Dot.create)Nr{  )Nrv  )rm   rn   ro   r	  r]   r   r   r  r  r  rH   ry  rD   rD   rD   rE   r     s   )
9r   )rG   )r	   F)r	   F)r	   F)=r	  
__future__r   r   rK   rer  r   r  rX   operatorr   r	   r   version_infor  r  r   r   r  r  r  r   r6  r&  r  rq  rF   rP   rU   rQ   r   compileUNICODEr   r   r   r   Sr   r   r   r   r   r   r   r   r   r   r   objectr   r   r
  r  r  r   r/  r.  rb  r   rD   rD   rD   rE   <module>   sp   	
.1$
#
'
'8 |
l 3    [/1