






import inspect
import warnings

import torch

from .state import AcceleratorState, GradientState
from .utils import DistributedType, honor_type, is_tpu_available


if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm





def 						A_					(						lowercase_	,  lowercase_			)				->Tuple:







 """simple docstring"""

 if isinstance(lowercase_	,  (list, tuple)			):
  return honor_type(lowercase_	,  (move_to_device(lowercase_	,  lowercase_			) for t in state)			)
 elif isinstance(lowercase_	,  lowercase_			):
  return type(lowercase_			)({k: move_to_device(lowercase_	,  lowercase_			) for k, v in state.items()}			)
 elif isinstance(lowercase_	,  torch.Tensor			):
  return state.to(lowercase_			)
 return state
class 	a_(		torch.optim.Optimizer	):



     """simple docstring"""



     def __init__(		self					:	Union[str, Any]  ,  lowerCAmelCase__					:	Any  ,  lowerCAmelCase__					:	str=True  ,  lowerCAmelCase__					:	Union[str, Any]=None)							->	Dict:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		optimizer
      SCREAMING_SNAKE_CASE				    =		scaler
      SCREAMING_SNAKE_CASE				    =		AcceleratorState()
      SCREAMING_SNAKE_CASE				    =		GradientState()
      SCREAMING_SNAKE_CASE				    =		device_placement
      SCREAMING_SNAKE_CASE				    =		False
      SCREAMING_SNAKE_CASE				    =		None

      # Handle device placement
      if device_placement:
       SCREAMING_SNAKE_CASE				    =		self.optimizer.state_dict()
       if self.accelerator_state.distributed_type == DistributedType.TPU:
        xm.send_cpu_data_to_device(lowerCAmelCase__  ,  self.accelerator_state.device)
       else:
        SCREAMING_SNAKE_CASE				    =		move_to_device(lowerCAmelCase__  ,  self.accelerator_state.device)
       self.optimizer.load_state_dict(lowerCAmelCase__)





     @property
     def     __UpperCamelCase						(		self					:	List[str])							->	List[Any]:

      """simple docstring"""
      return self.optimizer.state





     @state.setter
     def     __UpperCamelCase						(		self					:	Tuple  ,  lowerCAmelCase__					:	List[str])							->	Optional[int]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		state





     @property
     def     __UpperCamelCase						(		self					:	Union[str, Any])							->	str:

      """simple docstring"""
      return self.optimizer.param_groups





     @param_groups.setter
     def     __UpperCamelCase						(		self					:	List[Any]  ,  lowerCAmelCase__					:	Optional[int])							->	Union[str, Any]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		param_groups





     @property
     def     __UpperCamelCase						(		self					:	Tuple)							->	List[Any]:

      """simple docstring"""
      return self.optimizer.defaults





     @defaults.setter
     def     __UpperCamelCase						(		self					:	Tuple  ,  lowerCAmelCase__					:	int)							->	Dict:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		defaults





     def     __UpperCamelCase						(		self					:	Union[str, Any]  ,  lowerCAmelCase__					:	Optional[int])							->	Tuple:

      """simple docstring"""
      self.optimizer.add_param_group(lowerCAmelCase__)





     def     __UpperCamelCase						(		self					:	List[str]  ,  lowerCAmelCase__					:	str)							->	List[Any]:

      """simple docstring"""
      if self.accelerator_state.distributed_type == DistributedType.TPU and self.device_placement:
       xm.send_cpu_data_to_device(lowerCAmelCase__  ,  self.accelerator_state.device)
      self.optimizer.load_state_dict(lowerCAmelCase__)





     def     __UpperCamelCase						(		self					:	str)							->	Optional[Any]:

      """simple docstring"""
      return self.optimizer.state_dict()





     def     __UpperCamelCase						(		self					:	int  ,  lowerCAmelCase__					:	List[str]=None)							->	str:

      """simple docstring"""
      if self.gradient_state.sync_gradients:
       SCREAMING_SNAKE_CASE				    =		'set_to_none' in inspect.signature(self.optimizer.zero_grad).parameters
       if accept_arg:
        if set_to_none is None:
         SCREAMING_SNAKE_CASE				    =		False
        self.optimizer.zero_grad(set_to_none=lowerCAmelCase__)
       else:
        if set_to_none is not None:
         raise ValueError('`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.')
        self.optimizer.zero_grad()





     def     __UpperCamelCase						(		self					:	Any  ,  lowerCAmelCase__					:	str=None)							->	Any:

      """simple docstring"""
      if self.gradient_state.sync_gradients:
       if self.accelerator_state.distributed_type == DistributedType.TPU:
        SCREAMING_SNAKE_CASE				    =		{'closure': closure} if closure is not None else {}
        xm.optimizer_step(self.optimizer  ,  optimizer_args=lowerCAmelCase__)
       elif self.scaler is not None:
        SCREAMING_SNAKE_CASE				    =		False
        if self._last_scale is None:
         # `get_scale` is an async operation requiring full synchronization
         # on CPU and GPUs before finishing. As a result, we store away
         # the prior one to reduce the call overhead
         SCREAMING_SNAKE_CASE				    =		self.scaler.get_scale()
         SCREAMING_SNAKE_CASE				    =		True
        self.scaler.step(self.optimizer  ,  lowerCAmelCase__)
        self.scaler.update()
        SCREAMING_SNAKE_CASE				    =		self.scaler.get_scale()
        if not new_scale:
         # If we reduced the loss scale, it means the optimizer step was skipped because of gradient overflow.
         SCREAMING_SNAKE_CASE				    =		scale_after < self._last_scale
        SCREAMING_SNAKE_CASE				    =		scale_after

       else:
        self.optimizer.step(lowerCAmelCase__)





     def     __UpperCamelCase						(		self					:	Union[str, Any]  ,  lowerCAmelCase__					:	Optional[Any])							->	List[str]:

      """simple docstring"""
      for param_group in self.optimizer.param_groups:
       SCREAMING_SNAKE_CASE				    =		[parameters_map.get(lowerCAmelCase__  ,  lowerCAmelCase__) for p in param_group['params']]





     @property
     def     __UpperCamelCase						(		self					:	Optional[int])							->	Optional[int]:

      """simple docstring"""
      warnings.warn(
          'The `is_overflow` property is deprecated and will be removed in version 1.0 of Accelerate use '
          '`optimizer.step_was_skipped` instead.'  ,  lowerCAmelCase__  ,  )
      return self._is_overflow





     @property
     def     __UpperCamelCase						(		self					:	Optional[int])							->	str:

      """simple docstring"""
      return self._is_overflow





     def __getstate__(		self					:	List[Any])							->	Optional[Any]:

      """simple docstring"""
      return self.__dict__.copy()





     def __setstate__(		self					:	Optional[int]  ,  lowerCAmelCase__					:	Union[str, Any])							->	Union[str, Any]:

      """simple docstring"""
      self.__dict__.update(lowerCAmelCase__)









import numpy as np
import qiskit







def 							A     (						__UpperCAmelCase				,   __UpperCAmelCase      )			->			qiskit.QuantumCircuit:



						'''simple docstring'''






						UpperCAmelCase_					=	qiskit.QuantumCircuit(num_qubits + 1      )

						# First, let's deal with the case in which oracle is balanced
						if case == "balanced":
												# First generate a random number that tells us which CNOTs to
												# wrap in X-gates:
												UpperCAmelCase_					=	np.random.randint(1				,   2**num_qubits      )
												# Next, format 'b' as a binary string of length 'n', padded with zeros:
												UpperCAmelCase_					=	format(__UpperCAmelCase				,   f"0{num_qubits}b"      )
												# Next, we place the first X-gates. Each digit in our binary string
												# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
												# we apply an X-gate to that qubit:
												for index, bit in enumerate(__UpperCAmelCase      ):
																		if bit == "1":
																								oracle_qc.x(__UpperCAmelCase      )
        # Do the controlled-NOT gates for each qubit, using the output qubit
        # as the target:
												for index in range(__UpperCAmelCase      ):
																		oracle_qc.cx(__UpperCAmelCase				,   __UpperCAmelCase      )
												# Next, place the final X-gates
												for index, bit in enumerate(__UpperCAmelCase      ):
																		if bit == "1":
																								oracle_qc.x(__UpperCAmelCase      )

    # Case in which oracle is constant
						if case == "constant":
												# First decide what the fixed output of the oracle will be
												# (either always 0 or always 1)
												UpperCAmelCase_					=	np.random.randint(2      )
												if output == 1:
																		oracle_qc.x(__UpperCAmelCase      )

						UpperCAmelCase_					=	oracle_qc.to_gate()
						UpperCAmelCase_					=	'''Oracle'''  # To show when we display the circuit
						return oracle_gate







def 							A     (						__UpperCAmelCase				,   __UpperCAmelCase      )			->			qiskit.QuantumCircuit:



						'''simple docstring'''






						UpperCAmelCase_					=	qiskit.QuantumCircuit(num_qubits + 1				,   __UpperCAmelCase      )
						# Set up the output qubit:
						dj_circuit.x(__UpperCAmelCase      )
						dj_circuit.h(__UpperCAmelCase      )
						# And set up the input register:
						for qubit in range(__UpperCAmelCase      ):
												dj_circuit.h(__UpperCAmelCase      )
						# Let's append the oracle gate to our circuit:
						dj_circuit.append(__UpperCAmelCase				,   range(num_qubits + 1      )      )
						# Finally, perform the H-gates again and measure:
						for qubit in range(__UpperCAmelCase      ):
												dj_circuit.h(__UpperCAmelCase      )

						for i in range(__UpperCAmelCase      ):
												dj_circuit.measure(__UpperCAmelCase				,   __UpperCAmelCase      )

						return dj_circuit







def 							A     (						__UpperCAmelCase				,   __UpperCAmelCase      )			->			qiskit.result.counts.Counts:



						'''simple docstring'''






						UpperCAmelCase_					=	qiskit.Aer.get_backend('''aer_simulator'''      )

						UpperCAmelCase_					=	dj_oracle(__UpperCAmelCase				,   __UpperCAmelCase      )
						UpperCAmelCase_					=	dj_algorithm(__UpperCAmelCase				,   __UpperCAmelCase      )

						# Execute the circuit on the simulator
						UpperCAmelCase_					=	qiskit.execute(__UpperCAmelCase				,   __UpperCAmelCase				,   shots=1000      )

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


if __name__ == "__main__":
							print(f"Deutsch Jozsa - Constant Oracle: {deutsch_jozsa('constant', 3)}")
							print(f"Deutsch Jozsa - Balanced Oracle: {deutsch_jozsa('balanced', 3)}")





