id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
20,187
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value ...
null
20,188
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value ...
null
20,189
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: def is_sketch(ent...
null
20,190
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value ...
null
20,191
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def slvs_entity_pointer(cls, name, **kwargs): index_prop = name + "_i" annotations = {} if hasattr(cls, "__annotations__"): annotations = cls.__annotations__.co...
null
20,192
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def tag_update(self, context: Context): self.tag_update()
null
20,193
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def round_v(vec, ndigits=None): values = [] for v in vec: values.append(round(v, ndigits=ndigits)) return Vector(values)
null
20,194
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def get_connection_point(seg_1, seg_2): points = seg_1.connection_points() for p in seg_2.connection_points(): if p in points: return p
null
20,195
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def get_bezier_curve_midpoint_positions( curve_element, segment_count, midpoints, angle, cyclic=False ): positions = [] if segment_count == 1: return [] if...
null
20,196
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix def create_bezier_curve( segment_count, bezier_points, locations, center, base_offset, invert=False, cyclic=False, ): if cyclic: bezier_poin...
null
20,197
import logging import bpy from bpy.props import IntProperty from bpy.types import Context import math from mathutils import Vector, Matrix POINT = (*POINT3D, *POINT2D) LINE = (SlvsLine3D, SlvsLine2D) CURVE = (SlvsCircle, SlvsArc) class SlvsWorkplane(SlvsGenericEntity, PropertyGroup): """Representation of a plane ...
null
20,198
import logging import math from bpy.types import PropertyGroup from bpy.props import BoolProperty, FloatProperty, EnumProperty from bpy.utils import register_classes_factory from mathutils import Vector, Matrix from mathutils.geometry import distance_point_to_plane, intersect_point_line from ..solver import Solver from...
null
20,199
import logging import math from bpy.types import PropertyGroup from bpy.props import BoolProperty, FloatProperty, EnumProperty from bpy.utils import register_classes_factory from mathutils import Vector, Matrix from mathutils.geometry import distance_point_to_plane, intersect_point_line from ..solver import Solver from...
null
20,200
import logging import math from bpy.types import PropertyGroup from bpy.props import BoolProperty, FloatProperty, EnumProperty from bpy.utils import register_classes_factory from mathutils import Vector, Matrix from mathutils.geometry import distance_point_to_plane, intersect_point_line from ..solver import Solver from...
null
20,201
import logging from typing import List import bpy from bpy.types import PropertyGroup, Context from bpy.props import BoolProperty from gpu_extras.batch import batch_for_shader import math from mathutils import Vector, Matrix from mathutils.geometry import intersect_line_sphere_2d, intersect_sphere_sphere_2d from bpy.ut...
null
20,202
import logging from typing import Union, Generator import bpy from bpy.types import PropertyGroup, Context from bpy.utils import register_class, unregister_class from bpy.props import IntProperty, BoolProperty, PointerProperty, IntVectorProperty from .. import global_data from ..solver import solve_system from .utiliti...
null
20,203
import logging from typing import Union, Generator import bpy from bpy.types import PropertyGroup, Context from bpy.utils import register_class, unregister_class from bpy.props import IntProperty, BoolProperty, PointerProperty, IntVectorProperty from .. import global_data from ..solver import solve_system from .utiliti...
null
20,204
import bpy import logging from bpy.app.handlers import persistent def register_handlers(): def _setup_builtin_handlers(): def register(): _setup_builtin_handlers() register_handlers()
null
20,205
import bpy import logging from bpy.app.handlers import persistent def unregister_handlers(): global _builtin_handlers for handler_name in _builtin_handlers.keys(): msg = "Remove <{}> builtin handlers: ".format(handler_name) for cb in _builtin_handlers[handler_name]: handler_list = ge...
null
20,207
def apply_with_stopping_condition( module, apply_fn, apply_condition=None, stopping_condition=None, **other_args ): if stopping_condition(module): return if apply_condition(module): apply_fn(module, **other_args) for child in module.children(): apply_with_stopping_condition( ...
null
20,210
from typing import Optional from transformers import AutoModelForCausalLM, AutoTokenizer import open_clip from .flamingo import Flamingo from .flamingo_lm import FlamingoLMMixin from .utils import extend_instance def _infer_decoder_layers_attr_name(model): for k in __KNOWN_DECODER_LAYERS_ATTR_NAMES: if k.lo...
Initialize a Flamingo model from a pretrained vision encoder and language encoder. Appends special tokens to the tokenizer and freezes backbones. Args: clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32") clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "...
20,211
import argparse import glob import os import random import numpy as np import torch import wandb from data import get_data from distributed import init_distributed_device, world_info_from_env from torch.nn.parallel import DistributedDataParallel as DDP from torch.distributed.fsdp import FullyShardedDataParallel as FSDP...
null
20,212
import ast import json import logging import os import random import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import webdataset as wds from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info from torch.utils.dat...
null
20,213
import ast import json import logging import os import random import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import webdataset as wds from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info from torch.utils.dat...
null
20,214
import ast import json import logging import os import random import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import webdataset as wds from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info from torch.utils.dat...
null
20,215
import ast import json import logging import os import random import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import webdataset as wds from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info from torch.utils.dat...
get dataloader worker seed from pytorch
20,216
import functools import io import json import math import re import random import numpy as np import torch import torchvision import webdataset as wds from PIL import Image import base64 from scipy.optimize import linear_sum_assignment from data_utils import * def get_dataset_fn(dataset_type): """ Helper functi...
Interface for getting the webdatasets
20,218
import os import torch def is_using_horovod(): # NOTE w/ horovod run, OMPI vars should be set, but w/ SLURM PMI vars will be set # Differentiating between horovod and DDP use via SLURM may not be possible, so horovod arg still required... ompi_vars = ["OMPI_COMM_WORLD_RANK", "OMPI_COMM_WORLD_SIZE"] pmi...
null
20,219
import os import torch try: import horovod.torch as hvd except ImportError: hvd = None def is_using_distributed(): if "WORLD_SIZE" in os.environ: return int(os.environ["WORLD_SIZE"]) > 1 if "SLURM_NTASKS" in os.environ: return int(os.environ["SLURM_NTASKS"]) > 1 return False def worl...
null
20,220
import time from contextlib import suppress import torch from tqdm import tqdm from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import ( FullStateDictConfig, StateDictType, ) from torch.distributed.fsdp.api import FullOptimStateDictConfig import os import wandb fro...
null
20,221
import time from contextlib import suppress import torch from tqdm import tqdm from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import ( FullStateDictConfig, StateDictType, ) from torch.distributed.fsdp.api import FullOptimStateDictConfig import os import wandb fro...
null
20,222
import time from contextlib import suppress import torch from tqdm import tqdm from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import ( FullStateDictConfig, StateDictType, ) from torch.distributed.fsdp.api import FullOptimStateDictConfig import os import wandb fro...
Save training checkpoint with model, optimizer, and lr_scheduler state.
20,223
import numpy as np import torch import random import torch.nn as nn from contextlib import suppress The provided code snippet includes necessary dependencies for implementing the `get_indices_of_unique` function. Write a Python function `def get_indices_of_unique(x)` to solve the following problem: Return the indices ...
Return the indices of x that correspond to unique elements. If value v is unique and two indices in x have value v, the first index is returned.
20,224
import numpy as np import torch import random import torch.nn as nn from contextlib import suppress The provided code snippet includes necessary dependencies for implementing the `unwrap_model` function. Write a Python function `def unwrap_model(model)` to solve the following problem: Unwrap a model from a DataParalle...
Unwrap a model from a DataParallel or DistributedDataParallel wrapper.
20,225
import numpy as np import torch import random import torch.nn as nn from contextlib import suppress def get_cast_dtype(precision: str): cast_dtype = None if precision == "bf16": cast_dtype = torch.bfloat16 elif precision == "fp16": cast_dtype = torch.float16 return cast_dtype
null
20,226
import numpy as np import torch import random import torch.nn as nn from contextlib import suppress def get_autocast(precision): if precision == "amp": return torch.cuda.amp.autocast elif precision == "amp_bfloat16" or precision == "amp_bf16": # amp_bfloat16 is more stable than amp float16 for ...
null
20,227
import argparse import importlib import json import os import uuid import random from collections import defaultdict import numpy as np import torch from sklearn.metrics import roc_auc_score import utils import math from coco_metric import compute_cider, postprocess_captioning_generation from eval_datasets import ( ...
Evaluate a model on COCO dataset. Args: args (argparse.Namespace): arguments eval_model (BaseEvalModel): model to evaluate seed (int, optional): seed for random number generator. Defaults to 42. max_generation_length (int, optional): maximum length of the generated caption. Defaults to 20. num_beams (int, optional): nu...
20,228
import argparse import importlib import json import os import uuid import random from collections import defaultdict import numpy as np import torch from sklearn.metrics import roc_auc_score import utils import math from coco_metric import compute_cider, postprocess_captioning_generation from eval_datasets import ( ...
Evaluate a model on VQA datasets. Currently supports VQA v2.0, OK-VQA, VizWiz and TextVQA. Args: args (argparse.Namespace): arguments eval_model (BaseEvalModel): model to evaluate seed (int, optional): random seed. Defaults to 42. max_generation_length (int, optional): max generation length. Defaults to 5. num_beams (i...
20,229
import argparse import importlib import json import os import uuid import random from collections import defaultdict import numpy as np import torch from sklearn.metrics import roc_auc_score import utils import math from coco_metric import compute_cider, postprocess_captioning_generation from eval_datasets import ( ...
Evaluate a model on classification dataset. Args: eval_model (BaseEvalModel): model to evaluate seed (int, optional): random seed. Defaults to 42. num_shots (int, optional): number of shots to use. Defaults to 8. no_kv_caching (bool): whether to disable key-value caching dataset_name (str, optional): dataset name. Defa...
20,230
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp....
Flattens the full optimizer state dict, still keying by unflattened parameter names. If ``shard_state=True``, then FSDP-managed ``FlatParameter`` 's optimizer states are sharded, and otherwise, they are kept unsharded. If ``use_orig_params`` is True, each rank will have all FSDP-managed parameters but some of these par...
20,231
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp....
Processes positive-dimension tensor states in ``flat_optim_state_dict`` by replacing them with metadata. This is done so the processed optimizer state dict can be broadcast from rank 0 to all ranks without copying those tensor states, and thus, this is meant to only be called on rank 0. Args: flat_optim_state_dict (Dic...
20,232
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp....
Broadcasts the processed optimizer state dict from rank 0 to all ranks. Args: processed_optim_state_dict (Optional[Dict[str, Any]]): The flattened optimizer state dict with positive-dimension tensor states replaced with metadata if on rank 0; ignored otherwise. Returns: Dict[str, Any]: The processed optimizer state dic...
20,233
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp....
Takes ``processed_optim_state_dict``, which has metadata in place of positive-dimension tensor states, and broadcasts those tensor states from rank 0 to all ranks. For tensor states corresponding to FSDP parameters, rank 0 shards the tensor and broadcasts shard-by-shard, and for tensor states corresponding to non-FSDP ...
20,234
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp....
Rekeys the optimizer state dict from unflattened parameter names to flattened parameter IDs according to the calling rank's ``optim``, which may be different across ranks. In particular, the unflattened parameter names are represented as :class:`_OptimStateKey` s.
20,235
import copy import functools import warnings from dataclasses import dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.distributed as dist import torch.distributed.fsdp....
Consolidates the optimizer state and returns it as a :class:`dict` following the convention of :meth:`torch.optim.Optimizer.state_dict`, i.e. with keys ``"state"`` and ``"param_groups"``. The flattened parameters in ``FSDP`` modules contained in ``model`` are mapped back to their unflattened parameters. Parameter keys ...
20,236
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False
null
20,237
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def with_restore_point_creation_frequency(minutes, func): # Define the key path key_path = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore' # Open the key ...
null
20,238
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def create_restore_point(name): # Define the command cmd = f'powershell.exe -Command "Checkpoint-Computer -Description \'{name}\' -RestorePointType \'MODIFY_SETTINGS\'"' ...
null
20,239
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def uninstall_msix_package(package_full_name): # Define the PowerShell command cmd = f'powershell.exe -Command "Get-AppxPackage *{package_full_name}* | Remove-AppxPackage"' ...
null
20,240
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def delete_directory(dir_path): # Check if the directory exists if os.path.exists(dir_path): # Delete the directory shutil.rmtree(dir_path)
null
20,241
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def delete_registry_folders(): try: key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0, winreg.KEY_ALL_ACCESS) e...
null
20,242
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox target_string = "MicrosoftCorporationII.WindowsSubsystemForAndroid_8wekyb3d8bbwe" def delete_folders_and_files(root_path): target_string = 'MicrosoftCorporationII.WindowsSubsyste...
null
20,243
import os import shutil import subprocess import winreg import ctypes import logging import tkinter as tk from tkinter import messagebox def delete_shortcuts(target_string, start_menu_dir): # Walk through the file system starting from the start_menu_dir for dirpath, dirnames, filenames in os.walk(start_menu_di...
null
20,244
import sys import zipfile from pathlib import Path import platform import os from typing import Any, OrderedDict workdir = Path(sys.argv[3]) / "magisk" def extract_as(zip, name, as_name, dir): info = zip.getinfo(name) info.filename = as_name zip.extract(info, workdir / dir)
null
20,245
import html import logging import os import re import sys from pathlib import Path from threading import Thread from typing import Any, OrderedDict from xml.dom import minidom from requests import Session from packaging import version release_type = sys.argv[2] if sys.argv[2] != "" else "Retail" user = '' session = Ses...
null
20,246
from __future__ import annotations from io import TextIOWrapper from typing import OrderedDict from pathlib import Path import sys class Prop(OrderedDict): def __init__(self, file: TextIOWrapper) -> None: super().__init__() for i, line in enumerate(file.read().splitlines(False)): if '=' ...
null
20,247
from argparse import Namespace from pathlib import Path from typing import Tuple from exegol.config.ConstantConfig import ConstantConfig from exegol.config.DataCache import DataCache from exegol.config.UserConfig import UserConfig from exegol.manager.UpdateManager import UpdateManager from exegol.utils.DockerUtils impo...
Hybrid completer for auto-complet. The selector on exec action is hybrid between image and container depending on the mode (tmp or not). This completer will supply the adequate data.
20,248
from argparse import Namespace from pathlib import Path from typing import Tuple from exegol.config.ConstantConfig import ConstantConfig from exegol.config.DataCache import DataCache from exegol.config.UserConfig import UserConfig from exegol.manager.UpdateManager import UpdateManager from exegol.utils.DockerUtils impo...
Completer function for build profile parameter. The completer must be trigger only when an image name have already been chosen.
20,249
from argparse import Namespace from pathlib import Path from typing import Tuple from exegol.config.ConstantConfig import ConstantConfig from exegol.config.DataCache import DataCache from exegol.config.UserConfig import UserConfig from exegol.manager.UpdateManager import UpdateManager from exegol.utils.DockerUtils impo...
null
20,250
from argparse import Namespace from pathlib import Path from typing import Tuple from exegol.config.ConstantConfig import ConstantConfig from exegol.config.DataCache import DataCache from exegol.config.UserConfig import UserConfig from exegol.manager.UpdateManager import UpdateManager from exegol.utils.DockerUtils impo...
No option to auto-complet
20,251
import re from typing import Tuple, Union The provided code snippet includes necessary dependencies for implementing the `boolFormatter` function. Write a Python function `def boolFormatter(val: bool) -> str` to solve the following problem: Generic text formatter for bool value Here is the function: def boolFormatte...
Generic text formatter for bool value
20,252
import re from typing import Tuple, Union The provided code snippet includes necessary dependencies for implementing the `getColor` function. Write a Python function `def getColor(val: Union[bool, int, str]) -> Tuple[str, str]` to solve the following problem: Generic text color getter for bool value Here is the funct...
Generic text color getter for bool value
20,253
import re from typing import Tuple, Union The provided code snippet includes necessary dependencies for implementing the `richLen` function. Write a Python function `def richLen(text: str) -> int` to solve the following problem: Get real length of a text without Rich colors Here is the function: def richLen(text: st...
Get real length of a text without Rich colors
20,254
import re from typing import Tuple, Union def getArchColor(arch: str) -> str: if arch.startswith("arm"): color = "slate_blue3" elif "amd64" == arch: color = "medium_orchid3" else: color = "yellow3" return color
null
20,255
import rich.prompt The provided code snippet includes necessary dependencies for implementing the `Confirm` function. Write a Python function `def Confirm(question: str, default: bool) -> bool` to solve the following problem: Quick function to format rich Confirmation and options on every exegol interaction Here is t...
Quick function to format rich Confirmation and options on every exegol interaction
20,256
from typing import Union, Optional, Dict from git import RemoteProgress from git.objects.submodule.base import UpdateProgress from rich.console import Console from rich.progress import Progress, ProgressColumn, GetTimeCallable, Task from exegol.utils.ExeLog import console as exelog_console from exegol.utils.ExeLog impo...
null
20,257
logger: ExeLog = cast(ExeLog, logging.getLogger("main")) logger.setLevel(logging.INFO) def print_exception_banner(): logger.error("It seems that something unexpected happened ...") logger.error("To draw our attention to the problem and allow us to fix it, you can share your error with us " "...
null
20,258
import logging import re import stat import subprocess from pathlib import Path, PurePath from typing import Optional from exegol.config.EnvInfo import EnvInfo from exegol.utils.ExeLog import logger logger: ExeLog = cast(ExeLog, logging.getLogger("main")) logger.setLevel(logging.INFO) The provided code snippet includ...
Parse docker volume path to find the corresponding host path.
20,259
import logging import re import stat import subprocess from pathlib import Path, PurePath from typing import Optional from exegol.config.EnvInfo import EnvInfo from exegol.utils.ExeLog import logger def resolvPath(path: Path) -> str: """Resolv a filesystem path depending on the environment. On WSL, Windows PATH...
Try to resolv a filesystem path from a string.
20,260
import logging import re import stat import subprocess from pathlib import Path, PurePath from typing import Optional from exegol.config.EnvInfo import EnvInfo from exegol.utils.ExeLog import logger logger: ExeLog = cast(ExeLog, logging.getLogger("main")) logger.setLevel(logging.INFO) The provided code snippet includ...
Set the setgid permission bit to every recursive directory
20,261
import numpy as np def convert_to_ndc(origins, directions, ndc_coeffs, near: float = 1.0): """Convert a set of rays to NDC coordinates.""" t = (near - origins[Ellipsis, 2]) / directions[Ellipsis, 2] origins = origins + t[Ellipsis, None] * directions dx, dy, dz = directions[:, 0], directions[:, 1], direc...
null
20,262
import numpy as np def pad_poses(p: np.ndarray) -> np.ndarray: """Pad [..., 3, 4] pose matrices with a homogeneous bottom row [0,0,0,1].""" bottom = np.broadcast_to([0, 0, 0, 1.0], p[..., :1, :4].shape) return np.concatenate([p[..., :3, :4], bottom], axis=-2) def unpad_poses(p: np.ndarray) -> np.ndarray: ...
Transforms poses so principal components lie on XYZ axes. Args: poses: a (N, 3, 4) array containing the cameras' camera to world transforms. Returns: A tuple (poses, transform), with the transformed poses and the applied camera_to_world transforms.
20,263
import numpy as np def focus_point_fn(poses: np.ndarray) -> np.ndarray: """Calculate nearest point to all focal axes in poses.""" directions, origins = poses[:, :3, 2:3], poses[:, :3, 3:4] m = np.eye(3) - directions * np.transpose(directions, [0, 2, 1]) mt_m = np.transpose(m, [0, 2, 1]) @ m focus_pt...
Generate an elliptical render path based on the given poses.
20,264
import json import os import imageio import numpy as np import torch def pose_spherical(theta, phi, radius): c2w = trans_t(radius) c2w = rot_phi(phi / 180.0 * np.pi) @ c2w c2w = rot_theta(theta / 180.0 * np.pi) @ c2w c2w = ( torch.tensor([[-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])...
null
20,265
import json import os import gdown import imageio import numpy as np import torch def pose_spherical(theta, phi, radius): c2w = trans_t(radius) c2w = rot_phi(phi / 180.0 * np.pi) @ c2w c2w = rot_theta(theta / 180.0 * np.pi) @ c2w c2w = ( torch.tensor([[-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [...
null
20,266
import glob import os from typing import * import imageio import numpy as np def find_files(dir, exts): if os.path.isdir(dir): files_grabbed = [] for ext in exts: files_grabbed.extend(glob.glob(os.path.join(dir, ext))) if len(files_grabbed) > 0: files_grabbed = sorted...
null
20,267
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def ptstocam(pts, c2w): tt = np.matmul(c2w[:3, :3].T, (pts - c2w[:3, 3])[..., np.newaxis])[..., 0] return tt
null
20,268
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def normalize(x): return x / np.linalg.norm(x) def viewmatrix(z, up, pos): vec2 = normalize(z) vec1_avg = up vec0 = normalize(np.cross(vec1_avg, vec2)) vec1 = normalize(np.cross(v...
null
20,269
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def poses_avg(poses): hwf = poses[0, :3, -1:] center = poses[:, :3, 3].mean(0) vec2 = normalize(poses[:, :3, 2].sum(0)) up = poses[:, :3, 1].sum(0) c2w = np.concatenate([viewmatri...
null
20,270
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def normalize(x): return x / np.linalg.norm(x) def spherify_poses(poses, bds): p34_to_44 = lambda p: np.concatenate( [p, np.tile(np.reshape(np.eye(4)[-1, :], [1, 1, 4]), [p.shape[0]...
null
20,271
import os from subprocess import check_output import imageio import numpy as np import src.data.pose_utils as pose_utils def _load_data(basedir, factor=None, width=None, height=None, load_imgs=True): poses_arr = np.load(os.path.join(basedir, "poses_bounds.npy")) poses = poses_arr[:, :-2].reshape([-1, 3, 5]).tra...
null
20,272
import json import os import gdown import imageio import numpy as np import torch def pose_spherical(theta, phi, radius): def load_shiny_blender_data( datadir: str, scene_name: str, train_skip: int, val_skip: int, test_skip: int, cam_scale_factor: float, white_bkgd: bool, ): basedir = o...
null
20,273
import os from subprocess import check_output import imageio import numpy as np def ptstocam(pts, c2w): tt = np.matmul(c2w[:3, :3].T, (pts - c2w[:3, 3])[..., np.newaxis])[..., 0] return tt
null
20,274
import os from subprocess import check_output import imageio import numpy as np def normalize(x): def viewmatrix(z, up, pos): def render_path_spiral(c2w, up, rads, focal, zdelta, zrate, rots, N): render_poses = [] rads = np.array(list(rads) + [1.0]) hwf = c2w[:, 4:5] for theta in np.linspace(0.0, 2.0 ...
null
20,275
import os from subprocess import check_output import imageio import numpy as np def poses_avg(poses): hwf = poses[0, :3, -1:] center = poses[:, :3, 3].mean(0) vec2 = normalize(poses[:, :3, 2].sum(0)) up = poses[:, :3, 1].sum(0) c2w = np.concatenate([viewmatrix(vec2, up, center), hwf], 1) return ...
null
20,276
import os from subprocess import check_output import imageio import numpy as np def normalize(x): return x / np.linalg.norm(x) def spherify_poses(poses, bds): p34_to_44 = lambda p: np.concatenate( [p, np.tile(np.reshape(np.eye(4)[-1, :], [1, 1, 4]), [p.shape[0], 1, 1])], 1 ) rays_d = poses[:,...
null
20,277
import os from subprocess import check_output import imageio import numpy as np def _load_data(basedir, factor=None, width=None, height=None, load_imgs=True): def similarity_from_cameras(c2w): def transform_pose_llff(poses): def load_refnerf_real_data( datadir: str, scene_name: str, factor: int, cam_sc...
null
20,278
import os from subprocess import check_output from typing import * import imageio import numpy as np def ptstocam(pts, c2w): tt = np.matmul(c2w[:3, :3].T, (pts - c2w[:3, 3])[..., np.newaxis])[..., 0] return tt
null
20,279
import os from subprocess import check_output from typing import * import imageio import numpy as np def _load_data(basedir, factor=None, width=None, height=None, load_imgs=True): poses_arr = np.load(os.path.join(basedir, "poses_bounds.npy")) poses = poses_arr[:, :-2].reshape([-1, 3, 5]).transpose([1, 2, 0]) ...
null
20,280
import glob import os from typing import * import imageio import numpy as np def find_files(dir, exts): if os.path.isdir(dir): files_grabbed = [] for ext in exts: files_grabbed.extend(glob.glob(os.path.join(dir, ext))) if len(files_grabbed) > 0: files_grabbed = sorted...
null
20,281
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam class MaskedAdam(torch.optim.Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.99), eps=1e-8): if not 0.0 <= lr: raise...
null
20,282
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam def load_checkpoint(model, optimizer, ckpt_path, no_reload_optimizer): ckpt = torch.load(ckpt_path) start = ckpt["global_step"] model.load_stat...
null
20,283
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam def load_model(model_class, ckpt_path): ckpt = torch.load(ckpt_path) model = model_class(**ckpt["model_kwargs"]) model.load_state_dict(ckpt["mo...
null
20,284
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam def rgb_ssim( img0, img1, max_val, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03, return_map=False, ): # Modified ...
null
20,285
import numpy as np import scipy.signal import torch import torch.nn as nn from src.model.dvgo.__global__ import * from src.model.dvgo.masked_adam import MaskedAdam __LPIPS__ = {} def init_lpips(net_name, device): assert net_name in ["alex", "vgg"] import lpips print(f"init_lpips: lpips_{net_name}") retu...
null
20,286
import functools import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from src.model.dvgo.__global__ import * class DenseGrid(nn.Module): def __init__(self, channels, world_size, xyz_min, xyz_max, **kwargs): super(DenseGrid, self).__init__() sel...
null
20,287
import functools import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from src.model.dvgo.__global__ import * def compute_tensorf_feat( xy_plane, xz_plane, yz_plane, x_vec, y_vec, z_vec, f_vec, ind_norm ): # Interp feature (feat shape: [n_pts, n_comp]) ...
null
20,288
import functools import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from src.model.dvgo.__global__ import * def compute_tensorf_val(xy_plane, xz_plane, yz_plane, x_vec, y_vec, z_vec, ind_norm): # Interp feature (feat shape: [n_pts, n_comp]) xy_feat = ( ...
null
20,289
import functools import os import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch_scatter import segment_coo import src.model.dvgo.grid as grid from src.model.dvgo.__global__ import * from src.model.dvgo.dvgo import Alphas2Weights, Raw2Alpha def create_full_step_id...
null
20,290
import os from torch.utils.cpp_extension import load root_dir = __file__.split(os.path.relpath(__file__))[0] render_utils_cuda = None total_variation_cuda = None ub360_utils_cuda = None adam_upd_cuda = None sources = ["lib/dvgo/cuda/adam_upd.cpp", "lib/dvgo/cuda/adam_upd_kernel.cu"] def init(): global render_utils...
null