


'''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       UpperCAmelCase__ (     UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    None							)					->		torch.Tensor:
     ...



@overload
def       UpperCAmelCase__ (     UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor							)					->		Tuple[torch.Tensor, torch.Tensor]:
     ...



def       UpperCAmelCase__ (     UpperCAmelCase_   :    Tuple				,   UpperCAmelCase_   :    Optional[Any]				,   UpperCAmelCase_   :    Union[str, Any]							)					->		Optional[int]:
     __lowerCamelCase       :     Optional[int]        =		aatype == rc.restype_order['G']
     __lowerCamelCase       :     Optional[int]        =		rc.atom_order['CA']
     __lowerCamelCase       :     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       :     Union[str, Any]        =		torch.where(
              UpperCAmelCase_				,   all_atom_masks[..., ca_idx]				,   all_atom_masks[..., cb_idx]				,   )
          return pseudo_beta, pseudo_beta_mask
     else:
          return pseudo_beta



def       UpperCAmelCase__ (     UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    Dict[str, torch.Tensor]							)					->		torch.Tensor:
     __lowerCamelCase       :     Optional[int]        =		batched_gather(
         UpperCAmelCase_				,   batch['residx_atom37_to_atom14']				,   dim=-2				,   no_batch_dims=len(atomaa.shape[:-2]							)				,   )

     __lowerCamelCase       :     Tuple        =		atomaa_data * batch['atom37_atom_exists'][..., None]

     return atomaa_data



def       UpperCAmelCase__ (     UpperCAmelCase_   :    Dict[str, torch.Tensor]							)					->		torch.Tensor:
     __lowerCamelCase       :     str        =		template_feats['template_aatype']
     __lowerCamelCase       :     Tuple        =		template_feats['template_torsion_angles_sin_cos']
     __lowerCamelCase       :     Optional[int]        =		template_feats['template_alt_torsion_angles_sin_cos']
     __lowerCamelCase       :     List[str]        =		template_feats['template_torsion_angles_mask']
     __lowerCamelCase       :     Dict        =		torch.cat(
         [
             nn.functional.one_hot(UpperCAmelCase_				,   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_   :    Dict[str, torch.Tensor]				,   UpperCAmelCase_   :    torch.types.Number				,   UpperCAmelCase_   :    torch.types.Number				,   UpperCAmelCase_   :    int				,   UpperCAmelCase_   :    bool = False				,   UpperCAmelCase_   :    float = 1e-20				,   UpperCAmelCase_   :    float = 1e8				,   )					->		torch.Tensor:
     __lowerCamelCase       :     Dict        =		batch['template_pseudo_beta_mask']
     __lowerCamelCase       :     Optional[Any]        =		template_mask[..., None] * template_mask[..., None, :]

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

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

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

     __lowerCamelCase       :     List[str]        =		batch['template_aatype'].shape[-1]
     to_concat.append(aatype_one_hot[..., None, :, :].expand(*aatype_one_hot.shape[:-2]				,   UpperCAmelCase_				,   -1				,   -1							)							)
     to_concat.append(aatype_one_hot[..., None, :].expand(*aatype_one_hot.shape[:-2]				,   -1				,   UpperCAmelCase_				,   -1							)							)

     __lowerCamelCase       :     Optional[int]        =		[rc.atom_order[a] for a in ['N', 'CA', 'C']]
     __lowerCamelCase       :     Optional[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=UpperCAmelCase_				,   )
     __lowerCamelCase       :     Union[str, Any]        =		rigids.get_trans()[..., None, :, :]
     __lowerCamelCase       :     Tuple        =		rigids[..., None].invert_apply(UpperCAmelCase_							)

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

     __lowerCamelCase       :     Optional[int]        =		batch['template_all_atom_mask']
     __lowerCamelCase       :     Dict        =		t_aa_masks[..., n] * t_aa_masks[..., ca] * t_aa_masks[..., c]
     __lowerCamelCase       :     str        =		template_mask[..., None] * template_mask[..., None, :]

     __lowerCamelCase       :     Optional[int]        =		inv_distance_scalar * template_mask_ad
     __lowerCamelCase       :     Optional[int]        =		rigid_vec * inv_distance_scalar[..., None]

     if not use_unit_vector:
          __lowerCamelCase       :     List[str]        =		unit_vector * 0.0

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

     __lowerCamelCase       :     Optional[int]        =		torch.cat(UpperCAmelCase_				,   dim=-1							)
     __lowerCamelCase       :     Dict        =		act * template_mask_ad[..., None]

     return act



def       UpperCAmelCase__ (     UpperCAmelCase_   :    Dict[str, torch.Tensor]							)					->		torch.Tensor:
     __lowerCamelCase       :     torch.LongTensor        =		nn.functional.one_hot(batch['extra_msa']				,   23							)
     __lowerCamelCase       :     Optional[Any]        =		[
         msa_ahot,
         batch['extra_has_deletion'].unsqueeze(-1							),
         batch['extra_deletion_value'].unsqueeze(-1							),
     ]
     return torch.cat(UpperCAmelCase_				,   dim=-1							)



def       UpperCAmelCase__ (     UpperCAmelCase_   :    Rigid				,   UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor				,   )					->		Rigid:
     # [*, N, 8, 4, 4]
     __lowerCamelCase       :     str        =		rrgdf[aatype, ...]

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

     __lowerCamelCase       :     Dict        =		alpha.new_zeros((*((1,) * len(alpha.shape[:-1]							)), 2)							)
     __lowerCamelCase       :     int        =		1

     # [*, N, 8, 2]
     __lowerCamelCase       :     Dict        =		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       :     str        =		1
     __lowerCamelCase       :     List[Any]        =		alpha[..., 1]
     __lowerCamelCase       :     Any        =		-alpha[..., 0]
     __lowerCamelCase       :     List[Any]        =		alpha

     __lowerCamelCase       :     Optional[int]        =		default_r.compose(Rigid(Rotation(rot_mats=UpperCAmelCase_							)				,   UpperCAmelCase_							)							)

     __lowerCamelCase       :     List[Any]        =		all_frames[..., 5]
     __lowerCamelCase       :     Union[str, Any]        =		all_frames[..., 6]
     __lowerCamelCase       :     Dict        =		all_frames[..., 7]

     __lowerCamelCase       :     Optional[Any]        =		all_frames[..., 4]
     __lowerCamelCase       :     Any        =		chia_frame_to_bb.compose(UpperCAmelCase_							)
     __lowerCamelCase       :     List[str]        =		chia_frame_to_bb.compose(UpperCAmelCase_							)
     __lowerCamelCase       :     Union[str, Any]        =		chia_frame_to_bb.compose(UpperCAmelCase_							)

     __lowerCamelCase       :     Optional[Any]        =		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       :     Dict        =		r[..., None].compose(UpperCAmelCase_							)

     return all_frames_to_global



def       UpperCAmelCase__ (     UpperCAmelCase_   :    Rigid				,   UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor				,   UpperCAmelCase_   :    torch.Tensor				,   )					->		torch.Tensor:
     # [*, N, 14]
     __lowerCamelCase       :     Optional[int]        =		group_idx[aatype, ...]

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

     # [*, N, 14, 8]
     __lowerCamelCase       :     int        =		r[..., None, :] * group_mask_one_hot

     # [*, N, 14]
     __lowerCamelCase       :     int        =		t_atoms_to_global.map_tensor_fn(lambda UpperCAmelCase_							: torch.sum(UpperCAmelCase_				,   dim=-1							)							)

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

     # [*, N, 14, 3]
     __lowerCamelCase       :     Optional[int]        =		lit_positions[aatype, ...]
     __lowerCamelCase       :     Tuple        =		t_atoms_to_global.apply(UpperCAmelCase_							)
     __lowerCamelCase       :     Optional[Any]        =		pred_positions * atom_mask

     return pred_positions










'''simple docstring'''



import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mpnet import MPNetTokenizer


A__		: int												=  logging.get_logger(__name__)

A__		: Union[str, Any]												=  {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

A__		: int												=  {
    """vocab_file""": {
        """microsoft/mpnet-base""": """https://huggingface.co/microsoft/mpnet-base/resolve/main/vocab.txt""",
    },
    """tokenizer_file""": {
        """microsoft/mpnet-base""": """https://huggingface.co/microsoft/mpnet-base/resolve/main/tokenizer.json""",
    },
}

A__		: int												=  {
    """microsoft/mpnet-base""": 512,
}

A__		: Optional[Any]												=  {
    """microsoft/mpnet-base""": {"""do_lower_case""": True},
}





class        UpperCAmelCase_  (_UpperCAmelCase  ):





    """simple docstring"""






    lowerCamelCase  : int												=      VOCAB_FILES_NAMES
    lowerCamelCase  : int												=      PRETRAINED_VOCAB_FILES_MAP
    lowerCamelCase  : List[Any]												=      PRETRAINED_INIT_CONFIGURATION
    lowerCamelCase  : int												=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    lowerCamelCase  : Tuple												=      MPNetTokenizer
    lowerCamelCase  : List[Any]												=      ['input_ids', 'attention_mask']







    def __init__(							self      ,					SCREAMING_SNAKE_CASE_=None      ,					SCREAMING_SNAKE_CASE_=None      ,					SCREAMING_SNAKE_CASE_=True      ,					SCREAMING_SNAKE_CASE_="<s>"      ,					SCREAMING_SNAKE_CASE_="</s>"      ,					SCREAMING_SNAKE_CASE_="</s>"      ,					SCREAMING_SNAKE_CASE_="<s>"      ,					SCREAMING_SNAKE_CASE_="[UNK]"      ,					SCREAMING_SNAKE_CASE_="<pad>"      ,					SCREAMING_SNAKE_CASE_="<mask>"      ,					SCREAMING_SNAKE_CASE_=True      ,					SCREAMING_SNAKE_CASE_=None      ,					**SCREAMING_SNAKE_CASE_      ,					)    ->					Any:
         super().__init__(
             SCREAMING_SNAKE_CASE_      ,					tokenizer_file=SCREAMING_SNAKE_CASE_      ,					do_lower_case=SCREAMING_SNAKE_CASE_      ,					bos_token=SCREAMING_SNAKE_CASE_      ,					eos_token=SCREAMING_SNAKE_CASE_      ,					sep_token=SCREAMING_SNAKE_CASE_      ,					cls_token=SCREAMING_SNAKE_CASE_      ,					unk_token=SCREAMING_SNAKE_CASE_      ,					pad_token=SCREAMING_SNAKE_CASE_      ,					mask_token=SCREAMING_SNAKE_CASE_      ,					tokenize_chinese_chars=SCREAMING_SNAKE_CASE_      ,					strip_accents=SCREAMING_SNAKE_CASE_      ,					**SCREAMING_SNAKE_CASE_      ,					)

         __lowerCamelCase       :     Union[str, Any]        =		json.loads(self.backend_tokenizer.normalizer.__getstate__()     )
         if (
             pre_tok_state.get('lowercase'      ,					SCREAMING_SNAKE_CASE_     ) != do_lower_case
             or pre_tok_state.get('strip_accents'      ,					SCREAMING_SNAKE_CASE_     ) != strip_accents
         ):
              __lowerCamelCase       :     List[Any]        =		getattr(SCREAMING_SNAKE_CASE_      ,					pre_tok_state.pop('type'     )     )
              __lowerCamelCase       :     List[str]        =		do_lower_case
              __lowerCamelCase       :     str        =		strip_accents
              __lowerCamelCase       :     Union[str, Any]        =		pre_tok_class(**SCREAMING_SNAKE_CASE_     )

         __lowerCamelCase       :     Tuple        =		do_lower_case







    @property
    def 				lowercase_    (							self     )    ->					str:
         if self._mask_token is None:
              if self.verbose:
                   logger.error('Using mask_token, but it is not set yet.'     )
              return None
         return str(self._mask_token     )







    @mask_token.setter
    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_     )    ->					Union[str, Any]:
         __lowerCamelCase       :     Any        =		AddedToken(SCREAMING_SNAKE_CASE_      ,					lstrip=SCREAMING_SNAKE_CASE_      ,					rstrip=SCREAMING_SNAKE_CASE_     ) if isinstance(SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_     ) else value
         __lowerCamelCase       :     int        =		value







    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_=None     )    ->					Union[str, Any]:
         __lowerCamelCase       :     Dict        =		[self.bos_token_id] + token_ids_a + [self.eos_token_id]
         if token_ids_a is None:
              return output

         return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]







    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = None     )    ->					List[int]:
         __lowerCamelCase       :     List[Any]        =		[self.sep_token_id]
         __lowerCamelCase       :     List[Any]        =		[self.cls_token_id]

         if token_ids_a is None:
              return len(cls + token_ids_a + sep     ) * [0]
         return len(cls + token_ids_a + sep + sep + token_ids_a + sep     ) * [0]







    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = None     )    ->					Tuple[str]:
         __lowerCamelCase       :     Optional[Any]        =		self._tokenizer.model.save(SCREAMING_SNAKE_CASE_      ,					name=SCREAMING_SNAKE_CASE_     )
         return tuple(SCREAMING_SNAKE_CASE_     )






