






from __future__ import annotations

import os
import tempfile
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import is_tensorflow_text_available, is_tf_available
from transformers.testing_utils import require_tensorflow_text, require_tf, slow

from ..test_modeling_tf_common import floats_tensor
from .test_framework_agnostic import GenerationIntegrationTestsMixin


if is_tf_available():
							import tensorflow as tf

							from transformers import (
							    AutoTokenizer,
							    TFAutoModelForCausalLM,
							    TFAutoModelForSeqaSeqLM,
							    TFAutoModelForSpeechSeqaSeq,
							    TFAutoModelForVisionaSeq,
							    TFBartForConditionalGeneration,
							    TFLogitsProcessorList,
							    TFMinLengthLogitsProcessor,
							    tf_top_k_top_p_filtering,
							)

if is_tensorflow_text_available():
							import tensorflow_text as text




@require_tf
class 				__A     (			unittest.TestCase ):





				"""simple docstring"""







				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Optional[int]       		=tf.convert_to_tensor(
									    [
									        [
									            8.2_220_991,  # 3rd highest value; idx. 0
									            -0.5_620_044,
									            5.23_229_752,
									            4.0_386_393,
									            -6.8_798_378,
									            -0.54_785_802,
									            -3.2_012_153,
									            2.92_777_176,
									            1.88_171_953,
									            7.35_341_276,  # 5th highest value; idx. 9
									            8.43_207_833,  # 2nd highest value; idx. 10
									            -9.85_711_836,
									            -5.96_209_236,
									            -1.13_039_161,
									            -7.1_115_294,
									            -0.8_369_633,
									            -5.3_186_408,
									            7.06_427_407,
									            0.81_369_344,
									            -0.82_023_817,
									            -5.9_179_796,
									            0.58_813_443,
									            -6.99_778_438,
									            4.71_551_189,
									            -0.18_771_637,
									            7.44_020_759,  # 4th highest value; idx. 25
									            9.38_450_987,  # 1st highest value; idx. 26
									            2.12_662_941,
									            -9.32_562_038,
									            2.35_652_522,
									        ],  # cummulative prob of 5 highest values <= 0.6
									        [
									            0.58_425_518,
									            4.53_139_238,
									            -5.57_510_464,
									            -6.28_030_699,
									            -7.19_529_503,
									            -4.02_122_551,
									            1.39_337_037,
									            -6.06_707_057,
									            1.59_480_517,
									            -9.643_119,
									            0.03_907_799,
									            0.67_231_762,
									            -8.88_206_726,
									            6.27_115_922,  # 4th highest value; idx. 13
									            2.28_520_723,
									            4.82_767_506,
									            4.30_421_368,
									            8.8_275_313,  # 2nd highest value; idx. 17
									            5.44_029_958,  # 5th highest value; idx. 18
									            -4.4_735_794,
									            7.38_579_536,  # 3rd highest value; idx. 20
									            -2.91_051_663,
									            2.61_946_077,
									            -2.5_674_762,
									            -9.48_959_302,
									            -4.02_922_645,
									            -1.35_416_918,
									            9.67_702_323,  # 1st highest value; idx. 27
									            -5.89_478_553,
									            1.85_370_467,
									        ],  # cummulative prob of 5 highest values <= 0.6
									    ]							,  dtype=tf.floataa							,  )

									__UpperCamelCase      :					List[str]       		=tf.convert_to_tensor(
									    [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]]							,  dtype=tf.intaa							,  )  # expected non filtered idx as noted above

									__UpperCamelCase      :					List[Any]       		=tf.convert_to_tensor(
									    [8.222_099, 7.3_534_126, 8.432_078, 7.4_402_075, 9.38_451, 6.271_159, 8.827_531, 5.4_402_995, 7.3_857_956, 9.677_023]							,  dtype=tf.floataa							,  )  # expected non filtered values as noted above

									__UpperCamelCase      :					List[str]       		=tf_top_k_top_p_filtering(lowerCamelCase__							,  top_k=10							,  top_p=0.6							,  min_tokens_to_keep=4    )

									__UpperCamelCase      :					List[str]       		=output[output != -float('inf'    )]
									__UpperCamelCase      :					Optional[Any]       		=tf.cast(
									    tf.where(tf.not_equal(lowerCamelCase__							,  tf.constant(-float('inf'    )							,  dtype=tf.floataa    )    )    )							,  dtype=tf.intaa							,  )

									tf.debugging.assert_near(lowerCamelCase__							,  lowerCamelCase__							,  rtol=1E-12    )
									tf.debugging.assert_equal(lowerCamelCase__							,  lowerCamelCase__    )




@require_tf
class 				__A     (			unittest.TestCase      ,     lowercase_ ):





				"""simple docstring"""







				if is_tf_available():
								UpperCamelCase__ :      Optional[int]			 ={
								    """AutoModelForCausalLM""": TFAutoModelForCausalLM,
								    """AutoModelForSpeechSeq2Seq""": TFAutoModelForSpeechSeqaSeq,
								    """AutoModelForSeq2SeqLM""": TFAutoModelForSeqaSeqLM,
								    """AutoModelForVision2Seq""": TFAutoModelForVisionaSeq,
								    """LogitsProcessorList""": TFLogitsProcessorList,
								    """MinLengthLogitsProcessor""": TFMinLengthLogitsProcessor,
								    """create_tensor_fn""": tf.convert_to_tensor,
								    """floats_tensor""": floats_tensor,
								    """return_tensors""": """tf""",
								}


				@slow
				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Optional[int]       		=TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'    )
									__UpperCamelCase      :					List[Any]       		=2
									__UpperCamelCase      :					int       		=2




									class 				__A     (			tf.Module ):





													"""simple docstring"""







													def __init__( self							,  lowerCamelCase__    ):




																		"""simple docstring"""

																		super(lowerCamelCase__							,  self    ).__init__()
																		__UpperCamelCase      :					Any       		=model







													@tf.function(
													    input_signature=(
													        tf.TensorSpec((None, input_length)							,  tf.intaa							,  name='input_ids'    ),
													        tf.TensorSpec((None, input_length)							,  tf.intaa							,  name='attention_mask'    ),
													    )							,  jit_compile=lowerCamelCase__							,  )
													def       __lowercase							( self							,  lowerCamelCase__							,  lowerCamelCase__    ):




																		"""simple docstring"""

																		__UpperCamelCase      :					Optional[int]       		=self.model.generate(
																		    input_ids=lowerCamelCase__							,  attention_mask=lowerCamelCase__							,  max_new_tokens=lowerCamelCase__							,  return_dict_in_generate=lowerCamelCase__							,  )
																		return {"sequences": outputs["sequences"]}
									__UpperCamelCase      :					str       		=[[2, 0], [102, 103]]
									__UpperCamelCase      :					Optional[Any]       		=[[1, 0], [1, 1]]
									__UpperCamelCase      :					str       		=DummyModel(model=lowerCamelCase__    )
									with tempfile.TemporaryDirectory() as tmp_dir:
														tf.saved_model.save(lowerCamelCase__							,  lowerCamelCase__							,  signatures={'serving_default': dummy_model.serving}    )
														__UpperCamelCase      :					Optional[int]       		=tf.saved_model.load(lowerCamelCase__    ).signatures['serving_default']
														for batch_size in range(1							,  len(lowerCamelCase__    ) + 1    ):
																			__UpperCamelCase      :					str       		={
																			    'input_ids': tf.constant(dummy_input_ids[:batch_size]    ),
																			    'attention_mask': tf.constant(dummy_attention_masks[:batch_size]    ),
																			}
																			__UpperCamelCase      :					Optional[Any]       		=serving_func(**lowerCamelCase__    )['sequences']
																			__UpperCamelCase      :					List[Any]       		=test_model.generate(**lowerCamelCase__							,  max_new_tokens=lowerCamelCase__    )
																			tf.debugging.assert_equal(lowerCamelCase__							,  lowerCamelCase__    )


				@slow
				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					List[Any]       		=TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'    )
									__UpperCamelCase      :					List[str]       		=1
									__UpperCamelCase      :					Tuple       		=2




									class 				__A     (			tf.Module ):





													"""simple docstring"""







													def __init__( self							,  lowerCamelCase__    ):




																		"""simple docstring"""

																		super(lowerCamelCase__							,  self    ).__init__()
																		__UpperCamelCase      :					Any       		=model







													@tf.function(
													    input_signature=(
													        tf.TensorSpec((batch_size, None)							,  tf.intaa							,  name='input_ids'    ),
													        tf.TensorSpec((batch_size, None)							,  tf.intaa							,  name='attention_mask'    ),
													    )							,  jit_compile=lowerCamelCase__							,  )
													def       __lowercase							( self							,  lowerCamelCase__							,  lowerCamelCase__    ):




																		"""simple docstring"""

																		__UpperCamelCase      :					Optional[int]       		=self.model.generate(
																		    input_ids=lowerCamelCase__							,  attention_mask=lowerCamelCase__							,  max_new_tokens=lowerCamelCase__							,  return_dict_in_generate=lowerCamelCase__							,  )
																		return {"sequences": outputs["sequences"]}
									__UpperCamelCase      :					Tuple       		=[[2], [102, 103]]
									__UpperCamelCase      :					int       		=[[1], [1, 1]]
									__UpperCamelCase      :					Dict       		=DummyModel(model=lowerCamelCase__    )
									with tempfile.TemporaryDirectory() as tmp_dir:
														tf.saved_model.save(lowerCamelCase__							,  lowerCamelCase__							,  signatures={'serving_default': dummy_model.serving}    )
														__UpperCamelCase      :					List[str]       		=tf.saved_model.load(lowerCamelCase__    ).signatures['serving_default']
														for input_row in range(len(lowerCamelCase__    )    ):
																			__UpperCamelCase      :					List[Any]       		={
																			    'input_ids': tf.constant([dummy_input_ids[input_row]]    ),
																			    'attention_mask': tf.constant([dummy_attention_masks[input_row]]    ),
																			}
																			__UpperCamelCase      :					List[Any]       		=serving_func(**lowerCamelCase__    )['sequences']
																			__UpperCamelCase      :					List[Any]       		=test_model.generate(**lowerCamelCase__							,  max_new_tokens=lowerCamelCase__    )
																			tf.debugging.assert_equal(lowerCamelCase__							,  lowerCamelCase__    )


				@slow
				@require_tensorflow_text
				def       __lowercase							( self    ):




									"""simple docstring"""

									with tempfile.TemporaryDirectory() as tmp_dir:
														# file needed to load the TF tokenizer
														hf_hub_download(repo_id='google/flan-t5-small'							,  filename='spiece.model'							,  local_dir=lowerCamelCase__    )




														class 				__A     (			tf.keras.layers.Layer ):





																		"""simple docstring"""







																		def __init__( self    ):




																							"""simple docstring"""

																							super().__init__()
																							__UpperCamelCase      :					List[Any]       		=text.SentencepieceTokenizer(
																							    model=tf.io.gfile.GFile(os.path.join(lowerCamelCase__							,  'spiece.model'    )							,  'rb'    ).read()    )
																							__UpperCamelCase      :					Dict       		=TFAutoModelForSeqaSeqLM.from_pretrained('hf-internal-testing/tiny-random-t5'    )







																		def       __lowercase							( self							,  lowerCamelCase__							,  *lowerCamelCase__							,  **lowerCamelCase__    ):




																							"""simple docstring"""

																							__UpperCamelCase      :					List[str]       		=self.tokenizer.tokenize(lowerCamelCase__    )
																							__UpperCamelCase		,				__UpperCamelCase      :					Dict       		=text.pad_model_inputs(
																							    lowerCamelCase__							,  max_seq_length=64							,  pad_value=self.model.config.pad_token_id    )
																							__UpperCamelCase      :					List[Any]       		=self.model.generate(input_ids=lowerCamelCase__							,  attention_mask=lowerCamelCase__    )
																							return self.tokenizer.detokenize(lowerCamelCase__    )
														__UpperCamelCase      :					Union[str, Any]       		=CompleteSentenceTransformer()
														__UpperCamelCase      :					List[Any]       		=tf.keras.layers.Input(shape=(1,)							,  dtype=tf.string							,  name='inputs'    )
														__UpperCamelCase      :					List[str]       		=complete_model(lowerCamelCase__    )
														__UpperCamelCase      :					int       		=tf.keras.Model(lowerCamelCase__							,  lowerCamelCase__    )
														keras_model.save(lowerCamelCase__    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Tuple       		={
									    'do_sample': True,
									    'num_beams': 1,
									    'top_p': 0.7,
									    'top_k': 10,
									    'temperature': 0.7,
									}
									__UpperCamelCase      :					Optional[int]       		=14

									__UpperCamelCase      :					Optional[Any]       		=AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'    )
									__UpperCamelCase      :					Tuple       		='Hello, my dog is cute and'
									__UpperCamelCase      :					str       		=tokenizer(lowerCamelCase__							,  return_tensors='tf'    )
									__UpperCamelCase      :					str       		=TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'    )

									__UpperCamelCase      :					Union[str, Any]       		=638
									# forces the generation to happen on CPU, to avoid GPU-related quirks
									with tf.device(':/CPU:0'    ):
														tf.random.set_seed(0    )
														__UpperCamelCase      :					Tuple       		=model.generate(**lowerCamelCase__							,  eos_token_id=lowerCamelCase__							,  **lowerCamelCase__    )
									self.assertTrue(expectation == len(generated_tokens[0]    )    )

									__UpperCamelCase      :					Union[str, Any]       		=[638, 198]
									with tf.device(':/CPU:0'    ):
														tf.random.set_seed(0    )
														__UpperCamelCase      :					Optional[int]       		=model.generate(**lowerCamelCase__							,  eos_token_id=lowerCamelCase__							,  **lowerCamelCase__    )
									self.assertTrue(expectation == len(generated_tokens[0]    )    )







				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					str       		=AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-bart'    )
									__UpperCamelCase      :					Union[str, Any]       		='Hugging Face is a technology company based in New York and Paris.'
									__UpperCamelCase      :					List[Any]       		=bart_tokenizer(lowerCamelCase__							,  return_tensors='tf'    ).input_ids
									__UpperCamelCase      :					Dict       		=TFBartForConditionalGeneration.from_pretrained('hf-internal-testing/tiny-random-bart'    )
									__UpperCamelCase      :					Optional[int]       		=bart_model.generate(lowerCamelCase__    ).numpy()




									class 				__A     (			lowercase_ ):





													"""simple docstring"""







													def       __lowercase							( self							,  lowerCamelCase__							,  lowerCamelCase__=None							,  **lowerCamelCase__    ):




																		"""simple docstring"""

																		return super().call(lowerCamelCase__							,  **lowerCamelCase__    )
									__UpperCamelCase      :					Optional[Any]       		=FakeBart.from_pretrained('hf-internal-testing/tiny-random-bart'    )
									__UpperCamelCase      :					Dict       		=bart_model.generate(lowerCamelCase__							,  foo='bar'    ).numpy()
									self.assertTrue(np.array_equal(lowerCamelCase__							,  lowerCamelCase__    )    )




									class 				__A     (			bart_model.model.encoder.__class__ ):





													"""simple docstring"""







													def       __lowercase							( self							,  lowerCamelCase__							,  **lowerCamelCase__    ):




																		"""simple docstring"""

																		return super().call(lowerCamelCase__							,  **lowerCamelCase__    )
									__UpperCamelCase      :					Optional[Any]       		=FakeEncoder(bart_model.config							,  bart_model.model.shared    )
									__UpperCamelCase      :					List[Any]       		=fake_encoder

									# Normal generation still works (the output will be different because the encoder weights are different)
									__UpperCamelCase      :					Union[str, Any]       		=bart_model.generate(lowerCamelCase__    ).numpy()
									with self.assertRaises(lowerCamelCase__    ):
														# FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo"
														bart_model.generate(lowerCamelCase__							,  foo='bar'    )





'''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


lowerCamelCase							:   str  						=	Mapping[str, np.ndarray]
lowerCamelCase							:   List[Any]  						=	Mapping[str, Any]  # Is a nested dict.
lowerCamelCase							:   Any  						=	0.0_1
@dataclasses.dataclass(frozen=lowercase_     )
class   __lowerCAmelCase						:





      '''simple docstring'''






      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 _SCREAMING_SNAKE_CASE      (A       )       ->       Protein:






       """simple docstring"""







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

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






       """simple docstring"""







       lowercase__      			= []

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

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

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

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

       return pdb_headers

def _SCREAMING_SNAKE_CASE      (A  , A       )       ->       str:






       """simple docstring"""







       lowercase__      			= []
       lowercase__      			= pdb_str.split('''\n'''       )

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

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

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

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

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

       lowercase__      			= 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       ):
                            lowercase__      			= parents_per_chain[chain_counter]
                     else:
                            lowercase__      			= ['''N/A''']

                     out_pdb_lines.append(make_parent_line(A       )       )

       return "\n".join(A       )

def _SCREAMING_SNAKE_CASE      (A       )       ->       str:






       """simple docstring"""







       lowercase__      			= residue_constants.restypes + ['''X''']

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

       lowercase__      			= residue_constants.atom_types

       lowercase__      			= []

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

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

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

       lowercase__      			= aatype.shape[0]
       lowercase__      			= 1
       lowercase__      			= 0
       lowercase__      			= string.ascii_uppercase
       lowercase__      			= None
       # Add all atom sites.
       for i in range(A       ):
              lowercase__      			= 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

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

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

                     # PDB is a columnar format, every space matters here!
                     lowercase__      			= (
                         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

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

              if should_terminate:
                     # Close the chain.
                     lowercase__      			= '''TER'''
                     lowercase__      			= (
                         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 _SCREAMING_SNAKE_CASE      (A       )       ->       np.ndarray:






       """simple docstring"""







       return residue_constants.STANDARD_ATOM_MASK[prot.aatype]

def _SCREAMING_SNAKE_CASE      (A  , A  , A = None  , A = None  , A = None  , A = None  , A = None  , )       ->       Protein:






       """simple docstring"""







       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  , )




