
    JThG                     J   S r SSKrSSKrSSKJrJrJr  SSKr\(       a  SSKJ	r	  SSK
Jr  SSKJr  SSKJrJr  SSKJr  SS	KJr  S
SKJr  S
SKJrJrJrJrJr  S
SKJr  S
SKJ r   S
SK!J"r"  S
SK#J$r$J%r%J&r&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.J/r/J0r0J1r1  SS/r2 " S S5      r3 " S S5      r4g)zkProvide an API for writing protocol buffers to event files to be consumed by TensorBoard for visualization.    N)OptionalTYPE_CHECKINGUnion)Figure)tf)	event_pb2)Event
SessionLog)ProjectorConfig)EventFileWriter   )make_np)get_embedding_infomake_matmake_spritemake_tsvwrite_pbtxt)load_onnx_graph)graph)figure_to_image)audiocustom_scalars	histogramhistogram_rawhparamsimageimage_boxesmeshpr_curvepr_curve_rawscalartensor_prototextvideo
FileWriterSummaryWriterc                   b    \ rS rSrSrSS jrS rSS jrSS jrSS jr	SS	 jr
S
 rS rS rSrg)r%   +   a  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.
c                 <    [        U5      n[        XX45      U l        g)a  Create 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_suffixs        V/var/www/auris/envauris/lib/python3.13/site-packages/torch/utils/tensorboard/writer.py__init__FileWriter.__init__5   s    , g,+

    c                 6    U R                   R                  5       $ )z6Return the directory where event file will be written.)r+   
get_logdirr,   s    r1   r6   FileWriter.get_logdirP   s      ++--r4   Nc                     Uc  [         R                   " 5       OUUl        Ub  [        U5      Ul        U R                  R                  U5        g)a%  Add 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)time	wall_timeintstepr+   	add_event)r,   eventr=   walltimes       r1   r>   FileWriter.add_eventT   s?     *2)9$))+x TEJ##E*r4   c                 P    [         R                  " US9nU R                  XBU5        g)a  Add 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	   r>   )r,   rC   global_stepr@   r?   s        r1   add_summaryFileWriter.add_summarye   s      0u84r4   c                    US   nUS   n[         R                  " UR                  " 5       S9nU R                  USU5        [         R                  " SUR                  5       S9n[         R                  " US9nU R                  USU5        g)zAdd 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   	graph_defNstep1)tagrun_metadata)tagged_run_metadata)r   r	   SerializeToStringr>   TaggedRunMetadata)r,   graph_profiler@   r   	stepstatsr?   trms          r1   	add_graphFileWriter.add_graphu   s}     a !!$	%*A*A*CDudH-))i&A&A&C
 C8udH-r4   c                 p    [         R                  " UR                  " 5       S9nU R                  USU5        g)zAdd 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())
rH   N)r   r	   rN   r>   )r,   r   r@   r?   s       r1   add_onnx_graphFileWriter.add_onnx_graph   s+     %*A*A*CDudH-r4   c                 8    U R                   R                  5         gzrFlushes the event file to disk.

Call this method to make sure that all pending events have been written to
disk.
N)r+   flushr7   s    r1   rZ   FileWriter.flush   s     	!r4   c                 8    U R                   R                  5         g)zvFlushes the event file to disk and close the file.

Call this method when you do not need the summary writer anymore.
N)r+   closer7   s    r1   r]   FileWriter.close   s    
 	!r4   c                 8    U R                   R                  5         g)zReopens 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+   reopenr7   s    r1   r`   FileWriter.reopen   s     	  "r4   )r+   )
   x    NNN)__name__
__module____qualname____firstlineno____doc__r2   r6   r>   rE   rS   rV   rZ   r]   r`   __static_attributes__ r4   r1   r%   r%   +   s4    
6.+"5 .&	.""#r4   c                      \ rS rSrSr      S*S jrS rS r   S+S jr    S,S jr	S-S	 jr
  S-S
 jr    S.S jr  S-S jr S/S jr S0S jr     S1S jr   S2S\S\S\S   4   S\\   S\S\\   SS4S jjrS3S jr S4S jrS-S jrS r S5S jr\S 5       r     S6S jr     S7S jr!    S7S  jr" S8S! jr# S8S" jr$S# r%     S9S$ jr&S% r'S& r(S' r)S( r*S)r+g):r&      a  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.
Nc                 (   [         R                  R                  S5        U(       d`  SSKnSSKJn  UR                  5       R                  S5      n	[        R                  R                  SU	S-   UR                  5       -   U-   5      nXl        X0l        X@l        XPl        X`l        S=U l        U l        U R%                  5         Sn
/ n/ nU
S	:  a0  UR'                  U
5        UR'                  U
* 5        U
S
-  n
U
S	:  a  M0  USSS2   S/-   U-   U l        g)ah  Create a `SummaryWriter` that will write out events and summaries to the event file.

Args:
    log_dir (str): 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 (str): 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 (str): 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socketrq   nowstrftimeospathjoingethostnamer-   
purge_stepr.   r/   r0   file_writerall_writers_get_file_writerappenddefault_bins)r,   r-   commentr   r.   r/   r0   rx   rq   current_timevbucketsneg_bucketss                r1   r2   SummaryWriter.__init__   s   d 	$$%GH)#<<>22?CLgglls*V-?-?-AAGKG $"$. /324+ $hNN1r"HA $h ("-3g=r4   c           	         U R                   b  U R                  c  [        U R                  U R                  U R
                  U R                  5      U l        U R                  R                  5       U R                  0U l         U R                  bn  U R                  nU R                  R                  [        USS95        U R                  R                  [        U[        [        R                  S9S95        SU l        U R                  $ )z?Return the default FileWriter instance. Recreates it if closed.Nzbrain.Event:2)r=   file_version)status)r=   session_log)r   r   r%   r-   r.   r/   r0   r6   r   r>   r	   r
   START)r,   most_recent_steps     r1   r   SummaryWriter._get_file_writer  s    #t'7'7'?)dnndoot?S?S D !% 0 0 ; ; =t?O?OPD*#'??   **/oN   **-$.j6F6F$G #'r4   c                     U R                   $ )z7Return the directory where event files will be written.r-   r7   s    r1   r6   SummaryWriter.get_logdir  s    ||r4   c                    [         R                  R                  S5        [        U5      [        Ld  [        U5      [        La  [        S5      e[        XU5      u  pgnU(       d  [        [        R                  " 5       5      n[        R                  R                  U R                  5       R                  5       U5      n	[        U	S9 n
U
R                  R!                  Xe5        U
R                  R!                  Xu5        U
R                  R!                  X5        UR#                  5        H  u  pU
R%                  XU5        M     SSS5        g! , (       d  f       g= f)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.
    global_step (int): Global step value to record

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.r   N)ru   rv   rw   typedict	TypeErrorr   r*   r:   r{   r|   r}   r   r6   r&   r   rE   items
add_scalar)r,   hparam_dictmetric_dicthparam_domain_discreterun_namerD   expssiseilogdirw_hpkr   s                r1   add_hparamsSummaryWriter.add_hparams  s    P 	$$%FGD(D,=T,IOPP:PQ#499;'Hd335@@BHM6*d((:((:((:#))+k2 ,	 +**s   A=E
Ec                     [         R                  R                  S5        [        XXVS9nU R	                  5       R                  XsU5        g)a  Add scalar data to summary.

Args:
    tag (str): 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_scalar)	new_styledouble_precisionN)ru   rv   rw   r!   r   rE   )r,   rK   scalar_valuerD   r@   r   r   rC   s           r1   r   SummaryWriter.add_scalarV  sB    D 	$$%EF
 	++G(Kr4   c                 @   [         R                  R                  S5        Uc  [        R                  " 5       OUnU R	                  5       R                  5       nUR                  5        H  u  pgUS-   UR                  SS5      -   S-   U-   nU R                  c   eXR                  R                  5       ;   a  U R                  U   n	O9[        XR                  U R                  U R                  5      n	XR                  U'   U	R                  [        X5      X45        M     g)am  Add many scalar data to summary.

Args:
    main_tag (str): 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/rs   )ru   rv   rw   r:   r   r6   r   replacer   keysr%   r.   r/   r0   rE   r!   )
r,   main_tagtag_scalar_dictrD   r@   	fw_logdirrK   r   fw_tagfws
             r1   add_scalarsSummaryWriter.add_scalars  s    : 	$$%FG"*"2499;))+668	!0!6!6!8C_x'7'7S'AACG#MF##///))..00%%f-NNDOOT=Q=Q ,.  (NN6(9;Q "9r4   c                     [         R                  R                  S5        [        X5      nU R	                  5       R                  XSU5        g)a  Add tensor data to summary.

Args:
    tag (str): Data identifier
    tensor (torch.Tensor): tensor to save
    global_step (int): Global step value to record
Examples::

    from torch.utils.tensorboard import SummaryWriter
    writer = SummaryWriter()
    x = torch.tensor([1,2,3])
    writer.add_scalar('x', x)
    writer.close()

Expected result:
    Summary::tensor::float_val [1,2,3]
           ::tensor::shape [3]
           ::tag 'x'

ztensorboard.logging.add_tensorN)ru   rv   rw   r"   r   rE   )r,   rK   tensorrD   r@   rC   s         r1   
add_tensorSummaryWriter.add_tensor  s:    6 	$$%EFs+++G(Kr4   c           	          [         R                  R                  S5        [        U[        5      (       a  US:X  a  U R
                  nU R                  5       R                  [        XXFS9X55        g)aa  Add histogram to summary.

Args:
    tag (str): Data identifier
    values (torch.Tensor, numpy.ndarray, or string/blobname): Values to build histogram
    global_step (int): Global step value to record
    bins (str): 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_histogram
tensorflow)max_binsN)	ru   rv   rw   
isinstancer*   r   r   rE   r   )r,   rK   valuesrD   binsr@   r   s          r1   add_histogramSummaryWriter.add_histogram  sZ    H 	$$%HIdC  T\%9$$D++c4;[	
r4   c                     [         R                  R                  S5        [        U5      [        U5      :w  a  [	        S5      eU R                  5       R                  [        XX4XVXx5      U	U
5        g)a@  Add histogram with raw data.

Args:
    tag (str): 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.ndarray): Upper value per bucket.
      The number of elements of it should be the same as `bucket_counts`.
    bucket_counts (torch.Tensor, numpy.ndarray): 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)ru   rv   rw   len
ValueErrorr   rE   r   )r,   rK   minmaxnumsumsum_squaresbucket_limitsbucket_countsrD   r@   s              r1   add_histogram_rawSummaryWriter.add_histogram_raw  sl    | 	$$%LM}]!33M  	++#Cm 	
r4   c                     [         R                  R                  S5        U R                  5       R	                  [        XUS9X45        g)a$  Add image data to summary.

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

Args:
    tag (str): Data identifier
    img_tensor (torch.Tensor, numpy.ndarray, 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 (str): 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_imagedataformatsNru   rv   rw   r   rE   r   r,   rK   
img_tensorrD   r@   r   s         r1   	add_imageSummaryWriter.add_imageA  s;    \ 	$$%DE++#{;[	
r4   c                     [         R                  R                  S5        U R                  5       R	                  [        XUS9X45        g)ab  Add batched image data to summary.

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

Args:
    tag (str): Data identifier
    img_tensor (torch.Tensor, numpy.ndarray, 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 (str): 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   Nr   r   s         r1   
add_imagesSummaryWriter.add_imagest  s;    N 	$$%EF++#{;[	
r4   c	                    [         R                  R                  S5        Ub6  [        U[        5      (       a  U/n[        U5      UR                  S   :w  a  SnU R                  5       R                  [        UUUUUUS9UU5        g)a  Add image and draw bounding boxes on the image.

Args:
    tag (str): Data identifier
    img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data
    box_tensor (torch.Tensor, numpy.ndarray, 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 (str): 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.ndarray, 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_boxesNr   )rescaler   labels)
ru   rv   rw   r   r*   r   shaper   rE   r   )	r,   rK   r   
box_tensorrD   r@   r   r   r   s	            r1   add_image_with_boxes"SummaryWriter.add_image_with_boxes  s    @ 	$$%OP&#&& 6{j..q11++' 	
r4   rK   figurer   rD   r]   r@   returnc                     [         R                  R                  S5        [        U[        5      (       a  U R                  U[        X$5      UUSS9  gU R                  U[        X$5      UUSS9  g)a|  Render matplotlib figure into an image and add it to summary.

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

Args:
    tag: Data identifier
    figure: Figure or a list of figures
    global_step: Global step value to record
    close: Flag to automatically close the figure
    walltime: Optional override default walltime (time.time())
      seconds after epoch of event
ztensorboard.logging.add_figureNCHWr   CHWN)ru   rv   rw   r   listr   r   )r,   rK   r   rD   r]   r@   s         r1   
add_figureSummaryWriter.add_figure  sp    ( 	$$%EFfd##NN."   NN.!  r4   c                     [         R                  R                  S5        U R                  5       R	                  [        XU5      X55        g)a  Add video data to summary.

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

Args:
    tag (str): 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)ru   rv   rw   r   rE   r$   )r,   rK   
vid_tensorrD   fpsr@   s         r1   	add_videoSummaryWriter.add_video  s:     	$$%DE++#3'	
r4   c                     [         R                  R                  S5        U R                  5       R	                  [        XUS9X55        g)a  Add audio data to summary.

Args:
    tag (str): 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_audio)sample_rateN)ru   rv   rw   r   rE   r   )r,   rK   
snd_tensorrD   r   r@   s         r1   	add_audioSummaryWriter.add_audio  s:     	$$%DE++#{;[	
r4   c                     [         R                  R                  S5        U R                  5       R	                  [        X5      X45        g)ar  Add text data to summary.

Args:
    tag (str): Data identifier
    text_string (str): 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)ru   rv   rw   r   rE   r#   )r,   rK   text_stringrD   r@   s        r1   add_textSummaryWriter.add_text!  s8     	$$%CD++"K	
r4   c                     [         R                  R                  S5        U R                  5       R	                  [        U5      5        g )Nz"tensorboard.logging.add_onnx_graph)ru   rv   rw   r   rV   r   )r,   prototxts     r1   rV   SummaryWriter.add_onnx_graph4  s1    $$%IJ..x/HIr4   c                     [         R                  R                  S5        U R                  5       R	                  [        XX45      5        g)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_graphN)ru   rv   rw   r   rS   r   )r,   modelinput_to_modelverboseuse_strict_traces        r1   rS   SummaryWriter.add_graph8  s8     	$$%DE))%C	
r4   c                     U nUR                  SS[        S5      S 35      nUR                  SS[        S5      S 35      nUR                  SS[        S5      -  5      nU$ )N%02xr   \z%%%02x)r   ord)rawstrretvals     r1   _encodeSummaryWriter._encodeL  sa     qS#%78qS#%78h#d)&<=r4   c                 `   [         R                  R                  S5        [        U5      nUc  Sn[	        U5      R                  S5       SU R                  U5       3n[        R                  R                  U R                  5       R                  5       U5      n[        R                  R                  n	U	R                  U5      (       a1  U	R!                  U5      (       a  [#        S5        O [%        SU S35      eU	R'                  U5        Ub-  UR(                  S   [+        U5      :X  d   S	5       e[-        X(US
9  Ub2  UR(                  S   UR(                  S   :X  d   S5       e[/        X85        UR0                  S:X  d   S5       e[3        X5        [5        U S5      (       d  [7        5       U l        [;        X#XtU5      n
U R8                  R<                  R?                  U
/5        SSK J!n  URE                  U R8                  5      n[G        U R                  5       R                  5       U5        g)aW  Add embedding projector data to summary.

Args:
    mat (torch.Tensor or numpy.ndarray): A matrix which each row is the feature vector of the data point
    metadata (list): A list of labels, each element will be converted to string
    label_img (torch.Tensor): Images correspond to each data point
    global_step (int): Global step value to record
    tag (str): Name for the embedding
    metadata_header (list): A list of headers for multi-column metadata. If given, each metadata must be
        a list with values corresponding to headers.
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)

.. note::
    Categorical (i.e. non-numeric) metadata cannot have more than 50 unique values if they are to be used for
    coloring in the embedding projector.

z!tensorboard.logging.add_embeddingNr      r   zKwarning: Embedding dir exists, did you set global_step for add_embedding()?zPath: `z(` 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)$ru   rv   rw   r   r*   zfillr  r{   r|   r}   r   r6   r   iogfileexistsisdirprintNotADirectoryErrormakedirsr   r   r   r   ndimr   hasattrr   r  r   
embeddingsextendgoogle.protobufr  MessageToStringr   )r,   matmetadata	label_imgrD   rK   r  subdir	save_pathfsembedding_infor  config_pbtxts                r1   add_embeddingSummaryWriter.add_embeddingU  s   b 	$$%HIclK
 $**1-.aS0A/BCGGLL!6!6!8!C!C!EvN	UU[[99Yxx	""a )i[(PQ  KK	"99Q<3$  878  X/J 		!	 228782	- HHM	NM	N 
 t011%4%6D"+c
 	))00.1AB/"2243I3IJD))+668,Gr4   c           	          [         R                  R                  S5        [        U5      [        U5      p2U R	                  5       R                  [        XX5U5      UU5        g)a  Add 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 (str): Data identifier
    labels (torch.Tensor, numpy.ndarray, or string/blobname):
      Ground truth data. Binary label for each element.
    predictions (torch.Tensor, numpy.ndarray, 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)ru   rv   rw   r   r   rE   r   )r,   rK   r   predictionsrD   num_thresholdsweightsr@   s           r1   add_pr_curveSummaryWriter.add_pr_curve  sQ    R 	$$%GH%fow{/C++S+wG	
r4   c                     [         R                  R                  S5        U R                  5       R	                  [        UUUUUUUU	U
5	      UU5        g)a  Add precision recall curve with raw data.

Args:
    tag (str): Data identifier
    true_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): true positive counts
    false_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): false positive counts
    true_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): true negative counts
    false_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): false negative counts
    precision (torch.Tensor, numpy.ndarray, or string/blobname): precision
    recall (torch.Tensor, numpy.ndarray, 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)ru   rv   rw   r   rE   r    )r,   rK   true_positive_countsfalse_positive_countstrue_negative_countsfalse_negative_counts	precisionrecallrD   r)  r*  r@   s               r1   add_pr_curve_rawSummaryWriter.add_pr_curve_raw  sY    < 	$$%KL++$%$%
 	
r4   c                     [         R                  R                  S5        X#SU/00nU R                  5       R	                  [        U5      5        g)a  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_multilinechart	MultilineNru   rv   rw   r   rE   r   r,   tagscategorytitlelayouts        r1   !add_custom_scalars_multilinechart/SummaryWriter.add_custom_scalars_multilinechart  sI     	$$C	
 [$$789++N6,BCr4   c                     [         R                  R                  S5        [        U5      S:X  d   eX#SU/00nU R	                  5       R                  [        U5      5        g)aH  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   MarginN)ru   rv   rw   r   r   rE   r   r9  s        r1   add_custom_scalars_marginchart,SummaryWriter.add_custom_scalars_marginchart0  sY     	$$@	
 4yA~~Xt$456++N6,BCr4   c                     [         R                  R                  S5        U R                  5       R	                  [        U5      5        g)a  Create special chart by collecting charts tags in 'scalars'.

NOTE: 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_scalarsNr8  )r,   r=  s     r1   add_custom_scalars SummaryWriter.add_custom_scalarsF  s3    * 	$$%MN++N6,BCr4   c           	          [         R                  R                  S5        U R                  5       R	                  [        XX4U5      Xg5        g)a  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 (str): 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)ru   rv   rw   r   rE   r   )r,   rK   verticescolorsfacesconfig_dictrD   r@   s           r1   add_meshSummaryWriter.add_mesh^  s=    | 	$$%CD++{;[	
r4   c                     U R                   c  gU R                   R                  5        H  nUR                  5         M     grY   )r   r   rZ   r,   writers     r1   rZ   SummaryWriter.flush  s5     #&&--/FLLN 0r4   c                     U R                   c  g U R                   R                  5        H#  nUR                  5         UR                  5         M%     S =U l        U l         g rf   )r   r   rZ   r]   r   rP  s     r1   r]   SummaryWriter.close  sN    #&&--/FLLNLLN 0 /324+r4   c                     U $ rf   rm   r7   s    r1   	__enter__SummaryWriter.__enter__  s    r4   c                 $    U R                  5         g rf   )r]   )r,   exc_typeexc_valexc_tbs       r1   __exit__SummaryWriter.__exit__  s    

r4   )	r  r   r   r   r0   r/   r-   r.   r   )Nrd   Nrb   rc   rd   )NNN)NNFFre   )Nr   NN)NNr   )NNr   )NNr   r   N)NTN)N   N)NiD  N)NFT)NNNdefaultN)N   NN)r_  untitled)NNNNN),rg   rh   ri   rj   rk   r2   r   r6   r   r   r   r   r   r   r   r   r   r*   r   r   r   r<   boolfloatr   r   r   r   rV   rS   staticmethodr  r%  r+  r4  r>  rC  rF  rM  rZ   r]   rV  r\  rl   rm   r4   r1   r&   r&      s    N>` *  $53v 'LR*R` LH )
j I
X MR1
h MS*
b 1
n &*$($$ hX./$ c]	$
 $ 5/$ 
$L
* NR
(
&J
 KO
(   gH\ /
t -
` /9D& /9D,D8 A
F	3r4   )5rk   r{   r:   typingr   r   r   ru   matplotlib.figurer   tensorboard.compatr   tensorboard.compat.protor   "tensorboard.compat.proto.event_pb2r	   r
   2tensorboard.plugins.projector.projector_config_pb2r   ,tensorboard.summary.writer.event_file_writerr   _convert_npr   
_embeddingr   r   r   r   r   _onnx_graphr   _pytorch_graphr   _utilsr   rC   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   __all__r%   r&   rm   r4   r1   <module>rr     sw    q 	  1 1 ( ! . @ N H   X X ( ! #   " 
)~# ~#BL Lr4   