



from typing import Dict

import numpy as np
import torch

from . import residue_constants as rc
from .tensor_utils import tensor_tree_map, tree_map



def 	__a					(   lowerCAmelCase_       : Dict[str, torch.Tensor]    )				->			Dict[str, torch.Tensor]:






						'''simple docstring'''



						UpperCAmelCase_=       []
						UpperCAmelCase_=       []
						UpperCAmelCase_=       []

						for rt in rc.restypes:
												UpperCAmelCase_=       rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]
												restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names]    )
												UpperCAmelCase_=       {name: i for i, name in enumerate(lowerCAmelCase_    )}
												restype_atomaa_to_atomaa_list.append(
												    [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types]    )

												restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names]    )

						# Add dummy mapping for restype 'UNK'
						restype_atomaa_to_atomaa_list.append([0] * 14    )
						restype_atomaa_to_atomaa_list.append([0] * 37    )
						restype_atomaa_mask_list.append([0.0] * 14    )

						UpperCAmelCase_=       torch.tensor(
						    lowerCAmelCase_      ,dtype=torch.intaa      ,device=protein["""aatype"""].device      ,)
						UpperCAmelCase_=       torch.tensor(
						    lowerCAmelCase_      ,dtype=torch.intaa      ,device=protein["""aatype"""].device      ,)
						UpperCAmelCase_=       torch.tensor(
						    lowerCAmelCase_      ,dtype=torch.floataa      ,device=protein["""aatype"""].device      ,)
						UpperCAmelCase_=       protein["""aatype"""].to(torch.long    )

						# create the mapping for (residx, atom14) --> atom37, i.e. an array
						# with shape (num_res, 14) containing the atom37 indices for this protein
						UpperCAmelCase_=       restype_atomaa_to_atomaa[protein_aatype]
						UpperCAmelCase_=       restype_atomaa_mask[protein_aatype]

						UpperCAmelCase_=       residx_atomaa_mask
						UpperCAmelCase_=       residx_atomaa_to_atomaa.long()

						# create the gather indices for mapping back
						UpperCAmelCase_=       restype_atomaa_to_atomaa[protein_aatype]
						UpperCAmelCase_=       residx_atomaa_to_atomaa.long()

						# create the corresponding mask
						UpperCAmelCase_=       torch.zeros([21, 37]      ,dtype=torch.floataa      ,device=protein["""aatype"""].device    )
						for restype, restype_letter in enumerate(rc.restypes    ):
												UpperCAmelCase_=       rc.restype_atoa[restype_letter]
												UpperCAmelCase_=       rc.residue_atoms[restype_name]
												for atom_name in atom_names:
																		UpperCAmelCase_=       rc.atom_order[atom_name]
																		UpperCAmelCase_=       1

						UpperCAmelCase_=       restype_atomaa_mask[protein_aatype]
						UpperCAmelCase_=       residx_atomaa_mask

						return protein



def 	__a					(   lowerCAmelCase_       : Dict[str, torch.Tensor]    )				->			Dict[str, np.ndarray]:






						'''simple docstring'''



						UpperCAmelCase_=       tree_map(lambda lowerCAmelCase_    : torch.tensor(lowerCAmelCase_      ,device=batch["""aatype"""].device    )      ,lowerCAmelCase_      ,np.ndarray    )
						UpperCAmelCase_=       tensor_tree_map(lambda lowerCAmelCase_    : np.array(lowerCAmelCase_    )      ,make_atomaa_masks(lowerCAmelCase_    )    )
						return out









import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
	import torch_xla.core.xla_model as xm
	import torch_xla.debug.metrics as met






class 		lowercase						(			snake_case__):






	"""simple docstring"""


	def __init__(     self     :						Any						,  *__UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						List[str]=None						,  __UpperCAmelCase     :						Optional[int]=None						,  **__UpperCAmelCase     :						Dict					)      ->			Optional[int]:
							super().__init__(*__UpperCAmelCase						,  **__UpperCAmelCase					)
							UpperCAmelCase_=       eval_examples
							UpperCAmelCase_=       post_process_function




	def   _SCREAMING_SNAKE_CASE		(     self     :						Tuple						,  __UpperCAmelCase     :						Optional[Dataset] = None						,  __UpperCAmelCase     :						Optional[Any]=None						,  __UpperCAmelCase     :						Optional[List[str]] = None						,  __UpperCAmelCase     :						str = "eval"						,  **__UpperCAmelCase     :						Any						,  )      ->			Dict[str, float]:
							UpperCAmelCase_=       gen_kwargs.copy()
							UpperCAmelCase_=       (
							    gen_kwargs["""max_length"""] if gen_kwargs.get("""max_length"""					) is not None else self.args.generation_max_length
							)
							UpperCAmelCase_=       (
							    gen_kwargs["""num_beams"""] if gen_kwargs.get("""num_beams"""					) is not None else self.args.generation_num_beams
							)
							UpperCAmelCase_=       gen_kwargs

							UpperCAmelCase_=       self.eval_dataset if eval_dataset is None else eval_dataset
							UpperCAmelCase_=       self.get_eval_dataloader(__UpperCAmelCase					)
							UpperCAmelCase_=       self.eval_examples if eval_examples is None else eval_examples

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Evaluation"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics
							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)

							if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
													# Only the main node write the results by default
													UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase					)
													UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

													# Prefix all keys with metric_key_prefix + '_'
													for key in list(metrics.keys()					):
																			if not key.startswith(F"""{metric_key_prefix}_"""					):
																									UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)

													metrics.update(output.metrics					)
							else:
													UpperCAmelCase_=       output.metrics

							if self.args.should_log:
													# Only the main node log the results by default
													self.log(__UpperCAmelCase					)

							if self.args.tpu_metrics_debug or self.args.debug:
													# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
													xm.master_print(met.metrics_report()					)

							UpperCAmelCase_=       self.callback_handler.on_evaluate(self.args						,  self.state						,  self.control						,  __UpperCAmelCase					)
							return metrics




	def   _SCREAMING_SNAKE_CASE		(     self     :						int						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Optional[int]=None						,  __UpperCAmelCase     :						str = "test"						,  **__UpperCAmelCase     :						List[str]					)      ->			Tuple:
							UpperCAmelCase_=       gen_kwargs.copy()

							UpperCAmelCase_=       self.get_test_dataloader(__UpperCAmelCase					)

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Prediction"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics

							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)
							if self.post_process_function is None or self.compute_metrics is None:
													return output

							UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase						,  """predict"""					)
							UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

							# Prefix all keys with metric_key_prefix + '_'
							for key in list(metrics.keys()					):
													if not key.startswith(F"""{metric_key_prefix}_"""					):
																			UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)
							metrics.update(output.metrics					)
							return PredictionOutput(predictions=predictions.predictions						,  label_ids=predictions.label_ids						,  metrics=__UpperCAmelCase					)




