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_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 get_actions(self, observations):
"""Get actions given observations.
Args:
observations (np.ndarray): Observations from the environment.
Has shape :math:`(B, O)`, where :math:`B` is the batch
dimension and :math:`O` is the observation dimensionality (at
least 2).
Returns:
tuple:
* np.ndarray: Batch of optimal actions.
Has shape :math:`(B, 2)`, where :math:`B` is the batch
dimension.
Optimal action in the environment.
* dict[str, np.ndarray]: Agent info (empty).
"""
return (self.goal[np.newaxis, :].repeat(len(observations), axis=0) -
observations[:, :2]), {}
|
Get actions given observations.
Args:
observations (np.ndarray): Observations from the environment.
Has shape :math:`(B, O)`, where :math:`B` is the batch
dimension and :math:`O` is the observation dimensionality (at
least 2).
Returns:
tuple:
* np.ndarray: Batch of optimal actions.
Has shape :math:`(B, 2)`, where :math:`B` is the batch
dimension.
Optimal action in the environment.
* dict[str, np.ndarray]: Agent info (empty).
|
get_actions
|
python
|
rlworkgroup/garage
|
tests/garage/torch/algos/test_bc.py
|
https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_bc.py
|
MIT
|
def test_ddpg_pendulum(self):
"""Test DDPG with Pendulum environment.
This environment has a [-3, 3] action_space bound.
"""
deterministic.set_seed(0)
trainer = Trainer(snapshot_config)
env = normalize(GymEnv('InvertedPendulum-v2'))
policy = DeterministicMLPPolicy(env_spec=env.spec,
hidden_sizes=[64, 64],
hidden_nonlinearity=F.relu,
output_nonlinearity=torch.tanh)
exploration_policy = AddOrnsteinUhlenbeckNoise(env.spec,
policy,
sigma=0.2)
qf = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[64, 64],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6))
sampler = LocalSampler(agents=exploration_policy,
envs=env,
max_episode_length=env.spec.max_episode_length,
worker_class=FragmentWorker)
algo = DDPG(env_spec=env.spec,
policy=policy,
qf=qf,
replay_buffer=replay_buffer,
sampler=sampler,
steps_per_epoch=20,
n_train_steps=50,
min_buffer_size=int(1e4),
exploration_policy=exploration_policy,
target_update_tau=1e-2,
discount=0.9)
trainer.setup(algo, env)
last_avg_ret = trainer.train(n_epochs=10, batch_size=100)
assert last_avg_ret > 10
env.close()
|
Test DDPG with Pendulum environment.
This environment has a [-3, 3] action_space bound.
|
test_ddpg_pendulum
|
python
|
rlworkgroup/garage
|
tests/garage/torch/algos/test_ddpg.py
|
https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_ddpg.py
|
MIT
|
def setup_method(self):
"""Setup method which is called before every test."""
self.env = normalize(GymEnv(HalfCheetahDirEnv(),
max_episode_length=100),
expected_action_scale=10.)
task_sampler = SetTaskSampler(lambda: normalize(
GymEnv(HalfCheetahDirEnv()), expected_action_scale=10.))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None,
)
self.value_function = GaussianMLPValueFunction(env_spec=self.env.spec,
hidden_sizes=(32, 32))
self.algo = MAMLPPO(env=self.env,
policy=self.policy,
sampler=None,
task_sampler=task_sampler,
value_function=self.value_function,
meta_batch_size=5,
discount=0.99,
gae_lambda=1.,
inner_lr=0.1,
num_grad_updates=1)
|
Setup method which is called before every test.
|
setup_method
|
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_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 untouched
self.policy.apply(partial(self._test_params, 0.1))
adapt_policy.apply(partial(self._test_params, 0.2))
|
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._set_params, 0.1))
adapt_policy = self.algo.get_exploration_policy()
eps = sampler.obtain_samples(0, 100, adapt_policy)
self.algo.adapt_policy(adapt_policy, eps)
# Old policy should remain untouched
self.policy.apply(partial(self._test_params, 0.1))
# Adapted policy should not be identical to old policy
for v1, v2 in zip(adapt_policy.parameters(), self.policy.parameters()):
if v1.data.ne(v2.data).sum() > 0:
break
else:
pytest.fail('Parameters of adapted policy should not be '
'identical to the old policy.')
|
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 setup_method(self):
"""Setup method which is called before every test."""
self.env = normalize(GymEnv(HalfCheetahDirEnv(),
max_episode_length=100),
expected_action_scale=10.)
self.task_sampler = SetTaskSampler(
HalfCheetahDirEnv,
wrapper=lambda env, _: normalize(GymEnv(env,
max_episode_length=100),
expected_action_scale=10.))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None,
)
self.value_function = GaussianMLPValueFunction(env_spec=self.env.spec,
hidden_sizes=(32, 32))
self.sampler = LocalSampler(
agents=self.policy,
envs=self.env,
max_episode_length=self.env.spec.max_episode_length)
|
Setup method which is called before every test.
|
setup_method
|
python
|
rlworkgroup/garage
|
tests/garage/torch/algos/test_maml_ppo.py
|
https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_maml_ppo.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),
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None,
)
value_function = GaussianMLPValueFunction(env_spec=env.spec,
hidden_sizes=(32, 32))
task_sampler = SetTaskSampler(
DummyMultiTaskBoxEnv,
wrapper=lambda env, _: normalize(GymEnv(env, max_episode_length=100),
expected_action_scale=10.))
episodes_per_task = 2
max_episode_length = env.spec.max_episode_length
sampler = LocalSampler(agents=policy,
envs=env,
max_episode_length=env.spec.max_episode_length)
trainer = Trainer(snapshot_config)
algo = MAMLTRPO(env=env,
policy=policy,
sampler=sampler,
task_sampler=task_sampler,
value_function=value_function,
meta_batch_size=5,
discount=0.99,
gae_lambda=1.,
inner_lr=0.1,
num_grad_updates=1)
trainer.setup(algo, env)
trainer.train(n_epochs=2,
batch_size=episodes_per_task * max_episode_length)
|
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 setup_method(self):
"""Setup method which is called before every test."""
max_episode_length = 100
self.env = normalize(GymEnv(HalfCheetahDirEnv(),
max_episode_length=max_episode_length),
expected_action_scale=10.)
self.task_sampler = SetTaskSampler(
HalfCheetahDirEnv,
wrapper=lambda env, _: normalize(GymEnv(
env, max_episode_length=max_episode_length),
expected_action_scale=10.))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None,
)
self.value_function = GaussianMLPValueFunction(env_spec=self.env.spec,
hidden_sizes=(32, 32))
|
Setup method which is called before every test.
|
setup_method
|
python
|
rlworkgroup/garage
|
tests/garage/torch/algos/test_maml_vpg.py
|
https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_maml_vpg.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 = MultiEnvWrapper(task_envs, sample_strategy=round_robin_strategy)
deterministic.set_seed(0)
policy = TanhGaussianMLPPolicy(
env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=torch.nn.ReLU,
output_nonlinearity=None,
min_std=np.exp(-20.),
max_std=np.exp(2.),
)
qf1 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=F.relu)
qf2 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6), )
num_tasks = 2
buffer_batch_size = 2
mtsac = MTSAC(policy=policy,
qf1=qf1,
qf2=qf2,
sampler=None,
gradient_steps_per_itr=150,
eval_env=[env],
env_spec=env.spec,
num_tasks=num_tasks,
steps_per_epoch=5,
replay_buffer=replay_buffer,
min_buffer_size=1e3,
target_update_tau=5e-3,
discount=0.99,
buffer_batch_size=buffer_batch_size)
monkeypatch.setattr(mtsac, '_log_alpha', torch.Tensor([1., 2.]))
for i, _ in enumerate(env_names):
obs = torch.Tensor([env.reset()[0]] * buffer_batch_size)
log_alpha = mtsac._get_log_alpha(dict(observation=obs))
assert (log_alpha == torch.Tensor([i + 1, i + 1])).all().item()
assert log_alpha.size() == torch.Size([mtsac._buffer_batch_size])
|
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']
task_envs = [GymEnv(name, max_episode_length=150) for name in env_names]
env = MultiEnvWrapper(task_envs, sample_strategy=round_robin_strategy)
deterministic.set_seed(0)
policy = TanhGaussianMLPPolicy(
env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=torch.nn.ReLU,
output_nonlinearity=None,
min_std=np.exp(-20.),
max_std=np.exp(2.),
)
qf1 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=F.relu)
qf2 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6), )
buffer_batch_size = 2
mtsac = MTSAC(policy=policy,
qf1=qf1,
qf2=qf2,
sampler=None,
gradient_steps_per_itr=150,
eval_env=[env],
env_spec=env.spec,
num_tasks=4,
steps_per_epoch=5,
replay_buffer=replay_buffer,
min_buffer_size=1e3,
target_update_tau=5e-3,
discount=0.99,
buffer_batch_size=buffer_batch_size)
monkeypatch.setattr(mtsac, '_log_alpha', torch.Tensor([1., 2.]))
error_string = ('The number of tasks in the environment does '
'not match self._num_tasks. Are you sure that you passed '
'The correct number of tasks?')
obs = torch.Tensor([env.reset()[0]] * buffer_batch_size)
with pytest.raises(ValueError, match=error_string):
mtsac._get_log_alpha(dict(observation=obs))
|
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_strategy=round_robin_strategy)
test_envs = MultiEnvWrapper(task_envs,
sample_strategy=round_robin_strategy)
deterministic.set_seed(0)
trainer = Trainer(snapshot_config=snapshot_config)
policy = TanhGaussianMLPPolicy(
env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=torch.nn.ReLU,
output_nonlinearity=None,
min_std=np.exp(-20.),
max_std=np.exp(2.),
)
qf1 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
qf2 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6), )
num_tasks = 2
buffer_batch_size = 128
sampler = LocalSampler(agents=policy,
envs=env,
max_episode_length=env.spec.max_episode_length,
worker_class=FragmentWorker)
mtsac = MTSAC(policy=policy,
qf1=qf1,
qf2=qf2,
sampler=sampler,
gradient_steps_per_itr=100,
eval_env=[test_envs],
env_spec=env.spec,
num_tasks=num_tasks,
steps_per_epoch=5,
replay_buffer=replay_buffer,
min_buffer_size=1e3,
target_update_tau=5e-3,
discount=0.99,
buffer_batch_size=buffer_batch_size)
trainer.setup(mtsac, env)
ret = trainer.train(n_epochs=8, batch_size=128, plot=False)
assert ret > 0
|
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 = MultiEnvWrapper(task_envs, sample_strategy=round_robin_strategy)
deterministic.set_seed(0)
policy = TanhGaussianMLPPolicy(
env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=torch.nn.ReLU,
output_nonlinearity=None,
min_std=np.exp(-20.),
max_std=np.exp(2.),
)
qf1 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=F.relu)
qf2 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[1, 1],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6), )
num_tasks = 2
buffer_batch_size = 2
mtsac = MTSAC(policy=policy,
qf1=qf1,
qf2=qf2,
sampler=None,
gradient_steps_per_itr=150,
eval_env=[env],
env_spec=env.spec,
num_tasks=num_tasks,
steps_per_epoch=5,
replay_buffer=replay_buffer,
min_buffer_size=1e3,
target_update_tau=5e-3,
discount=0.99,
buffer_batch_size=buffer_batch_size)
set_gpu_mode(torch.cuda.is_available())
mtsac.to()
device = global_device()
for param in mtsac._qf1.parameters():
assert param.device == device
for param in mtsac._qf2.parameters():
assert param.device == device
for param in mtsac._qf2.parameters():
assert param.device == device
for param in mtsac.policy.parameters():
assert param.device == device
assert mtsac._log_alpha.device == device
|
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_strategy)
test_envs = MultiEnvWrapper(task_envs,
sample_strategy=round_robin_strategy)
deterministic.set_seed(0)
trainer = Trainer(snapshot_config=snapshot_config)
policy = TanhGaussianMLPPolicy(
env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=torch.nn.ReLU,
output_nonlinearity=None,
min_std=np.exp(-20.),
max_std=np.exp(2.),
)
qf1 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
qf2 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6), )
num_tasks = 2
buffer_batch_size = 128
sampler = LocalSampler(agents=policy,
envs=env,
max_episode_length=env.spec.max_episode_length,
worker_class=FragmentWorker)
mtsac = MTSAC(policy=policy,
qf1=qf1,
qf2=qf2,
sampler=sampler,
gradient_steps_per_itr=100,
eval_env=[test_envs],
env_spec=env.spec,
num_tasks=num_tasks,
steps_per_epoch=1,
replay_buffer=replay_buffer,
min_buffer_size=1e3,
target_update_tau=5e-3,
discount=0.99,
buffer_batch_size=buffer_batch_size,
fixed_alpha=np.exp(0.5))
if torch.cuda.is_available():
set_gpu_mode(True)
else:
set_gpu_mode(False)
mtsac.to()
assert torch.allclose(torch.Tensor([0.5] * num_tasks),
mtsac._log_alpha.to('cpu'))
trainer.setup(mtsac, env)
trainer.train(n_epochs=1, batch_size=128, plot=False)
assert torch.allclose(torch.Tensor([0.5] * num_tasks),
mtsac._log_alpha.to('cpu'))
assert not mtsac._use_automatic_entropy_tuning
|
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 setup_method(self):
"""Setup method which is called before every test."""
self.env = normalize(
GymEnv('InvertedDoublePendulum-v2', max_episode_length=100))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None,
)
self.value_function = GaussianMLPValueFunction(env_spec=self.env.spec)
|
Setup method which is called before every test.
|
setup_method
|
python
|
rlworkgroup/garage
|
tests/garage/torch/algos/test_ppo.py
|
https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_ppo.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(
env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=torch.nn.ReLU,
output_nonlinearity=None,
min_std=np.exp(-20.),
max_std=np.exp(2.),
)
qf1 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
qf2 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6), )
trainer = Trainer(snapshot_config=snapshot_config)
sampler = LocalSampler(agents=policy,
envs=env,
max_episode_length=env.spec.max_episode_length,
worker_class=FragmentWorker)
sac = SAC(env_spec=env.spec,
policy=policy,
qf1=qf1,
qf2=qf2,
sampler=sampler,
gradient_steps_per_itr=100,
replay_buffer=replay_buffer,
min_buffer_size=1e3,
target_update_tau=5e-3,
discount=0.99,
buffer_batch_size=64,
reward_scale=1.,
steps_per_epoch=2)
trainer.setup(sac, env)
if torch.cuda.is_available():
set_gpu_mode(True)
else:
set_gpu_mode(False)
sac.to()
ret = trainer.train(n_epochs=12, batch_size=200, plot=False)
# check that automatic entropy tuning is used
assert sac._use_automatic_entropy_tuning
# assert that there was a gradient properly connected to alpha
# this doesn't verify that the path from the temperature objective is
# correct.
assert not torch.allclose(torch.Tensor([1.]), sac._log_alpha.to('cpu'))
# check that policy is learning beyond predecided threshold
assert ret > 80
|
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_fixed_alpha():
"""Test if using fixed_alpha ensures that alpha is non differentiable."""
# pylint: disable=unexpected-keyword-arg
env = normalize(GymEnv('InvertedDoublePendulum-v2',
max_episode_length=100))
deterministic.set_seed(0)
policy = TanhGaussianMLPPolicy(
env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=torch.nn.ReLU,
output_nonlinearity=None,
min_std=np.exp(-20.),
max_std=np.exp(2.),
)
qf1 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
qf2 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6), )
trainer = Trainer(snapshot_config=snapshot_config)
sampler = LocalSampler(agents=policy,
envs=env,
max_episode_length=env.spec.max_episode_length,
worker_class=FragmentWorker)
sac = SAC(env_spec=env.spec,
policy=policy,
qf1=qf1,
qf2=qf2,
sampler=sampler,
gradient_steps_per_itr=100,
replay_buffer=replay_buffer,
min_buffer_size=100,
target_update_tau=5e-3,
discount=0.99,
buffer_batch_size=64,
reward_scale=1.,
steps_per_epoch=1,
fixed_alpha=np.exp(0.5))
trainer.setup(sac, env)
sac.to()
trainer.train(n_epochs=1, batch_size=100, plot=False)
assert torch.allclose(torch.Tensor([0.5]), sac._log_alpha.cpu())
assert not sac._use_automatic_entropy_tuning
|
Test if using fixed_alpha ensures that alpha is non differentiable.
|
test_fixed_alpha
|
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_nonlinearity=torch.nn.ReLU,
output_nonlinearity=None,
min_std=np.exp(-20.),
max_std=np.exp(2.),
)
qf1 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
qf2 = ContinuousMLPQFunction(env_spec=env.spec,
hidden_sizes=[32, 32],
hidden_nonlinearity=F.relu)
replay_buffer = PathBuffer(capacity_in_transitions=int(1e6), )
trainer = Trainer(snapshot_config=snapshot_config)
sampler = LocalSampler(agents=policy,
envs=env,
max_episode_length=env.spec.max_episode_length,
worker_class=FragmentWorker)
sac = SAC(env_spec=env.spec,
policy=policy,
qf1=qf1,
qf2=qf2,
sampler=sampler,
gradient_steps_per_itr=100,
replay_buffer=replay_buffer,
min_buffer_size=1e3,
target_update_tau=5e-3,
discount=0.99,
buffer_batch_size=64,
reward_scale=1.,
steps_per_epoch=2)
trainer.setup(sac, env)
if torch.cuda.is_available():
set_gpu_mode(True)
else:
set_gpu_mode(False)
sac.to()
trainer.setup(algo=sac, env=env)
trainer.train(n_epochs=1, batch_size=100)
log_alpha = torch.clone(sac._log_alpha).cpu()
set_gpu_mode(False)
sac.to()
assert torch.allclose(log_alpha, sac._log_alpha)
|
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 setup_method(self):
"""Setup method which is called before every test."""
self.env = normalize(
GymEnv('InvertedDoublePendulum-v2', max_episode_length=100))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None,
)
self.value_function = GaussianMLPValueFunction(env_spec=self.env.spec)
|
Setup method which is called before every test.
|
setup_method
|
python
|
rlworkgroup/garage
|
tests/garage/torch/algos/test_trpo.py
|
https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/algos/test_trpo.py
|
MIT
|
def setup_method(self):
"""Setup method which is called before every test."""
self._env = GymEnv('InvertedDoublePendulum-v2', max_episode_length=100)
self._trainer = Trainer(snapshot_config)
self._policy = GaussianMLPPolicy(env_spec=self._env.spec,
hidden_sizes=[64, 64],
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None)
self._sampler = LocalSampler(
agents=self._policy,
envs=self._env,
max_episode_length=self._env.spec.max_episode_length)
self._params = {
'env_spec': self._env.spec,
'policy': self._policy,
'value_function':
GaussianMLPValueFunction(env_spec=self._env.spec),
'sampler': self._sampler,
'discount': 0.99,
}
|
Setup method which is called before every test.
|
setup_method
|
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_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 = torch.ones(1) * 100
dist = TanhNormal(mean, std)
assert dist.mean >= -1.
|
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_tanh_action.tanh() == action).all()
assert -1 <= action <= 1.
assert -1 <= sample <= 1.
del dist
|
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 = dist.log_prob(action, pre_tanh_action)
log_prob_approx = dist.log_prob(action)
assert torch.allclose(log_prob, torch.Tensor([-0.2798519]))
assert torch.allclose(log_prob_approx, torch.Tensor([-0.2798185]))
del dist
|
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, std)
new_dist = dist.expand((2, ))
sample = new_dist.sample()
assert sample.shape == torch.Size((2, 1))
|
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)
assert torch.isfinite(log_prob_approx)
assert log_prob_approx < -20
del dist
|
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]): strides.
paddings (tuple[int]): value of zero-padding.
"""
module_with_nonlinear_function_and_module = CNNModule(
self.input_spec,
image_format='NCHW',
hidden_channels=hidden_channels,
kernel_sizes=kernel_sizes,
strides=strides,
paddings=paddings,
padding_mode='zeros',
hidden_nonlinearity=torch.relu,
hidden_w_init=nn.init.xavier_uniform_)
module_with_nonlinear_module_instance_and_function = CNNModule(
self.input_spec,
image_format='NCHW',
hidden_channels=hidden_channels,
kernel_sizes=kernel_sizes,
strides=strides,
paddings=paddings,
padding_mode='zeros',
hidden_nonlinearity=nn.ReLU(),
hidden_w_init=nn.init.xavier_uniform_)
output1 = module_with_nonlinear_function_and_module(self.input)
output2 = module_with_nonlinear_module_instance_and_function(
self.input)
current_size = self.input_width
for (filter_size, stride, padding) in zip(kernel_sizes, strides,
paddings):
# padding = float((filter_size - 1) / 2) # P = (F - 1) /2
current_size = int(
(current_size - filter_size + padding * 2) /
stride) + 1 # conv formula = ((W - F + 2P) / S) + 1
flatten_shape = current_size * current_size * hidden_channels[-1]
expected_output = torch.zeros((self.batch_size, flatten_shape))
assert np.array_equal(torch.all(torch.eq(output1, expected_output)),
True)
assert np.array_equal(torch.all(torch.eq(output2, expected_output)),
True)
|
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 channels.
strides (tuple[int]): strides.
paddings (tuple[int]): value of zero-padding.
"""
model = CNNModule(self.input_spec,
image_format='NCHW',
hidden_channels=hidden_channels,
kernel_sizes=kernel_sizes,
strides=strides,
paddings=paddings,
padding_mode='zeros',
hidden_nonlinearity=torch.relu,
hidden_w_init=nn.init.xavier_uniform_)
output = model(self.input)
current_size = self.input_width
for (filter_size, stride, padding) in zip(kernel_sizes, strides,
paddings):
# padding = float((filter_size - 1) / 2) # P = (F - 1) /2
current_size = int(
(current_size - filter_size + padding * 2) /
stride) + 1 # conv formula = ((W - F + 2P) / S) + 1
flatten_shape = current_size * current_size * hidden_channels[-1]
expected_output = torch.zeros((self.batch_size, flatten_shape))
assert np.array_equal(torch.all(torch.eq(output, expected_output)),
True)
|
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(self.input_spec,
image_format='NCHW',
hidden_channels=hidden_channels,
kernel_sizes=kernel_sizes,
strides=strides)
output1 = model(self.input)
h = pickle.dumps(model)
model_pickled = pickle.loads(h)
output2 = model_pickled(self.input)
assert np.array_equal(torch.all(torch.eq(output1, output2)), True)
|
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 function .* is not supported'
with pytest.raises(ValueError, match=expected_msg):
CNNModule(self.input_spec,
image_format='NCHW',
hidden_channels=(32, ),
kernel_sizes=(3, ),
strides=(1, ),
hidden_nonlinearity=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.
|
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.ones([1, input_dim], dtype=torch.float32)
module_with_nonlinear_function_and_module = MLPModule(
input_dim=input_dim,
output_dim=output_dim,
hidden_nonlinearity=torch.relu,
hidden_sizes=hidden_sizes,
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_,
output_nonlinearity=torch.nn.ReLU)
module_with_nonlinear_module_instance_and_function = MLPModule(
input_dim=input_dim,
output_dim=output_dim,
hidden_nonlinearity=torch.nn.ReLU(),
hidden_sizes=hidden_sizes,
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_,
output_nonlinearity=torch.relu)
output1 = module_with_nonlinear_function_and_module(input_val)
output2 = module_with_nonlinear_module_instance_and_function(input_val)
expected_output = torch.full([1, output_dim],
fill_value=5 * np.prod(hidden_sizes),
dtype=torch.float32)
assert torch.all(torch.eq(expected_output, output1))
assert torch.all(torch.eq(expected_output, output2))
|
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([1, input_dim], dtype=torch.float32)
module = MLPModule(input_dim=input_dim,
output_dim=output_dim,
hidden_nonlinearity=torch.relu,
hidden_sizes=hidden_sizes,
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_,
output_nonlinearity=torch.nn.ReLU)
output1 = module(input_val)
h = pickle.dumps(module)
model_pickled = pickle.loads(h)
output2 = model_pickled(input_val)
assert np.array_equal(torch.all(torch.eq(output1, output2)), True)
|
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 layers.
output_nonlinear (callable or torch.nn.Module): Non-linear
functions for output layer.
"""
expected_msg = 'Non linear function .* is not supported'
with pytest.raises(ValueError, match=expected_msg):
MLPModule(input_dim=3,
output_dim=5,
hidden_sizes=(2, 3),
hidden_nonlinearity=hidden_nonlinear,
output_nonlinearity=output_nonlinear)
|
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,
output_dim=output_dim,
hidden_nonlinearity=torch.nn.PReLU(init=10.),
hidden_sizes=hidden_sizes,
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_,
output_nonlinearity=torch.nn.PReLU(init=1.))
output = module(input_val)
output.sum().backward()
for tt in module.parameters():
assert torch.all(torch.ne(tt.grad, 0))
|
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.
output_w_init_vals (list[int]): Init values for output weights.
n_heads (int): Number of output layers.
"""
module = MultiHeadedMLPModule(n_heads=n_heads,
input_dim=input_dim,
output_dims=output_dim,
hidden_sizes=hidden_sizes,
hidden_nonlinearity=None,
hidden_w_init=nn.init.ones_,
output_nonlinearities=None,
output_w_inits=list(
map(_helper_make_inits,
output_w_init_vals)))
input_value = torch.ones(input_dim)
outputs = module(input_value)
if len(output_w_init_vals) == 1:
output_w_init_vals = list(output_w_init_vals) * n_heads
if len(output_dim) == 1:
output_dim = list(output_dim) * n_heads
for i, output in enumerate(outputs):
expected = input_dim * torch.Tensor(hidden_sizes).prod()
expected *= output_w_init_vals[i]
assert torch.equal(
output, torch.full((output_dim[i], ), expected, dtype=torch.float))
|
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 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.
"""
module = MultiHeadedMLPModule(n_heads=n_heads,
input_dim=input_dim,
output_dims=output_dim,
hidden_sizes=hidden_sizes,
hidden_nonlinearity=None,
layer_normalization=True,
hidden_w_init=nn.init.ones_,
output_nonlinearities=None,
output_w_inits=list(
map(_helper_make_inits,
output_w_init_vals)))
input_value = torch.ones(input_dim)
outputs = module(input_value)
if len(output_w_init_vals) == 1:
output_w_init_vals = list(output_w_init_vals) * n_heads
if len(output_dim) == 1:
output_dim = list(output_dim) * n_heads
for i, output in enumerate(outputs):
expected = input_dim * torch.Tensor(hidden_sizes).prod()
expected *= output_w_init_vals[i]
assert torch.equal(output, torch.zeros(output_dim[i]))
|
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 layers.
|
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]): Size of hidden layers.
n_heads (int): Number of output layers.
nonlinearity (callable or torch.nn.Module): Non-linear functions for
output layers
w_init (list[callable]): Initializer function for the weight in
output layer.
b_init (list[callable]): Initializer function for the bias in
output layer.
"""
expected_msg_template = ('should be either an integer or a collection of '
'length n_heads')
with pytest.raises(ValueError, match=expected_msg_template):
MultiHeadedMLPModule(n_heads=n_heads,
input_dim=input_dim,
output_dims=output_dim,
hidden_sizes=hidden_sizes,
hidden_nonlinearity=None,
hidden_w_init=nn.init.ones_,
output_nonlinearities=nonlinearity,
output_w_inits=list(
map(_helper_make_inits, w_init)),
output_b_inits=b_init)
|
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 functions for
output layers
w_init (list[callable]): Initializer function for the weight in
output layer.
b_init (list[callable]): Initializer function for the bias in
output layer.
|
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 = torch.sum(theta**2)
meta_loss.backward(create_graph=True)
diff_sgd.step()
theta_prime = list(policy.parameters())[0]
loss = torch.sum(theta_prime**2)
update_module_params(policy, named_theta)
diff_sgd.zero_grad()
loss.backward()
result = theta.grad
dtheta_prime = 1 - 2 * lr # dtheta_prime/dtheta
dloss = 2 * theta_prime # dloss/dtheta_prime
expected_result = dloss * dtheta_prime # dloss/dtheta
assert torch.allclose(result, expected_result)
|
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_num_steps = 1
loss_calls = 0
first_time = True
def f_loss():
nonlocal loss_calls, first_time
if first_time:
first_time = False
else:
loss_calls += 1
return -torch.tensor(loss_calls)
kl_calls = 0
def f_constrint():
nonlocal kl_calls
kl_calls += 1
return -torch.tensor(kl_calls)
descent_step = torch.tensor([0.05, 0.05])
optimizer._backtracking_line_search(params, descent_step, f_loss,
f_constrint)
assert loss_calls == expected_num_steps
assert kl_calls == expected_num_steps
|
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 = []
loss = 0
first_time = True
def f_loss():
nonlocal loss, first_time
if first_time:
first_time = False
else:
p1_history.append(p1.clone())
p2_history.append(p2.clone())
loss += 1
return torch.tensor(loss)
def f_constrint():
return torch.tensor(0)
descent_step = torch.tensor([0.05, 0.05])
optimizer._backtracking_line_search(params, descent_step, f_loss,
f_constrint)
p1_steps = []
p2_steps = []
for i in range(len(p1_history) - 1):
p1_steps.append(p1_history[i + 1] - p1_history[i])
p2_steps.append(p2_history[i + 1] - p2_history[i])
for i in range(len(p1_steps) - 1):
assert p1_steps[i] > p1_steps[i + 1]
assert p2_steps[i] > p2_steps[i + 1]
|
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_cg():
"""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
def hvp(v):
return torch.tensor(a.dot(v))
b = torch.tensor(np.linspace(-np.pi, np.pi, 5))
x = _conjugate_gradient(hvp, b, 5)
assert np.allclose(a.dot(x), b)
|
Solve Ax = b using Conjugate gradient method.
|
test_cg
|
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():
"""Test Hessian-vector product for a function with one variable."""
a = torch.tensor([5.0])
x = torch.tensor([10.0], requires_grad=True)
def f():
return a * (x**2)
expected_hessian = 2 * a
vector = torch.tensor([10.0])
expected_hvp = (expected_hessian * vector).detach()
f_Ax = _build_hessian_vector_product(f, [x])
computed_hvp = f_Ax(vector).detach()
assert np.allclose(computed_hvp, expected_hvp)
|
Test Hessian-vector product for a function with one variable.
|
test_hessian_vector_product
|
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 f():
a, b = obs[0], obs[1]
return a * (x**2) + b * (y**2)
expected_hessian = compute_hessian(f(), [x, y])
expected_hvp = torch.mm(vector, expected_hessian).detach()
f_Ax = _build_hessian_vector_product(f, [x, y])
hvp = f_Ax(vector[0]).detach()
assert np.allclose(hvp, expected_hvp, atol=1e-6)
|
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.tensor([x_val], requires_grad=True)
y = torch.tensor([y_val], requires_grad=True)
def f():
a, b = obs[0], obs[1]
kl = a * (x**3) + b * (y**3) + (x**2) * y + (y**2) * x
return kl
expected_hessian = compute_hessian(f(), [x, y])
expected_hvp = torch.mm(vector, expected_hessian).detach()
f_Ax = _build_hessian_vector_product(f, [x, y])
hvp = f_Ax(vector[0]).detach()
assert np.allclose(hvp, expected_hvp)
|
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,
allow_unused=True,
retain_graph=True)
h_ij = (torch.tensor(0.), ) if h_ij[0] is None else h_ij
h_i.append(h_ij[0])
h_i = torch.stack(h_i)
h.append(h_i)
h = torch.stack(h)
h = h.reshape((len(params), len(params)))
return h
|
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)
optimizer2 = pickle.loads(optimizer_pickled)
assert optimizer._max_constraint_value == optimizer2._max_constraint_value
assert optimizer._cg_iters == optimizer2._cg_iters
assert optimizer._max_backtracks == optimizer2._max_backtracks
assert optimizer._backtrack_ratio == optimizer2._backtrack_ratio
assert optimizer._hvp_reg_coeff == optimizer2._hvp_reg_coeff
assert optimizer._accept_violation == optimizer2._accept_violation
|
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_unpickle_empty_state():
"""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 = BrokenPicklingConjugateGradientOptimizer(params, 0.02)
optimizer_pickled = pickle.dumps(optimizer)
optimizer2 = pickle.loads(optimizer_pickled)
assert optimizer2._max_constraint_value == 0.01
# These asserts only pass because they contain the default values.
assert optimizer._cg_iters == optimizer2._cg_iters
assert optimizer._max_backtracks == optimizer2._max_backtracks
assert optimizer._backtrack_ratio == optimizer2._backtrack_ratio
assert optimizer._hvp_reg_coeff == optimizer2._hvp_reg_coeff
assert optimizer._accept_violation == optimizer2._accept_violation
|
Test that pickling works as one would normally expect.
|
test_unpickle_empty_state
|
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,
image_format='NHWC',
kernel_sizes=kernel_sizes,
hidden_channels=hidden_channels,
strides=strides,
hidden_sizes=hidden_sizes)
env.reset()
obs = env.step(1).observation
action, _ = policy.get_action(obs)
assert env.action_space.contains(action)
|
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,
image_format='NHWC',
kernel_sizes=kernel_sizes,
hidden_channels=hidden_channels,
strides=strides,
hidden_sizes=hidden_sizes)
env.reset()
obs = env.step(1).observation
actions, _ = policy.get_actions([obs, obs, obs])
for action in actions:
assert env.action_space.contains(action)
torch_obs = torch.Tensor(obs)
actions, _ = policy.get_actions([torch_obs, torch_obs, torch_obs])
for action in actions:
assert env.action_space.contains(action)
|
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_does_not_support_dict_obs_space(self):
"""Test that policy raises error if passed a dict obs space."""
env = GymEnv(DummyDictEnv(act_space_type='discrete'))
with pytest.raises(ValueError,
match=('CNN policies do not support '
'with akro.Dict observation spaces.')):
CategoricalCNNPolicy(env_spec=env.spec,
image_format='NHWC',
kernel_sizes=(3, ),
hidden_channels=(3, ))
|
Test that policy raises error if passed a dict obs space.
|
test_does_not_support_dict_obs_space
|
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',
kernel_sizes=(3, ),
hidden_channels=(3, ))
|
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_obs_unflattened(self, hidden_channels, kernel_sizes, strides,
hidden_sizes):
"""Test if a flattened image obs is passed to get_action
then it is unflattened.
"""
env = GymEnv(DummyDiscretePixelEnv(), is_image=True)
env.reset()
policy = CategoricalCNNPolicy(env_spec=env.spec,
image_format='NHWC',
kernel_sizes=kernel_sizes,
hidden_channels=hidden_channels,
strides=strides,
hidden_sizes=hidden_sizes)
obs = env.observation_space.sample()
action, _ = policy.get_action(env.observation_space.flatten(obs))
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/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,
hidden_sizes=(1, ),
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
obs = env.reset()[0]
action, _ = policy.get_action(obs)
assert env.action_space.shape == action.shape
actions, _ = policy.get_actions(np.array([obs, obs]))
for action in actions:
assert env.action_space.shape == action.shape
|
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_obs_unflattened(self, kernel_sizes, hidden_channels, strides,
paddings):
"""Test if a flattened image obs is passed to get_action
then it is unflattened.
"""
env = GymEnv(DummyDiscretePixelEnv())
env.reset()
policy = DiscreteCNNPolicy(env_spec=env.spec,
image_format='NHWC',
hidden_channels=hidden_channels,
kernel_sizes=kernel_sizes,
strides=strides,
paddings=paddings,
padding_mode='zeros',
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
obs = env.observation_space.sample()
action, _ = policy.get_action(env.observation_space.flatten(obs))
env.step(action[0])
|
Test if a flattened image obs is passed to get_action
then it is unflattened.
|
test_obs_unflattened
|
python
|
rlworkgroup/garage
|
tests/garage/torch/policies/test_discrete_cnn_policy.py
|
https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_discrete_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 = GaussianMLPPolicy(env_spec=env.spec,
hidden_nonlinearity=None,
hidden_sizes=(1, ),
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
obs = env.reset()[0]
action, _ = policy.get_action(obs)
assert env.action_space.shape == action.shape
actions, _ = policy.get_actions(np.array([obs, obs]))
for action in actions:
assert env.action_space.shape == action.shape
actions, _ = policy.get_actions(np.array([obs, obs]))
for action in actions:
assert env.action_space.shape == action.shape
|
Test if observations from dict obs spaces are properly flattened.
|
test_get_action_dict_space
|
python
|
rlworkgroup/garage
|
tests/garage/torch/policies/test_gaussian_mlp_policy.py
|
https://github.com/rlworkgroup/garage/blob/master/tests/garage/torch/policies/test_gaussian_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)
init_std = 2.
policy = TanhGaussianMLPPolicy(env_spec=env_spec,
hidden_sizes=hidden_sizes,
init_std=init_std,
hidden_nonlinearity=None,
std_parameterization='exp',
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
expected_mean = torch.full((act_dim, ), 1.0, dtype=torch.float)
action, prob = policy.get_action(obs)
assert np.allclose(prob['mean'], expected_mean.numpy(), rtol=1e-3)
assert action.shape == (act_dim, )
|
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_std = 2.
policy = TanhGaussianMLPPolicy(env_spec=env_spec,
hidden_sizes=hidden_sizes,
init_std=init_std,
hidden_nonlinearity=None,
std_parameterization='exp',
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
expected_mean = torch.full((act_dim, ), 1.0, dtype=torch.float)
action, prob = policy.get_action(obs)
assert np.allclose(prob['mean'], expected_mean.numpy(), rtol=1e-3)
assert action.shape == (act_dim, )
|
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.float32)
init_std = 2.
policy = TanhGaussianMLPPolicy(env_spec=env_spec,
hidden_sizes=hidden_sizes,
init_std=init_std,
hidden_nonlinearity=None,
std_parameterization='exp',
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
expected_mean = torch.full([batch_size, act_dim],
1.0,
dtype=torch.float)
action, prob = policy.get_actions(obs)
assert np.allclose(prob['mean'], expected_mean.numpy(), rtol=1e-3)
assert action.shape == (batch_size, act_dim)
|
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)
init_std = 2.
policy = TanhGaussianMLPPolicy(env_spec=env_spec,
hidden_sizes=hidden_sizes,
init_std=init_std,
hidden_nonlinearity=None,
std_parameterization='exp',
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
expected_mean = torch.full([batch_size, act_dim],
1.0,
dtype=torch.float)
action, prob = policy.get_actions(obs)
assert np.allclose(prob['mean'], expected_mean.numpy(), rtol=1e-3)
assert action.shape == (batch_size, act_dim)
|
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 = TanhGaussianMLPPolicy(env_spec=env_spec,
hidden_sizes=hidden_sizes,
init_std=init_std,
hidden_nonlinearity=None,
std_parameterization='exp',
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
output1_action, output1_prob = policy.get_actions(obs)
p = pickle.dumps(policy)
policy_pickled = pickle.loads(p)
output2_action, output2_prob = policy_pickled.get_actions(obs)
assert np.allclose(output2_prob['mean'],
output1_prob['mean'],
rtol=1e-3)
assert output1_action.shape == output2_action.shape
|
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,
hidden_nonlinearity=None,
std_parameterization='exp',
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
if torch.cuda.is_available():
policy.to(torch.device('cuda:0'))
assert str(next(policy.parameters()).device) == 'cuda:0'
else:
policy.to(None)
assert str(next(policy.parameters()).device) == 'cpu'
|
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 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 = TanhGaussianMLPPolicy(env_spec=env.spec,
hidden_nonlinearity=None,
hidden_sizes=(1, ),
hidden_w_init=nn.init.ones_,
output_w_init=nn.init.ones_)
obs = env.reset()[0]
action, _ = policy.get_action(obs)
assert env.action_space.shape == action.shape
actions, _ = policy.get_actions(np.array([obs, obs]))
for action in actions:
assert env.action_space.shape == action.shape
|
Test if observations from dict obs spaces are properly flattened.
|
test_get_action_dict_space
|
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 assertion is evaluated
assert subprocess.run([filepath], check=False, env=env).returncode == 0
|
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_episode_length', '5'
],
check=False,
env=env).returncode == 0
|
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',
'--max_episode_length', '1'
],
check=False,
env=env).returncode == 0
|
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',
'--max_episode_length', '5'
]
assert subprocess.run(command, check=False, env=env).returncode == 0
|
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',
'--max_episode_length', '5'
],
check=False,
env=env).returncode == 0
|
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.
proc = subprocess.Popen(args, preexec_fn=os.setpgrp)
launcher_proc = psutil.Process(proc.pid)
# This socket connects with the client in the algorithm, so we're
# notified of the different stages in the experiment lifecycle.
address = ('localhost', 6000)
listener = Listener(address)
conn = listener.accept()
while True:
msg = conn.recv()
if msg == lifecycle_stage:
# Notice that we're asking for the children of the launcher, not
# the children of this test script, since there could be other
# children processes attached to the process running this test
# that are not part of the launcher.
children = launcher_proc.children(recursive=True)
# Remove the semaphore tracker from the list of children, since
# we cannot stop its execution.
for child in children:
if any([
'multiprocessing.semaphore_tracker' in cmd
for cmd in child.cmdline()
]):
children.remove(child)
# We append the launcher to the list of children so later we can
# check it has died.
children.append(launcher_proc)
pgrp = os.getpgid(proc.pid)
os.killpg(pgrp, signal.SIGINT)
conn.close()
break
listener.close()
# Once the signal has been sent, all children should die
_, alive = psutil.wait_procs(children, timeout=6)
# If any, notify the zombie and sleeping processes and fail the test
clean_exit = True
error_msg = ''
for child in alive:
error_msg += (
str(child.as_dict(attrs=['pid', 'name', 'status', 'cmdline'])) +
'\n')
clean_exit = False
error_msg = ("These processes didn't die during %s:\n" %
(lifecycle_stage) + error_msg)
for child in alive:
os.kill(child.pid, signal.SIGINT)
assert clean_exit, error_msg
|
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.' %self.serverAddr)
|
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.
request = 'SETUP ' + self.fileName + ' RTSP/1.0\nCSeq: ' + str(self.rtspSeq) + '\nTransport: RTP/UDP; client_port= ' + str(self.rtpPort)
# Keep track of the sent request.
self.requestSent = self.SETUP
# Play request
elif requestCode == self.PLAY and self.state == self.READY:
self.rtspSeq += 1
request = 'PLAY ' + self.fileName + ' RTSP/1.0\nCSeq: ' + str(self.rtspSeq) + '\nSession: ' + str(self.sessionId)
self.requestSent = self.PLAY
# Pause request
elif requestCode == self.PAUSE and self.state == self.PLAYING:
self.rtspSeq += 1
request = 'PAUSE ' + self.fileName + ' RTSP/1.0\nCSeq: ' + str(self.rtspSeq) + '\nSession: ' + str(self.sessionId)
self.requestSent = self.PAUSE
# Teardown request
elif requestCode == self.TEARDOWN and not self.state == self.INIT:
self.rtspSeq += 1
request = 'TEARDOWN ' + self.fileName + ' RTSP/1.0\nCSeq: ' + str(self.rtspSeq) + '\nSession: ' + str(self.sessionId)
self.requestSent = self.TEARDOWN
else:
return
# Send the RTSP request using rtspSocket.
self.rtspSocket.send(request.encode())
print('\nData sent:\n' + request)
|
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.SHUT_RDWR)
self.rtspSocket.close()
break
|
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 session ID
if self.sessionId == 0:
self.sessionId = session
# Process only if the session ID is the same
if self.sessionId == session:
if int(lines[0].split(' ')[1]) == 200:
if self.requestSent == self.SETUP:
# Update RTSP state.
self.state = self.READY
# Open RTP port.
self.openRtpPort()
elif self.requestSent == self.PLAY:
self.state = self.PLAYING
elif self.requestSent == self.PAUSE:
self.state = self.READY
# The play thread exits. A new thread is created on resume.
self.playEvent.set()
elif self.requestSent == self.TEARDOWN:
self.state = self.INIT
# Flag the teardownAcked to close the socket.
self.teardownAcked = 1
|
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 the socket to the address using the RTP port given by the client user
self.rtpSocket.bind(("", self.rtpPort))
except:
tkMessageBox.showwarning('Unable to Bind', 'Unable to bind PORT=%d' %self.rtpPort)
|
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) | (extension << 4) | cc
header[1] = (marker << 7) | pt
header[2] = (seqnum >> 8) & 255 #upper bits
header[3] = seqnum & 255
header[4] = timestamp >> 24 & 255
header[5] = timestamp >> 16 & 255
header[6] = timestamp >> 8 & 255
header[7] = timestamp & 255
header[8] = ssrc >> 24 & 255
header[9] = ssrc >> 16 & 255
header[10] = ssrc >> 8 & 255
header[11] = ssrc & 255
self.header = header
# Get the payload from the argument
self.payload = payload
|
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
# 20037508.342789244
|
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
return (mx, my)
|
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
/ 180.0)) - math.pi / 2.0)
return (lat, lon)
|
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
|
def MetersToTile(
self,
mx,
my,
zoom,
):
'''Returns tile for given mercator coordinates'''
(px, py) = self.MetersToPixels(mx, my, zoom)
return self.PixelsToTile(px, py)
|
Returns tile for given mercator coordinates
|
MetersToTile
|
python
|
commenthol/gdal2tiles-leaflet
|
gdal2tiles-multiprocess.py
|
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
|
MIT
|
def TileBounds(
self,
tx,
ty,
zoom,
):
'''Returns bounds of the given tile in EPSG:900913 coordinates'''
(minx, miny) = self.PixelsToMeters(tx * self.tileSize, ty
* self.tileSize, zoom)
(maxx, maxy) = self.PixelsToMeters((tx + 1) * self.tileSize,
(ty + 1) * self.tileSize, zoom)
return (minx, miny, maxx, maxy)
|
Returns bounds of the given tile in EPSG:900913 coordinates
|
TileBounds
|
python
|
commenthol/gdal2tiles-leaflet
|
gdal2tiles-multiprocess.py
|
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
|
MIT
|
def TileLatLonBounds(
self,
tx,
ty,
zoom,
):
'''Returns bounds of the given tile in latutude/longitude using WGS84 datum'''
bounds = self.TileBounds(tx, ty, zoom)
(minLat, minLon) = self.MetersToLatLon(bounds[0], bounds[1])
(maxLat, maxLon) = self.MetersToLatLon(bounds[2], bounds[3])
return (minLat, minLon, maxLat, maxLon)
|
Returns bounds of the given tile in latutude/longitude using WGS84 datum
|
TileLatLonBounds
|
python
|
commenthol/gdal2tiles-leaflet
|
gdal2tiles-multiprocess.py
|
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
|
MIT
|
def Resolution(self, zoom):
'''Resolution (meters/pixel) for given zoom level (measured at Equator)'''
# return (2 * math.pi * 6378137) / (self.tileSize * 2**zoom)
return self.initialResolution / 2 ** zoom
|
Resolution (meters/pixel) for given zoom level (measured at Equator)
|
Resolution
|
python
|
commenthol/gdal2tiles-leaflet
|
gdal2tiles-multiprocess.py
|
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
|
MIT
|
def ZoomForPixelSize(self, pixelSize):
'''Maximal scaledown zoom of the pyramid closest to the pixelSize.'''
for i in range(MAXZOOMLEVEL):
if pixelSize > self.Resolution(i):
if i != 0:
return i - 1
else:
return 0 # We don't want to scale up
|
Maximal scaledown zoom of the pyramid closest to the pixelSize.
|
ZoomForPixelSize
|
python
|
commenthol/gdal2tiles-leaflet
|
gdal2tiles-multiprocess.py
|
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
|
MIT
|
def GoogleTile(
self,
tx,
ty,
zoom,
):
'''Converts TMS tile coordinates to Google Tile coordinates'''
# coordinate origin is moved from bottom-left to top-left corner of the extent
return (tx, 2 ** zoom - 1 - ty)
|
Converts TMS tile coordinates to Google Tile coordinates
|
GoogleTile
|
python
|
commenthol/gdal2tiles-leaflet
|
gdal2tiles-multiprocess.py
|
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
|
MIT
|
def QuadTree(
self,
tx,
ty,
zoom,
):
'''Converts TMS tile coordinates to Microsoft QuadTree'''
quadKey = ''
ty = 2 ** zoom - 1 - ty
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << i - 1
if tx & mask != 0:
digit += 1
if ty & mask != 0:
digit += 2
quadKey += str(digit)
return quadKey
|
Converts TMS tile coordinates to Microsoft QuadTree
|
QuadTree
|
python
|
commenthol/gdal2tiles-leaflet
|
gdal2tiles-multiprocess.py
|
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
|
MIT
|
def LonLatToPixels(
self,
lon,
lat,
zoom,
):
'''Converts lon/lat to pixel coordinates in given zoom of the EPSG:4326 pyramid'''
res = self.resFact / 2 ** zoom
px = (180 + lon) / res
py = (90 + lat) / res
return (px, py)
|
Converts lon/lat to pixel coordinates in given zoom of the EPSG:4326 pyramid
|
LonLatToPixels
|
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 coordinates of the tile covering region in pixel coordinates'''
tx = int(math.ceil(px / float(self.tileSize)) - 1)
ty = int(math.ceil(py / float(self.tileSize)) - 1)
return (tx, ty)
|
Returns coordinates of the tile covering region in pixel coordinates
|
PixelsToTile
|
python
|
commenthol/gdal2tiles-leaflet
|
gdal2tiles-multiprocess.py
|
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
|
MIT
|
def LonLatToTile(
self,
lon,
lat,
zoom,
):
'''Returns the tile for zoom which covers given lon/lat coordinates'''
(px, py) = self.LonLatToPixels(lon, lat, zoom)
return self.PixelsToTile(px, py)
|
Returns the tile for zoom which covers given lon/lat coordinates
|
LonLatToTile
|
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.