B
    É1`q  ã               @   s  d Z ddlZddlZddlZddlmZ ddlZddlZddlm	Z	 e 
d¡ejdd„ ƒƒZG dd	„ d	eƒ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e d¡ejdddd�ejddd d�e d!¡e d"¡ejd#d$„ ƒƒƒƒƒƒZd%d&„ Zd'ek�reƒ  dS )(z+
Fixme: make this into a proper click main
é    N)Údefaultdict)ÚunitsÚpgraphc             C   s   dS )z.
    Wire Cell Signal Processing Features
    N© )Úctxr   r   ú,/wcdo/src/wct/python/wirecell/pgraph/main.pyÚcli   s    r   c               @   s:   e Zd Zdd„ Zedd„ ƒZdd„ Zddd	„Zd
d„ ZdS )ÚNodec             K   sh   |st d| ƒ || _| d¡}|d | _y|d | _W n tk
rR   d| _Y nX ttƒ| _|| _	d S )NzNode(%s) with no attributesú:r   é   Ú )
ÚprintÚtnÚsplitÚtypeÚnameÚ
IndexErrorr   ÚsetÚportsÚattrs)Úselfr   r   r   r   r   Ú__init__   s    


zNode.__init__c             C   s   | j rd| j  S dS )Nz[%s]z	(unnamed))r   )r   r   r   r   Údisplay_name%   s    
zNode.display_namec             C   s   | j |  |¡ dS )zH
        Add a port of end "head" or "tail" and ident (number).
        N)r   Úadd)r   ÚendÚidentr   r   r   Úadd_port+   s    zNode.add_portNc             C   s   | j  dd¡S )Nr
   Ú_)r   Úreplace)r   Úportr   r   r   Údot_name1   s    zNode.dot_namec             C   s  t ƒ }d| jkr>dd dd„ t| jd ƒD ƒ¡f }| |¡ | j| jg}x\t| j ¡ ƒD ]J\}}t	|t ƒrxdt
|ƒ }t	|tƒrŽdt
|ƒ }d||f }| |¡ qZW d	 |¡}d| }| |¡ d
| jkrüdd dd„ t| jd
 ƒD ƒ¡f }| |¡ dd |¡f S )NÚheadz{%s}ú|c             S   s   g | ]}d ||f ‘qS )z<in%d>%dr   )Ú.0Únumr   r   r   ú
<listcomp>7   s    z"Node.dot_label.<locals>.<listcomp>zlist(%d)zdict(%d)z%s = %sz\nÚtailc             S   s   g | ]}d ||f ‘qS )z	<out%d>%dr   )r#   r$   r   r   r   r%   G   s    )Úlistr   ÚjoinÚsortedÚappendr   r   r   ÚitemsÚ
isinstanceÚlenÚdict)r   Úretr!   ÚbodyÚkÚvÚoner&   r   r   r   Ú	dot_label4   s&    
$





$
zNode.dot_label)N)	Ú__name__Ú
__module__Ú__qualname__r   Úpropertyr   r   r    r4   r   r   r   r   r	      s
   
r	   c             C   s   t | ƒt dƒt dƒgkS )Nr   )r   )Úxr   r   r   Ú	is_stringM   s    r:   c             C   s   t | ƒtgkS )N)r   r'   )r9   r   r   r   Úis_listO   s    r;   c             C   s   t | ƒsdS ttt| ƒƒS )NF)r;   ÚallÚmapr:   )r9   r   r   r   Úis_list_of_stringQ   s     r>   c          	      s”  t ƒ ‰‡ ‡fdd„}tƒ }xJ| D ]B}||dƒ\}}||dƒ\}}d| ¡ || ¡ |f }	| |	¡ q W xºtˆ ¡ ƒD ]ª\}
}x |j ¡ D ]’\}}d}t|ƒr¢|g}t|ƒr®|}|s´qˆxd|D ]\}|ˆ krÈqºˆ |d¡}|dkrøt	|fˆ  |i ¡Ž}|ˆ|< d| ¡ | ¡ f }	| |	¡ qºW qˆW qtW dd	d
g}x4t
ˆ ¡ ƒD ]$\}}| d| ¡ | ¡ f ¡ �q:W x|D ]}	| d|	 ¡ �qhW | d¡ d |¡S )zh
    Return GraphViz text.  If attrs is a dictionary, append to the
    node a list of its items.  
    c          	      sn   | | d }yˆ| }W n0 t k
rH   t|fˆ  |i ¡Ž}|ˆ|< Y nX | |  dd¡}| ||¡ ||fS )NÚnoder   r   )ÚKeyErrorr	   Úgetr   )Úedger   r   ÚnÚp)r   Únodesr   r   rA   \   s    zdotify.<locals>.getr&   r!   z"%s":out%d -> "%s":in%dNz%"%s" -> "%s"[style=dashed,color=gray]zdigraph pgraph {zrankdir=LR;z	node[shape=record];z	"%s"[label="%s"];z	%s;Ú}Ú
)r.   r'   r    r*   r+   r   r:   r>   rA   r	   r)   r4   r(   )Zedge_datr   rA   ÚedgesrB   ÚtÚtpÚhZhpÚer   rC   r1   r2   ZtocheckÚmaybeZcnr/   Únnr?   r   )r   rE   r   ÚdotifyU   sF    

 

rO   c          	   C   st   |st dƒ‚|d dkr|}ntj | |¡}|d dkr@t dƒ‚tj |¡sT|d fS t|ƒ�}|| ¡ fS Q R X d S )Nz$Got invalid filename (empty string).r   ú/éÿÿÿÿzAttempted to import a directory)ÚRuntimeErrorÚosÚpathr(   ÚisfileÚopenÚread)rT   ÚrelÚ	full_pathÚfr   r   r   Újsonnet_try_path‘   s    
r[   c          	   C   sj   | gt j dd¡ d¡ }xB|D ]:}yt||ƒ\}}W n tk
rL   w Y nX |r ||fS q W tdƒ‚d S )NZWIRECELL_PATHr   r
   zFile not found)rS   ÚenvironrA   r   r[   rR   )rT   rX   ÚpathsrM   rY   Úcontentr   r   r   Újsonnet_import_callback¡   s    
r_   c          	   C   sL   |  d¡}x<|D ]4}|sP yt|ƒ}W n tk
r:   Y nX | | } qW | S )z¯
    Select out a part of obj based on a "."-separated path.  Any
    element of the path that looks like an integer will be cast to
    one assuming it indexes an array.
    Ú.)r   ÚintÚ
ValueError)ÚobjÚjpathr3   r   r   r   Úresolve_path®   s    

re   c             C   sv   t ƒ }xj| D ]b}t|ƒt kr*tt|ƒ|ƒ |d }d|kr^|d r^t|d ƒ |d|d  7 }| di ¡||< qW |S )zo
    Given a list of nodes, return a dictionary of their "data" entries
    keyed by 'type' or 'type:name'
    r   r   r
   Údata)r.   r   r   rA   )Úusesr/   r3   r   r   r   r   Úuses_to_paramsÀ   s    
rh   z--jpathr   z@A dot-delimited path into the JSON to locate a graph-like object)ÚdefaultÚhelpz--params/--no-paramsTzDEnable/disable the inclusion of contents of configuration parametersz	json-filezout-filec             C   s(  |  d¡r"ddl}|j|td�}nt|ƒ ¡ }t |¡}yt||ƒ}W n, t	k
rr   t
 d| ¡ t d¡ Y nX | dd¡d	krªtd
|t|ƒf ƒ |d d }	|}
n|d }	| dtƒ ¡}
tƒ }|rÒt|
ƒ}t|	|ƒ}tj |¡d dd… }d||f }tj|dtjd�}|j| d¡d� dS )a  Convert a WCT JSON cfg file to a GraphViz dot file.

    The JSON file needs to at least contain a list of edges found at
    the given jpath.  Use, eg, "-1" to locate the last element of a
    configuration sequence which is typically the config for a
    Pgrapher.  If indeed it is, its [jpath].data.edges attribution
    will be located and the overall JSON data structure will be used
    as a list of nodes.  Otherwise [jpath].edges will be used and
    [jpath].uses will be used to provide an initial list of node
    objects.

    Example bash command using a full job config run from
    wire-cell-toolkit/ source:

    $ jsonnet -J cfg mycfg.jsonnet > mycfg.json

    $ wirecell-pgraph dotify --jpath=-1 mycfg.json mycfg.dot

    $ dot -Tpdf -o mycfg.pdf mycfg.dot

    z.jsonnetr   N)Zimport_callbackz'failed to resolve path "%s" in object:
r   r   r   ZPgrapherz2Pgrapher object found at jpath: "%s" with %d nodesrf   rH   rg   zdot -T %s -o %sT)ÚshellÚstdinzutf-8)Úinput)ÚendswithÚ_jsonnetZevaluate_filer_   rV   rW   ÚjsonÚloadsre   Ú	ExceptionÚclickZechoÚsysÚexitrA   r   r-   r'   r.   rh   rO   rS   rT   ÚsplitextÚ
subprocessÚPopenÚPIPEÚcommunicateÚencode)r   rd   ÚparamsZ	json_fileÚout_filero   ZjtextZdatZcfgrH   rg   r   ZdtextÚextÚdotÚprocr   r   r   Ú
cmd_dotifyÐ   s2    


r�   c               C   s   t tƒ d� d S )N)rc   )r   r.   r   r   r   r   Úmain  s    r‚   Ú__main__)Ú__doc__rS   rt   rp   Úcollectionsr   rw   rs   Úwirecellr   ÚgroupZpass_contextr   Úobjectr	   r:   r;   r>   rO   r[   r_   re   rh   ZcommandÚoptionZargumentr�   r‚   r5   r   r   r   r   Ú<module>   s:   7<9
