id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
22,926 | from . import *
def build_scenario(builder):
builder.config().game_duration = 3000
builder.config().right_team_difficulty = 0.95
builder.config().deterministic = False
if builder.EpisodeNumber() % 2 == 0:
first_team = Team.e_Left
second_team = Team.e_Right
else:
first_team = Team.e_Right
seco... | null |
22,927 | from . import *
def build_scenario(builder):
builder.config().game_duration = 3000
builder.config().right_team_difficulty = 1.0
builder.config().left_team_difficulty = 1.0
builder.config().deterministic = False
if builder.EpisodeNumber() % 2 == 0:
first_team = Team.e_Left
second_team = Team.e_Right
... | null |
22,928 | from . import *
def build_scenario(builder):
builder.config().game_duration = 3000
builder.config().right_team_difficulty = 0.05
builder.config().left_team_difficulty = 0.05
builder.config().deterministic = False
if builder.EpisodeNumber() % 2 == 0:
first_team = Team.e_Left
second_team = Team.e_Right... | null |
22,929 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
22,930 | from . import *
episode = 0
def build_scenario(builder):
global episode
episode += 1
builder.config().game_duration = 3000
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.con... | null |
22,931 | from . import *
def build_scenario(builder):
builder.config().game_duration = 3000
builder.config().right_team_difficulty = 0.6
builder.config().deterministic = False
if builder.EpisodeNumber() % 2 == 0:
first_team = Team.e_Left
second_team = Team.e_Right
else:
first_team = Team.e_Right
secon... | null |
22,932 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
22,933 | from baselines.common.models import register
import sonnet as snt
import tensorflow.compat.v1 as tf
def gfootball_impala_cnn():
def network_fn(frame):
# Convert to floats.
frame = tf.to_float(frame)
frame /= 255
with tf.variable_scope('convnet'):
conv_out = frame
conv_layers = [(16, 2), (... | null |
22,934 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import argparse
import gfootball.env as football_env
import gym
import ray
from ray import tune
from ray.rllib.env.multi_agent_env import MultiAgentEnv
from ray.tune.registry import reg... | null |
22,935 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import multiprocessing
import os
from absl import app
from absl import flags
from baselines import logger
from baselines.bench import monitor
from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv
fr... | Trains a PPO2 policy. |
22,936 | import random
import string
import time
import urllib.request
from gfootball.eval_server import config
import grpc
def get_grpc_channel(server):
# send keepalive ping every 10 second
# allow unlimited amount of keepalive pings
options = (('grpc.keepalive_time_ms', 10000),
('grpc.http2.max_pings_with... | null |
22,937 | import random
import string
import time
import urllib.request
from gfootball.eval_server import config
import grpc
def get_random_string(length=10, append_timestamp=True):
characters = string.ascii_lowercase + string.ascii_uppercase + string.digits
res = ''.join(random.choice(characters) for i in range(length))
i... | null |
22,938 | import grpc
from gfootball.eval_server.proto import master_pb2 as gfootball_dot_eval__server_dot_proto_dot_master__pb2
def add_MasterServicer_to_server(servicer, server):
rpc_method_handlers = {
'StartGame': grpc.unary_unary_rpc_method_handler(
servicer.StartGame,
request_deserializer=gfoot... | null |
22,939 | import grpc
from gfootball.eval_server.proto import game_server_pb2 as gfootball_dot_eval__server_dot_proto_dot_game__server__pb2
def add_GameServerServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetEnvResult': grpc.unary_unary_rpc_method_handler(
servicer.GetEnvResult,
reque... | null |
22,940 | import random
from absl import app
from absl import flags
from absl import logging
import gfootball.env as football_env
from gfootball.env import football_action_set
import grpc
import numpy as np
import tensorflow.compat.v2 as tf
FLAGS = flags.FLAGS
def random_actions(obs):
num_players = 1 if len(obs.shape) == 3 els... | null |
22,941 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from gfootball_engine import e_BackendAction
import numpy
from six.moves import range
action_left = CoreAction(
e_BackendAction.left, "left", sticky=True, directional=True)
action_release_direction = CoreAct... | null |
22,942 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from gfootball.env import football_action_set
import numpy as np
def rotate_3d_point(point):
"""Rotate 3d point around the center of the field.
Args:
points: [x, y, z] point.
Returns:
The rotated ... | Observation corresponding to the field rotated by 180 degrees. |
22,943 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from gfootball.env import football_action_set
import numpy as np
def flip_single_action(action, config):
def flip_action(action, config):
if isinstance(action, np.ndarray) or isinstance(action, list):
ret... | null |
22,944 | import pygame
_controllers = []
def add_controller(controller_kind, controller_index=None):
global _controllers
_controllers.append((controller_kind, controller_index)) | null |
22,945 | import pygame
_queue = []
_controllers = []
def fits(event, controller_kind, controller_index):
if controller_kind == 'keyboard':
return event.type in KEYBOARD_EVENTS
if controller_kind == 'gamepad':
return event.type in GAMEPAD_EVENTS and event.joy == controller_index
assert False, 'Unknown controller ki... | null |
22,946 | from __future__ import print_function
import copy
import tempfile
import os
import platform
from absl import flags
import gfootball_engine as libgame
def parse_player_definition(definition):
"""Parses player definition.
An example of player definition is: "agent:players=4" or "replay:path=...".
Args:
definiti... | Returns a number of left players given a definition. |
22,947 | from __future__ import print_function
import copy
import tempfile
import os
import platform
from absl import flags
import gfootball_engine as libgame
def parse_player_definition(definition):
"""Parses player definition.
An example of player definition is: "agent:players=4" or "replay:path=...".
Args:
definiti... | Returns a number of players given a definition. |
22,948 | from __future__ import print_function
import copy
import tempfile
import os
import platform
from absl import flags
import gfootball_engine as libgame
def count_players(definition):
"""Returns a number of players given a definition."""
_, player_definition = parse_player_definition(definition)
return (int(player_d... | Returns a total number of players controlled by an agent. |
22,949 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from gfootball.env import football_action_set
import numpy as np
from six.moves import range
SMM_WIDTH = 96
SMM_HEIGHT = 72
def get_smm_layers(config):
return SMM_LAYERS
def mark_points(frame, points):
"""Dr... | Returns a list of minimap observations given the raw features for each active player. Args: observation: raw features from the environment config: environment config channel_dimensions: resolution of SMM to generate Returns: (N, H, W, C) - shaped np array representing SMM. N stands for the number of players we are cont... |
22,950 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import datetime
import os
import shutil
import tempfile
import timeit
import traceback
from absl import logging
from gfootball.env import constants as const
from gfootball.env import football_... | null |
22,951 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import datetime
import os
import shutil
import tempfile
import timeit
import traceback
from absl import logging
from gfootball.env import constants as const
from gfootball.env import football_... | null |
22,952 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import datetime
import os
import shutil
import tempfile
import timeit
import traceback
from absl import logging
from gfootball.env import constants as const
from gfootball.env import football_... | null |
22,953 | import importlib
import os
import pkgutil
import random
import sys
from absl import flags
from absl import logging
import gfootball_engine as libgame
def all_scenarios():
path = os.path.abspath(__file__)
path = os.path.join(os.path.dirname(os.path.dirname(path)), 'scenarios')
scenarios = []
for m in pkgutil.it... | null |
22,954 | from baselines.common.policies import build_policy
from gfootball.env import football_action_set
from gfootball.env import observation_preprocessing
from gfootball.env import player_base
from gfootball.examples import models
import gym
import joblib
import numpy as np
import tensorflow.compat.v1 as tf
The provided c... | Loads variables from checkpoint of policy trained by baselines. |
22,955 | import torch
from thop import profile
import torchvision
import models
import argparse
def clever_format(nums, format="%.2f"):
clever_nums = []
for num in nums:
if num > 1e12:
clever_nums.append(format % (num / 1024 ** 4) + "T")
elif num > 1e9:
clever_nums.append(format... | null |
22,956 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | null |
22,957 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | null |
22,958 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | null |
22,959 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | Sets the learning rate to the initial LR decayed by 10 every 30 epochs |
22,960 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | null |
22,961 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | null |
22,962 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | null |
22,963 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | null |
22,964 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | Sets the learning rate to the initial LR decayed by 10 every 30 epochs |
22,965 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms... | null |
22,966 | from torch import nn
from .eca_module import eca_layer
class ECA_MobileNetV2(nn.Module):
def __init__(self, num_classes=1000, width_mult=1.0):
super(ECA_MobileNetV2, self).__init__()
block = InvertedResidual
input_channel = 32
last_channel = 1280
inverted_residual_setting = [... | Constructs a ECA_MobileNetV2 architecture from Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr |
22,967 | import torch.nn as nn
import math
from .eca_module import eca_layer
The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem:
3x3 convolution with padding
Here is the functio... | 3x3 convolution with padding |
22,968 | import torch.nn as nn
import math
from .eca_module import eca_layer
class ECABasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, k_size=3):
super(ECABasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.... | Constructs a ResNet-18 model. Args: k_size: Adaptive selection of kernel size pretrained (bool): If True, returns a model pre-trained on ImageNet num_classes:The classes of classification |
22,969 | import torch.nn as nn
import math
from .eca_module import eca_layer
class ECABasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, k_size=3):
super(ECABasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.... | Constructs a ResNet-34 model. Args: k_size: Adaptive selection of kernel size pretrained (bool): If True, returns a model pre-trained on ImageNet num_classes:The classes of classification |
22,970 | import torch.nn as nn
import math
from .eca_module import eca_layer
class ECABottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, k_size=3):
super(ECABottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
... | Constructs a ResNet-50 model. Args: k_size: Adaptive selection of kernel size num_classes:The classes of classification pretrained (bool): If True, returns a model pre-trained on ImageNet |
22,971 | import torch.nn as nn
import math
from .eca_module import eca_layer
class ECABottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, k_size=3):
super(ECABottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
... | Constructs a ResNet-101 model. Args: k_size: Adaptive selection of kernel size num_classes:The classes of classification pretrained (bool): If True, returns a model pre-trained on ImageNet |
22,972 | import torch.nn as nn
import math
from .eca_module import eca_layer
class ECABottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, k_size=3):
super(ECABottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
... | Constructs a ResNet-152 model. Args: k_size: Adaptive selection of kernel size num_classes:The classes of classification pretrained (bool): If True, returns a model pre-trained on ImageNet |
22,973 | import os
import sys
from setuptools import setup, find_packages, dist
import glob
import logging
import subprocess
import torch
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
def get_cuda_bare_metal_version(cuda_dir):
raw_output = subprocess.check_output([cuda_dir + "... | null |
22,974 | import os
import sys
from setuptools import setup, find_packages, dist
import glob
import logging
import subprocess
import torch
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME
if not torch.cuda.is_available():
if os.getenv('FORCE_CUDA', '0') == '1':
# From: http... | null |
22,975 | import os
def setup(app):
# -- To demonstrate ReadTheDocs switcher -------------------------------------
# This links a few JS and CSS files that mimic the environment that RTD uses
# so that we can test RTD-like behavior. We don't need to run it on RTD and we
# don't want it loaded in GitHub Actions
... | null |
22,976 | import numpy as np
import torch
import pathlib
import argparse
from kaolin.io.obj import import_mesh
from kaolin.ops.mesh import sample_points
from kaolin.render.mesh.utils import texture_mapping
from kaolin.ops.conversions.pointcloud import unbatched_pointcloud_to_spc
def convert_texture_to_torch_sample_format(texture... | Loads obj and converts it to a SPC. Output will reside in output_path. |
22,977 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `identity` function. Write a Python function `def identity(c: torch.Tensor) -> torch.Tensor` to solve the following problem:
A ... | A naive normalization function which assumes the value is already normalized and returned as is. Args: c (torch.Tensor): A single channel tensor of an arbitrary shape. Returns: (torch.Tensor): Input channel c is returned without a change. |
22,978 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
def normalize(c: torch.Tensor, min_val: Any = None, max_val: Any = None) -> torch.Tensor:
""" A linear normalization function which maps the channel c to the range of [0, 1].
If the min / max values ... | A normalization function which linear scales the channel before normalizing it to the range of [0, 1]. If the min / max values bounds of the channel are not explicitly specified, they're determined by c's values. If explicitly specified, the bounds are scaled as well. Args: c (torch.Tensor): A single channel tensor of ... |
22,979 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
def normalize(c: torch.Tensor, min_val: Any = None, max_val: Any = None) -> torch.Tensor:
""" A linear normalization function which maps the channel c to the range of [0, 1].
If the min / max values ... | A normalization function which applies log and linear scales to the channel before normalizing it to the range of [0, 1]. If the min / max values bounds of the channel are not explicitly specified, they're determined by c's values. If explicitly specified, the bounds are scaled as well. Args: c (torch.Tensor): A single... |
22,980 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
def normalize(c: torch.Tensor, min_val: Any = None, max_val: Any = None) -> torch.Tensor:
""" A linear normalization function which maps the channel c to the range of [0, 1].
If the min / max values ... | A normalization function which applies a L2 normalization over a channel of vector data. Args: c (torch.Tensor): A single channel tensor of an arbitrary shape. Returns: (torch.Tensor): Input channel c is normalized by the L2 norm. |
22,981 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_linear` function. Write a Python function `def blend_linear(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.Tensor, al... | A direct linear interpolation between c1 and c2. Useful for blending channels which do not consider the alpha value (i.e. the alpha channel itself). Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second channel tensor, in the shape of c1. alpha1 (torch.Tensor): Unused alpha2 (to... |
22,982 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_alpha_composite_over` function. Write a Python function `def blend_alpha_composite_over(c1: torch.Tensor, c2: torch.Tens... | An alpha compositing op where a front pixel is alpha blended with the background pixel (in a usual painter's algorithm manner). Useful for blending channels such as RGB. See: https://en.wikipedia.org/wiki/Alpha_compositing Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second ch... |
22,983 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_alpha_lerp` function. Write a Python function `def blend_alpha_lerp(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.Te... | A linear interpolation between c1 and c2, which uses the alpha channel as a weighting factor. Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second channel tensor, in the shape of c1. alpha1 (torch.Tensor): alpha channel tensor, corresponding to first channel, in the shape of c1... |
22,984 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
def normalize(c: torch.Tensor, min_val: Any = None, max_val: Any = None) -> torch.Tensor:
""" A linear normalization function which maps the channel c to the range of [0, 1].
If the min / max values ... | A spherical linear interpolation, useful for interpolating rotations or blending directional vectors. c1 and c2 are normalized and interpolated over the unit hypersphere. alpha1 acts as the interpolation weight. See: https://en.wikipedia.org/wiki/Slerp Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape... |
22,985 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_normal` function. Write a Python function `def blend_normal(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.Tensor, al... | A standard blend mode which uses the front pixel value, without mixing. Useful when alpha blending is undesired, or the channel contains categorical info (i.e. semantic class ids). Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): Unused alpha1 (torch.Tensor): Unused alpha2 (torch.... |
22,986 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_multiply` function. Write a Python function `def blend_multiply(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.Tensor... | Commutative blend mode which preserves dark colors. Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second channel tensor, in the shape of c1. alpha1 (torch.Tensor): Unused. alpha2 (torch.Tensor): Unused. Returns: (torch.Tensor): Blended channel in the shape of c1 |
22,987 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_screen` function. Write a Python function `def blend_screen(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.Tensor, al... | Commutative blend mode which preserves light colors. Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second channel tensor, in the shape of c1. alpha1 (torch.Tensor): Unused. alpha2 (torch.Tensor): Unused. Returns: (torch.Tensor): Blended channel in the shape of c1 |
22,988 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_add` function. Write a Python function `def blend_add(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.Tensor, alpha2: ... | An additive blend mode, for aggregation of channel information. Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second channel tensor, in the shape of c1. alpha1 (torch.Tensor): Unused. alpha2 (torch.Tensor): Unused. Returns: (torch.Tensor): Blended channel in the shape of c1 |
22,989 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_sub` function. Write a Python function `def blend_sub(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.Tensor, alpha2: ... | An subtractive blend mode, for removing channel information. Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second channel tensor, in the shape of c1. alpha1 (torch.Tensor): Unused. alpha2 (torch.Tensor): Unused. Returns: (torch.Tensor): Blended channel in the shape of c1 |
22,990 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_logical_and` function. Write a Python function `def blend_logical_and(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.... | For boolean channels, blends with a logical AND function. Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second channel tensor, in the shape of c1. alpha1 (torch.Tensor): Unused. alpha2 (torch.Tensor): Unused. Returns: (torch.Tensor): Blended channel in the shape of c1 |
22,991 | from __future__ import annotations
from typing import Callable, Any
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `blend_logical_or` function. Write a Python function `def blend_logical_or(c1: torch.Tensor, c2: torch.Tensor, alpha1: torch.Te... | For boolean channels, blends with a logical OR function. Args: c1 (torch.Tensor): first channel tensor of an arbitrary shape. c2 (torch.Tensor): second channel tensor, in the shape of c1. alpha1 (torch.Tensor): Unused. alpha2 (torch.Tensor): Unused. Returns: (torch.Tensor): Blended channel in the shape of c1 |
22,992 | from __future__ import annotations
from wisp.core.channel_fn import *
from dataclasses import dataclass
from typing import Any, Optional, Dict
from functools import partial
class Channel:
""" Defines how a Renderbuffer channel should behave in terms of functionalities like blending, normalization,
and bound... | A general channel template, to be used if no information about a channel have been recorded |
22,993 | from __future__ import annotations
from wisp.core.channel_fn import *
from dataclasses import dataclass
from typing import Any, Optional, Dict
from functools import partial
class Channel:
""" Defines how a Renderbuffer channel should behave in terms of functionalities like blending, normalization,
and bound... | Creates a predefined kit of channels commonly useful in the context of Wisp. Users may augment or replace this kit with additional custom channels. |
22,994 | from typing import List, Tuple
def color_wheel():
""" Returns:
(list) a list of all colors defined in the color module.
Each entry is a tuple of 3 floats (RGB values).
"""
return [
white, black, dark_gray, light_purple, lime, red, green, blue, orange, light_cyan, light_pink,
... | Generates the next color in the color wheel on each invocation. This generator repeats the color wheel cyclically when exhausted. Args: skip_colors |
22,995 | from __future__ import annotations
import time
import numpy as np
import torch
import torch.nn.functional as F
from typing import Tuple
from wisp.core import RenderBuffer, Rays
from wisp.ops.shaders import matcap_shader, pointlight_shadow_shader
from wisp.ops.differential import finitediff_gradient
from wisp.ops.geomet... | Vectorized look-at function, returns an array of ray origins and directions This function is mostly just a wrapper on top of generate_rays, but will calculate for you the view, right, and up vectors based on the from and to. Args: f (list of floats): [3] size list or tensor specifying the camera origin t (list of float... |
22,996 | import torch
from wisp.core import ObjectTransform
from wisp.models import Pipeline, RasterizationPipeline
from wisp.framework import WispState, BottomLevelRendererState
def add_pipeline_to_scene_graph(state: WispState,
name: str,
pipeline: Pipeline,
... | Adds a new object to the scene graph. obj can be any supported object type, neural or non-neural. This is the most general function used to manage adding new objects to the scene graph. Args: state (WispState): A wisp state object, containing the scene graph information. name (str): Unique name of object added to the s... |
22,997 | import torch
from wisp.core import ObjectTransform
from wisp.models import Pipeline, RasterizationPipeline
from wisp.framework import WispState, BottomLevelRendererState
def request_redraw(state):
""" Marks the canvas as dirty,
forcing the renderer core to refresh the object renderers on the next rendering iter... | Removes an existing pipeline from the scene graph. Args: state (WispState): A wisp state object, containing the scene graph information. name (str): Unique name of object added to the scene graph |
22,998 | from __future__ import annotations
from collections import defaultdict, deque
from typing import Type, TYPE_CHECKING, Union
from wisp.models import Pipeline, RasterizationPipeline
from wisp.models.nefs import BaseNeuralField
from wisp.tracers import BaseTracer
def _neural_field_to_renderer_cls(pipeline: Pipeline) -> Ty... | null |
22,999 | from __future__ import annotations
from typing import Type
from wisp.models.nefs import BaseNeuralField
from wisp.tracers import BaseTracer
from wisp.renderer.core.api.base_renderer import BottomLevelRenderer
from wisp.renderer.core.api.renderers_factory import register_neural_field_type, register_rasterizer_type
clas... | A decorator that registers a neural field type with a renderer. By registering the renderer type, the interactive renderer knows what type of renderer to create when dealing with this type of field. Essentially, this allows displaying custom types of objects on the canvas. |
23,000 | from __future__ import annotations
from typing import Type
from wisp.models.nefs import BaseNeuralField
from wisp.tracers import BaseTracer
from wisp.renderer.core.api.base_renderer import BottomLevelRenderer
from wisp.renderer.core.api.renderers_factory import register_neural_field_type, register_rasterizer_type
clas... | A decorator that registers a rasterizer type with a renderer. By registering the renderer type, the interactive renderer knows what type of renderer to create when dealing with this type of rasterizer. Essentially, this allows displaying custom types of objects on the canvas. |
23,001 | from __future__ import annotations
import copy
import torch
import wisp.framework.state as state
from wisp.renderer.core.control.camera_controller_mode import CameraControlMode
from wisp.renderer.core.control.io import WispMouseButton
def quat_mul(Q1, Q2):
return torch.tensor([Q1[0] * Q2[3] + Q1[3] * Q2[0] - Q1[2]... | null |
23,002 | from __future__ import annotations
import copy
import torch
import wisp.framework.state as state
from wisp.renderer.core.control.camera_controller_mode import CameraControlMode
from wisp.renderer.core.control.io import WispMouseButton
def quat_matrix(q): # True only for unit quaternions
xx = q[0] * q[0]
xy = q... | null |
23,003 | from __future__ import annotations
import abc
import math
import numpy as np
import torch
import copy
from collections import defaultdict
from typing import Dict, List, Iterable, Tuple
from kaolin.render.camera import Camera, PinholeIntrinsics, OrthographicIntrinsics
from wisp.framework import WispState, BottomLevelRen... | An extension to @torch.cuda.amp.autocast which queries WispState to check if mixed precision should be enabled. |
23,004 | import os
from contextlib import contextmanager
if not os.environ.get('ENABLE_PYCUDA') == '1':
from cuda import cuda
import torch
def cuda_map_resource(img):
"""Context manager simplifying use of cuda.cuGraphicsMapResources / cuGraphicsSubResourceGetMappedArray.
Boilerplate code based in par... | null |
23,005 | import os
from contextlib import contextmanager
def cuda_register_gl_image(image, target):
# Create shared GL / CUDA resource
map_flags = cuda.CUgraphicsRegisterFlags.CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD
register_result = cuda.cuGraphicsGLRegisterImage(image=image, target=target, Flags=map_... | null |
23,006 | import os
from contextlib import contextmanager
def cuda_unregister_resource(handle):
unregister_result = cuda.cuGraphicsUnregisterResource(handle)
if unregister_result[0] != cuda.CUresult.CUDA_SUCCESS:
raise RuntimeError('Failed to unregister CUDA resource.') | null |
23,007 | import os
from contextlib import contextmanager
if not os.environ.get('ENABLE_PYCUDA') == '1':
from cuda import cuda
import torch
def cuda_map_resource(img):
"""Context manager simplifying use of cuda.cuGraphicsMapResources / cuGraphicsSubResourceGetMappedArray.
Boilerplate code based in par... | null |
23,008 | import os
from contextlib import contextmanager
def cuda_register_gl_image(image, target):
# Create shared GL / CUDA resource
map_flags = pycuda_gl.graphics_map_flags.WRITE_DISCARD
resource_handle = pycuda_gl.RegisteredImage(image, target, map_flags)
return resource_handle | null |
23,009 | import os
from contextlib import contextmanager
def cuda_unregister_resource(handle):
# Nothing to be done - when ref count reaches zero on proxy object in python, unregister should
# be called automatically
pass | null |
23,010 | from __future__ import annotations
import contextlib
import glob
import io
import logging
import math
import os
import queue
import PIL.Image
import re
import threading
import time
import torch
import torchvision
from typing import Literal
from wisp.framework import WispState
from wisp.renderer.core import RendererCore... | null |
23,011 | from __future__ import annotations
import contextlib
import glob
import io
import logging
import math
import os
import queue
import PIL.Image
import re
import threading
import time
import torch
import torchvision
from typing import Literal
from wisp.framework import WispState
from wisp.renderer.core import RendererCore... | null |
23,012 | from __future__ import annotations
import contextlib
import glob
import io
import logging
import math
import os
import queue
import PIL.Image
import re
import threading
import time
import torch
import torchvision
from typing import Literal
from wisp.framework import WispState
from wisp.renderer.core import RendererCore... | Makes a render closure over input args, so render can be called without arguments. Args: render_core: the RendererCore to use for rendering downscale_factor: how much to downscale the image when rendering Returns: function() -> torch.Tensor 0..1 float, 4 x H x W, where H, W are determined by render_core.camera and the ... |
23,013 | from __future__ import annotations
import contextlib
import glob
import io
import logging
import math
import os
import queue
import PIL.Image
import re
import threading
import time
import torch
import torchvision
from typing import Literal
from wisp.framework import WispState
from wisp.renderer.core import RendererCore... | Convenience function to save a rendered frame to a default location, while appending a counter to the basename. Args: canvas: IpyCanvas canvas object filename: filename and extension where to save, note number will be appended `frame.png` --> `frame1.png` save_dir: directory where to save file; will use default _result... |
23,014 | from __future__ import annotations
import contextlib
import glob
import io
import logging
import math
import os
import queue
import PIL.Image
import re
import threading
import time
import torch
import torchvision
from typing import Literal
from wisp.framework import WispState
from wisp.renderer.core import RendererCore... | Converts numpy array to bytes in the specified image format. Args: np_img: numpy array H x W x C uint8 format: any format supported by Pillow, e.g. 'png' or 'jpeg' (note jpeg does not accept RGBA) Return: bytes |
23,015 | from __future__ import annotations
from abc import ABC
import sys
import numpy as np
import torch
from glumpy import app, gloo, gl, ext
import imgui
from typing import Optional, Type, Callable, Dict, List, Tuple
from kaolin.render.camera import Camera
from wisp.framework import WispState, watch
from wisp.renderer.core ... | An extension to @torch.cuda.amp.autocast which queries WispState to check if mixed precision should be enabled. |
23,016 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, Type, Any
from wisp.framework import WispState
from collections import deque
from wisp.core.colors import colors_generator, white, black, dark_gray, gray
_WIDGETS_REGISTRY: Dict[Type[Any], Type[WidgetImgui]] = dict()
class W... | A decorator that registers a gui widget to paint the contents of a given wisp block. By registering a widget, the gui system knows how to load this widget when it traverses the scene graph & properties and encounters the wisp_block type. Users adding new wisp blocks can directly register corresponding widgets using thi... |
23,017 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, Type, Any
from wisp.framework import WispState
from collections import deque
from wisp.core.colors import colors_generator, white, black, dark_gray, gray
_WIDGETS_REGISTRY: Dict[Type[Any], Type[WidgetImgui]] = dict()
class W... | Return a widget which matches the given wisp block. A wisp block can be of any type / subtype which was registered with @widget. The lookup logic will first look for a widget registered under the type of wisp_block, and if it cannot find it, it will start looking up the hierarchy. Note that multiple-inheritance may res... |
23,018 | from __future__ import annotations
import torch
from kaolin.render.camera import Camera
from kaolin.render.camera.intrinsics import CameraFOV
from wisp.core import Rays
def generate_default_grid(width, height, device=None):
h_coords = torch.arange(height, device=device, dtype=torch.float)
w_coords = torch.arang... | null |
23,019 | from __future__ import annotations
import torch
from kaolin.render.camera import Camera
from kaolin.render.camera.intrinsics import CameraFOV
from wisp.core import Rays
def _to_ndc_coords(pixel_x, pixel_y, camera):
pixel_x = 2 * (pixel_x / camera.width) - 1.0
pixel_y = 2 * (pixel_y / camera.height) - 1.0
re... | Default ray generation function for pinhole cameras. This function assumes that the principal point (the pinhole location) is specified by a displacement (camera.x0, camera.y0) in pixel coordinates from the center of the image. The Kaolin camera class does not enforce a coordinate space for how the principal point is s... |
23,020 | from __future__ import annotations
import torch
from kaolin.render.camera import Camera
from kaolin.render.camera.intrinsics import CameraFOV
from wisp.core import Rays
def _to_ndc_coords(pixel_x, pixel_y, camera):
pixel_x = 2 * (pixel_x / camera.width) - 1.0
pixel_y = 2 * (pixel_y / camera.height) - 1.0
re... | null |
23,021 | import torch
The provided code snippet includes necessary dependencies for implementing the `autodiff_gradient` function. Write a Python function `def autodiff_gradient(x, f)` to solve the following problem:
Compute gradient using the PyTorch autodiff. Args: x (torch.FloatTensor): Coordinate tensor f (nn.Module): The ... | Compute gradient using the PyTorch autodiff. Args: x (torch.FloatTensor): Coordinate tensor f (nn.Module): The function to perform autodiff on. |
23,022 | import torch
The provided code snippet includes necessary dependencies for implementing the `finitediff_gradient` function. Write a Python function `def finitediff_gradient(x, f, eps=0.005)` to solve the following problem:
Compute 3D gradient using finite difference. Args: x (torch.FloatTensor): Coordinate tensor of s... | Compute 3D gradient using finite difference. Args: x (torch.FloatTensor): Coordinate tensor of shape [..., 3] f (nn.Module): The function to perform autodiff on. |
23,023 | import torch
The provided code snippet includes necessary dependencies for implementing the `tetrahedron_gradient` function. Write a Python function `def tetrahedron_gradient(x, f, eps=0.005)` to solve the following problem:
Compute 3D gradient using finite difference (using tetrahedron method). Args: x (torch.FloatTe... | Compute 3D gradient using finite difference (using tetrahedron method). Args: x (torch.FloatTensor): Coordinate tensor of shape [..., 3] f (nn.Module): The function to perform autodiff on. |
23,024 | import torch
from kaolin import _C
import wisp._C as wisp_C
import kaolin.ops.spc as spc_ops
PRIMES = [1, 2654435761, 805459861]
The provided code snippet includes necessary dependencies for implementing the `hashgrid_naive` function. Write a Python function `def hashgrid_naive(coords, resolutions, codebook_bitwidth, ... | A naive PyTorch implementation of the hashgrid. This code exists here mostly as a reference: Do NOT expect a 1-to-1 numerical correspondence to the CUDA accelerated version. This code is comparatively very slow. :) Args: coords (torch.FloatTensor): 3D coordinates of shape [batch, 3] resolutions (torch.LongTensor): the ... |
23,025 | import torch
from kaolin import _C
import wisp._C as wisp_C
import kaolin.ops.spc as spc_ops
class HashGridInterpolate(torch.autograd.Function):
# TODO(ttakikawa): This class should also support the 2D case... which also means I have to write another kernel!
def forward(ctx, coords, resolutions, codebook_bitwid... | A hash-grid query + interpolation function, accelerated with CUDA. Args: coords (torch.FloatTensor): 3D coordinates of shape [batch, 3] codebook_bitwidth (int): The bitwidth of the codebook. The codebook will have 2^bw entries. lod_idx (int): The LOD to aggregate to. codebook (wisp.models.grids.utils.MultiTable): A cla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.