



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


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






@dataclasses.dataclass(frozen=A		)
class __A    :



 '''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 lowerCAmelCase						(__A):



     """simple docstring"""



     _a											=						r'''(\[[A-Z]+\]\n)'''
     _a											=						[tag.strip() for tag in re.split(__A						,			__A) if len(__A) > 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(__A)):
                    if seq[i] not in residue_constants.restypes:
                         _a											=						'''X'''  # FIXME: strings are immutable
               _a											=						np.array(
                   [residue_constants.restype_order.get(__A						,			residue_constants.restype_num) for res_symbol in seq])
          elif "[TERTIARY]" == g[0]:
               _a											=						[]
               for axis in range(3):
                    tertiary.append(list(map(__A						,			g[1][axis].split())))
               _a											=						np.array(__A)
               _a											=						np.zeros((len(tertiary[0]) // 3, residue_constants.atom_type_num, 3)).astype(np.floataa)
               for i, atom in enumerate(__A):
                    _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(__A),
                       residue_constants.atom_type_num,
                   )).astype(np.floataa)
               for i, atom in enumerate(__A):
                    _a											=						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 lowerCAmelCase						(__A						,			__A = 0):



     """simple docstring"""



     _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(__A						,			__A) if i == chain_id]

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

     pdb_headers.append(F'''PARENT {' '.join(__A)}''')

     return pdb_headers




def lowerCAmelCase						(__A						,			__A):



     """simple docstring"""



     _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(__A)						,			[])
                    parent_dict[str(__A)].append(__A)

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

     def make_parent_line(__A) -> str:
          return F'''PARENT {' '.join(__A)}'''

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

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

               out_pdb_lines.append(make_parent_line(__A))

     return "\n".join(__A)




def lowerCAmelCase						(__A):



     """simple docstring"""



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

     def res_atoa(__A) -> 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(__A)
     if len(__A) > 0:
          pdb_lines.extend(__A)

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

               _a											=						'''ATOM'''
               _a											=						atom_name if len(__A) == 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(__A)
               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(__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 lowerCAmelCase						(__A):



     """simple docstring"""



     return residue_constants.STANDARD_ATOM_MASK[prot.aatype]




def lowerCAmelCase						(__A						,			__A						,			__A = None						,			__A = None						,			__A = None						,			__A = None						,			__A = None						,			):



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








'''simple docstring'''





import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


lowercase_	 =						"\\n@INPROCEEDINGS{Papineni02bleu:a,\n    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n    booktitle = {},\n    year = {2002},\n    pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n    author = \"Lin, Chin-Yew  and\n      Och, Franz Josef\",\n    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n    month = \"aug 23{--}aug 27\",\n    year = \"2004\",\n    address = \"Geneva, Switzerland\",\n    publisher = \"COLING\",\n    url = \"https://www.aclweb.org/anthology/C04-1072\",\n    pages = \"501--507\",\n}\n"

lowercase_	 =						"\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n"

lowercase_	 =						"\nComputes BLEU score of translated segments against one or more references.\nArgs:\n    predictions: list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    max_order: Maximum n-gram order to use when computing BLEU score.\n    smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n    'bleu': bleu score,\n    'precisions': geometric mean of n-gram precisions,\n    'brevity_penalty': brevity penalty,\n    'length_ratio': ratio of lengths,\n    'translation_length': translation_length,\n    'reference_length': reference_length\nExamples:\n\n    >>> predictions = [\n    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample\n    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample\n    ... ]\n    >>> references = [\n    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)\n    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)\n    ... ]\n    >>> bleu = datasets.load_metric(\"bleu\")\n    >>> results = bleu.compute(predictions=predictions, references=references)\n    >>> print(results[\"bleu\"])\n    1.0\n"






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,     _KWARGS_DESCRIPTION		)
class __A    (						datasets.Metric		):



 '''simple docstring'''







 def       a__						(self )					->  Union[str, Any]:


      """simple docstring"""



      return datasets.MetricInfo(
          description=_DESCRIPTION				,     citation=_CITATION				,     inputs_description=_KWARGS_DESCRIPTION				,     features=datasets.Features(
              {
                  '''predictions''': datasets.Sequence(datasets.Value('''string'''				,     id='''token''' )				,     id='''sequence''' ),
                  '''references''': datasets.Sequence(
                      datasets.Sequence(datasets.Value('''string'''				,     id='''token''' )				,     id='''sequence''' )				,     id='''references''' ),
              } )				,     codebase_urls=['''https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py''']				,     reference_urls=[
              '''https://en.wikipedia.org/wiki/BLEU''',
              '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''',
          ]				,     )



 def       a__						(self				,     A				,     A				,     A=4				,     A=False )					->  Tuple:


      """simple docstring"""



      _a											=						compute_bleu(
          reference_corpus=A				,     translation_corpus=A				,     max_order=A				,     smooth=A )
      ((_a)						,					(_a)						,					(_a)						,					(_a)						,					(_a)						,					(_a))											=						score
      return {
          "bleu": bleu,
          "precisions": precisions,
          "brevity_penalty": bp,
          "length_ratio": ratio,
          "translation_length": translation_length,
          "reference_length": reference_length,
      }



