B
    )`+D                 @   s   d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZe	dZ
e	dZe	dZe	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dd Zdd Zd d! Zd"d# Zd$d% Zd&d' ZdS )(z7Command parsing module for TensorFlow Debugger (tfdbg).    )absolute_import)division)print_functionNz
\[[^\]]*\]z(\"[^\"]*\"|\'[^\']*\')z\s+z'[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	Intervalz5Represents an interval between a start and end value.c             C   s   || _ || _|| _|| _d S )N)startstart_includedendend_included)selfr   r   r   r	    r   Y/home/dcms/DCMS/lib/python3.7/site-packages/tensorflow/python/debug/cli/command_parser.py__init__$   s    zInterval.__init__c             C   s@   || j k s|| j kr| jsdS || jks8|| jkr<| js<dS dS )NFT)r   r   r   r	   )r
   valuer   r   r   contains*   s
    zInterval.containsc             C   s0   | j |j ko.| j|jko.| j|jko.| j|jkS )N)r   r   r   r	   )r
   otherr   r   r   __eq__1   s    zInterval.__eq__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   !   s   r   c                s   |   } | sg S dd t| D }dd t| D }dd t| D }|sV| gS g }d}x|t| dfg D ]p\ }t fdd|| D sr| |  }|d	r|d	s|d
r|d
r|dd }|	| |}qrW |S )aj  Parse command string into a list of arguments.

  - Disregards whitespace inside double quotes and brackets.
  - Strips paired leading and trailing double quotes in arguments.
  - Splits the command at whitespace.

  Nested double quotes and brackets are not handled.

  Args:
    command: (str) Input command.

  Returns:
    (list of str) List of arguments.
  c             S   s   g | ]}|  qS r   )span).0fr   r   r   
<listcomp>L   s    z!parse_command.<locals>.<listcomp>c             S   s   g | ]}|  qS r   )r   )r   r   r   r   r   r   M   s    c             S   s   g | ]}|  qS r   )r   )r   r   r   r   r   r   O   s    r   Nc             3   s.   | ]&}|d     k o |d k n  V  qdS )r      Nr   )r   interval)r   r   r   	<genexpr>Z   s   z parse_command.<locals>.<genexpr>"'r   )
strip_BRACKETS_PATTERNfinditer_QUOTES_PATTERN_WHITESPACE_PATTERNlenany
startswithendswithappend)commandZbrackets_intervalsZquotes_intervalsZwhitespaces_intervals	argumentsZidx0r   argumentr   )r   r   parse_command8   s(    
r-   c             C   s  | r| d  drtdn| r| d dryLt| d  t| dkr^| d dr^d}n| d dd }| dd } W n0 tk
r   | d dd }| dd } Y nX nt| dkr| d dkr| d }| dd } n| rV| d ddkrV| d d}|dkr,| d |d  d	kr,d}n(| d |d d }| d d| | d< nLt| dkr| d  dr| d }| dd } | d dd | d< nd}| |fS )
a@  Extract output file path from command arguments.

  Args:
    args: (list of str) command arguments.

  Returns:
    (list of str) Command arguments with the output file path part stripped.
    (str or None) Output file path (if any).

  Raises:
    SyntaxError: If there is no file path after the last ">" character.
  r   >zRedirect file path is emptyr   -Nr   =)r(   SyntaxErrorr'   _parse_intervalr%   
ValueErrorcountindex)argsZoutput_file_pathZgt_indexr   r   r   extract_output_file_pathh   s6     r8   c             C   sN   |  ddkr>| dr>| d| d }| | dd }n| }d}||fS )a  Parse tensor name, potentially suffixed by slicing string.

  Args:
    in_str: (str) Input name of the tensor, potentially followed by a slicing
      string. E.g.: Without slicing string: "hidden/weights/Variable:0", with
      slicing string: "hidden/weights/Variable:0[1, :]"

  Returns:
    (str) name of the tensor
    (str) slicing string, if any. If no slicing string is present, return "".
  [r   ]N )r5   r(   r6   )in_strtensor_nametensor_slicingr   r   r   parse_tensor_name_with_slicing   s    r?   c             C   s   t td| S )a7  Validate a slicing string.

  Check if the input string contains only brackets, digits, commas and
  colons that are valid characters in numpy-style array slicing.

  Args:
    slicing_string: (str) Input slicing string to be validated.

  Returns:
    (bool) True if and only if the slicing string is valid.
  z^\[(\d|,|\s|:)+\]$)boolresearch)slicing_stringr   r   r   validate_slicing_string   s    rD   c             C   s   g }x| dd  dD ]p}| d}t|dkrJ|t|d   qdt|  krbdkrn n|tdd	 |D   qtd
qW t|S )a-  Construct a tuple of slices from the slicing string.

  The string must be a valid slicing string.

  Args:
    slicing_string: (str) Input slicing string to be parsed.

  Returns:
    tuple(slice1, slice2, ...)

  Raises:
    ValueError: If tensor_slicing is not a valid numpy ndarray slicing str.
  r   r   ,:r         c             S   s$   g | ]}|  rt|  nd qS )N)r    int)r   r6   r   r   r   r      s    z!_parse_slices.<locals>.<listcomp>zInvalid tensor-slicing string.)splitr%   r)   rI   r    slicer4   tuple)rC   parsedZslice_stringindicesr   r   r   _parse_slices   s    
rO   c             C   sB   t dd| } | dr.| dr.| dd } dd | d	D S )
a7  Parse a string representing indices.

  For example, if the input is "[1, 2, 3]", the return value will be a list of
  indices: [1, 2, 3]

  Args:
    indices_string: (str) a string representing indices. Can optionally be
      surrounded by a pair of brackets.

  Returns:
    (list of int): Parsed indices.
  z\s+r;   r9   r:   r   r   c             S   s   g | ]}t |qS r   )rI   )r   elementr   r   r   r      s    z!parse_indices.<locals>.<listcomp>rE   )rA   subr'   r(   rJ   )Zindices_stringr   r   r   parse_indices   s    rR   c             C   s   |   } | sg S d| kr.tdttjj| } t| }t	|t
rVt	|d t
sV|g}xp|D ]h}t|dkrvtdq\t	|d ttfstdt|d  q\t	|d ttfs\tdt|d  q\W |S )a  Parse a string representing numerical range(s).

  Args:
    range_string: (str) A string representing a numerical range or a list of
      them. For example:
        "[-1.0,1.0]", "[-inf, 0]", "[[-inf, -1.0], [1.0, inf]]"

  Returns:
    (list of list of float) A list of numerical ranges parsed from the input
      string.

  Raises:
    ValueError: If the input doesn't represent a range or a list of ranges.
  infr   rG   z%Incorrect number of elements in rangez.Incorrect type in the 1st element of range: %sr   z.Incorrect type in the 2nd element of range: %s)r    rA   rQ   reprsys
float_infomaxastliteral_eval
isinstancelistr%   r4   rI   floattype)Zrange_stringrangesitemr   r   r   parse_ranges   s$    


r`   c             C   sZ   t | }d}td}|jr$t|j}|jr4t|j}||krHtd|  t||j||jS )a  Convert a human-readable memory interval to a tuple of start and end value.

  Args:
    interval_str: (`str`) A human-readable str representing an interval
      (e.g., "[10kB, 20kB]", "<100M", ">100G"). Only the units "kB", "MB", "GB"
      are supported. The "B character at the end of the input `str` may be
      omitted.

  Returns:
    `Interval` object where start and end are in bytes.

  Raises:
    ValueError: if the input is not valid.
  r   rS   zUInvalid interval %s. Start of interval must be less than or equal to end of interval.)	r3   r\   r   parse_readable_size_strr   r4   r   r   r	   )interval_strstr_intervalinterval_startinterval_endr   r   r   parse_memory_interval  s    

rf   c             C   sZ   t | }d}td}|jr$t|j}|jr4t|j}||krHtd|  t||j||jS )a|  Convert a human-readable time interval to a tuple of start and end value.

  Args:
    interval_str: (`str`) A human-readable str representing an interval
      (e.g., "[10us, 20us]", "<100s", ">100ms"). Supported time suffixes are
      us, ms, s.

  Returns:
    `Interval` object where start and end are in microseconds.

  Raises:
    ValueError: if the input is not valid.
  r   rS   z:Invalid interval %s. Start must be before end of interval.)	r3   r\   r   parse_readable_time_strr   r4   r   r   r	   )rb   rc   rd   re   r   r   r   parse_time_interval:  s    

rh   c             C   s  |   } | drPt| dd   rDtdd| dd   ddS td|  | drt| d	d   rtdd| d	d   ddS td
|  | drt| dd   rt| dd   ddddS td|  | dr,t| d	d   r t| d	d   ddddS td|  | drD| dsPtd|  | d	d d}t|dkr|td|  |d   }t|std| |d	   }t|std| t|| d dk|| d dkdS )a4  Convert a human-readable interval to a tuple of start and end value.

  Args:
    interval_str: (`str`) A human-readable str representing an interval
      (e.g., "[1M, 2M]", "<100k", ">100ms"). The items following the ">", "<",
      ">=" and "<=" signs have to start with a number (e.g., 3.0, -2, .98).
      The same requirement applies to the items in the parentheses or brackets.

  Returns:
    Interval object where start or end can be None
    if the range is specified as "<N" or ">N" respectively.

  Raises:
    ValueError: if the input is not valid.
  z<=rG   NFT)r   r   r   r	   z%Invalid value string after <= in '%s'<r   z$Invalid value string after < in '%s'z>=z%Invalid value string after >= in '%s'r.   z$Invalid value string after > in '%s')r9   ()r:   )zRInvalid interval format: %s. Valid formats are: [min, max], (min, max), <max, >minr   rE   z\Incorrect interval format: %s. Interval should specify two values: [min, max] or (min, max).r   z$Invalid first item in interval: '%s'z%Invalid second item in interval: '%s'r9   r:   )	r    r'   _NUMBER_PATTERNmatchr   r4   r(   rJ   r%   )rb   r   Z
start_itemZend_itemr   r   r   r3   W  sR    





r3   c             C   s   |   } | dr| dd } |  r.t| S | drPtt| dd d S | drrtt| dd d S | drtt| dd d	 S td
|  dS )a  Convert a human-readable str representation to number of bytes.

  Only the units "kB", "MB", "GB" are supported. The "B character at the end
  of the input `str` may be omitted.

  Args:
    size_str: (`str`) A human-readable str representing a number of bytes
      (e.g., "0", "1023", "1.1kB", "24 MB", "23GB", "100 G".

  Returns:
    (`int`) The parsed number of bytes.

  Raises:
    ValueError: on failure to parse the input `size_str`.
  BNr   ki   Mi   Gi   @z3Failed to parsed human-readable byte size str: "%s")r    r(   isdigitrI   r\   r4   )Zsize_strr   r   r   ra     s    



ra   c             C   s~   dd }|   } | dr.t|| dd S | drPt|| dd d S | drrt|| dd	 d
 S t|| S )aB  Parses a time string in the format N, Nus, Nms, Ns.

  Args:
    time_str: (`str`) string consisting of an integer time value optionally
      followed by 'us', 'ms', or 's' suffix. If suffix is not specified,
      value is assumed to be in microseconds. (e.g. 100us, 8ms, 5s, 100).

  Returns:
    Microseconds value.
  c             S   s    t | }|dk rtd|  |S )Nr   z-Invalid time %s. Time value must be positive.)r\   r4   )Z	value_strr   r   r   r   parse_positive_float  s
    
z5parse_readable_time_str.<locals>.parse_positive_floatusNr/   msg     @@sr   g    .A)r    r(   rI   )Ztime_strrs   r   r   r   rg     s    


rg   c             C   s    | }t |std| t| S )a~  Call eval on the slicing of a tensor, with validation.

  Args:
    tensor: (numpy ndarray) The tensor value.
    tensor_slicing: (str or None) Slicing of the tensor, e.g., "[:, 1]". If
      None, no slicing will be performed on the tensor.

  Returns:
    (numpy ndarray) The sliced tensor.

  Raises:
    ValueError: If tensor_slicing is not a valid numpy ndarray slicing str.
  zInvalid tensor-slicing string.)rD   r4   rO   )Ztensorr>   _r   r   r   evaluate_tensor_slice  s    rx   c             C   s   t j| t jd}|jdtdd |jdddtdd	d
 |jdddtddd
 |jdddddd |jddddd |jddtddd |S )zGet an ArgumentParser for a command that prints tensor values.

  Examples of such commands include print_tensor and print_feed.

  Args:
    description: Description of the ArgumentParser.

  Returns:
    An instance of argparse.ArgumentParser.
  )descriptionusager=   zwName of the tensor, followed by any slicing indices, e.g., hidden1/Wx_plus_b/MatMul:0, hidden1/Wx_plus_b/MatMul:0[1, :])r]   helpz-nz--numbernumberr   zV0-based dump number for the specified tensor. Required for tensor with multiple dumps.)destr]   defaultr{   z-rz--rangesr^   r;   zuNumerical ranges to highlight tensor elements in. Examples: -r 0,1e-8, -r [-0.1,0.1], -r "[[-inf, -0.1], [0.1, inf]]"z-az--allZ	print_all
store_truez<Print the tensor in its entirety, i.e., do not use ellipses.)r}   actionr{   z-sz--numeric_summaryz\Include summary for non-empty tensors of numeric (int*, float*, complex*) and Boolean types.)r   r{   z-wz--write_pathzGPath of the numpy file to write the tensor data to, using numpy.save().)r]   r~   r{   )argparseArgumentParserSUPPRESSadd_argumentstrrI   )ry   Zapr   r   r   get_print_tensor_argparser  sL    r   )r   
__future__r   r   r   r   rX   rA   rU   compiler!   r#   r$   rl   objectr   r-   r8   r?   rD   rO   rR   r`   rf   rh   r3   ra   rg   rx   r   r   r   r   r   <module>   s4   



0/)B"