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


__SCREAMING_SNAKE_CASE			:	Optional[int]	=    Mapping[str, np.ndarray]
__SCREAMING_SNAKE_CASE			:	str	=    Mapping[str, Any]  # Is a nested dict.
__SCREAMING_SNAKE_CASE			:	List[Any]	=    0.0_1

@dataclasses.dataclass(frozen=lowercase_       )
class       lowerCamelCase_      :
      '''simple docstring'''

      __UpperCamelCase:    List[str]         =		4_2  # [num_res, num_atom_type, 3]

      # Amino-acid type for each residue represented as an integer between 0 and
      # 20, where 20 is 'X'.
      __UpperCamelCase:    Dict         =		4_2  # [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.
      __UpperCamelCase:    List[str]         =		4_2  # [num_res, num_atom_type]

      # Residue index as used in PDB. It is not necessarily continuous or 0-indexed.
      __UpperCamelCase:    Union[str, Any]         =		4_2  # [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.
      __UpperCamelCase:    Dict         =		4_2  # [num_res, num_atom_type]

      # Chain indices for multi-chain predictions
      __UpperCamelCase:    int         =		None

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

      # Templates used to generate this protein (prediction-only)
      __UpperCamelCase:    Optional[int]         =		None

      # Chain corresponding to each parent
      __UpperCamelCase:    Dict         =		None

def       UpperCamelCase_				(   _UpperCAmelCase    : Optional[Any]       )       ->       List[str]:


       """simple docstring"""







       _UpperCAmelCase	:    str				 =       R"""(\[[A-Z]+\]\n)"""
       _UpperCAmelCase	:    List[str]				 =       [tag.strip() for tag in re.split(lowerCamelCase_     ,      lowerCamelCase_       ) if len(lowerCamelCase_       ) > 0]
       _UpperCAmelCase	:    Iterator[Tuple[str, List[str]]]				 =       zip(tags[0::2]     ,      [l.split("\n"       ) for l in tags[1::2]]       )

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


       """simple docstring"""







       _UpperCAmelCase	:    List[str]				 =       []

       _UpperCAmelCase	:    Optional[int]				 =       prot.remark
       if remark is not None:
              pdb_headers.append(F"""REMARK {remark}"""       )

       _UpperCAmelCase	:    Optional[int]				 =       prot.parents
       _UpperCAmelCase	:    Tuple				 =       prot.parents_chain_index
       if parents is not None and parents_chain_index is not None:
              _UpperCAmelCase	:    Union[str, Any]				 =       [p for i, p in zip(lowerCamelCase_     ,      lowerCamelCase_       ) if i == chain_id]

       if parents is None or len(lowerCamelCase_       ) == 0:
              _UpperCAmelCase	:    Any				 =       ["""N/A"""]

       pdb_headers.append(F"""PARENT {' '.join(lowerCamelCase_       )}"""       )

       return pdb_headers

def       UpperCamelCase_				(   _UpperCAmelCase    : Optional[Any]     ,      _UpperCAmelCase    : List[str]       )       ->       int:


       """simple docstring"""







       _UpperCAmelCase	:    List[str]				 =       []
       _UpperCAmelCase	:    Union[str, Any]				 =       pdb_str.split("\n"       )

       _UpperCAmelCase	:    Union[str, Any]				 =       prot.remark
       if remark is not None:
              out_pdb_lines.append(F"""REMARK {remark}"""       )

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

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

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

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

       _UpperCAmelCase	:    Any				 =       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_       ):
                            _UpperCAmelCase	:    List[str]				 =       parents_per_chain[chain_counter]
                     else:
                            _UpperCAmelCase	:    Any				 =       ["""N/A"""]

                     out_pdb_lines.append(make_parent_line(lowerCamelCase_       )       )

       return "\n".join(lowerCamelCase_       )

def       UpperCamelCase_				(   _UpperCAmelCase    : Any       )       ->       str:


       """simple docstring"""







       _UpperCAmelCase	:    List[str]				 =       residue_constants.restypes + ["""X"""]

       def res_atoa(_UpperCAmelCase    : Tuple       ) -> str:
              return residue_constants.restype_atoa.get(restypes[r]     ,      "UNK"       )

       _UpperCAmelCase	:    str				 =       residue_constants.atom_types

       _UpperCAmelCase	:    List[str]				 =       []

       _UpperCAmelCase	:    Dict				 =       prot.atom_mask
       _UpperCAmelCase	:    Dict				 =       prot.aatype
       _UpperCAmelCase	:    Any				 =       prot.atom_positions
       _UpperCAmelCase	:    str				 =       prot.residue_index.astype(np.intaa       )
       _UpperCAmelCase	:    Union[str, Any]				 =       prot.b_factors
       _UpperCAmelCase	:    List[Any]				 =       prot.chain_index

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

       _UpperCAmelCase	:    Optional[Any]				 =       get_pdb_headers(lowerCamelCase_       )
       if len(lowerCamelCase_       ) > 0:
              pdb_lines.extend(lowerCamelCase_       )

       _UpperCAmelCase	:    Optional[int]				 =       aatype.shape[0]
       _UpperCAmelCase	:    List[str]				 =       1
       _UpperCAmelCase	:    Any				 =       0
       _UpperCAmelCase	:    List[Any]				 =       string.ascii_uppercase
       _UpperCAmelCase	:    Any				 =       None
       # Add all atom sites.
       for i in range(lowerCamelCase_       ):
              _UpperCAmelCase	:    Optional[Any]				 =       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

                     _UpperCAmelCase	:    Tuple				 =       """ATOM"""
                     _UpperCAmelCase	:    str				 =       atom_name if len(lowerCamelCase_       ) == 4 else F""" {atom_name}"""
                     _UpperCAmelCase	:    List[Any]				 =       """"""
                     _UpperCAmelCase	:    List[Any]				 =       """"""
                     _UpperCAmelCase	:    Tuple				 =       1.0_0
                     _UpperCAmelCase	:    Any				 =       atom_name[0]  # Protein supports only C, N, O, S, this works.
                     _UpperCAmelCase	:    Tuple				 =       """"""

                     _UpperCAmelCase	:    Union[str, Any]				 =       """A"""
                     if chain_index is not None:
                            _UpperCAmelCase	:    Union[str, Any]				 =       chain_tags[chain_index[i]]

                     # PDB is a columnar format, every space matters here!
                     _UpperCAmelCase	:    Optional[int]				 =       (
                         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

              _UpperCAmelCase	:    Union[str, Any]				 =       i == n - 1
              if chain_index is not None:
                     if i != n - 1 and chain_index[i + 1] != prev_chain_index:
                            _UpperCAmelCase	:    Optional[int]				 =       True
                            _UpperCAmelCase	:    List[Any]				 =       chain_index[i + 1]

              if should_terminate:
                     # Close the chain.
                     _UpperCAmelCase	:    List[Any]				 =       """TER"""
                     _UpperCAmelCase	:    Tuple				 =       (
                         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       UpperCamelCase_				(   _UpperCAmelCase    : Any       )       ->       Union[str, Any]:


       """simple docstring"""







       return residue_constants.STANDARD_ATOM_MASK[prot.aatype]


def       UpperCamelCase_				(   _UpperCAmelCase    : List[Any]     ,      _UpperCAmelCase    : Tuple     ,      _UpperCAmelCase    : Dict = None     ,      _UpperCAmelCase    : Optional[Any] = None     ,      _UpperCAmelCase    : Optional[int] = None     ,      _UpperCAmelCase    : int = None     ,      _UpperCAmelCase    : List[str] = None     ,      )       ->       Optional[Any]:


       """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=lowerCamelCase_     ,      remark=lowerCamelCase_     ,      parents=lowerCamelCase_     ,      parents_chain_index=lowerCamelCase_     ,      )








'''simple docstring'''




__UpperCAmelCase            =       """0.18.2"""

from .configuration_utils import ConfigMixin
from .utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_onnx_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    logging,
)


try:
							if not is_onnx_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_onnx_objects import *  # noqa F403
else:
							from .pipelines import OnnxRuntimeModel

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_pt_objects import *  # noqa F403
else:
							from .models import (
							    AutoencoderKL,
							    ControlNetModel,
							    ModelMixin,
							    PriorTransformer,
							    TaFilmDecoder,
							    TransformeraDModel,
							    UNetaDModel,
							    UNetaDConditionModel,
							    UNetaDModel,
							    UNetaDConditionModel,
							    VQModel,
							)
							from .optimization import (
							    get_constant_schedule,
							    get_constant_schedule_with_warmup,
							    get_cosine_schedule_with_warmup,
							    get_cosine_with_hard_restarts_schedule_with_warmup,
							    get_linear_schedule_with_warmup,
							    get_polynomial_decay_schedule_with_warmup,
							    get_scheduler,
							)
							from .pipelines import (
							    AudioPipelineOutput,
							    ConsistencyModelPipeline,
							    DanceDiffusionPipeline,
							    DDIMPipeline,
							    DDPMPipeline,
							    DiffusionPipeline,
							    DiTPipeline,
							    ImagePipelineOutput,
							    KarrasVePipeline,
							    LDMPipeline,
							    LDMSuperResolutionPipeline,
							    PNDMPipeline,
							    RePaintPipeline,
							    ScoreSdeVePipeline,
							)
							from .schedulers import (
							    CMStochasticIterativeScheduler,
							    DDIMInverseScheduler,
							    DDIMParallelScheduler,
							    DDIMScheduler,
							    DDPMParallelScheduler,
							    DDPMScheduler,
							    DEISMultistepScheduler,
							    DPMSolverMultistepInverseScheduler,
							    DPMSolverMultistepScheduler,
							    DPMSolverSinglestepScheduler,
							    EulerAncestralDiscreteScheduler,
							    EulerDiscreteScheduler,
							    HeunDiscreteScheduler,
							    IPNDMScheduler,
							    KarrasVeScheduler,
							    KDPMaAncestralDiscreteScheduler,
							    KDPMaDiscreteScheduler,
							    PNDMScheduler,
							    RePaintScheduler,
							    SchedulerMixin,
							    ScoreSdeVeScheduler,
							    UnCLIPScheduler,
							    UniPCMultistepScheduler,
							    VQDiffusionScheduler,
							)
							from .training_utils import EMAModel

try:
							if not (is_torch_available() and is_scipy_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
							from .schedulers import LMSDiscreteScheduler

try:
							if not (is_torch_available() and is_torchsde_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
							from .schedulers import DPMSolverSDEScheduler

try:
							if not (is_torch_available() and is_transformers_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
							from .pipelines import (
							    AltDiffusionImgaImgPipeline,
							    AltDiffusionPipeline,
							    AudioLDMPipeline,
							    CycleDiffusionPipeline,
							    IFImgaImgPipeline,
							    IFImgaImgSuperResolutionPipeline,
							    IFInpaintingPipeline,
							    IFInpaintingSuperResolutionPipeline,
							    IFPipeline,
							    IFSuperResolutionPipeline,
							    ImageTextPipelineOutput,
							    KandinskyImgaImgPipeline,
							    KandinskyInpaintPipeline,
							    KandinskyPipeline,
							    KandinskyPriorPipeline,
							    KandinskyVaaControlnetImgaImgPipeline,
							    KandinskyVaaControlnetPipeline,
							    KandinskyVaaImgaImgPipeline,
							    KandinskyVaaInpaintPipeline,
							    KandinskyVaaPipeline,
							    KandinskyVaaPriorEmbaEmbPipeline,
							    KandinskyVaaPriorPipeline,
							    LDMTextToImagePipeline,
							    PaintByExamplePipeline,
							    SemanticStableDiffusionPipeline,
							    ShapEImgaImgPipeline,
							    ShapEPipeline,
							    StableDiffusionAttendAndExcitePipeline,
							    StableDiffusionControlNetImgaImgPipeline,
							    StableDiffusionControlNetInpaintPipeline,
							    StableDiffusionControlNetPipeline,
							    StableDiffusionDepthaImgPipeline,
							    StableDiffusionDiffEditPipeline,
							    StableDiffusionImageVariationPipeline,
							    StableDiffusionImgaImgPipeline,
							    StableDiffusionInpaintPipeline,
							    StableDiffusionInpaintPipelineLegacy,
							    StableDiffusionInstructPixaPixPipeline,
							    StableDiffusionLatentUpscalePipeline,
							    StableDiffusionLDMaDPipeline,
							    StableDiffusionModelEditingPipeline,
							    StableDiffusionPanoramaPipeline,
							    StableDiffusionParadigmsPipeline,
							    StableDiffusionPipeline,
							    StableDiffusionPipelineSafe,
							    StableDiffusionPixaPixZeroPipeline,
							    StableDiffusionSAGPipeline,
							    StableDiffusionUpscalePipeline,
							    StableUnCLIPImgaImgPipeline,
							    StableUnCLIPPipeline,
							    TextToVideoSDPipeline,
							    TextToVideoZeroPipeline,
							    UnCLIPImageVariationPipeline,
							    UnCLIPPipeline,
							    UniDiffuserModel,
							    UniDiffuserPipeline,
							    UniDiffuserTextDecoder,
							    VersatileDiffusionDualGuidedPipeline,
							    VersatileDiffusionImageVariationPipeline,
							    VersatileDiffusionPipeline,
							    VersatileDiffusionTextToImagePipeline,
							    VideoToVideoSDPipeline,
							    VQDiffusionPipeline,
							)

try:
							if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import *  # noqa F403
else:
							from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline

try:
							if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
							from .pipelines import StableDiffusionKDiffusionPipeline

try:
							if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_torch_and_transformers_and_onnx_objects import *  # noqa F403
else:
							from .pipelines import (
							    OnnxStableDiffusionImgaImgPipeline,
							    OnnxStableDiffusionInpaintPipeline,
							    OnnxStableDiffusionInpaintPipelineLegacy,
							    OnnxStableDiffusionPipeline,
							    OnnxStableDiffusionUpscalePipeline,
							    StableDiffusionOnnxPipeline,
							)

try:
							if not (is_torch_available() and is_librosa_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_torch_and_librosa_objects import *  # noqa F403
else:
							from .pipelines import AudioDiffusionPipeline, Mel

try:
							if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_transformers_and_torch_and_note_seq_objects import *  # noqa F403
else:
							from .pipelines import SpectrogramDiffusionPipeline

try:
							if not is_flax_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_flax_objects import *  # noqa F403
else:
							from .models.controlnet_flax import FlaxControlNetModel
							from .models.modeling_flax_utils import FlaxModelMixin
							from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel
							from .models.vae_flax import FlaxAutoencoderKL
							from .pipelines import FlaxDiffusionPipeline
							from .schedulers import (
							    FlaxDDIMScheduler,
							    FlaxDDPMScheduler,
							    FlaxDPMSolverMultistepScheduler,
							    FlaxKarrasVeScheduler,
							    FlaxLMSDiscreteScheduler,
							    FlaxPNDMScheduler,
							    FlaxSchedulerMixin,
							    FlaxScoreSdeVeScheduler,
							)


try:
							if not (is_flax_available() and is_transformers_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_flax_and_transformers_objects import *  # noqa F403
else:
							from .pipelines import (
							    FlaxStableDiffusionControlNetPipeline,
							    FlaxStableDiffusionImgaImgPipeline,
							    FlaxStableDiffusionInpaintPipeline,
							    FlaxStableDiffusionPipeline,
							)

try:
							if not (is_note_seq_available()):
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							from .utils.dummy_note_seq_objects import *  # noqa F403
else:
							from .pipelines import MidiProcessor



