




'''simple docstring'''





from dataclasses import dataclass
from typing import Optional, Tuple, Union

import flax
import jax.numpy as jnp
from jax import random

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left




@flax.struct.dataclass
class 				_snake_case	:
   lowerCAmelCase_  :   Tuple		 =					None
   lowerCAmelCase_  :   Optional[Any]		 =					None
   lowerCAmelCase_  :   str		 =					None




   @classmethod
   def      lowerCAmelCase__       (      cls							)       ->       Dict:

          '''simple docstring'''




          return cls()




@dataclass
class 				_snake_case	(			UpperCAmelCase_							):
   lowerCAmelCase_  :   Any		 =					42
   lowerCAmelCase_  :   str		 =					42
   lowerCAmelCase_  :   Optional[int]		 =					None




class 				_snake_case	(			UpperCAmelCase_		,		UpperCAmelCase_							):




   @property
   def      lowerCAmelCase__       (      self							)       ->       int:

          '''simple docstring'''




          return True




   @register_to_config
   def __init__(      self       ,							a__ = 2_000       ,							a__ = 0.1_5       ,							a__ = 0.0_1       ,							a__ = 1_348.0       ,							a__ = 1e-5       ,							a__ = 1       ,							)       ->       str:

          '''simple docstring'''




          pass




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

          '''simple docstring'''




          snake_case_			      =   ScoreSdeVeSchedulerState.create()
          return self.set_sigmas(
              __UpperCamelCase       ,							self.config.num_train_timesteps       ,							self.config.sigma_min       ,							self.config.sigma_max       ,							self.config.sampling_eps       ,							)




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

          '''simple docstring'''




          snake_case_			      =   sampling_eps if sampling_eps is not None else self.config.sampling_eps

          snake_case_			      =   jnp.linspace(1       ,							__UpperCamelCase       ,							__UpperCamelCase							)
          return state.replace(timesteps=__UpperCamelCase							)




   def      lowerCAmelCase__       (      self       ,							a__       ,							a__       ,							a__ = None       ,							a__ = None       ,							a__ = None       ,							)       ->       Optional[int]:

          '''simple docstring'''




          snake_case_			      =   sigma_min if sigma_min is not None else self.config.sigma_min
          snake_case_			      =   sigma_max if sigma_max is not None else self.config.sigma_max
          snake_case_			      =   sampling_eps if sampling_eps is not None else self.config.sampling_eps
          if state.timesteps is None:
                 snake_case_			      =   self.set_timesteps(__UpperCamelCase       ,							__UpperCamelCase       ,							__UpperCamelCase							)

          snake_case_			      =   jnp.exp(jnp.linspace(jnp.log(__UpperCamelCase							)       ,							jnp.log(__UpperCamelCase							)       ,							__UpperCamelCase							)							)
          snake_case_			      =   jnp.array([sigma_min * (sigma_max / sigma_min) ** t for t in state.timesteps]							)

          return state.replace(discrete_sigmas=__UpperCamelCase       ,							sigmas=__UpperCamelCase							)




   def      lowerCAmelCase__       (      self       ,							a__       ,							a__       ,							a__							)       ->       Optional[Any]:

          '''simple docstring'''




          return jnp.where(timesteps == 0       ,							jnp.zeros_like(__UpperCamelCase							)       ,							state.discrete_sigmas[timesteps - 1]							)




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

          '''simple docstring'''




          if state.timesteps is None:
                 raise ValueError(
                     "`state.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"							)

          snake_case_			      =   timestep * jnp.ones(
              sample.shape[0]       ,							)
          snake_case_			      =   (timestep * (len(state.timesteps							) - 1)).long()

          snake_case_			      =   state.discrete_sigmas[timesteps]
          snake_case_			      =   self.get_adjacent_sigma(__UpperCamelCase       ,							__UpperCamelCase       ,							__UpperCamelCase							)
          snake_case_			      =   jnp.zeros_like(__UpperCamelCase							)
          snake_case_			      =   (sigma**2 - adjacent_sigma**2) ** 0.5

          # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
          # also equation 47 shows the analog from SDE models to ancestral sampling methods
          snake_case_			      =   diffusion.flatten()
          snake_case_			      =   broadcast_to_shape_from_left(__UpperCamelCase       ,							sample.shape							)
          snake_case_			      =   drift - diffusion**2 * model_output

          #  equation 6: sample noise for the diffusion term of
          snake_case_			      =   random.split(__UpperCamelCase       ,							num=1							)
          snake_case_			      =   random.normal(key=__UpperCamelCase       ,							shape=sample.shape							)
          snake_case_			      =   sample - drift  # subtract because `dt` is a small negative timestep
          # TODO is the variable diffusion the correct scaling term for the noise?
          snake_case_			      =   prev_sample_mean + diffusion * noise  # add impact of diffusion field g

          if not return_dict:
                 return (prev_sample, prev_sample_mean, state)

          return FlaxSdeVeOutput(prev_sample=__UpperCamelCase       ,							prev_sample_mean=__UpperCamelCase       ,							state=__UpperCamelCase							)




   def      lowerCAmelCase__       (      self       ,							a__       ,							a__       ,							a__       ,							a__       ,							a__ = True       ,							)       ->       int:

          '''simple docstring'''




          if state.timesteps is None:
                 raise ValueError(
                     "`state.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"							)

          # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z"
          # sample noise for correction
          snake_case_			      =   random.split(__UpperCamelCase       ,							num=1							)
          snake_case_			      =   random.normal(key=__UpperCamelCase       ,							shape=sample.shape							)

          # compute step size from the model_output, the noise, and the snr
          snake_case_			      =   jnp.linalg.norm(__UpperCamelCase							)
          snake_case_			      =   jnp.linalg.norm(__UpperCamelCase							)
          snake_case_			      =   (self.config.snr * noise_norm / grad_norm) ** 2 * 2
          snake_case_			      =   step_size * jnp.ones(sample.shape[0]							)

          # compute corrected sample: model_output term and noise term
          snake_case_			      =   step_size.flatten()
          snake_case_			      =   broadcast_to_shape_from_left(__UpperCamelCase       ,							sample.shape							)
          snake_case_			      =   sample + step_size * model_output
          snake_case_			      =   prev_sample_mean + ((step_size * 2) ** 0.5) * noise

          if not return_dict:
                 return (prev_sample, state)

          return FlaxSdeVeOutput(prev_sample=__UpperCamelCase       ,							state=__UpperCamelCase							)




   def __len__(      self							)       ->       Optional[Any]:

          '''simple docstring'''




          return self.config.num_train_timesteps










'''simple docstring'''





import qiskit
from qiskit.providers import Backend


def   UpperCamelCase_(			snake_case							: int							,       snake_case							: int  ):

							'''simple docstring'''






							snake_case_      ,   snake_case_			      =   bin(snake_case  )[2:], bin(snake_case  )[2:]  # Remove leading '0b'

							# Ensure that both strings are of the same length
							if len(snake_case  ) > len(snake_case  ):
														snake_case_			      =   y.zfill(len(snake_case  )  )
							else:
														snake_case_			      =   x.zfill(len(snake_case  )  )

							# We need (3 * number of bits in the larger number)+1 qBits
							# The second parameter is the number of classical registers, to measure the result
							snake_case_			      =   qiskit.QuantumCircuit((len(snake_case  ) * 3) + 1							,       len(snake_case  ) + 1  )

							# We are essentially "not-ing" the bits that are 1
							# Reversed because it's easier to perform ops on more significant bits
							for i in range(len(snake_case  )  ):
														if x[::-1][i] == "1":
																					circuit.x(snake_case  )
							for j in range(len(snake_case  )  ):
														if y[::-1][j] == "1":
																					circuit.x(len(snake_case  ) + j  )

							return circuit, x, y


def   UpperCamelCase_(			snake_case							: qiskit.QuantumCircuit							,       snake_case							: int							,       snake_case							: int							,       snake_case							: int							,       snake_case							: int							,       ):

							'''simple docstring'''






							circuit.ccx(snake_case							,       snake_case							,       snake_case  )
							circuit.cx(snake_case							,       snake_case  )
							circuit.ccx(snake_case							,       snake_case							,       snake_case  )
							circuit.cx(snake_case							,       snake_case  )
							circuit.cx(snake_case							,       snake_case  )


def   UpperCamelCase_(			snake_case							: int							,       snake_case							: int							,       snake_case							: Backend = qiskit.Aer.get_backend("aer_simulator"  )							,       ):

							'''simple docstring'''






							if vala < 0 or vala < 0:
														raise ValueError("Both Integers must be positive!"  )

							# Store the Integers
							snake_case_      ,   snake_case_      ,   snake_case_			      =   store_two_classics(snake_case							,       snake_case  )
							for i in range(len(snake_case  )  ):
														full_adder(snake_case							,       snake_case							,       len(snake_case  ) + i							,       len(snake_case  ) + len(snake_case  ) + i							,       len(snake_case  ) + len(snake_case  ) + i + 1  )
														circuit.barrier()  # Optional, just for aesthetics

							# Measure the resultant qBits
							for i in range(len(snake_case  ) + 1  ):
														circuit.measure([(len(snake_case  ) * 2) + i]							,       [i]  )

							snake_case_			      =   qiskit.execute(snake_case							,       snake_case							,       shots=1  ).result()

							# The result is in binary. Convert it back to int
							return int(list(res.get_counts()  )[0]							,       2  )


if __name__ == "__main__":
		import doctest

		doctest.testmod()




