id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
141,961
import os import fire import langroid as lr from langroid.utils.configuration import settings import langroid.language_models as lm DEFAULT_LLM = lm.OpenAIChatModel.GPT4_TURBO settings = Settings() def app( m: str = DEFAULT_LLM, # model name d: bool = False, # debug nc: bool = False, # no cache ): ...
null
141,962
import typer from rich import print from rich.prompt import Prompt from dotenv import load_dotenv import tempfile from langroid.agent.openai_assistant import ( OpenAIAssistant, OpenAIAssistantConfig, AssistantTool, ToolType, ) from langroid.parsing.url_loader import URLLoader from langroid.agent.task im...
null
141,963
import typer from rich import print from rich.prompt import Prompt from dotenv import load_dotenv from langroid.agent.openai_assistant import OpenAIAssistant, OpenAIAssistantConfig from langroid.agent.task import Task from langroid.language_models.openai_gpt import OpenAIGPTConfig, OpenAIChatModel from langroid.utils.l...
null
141,964
import os import fire import pandas as pd import langroid as lr import langroid.language_models as lm from langroid.utils.configuration import settings PATH = "examples/summarize/data/hf-cnn-daily-news/news10.csv" settings = Settings() def app( m: str = "", # ollama/mistral:7b-instruct-v0.2-q8_0", d: bool = ...
null
141,965
import os import fire import pandas as pd import langroid as lr import langroid.language_models as lm from langroid.utils.configuration import settings PATH = "examples/summarize/data/news.csv" settings = Settings() def app( m: str = "", # ollama/mistral:7b-instruct-v0.2-q8_0", d: bool = False, # debug ): ...
null
141,966
from rich import print from rich.prompt import Prompt import urllib.parse from langroid.parsing.utils import closest_string import logging The provided code snippet includes necessary dependencies for implementing the `fix_uri` function. Write a Python function `def fix_uri(uri: str) -> str` to solve the following pro...
Fixes a URI by percent-encoding the username and password.
141,967
from rich import print from rich.prompt import Prompt import urllib.parse from langroid.parsing.utils import closest_string import logging DEFAULT_PORTS = dict( postgresql=5432, mysql=3306, mariadb=3306, mssql=1433, oracle=1521, mongodb=27017, redis=6379, ) def _create_database_uri( sche...
Main function to gather input and print the database URI.
141,968
import typer from rich import print from rich.prompt import Prompt from typing import Dict, Any import json import os from sqlalchemy import create_engine, inspect from sqlalchemy.engine import Engine from prettytable import PrettyTable from utils import get_database_uri, fix_uri from langroid.agent.special.sql.sql_cha...
Ask the user for a path to a JSON file and load context descriptions from it. Returns: dict: The context descriptions, or an empty dictionary if the user decides to skip this step.
141,969
import subprocess import os import sys import importlib.util import shlex import platform import json def check_python_version(): is_windows = platform.system() == "Windows" major = sys.version_info.major minor = sys.version_info.minor micro = sys.version_info.micro if is_windows: supporte...
null
141,970
import subprocess import os import sys import importlib.util import shlex import platform import json dir_repos = "repositories" script_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) if 'GRADIO_ANALYTICS_ENABLED' not in os.environ: os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False' def repo_dir(...
null
141,971
import subprocess import os import sys import importlib.util import shlex import platform import json python = sys.executable def run(command, desc=None, errdesc=None, custom_env=None, live=False): if desc is not None: print(desc) if live: result = subprocess.run(command, shell=True, env=os.envi...
null
141,972
import subprocess import os import sys import importlib.util import shlex import platform import json python = sys.executable def check_run(command): result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return result.returncode == 0 def check_run_python(code): return...
null
141,973
import subprocess import os import sys import importlib.util import shlex import platform import json git = os.environ.get('GIT', "git") if 'GRADIO_ANALYTICS_ENABLED' not in os.environ: os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False' def run(command, desc=None, errdesc=None, custom_env=None, live=False): if de...
null
141,974
import subprocess import os import sys import importlib.util import shlex import platform import json git = os.environ.get('GIT', "git") if 'GRADIO_ANALYTICS_ENABLED' not in os.environ: os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False' def git_pull_recursive(dir): for subdir, _, _ in os.walk(dir): if os...
null
141,975
import subprocess import os import sys import importlib.util import shlex import platform import json python = sys.executable if 'GRADIO_ANALYTICS_ENABLED' not in os.environ: os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False' def run(command, desc=None, errdesc=None, custom_env=None, live=False): if desc is not N...
null
141,976
import subprocess import os import sys import importlib.util import shlex import platform import json python = sys.executable skip_install = False if 'GRADIO_ANALYTICS_ENABLED' not in os.environ: os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False' def commit_hash(): def run(command, desc=None, errdesc=None, custom_env...
null
141,977
import subprocess import os import sys import importlib.util import shlex import platform import json def sadtalker_demo(checkpoint_path='checkpoints', config_path='src/config', warpfn=None): sad_talker = SadTalker(checkpoint_path, config_path, lazy_load=True) with gr.Blocks(analytics_enabled=False) as sadta...
null
141,978
import os import cv2 import time import glob import argparse import numpy as np from PIL import Image import torch from tqdm import tqdm from itertools import cycle from torch.multiprocessing import Pool, Process, set_start_method from facexlib.alignment import landmark_98_to_68 from facexlib.detection import init_dete...
null
141,979
import os import cv2 import time import glob import argparse import numpy as np from PIL import Image import torch from tqdm import tqdm from itertools import cycle from torch.multiprocessing import Pool, Process, set_start_method from facexlib.alignment import landmark_98_to_68 from facexlib.detection import init_dete...
null
141,980
import cv2 import numpy as np from src.face3d.models.bfm import ParametricFaceModel from src.face3d.models.facerecon_model import FaceReconModel import torch import subprocess, platform import scipy.io as scio from tqdm import tqdm class FaceReconModel(BaseModel): def modify_commandline_options(parser, is_train=F...
null
141,999
import torch from torch import nn class IBasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1): super(IBasicBlock, self).__init__() if groups != 1 or base_width != 64: raise ValueErro...
null
142,000
import torch from torch import nn class IBasicBlock(nn.Module): def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1): def forward(self, x): def _iresnet(arch, block, layers, pretrained, progress, **kwargs): def iresnet34(pretrained=False, p...
null
142,001
import torch from torch import nn class IBasicBlock(nn.Module): def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1): def forward(self, x): def _iresnet(arch, block, layers, pretrained, progress, **kwargs): def iresnet50(pretrained=False, p...
null
142,015
import torch from torch import nn class CosFace(nn.Module): def __init__(self, s=64.0, m=0.40): def forward(self, cosine, label): class ArcFace(nn.Module): def __init__(self, s=64.0, m=0.5): def forward(self, cosine: torch.Tensor, label): def get_loss(name): if name == "cosface": return...
null
142,020
import os import pickle import matplotlib import pandas as pd import matplotlib.pyplot as plt import timeit import sklearn import argparse import cv2 import numpy as np import torch from skimage import transform as trans from backbones import get_model from sklearn.metrics import roc_curve, auc from menpo.visualize.vie...
null
142,029
import datetime import os import pickle import mxnet as mx import numpy as np import sklearn import torch from mxnet import ndarray as nd from scipy import interpolate from sklearn.decomposition import PCA from sklearn.model_selection import KFold def calculate_roc(thresholds, embeddings1, ...
null
142,064
import numpy as np from PIL import Image from scipy.io import loadmat, savemat from array import array import os.path as osp def LoadExpBasis(bfm_folder='BFM'): n_vertex = 53215 Expbin = open(osp.join(bfm_folder, 'Exp_Pca.bin'), 'rb') exp_dim = array('i') exp_dim.fromfile(Expbin, 1) expMU = array('f...
null
142,071
import os import numpy as np from PIL import Image from skimage import io, img_as_float32, transform import torch import scipy.io as scio def transform_semantic_1(semantic, semantic_radius): semantic_list = [semantic for i in range(0, semantic_radius*2+1)] coeff_3dmm = np.concatenate(semantic_list, 0) retu...
null
142,076
from scipy.spatial import ConvexHull import torch import torch.nn.functional as F import numpy as np from tqdm import tqdm def keypoint_transformation(kp_canonical, he, wo_exp=False): kp = kp_canonical['value'] # (bs, k, 3) yaw, pitch, roll= he['yaw'], he['pitch'], he['roll'] yaw = headpose_pred_...
null
142,080
import torch, uuid import os, sys, shutil from src.utils.preprocess import CropAndExtract from src.test_audio2coeff import Audio2Coeff from src.facerender.animate import AnimateFromCoeff from src.generate_batch import get_data from src.generate_facerender_batch import get_facerender_data from src.utils.init_path impo...
null
142,082
import os from tqdm import tqdm import torch import numpy as np import random import scipy.io as scio import src.utils.audio as audio def crop_pad_audio(wav, audio_length): def parse_audio_length(audio_length, sr, fps): def generate_blink_seq_randomly(num_frames): def get_data(first_coeff_path, audio_path, device, ref...
null
142,083
import cv2, os import numpy as np from tqdm import tqdm import uuid from src.utils.videoio import save_video_with_watermark def save_video_with_watermark(video, audio, save_path, watermark=False): temp_file = str(uuid.uuid4())+'.mp4' cmd = r'ffmpeg -y -hide_banner -loglevel error -i "%s" -i "%s" -vcodec copy "...
null
142,084
import numpy as np import cv2, os, sys, torch from tqdm import tqdm from PIL import Image import safetensors import safetensors.torch from src.face3d.util.preprocess import align_img from src.face3d.util.load_mats import load_lm3d from src.face3d.models import networks from scipy.io import loadmat, savemat from src.u...
Return: coeffs_dict -- a dict of torch.tensors Parameters: coeffs -- torch.tensor, size (B, 256)
142,088
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def preemphasis(wav, k, preemphasize=True): def _stft(y): def _amp_to_db(x): def _normalize(S): def linearspectrogram(wav): D = _stft(preemphasis(wav, hp.preemp...
null
142,093
import os import torch from gfpgan import GFPGANer from tqdm import tqdm from src.utils.videoio import load_video_to_cv2 import cv2 def enhancer_generator_no_len(images, method='gfpgan', bg_upsampler='realesrgan'): """ Provide a generator function so that all of the enhanced images don't need to be stored in m...
null
142,094
import os import torch from gfpgan import GFPGANer from tqdm import tqdm from src.utils.videoio import load_video_to_cv2 import cv2 class GeneratorWithLen(object): """ From https://stackoverflow.com/a/7460929 """ def __init__(self, gen, length): self.gen = gen self.length = length def __len...
Provide a generator with a __len__ method so that it can passed to functions that call len()
142,095
def load_x_from_safetensor(checkpoint, key): x_generator = {} for k,v in checkpoint.items(): if key in k: x_generator[k.replace(key+'.', '')] = v return x_generator
null
142,097
import torch import yaml import os import safetensors from safetensors.torch import save_file from yacs.config import CfgNode as CN import sys from src.face3d.models import networks from src.facerender.modules.keypoint_detector import HEEstimator, KPDetector from src.facerender.modules.mapping import MappingNet from sr...
null
142,098
import torch import yaml import os import safetensors from safetensors.torch import save_file from yacs.config import CfgNode as CN import sys from src.face3d.models import networks from src.facerender.modules.keypoint_detector import HEEstimator, KPDetector from src.facerender.modules.mapping import MappingNet from sr...
null
142,099
import os, sys import gradio as gr from src.gradio_demo import SadTalker def toggle_audio_file(choice): if choice == False: return gr.update(visible=True), gr.update(visible=False) else: return gr.update(visible=False), gr.update(visible=True)
null
142,100
import os, sys import gradio as gr from src.gradio_demo import SadTalker def ref_video_fn(path_of_ref_video): if path_of_ref_video is not None: return gr.update(value=True) else: return gr.update(value=False)
null
142,101
import os import shutil from argparse import Namespace from src.utils.preprocess import CropAndExtract from src.test_audio2coeff import Audio2Coeff from src.facerender.animate import AnimateFromCoeff from src.generate_batch import get_data from src.generate_facerender_batch import get_facerender_data from src.utils.ini...
null
142,102
import os, sys from pathlib import Path import tempfile import gradio as gr from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call from modules.shared import opts, OptionInfo from modules import shared, paths, script_callbacks import launch import glob from huggingface_hub import snapshot_download def d...
null
142,103
import os, sys from pathlib import Path import tempfile import gradio as gr from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call from modules.shared import opts, OptionInfo from modules import shared, paths, script_callbacks import launch import glob from huggingface_hub import snapshot_download def g...
null
142,104
import os, sys from pathlib import Path import tempfile import gradio as gr from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call from modules.shared import opts, OptionInfo from modules import shared, paths, script_callbacks import launch import glob from huggingface_hub import snapshot_download def g...
null
142,105
import os, sys from pathlib import Path import tempfile import gradio as gr from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call from modules.shared import opts, OptionInfo from modules import shared, paths, script_callbacks import launch import glob from huggingface_hub import snapshot_download def g...
null
142,106
import os, sys from pathlib import Path import tempfile import gradio as gr from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call from modules.shared import opts, OptionInfo from modules import shared, paths, script_callbacks import launch import glob from huggingface_hub import snapshot_download def in...
null
142,107
import os, sys from pathlib import Path import tempfile import gradio as gr from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call from modules.shared import opts, OptionInfo from modules import shared, paths, script_callbacks import launch import glob from huggingface_hub import snapshot_download def o...
null
142,108
import os import pathlib import signal from typing import Tuple from absl import app from absl import flags from absl import logging import docker from docker import types _ROOT_MOUNT_DIRECTORY = '/mnt/' The provided code snippet includes necessary dependencies for implementing the `_create_mount` function. Write a Py...
Create a mount point for each file and directory used by the model.
142,109
import enum import json import os import pathlib import pickle import random import shutil import sys import time from typing import Any, Dict, Union from absl import app from absl import flags from absl import logging from alphafold.common import confidence from alphafold.common import protein from alphafold.common im...
null
142,110
import enum import json import os import pathlib import pickle import random import shutil import sys import time from typing import Any, Dict, Union from absl import app from absl import flags from absl import logging from alphafold.common import confidence from alphafold.common import protein from alphafold.common im...
Predicts structure using AlphaFold for the given sequence.
142,111
import io import time from typing import Collection, Optional, Sequence from absl import logging from alphafold.common import protein from alphafold.common import residue_constants from alphafold.model import folding from alphafold.relax import cleanup from alphafold.relax import utils import ml_collections import nump...
Run iterative amber relax. Successive relax iterations are performed until all violations have been resolved. Each iteration involves a restrained Amber minimization, with restraint exclusions determined by violation-participating residues. Args: prot: A protein to be relaxed. stiffness: kcal/mol A**2, the restraint st...
142,112
import io from alphafold.common import residue_constants from Bio import PDB import numpy as np The provided code snippet includes necessary dependencies for implementing the `overwrite_b_factors` function. Write a Python function `def overwrite_b_factors(pdb_str: str, bfactors: np.ndarray) -> str` to solve the follow...
Overwrites the B-factors in pdb_str with contents of bfactors array. Args: pdb_str: An input PDB string. bfactors: A numpy array with shape [1, n_residues, 37]. We assume that the B-factors are per residue; i.e. that the nonzero entries are identical in [0, i, :]. Returns: A new PDB string with the B-factors replaced.
142,113
import collections import contextlib import copy import dataclasses import json import os import tempfile from typing import Mapping, MutableMapping, Sequence from absl import logging from alphafold.common import protein from alphafold.common import residue_constants from alphafold.data import feature_processing from a...
Makes a mapping from PDB-format chain ID to sequence and description.
142,114
import collections import contextlib import copy import dataclasses import json import os import tempfile from typing import Mapping, MutableMapping, Sequence from absl import logging from alphafold.common import protein from alphafold.common import residue_constants from alphafold.data import feature_processing from a...
null
142,115
import collections import contextlib import copy import dataclasses import json import os import tempfile from typing import Mapping, MutableMapping, Sequence from absl import logging from alphafold.common import protein from alphafold.common import residue_constants from alphafold.data import feature_processing from a...
Reshapes and modifies monomer features for multimer models.
142,116
import collections import contextlib import copy import dataclasses import json import os import tempfile from typing import Mapping, MutableMapping, Sequence from absl import logging from alphafold.common import protein from alphafold.common import residue_constants from alphafold.data import feature_processing from a...
Add features to distinguish between chains. Args: all_chain_features: A dictionary which maps chain_id to a dictionary of features for each chain. Returns: all_chain_features: A dictionary which maps strings of the form `<seq_id>_<sym_id>` to the corresponding chain features. E.g. two chains from a homodimer would have...
142,117
import collections import contextlib import copy import dataclasses import json import os import tempfile from typing import Mapping, MutableMapping, Sequence from absl import logging from alphafold.common import protein from alphafold.common import residue_constants from alphafold.data import feature_processing from a...
null
142,118
import collections import dataclasses import itertools import re import string from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Set def _convert_sto_seq_to_a3m( query_non_gaps: Sequence[bool], sto_seq: str) -> Iterable[str]: for is_query_res_non_gap, sequence_res in zip(query_non_gaps, sto_seq)...
Converts MSA in Stockholm format to the A3M format.
142,121
import collections import dataclasses import itertools import re import string from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Set class TemplateHit: """Class representing a template hit.""" index: int name: str aligned_cols: int sum_probs: Optional[float] query: str hit_sequence: str ...
Parses the content of an entire HHR file.
142,122
import collections import dataclasses import itertools import re import string from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Set class TemplateHit: """Class representing a template hit.""" index: int name: str aligned_cols: int sum_probs: Optional[float] query: str hit_sequence: str ...
Parses an a3m string produced by hmmsearch. Args: query_sequence: The query sequence. a3m_string: The a3m string produced by hmmsearch. skip_first: Whether to skip the first sequence in the a3m string. Returns: A sequence of `TemplateHit` results.
142,123
import abc import dataclasses import datetime import functools import glob import os import re from typing import Any, Dict, Mapping, Optional, Sequence, Tuple from absl import logging from alphafold.common import residue_constants from alphafold.data import mmcif_parsing from alphafold.data import parsers from alphafo...
Parses the data file from PDB that lists which pdb_ids are obsolete.
142,124
import abc import dataclasses import datetime import functools import glob import os import re from typing import Any, Dict, Mapping, Optional, Sequence, Tuple from absl import logging from alphafold.common import residue_constants from alphafold.data import mmcif_parsing from alphafold.data import parsers from alphafo...
Parses release dates file, returns a mapping from PDBs to release dates.
142,125
import abc import dataclasses import datetime import functools import glob import os import re from typing import Any, Dict, Mapping, Optional, Sequence, Tuple from absl import logging from alphafold.common import residue_constants from alphafold.data import mmcif_parsing from alphafold.data import parsers from alphafo...
Tries to extract template features from a single HHSearch hit.
142,126
import os from typing import Any, Mapping, MutableMapping, Optional, Sequence, Union from absl import logging from alphafold.common import residue_constants from alphafold.data import msa_identifiers from alphafold.data import parsers from alphafold.data import templates from alphafold.data.tools import hhblits from al...
Constructs a feature dict of sequence features.
142,127
import os from typing import Any, Mapping, MutableMapping, Optional, Sequence, Union from absl import logging from alphafold.common import residue_constants from alphafold.data import msa_identifiers from alphafold.data import parsers from alphafold.data import templates from alphafold.data.tools import hhblits from al...
Constructs a feature dict of MSA features.
142,128
import os from typing import Any, Mapping, MutableMapping, Optional, Sequence, Union from absl import logging from alphafold.common import residue_constants from alphafold.data import msa_identifiers from alphafold.data import parsers from alphafold.data import templates from alphafold.data.tools import hhblits from al...
Runs an MSA tool, checking if output already exists first.
142,129
from typing import Iterable, MutableMapping, List from alphafold.common import residue_constants from alphafold.data import msa_pairing from alphafold.data import pipeline import numpy as np MAX_TEMPLATES = 4 MSA_CROP_SIZE = 2048 def _is_homomer_or_monomer(chains: Iterable[pipeline.FeatureDict]) -> bool: """Checks if...
Runs processing on features to augment, pair and merge. Args: all_chain_features: A MutableMap of dictionaries of features for each chain. Returns: A dictionary of features.
142,130
import os import subprocess from typing import Sequence from absl import logging from alphafold.data.tools import utils The provided code snippet includes necessary dependencies for implementing the `_to_a3m` function. Write a Python function `def _to_a3m(sequences: Sequence[str]) -> str` to solve the following proble...
Converts sequences to an a3m file.
142,133
from typing import AbstractSet, Any, Mapping, Optional, Sequence from alphafold.common import residue_constants from alphafold.data import parsers from matplotlib import pyplot as plt import numpy as np def clean_and_validate_single_sequence( input_sequence: str, min_length: int, max_length: int) -> str: """Check...
Validates and cleans input sequences.
142,134
from typing import AbstractSet, Any, Mapping, Optional, Sequence from alphafold.common import residue_constants from alphafold.data import parsers from matplotlib import pyplot as plt import numpy as np The provided code snippet includes necessary dependencies for implementing the `merge_chunked_msa` function. Write a...
Merges chunked database hits together into hits for the full database.
142,135
from typing import AbstractSet, Any, Mapping, Optional, Sequence from alphafold.common import residue_constants from alphafold.data import parsers from matplotlib import pyplot as plt import numpy as np The provided code snippet includes necessary dependencies for implementing the `show_msa_info` function. Write a Pyt...
Prints info and shows a plot of the deduplicated single chain MSA.
142,136
from typing import AbstractSet, Any, Mapping, Optional, Sequence from alphafold.common import residue_constants from alphafold.data import parsers from matplotlib import pyplot as plt import numpy as np def empty_placeholder_template_features( num_templates: int, num_res: int) -> Mapping[str, np.ndarray]: return...
null
142,137
from typing import AbstractSet, Any, Mapping, Optional, Sequence from alphafold.common import residue_constants from alphafold.data import parsers from matplotlib import pyplot as plt import numpy as np The provided code snippet includes necessary dependencies for implementing the `check_cell_execution_order` function...
Check that the cell execution order is correct. Args: cells_ran: Set of cell numbers that have been executed. cell_number: The number of the cell that this check is called in. Raises: If <1:cell_number> cells haven't been executed, raise error.
142,138
import collections import dataclasses import functools import io from typing import Any, Dict, List, Mapping, Optional, Tuple from alphafold.common import mmcif_metadata from alphafold.common import residue_constants from Bio.PDB import MMCIFParser from Bio.PDB import PDBParser from Bio.PDB.mmcifio import MMCIFIO from ...
Takes a mmCIF string and constructs a `Protein` object. WARNING: All non-standard residue types will be converted into UNK. All non-standard atoms will be ignored. Args: mmcif_str: The contents of the mmCIF file chain_id: If chain_id is specified (e.g. A), then only that chain is parsed. Otherwise all chains are parsed...
142,139
import collections import functools import os from typing import Final, List, Mapping, Tuple import numpy as np import tree residue_atoms = { 'ALA': ['C', 'CA', 'CB', 'N', 'O'], 'ARG': ['C', 'CA', 'CB', 'CG', 'CD', 'CZ', 'N', 'NE', 'O', 'NH1', 'NH2'], 'ASP': ['C', 'CA', 'CB', 'CG', 'N', 'O', 'OD1', 'OD2'], ...
Returns [num_res_types, num_atom_types] mask array.
142,140
import collections import functools import os from typing import Final, List, Mapping, Tuple import numpy as np import tree chi_angles_atoms = { 'ALA': [], # Chi5 in arginine is always 0 +- 5 degrees, so ignore it. 'ARG': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD'], ['CB', 'CG', 'CD', 'NE...
Define chi-angle rigid groups via one-hot representations.
142,141
import collections import functools import os from typing import Final, List, Mapping, Tuple import numpy as np import tree chi_angles_atoms = { 'ALA': [], # Chi5 in arginine is always 0 +- 5 degrees, so ignore it. 'ARG': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD'], ['CB', 'CG', 'CD', 'NE...
Fill the arrays above.
142,142
import haiku as hk import jax def safe_dropout(*, tensor, safe_key, rate, is_deterministic, is_training): if is_training and rate != 0.0 and not is_deterministic: return hk.dropout(safe_key.get(), rate, tensor) else: return tensor
null
142,143
import haiku as hk import jax def _safe_key_flatten(safe_key): # Flatten transfers "ownership" to the tree return (safe_key._key,), safe_key._used # pylint: disable=protected-access
null
142,144
import haiku as hk import jax class SafeKey: """Safety wrapper for PRNG keys.""" def __init__(self, key): self._key = key self._used = False def _assert_not_used(self): if self._used: raise RuntimeError('Random key has been used previously.') def get(self): self._assert_not_used() self...
null
142,145
import collections import contextlib import functools import numbers from typing import Mapping import haiku as hk import jax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `stable_softmax` function. Write a Python function `def stable_softmax(...
Numerically stable softmax for (potential) bfloat 16.
142,146
import collections import contextlib import functools import numbers from typing import Mapping import haiku as hk import jax import jax.numpy as jnp import numpy as np def bfloat16_creator(next_creator, shape, dtype, init, context): """Creates float32 variables when bfloat16 is requested.""" if context.original_dt...
null
142,147
import collections import contextlib import functools import numbers from typing import Mapping import haiku as hk import jax import jax.numpy as jnp import numpy as np def final_init(config): if config.zero_init: return 'zeros' else: return 'linear'
null
142,148
import numbers from typing import Union, Sequence import haiku as hk import jax.numpy as jnp import numpy as np TRUNCATED_NORMAL_STDDEV_FACTOR = np.asarray(.87962566103423978, dtype=np.float32) The provided code snippet includes necessary dependencies for implementing the `g...
Get Initializer for weights and scale to multiply activations by.
142,149
import functools from typing import Tuple import jax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `rot_to_quat` function. Write a Python function `def rot_to_quat(rot, unstack_inputs=False)` to solve the following problem: Convert rotation ma...
Convert rotation matrix to quaternion. Note that this function calls self_adjoint_eig which is extremely expensive on the GPU. If at all possible, this function should run on the CPU. Args: rot: rotation matrix (see below for format). unstack_inputs: If true, rotation matrix should be shape (..., 3, 3) otherwise the ro...
142,150
import functools from typing import Tuple import jax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `rot_list_to_tensor` function. Write a Python function `def rot_list_to_tensor(rot_list)` to solve the following problem: Convert list of lists ...
Convert list of lists to rotation tensor.
142,151
import functools from typing import Tuple import jax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `vec_list_to_tensor` function. Write a Python function `def vec_list_to_tensor(vec_list)` to solve the following problem: Convert list to vector...
Convert list to vector tensor.
142,152
import functools from typing import Tuple import jax import jax.numpy as jnp import numpy as np QUAT_TO_ROT = np.zeros((4, 4, 3, 3), dtype=np.float32) QUAT_TO_ROT[0, 0] = [[ 1, 0, 0], [ 0, 1, 0], [ 0, 0, 1]] QUAT_TO_ROT[1, 1] = [[ 1, 0, 0], [ 0,-1, 0], [ 0, 0,-1]] QUAT_TO_ROT[2, 2] = [[-1, 0, 0], [ 0, 1, 0], [ 0, 0,-...
Convert a normalized quaternion to a rotation matrix.
142,153
import functools from typing import Tuple import jax import jax.numpy as jnp import numpy as np QUAT_MULTIPLY_BY_VEC = QUAT_MULTIPLY[:, 1:, :] The provided code snippet includes necessary dependencies for implementing the `quat_multiply_by_vec` function. Write a Python function `def quat_multiply_by_vec(quat, vec)` to...
Multiply a quaternion by a pure-vector quaternion.
142,154
import functools from typing import Tuple import jax import jax.numpy as jnp import numpy as np QUAT_MULTIPLY = np.zeros((4, 4, 4), dtype=np.float32) QUAT_MULTIPLY[:, :, 0] = [[ 1, 0, 0, 0], [ 0,-1, 0, 0], [ 0, 0,-1, 0], [ 0, 0, 0,-1]] QUAT_M...
Multiply a quaternion by another quaternion.
142,155
import functools from typing import Tuple import jax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `apply_inverse_rot_to_vec` function. Write a Python function `def apply_inverse_rot_to_vec(rot, vec)` to solve the following problem: Multiply t...
Multiply the inverse of a rotation matrix by a vector.
142,156
import functools from typing import Tuple import jax import jax.numpy as jnp import numpy as np def make_canonical_transform( n_xyz: jnp.ndarray, ca_xyz: jnp.ndarray, c_xyz: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]: """Returns translation and rotation matrices to canonicalize residue atoms. Note ...
Returns rotation and translation matrices to convert from reference. Note that this method does not take care of symmetries. If you provide the atom positions in the non-standard way, the N atom will end up not at [-0.527250, 1.359329, 0.0] but instead at [-0.527250, -1.359329, 0.0]. You need to take care of such cases...
142,157
import collections import contextlib import functools import inspect from typing import Any, Callable, Optional, Tuple, Union import haiku as hk import jax import jax.numpy as jnp def nullcontext(): yield def maybe_with_rng(key): if key is not None: return hk.with_rng(key) else: return nullcontext()
null
142,158
import collections import contextlib import functools import inspect from typing import Any, Callable, Optional, Tuple, Union import haiku as hk import jax import jax.numpy as jnp def maybe_fold_in(key, data): if key is not None: return jax.random.fold_in(key, data) else: return None
null
142,159
import collections import contextlib import functools import inspect from typing import Any, Callable, Optional, Tuple, Union import haiku as hk import jax import jax.numpy as jnp def _check_no_varargs(f): if list(inspect.signature( f).parameters.values())[0].kind == inspect.Parameter.VAR_POSITIONAL: raise ...
Utility to wrap a Haiku function and recursively apply it to an input. A function is valid if it uses only explicit position parameters, and its return type matches its input type. The position parameters can be arbitrarily nested structures with `jnp.ndarray` at the leaf nodes. Note that kwargs are not supported, neit...
142,160
import io import os from alphafold.model import utils import haiku as hk import numpy as np The provided code snippet includes necessary dependencies for implementing the `get_model_haiku_params` function. Write a Python function `def get_model_haiku_params(model_name: str, data_dir: str) -> hk.Params` to solve the fo...
Get the Haiku parameters from a model name.
142,161
import tensorflow.compat.v1 as tf The provided code snippet includes necessary dependencies for implementing the `tf_combine_mask` function. Write a Python function `def tf_combine_mask(*masks)` to solve the following problem: Take the intersection of float-valued masks. Here is the function: def tf_combine_mask(*ma...
Take the intersection of float-valued masks.
142,162
from alphafold.common import residue_constants from alphafold.model.tf import shape_helpers from alphafold.model.tf import shape_placeholders from alphafold.model.tf import utils import numpy as np import tensorflow.compat.v1 as tf The provided code snippet includes necessary dependencies for implementing the `curry1`...
Supply all arguments but the first.
142,163
from alphafold.common import residue_constants from alphafold.model.tf import shape_helpers from alphafold.model.tf import shape_placeholders from alphafold.model.tf import utils import numpy as np import tensorflow.compat.v1 as tf def make_all_atom_aatype(protein): protein['all_atom_aatype'] = protein['aatype'] r...
null