'''simple docstring'''


from typing import Dict

import numpy as np
import torch

from . import residue_constants as rc
from .tensor_utils import tensor_tree_map, tree_map


def  _lowerCamelCase   (				lowerCamelCase_ :							Dict[str, torch.Tensor]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[Any]       =				[]
     UpperCAmelCase_							:       Dict       =				[]
     UpperCAmelCase_							:       Optional[Any]       =				[]

     for rt in rc.restypes:
          UpperCAmelCase_							:       Union[str, Any]       =				rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]
          restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names]       )
          UpperCAmelCase_							:       Any       =				{name: i for i, name in enumerate(lowerCamelCase_       )}
          restype_atomaa_to_atomaa_list.append(
              [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types]       )

          restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names]       )

     # Add dummy mapping for restype 'UNK'
     restype_atomaa_to_atomaa_list.append([0] * 14       )
     restype_atomaa_to_atomaa_list.append([0] * 37       )
     restype_atomaa_mask_list.append([0.0] * 14       )

     UpperCAmelCase_							:       List[str]       =				torch.tensor(
         lowerCamelCase_     ,					dtype=torch.intaa     ,					device=protein['aatype'].device     ,					)
     UpperCAmelCase_							:       int       =				torch.tensor(
         lowerCamelCase_     ,					dtype=torch.intaa     ,					device=protein['aatype'].device     ,					)
     UpperCAmelCase_							:       Tuple       =				torch.tensor(
         lowerCamelCase_     ,					dtype=torch.floataa     ,					device=protein['aatype'].device     ,					)
     UpperCAmelCase_							:       Optional[Any]       =				protein['aatype'].to(torch.long       )

     # create the mapping for (residx, atom14) --> atom37, i.e. an array
     # with shape (num_res, 14) containing the atom37 indices for this protein
     UpperCAmelCase_							:       Tuple       =				restype_atomaa_to_atomaa[protein_aatype]
     UpperCAmelCase_							:       List[Any]       =				restype_atomaa_mask[protein_aatype]

     UpperCAmelCase_							:       Tuple       =				residx_atomaa_mask
     UpperCAmelCase_							:       Union[str, Any]       =				residx_atomaa_to_atomaa.long()

     # create the gather indices for mapping back
     UpperCAmelCase_							:       Tuple       =				restype_atomaa_to_atomaa[protein_aatype]
     UpperCAmelCase_							:       int       =				residx_atomaa_to_atomaa.long()

     # create the corresponding mask
     UpperCAmelCase_							:       Tuple       =				torch.zeros([21, 37]     ,					dtype=torch.floataa     ,					device=protein['aatype'].device       )
     for restype, restype_letter in enumerate(rc.restypes       ):
          UpperCAmelCase_							:       str       =				rc.restype_atoa[restype_letter]
          UpperCAmelCase_							:       List[Any]       =				rc.residue_atoms[restype_name]
          for atom_name in atom_names:
               UpperCAmelCase_							:       Dict       =				rc.atom_order[atom_name]
               UpperCAmelCase_							:       Optional[Any]       =				1

     UpperCAmelCase_							:       Union[str, Any]       =				restype_atomaa_mask[protein_aatype]
     UpperCAmelCase_							:       Optional[Any]       =				residx_atomaa_mask

     return protein





def  _lowerCamelCase   (				lowerCamelCase_ :							Dict[str, torch.Tensor]       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[str]       =				tree_map(lambda lowerCamelCase_       : torch.tensor(lowerCamelCase_     ,					device=batch['aatype'].device       )     ,					lowerCamelCase_     ,					np.ndarray       )
     UpperCAmelCase_							:       Union[str, Any]       =				tensor_tree_map(lambda lowerCamelCase_       : np.array(lowerCamelCase_       )     ,					make_atomaa_masks(lowerCamelCase_       )       )
     return out







'''simple docstring'''


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

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import SchedulerMixin, SchedulerOutput






class 					__SCREAMING_SNAKE_CASE						(	lowerCamelCase_						,     lowerCamelCase_	):







  '''simple docstring'''






  lowerCamelCase_		:Union[str, Any]						   =		1


  @register_to_config
  def __init__(			self				,		snake_case_ = 1_0_0_0				,		snake_case_ = None						):




       '''simple docstring'''

       self.set_timesteps(snake_case_						)

       # standard deviation of the initial noise distribution
       UpperCAmelCase_							:       Union[str, Any]       =				1.0

       # For now we only support F-PNDM, i.e. the runge-kutta method
       # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
       # mainly at formula (9), (12), (13) and the Algorithm 2.
       UpperCAmelCase_							:       int       =				4

       # running values
       UpperCAmelCase_							:       str       =				[]


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_ = None						):




       '''simple docstring'''

       UpperCAmelCase_							:       Union[str, Any]       =				num_inference_steps
       UpperCAmelCase_							:       int       =				torch.linspace(1				,		0				,		num_inference_steps + 1						)[:-1]
       UpperCAmelCase_							:       Tuple       =				torch.cat([steps, torch.tensor([0.0]						)]						)

       if self.config.trained_betas is not None:
            UpperCAmelCase_							:       Optional[int]       =				torch.tensor(self.config.trained_betas				,		dtype=torch.floataa						)
       else:
            UpperCAmelCase_							:       Tuple       =				torch.sin(steps * math.pi / 2						) ** 2

       UpperCAmelCase_							:       Dict       =				(1.0 - self.betas**2) ** 0.5

       UpperCAmelCase_							:       str       =				(torch.atana(self.betas				,		self.alphas						) / math.pi * 2)[:-1]
       UpperCAmelCase_							:       str       =				timesteps.to(snake_case_						)

       UpperCAmelCase_							:       Any       =				[]


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_ = True				,		):




       '''simple docstring'''

       if self.num_inference_steps is None:
            raise ValueError(
                'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler'						)

       UpperCAmelCase_							:       Any       =				(self.timesteps == timestep).nonzero().item()
       UpperCAmelCase_							:       Optional[Any]       =				timestep_index + 1

       UpperCAmelCase_							:       Dict       =				sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
       self.ets.append(snake_case_						)

       if len(self.ets						) == 1:
            UpperCAmelCase_							:       Tuple       =				self.ets[-1]
       elif len(self.ets						) == 2:
            UpperCAmelCase_							:       Any       =				(3 * self.ets[-1] - self.ets[-2]) / 2
       elif len(self.ets						) == 3:
            UpperCAmelCase_							:       List[str]       =				(2_3 * self.ets[-1] - 1_6 * self.ets[-2] + 5 * self.ets[-3]) / 1_2
       else:
            UpperCAmelCase_							:       Union[str, Any]       =				(1 / 2_4) * (5_5 * self.ets[-1] - 5_9 * self.ets[-2] + 3_7 * self.ets[-3] - 9 * self.ets[-4])

       UpperCAmelCase_							:       Union[str, Any]       =				self._get_prev_sample(snake_case_				,		snake_case_				,		snake_case_				,		snake_case_						)

       if not return_dict:
            return (prev_sample,)

       return SchedulerOutput(prev_sample=snake_case_						)


  def _UpperCamelCase					(			self				,		snake_case_				,		*snake_case_				,		**snake_case_						):




       '''simple docstring'''

       return sample


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       int       =				self.alphas[timestep_index]
       UpperCAmelCase_							:       Union[str, Any]       =				self.betas[timestep_index]

       UpperCAmelCase_							:       Any       =				self.alphas[prev_timestep_index]
       UpperCAmelCase_							:       Dict       =				self.betas[prev_timestep_index]

       UpperCAmelCase_							:       List[Any]       =				(sample - sigma * ets) / max(snake_case_				,		1E-8						)
       UpperCAmelCase_							:       Tuple       =				next_alpha * pred + ets * next_sigma

       return prev_sample






  def __len__(			self						):




       '''simple docstring'''

       return self.config.num_train_timesteps






