o
    i:!                     @   s6   d dl Zd dl mZ ddlmZ daG dd dZdS )    N)Value   )SummaryWriterc                   @   s^   e Zd ZdZ			dddZdd	d
ZdddZdddZedd Z	e
dd Zdd ZdS )GlobalSummaryWritera  A class that implements an event writer that supports concurrent logging and global logging across
    different modules.

    The GlobalSummaryWriter class provides a set of API to write TensorBoard events from different processes.
    The writer instance can be accessed from different processes or modules. Also, the instance maintains
    the ``global_step`` value itself so that the interleaved requests to write an event will not conflict
    each other. This ensures that the resulting event file is TensorBoard compatible.
    With GlobalSummaryWriter, you can easily log the metrics of your parallel-trained model.
    The GlobalSummaryWriter and also be used like the ``logging`` module of Python.
    See how ``getSummaryWriter`` is used below.
    N 
   x   Tc
              
   K   sn   t ||||||||d| _t | _t  | _t  | _t  | _	t  | _
t  | _dS )a  
        Initialize a GlobalSummaryWriter. The resulting instance will maintain a monotonically
        increasing ``global_step`` for the the event to be written. So there is no need to pass
        the global_step when calling its member functions such as ``add_scalar()``.
        All arguments for the constructor will be passed to the ordinary ``SummaryWriter.__init__()`` directly.

        Examples::

            import multiprocessing as mp
            import numpy as np
            import time
            from tensorboardX import GlobalSummaryWriter
            w = GlobalSummaryWriter()

            def train(x):
                w.add_scalar('poolmap/1', x*np.random.randn())
                time.sleep(0.05*np.random.randint(0, 10))
                w.add_scalar('poolmap/2', x*np.random.randn())

            with mp.Pool() as pool:
                pool.map(train, range(100))

        Expected result:

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

        )logdircomment
purge_step	max_queue
flush_secsfilename_suffixwrite_to_disklog_dirN)r   smwmpLocklockManagerdictscalar_tag_to_stepimage_tag_to_stephistogram_tag_to_steptext_tag_to_stepaudio_tag_to_step)selfr	   r
   r   r   r   r   r   r   coalesce_processkwargs r   N/home/ubuntu/.local/lib/python3.10/site-packages/tensorboardX/global_writer.py__init__   s   
 
zGlobalSummaryWriter.__init__c                 C   sl   | j ) || jv r| j|  d7  < nd| j|< | j||| j| | W d   dS 1 s/w   Y  dS )zAdd scalar data to summary.

        Args:
            tag (string): Data identifier
            scalar_value (float): Value to save
            walltime (float): Optional override default walltime (time.time()) of event

        r   r   N)r   r   r   
add_scalar)r   tagscalar_valuewalltimer   r   r    r"   @   s   	

"zGlobalSummaryWriter.add_scalarCHWc                 C   sp   | j + || jv r| j|  d7  < nd| j|< | jj||| j| ||d W d   dS 1 s1w   Y  dS )aU  Add image data to summary.

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

        Args:
            tag (string): Data identifier
            img_tensor (torch.Tensor, numpy.array): An `uint8` or `float`
                Tensor of shape `[channel, height, width]` where `channel` is 1, 3, or 4.
                The elements in img_tensor can either have values in [0, 1] (float32) or [0, 255] (uint8).
                Users are responsible to scale the data in the correct range/type.
            walltime (float): Optional override default walltime (time.time()) of event.
            dataformats (string): This parameter specifies the meaning of each dimension of the input tensor.
        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 use ``add_images()`` and let us do the job.
            Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitible as long as
            corresponding ``dataformats`` argument is passed. e.g. CHW, HWC, HW.
        r   r   )r%   dataformatsN)r   r   r   	add_image)r   r#   
img_tensorr%   r'   r   r   r    r(   i   s   

"zGlobalSummaryWriter.add_imagec                 C   sn   | j * || jv r| j|  d7  < nd| j|< | jj||| j| |d W d   dS 1 s0w   Y  dS )zAdd text data to summary.

        Args:
            tag (string): Data identifier
            text_string (string): String to save
            walltime (float): Optional override default walltime (time.time()) of event

        r   r   )global_stepr%   N)r   r   r   add_text)r   r#   text_stringr%   r   r   r    r+      s   	

"zGlobalSummaryWriter.add_textc                   C   s0   t tdr
tjdu rt atdtjj  tS )aq  Get the writer from global namespace.

        Examples::

            # main.py
            import global_1
            import global_2

            # global1.py
            from tensorboardX import GlobalSummaryWriter
            writer = GlobalSummaryWriter.getSummaryWriter()  # This creates a new instance.
            writer.add_text('my_log', 'greeting from global1')

            # global2.py
            from tensorboardX import GlobalSummaryWriter
            writer = GlobalSummaryWriter.getSummaryWriter()  # Get the instance in global1.py.
            writer.add_text('my_log', 'greeting from global2')

        r   NzUsing the global logger in:)hasattr_writerr   r   printfile_writer
get_logdirr   r   r   r    getSummaryWriter   s   z$GlobalSummaryWriter.getSummaryWriterc                 C   s
   | j  S N)r   _get_file_writerr   r   r   r    r0      s   
zGlobalSummaryWriter.file_writerc                 C   s   | j   | j   d S r3   )r   flushcloser5   r   r   r    r7      s   
zGlobalSummaryWriter.close)	Nr   Nr   r   r   TNTr3   )Nr&   )__name__
__module____qualname____doc__r!   r"   r(   r+   staticmethodr2   propertyr0   r7   r   r   r   r    r   
   s    

*
)
/

r   )multiprocessingr   r   writerr   r.   r   r   r   r   r    <module>   s
    