




from typing import Dict, Tuple, overload

import torch
import torch.types
from torch import nn

from . import residue_constants as rc
from .rigid_utils import Rigid, Rotation
from .tensor_utils import batched_gather




@overload
def 							_UpperCAmelCase     (UpperCamelCase_       :       Tuple					,			UpperCamelCase_       :       Any					,			UpperCamelCase_       :       Union[str, Any]				):
				'''simple docstring'''
				...




@overload
def 							_UpperCAmelCase     (UpperCamelCase_       :       List[Any]					,			UpperCamelCase_       :       Optional[Any]					,			UpperCamelCase_       :       List[str]				):
				'''simple docstring'''
				...




def 							_UpperCAmelCase     (UpperCamelCase_       :       List[Any]					,			UpperCamelCase_       :       Tuple					,			UpperCamelCase_       :       Dict				):
				'''simple docstring'''
				_lowerCAmelCase			:			List[str]        =					aatype == rc.restype_order["""G"""]
				_lowerCAmelCase			:			List[str]        =					rc.atom_order["""CA"""]
				_lowerCAmelCase			:			Union[str, Any]        =					rc.atom_order["""CB"""]
				_lowerCAmelCase			:			Union[str, Any]        =					torch.where(
				    is_gly[..., None].expand(*((-1,) * len(is_gly.shape				))					,			3				)					,			all_atom_positions[..., ca_idx, :]					,			all_atom_positions[..., cb_idx, :]					,			)

				if all_atom_masks is not None:
								_lowerCAmelCase			:			List[str]        =					torch.where(
								    lowercase_					,			all_atom_masks[..., ca_idx]					,			all_atom_masks[..., cb_idx]					,			)
								return pseudo_beta, pseudo_beta_mask
				else:
								return pseudo_beta




def 							_UpperCAmelCase     (UpperCamelCase_       :       int					,			UpperCamelCase_       :       Any				):
				'''simple docstring'''
				_lowerCAmelCase			:			str        =					batched_gather(
				    lowercase_					,			batch["""residx_atom37_to_atom14"""]					,			dim=-2					,			no_batch_dims=len(atomaa.shape[:-2]				)					,			)

				_lowerCAmelCase			:			str        =					atomaa_data * batch["""atom37_atom_exists"""][..., None]

				return atomaa_data




def 							_UpperCAmelCase     (UpperCamelCase_       :       int				):
				'''simple docstring'''
				_lowerCAmelCase			:			Optional[Any]        =					template_feats["""template_aatype"""]
				_lowerCAmelCase			:			Union[str, Any]        =					template_feats["""template_torsion_angles_sin_cos"""]
				_lowerCAmelCase			:			Union[str, Any]        =					template_feats["""template_alt_torsion_angles_sin_cos"""]
				_lowerCAmelCase			:			Any        =					template_feats["""template_torsion_angles_mask"""]
				_lowerCAmelCase			:			Tuple        =					torch.cat(
				    [
				        nn.functional.one_hot(lowercase_					,			22				),
				        torsion_angles_sin_cos.reshape(*torsion_angles_sin_cos.shape[:-2]					,			14				),
				        alt_torsion_angles_sin_cos.reshape(*alt_torsion_angles_sin_cos.shape[:-2]					,			14				),
				        torsion_angles_mask,
				    ]					,			dim=-1					,			)

				return template_angle_feat




def 							_UpperCAmelCase     (UpperCamelCase_       :       List[str]					,			UpperCamelCase_       :       Optional[Any]					,			UpperCamelCase_       :       Union[str, Any]					,			UpperCamelCase_       :       Any					,			UpperCamelCase_       :       Union[str, Any] = False					,			UpperCamelCase_       :       Dict = 1E-2_0					,			UpperCamelCase_       :       str = 1E8					,			):
				'''simple docstring'''
				_lowerCAmelCase			:			Optional[Any]        =					batch["""template_pseudo_beta_mask"""]
				_lowerCAmelCase			:			Optional[int]        =					template_mask[..., None] * template_mask[..., None, :]

				# Compute distogram (this seems to differ slightly from Alg. 5)
				_lowerCAmelCase			:			Optional[Any]        =					batch["""template_pseudo_beta"""]
				_lowerCAmelCase			:			Union[str, Any]        =					torch.sum((tpb[..., None, :] - tpb[..., None, :, :]) ** 2					,			dim=-1					,			keepdim=lowercase_				)
				_lowerCAmelCase			:			Tuple        =					torch.linspace(lowercase_					,			lowercase_					,			lowercase_					,			device=tpb.device				) ** 2
				_lowerCAmelCase			:			Any        =					torch.cat([lower[1:], lower.new_tensor([inf]				)]					,			dim=-1				)
				_lowerCAmelCase			:			Any        =					((dgram > lower) * (dgram < upper)).type(dgram.dtype				)

				_lowerCAmelCase			:			Optional[Any]        =					[dgram, template_mask_ad[..., None]]

				_lowerCAmelCase			:			str        =					nn.functional.one_hot(
				    batch["""template_aatype"""]					,			rc.restype_num + 2					,			)

				_lowerCAmelCase			:			Dict        =					batch["""template_aatype"""].shape[-1]
				to_concat.append(aatype_one_hot[..., None, :, :].expand(*aatype_one_hot.shape[:-2]					,			lowercase_					,			-1					,			-1				)				)
				to_concat.append(aatype_one_hot[..., None, :].expand(*aatype_one_hot.shape[:-2]					,			-1					,			lowercase_					,			-1				)				)

				_lowerCAmelCase    ,			_lowerCAmelCase    ,			_lowerCAmelCase			:			List[Any]        =					[rc.atom_order[a] for a in ["""N""", """CA""", """C"""]]
				_lowerCAmelCase			:			List[Any]        =					Rigid.make_transform_from_reference(
				    n_xyz=batch["""template_all_atom_positions"""][..., n, :]					,			ca_xyz=batch["""template_all_atom_positions"""][..., ca, :]					,			c_xyz=batch["""template_all_atom_positions"""][..., c, :]					,			eps=lowercase_					,			)
				_lowerCAmelCase			:			Optional[int]        =					rigids.get_trans()[..., None, :, :]
				_lowerCAmelCase			:			int        =					rigids[..., None].invert_apply(lowercase_				)

				_lowerCAmelCase			:			List[str]        =					torch.rsqrt(eps + torch.sum(rigid_vec**2					,			dim=-1				)				)

				_lowerCAmelCase			:			int        =					batch["""template_all_atom_mask"""]
				_lowerCAmelCase			:			str        =					t_aa_masks[..., n] * t_aa_masks[..., ca] * t_aa_masks[..., c]
				_lowerCAmelCase			:			Any        =					template_mask[..., None] * template_mask[..., None, :]

				_lowerCAmelCase			:			Tuple        =					inv_distance_scalar * template_mask_ad
				_lowerCAmelCase			:			Any        =					rigid_vec * inv_distance_scalar[..., None]

				if not use_unit_vector:
								_lowerCAmelCase			:			Optional[int]        =					unit_vector * 0.0

				to_concat.extend(torch.unbind(unit_vector[..., None, :]					,			dim=-1				)				)
				to_concat.append(template_mask_ad[..., None]				)

				_lowerCAmelCase			:			List[Any]        =					torch.cat(lowercase_					,			dim=-1				)
				_lowerCAmelCase			:			List[Any]        =					act * template_mask_ad[..., None]

				return act




def 							_UpperCAmelCase     (UpperCamelCase_       :       Union[str, Any]				):
				'''simple docstring'''
				_lowerCAmelCase			:			Tuple        =					nn.functional.one_hot(batch["""extra_msa"""]					,			23				)
				_lowerCAmelCase			:			Dict        =					[
				    msa_ahot,
				    batch["""extra_has_deletion"""].unsqueeze(-1				),
				    batch["""extra_deletion_value"""].unsqueeze(-1				),
				]
				return torch.cat(lowercase_					,			dim=-1				)




def 							_UpperCAmelCase     (UpperCamelCase_       :       str					,			UpperCamelCase_       :       Any					,			UpperCamelCase_       :       Optional[Any]					,			UpperCamelCase_       :       int					,			):
				'''simple docstring'''
				_lowerCAmelCase			:			Union[str, Any]        =					rrgdf[aatype, ...]

				# [*, N, 8] transformations, i.e.
				#   One [*, N, 8, 3, 3] rotation matrix and
				#   One [*, N, 8, 3]    translation matrix
				_lowerCAmelCase			:			Union[str, Any]        =					r.from_tensor_axa(lowercase_				)

				_lowerCAmelCase			:			Optional[int]        =					alpha.new_zeros((*((1,) * len(alpha.shape[:-1]				)), 2)				)
				_lowerCAmelCase			:			List[str]        =					1

				# [*, N, 8, 2]
				_lowerCAmelCase			:			Any        =					torch.cat([bb_rot.expand(*alpha.shape[:-2]					,			-1					,			-1				), alpha]					,			dim=-2				)

				# [*, N, 8, 3, 3]
				# Produces rotation matrices of the form:
				# [
				#   [1, 0  , 0  ],
				#   [0, a_2,-a_1],
				#   [0, a_1, a_2]
				# ]
				# This follows the original code rather than the supplement, which uses
				# different indices.

				_lowerCAmelCase			:			List[str]        =					alpha.new_zeros(default_r.get_rots().get_rot_mats().shape				)
				_lowerCAmelCase			:			Any        =					1
				_lowerCAmelCase			:			Optional[int]        =					alpha[..., 1]
				_lowerCAmelCase			:			Optional[int]        =					-alpha[..., 0]
				_lowerCAmelCase			:			List[Any]        =					alpha

				_lowerCAmelCase			:			Dict        =					default_r.compose(Rigid(Rotation(rot_mats=lowercase_				)					,			lowercase_				)				)

				_lowerCAmelCase			:			List[str]        =					all_frames[..., 5]
				_lowerCAmelCase			:			Optional[Any]        =					all_frames[..., 6]
				_lowerCAmelCase			:			Union[str, Any]        =					all_frames[..., 7]

				_lowerCAmelCase			:			Dict        =					all_frames[..., 4]
				_lowerCAmelCase			:			Optional[Any]        =					chia_frame_to_bb.compose(lowercase_				)
				_lowerCAmelCase			:			Any        =					chia_frame_to_bb.compose(lowercase_				)
				_lowerCAmelCase			:			Tuple        =					chia_frame_to_bb.compose(lowercase_				)

				_lowerCAmelCase			:			Optional[int]        =					Rigid.cat(
				    [
				        all_frames[..., :5],
				        chia_frame_to_bb.unsqueeze(-1				),
				        chia_frame_to_bb.unsqueeze(-1				),
				        chia_frame_to_bb.unsqueeze(-1				),
				    ]					,			dim=-1					,			)

				_lowerCAmelCase			:			List[str]        =					r[..., None].compose(lowercase_				)

				return all_frames_to_global





def 							_UpperCAmelCase     (UpperCamelCase_       :       Dict					,			UpperCamelCase_       :       Optional[int]					,			UpperCamelCase_       :       Optional[Any]					,			UpperCamelCase_       :       List[Any]					,			UpperCamelCase_       :       Optional[int]					,			UpperCamelCase_       :       List[Any]					,			):
				'''simple docstring'''
				_lowerCAmelCase			:			Optional[int]        =					group_idx[aatype, ...]

				# [*, N, 14, 8]
				_lowerCAmelCase			:			Tuple        =					nn.functional.one_hot(
				    lowercase_					,			num_classes=default_frames.shape[-3]					,			)

				# [*, N, 14, 8]
				_lowerCAmelCase			:			List[str]        =					r[..., None, :] * group_mask_one_hot

				# [*, N, 14]
				_lowerCAmelCase			:			Optional[int]        =					t_atoms_to_global.map_tensor_fn(lambda UpperCamelCase_				: torch.sum(lowercase_					,			dim=-1				)				)

				# [*, N, 14, 1]
				_lowerCAmelCase			:			int        =					atom_mask[aatype, ...].unsqueeze(-1				)

				# [*, N, 14, 3]
				_lowerCAmelCase			:			Any        =					lit_positions[aatype, ...]
				_lowerCAmelCase			:			Tuple        =					t_atoms_to_global.apply(lowercase_				)
				_lowerCAmelCase			:			List[str]        =					pred_positions * atom_mask

				return pred_positions







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
 import PIL


a_      						=   logging.get_logger(__name__)

class        _lowerCamelCase  (	_SCREAMING_SNAKE_CASE      ):

      """simple docstring"""

      lowerCAmelCase__	:       Union[str, Any]			=    ["pixel_values"]







      def __init__(   self    :       Union[str, Any]       ,				snake_case    :       bool = True       ,				snake_case    :       Dict[str, int] = None       ,				snake_case    :       bool = True       ,				snake_case    :       Dict[str, int] = None       ,				snake_case    :       PILImageResampling = PILImageResampling.BICUBIC       ,				snake_case    :       bool = True       ,				snake_case    :       Union[int, float] = 1 / 255       ,				snake_case    :       bool = True       ,				snake_case    :       Optional[Union[float, List[float]]] = None       ,				snake_case    :       Optional[Union[float, List[float]]] = None       ,				**snake_case    :       Union[str, Any]       ,				):
          super().__init__(**snake_case )
          __UpperCamelCase     						=  crop_size if crop_size is not None else {'''height''': 256, '''width''': 256}
          __UpperCamelCase     						=  get_size_dict(snake_case       ,				param_name='''crop_size''' )
          __UpperCamelCase     						=  size if size is not None else {'''height''': 224, '''width''': 224}
          __UpperCamelCase     						=  get_size_dict(snake_case )

          __UpperCamelCase     						=  do_center_crop
          __UpperCamelCase     						=  crop_size
          __UpperCamelCase     						=  do_resize
          __UpperCamelCase     						=  size
          __UpperCamelCase     						=  resample
          __UpperCamelCase     						=  do_rescale
          __UpperCamelCase     						=  rescale_factor
          __UpperCamelCase     						=  do_normalize
          __UpperCamelCase     						=  image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
          __UpperCamelCase     						=  image_std if image_std is not None else IMAGENET_DEFAULT_STD







      def 					snake_case		(   self    :       Optional[Any]       ,				snake_case    :       np.ndarray       ,				snake_case    :       Dict[str, int]       ,				snake_case    :       Optional[int] = None       ,				snake_case    :       Optional[Union[str, ChannelDimension]] = None       ,				**snake_case    :       List[Any]       ,				):
          __UpperCamelCase     						=  self.size if size is None else size
          __UpperCamelCase     						=  get_size_dict(snake_case )
          __UpperCamelCase     						=  get_size_dict(snake_case       ,				param_name='''crop_size''' )

          __UpperCamelCase						,					__UpperCamelCase     						=  get_image_size(snake_case )
          __UpperCamelCase     						=  min(snake_case       ,				snake_case )
          __UpperCamelCase     						=  (size['''height'''] / crop_size['''height''']) * min_dim
          __UpperCamelCase     						=  (size['''width'''] / crop_size['''width''']) * min_dim
          return center_crop(snake_case       ,				size=(cropped_height, cropped_width)       ,				data_format=snake_case       ,				**snake_case )







      def 					snake_case		(   self    :       Union[str, Any]       ,				snake_case    :       np.ndarray       ,				snake_case    :       Dict[str, int]       ,				snake_case    :       PILImageResampling = PIL.Image.BICUBIC       ,				snake_case    :       Optional[Union[str, ChannelDimension]] = None       ,				**snake_case    :       List[str]       ,				):
          __UpperCamelCase     						=  get_size_dict(snake_case )
          if "height" not in size or "width" not in size:
              raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" )
          return resize(
              snake_case       ,				size=(size['''height'''], size['''width'''])       ,				resample=snake_case       ,				data_format=snake_case       ,				**snake_case )







      def 					snake_case		(   self    :       Union[str, Any]       ,				snake_case    :       np.ndarray       ,				snake_case    :       Union[int, float]       ,				snake_case    :       Optional[Union[str, ChannelDimension]] = None       ,				**snake_case    :       Optional[int]       ,				):
          return rescale(snake_case       ,				scale=snake_case       ,				data_format=snake_case       ,				**snake_case )







      def 					snake_case		(   self    :       Optional[int]       ,				snake_case    :       np.ndarray       ,				snake_case    :       Union[float, List[float]]       ,				snake_case    :       Union[float, List[float]]       ,				snake_case    :       Optional[Union[str, ChannelDimension]] = None       ,				**snake_case    :       Any       ,				):
          return normalize(snake_case       ,				mean=snake_case       ,				std=snake_case       ,				data_format=snake_case       ,				**snake_case )







      def 					snake_case		(   self    :       List[Any]       ,				snake_case    :       ImageInput       ,				snake_case    :       Optional[bool] = None       ,				snake_case    :       Optional[Dict[str, int]] = None       ,				snake_case    :       Optional[bool] = None       ,				snake_case    :       Optional[Dict[str, int]] = None       ,				snake_case    :       PILImageResampling = None       ,				snake_case    :       Optional[bool] = None       ,				snake_case    :       Optional[float] = None       ,				snake_case    :       Optional[bool] = None       ,				snake_case    :       Optional[Union[float, List[float]]] = None       ,				snake_case    :       Optional[Union[float, List[float]]] = None       ,				snake_case    :       Optional[Union[str, TensorType]] = None       ,				snake_case    :       ChannelDimension = ChannelDimension.FIRST       ,				**snake_case    :       Tuple       ,				):
          __UpperCamelCase     						=  do_center_crop if do_center_crop is not None else self.do_center_crop
          __UpperCamelCase     						=  crop_size if crop_size is not None else self.crop_size
          __UpperCamelCase     						=  get_size_dict(snake_case       ,				param_name='''crop_size''' )
          __UpperCamelCase     						=  do_resize if do_resize is not None else self.do_resize
          __UpperCamelCase     						=  size if size is not None else self.size
          __UpperCamelCase     						=  get_size_dict(snake_case )
          __UpperCamelCase     						=  resample if resample is not None else self.resample
          __UpperCamelCase     						=  do_rescale if do_rescale is not None else self.do_rescale
          __UpperCamelCase     						=  rescale_factor if rescale_factor is not None else self.rescale_factor
          __UpperCamelCase     						=  do_normalize if do_normalize is not None else self.do_normalize
          __UpperCamelCase     						=  image_mean if image_mean is not None else self.image_mean
          __UpperCamelCase     						=  image_std if image_std is not None else self.image_std

          __UpperCamelCase     						=  make_list_of_images(snake_case )

          if not valid_images(snake_case ):
              raise ValueError(
                  '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                  '''torch.Tensor, tf.Tensor or jax.ndarray.''' )

          if do_center_crop and crop_size is None:
              raise ValueError('''If `do_center_crop` is set to `True`, `crop_size` must be provided.''' )

          if do_resize and size is None:
              raise ValueError('''Size must be specified if do_resize is True.''' )

          if do_rescale and rescale_factor is None:
              raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )

          if do_normalize and (image_mean is None or image_std is None):
              raise ValueError('''Image mean and image standard deviation must be specified if do_normalize is True.''' )

          # All transformations expect numpy arrays.
          __UpperCamelCase     						=  [to_numpy_array(snake_case ) for image in images]

          if do_center_crop:
              __UpperCamelCase     						=  [self.center_crop(snake_case       ,				snake_case       ,				size=snake_case ) for image in images]

          if do_resize:
              __UpperCamelCase     						=  [self.resize(image=snake_case       ,				size=snake_case       ,				resample=snake_case ) for image in images]

          if do_rescale:
              __UpperCamelCase     						=  [self.rescale(image=snake_case       ,				scale=snake_case ) for image in images]

          if do_normalize:
              __UpperCamelCase     						=  [self.normalize(image=snake_case       ,				mean=snake_case       ,				std=snake_case ) for image in images]

          __UpperCamelCase     						=  [to_channel_dimension_format(snake_case       ,				snake_case ) for image in images]

          __UpperCamelCase     						=  {'''pixel_values''': images}
          return BatchFeature(data=snake_case       ,				tensor_type=snake_case )






