


'''simple docstring'''
from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available



def 				lowerCAmelCase__	(       UpperCAmelCase     ):






       """simple docstring"""





       if is_torch_available():
              import torch

              if isinstance(UpperCAmelCase    ,       torch.Tensor     ):
                     return True

       return isinstance(UpperCAmelCase    ,       np.ndarray     )







class 					_A						(						UpperCamelCase							):



   '''simple docstring'''






   def   __lowerCAmelCase						(	self	:					Any						)->	Union[str, Any]:
          snake_case__					:	Tuple          =					fields(self						)

          # Safety and consistency checks
          if not len(lowerCamelCase						):
                 raise ValueError(F"""{self.__class__.__name__} has no fields."""						)

          snake_case__					:	Any          =					getattr(self					, class_fields[0].name						)
          snake_case__					:	Optional[Any]          =					all(getattr(self					, field.name						) is None for field in class_fields[1:]						)

          if other_fields_are_none and isinstance(lowerCamelCase					, lowerCamelCase						):
                 for key, value in first_field.items():
                        snake_case__					:	str          =					value
          else:
                 for field in class_fields:
                        snake_case__					:	str          =					getattr(self					, field.name						)
                        if v is not None:
                               snake_case__					:	List[Any]          =					v




   def __delitem__(	self	:					Optional[Any]					, *lowerCamelCase	:					Optional[Any]					, **lowerCamelCase	:					str						)->	List[str]:
          raise Exception(F"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""						)




   def   __lowerCAmelCase						(	self	:					Optional[int]					, *lowerCamelCase	:					List[str]					, **lowerCamelCase	:					Union[str, Any]						)->	Tuple:
          raise Exception(F"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""						)




   def   __lowerCAmelCase						(	self	:					Dict					, *lowerCamelCase	:					Dict					, **lowerCamelCase	:					Union[str, Any]						)->	int:
          raise Exception(F"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""						)




   def   __lowerCAmelCase						(	self	:					Optional[Any]					, *lowerCamelCase	:					Any					, **lowerCamelCase	:					Optional[Any]						)->	Optional[Any]:
          raise Exception(F"""You cannot use ``update`` on a {self.__class__.__name__} instance."""						)




   def __getitem__(	self	:					Union[str, Any]					, lowerCamelCase	:					Optional[int]						)->	Dict:
          if isinstance(lowerCamelCase					, lowerCamelCase						):
                 snake_case__					:	Optional[int]          =					dict(self.items()						)
                 return inner_dict[k]
          else:
                 return self.to_tuple()[k]




   def __setattr__(	self	:					str					, lowerCamelCase	:					Union[str, Any]					, lowerCamelCase	:					Tuple						)->	Dict:
          if name in self.keys() and value is not None:
                 # Don't call self.__setitem__ to avoid recursion errors
                 super().__setitem__(lowerCamelCase					, lowerCamelCase						)
          super().__setattr__(lowerCamelCase					, lowerCamelCase						)




   def __setitem__(	self	:					str					, lowerCamelCase	:					List[Any]					, lowerCamelCase	:					Dict						)->	Dict:
          # Will raise a KeyException if needed
          super().__setitem__(lowerCamelCase					, lowerCamelCase						)
          # Don't call self.__setattr__ to avoid recursion errors
          super().__setattr__(lowerCamelCase					, lowerCamelCase						)




   def   __lowerCAmelCase						(	self	:					Tuple						)->	Tuple[Any]:
          return tuple(self[k] for k in self.keys()						)








'''simple docstring'''
from typing import Dict, Optional, Tuple

import torch



def 				lowerCAmelCase__	(       UpperCAmelCase     ):






       """simple docstring"""





       snake_case__					:	Optional[int]          =					boundaries[1] - boundaries[0]
       snake_case__					:	Optional[Any]          =					boundaries + step / 2
       snake_case__					:	str          =					torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1     )]    ,       dim=0     )
       return bin_centers



def 				lowerCAmelCase__	(       UpperCAmelCase    ,       UpperCAmelCase    ,       ):






       """simple docstring"""





       snake_case__					:	str          =					_calculate_bin_centers(UpperCAmelCase     )
       return (
           torch.sum(aligned_distance_error_probs * bin_centers    ,       dim=-1     ),
           bin_centers[-1],
       )



def 				lowerCAmelCase__	(       UpperCAmelCase    ,       UpperCAmelCase = 31    ,       UpperCAmelCase = 64    ,       **UpperCAmelCase    ,       ):






       """simple docstring"""





       snake_case__					:	Dict          =					torch.linspace(0    ,       UpperCAmelCase    ,       steps=(no_bins - 1)    ,       device=logits.device     )

       snake_case__					:	str          =					torch.nn.functional.softmax(UpperCAmelCase    ,       dim=-1     )
       snake_case__       ,   snake_case__					:	List[str]          =					_calculate_expected_aligned_error(
           alignment_confidence_breaks=UpperCAmelCase    ,       aligned_distance_error_probs=UpperCAmelCase    ,       )

       return {
           "aligned_confidence_probs": aligned_confidence_probs,
           "predicted_aligned_error": predicted_aligned_error,
           "max_predicted_aligned_error": max_predicted_aligned_error,
       }






def 				lowerCAmelCase__	(       UpperCAmelCase    ,       UpperCAmelCase = None    ,       UpperCAmelCase = 31    ,       UpperCAmelCase = 64    ,       UpperCAmelCase = 1E-8    ,       **UpperCAmelCase    ,       ):






       """simple docstring"""





       if residue_weights is None:
              snake_case__					:	List[Any]          =					logits.new_ones(logits.shape[-2]     )

       snake_case__					:	Optional[Any]          =					torch.linspace(0    ,       UpperCAmelCase    ,       steps=(no_bins - 1)    ,       device=logits.device     )

       snake_case__					:	int          =					_calculate_bin_centers(UpperCAmelCase     )
       torch.sum(UpperCAmelCase     )
       snake_case__					:	Dict          =					logits.shape[-2]
       snake_case__					:	Optional[Any]          =					max(UpperCAmelCase    ,       19     )

       snake_case__					:	Optional[int]          =					1.2_4 * (clipped_n - 15) ** (1.0 / 3) - 1.8

       snake_case__					:	Tuple          =					torch.nn.functional.softmax(UpperCAmelCase    ,       dim=-1     )

       snake_case__					:	int          =					1.0 / (1 + (bin_centers**2) / (da**2))
       snake_case__					:	Optional[int]          =					torch.sum(probs * tm_per_bin    ,       dim=-1     )

       snake_case__					:	Optional[Any]          =					residue_weights / (eps + residue_weights.sum())
       snake_case__					:	Any          =					torch.sum(predicted_tm_term * normed_residue_mask    ,       dim=-1     )

       snake_case__					:	Dict          =					per_alignment * residue_weights

       snake_case__					:	List[str]          =					(weighted == torch.max(UpperCAmelCase     )).nonzero()[0]
       return per_alignment[tuple(UpperCAmelCase     )]




