



"""simple docstring"""







import dataclasses
import re
import string
from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple

import numpy as np

from . import residue_constants


A    =			Mapping[str, np.ndarray]
A    =			Mapping[str, Any]  # Is a nested dict.
A    =			0.01






@dataclasses.dataclass(frozen=UpperCamelCase     )
class      UpperCAmelCase__		:
		lowerCAmelCase_       :	np.ndarray  # [num_res, num_atom_type, 3]

		# Amino-acid type for each residue represented as an integer between 0 and
		# 20, where 20 is 'X'.
		lowerCAmelCase_       :	np.ndarray  # [num_res]

		# Binary float mask to indicate presence of a particular atom. 1.0 if an atom
		# is present and 0.0 if not. This should be used for loss masking.
		lowerCAmelCase_       :	np.ndarray  # [num_res, num_atom_type]

		# Residue index as used in PDB. It is not necessarily continuous or 0-indexed.
		lowerCAmelCase_       :	np.ndarray  # [num_res]

		# B-factors, or temperature factors, of each residue (in sq. angstroms units),
		# representing the displacement of the residue from its ground truth mean
		# value.
		lowerCAmelCase_       :	np.ndarray  # [num_res, num_atom_type]

		# Chain indices for multi-chain predictions
		lowerCAmelCase_       :	Optional[np.ndarray] 							=     None

		# Optional remark about the protein. Included as a comment in output PDB
		# files
		lowerCAmelCase_       :	Optional[str] 							=     None

		# Templates used to generate this protein (prediction-only)
		lowerCAmelCase_       :	Optional[Sequence[str]] 							=     None

		# Chain corresponding to each parent
		lowerCAmelCase_       :	Optional[Sequence[int]] 							=     None



def   lowerCAmelCase__			(     lowerCamelCase__			) ->							Protein:
							A         =					R'(\[[A-Z]+\]\n)'
							A         =					[tag.strip() for tag in re.split(lowerCamelCase__				,      lowerCamelCase__			) if len(lowerCamelCase__			) > 0]
							A         =					zip(tags[0::2]				,      [l.split('\n'			) for l in tags[1::2]]			)

							A         =					["N", "CA", "C"]
							A         =					None
							A         =					None
							A         =					None
							for g in groups:
														if "[PRIMARY]" == g[0]:
																					A         =					g[1][0].strip()
																					for i in range(len(lowerCamelCase__			)			):
																												if seq[i] not in residue_constants.restypes:
																																			A         =					'X'  # FIXME: strings are immutable
																					A         =					np.array(
																					    [residue_constants.restype_order.get(lowerCamelCase__				,      residue_constants.restype_num			) for res_symbol in seq]			)
														elif "[TERTIARY]" == g[0]:
																					A         =					[]
																					for axis in range(3			):
																												tertiary.append(list(map(lowerCamelCase__				,      g[1][axis].split()			)			)			)
																					A         =					np.array(lowerCamelCase__			)
																					A         =					np.zeros((len(tertiary[0]			) // 3, residue_constants.atom_type_num, 3)			).astype(np.floataa			)
																					for i, atom in enumerate(lowerCamelCase__			):
																												A         =					np.transpose(tertiary_np[:, i::3]			)
																					atom_positions *= PICO_TO_ANGSTROM
														elif "[MASK]" == g[0]:
																					A         =					np.array(list(map({'-': 0, '+': 1}.get				,      g[1][0].strip()			)			)			)
																					A         =					np.zeros(
																					    (
																					        len(lowerCamelCase__			),
																					        residue_constants.atom_type_num,
																					    )			).astype(np.floataa			)
																					for i, atom in enumerate(lowerCamelCase__			):
																												A         =					1
																					atom_mask *= mask[..., None]

							assert aatype is not None

							return Protein(
							    atom_positions=lowerCamelCase__				,      atom_mask=lowerCamelCase__				,      aatype=lowerCamelCase__				,      residue_index=np.arange(len(lowerCamelCase__			)			)				,      b_factors=lowerCamelCase__				,      )

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__ = 0			) ->							List[str]:
							A         =					[]

							A         =					prot.remark
							if remark is not None:
														pdb_headers.append(f"""REMARK {remark}"""			)

							A         =					prot.parents
							A         =					prot.parents_chain_index
							if parents is not None and parents_chain_index is not None:
														A         =					[p for i, p in zip(lowerCamelCase__				,      lowerCamelCase__			) if i == chain_id]

							if parents is None or len(lowerCamelCase__			) == 0:
														A         =					['N/A']

							pdb_headers.append(f"""PARENT {' '.join(lowerCamelCase__			)}"""			)

							return pdb_headers

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__			) ->							str:
							A         =					[]
							A         =					pdb_str.split('\n'			)

							A         =					prot.remark
							if remark is not None:
														out_pdb_lines.append(f"""REMARK {remark}"""			)

							A         =					42
							if prot.parents is not None and len(prot.parents			) > 0:
														A         =					[]
														if prot.parents_chain_index is not None:
																					A         =					{}
																					for p, i in zip(prot.parents				,      prot.parents_chain_index			):
																												parent_dict.setdefault(str(lowerCamelCase__			)				,      []			)
																												parent_dict[str(lowerCamelCase__			)].append(lowerCamelCase__			)

																					A         =					max([int(lowerCamelCase__			) for chain_idx in parent_dict]			)
																					for i in range(max_idx + 1			):
																												A         =					parent_dict.get(str(lowerCamelCase__			)				,      ['N/A']			)
																												parents_per_chain.append(lowerCamelCase__			)
														else:
																					parents_per_chain.append(list(prot.parents			)			)
							else:
														A         =					[['N/A']]

							def make_parent_line(lowerCamelCase__			) -> str:
														return f"""PARENT {' '.join(lowerCamelCase__			)}"""

							out_pdb_lines.append(make_parent_line(parents_per_chain[0]			)			)

							A         =					0
							for i, l in enumerate(lowerCamelCase__			):
														if "PARENT" not in l and "REMARK" not in l:
																					out_pdb_lines.append(lowerCamelCase__			)
														if "TER" in l and "END" not in lines[i + 1]:
																					chain_counter += 1
																					if not chain_counter >= len(lowerCamelCase__			):
																												A         =					parents_per_chain[chain_counter]
																					else:
																												A         =					['N/A']

																					out_pdb_lines.append(make_parent_line(lowerCamelCase__			)			)

							return "\n".join(lowerCamelCase__			)

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							str:
							A         =					residue_constants.restypes + ['X']

							def res_atoa(lowerCamelCase__			) -> str:
														return residue_constants.restype_atoa.get(restypes[r]				,      'UNK'			)

							A         =					residue_constants.atom_types

							A         =					[]

							A         =					prot.atom_mask
							A         =					prot.aatype
							A         =					prot.atom_positions
							A         =					prot.residue_index.astype(np.intaa			)
							A         =					prot.b_factors
							A         =					prot.chain_index

							if np.any(aatype > residue_constants.restype_num			):
														raise ValueError('Invalid aatypes.'			)

							A         =					get_pdb_headers(lowerCamelCase__			)
							if len(lowerCamelCase__			) > 0:
														pdb_lines.extend(lowerCamelCase__			)

							A         =					aatype.shape[0]
							A         =					1
							A         =					0
							A         =					string.ascii_uppercase
							A         =					None
							# Add all atom sites.
							for i in range(lowerCamelCase__			):
														A         =					res_atoa(aatype[i]			)
														for atom_name, pos, mask, b_factor in zip(lowerCamelCase__				,      atom_positions[i]				,      atom_mask[i]				,      b_factors[i]			):
																					if mask < 0.5:
																												continue

																					A         =					'ATOM'
																					A         =					atom_name if len(lowerCamelCase__			) == 4 else f""" {atom_name}"""
																					A         =					''
																					A         =					''
																					A         =					1.00
																					A         =					atom_name[0]  # Protein supports only C, N, O, S, this works.
																					A         =					''

																					A         =					'A'
																					if chain_index is not None:
																												A         =					chain_tags[chain_index[i]]

																					# PDB is a columnar format, every space matters here!
																					A         =					(
																					    f"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}"""
																					    f"""{res_name_a:>3} {chain_tag:>1}"""
																					    f"""{residue_index[i]:>4}{insertion_code:>1}   """
																					    f"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}"""
																					    f"""{occupancy:>6.2f}{b_factor:>6.2f}          """
																					    f"""{element:>2}{charge:>2}"""
																					)
																					pdb_lines.append(lowerCamelCase__			)
																					atom_index += 1

														A         =					i == n - 1
														if chain_index is not None:
																					if i != n - 1 and chain_index[i + 1] != prev_chain_index:
																												A         =					True
																												A         =					chain_index[i + 1]

														if should_terminate:
																					# Close the chain.
																					A         =					'TER'
																					A         =					(
																					    f"""{chain_end:<6}{atom_index:>5}      {res_atoa(aatype[i]			):>3} {chain_tag:>1}{residue_index[i]:>4}"""
																					)
																					pdb_lines.append(lowerCamelCase__			)
																					atom_index += 1

																					if i != n - 1:
																												# "prev" is a misnomer here. This happens at the beginning of
																												# each new chain.
																												pdb_lines.extend(get_pdb_headers(lowerCamelCase__				,      lowerCamelCase__			)			)

							pdb_lines.append('END'			)
							pdb_lines.append(''			)
							return "\n".join(lowerCamelCase__			)

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							np.ndarray:
							return residue_constants.STANDARD_ATOM_MASK[prot.aatype]

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__ = None				,      lowerCamelCase__ = None				,      lowerCamelCase__ = None				,      lowerCamelCase__ = None				,      lowerCamelCase__ = None				,      ) ->							Protein:
							return Protein(
							    aatype=features['aatype']				,      atom_positions=result['final_atom_positions']				,      atom_mask=result['final_atom_mask']				,      residue_index=features['residue_index'] + 1				,      b_factors=b_factors if b_factors is not None else np.zeros_like(result['final_atom_mask']			)				,      chain_index=lowerCamelCase__				,      remark=lowerCamelCase__				,      parents=lowerCamelCase__				,      parents_chain_index=lowerCamelCase__				,      )








"""simple docstring"""







import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


A    =			logging.get_logger(__name__)

A    =			list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
A    =			tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class      UpperCAmelCase__		:
		lowerCAmelCase_       :	str 							=     field(
		    default=UpperCamelCase   ,metadata={"""help""": """Model type selected in the list: """ + """, """.join(UpperCamelCase     )}     )
		lowerCAmelCase_       :	str 							=     field(
		    default=UpperCamelCase   ,metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}     )
		lowerCAmelCase_       :	int 							=     field(
		    default=1_28   ,metadata={
		        """help""": (
		            """The maximum total input sequence length after tokenization. Sequences longer """
		            """than this will be truncated, sequences shorter will be padded."""
		        )
		    }   ,)
		lowerCAmelCase_       :	int 							=     field(
		    default=1_28   ,metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}   ,)
		lowerCAmelCase_       :	int 							=     field(
		    default=64   ,metadata={
		        """help""": (
		            """The maximum number of tokens for the question. Questions longer than this will """
		            """be truncated to this length."""
		        )
		    }   ,)
		lowerCAmelCase_       :	int 							=     field(
		    default=30   ,metadata={
		        """help""": (
		            """The maximum length of an answer that can be generated. This is needed because the start """
		            """and end predictions are not conditioned on one another."""
		        )
		    }   ,)
		lowerCAmelCase_       :	bool 							=     field(
		    default=UpperCamelCase   ,metadata={"""help""": """Overwrite the cached training and evaluation sets"""}     )
		lowerCAmelCase_       :	bool 							=     field(
		    default=UpperCamelCase   ,metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}     )
		lowerCAmelCase_       :	float 							=     field(
		    default=0.0   ,metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}     )
		lowerCAmelCase_       :	int 							=     field(
		    default=20   ,metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}     )
		lowerCAmelCase_       :	int 							=     field(
		    default=0   ,metadata={
		        """help""": (
		            """language id of input for language-specific xlm models (see"""
		            """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
		        )
		    }   ,)
		lowerCAmelCase_       :	int 							=     field(default=1   ,metadata={"""help""": """multiple threads for converting example to features"""}     )






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	str 							=     """train"""
		lowerCAmelCase_       :	Union[str, Any] 							=     """dev"""






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	SquadDataTrainingArguments
		lowerCAmelCase_       :	List[SquadFeatures]
		lowerCAmelCase_       :	Split
		lowerCAmelCase_       :	bool



		def __init__( self  :    List[Any]      ,							snake_case  :    SquadDataTrainingArguments      ,							snake_case  :    PreTrainedTokenizer      ,							snake_case  :    Optional[int] = None      ,							snake_case  :    Union[str, Split] = Split.train      ,							snake_case  :    Optional[bool] = False      ,							snake_case  :    Optional[str] = None      ,							snake_case  :    Optional[str] = "pt"      ,							)			->						Optional[Any]:






									'''simple docstring'''

									A         =					args
									A         =					is_language_sensitive
									A         =					SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
									if isinstance(snake_case      ,							snake_case				):
																try:
																							A         =					Split[mode]
																except KeyError:
																							raise KeyError('mode is not a valid split name'				)
									A         =					mode
									# Load data features from cache or dataset file
									A         =					'v2' if args.version_2_with_negative else 'v1'
									A         =					os.path.join(
									    cache_dir if cache_dir is not None else args.data_dir      ,							f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"""      ,							)

									# Make sure only the first process in distributed training processes the dataset,
									# and the others will use the cache.
									A         =					cached_features_file + '.lock'
									with FileLock(snake_case				):
																if os.path.exists(snake_case				) and not args.overwrite_cache:
																							A         =					time.time()
																							A         =					torch.load(snake_case				)

																							# Legacy cache files have only features, while new cache files
																							# will have dataset and examples also.
																							A         =					self.old_features['features']
																							A         =					self.old_features.get('dataset'      ,							snake_case				)
																							A         =					self.old_features.get('examples'      ,							snake_case				)
																							logger.info(
																							    f"""Loading features from cached file {cached_features_file} [took %.3f s]"""      ,							time.time() - start				)

																							if self.dataset is None or self.examples is None:
																														logger.warning(
																														    f"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"""
																														    ' future run'				)
																else:
																							if mode == Split.dev:
																														A         =					self.processor.get_dev_examples(args.data_dir				)
																							else:
																														A         =					self.processor.get_train_examples(args.data_dir				)

																							A      ,  A         =					squad_convert_examples_to_features(
																							    examples=self.examples      ,							tokenizer=snake_case      ,							max_seq_length=args.max_seq_length      ,							doc_stride=args.doc_stride      ,							max_query_length=args.max_query_length      ,							is_training=mode == Split.train      ,							threads=args.threads      ,							return_dataset=snake_case      ,							)

																							A         =					time.time()
																							torch.save(
																							    {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}      ,							snake_case      ,							)
																							# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																							logger.info(
																							    f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"""				)



		def __len__( self  :    Any				)			->						Dict:






									'''simple docstring'''

									return len(self.features				)



		def __getitem__( self  :    Union[str, Any]      ,							snake_case  :    List[str]				)			->						Dict[str, torch.Tensor]:






									'''simple docstring'''

									A         =					self.features[i]

									A         =					torch.tensor(feature.input_ids      ,							dtype=torch.long				)
									A         =					torch.tensor(feature.attention_mask      ,							dtype=torch.long				)
									A         =					torch.tensor(feature.token_type_ids      ,							dtype=torch.long				)
									A         =					torch.tensor(feature.cls_index      ,							dtype=torch.long				)
									A         =					torch.tensor(feature.p_mask      ,							dtype=torch.float				)
									A         =					torch.tensor(feature.is_impossible      ,							dtype=torch.float				)

									A         =					{
									    'input_ids': input_ids,
									    'attention_mask': attention_mask,
									    'token_type_ids': token_type_ids,
									}

									if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
																del inputs["token_type_ids"]

									if self.args.model_type in ["xlnet", "xlm"]:
																inputs.update({'cls_index': cls_index, 'p_mask': p_mask}				)
																if self.args.version_2_with_negative:
																							inputs.update({'is_impossible': is_impossible}				)
																if self.is_language_sensitive:
																							inputs.update({'langs': (torch.ones(input_ids.shape      ,							dtype=torch.intaa				) * self.args.lang_id)}				)

									if self.mode == Split.train:
																A         =					torch.tensor(feature.start_position      ,							dtype=torch.long				)
																A         =					torch.tensor(feature.end_position      ,							dtype=torch.long				)
																inputs.update({'start_positions': start_positions, 'end_positions': end_positions}				)

									return inputs



