repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
pointnerf | pointnerf-master/data/data_utils.py | import numpy as np
import open3d as o3d
def get_cv_raydir(pixelcoords, height, width, focal, rot):
# pixelcoords: H x W x 2
if isinstance(focal, float):
focal = [focal, focal]
x = (pixelcoords[..., 0] - width / 2.0) / focal[0]
y = (pixelcoords[..., 1] - height / 2.0) / focal[1]
z = np.ones_l... | 4,744 | 37.893443 | 128 | py |
pointnerf | pointnerf-master/data/scannet_ft_dataset.py | from models.mvs.mvs_utils import read_pfm
import os
import numpy as np
import cv2
import torch
from torchvision import transforms as T
import torchvision.transforms.functional as F
from kornia import create_meshgrid
import time
import json
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader
import to... | 32,944 | 43.162198 | 321 | py |
pointnerf | pointnerf-master/data/nerf_synth360_ft_dataset.py | from models.mvs.mvs_utils import read_pfm
import os
import numpy as np
import cv2
from PIL import Image
import torch
from torchvision import transforms as T
import torchvision.transforms.functional as F
from kornia import create_meshgrid
import time
import json
from . import data_utils
from plyfile import PlyData, PlyE... | 30,908 | 40.488591 | 321 | py |
pointnerf | pointnerf-master/data/__init__.py | import importlib
import torch.utils.data
import sys
sys.path.append("../")
from utils.ncg_string import underscore2camelcase
from .base_dataset import BaseDataset
import numpy as np
import time
def find_dataset_class_by_name(name):
'''
Input
name: string with underscore representation
Output
datas... | 2,880 | 31.738636 | 120 | py |
pointnerf | pointnerf-master/data/load_blender.py | import os
import numpy as np
import imageio
import json
import torch
import pickle, random
# trans_t = lambda t : tf.convert_to_tensor([
# [1,0,0,0],
# [0,1,0,0],
# [0,0,1,t],
# [0,0,0,1],
# ], dtype=tf.float32)
#
# rot_phi = lambda phi : tf.convert_to_tensor([
# [1,0,0,0],
# [0,tf.cos(phi),-t... | 3,956 | 29.206107 | 166 | py |
pointnerf | pointnerf-master/data/tt_ft_dataset.py | from models.mvs.mvs_utils import read_pfm
import os
import numpy as np
import cv2
from PIL import Image
import torch
from torchvision import transforms as T
import torchvision.transforms.functional as F
from kornia import create_meshgrid
import time
import json
from . import data_utils
from plyfile import PlyData, PlyE... | 31,438 | 39.82987 | 175 | py |
NLRN | NLRN-master/__init__.py | 0 | 0 | 0 | py | |
NLRN | NLRN-master/trainer.py | """Trainer
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import argparse
import importlib
import tensorflow as tf
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--dataset',
help='Dataset... | 4,328 | 28.053691 | 75 | py |
NLRN | NLRN-master/common/layers.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
class Conv2DWeightNorm(tf.layers.Conv2D):
def build(self, input_shape):
self.wn_g = self.add_weight(
name='wn_g',
shape=(self.filters,),
dtype=self.dtype... | 2,141 | 31.454545 | 63 | py |
NLRN | NLRN-master/common/__init__.py | 0 | 0 | 0 | py | |
NLRN | NLRN-master/models/__init__.py | """Basic Model
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def update_argparser(parser):
parser.add_argument(
'--learning_rate',
help='Learning rate',
default=0.001,
)
def model_fn(features, labels, ... | 1,510 | 24.610169 | 79 | py |
NLRN | NLRN-master/models/nlrn.py | """NLRN model for denoise dataset
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import models
def update_argparser(parser):
models.update_argparser(parser)
args, _ = parser.parse_known_args()
parser.add_argument(
... | 7,920 | 27.595668 | 79 | py |
NLRN | NLRN-master/datasets/denoise.py | """DIV2K dataset
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import argparse
from hashlib import sha256
from PIL import Image
import numpy as np
import tensorflow as tf
import datasets
NUM_CHANNELS = 1
def update_argparser(parser):
... | 7,652 | 31.565957 | 81 | py |
NLRN | NLRN-master/datasets/__init__.py | """Basic Dataset
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import random
import tensorflow as tf
def update_argparser(parser):
parser.add_argument(
'--train-batch-size',
help='Batch size for training steps',
... | 4,176 | 28.006944 | 79 | py |
NLRN | NLRN-master/datasets/div2k.py | """DIV2K dataset
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import argparse
from PIL import Image
import numpy as np
import tensorflow as tf
import datasets
REMOTE_URL = 'http://data.vision.ee.ethz.ch/cvl/DIV2K/'
TRAIN_LR_ARCHIVE_NAME ... | 7,489 | 31.707424 | 81 | py |
variational_dropout | variational_dropout-master/train.py | import argparse
import torch as t
import torch.nn as nn
import torchvision.transforms as transforms
from tensorboardX import SummaryWriter
from torch.autograd import Variable
from torch.optim import Adam
from torchvision import datasets
from models import *
if __name__ == "__main__":
parser = argparse.ArgumentP... | 4,518 | 39.348214 | 120 | py |
variational_dropout | variational_dropout-master/models/dropout_model.py | import torch.nn as nn
import torch.nn.functional as F
class DropoutModel(nn.Module):
def __init__(self):
super(DropoutModel, self).__init__()
self.fc = nn.ModuleList([
nn.Linear(784, 500),
nn.Linear(500, 50),
nn.Linear(50, 10)
])
def forward(self, ... | 1,009 | 27.857143 | 96 | py |
variational_dropout | variational_dropout-master/models/simple_model.py | import torch.nn as nn
import torch.nn.functional as F
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Sequential(
nn.Linear(784, 500),
nn.ELU(),
nn.Linear(500, 50),
nn.ELU(),
nn.Linear(5... | 744 | 24.689655 | 96 | py |
variational_dropout | variational_dropout-master/models/variational_dropout_model.py | import torch.nn as nn
import torch.nn.functional as F
from variational_dropout.variational_dropout import VariationalDropout
class VariationalDropoutModel(nn.Module):
def __init__(self):
super(VariationalDropoutModel, self).__init__()
self.fc = nn.ModuleList([
VariationalDropout(784,... | 1,648 | 31.333333 | 111 | py |
variational_dropout | variational_dropout-master/models/__init__.py | from .simple_model import SimpleModel
from .dropout_model import DropoutModel
from .variational_dropout_model import VariationalDropoutModel
| 141 | 34.5 | 62 | py |
variational_dropout | variational_dropout-master/variational_dropout/variational_dropout.py | import math
import torch as t
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.parameter import Parameter
class VariationalDropout(nn.Module):
def __init__(self, input_size, out_size, log_sigma2=-10, threshold=3):
"""
:param input_size: An in... | 2,575 | 31.2 | 111 | py |
variational_dropout | variational_dropout-master/variational_dropout/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/plot_log.py |
logp = '/home/chenxing/extra_test/BeamRider/ddpo_4/log.txt'
with open(logp, 'r') as f:
logs = f.read().split('\n')
data = {}
for log in logs:
if 'loss' in log:
dat = log.split('|')
key, value = dat[1].strip(),float(dat[2])
if key in data.keys():
data[key].append(value)
... | 761 | 22.090909 | 59 | py |
P3O | P3O-main/test.py | import gym
env = gym.make("Walker2d-v2")
# env = gym.make("Ant-v2")
env.reset()
for _ in range(20):
# env.render()
action = env.action_space.sample() # User-defined policy function
observation, reward, done, info = env.step(action)
print(info, reward)
if done:
env.reset()
env.close() | 307 | 22.692308 | 69 | py |
P3O | P3O-main/run_experiments.py |
a = 'export PYTHONPATH=/home/chenxing/tmp/baselines'
b = 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/chenxing/.mujoco/mujoco200/bin'
for seed in [1,2,3,4]:
algo = 'spg'
game = 'HalfCheetah-v2'
rename = 'spg+5rvkl'
cmd=[
"/home/chenxing/env/bin/python",
"-m",
"baselines.run"... | 593 | 22.76 | 82 | py |
P3O | P3O-main/plot_progress.py |
# logp = '/home/chenxing/extra_test/BeamRider/ppo2_1/progress.csv'
logp = '/home/chenxing/extra_test/BeamRider/ddpo_1/progress.csv'
with open(logp, 'r') as f:
logs = f.read().split('\n')
data = {}
keys = logs[0].split(',')
for key in keys:
data[key] = []
for log in logs[1:]:
if len(log)<2:
conti... | 1,338 | 22.086207 | 108 | py |
P3O | P3O-main/plot.py | import os
import numpy as np
import matplotlib
# matplotlib.use('TkAgg') # Can change to 'Agg' for non-interactive mode
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
# plt.rcParams['svg.fonttype'] = 'none'
# plt.rcParams["font.family"] = "Times New Roman"
# plt.rcParams['xtick.direction'] = 'in'
# plt.rcPara... | 4,543 | 33.424242 | 143 | py |
P3O | P3O-main/baselines/results_plotter.py | import numpy as np
import matplotlib
matplotlib.use('TkAgg') # Can change to 'Agg' for non-interactive mode
import matplotlib.pyplot as plt
plt.rcParams['svg.fonttype'] = 'none'
from baselines.common import plot_util
X_TIMESTEPS = 'timesteps'
X_EPISODES = 'episodes'
X_WALLTIME = 'walltime_hrs'
Y_REWARD = 'reward'
Y_... | 3,455 | 35.378947 | 144 | py |
P3O | P3O-main/baselines/logger.py | import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
from collections import defaultdict
from contextlib import contextmanager
DEBUG = 10
INFO = 20
WARN = 30
ERROR = 40
DISABLED = 50
class KVWriter(object):
def writekvs(self, kvs):
raise NotImpl... | 15,956 | 28.38674 | 122 | py |
P3O | P3O-main/baselines/run_test.py | import sys
import re
import multiprocessing
import os.path as osp
import gym
from collections import defaultdict
import tensorflow as tf
import numpy as np
from baselines.common.vec_env import VecFrameStack, VecNormalize, VecEnv
from baselines.common.vec_env.vec_video_recorder import VecVideoRecorder
from baselines.co... | 6,988 | 28.242678 | 176 | py |
P3O | P3O-main/baselines/run.py | import sys
import re
import multiprocessing
import os.path as osp
import gym
from collections import defaultdict
import tensorflow as tf
import numpy as np
from baselines.common.vec_env import VecFrameStack, VecNormalize, VecEnv
from baselines.common.vec_env.vec_video_recorder import VecVideoRecorder
from baselines.co... | 8,357 | 29.50365 | 176 | py |
P3O | P3O-main/baselines/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/vpg/vpg.py | import os
import random
import time
import numpy as np
import os.path as osp
from baselines import logger
from collections import deque
from baselines.common import explained_variance, set_global_seeds
from baselines.common.policies import build_policy
try:
from mpi4py import MPI
except ImportError:
MPI = None
... | 11,131 | 42.826772 | 184 | py |
P3O | P3O-main/baselines/vpg/model.py | import tensorflow as tf
import functools
from baselines.common.tf_util import get_session, save_variables, load_variables
from baselines.common.tf_util import initialize
from baselines.common.input import observation_placeholder
try:
from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer
from mpi4py ... | 6,912 | 38.502857 | 114 | py |
P3O | P3O-main/baselines/vpg/defaults.py | def mujoco():
return dict(
nsteps=2048,
nminibatches=32,
lam=0.95,
gamma=0.99,
noptepochs=10,
log_interval=1,
ent_coef=0.0,
lr=lambda f: 1e-4 * 1,
cliprange=0.2,
value_network='copy'
)
def atari():
return dict(
nsteps=1... | 549 | 19.37037 | 59 | py |
P3O | P3O-main/baselines/vpg/runner.py | import numpy as np
from baselines.common.runners import AbstractEnvRunner
class Runner(AbstractEnvRunner):
"""
We use this object to make a mini batch of experiences
__init__:
- Initialize the runner
run():
- Make a mini batch
"""
def __init__(self, *, env, model, nsteps, gamma, lam):
... | 3,194 | 40.493506 | 109 | py |
P3O | P3O-main/baselines/vpg/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/common/mpi_adam.py | import baselines.common.tf_util as U
import tensorflow as tf
import numpy as np
try:
from mpi4py import MPI
except ImportError:
MPI = None
class MpiAdam(object):
def __init__(self, var_list, *, beta1=0.9, beta2=0.999, epsilon=1e-08, scale_grad_by_procs=True, comm=None):
self.var_list = var_list
... | 3,296 | 30.701923 | 112 | py |
P3O | P3O-main/baselines/common/cg.py | import numpy as np
def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):
"""
Demmel p 312
"""
p = b.copy()
r = b.copy()
x = np.zeros_like(b)
rdotr = r.dot(r)
fmtstr = "%10i %10.3g %10.3g"
titlestr = "%10s %10s %10s"
if verbose: print(titlestr % ("iter... | 897 | 24.657143 | 88 | py |
P3O | P3O-main/baselines/common/runners.py | import numpy as np
from abc import ABC, abstractmethod
class AbstractEnvRunner(ABC):
def __init__(self, *, env, model, nsteps):
self.env = env
self.model = model
self.nenv = nenv = env.num_envs if hasattr(env, 'num_envs') else 1
self.batch_ob_shape = (nenv*nsteps,) + env.observation... | 670 | 32.55 | 106 | py |
P3O | P3O-main/baselines/common/distributions.py | import tensorflow as tf
import numpy as np
import baselines.common.tf_util as U
from baselines.a2c.utils import fc
from tensorflow.python.ops import math_ops
class Pd(object):
"""
A particular probability distribution
"""
def flatparam(self):
raise NotImplementedError
def mode(self):
... | 15,187 | 37.94359 | 217 | py |
P3O | P3O-main/baselines/common/mpi_util.py | from collections import defaultdict
import os, numpy as np
import platform
import shutil
import subprocess
import warnings
import sys
try:
from mpi4py import MPI
except ImportError:
MPI = None
def sync_from_root(sess, variables, comm=None):
"""
Send the root node's parameters to every worker.
Arg... | 4,259 | 30.791045 | 108 | py |
P3O | P3O-main/baselines/common/schedules.py | """This file is used for specifying various schedules that evolve over
time throughout the execution of the algorithm, such as:
- learning rate for the optimizer
- exploration epsilon for the epsilon greedy exploration strategy
- beta parameter for beta parameter in prioritized replay
Each schedule has a function `... | 3,702 | 36.03 | 90 | py |
P3O | P3O-main/baselines/common/atari_wrappers.py | import numpy as np
import os
os.environ.setdefault('PATH', '')
from collections import deque
import gym
from gym import spaces
import cv2
cv2.ocl.setUseOpenCL(False)
from .wrappers import TimeLimit
class NoopResetEnv(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking ra... | 9,686 | 32.28866 | 130 | py |
P3O | P3O-main/baselines/common/mpi_running_mean_std.py | try:
from mpi4py import MPI
except ImportError:
MPI = None
import tensorflow as tf, baselines.common.tf_util as U, numpy as np
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, epsilon=1e-2, shape=()):
self.... | 3,706 | 31.80531 | 126 | py |
P3O | P3O-main/baselines/common/test_mpi_util.py | from baselines.common import mpi_util
from baselines import logger
from baselines.common.tests.test_with_mpi import with_mpi
try:
from mpi4py import MPI
except ImportError:
MPI = None
@with_mpi()
def test_mpi_weighted_mean():
comm = MPI.COMM_WORLD
with logger.scoped_configure(comm=comm):
if com... | 986 | 31.9 | 68 | py |
P3O | P3O-main/baselines/common/misc_util.py | import gym
import numpy as np
import os
import pickle
import random
import tempfile
import zipfile
def zipsame(*seqs):
L = len(seqs[0])
assert all(len(seq) == L for seq in seqs[1:])
return zip(*seqs)
class EzPickle(object):
"""Objects that are pickled and unpickled via their constructor
argument... | 7,166 | 28.372951 | 97 | py |
P3O | P3O-main/baselines/common/mpi_fork.py | import os, subprocess, sys
def mpi_fork(n, bind_to_core=False):
"""Re-launches the current script with workers
Returns "parent" for original parent, "child" for MPI children
"""
if n<=1:
return "child"
if os.getenv("IN_MPI") is None:
env = os.environ.copy()
env.update(
... | 667 | 26.833333 | 66 | py |
P3O | P3O-main/baselines/common/dataset.py | import numpy as np
class Dataset(object):
def __init__(self, data_map, deterministic=False, shuffle=True):
self.data_map = data_map
self.deterministic = deterministic
self.enable_shuffle = shuffle
self.n = next(iter(data_map.values())).shape[0]
self._next_id = 0
self... | 2,132 | 33.967213 | 110 | py |
P3O | P3O-main/baselines/common/math_util.py | import numpy as np
import scipy.signal
def discount(x, gamma):
"""
computes discounted sums along 0th dimension of x.
inputs
------
x: ndarray
gamma: float
outputs
-------
y: ndarray with same shape as x, satisfying
y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gam... | 2,094 | 23.360465 | 75 | py |
P3O | P3O-main/baselines/common/tf_util.py | import numpy as np
import tensorflow as tf # pylint: ignore-module
import copy
import os
import functools
import collections
import multiprocessing
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value (int or bool).
Note that both `then_expres... | 17,008 | 37.136771 | 144 | py |
P3O | P3O-main/baselines/common/tile_images.py | import numpy as np
def tile_images(img_nhwc):
"""
Tile N images into one big PxQ image
(P,Q) are chosen to be as close as possible, and if N
is square, then P=Q.
input: img_nhwc, list or array of images, ndim=4 once turned into array
n = batch index, h = height, w = width, c = channel
... | 763 | 30.833333 | 80 | py |
P3O | P3O-main/baselines/common/running_mean_std.py | import tensorflow as tf
import numpy as np
from baselines.common.tf_util import get_session
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, epsilon=1e-4, shape=()):
self.mean = np.zeros(shape, 'float64')
sel... | 6,081 | 31.351064 | 142 | py |
P3O | P3O-main/baselines/common/retro_wrappers.py | from collections import deque
import cv2
cv2.ocl.setUseOpenCL(False)
from .atari_wrappers import WarpFrame, ClipRewardEnv, FrameStack, ScaledFloatFrame
from .wrappers import TimeLimit
import numpy as np
import gym
class StochasticFrameSkip(gym.Wrapper):
def __init__(self, env, n, stickprob):
gym.Wrapper._... | 9,752 | 33.708185 | 107 | py |
P3O | P3O-main/baselines/common/wrappers.py | import gym
class TimeLimit(gym.Wrapper):
def __init__(self, env, max_episode_steps=None):
super(TimeLimit, self).__init__(env)
self._max_episode_steps = max_episode_steps
self._elapsed_steps = 0
def step(self, ac):
observation, reward, done, info = self.env.step(ac)
sel... | 946 | 30.566667 | 79 | py |
P3O | P3O-main/baselines/common/segment_tree.py | import operator
class SegmentTree(object):
def __init__(self, capacity, operation, neutral_element):
"""Build a Segment Tree data structure.
https://en.wikipedia.org/wiki/Segment_tree
Can be used as regular array, but with two
important differences:
a) setting item's... | 4,899 | 32.561644 | 109 | py |
P3O | P3O-main/baselines/common/policies.py | import tensorflow as tf
from baselines.common import tf_util
from baselines.a2c.utils import fc
from baselines.common.distributions import make_pdtype
from baselines.common.input import observation_placeholder, encode_observation
from baselines.common.tf_util import adjust_shape
from baselines.common.mpi_running_mean_s... | 7,682 | 35.240566 | 137 | py |
P3O | P3O-main/baselines/common/models.py | import numpy as np
import tensorflow as tf
from baselines.a2c import utils
from baselines.a2c.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch
from baselines.common.mpi_running_mean_std import RunningMeanStd
mapping = {}
def register(name):
def _thunk(func):
mapping[name] = func
retur... | 9,515 | 30.098039 | 140 | py |
P3O | P3O-main/baselines/common/mpi_adam_optimizer.py | import numpy as np
import tensorflow as tf
from baselines.common import tf_util as U
from baselines.common.tests.test_with_mpi import with_mpi
from baselines import logger
try:
from mpi4py import MPI
except ImportError:
MPI = None
class MpiAdamOptimizer(tf.train.AdamOptimizer):
"""Adam optimizer that avera... | 3,976 | 42.703297 | 117 | py |
P3O | P3O-main/baselines/common/__init__.py | # flake8: noqa F403
from baselines.common.console_util import *
from baselines.common.dataset import Dataset
from baselines.common.math_util import *
from baselines.common.misc_util import *
| 191 | 31 | 44 | py |
P3O | P3O-main/baselines/common/mpi_moments.py | from mpi4py import MPI
import numpy as np
from baselines.common import zipsame
def mpi_mean(x, axis=0, comm=None, keepdims=False):
x = np.asarray(x)
assert x.ndim > 0
if comm is None: comm = MPI.COMM_WORLD
xsum = x.sum(axis=axis, keepdims=keepdims)
n = xsum.size
localsum = np.zeros(n+1, x.dtyp... | 2,018 | 31.564516 | 101 | py |
P3O | P3O-main/baselines/common/console_util.py | from __future__ import print_function
from contextlib import contextmanager
import numpy as np
import time
import shlex
import subprocess
# ================================================================
# Misc
# ================================================================
def fmt_row(width, row, header=False):
... | 2,179 | 25.91358 | 104 | py |
P3O | P3O-main/baselines/common/cmd_util.py | """
Helpers for scripts like run_atari.py.
"""
import os
try:
from mpi4py import MPI
except ImportError:
MPI = None
import gym
from gym.wrappers import FlattenObservation, FilterObservation
from baselines import logger
from baselines.bench import Monitor
from baselines.common import set_global_seeds
from base... | 7,922 | 37.275362 | 204 | py |
P3O | P3O-main/baselines/common/input.py | import numpy as np
import tensorflow as tf
from gym.spaces import Discrete, Box, MultiDiscrete
def observation_placeholder(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space
Parameters:
----------
ob_space: gym.... | 2,071 | 30.876923 | 121 | py |
P3O | P3O-main/baselines/common/plot_util.py | import matplotlib.pyplot as plt
import os.path as osp
import json
import os
import numpy as np
import pandas
from collections import defaultdict, namedtuple
from baselines.bench import monitor
from baselines.logger import read_json, read_csv
def smooth(y, radius, mode='two_sided', valid_only=False):
'''
Smooth... | 21,954 | 42.648111 | 181 | py |
P3O | P3O-main/baselines/common/tests/test_env_after_learn.py | import pytest
import gym
import tensorflow as tf
from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv
from baselines.run import get_learn_function
from baselines.common.tf_util import make_session
algos = ['a2c', 'acer', 'acktr', 'deepq', 'ppo2', 'trpo_mpi']
@pytest.mark.parametrize('algo', algos)
def ... | 865 | 29.928571 | 96 | py |
P3O | P3O-main/baselines/common/tests/test_fetchreach.py | import pytest
import gym
from baselines.run import get_learn_function
from baselines.common.tests.util import reward_per_episode_test
from baselines.common.tests import mark_slow
pytest.importorskip('mujoco_py')
common_kwargs = dict(
network='mlp',
seed=0,
)
learn_kwargs = {
'her': dict(total_timesteps=... | 860 | 20 | 65 | py |
P3O | P3O-main/baselines/common/tests/test_with_mpi.py | import os
import sys
import subprocess
import cloudpickle
import base64
import pytest
from functools import wraps
try:
from mpi4py import MPI
except ImportError:
MPI = None
def with_mpi(nproc=2, timeout=30, skip_if_no_mpi=True):
def outer_thunk(fn):
@wraps(fn)
def thunk(*args, **kwargs):
... | 997 | 24.589744 | 92 | py |
P3O | P3O-main/baselines/common/tests/test_tf_util.py | # tests for tf_util
import tensorflow as tf
from baselines.common.tf_util import (
function,
initialize,
single_threaded_session
)
def test_function():
with tf.Graph().as_default():
x = tf.placeholder(tf.int32, (), name="x")
y = tf.placeholder(tf.int32, (), name="y")
z = 3 * x ... | 1,072 | 23.953488 | 55 | py |
P3O | P3O-main/baselines/common/tests/test_schedules.py | import numpy as np
from baselines.common.schedules import ConstantSchedule, PiecewiseSchedule
def test_piecewise_schedule():
ps = PiecewiseSchedule([(-5, 100), (5, 200), (10, 50), (100, 50), (200, -50)], outside_value=500)
assert np.isclose(ps.value(-10), 500)
assert np.isclose(ps.value(0), 150)
ass... | 823 | 29.518519 | 101 | py |
P3O | P3O-main/baselines/common/tests/test_identity.py | import pytest
from baselines.common.tests.envs.identity_env import DiscreteIdentityEnv, BoxIdentityEnv, MultiDiscreteIdentityEnv
from baselines.run import get_learn_function
from baselines.common.tests.util import simple_test
from baselines.common.tests import mark_slow
common_kwargs = dict(
total_timesteps=30000,... | 2,304 | 28.935065 | 114 | py |
P3O | P3O-main/baselines/common/tests/test_segment_tree.py | import numpy as np
from baselines.common.segment_tree import SumSegmentTree, MinSegmentTree
def test_tree_set():
tree = SumSegmentTree(4)
tree[2] = 1.0
tree[3] = 3.0
assert np.isclose(tree.sum(), 4.0)
assert np.isclose(tree.sum(0, 2), 0.0)
assert np.isclose(tree.sum(0, 3), 1.0)
assert n... | 2,691 | 24.884615 | 72 | py |
P3O | P3O-main/baselines/common/tests/test_mnist.py | import pytest
# from baselines.acer import acer_simple as acer
from baselines.common.tests.envs.mnist_env import MnistEnv
from baselines.common.tests.util import simple_test
from baselines.run import get_learn_function
from baselines.common.tests import mark_slow
# TODO investigate a2c and ppo2 failures - is it due t... | 1,515 | 29.32 | 104 | py |
P3O | P3O-main/baselines/common/tests/util.py | import tensorflow as tf
import numpy as np
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
N_TRIALS = 10000
N_EPISODES = 100
_sess_config = tf.ConfigProto(
allow_soft_placement=True,
intra_op_parallelism_threads=1,
inter_op_parallelism_threads=1
)
def simple_test(env_fn, learn_fn, min_rewa... | 3,181 | 33.215054 | 127 | py |
P3O | P3O-main/baselines/common/tests/test_plot_util.py | # smoke tests of plot_util
from baselines.common import plot_util as pu
from baselines.common.tests.util import smoketest
def test_plot_util():
nruns = 4
logdirs = [smoketest('--alg=ppo2 --env=CartPole-v0 --num_timesteps=10000') for _ in range(nruns)]
data = pu.load_results(logdirs)
assert len(data) =... | 717 | 38.888889 | 101 | py |
P3O | P3O-main/baselines/common/tests/__init__.py | import os, pytest
mark_slow = pytest.mark.skipif(not os.getenv('RUNSLOW'), reason='slow') | 89 | 44 | 71 | py |
P3O | P3O-main/baselines/common/tests/test_doc_examples.py | import pytest
try:
import mujoco_py
_mujoco_present = True
except BaseException:
mujoco_py = None
_mujoco_present = False
@pytest.mark.skipif(
not _mujoco_present,
reason='error loading mujoco - either mujoco / mujoco key not present, or LD_LIBRARY_PATH is not pointing to mujoco library'
)
def... | 1,351 | 26.591837 | 128 | py |
P3O | P3O-main/baselines/common/tests/test_serialization.py | import os
import gym
import tempfile
import pytest
import tensorflow as tf
import numpy as np
from baselines.common.tests.envs.mnist_env import MnistEnv
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
from baselines.run import get_learn_function
from baselines.common.tf_util import make_session, get_ses... | 4,273 | 29.528571 | 105 | py |
P3O | P3O-main/baselines/common/tests/test_cartpole.py | import pytest
import gym
from baselines.run import get_learn_function
from baselines.common.tests.util import reward_per_episode_test
from baselines.common.tests import mark_slow
common_kwargs = dict(
total_timesteps=30000,
network='mlp',
gamma=1.0,
seed=0,
)
learn_kwargs = {
'a2c' : dict(nsteps=... | 1,098 | 22.891304 | 67 | py |
P3O | P3O-main/baselines/common/tests/test_fixed_sequence.py | import pytest
from baselines.common.tests.envs.fixed_sequence_env import FixedSequenceEnv
from baselines.common.tests.util import simple_test
from baselines.run import get_learn_function
from baselines.common.tests import mark_slow
common_kwargs = dict(
seed=0,
total_timesteps=50000,
)
learn_kwargs = {
... | 1,389 | 25.226415 | 165 | py |
P3O | P3O-main/baselines/common/tests/envs/mnist_env.py | import os.path as osp
import numpy as np
import tempfile
from gym import Env
from gym.spaces import Discrete, Box
class MnistEnv(Env):
def __init__(
self,
episode_len=None,
no_images=None
):
import filelock
from tensorflow.examples.tutorials.mnist import in... | 2,110 | 28.319444 | 101 | py |
P3O | P3O-main/baselines/common/tests/envs/fixed_sequence_env.py | import numpy as np
from gym import Env
from gym.spaces import Discrete
class FixedSequenceEnv(Env):
def __init__(
self,
n_actions=10,
episode_len=100
):
self.action_space = Discrete(n_actions)
self.observation_space = Discrete(1)
self.np_random = np.... | 1,054 | 22.977273 | 71 | py |
P3O | P3O-main/baselines/common/tests/envs/identity_env.py | import numpy as np
from abc import abstractmethod
from gym import Env
from gym.spaces import MultiDiscrete, Discrete, Box
from collections import deque
class IdentityEnv(Env):
def __init__(
self,
episode_len=None,
delay=0,
zero_first_rewards=True
):
self... | 2,444 | 25.868132 | 101 | py |
P3O | P3O-main/baselines/common/tests/envs/__init__.py | 0 | 0 | 0 | py | |
P3O | P3O-main/baselines/common/tests/envs/identity_env_test.py | from baselines.common.tests.envs.identity_env import DiscreteIdentityEnv
def test_discrete_nodelay():
nsteps = 100
eplen = 50
env = DiscreteIdentityEnv(10, episode_len=eplen)
ob = env.reset()
for t in range(nsteps):
action = env.action_space.sample()
next_ob, rew, done, info = env.... | 1,034 | 26.972973 | 72 | py |
P3O | P3O-main/baselines/common/vec_env/vec_video_recorder.py | import os
from baselines import logger
from baselines.common.vec_env import VecEnvWrapper
from gym.wrappers.monitoring import video_recorder
class VecVideoRecorder(VecEnvWrapper):
"""
Wrap VecEnv to record rendered image as mp4 video.
"""
def __init__(self, venv, directory, record_video_trigger, vide... | 2,746 | 29.522222 | 130 | py |
P3O | P3O-main/baselines/common/vec_env/vec_normalize.py | from . import VecEnvWrapper
import numpy as np
class VecNormalize(VecEnvWrapper):
"""
A vectorized wrapper that normalizes the observations
and returns from an environment.
"""
def __init__(self, venv, ob=True, ret=True, clipob=10., cliprew=10., gamma=0.99, epsilon=1e-8, use_tf=False):
Vec... | 1,854 | 37.645833 | 120 | py |
P3O | P3O-main/baselines/common/vec_env/test_vec_env.py | """
Tests for asynchronous vectorized environments.
"""
import gym
import numpy as np
import pytest
from .dummy_vec_env import DummyVecEnv
from .shmem_vec_env import ShmemVecEnv
from .subproc_vec_env import SubprocVecEnv
from baselines.common.tests.test_with_mpi import with_mpi
def assert_venvs_equal(venv1, venv2, n... | 5,162 | 31.471698 | 92 | py |
P3O | P3O-main/baselines/common/vec_env/vec_env.py | import contextlib
import os
from abc import ABC, abstractmethod
from baselines.common.tile_images import tile_images
class AlreadySteppingError(Exception):
"""
Raised when an asynchronous step is running while
step_async() is called again.
"""
def __init__(self):
msg = 'already running an... | 6,195 | 26.660714 | 219 | py |
P3O | P3O-main/baselines/common/vec_env/vec_monitor.py | from . import VecEnvWrapper
from baselines.bench.monitor import ResultsWriter
import numpy as np
import time
from collections import deque
class VecMonitor(VecEnvWrapper):
def __init__(self, venv, filename=None, keep_buf=0, info_keywords=()):
VecEnvWrapper.__init__(self, venv)
self.eprets = None
... | 1,971 | 34.214286 | 90 | py |
P3O | P3O-main/baselines/common/vec_env/dummy_vec_env.py | import numpy as np
from .vec_env import VecEnv
from .util import copy_obs_dict, dict_to_obs, obs_space_info
class DummyVecEnv(VecEnv):
"""
VecEnv that does runs multiple environments sequentially, that is,
the step and reset commands are send to one environment at a time.
Useful when debugging and when... | 2,923 | 34.658537 | 157 | py |
P3O | P3O-main/baselines/common/vec_env/util.py | """
Helpers for dealing with vectorized environments.
"""
from collections import OrderedDict
import gym
import numpy as np
def copy_obs_dict(obs):
"""
Deep-copy an observation dict.
"""
return {k: np.copy(v) for k, v in obs.items()}
def dict_to_obs(obs_dict):
"""
Convert an observation di... | 1,513 | 23.031746 | 82 | py |
P3O | P3O-main/baselines/common/vec_env/__init__.py | from .vec_env import AlreadySteppingError, NotSteppingError, VecEnv, VecEnvWrapper, VecEnvObservationWrapper, CloudpickleWrapper
from .dummy_vec_env import DummyVecEnv
from .shmem_vec_env import ShmemVecEnv
from .subproc_vec_env import SubprocVecEnv
from .vec_frame_stack import VecFrameStack
from .vec_monitor import Ve... | 668 | 59.818182 | 246 | py |
P3O | P3O-main/baselines/common/vec_env/subproc_vec_env.py | import multiprocessing as mp
import numpy as np
from .vec_env import VecEnv, CloudpickleWrapper, clear_mpi_env_vars
def worker(remote, parent_remote, env_fn_wrappers):
def step_env(env, action):
ob, reward, done, info = env.step(action)
if done:
ob = env.reset()
return ob, rew... | 5,069 | 35.47482 | 128 | py |
P3O | P3O-main/baselines/common/vec_env/test_video_recorder.py | """
Tests for asynchronous vectorized environments.
"""
import gym
import pytest
import os
import glob
import tempfile
from .dummy_vec_env import DummyVecEnv
from .shmem_vec_env import ShmemVecEnv
from .subproc_vec_env import SubprocVecEnv
from .vec_video_recorder import VecVideoRecorder
@pytest.mark.parametrize('kl... | 1,467 | 28.36 | 130 | py |
P3O | P3O-main/baselines/common/vec_env/shmem_vec_env.py | """
An interface for asynchronous vectorized environments.
"""
import multiprocessing as mp
import numpy as np
from .vec_env import VecEnv, CloudpickleWrapper, clear_mpi_env_vars
import ctypes
from baselines import logger
from .util import dict_to_obs, obs_space_info, obs_to_dict
_NP_TO_CT = {np.float32: ctypes.c_fl... | 5,178 | 35.471831 | 129 | py |
P3O | P3O-main/baselines/common/vec_env/vec_frame_stack.py | from .vec_env import VecEnvWrapper
import numpy as np
from gym import spaces
class VecFrameStack(VecEnvWrapper):
def __init__(self, venv, nstack):
self.venv = venv
self.nstack = nstack
wos = venv.observation_space # wrapped ob space
low = np.repeat(wos.low, self.nstack, axis=-1)
... | 1,150 | 36.129032 | 94 | py |
P3O | P3O-main/baselines/common/vec_env/vec_remove_dict_obs.py | from .vec_env import VecEnvObservationWrapper
class VecExtractDictObs(VecEnvObservationWrapper):
def __init__(self, venv, key):
self.key = key
super().__init__(venv=venv,
observation_space=venv.observation_space.spaces[self.key])
def process(self, obs):
return obs[self.key]... | 321 | 28.272727 | 70 | py |
P3O | P3O-main/baselines/clip/clip.py | import os
import time
import numpy as np
import os.path as osp
from baselines import logger
from collections import deque
from baselines.common import explained_variance, set_global_seeds
from baselines.common.policies import build_policy
try:
from mpi4py import MPI
except ImportError:
MPI = None
from baselines... | 9,868 | 44.270642 | 184 | py |
P3O | P3O-main/baselines/clip/model.py | import numpy as np
import tensorflow as tf
import functools
from baselines.common.tf_util import get_session, save_variables, load_variables
from baselines.common.tf_util import initialize
try:
from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer
from mpi4py import MPI
from baselines.common.mp... | 7,025 | 35.78534 | 126 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.