'''simple docstring'''





import inspect
from typing import List, Optional, Tuple, Union

import numpy as np
import PIL
import torch
import torch.utils.checkpoint

from ...models import UNetaDModel, VQModel
from ...schedulers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput





def 	lowerCAmelCase_				(					snake_case_       : str			)    ->      Optional[Any]:


     '''simple docstring'''




     UpperCAmelCase_    , UpperCAmelCase_           =   image.size
     UpperCAmelCase_    , UpperCAmelCase_           =   (x - x % 32 for x in (w, h))  # resize to integer multiple of 32
     UpperCAmelCase_           =   image.resize((w, h)					,    resample=PIL_INTERPOLATION["lanczos"]			)
     UpperCAmelCase_           =   np.array(snake_case_			).astype(np.floataa			) / 255.0
     UpperCAmelCase_           =   image[None].transpose(0					,    3					,    1					,    2			)
     UpperCAmelCase_           =   torch.from_numpy(snake_case_			)
     return 2.0 * image - 1.0






class        __A      ( UpperCamelCase__	):



    def __init__(self    :    Any   ,			__a    :    VQModel   ,			__a    :    UNetaDModel   ,			__a    :    Union[
            DDIMScheduler,
            PNDMScheduler,
            LMSDiscreteScheduler,
            EulerDiscreteScheduler,
            EulerAncestralDiscreteScheduler,
            DPMSolverMultistepScheduler,
        ]   ,			):
         super().__init__()
         self.register_modules(vqvae=__a   ,			unet=__a   ,			scheduler=__a )






    @torch.no_grad()
    def __call__(self    :    List[Any]   ,			__a    :    Union[torch.Tensor, PIL.Image.Image] = None   ,			__a    :    Optional[int] = 1   ,			__a    :    Optional[int] = 100   ,			__a    :    Optional[float] = 0.0   ,			__a    :    Optional[Union[torch.Generator, List[torch.Generator]]] = None   ,			__a    :    Optional[str] = "pil"   ,			__a    :    bool = True   ,			):
         if isinstance(__a   ,			PIL.Image.Image ):
              UpperCAmelCase_           =   1
         elif isinstance(__a   ,			torch.Tensor ):
              UpperCAmelCase_           =   image.shape[0]
         else:
              raise ValueError(f"""`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(__a )}""" )

         if isinstance(__a   ,			PIL.Image.Image ):
              UpperCAmelCase_           =   preprocess(__a )

         UpperCAmelCase_    , UpperCAmelCase_           =   image.shape[-2:]

         # in_channels should be 6: 3 for latents, 3 for low resolution image
         UpperCAmelCase_           =   (batch_size, self.unet.config.in_channels // 2, height, width)
         UpperCAmelCase_           =   next(self.unet.parameters() ).dtype

         UpperCAmelCase_           =   randn_tensor(__a   ,			generator=__a   ,			device=self.device   ,			dtype=__a )

         UpperCAmelCase_           =   image.to(device=self.device   ,			dtype=__a )

         # set timesteps and move to the correct device
         self.scheduler.set_timesteps(__a   ,			device=self.device )
         UpperCAmelCase_           =   self.scheduler.timesteps

         # scale the initial noise by the standard deviation required by the scheduler
         UpperCAmelCase_           =   latents * self.scheduler.init_noise_sigma

         # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
         # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
         # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
         # and should be between [0, 1]
         UpperCAmelCase_           =   "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() )
         UpperCAmelCase_           =   {}
         if accepts_eta:
              UpperCAmelCase_           =   eta

         for t in self.progress_bar(__a ):
              # concat latents and low resolution image in the channel dimension.
              UpperCAmelCase_           =   torch.cat([latents, image]   ,			dim=1 )
              UpperCAmelCase_           =   self.scheduler.scale_model_input(__a   ,			__a )
              # predict the noise residual
              UpperCAmelCase_           =   self.unet(__a   ,			__a ).sample
              # compute the previous noisy sample x_t -> x_t-1
              UpperCAmelCase_           =   self.scheduler.step(__a   ,			__a   ,			__a   ,			**__a ).prev_sample

         # decode the image latents with the VQVAE
         UpperCAmelCase_           =   self.vqvae.decode(__a ).sample
         UpperCAmelCase_           =   torch.clamp(__a   ,			-1.0   ,			1.0 )
         UpperCAmelCase_           =   image / 2 + 0.5
         UpperCAmelCase_           =   image.cpu().permute(0   ,			2   ,			3   ,			1 ).numpy()

         if output_type == "pil":
              UpperCAmelCase_           =   self.numpy_to_pil(__a )

         if not return_dict:
              return (image,)

         return ImagePipelineOutput(images=__a )





'''simple docstring'''





from math import log

from scipy.constants import Boltzmann, physical_constants

SCREAMING_SNAKE_CASE_:     Optional[int]  =3_00  # TEMPERATURE (unit = K)





def 	lowerCAmelCase_				(					snake_case_       : float					,    snake_case_       : float					,    snake_case_       : float					,    )    ->      float:


     '''simple docstring'''




     if donor_conc <= 0:
          raise ValueError("Donor concentration should be positive"			)
     elif acceptor_conc <= 0:
          raise ValueError("Acceptor concentration should be positive"			)
     elif intrinsic_conc <= 0:
          raise ValueError("Intrinsic concentration should be positive"			)
     elif donor_conc <= intrinsic_conc:
          raise ValueError(
              "Donor concentration should be greater than intrinsic concentration"			)
     elif acceptor_conc <= intrinsic_conc:
          raise ValueError(
              "Acceptor concentration should be greater than intrinsic concentration"			)
     else:
          return (
              Boltzmann
              * T
              * log((donor_conc * acceptor_conc) / intrinsic_conc**2			)
              / physical_constants["electron volt"][0]
          )


if __name__ == "__main__":
    import doctest

    doctest.testmod()




