


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   lowerCamelCase_					( _a			,     _a			,     _a ):




		"""simple docstring"""






		...






@overload
def   lowerCamelCase_					( _a			,     _a			,     _a ):




		"""simple docstring"""






		...






def   lowerCamelCase_					( _a			,     _a			,     _a ):




		"""simple docstring"""






		lowerCAmelCase__     :    Tuple					  =      aatype == rc.restype_order['''G''']
		lowerCAmelCase__     :    Tuple					  =      rc.atom_order['''CA''']
		lowerCAmelCase__     :    List[Any]					  =      rc.atom_order['''CB''']
		lowerCAmelCase__     :    int					  =      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__     :    Tuple					  =      torch.where(
				    _a			,     all_atom_masks[..., ca_idx]			,     all_atom_masks[..., cb_idx]			,     )
				return pseudo_beta, pseudo_beta_mask
		else:
				return pseudo_beta






def   lowerCamelCase_					( _a			,     _a ):




		"""simple docstring"""






		lowerCAmelCase__     :    Union[str, Any]					  =      batched_gather(
		    _a			,     batch['''residx_atom37_to_atom14''']			,     dim=-2			,     no_batch_dims=len(atomaa.shape[:-2] )			,     )

		lowerCAmelCase__     :    Any					  =      atomaa_data * batch['''atom37_atom_exists'''][..., None]

		return atomaa_data






def   lowerCamelCase_					( _a ):




		"""simple docstring"""






		lowerCAmelCase__     :    List[Any]					  =      template_feats['''template_aatype''']
		lowerCAmelCase__     :    Any					  =      template_feats['''template_torsion_angles_sin_cos''']
		lowerCAmelCase__     :    int					  =      template_feats['''template_alt_torsion_angles_sin_cos''']
		lowerCAmelCase__     :    Any					  =      template_feats['''template_torsion_angles_mask''']
		lowerCAmelCase__     :    Union[str, Any]					  =      torch.cat(
		    [
		        nn.functional.one_hot(_a			,     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   lowerCamelCase_					( _a			,     _a			,     _a			,     _a			,     _a = False			,     _a = 1e-2_0			,     _a = 1e8			,     ):




		"""simple docstring"""






		lowerCAmelCase__     :    Optional[int]					  =      batch['''template_pseudo_beta_mask''']
		lowerCAmelCase__     :    str					  =      template_mask[..., None] * template_mask[..., None, :]

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

		lowerCAmelCase__     :    List[Any]					  =      [dgram, template_mask_ad[..., None]]

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

		lowerCAmelCase__     :    Any					  =      batch['''template_aatype'''].shape[-1]
		to_concat.append(aatype_one_hot[..., None, :, :].expand(*aatype_one_hot.shape[:-2]			,     _a			,     -1			,     -1 ) )
		to_concat.append(aatype_one_hot[..., None, :].expand(*aatype_one_hot.shape[:-2]			,     -1			,     _a			,     -1 ) )

		lowerCAmelCase__  ,			lowerCAmelCase__  ,			lowerCAmelCase__     :    Any					  =      [rc.atom_order[a] for a in ['''N''', '''CA''', '''C''']]
		lowerCAmelCase__     :    str					  =      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=_a			,     )
		lowerCAmelCase__     :    Any					  =      rigids.get_trans()[..., None, :, :]
		lowerCAmelCase__     :    Dict					  =      rigids[..., None].invert_apply(_a )

		lowerCAmelCase__     :    Dict					  =      torch.rsqrt(eps + torch.sum(rigid_vec**2			,     dim=-1 ) )

		lowerCAmelCase__     :    List[str]					  =      batch['''template_all_atom_mask''']
		lowerCAmelCase__     :    Union[str, Any]					  =      t_aa_masks[..., n] * t_aa_masks[..., ca] * t_aa_masks[..., c]
		lowerCAmelCase__     :    Tuple					  =      template_mask[..., None] * template_mask[..., None, :]

		lowerCAmelCase__     :    Dict					  =      inv_distance_scalar * template_mask_ad
		lowerCAmelCase__     :    Dict					  =      rigid_vec * inv_distance_scalar[..., None]

		if not use_unit_vector:
				lowerCAmelCase__     :    List[Any]					  =      unit_vector * 0.0

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

		lowerCAmelCase__     :    Union[str, Any]					  =      torch.cat(_a			,     dim=-1 )
		lowerCAmelCase__     :    str					  =      act * template_mask_ad[..., None]

		return act






def   lowerCamelCase_					( _a ):




		"""simple docstring"""






		lowerCAmelCase__     :    torch.LongTensor					  =      nn.functional.one_hot(batch['''extra_msa''']			,     23 )
		lowerCAmelCase__     :    Optional[int]					  =      [
		    msa_ahot,
		    batch['''extra_has_deletion'''].unsqueeze(-1 ),
		    batch['''extra_deletion_value'''].unsqueeze(-1 ),
		]
		return torch.cat(_a			,     dim=-1 )






def   lowerCamelCase_					( _a			,     _a			,     _a			,     _a			,     ):




		"""simple docstring"""






		lowerCAmelCase__     :    Dict					  =      rrgdf[aatype, ...]

		# [*, N, 8] transformations, i.e.
		#   One [*, N, 8, 3, 3] rotation matrix and
		#   One [*, N, 8, 3]    translation matrix
		lowerCAmelCase__     :    int					  =      r.from_tensor_axa(_a )

		lowerCAmelCase__     :    str					  =      alpha.new_zeros((*((1,) * len(alpha.shape[:-1] )), 2) )
		lowerCAmelCase__     :    Tuple					  =      1

		# [*, N, 8, 2]
		lowerCAmelCase__     :    str					  =      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[Any]					  =      alpha.new_zeros(default_r.get_rots().get_rot_mats().shape )
		lowerCAmelCase__     :    int					  =      1
		lowerCAmelCase__     :    int					  =      alpha[..., 1]
		lowerCAmelCase__     :    Dict					  =      -alpha[..., 0]
		lowerCAmelCase__     :    str					  =      alpha

		lowerCAmelCase__     :    Any					  =      default_r.compose(Rigid(Rotation(rot_mats=_a )			,     _a ) )

		lowerCAmelCase__     :    Union[str, Any]					  =      all_frames[..., 5]
		lowerCAmelCase__     :    str					  =      all_frames[..., 6]
		lowerCAmelCase__     :    Tuple					  =      all_frames[..., 7]

		lowerCAmelCase__     :    Union[str, Any]					  =      all_frames[..., 4]
		lowerCAmelCase__     :    List[Any]					  =      chia_frame_to_bb.compose(_a )
		lowerCAmelCase__     :    Tuple					  =      chia_frame_to_bb.compose(_a )
		lowerCAmelCase__     :    Optional[int]					  =      chia_frame_to_bb.compose(_a )

		lowerCAmelCase__     :    List[str]					  =      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__     :    Optional[Any]					  =      r[..., None].compose(_a )

		return all_frames_to_global






def   lowerCamelCase_					( _a			,     _a			,     _a			,     _a			,     _a			,     _a			,     ):




		"""simple docstring"""






		lowerCAmelCase__     :    Tuple					  =      group_idx[aatype, ...]

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

		# [*, N, 14, 8]
		lowerCAmelCase__     :    Optional[Any]					  =      r[..., None, :] * group_mask_one_hot

		# [*, N, 14]
		lowerCAmelCase__     :    Union[str, Any]					  =      t_atoms_to_global.map_tensor_fn(lambda _a : torch.sum(_a			,     dim=-1 ) )

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

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

		return pred_positions








import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase		=	logging.get_logger(__name__)

lowerCamelCase		=	{
    '''facebook/sam-vit-huge''': '''https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json''',
    '''facebook/sam-vit-large''': '''https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json''',
    '''facebook/sam-vit-base''': '''https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json''',
}





class       _a							(       _lowercase):




	def __init__(      self		:	Union[str, Any]	,      _SCREAMING_SNAKE_CASE		:	Tuple=256	,      _SCREAMING_SNAKE_CASE		:	Optional[Any]=1024	,      _SCREAMING_SNAKE_CASE		:	List[Any]=16	,      _SCREAMING_SNAKE_CASE		:	Optional[int]=16	,      _SCREAMING_SNAKE_CASE		:	Union[str, Any]=4	,      _SCREAMING_SNAKE_CASE		:	Any="gelu"	,      _SCREAMING_SNAKE_CASE		:	Optional[Any]=1E-6	,      **_SCREAMING_SNAKE_CASE		:	List[Any]	,      )-> Tuple:
			super().__init__(**_SCREAMING_SNAKE_CASE	)
			lowerCAmelCase__     :    Any					  =      hidden_size
			lowerCAmelCase__     :    Tuple					  =      image_size
			lowerCAmelCase__     :    List[Any]					  =      patch_size
			lowerCAmelCase__     :    Any					  =      image_size // patch_size
			lowerCAmelCase__     :    Dict					  =      mask_input_channels
			lowerCAmelCase__     :    Dict					  =      num_point_embeddings
			lowerCAmelCase__     :    str					  =      hidden_act
			lowerCAmelCase__     :    List[Any]					  =      layer_norm_eps





class       _a							(       _lowercase):




	def __init__(      self		:	Tuple	,      _SCREAMING_SNAKE_CASE		:	Union[str, Any]=256	,      _SCREAMING_SNAKE_CASE		:	Dict="relu"	,      _SCREAMING_SNAKE_CASE		:	str=2048	,      _SCREAMING_SNAKE_CASE		:	List[Any]=2	,      _SCREAMING_SNAKE_CASE		:	Dict=8	,      _SCREAMING_SNAKE_CASE		:	str=2	,      _SCREAMING_SNAKE_CASE		:	Tuple=3	,      _SCREAMING_SNAKE_CASE		:	Optional[int]=3	,      _SCREAMING_SNAKE_CASE		:	Optional[Any]=256	,      _SCREAMING_SNAKE_CASE		:	Dict=1E-6	,      **_SCREAMING_SNAKE_CASE		:	Any	,      )-> List[Any]:
			super().__init__(**_SCREAMING_SNAKE_CASE	)
			lowerCAmelCase__     :    List[str]					  =      hidden_size
			lowerCAmelCase__     :    Union[str, Any]					  =      hidden_act
			lowerCAmelCase__     :    str					  =      mlp_dim
			lowerCAmelCase__     :    Optional[int]					  =      num_hidden_layers
			lowerCAmelCase__     :    int					  =      num_attention_heads
			lowerCAmelCase__     :    List[str]					  =      attention_downsample_rate
			lowerCAmelCase__     :    str					  =      num_multimask_outputs
			lowerCAmelCase__     :    Optional[int]					  =      iou_head_depth
			lowerCAmelCase__     :    Union[str, Any]					  =      iou_head_hidden_dim
			lowerCAmelCase__     :    Tuple					  =      layer_norm_eps





class       _a							(       _lowercase):




	def __init__(      self		:	List[str]	,      _SCREAMING_SNAKE_CASE		:	int=768	,      _SCREAMING_SNAKE_CASE		:	str=256	,      _SCREAMING_SNAKE_CASE		:	int=12	,      _SCREAMING_SNAKE_CASE		:	Tuple=12	,      _SCREAMING_SNAKE_CASE		:	Dict=3	,      _SCREAMING_SNAKE_CASE		:	Optional[int]=1024	,      _SCREAMING_SNAKE_CASE		:	Tuple=16	,      _SCREAMING_SNAKE_CASE		:	List[Any]="gelu"	,      _SCREAMING_SNAKE_CASE		:	Optional[int]=1E-06	,      _SCREAMING_SNAKE_CASE		:	int=0.0	,      _SCREAMING_SNAKE_CASE		:	int=1E-10	,      _SCREAMING_SNAKE_CASE		:	List[Any]=True	,      _SCREAMING_SNAKE_CASE		:	Any=4.0	,      _SCREAMING_SNAKE_CASE		:	List[str]=True	,      _SCREAMING_SNAKE_CASE		:	int=True	,      _SCREAMING_SNAKE_CASE		:	List[str]=14	,      _SCREAMING_SNAKE_CASE		:	Dict=[2, 5, 8, 11]	,      _SCREAMING_SNAKE_CASE		:	List[Any]=128	,      _SCREAMING_SNAKE_CASE		:	Dict=None	,      **_SCREAMING_SNAKE_CASE		:	str	,      )-> Any:
			super().__init__(**_SCREAMING_SNAKE_CASE	)

			lowerCAmelCase__     :    Optional[Any]					  =      hidden_size
			lowerCAmelCase__     :    Any					  =      output_channels
			lowerCAmelCase__     :    Optional[int]					  =      num_hidden_layers
			lowerCAmelCase__     :    Dict					  =      num_attention_heads
			lowerCAmelCase__     :    List[Any]					  =      num_channels
			lowerCAmelCase__     :    int					  =      image_size
			lowerCAmelCase__     :    Tuple					  =      patch_size
			lowerCAmelCase__     :    Union[str, Any]					  =      hidden_act
			lowerCAmelCase__     :    List[str]					  =      layer_norm_eps
			lowerCAmelCase__     :    Any					  =      attention_dropout
			lowerCAmelCase__     :    int					  =      initializer_range
			lowerCAmelCase__     :    List[Any]					  =      qkv_bias
			lowerCAmelCase__     :    List[Any]					  =      mlp_ratio
			lowerCAmelCase__     :    List[Any]					  =      use_abs_pos
			lowerCAmelCase__     :    Union[str, Any]					  =      use_rel_pos
			lowerCAmelCase__     :    Optional[Any]					  =      window_size
			lowerCAmelCase__     :    Union[str, Any]					  =      global_attn_indexes
			lowerCAmelCase__     :    Union[str, Any]					  =      num_pos_feats
			lowerCAmelCase__     :    str					  =      int(hidden_size * mlp_ratio	) if mlp_dim is None else mlp_dim





class       _a							(       _lowercase):
	_a						:						Tuple   					=							'''sam'''
	_a						:						Optional[Any]   					=							True




	def __init__(      self		:	Optional[Any]	,      _SCREAMING_SNAKE_CASE		:	Any=None	,      _SCREAMING_SNAKE_CASE		:	Optional[Any]=None	,      _SCREAMING_SNAKE_CASE		:	int=None	,      _SCREAMING_SNAKE_CASE		:	Tuple=0.02	,      **_SCREAMING_SNAKE_CASE		:	int	,      )-> Optional[int]:
			super().__init__(**_SCREAMING_SNAKE_CASE	)
			lowerCAmelCase__     :    Tuple					  =      vision_config if vision_config is not None else {}
			lowerCAmelCase__     :    List[str]					  =      prompt_encoder_config if prompt_encoder_config is not None else {}
			lowerCAmelCase__     :    List[str]					  =      mask_decoder_config if mask_decoder_config is not None else {}

			if isinstance(_SCREAMING_SNAKE_CASE	,      _SCREAMING_SNAKE_CASE	):
					lowerCAmelCase__     :    Any					  =      vision_config.to_dict()
			if isinstance(_SCREAMING_SNAKE_CASE	,      _SCREAMING_SNAKE_CASE	):
					lowerCAmelCase__     :    Any					  =      prompt_encoder_config.to_dict()
			if isinstance(_SCREAMING_SNAKE_CASE	,      _SCREAMING_SNAKE_CASE	):
					lowerCAmelCase__     :    List[Any]					  =      mask_decoder_config.to_dict()

			lowerCAmelCase__     :    Any					  =      SamVisionConfig(**_SCREAMING_SNAKE_CASE	)
			lowerCAmelCase__     :    List[Any]					  =      SamPromptEncoderConfig(**_SCREAMING_SNAKE_CASE	)
			lowerCAmelCase__     :    Dict					  =      SamMaskDecoderConfig(**_SCREAMING_SNAKE_CASE	)
			lowerCAmelCase__     :    List[Any]					  =      initializer_range




	def 							UpperCAmelCase__(      self		:	Any	)-> int:
			lowerCAmelCase__     :    Optional[int]					  =      copy.deepcopy(self.__dict__	)
			lowerCAmelCase__     :    Any					  =      self.vision_config.to_dict()
			lowerCAmelCase__     :    Optional[Any]					  =      self.prompt_encoder_config.to_dict()
			lowerCAmelCase__     :    str					  =      self.mask_decoder_config.to_dict()
			lowerCAmelCase__     :    Any					  =      self.__class__.model_type
			return output




