






"""simple docstring"""



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      SCREAMING_SNAKE_CASE__    (   snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor       , snake_case    :      None							)->						torch.Tensor:






     '''simple docstring'''



     ...


@overload
def      SCREAMING_SNAKE_CASE__    (   snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor							)->						Tuple[torch.Tensor, torch.Tensor]:






     '''simple docstring'''



     ...


def      SCREAMING_SNAKE_CASE__    (   snake_case    :      Tuple       , snake_case    :      Union[str, Any]       , snake_case    :      Optional[Any]							)->						Optional[Any]:






     '''simple docstring'''



     UpperCAmelCase__		:  Optional[int]				=				aatype == rc.restype_order["G"]
     UpperCAmelCase__		:  str				=				rc.atom_order["CA"]
     UpperCAmelCase__		:  Optional[Any]				=				rc.atom_order["CB"]
     UpperCAmelCase__		:  str				=				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:
          UpperCAmelCase__		:  List[Any]				=				torch.where(
              snake_case       , all_atom_masks[..., ca_idx]       , all_atom_masks[..., cb_idx]       , )
          return pseudo_beta, pseudo_beta_mask
     else:
          return pseudo_beta


def      SCREAMING_SNAKE_CASE__    (   snake_case    :      torch.Tensor       , snake_case    :      Dict[str, torch.Tensor]							)->						torch.Tensor:






     '''simple docstring'''



     UpperCAmelCase__		:  int				=				batched_gather(
         snake_case       , batch["residx_atom37_to_atom14"]       , dim=-2       , no_batch_dims=len(atomaa.shape[:-2]							)       , )

     UpperCAmelCase__		:  Dict				=				atomaa_data * batch["atom37_atom_exists"][..., None]

     return atomaa_data


def      SCREAMING_SNAKE_CASE__    (   snake_case    :      Dict[str, torch.Tensor]							)->						torch.Tensor:






     '''simple docstring'''



     UpperCAmelCase__		:  List[Any]				=				template_feats["template_aatype"]
     UpperCAmelCase__		:  List[Any]				=				template_feats["template_torsion_angles_sin_cos"]
     UpperCAmelCase__		:  Optional[Any]				=				template_feats["template_alt_torsion_angles_sin_cos"]
     UpperCAmelCase__		:  int				=				template_feats["template_torsion_angles_mask"]
     UpperCAmelCase__		:  List[Any]				=				torch.cat(
         [
             nn.functional.one_hot(snake_case       , 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      SCREAMING_SNAKE_CASE__    (   snake_case    :      Dict[str, torch.Tensor]       , snake_case    :      torch.types.Number       , snake_case    :      torch.types.Number       , snake_case    :      int       , snake_case    :      bool = False       , snake_case    :      float = 1E-2_0       , snake_case    :      float = 1E8       , )->						torch.Tensor:






     '''simple docstring'''



     UpperCAmelCase__		:  Union[str, Any]				=				batch["template_pseudo_beta_mask"]
     UpperCAmelCase__		:  Optional[int]				=				template_mask[..., None] * template_mask[..., None, :]

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

     UpperCAmelCase__		:  Union[str, Any]				=				[dgram, template_mask_ad[..., None]]

     UpperCAmelCase__		:  torch.LongTensor				=				nn.functional.one_hot(
         batch["template_aatype"]       , rc.restype_num + 2       , )

     UpperCAmelCase__		:  List[Any]				=				batch["template_aatype"].shape[-1]
     to_concat.append(aatype_one_hot[..., None, :, :].expand(*aatype_one_hot.shape[:-2]       , snake_case       , -1       , -1							)							)
     to_concat.append(aatype_one_hot[..., None, :].expand(*aatype_one_hot.shape[:-2]       , -1       , snake_case       , -1							)							)

     UpperCAmelCase__				,							UpperCAmelCase__				,							UpperCAmelCase__		:  List[Any]				=				[rc.atom_order[a] for a in ["N", "CA", "C"]]
     UpperCAmelCase__		:  int				=				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=snake_case       , )
     UpperCAmelCase__		:  List[str]				=				rigids.get_trans()[..., None, :, :]
     UpperCAmelCase__		:  Dict				=				rigids[..., None].invert_apply(snake_case							)

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

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

     UpperCAmelCase__		:  List[str]				=				inv_distance_scalar * template_mask_ad
     UpperCAmelCase__		:  Any				=				rigid_vec * inv_distance_scalar[..., None]

     if not use_unit_vector:
          UpperCAmelCase__		:  Any				=				unit_vector * 0.0

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

     UpperCAmelCase__		:  str				=				torch.cat(snake_case       , dim=-1							)
     UpperCAmelCase__		:  List[str]				=				act * template_mask_ad[..., None]

     return act


def      SCREAMING_SNAKE_CASE__    (   snake_case    :      Dict[str, torch.Tensor]							)->						torch.Tensor:






     '''simple docstring'''



     UpperCAmelCase__		:  torch.LongTensor				=				nn.functional.one_hot(batch["extra_msa"]       , 23							)
     UpperCAmelCase__		:  Dict				=				[
         msa_ahot,
         batch["extra_has_deletion"].unsqueeze(-1							),
         batch["extra_deletion_value"].unsqueeze(-1							),
     ]
     return torch.cat(snake_case       , dim=-1							)


def      SCREAMING_SNAKE_CASE__    (   snake_case    :      Rigid       , snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor       , )->						Rigid:






     '''simple docstring'''



     UpperCAmelCase__		:  Union[str, Any]				=				rrgdf[aatype, ...]

     # [*, N, 8] transformations, i.e.
     #   One [*, N, 8, 3, 3] rotation matrix and
     #   One [*, N, 8, 3]    translation matrix
     UpperCAmelCase__		:  List[Any]				=				r.from_tensor_axa(snake_case							)

     UpperCAmelCase__		:  List[Any]				=				alpha.new_zeros((*((1,) * len(alpha.shape[:-1]							)), 2)							)
     UpperCAmelCase__		:  str				=				1

     # [*, N, 8, 2]
     UpperCAmelCase__		:  Union[str, 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.

     UpperCAmelCase__		:  Any				=				alpha.new_zeros(default_r.get_rots().get_rot_mats().shape							)
     UpperCAmelCase__		:  Dict				=				1
     UpperCAmelCase__		:  Any				=				alpha[..., 1]
     UpperCAmelCase__		:  Optional[Any]				=				-alpha[..., 0]
     UpperCAmelCase__		:  Optional[Any]				=				alpha

     UpperCAmelCase__		:  str				=				default_r.compose(Rigid(Rotation(rot_mats=snake_case							)       , snake_case							)							)

     UpperCAmelCase__		:  Optional[int]				=				all_frames[..., 5]
     UpperCAmelCase__		:  str				=				all_frames[..., 6]
     UpperCAmelCase__		:  str				=				all_frames[..., 7]

     UpperCAmelCase__		:  Dict				=				all_frames[..., 4]
     UpperCAmelCase__		:  Tuple				=				chia_frame_to_bb.compose(snake_case							)
     UpperCAmelCase__		:  int				=				chia_frame_to_bb.compose(snake_case							)
     UpperCAmelCase__		:  List[Any]				=				chia_frame_to_bb.compose(snake_case							)

     UpperCAmelCase__		:  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       , )

     UpperCAmelCase__		:  List[Any]				=				r[..., None].compose(snake_case							)

     return all_frames_to_global



def      SCREAMING_SNAKE_CASE__    (   snake_case    :      Rigid       , snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor       , snake_case    :      torch.Tensor       , )->						torch.Tensor:






     '''simple docstring'''



     UpperCAmelCase__		:  List[Any]				=				group_idx[aatype, ...]

     # [*, N, 14, 8]
     UpperCAmelCase__		:  torch.LongTensor				=				nn.functional.one_hot(
         snake_case       , num_classes=default_frames.shape[-3]       , )

     # [*, N, 14, 8]
     UpperCAmelCase__		:  List[Any]				=				r[..., None, :] * group_mask_one_hot

     # [*, N, 14]
     UpperCAmelCase__		:  str				=				t_atoms_to_global.map_tensor_fn(lambda snake_case							: torch.sum(snake_case       , dim=-1							)							)

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

     # [*, N, 14, 3]
     UpperCAmelCase__		:  Any				=				lit_positions[aatype, ...]
     UpperCAmelCase__		:  Union[str, Any]				=				t_atoms_to_global.apply(snake_case							)
     UpperCAmelCase__		:  Any				=				pred_positions * atom_mask

     return pred_positions




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import ViTImageProcessor

class 				_UpperCamelCase (    unittest.TestCase     ):






			'''simple docstring'''

			def __init__(				self       :				Optional[int]  ,		snake_case_       :				Optional[Any]  ,		snake_case_       :				List[Any]=7  ,		snake_case_       :				int=3  ,		snake_case_       :				Tuple=18  ,		snake_case_       :				List[Any]=30  ,		snake_case_       :				Tuple=400  ,		snake_case_       :				Dict=True  ,		snake_case_       :				List[str]=None  ,		snake_case_       :				Any=True  ,		snake_case_       :				str=[0.5, 0.5, 0.5]  ,		snake_case_       :				Optional[Any]=[0.5, 0.5, 0.5]  ,		):
							UpperCamelCase_:							int		=  size if size is not None else {"""height""": 18, """width""": 18}
							UpperCamelCase_:							Any		=  parent
							UpperCamelCase_:							List[str]		=  batch_size
							UpperCamelCase_:							Union[str, Any]		=  num_channels
							UpperCamelCase_:							str		=  image_size
							UpperCamelCase_:							Optional[int]		=  min_resolution
							UpperCamelCase_:							Optional[Any]		=  max_resolution
							UpperCamelCase_:							Dict		=  do_resize
							UpperCamelCase_:							Union[str, Any]		=  size
							UpperCamelCase_:							Optional[Any]		=  do_normalize
							UpperCamelCase_:							str		=  image_mean
							UpperCamelCase_:							int		=  image_std




			def 					lowerCAmelCase__		(				self       :				Tuple					):
							return {
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							    "do_normalize": self.do_normalize,
							    "do_resize": self.do_resize,
							    "size": self.size,
							}




@require_torch
@require_vision
class 				_UpperCamelCase (    _A   ,				unittest.TestCase     ):






			'''simple docstring'''

			__UpperCamelCase					:  str    					=       ViTImageProcessor if is_vision_available() else None

			def 					lowerCAmelCase__		(				self       :				Any					):
							UpperCamelCase_:							Tuple		=  ViTImageProcessingTester(self					)

			@property
			def 					lowerCAmelCase__		(				self       :				Union[str, Any]					):
							return self.image_processor_tester.prepare_image_processor_dict()

			def 					lowerCAmelCase__		(				self       :				int					):
							UpperCamelCase_:							Union[str, Any]		=  self.image_processing_class(**self.image_processor_dict					)
							self.assertTrue(hasattr(snake_case_  ,		"""image_mean"""					)					)
							self.assertTrue(hasattr(snake_case_  ,		"""image_std"""					)					)
							self.assertTrue(hasattr(snake_case_  ,		"""do_normalize"""					)					)
							self.assertTrue(hasattr(snake_case_  ,		"""do_resize"""					)					)
							self.assertTrue(hasattr(snake_case_  ,		"""size"""					)					)

			def 					lowerCAmelCase__		(				self       :				Optional[Any]					):
							UpperCamelCase_:							Optional[Any]		=  self.image_processing_class.from_dict(self.image_processor_dict					)
							self.assertEqual(image_processor.size  ,		{"""height""": 18, """width""": 18}					)

							UpperCamelCase_:							Union[str, Any]		=  self.image_processing_class.from_dict(self.image_processor_dict  ,		size=42					)
							self.assertEqual(image_processor.size  ,		{"""height""": 42, """width""": 42}					)

			def 					lowerCAmelCase__		(				self       :				int					):
							pass

			def 					lowerCAmelCase__		(				self       :				int					):
							# Initialize image_processing
							UpperCamelCase_:							List[str]		=  self.image_processing_class(**self.image_processor_dict					)
							# create random PIL images
							UpperCamelCase_:							List[Any]		=  prepare_image_inputs(self.image_processor_tester  ,		equal_resolution=snake_case_					)
							for image in image_inputs:
											self.assertIsInstance(snake_case_  ,		Image.Image					)

							# Test not batched input
							UpperCamelCase_:							Optional[Any]		=  image_processing(image_inputs[0]  ,		return_tensors="""pt"""					).pixel_values
							self.assertEqual(
							    encoded_images.shape  ,		(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["""height"""],
							        self.image_processor_tester.size["""width"""],
							    )  ,		)

							# Test batched
							UpperCamelCase_:							List[str]		=  image_processing(snake_case_  ,		return_tensors="""pt"""					).pixel_values
							self.assertEqual(
							    encoded_images.shape  ,		(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["""height"""],
							        self.image_processor_tester.size["""width"""],
							    )  ,		)

			def 					lowerCAmelCase__		(				self       :				str					):
							# Initialize image_processing
							UpperCamelCase_:							List[str]		=  self.image_processing_class(**self.image_processor_dict					)
							# create random numpy tensors
							UpperCamelCase_:							Tuple		=  prepare_image_inputs(self.image_processor_tester  ,		equal_resolution=snake_case_  ,		numpify=snake_case_					)
							for image in image_inputs:
											self.assertIsInstance(snake_case_  ,		np.ndarray					)

							# Test not batched input
							UpperCamelCase_:							Any		=  image_processing(image_inputs[0]  ,		return_tensors="""pt"""					).pixel_values
							self.assertEqual(
							    encoded_images.shape  ,		(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["""height"""],
							        self.image_processor_tester.size["""width"""],
							    )  ,		)

							# Test batched
							UpperCamelCase_:							Dict		=  image_processing(snake_case_  ,		return_tensors="""pt"""					).pixel_values
							self.assertEqual(
							    encoded_images.shape  ,		(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["""height"""],
							        self.image_processor_tester.size["""width"""],
							    )  ,		)




			def 					lowerCAmelCase__		(				self       :				Any					):
							# Initialize image_processing
							UpperCamelCase_:							int		=  self.image_processing_class(**self.image_processor_dict					)
							# create random PyTorch tensors
							UpperCamelCase_:							Dict		=  prepare_image_inputs(self.image_processor_tester  ,		equal_resolution=snake_case_  ,		torchify=snake_case_					)
							for image in image_inputs:
											self.assertIsInstance(snake_case_  ,		torch.Tensor					)

							# Test not batched input
							UpperCamelCase_:							List[str]		=  image_processing(image_inputs[0]  ,		return_tensors="""pt"""					).pixel_values
							self.assertEqual(
							    encoded_images.shape  ,		(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["""height"""],
							        self.image_processor_tester.size["""width"""],
							    )  ,		)

							# Test batched
							UpperCamelCase_:							Any		=  image_processing(snake_case_  ,		return_tensors="""pt"""					).pixel_values
							self.assertEqual(
							    encoded_images.shape  ,		(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["""height"""],
							        self.image_processor_tester.size["""width"""],
							    )  ,		)






