
    1VhN                     H   d Z ddlZddlZddl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Zdd	Zdd
ZddZd Zd Zd Zd Zd Z G d d      Z G d dej6                        Z G d de      Z G d de      Z G d de      Z G d d      Z y) zzExperimental public APIs for the HParams plugin.

These are porcelain on top of `api_pb2` (`api.proto`) and `summary.py`.
    N)tf2)summary_pb2)api_pb2)metadata)plugin_data_pb2c                 6    t        | ||      }t        d|      S )a  Write hyperparameter values for a single trial.

    Args:
      hparams: A `dict` mapping hyperparameters to the values used in this
        trial. Keys should be the names of `HParam` objects used in an
        experiment, or the `HParam` objects themselves. Values should be
        Python `bool`, `int`, `float`, or `string` values, depending on
        the type of the hyperparameter. The corresponding numpy types,
        like `np.float32`, are also permitted.
      trial_id: An optional `str` ID for the set of hyperparameter values
        used in this trial. Defaults to a hash of the hyperparameters.
      start_time_secs: The time that this trial started training, as
        seconds since epoch. Defaults to the current time.

    Returns:
      A tensor whose value is `True` on success, or `False` if no summary
      was written because no default summary writer was available.
    )hparamstrial_idstart_time_secsr	   )
hparams_pb_write_summary)r	   r
   r   pbs       V/home/dcms/DCMS/lib/python3.12/site-packages/tensorboard/plugins/hparams/summary_v2.pyr	   r	   $   s&    ( 
'
B
 )R((    c                 2   |t        j                          }t        |       } t        ||       }t        j                  ||      }t        |       D ]  }| |   }t        |t              r||j                  |   _	        -t        |t        t        f      r||j                  |   _        Xt        |t              r||j                  |   _        }t        d|d|dt!        |             t#        t$        j&                  t        j(                  |            S )a  Create a summary encoding hyperparameter values for a single trial.

    Args:
      hparams: A `dict` mapping hyperparameters to the values used in this
        trial. Keys should be the names of `HParam` objects used in an
        experiment, or the `HParam` objects themselves. Values should be
        Python `bool`, `int`, `float`, or `string` values, depending on
        the type of the hyperparameter.
      trial_id: An optional `str` ID for the set of hyperparameter values
        used in this trial. Defaults to a hash of the hyperparameters.
      start_time_secs: The time that this trial started training, as
        seconds since epoch. Defaults to the current time.

    Returns:
      A TensorBoard `summary_pb2.Summary` message.
    )
group_namer   zhparams[z] = z, of unsupported type )session_start_info)time_normalize_hparams_derive_session_group_namer   SessionStartInfosorted
isinstanceboolr	   
bool_valuefloatintnumber_valuestrstring_value	TypeErrortype_summary_pbr   SESSION_START_INFO_TAGHParamsPluginData)r	   r
   r   r   r   hp_namehp_values          r   r   r   @   s   $ ))+ )G+Hg>J(99' '? 7#h%=E&&w/:5#,/?G&&w/<#&?G&&w/<Hd8n6  ''))1	
 r   c                 6    t        | ||      }t        d|      S )a  Write a top-level experiment configuration.

    This configuration describes the hyperparameters and metrics that will
    be tracked in the experiment, but does not record any actual values of
    those hyperparameters and metrics. It can be created before any models
    are actually trained.

    Args:
      hparams: A list of `HParam` values.
      metrics: A list of `Metric` values.
      time_created_secs: The time that this experiment was created, as
        seconds since epoch. Defaults to the current time.

    Returns:
      A tensor whose value is `True` on success, or `False` if no summary
      was written because no default summary writer was available.
    )r	   metricstime_created_secshparams_config)hparams_config_pbr   )r	   r)   r*   r   s       r   r+   r+   q   s'    & 
+
B
 *B//r   c                    g }| D ]h  }t        j                  |j                  |j                  |j                        }|j
                  }||j                  |       |j                  |       j |D cg c]  }|j                          }}t        j                  |||      }	t        t        j                  t        j                  |	            S c c}w )aO  Create a top-level experiment configuration.

    This configuration describes the hyperparameters and metrics that will
    be tracked in the experiment, but does not record any actual values of
    those hyperparameters and metrics. It can be created before any models
    are actually trained.

    Args:
      hparams: A list of `HParam` values.
      metrics: A list of `Metric` values.
      time_created_secs: The time that this experiment was created, as
        seconds since epoch. Defaults to the current time.

    Returns:
      A TensorBoard `summary_pb2.Summary` message.
    )namedescriptiondisplay_name)hparam_infosmetric_infosr*   )
experiment)r   
HParamInfor.   r/   r0   domainupdate_hparam_infoappendas_proto
Experimentr#   r   EXPERIMENT_TAGr   r%   )
r	   r)   r*   r1   hparaminfor5   metricr2   r3   s
             r   r,   r,      s    $ L 	"!!**,,

 %%d+D!	" 5<<&FOO%<L<##!!+J
 ))Z@  =s   4Cc                     i }| j                         D ]A  \  }}t        |t              r|j                  }||v rt	        d|      t        |      ||<   C |S )aJ  Normalize a dict keyed by `HParam`s and/or raw strings.

    Args:
      hparams: A `dict` whose keys are `HParam` objects and/or strings
        representing hyperparameter names, and whose values are
        hyperparameter values. No two keys may have the same name.

    Returns:
      A `dict` whose keys are hyperparameter names (as strings) and whose
      values are the corresponding hyperparameter values, after numpy
      normalization (see `_normalize_numpy_value`).

    Raises:
      ValueError: If two entries in `hparams` share the same
        hyperparameter name.
    z%multiple values specified for hparam )itemsr   HParamr.   
ValueError_normalize_numpy_value)r	   resultkvs       r   r   r      s_    " F .1a A;!MNN*1-q	. Mr   c                 Z    t        | t        j                        r| j                         S | S )a_  Convert a Python or Numpy scalar to a Python scalar.

    For instance, `3.0`, `np.float32(3.0)`, and `np.float64(3.0)` all
    map to `3.0`.

    Args:
      value: A Python scalar (`int`, `float`, `str`, or `bool`) or
        rank-0 `numpy` equivalent (e.g., `np.int64`, `np.float32`).

    Returns:
      A Python scalar equivalent to `value`.
    )r   npgenericitem)values    r   rB   rB      s#     %$zz|r   c                     |  t        | t              st        d|       | S t        j                  |dd      }t        j                  |j                  d            j                         S )Nz'`trial_id` should be a `str`, but got: T),:)	sort_keys
separatorszutf-8)	r   r   r!   jsondumpshashlibsha256encode	hexdigest)r
   r	   jparamss      r   r   r      sa    (C(?GI   jjDZHG>>'..12<<>>r   c                 6   |j                         }t        t        j                  j                  dd      xs t        j                  j
                  } ||       5  t        j                  j                  j                  |d      cddd       S # 1 sw Y   yxY w)a*  Write a summary, returning the writing op.

    Args:
      name: As passed to `summary_scope`.
      pb: A `summary_pb2.Summary` message.

    Returns:
      A tensor whose value is `True` on success, or `False` if no summary
      was written because no default summary writer was available.
    summary_scopeNr   )step)SerializeToStringgetattrtfsummaryexperimentalrX   write_raw_pb)r.   r   raw_pbrX   s       r   r   r      s     !!#F

''$? 	$::##  
t	 Dzz&&33F3CD D Ds   +BBc                     t        j                         }t        j                  |      }|j                  j                  | |t        j                        }|S )zCreate a summary holding the given `HParamsPluginData` message.

    Args:
      tag: The `str` tag to use.
      hparams_plugin_data: The `HParamsPluginData` message to use.

    Returns:
      A TensorBoard `summary_pb2.Summary` message.
    )tagr   tensor)r   Summaryr   create_summary_metadatarJ   addNULL_TENSOR)rb   hparams_plugin_datar]   summary_metadatarJ   s        r   r#   r#     sR     !!#G778KLMM*83G3G  E Nr   c                   d    e Zd ZdZd
dZd Zd Zed        Zed        Z	ed        Z
ed	        Zy)r@   zA hyperparameter in an experiment.

    This class describes a hyperparameter in the abstract. It ranges
    over a domain of values, but is not bound to any particular value.
    Nc                     || _         || _        || _        || _        t	        | j                  t
        t        d      f      st        d| j                        y)a	  Create a hyperparameter object.

        Args:
          name: A string ID for this hyperparameter, which should be unique
            within an experiment.
          domain: An optional `Domain` object describing the values that
            this hyperparameter can take on.
          display_name: An optional human-readable display name (`str`).
          description: An optional Markdown string describing this
            hyperparameter.

        Raises:
          ValueError: If `domain` is not a `Domain`.
        Nznot a domain: )_name_domain_display_name_descriptionr   Domainr"   rA   )selfr.   r5   r0   r/   s        r   __init__zHParam.__init__  sP     
)'$,,d(<=4<<ABB >r   c                 <    d| j                   d| j                  dS )Nz<HParam z: >)rl   rm   rq   s    r   __str__zHParam.__str__3  s    $(JJ==r   c                     d| j                   fd| j                  fd| j                  fd| j                  fg}dj	                  d |D              }d|z  S )Nr.   r5   r0   r/   , c              3   0   K   | ]  \  }}|d |  yw)=N ).0rD   rE   s      r   	<genexpr>z"HParam.__repr__.<locals>.<genexpr>=  s     !Hv1Q"2!Hs   z
HParam(%s))rl   rm   rn   ro   join)rq   fieldsfields_strings      r   __repr__zHParam.__repr__6  s^    TZZ t||$T//0D--.	
 		!H!HHm++r   c                     | j                   S N)rl   ru   s    r   r.   zHParam.name@  s    zzr   c                     | j                   S r   )rm   ru   s    r   r5   zHParam.domainD  s    ||r   c                     | j                   S r   )rn   ru   s    r   r0   zHParam.display_nameH  s    !!!r   c                     | j                   S r   )ro   ru   s    r   r/   zHParam.descriptionL  s       r   )NNN)__name__
__module____qualname____doc__rr   rv   r   propertyr.   r5   r0   r/   r{   r   r   r@   r@     sg    C,>,     " " ! !r   r@   c                       e Zd ZdZej
                  d        Zej                  efd       Z	ej                  d        Z
y)rp   zThe domain of a hyperparameter.

    Domains are restricted to values of the simple types `float`, `int`,
    `str`, and `bool`.
    c                      y)z;Data type of this domain: `float`, `int`, `str`, or `bool`.Nr{   ru   s    r   dtypezDomain.dtypeX  s     	r   c                      y)zSample a value from this domain uniformly at random.

        Args:
          rng: A `random.Random` interface; defaults to the `random` module
            itself.

        Raises:
          IndexError: If the domain is empty.
        Nr{   rq   rngs     r   sample_uniformzDomain.sample_uniform]  s     	r   c                      y)a  Update an `HParamInfo` proto to include this domain.

        This should update the `type` field on the proto and exactly one of
        the `domain` variants on the proto.

        Args:
          hparam_info: An `api_pb2.HParamInfo` proto to modify.
        Nr{   rq   hparam_infos     r   r6   zDomain.update_hparam_infoj  s     	r   N)r   r   r   r   abcabstractpropertyr   abstractmethodrandomr   r6   r{   r   r   rp   rp   Q  sX     	  	!' 
 
 		 	r   rp   )	metaclassc                   d    e Zd ZdZddZd Zd Zed        Zed        Z	ed        Z
efd	Zd
 Zy)IntIntervalz?A domain that takes on all integer values in a closed interval.Nc                     t        |t              st        d|      t        |t              st        d|      ||kD  rt        |d|      || _        || _        y)a;  Create an `IntInterval`.

        Args:
          min_value: The lower bound (inclusive) of the interval.
          max_value: The upper bound (inclusive) of the interval.

        Raises:
          TypeError: If `min_value` or `max_value` is not an `int`.
          ValueError: If `min_value > max_value`.
        zmin_value must be an int: zmax_value must be an int:  > N)r   r   r!   rA   
_min_value
_max_valuerq   	min_value	max_values      r   rr   zIntInterval.__init__z  sZ     )S)iIJJ)S)iIJJy )Y?@@##r   c                 <    d| j                   d| j                  dS N[rx   ]r   r   ru   s    r   rv   zIntInterval.__str__      !__doo>>r   c                 <    d| j                   d| j                  dS )NzIntInterval(rx   )r   ru   s    r   r   zIntInterval.__repr__  s    (,IIr   c                     t         S r   )r   ru   s    r   r   zIntInterval.dtype  s    
r   c                     | j                   S r   r   ru   s    r   r   zIntInterval.min_value      r   c                     | j                   S r   r   ru   s    r   r   zIntInterval.max_value  r   r   c                 N    |j                  | j                  | j                        S r   )randintr   r   r   s     r   r   zIntInterval.sample_uniform      {{4??DOO<<r   c                     t         j                  |_        | j                  |j                  _        | j                  |j                  _        y r   r   DATA_TYPE_FLOAT64r"   r   domain_intervalr   r   r   r   s     r   r6   zIntInterval.update_hparam_info  s9    %% 	 15##-04##-r   NNr   r   r   r   rr   rv   r   r   r   r   r   r   r   r6   r{   r   r   r   r   w  sa    I$(?J       "( =@r   r   c                   d    e Zd ZdZddZd Zd Zed        Zed        Z	ed        Z
efd	Zd
 Zy)RealIntervalz<A domain that takes on all real values in a closed interval.Nc                     t        |t              st        d|      t        |t              st        d|      ||kD  rt        |d|      || _        || _        y)a=  Create a `RealInterval`.

        Args:
          min_value: The lower bound (inclusive) of the interval.
          max_value: The upper bound (inclusive) of the interval.

        Raises:
          TypeError: If `min_value` or `max_value` is not an `float`.
          ValueError: If `min_value > max_value`.
        zmin_value must be a float: zmax_value must be a float: r   N)r   r   r!   rA   r   r   r   s      r   rr   zRealInterval.__init__  sZ     )U+yJKK)U+yJKKy )Y?@@##r   c                 <    d| j                   d| j                  dS r   r   ru   s    r   rv   zRealInterval.__str__  r   r   c                 <    d| j                   d| j                  dS )NzRealInterval(rx   r   r   ru   s    r   r   zRealInterval.__repr__  s    )-$//JJr   c                     t         S r   )r   ru   s    r   r   zRealInterval.dtype  s    r   c                     | j                   S r   r   ru   s    r   r   zRealInterval.min_value  r   r   c                     | j                   S r   r   ru   s    r   r   zRealInterval.max_value  r   r   c                 N    |j                  | j                  | j                        S r   )uniformr   r   r   s     r   r   zRealInterval.sample_uniform  r   r   c                     t         j                  |_        | j                  |j                  _        | j                  |j                  _        y r   r   r   s     r   r6   zRealInterval.update_hparam_info  s4    "4404##-04##-r   r   r   r{   r   r   r   r     sa    F$(?K       "( =@r   r   c                   T    e Zd ZdZd
dZd Zd Zed        Zed        Z	e
fdZd	 Zy)DiscretezhA domain that takes on a fixed set of values.

    These values may be of any (single) domain type.
    Nc                    t        |      | _        |0| j                  rt        | j                  d         }nt        d      |t        t
        t        t        fvrt        d|      || _        | j                  D ]>  }t        || j                        rt        d|d| j                  j                  d       | j                  j                          y)a  Construct a discrete domain.

        Args:
          values: A iterable of the values in this domain.
          dtype: The Python data type of values in this domain: one of
            `int`, `float`, `bool`, or `str`. If `values` is non-empty,
            `dtype` may be `None`, in which case it will be inferred as the
            type of the first element of `values`.

        Raises:
          ValueError: If `values` is empty but no `dtype` is specified.
          ValueError: If `dtype` or its inferred value is not `int`,
            `float`, `bool`, or `str`.
          TypeError: If an element of `values` is not an instance of
            `dtype`.
        Nr   z$Empty domain with no dtype specifiedzUnknown dtype: zdtype mismatch: not isinstance(rx   r   )list_valuesr"   rA   r   r   r   r   _dtyper   r!   r   sort)rq   valuesr   rJ   s       r   rr   zDiscrete.__init__  s    " F|=||T\\!_- !GHHeT3//E;<<\\ 	EeT[[1dkk224 	 	r   c                 L    ddj                  d | j                  D              z  S )Nz{%s}rx   c              3   2   K   | ]  }t        |        y wr   )repr)r|   xs     r   r}   z#Discrete.__str__.<locals>.<genexpr>  s     "Aq47"As   )r~   r   ru   s    r   rv   zDiscrete.__str__  s     "ADLL"AABBr   c                 "    d| j                   dS )Nz	Discrete(r   )r   ru   s    r   r   zDiscrete.__repr__  s    !%//r   c                     | j                   S r   )r   ru   s    r   r   zDiscrete.dtype  s    {{r   c                 ,    t        | j                        S r   )r   r   ru   s    r   r   zDiscrete.values  s    DLL!!r   c                 8    |j                  | j                        S r   )choicer   r   s     r   r   zDiscrete.sample_uniform  s    zz$,,''r   c                 8   t         t        j                  t        t        j                  t        t        j
                  t        t        j                  i| j                     |_	        |j                  d       |j                  j                  | j                         y )Ndomain_discrete)r   r   r   r   r   DATA_TYPE_BOOLr   DATA_TYPE_STRINGr   r"   
ClearFieldr   extendr   r   s     r   r6   zDiscrete.update_hparam_info  so    **7,,'(())	

 ++ 	01##**4<<8r   r   )r   r   r   r   rr   rv   r   r   r   r   r   r   r6   r{   r   r   r   r     sO    
 DC0   " " "( (9r   r   c                   V    e Zd ZdZej
                  Zej                  Z	 	 	 	 ddZ	d Z
y)MetriczA metric in an experiment.

    A metric is a real-valued function of a model. Each metric is
    associated with a TensorBoard scalar summary, which logs the
    metric's value as the model trains.
    Nc                     || _         || _        || _        || _        || _        | j                  dt
        j                  t
        j                  fvrt        d| j                        y)a_  

        Args:
          tag: The tag name of the scalar summary that corresponds to this
            metric (as a `str`).
          group: An optional string listing the subdirectory under the
            session's log directory containing summaries for this metric.
            For instance, if summaries for training runs are written to
            events files in `ROOT_LOGDIR/SESSION_ID/train`, then `group`
            should be `"train"`. Defaults to the empty string: i.e.,
            summaries are expected to be written to the session logdir.
          display_name: An optional human-readable display name.
          description: An optional Markdown string with a human-readable
            description of this metric, to appear in TensorBoard.
          dataset_type: Either `Metric.TRAINING` or `Metric.VALIDATION`, or
            `None`.
        Nzinvalid dataset type: )	_tag_grouprn   ro   _dataset_typer   TRAINING
VALIDATIONrA   )rq   rb   groupr0   r/   dataset_types         r   rr   zMetric.__init__,  sc    2 	)')dFOOV=N=N%OO4;M;MOPP Pr   c                     t        j                  t        j                  | j                  | j                        | j
                  | j                  | j                        S )N)r   rb   )r.   r0   r/   r   )r   
MetricInfo
MetricNamer   r   rn   ro   r   ru   s    r   r8   zMetric.as_protoM  sN    !!##kkII ++))++
 	
r   )NNNN)r   r   r   r   r   DATASET_TRAININGr   DATASET_VALIDATIONr   rr   r8   r{   r   r   r   r   !  s9     ''H++J
 QB	
r   r   r   r   )!r   r   rR   rP   r   r   numpyrG   tensorboard.compatr   r\   tensorboard.compat.protor   tensorboard.plugins.hparamsr   r   r   r	   r   r+   r,   r   rB   r   r   r#   r@   ABCMetarp   r   r   r   r   r{   r   r   <module>r      s          ( 0 / 0 7)8.b06&R6&
?D($8! 8!v#s{{ #L1@& 1@h/@6 /@dA9v A9H5
 5
r   