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
... | 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:
... | 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 = DeterministicMLPPoli... | 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(
... | 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 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 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(
Half... | 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),
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 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... | 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 = 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 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_... | 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(
... | 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(... | 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_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 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_... | 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,
... | 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 = 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_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_gradien... | 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_hes... | 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... | 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_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.d... | 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,
... | 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_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 '
... | 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',
... | 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()
poli... | 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... | 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 = DiscreteCNNPol... | 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,
... | 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)
... | 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 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,
... | 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 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 |
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.ti... | 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... | 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 ... | 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:
... | 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
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.