






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


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




@dataclasses.dataclass(frozen=snake_case_							)
class 					UpperCamelCase_ :



	'''simple docstring'''




	lowerCAmelCase						=					42  # [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						=					42  # [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						=					42  # [num_res, num_atom_type]

	# Residue index as used in PDB. It is not necessarily continuous or 0-indexed.
	lowerCAmelCase						=					42  # [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						=					42  # [num_res, num_atom_type]

	# Chain indices for multi-chain predictions
	lowerCAmelCase						=					None

	# Optional remark about the protein. Included as a comment in output PDB
	# files
	lowerCAmelCase						=					None

	# Templates used to generate this protein (prediction-only)
	lowerCAmelCase						=					None

	# Chain corresponding to each parent
	lowerCAmelCase						=					None






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

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

							assert aatype is not None

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





def 		__UpperCAmelCase     (	a_				,	a_ = 0):
							snake_case_           =				[]

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

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

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

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

							return pdb_headers





def 		__UpperCAmelCase     (	a_				,	a_):
							snake_case_           =				[]
							snake_case_           =				pdb_str.split('\n')

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

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

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

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

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

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

																					out_pdb_lines.append(make_parent_line(a_))

							return "\n".join(a_)





def 		__UpperCAmelCase     (	a_):
							snake_case_           =				residue_constants.restypes + ['X']

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

							snake_case_           =				residue_constants.atom_types

							snake_case_           =				[]

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

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

							snake_case_           =				get_pdb_headers(a_)
							if len(a_) > 0:
														pdb_lines.extend(a_)

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

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

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

																					# PDB is a columnar format, every space matters here!
																					snake_case_           =				(
																					    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(a_)
																					atom_index += 1

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

														if should_terminate:
																					# Close the chain.
																					snake_case_           =				'TER'
																					snake_case_           =				(
																					    f'''{chain_end:<6}{atom_index:>5}      {res_atoa(aatype[i]):>3} {chain_tag:>1}{residue_index[i]:>4}'''
																					)
																					pdb_lines.append(a_)
																					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(a_				,	a_))

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





def 		__UpperCAmelCase     (	a_):
							return residue_constants.STANDARD_ATOM_MASK[prot.aatype]





def 		__UpperCAmelCase     (	a_				,	a_				,	a_ = None				,	a_ = None				,	a_ = None				,	a_ = None				,	a_ = None				,	):
							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=a_				,	remark=a_				,	parents=a_				,	parents_chain_index=a_				,	)













from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import tensorflow as tf

	from transformers import TFCvtForImageClassification, TFCvtModel
	from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor




class 					UpperCamelCase_ (     snake_case_							):



	'''simple docstring'''




	def 				_UpperCamelCase     (			self   )			->       Any:
								snake_case_           =				self.config_class(**self.inputs_dict   )
								self.parent.assertTrue(hasattr(a			,     'embed_dim'   )   )
								self.parent.assertTrue(hasattr(a			,     'num_heads'   )   )






class 					UpperCamelCase_ :



	'''simple docstring'''




	def __init__(			self			,     a			,     a=13			,     a=64			,     a=3			,     a=[16, 48, 96]			,     a=[1, 3, 6]			,     a=[1, 2, 10]			,     a=[7, 3, 3]			,     a=[4, 2, 2]			,     a=[2, 1, 1]			,     a=[2, 2, 2]			,     a=[False, False, True]			,     a=[0.0, 0.0, 0.0]			,     a=0.02			,     a=1E-12			,     a=True			,     a=True			,     a=2			,     )			->       List[Any]:
								snake_case_           =				parent
								snake_case_           =				batch_size
								snake_case_           =				image_size
								snake_case_           =				patch_sizes
								snake_case_           =				patch_stride
								snake_case_           =				patch_padding
								snake_case_           =				is_training
								snake_case_           =				use_labels
								snake_case_           =				num_labels
								snake_case_           =				num_channels
								snake_case_           =				embed_dim
								snake_case_           =				num_heads
								snake_case_           =				stride_kv
								snake_case_           =				depth
								snake_case_           =				cls_token
								snake_case_           =				attention_drop_rate
								snake_case_           =				initializer_range
								snake_case_           =				layer_norm_eps




	def 				_UpperCamelCase     (			self   )			->       Dict:
								snake_case_           =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

								snake_case_           =				None
								if self.use_labels:
															# create a random int32 tensor of given shape
															snake_case_           =				ids_tensor([self.batch_size]			,     self.num_labels   )

								snake_case_           =				self.get_config()
								return config, pixel_values, labels




	def 				_UpperCamelCase     (			self   )			->       Dict:
								return CvtConfig(
								    image_size=self.image_size			,     num_labels=self.num_labels			,     num_channels=self.num_channels			,     embed_dim=self.embed_dim			,     num_heads=self.num_heads			,     patch_sizes=self.patch_sizes			,     patch_padding=self.patch_padding			,     patch_stride=self.patch_stride			,     stride_kv=self.stride_kv			,     depth=self.depth			,     cls_token=self.cls_token			,     attention_drop_rate=self.attention_drop_rate			,     initializer_range=self.initializer_range			,     )




	def 				_UpperCamelCase     (			self			,     a			,     a			,     a   )			->       int:
								snake_case_           =				TFCvtModel(config=a   )
								snake_case_           =				model(a			,     training=a   )
								snake_case_           =				(self.image_size, self.image_size)
								snake_case_     ,						snake_case_           =				image_size[0], image_size[1]
								for i in range(len(self.depth   )   ):
															snake_case_           =				floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
															snake_case_           =				floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
								self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.embed_dim[-1], height, width)   )




	def 				_UpperCamelCase     (			self			,     a			,     a			,     a   )			->       Dict:
								snake_case_           =				self.num_labels
								snake_case_           =				TFCvtForImageClassification(a   )
								snake_case_           =				model(a			,     labels=a			,     training=a   )
								self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.num_labels)   )






	def 				_UpperCamelCase     (			self   )			->       Tuple:
								snake_case_           =				self.prepare_config_and_inputs()
								snake_case_     ,						snake_case_     ,						snake_case_           =				config_and_inputs
								snake_case_           =				{'pixel_values': pixel_values}
								return config, inputs_dict






@require_tf
class 					UpperCamelCase_ (     snake_case_			,   snake_case_			,   unittest.TestCase							):



	'''simple docstring'''




	lowerCAmelCase						=					(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
	lowerCAmelCase						=					(
	    {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
	    if is_tf_available()
	    else {}
	)
	lowerCAmelCase						=					False
	lowerCAmelCase						=					False
	lowerCAmelCase						=					False
	lowerCAmelCase						=					False
	lowerCAmelCase						=					False




	def 				_UpperCamelCase     (			self   )			->       Optional[int]:
								snake_case_           =				TFCvtModelTester(self   )
								snake_case_           =				TFCvtConfigTester(self			,     config_class=a			,     has_text_modality=a			,     hidden_size=37   )




	def 				_UpperCamelCase     (			self   )			->       Optional[int]:
								self.config_tester.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()




	@unittest.skip(reason='Cvt does not output attentions'   )
	def 				_UpperCamelCase     (			self   )			->       Dict:
								pass




	@unittest.skip(reason='Cvt does not use inputs_embeds'   )
	def 				_UpperCamelCase     (			self   )			->       List[str]:
								pass




	@unittest.skip(reason='Cvt does not support input and output embeddings'   )
	def 				_UpperCamelCase     (			self   )			->       Optional[int]:
								pass




	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('GPU'   )   ) == 0			,     reason='TF does not support backprop for grouped convolutions on CPU.'			,     )
	def 				_UpperCamelCase     (			self   )			->       Dict:
								super().test_dataset_conversion()




	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('GPU'   )   ) == 0			,     reason='TF does not support backprop for grouped convolutions on CPU.'			,     )
	@slow
	def 				_UpperCamelCase     (			self   )			->       Dict:
								super().test_keras_fit()




	@unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'   )
	def 				_UpperCamelCase     (			self   )			->       List[str]:
								snake_case_           =				tf.keras.mixed_precision.Policy('mixed_float16'   )
								tf.keras.mixed_precision.set_global_policy(a   )
								super().test_keras_fit()
								tf.keras.mixed_precision.set_global_policy('float32'   )




	def 				_UpperCamelCase     (			self   )			->       Optional[int]:
								snake_case_     ,						snake_case_           =				self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															snake_case_           =				model_class(a   )
															snake_case_           =				inspect.signature(model.call   )
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															snake_case_           =				[*signature.parameters.keys()]

															snake_case_           =				['pixel_values']
															self.assertListEqual(arg_names[:1]			,     a   )




	def 				_UpperCamelCase     (			self   )			->       Optional[Any]:
								def check_hidden_states_output(a			,     a			,     a   ):
															snake_case_           =				model_class(a   )

															snake_case_           =				model(**self._prepare_for_class(a			,     a   )   )
															snake_case_           =				outputs.hidden_states

															snake_case_           =				len(self.model_tester.depth   )
															self.assertEqual(len(a   )			,     a   )

															# verify the first hidden states (first block)
															self.assertListEqual(
															    list(hidden_states[0].shape[-3:]   )			,     [
															        self.model_tester.embed_dim[0],
															        self.model_tester.image_size // 4,
															        self.model_tester.image_size // 4,
															    ]			,     )

								snake_case_     ,						snake_case_           =				self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															snake_case_           =				True
															check_hidden_states_output(a			,     a			,     a   )

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															snake_case_           =				True

															check_hidden_states_output(a			,     a			,     a   )




	def 				_UpperCamelCase     (			self   )			->       List[Any]:
								snake_case_           =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a   )




	def 				_UpperCamelCase     (			self   )			->       List[str]:
								snake_case_           =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*a   )






	@slow
	def 				_UpperCamelCase     (			self   )			->       int:
								for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															snake_case_           =				TFCvtModel.from_pretrained(a   )
															self.assertIsNotNone(a   )






def 		__UpperCAmelCase     (	):
							snake_case_           =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
							return image




@require_tf
@require_vision
class 					UpperCamelCase_ (     unittest.TestCase							):



	'''simple docstring'''




	@cached_property
	def 				_UpperCamelCase     (			self   )			->       Any:
								return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )






	@slow
	def 				_UpperCamelCase     (			self   )			->       Dict:
								snake_case_           =				TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

								snake_case_           =				self.default_image_processor
								snake_case_           =				prepare_img()
								snake_case_           =				image_processor(images=a			,     return_tensors='tf'   )

								# forward pass
								snake_case_           =				model(**a   )

								# verify the logits
								snake_case_           =				tf.TensorShape((1, 10_00)   )
								self.assertEqual(outputs.logits.shape			,     a   )

								snake_case_           =				tf.constant([0.9_285, 0.9_015, -0.3_150]   )
								self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()			,     a			,     atol=1E-4   )   )





