U
    ‰d»  ã                   @   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lmZ d	d
lmZ d	dlmZmZmZmZmZ d	dlmZ d	dlmZ d	dlmZ d	dlmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* G dd„ de+ƒZ,G dd„ de+ƒZ-dS )zlProvides an API for writing protocol buffers to event files to be
consumed by TensorBoard for visualization.é    N)Útf)Ú
SessionLog)ÚEvent)Ú	event_pb2)ÚProjectorConfig)ÚEventFileWriteré   )Úmake_np)Úmake_matÚmake_spriteÚmake_tsvÚwrite_pbtxtÚget_embedding_info)Úload_onnx_graph)Úgraph)Úfigure_to_image)ÚscalarÚ	histogramÚhistogram_rawÚimageÚaudioÚtextÚpr_curveÚpr_curve_rawÚvideoÚcustom_scalarsÚimage_boxesÚmeshÚhparamsc                   @   sb   e Zd ZdZddd„Zdd„ Zdd
d„Zddd„Zddd„Zddd„Z	dd„ Z
dd„ Zdd„ Zd	S )Ú
FileWritera—  Writes protocol buffers to event files to be consumed by TensorBoard.

    The `FileWriter` class provides a mechanism to create an event file in a
    given directory and add summaries and events to it. The class updates the
    file contents asynchronously. This allows a training program to call methods
    to add data to the file directly from the training loop, without slowing down
    training.
    é
   éx   Ú c                 C   s   t |ƒ}t||||ƒ| _dS )ag  Creates a `FileWriter` and an event file.
        On construction the writer creates a new event file in `log_dir`.
        The other arguments to the constructor control the asynchronous writes to
        the event file.

        Args:
          log_dir: A string. Directory where event file will be written.
          max_queue: Integer. Size of the queue for pending events and
            summaries before one of the 'add' calls forces a flush to disk.
            Default is ten items.
          flush_secs: Number. How often, in seconds, to flush the
            pending events and summaries to disk. Default is every two minutes.
          filename_suffix: A string. Suffix added to all event filenames
            in the log_dir directory. More details on filename construction in
            tensorboard.summary.writer.event_file_writer.EventFileWriter.
        N)Ústrr   Úevent_writer)ÚselfÚlog_dirÚ	max_queueÚ
flush_secsÚfilename_suffix© r*   úB/tmp/pip-unpacked-wheel-ua33x9lu/torch/utils/tensorboard/writer.pyÚ__init__5   s       ÿzFileWriter.__init__c                 C   s
   | j  ¡ S )z7Returns the directory where event file will be written.)r$   Ú
get_logdir©r%   r*   r*   r+   r-   O   s    zFileWriter.get_logdirNc                 C   s8   |dkrt   ¡ n||_|dk	r(t|ƒ|_| j |¡ dS )a]  Adds an event to the event file.
        Args:
          event: An `Event` protocol buffer.
          step: Number. Optional global step value for training process
            to record with the event.
          walltime: float. Optional walltime to override the default (current)
            walltime (from time.time()) seconds after epoch
        N)ÚtimeZ	wall_timeÚintÚstepr$   Ú	add_event)r%   Úeventr1   Úwalltimer*   r*   r+   r2   S   s    	
zFileWriter.add_eventc                 C   s   t j|d}|  |||¡ dS )añ  Adds a `Summary` protocol buffer to the event file.
        This method wraps the provided summary in an `Event` protocol buffer
        and adds it to the event file.

        Args:
          summary: A `Summary` protocol buffer.
          global_step: Number. Optional global step value for training process
            to record with the summary.
          walltime: float. Optional walltime to override the default (current)
            walltime (from time.time()) seconds after epoch
        )ÚsummaryN)r   r   r2   )r%   r5   Úglobal_stepr4   r3   r*   r*   r+   Úadd_summaryc   s    zFileWriter.add_summaryc                 C   s^   |d }|d }t j| ¡ d}|  |d|¡ t jd| ¡ d}t j|d}|  |d|¡ dS )a&  Adds a `Graph` and step stats protocol buffer to the event file.

        Args:
          graph_profile: A `Graph` and step stats protocol buffer.
          walltime: float. Optional walltime to override the default (current)
            walltime (from time.time()) seconds after epoch
        r   r   ©Z	graph_defNZstep1)ÚtagZrun_metadata)Ztagged_run_metadata)r   r   ÚSerializeToStringr2   ZTaggedRunMetadata)r%   Zgraph_profiler4   r   Z	stepstatsr3   Ztrmr*   r*   r+   Ú	add_graphr   s     ÿzFileWriter.add_graphc                 C   s"   t j| ¡ d}|  |d|¡ dS )zòAdds a `Graph` protocol buffer to the event file.

        Args:
          graph: A `Graph` protocol buffer.
          walltime: float. Optional walltime to override the default (current)
            _get_file_writerfrom time.time())
        r8   N)r   r   r:   r2   )r%   r   r4   r3   r*   r*   r+   Úadd_onnx_graph…   s    zFileWriter.add_onnx_graphc                 C   s   | j  ¡  dS ©z‰Flushes the event file to disk.
        Call this method to make sure that all pending events have been written to
        disk.
        N)r$   Úflushr.   r*   r*   r+   r>      s    zFileWriter.flushc                 C   s   | j  ¡  dS )z…Flushes the event file to disk and close the file.
        Call this method when you do not need the summary writer anymore.
        N)r$   Úcloser.   r*   r*   r+   r?   —   s    zFileWriter.closec                 C   s   | j  ¡  dS )zäReopens the EventFileWriter.
        Can be called after `close()` to add more events in the same directory.
        The events will go into a new events file.
        Does nothing if the EventFileWriter was not closed.
        N)r$   Úreopenr.   r*   r*   r+   r@      s    zFileWriter.reopen)r    r!   r"   )NN)NN)N)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r,   r-   r2   r7   r;   r<   r>   r?   r@   r*   r*   r*   r+   r   +   s   	




r   c                   @   s,  e Zd ZdZdMdd„Zdd	„ Zd
d„ Zdd„ ZdNdd„ZdOdd„Z	dPdd„Z
dQdd„ZdRdd„ZdSdd„ZdTdd„ZdUd!d"„ZdVd$d%„ZdWd'd(„ZdXd*d+„ZdYd,d-„Zd.d/„ ZdZd0d1„Zed2d3„ ƒZd[d5d6„Zd\d8d9„Zd]d:d;„Zd^d=d>„Zd_d?d@„ZdAdB„ Zd`dCdD„ZdEdF„ ZdGdH„ Z dIdJ„ Z!dKdL„ Z"dS )aÚSummaryWritera²  Writes entries directly to event files in the log_dir to be
    consumed by TensorBoard.

    The `SummaryWriter` class provides a high-level API to create an event file
    in a given directory and add summaries and events to it. The class updates the
    file contents asynchronously. This allows a training program to call methods
    to add data to the file directly from the training loop, without slowing down
    training.
    Nr"   r    r!   c                 C   sÔ   t j d¡ |sPddl}ddlm} | ¡  d¡}	tj 	d|	d | 
¡  | ¡}|| _|| _|| _|| _|| _d | _| _|  ¡  d}
g }g }|
d	k r¶| |
¡ | |
 ¡ |
d
9 }
qŽ|ddd… dg | | _dS )a‚  Creates a `SummaryWriter` that will write out events and summaries
        to the event file.

        Args:
            log_dir (string): Save directory location. Default is
              runs/**CURRENT_DATETIME_HOSTNAME**, which changes after each run.
              Use hierarchical folder structure to compare
              between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc.
              for each new experiment to compare across them.
            comment (string): Comment log_dir suffix appended to the default
              ``log_dir``. If ``log_dir`` is assigned, this argument has no effect.
            purge_step (int):
              When logging crashes at step :math:`T+X` and restarts at step :math:`T`,
              any events whose global_step larger or equal to :math:`T` will be
              purged and hidden from TensorBoard.
              Note that crashed and resumed experiments should have the same ``log_dir``.
            max_queue (int): Size of the queue for pending events and
              summaries before one of the 'add' calls forces a flush to disk.
              Default is ten items.
            flush_secs (int): How often, in seconds, to flush the
              pending events and summaries to disk. Default is every two minutes.
            filename_suffix (string): Suffix added to all event filenames in
              the log_dir directory. More details on filename construction in
              tensorboard.summary.writer.event_file_writer.EventFileWriter.

        Examples::

            from torch.utils.tensorboard import SummaryWriter

            # create a summary writer with automatically generated folder name.
            writer = SummaryWriter()
            # folder location: runs/May04_22-14-54_s-MacBook-Pro.local/

            # create a summary writer using the specified folder name.
            writer = SummaryWriter("my_experiment")
            # folder location: my_experiment

            # create a summary writer with comment appended.
            writer = SummaryWriter(comment="LR_0.1_BATCH_16")
            # folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/

        z tensorboard.create.summarywriterr   N)Údatetimez%b%d_%H-%M-%SÚrunsÚ_gê-™—q=g@Œµx¯Dgš™™™™™ñ?éÿÿÿÿ)ÚtorchÚ_CÚ_log_api_usage_onceÚsocketrF   ÚnowÚstrftimeÚosÚpathÚjoinÚgethostnamer&   Ú
purge_stepr'   r(   r)   Úfile_writerÚall_writersÚ_get_file_writerÚappendÚdefault_bins)r%   r&   ÚcommentrT   r'   r(   r)   rM   rF   Úcurrent_timeÚvZbucketsZneg_bucketsr*   r*   r+   r,   ±   s0    3 ÿ

zSummaryWriter.__init__c                 C   s
   t |tƒS )ag  
        Caffe2 users have the option of passing a string representing the name of
        a blob in the workspace instead of passing the actual Tensor/array containing
        the numeric values. Thus, we need to check if we received a string as input
        instead of an actual Tensor/array, and if so, we need to fetch the Blob
        from the workspace corresponding to that name. Fetching can be done with the
        following:

        from caffe2.python import workspace (if not already imported)
        workspace.FetchBlob(blob_name)
        workspace.FetchBlobs([blob_name1, blob_name2, ...])
        )Ú
isinstancer#   )r%   Úitemr*   r*   r+   Ú_check_caffe2_blob  s    z SummaryWriter._check_caffe2_blobc                 C   sŠ   | j dks| jdkr„t| j| j| j| jƒ| _| j ¡ | ji| _ | jdk	r„| j}| j 	t
|dd¡ | j 	t
|ttjdd¡ d| _| jS )z@Returns the default FileWriter instance. Recreates it if closed.Nzbrain.Event:2)r1   Zfile_version)Ústatus)r1   Zsession_log)rV   rU   r   r&   r'   r(   r)   r-   rT   r2   r   r   ÚSTART)r%   Zmost_recent_stepr*   r*   r+   rW     s*       ÿ

ÿ
þÿzSummaryWriter._get_file_writerc                 C   s   | j S )z8Returns the directory where event files will be written.©r&   r.   r*   r*   r+   r-   &  s    zSummaryWriter.get_logdirc              	   C   sÀ   t j d¡ t|ƒtk	s$t|ƒtk	r,tdƒ‚t|||ƒ\}}}|sNtt ¡ ƒ}t	j
 |  ¡  ¡ |¡}t|dH}	|	j |¡ |	j |¡ |	j |¡ | ¡ D ]\}
}|	 |
|¡ qœW 5 Q R X dS )a   Add a set of hyperparameters to be compared in TensorBoard.

        Args:
            hparam_dict (dict): Each key-value pair in the dictionary is the
              name of the hyper parameter and it's corresponding value.
              The type of the value can be one of `bool`, `string`, `float`,
              `int`, or `None`.
            metric_dict (dict): Each key-value pair in the dictionary is the
              name of the metric and it's corresponding value. Note that the key used
              here should be unique in the tensorboard record. Otherwise the value
              you added by ``add_scalar`` will be displayed in hparam plugin. In most
              cases, this is unwanted.
            hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that
              contains names of the hyperparameters and all discrete values they can hold
            run_name (str): Name of the run, to be included as part of the logdir.
              If unspecified, will use current timestamp.

        Examples::

            from torch.utils.tensorboard import SummaryWriter
            with SummaryWriter() as w:
                for i in range(5):
                    w.add_hparams({'lr': 0.1*i, 'bsize': i},
                                  {'hparam/accuracy': 10*i, 'hparam/loss': 10*i})

        Expected result:

        .. image:: _static/img/tensorboard/add_hparam.png
           :scale: 50 %

        ztensorboard.logging.add_hparamsz1hparam_dict and metric_dict should be dictionary.rb   N)rJ   rK   rL   ÚtypeÚdictÚ	TypeErrorr   r#   r/   rP   rQ   rR   rW   r-   rE   rU   r7   ÚitemsÚ
add_scalar)r%   Zhparam_dictZmetric_dictZhparam_domain_discreteZrun_nameÚexpZssiZseiZlogdirZw_hpÚkr\   r*   r*   r+   Úadd_hparams*  s    "zSummaryWriter.add_hparamsFc           	      C   sR   t j d¡ |  |¡r,ddlm} | |¡}t||||d}|  ¡  	|||¡ dS )ah  Add scalar data to summary.

        Args:
            tag (string): Data identifier
            scalar_value (float or string/blobname): Value to save
            global_step (int): Global step value to record
            walltime (float): Optional override default walltime (time.time())
              with seconds after epoch of event
            new_style (boolean): Whether to use new style (tensor field) or old
              style (simple_value field). New style could lead to faster data loading.
        Examples::

            from torch.utils.tensorboard import SummaryWriter
            writer = SummaryWriter()
            x = range(100)
            for i in x:
                writer.add_scalar('y=2x', i * 2, i)
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_scalar.png
           :scale: 50 %

        ztensorboard.logging.add_scalarr   ©Ú	workspace)Ú	new_styleÚdouble_precisionN)
rJ   rK   rL   r_   Úcaffe2.pythonrl   Ú	FetchBlobr   rW   r7   )	r%   r9   Úscalar_valuer6   r4   rm   rn   rl   r5   r*   r*   r+   rg   [  s    "

   ÿzSummaryWriter.add_scalarc                 C   sØ   t j d¡ |dkrt ¡ n|}|  ¡  ¡ }| ¡ D ]ž\}}|d | dd¡ d | }| jdk	sft	‚|| j 
¡ kr€| j| }	nt|| j| j| jƒ}	|	| j|< |  |¡r¾ddlm}
 |
 |¡}|	 t||ƒ||¡ q4dS )a  Adds many scalar data to summary.

        Args:
            main_tag (string): The parent name for the tags
            tag_scalar_dict (dict): Key-value pair storing the tag and corresponding values
            global_step (int): Global step value to record
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event

        Examples::

            from torch.utils.tensorboard import SummaryWriter
            writer = SummaryWriter()
            r = 5
            for i in range(100):
                writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r),
                                                'xcosx':i*np.cos(i/r),
                                                'tanx': np.tan(i/r)}, i)
            writer.close()
            # This call adds three values to the same scalar plot with the tag
            # 'run_14h' in TensorBoard's scalar section.

        Expected result:

        .. image:: _static/img/tensorboard/add_scalars.png
           :scale: 50 %

        ztensorboard.logging.add_scalarsNú/rH   r   rk   )rJ   rK   rL   r/   rW   r-   rf   ÚreplacerV   ÚAssertionErrorÚkeysr   r'   r(   r)   r_   ro   rl   rp   r7   r   )r%   Zmain_tagZtag_scalar_dictr6   r4   Z	fw_logdirr9   rq   Zfw_tagÚfwrl   r*   r*   r+   Úadd_scalarsˆ  s&       ÿ


zSummaryWriter.add_scalarsÚ
tensorflowc                 C   sf   t j d¡ |  |¡r,ddlm} | |¡}t|tƒrD|dkrD| j	}|  
¡  t||||d||¡ dS )a  Add histogram to summary.

        Args:
            tag (string): Data identifier
            values (torch.Tensor, numpy.array, or string/blobname): Values to build histogram
            global_step (int): Global step value to record
            bins (string): One of {'tensorflow','auto', 'fd', ...}. This determines how the bins are made. You can find
              other options in: https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event

        Examples::

            from torch.utils.tensorboard import SummaryWriter
            import numpy as np
            writer = SummaryWriter()
            for i in range(10):
                x = np.random.random(1000)
                writer.add_histogram('distribution centers', x + i, i)
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_histogram.png
           :scale: 50 %

        z!tensorboard.logging.add_histogramr   rk   rx   )Úmax_binsN)rJ   rK   rL   r_   ro   rl   rp   r]   r#   rY   rW   r7   r   )r%   r9   Úvaluesr6   Zbinsr4   ry   rl   r*   r*   r+   Úadd_histogram¸  s    $

  ÿzSummaryWriter.add_histogramc                 C   sL   t j d¡ t|ƒt|ƒkr$tdƒ‚|  ¡  t||||||||ƒ|	|
¡ dS )aˆ  Adds histogram with raw data.

        Args:
            tag (string): Data identifier
            min (float or int): Min value
            max (float or int): Max value
            num (int): Number of values
            sum (float or int): Sum of all values
            sum_squares (float or int): Sum of squares for all values
            bucket_limits (torch.Tensor, numpy.array): Upper value per bucket.
              The number of elements of it should be the same as `bucket_counts`.
            bucket_counts (torch.Tensor, numpy.array): Number of values per bucket
            global_step (int): Global step value to record
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
            see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/histogram/README.md

        Examples::

            from torch.utils.tensorboard import SummaryWriter
            import numpy as np
            writer = SummaryWriter()
            dummy_data = []
            for idx, value in enumerate(range(50)):
                dummy_data += [idx + 0.001] * value

            bins = list(range(50+2))
            bins = np.array(bins)
            values = np.array(dummy_data).astype(float).reshape(-1)
            counts, limits = np.histogram(values, bins=bins)
            sum_sq = values.dot(values)
            writer.add_histogram_raw(
                tag='histogram_with_raw_data',
                min=values.min(),
                max=values.max(),
                num=len(values),
                sum=values.sum(),
                sum_squares=sum_sq,
                bucket_limits=limits[1:].tolist(),
                bucket_counts=counts.tolist(),
                global_step=0)
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_histogram_raw.png
           :scale: 50 %

        z%tensorboard.logging.add_histogram_rawz;len(bucket_limits) != len(bucket_counts), see the document.N)rJ   rK   rL   ÚlenÚ
ValueErrorrW   r7   r   )r%   r9   ÚminÚmaxÚnumÚsumZsum_squaresZbucket_limitsZbucket_countsr6   r4   r*   r*   r+   Úadd_histogram_rawç  s&    >ÿ       ÿûzSummaryWriter.add_histogram_rawÚCHWc                 C   sL   t j d¡ |  |¡r,ddlm} | |¡}|  ¡  t	|||d||¡ dS )a(  Add image data to summary.

        Note that this requires the ``pillow`` package.

        Args:
            tag (string): Data identifier
            img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data
            global_step (int): Global step value to record
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
            dataformats (string): Image data format specification of the form
              CHW, HWC, HW, WH, etc.
        Shape:
            img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to
            convert a batch of tensor into 3xHxW format or call ``add_images`` and let us do the job.
            Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitable as long as
            corresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``.

        Examples::

            from torch.utils.tensorboard import SummaryWriter
            import numpy as np
            img = np.zeros((3, 100, 100))
            img[0] = np.arange(0, 10000).reshape(100, 100) / 10000
            img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000

            img_HWC = np.zeros((100, 100, 3))
            img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000
            img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000

            writer = SummaryWriter()
            writer.add_image('my_image', img, 0)

            # If you have non-default dimension setting, set the dataformats argument.
            writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC')
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_image.png
           :scale: 50 %

        ztensorboard.logging.add_imager   rk   ©ÚdataformatsN©
rJ   rK   rL   r_   ro   rl   rp   rW   r7   r   ©r%   r9   Ú
img_tensorr6   r4   r…   rl   r*   r*   r+   Ú	add_image2  s    .

  ÿzSummaryWriter.add_imageÚNCHWc                 C   sL   t j d¡ |  |¡r,ddlm} | |¡}|  ¡  t	|||d||¡ dS )a6  Add batched image data to summary.

        Note that this requires the ``pillow`` package.

        Args:
            tag (string): Data identifier
            img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data
            global_step (int): Global step value to record
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
            dataformats (string): Image data format specification of the form
              NCHW, NHWC, CHW, HWC, HW, WH, etc.
        Shape:
            img_tensor: Default is :math:`(N, 3, H, W)`. If ``dataformats`` is specified, other shape will be
            accepted. e.g. NCHW or NHWC.

        Examples::

            from torch.utils.tensorboard import SummaryWriter
            import numpy as np

            img_batch = np.zeros((16, 3, 100, 100))
            for i in range(16):
                img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i
                img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i

            writer = SummaryWriter()
            writer.add_images('my_image_batch', img_batch, 0)
            writer.close()

        Expected result:

        .. image:: _static/img/tensorboard/add_images.png
           :scale: 30 %

        ztensorboard.logging.add_imagesr   rk   r„   Nr†   r‡   r*   r*   r+   Ú
add_imagesi  s    '

  ÿzSummaryWriter.add_imagesr   c	           
   
   C   s    t j d¡ |  |¡r,ddlm}	 |	 |¡}|  |¡rLddlm}	 |	 |¡}|dk	rzt|tƒrd|g}t	|ƒ|j
d krzd}|  ¡  t||||||d||¡ dS )au  Add image and draw bounding boxes on the image.

        Args:
            tag (string): Data identifier
            img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data
            box_tensor (torch.Tensor, numpy.array, or string/blobname): Box data (for detected objects)
              box should be represented as [x1, y1, x2, y2].
            global_step (int): Global step value to record
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
            rescale (float): Optional scale override
            dataformats (string): Image data format specification of the form
              NCHW, NHWC, CHW, HWC, HW, WH, etc.
            labels (list of string): The label to be shown for each bounding box.
        Shape:
            img_tensor: Default is :math:`(3, H, W)`. It can be specified with ``dataformats`` argument.
            e.g. CHW or HWC

            box_tensor: (torch.Tensor, numpy.array, or string/blobname): NX4,  where N is the number of
            boxes and each 4 elements in a row represents (xmin, ymin, xmax, ymax).
        z(tensorboard.logging.add_image_with_boxesr   rk   N)Úrescaler…   Úlabels)rJ   rK   rL   r_   ro   rl   rp   r]   r#   r|   ÚshaperW   r7   r   )
r%   r9   rˆ   Z
box_tensorr6   r4   rŒ   r…   r   rl   r*   r*   r+   Úadd_image_with_boxes™  s0     




úöz"SummaryWriter.add_image_with_boxesTc                 C   sP   t j d¡ t|tƒr2| j|t||ƒ||dd n| j|t||ƒ||dd dS )a  Render matplotlib figure into an image and add it to summary.

        Note that this requires the ``matplotlib`` package.

        Args:
            tag (string): Data identifier
            figure (matplotlib.pyplot.figure) or list of figures: Figure or a list of figures
            global_step (int): Global step value to record
            close (bool): Flag to automatically close the figure
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
        ztensorboard.logging.add_figurerŠ   r„   rƒ   N)rJ   rK   rL   r]   Úlistr‰   r   )r%   r9   Úfigurer6   r?   r4   r*   r*   r+   Ú
add_figureÔ  s     
ûûzSummaryWriter.add_figureé   c                 C   s*   t j d¡ |  ¡  t|||ƒ||¡ dS )a>  Add video data to summary.

        Note that this requires the ``moviepy`` package.

        Args:
            tag (string): Data identifier
            vid_tensor (torch.Tensor): Video data
            global_step (int): Global step value to record
            fps (float or int): Frames per second
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
        Shape:
            vid_tensor: :math:`(N, T, C, H, W)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`.
        ztensorboard.logging.add_videoN)rJ   rK   rL   rW   r7   r   )r%   r9   Z
vid_tensorr6   Zfpsr4   r*   r*   r+   Ú	add_videoó  s    
  ÿzSummaryWriter.add_videoéD¬  c                 C   sL   t j d¡ |  |¡r,ddlm} | |¡}|  ¡  t	|||d||¡ dS )aÒ  Add audio data to summary.

        Args:
            tag (string): Data identifier
            snd_tensor (torch.Tensor): Sound data
            global_step (int): Global step value to record
            sample_rate (int): sample rate in Hz
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
        Shape:
            snd_tensor: :math:`(1, L)`. The values should lie between [-1, 1].
        ztensorboard.logging.add_audior   rk   )Úsample_rateN)
rJ   rK   rL   r_   ro   rl   rp   rW   r7   r   )r%   r9   Z
snd_tensorr6   r–   r4   rl   r*   r*   r+   Ú	add_audio  s    

  ÿzSummaryWriter.add_audioc                 C   s(   t j d¡ |  ¡  t||ƒ||¡ dS )aÈ  Add text data to summary.

        Args:
            tag (string): Data identifier
            text_string (string): String to save
            global_step (int): Global step value to record
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
        Examples::

            writer.add_text('lstm', 'This is an lstm', 0)
            writer.add_text('rnn', 'This is an rnn', 10)
        ztensorboard.logging.add_textN)rJ   rK   rL   rW   r7   r   )r%   r9   Ztext_stringr6   r4   r*   r*   r+   Úadd_text  s      ÿzSummaryWriter.add_textc                 C   s"   t j d¡ |  ¡  t|ƒ¡ d S )Nz"tensorboard.logging.add_onnx_graph)rJ   rK   rL   rW   r<   r   )r%   Zprototxtr*   r*   r+   r<   2  s    zSummaryWriter.add_onnx_graphc                 C   sÄ   t j d¡ t|dƒr0|  ¡  t||||ƒ¡ nddlm} ddl	m
} ddlm}m}m}	 t|tƒršt|d |jƒr€||ƒ}
q¢t|d |jƒr¢|	|ƒ}
n||ƒ}
tj|
 ¡ d}|  ¡  |¡ d	S )
a  Add graph data to summary.

        Args:
            model (torch.nn.Module): Model to draw.
            input_to_model (torch.Tensor or list of torch.Tensor): A variable or a tuple of
                variables to be fed.
            verbose (bool): Whether to print graph structure in console.
            use_strict_trace (bool): Whether to pass keyword argument `strict` to
                `torch.jit.trace`. Pass False when you want the tracer to
                record your mutable container types (list, dict)
        ztensorboard.logging.add_graphZforwardr   )Ú
caffe2_pb2)Úcorer   )Úmodel_to_graph_defÚnets_to_graph_defÚprotos_to_graph_defr8   N)rJ   rK   rL   ÚhasattrrW   r;   r   Zcaffe2.protor™   ro   rš   Z_caffe2_graphr›   rœ   r   r]   r   ZNetZNetDefr   r   r:   r2   )r%   ÚmodelZinput_to_modelÚverboseZuse_strict_tracer™   rš   r›   rœ   r   Zcurrent_graphr3   r*   r*   r+   r;   6  s     
ÿ


zSummaryWriter.add_graphc                 C   sD   | }|  ddtdƒ ¡}|  ddtdƒ ¡}|  ddtdƒ ¡}|S )Nú%z%%%02xrr   ú\)rs   Úord)ZrawstrÚretvalr*   r*   r+   Ú_encode_  s
    zSummaryWriter._encodeÚdefaultc                 C   sv  t j d¡ t|ƒ}|dkr d}dt|ƒ d¡|  |¡f }tj 	|  
¡  ¡ |¡}tjj |¡}	|	 |¡rŒ|	 |¡r~tdƒ q–td| ƒ‚n
|	 |¡ |dk	rÆ|jd t|ƒks¸tdƒ‚t|||d	 |dk	rô|jd |jd ksêtd
ƒ‚t||ƒ |jdkstdƒ‚t||ƒ t| dƒs&tƒ | _t|||	|||ƒ}
| jj  !|
g¡ ddl"m#} | $| j¡}t%|  
¡  ¡ |ƒ dS )aÝ  Add embedding projector data to summary.

        Args:
            mat (torch.Tensor or numpy.array): A matrix which each row is the feature vector of the data point
            metadata (list): A list of labels, each element will be convert to string
            label_img (torch.Tensor): Images correspond to each data point
            global_step (int): Global step value to record
            tag (string): Name for the embedding
        Shape:
            mat: :math:`(N, D)`, where N is number of data and D is feature dimension

            label_img: :math:`(N, C, H, W)`

        Examples::

            import keyword
            import torch
            meta = []
            while len(meta)<100:
                meta = meta+keyword.kwlist # get some strings
            meta = meta[:100]

            for i, v in enumerate(meta):
                meta[i] = v+str(i)

            label_img = torch.rand(100, 3, 10, 32)
            for i in range(100):
                label_img[i]*=i/100.0

            writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img)
            writer.add_embedding(torch.randn(100, 5), label_img=label_img)
            writer.add_embedding(torch.randn(100, 5), metadata=meta)
        z!tensorboard.logging.add_embeddingNr   z%s/%sé   zKwarning: Embedding dir exists, did you set global_step for add_embedding()?z1Path: `%s` exists, but is a file. Cannot proceed.z&#labels should equal with #data points)Úmetadata_headerz&#images should equal with #data pointsé   z@mat should be 2D, where mat.size(0) is the number of data pointsÚ_projector_config)Útext_format)&rJ   rK   rL   r	   r#   Úzfillr¥   rP   rQ   rR   rW   r-   r   ÚioZgfileZget_filesystemÚexistsÚisdirÚprintÚ	ExceptionÚmakedirsrŽ   r|   rt   r   r   Úndimr
   rž   r   rª   r   Z
embeddingsÚextendZgoogle.protobufr«   ZMessageToStringr   )r%   ÚmatÚmetadataZ	label_imgr6   r9   r¨   ÚsubdirZ	save_pathÚfsZembedding_infor«   Zconfig_pbtxtr*   r*   r+   Úadd_embeddingh  s`    *

ÿÿ

ÿþÿþ
ÿþ
     ÿzSummaryWriter.add_embeddingé   c                 C   s@   t j d¡ t|ƒt|ƒ }}|  ¡  t|||||ƒ||¡ dS )ar  Adds precision recall curve.
        Plotting a precision-recall curve lets you understand your model's
        performance under different threshold settings. With this function,
        you provide the ground truth labeling (T/F) and prediction confidence
        (usually the output of your model) for each target. The TensorBoard UI
        will let you choose the threshold interactively.

        Args:
            tag (string): Data identifier
            labels (torch.Tensor, numpy.array, or string/blobname):
              Ground truth data. Binary label for each element.
            predictions (torch.Tensor, numpy.array, or string/blobname):
              The probability that an element be classified as true.
              Value should be in [0, 1]
            global_step (int): Global step value to record
            num_thresholds (int): Number of thresholds used to draw the curve.
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event

        Examples::

            from torch.utils.tensorboard import SummaryWriter
            import numpy as np
            labels = np.random.randint(2, size=100)  # binary label
            predictions = np.random.rand(100)
            writer = SummaryWriter()
            writer.add_pr_curve('pr_curve', labels, predictions, 0)
            writer.close()

        z tensorboard.logging.add_pr_curveN)rJ   rK   rL   r	   rW   r7   r   )r%   r9   r   Zpredictionsr6   Únum_thresholdsÚweightsr4   r*   r*   r+   Úadd_pr_curveÊ  s    (ýzSummaryWriter.add_pr_curvec                 C   s6   t j d¡ |  ¡  t||||||||	|
ƒ	||¡ dS )a  Adds precision recall curve with raw data.

        Args:
            tag (string): Data identifier
            true_positive_counts (torch.Tensor, numpy.array, or string/blobname): true positive counts
            false_positive_counts (torch.Tensor, numpy.array, or string/blobname): false positive counts
            true_negative_counts (torch.Tensor, numpy.array, or string/blobname): true negative counts
            false_negative_counts (torch.Tensor, numpy.array, or string/blobname): false negative counts
            precision (torch.Tensor, numpy.array, or string/blobname): precision
            recall (torch.Tensor, numpy.array, or string/blobname): recall
            global_step (int): Global step value to record
            num_thresholds (int): Number of thresholds used to draw the curve.
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event
            see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/README.md
        z$tensorboard.logging.add_pr_curve_rawN)rJ   rK   rL   rW   r7   r   )r%   r9   Ztrue_positive_countsZfalse_positive_countsZtrue_negative_countsZfalse_negative_countsZ	precisionZrecallr6   r»   r¼   r4   r*   r*   r+   Úadd_pr_curve_rawú  s     ÷ózSummaryWriter.add_pr_curve_rawÚuntitledc                 C   s2   t j d¡ ||d|gii}|  ¡  t|ƒ¡ dS )aJ  Shorthand for creating multilinechart. Similar to ``add_custom_scalars()``, but the only necessary argument
        is *tags*.

        Args:
            tags (list): list of tags that have been used in ``add_scalar()``

        Examples::

            writer.add_custom_scalars_multilinechart(['twse/0050', 'twse/2330'])
        z5tensorboard.logging.add_custom_scalars_multilinechartZ	MultilineN©rJ   rK   rL   rW   r7   r   ©r%   ÚtagsÚcategoryÚtitleÚlayoutr*   r*   r+   Ú!add_custom_scalars_multilinechart)  s
    ÿz/SummaryWriter.add_custom_scalars_multilinechartc                 C   sB   t j d¡ t|ƒdkst‚||d|gii}|  ¡  t|ƒ¡ dS )aw  Shorthand for creating marginchart. Similar to ``add_custom_scalars()``, but the only necessary argument
        is *tags*, which should have exactly 3 elements.

        Args:
            tags (list): list of tags that have been used in ``add_scalar()``

        Examples::

            writer.add_custom_scalars_marginchart(['twse/0050', 'twse/2330', 'twse/2006'])
        z2tensorboard.logging.add_custom_scalars_margincharté   ZMarginN)rJ   rK   rL   r|   rt   rW   r7   r   rÁ   r*   r*   r+   Úadd_custom_scalars_marginchart<  s    ÿz,SummaryWriter.add_custom_scalars_marginchartc                 C   s"   t j d¡ |  ¡  t|ƒ¡ dS )a  Create special chart by collecting charts tags in 'scalars'. Note that this function can only be called once
        for each SummaryWriter() object. Because it only provides metadata to tensorboard, the function can be called
        before or after the training loop.

        Args:
            layout (dict): {categoryName: *charts*}, where *charts* is also a dictionary
              {chartName: *ListOfProperties*}. The first element in *ListOfProperties* is the chart's type
              (one of **Multiline** or **Margin**) and the second element should be a list containing the tags
              you have used in add_scalar function, which will be collected into the new chart.

        Examples::

            layout = {'Taiwan':{'twse':['Multiline',['twse/0050', 'twse/2330']]},
                         'USA':{ 'dow':['Margin',   ['dow/aaa', 'dow/bbb', 'dow/ccc']],
                              'nasdaq':['Margin',   ['nasdaq/aaa', 'nasdaq/bbb', 'nasdaq/ccc']]}}

            writer.add_custom_scalars(layout)
        z&tensorboard.logging.add_custom_scalarsNrÀ   )r%   rÅ   r*   r*   r+   Úadd_custom_scalarsP  s    z SummaryWriter.add_custom_scalarsc                 C   s.   t j d¡ |  ¡  t|||||ƒ||¡ dS )af  Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js,
        so it allows users to interact with the rendered object. Besides the basic definitions
        such as vertices, faces, users can further provide camera parameter, lighting condition, etc.
        Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for
        advanced usage.

        Args:
            tag (string): Data identifier
            vertices (torch.Tensor): List of the 3D coordinates of vertices.
            colors (torch.Tensor): Colors for each vertex
            faces (torch.Tensor): Indices of vertices within each triangle. (Optional)
            config_dict: Dictionary with ThreeJS classes names and configuration.
            global_step (int): Global step value to record
            walltime (float): Optional override default walltime (time.time())
              seconds after epoch of event

        Shape:
            vertices: :math:`(B, N, 3)`. (batch, number_of_vertices, channels)

            colors: :math:`(B, N, 3)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`.

            faces: :math:`(B, N, 3)`. The values should lie in [0, number_of_vertices] for type `uint8`.

        Examples::

            from torch.utils.tensorboard import SummaryWriter
            vertices_tensor = torch.as_tensor([
                [1, 1, 1],
                [-1, -1, 1],
                [1, -1, -1],
                [-1, 1, -1],
            ], dtype=torch.float).unsqueeze(0)
            colors_tensor = torch.as_tensor([
                [255, 0, 0],
                [0, 255, 0],
                [0, 0, 255],
                [255, 0, 255],
            ], dtype=torch.int).unsqueeze(0)
            faces_tensor = torch.as_tensor([
                [0, 2, 3],
                [0, 3, 1],
                [0, 1, 2],
                [1, 3, 2],
            ], dtype=torch.int).unsqueeze(0)

            writer = SummaryWriter()
            writer.add_mesh('my_mesh', vertices=vertices_tensor, colors=colors_tensor, faces=faces_tensor)

            writer.close()
        ztensorboard.logging.add_meshN)rJ   rK   rL   rW   r7   r   )r%   r9   ZverticesÚcolorsZfacesZconfig_dictr6   r4   r*   r*   r+   Úadd_meshf  s    <  ÿzSummaryWriter.add_meshc                 C   s*   | j dkrdS | j  ¡ D ]}| ¡  qdS r=   )rV   rz   r>   ©r%   Úwriterr*   r*   r+   r>   §  s    
zSummaryWriter.flushc                 C   s>   | j d krd S | j  ¡ D ]}| ¡  | ¡  qd  | _| _ d S ©N)rV   rz   r>   r?   rU   rÌ   r*   r*   r+   r?   ±  s    

zSummaryWriter.closec                 C   s   | S rÎ   r*   r.   r*   r*   r+   Ú	__enter__¹  s    zSummaryWriter.__enter__c                 C   s   |   ¡  d S rÎ   )r?   )r%   Úexc_typeÚexc_valÚexc_tbr*   r*   r+   Ú__exit__¼  s    zSummaryWriter.__exit__)Nr"   Nr    r!   r"   )NN)NNFF)NN)Nrx   NN)NN)NNrƒ   )NNrŠ   )NNr   rƒ   N)NTN)Nr“   N)Nr•   N)NN)NFT)NNNr¦   N)Nrº   NN)Nrº   NN)r¦   r¿   )r¦   r¿   )NNNNN)#rA   rB   rC   rD   r,   r_   rW   r-   rj   rg   rw   r{   r‚   r‰   r‹   r   r’   r”   r—   r˜   r<   r;   Ústaticmethodr¥   r¹   r½   r¾   rÆ   rÈ   rÉ   rË   r>   r?   rÏ   rÓ   r*   r*   r*   r+   rE   ¦   s²         ù
Q   ÿ
5    ù
-
4    ù
9  õ
L     ÿ
8     ÿ
5     ÷
;

     ÿ

     ÿ
)
     ù
g    ø
9    ô
0   ÿ
   ÿ
     ø
A
rE   ).rD   rP   r/   rJ   Ztensorboard.compatr   Z"tensorboard.compat.proto.event_pb2r   r   Ztensorboard.compat.protor   Z2tensorboard.plugins.projector.projector_config_pb2r   Z,tensorboard.summary.writer.event_file_writerr   Z_convert_npr	   Z
_embeddingr
   r   r   r   r   Z_onnx_graphr   Z_pytorch_graphr   Ú_utilsr   r5   r   r   r   r   r   r   r   r   r   r   r   r   r   Úobjectr   rE   r*   r*   r*   r+   Ú<module>   s"   <{