U
    VcA;                     @   s&  d Z ddlZddlZddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ dd	d
ddZejD ]Zeekrleee< qlee ZddgZddge Zee ZeddddgZeddddgZdZd.ddZdd Zd/d d!Zd"d# Zd$d% Zd&d' Zd(d) Zd0d*d+Z d1d,d-Z!dS )2a"  Logic for TensorBoard inspector to help humans investigate event files.

Example usages:
tensorboard --inspect --event_file myevents.out
tensorboard --inspect --event_file myevents.out --tag loss
tensorboard --inspect --logdir mylogdir
tensorboard --inspect --logdir mylogdir --tag loss


This script runs over a logdir and creates an InspectionUnit for every
subdirectory with event files. If running over an event file, it creates only
one InspectionUnit. One block of output is printed to console for each
InspectionUnit.

The primary content of an InspectionUnit is the dict field_to_obs that maps
fields (e.g. "scalar", "histogram", "session_log:start", etc.) to a list of
Observations for the field. Observations correspond one-to-one with Events in an
event file but contain less information because they only store what is
necessary to generate the final console output.

The final output is rendered to console by applying some aggregating function
to the lists of Observations. Different functions are applied depending on the
type of field. For instance, for "scalar" fields, the inspector shows aggregate
statistics. For other fields like "session_log:start", all observed steps are
printed in order to aid debugging.


[1] Query a logdir or an event file for its logged tags and summary statistics
using --logdir or --event_file.

[[event_file]] contains these tags:
histograms
   binary/Sign/Activations
   binary/nn_tanh/act/Activations
   binary/nn_tanh/biases
   binary/nn_tanh/biases:gradient
   binary/nn_tanh/weights
   binary/nn_tanh/weights:gradient
images
   input_images/image/0
   input_images/image/1
   input_images/image/2
scalars
   Learning Rate
   Total Cost
   Total Cost (raw)

Debug output aggregated over all tags:
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms
   first_step           491
   last_step            659823
   max_step             659823
   min_step             491
   num_steps            993
   outoforder_steps     []
images -
scalars
   first_step           0
   last_step            659823
   max_step             659823
   min_step             0
   num_steps            1985
   outoforder_steps     []
sessionlog:checkpoint
   first_step           7129
   last_step            657167
   max_step             657167
   min_step             7129
   num_steps            99
   outoforder_steps     []
sessionlog:start
   outoforder_steps     []
   steps                [0L]
sessionlog:stop -


[2] Drill down into a particular tag using --tag.

Debug output for binary/Sign/Activations:
histograms
   first_step           491
   last_step            659823
   max_step             659823
   min_step             491
   num_steps            993
   outoforder_steps     []
    N)event_accumulator)event_file_loader)
io_wrapper)tf)	event_pb2ZscalarsZ
histogramsZimagesaudio)Zsimple_valueZhistoimager   sessionlog:startsessionlog:stopgraphsessionlog:checkpointObservationstep	wall_timetagInspectionUnitname	generatorfield_to_obszG======================================================================
 c                    s   d fdd	}t dd tD  | D ]}|dr@|s@|d| |dr|s|jj}|tjjkrn|d	| q|tjjkr|d
| q|tjj	kr|d| q$|dr$|j
jD ]>}|r|j|krqt D ] \}}||r||||j qqq$ S )aE  Return a field to `Observations` dict for the event generator.

    Args:
      generator: A generator over event protos.
      query_for_tag: A string that if specified, only create observations for
        events with this tag name.

    Returns:
      A dict mapping keys in `TRACKED_FIELDS` to an `Observation` list.
    r   c                    s0   | t kst |  t|j|j|d  d S )N)r   r   r   )TRACKED_FIELDSAssertionErrorappendr   r   r   _asdict)stateventr   r    ]/tmp/pip-unpacked-wheel-g8kmtpbc/tensorboard/backend/event_processing/event_file_inspector.py	increment   s      z0get_field_to_observations_map.<locals>.incrementc                 S   s   g | ]}|g fqS r   r   ).0tr   r   r   
<listcomp>   s     z1get_field_to_observations_map.<locals>.<listcomp>Z	graph_defr   session_logr	   r
   r   summary)r   )dictr   ZHasFieldr#   statusr   Z
SessionLogSTARTSTOP
CHECKPOINTr$   valuer   SUMMARY_TYPE_TO_FIELDitems)r   Zquery_for_tagr   r   r&   r*   Z
proto_nameZdisplay_namer   r   r   get_field_to_observations_map   s*    


r-   c                 C   s   dd |   D S )a  Returns a dictionary of tags that a user could query over.

    Args:
      field_to_obs: Dict that maps string field to `Observation` list.

    Returns:
      A dict that maps keys in `TAG_FIELDS` to a list of string tags present in
      the event files. If the dict does not have any observations of the type,
      maps to an empty list so that we can render this to console.
    c                 S   s0   i | ](\}}|t kr|ttd d |D qS )c                 S   s   g | ]}| d dqS )r   r   )getr    xr   r   r   r"      s     z.get_unique_tags.<locals>.<dictcomp>.<listcomp>)
TAG_FIELDSsortedset)r    fieldobservationsr   r   r   
<dictcomp>   s    z#get_unique_tags.<locals>.<dictcomp>)r,   r   r   r   r   get_unique_tags   s    r7   Tc                 C   s   t |  D ]\}}|s,|r,td| qt|trXt| |D ]}td| qBqt|trt| t | D ]\}}td|| qvqdS )zPrints a shallow dict to console.

    Args:
      d: Dict to print.
      show_missing: Whether to show keys with empty values.
    z{} -z   {}z   {:<20} {}N)r2   r,   printformat
isinstancelistr%   )dshow_missingkvitemkkvvr   r   r   
print_dict   s    

rC   c                 C   sn   dd }dd }i }|   D ]L\}}|s2d||< qdd |D }|tkrT||||< |tkr||||< q|S )zTransform the field-to-obs mapping into a printable dictionary.

    Args:
      field_to_obs: Dict that maps string field to `Observation` list.

    Returns:
      A dict with the keys and values to print to console.
    c                 S   s.   t t| t| t| | d | d t| dS )Nr   )Z	num_stepsZmin_stepZmax_stepZ	last_stepZ
first_stepoutoforder_steps)lenr3   minmaxget_out_of_orderstepsr   r   r   compressed_steps	  s    
z+get_dict_to_print.<locals>.compressed_stepsc                 S   s   | t | dS )N)rK   rE   )rI   rJ   r   r   r   
full_steps  s    z%get_dict_to_print.<locals>.full_stepsNc                 S   s   g | ]}|d  qS )r   r   r/   r   r   r   r"     s     z%get_dict_to_print.<locals>.<listcomp>)r,   SHORT_FIELDSLONG_FIELDS)r   rL   rM   outputr4   r5   rK   r   r   r   get_dict_to_print   s    

rQ   c                 C   sR   g }t t| D ]<}|dkrq| | | |d  k r|| |d  | | f q|S )a  Returns elements that break the monotonically non-decreasing trend.

    This is used to find instances of global step values that are "out-of-order",
    which may trigger TensorBoard event discarding logic.

    Args:
      list_of_numbers: A list of numbers.

    Returns:
      A list of tuples in which each tuple are two elements are adjacent, but the
      second element is lower than the first.
    r      )rangerF   r   )Zlist_of_numbersresultir   r   r   rI   %  s    rI   c                 C   s   t | }dd |D }|S )a  Returns a list of event generators for subdirectories with event files.

    The number of generators returned should equal the number of directories
    within logdir that contain event files. If only logdir contains event files,
    returns a list of length one.

    Args:
      logdir: A log directory that contains event files.

    Returns:
      List of event generators for each subdirectory with event files.
    c                    s.   g | ]& t j fd dtjj D  qS )c                    s2   g | ]*}t tj |rttj |qS r   r   IsTensorFlowEventsFileospathjoingenerator_from_event_filer    fsubdirr   r   r"   N  s   z5generators_from_logdir.<locals>.<listcomp>.<listcomp>)	itertoolschainr   iogfilelistdir)r    r   r^   r   r"   L  s   
z*generators_from_logdir.<locals>.<listcomp>)r   GetLogdirSubdirectories)logdirsubdirs
generatorsr   r   r   generators_from_logdir>  s
    

ri   c                 C   s   t |  S )z:Returns a generator that yields events from an event file.)r   ZLegacyEventFileLoaderLoad)
event_filer   r   r   r[   Y  s    r[   c              	      s   | rt | }g }|D ]@ tj fddtjj D  }|t	 |t
||d q|r|tdddd |D  n(t | rtd|  ntd|  |S |rt|}t	||t
||dgS g S )	a  Returns a list of InspectionUnit objects given either logdir or
    event_file.

    If logdir is given, the number of InspectionUnits should equal the
    number of directories or subdirectories that contain event files.

    If event_file is given, the number of InspectionUnits should be 1.

    Args:
      logdir: A log directory that contains event files.
      event_file: Or, a particular event file path.
      tag: An optional tag name to query for.

    Returns:
      A list of InspectionUnit objects.
    c                    s2   g | ]*}t tj |rttj |qS r   rV   r\   r^   r   r   r"   t  s
   z(get_inspection_units.<locals>.<listcomp>)r   r   r   zFound event files in:
{}

c                 S   s   g | ]
}|j qS r   )r   )r    ur   r   r   r"     s     zIt seems that {} may be an event file instead of a logdir. If this is the case, use --event_file instead of --logdir to pass it in.z%No event files found within logdir {})r   re   r`   ra   r   rb   rc   rd   r   r   r-   r8   r9   rZ   rW   r[   )rf   rk   r   rg   inspection_unitsr   r   r^   r   get_inspection_units^  sN    

	
ro   c                 C   s   t td t  t| ||}|D ]n}|r<t d||j n6t d|j tt|j t t t d|j tt|j| d t t q dS )aM  Main function for inspector that prints out a digest of event files.

    Args:
      logdir: A log directory that contains event files.
      event_file: Or, a particular event file path.
      tag: An optional tag name to query for.

    Raises:
      ValueError: If neither logdir and event_file are given, or both are given.
    z8Processing event files... (this can take a few minutes)
z"Event statistics for tag {} in {}:zThese tags are in {}:zEvent statistics for {}:)r=   N)	r8   PRINT_SEPARATORro   r9   r   rC   r7   r   rQ   )rf   rk   r   rn   unitr   r   r   inspect  s"    rr   )r   )T)r   r   r   )r   r   r   )"__doc__collectionsr`   rX   Z$tensorboard.backend.event_processingr   r   r   Ztensorboard.compatr   Ztensorboard.compat.protor   r+   ZSUMMARY_TYPESZsummary_typer;   valuesr1   rO   rN   r   
namedtupler   r   rp   r-   r7   rC   rQ   rI   ri   r[   ro   rr   r   r   r   r   <module>   sL   `

  
-
&
@