




'''simple docstring'''
from typing import Dict, Tuple, overload

import torch
import torch.types
from torch import nn

from . import residue_constants as rc
from .rigid_utils import Rigid, Rotation
from .tensor_utils import batched_gather
@overload
def 							snake_case_    (  a__						:      torch.Tensor       ,a__						:      torch.Tensor       ,a__						:      None     ):



    """simple docstring"""




    ...
@overload
def 							snake_case_    (  a__						:      torch.Tensor       ,a__						:      torch.Tensor       ,a__						:      torch.Tensor     ):



    """simple docstring"""




    ...
def 							snake_case_    (  a__						:      Any       ,a__						:      Dict       ,a__						:      List[str]     ):



    """simple docstring"""




    __lowercase     							=		aatype == rc.restype_order["""G"""]
    __lowercase     							=		rc.atom_order["""CA"""]
    __lowercase     							=		rc.atom_order["""CB"""]
    __lowercase     							=		torch.where(
        is_gly[..., None].expand(*((-1,) * len(is_gly.shape     ))       ,3     )       ,all_atom_positions[..., ca_idx, :]       ,all_atom_positions[..., cb_idx, :]       ,)

    if all_atom_masks is not None:
        __lowercase     							=		torch.where(
            a__       ,all_atom_masks[..., ca_idx]       ,all_atom_masks[..., cb_idx]       ,)
        return pseudo_beta, pseudo_beta_mask
    else:
        return pseudo_beta
def 							snake_case_    (  a__						:      torch.Tensor       ,a__						:      Dict[str, torch.Tensor]     ):



    """simple docstring"""




    __lowercase     							=		batched_gather(
        a__       ,batch["""residx_atom37_to_atom14"""]       ,dim=-2       ,no_batch_dims=len(atomaa.shape[:-2]     )       ,)

    __lowercase     							=		atomaa_data * batch["""atom37_atom_exists"""][..., None]

    return atomaa_data
def 							snake_case_    (  a__						:      Dict[str, torch.Tensor]     ):



    """simple docstring"""




    __lowercase     							=		template_feats["""template_aatype"""]
    __lowercase     							=		template_feats["""template_torsion_angles_sin_cos"""]
    __lowercase     							=		template_feats["""template_alt_torsion_angles_sin_cos"""]
    __lowercase     							=		template_feats["""template_torsion_angles_mask"""]
    __lowercase     							=		torch.cat(
        [
            nn.functional.one_hot(a__       ,22     ),
            torsion_angles_sin_cos.reshape(*torsion_angles_sin_cos.shape[:-2]       ,14     ),
            alt_torsion_angles_sin_cos.reshape(*alt_torsion_angles_sin_cos.shape[:-2]       ,14     ),
            torsion_angles_mask,
        ]       ,dim=-1       ,)

    return template_angle_feat
def 							snake_case_    (  a__						:      Dict[str, torch.Tensor]       ,a__						:      torch.types.Number       ,a__						:      torch.types.Number       ,a__						:      int       ,a__						:      bool = False       ,a__						:      float = 1e-20       ,a__						:      float = 1e8       ,):



    """simple docstring"""




    __lowercase     							=		batch["""template_pseudo_beta_mask"""]
    __lowercase     							=		template_mask[..., None] * template_mask[..., None, :]

    # Compute distogram (this seems to differ slightly from Alg. 5)
    __lowercase     							=		batch["""template_pseudo_beta"""]
    __lowercase     							=		torch.sum((tpb[..., None, :] - tpb[..., None, :, :]) ** 2       ,dim=-1       ,keepdim=a__     )
    __lowercase     							=		torch.linspace(a__       ,a__       ,a__       ,device=tpb.device     ) ** 2
    __lowercase     							=		torch.cat([lower[1:], lower.new_tensor([inf]     )]       ,dim=-1     )
    __lowercase     							=		((dgram > lower) * (dgram < upper)).type(dgram.dtype     )

    __lowercase     							=		[dgram, template_mask_ad[..., None]]

    __lowercase     							=		nn.functional.one_hot(
        batch["""template_aatype"""]       ,rc.restype_num + 2       ,)

    __lowercase     							=		batch["""template_aatype"""].shape[-1]
    to_concat.append(aatype_one_hot[..., None, :, :].expand(*aatype_one_hot.shape[:-2]       ,a__       ,-1       ,-1     )     )
    to_concat.append(aatype_one_hot[..., None, :].expand(*aatype_one_hot.shape[:-2]       ,-1       ,a__       ,-1     )     )

    __lowercase							,__lowercase							,__lowercase     							=		[rc.atom_order[a] for a in ["""N""", """CA""", """C"""]]
    __lowercase     							=		Rigid.make_transform_from_reference(
        n_xyz=batch["""template_all_atom_positions"""][..., n, :]       ,ca_xyz=batch["""template_all_atom_positions"""][..., ca, :]       ,c_xyz=batch["""template_all_atom_positions"""][..., c, :]       ,eps=a__       ,)
    __lowercase     							=		rigids.get_trans()[..., None, :, :]
    __lowercase     							=		rigids[..., None].invert_apply(a__     )

    __lowercase     							=		torch.rsqrt(eps + torch.sum(rigid_vec**2       ,dim=-1     )     )

    __lowercase     							=		batch["""template_all_atom_mask"""]
    __lowercase     							=		t_aa_masks[..., n] * t_aa_masks[..., ca] * t_aa_masks[..., c]
    __lowercase     							=		template_mask[..., None] * template_mask[..., None, :]

    __lowercase     							=		inv_distance_scalar * template_mask_ad
    __lowercase     							=		rigid_vec * inv_distance_scalar[..., None]

    if not use_unit_vector:
        __lowercase     							=		unit_vector * 0.0

    to_concat.extend(torch.unbind(unit_vector[..., None, :]       ,dim=-1     )     )
    to_concat.append(template_mask_ad[..., None]     )

    __lowercase     							=		torch.cat(a__       ,dim=-1     )
    __lowercase     							=		act * template_mask_ad[..., None]

    return act
def 							snake_case_    (  a__						:      Dict[str, torch.Tensor]     ):



    """simple docstring"""




    __lowercase     							=		nn.functional.one_hot(batch["""extra_msa"""]       ,23     )
    __lowercase     							=		[
        msa_ahot,
        batch["""extra_has_deletion"""].unsqueeze(-1     ),
        batch["""extra_deletion_value"""].unsqueeze(-1     ),
    ]
    return torch.cat(a__       ,dim=-1     )
def 							snake_case_    (  a__						:      Rigid       ,a__						:      torch.Tensor       ,a__						:      torch.Tensor       ,a__						:      torch.Tensor       ,):



    """simple docstring"""




    __lowercase     							=		rrgdf[aatype, ...]

    # [*, N, 8] transformations, i.e.
    #   One [*, N, 8, 3, 3] rotation matrix and
    #   One [*, N, 8, 3]    translation matrix
    __lowercase     							=		r.from_tensor_axa(a__     )

    __lowercase     							=		alpha.new_zeros((*((1,) * len(alpha.shape[:-1]     )), 2)     )
    __lowercase     							=		1

    # [*, N, 8, 2]
    __lowercase     							=		torch.cat([bb_rot.expand(*alpha.shape[:-2]       ,-1       ,-1     ), alpha]       ,dim=-2     )

    # [*, N, 8, 3, 3]
    # Produces rotation matrices of the form:
    # [
    #   [1, 0  , 0  ],
    #   [0, a_2,-a_1],
    #   [0, a_1, a_2]
    # ]
    # This follows the original code rather than the supplement, which uses
    # different indices.

    __lowercase     							=		alpha.new_zeros(default_r.get_rots().get_rot_mats().shape     )
    __lowercase     							=		1
    __lowercase     							=		alpha[..., 1]
    __lowercase     							=		-alpha[..., 0]
    __lowercase     							=		alpha

    __lowercase     							=		default_r.compose(Rigid(Rotation(rot_mats=a__     )       ,a__     )     )

    __lowercase     							=		all_frames[..., 5]
    __lowercase     							=		all_frames[..., 6]
    __lowercase     							=		all_frames[..., 7]

    __lowercase     							=		all_frames[..., 4]
    __lowercase     							=		chia_frame_to_bb.compose(a__     )
    __lowercase     							=		chia_frame_to_bb.compose(a__     )
    __lowercase     							=		chia_frame_to_bb.compose(a__     )

    __lowercase     							=		Rigid.cat(
        [
            all_frames[..., :5],
            chia_frame_to_bb.unsqueeze(-1     ),
            chia_frame_to_bb.unsqueeze(-1     ),
            chia_frame_to_bb.unsqueeze(-1     ),
        ]       ,dim=-1       ,)

    __lowercase     							=		r[..., None].compose(a__     )

    return all_frames_to_global



def 							snake_case_    (  a__						:      Rigid       ,a__						:      torch.Tensor       ,a__						:      torch.Tensor       ,a__						:      torch.Tensor       ,a__						:      torch.Tensor       ,a__						:      torch.Tensor       ,):



    """simple docstring"""




    __lowercase     							=		group_idx[aatype, ...]

    # [*, N, 14, 8]
    __lowercase     							=		nn.functional.one_hot(
        a__       ,num_classes=default_frames.shape[-3]       ,)

    # [*, N, 14, 8]
    __lowercase     							=		r[..., None, :] * group_mask_one_hot

    # [*, N, 14]
    __lowercase     							=		t_atoms_to_global.map_tensor_fn(lambda a__     : torch.sum(a__       ,dim=-1     )     )

    # [*, N, 14, 1]
    __lowercase     							=		atom_mask[aatype, ...].unsqueeze(-1     )

    # [*, N, 14, 3]
    __lowercase     							=		lit_positions[aatype, ...]
    __lowercase     							=		t_atoms_to_global.apply(a__     )
    __lowercase     							=		pred_positions * atom_mask

    return pred_positions










'''simple docstring'''
import numpy as np
def 							snake_case_    (  a__						:      Tuple     ):



    """simple docstring"""




    __lowercase							,__lowercase     							=		a.shape
    __lowercase     							=		min(a__       ,a__     )
    __lowercase     							=		np.eye(a__     )
    __lowercase     							=		a.copy()

    for k in range(t - 1     ):
        # select a column of modified matrix A':
        __lowercase     							=		r[k:, [k]]
        # construct first basis vector
        __lowercase     							=		np.zeros_like(a__     )
        __lowercase     							=		1.0
        # determine scaling factor
        __lowercase     							=		np.linalg.norm(a__     )
        # construct vector v for Householder reflection
        __lowercase     							=		x + np.sign(x[0]     ) * alpha * ea
        v /= np.linalg.norm(a__     )

        # construct the Householder matrix
        __lowercase     							=		np.eye(m - k     ) - 2.0 * v @ v.T
        # pad with ones and zeros as necessary
        __lowercase     							=		np.block([[np.eye(a__     ), np.zeros((k, m - k)     )], [np.zeros((m - k, k)     ), q_k]]     )

        __lowercase     							=		q @ q_k.T
        __lowercase     							=		q_k @ r

    return q, r


if __name__ == "__main__":
  import doctest

  doctest.testmod()




