






import re
from typing import Callable, List, Optional, Union

import tensorflow as tf


try:
   from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
   from tensorflow.keras.optimizers import Adam


class  SCREAMING_SNAKE_CASE			(			tf.keras.optimizers.schedules.LearningRateSchedule					):
     '''simple docstring'''


     def __init__(				self       :	str					, UpperCAmelCase_       :	float					, UpperCAmelCase_       :	Callable					, UpperCAmelCase_       :	int					, UpperCAmelCase_       :	float = 1.0					, UpperCAmelCase_       :	str = None					, ):
       super().__init__()
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    initial_learning_rate
       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    warmup_steps
       SCREAMING_SNAKE_CASE       :      Tuple							=    power
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    decay_schedule_fn
       SCREAMING_SNAKE_CASE       :      int							=    name


     def __call__(				self       :	Union[str, Any]					, UpperCAmelCase_       :	List[Any]      ):
       with tf.name_scope(self.name or "WarmUp"      ) as name:
         # Implements polynomial warmup. i.e., if global_step < warmup_steps, the
         # learning rate will be `global_step/num_warmup_steps * init_lr`.
         SCREAMING_SNAKE_CASE       :      Dict							=    tf.cast(UpperCAmelCase_					, tf.floataa      )
         SCREAMING_SNAKE_CASE       :      str							=    tf.cast(self.warmup_steps					, tf.floataa      )
         SCREAMING_SNAKE_CASE       :      Any							=    global_step_float / warmup_steps_float
         SCREAMING_SNAKE_CASE       :      Any							=    self.initial_learning_rate * tf.math.pow(UpperCAmelCase_					, self.power      )
         return tf.cond(
             global_step_float < warmup_steps_float					, lambda: warmup_learning_rate					, lambda: self.decay_schedule_fn(step - self.warmup_steps      )					, name=UpperCAmelCase_					, )






     def 				_A       (				self       :	Tuple      ):
       return {
           "initial_learning_rate": self.initial_learning_rate,
           "decay_schedule_fn": self.decay_schedule_fn,
           "warmup_steps": self.warmup_steps,
           "power": self.power,
           "name": self.name,
       }





def   lowerCamelCase__			(     lowercase						,     lowercase						,     lowercase						,     lowercase = 0.0						,     lowercase = 0.9						,     lowercase = 0.999						,     lowercase = 1E-8						,     lowercase = None						,     lowercase = None						,     lowercase = 0.0						,     lowercase = 1.0						,     lowercase = None						,     ):

  """simple docstring"""






  SCREAMING_SNAKE_CASE       :      Optional[int]							=    tf.keras.optimizers.schedules.PolynomialDecay(
      initial_learning_rate=lowercase						,     decay_steps=num_train_steps - num_warmup_steps						,     end_learning_rate=init_lr * min_lr_ratio						,     power=lowercase						,     )
  if num_warmup_steps:
    SCREAMING_SNAKE_CASE       :      int							=    WarmUp(
        initial_learning_rate=lowercase						,     decay_schedule_fn=lowercase						,     warmup_steps=lowercase						,     )
  if weight_decay_rate > 0.0:
    SCREAMING_SNAKE_CASE       :      Dict							=    AdamWeightDecay(
        learning_rate=lowercase						,     weight_decay_rate=lowercase						,     beta_a=lowercase						,     beta_a=lowercase						,     epsilon=lowercase						,     clipnorm=lowercase						,     global_clipnorm=lowercase						,     exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]						,     include_in_weight_decay=lowercase						,     )
  else:
    SCREAMING_SNAKE_CASE       :      Dict							=    tf.keras.optimizers.Adam(
        learning_rate=lowercase						,     beta_a=lowercase						,     beta_a=lowercase						,     epsilon=lowercase						,     clipnorm=lowercase						,     global_clipnorm=lowercase						,     )
  # We return the optimizer and the LR scheduler in order to better track the
  # evolution of the LR independently of the optimizer.
  return optimizer, lr_schedule


class  SCREAMING_SNAKE_CASE			(			lowerCAmelCase					):
     '''simple docstring'''


     def __init__(				self       :	Any					, UpperCAmelCase_       :	Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.001					, UpperCAmelCase_       :	float = 0.9					, UpperCAmelCase_       :	float = 0.999					, UpperCAmelCase_       :	float = 1E-7					, UpperCAmelCase_       :	bool = False					, UpperCAmelCase_       :	float = 0.0					, UpperCAmelCase_       :	Optional[List[str]] = None					, UpperCAmelCase_       :	Optional[List[str]] = None					, UpperCAmelCase_       :	str = "AdamWeightDecay"					, **UpperCAmelCase_       :	Union[str, Any]					, ):
       super().__init__(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, **UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      List[Any]							=    weight_decay_rate
       SCREAMING_SNAKE_CASE       :      str							=    include_in_weight_decay
       SCREAMING_SNAKE_CASE       :      int							=    exclude_from_weight_decay


     @classmethod
     def 				_A       (				cls       :	Tuple					, UpperCAmelCase_       :	List[Any]      ):
       SCREAMING_SNAKE_CASE       :      str							=    {"WarmUp": WarmUp}
       return super(UpperCAmelCase_					, cls      ).from_config(UpperCAmelCase_					, custom_objects=UpperCAmelCase_      )


     def 				_A       (				self       :	str					, UpperCAmelCase_       :	int					, UpperCAmelCase_       :	Union[str, Any]					, UpperCAmelCase_       :	str      ):
       super(UpperCAmelCase_					, self      )._prepare_local(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Tuple							=    tf.constant(
           self.weight_decay_rate					, name="adam_weight_decay_rate"      )


     def 				_A       (				self       :	List[str]					, UpperCAmelCase_       :	Any					, UpperCAmelCase_       :	Dict					, UpperCAmelCase_       :	List[Any]      ):
       SCREAMING_SNAKE_CASE       :      str							=    self._do_use_weight_decay(var.name      )
       if do_decay:
         return var.assign_sub(
             learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]["weight_decay_rate"]					, use_locking=self._use_locking					, )
       return tf.no_op()


     def 				_A       (				self       :	Any					, UpperCAmelCase_       :	Tuple					, UpperCAmelCase_       :	Union[str, Any]=None					, **UpperCAmelCase_       :	Union[str, Any]      ):
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    list(zip(*UpperCAmelCase_      )      )
       return super(UpperCAmelCase_					, self      ).apply_gradients(zip(UpperCAmelCase_					, UpperCAmelCase_      )					, name=UpperCAmelCase_					, **UpperCAmelCase_      )


     def 				_A       (				self       :	Tuple					, UpperCAmelCase_       :	Tuple					, UpperCAmelCase_       :	Union[str, Any]					, UpperCAmelCase_       :	List[str]      ):
       if apply_state is None:
         return self._decayed_lr_t[var_dtype], {}

       SCREAMING_SNAKE_CASE       :      Any							=    apply_state or {}
       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    apply_state.get((var_device, var_dtype)      )
       if coefficients is None:
         SCREAMING_SNAKE_CASE       :      str							=    self._fallback_apply_state(UpperCAmelCase_					, UpperCAmelCase_      )
         SCREAMING_SNAKE_CASE       :      Dict							=    coefficients

       return coefficients["lr_t"], {"apply_state": apply_state}


     def 				_A       (				self       :	Optional[int]					, UpperCAmelCase_       :	Any					, UpperCAmelCase_       :	List[Any]					, UpperCAmelCase_       :	Optional[Any]=None      ):
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      List[str]							=    self._get_lr(var.device					, var.dtype.base_dtype					, UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    self._decay_weights_op(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_      )
       with tf.control_dependencies([decay]      ):
         return super(UpperCAmelCase_					, self      )._resource_apply_dense(UpperCAmelCase_					, UpperCAmelCase_					, **UpperCAmelCase_      )


     def 				_A       (				self       :	str					, UpperCAmelCase_       :	int					, UpperCAmelCase_       :	str					, UpperCAmelCase_       :	Union[str, Any]					, UpperCAmelCase_       :	Union[str, Any]=None      ):
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Optional[int]							=    self._get_lr(var.device					, var.dtype.base_dtype					, UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    self._decay_weights_op(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_      )
       with tf.control_dependencies([decay]      ):
         return super(UpperCAmelCase_					, self      )._resource_apply_sparse(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, **UpperCAmelCase_      )


     def 				_A       (				self       :	int      ):
       SCREAMING_SNAKE_CASE       :      int							=    super().get_config()
       config.update({"weight_decay_rate": self.weight_decay_rate}      )
       return config






     def 				_A       (				self       :	Optional[int]					, UpperCAmelCase_       :	Optional[int]      ):
       if self.weight_decay_rate == 0:
         return False

       if self._include_in_weight_decay:
         for r in self._include_in_weight_decay:
           if re.search(UpperCAmelCase_					, UpperCAmelCase_      ) is not None:
             return True

       if self._exclude_from_weight_decay:
         for r in self._exclude_from_weight_decay:
           if re.search(UpperCAmelCase_					, UpperCAmelCase_      ) is not None:
             return False
       return True





class  SCREAMING_SNAKE_CASE			(			lowerCAmelCase					):
     '''simple docstring'''


     def __init__(				self       :	Optional[int]      ):
       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    []
       SCREAMING_SNAKE_CASE       :      str							=    None


     @property
     def 				_A       (				self       :	str      ):
       if self._accum_steps is None:
         SCREAMING_SNAKE_CASE       :      int							=    tf.Variable(
             tf.constant(0					, dtype=tf.intaa      )					, trainable=UpperCAmelCase_					, synchronization=tf.VariableSynchronization.ON_READ					, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA					, )

       return self._accum_steps.value()


     @property
     def 				_A       (				self       :	Optional[int]      ):
       if not self._gradients:
         raise ValueError("The accumulator should be called first to initialize the gradients"      )
       return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]


     def __call__(				self       :	List[Any]					, UpperCAmelCase_       :	List[Any]      ):
       if not self._gradients:
         SCREAMING_SNAKE_CASE       :      Optional[int]							=    self.step  # Create the step variable.
         self._gradients.extend(
             [
                 tf.Variable(
                     tf.zeros_like(UpperCAmelCase_      )					, trainable=UpperCAmelCase_					, synchronization=tf.VariableSynchronization.ON_READ					, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA					, )
                 if gradient is not None
                 else gradient
                 for gradient in gradients
             ]      )
       if len(UpperCAmelCase_      ) != len(self._gradients      ):
         raise ValueError(f'''Expected {len(self._gradients      )} gradients, but got {len(UpperCAmelCase_      )}'''      )

       for accum_gradient, gradient in zip(self._gradients					, UpperCAmelCase_      ):
         if accum_gradient is not None and gradient is not None:
           accum_gradient.assign_add(UpperCAmelCase_      )

       self._accum_steps.assign_add(1      )






     def 				_A       (				self       :	List[str]      ):
       if not self._gradients:
         return
       self._accum_steps.assign(0      )
       for gradient in self._gradients:
         if gradient is not None:
           gradient.assign(tf.zeros_like(UpperCAmelCase_      )      )














import qiskit


def   lowerCamelCase__			(     lowercase						,     lowercase				):

  """simple docstring"""






  SCREAMING_SNAKE_CASE       :      List[str]							=    qiskit.Aer.get_backend("aer_simulator"				)

  # Create a Quantum Circuit acting on the q register
  SCREAMING_SNAKE_CASE       :      Dict							=    qiskit.QuantumCircuit(lowercase						,     lowercase				)

  # Map the quantum measurement to the classical bits
  circuit.measure([0]						,     [0]				)

  # Execute the circuit on the simulator
  SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    qiskit.execute(lowercase						,     lowercase						,     shots=1000				)

  # Return the histogram data of the results of the experiment.
  return job.result().get_counts(lowercase				)


if __name__ == "__main__":
   print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")






