id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
4,580 | import re
from azure.core.exceptions import HttpResponseError, ResourceExistsError
from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
from exceptions import (
SecretNameAlreadyExistsException,
SecretNameInvalidException,
SecretNoSetPermissionException,
)
KVUri ... | null |
4,581 | import re
from azure.core.exceptions import HttpResponseError, ResourceExistsError
from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
from exceptions import (
SecretNameAlreadyExistsException,
SecretNameInvalidException,
SecretNoSetPermissionException,
)
def g... | null |
4,582 | import re
from azure.core.exceptions import HttpResponseError, ResourceExistsError
from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
from exceptions import (
SecretNameAlreadyExistsException,
SecretNameInvalidException,
SecretNoSetPermissionException,
)
reserv... | null |
4,583 | import re
from azure.core.exceptions import HttpResponseError, ResourceExistsError
from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
from exceptions import (
SecretNameAlreadyExistsException,
SecretNameInvalidException,
SecretNoSetPermissionException,
)
key_va... | null |
4,584 | import argparse
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from ghactions_driver.readme_parse import readme_parser
from ghactions_driver.readme_step import ReadmeStepsManage
def readme_parser(filename: str):
real_filename = Path(ReadmeStepsManage.git_base_dir()) / filename
data =... | null |
4,585 | from pathlib import Path
from .readme_step import ReadmeStepsManage, ReadmeSteps
from ghactions_driver.telemetry_obj import Telemetry
class ReadmeSteps:
"""
Static class to record steps, to be filled in workflow templates and Readme
"""
step_array = [] # Record steps
readme_name = "" # Record re... | null |
4,586 | import os
import glob
import argparse
from pathlib import Path
import ntpath
import re
import hashlib
import json
from jinja2 import Environment, FileSystemLoader
from ghactions_driver.readme_step import ReadmeStepsManage
from ghactions_driver.resource_resolver import resolve_tutorial_resource
from ghactions_driver.tel... | null |
4,587 | import os
import glob
import argparse
from pathlib import Path
import ntpath
import re
import hashlib
import json
from jinja2 import Environment, FileSystemLoader
from ghactions_driver.readme_step import ReadmeStepsManage
from ghactions_driver.resource_resolver import resolve_tutorial_resource
from ghactions_driver.tel... | Convert the path list to unix format. :param paths_list: The input path list. :returns: The same list with unix-like paths. |
4,588 | import os
import glob
import argparse
from pathlib import Path
import ntpath
import re
import hashlib
import json
from jinja2 import Environment, FileSystemLoader
from ghactions_driver.readme_step import ReadmeStepsManage
from ghactions_driver.resource_resolver import resolve_tutorial_resource
from ghactions_driver.tel... | null |
4,589 | import os
import glob
import argparse
from pathlib import Path
import ntpath
import re
import hashlib
import json
from jinja2 import Environment, FileSystemLoader
from ghactions_driver.readme_step import ReadmeStepsManage
from ghactions_driver.resource_resolver import resolve_tutorial_resource
from ghactions_driver.tel... | null |
4,590 | import os
import glob
import argparse
from pathlib import Path
import ntpath
import re
import hashlib
import json
from jinja2 import Environment, FileSystemLoader
from ghactions_driver.readme_step import ReadmeStepsManage
from ghactions_driver.resource_resolver import resolve_tutorial_resource
from ghactions_driver.tel... | Set each ipynb metadata no_readme_generation to "true" to skip readme generation |
4,591 | import json
from pathlib import Path
import workflow_generator
import readme_generator
from jinja2 import Environment, FileSystemLoader
from ghactions_driver.readme_step import ReadmeStepsManage
from operator import itemgetter
import argparse
import sys
import os
import re
BRANCH = "main"
def get_notebook_readme_descri... | null |
4,592 | import argparse
from pathlib import Path
from functools import reduce
from ghactions_driver.readme_workflow_generate import write_readme_workflow
from ghactions_driver.readme_step import ReadmeStepsManage, ReadmeSteps
from ghactions_driver.readme_parse import readme_parser
from ghactions_driver.telemetry_obj import Tel... | null |
4,593 | import argparse
from pathlib import Path
from functools import reduce
from ghactions_driver.readme_workflow_generate import write_readme_workflow
from ghactions_driver.readme_step import ReadmeStepsManage, ReadmeSteps
from ghactions_driver.readme_parse import readme_parser
from ghactions_driver.telemetry_obj import Tel... | If there is no steps in the readme, then no generation |
4,594 | from promptflow._sdk._load_functions import load_yaml
from promptflow._sdk._pf_client import PFClient
from ghactions_driver.readme_step import ReadmeStepsManage
from pathlib import Path
import os
import subprocess
import sys
def install(filename):
subprocess.check_call([sys.executable, "-m", "pip", "install", "-r"... | null |
4,595 | import os
import sys
import argparse
from lib.option import initOption
from config.config import pyVersion, urlVersion
from config.data import logger
pyVersion = platform.python_version()
urlVersion = urllib3.__version__
logger = MY_LOGGER
def version_check():
if pyVersion < "3.7.3":
logger.error(
... | null |
4,596 | import os
import sys
import argparse
from lib.option import initOption
from config.config import pyVersion, urlVersion
from config.data import logger
import sys
sys.dont_write_bytecode = True
The provided code snippet includes necessary dependencies for implementing the `modulePath` function. Write a Python function ... | This will get us the program's directory, even if we are frozen using py2exe |
4,597 | import os
import sys
import random
import prettytable as pt
from mod.fofa import fmain
from mod.zoomeye import zmain
from mod.quake import qmain
from mod.website import mwebs
from mod.rulesCli import ruleMain
from mod.output import outMain
from lib.proxy import checkProxyFile
from lib.update import update
from lib.comm... | null |
4,598 | import os
from setuptools import setup, find_packages, dist
import importlib
from pkg_resources import parse_version
import subprocess
import warnings
import os
import sys
import logging
import glob
import numpy
import torch
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
cw... | null |
4,599 | import os
from setuptools import setup, find_packages, dist
import importlib
from pkg_resources import parse_version
import subprocess
import warnings
import os
import sys
import logging
import glob
import numpy
import torch
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
cw... | null |
4,600 | import os
from setuptools import setup, find_packages, dist
import importlib
from pkg_resources import parse_version
import subprocess
import warnings
import os
import sys
import logging
import glob
import numpy
import torch
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
d... | null |
4,601 | import os
from setuptools import setup, find_packages, dist
import importlib
from pkg_resources import parse_version
import subprocess
import warnings
import os
import sys
import logging
import glob
import numpy
import torch
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
if... | null |
4,602 | import os
def run_apidoc(_):
def setup(app):
app.connect("builder-inited", run_apidoc) | null |
4,603 | import argparse
import os
import torch
import kaolin as kal
The provided code snippet includes necessary dependencies for implementing the `preprocessing_transform` function. Write a Python function `def preprocessing_transform(inputs)` to solve the following problem:
This the transform used in shapenet dataset __geti... | This the transform used in shapenet dataset __getitem__. Three tasks are done: 1) Get the areas of each faces, so it can be used to sample points 2) Get a proper list of RGB diffuse map 3) Get the material associated to each face |
4,604 | import torch
import numpy as np
from typing import Tuple
from kaolin.render.camera import Camera, CameraFOV
def generate_pixel_grid(res_x=None, res_y=None, device='cuda'):
h_coords = torch.arange(res_x, device=device)
w_coords = torch.arange(res_y, device=device)
pixel_y, pixel_x = torch.meshgrid(h_coords,... | null |
4,605 | import torch
import numpy as np
from typing import Tuple
from kaolin.render.camera import Camera, CameraFOV
ray_orig, ray_dir, near, far = generate_perspective_rays(camera, pixel_grid)
def generate_perspective_rays(camera: Camera, pixel_grid: Tuple[torch.Tensor, torch.Tensor]):
# coords_grid should remain immutabl... | null |
4,606 | import torch
import kaolin
spc = kaolin.rep.Spc.make_dense(level, device='cuda')
print(f'Input SPC features: {colors.shape}')
color_hierarchy = encode(colors=colors,
octree=spc.octrees,
point_hierachy=spc.point_hierarchies,
pyramids=spc.pyramids... | null |
4,607 | import argparse
import logging
import os
import random
import torch
import sys
import kaolin
The provided code snippet includes necessary dependencies for implementing the `__normalize_vertices` function. Write a Python function `def __normalize_vertices(vertices)` to solve the following problem:
Normalizes vertices t... | Normalizes vertices to fit an [-1...1] bounding box, common during training, but not necessary for visualization. |
4,608 | import os
import argparse
from kaolin.io import usd
from kaolin.io.utils import mesh_handler_naive_triangulate
def mesh_handler_naive_triangulate(vertices, face_vertex_counts, *features, face_assignments=None):
def import_kitchen_set(kitchen_set_usd):
# The Kitchen Set example organizes assets in a particular way... | null |
4,609 | import os
import argparse
from kaolin.io import usd
from kaolin.io.utils import mesh_handler_naive_triangulate
def save_kitchen_set_dataset(meshes, out_dir):
for i, m in enumerate(meshes):
out_path = os.path.join(out_dir, f'mesh_{i}.usd')
usd.export_mesh(
file_path=out_path,
... | null |
4,610 | import torch
from tqdm import tqdm
class Embedder:
def __init__(self, **kwargs):
self.kwargs = kwargs
self.create_embedding_fn()
def create_embedding_fn(self):
embed_fns = []
d = self.kwargs['input_dims']
out_dim = 0
if self.kwargs['include_input']:
em... | null |
4,611 | from collections import deque
from termcolor import colored
def push_pop_octree(q, oct_item):
def format_octree_str(octree_byte, octree_path, level_idx, max_level):
def describe_octree(octree, level, limit_levels=None):
bit_counter = lambda x: bin(x).count('1')
level_idx, curr_level_remaining_cells, next_level... | null |
4,612 | import torch
from kaolin import _C
def sided_distance(p1, p2):
r"""For each point in :math:`p_{1i} \in P_1` will find the indices and squared euclidean
distances of the closest point :math:`P_2`, as following:
:math:`\text{sided_distance}(p_{1i}, P_2) = \min\limits_{p_{2j}\in{P_2}}(||p_{1i} - p_{2j}||_2^2)... | r"""Computes the chamfer distance between two pointclouds, defined as following: :math:`\dfrac{w_1}{|P_1|}\sum\limits_{p_{1i} \in P_1}\min\limits_{p_{2j} \in P_2}(||p_{1i} - p_{2j}||_2^2) + \dfrac{w_2}{|P_2|}\sum\limits_{p_{2j} \in P_2}\min\limits_{p_{1i} \in P_1}(||p_{2j} - p_{1i}||_2^2)` Args: p1 (torch.Tensor): Poin... |
4,613 | import torch
from kaolin import _C
def sided_distance(p1, p2):
r"""For each point in :math:`p_{1i} \in P_1` will find the indices and squared euclidean
distances of the closest point :math:`P_2`, as following:
:math:`\text{sided_distance}(p_{1i}, P_2) = \min\limits_{p_{2j}\in{P_2}}(||p_{1i} - p_{2j}||_2^2)... | r"""Computes the f-score of two sets of points, with a hit defined by two point existing within a defined radius of each other. Args: gt_points (torch.Tensor): Ground truth pointclouds, of shape :math:`(\text{batch_size}, \text{num_gt_points}, 3)`. pred_points (torch.Tensor): Predicted points pointclouds, of shape :mat... |
4,614 | import torch
from kaolin import _C
The provided code snippet includes necessary dependencies for implementing the `_sided_distance` function. Write a Python function `def _sided_distance(p1, p2)` to solve the following problem:
Pytorch version of sided distances for testing.
Here is the function:
def _sided_distance... | Pytorch version of sided distances for testing. |
4,615 | import torch
from kaolin import _C
from ..ops.mesh import uniform_laplacian
class _UnbatchedTriangleDistanceCuda(torch.autograd.Function):
def forward(ctx, points, face_vertices):
num_points = points.shape[0]
num_faces = face_vertices.shape[0]
min_dist = torch.zeros((num_points), device=poin... | r"""Computes the distances from pointclouds to meshes (represented by vertices and faces). For each point in the pointcloud, it finds the nearest triangle in the mesh, and calculated its distance to that triangle. .. note:: The calculated distance is the squared euclidean distance. Type 0 indicates the distance is from... |
4,616 | import torch
from kaolin import _C
from ..ops.mesh import uniform_laplacian
The provided code snippet includes necessary dependencies for implementing the `average_edge_length` function. Write a Python function `def average_edge_length(vertices, faces)` to solve the following problem:
r"""Returns the average length of... | r"""Returns the average length of each faces in a mesh. Args: vertices (torch.Tensor): Batched vertices, of shape :math:`(\text{batch_size}, \text{num_vertices}, 3)`. faces (torch.LongTensor): Faces, of shape :math:`(\text{num_faces}, 3)`. Returns: (torch.Tensor): average length of each edges in a face, of shape :math:... |
4,617 | import torch
from kaolin import _C
from ..ops.mesh import uniform_laplacian
The provided code snippet includes necessary dependencies for implementing the `uniform_laplacian_smoothing` function. Write a Python function `def uniform_laplacian_smoothing(vertices, faces)` to solve the following problem:
r"""Calculates th... | r"""Calculates the uniform laplacian smoothing of meshes. The position of updated vertices is defined as :math:`V_i = \frac{1}{N} * \sum^{N}_{j=1}V_j`, where :math:`N` is the number of neighbours of :math:`V_i`, :math:`V_j` is the position of the j-th adjacent vertex. Args: vertices (torch.Tensor): Vertices of the mesh... |
4,618 | import torch
The provided code snippet includes necessary dependencies for implementing the `mask_iou` function. Write a Python function `def mask_iou(lhs_mask, rhs_mask)` to solve the following problem:
r"""Compute the Intersection over Union of two segmentation masks. Args: lhs_mask (torch.FloatTensor): A segmentati... | r"""Compute the Intersection over Union of two segmentation masks. Args: lhs_mask (torch.FloatTensor): A segmentation mask, of shape :math:`(\text{batch_size}, \text{height}, \text{width})`. rhs_mask (torch.FloatTensor): A segmentation mask, of shape :math:`(\text{batch_size}, \text{height}, \text{width})`. Returns: (t... |
4,619 | import torch
from kaolin.ops.mesh.tetmesh import _validate_tet_vertices
def tetrahedron_volume(tet_vertices):
r"""Compute the volume of tetrahedrons.
Args:
tet_vertices (torch.Tensor):
Batched tetrahedrons, of shape
:math:`(\text{batch_size}, \text{num_tetrahedrons}, 4, 3)`.
... | r"""Compute the EquiVolume loss as devised by *Gao et al.* in `Learning Deformable Tetrahedral Meshes for 3D Reconstruction <https://nv-tlabs.github.io/DefTet/>`_ NeurIPS 2020. See `supplementary material <https://nv-tlabs.github.io/DefTet/files/supplement.pdf>`_ for the definition of the loss function. Args: tet_verti... |
4,620 | import torch
from kaolin.ops.mesh.tetmesh import _validate_tet_vertices
def _validate_tet_vertices(tet_vertices):
r"""Helper method to validate the dimensions of the batched tetrahedrons tensor.
Args:
tet_vertices (torch.Tensor):
Batched tetrahedrons, of shape
:math:`(\text{bat... | r"""Compute the AMIPS (Advanced MIPS) loss as devised by *Fu et al.* in `Computing Locally Injective Mappings by Advanced MIPS. \ <https://www.microsoft.com/en-us/research/publication/computing-locally-injective-mappings-advanced-mips/>`_ ACM Transactions on Graphics (TOG) - Proceedings of ACM SIGGRAPH 2015. The Jacobi... |
4,621 | import torch
The provided code snippet includes necessary dependencies for implementing the `iou` function. Write a Python function `def iou(pred, gt)` to solve the following problem:
r"""Computes IoU across two voxelgrids Arguments: pred (torch.Tensor): predicted (binary) voxelgrids, of shape :math:`(\text{batch_size... | r"""Computes IoU across two voxelgrids Arguments: pred (torch.Tensor): predicted (binary) voxelgrids, of shape :math:`(\text{batch_size}, \text{X}, \text{Y}, \text{Z})`. gt (torch.Tensor): ground-truth (binary) voxelgrids, of shape :math:`(\text{batch_size}, \text{X}, \text{Y}, \text{Z})`. Returns: (torch.FloatTensor):... |
4,622 | import math
import torch
from kaolin import _C
def _dot(a, b):
"""Compute dot product of two tensors on the last axis."""
return torch.sum(a * b, dim=-1, keepdim=True)
def _ggx_v1(m2, nDotX):
"""Helper for computing the Smith visibility term with Trowbridge-Reitz (GGX) distribution"""
return 1. / (nDotX... | r"""Computes the specular reflectance from a spherical gaussians lobes representing incoming radiance, using the Cook-Torrance microfacet specular shading model. Args: amplitude (torch.Tensor): The amplitudes of the spherical gaussians representing the incoming radiance, of shape :math:`(\text{num_sg}, 3)`. direction (... |
4,623 | import math
import torch
from kaolin import _C
def sg_irradiance_fitted(amplitude, direction, sharpness, normal):
r"""Computes an approximate incident irradiance from multiple spherical gaussians
representing the incoming radiance.
The result is broadcasted per point per spherical gaussian.
.. note::
... | r"""Computes the outgoing radiance from multiple spherical gaussians representing incoming radiance, using a Lambertian diffuse BRDF. .. note:: The irradiance is computed using a fitted approximation polynomial, this approximation were provided by Stephen Hill. See :func:`sg_irradiance_fitted`. Args: amplitude (torch.T... |
4,624 | import math
import torch
from kaolin import _C
def sg_irradiance_inner_product(amplitude, direction, sharpness, normal):
r"""Computes the approximate incident irradiance from multiple spherical gaussians representing incoming radiance.
The clamped cosine lobe is approximated as a spherical gaussian,
and con... | r"""Computes the outgoing radiance from multiple spherical gaussians representing incoming radiance, using a Lambertian diffuse BRDF. This is the diffuse reflectance used in `DIB-R++\: Learning to Predict Lighting and Material with a Hybrid Differentiable Renderer`_ NeurIPS 2021. Args: amplitude (torch.Tensor): The amp... |
4,625 | import math
import torch
def project_onto_sh9(directions):
r"""Project directions, represented as cartesian coordinates,
onto the spherical harmonic coefficients of degree 3.
Args:
directions (torch.Tensor or list of int):
The directions as cartesian coordinates,
of any shape... | r"""Compute the outgoing radiance from a single spherical harmonic lobe of degree 3 representing incoming radiance, using a Lambertian diffuse BRDF. Args: directions (torch.Tensor): Light directions, of 1D size :math:`(3,)`. normals (torch.Tensor): Normal of the points where the radiance is to be estimated, of shape :m... |
4,626 | from __future__ import division
import torch
from .. import camera
from ... import ops
The provided code snippet includes necessary dependencies for implementing the `texture_mapping` function. Write a Python function `def texture_mapping(texture_coordinates, texture_maps, mode='nearest')` to solve the following probl... | r"""Interpolates texture_maps by dense or sparse texture_coordinates. This function supports sampling texture coordinates for: 1. An entire 2D image 2. A sparse point cloud of texture coordinates. Args: texture_coordinates(torch.FloatTensor): dense image texture coordinate, of shape :math:`(\text{batch_size}, h, w, 2)`... |
4,627 | from __future__ import division
import torch
from .. import camera
from ... import ops
The provided code snippet includes necessary dependencies for implementing the `spherical_harmonic_lighting` function. Write a Python function `def spherical_harmonic_lighting(imnormal, lights)` to solve the following problem:
r"""C... | r"""Creates lighting effects. Follows convention set by *Wojciech Jarosz* in `Efficient Monte Carlo Methods for Light Transport in Scattering Media`_. .. deprecated:: 0.13.0 This function is deprecated. Use :func:`kaolin.render.lighting.sh9_irradiance`. Args: imnormal (torch.FloatTensor): per pixel normal, of shape :ma... |
4,628 | from __future__ import division
import torch
from .. import camera
from ... import ops
from . import camera
from . import ops
The provided code snippet includes necessary dependencies for implementing the `prepare_vertices` function. Write a Python function `def prepare_vertices(vertices, faces, camera_proj, camera_... | r"""Wrapper function to move and project vertices to cameras then index them with faces. Args: vertices (torch.Tensor): the meshes vertices, of shape :math:`(\text{batch_size}, \text{num_vertices}, 3)`. faces (torch.LongTensor): the meshes faces, of shape :math:`(\text{num_faces}, \text{face_size})`. camera_proj (torch... |
4,629 | import torch
from torch.autograd import Function
from kaolin import _C
from .rasterization import rasterize, _legacy_to_opengl, nvdiff, _get_nvdiff_glctx
def dibr_soft_mask(face_vertices_image, selected_face_idx,
sigmainv=7000, boxlen=0.02, knum=30, multiplier=1000.):
r"""Compute a soft mask gene... | r"""Fully differentiable DIB-R renderer implementation, that renders 3D triangle meshes with per-vertex per-face features to generalized feature "images", soft foreground masks, and face index maps. Args: height (int): the size of rendered images. width (int): the size of rendered images. face_vertices_z (torch.FloatTe... |
4,630 | import torch
from torch.autograd import Function
from kaolin import _C
def _base_naive_deftet_render(
pixel_coords, # (2,)
render_range, # (2,)
face_vertices_image, # (num_faces, 3, 2)
face_vertices_z, # (num_faces, 3)
face_vertices_min, # (num_faces, 2)
... | r"""Naive implementation of :func:`deftet_sparse_render`. Note: The behavior is different than :func:`deftet_sparse_render` when knum < max(number of faces per pixel), as this returns the first faces by pixel_depth while deftet_render returns the first faces by the mesh order. Note: if `face_camera_vertices` and `face_... |
4,631 | import torch
from torch.autograd import Function
from kaolin import _C
class DeftetSparseRenderer(Function):
"""torch.autograd.Function for :func:`deftet_sparse_render`."""
def forward(ctx, pixel_coords, render_ranges, face_vertices_z,
face_vertices_image, face_features, knum, eps):
# di... | r"""Fully differentiable volumetric renderer devised by *Gao et al.* in `Learning Deformable Tetrahedral Meshes for 3D Reconstruction`_ NeurIPS 2020. This is rasterizing a mesh w.r.t to a list of pixel coordinates, but instead of just rendering the closest intersection. it will render all the intersections sorted by de... |
4,632 | from __future__ import division
import torch
import torch.nn
from numpy import tan
The provided code snippet includes necessary dependencies for implementing the `rotate_translate_points` function. Write a Python function `def rotate_translate_points(points, camera_rot, camera_trans)` to solve the following problem:
r... | r"""Rotate and translate 3D points on based on rotation matrix and transformation matrix. Formula is :math:`\text{P_new} = R * (\text{P_old} - T)` Args: points (torch.FloatTensor): 3D points, of shape :math:`(\text{batch_size}, \text{num_points}, 3)`. camera_rot (torch.FloatTensor): rotation matrix, of shape :math:`(\t... |
4,633 | from __future__ import division
import torch
import torch.nn
from numpy import tan
The provided code snippet includes necessary dependencies for implementing the `generate_rotate_translate_matrices` function. Write a Python function `def generate_rotate_translate_matrices(camera_position, look_at, camera_up_direction)... | r"""Generate rotation and translation matrix for given camera parameters. Formula is :math:`\text{P_cam} = \text{rot_mtx} * (\text{P_world} - \text{trans_mtx})` Args: camera_position (torch.FloatTensor): camera positions of shape :math:`(\text{batch_size}, 3)`, it means where your cameras are look_at (torch.FloatTensor... |
4,634 | from __future__ import division
import torch
import torch.nn
from numpy import tan
The provided code snippet includes necessary dependencies for implementing the `generate_transformation_matrix` function. Write a Python function `def generate_transformation_matrix(camera_position, look_at, camera_up_direction)` to sol... | r"""Generate transformation matrix for given camera parameters. Formula is :math:`\text{P_cam} = \text{P_world} * \text{transformation_mtx}`, with :math:`\text{P_world}` being the points coordinates padded with 1. Args: camera_position (torch.FloatTensor): camera positions of shape :math:`(\text{batch_size}, 3)`, it me... |
4,635 | from __future__ import division
import torch
import torch.nn
from numpy import tan
The provided code snippet includes necessary dependencies for implementing the `perspective_camera` function. Write a Python function `def perspective_camera(points, camera_proj)` to solve the following problem:
r"""Projects 3D points o... | r"""Projects 3D points on 2D images in perspective projection mode. Args: points (torch.FloatTensor): 3D points in camera coordinate, of shape :math:`(\text{batch_size}, \text{num_points}, 3)`. camera_proj (torch.FloatTensor): projection matrix of shape :math:`(3, 1)`. Returns: (torch.FloatTensor): 2D points on image p... |
4,636 | from __future__ import division
import torch
import torch.nn
from numpy import tan
The provided code snippet includes necessary dependencies for implementing the `generate_perspective_projection` function. Write a Python function `def generate_perspective_projection(fovyangle, ratio... | r"""Generate perspective projection matrix for a given camera fovy angle. Args: fovyangle (float): field of view angle of y axis, :math:`tan(\frac{fovy}{2}) = \frac{y}{f}`. ratio (float): aspect ratio :math:`(\frac{width}{height})`. Default: 1.0. Returns: (torch.FloatTensor): camera projection matrix, of shape :math:`(... |
4,637 | import torch
The provided code snippet includes necessary dependencies for implementing the `blender_coords` function. Write a Python function `def blender_coords()` to solve the following problem:
Blender world coordinates are right handed, with the z axis pointing upwards :: Z Y ^ / | / |---------> X
Here is the fu... | Blender world coordinates are right handed, with the z axis pointing upwards :: Z Y ^ / | / |---------> X |
4,638 | import torch
The provided code snippet includes necessary dependencies for implementing the `opengl_coords` function. Write a Python function `def opengl_coords()` to solve the following problem:
Contemporary OpenGL doesn't enforce specific handedness on world coordinates. However it is common standard to define OpenG... | Contemporary OpenGL doesn't enforce specific handedness on world coordinates. However it is common standard to define OpenGL world coordinates as right handed, with the y axis pointing upwards (cartesian):: Y ^ | |---------> X / Z |
4,639 | from __future__ import annotations
import functools
from copy import deepcopy
import torch
import inspect
from typing import Sequence, List, Dict, Union, Tuple, Type, FrozenSet, Callable
from torch.types import _float, _bool
from .extrinsics import CameraExtrinsics, ExtrinsicsParamsDefEnum
from .intrinsics import Camer... | Registers a torch function override for Camera |
4,640 | from __future__ import annotations
import functools
from copy import deepcopy
import torch
import inspect
from typing import Sequence, List, Dict, Union, Tuple, Type, FrozenSet, Callable
from torch.types import _float, _bool
from .extrinsics import CameraExtrinsics, ExtrinsicsParamsDefEnum
from .intrinsics import Camer... | r"""Given a variable list of camera modules, returns a mapping of their constructors, used to disambiguate which ctor should be called according to kwargs. The mapping can be used to disambiguate which ctor should be called according to kwargs. Args: *cam_modules (CameraModuleType): A variable list of CameraExtrinsics ... |
4,641 | from __future__ import annotations
import functools
from copy import deepcopy
import torch
import inspect
from typing import Sequence, List, Dict, Union, Tuple, Type, FrozenSet, Callable
from torch.types import _float, _bool
from .extrinsics import CameraExtrinsics, ExtrinsicsParamsDefEnum
from .intrinsics import Camer... | This function checks if the camera extrinsics and intrinsics, are close using :func:`torch.allclose`. Args: input (Camera): first camera to compare other (Camera): second camera to compare atol (float, optional): absolute tolerance. Default: 1e-08 rtol (float, optional): relative tolerance. Default: 1e-05 equal_nan (bo... |
4,642 | from __future__ import annotations
from typing import Union, Tuple, Iterable, Sequence, List, Dict
import functools
import numpy as np
import torch
from torch.types import _float, _bool
from . import extrinsics_backends
from .extrinsics_backends import ExtrinsicsParamsDefEnum, ExtrinsicsRep, _REGISTERED_BACKENDS
_HANDL... | Registers a torch function override for CameraExtrinsics |
4,643 | from __future__ import annotations
from typing import Union, Tuple, Iterable, Sequence, List, Dict
import functools
import numpy as np
import torch
from torch.types import _float, _bool
from . import extrinsics_backends
from .extrinsics_backends import ExtrinsicsParamsDefEnum, ExtrinsicsRep, _REGISTERED_BACKENDS
The p... | Registers a representation backend class with a unique name. CameraExtrinsics can switch between registered representations dynamically (see :func:`switch_backend()`). |
4,644 | from __future__ import annotations
from typing import Union, Tuple, Iterable, Sequence, List, Dict
import functools
import numpy as np
import torch
from torch.types import _float, _bool
from . import extrinsics_backends
from .extrinsics_backends import ExtrinsicsParamsDefEnum, ExtrinsicsRep, _REGISTERED_BACKENDS
class ... | :func:`torch.allclose` compatibility implementation for CameraExtrinsics. Args: input (Camera): first camera to compare other (Camera): second camera to compare atol (float, optional): absolute tolerance. Default: 1e-08 rtol (float, optional): relative tolerance. Default: 1e-05 equal_nan (bool, optional): if ``True``, ... |
4,645 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Type, Union
from enum import IntEnum
import warnings
import torch
_REGISTERED_BACKENDS = dict()
class ExtrinsicsRep(ABC):
"""
An abstract class for representing CameraExtrinsics representation backends.
This clas... | Registers a representation backend class with a unique name. CameraExtrinsics can switch between registered representations dynamically (see switch_backend()). |
4,646 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Type, Dict, List, Union, Sequence
from enum import IntEnum
import functools
import copy
import torch
from torch.types import _float, _bool
_HANDLED_TORCH_FUNCTIONS = dict()
The provided code snippet includes necessary dependencie... | Registers a torch function override for CameraIntrinsics |
4,647 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Type, Dict, List, Union, Sequence
from enum import IntEnum
import functools
import copy
import torch
from torch.types import _float, _bool
The provided code snippet includes necessary dependencies for implementing the `up_to_homo... | Up-projects vectors to homogeneous coordinates of four dimensions. If the vectors are already in homogeneous coordinates, this function return the inputs. Args: vectors (torch.Tensor): the inputs vectors to project, of shape :math:`(..., 3)` Returns: (torch.Tensor): The projected vectors, of same shape than inputs but ... |
4,648 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Type, Dict, List, Union, Sequence
from enum import IntEnum
import functools
import copy
import torch
from torch.types import _float, _bool
The provided code snippet includes necessary dependencies for implementing the `down_from_... | (1) Performs perspective division by dividing each vector by its w coordinate. (2) Down-projects vectors from 4D homogeneous space to 3D space. Args: homogenenous_vectors: the inputs vectors, of shape :math:`(..., 4)` Returns: (torch.Tensor): the 3D vectors, of same shape than inputs but last dim to be 3 |
4,649 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Type, Dict, List, Union, Sequence
from enum import IntEnum
import functools
import copy
import torch
from torch.types import _float, _bool
class CameraIntrinsics(ABC):
r"""Holds the intrinsics parameters of a camera: how it sh... | :func:`torch.allclose` compatibility implementation for CameraIntrinsics. Args: input (Camera): first camera to compare other (Camera): second camera to compare atol (float, optional): absolute tolerance. Default: 1e-08 rtol (float, optional): relative tolerance. Default: 1e-05 equal_nan (bool, optional): if ``True``, ... |
4,650 | import warnings
from kaolin import _C
import torch
The provided code snippet includes necessary dependencies for implementing the `unbatched_raytrace` function. Write a Python function `def unbatched_raytrace(octree, point_hierarchy, pyramid, exsum, origin, direction, level, return_depth=True, w... | r"""Apply ray tracing over an unbatched SPC structure. The SPC model will be always normalized between -1 and 1 for each axis. Args: octree (torch.ByteTensor): the octree structure, of shape :math:`(\text{num_bytes})`. point_hierarchy (torch.ShortTensor): the point hierarchy associated to the octree, of shape :math:`(\... |
4,651 | import warnings
from kaolin import _C
import torch
def mark_pack_boundaries(pack_ids):
r"""Mark the boundaries of pack IDs.
Pack IDs are sorted tensors which mark the ID of the pack each element belongs in.
For example, the SPC ray trace kernel will return the ray index tensor which marks the ID of the ray
... | r"""Mark the first hit in the nuggets. .. deprecated:: 0.10.0 This function is deprecated. Use :func:`mark_pack_boundaries`. The nuggets are a packed tensor containing correspondences from ray index to point index, sorted within each ray pack by depth. This will mark true for each first hit (by depth) for a pack of nug... |
4,652 | import warnings
from kaolin import _C
import torch
The provided code snippet includes necessary dependencies for implementing the `diff` function. Write a Python function `def diff(feats, boundaries)` to solve the following problem:
r"""Find the delta between each of the features in a pack. The deltas are given by `ou... | r"""Find the delta between each of the features in a pack. The deltas are given by `out[i] = feats[i+1] - feats[i]` The behavior is similar to :func:`torch.diff` for non-packed tensors, but :func:`torch.diff` will reduce the number of features by 1. This function will instead populate the last diff with 0. Args: feats ... |
4,653 | import warnings
from kaolin import _C
import torch
class Cumprod(torch.autograd.Function):
def forward(ctx, feats, info, exclusive, reverse):
nonzero = torch.nonzero(info).int().contiguous()[..., 0]
prod = _C.render.spc.cumprod_cuda(feats, nonzero, exclusive, reverse)
ctx.save_for_backward(f... | r"""Cumulative product across packs of features. This function is similar to :func:`tf.math.cumprod` with the same options, but for packed tensors. Refer to the TensorFlow docs for numerical examples of the options. Note that the backward gradient follows the same behaviour in TensorFlow, which is to replace NaNs by ze... |
4,654 | import warnings
from kaolin import _C
import torch
def sum_reduce(feats, boundaries):
r"""Sum the features of packs.
Args:
feats (torch.FloatTensor): features of shape :math:`(\text{num_rays}, \text{num_feats})`.
boundaries (torch.BoolTensor): bools to mark pack boundaries of shape :math:`(\text... | r"""Exponential transmittance integration across packs using the optical thickness (tau). Exponential transmittance is derived from the Beer-Lambert law. Typical implementations of exponential transmittance is calculated with :func:`cumprod`, but the exponential allows a reformulation as a :func:`cumsum` which its grad... |
4,655 | import torch
from kaolin import _C
def get_shape_per_tensor(tensor_list):
r"""Returns the shape of each tensor in the tensor list except the last dimension.
See shape_per_tensor for :ref:`packed<packed_shape_per_tensor>` or :ref:`padded<padded_shape_per_tensor>`
for more information.
Args:
tenso... | r"""Converts a sequence of torch.Tensor into a single :ref:`packed tensor<packed>`. torch.Tensor of same type, number of dimensions and last dimension size will be reshaped to :math:`(-1, \text{last_dim})` and concatenated on first axis. E.g.: With input of shapes :math:`[(X_0, Y_0, Z_0, C), (X_1, Y_1, Z_1, C)]` the ou... |
4,656 | import torch
from kaolin import _C
The provided code snippet includes necessary dependencies for implementing the `packed_to_list` function. Write a Python function `def packed_to_list(packed_tensor, shape_per_tensor, first_idx)` to solve the following problem:
Converts a single packed tensor into a sequence of torch.... | Converts a single packed tensor into a sequence of torch.Tensor. Args: packed_tensor (torch.Tensor): input packed tensor. shape_per_tensor (torch.LongTensor): :ref:`shape_per_tensor<packed_shape_per_tensor>` associated to the packed tensor. first_idx (torch.LongTensor): :ref:`first_idx<packed_first_idx>` associated to ... |
4,657 | import torch
from kaolin import _C
def get_shape_per_tensor(tensor_list):
r"""Returns the shape of each tensor in the tensor list except the last dimension.
See shape_per_tensor for :ref:`packed<packed_shape_per_tensor>` or :ref:`padded<padded_shape_per_tensor>`
for more information.
Args:
tenso... | r"""Converts a sequence of torch.Tensor into a single :ref:`padded tensor<padded>`. torch.Tensor of same type, number of dimensions and last dimension size will be padded and stacked on first axis. E.g.: With input of shapes :math:`[(X_0, Y_0, Z_0, C), (X_1, Y_1, Z_1, C)]` the output padded tensor will be of shape :mat... |
4,658 | import torch
from kaolin import _C
def padded_to_list(padded_tensor, shape_per_tensor):
"""Converts a single padded tensor into a sequence of torch.Tensor.
Args:
padded_tensor (torch.Tensor): a :ref:`padded tensor<padded>`.
shape_per_tensor (torch.LongTensor): the :ref:`shape_per_tensor<padded_s... | Converts a single padded tensor into a packed tensor. Args: padded_tensor (torch.Tensor): a :ref:`padded tensor<padded>`. shape_per_tensor (torch.LongTensor): the :ref:`shape_per_tensor<padded_shape_per_tensor>` tensor associated to the padded tensor. Returns: (torch.Tensor): the :ref:`packed tensor<packed>`. |
4,659 | from __future__ import division
import torch
The provided code snippet includes necessary dependencies for implementing the `spherical2cartesian` function. Write a Python function `def spherical2cartesian(azimuth, elevation, distance=None)` to solve the following problem:
Convert spherical coordinates to cartesian. As... | Convert spherical coordinates to cartesian. Assuming X toward camera, Z-up and Y-right. Args: azimuth (torch.Tensor): azimuth in radianss. elevation (torch.Tensor): elevation in radians. distance (torch.Tensor or float, optional): distance. Default: 1. Returns: (torch.Tensor, torch.Tensor, torch.Tensor): x, y, z, of sa... |
4,660 | from __future__ import division
import torch
The provided code snippet includes necessary dependencies for implementing the `cartesian2spherical` function. Write a Python function `def cartesian2spherical(x, y, z)` to solve the following problem:
Convert cartersian coordinates to spherical in radians. Assuming X towar... | Convert cartersian coordinates to spherical in radians. Assuming X toward camera, Z-up and Y-right. Args: x (torch.Tensor): X components of the coordinates. y (torch.Tensor): Y components of the coordinates. z (torch.Tensor): Z components of the coordinates. Returns: (torch.Tensor, torch.Tensor, torch.Tensor): azimuth,... |
4,661 | import numpy as np
import torch
from . import triangle_hash
from kaolin import _C
def _unbatched_check_sign_cuda(verts, faces, points):
n, _ = points.size()
points = points.contiguous()
v1 = torch.index_select(verts, 0, faces[:, 0]).view(-1, 3).contiguous()
v2 = torch.index_select(verts, 0, faces[:, 1])... | r"""Checks if a set of points is contained inside a watertight triangle mesh. Shoots a ray from each point to be checked and calculates the number of intersections between the ray and triangles in the mesh. Uses the parity of the number of intersections to determine if the point is inside the mesh. Args: verts (torch.T... |
4,662 | import torch
The provided code snippet includes necessary dependencies for implementing the `index_vertices_by_faces` function. Write a Python function `def index_vertices_by_faces(vertices_features, faces)` to solve the following problem:
r"""Index vertex features to convert per vertex tensor to per vertex per face t... | r"""Index vertex features to convert per vertex tensor to per vertex per face tensor. Args: vertices_features (torch.FloatTensor): vertices features, of shape :math:`(\text{batch_size}, \text{num_points}, \text{knum})`, ``knum`` is feature dimension, the features could be xyz position, rgb color, or even neural network... |
4,663 | import torch
def adjacency_matrix(num_vertices, faces, sparse=True):
r"""Calculates a adjacency matrix of a mesh.
Args:
num_vertices (int): Number of vertices of the mesh.
faces (torch.LongTensor):
Faces of shape :math:`(\text{num_faces}, \text{face_size})` of the mesh.
spars... | r"""Calculates the uniform laplacian of a mesh. :math:`L[i, j] = \frac{1}{num\_neighbours(i)}` if i, j are neighbours. :math:`L[i, j] = -1` if i == j. :math:`L[i, j] = 0` otherwise. Args: num_vertices (int): Number of vertices for the mesh. faces (torch.LongTensor): Faces of shape :math:`(\text{num_faces}, \text{face_s... |
4,664 | import torch
The provided code snippet includes necessary dependencies for implementing the `compute_vertex_normals` function. Write a Python function `def compute_vertex_normals(faces, face_normals, num_vertices=None)` to solve the following problem:
r"""Computes normals for every vertex by averaging face normals ass... | r"""Computes normals for every vertex by averaging face normals assigned to that vertex for every face that has this vertex. Args: faces (torch.LongTensor): vertex indices of faces of a fixed-topology mesh batch with shape :math:`(\text{num_faces}, \text{face_size})`. face_normals (torch.FloatTensor): pre-normalized xy... |
4,665 | import math
import torch
from ..batch import tile_to_packed, packed_to_padded, get_first_idx
def _base_face_areas(face_vertices_0, face_vertices_1, face_vertices_2):
"""Base function to compute the face areas."""
x1, x2, x3 = torch.split(face_vertices_0 - face_vertices_1, 1, dim=-1)
y1, y2, y3 = torch.split... | Compute the areas of each face of triangle meshes. Args: vertices (torch.Tensor): The vertices of the meshes, of shape :math:`(\\text{batch_size}, \\text{num_vertices}, 3)`. faces (torch.LongTensor): the faces of the meshes, of shape :math:`(\\text{num_faces}, 3)`. Returns: (torch.Tensor): the face areas of same type a... |
4,666 | import math
import torch
from ..batch import tile_to_packed, packed_to_padded, get_first_idx
def _base_face_areas(face_vertices_0, face_vertices_1, face_vertices_2):
"""Base function to compute the face areas."""
x1, x2, x3 = torch.split(face_vertices_0 - face_vertices_1, 1, dim=-1)
y1, y2, y3 = torch.split... | Compute the areas of each face of triangle meshes. Args: vertices (torch.Tensor): The packed vertices of the meshes, of shape :math:`(\\text{num_vertices}, 3)`. first_idx_vertices (torch.Tensor): The :ref:`first_idx<packed_first_idx>` associated to vertices, of shape :math:`(\\text{batch_size})`. faces (torch.LongTenso... |
4,667 | import math
import torch
from ..batch import tile_to_packed, packed_to_padded, get_first_idx
def _base_face_areas(face_vertices_0, face_vertices_1, face_vertices_2):
"""Base function to compute the face areas."""
x1, x2, x3 = torch.split(face_vertices_0 - face_vertices_1, 1, dim=-1)
y1, y2, y3 = torch.split... | r"""Uniformly sample points over the surface of triangle meshes. First face on which the point is sampled is randomly selected, with the probability of selection being proportional to the area of the face. then the coordinate on the face is uniformly sampled. If ``face_features`` is defined for the mesh faces, the samp... |
4,668 | import math
import torch
from ..batch import tile_to_packed, packed_to_padded, get_first_idx
def _base_face_areas(face_vertices_0, face_vertices_1, face_vertices_2):
"""Base function to compute the face areas."""
x1, x2, x3 = torch.split(face_vertices_0 - face_vertices_1, 1, dim=-1)
y1, y2, y3 = torch.split... | r"""Uniformly sample points over the surface of triangle meshes. First face on which the point is sampled is randomly selected, with the probability of selection being proportional to the area of the face. then the coordinate on the face is uniformly sampled. The return pointclouds are with fixed batching. Args: vertic... |
4,669 | import math
import torch
from ..batch import tile_to_packed, packed_to_padded, get_first_idx
The provided code snippet includes necessary dependencies for implementing the `face_normals` function. Write a Python function `def face_normals(face_vertices, unit=False)` to solve the following problem:
r"""Calculate normal... | r"""Calculate normals of triangle meshes. Left-hand rule convention is used for picking normal direction. Args: face_vertices (torch.Tensor): of shape :math:`(\text{batch_size}, \text{num_faces}, 3, 3)`. unit (bool): if true, return normals as unit vectors. Default: False. Returns: (torch.FloatTensor): face normals, of... |
4,670 | import math
import torch
from ..batch import tile_to_packed, packed_to_padded, get_first_idx
def _get_adj_verts(edges_ex2, v):
"""Get sparse adjacency matrix for vertices given edges"""
adj_sparse_idx = torch.cat([edges_ex2, torch.flip(edges_ex2, [1])])
adj_sparse_idx = torch.unique(adj_sparse_idx, dim=0)
... | r"""Subdivide triangular meshes following the scheme of Loop subdivision proposed in `Smooth Subdivision Surfaces Based on Triangles`_. If the smoothing factor alpha is not given, this function performs exactly as Loop subdivision. Elsewise the vertex position is updated using the given per-vertex alpha value, which is... |
4,671 | import math
import torch
from ..batch import tile_to_packed, packed_to_padded, get_first_idx
The provided code snippet includes necessary dependencies for implementing the `vertex_tangents` function. Write a Python function `def vertex_tangents(faces, face_vertices, face_uvs, vertex_normals)` to solve the following pr... | r"""Compute vertex tangents. The vertex tangents are useful to apply normal maps during rendering. .. seealso:: https://en.wikipedia.org/wiki/Normal_mapping#Calculating_tangent_space Args: faces (torch.LongTensor): unbatched triangle mesh faces, of shape :math:`(\text{num_faces}, 3)`. face_vertices (torch.Tensor): unba... |
4,672 | import torch
from kaolin.ops.conversions.tetmesh import _sort_edges
def _validate_tet_vertices(tet_vertices):
r"""Helper method to validate the dimensions of the batched tetrahedrons tensor.
Args:
tet_vertices (torch.Tensor):
Batched tetrahedrons, of shape
:math:`(\text{batch_siz... | r"""Given tetrahedrons with 4 vertices A, B, C, D. Compute the inverse of the offset matrix w.r.t. vertex A for each tetrahedron. The offset matrix is obtained by the concatenation of :math:`B - A`, :math:`C - A` and :math:`D - A`. The resulting shape of the offset matrix is :math:`(\text{batch_size}, \text{num_tetrahe... |
4,673 | import torch
from kaolin.ops.conversions.tetmesh import _sort_edges
base_tet_edges = torch.tensor([0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3], dtype=torch.long)
def _sort_edges(edges):
"""sort last dimension of edges of shape (E, 2)"""
with torch.no_grad():
order = (edges[:, 0] > edges[:, 1]).long()
o... | r"""Subdivide each tetrahedron in tetmesh into 8 smaller tetrahedrons by adding midpoints. If per-vertex features (e.g. SDF value) are given, the features of the new vertices are computed by averaging the features of vertices on the edge. For more details and example usage in learning, see `Deep Marching Tetrahedra\: a... |
4,674 | from __future__ import annotations
import torch
The provided code snippet includes necessary dependencies for implementing the `center_points` function. Write a Python function `def center_points(points: torch.FloatTensor, normalize: bool = False, eps=1e-6)` to solve the following problem:
r"""Returns points centered ... | r"""Returns points centered at the origin for every pointcloud. If `normalize` is set, will also normalize each point cloud spearately to the range of [-0.5, 0.5]. Note that each point cloud is centered individually. Args: points (torch.FloatTensor): point clouds of shape :math:`(\text{batch_size}, \text{num_points}, 3... |
4,675 | import torch
from torch import nn
The provided code snippet includes necessary dependencies for implementing the `sparse_bmm` function. Write a Python function `def sparse_bmm(sparse_matrix, dense_matrix_batch)` to solve the following problem:
r"""Perform torch.bmm on an unbatched sparse matrix and a batched dense mat... | r"""Perform torch.bmm on an unbatched sparse matrix and a batched dense matrix. Args: sparse_matrix (torch.sparse.FloatTensor): Input sparse matrix, of shape :math:`(\text{M}, \text{N})`. dense_matrix_batch (torch.FloatTensor): Input batched dense matrix, of shape :math:`(\text{batch_size}, \text{N}, \text{P})`. Return... |
4,676 | import torch
from torch import nn
The provided code snippet includes necessary dependencies for implementing the `normalize_adj` function. Write a Python function `def normalize_adj(adj)` to solve the following problem:
r"""Normalize the adjacency matrix such that the sum of each row is 1. This operation is slow, so i... | r"""Normalize the adjacency matrix such that the sum of each row is 1. This operation is slow, so it should be done only once for a graph and then reused. This supports both sparse tensor and regular tensor. The return type will be the same as the input type. For example, if the input is a sparse tensor, the normalized... |
4,677 | import random
import math
import numpy as np
import torch
from .spc.uint8 import uint8_to_bits
import random
The provided code snippet includes necessary dependencies for implementing the `manual_seed` function. Write a Python function `def manual_seed(torch_seed, random_seed=None, numpy_seed=None)` to solve the foll... | Set the seed for random and torch modules. Args: torch_seed (int): The desired seed for torch module. random_seed (int): The desired seed for random module. Default: ``torch_seed`` value. numpy_seed (int): The desired seed for numpy module. Default: ``torch_seed`` value. |
4,678 | import random
import math
import numpy as np
import torch
from .spc.uint8 import uint8_to_bits
import random
The provided code snippet includes necessary dependencies for implementing the `set_state` function. Write a Python function `def set_state(torch_state, random_state, numpy_state)` to solve the following probl... | Set the generator states for generating random numbers. Mostly used in pair with :func:`get_state` Args: torch_state (torch.ByteTensor): the state of torch module. random_state (tuple): the state of random module. numpy_state (tuple): the state of numpy module. Example: >>> torch_state, random_state, numpy_state = get_... |
4,679 | import random
import math
import numpy as np
import torch
from .spc.uint8 import uint8_to_bits
import random
The provided code snippet includes necessary dependencies for implementing the `get_state` function. Write a Python function `def get_state()` to solve the following problem:
Returns the generator states for g... | Returns the generator states for generating random numbers. Mostly used in pair with :func:`set_state`. See also: * https://pytorch.org/docs/stable/generated/torch.get_rng_state.html#torch.get_rng_state * https://docs.python.org/3/library/random.html#random.getstate * https://numpy.org/doc/stable/reference/random/gener... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.