code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_pickleable(env_ids):
"""Test Bullet environments are pickle-able"""
for env_id in env_ids:
# extract id string
env_id = env_id.replace('- ', '')
env = BulletEnv(env_id)
round_trip = pickle.loads(pickle.dumps(env))
assert round_trip
env.close() | Test Bullet environments are pickle-able | test_pickleable | python | rlworkgroup/garage | tests/garage/envs/bullet/test_bullet_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/bullet/test_bullet_env.py | MIT |
def test_pickle_creates_new_server(env_ids):
"""Test pickling a Bullet environment creates a new connection.
If all pickling create new connections, no repetition of client id
should be found.
"""
n_env = 4
for env_id in env_ids:
# extract id string
env_id = env_id.replace('- ',... | Test pickling a Bullet environment creates a new connection.
If all pickling create new connections, no repetition of client id
should be found.
| test_pickle_creates_new_server | python | rlworkgroup/garage | tests/garage/envs/bullet/test_bullet_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/bullet/test_bullet_env.py | MIT |
def test_grayscale_reset(self):
"""
RGB to grayscale conversion using scikit-image.
Weights used for conversion:
Y = 0.2125 R + 0.7154 G + 0.0721 B
Reference:
http://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.rgb2grey
"""
grayscale_ou... |
RGB to grayscale conversion using scikit-image.
Weights used for conversion:
Y = 0.2125 R + 0.7154 G + 0.0721 B
Reference:
http://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.rgb2grey
| test_grayscale_reset | python | rlworkgroup/garage | tests/garage/envs/wrappers/test_grayscale_env.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/envs/wrappers/test_grayscale_env.py | MIT |
def test_deterministic_tfp_seed_stream():
"""Test deterministic behavior of TFP SeedStream"""
deterministic.set_seed(0)
with tf.compat.v1.Session() as sess:
rand_tensor = sess.run(
tf.random.uniform((5, 5),
seed=deterministic.get_tf_seed_stream(),
... | Test deterministic behavior of TFP SeedStream | test_deterministic_tfp_seed_stream | python | rlworkgroup/garage | tests/garage/experiment/test_deterministic.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/experiment/test_deterministic.py | MIT |
def setup_method(self):
"""Setup method which is called before every test."""
self.env = normalize(GymEnv('InvertedDoublePendulum-v2'))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
... | Setup method which is called before every test. | setup_method | python | rlworkgroup/garage | tests/garage/experiment/test_trainer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/experiment/test_trainer.py | MIT |
def test_ddpg_pendulum(self):
"""Test DDPG with Pendulum environment.
This environment has a [-3, 3] action_space bound.
"""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
env = normalize(
GymEnv('InvertedPendulum-v2', max_episode_length=100))
... | Test DDPG with Pendulum environment.
This environment has a [-3, 3] action_space bound.
| test_ddpg_pendulum | python | rlworkgroup/garage | tests/garage/tf/algos/test_ddpg.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ddpg.py | MIT |
def test_ddpg_pendulum_with_decayed_weights(self):
"""Test DDPG with Pendulum environment and decayed weights.
This environment has a [-3, 3] action_space bound.
"""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
env = normalize(
GymEnv('Inverted... | Test DDPG with Pendulum environment and decayed weights.
This environment has a [-3, 3] action_space bound.
| test_ddpg_pendulum_with_decayed_weights | python | rlworkgroup/garage | tests/garage/tf/algos/test_ddpg.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ddpg.py | MIT |
def test_npo_with_unknown_pg_loss(self):
"""Test NPO with unkown pg loss."""
with pytest.raises(ValueError, match='Invalid pg_loss'):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
sampler=self.sampler,... | Test NPO with unkown pg loss. | test_npo_with_unknown_pg_loss | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_npo_with_invalid_entropy_method(self):
"""Test NPO with invalid entropy method."""
with pytest.raises(ValueError, match='Invalid entropy_method'):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test NPO with invalid entropy method. | test_npo_with_invalid_entropy_method | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_npo_with_max_entropy_and_center_adv(self):
"""Test NPO with max entropy and center_adv."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
sampler=self.sampler,
... | Test NPO with max entropy and center_adv. | test_npo_with_max_entropy_and_center_adv | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_npo_with_max_entropy_and_no_stop_entropy_gradient(self):
"""Test NPO with max entropy and false stop_entropy_gradient."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test NPO with max entropy and false stop_entropy_gradient. | test_npo_with_max_entropy_and_no_stop_entropy_gradient | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_npo_with_invalid_no_entropy_configuration(self):
"""Test NPO with invalid no entropy configuration."""
with pytest.raises(ValueError):
NPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
sampler=sel... | Test NPO with invalid no entropy configuration. | test_npo_with_invalid_no_entropy_configuration | python | rlworkgroup/garage | tests/garage/tf/algos/test_npo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_npo.py | MIT |
def test_ppo_with_maximum_entropy(self):
"""Test PPO with maxium entropy method."""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test PPO with maxium entropy method. | test_ppo_with_maximum_entropy | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_with_neg_log_likeli_entropy_estimation_and_max(self):
"""
Test PPO with negative log likelihood entropy estimation and max
entropy method.
"""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec,
... |
Test PPO with negative log likelihood entropy estimation and max
entropy method.
| test_ppo_with_neg_log_likeli_entropy_estimation_and_max | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_with_neg_log_likeli_entropy_estimation_and_regularized(self):
"""
Test PPO with negative log likelihood entropy estimation and
regularized entropy method.
"""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec,
... |
Test PPO with negative log likelihood entropy estimation and
regularized entropy method.
| test_ppo_with_neg_log_likeli_entropy_estimation_and_regularized | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_with_regularized_entropy(self):
"""Test PPO with regularized entropy method."""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
algo = PPO(env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
... | Test PPO with regularized entropy method. | test_ppo_with_regularized_entropy | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_ppo_pendulum_recurrent_continuous_baseline(self):
"""Test PPO with Pendulum environment and recurrent policy."""
with TFTrainer(snapshot_config) as trainer:
env = normalize(
GymEnv('InvertedDoublePendulum-v2', max_episode_length=100))
policy = GaussianLST... | Test PPO with Pendulum environment and recurrent policy. | test_ppo_pendulum_recurrent_continuous_baseline | python | rlworkgroup/garage | tests/garage/tf/algos/test_ppo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_ppo.py | MIT |
def test_reps_cartpole(self):
"""Test REPS with gym Cartpole environment."""
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
env = GymEnv('CartPole-v0')
policy = CategoricalMLPPolicy(env_spec=env.spec,
hidden_sizes=[32, 32])
... | Test REPS with gym Cartpole environment. | test_reps_cartpole | python | rlworkgroup/garage | tests/garage/tf/algos/test_reps.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_reps.py | MIT |
def circle(r, n):
"""Generate n points on a circle of radius r.
Args:
r (float): Radius of the circle.
n (int): Number of points to generate.
Yields:
tuple(float, float): Coordinate of a point.
"""
for t in np... | Generate n points on a circle of radius r.
Args:
r (float): Radius of the circle.
n (int): Number of points to generate.
Yields:
tuple(float, float): Coordinate of a point.
| circle | python | rlworkgroup/garage | tests/garage/tf/algos/test_te.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_te.py | MIT |
def test_trpo_unknown_kl_constraint(self):
"""Test TRPO with unkown KL constraints."""
with pytest.raises(ValueError, match='Invalid kl_constraint'):
TRPO(
env_spec=self.env.spec,
policy=self.policy,
baseline=self.baseline,
samp... | Test TRPO with unkown KL constraints. | test_trpo_unknown_kl_constraint | python | rlworkgroup/garage | tests/garage/tf/algos/test_trpo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/algos/test_trpo.py | MIT |
def test_cg(self):
"""Solve Ax = b using Conjugate gradient method."""
a = np.linspace(-np.pi, np.pi, 25).reshape((5, 5))
a = a.T.dot(a) # make sure a is positive semi-definite
b = np.linspace(-np.pi, np.pi, 5)
x = _cg(a.dot, b, cg_iters=5)
assert np.allclose(a.dot(x), b... | Solve Ax = b using Conjugate gradient method. | test_cg | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_pearl_mutter_hvp_1x1(self):
"""Test Hessian-vector product for a function with one variable."""
policy = HelperPolicy(n_vars=1)
x = policy.get_params()[0]
a_val = np.array([5.0])
a = tf.constant([0.0])
f = a * (x**2)
expected_hessian = 2 * a_val
v... | Test Hessian-vector product for a function with one variable. | test_pearl_mutter_hvp_1x1 | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_pearl_mutter_hvp_2x2(self, a_val, b_val, x_val, y_val, vector):
"""Test Hessian-vector product for a function with two variables."""
a_val = [a_val]
b_val = [b_val]
vector = np.array([vector], dtype=np.float32)
policy = HelperPolicy(n_vars=2)
params = policy.get... | Test Hessian-vector product for a function with two variables. | test_pearl_mutter_hvp_2x2 | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_pearl_mutter_hvp_2x2_non_diagonal(self, a_val, b_val, x_val,
y_val, vector):
"""Test Hessian-vector product for a function with two variables whose Hessian
is non-diagonal.
"""
a_val = [a_val]
b_val = [b_val]
vector ... | Test Hessian-vector product for a function with two variables whose Hessian
is non-diagonal.
| test_pearl_mutter_hvp_2x2_non_diagonal | python | rlworkgroup/garage | tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/optimizers/test_conjugate_gradient_optimizer.py | MIT |
def test_does_not_support_dict_obs_space(self, filters, strides, padding,
hidden_sizes):
"""Test that policy raises error if passed a dict obs space."""
env = GymEnv(DummyDictEnv(act_space_type='discrete'))
with pytest.raises(ValueError):
... | Test that policy raises error if passed a dict obs space. | test_does_not_support_dict_obs_space | python | rlworkgroup/garage | tests/garage/tf/policies/test_categorical_cnn_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/policies/test_categorical_cnn_policy.py | MIT |
def test_obs_unflattened(self):
"""Test if a flattened image obs is passed to get_action
then it is unflattened.
"""
obs = self.env.observation_space.sample()
action, _ = self.policy.get_action(
self.env.observation_space.flatten(obs))
self.env.step(action) | Test if a flattened image obs is passed to get_action
then it is unflattened.
| test_obs_unflattened | python | rlworkgroup/garage | tests/garage/tf/policies/test_discrete_qf_argmax_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/tf/policies/test_discrete_qf_argmax_policy.py | MIT |
def test_utils_set_gpu_mode():
"""Test setting gpu mode to False to force CPU."""
if torch.cuda.is_available():
set_gpu_mode(mode=True)
assert global_device() == torch.device('cuda:0')
assert tu._USE_GPU
else:
set_gpu_mode(mode=False)
assert global_device() == torch.d... | Test setting gpu mode to False to force CPU. | test_utils_set_gpu_mode | python | rlworkgroup/garage | tests/garage/torch/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/test_functions.py | MIT |
def test_torch_to_np():
"""Test whether tuples of tensors can be converted to np arrays."""
tup = (torch.zeros(1), torch.zeros(1))
np_out_1, np_out_2 = torch_to_np(tup)
assert isinstance(np_out_1, np.ndarray)
assert isinstance(np_out_2, np.ndarray) | Test whether tuples of tensors can be converted to np arrays. | test_torch_to_np | python | rlworkgroup/garage | tests/garage/torch/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/test_functions.py | MIT |
def test_as_torch_dict():
"""Test if dict whose values are tensors can be converted to np arrays."""
dic = {'a': np.zeros(1), 'b': np.ones(1)}
as_torch_dict(dic)
for dic_value in dic.values():
assert isinstance(dic_value, torch.Tensor) | Test if dict whose values are tensors can be converted to np arrays. | test_as_torch_dict | python | rlworkgroup/garage | tests/garage/torch/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/test_functions.py | MIT |
def test_product_of_gaussians():
"""Test computing mu, sigma of product of gaussians."""
size = 5
mu = torch.ones(size)
sigmas_squared = torch.ones(size)
output = product_of_gaussians(mu, sigmas_squared)
assert output[0] == 1
assert output[1] == 1 / size | Test computing mu, sigma of product of gaussians. | test_product_of_gaussians | python | rlworkgroup/garage | tests/garage/torch/test_functions.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/test_functions.py | MIT |
def _test_params(v, m):
"""Test if all parameters of a module equal to a value."""
if isinstance(m, torch.nn.Linear):
assert torch.all(torch.eq(m.weight.data, v))
assert torch.all(torch.eq(m.bias.data, v)) | Test if all parameters of a module equal to a value. | _test_params | python | rlworkgroup/garage | tests/garage/torch/algos/test_maml.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_maml.py | MIT |
def test_get_exploration_policy(self):
"""Test if an independent copy of policy is returned."""
self.policy.apply(partial(self._set_params, 0.1))
adapt_policy = self.algo.get_exploration_policy()
adapt_policy.apply(partial(self._set_params, 0.2))
# Old policy should remain untou... | Test if an independent copy of policy is returned. | test_get_exploration_policy | python | rlworkgroup/garage | tests/garage/torch/algos/test_maml.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_maml.py | MIT |
def test_adapt_policy(self):
"""Test if policy can adapt to samples."""
worker = WorkerFactory(seed=100, max_episode_length=100)
sampler = LocalSampler.from_worker_factory(worker, self.policy,
self.env)
self.policy.apply(partial(self._s... | Test if policy can adapt to samples. | test_adapt_policy | python | rlworkgroup/garage | tests/garage/torch/algos/test_maml.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_maml.py | MIT |
def test_maml_trpo_dummy_named_env():
"""Test with dummy environment that has env_name."""
env = normalize(GymEnv(DummyMultiTaskBoxEnv(), max_episode_length=100),
expected_action_scale=10.)
policy = GaussianMLPPolicy(
env_spec=env.spec,
hidden_sizes=(64, 64),
hidd... | Test with dummy environment that has env_name. | test_maml_trpo_dummy_named_env | python | rlworkgroup/garage | tests/garage/torch/algos/test_maml_trpo.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_maml_trpo.py | MIT |
def test_mtsac_get_log_alpha(monkeypatch):
"""Check that the private function _get_log_alpha functions correctly.
MTSAC uses disentangled alphas, meaning that
"""
env_names = ['CartPole-v0', 'CartPole-v1']
task_envs = [GymEnv(name, max_episode_length=100) for name in env_names]
env = MultiEnvW... | Check that the private function _get_log_alpha functions correctly.
MTSAC uses disentangled alphas, meaning that
| test_mtsac_get_log_alpha | python | rlworkgroup/garage | tests/garage/torch/algos/test_mtsac.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_mtsac.py | MIT |
def test_mtsac_get_log_alpha_incorrect_num_tasks(monkeypatch):
"""Check that if the num_tasks passed does not match the number of tasks
in the environment, then the algorithm should raise an exception.
MTSAC uses disentangled alphas, meaning that
"""
env_names = ['CartPole-v0', 'CartPole-v1']
... | Check that if the num_tasks passed does not match the number of tasks
in the environment, then the algorithm should raise an exception.
MTSAC uses disentangled alphas, meaning that
| test_mtsac_get_log_alpha_incorrect_num_tasks | python | rlworkgroup/garage | tests/garage/torch/algos/test_mtsac.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_mtsac.py | MIT |
def test_mtsac_inverted_double_pendulum():
"""Performance regression test of MTSAC on 2 InvDoublePendulum envs."""
env_names = ['InvertedDoublePendulum-v2', 'InvertedDoublePendulum-v2']
task_envs = [GymEnv(name, max_episode_length=100) for name in env_names]
env = MultiEnvWrapper(task_envs, sample_strat... | Performance regression test of MTSAC on 2 InvDoublePendulum envs. | test_mtsac_inverted_double_pendulum | python | rlworkgroup/garage | tests/garage/torch/algos/test_mtsac.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_mtsac.py | MIT |
def test_to():
"""Test the torch function that moves modules to GPU.
Test that the policy and qfunctions are moved to gpu if gpu is
available.
"""
env_names = ['CartPole-v0', 'CartPole-v1']
task_envs = [GymEnv(name, max_episode_length=100) for name in env_names]
env = MultiEnvWrapp... | Test the torch function that moves modules to GPU.
Test that the policy and qfunctions are moved to gpu if gpu is
available.
| test_to | python | rlworkgroup/garage | tests/garage/torch/algos/test_mtsac.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_mtsac.py | MIT |
def test_fixed_alpha():
"""Test if using fixed_alpha ensures that alpha is non differentiable."""
env_names = ['InvertedDoublePendulum-v2', 'InvertedDoublePendulum-v2']
task_envs = [GymEnv(name, max_episode_length=100) for name in env_names]
env = MultiEnvWrapper(task_envs, sample_strategy=round_robin_s... | Test if using fixed_alpha ensures that alpha is non differentiable. | test_fixed_alpha | python | rlworkgroup/garage | tests/garage/torch/algos/test_mtsac.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_mtsac.py | MIT |
def __call__(self, observation):
"""Dummy forward operation. Returns a dummy distribution."""
action = torch.Tensor([self._action])
return _MockDistribution(action), {} | Dummy forward operation. Returns a dummy distribution. | __call__ | python | rlworkgroup/garage | tests/garage/torch/algos/test_sac.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_sac.py | MIT |
def test_sac_inverted_double_pendulum():
"""Test Sac performance on inverted pendulum."""
# pylint: disable=unexpected-keyword-arg
env = normalize(GymEnv('InvertedDoublePendulum-v2',
max_episode_length=100))
deterministic.set_seed(0)
policy = TanhGaussianMLPPolicy(
... | Test Sac performance on inverted pendulum. | test_sac_inverted_double_pendulum | python | rlworkgroup/garage | tests/garage/torch/algos/test_sac.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_sac.py | MIT |
def test_sac_to():
"""Test moving Sac between CPU and GPU."""
env = normalize(GymEnv('InvertedDoublePendulum-v2',
max_episode_length=100))
deterministic.set_seed(0)
policy = TanhGaussianMLPPolicy(
env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonline... | Test moving Sac between CPU and GPU. | test_sac_to | python | rlworkgroup/garage | tests/garage/torch/algos/test_sac.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_sac.py | MIT |
def test_invalid_entropy_config(self, algo_param, error, msg):
"""Test VPG with invalid entropy config."""
self._params.update(algo_param)
with pytest.raises(error, match=msg):
VPG(**self._params) | Test VPG with invalid entropy config. | test_invalid_entropy_config | python | rlworkgroup/garage | tests/garage/torch/algos/test_vpg.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_vpg.py | MIT |
def test_tanh_normal_bounds(self):
"""Test to make sure the tanh_normal dist obeys the bounds (-1,1)."""
mean = torch.ones(1) * 100
std = torch.ones(1) * 100
dist = TanhNormal(mean, std)
assert dist.mean <= 1.
del dist
mean = torch.ones(1) * -100
std = tor... | Test to make sure the tanh_normal dist obeys the bounds (-1,1). | test_tanh_normal_bounds | python | rlworkgroup/garage | tests/garage/torch/distributions/test_tanh_normal_dist.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/distributions/test_tanh_normal_dist.py | MIT |
def test_tanh_normal_rsample(self):
"""Test the bounds of the tanh_normal rsample function."""
mean = torch.zeros(1)
std = torch.ones(1)
dist = TanhNormal(mean, std)
sample = dist.rsample()
pre_tanh_action, action = dist.rsample_with_pre_tanh_value()
assert (pre_t... | Test the bounds of the tanh_normal rsample function. | test_tanh_normal_rsample | python | rlworkgroup/garage | tests/garage/torch/distributions/test_tanh_normal_dist.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/distributions/test_tanh_normal_dist.py | MIT |
def test_tanh_normal_log_prob(self):
"""Verify the correctnes of the tanh_normal log likelihood function."""
mean = torch.zeros(1)
std = torch.ones(1)
dist = TanhNormal(mean, std)
pre_tanh_action = torch.Tensor([[2.0960]])
action = pre_tanh_action.tanh()
log_prob ... | Verify the correctnes of the tanh_normal log likelihood function. | test_tanh_normal_log_prob | python | rlworkgroup/garage | tests/garage/torch/distributions/test_tanh_normal_dist.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/distributions/test_tanh_normal_dist.py | MIT |
def test_tanh_normal_expand(self):
"""Test for expand function.
Checks whether expand returns a distribution that has potentially a
different batch size from the already existing distribution.
"""
mean = torch.zeros(1)
std = torch.ones(1)
dist = TanhNormal(mean,... | Test for expand function.
Checks whether expand returns a distribution that has potentially a
different batch size from the already existing distribution.
| test_tanh_normal_expand | python | rlworkgroup/garage | tests/garage/torch/distributions/test_tanh_normal_dist.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/distributions/test_tanh_normal_dist.py | MIT |
def test_tanh_normal_repr(self):
"""Test that the repr function outputs the class name."""
mean = torch.zeros(1)
std = torch.ones(1)
dist = TanhNormal(mean, std)
assert repr(dist) == 'TanhNormal' | Test that the repr function outputs the class name. | test_tanh_normal_repr | python | rlworkgroup/garage | tests/garage/torch/distributions/test_tanh_normal_dist.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/distributions/test_tanh_normal_dist.py | MIT |
def test_tanh_normal_log_prob_of_clipped_action(self):
"""Verify that clipped actions still have a valid log probability."""
mean = torch.zeros(2)
std = torch.ones(2)
dist = TanhNormal(mean, std)
action = torch.Tensor([[1., -1.]])
log_prob_approx = dist.log_prob(action)
... | Verify that clipped actions still have a valid log probability. | test_tanh_normal_log_prob_of_clipped_action | python | rlworkgroup/garage | tests/garage/torch/distributions/test_tanh_normal_dist.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/distributions/test_tanh_normal_dist.py | MIT |
def test_output_values(self, kernel_sizes, hidden_channels, strides,
paddings):
"""Test output values from CNNBaseModule.
Args:
kernel_sizes (tuple[int]): Kernel sizes.
hidden_channels (tuple[int]): hidden channels.
strides (tuple[int]): st... | Test output values from CNNBaseModule.
Args:
kernel_sizes (tuple[int]): Kernel sizes.
hidden_channels (tuple[int]): hidden channels.
strides (tuple[int]): strides.
paddings (tuple[int]): value of zero-padding.
| test_output_values | python | rlworkgroup/garage | tests/garage/torch/modules/test_cnn_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_cnn_module.py | MIT |
def test_output_values_with_unequal_stride_with_padding(
self, hidden_channels, kernel_sizes, strides, paddings):
"""Test output values with unequal stride and padding from CNNModule.
Args:
kernel_sizes (tuple[int]): Kernel sizes.
hidden_channels (tuple[int]): hidden... | Test output values with unequal stride and padding from CNNModule.
Args:
kernel_sizes (tuple[int]): Kernel sizes.
hidden_channels (tuple[int]): hidden channels.
strides (tuple[int]): strides.
paddings (tuple[int]): value of zero-padding.
| test_output_values_with_unequal_stride_with_padding | python | rlworkgroup/garage | tests/garage/torch/modules/test_cnn_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_cnn_module.py | MIT |
def test_is_pickleable(self, hidden_channels, kernel_sizes, strides):
"""Check CNNModule is pickeable.
Args:
hidden_channels (tuple[int]): hidden channels.
kernel_sizes (tuple[int]): Kernel sizes.
strides (tuple[int]): strides.
"""
model = CNNModule(... | Check CNNModule is pickeable.
Args:
hidden_channels (tuple[int]): hidden channels.
kernel_sizes (tuple[int]): Kernel sizes.
strides (tuple[int]): strides.
| test_is_pickleable | python | rlworkgroup/garage | tests/garage/torch/modules/test_cnn_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_cnn_module.py | MIT |
def test_no_head_invalid_settings(self, hidden_nonlinear):
"""Check CNNModule throws exception with invalid non-linear functions.
Args:
hidden_nonlinear (callable or torch.nn.Module): Non-linear
functions for hidden layers.
"""
expected_msg = 'Non linear fun... | Check CNNModule throws exception with invalid non-linear functions.
Args:
hidden_nonlinear (callable or torch.nn.Module): Non-linear
functions for hidden layers.
| test_no_head_invalid_settings | python | rlworkgroup/garage | tests/garage/torch/modules/test_cnn_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_cnn_module.py | MIT |
def test_output_values(self, input_dim, output_dim, hidden_sizes):
"""Test output values from MLPModule.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): Size of hidden layers.
"""
input_val = torch... | Test output values from MLPModule.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): Size of hidden layers.
| test_output_values | python | rlworkgroup/garage | tests/garage/torch/modules/test_mlp_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_mlp_module.py | MIT |
def test_is_pickleable(self, input_dim, output_dim, hidden_sizes):
"""Check MLPModule is pickeable.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): Size of hidden layers.
"""
input_val = torch.ones... | Check MLPModule is pickeable.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): Size of hidden layers.
| test_is_pickleable | python | rlworkgroup/garage | tests/garage/torch/modules/test_mlp_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_mlp_module.py | MIT |
def test_no_head_invalid_settings(self, hidden_nonlinear,
output_nonlinear):
"""Check MLPModule throws exception with invalid non-linear functions.
Args:
hidden_nonlinear (callable or torch.nn.Module): Non-linear
functions for hidden lay... | Check MLPModule throws exception with invalid non-linear functions.
Args:
hidden_nonlinear (callable or torch.nn.Module): Non-linear
functions for hidden layers.
output_nonlinear (callable or torch.nn.Module): Non-linear
functions for output layer.
... | test_no_head_invalid_settings | python | rlworkgroup/garage | tests/garage/torch/modules/test_mlp_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_mlp_module.py | MIT |
def test_mlp_with_learnable_non_linear_function(self):
"""Test MLPModule with learnable non-linear functions."""
input_dim, output_dim, hidden_sizes = 1, 1, (3, 2)
input_val = -torch.ones([1, input_dim], dtype=torch.float32)
module = MLPModule(input_dim=input_dim,
... | Test MLPModule with learnable non-linear functions. | test_mlp_with_learnable_non_linear_function | python | rlworkgroup/garage | tests/garage/torch/modules/test_mlp_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_mlp_module.py | MIT |
def test_multi_headed_mlp_module(input_dim, output_dim, hidden_sizes,
output_w_init_vals, n_heads):
"""Test Multi-headed MLPModule.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): Size of hidden layers... | Test Multi-headed MLPModule.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): Size of hidden layers.
output_w_init_vals (list[int]): Init values for output weights.
n_heads (int): Number of output layers.
| test_multi_headed_mlp_module | python | rlworkgroup/garage | tests/garage/torch/modules/test_multi_headed_mlp_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_multi_headed_mlp_module.py | MIT |
def test_multi_headed_mlp_module_with_layernorm(input_dim, output_dim,
hidden_sizes,
output_w_init_vals, n_heads):
"""Test Multi-headed MLPModule with layer normalization.
Args:
input_dim (int): Input dimens... | Test Multi-headed MLPModule with layer normalization.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): Size of hidden layers.
output_w_init_vals (list[int]): Init values for output weights.
n_heads (int): Number of output l... | test_multi_headed_mlp_module_with_layernorm | python | rlworkgroup/garage | tests/garage/torch/modules/test_multi_headed_mlp_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_multi_headed_mlp_module.py | MIT |
def test_invalid_settings(input_dim, output_dim, hidden_sizes, n_heads,
nonlinearity, w_init, b_init):
"""Test Multi-headed MLPModule with invalid parameters.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): S... | Test Multi-headed MLPModule with invalid parameters.
Args:
input_dim (int): Input dimension.
output_dim (int): Ouput dimension.
hidden_sizes (list[int]): Size of hidden layers.
n_heads (int): Number of output layers.
nonlinearity (callable or torch.nn.Module): Non-linear fun... | test_invalid_settings | python | rlworkgroup/garage | tests/garage/torch/modules/test_multi_headed_mlp_module.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/modules/test_multi_headed_mlp_module.py | MIT |
def test_differentiable_sgd():
"""Test second order derivative after taking optimization step."""
policy = torch.nn.Linear(10, 10, bias=False)
lr = 0.01
diff_sgd = DifferentiableSGD(policy, lr=lr)
named_theta = dict(policy.named_parameters())
theta = list(named_theta.values())[0]
meta_loss ... | Test second order derivative after taking optimization step. | test_differentiable_sgd | python | rlworkgroup/garage | tests/garage/torch/optimizers/test_differentiable_sgd.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/optimizers/test_differentiable_sgd.py | MIT |
def test_line_search_should_stop(self):
"""Test if line search stops when loss is decreasing, and constraint is satisfied.""" # noqa: E501
p1 = torch.tensor([0.1])
p2 = torch.tensor([0.1])
params = [p1, p2]
optimizer = ConjugateGradientOptimizer(params, 0.01)
expected_nu... | Test if line search stops when loss is decreasing, and constraint is satisfied. | test_line_search_should_stop | python | rlworkgroup/garage | tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | MIT |
def test_line_search_step_size_should_decrease(self):
"""Line search step size should always decrease."""
p1 = torch.tensor([0.1])
p2 = torch.tensor([0.1])
params = [p1, p2]
optimizer = ConjugateGradientOptimizer(params, 0.01)
p1_history = []
p2_history = []
... | Line search step size should always decrease. | test_line_search_step_size_should_decrease | python | rlworkgroup/garage | tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | MIT |
def test_hessian_vector_product_2x2(a_val, b_val, x_val, y_val, vector):
"""Test for a function with two variables."""
obs = [torch.tensor([a_val]), torch.tensor([b_val])]
vector = torch.tensor([vector])
x = torch.tensor(x_val, requires_grad=True)
y = torch.tensor(y_val, requires_grad=True)
def... | Test for a function with two variables. | test_hessian_vector_product_2x2 | python | rlworkgroup/garage | tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | MIT |
def test_hessian_vector_product_2x2_non_diagonal(a_val, b_val, x_val, y_val,
vector):
"""Test for a function with two variables and non-diagonal Hessian."""
obs = [torch.tensor([a_val]), torch.tensor([b_val])]
vector = torch.tensor([vector])
x = torch.ten... | Test for a function with two variables and non-diagonal Hessian. | test_hessian_vector_product_2x2_non_diagonal | python | rlworkgroup/garage | tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | MIT |
def compute_hessian(f, params):
"""Compute hessian matrix of given function."""
h = []
for i in params:
h_i = []
for j in params:
grad = torch.autograd.grad(f, j, create_graph=True)
h_ij = torch.autograd.grad(grad,
i,
... | Compute hessian matrix of given function. | compute_hessian | python | rlworkgroup/garage | tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | MIT |
def test_pickle_round_trip():
"""Test that pickling works as one would normally expect."""
# pylint: disable=protected-access
p1 = torch.tensor([0.1])
p2 = torch.tensor([0.1])
params = [p1, p2]
optimizer = ConjugateGradientOptimizer(params, 0.01)
optimizer_pickled = pickle.dumps(optimizer)
... | Test that pickling works as one would normally expect. | test_pickle_round_trip | python | rlworkgroup/garage | tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | MIT |
def test_get_action_img_obs(self, hidden_channels, kernel_sizes, strides,
hidden_sizes):
"""Test get_action function with akro.Image observation space."""
env = GymEnv(DummyDiscretePixelEnv(), is_image=True)
policy = CategoricalCNNPolicy(env_spec=env.spec,
... | Test get_action function with akro.Image observation space. | test_get_action_img_obs | python | rlworkgroup/garage | tests/garage/torch/policies/test_categorical_cnn_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_categorical_cnn_policy.py | MIT |
def test_get_actions(self, hidden_channels, kernel_sizes, strides,
hidden_sizes):
"""Test get_actions function with akro.Image observation space."""
env = GymEnv(DummyDiscretePixelEnv(), is_image=True)
policy = CategoricalCNNPolicy(env_spec=env.spec,
... | Test get_actions function with akro.Image observation space. | test_get_actions | python | rlworkgroup/garage | tests/garage/torch/policies/test_categorical_cnn_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_categorical_cnn_policy.py | MIT |
def test_invalid_action_spaces(self):
"""Test that policy raises error if passed a box obs space."""
env = GymEnv(DummyDictEnv(act_space_type='box'))
with pytest.raises(ValueError):
CategoricalCNNPolicy(env_spec=env.spec,
image_format='NHWC',
... | Test that policy raises error if passed a box obs space. | test_invalid_action_spaces | python | rlworkgroup/garage | tests/garage/torch/policies/test_categorical_cnn_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_categorical_cnn_policy.py | MIT |
def test_get_action_dict_space(self):
"""Test if observations from dict obs spaces are properly flattened."""
env = GymEnv(DummyDictEnv(obs_space_type='box', act_space_type='box'))
policy = DeterministicMLPPolicy(env_spec=env.spec,
hidden_nonlinearity=None... | Test if observations from dict obs spaces are properly flattened. | test_get_action_dict_space | python | rlworkgroup/garage | tests/garage/torch/policies/test_deterministic_mlp_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_deterministic_mlp_policy.py | MIT |
def test_get_action(self, hidden_sizes):
"""Test Tanh Gaussian Policy get action function."""
env_spec = GymEnv(DummyBoxEnv())
obs_dim = env_spec.observation_space.flat_dim
act_dim = env_spec.action_space.flat_dim
obs = torch.ones(obs_dim, dtype=torch.float32).unsqueeze(0)
... | Test Tanh Gaussian Policy get action function. | test_get_action | python | rlworkgroup/garage | tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | MIT |
def test_get_action_np(self, hidden_sizes):
"""Test Policy get action function with numpy inputs."""
env_spec = GymEnv(DummyBoxEnv())
obs_dim = env_spec.observation_space.flat_dim
act_dim = env_spec.action_space.flat_dim
obs = np.ones((obs_dim, ), dtype=np.float32)
init_s... | Test Policy get action function with numpy inputs. | test_get_action_np | python | rlworkgroup/garage | tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | MIT |
def test_get_actions(self, batch_size, hidden_sizes):
"""Test Tanh Gaussian Policy get actions function."""
env_spec = GymEnv(DummyBoxEnv())
obs_dim = env_spec.observation_space.flat_dim
act_dim = env_spec.action_space.flat_dim
obs = torch.ones([batch_size, obs_dim], dtype=torch.... | Test Tanh Gaussian Policy get actions function. | test_get_actions | python | rlworkgroup/garage | tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | MIT |
def test_get_actions_np(self, batch_size, hidden_sizes):
"""Test get actions with np.ndarray inputs."""
env_spec = GymEnv(DummyBoxEnv())
obs_dim = env_spec.observation_space.flat_dim
act_dim = env_spec.action_space.flat_dim
obs = np.ones((batch_size, obs_dim), dtype=np.float32)
... | Test get actions with np.ndarray inputs. | test_get_actions_np | python | rlworkgroup/garage | tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | MIT |
def test_is_pickleable(self, batch_size, hidden_sizes):
"""Test if policy is unchanged after pickling."""
env_spec = GymEnv(DummyBoxEnv())
obs_dim = env_spec.observation_space.flat_dim
obs = torch.ones([batch_size, obs_dim], dtype=torch.float32)
init_std = 2.
policy = Ta... | Test if policy is unchanged after pickling. | test_is_pickleable | python | rlworkgroup/garage | tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | MIT |
def test_to(self):
"""Test Tanh Gaussian Policy can be moved to cpu."""
env_spec = GymEnv(DummyBoxEnv())
init_std = 2.
policy = TanhGaussianMLPPolicy(env_spec=env_spec,
hidden_sizes=(1, ),
init_std=init_std,
... | Test Tanh Gaussian Policy can be moved to cpu. | test_to | python | rlworkgroup/garage | tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | MIT |
def enumerate_algo_examples():
"""Return a list of paths for all algo examples.
Returns:
List[str]: list of path strings
"""
exclude = NON_ALGO_EXAMPLES + LONG_RUNNING_EXAMPLES
all_examples = EXAMPLES_ROOT_DIR.glob('**/*.py')
return [str(e) for e in all_examples if e not in exclude] | Return a list of paths for all algo examples.
Returns:
List[str]: list of path strings
| enumerate_algo_examples | python | rlworkgroup/garage | tests/integration_tests/test_examples.py | https://github.com/rlworkgroup/garage/blob/master/tests/integration_tests/test_examples.py | MIT |
def test_algo_examples(filepath):
"""Test algo examples.
Args:
filepath (str): path string of example
"""
env = os.environ.copy()
env['GARAGE_EXAMPLE_TEST_N_EPOCHS'] = '1'
# Don't use check=True, since that causes subprocess to throw an error
# in case of failure before the asserti... | Test algo examples.
Args:
filepath (str): path string of example
| test_algo_examples | python | rlworkgroup/garage | tests/integration_tests/test_examples.py | https://github.com/rlworkgroup/garage/blob/master/tests/integration_tests/test_examples.py | MIT |
def test_dqn_pong():
"""Test tf/dqn_pong.py with reduced replay buffer size.
This is to reduced memory consumption.
"""
env = os.environ.copy()
env['GARAGE_EXAMPLE_TEST_N_EPOCHS'] = '1'
assert subprocess.run([
EXAMPLES_ROOT_DIR / 'tf/dqn_pong.py', '--buffer_size', '5',
'--max_e... | Test tf/dqn_pong.py with reduced replay buffer size.
This is to reduced memory consumption.
| test_dqn_pong | python | rlworkgroup/garage | tests/integration_tests/test_examples.py | https://github.com/rlworkgroup/garage/blob/master/tests/integration_tests/test_examples.py | MIT |
def test_dqn_atari():
"""Test torch/dqn_atari.py with reduced replay buffer size.
This is to reduced memory consumption.
"""
env = os.environ.copy()
env['GARAGE_EXAMPLE_TEST_N_EPOCHS'] = '1'
assert subprocess.run([
EXAMPLES_ROOT_DIR / 'torch/dqn_atari.py', 'Pong', '--buffer_size', '1',... | Test torch/dqn_atari.py with reduced replay buffer size.
This is to reduced memory consumption.
| test_dqn_atari | python | rlworkgroup/garage | tests/integration_tests/test_examples.py | https://github.com/rlworkgroup/garage/blob/master/tests/integration_tests/test_examples.py | MIT |
def test_ppo_memorize_digits():
"""Test tf/ppo_memorize_digits.py with reduced batch size.
This is to reduced memory consumption.
"""
env = os.environ.copy()
env['GARAGE_EXAMPLE_TEST_N_EPOCHS'] = '1'
command = [
EXAMPLES_ROOT_DIR / 'tf/ppo_memorize_digits.py', '--batch_size', '4',
... | Test tf/ppo_memorize_digits.py with reduced batch size.
This is to reduced memory consumption.
| test_ppo_memorize_digits | python | rlworkgroup/garage | tests/integration_tests/test_examples.py | https://github.com/rlworkgroup/garage/blob/master/tests/integration_tests/test_examples.py | MIT |
def test_trpo_cubecrash():
"""Test tf/trpo_cubecrash.py with reduced batch size.
This is to reduced memory consumption.
"""
env = os.environ.copy()
env['GARAGE_EXAMPLE_TEST_N_EPOCHS'] = '1'
assert subprocess.run([
EXAMPLES_ROOT_DIR / 'tf/trpo_cubecrash.py', '--batch_size', '4',
... | Test tf/trpo_cubecrash.py with reduced batch size.
This is to reduced memory consumption.
| test_trpo_cubecrash | python | rlworkgroup/garage | tests/integration_tests/test_examples.py | https://github.com/rlworkgroup/garage/blob/master/tests/integration_tests/test_examples.py | MIT |
def interrupt_experiment(experiment_script, lifecycle_stage):
"""Interrupt the experiment and verify no children processes remain."""
args = ['python', experiment_script]
# The pre-executed function setpgrp allows to create a process group
# so signals are propagated to all the process in the group.
... | Interrupt the experiment and verify no children processes remain. | interrupt_experiment | python | rlworkgroup/garage | tests/integration_tests/test_sigint.py | https://github.com/rlworkgroup/garage/blob/master/tests/integration_tests/test_sigint.py | MIT |
def writeFrame(self, data):
"""Write the received frame to a temp image file. Return the image file."""
cachename = CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT
file = open(cachename, "wb")
file.write(data)
file.close()
return cachename | Write the received frame to a temp image file. Return the image file. | writeFrame | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | MIT |
def updateMovie(self, imageFile):
"""Update the image file as video frame in the GUI."""
photo = ImageTk.PhotoImage(Image.open(imageFile))
self.label.configure(image = photo, height=288)
self.label.image = photo | Update the image file as video frame in the GUI. | updateMovie | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | MIT |
def connectToServer(self):
"""Connect to the Server. Start a new RTSP/TCP session."""
self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.rtspSocket.connect((self.serverAddr, self.serverPort))
except:
tkMessageBox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %s... | Connect to the Server. Start a new RTSP/TCP session. | connectToServer | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | MIT |
def sendRtspRequest(self, requestCode):
"""Send RTSP request to the server."""
# Setup request
if requestCode == self.SETUP and self.state == self.INIT:
threading.Thread(target=self.recvRtspReply).start()
# Update RTSP sequence number.
self.rtspSeq += 1
# Write the RTSP request to be sent.
r... | Send RTSP request to the server. | sendRtspRequest | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | MIT |
def recvRtspReply(self):
"""Receive RTSP reply from the server."""
while True:
reply = self.rtspSocket.recv(1024)
if reply:
self.parseRtspReply(reply.decode("utf-8"))
# Close the RTSP socket upon requesting Teardown
if self.requestSent == self.TEARDOWN:
self.rtspSocket.shutdown(socket.S... | Receive RTSP reply from the server. | recvRtspReply | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | MIT |
def parseRtspReply(self, data):
"""Parse the RTSP reply from the server."""
lines = str(data).split('\n')
seqNum = int(lines[1].split(' ')[1])
# Process only if the server reply's sequence number is the same as the request's
if seqNum == self.rtspSeq:
session = int(lines[2].split(' ')[1])
# New RTSP ... | Parse the RTSP reply from the server. | parseRtspReply | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | MIT |
def openRtpPort(self):
"""Open RTP socket binded to a specified port."""
# Create a new datagram socket to receive RTP packets from the server
self.rtpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set the timeout value of the socket to 0.5sec
self.rtpSocket.settimeout(0.5)
try:
# Bind t... | Open RTP socket binded to a specified port. | openRtpPort | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | MIT |
def handler(self):
"""Handler on explicitly closing the GUI window."""
self.pauseMovie()
if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"):
self.exitClient()
else: # When the user presses cancel, resume playing.
self.playMovie() | Handler on explicitly closing the GUI window. | handler | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/Client.py | MIT |
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload):
"""Encode the RTP packet with header fields and payload."""
timestamp = int(time())
header = bytearray(HEADER_SIZE)
# Fill the header bytearray with RTP header fields
header[0] = (version << 6) | (padding << 5) | (extensi... | Encode the RTP packet with header fields and payload. | encode | python | moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES | Resource/7th-Python-Solution/Solutions/StreamingVideo/RtpPacket.py | https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES/blob/master/Resource/7th-Python-Solution/Solutions/StreamingVideo/RtpPacket.py | MIT |
def __init__(self, tileSize=256):
'''Initialize the TMS Global Mercator pyramid'''
self.tileSize = tileSize
self.initialResolution = 2 * math.pi * 6378137 / self.tileSize
# 156543.03392804062 for tileSize 256 pixels
self.originShift = 2 * math.pi * 6378137 / 2.0
# 200... | Initialize the TMS Global Mercator pyramid | __init__ | python | commenthol/gdal2tiles-leaflet | gdal2tiles-multiprocess.py | https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py | MIT |
def LatLonToMeters(self, lat, lon):
'''Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913'''
mx = lon * self.originShift / 180.0
my = math.log(math.tan((90 + lat) * math.pi / 360.0)) \
/ (math.pi / 180.0)
my = my * self.originShift / 180.0
... | Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913 | LatLonToMeters | python | commenthol/gdal2tiles-leaflet | gdal2tiles-multiprocess.py | https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py | MIT |
def MetersToLatLon(self, mx, my):
'''Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum'''
lon = mx / self.originShift * 180.0
lat = my / self.originShift * 180.0
lat = 180 / math.pi * (2 * math.atan(math.exp(lat * math.pi
/ 1... | Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum | MetersToLatLon | python | commenthol/gdal2tiles-leaflet | gdal2tiles-multiprocess.py | https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py | MIT |
def PixelsToMeters(
self,
px,
py,
zoom,
):
'''Converts pixel coordinates in given zoom level of pyramid to EPSG:900913'''
res = self.Resolution(zoom)
mx = px * res - self.originShift
my = py * res - self.originShift
return (mx, my) | Converts pixel coordinates in given zoom level of pyramid to EPSG:900913 | PixelsToMeters | python | commenthol/gdal2tiles-leaflet | gdal2tiles-multiprocess.py | https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py | MIT |
def MetersToPixels(
self,
mx,
my,
zoom,
):
'''Converts EPSG:900913 to pyramid pixel coordinates in given zoom level'''
res = self.Resolution(zoom)
px = (mx + self.originShift) / res
py = (my + self.originShift) / res
return (px, py) | Converts EPSG:900913 to pyramid pixel coordinates in given zoom level | MetersToPixels | python | commenthol/gdal2tiles-leaflet | gdal2tiles-multiprocess.py | https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py | MIT |
def PixelsToTile(self, px, py):
'''Returns a tile covering region in given pixel coordinates'''
tx = int(math.ceil(px / float(self.tileSize)) - 1)
ty = int(math.ceil(py / float(self.tileSize)) - 1)
return (tx, ty) | Returns a tile covering region in given pixel coordinates | PixelsToTile | python | commenthol/gdal2tiles-leaflet | gdal2tiles-multiprocess.py | https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py | MIT |
def PixelsToRaster(
self,
px,
py,
zoom,
):
'''Move the origin of pixel coordinates to top-left corner'''
mapSize = self.tileSize << zoom
return (px, mapSize - py) | Move the origin of pixel coordinates to top-left corner | PixelsToRaster | python | commenthol/gdal2tiles-leaflet | gdal2tiles-multiprocess.py | https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.