
    1Vh{I                         d 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
  e
j                         Z G d d	      Zy)
z<Provides an interface for working with multiple event files.    N)Optional)directory_watcher)event_accumulator)
io_wrapper)
tb_loggingc                       e Zd ZdZ	 ddZddZddZd Zd Zd Z	d	 Z
d
ee   fdZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zy)EventMultiplexera:  An `EventMultiplexer` manages access to multiple `EventAccumulator`s.

    Each `EventAccumulator` is associated with a `run`, which is a self-contained
    TensorFlow execution. The `EventMultiplexer` provides methods for extracting
    information about events from multiple `run`s.

    Example usage for loading specific runs from files:

    ```python
    x = EventMultiplexer({'run1': 'path/to/run1', 'run2': 'path/to/run2'})
    x.Reload()
    ```

    Example usage for loading a directory where each subdirectory is a run

    ```python
    (eg:) /parent/directory/path/
          /parent/directory/path/run1/
          /parent/directory/path/run1/events.out.tfevents.1001
          /parent/directory/path/run1/events.out.tfevents.1002

          /parent/directory/path/run2/
          /parent/directory/path/run2/events.out.tfevents.9232

          /parent/directory/path/run3/
          /parent/directory/path/run3/events.out.tfevents.9232
    x = EventMultiplexer().AddRunsFromDirectory('/parent/directory/path')
    (which is equivalent to:)
    x = EventMultiplexer({'run1': '/parent/directory/path/run1', 'run2':...}
    ```

    If you would like to watch `/parent/directory/path`, wait for it to be created
      (if necessary) and then periodically pick up new runs, use
      `AutoloadingMultiplexer`
    @@Tensors
    Nc                 x   t         j                  d       t        j                         | _        i | _        i | _        d| _        |xs t        j                  | _
        || _        |@t         j                  d|       |j                         D ]  \  }}| j                  ||        t         j                  d       y)aU  Constructor for the `EventMultiplexer`.

        Args:
          run_path_map: Dict `{run: path}` which specifies the
            name of a run, and the path to find the associated events. If it is
            None, then the EventMultiplexer initializes without any runs.
          size_guidance: A dictionary mapping from `tagType` to the number of items
            to store for each tag of that type. See
            `event_accumulator.EventAccumulator` for details.
          purge_orphaned_data: Whether to discard any events that were "orphaned" by
            a TensorFlow restart.
        zEvent Multiplexer initializing.FNz1Event Multplexer doing initialization load for %sz#Event Multiplexer done initializing)loggerinfo	threadingLock_accumulators_mutex_accumulators_paths_reload_calledr   DEFAULT_SIZE_GUIDANCE_size_guidancepurge_orphaned_dataitemsAddRun)selfrun_path_mapsize_guidancer   runpaths         f/home/dcms/DCMS/lib/python3.12/site-packages/tensorboard/backend/event_processing/event_multiplexer.py__init__zEventMultiplexer.__init__F   s     	56#,>>#3 #D.DD 	 $7 #KKC *//1 '	TD#&'9:    c                    |xs |}d}| j                   5  || j                  vs| j                  |   |k7  r|| j                  v r7| j                  |   |k7  r%t        j	                  d|| j                  |   |       t        j                  d|       t        j                  || j                  | j                        }|| j                  |<   || j                  |<   ddd       |r| j                  r|j                          | S # 1 sw Y   )xY w)aW  Add a run to the multiplexer.

        If the name is not specified, it is the same as the path.

        If a run by that name exists, and we are already watching the right path,
          do nothing. If we are watching a different path, replace the event
          accumulator.

        If `Reload` has been called, it will `Reload` the newly created
        accumulators.

        Args:
          path: Path to the event files (or event directory) for given run.
          name: Name of the run to add. If not provided, is set to path.

        Returns:
          The `EventMultiplexer`.
        Nz.Conflict for name %s: old path %s, new path %sz$Constructing EventAccumulator for %s)r   r   )r   r   r   r   warningr   r   EventAccumulatorr   r   r   Reload)r   r   nameaccumulators       r   r   zEventMultiplexer.AddRung   s   & |t%% 	)4---T1Bd1J4;;&4;;t+<+D NNHD)	 BDI/@@"&"5"5(,(@(@
 ,7""4($(D!%	)& """"$-	) 	)s   CDDc                 l   t         j                  d|       t        j                  |      D ]o  }t         j                  d|       t        j
                  j                  ||      }|r t        j
                  j                  ||      n|}| j                  ||       q t         j                  d|       | S )a  Load runs from a directory; recursively walks subdirectories.

        If path doesn't exist, no-op. This ensures that it is safe to call
          `AddRunsFromDirectory` multiple times, even before the directory is made.

        If path is a directory, load event files in the directory (if any exist) and
          recursively call AddRunsFromDirectory on any subdirectories. This mean you
          can call AddRunsFromDirectory at the root of a tree of event logs and
          TensorBoard will load them all.

        If the `EventMultiplexer` is already loaded this will cause
        the newly created accumulators to `Reload()`.
        Args:
          path: A string path to a directory to load runs from.
          name: Optionally, what name to apply to the runs. If name is provided
            and the directory contains run subdirectories, the name of each subrun
            is the concatenation of the parent name and the subdirectory name. If
            name is provided and the directory contains event files, then a run
            is added called "name" and with the events from the path.

        Raises:
          ValueError: If the path exists and isn't a directory.

        Returns:
          The `EventMultiplexer`.
        z!Starting AddRunsFromDirectory: %szAdding events from directory %s)r$   z"Done with AddRunsFromDirectory: %s)	r   r   r   GetLogdirSubdirectoriesosr   relpathjoinr   )r   r   r$   subdirrpathsubnames         r   AddRunsFromDirectoryz%EventMultiplexer.AddRunsFromDirectory   s    6 	7> 88> 	.FKK96BGGOOFD1E37bggll4/UGKKWK-		.
 	8$?r   c                    t         j                  d       d| _        | j                  5  t	        | j
                  j                               }ddd       t               }D ]  \  }}	 |j                           | j                  5  |D ]%  }t         j                  d|       | j
                  |= ' 	 ddd       t         j                  d       | S # 1 sw Y   xY w# t        t        f$ r!}t         j                  d||       Y d}~d}~wt        j                  $ r |j                  |       Y w xY w# 1 sw Y   xY w)z*Call `Reload` on every `EventAccumulator`.z#Beginning EventMultiplexer.Reload()TNz%Unable to reload accumulator '%s': %szDeleting accumulator '%s'z'Finished with EventMultiplexer.Reload())r   r   r   r   listr   r   setr#   OSErrorIOErrorerrorr   DirectoryDeletedErroraddr!   )r   r   names_to_deleter$   r%   es         r   r#   zEventMultiplexer.Reload   s%   9:" %% 	5++1134E	5 %!& 	*D+*""$	* %% 	-' -:DA&&t,-	- 	=>#	5 	5 W% ODdANN$:: *##D)*	- 	-s5   $C(C+D5CD2,D'D21D25D>c                     | j                   5  t        | j                  j                               }ddd       D ci c]  \  }}||j	                  |       c}}S # 1 sw Y   .xY wc c}}w )zGet index of runs and assets for a given plugin.

        Args:
          plugin_name: Name of the plugin we are checking for.

        Returns:
          A dictionary that maps from run_name to a list of plugin
            assets for that run.
        N)r   r0   r   r   PluginAssets)r   plugin_namer   r   accums        r   r:   zEventMultiplexer.PluginAssets   si     %% 	5++1134E	5 HMMeU''44MM		5 	5 Ns   $AA*A'c                 H    | j                  |      }|j                  ||      S )an  Return the contents for a specific plugin asset from a run.

        Args:
          run: The string name of the run.
          plugin_name: The string name of a plugin.
          asset_name: The string name of an asset.

        Returns:
          The string contents of the plugin asset.

        Raises:
          KeyError: If the asset is not available.
        )GetAccumulatorRetrievePluginAsset)r   r   r;   
asset_namer%   s        r   r?   z$EventMultiplexer.RetrievePluginAsset   s'     ))#...{JGGr   c                 D    | j                  |      }|j                         S )a  Return the timestamp of the first event of the given run.

        This may perform I/O if no events have been loaded yet for the run.

        Args:
          run: A string name of the run for which the timestamp is retrieved.

        Returns:
          The wall_time of the first event of the run, which will typically be
          seconds since the epoch.

        Raises:
          KeyError: If the run is not found.
          ValueError: If the run has no events loaded and there are no events on
            disk to load.
        )r>   FirstEventTimestampr   r   r%   s      r   rB   z$EventMultiplexer.FirstEventTimestamp   s#    " ))#...00r   returnc                 D    | j                  |      }|j                         S )aO  Returns the source writer name from the first event of the given run.

        Assuming each run has only one source writer.

        Args:
          run: A string name of the run from which the event source information
            is retrieved.

        Returns:
          Name of the writer that wrote the events in the run.
        )r>   GetSourceWriterrC   s      r   rF   z EventMultiplexer.GetSourceWriter  s#     ))#.**,,r   c                 F    | j                  |      }|j                  |      S )a  Retrieve the scalar events associated with a run and tag.

        Args:
          run: A string name of the run for which values are retrieved.
          tag: A string name of the tag for which values are retrieved.

        Raises:
          KeyError: If the run is not found, or the tag is not available for
            the given run.

        Returns:
          An array of `event_accumulator.ScalarEvents`.
        )r>   Scalarsr   r   tagr%   s       r   rH   zEventMultiplexer.Scalars  %     ))#.""3''r   c                 D    | j                  |      }|j                         S )aO  Retrieve the graph associated with the provided run.

        Args:
          run: A string name of a run to load the graph for.

        Raises:
          KeyError: If the run is not found.
          ValueError: If the run does not have an associated graph.

        Returns:
          The `GraphDef` protobuf data structure.
        )r>   GraphrC   s      r   rM   zEventMultiplexer.Graph&  s#     ))#.  ""r   c                 D    | j                  |      }|j                         S )aq  Retrieve the serialized graph associated with the provided run.

        Args:
          run: A string name of a run to load the graph for.

        Raises:
          KeyError: If the run is not found.
          ValueError: If the run does not have an associated graph.

        Returns:
          The serialized form of the `GraphDef` protobuf data structure.
        )r>   SerializedGraphrC   s      r   rO   z EventMultiplexer.SerializedGraph6  s#     ))#.**,,r   c                 D    | j                  |      }|j                         S )aW  Retrieve the metagraph associated with the provided run.

        Args:
          run: A string name of a run to load the graph for.

        Raises:
          KeyError: If the run is not found.
          ValueError: If the run does not have an associated graph.

        Returns:
          The `MetaGraphDef` protobuf data structure.
        )r>   	MetaGraphrC   s      r   rQ   zEventMultiplexer.MetaGraphF  s#     ))#.$$&&r   c                 F    | j                  |      }|j                  |      S )a  Get the session.run() metadata associated with a TensorFlow run and
        tag.

        Args:
          run: A string name of a TensorFlow run.
          tag: A string name of the tag associated with a particular session.run().

        Raises:
          KeyError: If the run is not found, or the tag is not available for the
            given run.

        Returns:
          The metadata in the form of `RunMetadata` protobuf data structure.
        )r>   RunMetadatarI   s       r   rS   zEventMultiplexer.RunMetadataV  s%     ))#.&&s++r   c                 F    | j                  |      }|j                  |      S )a  Retrieve the histogram events associated with a run and tag.

        Args:
          run: A string name of the run for which values are retrieved.
          tag: A string name of the tag for which values are retrieved.

        Raises:
          KeyError: If the run is not found, or the tag is not available for
            the given run.

        Returns:
          An array of `event_accumulator.HistogramEvents`.
        )r>   
HistogramsrI   s       r   rU   zEventMultiplexer.Histogramsh  s%     ))#.%%c**r   c                 F    | j                  |      }|j                  |      S )a  Retrieve the compressed histogram events associated with a run and
        tag.

        Args:
          run: A string name of the run for which values are retrieved.
          tag: A string name of the tag for which values are retrieved.

        Raises:
          KeyError: If the run is not found, or the tag is not available for
            the given run.

        Returns:
          An array of `event_accumulator.CompressedHistogramEvents`.
        )r>   CompressedHistogramsrI   s       r   rW   z%EventMultiplexer.CompressedHistogramsy  s%     ))#.//44r   c                 F    | j                  |      }|j                  |      S )a  Retrieve the image events associated with a run and tag.

        Args:
          run: A string name of the run for which values are retrieved.
          tag: A string name of the tag for which values are retrieved.

        Raises:
          KeyError: If the run is not found, or the tag is not available for
            the given run.

        Returns:
          An array of `event_accumulator.ImageEvents`.
        )r>   ImagesrI   s       r   rY   zEventMultiplexer.Images  s%     ))#.!!#&&r   c                 F    | j                  |      }|j                  |      S )a  Retrieve the audio events associated with a run and tag.

        Args:
          run: A string name of the run for which values are retrieved.
          tag: A string name of the tag for which values are retrieved.

        Raises:
          KeyError: If the run is not found, or the tag is not available for
            the given run.

        Returns:
          An array of `event_accumulator.AudioEvents`.
        )r>   AudiorI   s       r   r[   zEventMultiplexer.Audio  s%     ))#.  %%r   c                 F    | j                  |      }|j                  |      S )a  Retrieve the tensor events associated with a run and tag.

        Args:
          run: A string name of the run for which values are retrieved.
          tag: A string name of the tag for which values are retrieved.

        Raises:
          KeyError: If the run is not found, or the tag is not available for
            the given run.

        Returns:
          An array of `event_accumulator.TensorEvent`s.
        )r>   TensorsrI   s       r   r]   zEventMultiplexer.Tensors  rK   r   c                     i }| j                         D ](  }	 | j                  |      j                  |      }|||<   * |S # t        $ r Y 8w xY w)a  Returns a 2-layer dictionary of the form {run: {tag: content}}.

        The `content` referred above is the content field of the PluginData proto
        for the specified plugin within a Summary.Value proto.

        Args:
          plugin_name: The name of the plugin for which to fetch content.

        Returns:
          A dictionary of the form {run: {tag: content}}.
        )Runsr>   PluginTagToContentKeyError)r   r;   mappingr   tag_to_contents        r   PluginRunToTagToContentz(EventMultiplexer.PluginRunToTagToContent  sg     99; 	*C!%!4!4S!9!L!L" *GCL	* 	  s    A  	AAc                 F    | j                  |      }|j                  |      S )a  Return the summary metadata for the given tag on the given run.

        Args:
          run: A string name of the run for which summary metadata is to be
            retrieved.
          tag: A string name of the tag whose summary metadata is to be
            retrieved.

        Raises:
          KeyError: If the run is not found, or the tag is not available for
            the given run.

        Returns:
          A `SummaryMetadata` protobuf.
        )r>   SummaryMetadatarI   s       r   rf   z EventMultiplexer.SummaryMetadata  s%      ))#.**3//r   c                     | j                   5  t        | j                  j                               }ddd       D ci c]  \  }}||j	                          c}}S # 1 sw Y   -xY wc c}}w )a|  Return all the run names in the `EventMultiplexer`.

        Returns:
        ```
          {runName: { images: [tag1, tag2, tag3],
                      scalarValues: [tagA, tagB, tagC],
                      histograms: [tagX, tagY, tagZ],
                      compressedHistograms: [tagX, tagY, tagZ],
                      graph: true, meta_graph: true}}
        ```
        N)r   r0   r   r   Tags)r   r   run_namer%   s       r   r_   zEventMultiplexer.Runs  sh     %% 	5++1134E	5 KPP1F;+**,,PP	5 	5 Qs   $AA)A&c                     | j                   S )z5Returns a dict mapping run names to event file paths.)r   )r   s    r   RunPathszEventMultiplexer.RunPaths  s    {{r   c                 d    | j                   5  | j                  |   cddd       S # 1 sw Y   yxY w)zReturns EventAccumulator for a given run.

        Args:
          run: String name of run.

        Returns:
          An EventAccumulator object.

        Raises:
          KeyError: If run does not exist.
        N)r   r   )r   r   s     r   r>   zEventMultiplexer.GetAccumulator  s0     %% 	+%%c*	+ 	+ 	+s   &/)NNT)N)__name__
__module____qualname____doc__r   r   r.   r#   r:   r?   rB   r   strrF   rH   rM   rO   rQ   rS   rU   rW   rY   r[   r]   rd   rf   r_   rk   r>    r   r   r	   r	       s    #L JN;B+Z"H2N H"1(-hsm -("# - ' ,$+"5$'"&"("00&Q"+r   r	   )rp   r(   r   typingr   $tensorboard.backend.event_processingr   r   r   tensorboard.utilr   
get_loggerr   r	   rr   r   r   <module>rw      s@    C 
   B B ; ' 
			 k+ k+r   