python_code
stringlengths 0
780k
| repo_name
stringlengths 7
38
| file_path
stringlengths 5
103
|
---|---|---|
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities to construct and learn from policy targets."""
import functools
import chex
import distrax
import jax
import jax.numpy as jnp
@chex.dataclass(frozen=True)
class PolicyTarget:
"""A dataclass to hold (possibly sampled) policy targets."""
# The sampled target actions. These may not cover all actions.
# The shape is [N_targets, ...]
actions: chex.Array
# Probabilities for the corresponding actions. They may have been
# importance weighted. The shape matches log_prob(actions).shape.
weights: chex.Array
def constant_policy_targets(
distribution: distrax.DistributionLike,
rng_key: chex.PRNGKey,
num_samples: int,
weights_scale: float = 1.) -> PolicyTarget:
"""Create policy targets with constant weights.
The actions will be sampled from `distribution` and will all be associated to
a constant `weights_scale`. If `distribution` is a (discrete or continuous)
uniform probability distribution, distilling these targets will push the
agent's policy towards a uniform distribution. The strength of the penalty
associated with a non-uniform policy depends on `weights_scale` (e.g. in the
extreme case `weights_scale==0`, distillation loss is 0 for any policy).
Args:
distribution: a `distrax` or `tfp` distribution for sampling actions.
rng_key: a JAX pseudo random number generator.
num_samples: number of action sampled in the PolicyTarget.
weights_scale: constant weight associated with each action.
Returns:
a PolicyTarget to learn from.
"""
random_actions = distribution.sample(
seed=rng_key, sample_shape=(num_samples,))
return PolicyTarget(
actions=random_actions,
weights=weights_scale * jnp.ones(
(num_samples,) + distribution.batch_shape))
zero_policy_targets = functools.partial(
constant_policy_targets, weights_scale=0.0)
def sampled_policy_distillation_loss(
distribution: distrax.DistributionLike,
policy_targets: PolicyTarget,
stop_target_gradients: bool = True,
) -> chex.Numeric:
"""Compute a sampled cross-entropy-like loss.
The loss corresponds to taking the mean of `-weights * log_prob(actions)`,
where the weights and actions come from a `PolicyTarget` object, and the mean
is computed over the N samples in the `policy_target` as well as any batch
dimension. The loss is suitable for both discrete and continuous actions.
Args:
distribution: a predicted `distrax` or `tfp` distribution.
policy_targets: a policy target to learn from.
stop_target_gradients: bool indicating whether or not to apply a stop
gradient to the policy_targets, default True.
Returns:
a scalar loss.
"""
# Optionally, stop gradients from propagating into the targets and into
# the actions; the latter is mostly relevant in continuous control.
weights = jax.lax.select(
stop_target_gradients,
jax.lax.stop_gradient(policy_targets.weights), policy_targets.weights)
actions = jax.lax.select(
stop_target_gradients,
jax.lax.stop_gradient(policy_targets.actions), policy_targets.actions)
# Compute log-probabilities.
log_probs = distribution.log_prob(actions)
# Assert shapes are compatible.
chex.assert_equal_shape([weights, log_probs])
# We avoid NaNs from `0 * (-inf)` by using `0 * min_logp` in that case.
min_logp = jnp.finfo(log_probs.dtype).min
# We average over the samples, over time and batch, and if the actions are
# a continuous vector also over the actions.
return -jnp.mean(weights * jnp.maximum(log_probs, min_logp))
| rlax-master | rlax/_src/policy_targets.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tree utilities."""
import functools
from typing import Any, Callable, Sequence
import chex
import jax
import jax.numpy as jnp
import numpy as np
from rlax._src import base
Array = chex.Array
tree_structure = jax.tree_util.tree_structure
def tree_select(pred: Array, on_true: Any, on_false: Any):
"""Select either one of two identical nested structs based on condition.
Args:
pred: a boolean condition.
on_true: an arbitrary nested structure.
on_false: a nested structure identical to `on_true`.
Returns:
the selected nested structure.
"""
if tree_structure(on_true) != tree_structure(on_false):
raise ValueError('The two branches must have the same structure.')
return jax.tree_util.tree_map(
lambda x, y: jax.lax.select(pred, x, y), on_true, on_false
)
def tree_map_zipped(fn: Callable[..., Any], nests: Sequence[Any]):
"""Map a function over a list of identical nested structures.
Args:
fn: the function to map; must have arity equal to `len(list_of_nests)`.
nests: a list of identical nested structures.
Returns:
a nested structure whose leaves are outputs of applying `fn`.
"""
if not nests:
return nests
tree_def = tree_structure(nests[0])
if any(tree_structure(x) != tree_def for x in nests[1:]):
raise ValueError('All elements must share the same tree structure.')
return jax.tree_util.tree_unflatten(
tree_def, [fn(*d) for d in zip(*[jax.tree_leaves(x) for x in nests])])
def tree_split_key(rng_key: Array, tree_like: Any):
"""Generate random keys for each leaf in a tree.
Args:
rng_key: a JAX pseudo random number generator key.
tree_like: a nested structure.
Returns:
a new key, and a tree of keys with same shape as `tree_like`.
"""
leaves, treedef = jax.tree_util.tree_flatten(tree_like)
rng_key, *keys = jax.random.split(rng_key, num=len(leaves) + 1)
return rng_key, jax.tree_util.tree_unflatten(treedef, keys)
def tree_split_leaves(tree_like: Any,
axis: int = 0,
keepdim: bool = False):
"""Splits a tree of arrays into an array of trees avoiding data copying.
Note: `jax.numpy.DeviceArray`'s data gets copied.
Args:
tree_like: a nested object with leaves to split.
axis: an axis for splitting.
keepdim: a bool indicating whether to keep `axis` dimension.
Returns:
A tuple of `size(axis)` trees containing results of splitting.
"""
# Disable pylint to correctly process `np.ndarray`s.
if len(tree_like) == 0: # pylint: disable=g-explicit-length-test
return tree_like
leaves, treedef = jax.tree_util.tree_flatten(tree_like)
axis_size = leaves[0].shape[axis]
split_leaves = [np.split(l, axis_size, axis=axis) for l in leaves]
ind_ = lambda x, i: x[i] if keepdim else np.squeeze(x[i], axis)
split_trees = ((ind_(l, i) for l in split_leaves) for i in range(axis_size))
return tuple(jax.tree_util.tree_unflatten(treedef, t) for t in split_trees)
def tree_replace_masked(tree_data, tree_replacement, mask):
"""Replace slices of the leaves when mask is 1.
Args:
tree_data: a nested object with leaves to mask.
tree_replacement: nested object with the same structure of `tree_data`,
that cointains the data to insert according to `mask`. If `None`,
then the masked elements in `tree_data` will be replaced with zeros.
mask: a mask of 0/1s, whose shape is a prefix of the shape of the leaves
in `tree_data` and in `tree_replacement`.
Returns:
the updated tensor.
"""
if tree_replacement is None:
tree_replacement = jax.tree_map(jnp.zeros_like, tree_data)
return jax.tree_map(
lambda data, replacement: base.replace_masked(data, replacement, mask),
tree_data, tree_replacement)
def tree_fn(fn, **unmapped_kwargs):
"""Wrap a function to jax.tree_map over its arguments.
You may set some named arguments via a partial to skip the `tree_map` on those
arguments. Usual caveats of `partial` apply (e.g. set named args must be a
suffix of the argument list).
Args:
fn: the function to be wrapped.
**unmapped_kwargs: the named arguments to be set via a partial.
Returns:
a function
"""
pfn = functools.partial(fn, **unmapped_kwargs)
def _wrapped(*args):
return jax.tree_map(pfn, *args)
return _wrapped
def transpose_last_axis_to_first(tree: chex.ArrayTree) -> chex.ArrayTree:
"""Function to transpose the last axis to be first for all leaves in a pytree.
This function will transpose the last axis to the front for all leaves in a
pytree; each leaf with shape [D_1, ..., D_{n-1}, D_n] will have shape
[D_n, D_1, ..., D_{n-1}].
Args:
tree: the pytree of Arrays to be transposed.
Returns:
tree: the transposed output tree.
"""
def _transpose(tree):
return jnp.transpose(tree, [tree.ndim - 1] + list(range(tree.ndim - 1)))
return tree_fn(_transpose)(tree)
def transpose_first_axis_to_last(tree: chex.ArrayTree) -> chex.ArrayTree:
"""Function to transpose the first axis to be last for all leaves in a pytree.
This function will transpose the first axis to the last dim of all leaves in a
pytree; each leaf with shape [D_1, D_2, ..., D_n] will have shape
[D_2, ..., D_n, D_1].
Args:
tree: the pytree of Arrays to be transposed.
Returns:
tree: the transposed output tree.
"""
def _transpose(tree):
return jnp.transpose(tree, list(range(1, tree.ndim)) + [0])
return tree_fn(_transpose)(tree)
| rlax-master | rlax/_src/tree_util.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Unit tests for `nonlinear_bellman.py`."""
import functools
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import numpy as np
from rlax._src import nonlinear_bellman
class IdentityTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.q_t = np.array(
[[[1.2, 2.2], [-1.2, 0.2], [2.2, -1.2]],
[[4.2, 2.2], [1.2, 1.2], [-1.2, -2.2]]],
dtype=np.float64)
@parameterized.parameters(
nonlinear_bellman.IDENTITY_PAIR,
nonlinear_bellman.SIGNED_LOGP1_PAIR,
nonlinear_bellman.SIGNED_HYPERBOLIC_PAIR,
nonlinear_bellman.HYPERBOLIC_SIN_PAIR)
def test_identity(self, tx, inv_tx):
"""Tests that tx(inv_tx(x)) == inv_tx(tx(x)) == x."""
np.testing.assert_allclose(inv_tx(tx(self.q_t)), self.q_t, rtol=1e-3)
np.testing.assert_allclose(tx(inv_tx(self.q_t)), self.q_t, rtol=1e-3)
def test_muzero_pair_is_consistent(self):
a = np.array([1.03, 4.43, -3012.33, 0.0])
tx = nonlinear_bellman.muzero_pair(
num_bins=601,
min_value=-300,
max_value=300,
tx=nonlinear_bellman.SIGNED_HYPERBOLIC_PAIR)
probs = tx.apply(a)
scalar = tx.apply_inv(probs)
np.testing.assert_allclose(a, scalar, rtol=1e-4, atol=1e-4)
def test_unbiased_transform_pair_is_consistent(self):
a = np.array([1.03, 4.43, -3012.33, 0.0])
tx = nonlinear_bellman.unbiased_transform_pair(
num_bins=601,
min_value=-300,
max_value=300,
tx=nonlinear_bellman.SIGNED_HYPERBOLIC_PAIR)
probs = tx.apply(a)
scalar = tx.apply_inv(probs)
np.testing.assert_allclose(a, scalar, rtol=1e-4, atol=1e-4)
class TransformedQLambdaTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.lambda_ = 0.75
self.q_tm1 = np.array(
[[[1.1, 2.1], [-1.1, 1.1], [3.1, -3.1]],
[[2.1, 3.1], [-1.1, 0.1], [-2.1, -1.1]]],
dtype=np.float32)
self.a_tm1 = np.array(
[[0, 1, 0],
[1, 0, 0]],
dtype=np.int32)
self.discount_t = np.array(
[[0., 0.89, 0.85],
[0.88, 1., 0.83]],
dtype=np.float32)
self.r_t = np.array(
[[-1.3, -1.3, 2.3],
[1.3, 5.3, -3.3]],
dtype=np.float32)
self.q_t = np.array(
[[[1.2, 2.2], [-1.2, 0.2], [2.2, -1.2]],
[[4.2, 2.2], [1.2, 1.2], [-1.2, -2.2]]],
dtype=np.float32)
self.expected_td = np.array(
[[[-2.4, 0.4280, 1.07], [0.6935, 3.478, -2.196]],
[[-1.9329, 0.6643, -0.7854], [-0.20713, 2.1855, 0.27132]],
[[-1.6179, 0.4633, -0.7576], [-1.1097, 1.6509, 0.3598]],
[[-2.1785, 0.6562, -0.5938], [-0.0892, 2.6553, -0.1208]]],
dtype=np.float32)
@chex.all_variants()
@parameterized.named_parameters(
('identity0', nonlinear_bellman.IDENTITY_PAIR, 0),
('signed_logp11', nonlinear_bellman.SIGNED_LOGP1_PAIR, 1),
('signed_hyperbolic2', nonlinear_bellman.SIGNED_HYPERBOLIC_PAIR, 2),
('hyperbolic_sin3', nonlinear_bellman.HYPERBOLIC_SIN_PAIR, 3))
def test_transformed_q_lambda_batch(self, tx_pair, td_index):
"""Tests correctness for full batch."""
transformed_q_lambda = self.variant(jax.vmap(functools.partial(
nonlinear_bellman.transformed_q_lambda, tx_pair=tx_pair,
lambda_=self.lambda_)))
# Compute vtrace output.
actual_td = transformed_q_lambda(
self.q_tm1, self.a_tm1, self.r_t, self.discount_t, self.q_t)
# Test output.
np.testing.assert_allclose(self.expected_td[td_index], actual_td, rtol=1e-3)
class TransformedNStepQLearningTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.n = 2
self.q_tm1 = np.array(
[[[1.1, 2.1], [-1.1, 1.1], [3.1, -3.1]],
[[2.1, 3.1], [-1.1, 0.1], [-2.1, -1.1]]],
dtype=np.float32)
self.a_tm1 = np.array(
[[0, 1, 0],
[1, 0, 0]],
dtype=np.int32)
self.discount_t = np.array(
[[0., 0.89, 0.85],
[0.88, 1., 0.83]],
dtype=np.float32)
self.r_t = np.array(
[[-1.3, -1.3, 2.3],
[1.3, 5.3, -3.3]],
dtype=np.float32)
self.target_q_t = np.array(
[[[1.2, 2.2], [-1.2, 0.2], [2.2, -1.2]],
[[4.2, 2.2], [1.2, 1.2], [-1.2, -2.2]]],
dtype=np.float32)
self.a_t = np.array(
[[0, 1, 0],
[1, 0, 0]],
dtype=np.int32)
self.expected_td = np.array([
[[-2.4, 1.3112999, 1.0700002],
[3.9199996, 2.104, -2.196]],
[[-1.9329091, 0.9564189, -0.7853615],
[-0.9021418, 1.1716722, 0.2713145]],
[[-1.6178751, 0.85600746, -0.75762916],
[-0.87689304, 0.6246443, 0.3598088]],
[[-2.178451, 1.02313, -0.593768],
[-0.415362, 1.790864, -0.120749]]
], dtype=np.float32)
@chex.all_variants()
@parameterized.named_parameters(
('identity0', nonlinear_bellman.IDENTITY_PAIR, 0),
('signed_logp11', nonlinear_bellman.SIGNED_LOGP1_PAIR, 1),
('signed_hyperbolic2', nonlinear_bellman.SIGNED_HYPERBOLIC_PAIR, 2),
('hyperbolic_sin3', nonlinear_bellman.HYPERBOLIC_SIN_PAIR, 3))
def test_transformed_q_lambda_batch(self, tx_pair, td_index):
"""Tests correctness for full batch."""
transformed_n_step_q_learning = self.variant(jax.vmap(functools.partial(
nonlinear_bellman.transformed_n_step_q_learning, tx_pair=tx_pair,
n=self.n)))
actual_td = transformed_n_step_q_learning(
self.q_tm1, self.a_tm1, self.target_q_t, self.a_t, self.r_t,
self.discount_t)
np.testing.assert_allclose(self.expected_td[td_index], actual_td, rtol=1e-3)
class TransformedRetraceTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self._lambda = 0.9
self._qs = np.array(
[[[1.1, 2.1], [-1.1, 1.1], [3.1, -3.1], [-1.2, 0.0]],
[[2.1, 3.1], [9.5, 0.1], [-2.1, -1.1], [0.1, 7.4]]],
dtype=np.float32)
self._targnet_qs = np.array(
[[[1.2, 2.2], [-1.2, 0.2], [2.2, -1.2], [-2.25, -6.0]],
[[4.2, 2.2], [1.2, 1.2], [-1.2, -2.2], [1.5, 1.0]]],
dtype=np.float32)
self._actions = np.array(
[[0, 1, 0, 0],
[1, 0, 0, 1]],
dtype=np.int32)
self._rewards = np.array(
[[-1.3, -1.3, 2.3, 42.0],
[1.3, 5.3, -3.3, -5.0]],
dtype=np.float32)
self._pcontinues = np.array(
[[0., 0.89, 0.85, 0.99],
[0.88, 1., 0.83, 0.95]],
dtype=np.float32)
self._target_policy_probs = np.array(
[[[0.5, 0.5], [0.2, 0.8], [0.6, 0.4], [0.9, 0.1]],
[[0.1, 0.9], [1.0, 0.0], [0.3, 0.7], [0.7, 0.3]]],
dtype=np.float32)
self._behavior_policy_probs = np.array(
[[0.5, 0.1, 0.9, 0.3],
[0.4, 0.6, 1.0, 0.9]],
dtype=np.float32)
self.expected_td = np.array(
[[[-2.4, -2.7905, -3.0313], [0.7889, -6.3645, -0.0795]],
[[-1.9329, -4.2626, -6.7738], [-2.3989, -9.9802, 1.4852]],
[[-1.6179, -3.0165, -5.2699], [-2.7742, -9.9544, 2.3167]],
[[-2.1785, -4.2530, -6.7081], [-1.3654, -8.2213, 0.7641]]],
dtype=np.float32)
@chex.all_variants()
@parameterized.named_parameters(
('identity0', nonlinear_bellman.IDENTITY_PAIR, 0),
('signed_logp11', nonlinear_bellman.SIGNED_LOGP1_PAIR, 1),
('signed_hyperbolic2', nonlinear_bellman.SIGNED_HYPERBOLIC_PAIR, 2),
('hyperbolic_sin3', nonlinear_bellman.HYPERBOLIC_SIN_PAIR, 3))
def test_transformed_retrace_batch(self, tx_pair, td_index):
"""Tests correctness for full batch."""
transformed_retrace = self.variant(jax.vmap(functools.partial(
nonlinear_bellman.transformed_retrace,
tx_pair=tx_pair, lambda_=self._lambda)))
# Compute transformed vtrace td errors in batch.
actual_td = transformed_retrace(
self._qs[:, :-1], self._targnet_qs[:, 1:], self._actions[:, :-1],
self._actions[:, 1:], self._rewards[:, :-1], self._pcontinues[:, :-1],
self._target_policy_probs[:, 1:], self._behavior_policy_probs[:, 1:])
# Test output.
np.testing.assert_allclose(self.expected_td[td_index], actual_td, rtol=1e-3)
if __name__ == '__main__':
jax.config.update('jax_numpy_rank_promotion', 'raise')
absltest.main()
| rlax-master | rlax/_src/nonlinear_bellman_test.py |
# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for mpo_ops.py."""
import functools
import math
from typing import Tuple
from absl.testing import absltest
from absl.testing import parameterized
import chex
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
from rlax._src import distributions
from rlax._src import mpo_ops
Array = chex.Array
Numeric = chex.Numeric
NUM_SAMPLES = 10
ACTION_DIM = 3
TIME_DIM = 8
BATCH_DIM = 100
# NOTE: These are not typical values used for MPO. In the test case, we know the
# Q function perfectly so we loosen the bound on the mean to zone in to the
# optimal policy very quickly. Similarly, we maintain a high variance to sample
# distinct actions to explore and learn from.
_INIT_TEMPERATURE = 0.2
_INIT_ALPHA_MEAN = 0.001
_INIT_ALPHA_COVARIANCE = float(1e6)
_EPSILON_BOUND = 0.01
_EPSILON_MEAN_BOUND = 10.0
_EPSILON_COVARIANCE_BOUND = 1e-12
_NUM_ITERATIONS = 5000
_TARGET_UPDATE_PERIOD = 100
_RANDOM_SEED = 42
# The offset to ensure initially the policy is not close to 0
_MEAN_OFFSET = 2.0
# The final action should optimize down to be close to 0.0
_MAX_ACTION_ERROR = 0.2
_MAX_KL_ERROR = 1e-6
_DIAGONAL_GAUSSIAN_DIST = distributions.gaussian_diagonal()
_PROJECTION_OPERATOR = functools.partial(jnp.clip, a_min=1e-10)
def _hk_mock_policy_params(s_tm1):
"""Returns mock policy params."""
# Outputs of the network are mu and sigma. Both shaped [B, ACTION_DIM].
pi_out = hk.nets.MLP(
output_sizes=[2 * ACTION_DIM],
w_init=hk.initializers.VarianceScaling(1e-3),
activation=jnp.tanh,
activate_final=False,
name='online_policy')(s_tm1)
pi_mean, pi_cov = jnp.split(pi_out, 2, axis=-1)
pi_cov = jax.nn.softplus(pi_cov)
pi_mean = pi_mean + _MEAN_OFFSET
return {'mean': pi_mean, 'stddev': pi_cov}
def _init_params(key):
init_fn, _ = hk.transform(_hk_mock_policy_params)
key_seq = hk.PRNGSequence(key)
s_tm1 = jax.random.normal(
next(key_seq), (TIME_DIM, BATCH_DIM, ACTION_DIM), jnp.float32)
online_params = init_fn(next(key_seq), s_tm1)
return dict(
online=online_params,
target=online_params,
mpo=dict(
temperature=jnp.array(_INIT_TEMPERATURE),
alpha_mean=_INIT_ALPHA_MEAN,
alpha_covariance=_INIT_ALPHA_COVARIANCE),
)
def _mock_outputs(online_params, target_params, key, target_name):
"""Returns mock network outputs."""
_, policy_params_fn = hk.transform(_hk_mock_policy_params)
key_seq = hk.PRNGSequence(key)
state_size = ACTION_DIM
# Input state: [TIME_DIM, BATCH_DIM, DIM_STATE]
s_tm1 = jax.random.normal(
next(key_seq), (TIME_DIM, BATCH_DIM, state_size), jnp.float32)
policy_params = policy_params_fn(online_params, None, s_tm1)
target_policy_params = policy_params_fn(target_params, None, s_tm1)
# Shape for actions: [NUM_SAMPLES, TIME_DIM, BATCH_DIM, ACTION_DIM]
mean, stddev = target_policy_params['mean'], target_policy_params['stddev']
mean_repeated = jnp.repeat(
mean.reshape((1,) + mean.shape), NUM_SAMPLES, axis=0)
stddev_repeated = jnp.repeat(
stddev.reshape((1,) + stddev.shape), NUM_SAMPLES, axis=0)
target_actions = _DIAGONAL_GAUSSIAN_DIST.sample(
next(key_seq), mean_repeated, stddev_repeated)
# If the target is advantages then num samples is 1.
if target_name == 'advantages':
target_actions = target_actions[0, ...]
# Shape for Q: [NUM_SAMPLES, TIME_DIM, BATCH_DIM]
# Setting Q = -a_t * tf.transpose(a_t) where a_t = s_t + a.
# The solution to optimizing this is basically for the policy to output
# 0 actions thereby minimizing the cost. Since this is a convex
# optimization problem, the algorithm should get to a good solution quickly.
# First compute a_t = s_t + a with shape: [NUM_SAMPLES, TIME_DIM, BATCH_DIM,
# ACTION_DIM] since action dim is the same as shape dim here and then compute
# the quadratic form.
a_t = target_actions + jnp.expand_dims(s_tm1, 0)
sample_q_values = -jnp.sum(a_t ** 2, axis=-1)
# Set the advantage to the same as the q value.
# Shape for advantages: [TIME_DIM, BATCH_DIM]
advantages = sample_q_values[0, :, :]
return dict(
pi_params=policy_params,
target_pi_params=target_policy_params,
sample_q_values=sample_q_values,
advantages=advantages,
target_actions=target_actions,
)
def get_common_loss_fn_inputs(params, key, target_name):
out = _mock_outputs(params['online'], params['target'], key, target_name)
pi_sample_log_probs = _DIAGONAL_GAUSSIAN_DIST.logprob(
out['target_actions'], out['pi_params']['mean'],
out['pi_params']['stddev'])
return out, {
'sample_log_probs': pi_sample_log_probs,
target_name: out[target_name],
'temperature_constraint': mpo_ops.LagrangePenalty(
params['mpo']['temperature'], _EPSILON_BOUND)}
def _decoupled_multivariate_normal_kl_divergence(
mu_0: Array, sigma_0: Numeric, mu_1: Array, sigma_1: Numeric,
per_dimension: bool = False
) -> Tuple[Array, Array]:
"""Compute the KL between diagonal Gaussians decomposed into mean and covar-e.
Args:
mu_0: array like of mean values for policy 0
sigma_0: array like of std values for policy 0
mu_1: array like of mean values for policy 1
sigma_1: array like of std values for policy 1
per_dimension: Whether to return a separate kl divergence for each dimension
on the last axis.
Returns:
the kl divergence between the distributions decomposed into mean and
covariance.
"""
# Support scalar and vector `sigma`. If vector, mu.shape==sigma.shape.
sigma_1 = jnp.ones_like(mu_1) * sigma_1
sigma_0 = jnp.ones_like(mu_0) * sigma_0
v1 = jnp.clip(sigma_1**2, 1e-6, 1e6)
v0 = jnp.clip(sigma_0**2, 1e-6, 1e6)
mu_diff = mu_1 - mu_0
kl_mean = 0.5 * jnp.divide(mu_diff**2, v1)
kl_cov = 0.5 * (jnp.divide(v0, v1) - jnp.ones_like(mu_1) + jnp.log(v1) -
jnp.log(v0))
if not per_dimension:
kl_mean = jnp.sum(kl_mean, axis=-1)
kl_cov = jnp.sum(kl_cov, axis=-1)
return kl_mean, kl_cov
def get_decoupled_kl_constraints(out, params, per_dimension):
"""Factorises KL for Gaussian."""
kl_mean, kl_covariance = (
_decoupled_multivariate_normal_kl_divergence(
out['target_pi_params']['mean'], out['target_pi_params']['stddev'],
out['pi_params']['mean'], out['pi_params']['stddev'],
per_dimension=per_dimension))
alpha_mean = params['mpo']['alpha_mean'] * jnp.ones_like(kl_mean)
alpha_covariance = params['mpo']['alpha_covariance'] * jnp.ones_like(
kl_covariance)
return [
(kl_mean, mpo_ops.LagrangePenalty(
alpha=alpha_mean, epsilon=_EPSILON_MEAN_BOUND,
per_dimension=per_dimension)),
(kl_covariance, mpo_ops.LagrangePenalty(
alpha=alpha_covariance, epsilon=_EPSILON_COVARIANCE_BOUND,
per_dimension=per_dimension)),
]
def get_coupled_kl_constraints(out, params, per_dimension):
kl_mean, kl_covariance = (
_decoupled_multivariate_normal_kl_divergence(
out['target_pi_params']['mean'], out['target_pi_params']['stddev'],
out['pi_params']['mean'], out['pi_params']['stddev'],
per_dimension=per_dimension))
alpha_mean = params['mpo']['alpha_mean'] * jnp.ones_like(kl_mean)
return [
(kl_mean + kl_covariance, mpo_ops.LagrangePenalty(
alpha=alpha_mean,
epsilon=_EPSILON_MEAN_BOUND + _EPSILON_COVARIANCE_BOUND,
per_dimension=per_dimension))
]
def vmpo_e_step_without_restarting_or_importance_weights(advantages, **kwargs):
restarting_weights = jnp.ones_like(advantages)
importance_weights = jnp.ones_like(advantages)
return mpo_ops.vmpo_compute_weights_and_temperature_loss(
advantages=advantages, restarting_weights=restarting_weights,
importance_weights=importance_weights, **kwargs)
class MPOTest(parameterized.TestCase):
"""Tests for the MPO losses."""
@parameterized.parameters(
{'target_name': 'sample_q_values',
'loss_fn': mpo_ops.mpo_loss,
'get_kl_constraints': get_decoupled_kl_constraints,
'per_dimension': False},
{'target_name': 'advantages',
'loss_fn': mpo_ops.vmpo_loss,
'get_kl_constraints': get_decoupled_kl_constraints,
'per_dimension': False},
{'target_name': 'sample_q_values',
'loss_fn': mpo_ops.mpo_loss,
'get_kl_constraints': get_coupled_kl_constraints,
'per_dimension': False},
{'target_name': 'advantages',
'loss_fn': mpo_ops.vmpo_loss,
'get_kl_constraints': get_coupled_kl_constraints,
'per_dimension': False},
{'target_name': 'sample_q_values',
'loss_fn': mpo_ops.mpo_loss,
'get_kl_constraints': get_decoupled_kl_constraints,
'per_dimension': True},
{'target_name': 'advantages',
'loss_fn': mpo_ops.vmpo_loss,
'get_kl_constraints': get_decoupled_kl_constraints,
'per_dimension': True},
{'target_name': 'sample_q_values',
'loss_fn': mpo_ops.mpo_loss,
'get_kl_constraints': get_coupled_kl_constraints,
'per_dimension': True},
{'target_name': 'advantages',
'loss_fn': mpo_ops.vmpo_loss,
'get_kl_constraints': get_coupled_kl_constraints,
'per_dimension': True},
)
def test_optimization(
self, target_name, loss_fn, get_kl_constraints, per_dimension):
"""Tests that the policy optimization works correctly."""
def _loss(params, key):
out, loss_fn_inputs = get_common_loss_fn_inputs(params, key, target_name)
kl_constraints = get_kl_constraints(out, params, per_dimension)
loss_fn_inputs.update({'kl_constraints': kl_constraints})
loss, mpo_stats = loss_fn(**loss_fn_inputs)
loss = jnp.mean(loss)
temperature_bound = jnp.mean(mpo_stats.normalized_weights * jnp.log(
mpo_stats.num_samples * mpo_stats.normalized_weights + 1e-8))
return loss, {'outputs': out, 'temperature_bound': temperature_bound}
key = jax.random.PRNGKey(_RANDOM_SEED)
grad_fn = jax.jit(jax.grad(_loss, has_aux=True))
optimizer = optax.adam(1e-3)
key, new_key = jax.random.split(key)
params = _init_params(new_key)
opt_state = optimizer.init((params['online'], params['mpo']))
@jax.jit
def _update(params_, opt_state_, key_):
next_key, key_ = jax.random.split(key_)
grad, stats = grad_fn(params_, key_)
updates, opt_state_ = optimizer.update(
(grad['online'], grad['mpo']), opt_state_)
online_params, mpo_params = optax.apply_updates(
(params_['online'], params_['mpo']), updates)
params_['online'] = online_params
params_['mpo'] = mpo_params
return params_, opt_state_, stats, next_key
for iter_idx in range(_NUM_ITERATIONS):
params, opt_state, extra, key = _update(params, opt_state, key)
if iter_idx % _TARGET_UPDATE_PERIOD == 0:
params['target'] = params['online']
# Test the bounds are within tolerance.
key, new_key = jax.random.split(key)
_, extra = _loss(params, new_key)
action_mean = jnp.mean(extra['outputs']['pi_params']['mean'])
# Check action mean is close to 0.
self.assertBetween(action_mean, -_MAX_ACTION_ERROR, _MAX_ACTION_ERROR)
# Check the temperature are within the bounds.
self.assertLess(extra['temperature_bound'], _EPSILON_BOUND)
@parameterized.parameters(
{'e_step_fn': mpo_ops.mpo_compute_weights_and_temperature_loss,
'additional_inputs': {},
# dL/dq == 1 and dL/dt == epsilon (for one sample)
'expected_deriv_of_target': [[[1]]],
'sample_dimension': True},
{'e_step_fn': vmpo_e_step_without_restarting_or_importance_weights,
'additional_inputs': {'top_k_fraction': 1.0},
'expected_deriv_of_target': [[1]],
'sample_dimension': False},
)
def test_e_step_gradient_computation(
self, e_step_fn, additional_inputs, expected_deriv_of_target,
sample_dimension):
"""Tests the gradients from the E-step against the analytic ones."""
# Target has shape [NUM_SAMPLES, T, B] => [1, 1, 1]
target = jnp.array([[3]], jnp.float32)
if sample_dimension:
target = jnp.expand_dims(target, axis=0)
temperature = jnp.array(0.1, jnp.float32)
def fn(target_, temperature_):
temperature_constraint = mpo_ops.LagrangePenalty(
temperature_, _EPSILON_BOUND)
temperature_loss, _, _ = e_step_fn(
target_, temperature_constraint=temperature_constraint,
projection_operator=_PROJECTION_OPERATOR,
**additional_inputs)
return jnp.mean(temperature_loss)
grad = jax.grad(fn, argnums=(0, 1))(target, temperature)
np.testing.assert_almost_equal(np.array(grad[0]), np.array(
expected_deriv_of_target, np.float32), decimal=4)
self.assertAlmostEqual(grad[1], _EPSILON_BOUND, places=4)
@parameterized.parameters(
{'e_step_fn': mpo_ops.mpo_compute_weights_and_temperature_loss,
'additional_inputs': {},
'sample_dimension': True},
{'e_step_fn': vmpo_e_step_without_restarting_or_importance_weights,
'additional_inputs': {'top_k_fraction': 1.0},
'sample_dimension': False},
)
def test_e_step_stop_gradient(
self, e_step_fn, additional_inputs, sample_dimension):
"""Tests no gradients flow through `weights` in the E-Step."""
# Target has shape [NUM_SAMPLES, T, B] => [1, 1, 1]
target = jnp.array([[3]], jnp.float32)
if sample_dimension:
target = jnp.expand_dims(target, axis=0)
temperature = jnp.array(0.1)
# pylint: disable=g-long-lambda
def mean_weights_fn(target_, temperature_):
temperature_constraint = mpo_ops.LagrangePenalty(
temperature_, _EPSILON_BOUND)
_, weights, _ = e_step_fn(
target_, temperature_constraint=temperature_constraint,
projection_operator=_PROJECTION_OPERATOR,
**additional_inputs)
return jnp.mean(weights)
grad = jax.grad(mean_weights_fn, argnums=(0, 1))(target, temperature)
np.testing.assert_almost_equal(
np.array(grad[0]), np.zeros_like(grad[0]), decimal=4)
self.assertAlmostEqual(grad[1], 0., places=4)
def test_kl_constraint_loss_gradients(self):
"""Tests the gradients in the `_kl_constraint_loss` method."""
kl = jnp.array(1., jnp.float32)
alpha = jnp.array(1., jnp.float32)
_, _, alpha = mpo_ops.kl_constraint_loss(kl, mpo_ops.LagrangePenalty(
alpha=alpha, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False),
_PROJECTION_OPERATOR)
def alpha_loss_fn(alpha_):
penalty = mpo_ops.LagrangePenalty(
alpha=alpha_, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False)
_, alpha_loss, _ = mpo_ops.kl_constraint_loss(
kl, penalty, _PROJECTION_OPERATOR)
return alpha_loss
alpha_gradients = jax.grad(alpha_loss_fn)(alpha)
actual_alpha_gradients = _EPSILON_MEAN_BOUND - kl
def kl_loss_fn(kl_):
penalty = mpo_ops.LagrangePenalty(
alpha=alpha, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False)
kl_loss, _, _ = mpo_ops.kl_constraint_loss(
kl_, penalty, _PROJECTION_OPERATOR)
return kl_loss
kl_gradients = jax.grad(kl_loss_fn)(kl)
actual_kl_gradients = alpha
self.assertAlmostEqual(kl_gradients, actual_kl_gradients)
self.assertAlmostEqual(alpha_gradients, actual_alpha_gradients)
def test_kl_constraint_loss_stop_gradients(self):
"""Tests the stop gradients in the `kl_constraint_loss` function.
The `alpha_loss` term should not affect the KL and the `kl` term should
not affect `alpha`.
"""
kl = jnp.array(1., jnp.float32)
alpha = jnp.array(1., jnp.float32)
_, _, alpha = mpo_ops.kl_constraint_loss(kl, mpo_ops.LagrangePenalty(
alpha=alpha, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False),
_PROJECTION_OPERATOR)
def kl_loss_fn(alpha_):
penalty = mpo_ops.LagrangePenalty(
alpha=alpha_, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False)
kl_loss, _, _ = mpo_ops.kl_constraint_loss(
kl, penalty, _PROJECTION_OPERATOR)
return kl_loss
kl_gradients = jax.grad(kl_loss_fn)(alpha)
def alpha_loss_fn(kl_):
penalty = mpo_ops.LagrangePenalty(
alpha=alpha, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False)
_, alpha_loss, _ = mpo_ops.kl_constraint_loss(
kl_, penalty, _PROJECTION_OPERATOR)
return alpha_loss
alpha_gradients = jax.grad(alpha_loss_fn)(kl)
# Test that there are no gradients of KL w.r.t alpha
self.assertEqual(kl_gradients, 0.)
# Test that there are no gradients of alpha w.r.t kl
self.assertEqual(alpha_gradients, 0.)
@parameterized.parameters(
# With restarting weights of 1 (and temperature of 1) the weights should
# be e^-1, 1, max advantage is 2 and num samples is 2 so temperature loss
# is log(1 + e^-1) + 2 - log(2) + temperature epsilon
{'advantages': np.array([[1.0, 2.0]]),
'restarting_weights': np.array([[1.0, 1.0]]),
'expected_temperature_loss': (math.log(1.0 + math.exp(-1.0)) + 2.0 -
math.log(2.0) + _EPSILON_BOUND)},
# With the second restarting weight set to 0 the weights become 1, 0
# max advantage is 1 and num samples is 1 so temperature loss is
# log(1) + 1 - log(1) + temperature epsilon
{'advantages': np.array([[1.0, 2.0]]),
'restarting_weights': np.array([[1.0, 0.0]]),
'expected_temperature_loss': 1.0 + _EPSILON_BOUND},
)
def test_restarting_weights(
self, advantages, restarting_weights, expected_temperature_loss):
"""Test that calculation is correct if restarting weight is set to 0."""
temperature_loss, _, _ = mpo_ops.vmpo_compute_weights_and_temperature_loss(
advantages, restarting_weights, np.ones_like(restarting_weights),
mpo_ops.LagrangePenalty(jnp.array(1.0), _EPSILON_BOUND),
functools.partial(np.clip, a_min=1e-8, a_max=None), 1.0)
self.assertAlmostEqual(
temperature_loss, expected_temperature_loss, places=4)
@parameterized.parameters(
# When the top k fraction is 1.0 all of the weights should be 1
{'top_k_fraction': 1.0,
'scaled_advantages': np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
'expected_top_k_weights': np.array([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])},
# When the top k fraction is 0.5 it will take the bottom row as these are
# the highest.
{'top_k_fraction': 0.5,
'scaled_advantages': np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
'expected_top_k_weights': np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])}
)
def test_top_k_fraction(
self, top_k_fraction, scaled_advantages, expected_top_k_weights):
"""Test that only the top k fraction are used."""
top_k_weights = mpo_ops.get_top_k_weights(
top_k_fraction, jnp.ones_like(scaled_advantages), scaled_advantages)
np.testing.assert_allclose(top_k_weights, expected_top_k_weights)
def test_top_k_fraction_too_low(self):
"""Test if the top k fraction returns 0 advantages we raise an error."""
with self.assertRaises(ValueError):
mpo_ops.get_top_k_weights(0.01, jnp.ones((3, 2)), jnp.ones((3, 2)))
@parameterized.parameters(
# With importance weights of 1 (and temperature of 1) the weights should
# be e^-1, 1, max advantage is 2 and num samples is 2 so temperature loss
# is log(1 + e^-1) + 2 - log(2) + temperature epsilon
{'advantages': np.array([[1.0, 2.0]]),
'importance_weights': np.array([[1.0, 1.0]]),
'expected_temperature_loss': (math.log(1.0 + math.exp(-1.0)) + 2.0 -
math.log(2.0) + _EPSILON_BOUND)},
# If the second importance weight is 0.5 temperature loss becomes
# log(0.5 + e^-1) + 2 - log(2) + temperature epsilon
{'advantages': np.array([[1.0, 2.0]]),
'importance_weights': np.array([[1.0, 0.5]]),
'expected_temperature_loss': (math.log(0.5 + math.exp(-1.0)) + 2.0 -
math.log(2.0) + _EPSILON_BOUND)},
)
def test_importance_weights(
self, advantages, importance_weights, expected_temperature_loss):
"""Test that importance weights have the correct effect."""
temperature_loss, _, _ = mpo_ops.vmpo_compute_weights_and_temperature_loss(
advantages, np.ones_like(importance_weights), importance_weights,
mpo_ops.LagrangePenalty(jnp.array(1.0), _EPSILON_BOUND),
functools.partial(np.clip, a_min=1e-8, a_max=None), 1.0)
self.assertAlmostEqual(
temperature_loss, expected_temperature_loss, places=4)
@parameterized.parameters({'per_dimension': True}, {'per_dimension': False})
def test_mpo_input_axis_order_equivalence(self, per_dimension):
"""Test loss functions are equivalent regardless of axis order."""
key = jax.random.PRNGKey(_RANDOM_SEED)
key, new_key = jax.random.split(key)
params = _init_params(new_key)
out, mpo_inputs = get_common_loss_fn_inputs(params, key, 'sample_q_values')
kl_constraints = get_coupled_kl_constraints(out, params,
per_dimension=per_dimension)
mpo_inputs.update({'kl_constraints': kl_constraints})
# Original loss fn inputs are [S T B],
stb_loss, stb_outputs = mpo_ops.mpo_loss(**mpo_inputs)
mean_stb_loss = jnp.mean(stb_loss)
# Swap axes and try [S B T]
mpo_inputs.update({
'sample_log_probs': jnp.swapaxes(mpo_inputs['sample_log_probs'], 1, 2),
'sample_q_values': jnp.swapaxes(mpo_inputs['sample_q_values'], 1, 2),
'kl_constraints': [(jnp.swapaxes(kl, 0, 1), mpo_ops.LagrangePenalty(
alpha=jnp.swapaxes(pen.alpha, 0, 1), epsilon=pen.epsilon,
per_dimension=pen.per_dimension)) for (kl, pen) in kl_constraints],
})
sbt_loss, sbt_outputs = mpo_ops.mpo_loss(**mpo_inputs)
mean_sbt_loss = jnp.mean(sbt_loss)
# Try [T B S] denoting sample_axis at 2 instead of 0.
mpo_inputs.update({
'sample_log_probs': jnp.swapaxes(mpo_inputs['sample_log_probs'], 0, 2),
'sample_q_values': jnp.swapaxes(mpo_inputs['sample_q_values'], 0, 2),
'kl_constraints': kl_constraints, # T B
'sample_axis': 2
})
tbs_loss, tbs_outputs = mpo_ops.mpo_loss(**mpo_inputs)
mean_tbs_loss = jnp.mean(tbs_loss)
self.assertAlmostEqual(mean_stb_loss, mean_sbt_loss, places=4)
self.assertAlmostEqual(mean_tbs_loss, mean_sbt_loss, places=4)
self.assertEqual(tbs_outputs.num_samples, sbt_outputs.num_samples)
self.assertEqual(tbs_outputs.num_samples, stb_outputs.num_samples)
@parameterized.parameters({'per_dimension': True}, {'per_dimension': False})
def test_vmpo_input_axis_order_equivalence(self, per_dimension):
"""Test loss functions are equivalent regardless of axis order."""
key = jax.random.PRNGKey(_RANDOM_SEED)
key, new_key = jax.random.split(key)
params = _init_params(new_key)
out, vmpo_inputs = get_common_loss_fn_inputs(params, key, 'advantages')
kl_constraints = get_coupled_kl_constraints(out, params,
per_dimension=per_dimension)
vmpo_inputs.update({'kl_constraints': kl_constraints})
# Original loss fn inputs are [T B],
tb_loss, tb_outputs = mpo_ops.vmpo_loss(**vmpo_inputs)
mean_tb_loss = jnp.mean(tb_loss)
# Swap axes and try [B T]
vmpo_inputs.update({
'sample_log_probs': jnp.swapaxes(vmpo_inputs['sample_log_probs'], 0, 1),
'advantages': jnp.swapaxes(vmpo_inputs['advantages'], 0, 1),
'kl_constraints': [(jnp.swapaxes(kl, 0, 1), mpo_ops.LagrangePenalty(
alpha=jnp.swapaxes(pen.alpha, 0, 1), epsilon=pen.epsilon,
per_dimension=pen.per_dimension)) for (kl, pen) in kl_constraints],
})
bt_loss, bt_outputs = mpo_ops.vmpo_loss(**vmpo_inputs)
mean_bt_loss = jnp.mean(bt_loss)
self.assertAlmostEqual(mean_tb_loss, mean_bt_loss, places=4)
self.assertEqual(tb_outputs.num_samples, bt_outputs.num_samples)
if __name__ == '__main__':
absltest.main()
| rlax-master | rlax/_src/mpo_ops_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Unit tests for `multistep.py`."""
import functools
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from rlax._src import multistep
class LambdaReturnsTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.lambda_ = 0.75
self.r_t = np.array(
[[1.0, 0.0, -1.0, 0.0, 1.0], [0.5, 0.8, -0.7, 0.0, 2.1]])
self.discount_t = np.array(
[[0.5, 0.9, 1.0, 0.5, 0.8], [0.9, 0.5, 0.3, 0.8, 0.7]])
self.v_t = np.array(
[[3.0, 1.0, 5.0, -5.0, 3.0], [-1.7, 1.2, 2.3, 2.2, 2.7]])
self.expected = np.array(
[[1.6460547, 0.72281253, 0.7375001, 0.6500001, 3.4],
[0.7866317, 0.9913063, 0.1101501, 2.834, 3.99]],
dtype=np.float32)
@chex.all_variants()
def test_lambda_returns_batch(self):
"""Tests for a full batch."""
lambda_returns = self.variant(jax.vmap(functools.partial(
multistep.lambda_returns, lambda_=self.lambda_)))
# Compute lambda return in batch.
actual = lambda_returns(self.r_t, self.discount_t, self.v_t)
# Test return estimate.
np.testing.assert_allclose(self.expected, actual, rtol=1e-5)
class DiscountedReturnsTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.r_t = np.array(
[[1.0, 0.0, -1.0, 0.0, 1.0], [0.5, 0.8, -0.7, 0.0, 2.1]])
self.discount_t = np.array(
[[0.5, 0.9, 1.0, 0.5, 0.8], [0.9, 0.5, 0.3, 0.8, 0.7]])
self.v_t = np.array(
[[3.0, 1.0, 5.0, -5.0, 3.0], [-1.7, 1.2, 2.3, 2.2, 2.7]])
self.bootstrap_v = np.array([v[-1] for v in self.v_t])
self.expected = np.array(
[[1.315, 0.63000005, 0.70000005, 1.7, 3.4],
[1.33592, 0.9288, 0.2576, 3.192, 3.9899998]],
dtype=np.float32)
@chex.all_variants()
def test_discounted_returns_batch(self):
"""Tests for a single element."""
discounted_returns = self.variant(jax.vmap(multistep.discounted_returns))
# Compute discounted return.
actual_scalar = discounted_returns(self.r_t, self.discount_t,
self.bootstrap_v)
actual_vector = discounted_returns(self.r_t, self.discount_t, self.v_t)
# Test output.
np.testing.assert_allclose(self.expected, actual_scalar, rtol=1e-5)
np.testing.assert_allclose(self.expected, actual_vector, rtol=1e-5)
class NStepBootstrappedReturnsTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.r_t = np.array(
[[1.0, 0.0, -1.0, 0.0, 1.0], [0.5, 0.8, -0.7, 0.0, 2.1]])
self.discount_t = np.array(
[[0.5, 0.9, 1.0, 0.5, 0.8], [0.9, 0.5, 0.3, 0.8, 0.7]])
self.v_t = np.array(
[[3.0, 1.0, 5.0, -5.0, 3.0], [-1.7, 1.2, 2.3, 2.2, 2.7]])
# Different expected results for different values of n.
self.expected = {}
self.expected[3] = np.array(
[[2.8, -3.15, 0.7, 1.7, 3.4], [1.2155, 0.714, 0.2576, 3.192, 3.99]],
dtype=np.float32)
self.expected[5] = np.array(
[[1.315, 0.63, 0.7, 1.7, 3.4], [1.33592, 0.9288, 0.2576, 3.192, 3.99]],
dtype=np.float32)
self.expected[7] = np.array(
[[1.315, 0.63, 0.7, 1.7, 3.4], [1.33592, 0.9288, 0.2576, 3.192, 3.99]],
dtype=np.float32)
@chex.all_variants()
@parameterized.named_parameters(
('smaller_n', 3,), ('equal_n', 5,), ('bigger_n', 7,))
def test_n_step_sequence_returns_batch(self, n):
"""Tests for a full batch."""
n_step_returns = self.variant(jax.vmap(functools.partial(
multistep.n_step_bootstrapped_returns, n=n)))
# Compute n-step return in batch.
actual = n_step_returns(self.r_t, self.discount_t, self.v_t)
# Test return estimate.
np.testing.assert_allclose(self.expected[n], actual, rtol=1e-5)
def test_reduces_to_lambda_returns(self):
"""Test function is the same as lambda_returns when n is sequence length."""
lambda_t = 0.75
n = len(self.r_t[0])
expected = multistep.lambda_returns(self.r_t[0], self.discount_t[0],
self.v_t[0], lambda_t)
actual = multistep.n_step_bootstrapped_returns(self.r_t[0],
self.discount_t[0],
self.v_t[0], n, lambda_t)
np.testing.assert_allclose(expected, actual, rtol=1e-5)
class TDErrorTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.r_t = np.array(
[[1.0, 0.0, -1.0, 0.0, 1.0], [0.5, 0.8, -0.7, 0.0, 2.1]])
self.discount_t = np.array(
[[0.5, 0.9, 1.0, 0.5, 0.8], [0.9, 0.5, 0.3, 0.8, 0.7]])
self.rho_tm1 = np.array(
[[0.5, 0.9, 1.3, 0.2, 0.8], [2., 0.1, 1., 0.4, 1.7]])
self.values = np.array(
[[3.0, 1.0, 5.0, -5.0, 3.0, 1.], [-1.7, 1.2, 2.3, 2.2, 2.7, 2.]])
@chex.all_variants()
def test_importance_corrected_td_errors_batch(self):
"""Tests equivalence to computing the error from a the lambda-return."""
# Vmap and optionally compile.
lambda_returns = self.variant(jax.vmap(multistep.lambda_returns))
td_errors = self.variant(jax.vmap(multistep.importance_corrected_td_errors))
# Compute multistep td-error with recursion on deltas.
td_direct = td_errors(self.r_t, self.discount_t, self.rho_tm1,
np.ones_like(self.discount_t), self.values)
# Compute off-policy corrected return, and derive td-error from it.
ls_ = np.concatenate((self.rho_tm1[:, 1:], [[1.], [1.]]), axis=1)
td_from_returns = self.rho_tm1 * (
lambda_returns(self.r_t, self.discount_t, self.values[:, 1:], ls_) -
self.values[:, :-1])
# Check equivalence.
np.testing.assert_allclose(td_direct, td_from_returns, rtol=1e-5)
class TruncatedGeneralizedAdvantageEstimationTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.r_t = jnp.array([[0., 0., 1., 0., -0.5],
[0., 0., 0., 0., 1.]])
self.v_t = jnp.array([[1., 4., -3., -2., -1., -1.],
[-3., -2., -1., 0.0, 5., -1.]])
self.discount_t = jnp.array([[0.99, 0.99, 0.99, 0.99, 0.99],
[0.9, 0.9, 0.9, 0.0, 0.9]])
self.dummy_rho_tm1 = jnp.array([[1., 1., 1., 1., 1],
[1., 1., 1., 1., 1.]])
self.array_lambda = jnp.array([[0.9, 0.9, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.9, 0.9, 0.9]])
# Different expected results for different values of lambda.
self.expected = {}
self.expected[1.] = np.array(
[[-1.45118, -4.4557, 2.5396, 0.5249, -0.49],
[3., 2., 1., 0., -4.9]],
dtype=np.float32)
self.expected[0.7] = np.array(
[[-0.676979, -5.248167, 2.4846, 0.6704, -0.49],
[2.2899, 1.73, 1., 0., -4.9]],
dtype=np.float32)
self.expected[0.4] = np.array(
[[0.56731, -6.042, 2.3431, 0.815, -0.49],
[1.725, 1.46, 1., 0., -4.9]],
dtype=np.float32)
@chex.all_variants()
@parameterized.named_parameters(
('lambda1', 1.0),
('lambda0.7', 0.7),
('lambda0.4', 0.4))
def test_truncated_gae(self, lambda_):
"""Tests truncated GAE for a full batch."""
batched_advantage_fn_variant = self.variant(jax.vmap(
multistep.truncated_generalized_advantage_estimation,
in_axes=(0, 0, None, 0), out_axes=0))
actual = batched_advantage_fn_variant(
self.r_t, self.discount_t, lambda_, self.v_t)
np.testing.assert_allclose(self.expected[lambda_], actual, atol=1e-3)
@chex.all_variants()
def test_array_lambda(self):
"""Tests that truncated GAE is consistent with scalar or array lambda_."""
scalar_lambda_fn = self.variant(jax.vmap(
multistep.truncated_generalized_advantage_estimation,
in_axes=(0, 0, None, 0), out_axes=0))
array_lambda_fn = self.variant(jax.vmap(
multistep.truncated_generalized_advantage_estimation))
scalar_lambda_result = scalar_lambda_fn(
self.r_t, self.discount_t, 0.9, self.v_t)
array_lambda_result = array_lambda_fn(
self.r_t, self.discount_t, self.array_lambda, self.v_t)
np.testing.assert_allclose(scalar_lambda_result, array_lambda_result,
atol=1e-3)
@chex.all_variants()
@parameterized.named_parameters(
('lambda_1', 1.0),
('lambda_0.7', 0.7),
('lambda_0.4', 0.4))
def test_gae_as_special_case_of_importance_corrected_td_errors(self, lambda_):
"""Tests truncated GAE.
Tests that truncated GAE yields same output as importance corrected
td errors with dummy ratios.
Args:
lambda_: a lambda to use in GAE.
"""
batched_gae_fn_variant = self.variant(jax.vmap(
multistep.truncated_generalized_advantage_estimation,
in_axes=(0, 0, None, 0), out_axes=0))
gae_result = batched_gae_fn_variant(
self.r_t, self.discount_t, lambda_, self.v_t)
batched_ictd_errors_fn_variant = self.variant(jax.vmap(
multistep.importance_corrected_td_errors))
ictd_errors_result = batched_ictd_errors_fn_variant(
self.r_t,
self.discount_t,
self.dummy_rho_tm1,
jnp.ones_like(self.discount_t) * lambda_,
self.v_t)
np.testing.assert_allclose(gae_result, ictd_errors_result, atol=1e-3)
if __name__ == '__main__':
jax.config.update('jax_numpy_rank_promotion', 'raise')
absltest.main()
| rlax-master | rlax/_src/multistep_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""JAX implementation of common losses.
Deep reinforcement learning algorithms are often expressed as gradients of
suitable pseudo-loss functions constructed from the observations and rewards
collected in the environment. In this subpackage we collate common mathematical
transformations used to construct such losses.
"""
import functools
from typing import Optional, Union
import chex
import jax
import jax.numpy as jnp
from rlax._src import general_value_functions
from rlax._src import value_learning
Scalar = chex.Scalar
Array = chex.Array
def l2_loss(predictions: Array,
targets: Optional[Array] = None) -> Array:
"""Caculates the L2 loss of predictions wrt targets.
If targets are not provided this function acts as an L2-regularizer for preds.
Note: the 0.5 term is standard in "Pattern Recognition and Machine Learning"
by Bishop, but not "The Elements of Statistical Learning" by Tibshirani.
Args:
predictions: a vector of arbitrary shape.
targets: a vector of shape compatible with predictions.
Returns:
a vector of same shape of `predictions`.
"""
if targets is None:
targets = jnp.zeros_like(predictions)
chex.assert_type([predictions, targets], float)
return 0.5 * (predictions - targets)**2
def likelihood(predictions: Array, targets: Array) -> Array:
"""Calculates the likelihood of predictions wrt targets.
Args:
predictions: a vector of arbitrary shape.
targets: a vector of shape compatible with predictions.
Returns:
a vector of same shape of `predictions`.
"""
chex.assert_type([predictions, targets], float)
likelihood_vals = predictions**targets * (1. - predictions)**(1. - targets)
# Note: 0**0 evaluates to NaN on TPUs, manually set these cases to 1.
filter_indices = jnp.logical_or(
jnp.logical_and(targets == 1, predictions == 1),
jnp.logical_and(targets == 0, predictions == 0))
return jnp.where(filter_indices, 1, likelihood_vals)
def log_loss(
predictions: Array,
targets: Array,
) -> Array:
"""Calculates the log loss of predictions wrt targets.
Args:
predictions: a vector of probabilities of arbitrary shape.
targets: a vector of probabilities of shape compatible with predictions.
Returns:
a vector of same shape of `predictions`.
"""
chex.assert_type([predictions, targets], float)
return -jnp.log(likelihood(predictions, targets))
def pixel_control_loss(
observations: Array,
actions: Array,
action_values: Array,
discount_factor: Union[Array, Scalar],
cell_size: int):
"""Calculate n-step Q-learning loss for pixel control auxiliary task.
For each pixel-based pseudo reward signal, the corresponding action-value
function is trained off-policy, using Q(lambda). A discount of 0.9 is
commonly used for learning the value functions.
Note that, since pseudo rewards have a spatial structure, with neighbouring
cells exhibiting strong correlations, it is convenient to predict the action
values for all the cells through a deconvolutional head.
See "Reinforcement Learning with Unsupervised Auxiliary Tasks" by Jaderberg,
Mnih, Czarnecki et al. (https://arxiv.org/abs/1611.05397).
Args:
observations: A tensor of shape `[T+1, ...]`; `...` is the observation
shape, `T` the sequence length.
actions: A tensor, shape `[T,]`, of the actions across each sequence.
action_values: A tensor, shape `[T+1, H, W, N]` of pixel control action
values, where `H`, `W` are the number of pixel control cells/tasks, and
`N` is the number of actions.
discount_factor: discount used for learning the value function associated
to the pseudo rewards; must be a scalar or a Tensor of shape [T].
cell_size: size of the cells used to derive the pixel based pseudo-rewards.
Returns:
a tensor containing the spatial loss, shape [T, H, W].
Raises:
ValueError: if the shape of `action_values` is not compatible with that of
the pseudo-rewards derived from the observations.
"""
# Check shapes
assert len(actions.shape) == 1
assert len(action_values.shape) == 4
# Check types
chex.assert_type([observations], float)
chex.assert_type([actions], int)
# Useful shapes.
sequence_length = actions.shape[0]
num_actions = action_values.shape[-1]
height_width_q = action_values.shape[1:-1]
# Calculate rewards using the observations.
# Compute pseudo-rewards and get their shape.
pseudo_rewards = general_value_functions.pixel_control_rewards(
observations, cell_size)
height_width = pseudo_rewards.shape[1:]
# Check that pseudo-rewards and Q-values are compatible in shape.
if height_width != height_width_q:
raise ValueError(
"Pixel Control values are not compatible with the shape of the"
"pseudo-rewards derived from the observation. Pseudo-rewards have "
f"shape {height_width}, while Pixel Control values have "
f"shape {height_width_q}")
# We now have Q(s,a) and rewards, so can calculate the n-step loss. The
# QLambda loss op expects inputs of shape [T,N] and [T], but our tensors
# are in a variety of incompatible shapes. The state-action values have
# shape [T,H,W,N] and rewards have shape [T,H,W]. We can think of the
# [H,W] dimensions as extra batch dimensions for the purposes of the loss
# calculation, so we first collapse [H,W] into a single dimension.
q_tm1 = jnp.reshape(action_values[:-1], (sequence_length, -1, num_actions))
r_t = jnp.reshape(pseudo_rewards, (sequence_length, -1))
q_t = jnp.reshape(action_values[1:], (sequence_length, -1, num_actions))
# The actions tensor is of shape [T], and is the same for each H and W.
# We thus expand it to be same shape as the reward tensor, [T,HW].
expanded_actions = actions[..., None, None]
a_tm1 = jnp.tile(expanded_actions, (1,) + height_width)
a_tm1 = jnp.reshape(a_tm1, (sequence_length, -1))
# We similarly expand-and-tile the discount to [T,HW].
discount_factor = jnp.asarray(discount_factor)
if not discount_factor.shape:
pcont_t = jnp.reshape(discount_factor, (1,))
pcont_t = jnp.tile(pcont_t, a_tm1.shape)
elif len(discount_factor.shape) == 1:
tiled_pcont = jnp.tile(
discount_factor[:, None, None], (1,) + height_width)
pcont_t = jnp.reshape(tiled_pcont, (sequence_length, -1))
else:
raise ValueError(
"The discount_factor must be a scalar or a tensor of rank 1. "
f"instead is a tensor of shape {discount_factor.shape}")
# Compute a QLambda loss of shape [T,HW]
batched_q_lambda = jax.vmap(
functools.partial(
value_learning.q_lambda, lambda_=1.0),
in_axes=1, out_axes=1)
td_error = batched_q_lambda(q_tm1, a_tm1, r_t, pcont_t, q_t)
loss = 0.5 * td_error**2
expanded_shape = (sequence_length,) + height_width
spatial_loss = jnp.reshape(loss, expanded_shape) # [T,H,W].
return spatial_loss
def expectile_loss(predictions: Array, targets: Array, expectile: float):
"""Expectile loss that weighs over-/under-estimations of targets differently.
The formulation is an asymmetric least squares loss which downweights the
contributions of predictions that underestimate targets and upweights
overestimation of targets.
See Implicit Q Learning (https://arxiv.org/pdf/2110.06169.pdf) Sec 4.1 for
more details on this loss.
Args:
predictions: Tensor of shape [T, ...] where T is the sequence length.
targets: Target values for predictions with identical shape as predictions.
expectile: A float value that represents the weights assigned to predictions
that over-estimate targets.
Returns:
a vector of same shape as predictions.
"""
chex.assert_equal_shape([predictions, targets])
diff = targets - predictions
is_underestimation = jnp.less(diff, 0)
weight = jnp.abs(expectile - is_underestimation)
return weight * (diff**2)
| rlax-master | rlax/_src/losses.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Unit tests for `policy_targets.py`."""
from absl.testing import absltest
import distrax
import jax
import jax.numpy as jnp
import numpy as np
from rlax._src import policy_targets
class PolicyTargetsTest(absltest.TestCase):
def test_sampled_policy_distillation_loss(self):
targets = policy_targets.PolicyTarget(
actions=jnp.array([0, 1], dtype=jnp.int32),
weights=jnp.array([0.5, 0.0], dtype=jnp.float32))
distribution = distrax.Categorical(
probs=jnp.array([[0.7, 0.3], [0.9, 0.1]], dtype=jnp.float32))
loss = policy_targets.sampled_policy_distillation_loss(
distribution=distribution,
policy_targets=targets)
expected_loss = 0.089169
np.testing.assert_allclose(expected_loss, loss, atol=1e-4)
def test_constant_policy_targets(self):
rng_key = jax.random.PRNGKey(42)
num_samples = 4
weights_scale = 0.2
distribution = distrax.Categorical(
probs=jnp.array([0.5, 0.5], dtype=jnp.float32))
constant_targets = policy_targets.constant_policy_targets(
distribution, rng_key, num_samples, weights_scale)
expected_random_actions = distribution.sample(
seed=rng_key, sample_shape=(num_samples,))
expected_target_weights = weights_scale * jnp.ones((num_samples,))
np.testing.assert_allclose(
constant_targets.weights,
expected_target_weights, atol=1e-4)
np.testing.assert_allclose(
constant_targets.actions,
expected_random_actions, atol=1e-4)
if __name__ == '__main__':
absltest.main()
| rlax-master | rlax/_src/policy_targets_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for perturbations.py."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from rlax._src import nested_updates
class NestedUpdatesTest(parameterized.TestCase):
def setUp(self):
super().setUp()
old = jnp.zeros((3,), dtype=jnp.float32)
new = jnp.ones((3,), dtype=jnp.float32)
self._old_struct = ((old, old), old)
self._new_struct = ((new, new), new)
@chex.all_variants()
def test_conditional_update_is_time(self):
"""Check periodic update enabled."""
conditional_update = self.variant(nested_updates.conditional_update)
is_time = jnp.array(True)
output = conditional_update(self._new_struct, self._old_struct, is_time)
for o, exp in zip(
jax.tree_leaves(output), jax.tree_leaves(self._new_struct)):
np.testing.assert_allclose(o, exp)
@chex.all_variants()
def test_conditional_update_is_not_time(self):
"""Check periodic update disables."""
conditional_update = self.variant(nested_updates.conditional_update)
is_not_time = jnp.array(False)
output = conditional_update(self._new_struct, self._old_struct, is_not_time)
for o, exp in zip(
jax.tree_leaves(output), jax.tree_leaves(self._old_struct)):
np.testing.assert_allclose(o, exp)
if __name__ == '__main__':
absltest.main()
| rlax-master | rlax/_src/nested_updates_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for losses.py."""
import functools
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
import numpy as np
from rlax._src import losses
class L2LossTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.xs = jnp.array([-2, -1, -0.5, 0, 0.5, 1, 2])
self.ys = jnp.array([2., 0.5, 0.125, 0, 0.125, 0.5, 2.])
self.dys = jnp.array([-2, -1, -0.5, 0, 0.5, 1, 2])
@chex.all_variants()
def test_l2_loss_scalar(self):
l2_loss = self.variant(losses.l2_loss)
x = jnp.array(0.5)
# Test output.
np.testing.assert_allclose(l2_loss(x), 0.125)
@chex.all_variants()
def test_l2_loss_vector(self):
l2_loss = self.variant(losses.l2_loss)
# Test output.
np.testing.assert_allclose(l2_loss(self.xs), self.ys)
@chex.all_variants()
def test_l2_regularizer(self):
l2_loss = self.variant(losses.l2_loss)
# Test output.
np.testing.assert_allclose(
l2_loss(self.xs), l2_loss(self.xs, jnp.zeros_like(self.xs)))
@chex.all_variants()
def test_gradients(self):
l2_loss = self.variant(losses.l2_loss)
# Compute gradient in batch
batch_grad_func = jax.vmap(jax.grad(l2_loss), (0))
actual = batch_grad_func(self.xs)
np.testing.assert_allclose(actual, self.dys)
class ExpectileLossTest(parameterized.TestCase):
@chex.all_variants()
@parameterized.named_parameters(
('expectile_0.5', 0.5, [-2., -1., -0.5, 0., 0.5, 1., 2.
], [2., 0.5, 0.125, 0., 0.125, 0.5, 2.]),
('expectile_0.0', 0.0, [-2., -1., -0.5, 0., 0.5, 1., 2.
], [0., 0., 0., 0., 0.25, 1.0, 4.0]),
('expectile_1.0', 1.0, [-2., -1., -0.5, 0., 0.5, 1., 2.
], [4.0, 1.0, 0.25, 0., 0.0, 0.0, 0.0]),
('expectile_0.75', 0.75, [-2., -1., -0.5, 0., 0.5, 1., 2.
], [3.0, 0.75, 0.1875, 0., 0.0625, 0.25, 1.0]),
)
def test_expectile_loss_vector(self, expectile, predictions, expected_loss):
expectile_loss = self.variant(losses.expectile_loss)
predictions = jnp.array(predictions)
expected_loss = jnp.array(expected_loss)
targets = jnp.zeros_like(predictions)
# Test output.
np.testing.assert_allclose(
expectile_loss(
predictions=predictions,
targets=targets,
expectile=expectile,
),
expected_loss,
atol=1e-4)
@chex.all_variants()
@parameterized.named_parameters(
('expectile_0.5', 0.5, [-2., -1., -0.5, 0., 0.5, 1., 2.
], [-2., -1., -0.5, 0., 0.5, 1.0, 2.0]),
('expectile_0.0', 0.0, [-2., -1., -0.5, 0., 0.5, 1., 2.
], [0., 0., 0., 0., 1.0, 2.0, 4.0]),
('expectile_1.0', 1.0, [-2., -1., -0.5, 0., 0.5, 1., 2.
], [-4.0, -2.0, -1.0, 0.0, 0.0, 0.0, 0.0]),
('expectile_0.75', 0.75, [-2., -1., -0.5, 0., 0.5, 1., 2.
], [-3.0, -1.5, -0.75, 0., 0.25, 0.50, 1.0]),
)
def test_gradients(self, expectile, predictions, expected_grads):
predictions = jnp.array(predictions)
expected_grads = jnp.array(expected_grads)
targets = jnp.zeros_like(predictions)
expectile_loss_fn = self.variant(
functools.partial(losses.expectile_loss, expectile=expectile))
batch_grad_fn = jax.vmap(jax.grad(expectile_loss_fn), (0, 0))
predicted_grads = batch_grad_fn(predictions, targets)
np.testing.assert_allclose(predicted_grads, expected_grads, atol=1e-4)
class LogLossTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.preds = jnp.array([1., 1., 0., 0., 0.5, 0.5])
self.targets = jnp.array([1., 0., 0., 1., 1., 0])
self.expected = jnp.array([0., np.inf, 0., np.inf, 0.6931472, 0.6931472])
@chex.all_variants()
def test_log_loss_scalar(self):
log_loss = self.variant(losses.log_loss)
preds = self.preds[2]
targets = self.targets[2]
# Test output.
np.testing.assert_allclose(
log_loss(preds, targets), self.expected[2], atol=1e-4)
@chex.all_variants()
def test_log_loss_vector(self):
log_loss = self.variant(losses.log_loss)
# Test output.
np.testing.assert_allclose(
log_loss(self.preds, self.targets), self.expected, atol=1e-4)
class PixelControlLossTest(parameterized.TestCase):
"""Test the `pixel_control_loss` op."""
def setUp(self):
"""Defines example data and expected result for the op."""
super().setUp()
# Observation shape is (2,2,3) (i.e., height 2, width 2, and 3 channels).
# We will use no cropping, and a cell size of 1. We have num_actions = 3,
# meaning our Q values should be (2,2,3). We will set the Q value equal to
# the observation.
self.seq_length = 3
self.discount = 0.9
self.cell_size = 1
# Observations.
obs1 = np.array([[[1, 2, 3], [3, 4, 5]], [[5, 6, 7], [7, 8, 9]]])
obs2 = np.array([[[7, 8, 9], [1, 2, 3]], [[3, 4, 5], [5, 6, 7]]])
obs3 = np.array([[[5, 6, 7], [7, 8, 9]], [[1, 2, 3], [3, 4, 5]]])
obs4 = np.array([[[3, 4, 5], [5, 6, 7]], [[7, 8, 9], [1, 2, 3]]])
# Actions.
action1 = 0
action2 = 1
action3 = 2
# Compute loss for constant discount.
qa_tm1 = obs3[:, :, action3]
reward3 = np.mean(np.abs(obs4 - obs3), axis=2)
qmax_t = np.amax(obs4, axis=2)
target = reward3 + self.discount * qmax_t
error3 = target - qa_tm1
qa_tm1 = obs2[:, :, action2]
reward2 = np.mean(np.abs(obs3 - obs2), axis=2)
target = reward2 + self.discount * target
error2 = target - qa_tm1
qa_tm1 = obs1[:, :, action1]
reward1 = np.mean(np.abs(obs2 - obs1), axis=2)
target = reward1 + self.discount * target
error1 = target - qa_tm1
# Compute loss for episode termination with discount 0.
qa_tm1 = obs1[:, :, action1]
reward1 = np.mean(np.abs(obs2 - obs1), axis=2)
target = reward1 + 0. * target
error1_term = target - qa_tm1
self.error = np.sum(
np.square(error1) + np.square(error2) + np.square(error3)) * 0.5
self.error_term = np.sum(
np.square(error1_term) + np.square(error2) + np.square(error3)) * 0.5
self.observations = np.stack([obs1, obs2, obs3, obs4], axis=0).astype(
np.float32)
self.action_values = self.observations
self.actions = np.array([action1, action2, action3])
@chex.all_variants()
def testPixelControlLossScalarDiscount(self):
"""Compute loss for given observations, actions, values, scalar discount."""
loss_fn = self.variant(functools.partial(
losses.pixel_control_loss, cell_size=self.cell_size))
loss = loss_fn(
self.observations,
self.actions,
self.action_values,
self.discount)
loss = jnp.sum(loss)
np.testing.assert_allclose(loss, self.error, rtol=1e-3)
@chex.all_variants()
def testPixelControlLossTensorDiscount(self):
"""Compute loss for given observations, actions, values, tensor discount."""
zero_discount = np.zeros((1,))
non_zero_discount = self.discount * np.ones(self.seq_length - 1)
discount = np.concatenate([zero_discount, non_zero_discount], axis=0)
loss_fn = self.variant(functools.partial(
losses.pixel_control_loss, cell_size=self.cell_size))
loss = loss_fn(
self.observations,
self.actions,
self.action_values,
discount)
loss = jnp.sum(loss)
np.testing.assert_allclose(loss, self.error_term, rtol=1e-3)
@chex.all_variants()
def testPixelControlLossShapes(self):
with self.assertRaisesRegex(
ValueError, 'Pixel Control values are not compatible'):
loss_fn = self.variant(functools.partial(
losses.pixel_control_loss, cell_size=self.cell_size))
loss_fn(
self.observations, self.actions,
self.action_values[:, :-1], self.discount)
@chex.all_variants()
def testTensorDiscountShape(self):
with self.assertRaisesRegex(
ValueError, 'discount_factor must be a scalar or a tensor of rank 1'):
discount = np.tile(
np.reshape(self.discount, (1, 1)), (self.seq_length, 1))
loss_fn = self.variant(functools.partial(
losses.pixel_control_loss, cell_size=self.cell_size))
loss_fn(
self.observations, self.actions, self.action_values, discount)
if __name__ == '__main__':
jax.config.update('jax_numpy_rank_promotion', 'raise')
absltest.main()
| rlax-master | rlax/_src/losses_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for pop_art.py."""
import functools
from absl.testing import absltest
from absl.testing import parameterized
import chex
import haiku as hk
from haiku import data_structures
from haiku import initializers
import jax
import jax.nn
import jax.numpy as jnp
import numpy as np
from rlax._src import pop_art
_INPUT_DIM = 3
def setUpModule():
chex.set_n_cpu_devices(n=4)
chex.assert_devices_available(n=4, devtype='cpu', backend='cpu')
def get_constant_linear_params(num_outputs):
w = np.ones([_INPUT_DIM, num_outputs])
b = np.zeros([num_outputs])
return dict(w=w, b=b)
def get_fake_pop_art_state(num_outputs):
"""Returns a fake PopArtState."""
shift = np.arange(num_outputs).astype(np.float32) + 1
scale = shift
second_moment = np.square(scale) + np.square(shift)
return pop_art.PopArtState(shift, scale, second_moment)
class PopArtTest(parameterized.TestCase):
@parameterized.parameters(
(None, np.array([[[0., 0., 1.],
[0., 5., 0.]],
[[9., 0., 0.],
[0., 0., 0.]]])),
([], np.array([[[0., 0., 1.],
[0., 5., 0.]],
[[9., 0., 0.],
[0., 0., 0.]]])),
(['i'], np.array([[[0., 5., 1.],
[0., 5., 1.]],
[[9., 0., 0.],
[9., 0., 0.]]])),
(['j'], np.array([[[9., 0., 1.],
[0., 5., 0.]],
[[9., 0., 1.],
[0., 5., 0.]]])),
(['i', 'j'], np.array([[[9., 5., 1.],
[9., 5., 1.]],
[[9., 5., 1.],
[9., 5., 1.]]])))
def test_cross_replica_scatter_add(self, axes, expected):
shape = (2, 2, 3)
source = np.zeros(shape)
fn = functools.partial(pop_art._cross_replica_scatter_add, axis_name=axes)
mapped_fn = jax.pmap(fn, axis_name='i', backend='cpu')
mapped_fn = jax.pmap(mapped_fn, axis_name='j', backend='cpu')
updates = np.array([[[1., 0., 0.],
[0., 5., 0.]],
[[0., 0., 9.],
[0., 0., 0.]]])
indices = np.array([[[2, 2, 2],
[1, 1, 1]],
[[0, 0, 0],
[0, 1, 2]]])
np.testing.assert_equal(mapped_fn(source, indices, updates), expected)
def test_normalize_unnormalize_is_identity(self):
num_outputs = 3
state = get_fake_pop_art_state(num_outputs)
np.random.seed(42)
# Draws random numbers with the same magnitude as the pop art shift and
# scales to ensure numerical stability.
values = np.random.randint(-10, 10, size=(100,)).astype(np.float32)
indices = np.random.randint(0, num_outputs, size=(100,))
np.testing.assert_allclose(
values,
pop_art.normalize(state, pop_art.unnormalize(state, values, indices),
indices))
np.testing.assert_allclose(
values,
pop_art.unnormalize(state, pop_art.normalize(state, values, indices),
indices))
def test_unnormalize_linear(self):
num_outputs = 3
state = get_fake_pop_art_state(num_outputs)
# Verify that it denormalizes as planned.
inputs = np.ones([num_outputs, num_outputs])
indices = np.arange(num_outputs)[::-1]
out = pop_art.unnormalize_linear(state, inputs, indices)
expected_normalized = np.asarray([1, 1, 1])
expected_unnormalized = np.asarray([6, 4, 2])
np.testing.assert_allclose(out.normalized, expected_normalized)
np.testing.assert_allclose(out.unnormalized, expected_unnormalized)
def test_learn_scale_shift(self):
num_outputs = 2
initial_state, update = pop_art.popart(
num_outputs, step_size=1e-1, scale_lb=1e-6, scale_ub=1e6)
state = initial_state()
params = get_constant_linear_params(num_outputs)
targets = np.arange(6) - 3
indices = np.asarray([0, 0, 0, 1, 1, 1])
# Learn the parameters.
for _ in range(10):
_, state = update(params, state, targets, indices)
expected_scale = np.std(targets[:3])
expected_scale = np.asarray([expected_scale, expected_scale])
expected_shift = np.asarray([-2., 1.])
# Loose tolerances; just get close.
np.testing.assert_allclose(
state.scale, expected_scale, atol=1e-1, rtol=1e-1)
np.testing.assert_allclose(
state.shift, expected_shift, atol=1e-1, rtol=1e-1)
def test_slow_update(self):
num_outputs = 2
# Two step sizes: 0.1, and 0.8
kwargs = dict(
num_outputs=num_outputs,
scale_lb=1e-6,
scale_ub=1e6,
)
initial_state, slow_update = pop_art.popart(step_size=1e-2, **kwargs)
_, fast_update = pop_art.popart(step_size=1e-1, **kwargs)
state = initial_state()
params = get_constant_linear_params(num_outputs)
targets = np.arange(6) * 3 # standard deviation > 1 and mean > 0
indices = np.asarray([0, 0, 0, 1, 1, 1])
_, slow_state = slow_update(params, state, targets, indices)
_, fast_state = fast_update(params, state, targets, indices)
# Faster step size means faster adjustment.
np.testing.assert_array_less(slow_state.shift, fast_state.shift)
np.testing.assert_array_less(slow_state.scale, fast_state.scale)
def test_scale_bounded(self):
num_outputs = 1
# Set scale_lb and scale_ub to 1 and verify this is obeyed.
initial_state, update = pop_art.popart(
num_outputs, step_size=1e-1, scale_lb=1., scale_ub=1.)
state = initial_state()
params = get_constant_linear_params(num_outputs)
targets = np.ones((4, 2))
indices = np.zeros((4, 2), dtype=np.int32)
for _ in range(4):
_, state = update(params, state, targets, indices)
self.assertAlmostEqual(float(state.scale[0]), 1.)
def test_outputs_preserved(self):
num_outputs = 2
initial_state, update = pop_art.popart(
num_outputs, step_size=1e-3, scale_lb=1e-6, scale_ub=1e6)
state = initial_state()
key = jax.random.PRNGKey(428)
def net(x):
linear = hk.Linear(
num_outputs, b_init=initializers.RandomUniform(), name='head')
return linear(x)
init_fn, apply_fn = hk.without_apply_rng(hk.transform(net))
key, subkey1, subkey2 = jax.random.split(key, 3)
fixed_data = jax.random.uniform(subkey1, (4, 3))
params = init_fn(subkey2, fixed_data)
initial_result = apply_fn(params, fixed_data)
indices = np.asarray([0, 1, 0, 1, 0, 1, 0, 1])
# Repeatedly update state and verify that params still preserve outputs.
for _ in range(30):
key, subkey1, subkey2 = jax.random.split(key, 3)
targets = jax.random.uniform(subkey1, (8,))
linear_params, state = update(params['head'], state, targets, indices)
params = data_structures.to_mutable_dict(params)
params['head'] = linear_params
# Apply updated linear transformation and unnormalize outputs.
transform = apply_fn(params, fixed_data)
out = jnp.broadcast_to(state.scale,
transform.shape) * transform + jnp.broadcast_to(
state.shift, transform.shape)
np.testing.assert_allclose(initial_result, out, atol=1e-2)
if __name__ == '__main__':
jax.config.update('jax_numpy_rank_promotion', 'raise')
absltest.main()
| rlax-master | rlax/_src/pop_art_test.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""JAX functions implementing utilities on a simple episodic memory.
Some reinforcement learning agents utilize episodic memory to calculate
exploration bonus rewards among other things. This subpackage contains utility
functions for querying episodic memory.
"""
import functools
from typing import Callable
import chex
import jax
import jax.numpy as jnp
Array = chex.Array
MetricFn = Callable[[Array, Array], Array]
@chex.dataclass
class KNNQueryResult():
neighbors: jnp.ndarray
neighbor_indices: jnp.ndarray
neighbor_neg_distances: jnp.ndarray
def _sqeuclidian(x: Array, y: Array) -> Array:
return jnp.sum(jnp.square(x - y))
def _cdist(a: Array, b: Array, metric: MetricFn) -> Array:
"""Returns the distance between each pair of the two collections of inputs."""
return jax.vmap(jax.vmap(metric, (None, 0)), (0, None))(a, b)
def knn_query(
data: Array,
query_points: Array,
num_neighbors: int,
metric: MetricFn = _sqeuclidian,
) -> KNNQueryResult:
"""Finds closest neighbors in data to the query points & their neg distances.
NOTE: For this function to be jittable, static_argnums=[2,] must be passed, as
the internal jax.lax.top_k(neg_distances, num_neighbors) computation cannot be
jitted with a dynamic num_neighbors that is passed as an argument.
Args:
data: array of existing data points (elements in database x feature size)
query_points: array of points to find neighbors of
(num query points x feature size).
num_neighbors: number of neighbors to find.
metric: Metric to use in calculating distance between two points.
Returns:
KNNQueryResult with (all sorted by neg distance):
- neighbors (num query points x num neighbors x feature size)
- neighbor_indices (num query points x num neighbors)
- neighbor_neg_distances (num query points x num neighbors)
* if num_neighbors is greater than number of elements in the database,
just return KNNQueryResult with the number of elements in the database.
"""
chex.assert_rank([data, query_points], 2)
assert data.shape[-1] == query_points.shape[-1]
distance_fn = jax.jit(functools.partial(_cdist, metric=metric))
neg_distances = -distance_fn(query_points, data)
neg_distances, indices = jax.lax.top_k(
neg_distances, k=min(num_neighbors, data.shape[0]))
# Batch index into data using indices shaped [num queries, num neighbors]
neighbors = jax.vmap(lambda d, i: d[i], (None, 0))(jnp.array(data), indices)
return KNNQueryResult(neighbors=neighbors, neighbor_indices=indices,
neighbor_neg_distances=neg_distances)
| rlax-master | rlax/_src/episodic_memory.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities for RLax functions."""
from typing import Optional, Sequence, Union
import chex
import jax
import jax.numpy as jnp
import numpy as np
Array = chex.Array
Numeric = chex.Numeric
def batched_index(
values: Array, indices: Array, keepdims: bool = False
) -> Array:
"""Index into the last dimension of a tensor, preserving all others dims.
Args:
values: a tensor of shape [..., D],
indices: indices of shape [...].
keepdims: whether to keep the final dimension.
Returns:
a tensor of shape [...] or [..., 1].
"""
indexed = jnp.take_along_axis(values, indices[..., None], axis=-1)
if not keepdims:
indexed = jnp.squeeze(indexed, axis=-1)
return indexed
def one_hot(indices, num_classes, dtype=jnp.float32):
"""Returns a one-hot version of indices.
Args:
indices: A tensor of indices.
num_classes: Number of classes in the one-hot dimension.
dtype: The dtype.
Returns:
The one-hot tensor. If indices' shape is [A, B, ...], shape is
[A, B, ..., num_classes].
"""
labels = jnp.arange(num_classes)
for _ in range(indices.ndim):
labels = jnp.expand_dims(labels, axis=0)
return jnp.array(
indices[..., jnp.newaxis] == labels, dtype=dtype)
def lhs_broadcast(source, target):
"""Ensures that source is compatible with target for broadcasting."""
same_shape = np.array(source.shape) == np.array(target.shape[:source.ndim])
ones = np.array(source.shape) == np.ones((source.ndim,))
if np.all(same_shape + ones):
broadcast_shape = source.shape + (1,) * (target.ndim - source.ndim)
return jnp.reshape(source, broadcast_shape)
raise ValueError(
f"source shape {source.shape} is not compatible with "
f"target shape {target.shape}")
def replace_masked(
data: chex.Array, replacement: Optional[chex.Array], mask: chex.Array
):
"""Replace slices of an array as indicated by a mask.
Args:
data: an array whose some elements we want to replace.
replacement: an array with the same shape as `data`, containing the data to
insert according to `mask`. If `None` is passed, then the masked elements
in `data` will be replaced with zeros.
mask: a mask of 0/1s, whose shape is a prefix of `data` and `replacements`.
When the mask is 1, values of data are replaced.
Returns:
the updated tensor.
"""
if replacement is None:
replacement = jnp.zeros_like(data)
return jnp.where(lhs_broadcast(mask, data), replacement, data)
class AllSum:
"""Helper for summing over elements in an array and over devices."""
def __init__(self, axis_name: Optional[str] = None):
"""Sums locally and then over devices with the axis name provided."""
self._axis_name = axis_name
def __call__(
self, x: Array, axis: Optional[Union[int, Sequence[int]]] = None
) -> Array:
s = jnp.sum(x, axis=axis)
if self._axis_name:
s = jax.lax.psum(s, axis_name=self._axis_name)
return s
| rlax-master | rlax/_src/base.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `tree_util.py`."""
from absl.testing import absltest
import chex
import jax
import jax.numpy as jnp
import numpy as np
from rlax._src import tree_util
NUM_NESTS = 5
class TreeUtilTest(absltest.TestCase):
def test_tree_split_key(self):
rng_key = jax.random.PRNGKey(42)
tree_like = (1, (2, 3), {'a': 4})
_, tree_keys = tree_util.tree_split_key(rng_key, tree_like)
self.assertLen(jax.tree_leaves(tree_keys), 4)
def test_tree_map_zipped(self):
nests = [
dict(a=jnp.zeros((1, 3)), b=jnp.zeros((1, 5)))] * NUM_NESTS
nest_output = tree_util.tree_map_zipped(
lambda *args: jnp.concatenate(args), nests)
self.assertEqual(nest_output['a'].shape, (NUM_NESTS, 3))
self.assertEqual(nest_output['b'].shape, (NUM_NESTS, 5))
def test_tree_map_zipped_wrong_structure(self):
nests = [
dict(a=jnp.zeros((1, 3)), b=jnp.zeros((1, 5)))] * (NUM_NESTS - 1)
nests.append(dict(c=jnp.zeros((1, 3)))) # add a non-matching nest
with self.assertRaisesRegex(ValueError, 'must share the same tree'):
tree_util.tree_map_zipped(
lambda *args: jnp.concatenate(args), nests)
def test_tree_map_zipped_empty(self):
outputs = tree_util.tree_map_zipped(lambda *args: jnp.concatenate(args), [])
self.assertEmpty(outputs)
def test_select_true(self):
on_true = ((jnp.zeros(3,),), jnp.zeros(4,))
on_false = ((jnp.ones(3,),), jnp.ones(4,))
output = tree_util.tree_select(jnp.array(True), on_true, on_false)
chex.assert_trees_all_close(output, on_true)
def test_select_false(self):
on_true = ((jnp.zeros(3,),), jnp.zeros(4,))
on_false = ((jnp.ones(3,),), jnp.ones(4,))
output = tree_util.tree_select(jnp.array(False), on_true, on_false)
chex.assert_trees_all_close(output, on_false)
def test_tree_split_leaves(self):
t = {
'a0': np.zeros(3),
'd': {
'a1': np.arange(3),
'a2': np.zeros([3, 3]) + 2,
},
't4': (np.zeros([3, 2]) + 4, np.arange(3)),
}
for keepdim in (False, True):
expd_shapes = jax.tree_map(lambda x: np.zeros(x.shape[1:]), t)
if keepdim:
expd_shapes = jax.tree_map(lambda x: np.expand_dims(x, 0), expd_shapes)
res_trees = tree_util.tree_split_leaves(t, axis=0, keepdim=keepdim)
self.assertLen(res_trees, 3)
chex.assert_trees_all_equal_shapes(expd_shapes, *res_trees)
for i, res_t in enumerate(res_trees):
np.testing.assert_allclose(res_t['a0'], 0)
np.testing.assert_allclose(res_t['d']['a1'], i)
np.testing.assert_allclose(res_t['d']['a2'], 2)
np.testing.assert_allclose(res_t['t4'][0], 4)
np.testing.assert_allclose(res_t['t4'][1], i)
def test_tree_fn(self):
def add(x, y):
return x + y
tree_add = tree_util.tree_fn(add)
tree_x = [1, 2, 3]
tree_y = [1, 10, 100]
output = tree_add(tree_x, tree_y)
exp_output = [2, 12, 103]
# Test output.
np.testing.assert_allclose(output, exp_output)
def test_tree_fn_with_partials(self):
def add(x, y):
return x + y
tree_add = tree_util.tree_fn(add, y=1)
tree_x = [1, 2, 3]
output = tree_add(tree_x)
exp_output = [2, 3, 4]
# Test output.
np.testing.assert_allclose(output, exp_output)
def test_tree_replace_masked(self):
data = jnp.array([
[1, 2, 3, 4, 5, 6],
[-1, -2, -3, -4, -5, -6]
])
tree_data = {'a': data, 'b': data}
replacement = data * 10
tree_replacement = {'a': replacement, 'b': replacement}
mask = jnp.array([0, 1])
tree_output = tree_util.tree_replace_masked(
tree_data, tree_replacement, mask)
expected_output = jnp.array([
[1, 2, 3, 4, 5, 6],
[-10, -20, -30, -40, -50, -60],
])
expected_tree_output = {'a': expected_output, 'b': expected_output}
# Test output.
np.testing.assert_allclose(tree_output['a'], expected_tree_output['a'])
np.testing.assert_allclose(tree_output['b'], expected_tree_output['b'])
def test_transpose_last_axis_to_first(self):
tree = {'a': jnp.ones((1, 2, 3, 4)), 'b': {'c': jnp.ones((1, 2, 3, 4))}}
expected_tree = {
'a': jnp.ones((4, 1, 2, 3)),
'b': {
'c': jnp.ones((4, 1, 2, 3))
}
}
chex.assert_trees_all_equal_shapes(
tree_util.transpose_last_axis_to_first(tree['a']), expected_tree['a'])
chex.assert_trees_all_equal_shapes(
tree_util.transpose_last_axis_to_first(tree), expected_tree)
def test_transpose_first_axis_to_last(self):
tree = {'a': jnp.ones((1, 2, 3, 4)), 'b': {'c': jnp.ones((1, 2, 3, 4))}}
expected_tree = {
'a': jnp.ones((2, 3, 4, 1)),
'b': {
'c': jnp.ones((2, 3, 4, 1))
}
}
chex.assert_trees_all_equal_shapes(
tree_util.transpose_first_axis_to_last(tree['a']), expected_tree['a'])
chex.assert_trees_all_equal_shapes(
tree_util.transpose_first_axis_to_last(tree), expected_tree)
if __name__ == '__main__':
jax.config.update('jax_numpy_rank_promotion', 'raise')
absltest.main()
| rlax-master | rlax/_src/tree_util_test.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Configuration file for the Sphinx documentation builder."""
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# pylint: disable=g-bad-import-order
# pylint: disable=g-import-not-at-top
import inspect
import os
import sys
import typing
def _add_annotations_import(path):
"""Appends a future annotations import to the file at the given path."""
with open(path) as f:
contents = f.read()
if contents.startswith('from __future__ import annotations'):
# If we run sphinx multiple times then we will append the future import
# multiple times too.
return
assert contents.startswith('#'), (path, contents.split('\n')[0])
with open(path, 'w') as f:
# NOTE: This is subtle and not unit tested, we're prefixing the first line
# in each Python file with this future import. It is important to prefix
# not insert a newline such that source code locations are accurate (we link
# to GitHub). The assertion above ensures that the first line in the file is
# a comment so it is safe to prefix it.
f.write('from __future__ import annotations ')
f.write(contents)
def _recursive_add_annotations_import():
for path, _, files in os.walk('../rlax/'):
for file in files:
if file.endswith('.py'):
_add_annotations_import(os.path.abspath(os.path.join(path, file)))
if 'READTHEDOCS' in os.environ:
_recursive_add_annotations_import()
# TODO(b/254461517) Remove the annotation filtering when we drop Python 3.8
# support.
# We remove `None` type annotations as this breaks Sphinx under Python 3.7 and
# 3.8 with error `AssertionError: Invalid annotation [...] None is not a class.`
filter_nones = lambda x: dict((k, v) for k, v in x.items() if v is not None)
typing.get_type_hints = lambda obj, *unused: filter_nones(obj.__annotations__)
sys.path.insert(0, os.path.abspath('../'))
sys.path.append(os.path.abspath('ext'))
import rlax
import sphinxcontrib.katex as katex
# -- Project information -----------------------------------------------------
project = 'RLax'
copyright = '2021, DeepMind' # pylint: disable=redefined-builtin
author = 'RLax Contributors'
# -- General configuration ---------------------------------------------------
master_doc = 'index'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.inheritance_diagram',
'sphinx.ext.intersphinx',
'sphinx.ext.linkcode',
'sphinx.ext.napoleon',
'sphinxcontrib.bibtex',
'sphinxcontrib.katex',
'sphinx_autodoc_typehints',
'sphinx_book_theme',
'coverage_check',
'myst_nb', # This is used for the .ipynb notebooks
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for autodoc -----------------------------------------------------
autodoc_default_options = {
'member-order': 'bysource',
'special-members': True,
'exclude-members': '__repr__, __str__, __weakref__',
}
# -- Options for bibtex ------------------------------------------------------
bibtex_bibfiles = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_book_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# html_favicon = '_static/favicon.ico'
# -- Options for myst -------------------------------------------------------
jupyter_execute_notebooks = 'force'
execution_allow_errors = False
# -- Options for katex ------------------------------------------------------
# See: https://sphinxcontrib-katex.readthedocs.io/en/0.4.1/macros.html
latex_macros = r"""
\def \d #1{\operatorname{#1}}
"""
# Translate LaTeX macros to KaTeX and add to options for HTML builder
katex_macros = katex.latex_defs_to_katex_macros(latex_macros)
katex_options = 'macros: {' + katex_macros + '}'
# Add LaTeX macros for LATEX builder
latex_elements = {'preamble': latex_macros}
# -- Source code links -------------------------------------------------------
def linkcode_resolve(domain, info):
"""Resolve a GitHub URL corresponding to Python object."""
if domain != 'py':
return None
try:
mod = sys.modules[info['module']]
except ImportError:
return None
obj = mod
try:
for attr in info['fullname'].split('.'):
obj = getattr(obj, attr)
except AttributeError:
return None
else:
obj = inspect.unwrap(obj)
try:
filename = inspect.getsourcefile(obj)
except TypeError:
return None
try:
source, lineno = inspect.getsourcelines(obj)
except OSError:
return None
# TODO(slebedev): support tags after we release an initial version.
return 'https://github.com/deepmind/rlax/tree/master/rlax/%s#L%d#L%d' % (
os.path.relpath(filename, start=os.path.dirname(
rlax.__file__)), lineno, lineno + len(source) - 1)
# -- Intersphinx configuration -----------------------------------------------
intersphinx_mapping = {
'jax': ('https://jax.readthedocs.io/en/latest/', None),
}
source_suffix = ['.rst', '.md', '.ipynb']
| rlax-master | docs/conf.py |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Asserts all public symbols are covered in the docs."""
from typing import Any, Mapping
import rlax
from rlax._src import test_utils
from sphinx import application
from sphinx import builders
from sphinx import errors
def rlax_public_symbols():
names = set()
for module_name, module in test_utils.find_internal_python_modules(rlax):
for name in module.__all__:
names.add(module_name + "." + name)
return names
class RLaxCoverageCheck(builders.Builder):
"""Builder that checks all public symbols are included."""
name = "coverage_check"
def get_outdated_docs(self) -> str:
return "coverage_check"
def write(self, *ignored: Any) -> None:
pass
def finish(self) -> None:
documented_objects = frozenset(self.env.domaindata["py"]["objects"])
undocumented_objects = set(rlax_public_symbols()) - documented_objects
if undocumented_objects:
undocumented_objects = tuple(sorted(undocumented_objects))
raise errors.SphinxError(
"All public symbols must be included in our documentation, did you "
"forget to add an entry to `api.rst`?\n"
f"Undocumented symbols: {undocumented_objects}")
def setup(app: application.Sphinx) -> Mapping[str, Any]:
app.add_builder(RLaxCoverageCheck)
return dict(version=rlax.__version__, parallel_read_safe=True)
| rlax-master | docs/ext/coverage_check.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""An online Q-lambda agent trained to play BSuite's Catch env."""
import collections
from absl import app
from absl import flags
from bsuite.environments import catch
import dm_env
import haiku as hk
from haiku import nets
import jax
import jax.numpy as jnp
import numpy as np
import optax
import rlax
from rlax.examples import experiment
ActorOutput = collections.namedtuple("ActorOutput", ["actions", "q_values"])
FLAGS = flags.FLAGS
flags.DEFINE_integer("seed", 42, "Random seed.")
flags.DEFINE_integer("train_episodes", 500, "Number of train episodes.")
flags.DEFINE_integer("num_hidden_units", 50, "Number of network hidden units.")
flags.DEFINE_integer("sequence_length", 4,
"Length of (action, timestep) sequences.")
flags.DEFINE_float("epsilon", 0.01, "Epsilon-greedy exploration probability.")
flags.DEFINE_float("lambda_", 0.9, "Mixing parameter for Q(lambda).")
flags.DEFINE_float("discount_factor", 0.99, "Q-learning discount factor.")
flags.DEFINE_float("learning_rate", 0.005, "Optimizer learning rate.")
flags.DEFINE_integer("eval_episodes", 100, "Number of evaluation episodes.")
flags.DEFINE_integer("evaluate_every", 50,
"Number of episodes between evaluations.")
def build_network(num_hidden_units: int, num_actions: int) -> hk.Transformed:
"""Factory for a simple MLP network for approximating Q-values."""
def q(obs):
flatten = lambda x: jnp.reshape(x, (-1,))
network = hk.Sequential(
[flatten, nets.MLP([num_hidden_units, num_actions])])
return network(obs)
return hk.without_apply_rng(hk.transform(q))
class SequenceAccumulator:
"""Accumulator for gathering the latest timesteps into sequences.
Note sequences can overlap and cross episode boundaries.
"""
def __init__(self, length):
self._timesteps = collections.deque(maxlen=length)
def push(self, timestep, action):
# Replace `None`s with zeros as these will be put into NumPy arrays.
a_tm1 = 0 if action is None else action
timestep_t = timestep._replace(
step_type=int(timestep.step_type),
reward=0. if timestep.reward is None else timestep.reward,
discount=0. if timestep.discount is None else timestep.discount,
)
self._timesteps.append((a_tm1, timestep_t))
def sample(self, batch_size):
"""Returns current sequence of accumulated timesteps."""
if batch_size != 1:
raise ValueError("Require batch_size == 1.")
if len(self._timesteps) != self._timesteps.maxlen:
raise ValueError("Not enough timesteps for a full sequence.")
actions, timesteps = jax.tree_map(lambda *ts: np.stack(ts),
*self._timesteps)
return actions, timesteps
def is_ready(self, batch_size):
if batch_size != 1:
raise ValueError("Require batch_size == 1.")
return len(self._timesteps) == self._timesteps.maxlen
class OnlineQLambda:
"""An online Q-lambda agent."""
def __init__(self, observation_spec, action_spec, num_hidden_units, epsilon,
lambda_, learning_rate):
self._observation_spec = observation_spec
self._action_spec = action_spec
self._epsilon = epsilon
self._lambda = lambda_
# Neural net and optimiser.
self._network = build_network(num_hidden_units, action_spec.num_values)
self._optimizer = optax.adam(learning_rate)
# Jitting for speed.
self.actor_step = jax.jit(self.actor_step)
self.learner_step = jax.jit(self.learner_step)
def initial_params(self, key):
sample_input = self._observation_spec.generate_value()
return self._network.init(key, sample_input)
def initial_actor_state(self):
return ()
def initial_learner_state(self, params):
return self._optimizer.init(params)
def actor_step(self, params, env_output, actor_state, key, evaluation):
q = self._network.apply(params, env_output.observation)
train_a = rlax.epsilon_greedy(self._epsilon).sample(key, q)
eval_a = rlax.greedy().sample(key, q)
a = jax.lax.select(evaluation, eval_a, train_a)
return ActorOutput(actions=a, q_values=q), actor_state
def learner_step(self, params, data, learner_state, unused_key):
dloss_dtheta = jax.grad(self._loss)(params, *data)
updates, learner_state = self._optimizer.update(dloss_dtheta, learner_state)
params = optax.apply_updates(params, updates)
return params, learner_state
def _loss(self, params, actions, timesteps):
"""Calculates Q-lambda loss given parameters, actions and timesteps."""
network_apply_sequence = jax.vmap(self._network.apply, in_axes=(None, 0))
q = network_apply_sequence(params, timesteps.observation)
# Use a mask since the sequence could cross episode boundaries.
mask = jnp.not_equal(timesteps.step_type, int(dm_env.StepType.LAST))
a_tm1 = actions[1:]
r_t = timesteps.reward[1:]
# Discount ought to be zero on a LAST timestep, use the mask to ensure this.
discount_t = timesteps.discount[1:] * mask[1:]
q_tm1 = q[:-1]
q_t = q[1:]
mask_tm1 = mask[:-1]
# Mask out TD errors for the last state in an episode.
td_error_tm1 = mask_tm1 * rlax.q_lambda(
q_tm1, a_tm1, r_t, discount_t, q_t, lambda_=self._lambda)
return jnp.sum(rlax.l2_loss(td_error_tm1)) / jnp.sum(mask_tm1)
def main(unused_arg):
env = catch.Catch(seed=FLAGS.seed)
agent = OnlineQLambda(
observation_spec=env.observation_spec(),
action_spec=env.action_spec(),
num_hidden_units=FLAGS.num_hidden_units,
epsilon=FLAGS.epsilon,
lambda_=FLAGS.lambda_,
learning_rate=FLAGS.learning_rate)
accumulator = SequenceAccumulator(length=FLAGS.sequence_length)
experiment.run_loop(
agent=agent,
environment=env,
accumulator=accumulator,
seed=FLAGS.seed,
batch_size=1,
train_episodes=FLAGS.train_episodes,
evaluate_every=FLAGS.evaluate_every,
eval_episodes=FLAGS.eval_episodes,
)
if __name__ == "__main__":
app.run(main)
| rlax-master | examples/online_q_lambda.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""An online Q-learning agent with PopArt on Catch with large rewards.
Learns faster with PopArt than without.
"""
import collections
from absl import app
from absl import flags
from bsuite.environments import catch
from bsuite.utils import wrappers
import haiku as hk
from haiku import nets
import jax
import jax.numpy as jnp
import optax
import rlax
from rlax.examples import experiment
ActorOutput = collections.namedtuple("ActorOutput", "actions")
Transition = collections.namedtuple("Transition",
"obs_tm1 a_tm1 r_t discount_t obs_t")
FLAGS = flags.FLAGS
flags.DEFINE_integer("seed", 42, "Random seed.")
flags.DEFINE_float("reward_scale", 10000, "Reward scale on Catch.")
flags.DEFINE_integer("train_episodes", 1000, "Number of train episodes.")
flags.DEFINE_integer("num_hidden_units", 50, "Number of network hidden units.")
flags.DEFINE_float("epsilon", 0.01, "Epsilon-greedy exploration probability.")
flags.DEFINE_float("discount_factor", 0.99, "Q-learning discount factor.")
flags.DEFINE_float("learning_rate", 0.005, "Optimizer learning rate.")
flags.DEFINE_float("pop_art_step_size", 3e-3, "PopArt normalization step size.")
flags.DEFINE_integer("eval_episodes", 100, "Number of evaluation episodes.")
flags.DEFINE_integer("evaluate_every", 50,
"Number of episodes between evaluations.")
def build_network(num_hidden_units: int, num_actions: int) -> hk.Transformed:
"""Factory for a simple MLP network for approximating Q-values."""
def q(obs):
flatten = lambda x: jnp.reshape(x, (-1,))
network = hk.Sequential(
[flatten, nets.MLP([num_hidden_units, num_actions])])
return network(obs)
return hk.without_apply_rng(hk.transform(q))
class TransitionAccumulator:
"""Simple Python accumulator for transitions."""
def __init__(self):
self._prev = None
self._action = None
self._latest = None
def push(self, env_output, action):
self._prev = self._latest
self._action = action
self._latest = env_output
def sample(self, batch_size):
assert batch_size == 1
return Transition(self._prev.observation, self._action, self._latest.reward,
self._latest.discount, self._latest.observation)
def is_ready(self, batch_size):
assert batch_size == 1
return self._prev is not None
class PopArtAgent:
"""An online Q-learning deep RL agent with PopArt."""
def __init__(self, observation_spec, action_spec, num_hidden_units, epsilon,
learning_rate, pop_art_step_size):
self._observation_spec = observation_spec
self._action_spec = action_spec
self._epsilon = epsilon
# Neural net and optimiser.
self._network = build_network(num_hidden_units, action_spec.num_values)
self._optimizer = optax.adam(learning_rate)
# Jitting for speed.
self.actor_step = jax.jit(self.actor_step)
self.learner_step = jax.jit(self.learner_step)
self._initial_pop_art_state, self._pop_art_update = rlax.popart(
num_outputs=1, step_size=pop_art_step_size, scale_lb=1e-5, scale_ub=1e5)
def initial_params(self, key):
sample_input = self._observation_spec.generate_value()
return self._network.init(key, sample_input)
def initial_actor_state(self):
return ()
def initial_learner_state(self, params):
return self._optimizer.init(params), self._initial_pop_art_state()
def actor_step(self, params, env_output, actor_state, key, evaluation):
norm_q = self._network.apply(params, env_output.observation)
# This is equivalent to epsilon-greedy on the (unnormalized) Q-values
# because normalization is linear, therefore the argmaxes are the same.
train_a = rlax.epsilon_greedy(self._epsilon).sample(key, norm_q)
eval_a = rlax.greedy().sample(key, norm_q)
a = jax.lax.select(evaluation, eval_a, train_a)
return ActorOutput(actions=a), actor_state
def learner_step(self, params, data, learner_state, unused_key):
opt_state, pop_art_state = learner_state
dloss_dtheta, pop_art_state = jax.grad(
self._loss, has_aux=True)(params, pop_art_state, *data)
updates, opt_state = self._optimizer.update(dloss_dtheta, opt_state)
params = optax.apply_updates(params, updates)
return params, (opt_state, pop_art_state)
def _loss(self, params, pop_art_state, obs_tm1, a_tm1, r_t, discount_t,
obs_t):
"""Loss function."""
indices = jnp.array(0) # Only one output for normalization.
# Calculate targets by unnormalizing Q-values output by network.
norm_q_t = self._network.apply(params, obs_t)
q_t = rlax.unnormalize(pop_art_state, norm_q_t, indices)
target_tm1 = r_t + discount_t * jnp.max(q_t)
# Update PopArt statistics and use them to update the network parameters to
# POP (preserve outputs precisely). If there were target networks, the
# parameters for these would also need to be updated.
final_linear_module_name = "mlp/~/linear_1"
mutable_params = hk.data_structures.to_mutable_dict(params)
linear_params = mutable_params[final_linear_module_name]
popped_linear_params, new_pop_art_state = self._pop_art_update(
params=linear_params, state=pop_art_state, targets=target_tm1,
indices=indices)
mutable_params[final_linear_module_name] = popped_linear_params
popped_params = hk.data_structures.to_immutable_dict(mutable_params)
# Normalize target with updated PopArt statistics.
norm_target_tm1 = rlax.normalize(new_pop_art_state, target_tm1, indices)
# Calculate parameter update with normalized target and popped parameters.
norm_q_t = self._network.apply(popped_params, obs_t)
norm_q_tm1 = self._network.apply(popped_params, obs_tm1)
td_error = jax.lax.stop_gradient(norm_target_tm1) - norm_q_tm1[a_tm1]
return rlax.l2_loss(td_error), new_pop_art_state
def main(unused_arg):
env = catch.Catch(seed=FLAGS.seed)
env = wrappers.RewardScale(env, reward_scale=FLAGS.reward_scale)
agent = PopArtAgent(
observation_spec=env.observation_spec(),
action_spec=env.action_spec(),
num_hidden_units=FLAGS.num_hidden_units,
epsilon=FLAGS.epsilon,
learning_rate=FLAGS.learning_rate,
pop_art_step_size=FLAGS.pop_art_step_size,
)
accumulator = TransitionAccumulator()
experiment.run_loop(
agent=agent,
environment=env,
accumulator=accumulator,
seed=FLAGS.seed,
batch_size=1,
train_episodes=FLAGS.train_episodes,
evaluate_every=FLAGS.evaluate_every,
eval_episodes=FLAGS.eval_episodes,
)
if __name__ == "__main__":
app.run(main)
| rlax-master | examples/pop_art.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
| rlax-master | examples/__init__.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Experiment loop."""
import haiku as hk
import jax
def run_loop(
agent, environment, accumulator, seed,
batch_size, train_episodes, evaluate_every, eval_episodes):
"""A simple run loop for examples of reinforcement learning with rlax."""
# Init agent.
rng = hk.PRNGSequence(jax.random.PRNGKey(seed))
params = agent.initial_params(next(rng))
learner_state = agent.initial_learner_state(params)
print(f"Training agent for {train_episodes} episodes")
for episode in range(train_episodes):
# Prepare agent, environment and accumulator for a new episode.
timestep = environment.reset()
accumulator.push(timestep, None)
actor_state = agent.initial_actor_state()
while not timestep.last():
# Acting.
actor_output, actor_state = agent.actor_step(
params, timestep, actor_state, next(rng), evaluation=False)
# Agent-environment interaction.
action = int(actor_output.actions)
timestep = environment.step(action)
# Accumulate experience.
accumulator.push(timestep, action)
# Learning.
if accumulator.is_ready(batch_size):
params, learner_state = agent.learner_step(
params, accumulator.sample(batch_size), learner_state, next(rng))
# Evaluation.
if not episode % evaluate_every:
returns = 0.
for _ in range(eval_episodes):
timestep = environment.reset()
actor_state = agent.initial_actor_state()
while not timestep.last():
actor_output, actor_state = agent.actor_step(
params, timestep, actor_state, next(rng), evaluation=True)
timestep = environment.step(int(actor_output.actions))
returns += timestep.reward
avg_returns = returns / eval_episodes
print(f"Episode {episode:4d}: Average returns: {avg_returns:.2f}")
| rlax-master | examples/experiment.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A simple online Q-learning agent trained to play BSuite's Catch env."""
import collections
from absl import app
from absl import flags
from bsuite.environments import catch
import haiku as hk
from haiku import nets
import jax
import jax.numpy as jnp
import optax
import rlax
from rlax.examples import experiment
ActorOutput = collections.namedtuple("ActorOutput", "actions q_values")
Transition = collections.namedtuple("Transition",
"obs_tm1 a_tm1 r_t discount_t obs_t")
FLAGS = flags.FLAGS
flags.DEFINE_integer("seed", 42, "Random seed.")
flags.DEFINE_integer("train_episodes", 500, "Number of train episodes.")
flags.DEFINE_integer("num_hidden_units", 50, "Number of network hidden units.")
flags.DEFINE_float("epsilon", 0.01, "Epsilon-greedy exploration probability.")
flags.DEFINE_float("discount_factor", 0.99, "Q-learning discount factor.")
flags.DEFINE_float("learning_rate", 0.005, "Optimizer learning rate.")
flags.DEFINE_integer("eval_episodes", 100, "Number of evaluation episodes.")
flags.DEFINE_integer("evaluate_every", 50,
"Number of episodes between evaluations.")
def build_network(num_hidden_units: int, num_actions: int) -> hk.Transformed:
"""Factory for a simple MLP network for approximating Q-values."""
def q(obs):
flatten = lambda x: jnp.reshape(x, (-1,))
network = hk.Sequential(
[flatten, nets.MLP([num_hidden_units, num_actions])])
return network(obs)
return hk.without_apply_rng(hk.transform(q))
class TransitionAccumulator:
"""Simple Python accumulator for transitions."""
def __init__(self):
self._prev = None
self._action = None
self._latest = None
def push(self, env_output, action):
self._prev = self._latest
self._action = action
self._latest = env_output
def sample(self, batch_size):
assert batch_size == 1
return Transition(self._prev.observation, self._action, self._latest.reward,
self._latest.discount, self._latest.observation)
def is_ready(self, batch_size):
assert batch_size == 1
return self._prev is not None
class OnlineQ:
"""An online Q-learning deep RL agent."""
def __init__(self, observation_spec, action_spec, num_hidden_units, epsilon,
learning_rate):
self._observation_spec = observation_spec
self._action_spec = action_spec
self._epsilon = epsilon
# Neural net and optimiser.
self._network = build_network(num_hidden_units, action_spec.num_values)
self._optimizer = optax.adam(learning_rate)
# Jitting for speed.
self.actor_step = jax.jit(self.actor_step)
self.learner_step = jax.jit(self.learner_step)
def initial_params(self, key):
sample_input = self._observation_spec.generate_value()
return self._network.init(key, sample_input)
def initial_actor_state(self):
return ()
def initial_learner_state(self, params):
return self._optimizer.init(params)
def actor_step(self, params, env_output, actor_state, key, evaluation):
q = self._network.apply(params, env_output.observation)
train_a = rlax.epsilon_greedy(self._epsilon).sample(key, q)
eval_a = rlax.greedy().sample(key, q)
a = jax.lax.select(evaluation, eval_a, train_a)
return ActorOutput(actions=a, q_values=q), actor_state
def learner_step(self, params, data, learner_state, unused_key):
dloss_dtheta = jax.grad(self._loss)(params, *data)
updates, learner_state = self._optimizer.update(dloss_dtheta, learner_state)
params = optax.apply_updates(params, updates)
return params, learner_state
def _loss(self, params, obs_tm1, a_tm1, r_t, discount_t, obs_t):
q_tm1 = self._network.apply(params, obs_tm1)
q_t = self._network.apply(params, obs_t)
td_error = rlax.q_learning(q_tm1, a_tm1, r_t, discount_t, q_t)
return rlax.l2_loss(td_error)
def main(unused_arg):
env = catch.Catch(seed=FLAGS.seed)
agent = OnlineQ(
observation_spec=env.observation_spec(),
action_spec=env.action_spec(),
num_hidden_units=FLAGS.num_hidden_units,
epsilon=FLAGS.epsilon,
learning_rate=FLAGS.learning_rate,
)
accumulator = TransitionAccumulator()
experiment.run_loop(
agent=agent,
environment=env,
accumulator=accumulator,
seed=FLAGS.seed,
batch_size=1,
train_episodes=FLAGS.train_episodes,
evaluate_every=FLAGS.evaluate_every,
eval_episodes=FLAGS.eval_episodes,
)
if __name__ == "__main__":
app.run(main)
| rlax-master | examples/online_q_learning.py |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A simple double-DQN agent trained to play BSuite's Catch env."""
import collections
import random
from absl import app
from absl import flags
from bsuite.environments import catch
import haiku as hk
from haiku import nets
import jax
import jax.numpy as jnp
import numpy as np
import optax
import rlax
from rlax.examples import experiment
Params = collections.namedtuple("Params", "online target")
ActorState = collections.namedtuple("ActorState", "count")
ActorOutput = collections.namedtuple("ActorOutput", "actions q_values")
LearnerState = collections.namedtuple("LearnerState", "count opt_state")
Data = collections.namedtuple("Data", "obs_tm1 a_tm1 r_t discount_t obs_t")
FLAGS = flags.FLAGS
flags.DEFINE_integer("seed", 42, "Random seed.")
flags.DEFINE_integer("train_episodes", 301, "Number of train episodes.")
flags.DEFINE_integer("batch_size", 32, "Size of the training batch")
flags.DEFINE_float("target_period", 50, "How often to update the target net.")
flags.DEFINE_integer("replay_capacity", 2000, "Capacity of the replay buffer.")
flags.DEFINE_integer("hidden_units", 50, "Number of network hidden units.")
flags.DEFINE_float("epsilon_begin", 1., "Initial epsilon-greedy exploration.")
flags.DEFINE_float("epsilon_end", 0.01, "Final epsilon-greedy exploration.")
flags.DEFINE_integer("epsilon_steps", 1000, "Steps over which to anneal eps.")
flags.DEFINE_float("discount_factor", 0.99, "Q-learning discount factor.")
flags.DEFINE_float("learning_rate", 0.005, "Optimizer learning rate.")
flags.DEFINE_integer("eval_episodes", 100, "Number of evaluation episodes.")
flags.DEFINE_integer("evaluate_every", 50,
"Number of episodes between evaluations.")
def build_network(num_actions: int) -> hk.Transformed:
"""Factory for a simple MLP network for approximating Q-values."""
def q(obs):
network = hk.Sequential(
[hk.Flatten(),
nets.MLP([FLAGS.hidden_units, num_actions])])
return network(obs)
return hk.without_apply_rng(hk.transform(q))
class ReplayBuffer(object):
"""A simple Python replay buffer."""
def __init__(self, capacity):
self._prev = None
self._action = None
self._latest = None
self.buffer = collections.deque(maxlen=capacity)
def push(self, env_output, action):
self._prev = self._latest
self._action = action
self._latest = env_output
if action is not None:
self.buffer.append(
(self._prev.observation, self._action, self._latest.reward,
self._latest.discount, self._latest.observation))
def sample(self, batch_size):
obs_tm1, a_tm1, r_t, discount_t, obs_t = zip(
*random.sample(self.buffer, batch_size))
return (np.stack(obs_tm1), np.asarray(a_tm1), np.asarray(r_t),
np.asarray(discount_t) * FLAGS.discount_factor, np.stack(obs_t))
def is_ready(self, batch_size):
return batch_size <= len(self.buffer)
class DQN:
"""A simple DQN agent."""
def __init__(self, observation_spec, action_spec, epsilon_cfg, target_period,
learning_rate):
self._observation_spec = observation_spec
self._action_spec = action_spec
self._target_period = target_period
# Neural net and optimiser.
self._network = build_network(action_spec.num_values)
self._optimizer = optax.adam(learning_rate)
self._epsilon_by_frame = optax.polynomial_schedule(**epsilon_cfg)
# Jitting for speed.
self.actor_step = jax.jit(self.actor_step)
self.learner_step = jax.jit(self.learner_step)
def initial_params(self, key):
sample_input = self._observation_spec.generate_value()
sample_input = jnp.expand_dims(sample_input, 0)
online_params = self._network.init(key, sample_input)
return Params(online_params, online_params)
def initial_actor_state(self):
actor_count = jnp.zeros((), dtype=jnp.float32)
return ActorState(actor_count)
def initial_learner_state(self, params):
learner_count = jnp.zeros((), dtype=jnp.float32)
opt_state = self._optimizer.init(params.online)
return LearnerState(learner_count, opt_state)
def actor_step(self, params, env_output, actor_state, key, evaluation):
obs = jnp.expand_dims(env_output.observation, 0) # add dummy batch
q = self._network.apply(params.online, obs)[0] # remove dummy batch
epsilon = self._epsilon_by_frame(actor_state.count)
train_a = rlax.epsilon_greedy(epsilon).sample(key, q)
eval_a = rlax.greedy().sample(key, q)
a = jax.lax.select(evaluation, eval_a, train_a)
return ActorOutput(actions=a, q_values=q), ActorState(actor_state.count + 1)
def learner_step(self, params, data, learner_state, unused_key):
target_params = optax.periodic_update(params.online, params.target,
learner_state.count,
self._target_period)
dloss_dtheta = jax.grad(self._loss)(params.online, target_params, *data)
updates, opt_state = self._optimizer.update(dloss_dtheta,
learner_state.opt_state)
online_params = optax.apply_updates(params.online, updates)
return (Params(online_params, target_params),
LearnerState(learner_state.count + 1, opt_state))
def _loss(self, online_params, target_params, obs_tm1, a_tm1, r_t, discount_t,
obs_t):
q_tm1 = self._network.apply(online_params, obs_tm1)
q_t_val = self._network.apply(target_params, obs_t)
q_t_select = self._network.apply(online_params, obs_t)
batched_loss = jax.vmap(rlax.double_q_learning)
td_error = batched_loss(q_tm1, a_tm1, r_t, discount_t, q_t_val, q_t_select)
return jnp.mean(rlax.l2_loss(td_error))
def main(unused_arg):
env = catch.Catch(seed=FLAGS.seed)
epsilon_cfg = dict(
init_value=FLAGS.epsilon_begin,
end_value=FLAGS.epsilon_end,
transition_steps=FLAGS.epsilon_steps,
power=1.)
agent = DQN(
observation_spec=env.observation_spec(),
action_spec=env.action_spec(),
epsilon_cfg=epsilon_cfg,
target_period=FLAGS.target_period,
learning_rate=FLAGS.learning_rate,
)
accumulator = ReplayBuffer(FLAGS.replay_capacity)
experiment.run_loop(
agent=agent,
environment=env,
accumulator=accumulator,
seed=FLAGS.seed,
batch_size=FLAGS.batch_size,
train_episodes=FLAGS.train_episodes,
evaluate_every=FLAGS.evaluate_every,
eval_episodes=FLAGS.eval_episodes,
)
if __name__ == "__main__":
app.run(main)
| rlax-master | examples/simple_dqn.py |
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Simple package definition for using with `pip`."""
import os
import pkg_resources
import setuptools
from setuptools import find_packages
from setuptools import setup
from setuptools.command.build_ext import build_ext
from setuptools.command.build_py import build_py
_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# Tuple of proto message definitions to build Python bindings for. Paths must
# be relative to root directory.
_ANDROID_ENV_PROTOS = (
'android_env/proto/adb.proto',
'android_env/proto/emulator_controller.proto',
'android_env/proto/snapshot.proto',
'android_env/proto/snapshot_service.proto',
'android_env/proto/state.proto',
'android_env/proto/task.proto',
)
testing_requirements = [
'attrs==20.3.0', # temporary pin to fix pytype issue.
'pillow',
'pytype',
'pytest-xdist',
'gym',
]
class _GenerateProtoFiles(setuptools.Command):
"""Command to generate protobuf bindings for AndroidEnv protos."""
descriptions = 'Generates Python protobuf bindings for AndroidEnv protos.'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
# Import grpc_tools here, after setuptools has installed setup_requires
# dependencies.
from grpc_tools import protoc # pylint: disable=g-import-not-at-top
grpc_protos_include = pkg_resources.resource_filename(
'grpc_tools', '_proto')
for proto_path in _ANDROID_ENV_PROTOS:
proto_args = [
'grpc_tools.protoc',
'--proto_path={}'.format(grpc_protos_include),
'--proto_path={}'.format(_ROOT_DIR),
'--python_out={}'.format(_ROOT_DIR),
'--grpc_python_out={}'.format(_ROOT_DIR),
os.path.join(_ROOT_DIR, proto_path),
]
if protoc.main(proto_args) != 0:
raise RuntimeError('ERROR: {}'.format(proto_args))
class _BuildExt(build_ext):
"""Generate protobuf bindings in build_ext stage."""
def run(self):
self.run_command('generate_protos')
build_ext.run(self)
class _BuildPy(build_py):
"""Generate protobuf bindings in build_py stage."""
def run(self):
self.run_command('generate_protos')
build_py.run(self)
setup(
packages=find_packages(exclude=['examples']),
package_data={'': ['proto/*.proto']}, # Copy protobuf files.
include_package_data=True,
setup_requires=['grpcio-tools'],
cmdclass={
'build_ext': _BuildExt,
'build_py': _BuildPy,
'generate_protos': _GenerateProtoFiles,
},
)
| android_env-main | setup.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| android_env-main | android_env/__init__.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Function for loading AndroidEnv."""
import os
from android_env import environment
from android_env.components import coordinator as coordinator_lib
from android_env.components import task_manager as task_manager_lib
from android_env.components.simulators.emulator import emulator_simulator
from android_env.proto import task_pb2
from google.protobuf import text_format
def load(task_path: str,
avd_name: str,
android_avd_home: str = '~/.android/avd',
android_sdk_root: str = '~/Android/Sdk',
emulator_path: str = '~/Android/Sdk/emulator/emulator',
adb_path: str = '~/Android/Sdk/platform-tools/adb',
run_headless: bool = False) -> environment.AndroidEnv:
"""Loads an AndroidEnv instance.
Args:
task_path: Path to the task textproto file.
avd_name: Name of the AVD (Android Virtual Device).
android_avd_home: Path to the AVD (Android Virtual Device).
android_sdk_root: Root directory of the SDK.
emulator_path: Path to the emulator binary.
adb_path: Path to the ADB (Android Debug Bridge).
run_headless: If True, the emulator display is turned off.
Returns:
env: An AndroidEnv instance.
"""
# Create simulator.
simulator = emulator_simulator.EmulatorSimulator(
adb_controller_args=dict(
adb_path=os.path.expanduser(adb_path),
adb_server_port=5037,
),
emulator_launcher_args=dict(
avd_name=avd_name,
android_avd_home=os.path.expanduser(android_avd_home),
android_sdk_root=os.path.expanduser(android_sdk_root),
emulator_path=os.path.expanduser(emulator_path),
run_headless=run_headless,
gpu_mode='swiftshader_indirect',
),
)
# Prepare task.
task = task_pb2.Task()
with open(task_path, 'r') as proto_file:
text_format.Parse(proto_file.read(), task)
task_manager = task_manager_lib.TaskManager(task)
coordinator = coordinator_lib.Coordinator(simulator, task_manager)
# Load environment.
return environment.AndroidEnv(coordinator=coordinator)
| android_env-main | android_env/loader.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Android environment implementation."""
from typing import Any
from absl import logging
from android_env import env_interface
from android_env.components import coordinator as coordinator_lib
from android_env.proto import adb_pb2
from android_env.proto import state_pb2
from android_env.proto import task_pb2
import dm_env
import numpy as np
class AndroidEnv(env_interface.AndroidEnvInterface):
"""An RL environment that interacts with Android apps."""
def __init__(self, coordinator: coordinator_lib.Coordinator):
"""Initializes the state of this AndroidEnv object."""
self._coordinator = coordinator
self._latest_action = {}
self._latest_observation = {}
self._latest_extras = {}
self._reset_next_step = True
self._is_closed = False
logging.info('Action spec: %s', self.action_spec())
logging.info('Observation spec: %s', self.observation_spec())
def __del__(self) -> None:
self.close()
# Methods required by dm_env.Environment.
def action_spec(self) -> dict[str, dm_env.specs.Array]:
return self._coordinator.action_spec()
def observation_spec(self) -> dict[str, dm_env.specs.Array]:
return self._coordinator.observation_spec()
def reset(self) -> dm_env.TimeStep:
"""Resets the environment for a new RL episode."""
logging.info('Resetting AndroidEnv...')
# Execute a reset. Timestep will be of type FIRST.
timestep = self._coordinator.rl_reset()
# Process relevant information.
if timestep.observation is not None:
self._latest_extras = timestep.observation.pop('extras')
self._latest_observation = timestep.observation.copy()
else:
# If the observation is None, we return the latest observation again.
timestep = timestep._replace(observation=self._latest_observation.copy())
self._latest_action = {}
self._reset_next_step = False
logging.info('Done resetting AndroidEnv.')
logging.info('************* NEW EPISODE *************')
return timestep
def step(self, action: dict[str, np.ndarray]) -> dm_env.TimeStep:
"""Takes a step in the environment."""
# Check if it's time to reset the episode.
if self._reset_next_step:
return self.reset()
# Execute selected action.
timestep = self._coordinator.rl_step(action)
# Process relevant information.
if timestep.observation is not None:
self._latest_extras = timestep.observation.pop('extras')
self._latest_observation = timestep.observation.copy()
else:
# If the observation is None, we return the latest observation again.
timestep = timestep._replace(observation=self._latest_observation.copy())
self._latest_action = action.copy()
if timestep.last():
self._reset_next_step = True
logging.info('************* END OF EPISODE *************')
return timestep
def close(self) -> None:
"""Cleans up running processes, threads and local files."""
if not self._is_closed:
logging.info('Cleaning up AndroidEnv...')
if hasattr(self, '_coordinator'):
self._coordinator.close()
logging.info('Done cleaning up AndroidEnv.')
self._is_closed = True
# Extensions provided by AndroidEnv.
def task_extras(self, latest_only: bool = True) -> dict[str, np.ndarray]:
"""Returns latest task extras."""
task_extras = {} # Build a copy to avoid reusing objects.
for k, spec in self._latest_extras.items():
extra_values = spec.astype(spec.dtype)
task_extras[k] = extra_values[-1] if latest_only else extra_values
return task_extras
@property
def raw_action(self):
return self._latest_action.copy()
@property
def raw_observation(self):
return self._latest_observation.copy()
def stats(self) -> dict[str, Any]:
return self._coordinator.stats()
def execute_adb_call(self, call: adb_pb2.AdbRequest) -> adb_pb2.AdbResponse:
return self._coordinator.execute_adb_call(call)
def load_state(
self, request: state_pb2.LoadStateRequest
) -> state_pb2.LoadStateResponse:
"""Loads a state.
Args:
request: A `LoadStateRequest` containing any parameters necessary to
specify how/what state to load.
Returns:
A `LoadStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
return self._coordinator.load_state(request)
def save_state(
self, request: state_pb2.SaveStateRequest
) -> state_pb2.SaveStateResponse:
"""Saves a state.
Args:
request: A `SaveStateRequest` containing any parameters necessary to
specify how/what state to save.
Returns:
A `SaveStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
return self._coordinator.save_state(request)
| android_env-main | android_env/environment.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for AndroidEnv."""
from unittest import mock
from absl.testing import absltest
from android_env import environment
from android_env.components import coordinator as coordinator_lib
from android_env.proto import adb_pb2
from android_env.proto import state_pb2
from android_env.proto import task_pb2
import dm_env
import numpy as np
def _create_mock_coordinator() -> coordinator_lib.Coordinator:
coordinator = mock.create_autospec(coordinator_lib.Coordinator)
coordinator.action_spec.return_value = {
'action_type':
dm_env.specs.DiscreteArray(num_values=3),
'touch_position':
dm_env.specs.BoundedArray(
shape=(2,), dtype=np.float32, minimum=0.0, maximum=1.0),
}
coordinator.observation_spec.return_value = {
'pixels': dm_env.specs.Array(shape=(123, 456, 3), dtype=np.uint8),
'timedelta': dm_env.specs.Array(shape=(), dtype=np.int64),
'orientation': dm_env.specs.Array(shape=(4,), dtype=np.uint8),
}
return coordinator
class AndroidEnvTest(absltest.TestCase):
def test_specs(self):
env = environment.AndroidEnv(_create_mock_coordinator())
# Check action spec.
self.assertNotEmpty(env.action_spec())
self.assertIn('action_type', env.action_spec())
self.assertIsInstance(env.action_spec()['action_type'],
dm_env.specs.DiscreteArray)
self.assertIn('touch_position', env.action_spec())
self.assertIsInstance(env.action_spec()['touch_position'],
dm_env.specs.BoundedArray)
# Check observation spec.
self.assertNotEmpty(env.observation_spec())
self.assertIn('pixels', env.observation_spec())
self.assertIsInstance(env.observation_spec()['pixels'], dm_env.specs.Array)
# The `pixels` entry in the observation spec should match the screen size of
# the simulator with three color channels (RGB).
self.assertEqual(env.observation_spec()['pixels'].shape, (123, 456, 3))
self.assertIn('timedelta', env.observation_spec())
self.assertIsInstance(env.observation_spec()['timedelta'],
dm_env.specs.Array)
# The `timedelta` should be a scalar.
self.assertEqual(env.observation_spec()['timedelta'].shape, ())
self.assertIn('orientation', env.observation_spec())
# The `orientation` should be a one-hot vector with four dimensions.
self.assertIsInstance(env.observation_spec()['orientation'],
dm_env.specs.Array)
self.assertEqual(env.observation_spec()['orientation'].shape, (4,))
def test_reset_and_step(self):
coordinator = mock.create_autospec(coordinator_lib.Coordinator)
coordinator.action_spec.return_value = {
'action_type':
dm_env.specs.DiscreteArray(num_values=3),
'touch_position':
dm_env.specs.BoundedArray(
shape=(2,), dtype=np.float32, minimum=0.0, maximum=1.0),
}
coordinator.observation_spec.return_value = {
'pixels': dm_env.specs.Array(shape=(123, 456, 3), dtype=np.uint8),
'timedelta': dm_env.specs.Array(shape=(), dtype=np.int64),
'orientation': dm_env.specs.Array(shape=(4,), dtype=np.uint8),
}
env = environment.AndroidEnv(coordinator)
coordinator.rl_reset.return_value = dm_env.TimeStep(
step_type=dm_env.StepType.FIRST,
reward=0.0,
discount=0.0,
observation={
'pixels': np.random.rand(987, 654, 3),
'timedelta': 123456,
'orientation': np.array((1, 0, 0, 0)),
'extras': {
'click': np.array([[246]], dtype=np.int64)
}
},
)
ts = env.reset()
self.assertIsInstance(ts, dm_env.TimeStep)
# After a `reset()` the TimeStep should follow some expectations.
self.assertTrue(ts.first())
self.assertEqual(ts.reward, 0.0)
self.assertEqual(ts.discount, 0.0)
obs = ts.observation
self.assertIn('pixels', obs)
self.assertEqual(obs['pixels'].shape, (987, 654, 3))
self.assertIn('timedelta', obs)
self.assertEqual(obs['timedelta'], 123456)
self.assertIn('orientation', obs)
self.assertEqual(obs['orientation'].shape, (4,))
np.testing.assert_equal(obs['orientation'], (1, 0, 0, 0))
# Extras should also be provided.
extras = env.task_extras()
self.assertIn('click', extras)
self.assertEqual(extras['click'], np.array([246], dtype=np.int64))
coordinator.stats.return_value = {
'my_measurement': 135,
}
# Step again in the environment and check expectations again.
pixels = np.random.rand(987, 654, 3)
latest_observation = {
'pixels': pixels,
'timedelta': 123456,
'orientation': np.array((1, 0, 0, 0)),
'extras': {
'click': np.array([[246]], dtype=np.int64)
}
}
coordinator.rl_step.return_value = dm_env.transition(
reward=0.0,
discount=0.0,
observation=latest_observation,
)
ts = env.step({'action_type': 1, 'touch_position': (10, 20)})
self.assertIsInstance(ts, dm_env.TimeStep)
# The StepType now should NOT be FIRST.
self.assertFalse(ts.first())
self.assertEqual(ts.reward, 0.0)
self.assertEqual(ts.discount, 0.0)
obs = ts.observation
self.assertIn('pixels', obs)
self.assertEqual(obs['pixels'].shape, (987, 654, 3))
self.assertIn('timedelta', obs)
self.assertEqual(obs['timedelta'], 123456)
self.assertIn('orientation', obs)
self.assertEqual(obs['orientation'].shape, (4,))
np.testing.assert_equal(obs['orientation'], (1, 0, 0, 0))
# Extras should still be provided.
extras = env.task_extras()
self.assertIn('click', extras)
self.assertEqual(extras['click'], np.array([246], dtype=np.int64))
# At this point these methods and properties should return something.
self.assertNotEmpty(env.stats())
self.assertNotEmpty(env.raw_observation)
self.assertNotIn('extras', env.raw_observation)
self.assertNotEmpty(env.raw_action)
# If the observation is None, we want to return the latest observation.
coordinator.rl_step.return_value = dm_env.truncation(
reward=0.0,
observation=None,
)
ts = env.step({'action_type': 1, 'touch_position': (10, 20)})
self.assertIsInstance(ts, dm_env.TimeStep)
# Assert the observation matches the latest observation.
obs = ts.observation
self.assertIn('pixels', obs)
self.assertEqual(obs['pixels'].shape, (987, 654, 3))
np.testing.assert_equal(obs['pixels'], pixels)
self.assertIn('timedelta', obs)
self.assertEqual(obs['timedelta'], 123456)
self.assertIn('orientation', obs)
self.assertEqual(obs['orientation'].shape, (4,))
np.testing.assert_equal(obs['orientation'], (1, 0, 0, 0))
def test_adb_call(self):
coordinator = _create_mock_coordinator()
env = environment.AndroidEnv(coordinator)
call = adb_pb2.AdbRequest(
force_stop=adb_pb2.AdbRequest.ForceStop(package_name='blah'))
expected_response = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK)
coordinator.execute_adb_call.return_value = expected_response
response = env.execute_adb_call(call)
self.assertEqual(response, expected_response)
coordinator.execute_adb_call.assert_called_once_with(call)
def test_load_state(self):
coordinator = _create_mock_coordinator()
env = environment.AndroidEnv(coordinator)
expected_response = state_pb2.LoadStateResponse(
status=state_pb2.LoadStateResponse.Status.OK
)
request = state_pb2.LoadStateRequest(args={'foo': 'bar'})
coordinator.load_state.return_value = expected_response
response = env.load_state(request)
self.assertEqual(response, expected_response)
coordinator.load_state.assert_called_once_with(request)
def test_save_state(self):
coordinator = _create_mock_coordinator()
env = environment.AndroidEnv(coordinator)
expected_response = state_pb2.SaveStateResponse(
status=state_pb2.SaveStateResponse.Status.OK
)
request = state_pb2.SaveStateRequest(args={'foo': 'bar'})
coordinator.save_state.return_value = expected_response
response = env.save_state(request)
self.assertEqual(response, expected_response)
coordinator.save_state.assert_called_once_with(request)
def test_double_close(self):
coordinator = _create_mock_coordinator()
env = environment.AndroidEnv(coordinator)
env.close()
env.close()
coordinator.close.assert_called_once()
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/environment_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Abstract AndroidEnv interface.
AndroidEnv is a standard dm_env.Environment instance, but it also offers a few
extra methods that clients may use for extended functionality.
"""
import abc
from typing import Any
from android_env.proto import adb_pb2
from android_env.proto import state_pb2
import dm_env
import numpy as np
class AndroidEnvInterface(dm_env.Environment, metaclass=abc.ABCMeta):
"""Pure virtual interface for AndroidEnv implementations."""
# Methods required by dm_env.Environment.
@abc.abstractmethod
def action_spec(self) -> dict[str, dm_env.specs.Array]:
"""Returns the action specification."""
@abc.abstractmethod
def observation_spec(self) -> dict[str, dm_env.specs.Array]:
"""Returns the observation specification."""
@abc.abstractmethod
def reset(self) -> dm_env.TimeStep:
"""Resets the current episode."""
@abc.abstractmethod
def step(self, action: dict[str, np.ndarray]) -> dm_env.TimeStep:
"""Executes `action` and returns a `TimeStep`."""
@abc.abstractmethod
def close(self) -> None:
"""Frees up resources."""
# Extensions provided by AndroidEnv.
def task_extras(self, latest_only: bool = True) -> dict[str, np.ndarray]:
"""Returns extra info provided by tasks."""
return {}
@property
def raw_action(self):
"""Returns the latest action."""
@property
def raw_observation(self):
"""Returns the latest observation."""
def stats(self) -> dict[str, Any]:
"""Returns information generated inside the implementation."""
return {}
def execute_adb_call(self, call: adb_pb2.AdbRequest) -> adb_pb2.AdbResponse:
"""Executes `call` and returns its response."""
return adb_pb2.AdbResponse()
def load_state(
self, request: state_pb2.LoadStateRequest
) -> state_pb2.LoadStateResponse:
"""Loads a state.
Args:
request: A `LoadStateRequest` containing any parameters necessary to
specify how/what state to load.
Returns:
A `LoadStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
raise NotImplementedError('This environment does not support loading state')
def save_state(
self, request: state_pb2.SaveStateRequest
) -> state_pb2.SaveStateResponse:
"""Saves a state.
Args:
request: A `SaveStateRequest` containing any parameters necessary to
specify how/what state to save.
Returns:
A `SaveStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
raise NotImplementedError('This environment does not support saving state')
| android_env-main | android_env/env_interface.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for loader."""
import builtins
import os
from unittest import mock
from absl.testing import absltest
from android_env import environment
from android_env import loader
from android_env.components import coordinator as coordinator_lib
from android_env.components import task_manager as task_manager_lib
from android_env.components.simulators.emulator import emulator_simulator
from android_env.proto import task_pb2
class LoaderTest(absltest.TestCase):
@mock.patch.object(task_manager_lib, 'TaskManager', autospec=True)
@mock.patch.object(emulator_simulator, 'EmulatorSimulator', autospec=True)
@mock.patch.object(coordinator_lib, 'Coordinator', autospec=True)
@mock.patch.object(builtins, 'open', autospec=True)
def test_load(self, mock_open, coordinator, simulator, task_manager):
mock_open.return_value.__enter__ = mock_open
mock_open.return_value.read.return_value = ''
env = loader.load(
task_path='some/path/',
avd_name='my_avd',
android_avd_home='~/.android/avd',
android_sdk_root='~/Android/Sdk',
emulator_path='~/Android/Sdk/emulator/emulator',
adb_path='~/Android/Sdk/platform-tools/adb',
run_headless=False,
)
self.assertIsInstance(env, environment.AndroidEnv)
simulator.assert_called_with(
adb_controller_args=dict(
adb_path=os.path.expanduser('~/Android/Sdk/platform-tools/adb'),
adb_server_port=5037,
),
emulator_launcher_args=dict(
avd_name='my_avd',
android_avd_home=os.path.expanduser('~/.android/avd'),
android_sdk_root=os.path.expanduser('~/Android/Sdk'),
emulator_path=os.path.expanduser('~/Android/Sdk/emulator/emulator'),
run_headless=False,
gpu_mode='swiftshader_indirect'),
)
coordinator.assert_called_with(
simulator.return_value,
task_manager.return_value,
)
@mock.patch.object(task_manager_lib, 'TaskManager', autospec=True)
@mock.patch.object(emulator_simulator, 'EmulatorSimulator', autospec=True)
@mock.patch.object(coordinator_lib, 'Coordinator', autospec=True)
@mock.patch.object(builtins, 'open', autospec=True)
def test_task(self, mock_open, coordinator, simulator, task_manager):
del coordinator, simulator
mock_open.return_value.__enter__ = mock_open
mock_open.return_value.read.return_value = r'''
id: "fake_task"
name: "Fake Task"
description: "Task for testing loader."
max_episode_sec: 0
'''
env = loader.load(
task_path='some/path/',
avd_name='my_avd',
)
expected_task = task_pb2.Task()
expected_task.id = 'fake_task'
expected_task.name = 'Fake Task'
expected_task.description = 'Task for testing loader.'
expected_task.max_episode_sec = 0
task_manager.assert_called_with(expected_task)
assert isinstance(env, environment.AndroidEnv)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/loader_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wraps the AndroidEnv environment to make its interface flat."""
from typing import Any
from android_env.wrappers import base_wrapper
import dm_env
from dm_env import specs
import numpy as np
RGB_CHANNELS = (0, 1, 2)
def _extract_screen_pixels(obs: np.ndarray):
"""Get only screen pixels by removing previous action layer."""
is_grayscale_image = obs.shape[-1] == 2
if is_grayscale_image:
return np.expand_dims(obs[..., 0], -1)
return obs[..., RGB_CHANNELS]
def _get_no_action_observation_spec(obs_spec: specs.BoundedArray):
"""Create an observation spec without the action layer."""
shape = np.array(obs_spec.shape)
shape[2] -= 1
minimum = obs_spec.minimum
maximum = obs_spec.maximum
is_scalar = lambda x: np.isscalar(x) or np.ndim(x) == 0
if not is_scalar(minimum):
minimum = _extract_screen_pixels(minimum)
if not is_scalar(maximum):
maximum = _extract_screen_pixels(maximum)
return obs_spec.replace(shape=shape, minimum=minimum, maximum=maximum)
class FlatInterfaceWrapper(base_wrapper.BaseWrapper):
"""Simple interface for AndroidEnv.
Removes the structure from observations and actions, keeping only the pixel
observations. Also exposes action as an int32 scalar, making it easier to use
with conventional discrete agents. This wrapper expects a discretized action
space.
"""
def __init__(self,
env: dm_env.Environment,
flat_actions: bool = True,
flat_observations: bool = True,
keep_action_layer: bool = True):
super().__init__(env)
self._flat_actions = flat_actions
self._flat_observations = flat_observations
self._keep_action_layer = keep_action_layer
self._action_name = list(self._env.action_spec())[0]
self._assert_base_env()
def _assert_base_env(self):
base_action_spec = self._env.action_spec()
assert len(base_action_spec) == 1, self._env.action_spec()
assert isinstance(base_action_spec, dict)
assert isinstance(base_action_spec[self._action_name], specs.BoundedArray)
def _process_action(self, action: int | np.ndarray | dict[str, Any]):
if self._flat_actions:
return {self._action_name: action}
else:
return action
def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep:
if self._flat_observations:
step_type, reward, discount, observation = timestep
# Keep only the pixels.
pixels = observation['pixels']
pixels = pixels if self._keep_action_layer else _extract_screen_pixels(
pixels)
return dm_env.TimeStep(
step_type=step_type,
reward=reward,
discount=discount,
observation=pixels)
else:
return timestep
def reset(self) -> dm_env.TimeStep:
timestep = self._env.reset()
return self._process_timestep(timestep)
def step(self, action: int) -> dm_env.TimeStep:
timestep = self._env.step(self._process_action(action))
return self._process_timestep(timestep)
def observation_spec(self) -> specs.Array | dict[str, specs.Array]: # pytype: disable=signature-mismatch # overriding-return-type-checks
if self._flat_observations:
pixels_spec = self._env.observation_spec()['pixels']
if not self._keep_action_layer:
return _get_no_action_observation_spec(pixels_spec)
return pixels_spec
else:
return self._env.observation_spec()
def action_spec(self) -> specs.BoundedArray | dict[str, specs.Array]: # pytype: disable=signature-mismatch # overriding-return-type-checks
if self._flat_actions:
return self._env.action_spec()[self._action_name]
else:
return self._env.action_spec()
| android_env-main | android_env/wrappers/flat_interface_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.wrappers.float_pixels_wrapper."""
from unittest import mock
from absl.testing import absltest
from android_env.wrappers import float_pixels_wrapper
import dm_env
from dm_env import specs
import numpy as np
def _make_array_spec(shape, dtype=np.float32, name=None):
return specs.Array(
shape=shape,
dtype=dtype,
name=name,
)
def _make_bounded_array_spec(
shape, dtype=np.float32, name=None, maximum=1.0, minimum=0.0):
return specs.BoundedArray(
shape=shape,
dtype=dtype,
name=name,
maximum=maximum,
minimum=minimum,
)
def _simple_timestep(obs_shape, obs_type):
return dm_env.TimeStep(
step_type=dm_env.StepType.MID,
reward=3.14,
discount=0.9,
observation=(np.ones(shape=obs_shape, dtype=obs_type),),
)
class FloatPixelsWrapperTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.pixels_shape = (3, 4)
base_pixel_spec = _make_array_spec(
shape=self.pixels_shape, dtype=np.uint8, name='pixels')
self.other_obs_spec = _make_array_spec(
shape=(1,), dtype=np.float32, name='other_obs')
base_observation_spec = {
'pixels': base_pixel_spec,
'other_obs': self.other_obs_spec
}
self.base_env = mock.create_autospec(dm_env.Environment)
self.base_env.observation_spec.return_value = base_observation_spec
self.base_timestep = dm_env.TimeStep(
step_type=dm_env.StepType.MID,
reward=3.14,
discount=0.9,
observation={
'pixels': np.ones(shape=self.pixels_shape, dtype=np.uint8),
'other_obs': [42.2]})
self.base_env.step.return_value = self.base_timestep
self.base_env.reset.return_value = self.base_timestep
def test_float_pixels_wrapper_spec(self):
expected_pixel_spec = _make_bounded_array_spec(
shape=self.pixels_shape,
dtype=np.float32,
name='pixels',
minimum=0.0,
maximum=1.0)
wrapped_env = float_pixels_wrapper.FloatPixelsWrapper(self.base_env)
self.assertLen(wrapped_env.observation_spec(), 2)
self.assertEqual(expected_pixel_spec,
wrapped_env.observation_spec()['pixels'])
self.assertEqual(self.other_obs_spec,
wrapped_env.observation_spec()['other_obs'])
def test_float_pixels_wrapper_step(self):
wrapped_env = float_pixels_wrapper.FloatPixelsWrapper(self.base_env)
ts = wrapped_env.step({'fake_action': np.array([1, 2, 3])})
self.assertEqual(self.base_timestep.step_type, ts.step_type)
self.assertEqual(self.base_timestep.reward, ts.reward)
self.assertEqual(self.base_timestep.discount, ts.discount)
self.assertEqual(self.base_timestep.observation['other_obs'],
ts.observation['other_obs'])
expected_pixel_value = 1. / 255. # original values are unit8
expected_pixels = np.ones(
self.pixels_shape, dtype=np.float32) * expected_pixel_value
np.testing.assert_equal(expected_pixels, ts.observation['pixels'])
def test_float_pixels_wrapper_reset(self):
wrapped_env = float_pixels_wrapper.FloatPixelsWrapper(self.base_env)
ts = wrapped_env.reset()
self.assertEqual(self.base_timestep.step_type, ts.step_type)
self.assertEqual(self.base_timestep.reward, ts.reward)
self.assertEqual(self.base_timestep.discount, ts.discount)
self.assertEqual(self.base_timestep.observation['other_obs'],
ts.observation['other_obs'])
expected_pixel_value = 1. / 255. # original values are unit8
expected_pixels = np.ones(
self.pixels_shape, dtype=np.float32) * expected_pixel_value
np.testing.assert_equal(expected_pixels, ts.observation['pixels'])
def test_float_pixels_wrapper_already_float(self):
base_pixel_spec = _make_array_spec(
shape=self.pixels_shape, dtype=np.float64, name='pixels')
base_observation_spec = {
'pixels': base_pixel_spec,
'other_obs': self.other_obs_spec
}
base_env = mock.create_autospec(dm_env.Environment)
base_env.observation_spec.return_value = base_observation_spec
wrapped_env = float_pixels_wrapper.FloatPixelsWrapper(base_env)
# If the pixels are already float values, then obs_spec does not change.
self.assertEqual(base_env.observation_spec(),
wrapped_env.observation_spec())
# The wrapper should not touch the timestep in this case.
fake_timestep = ('step_type', 'reward', 'discount', 'obs')
base_env.step.return_value = fake_timestep
ts = wrapped_env.step({'fake_action': np.array([1, 2, 3])})
self.assertEqual(fake_timestep, ts)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/float_pixels_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wraps the AndroidEnv environment to rescale the observations."""
from typing import Sequence
from android_env.wrappers import base_wrapper
import dm_env
from dm_env import specs
import numpy as np
from PIL import Image
# Taken from https://pillow.readthedocs.io/en/3.2.x/reference/Image.html#PIL.Image.Image.convert
#
# This array maps an RGB image to a grayscale image using the ITU-R 709
# specification which is good for computer displays and HDTV.
RGB_TO_GRAYSCALE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]
class ImageRescaleWrapper(base_wrapper.BaseWrapper):
"""AndroidEnv with rescaled observations."""
def __init__(
self,
env: dm_env.Environment,
zoom_factors: Sequence[float] | None = (0.5, 0.5),
grayscale: bool = False,
):
super().__init__(env)
assert 'pixels' in self._env.observation_spec()
assert self._env.observation_spec()['pixels'].shape[-1] in [1, 3], (
'Number of pixel channels should be 1 or 3.')
self._grayscale = grayscale
if zoom_factors is None:
zoom_factors = (1.0, 1.0)
# We only zoom the width and height of each layer, and we explicitly do not
# want to zoom the number of channels so we just multiply it by 1.0.
self._zoom_factors = tuple(zoom_factors) + (1.0,)
def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep:
observation = timestep.observation
processed_observation = observation.copy()
processed_observation['pixels'] = self._process_pixels(
observation['pixels'])
return timestep._replace(observation=processed_observation)
def _process_pixels(self, raw_observation: np.ndarray) -> np.ndarray:
# We expect `raw_observation` to have shape (W, H, 3) - 3 for RGB
new_shape = np.array(
self._zoom_factors[0:2] * np.array(raw_observation.shape[0:2]),
dtype=np.int32)[::-1]
if self._grayscale:
# When self._grayscale == True, we squash the RGB into a single layer
image = np.dot(raw_observation, RGB_TO_GRAYSCALE_COEFFICIENTS)
else:
image = raw_observation
return self._resize_image_array(image, new_shape)
def _resize_image_array(
self,
grayscale_or_rbg_array: np.ndarray,
new_shape: Sequence[int]) -> np.ndarray:
"""Resize color or grayscale/action_layer array to new_shape."""
assert np.array(new_shape).ndim == 1
assert len(new_shape) == 2
resized_array = np.array(Image.fromarray(
grayscale_or_rbg_array.astype('uint8')).resize(new_shape))
if resized_array.ndim == 2:
return np.expand_dims(resized_array, axis=-1)
return resized_array
def reset(self) -> dm_env.TimeStep:
timestep = self._env.reset()
return self._process_timestep(timestep)
def step(self, action) -> dm_env.TimeStep:
timestep = self._env.step(action)
return self._process_timestep(timestep)
def observation_spec(self) -> dict[str, specs.Array]:
parent_spec = self._env.observation_spec().copy()
out_shape = np.multiply(parent_spec['pixels'].shape,
self._zoom_factors).astype(np.int32)
if self._grayscale:
# In grayscale mode we want the output shape to be [W, H, 1]
out_shape[-1] = 1
parent_spec['pixels'] = specs.BoundedArray(
shape=out_shape,
dtype=parent_spec['pixels'].dtype,
name=parent_spec['pixels'].name,
minimum=parent_spec['pixels'].minimum,
maximum=parent_spec['pixels'].maximum)
return parent_spec
| android_env-main | android_env/wrappers/image_rescale_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for rate_limit_wrapper."""
import time
from typing import Any, Protocol
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
from android_env import env_interface
from android_env.components import action_type
from android_env.wrappers import rate_limit_wrapper
import dm_env
from dm_env import specs
import numpy as np
def _get_base_env():
env = mock.create_autospec(env_interface.AndroidEnvInterface)
env.action_spec.return_value = {
'action_type':
specs.DiscreteArray(
num_values=len(action_type.ActionType),
name='action_type'),
'touch_position':
specs.BoundedArray(
shape=(2,),
dtype=np.float32,
minimum=[0.0, 0.0],
maximum=[1.0, 1.0],
name='touch_position'),
}
return env
class _FnWithTimestamps(Protocol):
"""A function with `timestamp` and `timestamps` attributes."""
timestamp: float
timestamps: list[float]
def _with_timestamp(fn: Any) -> _FnWithTimestamps:
return fn
class RateLimitWrapperTest(parameterized.TestCase):
@parameterized.named_parameters(
('zero_rate', 0),
('negative_rate', -50),
)
@mock.patch.object(time, 'sleep', autospec=True)
def test_disabled(self, rate, mock_sleep):
"""With a non-positive rate, this wrapper should do nothing."""
env = _get_base_env()
wrapper = rate_limit_wrapper.RateLimitWrapper(env, rate=rate)
_ = wrapper.reset()
mock_sleep.assert_not_called()
_ = wrapper.step({
'action_type': np.array(action_type.ActionType.LIFT, dtype=np.uint8),
'touch_position': np.array([0.123, 0.456])
})
mock_sleep.assert_not_called()
# When the wrapper is disabled, base step should only be called once.
env.step.assert_called_once()
@mock.patch.object(time, 'sleep', autospec=True)
def test_enabled(self, mock_sleep):
"""When enabled, the wrapper should sleep for a period in [0, 1/rate]."""
env = _get_base_env()
env.step.return_value = dm_env.transition(reward=None, observation=None)
wrapper = rate_limit_wrapper.RateLimitWrapper(env, rate=1/33.33)
_ = wrapper.reset()
mock_sleep.assert_not_called() # It should never sleep during reset().
# Step for 100 steps.
for _ in range(100):
_ = wrapper.step({
'action_type':
np.array(action_type.ActionType.LIFT, dtype=np.uint8),
'touch_position':
np.array([0.123, 0.456])
})
# Check that there are 100 calls and that they're all within [0, 1/rate].
self.assertLen(mock_sleep.call_args_list, 100)
for call in mock_sleep.call_args_list:
args, unused_kwargs = call
sleep_time = args[0]
self.assertBetween(sleep_time, 0.0, 33.33)
@mock.patch.object(time, 'sleep', autospec=True)
def test_enabled_sleep_type_before(self, mock_sleep):
"""When sleep_type==BEFORE, sleep should come before step()."""
env = _get_base_env()
wrapper = rate_limit_wrapper.RateLimitWrapper(
env,
rate=1/33.33,
sleep_type=rate_limit_wrapper.RateLimitWrapper.SleepType.BEFORE)
_ = wrapper.reset()
mock_sleep.assert_not_called() # It should never sleep during reset().
@_with_timestamp
def _sleep_fn(sleep_time):
_sleep_fn.timestamp = time.time()
self.assertBetween(sleep_time, 0.0, 33.33)
mock_sleep.side_effect = _sleep_fn
def _step_fn(action):
self.assertEqual(
action['action_type'],
np.array(action_type.ActionType.LIFT, dtype=np.uint8))
_step_fn.timestamps.append(time.time())
return dm_env.transition(reward=None, observation=None)
_step_fn.timestamps = []
env.step.side_effect = _step_fn
_ = wrapper.step({
'action_type': np.array(action_type.ActionType.LIFT, dtype=np.uint8),
'touch_position': np.array([0.123, 0.456])
})
self.assertLen(_step_fn.timestamps, 1)
# We expect sleep to have been executed BEFORE a single `step()`.
self.assertGreaterEqual(_step_fn.timestamps[0], _sleep_fn.timestamp)
@mock.patch.object(time, 'sleep', autospec=True)
def test_enabled_sleep_type_after(self, mock_sleep):
"""When sleep_type==AFTER, sleep should come after step()."""
env = _get_base_env()
wrapper = rate_limit_wrapper.RateLimitWrapper(
env,
rate=1/33.33,
sleep_type=rate_limit_wrapper.RateLimitWrapper.SleepType.AFTER)
_ = wrapper.reset()
mock_sleep.assert_not_called() # It should never sleep during reset().
@_with_timestamp
def _sleep_fn(sleep_time):
_sleep_fn.timestamp = time.time()
self.assertBetween(sleep_time, 0.0, 33.33)
mock_sleep.side_effect = _sleep_fn
def _step_fn(action):
self.assertEqual(
action['action_type'],
np.array(action_type.ActionType.LIFT, dtype=np.uint8))
_step_fn.timestamps.append(time.time())
return dm_env.transition(reward=None, observation=None)
_step_fn.timestamps = []
env.step.side_effect = _step_fn
_ = wrapper.step({
'action_type': np.array(action_type.ActionType.LIFT, dtype=np.uint8),
'touch_position': np.array([0.123, 0.456])
})
# We expect sleep to have been executed AFTER a single `step()`.
self.assertLen(_step_fn.timestamps, 1)
self.assertLessEqual(_step_fn.timestamps[0], _sleep_fn.timestamp)
@mock.patch.object(time, 'sleep', autospec=True)
def test_enabled_sleep_type_after_with_repeat(self, mock_sleep):
"""When sleep_type==AFTER_WITH_REPEAT, sleep should be between 2 steps()."""
env = _get_base_env()
wrapper = rate_limit_wrapper.RateLimitWrapper(
env,
rate=1/33.33,
sleep_type=rate_limit_wrapper.RateLimitWrapper.SleepType
.AFTER_WITH_REPEAT)
_ = wrapper.reset()
mock_sleep.assert_not_called() # It should never sleep during reset().
@_with_timestamp
def _sleep_fn(sleep_time):
_sleep_fn.timestamp = time.time()
self.assertBetween(sleep_time, 0.0, 33.33)
mock_sleep.side_effect = _sleep_fn
@_with_timestamp
def _step_fn(action):
# On even calls the action should be the actual agent action, but on odd
# calls they should be REPEATs.
if len(_step_fn.timestamps) % 2 == 0:
self.assertEqual(
action['action_type'],
np.array(action_type.ActionType.LIFT, dtype=np.uint8))
else:
self.assertEqual(
action['action_type'],
np.array(action_type.ActionType.REPEAT, dtype=np.uint8))
_step_fn.timestamps.append(time.time())
return dm_env.transition(reward=1.0, observation=None)
_step_fn.timestamps = []
env.step.side_effect = _step_fn
timestep = wrapper.step({
'action_type': np.array(action_type.ActionType.LIFT, dtype=np.uint8),
'touch_position': np.array([0.123, 0.456])
})
# When the wrapper is enabled, base step should be called twice.
self.assertEqual(env.step.call_count, 2)
# `step()` should be called twice: before `sleep()` and after it.
self.assertLen(_step_fn.timestamps, 2)
self.assertGreaterEqual(_sleep_fn.timestamp, _step_fn.timestamps[0])
self.assertLessEqual(_sleep_fn.timestamp, _step_fn.timestamps[1])
# Rewards should accumulate over the two step() calls
self.assertEqual(timestep.reward, 2.0)
@mock.patch.object(time, 'sleep', autospec=True)
def test_enabled_sleep_type_after_with_repeat_last(self, mock_sleep):
"""If the first step is a LAST, second step should not be taken."""
env = _get_base_env()
wrapper = rate_limit_wrapper.RateLimitWrapper(
env,
rate=1/33.33,
sleep_type=rate_limit_wrapper.RateLimitWrapper.SleepType
.AFTER_WITH_REPEAT)
_ = wrapper.reset()
mock_sleep.assert_not_called() # It should never sleep during reset().
env.step.return_value = dm_env.termination(reward=None, observation=None)
_ = wrapper.step({
'action_type': np.array(action_type.ActionType.LIFT, dtype=np.uint8),
'touch_position': np.array([0.123, 0.456])
})
# Second step call should be skipped.
env.step.assert_called_once()
mock_sleep.assert_not_called()
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/rate_limit_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Converts pixel observation to from int to float32 between 0.0 and 1.0."""
from android_env.components import utils
from android_env.wrappers import base_wrapper
import dm_env
from dm_env import specs
import numpy as np
class FloatPixelsWrapper(base_wrapper.BaseWrapper):
"""Wraps AndroidEnv for Panultimate agent."""
def __init__(self, env: dm_env.Environment):
super().__init__(env)
self._input_spec = self._env.observation_spec()['pixels']
self._should_convert_int_to_float = np.issubdtype(self._input_spec.dtype,
np.integer)
def _process_observation(
self, observation: dict[str, np.ndarray]
) -> dict[str, np.ndarray]:
if self._should_convert_int_to_float:
float_pixels = utils.convert_int_to_float(observation['pixels'],
self._input_spec, np.float32)
observation['pixels'] = float_pixels
return observation
def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep:
step_type, reward, discount, observation = timestep
return dm_env.TimeStep(
step_type=step_type,
reward=reward,
discount=discount,
observation=self._process_observation(observation))
def reset(self) -> dm_env.TimeStep:
return self._process_timestep(self._env.reset())
def step(self, action: dict[str, np.ndarray]) -> dm_env.TimeStep:
return self._process_timestep(self._env.step(action))
def observation_spec(self) -> dict[str, specs.Array]:
if self._should_convert_int_to_float:
observation_spec = self._env.observation_spec()
observation_spec['pixels'] = specs.BoundedArray(
shape=self._env.observation_spec()['pixels'].shape,
dtype=np.float32,
minimum=0.0,
maximum=1.0,
name=self._env.observation_spec()['pixels'].name)
return observation_spec
return self._env.observation_spec()
| android_env-main | android_env/wrappers/float_pixels_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.wrappers.discrete_action_wrapper."""
from unittest import mock
from absl.testing import absltest
from android_env import env_interface
from android_env.components import action_type as action_type_lib
from android_env.wrappers import discrete_action_wrapper
from dm_env import specs
import numpy as np
ActionType = action_type_lib.ActionType
def _make_array_spec(shape, dtype, name):
assert len(shape) == 1
return specs.BoundedArray(
name=name,
shape=shape,
dtype=dtype,
minimum=np.zeros(shape),
maximum=(shape[0] - 1) * np.ones(shape), # maximum is inclusive.
)
def _valid_shape(action):
assert len(action) == 2, action
assert not action['action_type'].shape, (
'action: %r, shape: %r' %
(action['action_type'], action['action_type'].shape))
assert action['touch_position'].shape == (
2,), ('action: %r, shape: %r' %
(action['touch_position'], action['touch_position'].shape))
def _valid_types(action, types):
for a, t in zip(action.values(), types):
assert a.dtype == t, '%r is not of dtype %r' % (a, t)
class DiscreteActionWrapperTest(absltest.TestCase):
def setUp(self):
super().setUp()
self._num_action_types = 3 # Only TOUCH, LIFT, REPEAT.
self._base_action_spec = {
'action_type': specs.DiscreteArray(
num_values=self._num_action_types, name='action_type'),
'touch_position': _make_array_spec(
shape=(2,), dtype=np.float32, name='touch_position'),
}
self.base_env = mock.create_autospec(env_interface.AndroidEnvInterface)
self.base_env.action_spec.return_value = self._base_action_spec
def test_num_actions(self):
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env, action_grid=(3, 3), redundant_actions=True)
# 27 = 3 * 3 * 2 (H * W * self._num_action_types).
self.assertEqual(27, wrapped_env.num_actions)
def test_num_actions_non_redundant(self):
# Check that with `redundant_actions`==False we get an additive term instead
# of a multiplier in the number of actions.
non_redudant_wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env, action_grid=(3, 3), redundant_actions=False)
# 11 = 3 * 3 + 2 (H * W + (self._num_action_types - 1)).
self.assertEqual(11, non_redudant_wrapped_env.num_actions)
def test_reset(self):
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env, redundant_actions=True)
fake_timestep = 'ts'
self.base_env.reset.return_value = fake_timestep
ts = wrapped_env.reset()
self.base_env.reset.assert_called_once()
self.assertEqual(fake_timestep, ts)
def test_step_no_noise(self):
height = 4
width = 3
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env,
action_grid=(height, width),
noise=0.0,
redundant_actions=True)
self.assertEqual(height * width * self._num_action_types,
wrapped_env.num_actions)
vertical_half_step = 1. / float(height) / 2.
horizontal_half_step = 1. / float(width) / 2.
delta = 0.0001
# Testing the four corners with each finger position
def get_verifier(expected_action_type, lower_x, lower_y):
def verifier(x):
_valid_shape(x)
_valid_types(x, [np.int32, np.float32])
self.assertEqual(
expected_action_type, x['action_type'])
if lower_y:
self.assertAlmostEqual(
vertical_half_step, x['touch_position'][1], delta=delta)
else:
self.assertAlmostEqual(
1 - vertical_half_step, x['touch_position'][1], delta=delta)
if lower_x:
self.assertAlmostEqual(
horizontal_half_step, x['touch_position'][0], delta=delta)
else:
self.assertAlmostEqual(
1 - horizontal_half_step, x['touch_position'][0], delta=delta)
return True
return verifier
action_tests = {
0: get_verifier(0, lower_x=True, lower_y=True),
2: get_verifier(0, lower_x=False, lower_y=True),
9: get_verifier(0, lower_x=True, lower_y=False),
11: get_verifier(0, lower_x=False, lower_y=False),
12: get_verifier(1, lower_x=True, lower_y=True),
14: get_verifier(1, lower_x=False, lower_y=True),
21: get_verifier(1, lower_x=True, lower_y=False),
23: get_verifier(1, lower_x=False, lower_y=False),
24: get_verifier(2, lower_x=True, lower_y=True),
26: get_verifier(2, lower_x=False, lower_y=True),
33: get_verifier(2, lower_x=True, lower_y=False),
35: get_verifier(2, lower_x=False, lower_y=False),
}
fake_timestep = 'ts'
self.base_env.step.return_value = fake_timestep
for action_id, verifier in action_tests.items():
ts = wrapped_env.step({'action_id': action_id})
verifier(self.base_env.step.call_args[0][0])
self.assertEqual(fake_timestep, ts)
def test_step_redundant_actions_invalid_action_id(self):
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env,
action_grid=(4, 3),
noise=0.0,
redundant_actions=True)
with self.assertRaises(AssertionError):
_ = wrapped_env.step({'action_id': 36})
def test_step_no_noise_no_redudant_actions(self):
height = 4
width = 3
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env,
action_grid=(height, width),
noise=0.0,
redundant_actions=False)
self.assertEqual(height * width + (self._num_action_types - 1),
wrapped_env.num_actions)
vertical_half_step = 1. / float(height) / 2.
horizontal_half_step = 1. / float(width) / 2.
delta = 0.0001
# Testing the four corners with each finger position
def get_verifier(expected_action_type, lower_x, lower_y):
def verifier(x):
_valid_shape(x)
_valid_types(x, [np.int32, np.float32])
self.assertEqual(expected_action_type, x['action_type'])
# If the action type == TOUCH, then check the coordinate values.
if x['action_type'] == ActionType.TOUCH:
if lower_y:
self.assertAlmostEqual(
vertical_half_step, x['touch_position'][1], delta=delta)
else:
self.assertAlmostEqual(
1 - vertical_half_step, x['touch_position'][1], delta=delta)
if lower_x:
self.assertAlmostEqual(
horizontal_half_step, x['touch_position'][0], delta=delta)
else:
self.assertAlmostEqual(
1 - horizontal_half_step, x['touch_position'][0], delta=delta)
return True
return verifier
action_tests = {
# Touch type actions
0: get_verifier(0, lower_x=True, lower_y=True),
2: get_verifier(0, lower_x=False, lower_y=True),
9: get_verifier(0, lower_x=True, lower_y=False),
11: get_verifier(0, lower_x=False, lower_y=False),
# Actions > grid_size return non-touch actions with (0,0) coordinates.
12: get_verifier(1, lower_x=False, lower_y=False),
13: get_verifier(2, lower_x=False, lower_y=False),
}
fake_timestep = 'ts'
self.base_env.step.return_value = fake_timestep
for action_id, verifier in action_tests.items():
ts = wrapped_env.step({'action_id': action_id})
verifier(self.base_env.step.call_args[0][0])
self.assertEqual(fake_timestep, ts)
def test_step_no_redundant_actions_invalid_action_id(self):
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env,
action_grid=(4, 3),
noise=0.0,
redundant_actions=False)
with self.assertRaises(AssertionError):
_ = wrapped_env.step({'action_id': 14})
def test_step_with_noise(self):
height = 4
width = 3
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env, action_grid=(height, width), noise=1.0)
self.assertEqual(height * width * self._num_action_types,
wrapped_env.num_actions)
vertical_grid_step = 1. / float(height)
horizontal_grid_step = 1. / float(width)
# Testing the four corners with each finger position
def get_verifier(expected_up_down, lower_x, lower_y):
def verifier(x):
_valid_shape(x)
_valid_types(x, [np.int32, np.float32])
self.assertEqual(expected_up_down, x['action_type'])
if lower_y:
self.assertGreater(vertical_grid_step, x['touch_position'][1])
else:
self.assertLess(1 - vertical_grid_step, x['touch_position'][1])
if lower_x:
self.assertGreater(horizontal_grid_step, x['touch_position'][0])
else:
self.assertLess(1 - horizontal_grid_step, x['touch_position'][0])
return True
return verifier
action_tests = {
0: get_verifier(0, lower_x=True, lower_y=True),
2: get_verifier(0, lower_x=False, lower_y=True),
9: get_verifier(0, lower_x=True, lower_y=False),
11: get_verifier(0, lower_x=False, lower_y=False),
12: get_verifier(1, lower_x=True, lower_y=True),
14: get_verifier(1, lower_x=False, lower_y=True),
21: get_verifier(1, lower_x=True, lower_y=False),
23: get_verifier(1, lower_x=False, lower_y=False),
24: get_verifier(2, lower_x=True, lower_y=True),
26: get_verifier(2, lower_x=False, lower_y=True),
33: get_verifier(2, lower_x=True, lower_y=False),
35: get_verifier(2, lower_x=False, lower_y=False),
}
fake_timestep = 'ts'
self.base_env.step.return_value = fake_timestep
for action_id, verifier in action_tests.items():
ts = wrapped_env.step({'action_id': action_id})
verifier(self.base_env.step.call_args[0][0])
self.assertEqual(fake_timestep, ts)
def test_parent_spec_type(self):
base_action_spec = {
'action_type': specs.DiscreteArray(
num_values=self._num_action_types, name='action_type'),
'touch_position': _make_array_spec(
shape=(2,), dtype=np.float64, name='touch_position'),
}
base_env = mock.create_autospec(env_interface.AndroidEnvInterface)
base_env.action_spec.return_value = base_action_spec
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
base_env, noise=0.0)
fake_timestep = 'ts'
base_env.step.return_value = fake_timestep
def verifier(x):
_valid_types(x, [np.int32, np.float64])
return True
ts = wrapped_env.step({'action_id': 1})
verifier(base_env.step.call_args[0][0])
self.assertEqual(fake_timestep, ts)
def test_observation_spec(self):
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env)
fake_obs_spec = 'fake_obs_spec'
self.base_env.observation_spec.return_value = fake_obs_spec
observation_spec = wrapped_env.observation_spec()
self.base_env.observation_spec.assert_called_once()
self.assertEqual(fake_obs_spec, observation_spec)
def test_action_spec(self):
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env, action_grid=(4, 5), redundant_actions=True)
expected_action_spec = {
'action_id':
specs.DiscreteArray(
num_values=4 * 5 * self._num_action_types, name='action_type')
}
self.assertEqual(expected_action_spec, wrapped_env.action_spec())
def test_action_spec_non_redundant(self):
wrapped_env = discrete_action_wrapper.DiscreteActionWrapper(
self.base_env, action_grid=(4, 5), redundant_actions=False)
num_non_touch_actions = self._num_action_types - 1
expected_action_spec = {
'action_id':
specs.DiscreteArray(
num_values=4 * 5 + num_non_touch_actions, name='action_type')
}
self.assertEqual(expected_action_spec, wrapped_env.action_spec())
def test_assert_base_env_action_spec_too_short(self):
self.base_env.action_spec.return_value = {
'action_type': specs.DiscreteArray(
num_values=self._num_action_types, name='action_type'),
}
with self.assertRaises(AssertionError):
_ = discrete_action_wrapper.DiscreteActionWrapper(self.base_env)
def test_assert_base_env_action_spec_too_long(self):
self.base_env.action_spec.return_value = {
'action_type': specs.DiscreteArray(
num_values=self._num_action_types, name='action_type'),
'touch_position': _make_array_spec(
shape=(2,), dtype=np.float32, name='touch_position'),
'too_long': _make_array_spec(
shape=(1,), dtype=np.float32, name='too_long'),
}
with self.assertRaises(AssertionError):
_ = discrete_action_wrapper.DiscreteActionWrapper(self.base_env)
def test_assert_base_env_action_spec_wrong_shapes(self):
self.base_env.action_spec.return_value = {
'action_type': _make_array_spec(
shape=(2,), dtype=np.float32, name='action_type'),
'touch_position': _make_array_spec(
shape=(1,), dtype=np.float32, name='touch_position')
}
with self.assertRaises(AssertionError):
_ = discrete_action_wrapper.DiscreteActionWrapper(self.base_env)
def test_assert_base_env_ok(self):
self.base_env.action_spec.return_value = {
'action_type': specs.DiscreteArray(
num_values=self._num_action_types, name='action_type'),
'touch_position': _make_array_spec(
shape=(2,), dtype=np.float32, name='touch_position'),
}
_ = discrete_action_wrapper.DiscreteActionWrapper(self.base_env)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/discrete_action_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.wrappers.flat_interface_wrapper."""
from typing import cast
from unittest import mock
from absl.testing import absltest
from android_env.wrappers import flat_interface_wrapper
import dm_env
from dm_env import specs
import numpy as np
def _make_array_spec(shape, dtype=np.float32, name=None, maximum=3, minimum=0):
return specs.BoundedArray(
shape=shape,
dtype=dtype,
name=name,
maximum=np.ones(shape) * maximum,
minimum=np.ones(shape) * minimum)
def _make_timestep(observation):
return dm_env.TimeStep(
step_type='fake_step_type',
reward='fake_reward',
discount='fake_discount',
observation=observation,
)
class FlatInterfaceWrapperTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.action_shape = (1,)
self.base_action_spec: dict[str, specs.DiscreteArray] = {
'action_id': specs.DiscreteArray(name='action_id', num_values=4)
}
self.int_obs_shape = (3, 4, 2)
self.float_obs_shape = (2,)
self.base_observation_spec = {
'pixels': _make_array_spec(
shape=self.int_obs_shape, dtype=np.uint8, name='pixels'),
'obs1': _make_array_spec(
shape=self.float_obs_shape, dtype=np.float32, name='obs1'),
}
# Expected.
self.expected_observation_spec = _make_array_spec(
shape=self.int_obs_shape, dtype=np.uint8, name='pixels')
self.image_obs = np.ones(self.int_obs_shape, dtype=np.uint8)
self.expected_timestep = _make_timestep(self.image_obs)
# Expected for no new action layer shape.
expected_new_shape_no_action_layer = (3, 4, 1)
self.expected_observation_spec_no_action_layer = _make_array_spec(
shape=expected_new_shape_no_action_layer, dtype=np.uint8, name='pixels')
self.expected_timestep_no_action_layer = _make_timestep(
np.ones(expected_new_shape_no_action_layer, dtype=np.uint8))
# Base environment.
self.other_obs = np.ones(self.float_obs_shape, dtype=np.float32)
self.base_timestep = _make_timestep({
'pixels': self.image_obs,
'obs1': self.other_obs})
self.base_env = mock.create_autospec(dm_env.Environment)
self.base_env.action_spec.return_value = self.base_action_spec
self.base_env.observation_spec.return_value = self.base_observation_spec
self.base_env.reset.return_value = self.base_timestep
self.base_env.step.return_value = self.base_timestep
def test_reset(self):
wrapped_env = flat_interface_wrapper.FlatInterfaceWrapper(self.base_env)
ts = wrapped_env.reset()
self.base_env.reset.assert_called_once()
self.assertEqual(self.expected_timestep, ts)
def test_reset_no_action_layer(self):
wrapped_env = flat_interface_wrapper.FlatInterfaceWrapper(
self.base_env, keep_action_layer=False)
ts = wrapped_env.reset()
self.base_env.reset.assert_called_once()
self.assertEqual(
self.expected_timestep_no_action_layer.observation.tolist(),
ts.observation.tolist())
def test_step(self):
wrapped_env = flat_interface_wrapper.FlatInterfaceWrapper(self.base_env)
action = 2
ts = wrapped_env.step(action)
def verifier(x):
self.assertIsInstance(x, dict)
self.assertIsInstance(x['action_id'], int)
self.assertEqual(x['action_id'], action)
return True
verifier(self.base_env.step.call_args[0][0])
self.assertEqual(self.expected_timestep, ts)
def test_step_no_action_layer(self):
wrapped_env = flat_interface_wrapper.FlatInterfaceWrapper(
self.base_env, keep_action_layer=False)
action = 2
ts = wrapped_env.step(action)
def verifier(x):
self.assertIsInstance(x, dict)
self.assertIsInstance(x['action_id'], int)
self.assertEqual(x['action_id'], action)
return True
verifier(self.base_env.step.call_args[0][0])
self.assertEqual(
self.expected_timestep_no_action_layer.observation.tolist(),
ts.observation.tolist())
def test_observation_spec(self):
wrapped_env = flat_interface_wrapper.FlatInterfaceWrapper(self.base_env)
observation_spec = wrapped_env.observation_spec()
self.base_env.observation_spec.assert_called_once()
self.assertEqual(self.expected_observation_spec, observation_spec)
def test_observation_spec_no_action_layer(self):
wrapped_env = flat_interface_wrapper.FlatInterfaceWrapper(
self.base_env, keep_action_layer=False)
observation_spec = wrapped_env.observation_spec()
self.base_env.observation_spec.assert_called_once()
self.assertEqual(self.expected_observation_spec_no_action_layer,
observation_spec)
def test_action_spec(self):
wrapped_env = flat_interface_wrapper.FlatInterfaceWrapper(self.base_env)
action_spec = cast(specs.BoundedArray, wrapped_env.action_spec())
parent_action_spec = self.base_action_spec['action_id']
self.assertEqual(parent_action_spec.name, action_spec.name)
self.assertEqual((), action_spec.shape)
self.assertEqual(np.int32, action_spec.dtype)
self.assertEqual(0, action_spec.minimum)
def test_bad_action_spec_structured_action(self):
bad_base_env = mock.create_autospec(dm_env.Environment)
bad_base_env.action_spec.return_value = {
'action_id': _make_array_spec((1,)),
'too_many': _make_array_spec((1,))
}
with self.assertRaises(AssertionError):
_ = flat_interface_wrapper.FlatInterfaceWrapper(bad_base_env)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/flat_interface_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| android_env-main | android_env/wrappers/__init__.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wraps the AndroidEnv environment to provide tap actions of a given duration."""
from typing import Sequence
from android_env.components import action_type
from android_env.wrappers import base_wrapper
import dm_env
import numpy as np
ActionType = action_type.ActionType
class TapActionWrapper(base_wrapper.BaseWrapper):
"""AndroidEnv with tap actions."""
def __init__(self,
env: dm_env.Environment,
num_frames: int = 5,
touch_only: bool = False):
super().__init__(env)
assert 'action_type' in env.action_spec()
self._touch_only = touch_only
self._num_frames = num_frames
self._env_steps = 0
def stats(self):
"""Returns a dictionary of metrics logged by the environment."""
logs = self._env.stats()
logs.update({'env_steps': self._env_steps})
return logs
def _process_action(
self, action: dict[str, np.ndarray]
) -> Sequence[dict[str, np.ndarray]]:
if self._touch_only:
assert action['action_type'] == 0
touch_action = action.copy()
touch_action['action_type'] = np.array(ActionType.TOUCH).astype(
self.action_spec()['action_type'].dtype)
actions = [touch_action] * self._num_frames
lift_action = action.copy()
lift_action['action_type'] = np.array(ActionType.LIFT).astype(
self.action_spec()['action_type'].dtype)
actions.append(lift_action)
else:
if action['action_type'] == ActionType.TOUCH:
actions = [action] * self._num_frames
lift_action = action.copy()
lift_action['action_type'] = np.array(ActionType.LIFT).astype(
self.action_spec()['action_type'].dtype)
actions.append(lift_action)
else:
actions = [action] * (self._num_frames + 1)
return actions
def step(self, action: dict[str, np.ndarray]) -> dm_env.TimeStep:
"""Takes a step in the environment."""
self._env_steps += self._num_frames + 1
actions = self._process_action(action)
total_reward = 0.0
for idx in range(len(actions)):
step_type, reward, discount, observation = self._env.step(actions[idx])
if reward:
total_reward += reward
if step_type == dm_env.StepType.LAST:
return dm_env.TimeStep(
step_type=step_type,
reward=total_reward,
discount=discount,
observation=observation)
return dm_env.TimeStep(
step_type=step_type,
reward=total_reward,
discount=discount,
observation=observation)
def action_spec(self) -> dict[str, dm_env.specs.Array]:
if self._touch_only:
return {
'action_type':
dm_env.specs.DiscreteArray(num_values=1, name='action_type'),
'touch_position':
self._env.action_spec()['touch_position'],
}
else:
return self._env.action_spec()
| android_env-main | android_env/wrappers/tap_action_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Base class for AndroidEnv wrappers."""
from typing import Any
from absl import logging
from android_env import env_interface
from android_env.proto import adb_pb2
from android_env.proto import state_pb2
import dm_env
from dm_env import specs
import numpy as np
class BaseWrapper(env_interface.AndroidEnvInterface):
"""AndroidEnv wrapper."""
def __init__(self, env):
self._env = env
logging.info('Wrapping with %s', self.__class__.__name__)
def reset(self) -> dm_env.TimeStep:
self._reset_state()
timestep = self._process_timestep(self._env.reset())
return timestep
def step(self, action: Any) -> dm_env.TimeStep:
action = self._process_action(action)
return self._process_timestep(self._env.step(action))
def task_extras(self, latest_only: bool = True) -> dict[str, np.ndarray]:
return self._env.task_extras(latest_only=latest_only)
def _reset_state(self):
pass
def _process_action(self, action: Any) -> Any:
return action
def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep:
return timestep
def observation_spec(self) -> dict[str, specs.Array]:
return self._env.observation_spec()
def action_spec(self) -> dict[str, specs.Array]:
return self._env.action_spec()
def reward_spec(self) -> specs.Array:
return self._env.reward_spec()
def discount_spec(self) -> specs.Array:
return self._env.discount_spec()
def _wrapper_stats(self) -> dict[str, Any]:
"""Add wrapper specific logging here."""
return {}
def stats(self) -> dict[str, Any]:
info = self._env.stats()
info.update(self._wrapper_stats())
return info
def load_state(
self, request: state_pb2.LoadStateRequest
) -> state_pb2.LoadStateResponse:
"""Loads a state."""
return self._env.load_state(request)
def save_state(
self, request: state_pb2.SaveStateRequest
) -> state_pb2.SaveStateResponse:
"""Saves a state.
Args:
request: A `SaveStateRequest` containing any parameters necessary to
specify how/what state to save.
Returns:
A `SaveStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
return self._env.save_state(request)
def execute_adb_call(self,
adb_call: adb_pb2.AdbRequest) -> adb_pb2.AdbResponse:
return self._env.execute_adb_call(adb_call)
@property
def raw_action(self):
return self._env.raw_action
@property
def raw_observation(self):
return self._env.raw_observation
@property
def raw_env(self):
"""Recursively unwrap until we reach the true 'raw' env."""
wrapped = self._env
if hasattr(wrapped, 'raw_env'):
return wrapped.raw_env
return wrapped
def __getattr__(self, attr):
"""Delegate attribute access to underlying environment."""
return getattr(self._env, attr)
def close(self):
self._env.close()
| android_env-main | android_env/wrappers/base_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.wrappers.gym_wrapper."""
from unittest import mock
from absl.testing import absltest
from android_env import env_interface
from android_env.wrappers import gym_wrapper
import dm_env
from dm_env import specs
from gym import spaces
import numpy as np
class GymInterfaceWrapperTest(absltest.TestCase):
def setUp(self):
super().setUp()
self._base_env = mock.create_autospec(env_interface.AndroidEnvInterface)
self._base_env.action_spec.return_value = {
'action_type':
specs.DiscreteArray(
num_values=3,
name='action_type'),
'touch_position':
specs.BoundedArray(
shape=(2,),
dtype=np.float32,
minimum=[0.0, 0.0],
maximum=[1.0, 1.0],
name='touch_position'),
}
self._base_env.observation_spec.return_value = {
'pixels':
specs.Array(
shape=(480, 320, 3),
dtype=np.uint8,
name='pixels'),
'timedelta':
specs.Array(shape=(), dtype=np.int64, name='timedelta'),
'orientation':
specs.Array(
shape=np.array([4]),
dtype=np.uint8,
name='orientation'),
}
self._wrapped_env = gym_wrapper.GymInterfaceWrapper(self._base_env)
self._fake_ts = dm_env.TimeStep(
step_type=dm_env.StepType.MID,
observation={'pixels': np.ones(shape=(2, 3))},
reward=10.0,
discount=1.0)
def test_render(self):
self._base_env.step.return_value = self._fake_ts
_ = self._wrapped_env.step(action=np.zeros(shape=(1,)))
image = self._wrapped_env.render(mode='rgb_array')
self.assertTrue(np.array_equal(image, np.ones(shape=(2, 3))))
def test_render_error(self):
with self.assertRaises(ValueError):
_ = self._wrapped_env.render(mode='human')
def test_reset(self):
self._base_env.reset.return_value = dm_env.TimeStep(
step_type=dm_env.StepType.FIRST,
observation={'pixels': np.ones(shape=(2, 3))},
reward=10.0,
discount=1.0)
obs = self._wrapped_env.reset()
self._base_env.reset.assert_called_once()
self.assertTrue(np.array_equal(obs['pixels'], np.ones(shape=(2, 3))))
def test_step(self):
self._base_env.step.return_value = self._fake_ts
obs, _, _, _ = self._wrapped_env.step(action=np.zeros(shape=(1,)))
self._base_env.step.assert_called_once()
self.assertTrue(np.array_equal(obs['pixels'], np.ones(shape=(2, 3))))
def test_spec_to_space(self):
spec = specs.Array(
shape=(2, 3),
dtype=np.float32)
space = self._wrapped_env._spec_to_space(spec)
self.assertEqual(space, spaces.Box(
low=-np.inf, high=np.inf, shape=spec.shape, dtype=spec.dtype))
spec = specs.BoundedArray(
shape=(),
dtype=np.float32,
minimum=4,
maximum=5)
space = self._wrapped_env._spec_to_space(spec)
self.assertEqual(space, spaces.Box(
low=4, high=5, shape=spec.shape, dtype=spec.dtype))
spec = specs.DiscreteArray(num_values=4)
space = self._wrapped_env._spec_to_space(spec)
self.assertEqual(space, spaces.Box(
low=0, high=3, shape=(), dtype=np.int32))
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/gym_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.wrappers.last_action_wrapper."""
from typing import Any
from unittest import mock
from absl.testing import absltest
from android_env import env_interface
from android_env.components import action_type
from android_env.wrappers import last_action_wrapper
import dm_env
from dm_env import specs
import numpy as np
def _simple_spec():
return specs.BoundedArray(
shape=np.array([120, 80, 3]),
dtype=np.uint8,
name='pixels',
minimum=0,
maximum=255)
def _simple_timestep():
observation = np.ones(shape=[120, 80, 3])
return dm_env.TimeStep(
step_type=dm_env.StepType.MID,
reward=3.14,
discount=0.9,
observation={'pixels': observation})
class LastActionWrapperTest(absltest.TestCase):
def test_concat_to_pixels(self):
fake_timestep = _simple_timestep()
fake_env = mock.create_autospec(env_interface.AndroidEnvInterface)
fake_env.observation_spec.return_value = {'pixels': _simple_spec()}
fake_env.reset.return_value = fake_timestep
fake_env.step.return_value = fake_timestep
wrapper = last_action_wrapper.LastActionWrapper(
fake_env, concat_to_pixels=True)
self.assertIsNotNone(wrapper)
self.assertEqual(wrapper.observation_spec()['pixels'].shape, (120, 80, 4))
reset_timestep = wrapper.reset()
reset_image = reset_timestep.observation['pixels']
self.assertEqual(reset_image.shape, (120, 80, 4))
last_action_layer = reset_image[:, :, -1]
self.assertEqual(np.sum(last_action_layer), 0)
action1 = {
'action_type': action_type.ActionType.TOUCH,
'touch_position': np.array([0.25, 0.75], dtype=np.float32), # (W x H)
}
type(fake_env).raw_action = mock.PropertyMock(return_value=action1)
step_timestep = wrapper.step(action=action1)
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (120, 80, 4)) # (H x W)
last_action_layer = step_image[:, :, -1]
self.assertEqual(np.sum(last_action_layer), 255)
y, x = np.where(last_action_layer == 255)
self.assertEqual((y.item(), x.item()), (90, 20))
action2 = {
'action_type': action_type.ActionType.LIFT,
'touch_position': np.array([0.25, 0.75], dtype=np.float32),
}
type(fake_env).raw_action = mock.PropertyMock(return_value=action2)
step_timestep = wrapper.step(action=action2)
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (120, 80, 4))
last_action_layer = step_image[:, :, -1]
self.assertEqual(np.sum(last_action_layer), 0)
action3 = {
'action_type': action_type.ActionType.TOUCH,
'touch_position': np.array([0.25, 1.0], dtype=np.float32),
}
type(fake_env).raw_action = mock.PropertyMock(return_value=action3)
step_timestep = wrapper.step(action=action3)
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (120, 80, 4))
last_action_layer = step_image[:, :, -1]
self.assertEqual(np.sum(last_action_layer), 255)
y, x = np.where(last_action_layer == 255)
self.assertEqual((y.item(), x.item()), (119, 20))
def test_no_concat_to_pixels(self):
fake_timestep = _simple_timestep()
fake_env = mock.create_autospec(env_interface.AndroidEnvInterface)
fake_env.observation_spec.return_value = {'pixels': _simple_spec()}
fake_env.reset.return_value = fake_timestep
fake_env.step.return_value = fake_timestep
wrapper = last_action_wrapper.LastActionWrapper(
fake_env, concat_to_pixels=False)
self.assertIsNotNone(wrapper)
self.assertEqual(wrapper.observation_spec()['pixels'].shape, (120, 80, 3))
self.assertEqual(wrapper.observation_spec()['last_action'].shape, (120, 80))
reset_timestep = wrapper.reset()
reset_image = reset_timestep.observation['pixels']
self.assertEqual(reset_image.shape, (120, 80, 3))
last_action_layer = reset_timestep.observation['last_action']
self.assertEqual(np.sum(last_action_layer), 0)
action1 = {
'action_type': action_type.ActionType.TOUCH,
'touch_position': np.array([0.25, 0.75], dtype=np.float32),
}
type(fake_env).raw_action = mock.PropertyMock(return_value=action1)
step_timestep = wrapper.step(action=action1)
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (120, 80, 3))
last_action_layer = step_timestep.observation['last_action']
self.assertEqual(np.sum(last_action_layer), 255)
y, x = np.where(last_action_layer == 255)
self.assertEqual((y.item(), x.item()), (90, 20))
action2 = {
'action_type': action_type.ActionType.LIFT,
'touch_position': np.array([0.25, 0.75], dtype=np.float32),
}
type(fake_env).raw_action = mock.PropertyMock(return_value=action2)
step_timestep = wrapper.step(action=action2)
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (120, 80, 3))
last_action_layer = step_timestep.observation['last_action']
self.assertEqual(np.sum(last_action_layer), 0)
action3 = {
'action_type': action_type.ActionType.TOUCH,
'touch_position': np.array([1.0, 0.75], dtype=np.float32),
}
type(fake_env).raw_action = mock.PropertyMock(return_value=action3)
step_timestep = wrapper.step(action=action3)
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (120, 80, 3))
last_action_layer = step_timestep.observation['last_action']
self.assertEqual(np.sum(last_action_layer), 255)
y, x = np.where(last_action_layer == 255)
self.assertEqual((y.item(), x.item()), (90, 79))
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/last_action_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Extends Android observation with the latest action taken."""
from android_env.components import action_type
from android_env.components import utils
from android_env.wrappers import base_wrapper
import dm_env
from dm_env import specs
import numpy as np
class LastActionWrapper(base_wrapper.BaseWrapper):
"""Extends Android observations with information about the last action taken.
The position of the last action is denoted by a single white pixel (with a
value of 255) in a channel of all black pixels (with a value of 0).
As this wrapper makes use of temporarily stored information about the
last action taken, it is important to apply on the environment side rather
than the agent side. Recommended not to apply before an ImageRescaleWrapper,
to avoid distortion of the single pixel denoting the action position.
"""
def __init__(self,
env: dm_env.Environment,
concat_to_pixels: bool = True):
"""Initializes the internal state of this wrapper.
Args:
env: the environment to wrap.
concat_to_pixels: If True, will add a channel to the pixel observation.
If False, will pass the action as an extra observation.
"""
super().__init__(env)
self._concat_to_pixels = concat_to_pixels
self._screen_dimensions = self._env.observation_spec()['pixels'].shape[:2]
def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep:
observation = timestep.observation.copy()
processed_observation = self._process_observation(observation)
return timestep._replace(observation=processed_observation)
def _process_observation(
self, observation: dict[str, np.ndarray]
) -> dict[str, np.ndarray]:
"""Extends observation with last_action data."""
processed_observation = observation.copy()
last_action_layer = self._get_last_action_layer(observation['pixels'])
if self._concat_to_pixels:
pixels = observation['pixels'].copy()
processed_pixels = np.dstack((pixels, last_action_layer))
processed_observation['pixels'] = processed_pixels
else:
processed_observation['last_action'] = last_action_layer
return processed_observation
def _get_last_action_layer(self, pixels: np.ndarray) -> np.ndarray:
"""Makes sure the rescaling doesn't distort the last_action layer."""
last_action = self._env.raw_action
last_action_layer = np.zeros(self._screen_dimensions, dtype=pixels.dtype)
if ('action_type' in last_action and
last_action['action_type'] == action_type.ActionType.TOUCH):
touch_position = last_action['touch_position']
x, y = utils.touch_position_to_pixel_position(
touch_position, width_height=self._screen_dimensions[::-1])
last_action_layer[y, x] = 255
return last_action_layer
def reset(self) -> dm_env.TimeStep:
timestep = self._env.reset()
return self._process_timestep(timestep)
def step(self, action) -> dm_env.TimeStep:
timestep = self._env.step(action)
return self._process_timestep(timestep)
def observation_spec(self) -> dict[str, specs.Array]:
parent_spec = self._env.observation_spec().copy()
shape = parent_spec['pixels'].shape
if self._concat_to_pixels:
parent_spec['pixels'] = specs.BoundedArray(
shape=(shape[0], shape[1], shape[2] + 1),
dtype=parent_spec['pixels'].dtype,
name=parent_spec['pixels'].name,
minimum=parent_spec['pixels'].minimum,
maximum=parent_spec['pixels'].maximum)
else:
parent_spec.update({
'last_action':
specs.BoundedArray(
shape=(shape[0], shape[1]),
dtype=parent_spec['pixels'].dtype,
name='last_action',
minimum=parent_spec['pixels'].minimum,
maximum=parent_spec['pixels'].maximum)
})
return parent_spec
| android_env-main | android_env/wrappers/last_action_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Limits interactions with the environment to a given rate."""
import enum
import time
from android_env import env_interface
from android_env.components import action_type
from android_env.wrappers import base_wrapper
import dm_env
import numpy as np
class RateLimitWrapper(base_wrapper.BaseWrapper):
"""Limits interactions with the environment to a given rate."""
class SleepType(enum.IntEnum):
"""Determines how the wrapper interacts with the underlying environment."""
# The wrapper sleeps before calling `step()` on the underlying environment.
BEFORE = 0
# The wrapper sleeps after calling `step()` on the underlying environment.
AFTER = 1
# The wrapper first calls `step()`, obtaining a TimeStep which is ignored,
# then it sleeps, and then it calls `step(REPEAT)` to obtain a TimeStep
# that's as fresh as possible.
#
# Note that for both BEFORE and AFTER_WITH_REPEAT, the _total_ amount of
# time inside this wrapper may go beyond the rate specified in `rate`
# because the sleep does not account for the time taken by step().
AFTER_WITH_REPEAT = 2
def __init__(self,
env: env_interface.AndroidEnvInterface,
rate: float,
sleep_type: SleepType = SleepType.AFTER_WITH_REPEAT):
"""Initializes this wrapper.
Args:
env: The underlying environment to which this wrapper is applied.
rate: The desired rate in Hz to interact with the environment. If <=0.0,
this wrapper will be disabled.
sleep_type: This determines how the wrapper will interact with the
underlying AndroidEnv environment.
"""
super().__init__(env)
self._assert_base_env()
self._last_step_time = None
self._max_wait = 1.0 / rate if rate > 0.0 else 0.0
self._sleep_type = sleep_type
def _assert_base_env(self):
"""Checks that the wrapped env has the right action spec format."""
parent_action_spec = self._env.action_spec()
assert len(parent_action_spec) == 2
assert not parent_action_spec['action_type'].shape
assert parent_action_spec['touch_position'].shape == (2,)
def reset(self):
timestep = self._env.reset()
self._last_step_time = time.time()
return timestep
def step(self, action: dict[str, np.ndarray]) -> dm_env.TimeStep:
"""Takes a step while maintaining a steady interaction rate."""
# If max_wait is non-positive, the wrapper has no effect.
if self._max_wait <= 0.0:
return self._env.step(action)
if self._sleep_type == RateLimitWrapper.SleepType.BEFORE:
self._wait()
timestep = self._env.step(action)
if timestep.last():
return timestep
if self._sleep_type == RateLimitWrapper.SleepType.AFTER_WITH_REPEAT:
for k in action.keys():
if k.startswith('action_type'):
action[k] = np.array(action_type.ActionType.REPEAT, dtype=np.uint8)
self._wait()
first_reward = timestep.reward or 0.0
timestep = self._env.step(action)
second_reward = timestep.reward or 0.0
# Accumulate rewards over the two steps taken.
timestep = timestep._replace(reward=first_reward + second_reward)
elif self._sleep_type == RateLimitWrapper.SleepType.AFTER:
self._wait()
self._last_step_time = time.time()
return timestep
def _wait(self) -> None:
if self._max_wait > 0.0 and self._last_step_time is not None:
time_since_step = time.time() - self._last_step_time
sec_to_wait = self._max_wait - time_since_step
if sec_to_wait > 0.0:
time.sleep(sec_to_wait)
| android_env-main | android_env/wrappers/rate_limit_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wraps the AndroidEnv to expose an OpenAI Gym interface."""
from typing import Any
from android_env.wrappers import base_wrapper
import dm_env
from dm_env import specs
import gym
from gym import spaces
import numpy as np
class GymInterfaceWrapper(gym.Env):
"""AndroidEnv with OpenAI Gym interface."""
def __init__(self, env: dm_env.Environment):
self._env = env
self.spec = None
self.action_space = self._spec_to_space(self._env.action_spec())
self.observation_space = self._spec_to_space(self._env.observation_spec())
self.metadata = {'render.modes': ['rgb_array']}
self._latest_observation = None
def _spec_to_space(self, spec: specs.Array) -> spaces.Space:
"""Converts dm_env specs to OpenAI Gym spaces."""
if isinstance(spec, list):
return spaces.Tuple([self._spec_to_space(s) for s in spec])
if isinstance(spec, dict):
return spaces.Dict(
{name: self._spec_to_space(s) for name, s in spec.items()}
)
if isinstance(spec, specs.DiscreteArray):
return spaces.Box(
shape=(),
dtype=spec.dtype,
low=0,
high=spec.num_values-1)
if isinstance(spec, specs.BoundedArray):
return spaces.Box(
shape=spec.shape,
dtype=spec.dtype,
low=spec.minimum,
high=spec.maximum)
if isinstance(spec, specs.Array):
if spec.dtype == np.uint8:
low = 0
high = 255
else:
low = -np.inf
high = np.inf
return spaces.Box(shape=spec.shape, dtype=spec.dtype, low=low, high=high)
raise ValueError('Unknown type for specs: {}'.format(spec))
def render(self, mode='rgb_array'):
"""Renders the environment."""
if mode == 'rgb_array':
if self._latest_observation is None:
return
return self._latest_observation['pixels']
else:
raise ValueError('Only supported render mode is rgb_array.')
def reset(self) -> np.ndarray:
self._latest_observation = None
timestep = self._env.reset()
return timestep.observation
def step(self, action: dict[str, int]) -> tuple[Any, ...]:
"""Take a step in the base environment."""
timestep = self._env.step(action)
observation = timestep.observation
self._latest_observation = observation
reward = timestep.reward
done = timestep.step_type == dm_env.StepType.LAST
info = {'discount': timestep.discount}
return observation, reward, done, info
| android_env-main | android_env/wrappers/gym_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wraps the AndroidEnv environment to provide discrete actions."""
from typing import Sequence
from android_env.components import action_type
from android_env.wrappers import base_wrapper
import dm_env
from dm_env import specs
import numpy as np
_NOISE_CLIP_VALUE = 0.4999
class DiscreteActionWrapper(base_wrapper.BaseWrapper):
"""AndroidEnv with discrete actions."""
def __init__(
self,
env: dm_env.Environment,
action_grid: Sequence[int] | None = (10, 10),
redundant_actions: bool = True,
noise: float = 0.1,
):
super().__init__(env)
self._parent_action_spec = self._env.action_spec()
self._assert_base_env()
self._action_grid = action_grid # [height, width]
self._grid_size = np.prod(self._action_grid)
self._num_action_types = self._parent_action_spec['action_type'].num_values
self._redundant_actions = redundant_actions
self._noise = noise
def _assert_base_env(self):
"""Checks that the wrapped env has the right action spec format."""
assert len(self._parent_action_spec) == 2
assert not self._parent_action_spec['action_type'].shape
assert self._parent_action_spec['touch_position'].shape == (2,)
@property
def num_actions(self) -> int:
"""Number of discrete actions."""
if self._redundant_actions:
return np.prod(self._action_grid) * self._num_action_types
else:
return np.prod(self._action_grid) + self._num_action_types - 1
def step(self, action: dict[str, int]) -> dm_env.TimeStep:
"""Take a step in the base environment."""
return self._env.step(self._process_action(action))
def _process_action(self, action: dict[str, int]) -> dict[str, np.ndarray]:
"""Transforms action so that it agrees with AndroidEnv's action spec."""
return {
'action_type':
np.array(self._get_action_type(action['action_id']),
dtype=self._parent_action_spec['action_type'].dtype),
'touch_position':
np.array(self._get_touch_position(action['action_id']),
dtype=self._parent_action_spec['touch_position'].dtype)
}
def _get_action_type(self, action_id: int) -> action_type.ActionType:
"""Compute action type corresponding to the given action_id.
When `self._redundant_actions` == True the `grid_size` is "broadcast" over
all the possible actions so you end up with `grid_size` discrete actions
of type 0, `grid_size` discrete actions of type 1, etc. for all action
types.
When `self._redundant_actions` == False the first `grid_size` actions are
reserved for "touch" and the rest are just added (NOT multiplied) to the
total number of discrete actions (exactly one of LIFT and REPEAT).
Args:
action_id: A discrete action.
Returns:
action_type: The action_type of the action.
"""
if self._redundant_actions:
assert action_id < self._num_action_types * self._grid_size
return action_id // self._grid_size
else:
assert action_id <= self._grid_size + 1
if action_id < self._grid_size:
return action_type.ActionType.TOUCH
elif action_id == self._grid_size:
return action_type.ActionType.LIFT
else:
return action_type.ActionType.REPEAT
def _get_touch_position(self, action_id: int) -> Sequence[float]:
"""Compute the position corresponding to the given action_id.
Note: in the touch_position (x, y) of an action, x corresponds to the
horizontal axis (width), and y corresponds to the vertical axis (height)
of the screen. BUT, the screen has dimensions (height, width), i.e. the
first coordinate corresponds to y, and the second coordinate corresponds
to x. Pay attention to this mismatch in the calculations below.
Args:
action_id: A discrete action.
Returns:
touch_position: The [0,1]x[0,1] coordinate of the action.
"""
position_idx = action_id % self._grid_size
x_pos_grid = position_idx % self._action_grid[1] # WIDTH
y_pos_grid = position_idx // self._action_grid[1] # HEIGHT
noise_x = np.random.normal(loc=0.0, scale=self._noise)
noise_y = np.random.normal(loc=0.0, scale=self._noise)
# Noise is clipped so that the action will strictly stay in the cell.
noise_x = max(min(noise_x, _NOISE_CLIP_VALUE), -_NOISE_CLIP_VALUE)
noise_y = max(min(noise_y, _NOISE_CLIP_VALUE), -_NOISE_CLIP_VALUE)
x_pos = (x_pos_grid + 0.5 + noise_x) / self._action_grid[1] # WIDTH
y_pos = (y_pos_grid + 0.5 + noise_y) / self._action_grid[0] # HEIGHT
# Project action space to action_spec ranges. For the default case of
# minimum = [0, 0] and maximum = [1, 1], this will not do anything.
x_min, y_min = self._parent_action_spec['touch_position'].minimum
x_max, y_max = self._parent_action_spec['touch_position'].maximum
x_pos = x_min + x_pos * (x_max - x_min)
y_pos = y_min + y_pos * (y_max - y_min)
return [x_pos, y_pos]
def action_spec(self) -> dict[str, specs.Array]:
"""Action spec of the wrapped environment."""
return {
'action_id':
specs.DiscreteArray(
num_values=self.num_actions,
name='action_id')
}
| android_env-main | android_env/wrappers/discrete_action_wrapper.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.wrappers.base_wrapper."""
from unittest import mock
from absl import logging
from absl.testing import absltest
from android_env import env_interface
from android_env.proto import state_pb2
from android_env.wrappers import base_wrapper
class BaseWrapperTest(absltest.TestCase):
@mock.patch.object(logging, 'info')
def test_base_function_forwarding(self, mock_info):
base_env = mock.create_autospec(env_interface.AndroidEnvInterface)
wrapped_env = base_wrapper.BaseWrapper(base_env)
mock_info.assert_called_with('Wrapping with %s', 'BaseWrapper')
fake_ts = 'fake_ts'
base_env.reset.return_value = fake_ts
self.assertEqual(fake_ts, wrapped_env.reset())
base_env.reset.assert_called_once()
fake_ts = 'fake_ts'
fake_action = 'fake_action'
base_env.step.return_value = fake_ts
self.assertEqual(fake_ts, wrapped_env.step(fake_action))
base_env.step.assert_called_once_with(fake_action)
fake_extras = 'fake_task_extras'
base_env.task_extras.return_value = fake_extras
self.assertEqual(fake_extras, wrapped_env.task_extras(latest_only=True))
base_env.task_extras.assert_called_once_with(latest_only=True)
fake_obs_spec = 'fake_obs_spec'
base_env.observation_spec.return_value = fake_obs_spec
self.assertEqual(fake_obs_spec, wrapped_env.observation_spec())
base_env.observation_spec.assert_called_once()
fake_action_spec = 'fake_action_spec'
base_env.action_spec.return_value = fake_action_spec
self.assertEqual(fake_action_spec, wrapped_env.action_spec())
base_env.action_spec.assert_called_once()
fake_raw_action = 'fake_raw_action'
type(base_env).raw_action = mock.PropertyMock(return_value=fake_raw_action)
self.assertEqual(fake_raw_action, wrapped_env.raw_action)
fake_raw_observation = 'fake_raw_observation'
type(base_env).raw_observation = mock.PropertyMock(
return_value=fake_raw_observation)
self.assertEqual(fake_raw_observation, wrapped_env.raw_observation)
load_request = state_pb2.LoadStateRequest(args={})
expected_response = state_pb2.LoadStateResponse(
status=state_pb2.LoadStateResponse.Status.OK
)
base_env.load_state.return_value = expected_response
self.assertEqual(wrapped_env.load_state(load_request), expected_response)
base_env.load_state.assert_called_once_with(load_request)
save_request = state_pb2.SaveStateRequest(args={})
expected_response = state_pb2.SaveStateResponse(
status=state_pb2.SaveStateResponse.Status.OK
)
base_env.save_state.return_value = expected_response
self.assertEqual(wrapped_env.save_state(save_request), expected_response)
base_env.save_state.assert_called_once_with(save_request)
wrapped_env.close()
base_env.close.assert_called_once()
fake_return_value = 'fake'
# AndroidEnv::some_random_function() does not exist and calling it should
# raise an AttributeError.
with self.assertRaises(AttributeError):
base_env.some_random_function.return_value = fake_return_value
def test_multiple_wrappers(self):
base_env = mock.create_autospec(env_interface.AndroidEnvInterface)
wrapped_env_1 = base_wrapper.BaseWrapper(base_env)
wrapped_env_2 = base_wrapper.BaseWrapper(wrapped_env_1)
wrapped_env_2.close()
base_env.close.assert_called_once()
def test_raw_env(self):
base_env = 'fake_env'
wrapped_env_1 = base_wrapper.BaseWrapper(base_env)
wrapped_env_2 = base_wrapper.BaseWrapper(wrapped_env_1)
self.assertEqual(base_env, wrapped_env_2.raw_env)
def test_stats(self):
base_env = mock.create_autospec(env_interface.AndroidEnvInterface)
wrapped_env = base_wrapper.BaseWrapper(base_env)
base_stats = {'base': 'stats'}
base_env.stats.return_value = base_stats
self.assertEqual(base_stats, wrapped_env.stats())
@mock.patch.object(logging, 'info')
def test_wrapped_stats(self, mock_info):
base_env = mock.create_autospec(env_interface.AndroidEnvInterface)
class LoggingWrapper1(base_wrapper.BaseWrapper):
def _wrapper_stats(self):
return {
'wrapper1': 'stats',
'shared': 1,
}
class LoggingWrapper2(base_wrapper.BaseWrapper):
def _wrapper_stats(self):
return {
'wrapper2': 'stats',
'shared': 2,
}
wrapped_env = LoggingWrapper2(LoggingWrapper1(base_env))
mock_info.assert_has_calls([
mock.call('Wrapping with %s', 'LoggingWrapper1'),
mock.call('Wrapping with %s', 'LoggingWrapper2'),
])
base_stats = {'base': 'stats'}
base_env.stats.return_value = base_stats
expected_stats = {
'base': 'stats',
'wrapper1': 'stats',
'wrapper2': 'stats',
'shared': 2,
}
self.assertEqual(expected_stats, wrapped_env.stats())
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/base_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tap_action_wrapper."""
from unittest import mock
from absl.testing import absltest
from android_env import env_interface
from android_env.components import action_type
from android_env.wrappers import tap_action_wrapper
import dm_env
from dm_env import specs
import numpy as np
ActionType = action_type.ActionType
def _make_array_spec(shape, dtype, name):
return specs.BoundedArray(
name=name,
shape=shape,
dtype=dtype,
minimum=np.zeros(shape),
maximum=np.ones(shape), # maximum is inclusive.
)
class TapActionWrapperTest(absltest.TestCase):
def setUp(self):
super().setUp()
self._base_action_spec = {
'action_type': specs.DiscreteArray(
num_values=3, name='action_type'),
'touch_position': _make_array_spec(
shape=(2,), dtype=np.float32, name='touch_position'),
}
self.base_env = mock.create_autospec(env_interface.AndroidEnvInterface)
self.base_env.action_spec.return_value = self._base_action_spec
def test_process_action_repeat(self):
wrapped_env = tap_action_wrapper.TapActionWrapper(
self.base_env, num_frames=3)
action = {
'action_type': np.array(ActionType.REPEAT, dtype=np.int32),
'touch_position': np.array([0.5, 0.5], dtype=np.float32)
}
actions = wrapped_env._process_action(action)
self.assertLen(actions, wrapped_env._num_frames + 1)
self.assertEqual(action, actions[-1])
def test_process_action_lift(self):
wrapped_env = tap_action_wrapper.TapActionWrapper(
self.base_env, num_frames=3)
action = {
'action_type': np.array(ActionType.LIFT, dtype=np.int32),
'touch_position': np.array([0.5, 0.5], dtype=np.float32)
}
actions = wrapped_env._process_action(action)
self.assertLen(actions, wrapped_env._num_frames + 1)
self.assertEqual(action, actions[-1])
def test_process_action_touch(self):
wrapped_env = tap_action_wrapper.TapActionWrapper(
self.base_env, num_frames=3)
action = {
'action_type': np.array(ActionType.TOUCH, dtype=np.int32),
'touch_position': np.array([0.5, 0.5], dtype=np.float32)
}
actions = wrapped_env._process_action(action)
self.assertLen(actions, wrapped_env._num_frames + 1)
self.assertEqual(actions[-1]['action_type'], np.array(ActionType.LIFT))
def test_reset(self):
wrapped_env = tap_action_wrapper.TapActionWrapper(
self.base_env, num_frames=5)
fake_timestep = 'ts'
self.base_env.reset.return_value = fake_timestep
ts = wrapped_env.reset()
self.base_env.reset.assert_called_once()
self.assertEqual(fake_timestep, ts)
def test_step(self):
wrapped_env = tap_action_wrapper.TapActionWrapper(
self.base_env, num_frames=5)
fake_timestep = dm_env.TimeStep(
step_type='fake_type',
reward=0.0,
discount=1.0,
observation='fake_obs')
self.base_env.step.return_value = fake_timestep
ts = wrapped_env.step({
'action_type': np.array(ActionType.REPEAT, dtype=np.int32),
'touch_position': np.array([0.5, 0.5], dtype=np.float32)
})
self.assertEqual(wrapped_env._num_frames+1, self.base_env.step.call_count)
self.assertIsInstance(ts, dm_env.TimeStep)
self.assertEqual(wrapped_env._env_steps, 6)
def test_observation_spec(self):
wrapped_env = tap_action_wrapper.TapActionWrapper(
self.base_env, num_frames=5)
fake_obs_spec = 'fake_obs_spec'
self.base_env.observation_spec.return_value = fake_obs_spec
observation_spec = wrapped_env.observation_spec()
self.base_env.observation_spec.assert_called_once()
self.assertEqual(fake_obs_spec, observation_spec)
def test_action_spec(self):
wrapped_env = tap_action_wrapper.TapActionWrapper(
self.base_env, num_frames=5)
self.base_env.action_spec.return_value = self._base_action_spec
action_spec = wrapped_env.action_spec()
self.base_env.action_spec.assert_called()
self.assertEqual(self.base_env.action_spec(),
action_spec)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/tap_action_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.wrappers.image_rescale_wrapper."""
from typing import Any
from unittest import mock
from absl.testing import absltest
from android_env import env_interface
from android_env.wrappers import image_rescale_wrapper
import dm_env
from dm_env import specs
import numpy as np
def _simple_spec():
return specs.BoundedArray(
shape=np.array([300, 300, 3]),
dtype=np.uint8,
name='pixels',
minimum=0,
maximum=255)
def _simple_timestep():
observation = np.ones(shape=[300, 300, 3])
return dm_env.TimeStep(
step_type=dm_env.StepType.MID,
reward=3.14,
discount=0.9,
observation={'pixels': observation})
class ImageRescaleWrapperTest(absltest.TestCase):
def test_100x50_grayscale(self):
fake_timestep = _simple_timestep()
fake_env = mock.create_autospec(env_interface.AndroidEnvInterface)
fake_env.observation_spec.return_value = {'pixels': _simple_spec()}
fake_env.reset.return_value = fake_timestep
fake_env.step.return_value = fake_timestep
wrapper = image_rescale_wrapper.ImageRescaleWrapper(
fake_env, zoom_factors=(1.0 / 3, 1.0 / 6.0), grayscale=True)
self.assertIsNotNone(wrapper)
self.assertEqual(wrapper.observation_spec()['pixels'].shape, (100, 50, 1))
reset_timestep = wrapper.reset()
reset_image = reset_timestep.observation['pixels']
self.assertEqual(reset_image.shape, (100, 50, 1))
step_timestep = wrapper.step(action='fake_action')
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (100, 50, 1))
def test_150x60_full_channels(self):
fake_timestep = _simple_timestep()
fake_env = mock.create_autospec(env_interface.AndroidEnvInterface)
fake_env.observation_spec.return_value = {'pixels': _simple_spec()}
fake_env.reset.return_value = fake_timestep
fake_env.step.return_value = fake_timestep
wrapper = image_rescale_wrapper.ImageRescaleWrapper(
fake_env, zoom_factors=(1.0 / 2.0, 1.0 / 5.0))
self.assertIsNotNone(wrapper)
self.assertEqual(wrapper.observation_spec()['pixels'].shape, (150, 60, 3))
reset_timestep = wrapper.reset()
reset_image = reset_timestep.observation['pixels']
self.assertEqual(reset_image.shape, (150, 60, 3))
step_timestep = wrapper.step(action='fake_action')
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (150, 60, 3))
def test_list_zoom_factor(self):
fake_timestep = _simple_timestep()
fake_env = mock.create_autospec(env_interface.AndroidEnvInterface)
fake_env.observation_spec.return_value = {'pixels': _simple_spec()}
fake_env.reset.return_value = fake_timestep
fake_env.step.return_value = fake_timestep
wrapper = image_rescale_wrapper.ImageRescaleWrapper(
fake_env, zoom_factors=[0.5, 0.2])
self.assertIsNotNone(wrapper)
self.assertEqual(wrapper.observation_spec()['pixels'].shape, (150, 60, 3))
reset_timestep = wrapper.reset()
reset_image = reset_timestep.observation['pixels']
self.assertEqual(reset_image.shape, (150, 60, 3))
step_timestep = wrapper.step(action='fake_action')
step_image = step_timestep.observation['pixels']
self.assertEqual(step_image.shape, (150, 60, 3))
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/wrappers/image_rescale_wrapper_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| android_env-main | android_env/proto/__init__.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Base specs for AndroidEnv."""
from android_env.components import action_type
from android_env.proto import task_pb2
from dm_env import specs
import numpy as np
_PROTO_DTYPE_TO_NUMPY_DTYPE = {
task_pb2.ArraySpec.DataType.FLOAT: np.float32,
task_pb2.ArraySpec.DataType.DOUBLE: np.float64,
task_pb2.ArraySpec.DataType.INT8: np.int8,
task_pb2.ArraySpec.DataType.INT16: np.int16,
task_pb2.ArraySpec.DataType.INT32: np.int32,
task_pb2.ArraySpec.DataType.INT64: np.int64,
task_pb2.ArraySpec.DataType.UINT8: np.uint8,
task_pb2.ArraySpec.DataType.UINT16: np.uint16,
task_pb2.ArraySpec.DataType.UINT32: np.uint32,
task_pb2.ArraySpec.DataType.UINT64: np.uint64,
task_pb2.ArraySpec.DataType.BOOL: np.bool_,
task_pb2.ArraySpec.DataType.STRING_U1: np.dtype(('U1')),
task_pb2.ArraySpec.DataType.STRING_U16: np.dtype(('<U16')),
task_pb2.ArraySpec.DataType.STRING_U25: np.dtype(('<U25')),
task_pb2.ArraySpec.DataType.STRING_U250: np.dtype(('<U250')),
task_pb2.ArraySpec.DataType.STRING: np.dtype(('<U0')),
task_pb2.ArraySpec.DataType.OBJECT: np.dtype('O'),
}
def base_action_spec(
num_fingers: int = 1, enable_key_events: bool = False
) -> dict[str, specs.Array]:
"""Default action spec for AndroidEnv.
Args:
num_fingers: Number of virtual fingers of the agent.
enable_key_events: Whether keyboard key events are enabled.
Returns:
A dict of action specs, each item corresponding to a virtual finger.
action_type: An integer of type ActionType: TOUCH=0, LIFT=1, REPEAT=2
touch_position: Position [x, y] of the touch action, where x, y are float
values between 0.0 and 1.0 corresponding to the relative position on the
screen. IGNORED when (action_type != ActionType.TOUCH).
keycode: code representing the desired key press in XKB format. See the
emulator_controller_pb2 for details.
action_type_i: Action type for additional fingers (i>1).
touch_position_i: Touch position for additional fingers (i>1).
"""
num_actions = len(action_type.ActionType) if enable_key_events else 3
action_spec = {
'action_type':
specs.DiscreteArray(num_values=num_actions, name='action_type'),
'touch_position':
specs.BoundedArray(
shape=(2,),
dtype=np.float32,
minimum=[0.0, 0.0],
maximum=[1.0, 1.0],
name='touch_position'),
}
for i in range(2, num_fingers + 1):
action_spec.update({
f'action_type_{i}':
specs.DiscreteArray(
num_values=len(action_type.ActionType),
name=f'action_type_{i}'),
f'touch_position_{i}':
specs.BoundedArray(
shape=(2,),
dtype=np.float32,
minimum=[0.0, 0.0],
maximum=[1.0, 1.0],
name=f'touch_position_{i}'),
})
if enable_key_events:
action_spec['keycode'] = specs.DiscreteArray(
num_values=(1 << 16) - 1, name='keycode')
return action_spec
def base_observation_spec(height: int, width: int) -> dict[str, specs.Array]:
"""Default observation spec for AndroidEnv.
Args:
height: Height of the device screen in pixels.
width: Width of the device screen in pixels.
Returns:
pixels: Spec for the RGB screenshot of the device. Has shape (H, W, 3)
timedelta: Spec for time delta since the last observation (in microseconds).
The first timestep immediately after reset() will have this value set to
0.
orientation: Spec for the latest orientation in a one-hot representation:
[1, 0, 0, 0]: PORTRAIT (0 degrees)
[0, 1, 0, 0]: LANDSCAPE (90 degrees clockwise)
[0, 0, 1, 0]: PORTRAIT (180 degrees) ("upside down")
[0, 0, 0, 1]: LANDSCAPE (270 degrees clockwise)
"""
return {
'pixels':
specs.BoundedArray(
shape=(height, width, 3),
dtype=np.uint8,
name='pixels',
minimum=0,
maximum=255),
'timedelta':
specs.Array(shape=(), dtype=np.int64, name='timedelta'),
'orientation':
specs.BoundedArray(
shape=np.array([4]),
dtype=np.uint8,
name='orientation',
minimum=0,
maximum=1),
}
| android_env-main | android_env/components/specs.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A class that launches a thread to read Android log outputs."""
import re
import threading
# `typing.Pattern` has been deprecated in Python 3.9 in favor of `re.Pattern`,
# but it is not available even in slightly older Python versions.
# Please see https://www.python.org/dev/peps/pep-0585/
from typing import Callable, Match, NamedTuple, Pattern
from absl import logging
from android_env.components import log_stream as log_stream_lib
class EventListener(NamedTuple):
regexp: Pattern[str]
handler_fn: Callable[[Pattern[str], Match[str]], None]
class LogcatThread:
"""Reads log entries in a separate thread."""
def __init__(self, log_stream: log_stream_lib.LogStream):
"""Initializes this LogcatThread with optional filters.
Please see https://developer.android.com/studio/command-line/logcat for more
info on `logcat`.
Args:
log_stream: Stream of logs from simulator.
"""
self._log_stream = log_stream
self._listeners = {}
self._line_ready = threading.Event()
self._line_ready.set()
self._should_stop = threading.Event()
self._thread = threading.Thread(target=self._process_logs)
self._thread.daemon = True
self._thread.start()
def add_event_listener(self, event_listener: EventListener) -> None:
"""Adds `fn` to the list of handlers to call when `event` occurs."""
event_regexp = event_listener.regexp
if event_regexp not in self._listeners:
self._listeners[event_regexp] = []
self._listeners[event_regexp].append(event_listener.handler_fn)
def remove_event_listener(self, event_listener: EventListener) -> None:
"""Removes `fn` from the list of handlers to call when `event` occurs."""
event_regexp = event_listener.regexp
if event_regexp not in self._listeners:
logging.error('Event: %r is not registered.', event_regexp)
return
self._listeners[event_regexp].remove(event_listener.handler_fn)
def line_ready(self) -> threading.Event:
"""Indicates whether all listeners have been notified for a given line."""
return self._line_ready
def pause(self):
self._log_stream.pause_stream()
def resume(self):
self._log_stream.resume_stream()
def kill(self):
self._should_stop.set()
self._log_stream.stop_stream()
self._thread.join(timeout=3.0)
def _process_logs(self) -> None:
"""A loop that runs until `self._should_stop` is set()."""
# pylint: disable=g-line-too-long
# Format is: "TIME_SEC PID TID PRIORITY TAG: MESSAGE"
#
# Example:
# ' 1553110400.424 5583 5658 D NostalgicRacer: com.google.example.games.nostalgicracer.views.renderers.OpenGLRenderDriver@912fb8.onSurfaceChanged 480x320' #
# pylint: enable=g-line-too-long
logline_regexp = r"""
^ # Beginning of the line.
[ ]+(?P<timestamp>[0-9]+\.[0-9]+) # Spaces and a float.
[ ]+(?P<pid>[0-9]+) # Spaces and an int.
[ ]+(?P<tid>[0-9]+) # Spaces and an int.
[ ]+(?P<priority>.) # Spaces and any single character.
[ ]+(?P<tag>[^:]*): # Spaces and any char that's not ':'.
[ ](?P<message>.*)$ # The actual log message.
"""
logline_re = re.compile(logline_regexp, re.VERBOSE)
for line in self._log_stream.get_stream_output():
if self._should_stop.is_set():
break
if not line: # Skip empty lines.
continue
matches = logline_re.match(line)
if not matches or len(matches.groups()) != 6:
continue
# Make sure that values are not read until all listeners are notified.
self._line_ready.clear()
# We're currently only consuming `message`, but we may use the other
# fields in the future.
content = matches.group('message')
for ev, listeners in self._listeners.items():
ev_matches = ev.match(content)
if ev_matches:
for listener in listeners: # Notify listeners.
listener(ev, ev_matches)
self._line_ready.set() # Allow consumers to read values.
| android_env-main | android_env/components/logcat_thread.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for adb_log_stream."""
import subprocess
from unittest import mock
from absl.testing import absltest
from android_env.components import adb_log_stream
class FakeAdbSubprocess:
@property
def stdout(self):
return [f'line_{i}' for i in range(100)]
def kill(self):
pass
class AdbLogStreamTest(absltest.TestCase):
@mock.patch.object(subprocess, 'check_output', return_value=b'')
@mock.patch.object(subprocess, 'Popen', return_value=FakeAdbSubprocess())
def test_get_stream_output(self, mock_popen, unused_mock_check_output):
stream = adb_log_stream.AdbLogStream(adb_command_prefix=['foo'])
stream.set_log_filters(['bar'])
stream_output = stream.get_stream_output()
for i, line in enumerate(stream_output):
self.assertEqual(line, f'line_{i}')
mock_popen.assert_called_with(
['foo', 'logcat', '-v', 'epoch', 'bar', '*:S'],
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
bufsize=1,
universal_newlines=True)
def test_stop_stream_before_get_stream_output(self):
"""Calling `stop_stream()` before `get_stream_output()` should not crash."""
# Arrange.
stream = adb_log_stream.AdbLogStream(adb_command_prefix=['foo'])
# Act.
stream.stop_stream()
# Assert.
# Nothing to assert. The test should just finish without raising an
# exception.
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/adb_log_stream_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Coordinator handles interaction between internal components of AndroidEnv."""
import copy
import socket
import tempfile
import threading
import time
from typing import Any
from absl import logging
from android_env.components import action_type as action_type_lib
from android_env.components import adb_call_parser
from android_env.components import errors
from android_env.components import specs
from android_env.components import task_manager as task_manager_lib
from android_env.components import utils
from android_env.components.simulators import base_simulator
from android_env.proto import adb_pb2
from android_env.proto import state_pb2
from android_env.proto import task_pb2
import dm_env
import numpy as np
class Coordinator:
"""Handles interaction between internal components of AndroidEnv."""
def __init__(
self,
simulator: base_simulator.BaseSimulator,
task_manager: task_manager_lib.TaskManager,
num_fingers: int = 1,
interaction_rate_sec: float = 0.0,
enable_key_events: bool = False,
show_touches: bool = True,
show_pointer_location: bool = True,
show_status_bar: bool = False,
show_navigation_bar: bool = False,
periodic_restart_time_min: float = 0.0,
tmp_dir: str | None = None,
):
"""Handles communication between AndroidEnv and its components.
Args:
simulator: A BaseSimulator instance.
task_manager: The TaskManager, responsible for coordinating RL tasks.
num_fingers: Number of virtual fingers of the agent.
interaction_rate_sec: How often (in seconds) to fetch the screenshot from
the simulator (asynchronously). If <= 0, stepping the environment blocks
on fetching the screenshot (the environment is synchronous). If > 0,
screenshots are grabbed in a separate thread at this rate; stepping
returns the most recently grabbed screenshot.
enable_key_events: Whether keyboard key events are enabled.
show_touches: Whether to show circles on the screen indicating the
position of the current touch.
show_pointer_location: Whether to show blue lines on the screen indicating
the position of the current touch.
show_status_bar: Whether or not to show the status bar (at the top of the
screen, displays battery life, time, notifications etc.).
show_navigation_bar: Whether or not to show the navigation bar (at the
bottom of the screen, displayes BACK and HOME buttons, etc.)
periodic_restart_time_min: Time between periodic restarts in minutes. If >
0.0, will trigger a simulator restart at the end of the next episode
once the time has been reached.
tmp_dir: Temporary directory to write transient data.
"""
self._simulator = simulator
self._task_manager = task_manager
self._num_fingers = num_fingers
self._enable_key_events = enable_key_events
self._show_touches = show_touches
self._show_pointer_location = show_pointer_location
self._show_status_bar = show_status_bar
self._show_navigation_bar = show_navigation_bar
self._adb_call_parser: adb_call_parser.AdbCallParser = None
self._periodic_restart_time_min = periodic_restart_time_min
self._tmp_dir = tmp_dir or tempfile.gettempdir()
self._orientation = np.zeros(4, dtype=np.uint8)
self._interaction_rate_sec = interaction_rate_sec
self._interaction_thread = None
# The size of the device screen in pixels (H x W).
self._screen_size = np.array([0, 0], dtype=np.int32)
# Initialize stats.
self._stats = {
'relaunch_count': 0,
'relaunch_count_periodic': 0,
'relaunch_count_setup_steps': 0,
'relaunch_count_reset_steps': 0,
'relaunch_count_simulator_launch': 0,
'relaunch_count_simulator_reset': 0,
'relaunch_count_execute_action': 0,
'relaunch_count_fetch_observation': 0,
'relaunch_count_update_settings': 0,
'failed_task_updates': 0,
}
# Initialize counters.
self._simulator_healthy = False
self._latest_observation_time = 0
self._simulator_start_time = None
logging.info('Starting the simulator...')
self._launch_simulator()
def action_spec(self) -> dict[str, dm_env.specs.Array]:
return specs.base_action_spec(
num_fingers=self._num_fingers,
enable_key_events=self._enable_key_events)
def observation_spec(self) -> dict[str, dm_env.specs.Array]:
return specs.base_observation_spec(
height=self._screen_size[0], width=self._screen_size[1])
def _update_screen_size(self) -> None:
"""Sets the screen size from a screenshot ignoring the color channel."""
screenshot = self._simulator.get_screenshot()
self._screen_size = np.array(screenshot.shape[:2], dtype=np.int32)
def _update_device_orientation(self) -> None:
"""Updates the current device orientation."""
# Skip fetching the orientation if we already have it.
if not np.all(self._orientation == np.zeros(4)):
logging.info('self._orientation already set, not setting it again')
return
orientation_response = self._adb_call_parser.parse(
adb_pb2.AdbRequest(
get_orientation=adb_pb2.AdbRequest.GetOrientationRequest()))
if orientation_response.status != adb_pb2.AdbResponse.Status.OK:
logging.error('Got bad orientation: %r', orientation_response)
return
orientation = orientation_response.get_orientation.orientation
if orientation not in {0, 1, 2, 3}:
logging.error('Got bad orientation: %r', orientation_response)
return
# Transform into one-hot format.
orientation_onehot = np.zeros([4], dtype=np.uint8)
orientation_onehot[orientation] = 1
self._orientation = orientation_onehot
def _lift_all_fingers(self) -> None:
"""Performs a lift action with every finger."""
lift_action = {
'action_type': np.array(action_type_lib.ActionType.LIFT),
'touch_position': np.array([0, 0]),
}
for i in range(2, self._num_fingers + 1):
lift_action.update({
f'action_type_{i}': np.array(action_type_lib.ActionType.LIFT),
f'touch_position_{i}': np.array([0, 0]),
})
self._send_action_to_simulator(lift_action)
def _should_periodic_relaunch(self) -> bool:
"""Checks if it is time to restart the simulator.
If a periodic restart time was specified, the Coordinator will re-launch
the simulator at regular time intervals. This helps to make sure that the
simulator is not in a stale state even if the environment has been running
for a significant amount of time.
Returns:
Boolean indicating if it is time to restart the simulator.
"""
if self._periodic_restart_time_min and self._simulator_start_time:
sim_alive_time = (time.time() - self._simulator_start_time) / 60.0
logging.info('Simulator has been running for %f mins', sim_alive_time)
if sim_alive_time > self._periodic_restart_time_min:
logging.info('Maximum alive time reached. Restarting simulator.')
self._stats['relaunch_count_periodic'] += 1
return True
return False
def _launch_simulator(self, max_retries: int = 3):
"""Launches the simulator.
Sets up the simulator and other task-related settings.
Args:
max_retries: Number of times to attempt a restart before raising an error.
"""
self._simulator_healthy = False
# Stop screenshot thread.
if self._interaction_thread is not None:
self._interaction_thread.stop()
self._interaction_thread.join()
# Attempt to restart the system a given number of times.
num_tries = 1
latest_error = None
while True:
if num_tries > max_retries:
raise errors.TooManyRestartsError(
'Maximum number of restart attempts reached.') from latest_error
logging.info('Simulator launch attempt %d of %d', num_tries, max_retries)
self._task_manager.stop()
# Launch the simulator.
self._simulator.launch()
self._simulator_start_time = time.time()
# From here on, the simulator is assumed to be up and running.
self._adb_call_parser = self._create_adb_call_parser()
try:
self._update_settings()
except errors.AdbControllerError as e:
logging.exception('_update_settings() failed.')
self._stats['relaunch_count_update_settings'] += 1
self._latest_error = e
num_tries += 1
continue
# Start the task.
self._task_manager.start(
adb_call_parser_factory=self._create_adb_call_parser,
log_stream=self._simulator.create_log_stream(),
)
try:
self._task_manager.setup_task()
except errors.StepCommandError as error:
logging.exception('Failed to set up the task. Restarting simulator.')
self._stats['relaunch_count_setup_steps'] += 1
latest_error = error
num_tries += 1
continue
# Restart was successful.
self._simulator_healthy = True
self._stats['relaunch_count'] += 1
break
if self._interaction_rate_sec > 0:
self._interaction_thread = InteractionThread(self._simulator,
self._interaction_rate_sec)
self._interaction_thread.start()
def _update_settings(self) -> None:
"""Updates some internal state and preferences given in the constructor."""
self._update_screen_size()
self._adb_call_parser.parse(
adb_pb2.AdbRequest(
settings=adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
put=adb_pb2.AdbRequest.SettingsRequest.Put(
key='show_touches',
value='1' if self._show_touches else '0'))))
self._adb_call_parser.parse(
adb_pb2.AdbRequest(
settings=adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
put=adb_pb2.AdbRequest.SettingsRequest.Put(
key='pointer_location',
value='1' if self._show_pointer_location else '0'))))
if self._show_navigation_bar and self._show_status_bar:
policy_control_value = 'null*'
elif self._show_navigation_bar and not self._show_status_bar:
policy_control_value = 'immersive.status=*'
elif not self._show_navigation_bar and self._show_status_bar:
policy_control_value = 'immersive.navigation=*'
else:
policy_control_value = 'immersive.full=*'
self._adb_call_parser.parse(
adb_pb2.AdbRequest(
settings=adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.GLOBAL,
put=adb_pb2.AdbRequest.SettingsRequest.Put(
key='policy_control', value=policy_control_value))))
def _create_adb_call_parser(self):
"""Creates a new AdbCallParser instance."""
return adb_call_parser.AdbCallParser(
adb_controller=self._simulator.create_adb_controller(),
tmp_dir=self._tmp_dir)
def execute_adb_call(self, call: adb_pb2.AdbRequest) -> adb_pb2.AdbResponse:
return self._adb_call_parser.parse(call)
def rl_reset(self) -> dm_env.TimeStep:
"""Resets the RL episode."""
# Relaunch the simulator if necessary.
if not self._simulator_healthy or self._should_periodic_relaunch():
self._launch_simulator()
# Reset counters.
self._latest_observation_time = 0
for key in self._stats:
if key.startswith('episode'):
self._stats[key] = 0.0
# Execute a lift action before resetting the task.
self._lift_all_fingers()
# Reset the task.
self._task_manager.reset_task()
self._update_device_orientation()
# Get data from the simulator.
simulator_signals = self._gather_simulator_signals()
return self._task_manager.rl_reset(simulator_signals)
def rl_step(self, agent_action: dict[str, np.ndarray]) -> dm_env.TimeStep:
"""Executes the selected action and returns a timestep.
Args:
agent_action: Selected action to perform on the simulated Android device.
If `agent_action` is `None` it means that this is an RL reset (to start
a new episode).
Returns:
An RL timestep.
"""
self._send_action_to_simulator(agent_action)
# Get data from the simulator.
try:
simulator_signals = self._gather_simulator_signals()
except (errors.ReadObservationError, socket.error):
logging.exception('Unable to fetch observation. Restarting simulator.')
self._stats['relaunch_count_fetch_observation'] += 1
self._simulator_healthy = False
if not self._simulator_healthy:
return dm_env.truncation(reward=0.0, observation=None)
return self._task_manager.rl_step(simulator_signals)
def _gather_simulator_signals(self) -> dict[str, np.ndarray]:
"""Gathers data from various sources to assemble the RL observation."""
# Get current timestamp and update the delta.
now = time.time()
timestamp_delta = (0 if self._latest_observation_time == 0 else
(now - self._latest_observation_time) * 1e6)
self._latest_observation_time = now
# Grab pixels.
if self._interaction_rate_sec > 0:
pixels = self._interaction_thread.screenshot() # Async mode.
else:
pixels = self._simulator.get_screenshot() # Sync mode.
return {
'pixels': pixels,
'orientation': self._orientation,
'timedelta': np.array(timestamp_delta, dtype=np.int64),
}
def __del__(self):
self.close()
def _send_action_to_simulator(self, action: dict[str, np.ndarray]) -> None:
"""Sends the selected action to the simulator.
The simulator will interpret the action as a touchscreen event and perform
it accordingly. The effect this action triggers in the Android OS will be
determined by the currently running application.
Args:
action: action which will get interpreted as a touchscreen event.
"""
try:
match action['action_type']:
# If the action is a TOUCH or LIFT, send a touch event to the simulator.
case action_type_lib.ActionType.TOUCH | action_type_lib.ActionType.LIFT:
prepared_action = self._prepare_touch_action(action)
self._simulator.send_touch(prepared_action)
# If the action is a key event, send a key event to the simulator.
case action_type_lib.ActionType.KEYDOWN:
self._simulator.send_key(
action['keycode'].item(0), event_type='keydown'
)
case action_type_lib.ActionType.KEYUP:
self._simulator.send_key(
action['keycode'].item(0), event_type='keyup'
)
case action_type_lib.ActionType.KEYPRESS:
self._simulator.send_key(
action['keycode'].item(0), event_type='keypress'
)
except (socket.error, errors.SendActionError):
logging.exception('Unable to execute action. Restarting simulator.')
self._stats['relaunch_count_execute_action'] += 1
self._simulator_healthy = False
def _prepare_touch_action(
self, action: dict[str, np.ndarray]
) -> list[tuple[int, int, bool, int]]:
"""Turns an AndroidEnv action into values that the simulator can interpret.
Converts float-valued 'touch_position' to integer coordinates corresponding
to specific pixels, and 'action_type' to booleans indicating whether the
screen is touched at said location or not. The result of this function can
be sent directly to the underlying simulator (e.g. the Android Emulator,
virtual machine, or a phone).
Args:
action: An action containing 'action_type' and 'touch_position'.
Returns:
A tuple with the format (x: int, y: int, down/up: bool).
"""
touch_events = []
width_height = self._screen_size[::-1]
for i, finger_action in enumerate(self._split_touch_action(action)):
is_touch = (
finger_action['action_type'] == action_type_lib.ActionType.TOUCH)
touch_position = finger_action['touch_position']
touch_pixels = utils.touch_position_to_pixel_position(
touch_position, width_height=width_height)
touch_events.append((touch_pixels[0], touch_pixels[1], is_touch, i))
return touch_events
def _split_touch_action(
self, action: dict[str, np.ndarray]
) -> list[dict[str, np.ndarray]]:
"""Splits a multitouch action into a list of single-touch actions."""
single_touch_actions = [{
'action_type': action['action_type'],
'touch_position': action['touch_position'],
}]
for i in range(2, self._num_fingers + 1):
single_touch_actions.append({
'action_type': action[f'action_type_{i}'],
'touch_position': action[f'touch_position_{i}'],
})
return single_touch_actions
def _get_time_since_last_observation(self) -> float:
"""Computes time passed since the last observation was fetched."""
return time.time() - self._latest_observation_time
def stats(self) -> dict[str, Any]:
"""Returns various statistics."""
output = copy.deepcopy(self._stats)
output.update(self._task_manager.stats())
return output
def load_state(
self, request: state_pb2.LoadStateRequest
) -> state_pb2.LoadStateResponse:
"""Loads a state.
Args:
request: A `LoadStateRequest` containing any parameters necessary to
specify how/what state to load.
Returns:
A `LoadStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
self._task_manager.stop()
response = self._simulator.load_state(request)
self._task_manager.start(
adb_call_parser_factory=self._create_adb_call_parser,
log_stream=self._simulator.create_log_stream(),
)
return response
def save_state(
self, request: state_pb2.SaveStateRequest
) -> state_pb2.SaveStateResponse:
"""Saves a state.
Args:
request: A `SaveStateRequest` containing any parameters necessary to
specify how/what state to save.
Returns:
A `SaveStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
return self._simulator.save_state(request)
def close(self):
"""Cleans up the state of this Coordinator."""
if self._interaction_thread is not None:
self._interaction_thread.stop()
self._interaction_thread.join()
if hasattr(self, '_task_manager'):
self._task_manager.stop()
if hasattr(self, '_simulator'):
self._simulator.close()
class InteractionThread(threading.Thread):
"""A thread that interacts with a simulator."""
def __init__(self, simulator: base_simulator.BaseSimulator,
interaction_rate_sec: float):
super().__init__()
self._simulator = simulator
self._interaction_rate_sec = interaction_rate_sec
self._should_stop = threading.Event()
self._screenshot = self._simulator.get_screenshot()
def run(self):
last_read = time.time()
while not self._should_stop.is_set():
self._screenshot = self._simulator.get_screenshot()
now = time.time()
elapsed = now - last_read
last_read = now
sleep_time = self._interaction_rate_sec - elapsed
if sleep_time > 0.0:
time.sleep(sleep_time)
logging.info('InteractionThread.run() finished.')
def stop(self):
logging.info('Stopping InteractionThread.')
self._should_stop.set()
def screenshot(self):
return self._screenshot
| android_env-main | android_env/components/coordinator.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A class to manage and control an external ADB process."""
import os
import subprocess
import time
from absl import logging
from android_env.components import errors
class AdbController:
"""Manages communication with adb."""
def __init__(self,
device_name: str = '',
adb_path: str = 'adb',
adb_server_port: int = 5037,
default_timeout: float = 120.0):
"""Instantiates an AdbController object.
Args:
device_name: Name of the device to communicate with.
adb_path: Path to the adb binary.
adb_server_port: Port for adb server.
default_timeout: Default timeout in seconds.
"""
self._device_name = device_name
self._adb_path = os.path.expandvars(adb_path)
self._adb_server_port = str(adb_server_port)
self._default_timeout = default_timeout
logging.info('adb_path: %r', self._adb_path)
# Unset problematic environment variables. ADB commands will fail if these
# are set. They are normally exported by AndroidStudio.
if 'ANDROID_HOME' in os.environ:
del os.environ['ANDROID_HOME']
if 'ANDROID_ADB_SERVER_PORT' in os.environ:
del os.environ['ANDROID_ADB_SERVER_PORT']
# Explicitly expand the $HOME environment variable.
self._os_env_vars = dict(os.environ).copy()
self._os_env_vars.update(
{'HOME': os.path.expandvars(self._os_env_vars.get('HOME', ''))}
)
logging.info('self._os_env_vars: %r', self._os_env_vars)
def command_prefix(self, include_device_name: bool = True) -> list[str]:
"""The command for instantiating an adb client to this server."""
command_prefix = [self._adb_path, '-P', self._adb_server_port]
if include_device_name:
command_prefix.extend(['-s', self._device_name])
return command_prefix
def init_server(self, timeout: float | None = None):
"""Initialize the ADB server deamon on the given port.
This function should be called immediately after initializing the first
adb_controller, and before launching the simulator.
Args:
timeout: A timeout to use for this operation. If not set the default
timeout set on the constructor will be used.
"""
# Make an initial device-independent call to ADB to start the deamon.
self.execute_command(['devices'], timeout, device_specific=False)
time.sleep(0.2)
def _restart_server(self, timeout: float | None = None):
"""Kills and restarts the adb server.
Args:
timeout: A timeout to use for this operation. If not set the default
timeout set on the constructor will be used.
"""
logging.info('Restarting adb server.')
self.execute_command(
['kill-server'], timeout=timeout, device_specific=False)
time.sleep(0.2)
cmd_output = self.execute_command(
['start-server'], timeout=timeout, device_specific=False)
logging.info('start-server output: %r', cmd_output.decode('utf-8'))
time.sleep(2.0)
self.execute_command(
['devices'], timeout=timeout, device_specific=False)
time.sleep(0.2)
def execute_command(
self,
args: list[str],
timeout: float | None = None,
device_specific: bool = True,
) -> bytes:
"""Executes an adb command.
Args:
args: A list of strings representing each adb argument.
For example: ['install', '/my/app.apk']
timeout: A timeout to use for this operation. If not set the default
timeout set on the constructor will be used.
device_specific: Whether the call is device-specific or independent.
Returns:
The output of running such command as a binary string.
"""
timeout = self._default_timeout if timeout is None else timeout
command = self.command_prefix(include_device_name=device_specific) + args
command_str = 'adb ' + ' '.join(command[1:])
n_tries = 1
latest_error = None
while n_tries < 3:
try:
logging.info('Executing ADB command: [%s]', command_str)
cmd_output = subprocess.check_output(
command,
stderr=subprocess.STDOUT,
timeout=timeout,
env=self._os_env_vars,
)
logging.debug('ADB command output: %s', cmd_output)
return cmd_output
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
logging.exception(
'Failed to execute ADB command (try %r of 3): [%s]',
n_tries, command_str)
if e.stdout is not None:
logging.error('**stdout**:')
for line in e.stdout.splitlines():
logging.error(' %s', line)
if e.stderr is not None:
logging.error('**stderr**:')
for line in e.stderr.splitlines():
logging.error(' %s', line)
n_tries += 1
latest_error = e
if device_specific:
self._restart_server(timeout=timeout)
raise errors.AdbControllerError(
f'Error executing adb command: [{command_str}]\n'
f'Caused by: {latest_error}\n'
f'adb stdout: [{latest_error.stdout}]\n'
f'adb stderr: [{latest_error.stderr}]') from latest_error
| android_env-main | android_env/components/adb_controller.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Determines if the current app screen matches an expected app screen."""
import enum
import re
import time
from typing import Callable, Optional, Sequence, Pattern
from absl import logging
from android_env.components import adb_call_parser as adb_call_parser_lib
from android_env.components import errors
from android_env.proto import adb_pb2
from android_env.proto import task_pb2
class _DumpsysNode:
"""A node in a dumpsys tree."""
def __init__(self, data: str | None = None):
self._children = []
self._data = data
@property
def data(self) -> str:
return self._data
@property
def children(self) -> list['_DumpsysNode']:
return self._children
def find_child(
self, predicate: Callable[['_DumpsysNode'], bool], max_levels: int = 0
) -> Optional['_DumpsysNode']:
"""Returns the first direct child that matches `predicate`, None otherwise.
Args:
predicate: Function-like that accepts a _DumpsysNode and returns boolean.
max_levels: Maximum number of levels down the tree to search for a child.
If non-positive, only direct children will be searched for.
Returns:
A _DumpsysNode or None.
"""
if not self.children:
return None
try:
return next(x for x in self.children if predicate(x))
except StopIteration:
logging.info('Failed to find child. max_levels: %i.', max_levels)
# Search children.
if max_levels:
for child in self.children:
child_result = child.find_child(predicate, max_levels - 1)
if child_result is not None:
return child_result
return None
def __repr__(self):
return self._data
def print_tree(self, indent: int = 2):
"""Prints this tree in logging.info()."""
logging.info(' ' * indent + self.data)
for c in self.children:
c.print_tree(indent + 2)
def build_tree_from_dumpsys_output(dumpsys_output: str) -> _DumpsysNode:
"""Constructs a tree from a dumpsys string output.
Args:
dumpsys_output: string Verbatim output from adb dumpsys. The expected format
is a list where each line is a node and the indentation marks the
relationship with its parent or sibling.
Returns:
_DumpsysNode The root of the tree.
"""
lines = dumpsys_output.split('\n') # Split by lines.
lines = [x.rstrip(' \r') for x in lines]
lines = [x for x in lines if len(x)] # Remove empty lines.
root = _DumpsysNode('___root___') # The root of all nodes.
parents_stack = [root]
for line in lines:
stripped_line = line.lstrip(' ')
indent = len(line) - len(stripped_line) # Number of indent spaces.
new_node = _DumpsysNode(stripped_line) # Create a node without indentation.
parent = parents_stack.pop()
if parent.data == '___root___': # The root is an exception for indentation.
parent_indent = -2
else:
parent_indent = (len(parents_stack) - 1) * 2
if indent == parent_indent: # `new_node` is a sibiling.
parent = parents_stack.pop()
elif indent < parent_indent: # Indentation reduced (i.e. a block finished)
num_levels = (indent // 2) + 1
parents_stack = parents_stack[:num_levels]
parent = parents_stack.pop()
elif indent > parent_indent: # `new_node` is a child.
pass # No need to change the current parent.
parent.children.append(new_node)
parents_stack.append(parent)
parents_stack.append(new_node)
return root
def matches_path(dumpsys_activity_output: str,
expected_view_hierarchy_path: Sequence[Pattern[str]],
max_levels: int = 0) -> bool:
"""Returns True if the current dumpsys output matches the expected path.
Args:
dumpsys_activity_output: The output of running `dumpsys activity ...`.
expected_view_hierarchy_path: [regex] A list of regular expressions to be
tested at each level of the tree.
max_levels: How many levels to search from root for View Hierarchy.
Returns:
True if the dumpsys tree contains one path that matches all regexes.
"""
root = build_tree_from_dumpsys_output(dumpsys_activity_output)
# Find the View Hierarchy.
view_hierarchy = root.find_child(
lambda x: x.data.startswith('View Hierarchy'), max_levels)
if view_hierarchy is None:
logging.error(
'view_hierarchy is None. Dumpsys activity output: %s. tree: %r',
str(dumpsys_activity_output), root.print_tree())
logging.error('Tree root: %s', str(root))
return None
current_node = view_hierarchy
for i, regex in enumerate(expected_view_hierarchy_path):
def regex_predicate(node, expr=regex):
matches = expr.match(node.data)
return matches is not None
child = current_node.find_child(regex_predicate)
if child is None:
logging.error('Mismatched regex (%i, %s). current_node: %s', i,
regex.pattern, current_node)
logging.error('Dumpsys activity output: %s', str(dumpsys_activity_output))
logging.error('Tree root: %s', str(root))
return None
else:
current_node = child
return True
class AppScreenChecker:
"""Checks that the current app screen matches an expected screen."""
class Outcome(enum.IntEnum):
"""Possible return vales from checking the current app screen."""
# The current app screen matches the expected app screen.
SUCCESS = 0
# There's no activity to check.
EMPTY_EXPECTED_ACTIVITY = 1
# We were unable to determine the current activity.
FAILED_ACTIVITY_EXTRACTION = 2
# The current activity does not match the expected activity.
UNEXPECTED_ACTIVITY = 3
# The current view hierarchy does not match the expected view hierarchy.
UNEXPECTED_VIEW_HIERARCHY = 4
def __init__(self, adb_call_parser: adb_call_parser_lib.AdbCallParser,
expected_app_screen: task_pb2.AppScreen):
self._adb_call_parser = adb_call_parser
self._expected_app_screen = expected_app_screen
self._expected_activity = expected_app_screen.activity
self._expected_view_hierarchy_path = [
re.compile(regex) for regex in expected_app_screen.view_hierarchy_path
]
# Return type is AppScreenChecker.Outcome, but pytype doesn't understand that.
def matches_current_app_screen(self) -> enum.IntEnum:
"""Determines whether the current app screen matches `expected_app_screen`."""
if not self._expected_activity:
return AppScreenChecker.Outcome.EMPTY_EXPECTED_ACTIVITY
# Check if we are still on the expected Activity.
response = self._adb_call_parser.parse(
adb_pb2.AdbRequest(
get_current_activity=adb_pb2.AdbRequest.GetCurrentActivity()))
if response.status != adb_pb2.AdbResponse.OK:
return AppScreenChecker.Outcome.FAILED_ACTIVITY_EXTRACTION
current_activity = response.get_current_activity.full_activity
if current_activity != self._expected_activity:
logging.error('current_activity: %s, expected_activity: %s',
current_activity, self._expected_activity)
return AppScreenChecker.Outcome.UNEXPECTED_ACTIVITY
# Extract just the package name from the full activity name.
package_name = self._expected_activity.split('/')[0]
# Check if we are in the expected view hierarchy path.
if self._expected_view_hierarchy_path:
dumpsys_response = self._adb_call_parser.parse(
adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(
service='activity', args=[package_name, package_name])))
if dumpsys_response.status != adb_pb2.AdbResponse.OK:
return AppScreenChecker.Outcome.FAILED_ACTIVITY_EXTRACTION
if dumpsys_response.dumpsys.output:
if not matches_path(
dumpsys_response.dumpsys.output.decode('utf-8'),
self._expected_view_hierarchy_path,
max_levels=3):
return AppScreenChecker.Outcome.UNEXPECTED_VIEW_HIERARCHY
return AppScreenChecker.Outcome.SUCCESS
def wait_for_app_screen(self, timeout_sec: float) -> float:
"""Waits for `self._expected_app_screen` to be the current screen.
Args:
timeout_sec: Maximum total time to wait for the screen to pop up.
Returns:
The total amount of time in seconds spent waiting for the screen to pop
up.
Raises:
errors.WaitForAppScreenError if the screen does not pop up within
`timeout_sec`.
"""
logging.info('Waiting for app screen...')
start_time = time.time()
while time.time() - start_time < timeout_sec:
if self.matches_current_app_screen() == AppScreenChecker.Outcome.SUCCESS:
wait_time = time.time() - start_time
logging.info('Successfully waited for app screen in %r seconds: [%r]',
wait_time, self._expected_app_screen)
return wait_time
time.sleep(0.1)
wait_time = time.time() - start_time
logging.error('Failed to wait for app screen in %r seconds: [%r].',
wait_time, self._expected_app_screen)
raise errors.WaitForAppScreenError()
| android_env-main | android_env/components/app_screen_checker.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.task_manager.py."""
import json
from unittest import mock
from absl.testing import absltest
from android_env.components import adb_call_parser as adb_call_parser_lib
from android_env.components import dumpsys_thread
from android_env.components import log_stream
from android_env.components import logcat_thread
from android_env.components import setup_step_interpreter
from android_env.components import task_manager
from android_env.proto import task_pb2
import numpy as np
class TaskManagerTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.addCleanup(mock.patch.stopall) # Disable previous patches.
self._setup_step_interpreter = mock.create_autospec(
setup_step_interpreter.SetupStepInterpreter)
self._dumpsys_thread = mock.create_autospec(dumpsys_thread.DumpsysThread)
self._logcat_thread = mock.create_autospec(logcat_thread.LogcatThread)
self._log_stream = mock.create_autospec(log_stream.LogStream)
mock.patch.object(
setup_step_interpreter,
'SetupStepInterpreter',
return_value=self._setup_step_interpreter).start()
mock.patch.object(
dumpsys_thread, 'DumpsysThread',
return_value=self._dumpsys_thread).start()
mock.patch.object(
logcat_thread, 'LogcatThread',
return_value=self._logcat_thread).start()
mock.patch.object(
log_stream, 'LogStream',
return_value=self._log_stream).start()
def test_start(self):
task_mgr = task_manager.TaskManager(task=task_pb2.Task())
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
self.assertIsNotNone(task_mgr._logcat_thread)
self.assertIsNotNone(task_mgr._dumpsys_thread)
self.assertIsNotNone(task_mgr._setup_step_interpreter)
def test_setup_task(self):
task_mgr = task_manager.TaskManager(task=task_pb2.Task())
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
self._setup_step_interpreter.interpret.assert_called_once()
def test_step_count(self):
task_mgr = task_manager.TaskManager(task=task_pb2.Task())
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
task_mgr.rl_reset(observation={})
self.assertEqual(task_mgr.stats()['episode_steps'], 0)
task_mgr.rl_step(observation={})
self.assertEqual(task_mgr.stats()['episode_steps'], 1)
task_mgr.rl_step(observation={})
self.assertEqual(task_mgr.stats()['episode_steps'], 2)
task_mgr.rl_reset(observation={})
self.assertEqual(task_mgr.stats()['episode_steps'], 0)
def test_get_current_reward(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
match = event_listener.regexp.match('Reward: 123.0')
if match is None: # Ignore events that are not rewards.
return
event_listener.handler_fn(event_listener.regexp, match)
task = task_pb2.Task()
task.log_parsing_config.log_regexps.reward.extend([
'^[Rr]eward: ([-+]?[0-9]*\\.?[0-9]*)$'
])
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
self.assertEqual(timestep.reward, 123.0)
np.testing.assert_equal(timestep.observation['pixels'], np.array([1, 2, 3]))
def test_reward_event(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
match_1 = event_listener.regexp.match('foo_1')
match_2 = event_listener.regexp.match('foo_2')
match_3 = event_listener.regexp.match('Reward: 2.0')
if match_1:
event_listener.handler_fn(event_listener.regexp, match_1)
if match_2:
event_listener.handler_fn(event_listener.regexp, match_2)
if match_3:
event_listener.handler_fn(event_listener.regexp, match_3)
task = task_pb2.Task()
reward_event_1 = task_pb2.LogParsingConfig.LogRegexps.RewardEvent(
event='foo_1', reward=5.0)
reward_event_2 = task_pb2.LogParsingConfig.LogRegexps.RewardEvent(
event='foo_2', reward=-1.0)
task.log_parsing_config.log_regexps.reward_event.extend(
[reward_event_1, reward_event_2])
task.log_parsing_config.log_regexps.reward.extend(
['^[Rr]eward: ([-+]?[0-9]*\\.?[0-9]*)$'])
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
self.assertEqual(timestep.reward, 6.0)
def test_get_current_reward_via_score(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
event = event_listener.regexp
match = event.match('score: 200.0')
if match is None: # Ignore events that are not scores.
return
event_listener.handler_fn(event, match)
# Scores are accumulated by their differences, so a subsequent lower score
# means that the final reward decreases.
match = event.match('score: 185')
event_listener.handler_fn(event, match)
task = task_pb2.Task()
task.log_parsing_config.log_regexps.score = (
'^score: ([-+]?[0-9]*\\.?[0-9]*)$')
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
self.assertEqual(timestep.reward, 185.0)
def test_get_current_extras(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
event = event_listener.regexp
match = event.match('extra: some_extra [1, 2]')
if match is None: # Ignore events that are not extras.
return
# Emit events.
fn = event_listener.handler_fn
fn(event, event.match('extra: an_extra [1, 2, 3]'))
fn(event, event.match('extra: an_extra [4, 5, 6]'))
fn(event, event.match('extra: another_extra 0.5'))
fn(event, event.match('extra: multi_dimension_extra [[9,8,7],[6,5,4]]'))
fn(event, event.match('extra: boolean_extra'))
# Setup the task and trigger the listener.
task = task_pb2.Task()
task.log_parsing_config.log_regexps.extra.extend([
'^extra: (?P<name>[^ ]*)[ ]?(?P<extra>.*)$'
])
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
# Check expectations.
self.assertIn('extras', timestep.observation)
extras = timestep.observation['extras']
np.testing.assert_almost_equal([[1, 2, 3], [4, 5, 6]],
extras.get('an_extra'))
np.testing.assert_almost_equal([0.5], extras.get('another_extra'))
np.testing.assert_almost_equal([[[9, 8, 7], [6, 5, 4]]],
extras.get('multi_dimension_extra'))
np.testing.assert_equal([1], extras.get('boolean_extra'))
def test_get_current_extras_json_format(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
event = event_listener.regexp
match = event.match('json_extra: {}')
if match is None: # Ignore events that are not extras.
return
# Emit events.
extra = {
'extra_scalar': 0,
'extra_list': [1, 2, 3, 4],
'extra_dict': {
'foo': 'bar'
},
'extra_string': 'a_string'
}
extra_update = {'extra_string': 'a_new_string', 'extra_float': 0.6}
fn = event_listener.handler_fn
fn(event, event.match(f'json_extra: {json.dumps(extra)}'))
fn(event, event.match(f'json_extra: {json.dumps(extra_update)}'))
# Setup the task and trigger the listener.
task = task_pb2.Task()
task.log_parsing_config.log_regexps.json_extra.extend([
'^json_extra: (?P<json_extra>.*)$'
])
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
# Check expectations.
self.assertIn('extras', timestep.observation)
extras = timestep.observation['extras']
expected_extra = {
'extra_scalar': [0],
'extra_list': [[1, 2, 3, 4]],
'extra_dict': [{
'foo': 'bar'
}],
'extra_string': ['a_string', 'a_new_string'],
'extra_float': [0.6]
}
np.testing.assert_almost_equal(
expected_extra.get('extra_scalar'), extras.get('extra_scalar'))
np.testing.assert_almost_equal(
expected_extra.get('extra_list'), extras.get('extra_list'))
np.testing.assert_equal(
expected_extra.get('extra_string'), extras.get('extra_string'))
np.testing.assert_almost_equal(
expected_extra.get('extra_float'), extras.get('extra_float'))
np.testing.assert_equal(
expected_extra.get('extra_dict'), extras.get('extra_dict'))
def test_get_current_extras_failed_to_parse(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
event = event_listener.regexp
match = event.match('extra: some_extra [1, 2]')
if match is None: # Ignore events that are not extras.
return
# Emit events.
fn = event_listener.handler_fn
fn(event, event.match('extra: extra_with_malformed_1 [1]'))
fn(event, event.match('extra: extra_with_malformed_1 [\'this is \\ bad]'))
fn(event, event.match('extra: extra_with_malformed_1 [2]'))
fn(event, event.match('extra: extra_with_malformed_2 [\'this is bad]'))
fn(event, event.match('extra: extra_with_malformed_2 [1]'))
fn(event, event.match('extra: extra_malformed_only [_very_bad_news]'))
# Setup the task and trigger the listener.
task = task_pb2.Task()
task.log_parsing_config.log_regexps.extra.extend([
'^extra: (?P<name>[^ ]*)[ ]?(?P<extra>.*)$'
])
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
# Check expectations.
self.assertIn('extras', timestep.observation)
extras = timestep.observation['extras']
np.testing.assert_almost_equal(extras.get('extra_with_malformed_1'),
[[1], [2]])
np.testing.assert_almost_equal(extras.get('extra_with_malformed_2'), [[1]])
self.assertNotIn('extra_malformed_only', extras)
def test_multi_log_regexp(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
match = event_listener.regexp.match('Reward_2: 123.0')
if match is None: # Ignore events that are not rewards.
return
event_listener.handler_fn(event_listener.regexp, match)
task = task_pb2.Task()
task.log_parsing_config.log_regexps.reward.extend([
'^[Rr]eward_1: ([-+]?[0-9]*\\.?[0-9]*)$',
'^[Rr]eward_2: ([-+]?[0-9]*\\.?[0-9]*)$'
])
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
self.assertEqual(timestep.reward, 123.0)
def test_multi_reward_regexp(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.'
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
match_1 = event_listener.regexp.match('Reward_1: 5.0')
match_2 = event_listener.regexp.match('Reward_2: 10.0')
if match_1:
event_listener.handler_fn(event_listener.regexp, match_1)
if match_2:
event_listener.handler_fn(event_listener.regexp, match_2)
task = task_pb2.Task()
task.log_parsing_config.log_regexps.reward.extend([
'^[Rr]eward_1: ([-+]?[0-9]*\\.?[0-9]*)$',
'^[Rr]eward_2: ([-+]?[0-9]*\\.?[0-9]*)$',
])
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
self.assertEqual(timestep.reward, 15.0)
def test_determine_transition_fn(self):
# Replace `LogcatThread.add_event_listener` with one that simply calls `fn`
# right away.
def my_add_ev_listener(event_listener: logcat_thread.EventListener):
# Check that the event matches what's expected.
event = event_listener.regexp
match = event.match('I am done!')
if match is None: # Ignore events that are not episode end.
return
event_listener.handler_fn(event, match)
task = task_pb2.Task()
task.log_parsing_config.log_regexps.episode_end.extend(['I am done!'])
task_mgr = task_manager.TaskManager(task=task)
self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener
adb_call_parser = mock.create_autospec(adb_call_parser_lib.AdbCallParser)
task_mgr.start(lambda: adb_call_parser, log_stream=self._log_stream)
task_mgr.setup_task()
timestep = task_mgr.rl_step(
observation={
'pixels': np.array([1, 2, 3]),
})
self.assertTrue(timestep.last())
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/task_manager_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Abstract class for handling a stream of logs from a simulator."""
import abc
import threading
from typing import Generator, Sequence
from absl import logging
class LogStream(metaclass=abc.ABCMeta):
"""Manages the stream of logs output by a simulator."""
def __init__(self, verbose: bool = False):
self._verbose = verbose
self._filters = []
self._should_stream = threading.Event()
def get_stream_output(self) -> Generator[str, None, None]:
"""Starts log process and returns the stream of logs."""
for line in self._get_stream_output():
if self._verbose:
logging.info('line: %r', line)
if self._should_stream.is_set():
yield line
@abc.abstractmethod
def _get_stream_output(self):
"""Starts log process and returns the stream of logs."""
pass
@abc.abstractmethod
def stop_stream(self) -> None:
"""Terminates the log stream.
NOTE: This should only be called _after_ `get_stream_output()`.
"""
def pause_stream(self) -> None:
"""No lines are yielded while the event is not set."""
logging.info('Pausing LogStream.')
self._should_stream.clear()
def resume_stream(self) -> None:
"""The stream will continue yielding lines if the event is set."""
logging.info('Resuming LogStream.')
self._should_stream.set()
def set_log_filters(self, log_filters: Sequence[str]):
"""Sets the filters for the log stream."""
self._filters = list(log_filters) + ['*:S']
| android_env-main | android_env/components/log_stream.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for errors.py."""
from absl.testing import absltest
from absl.testing import parameterized
from android_env.components import errors
class ErrorsTest(parameterized.TestCase):
@parameterized.parameters(
(errors.ReadObservationError, 1),
(errors.CoordinatorError, 2),
(errors.TooManyRestartsError, 3),
(errors.AdbControllerError, 4),
(errors.SimulatorError, 5),
(errors.SendActionError, 6),
(errors.StepCommandError, 7),
(errors.WaitForAppScreenError, 8),
(errors.CheckInstallError, 9),
)
def test_error_codes(self, error, expected_error_code):
with self.assertRaises(error) as context:
raise error()
self.assertEqual(context.exception.ERROR_CODE, expected_error_code)
def test_error_codes_unique(self):
error_codes = set()
errors_list = (
errors.ReadObservationError,
errors.CoordinatorError,
errors.TooManyRestartsError,
errors.AdbControllerError,
errors.SimulatorError,
errors.SendActionError,
errors.StepCommandError,
errors.WaitForAppScreenError,
errors.CheckInstallError,
)
for error in errors_list:
self.assertNotIn(error.ERROR_CODE, error_codes)
error_codes.add(error.ERROR_CODE)
@parameterized.parameters([
errors.ReadObservationError(),
errors.CoordinatorError(),
errors.TooManyRestartsError(),
errors.AdbControllerError(),
errors.SimulatorError(),
errors.SendActionError(),
errors.StepCommandError(),
errors.WaitForAppScreenError(),
errors.CheckInstallError(),
])
def test_all_errors_are_androidenv_errors(self, error):
self.assertIsInstance(error, errors.AndroidEnvError)
@parameterized.named_parameters([
('less_than_zero', -1),
# The largest `ERROR_CODE` is currently `CheckInstallError == 10`.
('greater_than_all_errors', 10 + 1),
('less_than_zero_float', -3.14159265),
('greater_than_all_errors_float', 123.456),
])
def test_from_code_unsupported_code(self, code: int):
"""Unsupported errors should raise `RuntimeError`."""
self.assertIsNone(errors.from_code(code))
@parameterized.parameters([
(-1, None, 'No such error code.'),
(0, errors.AndroidEnvError, 'hello'),
(0, errors.AndroidEnvError, ''),
(1, errors.ReadObservationError, 'Could not read obs.'),
(2, errors.CoordinatorError, 'Some error'),
(3, errors.TooManyRestartsError, 'Too many already...'),
(4, errors.AdbControllerError, 'Some adb error...'),
(5, errors.SimulatorError, 'Simulator is not coping.'),
(6, errors.SendActionError, 'Could not send action.'),
(7, errors.StepCommandError, 'Some issue setting up the task.'),
(8, errors.WaitForAppScreenError, 'Waited for too long!'),
(9, errors.CheckInstallError, 'App did not install correctly.'),
])
def test_from_code(self, code: int, expected_class: errors.AndroidEnvError,
msg: str):
"""`from_code` should produce consistent outputs for known errors."""
error = errors.from_code(code, msg)
if error is not None:
self.assertIsInstance(error, expected_class)
self.assertEqual(error.ERROR_CODE, code)
self.assertEqual(str(error), msg)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/errors_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.logcat_thread."""
import re
import threading
from typing import Match, Pattern
from absl.testing import absltest
from android_env.components import log_stream
from android_env.components import logcat_thread
from android_env.proto import task_pb2
class FakeStream:
"""This class simulates the logs coming from ADB."""
def __init__(self):
self._values = []
self._kill = False
self._lock = threading.Lock()
def send_value(self, value):
with self._lock:
self._values.append(value)
def has_next_value(self):
return bool(self._values)
def kill(self):
self._kill = True
def __iter__(self):
while True:
if self._kill:
return
if not self._values:
continue
else:
with self._lock:
next_value = self._values.pop(0)
yield next_value
def make_stdout(data):
"""Returns a valid log output with given data as message."""
return ' 1553110400.424 5583 5658 D Tag: %s' % data
class FakeLogStream(log_stream.LogStream):
"""FakeLogStream class that wraps a FakeStream."""
def __init__(self):
super().__init__(verbose=False)
self.logs = FakeStream()
self.stream_is_alive = True
def _get_stream_output(self):
return self.logs
def stop_stream(self):
self.stream_is_alive = False
self.logs.kill()
class LogcatThreadTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.fake_log_stream = FakeLogStream()
def tearDown(self):
self.fake_log_stream.stop_stream()
super().tearDown()
def test_set_filters(self):
log_parsing_config = task_pb2.LogParsingConfig(filters=['AndroidRLTask:V'])
self.fake_log_stream.set_log_filters(log_parsing_config.filters)
_ = logcat_thread.LogcatThread(log_stream=self.fake_log_stream)
expected_filters = ['AndroidRLTask:V', '*:S']
self.assertEqual(expected_filters, self.fake_log_stream._filters)
def test_kill(self):
logcat = logcat_thread.LogcatThread(log_stream=self.fake_log_stream)
self.assertTrue(self.fake_log_stream.stream_is_alive)
logcat.kill()
self.assertFalse(self.fake_log_stream.stream_is_alive)
def test_listeners(self):
"""Ensures that we can wait for a specific message without polling."""
logcat = logcat_thread.LogcatThread(log_stream=self.fake_log_stream)
# Start yielding lines from LogStream.
logcat.resume()
# Set up a listener that modifies an arbitrary state.
some_state = threading.Event()
def my_handler(event: Pattern[str], match: Match[str]):
del event, match
nonlocal some_state
some_state.set()
# Create a desired event and hook up the listener.
my_event = re.compile('Hello world')
listener = logcat_thread.EventListener(my_event, my_handler)
logcat.add_event_listener(listener)
self.fake_log_stream.logs.send_value('Hi there!') # This should not match.
self.assertFalse(some_state.is_set())
self.fake_log_stream.logs.send_value(make_stdout('Hello world'))
some_state.wait(timeout=1.0)
self.assertTrue(some_state.is_set())
# Waiting for any events should also trigger the listener.
some_state.clear()
self.fake_log_stream.logs.send_value(make_stdout('Hello world'))
some_state.wait(timeout=1.0)
self.assertTrue(some_state.is_set())
# After removing the listener, it should not be called anymore.
some_state.clear()
logcat.remove_event_listener(listener)
self.fake_log_stream.logs.send_value(make_stdout('Hello world'))
some_state.wait(timeout=1.0)
self.assertFalse(some_state.is_set())
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/logcat_thread_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.utils."""
from absl.testing import absltest
from absl.testing import parameterized
from android_env.components import utils
from dm_env import specs
import numpy as np
class UtilsTest(parameterized.TestCase):
@parameterized.parameters(
([0.5, 0.5], [320, 480], (160, 240)),
([0.25, 0.75], [320, 480], (80, 360)),
([0.0, 0.0], [320, 480], (0, 0)),
([1.0, 1.0], [320, 480], (319, 479)),
)
def test_touch_position_to_pixel_position(
self, touch_pos, width_height, pixel_pos):
self.assertEqual(utils.touch_position_to_pixel_position(
np.array(touch_pos), width_height), pixel_pos)
def test_transpose_pixels(self):
image = np.reshape(np.array(range(12)), (3, 2, 2))
expected = [[[0, 1], [4, 5], [8, 9]], [[2, 3], [6, 7], [10, 11]]]
self.assertEqual(utils.transpose_pixels(image).shape, (2, 3, 2))
self.assertTrue((utils.transpose_pixels(image) == expected).all())
def test_orient_pixels(self):
image = np.reshape(np.array(range(12)), (3, 2, 2))
expected_90 = [[[8, 9], [4, 5], [0, 1]], [[10, 11], [6, 7], [2, 3]]]
rot_90 = 1 # LANDSCAPE_90
rotated = utils.orient_pixels(image, rot_90)
self.assertEqual(rotated.shape, (2, 3, 2))
self.assertTrue((rotated == expected_90).all())
expected_180 = [[[10, 11], [8, 9]], [[6, 7], [4, 5]], [[2, 3], [0, 1]]]
rot_180 = 2 # PORTRAIT_180
rotated = utils.orient_pixels(image, rot_180)
self.assertEqual(rotated.shape, (3, 2, 2))
self.assertTrue((rotated == expected_180).all())
expected_270 = [[[2, 3], [6, 7], [10, 11]], [[0, 1], [4, 5], [8, 9]]]
rot_270 = 3 # LANDSCAPE_270
rotated = utils.orient_pixels(image, rot_270)
self.assertEqual(rotated.shape, (2, 3, 2))
self.assertTrue((rotated == expected_270).all())
rot_0 = 0 # PORTRAIT_0
rotated = utils.orient_pixels(image, rot_0)
self.assertEqual(rotated.shape, (3, 2, 2))
self.assertTrue((rotated == image).all())
def test_convert_int_to_float_bounded_array(self):
spec = specs.BoundedArray(
shape=(4,),
dtype=np.int32,
minimum=[0, 1, 10, -2],
maximum=[5, 5, 20, 2],
name='bounded_array')
data = np.array([2, 2, 10, 0], dtype=np.int32)
float_data = utils.convert_int_to_float(data, spec, np.float64)
np.testing.assert_equal(
np.array([2. / 5., 1. / 4., 0., 0.5], dtype=np.float64), float_data)
def test_convert_int_to_float_bounded_array_broadcast(self):
spec = specs.BoundedArray(
shape=(3,), dtype=np.int16, minimum=2, maximum=4, name='bounded_array')
data = np.array([2, 3, 4], dtype=np.int16)
float_data = utils.convert_int_to_float(data, spec, np.float32)
np.testing.assert_equal(
np.array([0.0, 0.5, 1.0], dtype=np.float32), float_data)
def test_convert_int_to_float_no_bounds(self):
spec = specs.Array(
shape=(3,),
dtype=np.int8, # int8 implies min=-128, max=127
name='bounded_array')
data = np.array([-128, 0, 127], dtype=np.int16)
float_data = utils.convert_int_to_float(data, spec, np.float32)
np.testing.assert_equal(
np.array([0.0, 128. / 255., 1.0], dtype=np.float32), float_data)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/utils_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Class for a stream of logs output by a locally running emulator."""
import subprocess
from absl import logging
from android_env.components import log_stream
_LOGCAT_COMMAND = ['logcat', '-v', 'epoch']
class AdbLogStream(log_stream.LogStream):
"""Manages adb logcat process for a locally running emulator."""
def __init__(self, adb_command_prefix: list[str], *args, **kwargs):
super().__init__(*args, **kwargs)
self._adb_command_prefix = adb_command_prefix
def _get_stream_output(self):
# Before spawning a long-lived process, we issue `logcat -b all -c` to clear
# all buffers to avoid interference from previous runs.
clear_buffer_output = subprocess.check_output(
self._adb_command_prefix + ['logcat', '-b', 'all', '-c'],
stderr=subprocess.STDOUT,
timeout=100)
logging.info('clear_buffer_output: %r', clear_buffer_output)
cmd = self._adb_command_prefix + _LOGCAT_COMMAND + self._filters
self._adb_subprocess = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
universal_newlines=True)
return self._adb_subprocess.stdout
def stop_stream(self):
if not hasattr(self, '_adb_subprocess') or self._adb_subprocess is None:
logging.error('`stop_stream()` called before `get_stream_output()`. '
'This violates the `LogStream` API.')
else:
self._adb_subprocess.kill()
| android_env-main | android_env/components/adb_log_stream.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The different kinds of actions that AndroidEnv supports."""
import enum
@enum.unique
class ActionType(enum.IntEnum):
"""Integer values to describe each supported action in AndroidEnv."""
TOUCH = 0
LIFT = 1
REPEAT = 2
KEYDOWN = 3
KEYUP = 4
KEYPRESS = 5
| android_env-main | android_env/components/action_type.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.setup_step_interpreter."""
from unittest import mock
from absl.testing import absltest
from android_env.components import adb_call_parser
from android_env.components import errors
from android_env.components import setup_step_interpreter
from android_env.proto import adb_pb2
from android_env.proto import task_pb2
from google.protobuf import text_format
def _to_proto(proto_class, text):
proto = proto_class()
text_format.Parse(text, proto)
return proto
class SetupStepInterpreterTest(absltest.TestCase):
def setUp(self):
super().setUp()
self._parser = mock.create_autospec(
adb_call_parser.AdbCallParser, instance=True)
def test_empty_setup_steps(self):
"""Simple test where nothing should break, and nothing should be done.
The test simply expects this test to not crash.
"""
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([])
def test_none_setup_steps(self):
"""Simple test where nothing should break, and nothing should be done.
The test simply expects this test to not crash.
"""
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
# Empty setup steps should be ignored.
interpreter.interpret([])
def test_invalid_setup_step(self):
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
# Empty setup steps should be ignored.
self.assertRaises(AssertionError, interpreter.interpret,
[task_pb2.SetupStep()])
def test_adb_install_apk_filesystem(self):
self._parser.parse.return_value = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK)
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
adb_request: {
install_apk: {
filesystem: {
path: "/my/favorite/dir/my_apk.apk"
}
}
}""")
])
self._parser.parse.assert_called_once_with(
adb_pb2.AdbRequest(
install_apk=adb_pb2.AdbRequest.InstallApk(
filesystem=adb_pb2.AdbRequest.InstallApk.Filesystem(
path='/my/favorite/dir/my_apk.apk'))))
def test_adb_force_stop(self):
self._parser.parse.return_value = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK)
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
adb_request: { force_stop: { package_name: "my.app.Activity" } }""")
])
self._parser.parse.assert_called_once_with(
adb_pb2.AdbRequest(
force_stop=adb_pb2.AdbRequest.ForceStop(
package_name='my.app.Activity')))
def test_adb_start_activity(self):
self._parser.parse.return_value = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK)
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
adb_request: {
start_activity: {
full_activity: "my.app.Activity"
extra_args: "arg1"
extra_args: "arg2"
}
}""")
])
self._parser.parse.assert_called_once_with(
adb_pb2.AdbRequest(
start_activity=adb_pb2.AdbRequest.StartActivity(
full_activity='my.app.Activity', extra_args=['arg1', 'arg2'])))
def test_adb_single_tap(self):
self._parser.parse.return_value = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK)
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([
_to_proto(task_pb2.SetupStep, """
adb_request: {
tap: {
x: 321
y: 654
}
}""")
])
self._parser.parse.assert_called_once_with(
adb_pb2.AdbRequest(tap=adb_pb2.AdbRequest.Tap(x=321, y=654)))
def test_adb_press_button(self):
self._parser.parse.return_value = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK)
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([
_to_proto(task_pb2.SetupStep,
""" adb_request: { press_button: { button: HOME } }""")
])
self._parser.parse.assert_called_once_with(
adb_pb2.AdbRequest(
press_button=adb_pb2.AdbRequest.PressButton(
button=adb_pb2.AdbRequest.PressButton.Button.HOME)))
self._parser.reset_mock()
interpreter.interpret([
_to_proto(task_pb2.SetupStep,
""" adb_request: { press_button: { button: BACK } }""")
])
self._parser.parse.assert_called_once_with(
adb_pb2.AdbRequest(
press_button=adb_pb2.AdbRequest.PressButton(
button=adb_pb2.AdbRequest.PressButton.Button.BACK)))
def test_adb_start_screen_pinning(self):
self._parser.parse.return_value = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK)
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
adb_request: {
start_screen_pinning: {
full_activity: "my.app.HighlanderApp" # "There can be only one".
}
}""")
])
self._parser.parse.assert_called_once_with(
adb_pb2.AdbRequest(
start_screen_pinning=adb_pb2.AdbRequest.StartScreenPinning(
full_activity='my.app.HighlanderApp')))
@mock.patch('time.sleep')
def test_time_sleep(self, mock_sleep):
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret(
[_to_proto(task_pb2.SetupStep, """sleep: { time_sec: 0.875 }""")])
assert mock_sleep.call_count == 2
mock_sleep.assert_has_calls([mock.call(0.875), mock.call(0.5)])
@mock.patch('time.sleep')
def test_wait_for_app_screen_empty_activity(self, unused_mock_sleep):
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
with self.assertRaises(errors.StepCommandError):
interpreter.interpret([
_to_proto(task_pb2.SetupStep,
"""success_condition: {wait_for_app_screen: { }}""")
])
@mock.patch('time.sleep')
def test_check_install_not_installed(self, unused_mock_sleep):
self._parser.parse.return_value = adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(items=[
'com.some.package',
'not.what.you.are.looking.for',
])))
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
with self.assertRaises(errors.StepCommandError):
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
success_condition: {
check_install: {
package_name: "faz"
timeout_sec: 0.0001
}
}
""")
])
def test_check_install_installed(self):
self._parser.parse.return_value = adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(items=[
'com.some.package',
'baz',
])))
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
# The test checks that this command raises no AssertionError.
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
success_condition: {
check_install: {
package_name: "baz"
timeout_sec: 0.0001
}
}""")
])
def test_num_retries_failure(self):
self._parser.parse.side_effect = [
adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(
items=[]))),
] * 3
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
with self.assertRaises(errors.StepCommandError):
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
success_condition: {
check_install: {
package_name: "faz"
timeout_sec: 0.0001
}
num_retries: 3
}""")
])
# We retried 3 times after the first call, so we expect 3+1 calls.
self.assertEqual(self._parser.parse.call_count, 3)
@mock.patch('time.sleep')
def test_num_retries_success(self, unused_mock_sleep):
self._parser.parse.side_effect = [
adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(
items=[]))),
adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(
items=[]))),
adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(items=[
'com.some.package',
'bar',
]))),
adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(items=[])))
]
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
success_condition: {
check_install: {
package_name: "bar"
timeout_sec: 0.0001
}
num_retries: 5
}""")
])
# The check should succeed on the third try.
self.assertEqual(self._parser.parse.call_count, 3)
def test_retry_step(self):
self._parser.parse.side_effect = [
adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(
items=[]))),
adb_pb2.AdbResponse(
package_manager=adb_pb2.AdbResponse.PackageManagerResponse(
list=adb_pb2.AdbResponse.PackageManagerResponse.List(items=[
'com.some.package',
'bar',
]))),
]
interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=self._parser)
interpreter.interpret([
_to_proto(
task_pb2.SetupStep, """
success_condition: {
check_install: {
package_name: "bar"
timeout_sec: 0.0001
}
num_retries: 2
}""")
])
# We expect the check to fail once and succeed on the second pass.
self.assertEqual(self._parser.parse.call_count, 2)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/setup_step_interpreter_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.coordinator."""
import tempfile
import time
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
from android_env.components import action_type
from android_env.components import adb_call_parser
from android_env.components import coordinator as coordinator_lib
from android_env.components import errors
from android_env.components import task_manager
from android_env.components.simulators import base_simulator
from android_env.proto import adb_pb2
from android_env.proto import state_pb2
from android_env.proto import task_pb2
import dm_env
import numpy as np
class MockScreenshotGetter:
def __init__(self):
self._screenshot_index = 0
def get_screenshot(self):
self._screenshot_index += 1
return np.array(self._screenshot_index, ndmin=3)
class CoordinatorTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.addCleanup(mock.patch.stopall) # Disable previous patches.
self._simulator = mock.create_autospec(base_simulator.BaseSimulator)
self._random_screenshot = np.random.randint(
low=0, high=255, size=(800, 600, 3), dtype=np.uint8)
self._simulator.get_screenshot.return_value = self._random_screenshot
self._task_manager = mock.create_autospec(task_manager.TaskManager)
self._adb_call_parser = mock.create_autospec(adb_call_parser.AdbCallParser)
self.enter_context(
mock.patch.object(
adb_call_parser,
'AdbCallParser',
autospec=True,
return_value=self._adb_call_parser))
self._coordinator = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
num_fingers=1,
periodic_restart_time_min=0)
def tearDown(self):
super().tearDown()
self._coordinator.close()
@mock.patch.object(time, 'sleep', autospec=True)
def test_relaunch_simulator(self, unused_mock_sleep):
relaunch_count = self._coordinator.stats()['relaunch_count']
self._coordinator._launch_simulator()
self.assertEqual(self._coordinator.stats()['relaunch_count'],
relaunch_count + 1)
@mock.patch.object(time, 'sleep', autospec=True)
def test_reset(self, unused_mock_sleep):
self._coordinator.rl_reset()
@mock.patch.object(time, 'sleep', autospec=True)
def test_lift_all_fingers(self, unused_mock_sleep):
self._coordinator = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
num_fingers=3,
periodic_restart_time_min=0)
self._coordinator.rl_reset()
expected_actions = [
# (x, y, is_down, identifier).
(0, 0, False, 0),
(0, 0, False, 1),
(0, 0, False, 2),
]
actual_actions = self._simulator.send_touch.call_args[0][0]
for actual, expected in zip(actual_actions, expected_actions):
np.testing.assert_array_equal(actual, expected)
@mock.patch.object(time, 'sleep', autospec=True)
def test_process_action(self, unused_mock_sleep):
def fake_rl_step(simulator_signals):
return dm_env.transition(
reward=10.0,
observation={
'pixels': simulator_signals['pixels'],
'orientation': simulator_signals['orientation'],
'timedelta': simulator_signals['timedelta'],
'extras': {
'extra': [0.0]
}
})
self._task_manager.rl_step.side_effect = fake_rl_step
timestep = self._coordinator.rl_step(
agent_action={
'action_type': np.array(action_type.ActionType.LIFT),
'touch_position': np.array([0.5, 0.5]),
})
obs = timestep.observation
self.assertEqual(obs['pixels'].shape, (800, 600, 3))
np.testing.assert_equal(obs['orientation'],
np.array([0, 0, 0, 0], dtype=np.uint8))
self.assertEqual(timestep.reward, 10.0)
self.assertEqual(obs['extras'], {'extra': [0.0]})
self.assertFalse(timestep.last())
@mock.patch.object(time, 'sleep', autospec=True)
def test_process_action_error(self, unused_mock_sleep):
def fake_rl_step(simulator_signals):
self.assertFalse(simulator_signals['simulator_healthy'])
return dm_env.truncation(reward=0.0, observation=None)
self._task_manager.rl_step.side_effect = fake_rl_step
self._simulator.get_screenshot.side_effect = errors.ReadObservationError()
timestep = self._coordinator.rl_step(
agent_action={
'action_type': np.array(action_type.ActionType.LIFT),
'touch_position': np.array([0.5, 0.5]),
})
self.assertIsNone(timestep.observation)
self.assertEqual(timestep.reward, 0.0)
self.assertTrue(timestep.last())
@mock.patch.object(time, 'sleep', autospec=True)
def test_process_action_error_async(self, unused_mock_sleep):
mock_interaction_thread = mock.create_autospec(
coordinator_lib.InteractionThread)
with mock.patch.object(
coordinator_lib,
'InteractionThread',
autospec=True,
return_value=mock_interaction_thread):
coordinator = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
num_fingers=1,
interaction_rate_sec=0.016)
def fake_rl_step(agent_action, simulator_signals):
del agent_action
self.assertFalse(simulator_signals['simulator_healthy'])
return dm_env.truncation(reward=0.0, observation=None)
self._task_manager.rl_step.side_effect = fake_rl_step
mock_interaction_thread.screenshot.side_effect = errors.ReadObservationError(
)
timestep = coordinator.rl_step(
agent_action={
'action_type': np.array(action_type.ActionType.LIFT),
'touch_position': np.array([0.5, 0.5]),
})
self.assertIsNone(timestep.observation)
self.assertEqual(timestep.reward, 0.0)
self.assertTrue(timestep.last())
coordinator.close()
def test_async_step_faster_than_screenshot(self):
"""Return same screenshot when step is faster than the interaction rate."""
screenshot_getter = MockScreenshotGetter()
self._simulator.get_screenshot.side_effect = screenshot_getter.get_screenshot
def fake_rl_step(simulator_signals):
return dm_env.transition(
reward=10.0,
observation={
'pixels': simulator_signals['pixels'],
'orientation': simulator_signals['orientation'],
'timedelta': simulator_signals['timedelta'],
'extras': {
'extra': [0.0]
}
})
self._task_manager.rl_step.side_effect = fake_rl_step
coordinator = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
num_fingers=1,
interaction_rate_sec=0.5)
ts1 = coordinator.rl_step(
agent_action={
'action_type': np.array(action_type.ActionType.LIFT),
'touch_position': np.array([0.5, 0.5]),
})
ts2 = coordinator.rl_step(
agent_action={
'action_type': np.array(action_type.ActionType.LIFT),
'touch_position': np.array([0.5, 0.5]),
})
np.testing.assert_almost_equal(ts2.observation['pixels'],
ts1.observation['pixels'])
coordinator.close()
def test_async_step_slower_than_screenshot(self):
"""Return different screenshots when step slower than the interaction rate."""
screenshot_getter = MockScreenshotGetter()
self._simulator.get_screenshot.side_effect = screenshot_getter.get_screenshot
def fake_rl_step(simulator_signals):
return dm_env.transition(
reward=10.0,
observation={
'pixels': simulator_signals['pixels'],
'orientation': simulator_signals['orientation'],
'timedelta': simulator_signals['timedelta'],
'extras': {
'extra': [0.0]
}
})
self._task_manager.rl_step.side_effect = fake_rl_step
coordinator = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
num_fingers=1,
interaction_rate_sec=0.01)
ts1 = coordinator.rl_step(
agent_action={
'action_type': np.array(action_type.ActionType.LIFT),
'touch_position': np.array([0.5, 0.5]),
})
time.sleep(0.5)
ts2 = coordinator.rl_step(
agent_action={
'action_type': np.array(action_type.ActionType.LIFT),
'touch_position': np.array([0.5, 0.5]),
})
np.testing.assert_raises(AssertionError, np.testing.assert_array_equal,
ts2.observation['pixels'],
ts1.observation['pixels'])
coordinator.close()
def test_interaction_thread_closes_upon_relaunch(self):
"""Async coordinator should kill the InteractionThread when relaunching."""
mock_interaction_thread = mock.create_autospec(
coordinator_lib.InteractionThread)
with mock.patch.object(
coordinator_lib,
'InteractionThread',
autospec=True,
return_value=mock_interaction_thread):
coordinator = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
num_fingers=1,
periodic_restart_time_min=1E-6,
interaction_rate_sec=0.5)
mock_interaction_thread.stop.assert_not_called()
mock_interaction_thread.join.assert_not_called()
time.sleep(0.1)
coordinator.rl_reset()
mock_interaction_thread.stop.assert_called_once()
mock_interaction_thread.join.assert_called_once()
coordinator.close()
@mock.patch.object(time, 'sleep', autospec=True)
def test_execute_action_touch(self, unused_mock_sleep):
def fake_rl_step(simulator_signals):
return dm_env.transition(
reward=123.0,
observation={
'pixels': simulator_signals['pixels'],
'orientation': simulator_signals['orientation'],
'timedelta': simulator_signals['timedelta'],
'extras': {
'extra': [0.0]
}
})
self._task_manager.rl_step.side_effect = fake_rl_step
timestep = self._coordinator.rl_step(
agent_action={
'action_type': np.array(action_type.ActionType.TOUCH),
'touch_position': np.array([0.5, 0.5])
})
self.assertEqual(timestep.reward, 123.0)
np.testing.assert_equal(timestep.observation['pixels'],
self._random_screenshot)
self._simulator.send_touch.assert_called_once_with([(300, 400, True, 0)])
@mock.patch.object(time, 'sleep', autospec=True)
def test_execute_multitouch_action(self, unused_mock_sleep):
self._coordinator = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
num_fingers=3,
periodic_restart_time_min=0)
def fake_rl_step(simulator_signals):
return dm_env.transition(
reward=456.0,
observation={
'pixels': simulator_signals['pixels'],
'orientation': simulator_signals['orientation'],
'timedelta': simulator_signals['timedelta'],
'extras': {
'extra': [0.0]
}
})
self._task_manager.rl_step.side_effect = fake_rl_step
action = {
'action_type': np.array([action_type.ActionType.TOUCH]),
'touch_position': np.array([0.25, 0.75]),
'action_type_2': np.array([action_type.ActionType.TOUCH]),
'touch_position_2': np.array([0.75, 0.25]),
'action_type_3': np.array([action_type.ActionType.LIFT]),
'touch_position_3': np.array([0.5, 0.5]),
}
timestep = self._coordinator.rl_step(action)
self._simulator.send_touch.assert_called_once_with([(150, 600, True, 0),
(450, 200, True, 1),
(300, 400, False, 2)])
self.assertEqual(timestep.reward, 456.0)
np.testing.assert_equal(timestep.observation['pixels'],
self._random_screenshot)
@mock.patch.object(time, 'sleep', autospec=True)
def test_execute_action_repeat(self, unused_mock_sleep):
def fake_rl_step(simulator_signals):
return dm_env.transition(
reward=10.0,
observation={
'pixels': simulator_signals['pixels'],
'orientation': simulator_signals['orientation'],
'timedelta': simulator_signals['timedelta'],
'extras': {
'extra': [0.0]
}
})
self._task_manager.rl_step.side_effect = fake_rl_step
timestep = self._coordinator.rl_step(
{'action_type': np.array(action_type.ActionType.REPEAT)})
self._simulator.send_touch.assert_not_called()
np.testing.assert_equal(timestep.observation['pixels'],
self._random_screenshot)
@mock.patch.object(time, 'sleep', autospec=True)
def test_execute_action_error(self, unused_mock_sleep):
def fake_rl_step(simulator_signals):
self.assertFalse(simulator_signals['simulator_healthy'])
return dm_env.truncation(reward=0.0, observation=None)
self._task_manager.rl_step.side_effect = fake_rl_step
self._simulator.send_touch.side_effect = errors.SendActionError
timestep = self._coordinator.rl_step({
'action_type': np.array(action_type.ActionType.TOUCH),
'touch_position': np.array([0.3, 0.8])
})
self.assertIsNone(timestep.observation)
@mock.patch.object(time, 'sleep', autospec=True)
def test_max_restarts_setup_steps(self, unused_mock_sleep):
init_fn_call = self._task_manager.setup_task.call_count
self._task_manager.setup_task.side_effect = errors.StepCommandError
self.assertRaises(errors.TooManyRestartsError,
self._coordinator._launch_simulator)
# The method was called three more times when attempting to relaunch.
self.assertEqual(init_fn_call + 3,
self._task_manager.setup_task.call_count)
@mock.patch.object(time, 'sleep', autospec=True)
def test_execute_adb_call(self, unused_mock_sleep):
call = adb_pb2.AdbRequest(
force_stop=adb_pb2.AdbRequest.ForceStop(package_name='blah'))
expected_response = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK)
self._adb_call_parser.parse.side_effect = [expected_response]
response = self._coordinator.execute_adb_call(call)
self.assertEqual(response, expected_response)
self._adb_call_parser.parse.assert_called_with(call)
@mock.patch.object(time, 'sleep', autospec=True)
@mock.patch.object(tempfile, 'gettempdir', autospec=True)
def test_with_tmp_dir_no_tempfile_call(self, mock_gettempdir,
unused_mock_sleep):
"""If passing a `tmp_dir`, `tempfile.gettempdir()` should not be called."""
_ = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
periodic_restart_time_min=0,
tmp_dir=absltest.get_default_test_tmpdir())
mock_gettempdir.assert_not_called()
@mock.patch.object(time, 'sleep', autospec=True)
@mock.patch.object(tempfile, 'gettempdir', autospec=True)
def test_no_tmp_dir_calls_tempfile(self, mock_gettempdir, unused_mock_sleep):
"""If not passing a `tmp_dir`, `tempfile.gettempdir()` should be called."""
_ = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
periodic_restart_time_min=0)
mock_gettempdir.assert_called_once()
@parameterized.parameters(
(True, '1'),
(False, '0'),
)
@mock.patch.object(time, 'sleep', autospec=True)
def test_touch_indicator(self, show, expected_value, unused_mock_sleep):
_ = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
show_touches=show)
self._adb_call_parser.parse.assert_any_call(
adb_pb2.AdbRequest(
settings=adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
put=adb_pb2.AdbRequest.SettingsRequest.Put(
key='show_touches', value=expected_value))))
@parameterized.parameters(
(True, '1'),
(False, '0'),
)
@mock.patch.object(time, 'sleep', autospec=True)
def test_pointer_location(self, show, expected_value, unused_mock_sleep):
_ = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
show_pointer_location=show)
self._adb_call_parser.parse.assert_any_call(
adb_pb2.AdbRequest(
settings=adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
put=adb_pb2.AdbRequest.SettingsRequest.Put(
key='pointer_location', value=expected_value))))
@parameterized.parameters(
(True, True, 'null*'),
(True, False, 'immersive.status=*'),
(False, True, 'immersive.navigation=*'),
(False, False, 'immersive.full=*'),
(None, None, 'immersive.full=*'), # Defaults to hiding both.
)
@mock.patch.object(time, 'sleep', autospec=True)
def test_bar_visibility(self, show_navigation_bar, show_status_bar,
expected_value, unused_mock_sleep):
_ = coordinator_lib.Coordinator(
simulator=self._simulator,
task_manager=self._task_manager,
show_navigation_bar=show_navigation_bar,
show_status_bar=show_status_bar)
self._adb_call_parser.parse.assert_any_call(
adb_pb2.AdbRequest(
settings=adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.GLOBAL,
put=adb_pb2.AdbRequest.SettingsRequest.Put(
key='policy_control', value=expected_value))))
def test_load_state(self):
expected_response = state_pb2.LoadStateResponse(
status=state_pb2.LoadStateResponse.Status.OK
)
request = state_pb2.LoadStateRequest(args={'foo': 'bar'})
self._simulator.load_state.return_value = expected_response
stop_call_count = self._task_manager.stop.call_count
start_call_count = self._task_manager.start.call_count
response = self._coordinator.load_state(request)
self.assertEqual(response, expected_response)
self._simulator.load_state.assert_called_once_with(request)
self.assertEqual(self._task_manager.stop.call_count, stop_call_count + 1)
self.assertEqual(self._task_manager.start.call_count, start_call_count + 1)
def test_save_state(self):
expected_response = state_pb2.SaveStateResponse(
status=state_pb2.SaveStateResponse.Status.OK
)
request = state_pb2.SaveStateRequest(args={'foo': 'bar'})
self._simulator.save_state.return_value = expected_response
response = self._coordinator.save_state(request)
self.assertEqual(response, expected_response)
self._simulator.save_state.assert_called_once_with(request)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/coordinator_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for specs.py."""
from absl.testing import absltest
from absl.testing import parameterized
from android_env.components import specs
from android_env.proto import task_pb2
from dm_env import specs as dm_env_specs
import numpy as np
class SpecsTest(parameterized.TestCase):
def test_base_action_spec(self):
action_spec = specs.base_action_spec(num_fingers=1)
for spec in action_spec.values():
self.assertIsInstance(spec, dm_env_specs.Array)
self.assertEqual(action_spec['action_type'].shape, ())
self.assertEqual(action_spec['action_type'].dtype, np.int32)
self.assertEqual(action_spec['touch_position'].shape, (2,))
self.assertEqual(action_spec['touch_position'].dtype, np.float32)
def test_base_action_spec_with_key_events(self):
action_spec = specs.base_action_spec(num_fingers=1, enable_key_events=True)
for spec in action_spec.values():
self.assertIsInstance(spec, dm_env_specs.Array)
self.assertEqual(action_spec['action_type'].shape, ())
self.assertEqual(action_spec['action_type'].dtype, np.int32)
self.assertEqual(action_spec['touch_position'].shape, (2,))
self.assertEqual(action_spec['touch_position'].dtype, np.float32)
self.assertEqual(action_spec['keycode'].shape, ())
self.assertEqual(action_spec['keycode'].dtype, np.int32)
def test_base_action_spec_multitouch(self):
action_spec = specs.base_action_spec(num_fingers=3)
self.assertLen(action_spec.keys(), 6)
for spec in action_spec.values():
self.assertIsInstance(spec, dm_env_specs.Array)
self.assertEqual(action_spec['action_type'].shape, ())
self.assertEqual(action_spec['action_type'].dtype, np.int32)
self.assertEqual(action_spec['touch_position'].shape, (2,))
self.assertEqual(action_spec['touch_position'].dtype, np.float32)
self.assertEqual(action_spec['action_type_2'].shape, ())
self.assertEqual(action_spec['action_type_2'].dtype, np.int32)
self.assertEqual(action_spec['touch_position_2'].shape, (2,))
self.assertEqual(action_spec['touch_position_2'].dtype, np.float32)
self.assertEqual(action_spec['action_type_3'].shape, ())
self.assertEqual(action_spec['action_type_3'].dtype, np.int32)
self.assertEqual(action_spec['touch_position_3'].shape, (2,))
self.assertEqual(action_spec['touch_position_3'].dtype, np.float32)
@parameterized.parameters(
(480, 320),
(100, 100),
(1440, 1960),
)
def test_base_observation_spec(self, height, width):
observation_spec = specs.base_observation_spec(height, width)
for spec in observation_spec.values():
self.assertIsInstance(spec, dm_env_specs.Array)
self.assertEqual(observation_spec['pixels'].shape, (height, width, 3))
self.assertEqual(observation_spec['pixels'].dtype, np.uint8)
self.assertEqual(observation_spec['timedelta'].shape, ())
self.assertEqual(observation_spec['timedelta'].dtype, np.int64)
self.assertEqual(observation_spec['orientation'].shape, (4,))
self.assertEqual(observation_spec['orientation'].dtype, np.uint8)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/specs_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| android_env-main | android_env/components/__init__.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.dumpsys_thread."""
from unittest import mock
from absl.testing import absltest
from android_env.components import app_screen_checker as screen_checker
from android_env.components import dumpsys_thread
class DumpsysThreadTest(absltest.TestCase):
def setUp(self):
super().setUp()
self._app_screen_checker = mock.create_autospec(
screen_checker.AppScreenChecker)
def test_unexpected_activity(self):
dumpsys = dumpsys_thread.DumpsysThread(
app_screen_checker=self._app_screen_checker, check_frequency=1)
outcome = screen_checker.AppScreenChecker.Outcome.UNEXPECTED_ACTIVITY
self._app_screen_checker.matches_current_app_screen.return_value = outcome
# The first time that `check_user_exited()` is called, it'll only trigger
# the processing, but it should return immediately.
self.assertFalse(dumpsys.check_user_exited(timeout=1.0))
# The second time it should then wait for the result.
self.assertTrue(dumpsys.check_user_exited(timeout=1.0))
def test_unexpected_view_hierarchy(self):
dumpsys = dumpsys_thread.DumpsysThread(
app_screen_checker=self._app_screen_checker, check_frequency=1)
outcome = screen_checker.AppScreenChecker.Outcome.UNEXPECTED_VIEW_HIERARCHY
self._app_screen_checker.matches_current_app_screen.return_value = outcome
self.assertFalse(dumpsys.check_user_exited(timeout=1.0))
self.assertTrue(dumpsys.check_user_exited(timeout=1.0))
def test_success(self):
dumpsys = dumpsys_thread.DumpsysThread(
app_screen_checker=self._app_screen_checker, check_frequency=1)
outcome = screen_checker.AppScreenChecker.Outcome.SUCCESS
self._app_screen_checker.matches_current_app_screen.return_value = outcome
self.assertFalse(dumpsys.check_user_exited(timeout=1.0))
self.assertFalse(dumpsys.check_user_exited(timeout=1.0))
def test_skipped(self):
dumpsys = dumpsys_thread.DumpsysThread(
app_screen_checker=self._app_screen_checker, check_frequency=5)
self._app_screen_checker.matches_current_app_screen.side_effect = [
screen_checker.AppScreenChecker.Outcome.SUCCESS,
screen_checker.AppScreenChecker.Outcome.FAILED_ACTIVITY_EXTRACTION
]
for _ in range(17):
self.assertFalse(dumpsys.check_user_exited(timeout=1.0))
# The first 4 calls will hit the early exit from `check_frequency`.
# The 5th call will trigger the processing (increasing the call count to
# matches_current_app_screen() by 1), but it should return early.
# The 10th call will find a result of the previous processing, and it should
# be SUCCESS.
# The next 4 calls (11, 12, 13, 14) will hit the early exit from
# `check_frequency`.
# The 15th call should trigger the processing again (increasing the call
# count to matches_current_app_screen() by 1), but it should return early.
# The next 2 calls (16, 17) will hit the early exit from `check_frequency`.
# In total there should be only two calls to `matches_current_app_screen()`.
expected_call_count = 2
self.assertEqual(
self._app_screen_checker.matches_current_app_screen.call_count,
expected_call_count)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/dumpsys_thread_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utils for AndroidEnv."""
from typing import Sequence
from dm_env import specs
import numpy as np
import numpy.typing as np_typing
def touch_position_to_pixel_position(
touch_position: np.ndarray,
width_height: Sequence[int],
) -> tuple[int, int]:
"""Maps touch position in [0,1] to the corresponding pixel on the screen."""
touch_pixels = (touch_position * width_height).astype(np.int32)
cap_idx = lambda v, idx_len: min(v, idx_len - 1)
return tuple(map(cap_idx, touch_pixels, width_height))
def transpose_pixels(frame: np.ndarray) -> np.ndarray:
"""Converts image from shape (H, W, C) to (W, H, C) and vice-versa."""
return np.transpose(frame, axes=(1, 0, 2))
def orient_pixels(frame: np.ndarray, orientation: int) -> np.ndarray:
"""Rotates screen pixels according to the given orientation."""
match orientation:
case 0: # PORTRAIT_90
return frame
case 1: # LANDSCAPE_90
return np.rot90(frame, k=3, axes=(0, 1))
case 2: # PORTRAIT_180
return np.rot90(frame, k=2, axes=(0, 1))
case 3: # LANDSCAPE_270
return np.rot90(frame, k=1, axes=(0, 1))
case _:
raise ValueError(
'Orientation must be an integer in [0, 3] but is %r' % orientation
)
def convert_int_to_float(data: np.ndarray,
data_spec: specs.Array,
float_type: np_typing.DTypeLike = np.float32):
"""Converts an array of int values to floats between 0 and 1."""
if not np.issubdtype(data.dtype, np.integer):
raise TypeError(f'{data.dtype} is not an integer type')
if not np.issubdtype(float_type, np.floating):
raise TypeError(f'{float_type} is not a floating-point type')
if isinstance(data_spec, specs.BoundedArray):
value_min = data_spec.minimum
value_max = data_spec.maximum
else:
# We use the int type to figure out the boundaries.
iinfo = np.iinfo(data_spec.dtype)
value_min = iinfo.min
value_max = iinfo.max
return float_type(1.0 * (data - value_min) / (value_max - value_min))
| android_env-main | android_env/components/utils.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TaskManager handles all events and information related to the task."""
import ast
import copy
import datetime
import json
import re
import threading
from typing import Any, Callable
from absl import logging
from android_env.components import adb_call_parser as adb_call_parser_lib
from android_env.components import app_screen_checker
from android_env.components import dumpsys_thread
from android_env.components import log_stream as log_stream_lib
from android_env.components import logcat_thread
from android_env.components import setup_step_interpreter
from android_env.proto import task_pb2
import dm_env
import numpy as np
class TaskManager:
"""Handles all events and information related to the task."""
def __init__(
self,
task: task_pb2.Task,
max_bad_states: int = 3,
dumpsys_check_frequency: int = 150,
max_failed_current_activity: int = 10,
extras_max_buffer_size: int = 100,
):
"""Controls task-relevant events and information.
Args:
task: A task proto defining the RL task.
max_bad_states: How many bad states in a row are allowed before a restart
of the simulator is triggered.
dumpsys_check_frequency: Frequency, in steps, at which to check
current_activity and view hierarchy
max_failed_current_activity: The maximum number of tries for extracting
the current activity before forcing the episode to restart.
extras_max_buffer_size: The maximum number of extras elements to store. If
this number is exceeded, elements are dropped in the order they were
received.
"""
self._task = task
self._max_bad_states = max_bad_states
self._dumpsys_check_frequency = dumpsys_check_frequency
self._max_failed_current_activity = max_failed_current_activity
self._lock = threading.Lock()
self._extras_max_buffer_size = extras_max_buffer_size
self._logcat_thread = None
self._dumpsys_thread = None
self._setup_step_interpreter = None
# Initialize stats.
self._stats = {
'episode_steps': 0,
'reset_count_step_timeout': 0,
'reset_count_user_exited': 0,
'reset_count_episode_end': 0,
'reset_count_max_duration_reached': 0,
'restart_count_max_bad_states': 0,
'task_updates': 0,
}
# Initialize internal state
self._task_start_time = None
self._bad_state_counter = 0
self._is_bad_episode = False
self._latest_values = {
'reward': 0.0,
'score': 0.0,
'extra': {},
'episode_end': False,
}
logging.info('Task config: %s', self._task)
def stats(self) -> dict[str, Any]:
"""Returns a dictionary of stats.
This method is expected to be called after setup_task() has been called.
"""
output = copy.deepcopy(self._stats)
if self._setup_step_interpreter is not None:
output.update(self._setup_step_interpreter.stats())
return output
def setup_task(self) -> None:
"""Performs one-off task setup.."""
self._setup_step_interpreter.interpret(self._task.setup_steps)
def stop(self) -> None:
"""Suspends task processing."""
self._stop_logcat_thread()
def start(
self,
adb_call_parser_factory: Callable[[], adb_call_parser_lib.AdbCallParser],
log_stream: log_stream_lib.LogStream) -> None:
"""Starts task processing."""
self._start_logcat_thread(log_stream=log_stream)
self._logcat_thread.resume()
self._start_dumpsys_thread(adb_call_parser_factory())
self._start_setup_step_interpreter(adb_call_parser_factory())
def reset_task(self) -> None:
"""Resets a task for a new run."""
self._logcat_thread.pause()
self._setup_step_interpreter.interpret(self._task.reset_steps)
self._logcat_thread.resume()
# Reset some other variables.
if not self._is_bad_episode:
self._bad_state_counter = 0
self._is_bad_episode = False
self._task_start_time = datetime.datetime.now()
with self._lock:
self._latest_values = {
'reward': 0.0,
'score': 0.0,
'extra': {},
'episode_end': False,
}
def rl_reset(self, observation: dict[str, Any]) -> dm_env.TimeStep:
"""Performs one RL step."""
self._stats['episode_steps'] = 0
self._logcat_thread.line_ready().wait()
with self._lock:
extras = self._get_current_extras()
observation['extras'] = extras
return dm_env.TimeStep(
step_type=dm_env.StepType.FIRST,
reward=0.0,
discount=0.0,
observation=observation)
def rl_step(self, observation: dict[str, Any]) -> dm_env.TimeStep:
"""Performs one RL step."""
self._stats['episode_steps'] += 1
self._logcat_thread.line_ready().wait()
with self._lock:
reward = self._get_current_reward()
extras = self._get_current_extras()
transition_fn = self._determine_transition_fn()
observation['extras'] = extras
return transition_fn(reward=reward, observation=observation)
def _get_current_reward(self) -> float:
"""Returns total reward accumulated since the last step."""
reward = self._latest_values['reward']
self._latest_values['reward'] = 0.0
return reward
def _get_current_extras(self) -> dict[str, Any]:
"""Returns task extras accumulated since the last step."""
extras = {}
for name, values in self._latest_values['extra'].items():
extras[name] = np.stack(values)
self._latest_values['extra'] = {}
return extras
def _determine_transition_fn(self) -> Callable[..., dm_env.TimeStep]:
"""Determines the type of RL transition will be used."""
# Check if user existed the task
if self._dumpsys_thread.check_user_exited():
self._increment_bad_state()
self._stats['reset_count_user_exited'] += 1
logging.warning('User exited the task. Truncating the episode.')
logging.info('************* END OF EPISODE *************')
return dm_env.truncation
# Check if episode has ended
if self._latest_values['episode_end']:
self._stats['reset_count_episode_end'] += 1
logging.info('End of episode from logcat! Ending episode.')
return dm_env.termination
# Check if step limit or time limit has been reached
if self._task.max_episode_steps > 0:
if self._stats['episode_steps'] > self._task.max_episode_steps:
self._stats['reset_count_max_duration_reached'] += 1
logging.info('Maximum task duration (%r steps) reached. '
'Truncating the episode.', self._task.max_episode_steps)
return dm_env.truncation
if self._task.max_episode_sec > 0.0:
task_duration = datetime.datetime.now() - self._task_start_time
max_episode_sec = self._task.max_episode_sec
if task_duration > datetime.timedelta(seconds=int(max_episode_sec)):
self._stats['reset_count_max_duration_reached'] += 1
logging.info('Maximum task duration (%r sec) reached. '
'Truncating the episode.', max_episode_sec)
return dm_env.truncation
return dm_env.transition
def _start_setup_step_interpreter(
self, adb_call_parser: adb_call_parser_lib.AdbCallParser):
self._setup_step_interpreter = setup_step_interpreter.SetupStepInterpreter(
adb_call_parser=adb_call_parser)
def _start_logcat_thread(self, log_stream: log_stream_lib.LogStream):
log_stream.set_log_filters(list(self._task.log_parsing_config.filters))
self._logcat_thread = logcat_thread.LogcatThread(log_stream=log_stream)
for event_listener in self._logcat_listeners():
self._logcat_thread.add_event_listener(event_listener)
def _start_dumpsys_thread(self,
adb_call_parser: adb_call_parser_lib.AdbCallParser):
self._dumpsys_thread = dumpsys_thread.DumpsysThread(
app_screen_checker=app_screen_checker.AppScreenChecker(
adb_call_parser=adb_call_parser,
expected_app_screen=self._task.expected_app_screen),
check_frequency=self._dumpsys_check_frequency,
max_failed_current_activity=self._max_failed_current_activity)
def _stop_logcat_thread(self):
if self._logcat_thread is not None:
self._logcat_thread.kill()
self._logcat_thread = None
def _increment_bad_state(self) -> None:
"""Increments the bad state counter.
Bad states are errors that shouldn't happen and that trigger an
episode reset. If enough bad states have been seen consecutively,
we restart the simulation in the hope of returning the simulation
to a good state.
"""
logging.warning('Bad state detected.')
if self._max_bad_states:
self._is_bad_episode = True
self._bad_state_counter += 1
logging.warning('Bad state counter: %d.', self._bad_state_counter)
if self._bad_state_counter >= self._max_bad_states:
logging.error('Too many consecutive bad states. Restarting simulator.')
self._stats['restart_count_max_bad_states'] += 1
self._should_restart = True
else:
logging.warning('Max bad states not set, bad states will be ignored.')
def _logcat_listeners(self):
"""Creates list of EventListeners for logcat thread."""
# Defaults to 'a^' since that regex matches no string by definition.
regexps = self._task.log_parsing_config.log_regexps
listeners = []
# Reward listeners
def _reward_handler(event, match):
del event
reward = float(match.group(1))
with self._lock:
self._latest_values['reward'] += reward
for regexp in regexps.reward:
listeners.append(logcat_thread.EventListener(
regexp=re.compile(regexp or 'a^'),
handler_fn=_reward_handler))
# RewardEvent listeners
for reward_event in regexps.reward_event:
def get_reward_event_handler(reward):
def _reward_event_handler(event, match):
del event, match
with self._lock:
self._latest_values['reward'] += reward
return _reward_event_handler
listeners.append(logcat_thread.EventListener(
regexp=re.compile(reward_event.event or 'a^'),
handler_fn=get_reward_event_handler(reward_event.reward)))
# Score listener
def _score_handler(event, match):
del event
current_score = float(match.group(1))
with self._lock:
current_reward = current_score - self._latest_values['score']
self._latest_values['score'] = current_score
self._latest_values['reward'] += current_reward
listeners.append(logcat_thread.EventListener(
regexp=re.compile(regexps.score or 'a^'),
handler_fn=_score_handler))
# Episode end listeners
def _episode_end_handler(event, match):
del event, match
with self._lock:
self._latest_values['episode_end'] = True
for regexp in regexps.episode_end:
listeners.append(logcat_thread.EventListener(
regexp=re.compile(regexp or 'a^'),
handler_fn=_episode_end_handler))
# Extra listeners
def _extras_handler(event, match):
del event
extra_name = match.group('name')
extra = match.group('extra')
if extra:
try:
extra = ast.literal_eval(extra)
# Except all to avoid unnecessary crashes, only log error.
except Exception: # pylint: disable=broad-except
logging.exception('Could not parse extra: %s', extra)
# Don't try to process the extra as text; that would probably crash.
return
else:
# No extra value provided for boolean extra. Setting value to True.
extra = 1
_process_extra(extra_name, extra)
for regexp in regexps.extra:
listeners.append(logcat_thread.EventListener(
regexp=re.compile(regexp or 'a^'),
handler_fn=_extras_handler))
# JSON extra listeners
def _json_extras_handler(event, match):
del event
extra_data = match.group('json_extra')
try:
extra = dict(json.loads(extra_data))
except ValueError:
logging.error('JSON string could not be parsed: %s', extra_data)
return
for extra_name, extra_value in extra.items():
_process_extra(extra_name, extra_value)
for regexp in regexps.json_extra:
listeners.append(logcat_thread.EventListener(
regexp=re.compile(regexp or 'a^'),
handler_fn=_json_extras_handler))
def _process_extra(extra_name, extra):
extra = np.array(extra)
with self._lock:
latest_extras = self._latest_values['extra']
if extra_name in latest_extras:
# If latest extra is not flushed, append.
if len(latest_extras[extra_name]) >= self._extras_max_buffer_size:
latest_extras[extra_name].pop(0)
latest_extras[extra_name].append(extra)
else:
latest_extras[extra_name] = [extra]
self._latest_values['extra'] = latest_extras
return listeners
| android_env-main | android_env/components/task_manager.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for log_stream."""
from absl.testing import absltest
from android_env.components import log_stream
class FakeLogStream(log_stream.LogStream):
def __init__(self, filter_name: str):
super().__init__()
self._filter_name = filter_name
def _get_stream_output(self):
"""Starts a log process and returns the stream of logs."""
lines = [
f'{self._filter_name} fake_line_1',
'fake_line_2',
f'{self._filter_name} fake_line_3',
f'{self._filter_name} fake_line_4',
'fake_line_5',
'fake_line_6',
]
for line in lines:
if f'{self._filter_name}:V' in self._filters:
if self._filter_name in line:
yield line
else:
yield line
def stop_stream(self):
"""Stops the log stream from the simulator."""
pass
class LogStreamTest(absltest.TestCase):
def test_get_stream_output(self):
filter_name = 'AndroidRLTask'
stream = FakeLogStream(filter_name=filter_name)
stream.resume_stream()
stream_output = stream.get_stream_output()
expected_lines = [
f'{filter_name} fake_line_1',
'fake_line_2',
f'{filter_name} fake_line_3',
f'{filter_name} fake_line_4',
'fake_line_5',
'fake_line_6',
]
for line, expected_line in zip(stream_output, expected_lines):
self.assertEqual(line, expected_line)
def test_set_log_filters(self):
filter_name = 'AndroidRLTask'
stream = FakeLogStream(filter_name=filter_name)
stream.set_log_filters([f'{filter_name}:V'])
stream.resume_stream()
stream_output = stream.get_stream_output()
expected_lines = [
f'{filter_name} fake_line_1',
f'{filter_name} fake_line_3',
f'{filter_name} fake_line_4',
]
for line, expected_line in zip(stream_output, expected_lines):
self.assertEqual(line, expected_line)
def test_pause_resume_stream(self):
filter_name = 'AndroidRLTask'
stream = FakeLogStream(filter_name=filter_name)
stream.resume_stream()
stream_output = stream.get_stream_output()
expected_lines = [
f'{filter_name} fake_line_1',
'fake_line_2',
f'{filter_name} fake_line_3',
f'{filter_name} fake_line_4',
'fake_line_5',
'fake_line_6',
]
for line, expected_line in zip(stream_output, expected_lines):
self.assertEqual(line, expected_line)
# If the stream is paused, we expect no lines to be yielded.
stream.pause_stream()
stream_output = list(stream.get_stream_output())
self.assertEmpty(stream_output)
# If the stream is resumed, we expect to see all lines yielded.
stream.resume_stream()
stream_output = stream.get_stream_output()
for line, expected_line in zip(stream_output, expected_lines):
self.assertEqual(line, expected_line)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/log_stream_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Definitions of exceptions used by AndroidEnv."""
class AndroidEnvError(Exception):
"""Base class for all known errors generated by AndroidEnv."""
# An integer that identifies this class of error.
# Subclasses should use a different value.
ERROR_CODE: int = 0
class ReadObservationError(AndroidEnvError):
"""When the environment is unable to obtain an observation from a simulator."""
ERROR_CODE = 1
class CoordinatorError(AndroidEnvError):
"""Error raised by the Coordinator."""
ERROR_CODE = 2
class TooManyRestartsError(CoordinatorError):
"""The number of restarts has exceeded _MAX_RESTART_TRIES."""
ERROR_CODE = 3
class AdbControllerError(AndroidEnvError):
"""Errors that can be raised by ADBController."""
ERROR_CODE = 4
class SimulatorError(AndroidEnvError):
"""Errors that can be raised by a simulator."""
ERROR_CODE = 5
class SendActionError(AndroidEnvError):
"""Raised when action couldn't be sent successfully."""
ERROR_CODE = 6
class StepCommandError(AndroidEnvError):
"""Raised when setup step interpreter cannot process a command."""
ERROR_CODE = 7
class WaitForAppScreenError(StepCommandError):
"""Raised when the wait_for_app_screen success check is not met."""
ERROR_CODE = 8
class CheckInstallError(StepCommandError):
"""Raised when the check_install success check is not met."""
ERROR_CODE = 9
def from_code(code: int, msg: str = '') -> AndroidEnvError | None:
"""Returns an AndroidEnvError instance from the given arguments."""
code_to_error = {
0: AndroidEnvError,
1: ReadObservationError,
2: CoordinatorError,
3: TooManyRestartsError,
4: AdbControllerError,
5: SimulatorError,
6: SendActionError,
7: StepCommandError,
8: WaitForAppScreenError,
9: CheckInstallError,
}
if code in code_to_error:
return code_to_error[code](msg)
| android_env-main | android_env/components/errors.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Processes adb_pb2.AdbRequest commands."""
import os
import re
import subprocess
import sys
import tempfile
from absl import logging
from android_env.components import adb_controller as adb_control
from android_env.proto import adb_pb2
# A mapping from a Button enum to keycode strings.
#
# Please see https://developer.android.com/reference/android/view/KeyEvent
#
# We currently only accept the following entries:
_BUTTON_TO_KEYCODE = {
adb_pb2.AdbRequest.PressButton.Button.HOME: 'KEYCODE_HOME',
adb_pb2.AdbRequest.PressButton.Button.BACK: 'KEYCODE_BACK',
adb_pb2.AdbRequest.PressButton.Button.ENTER: 'KEYCODE_ENTER',
}
class AdbCallParser:
"""Parses AdbRequest messages and executes corresponding adb commands."""
def __init__(self, adb_controller: adb_control.AdbController, tmp_dir: str):
self._adb_controller = adb_controller
self._tmp_dir = tmp_dir
self._handlers = {
'install_apk': self._install_apk,
'start_activity': self._start_activity,
'force_stop': self._force_stop,
'tap': self._tap,
'press_button': self._press_button,
'start_screen_pinning': self._start_screen_pinning,
'send_broadcast': self._send_broadcast,
'uninstall_package': self._handle_uninstall_package,
'get_current_activity': self._get_current_activity,
'get_orientation': self._get_orientation,
'push': self._push,
'pull': self._pull,
'input_text': self._input_text,
'settings': self._handle_settings,
'generic': self._handle_generic,
'package_manager': self._handle_package_manager,
'dumpsys': self._handle_dumpsys,
}
def _execute_command(
self, command_args: list[str], timeout: float | None
) -> tuple[adb_pb2.AdbResponse, bytes]:
"""Executes the command, catches errors and populates the response status.
Args:
command_args: a list of arguments for the ADB request.
timeout: Timeout in seconds.
Returns:
A tuple of the AdbResponse with the status populated, and the output
bytes from the command.
"""
response = adb_pb2.AdbResponse(status=adb_pb2.AdbResponse.Status.OK)
command_output = b''
try:
command_output = self._adb_controller.execute_command(
command_args, timeout=timeout)
except subprocess.CalledProcessError as adb_error:
if adb_error.stdout is not None:
response.status = adb_pb2.AdbResponse.Status.ADB_ERROR
response.error_message = adb_error.stdout
except subprocess.TimeoutExpired:
response.status = adb_pb2.AdbResponse.Status.TIMEOUT
response.error_message = 'Timeout'
return response, command_output
def parse(self, request: adb_pb2.AdbRequest) -> adb_pb2.AdbResponse:
"""Executes `request` and returns an appropriate response."""
response = adb_pb2.AdbResponse(status=adb_pb2.AdbResponse.Status.OK)
command_type = request.WhichOneof('command')
logging.info('AdbRequest command type: %s', command_type)
if command_type is None:
response.status = adb_pb2.AdbResponse.Status.UNKNOWN_COMMAND
response.error_message = 'AdbRequest.command is None.'
return response
if request.timeout_sec < 0:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = ('AdbRequest.timeout_sec cannot be negative. '
f'Got: {request.timeout_sec}')
return response
timeout: float | None = request.timeout_sec or None
return self._handlers[command_type](request, timeout)
def _force_stop(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Stops an application.
Args:
request: The external request containing the package to force stop.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse.
"""
force_stop = request.force_stop
response = adb_pb2.AdbResponse(status=adb_pb2.AdbResponse.Status.OK)
if not force_stop.package_name:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = '`force_stop.package_name` cannot be empty.'
return response
response, _ = self._execute_command(
['shell', 'am', 'force-stop', force_stop.package_name], timeout)
return response
def _fetch_current_task_id(
self, full_activity_name: str, timeout: float | None = None
) -> int:
"""Returns the task ID of the given `full_activity_name`.
Args:
full_activity_name: The full name of the activity whose corresponding
task id we are looking for.
timeout: Optional time limit in seconds.
Returns:
task_id: An integer corresponding to the specified activity.
"""
stack = self._adb_controller.execute_command(
['shell', 'am', 'stack', 'list'], timeout=timeout)
lines = stack.decode('utf-8').splitlines()
regex = re.compile(
r'^\ *taskId=(?P<id>[0-9]*): (?P<base_activity>[^\s]*) .*visible=true'
r'.*topActivity=ComponentInfo{(?P<top_activity>[^\s]*)}$')
for line in lines:
match = regex.search(line)
if match is None:
continue
current_task_id_str = match.group('id')
base_activity = match.group('base_activity')
top_activity = match.group('top_activity')
# If neither of the matched activities equals the activity we are
# looking for, we discard their task id and continue the search.
if full_activity_name not in {base_activity, top_activity}:
logging.info('Full activity %s was not found in current line %s',
full_activity_name, line)
continue
# Otherwise return the integer task id.
try:
return int(current_task_id_str)
except ValueError:
logging.info('Failed to parse task ID [%r].', current_task_id_str)
# At this point if we could not find a task ID, there's nothing we can do.
logging.error('Could not find current activity in stack list: %r', lines)
return -1
def _start_screen_pinning(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Pins an application.
Args:
request: The request containing the activity to pin.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse.
"""
full_activity = request.start_screen_pinning.full_activity
response = adb_pb2.AdbResponse(status=adb_pb2.AdbResponse.Status.OK)
if not full_activity:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
'`start_screen_pinning.full_activity` cannot be empty.')
return response
current_task_id = self._fetch_current_task_id(full_activity, timeout)
if current_task_id == -1:
response.status = adb_pb2.AdbResponse.Status.INTERNAL_ERROR
response.error_message = ('Could not find task ID for activity '
f'[{full_activity}]')
return response
response, _ = self._execute_command(
['shell', 'am', 'task', 'lock',
str(current_task_id)], timeout=timeout)
return response
def _send_broadcast(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Sends a broadcast.
Args:
request: The request with the information for the broadcast event.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse.
"""
send_brodcast = request.send_broadcast
response = adb_pb2.AdbResponse(status=adb_pb2.AdbResponse.Status.OK)
if not send_brodcast.action:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = ('`send_broadcast.{action}` cannot be empty.')
return response
response, _ = self._execute_command(
['shell', 'am', 'broadcast', '-a', send_brodcast.action],
timeout=timeout)
return response
def _install_apk(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Installs an app given its local path in the filesystem.
Args:
request: The external request with an install_apk field.
Contains information for the .apk installation.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse.
"""
install_apk = request.install_apk
response = adb_pb2.AdbResponse()
location_type = install_apk.WhichOneof('location')
logging.info('location_type: %s', location_type)
match location_type:
case 'filesystem':
fpath = install_apk.filesystem.path
if not os.path.exists(fpath):
response.status = adb_pb2.AdbResponse.Status.INTERNAL_ERROR
response.error_message = f'Could not find local_apk_path: {fpath}'
return response
case 'blob':
with tempfile.NamedTemporaryFile(
dir=self._tmp_dir, suffix='.apk', delete=False
) as f:
fpath = f.name
f.write(install_apk.blob.contents)
case _:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
f'Unsupported `install_apk.location` type: {location_type}'
)
return response
response, _ = self._execute_command(
['install', '-r', '-t', '-g', fpath], timeout=timeout
)
return response
def _start_activity(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Starts a given activity.
Options for `start_activity`:
`am start` command options:
-D: enable debugging
-W: wait for launch to complete
--start-profiler <FILE>: start profiler and send results to <FILE>
-P <FILE>: like above, but profiling stops when app goes idle
-R: repeat the activity launch <COUNT> times. Prior to each repeat,
the top activity will be finished.
-S: force stop the target app before starting the activity
--opengl-trace: enable tracing of OpenGL functions
Args:
request: The request with information on what activity to start.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse. If successful, StartActivityResponse will contain the
activity name and adb command output.
"""
activity = request.start_activity.full_activity
if not activity:
return adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.FAILED_PRECONDITION,
error_message='`start_activity.full_activity` cannot be empty.')
force_stop = '-S' if request.start_activity.force_stop else ''
response, command_output = self._execute_command(
['shell', 'am', 'start', force_stop, '-W', '-n', activity] +
list(request.start_activity.extra_args or []),
timeout=timeout)
# Check command output for potential errors.
expected_error = re.compile(r""".*Error.*""", re.VERBOSE)
if expected_error.match(str(command_output)):
return adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.INTERNAL_ERROR,
error_message=f'start_activity failed with error: {command_output}')
response.start_activity.full_activity = activity
response.start_activity.output = command_output
return response
def _press_button(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Presses a keyboard key.
Args:
request: The request with information on what button to press.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse.
"""
button = request.press_button.button
if button not in _BUTTON_TO_KEYCODE:
return adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.FAILED_PRECONDITION,
error_message=('PressButton.button must be one of '
f'[{_BUTTON_TO_KEYCODE.keys()}]. '
f'Got: {button}. Please see `adb.proto`.'))
keycode = _BUTTON_TO_KEYCODE[button]
response, command_output = self._execute_command(
['shell', 'input', 'keyevent', keycode], timeout=timeout)
response.press_button.output = command_output
return response
def _handle_uninstall_package(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Handles UninstallPackage messages.
Args:
request: The specification of what to uninstall.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse
"""
package_name = request.uninstall_package.package_name
response = adb_pb2.AdbResponse()
# Every UninstallPackage should have a package_name.
if not package_name:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
'`uninstall_package.package_name` cannot be empty.')
return response
# Get list of installed packages and issue an uninstall only if it's
# already installed.
package_response = self._handle_package_manager(
adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
list=adb_pb2.AdbRequest.PackageManagerRequest.List(
packages=adb_pb2.AdbRequest.PackageManagerRequest.List
.Packages()))))
if package_name in package_response.package_manager.list.items:
response, _ = self._execute_command(['uninstall', package_name], timeout)
else:
msg = (f'Cannot uninstall {package_name} since it is not installed.')
logging.warning(msg)
response.error_message = msg
return response
def _get_current_activity(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Fetches current activity.
Args:
request: The request with the `.get_current_activity` field set. This is
unused, but it's in the signature so that all calls are uniform.
timeout: Optional time limit in seconds.
Returns:
AdbResponse containing the current activity.
"""
del request # Unused.
response, visible_task = self._execute_command(
['shell', 'am', 'stack', 'list', '|', 'grep', '-E', 'visible=true'],
timeout=timeout)
if response.status != adb_pb2.AdbResponse.Status.OK:
return response
if not visible_task:
_, am_stack_list = self._execute_command(['shell', 'am', 'stack', 'list'],
timeout=timeout)
response.status = adb_pb2.AdbResponse.Status.INTERNAL_ERROR
response.error_message = ('Empty visible_task. `am stack list`: '
f'{am_stack_list}')
return response
visible_task = visible_task.decode('utf-8')
if sys.platform == 'win32':
visible_task_list = re.findall(
r'visible=true topActivity=ComponentInfo{(.+?)}', visible_task)
if not visible_task_list:
visible_task = ''
else:
visible_task = 'ComponentInfo{' + visible_task_list[0] + '}'
p = re.compile(r'.*\{(.*)\}')
matches = p.search(visible_task)
if matches is None:
_, am_stack_list = self._execute_command(['shell', 'am', 'stack', 'list'],
timeout=timeout)
response.status = adb_pb2.AdbResponse.Status.INTERNAL_ERROR
response.error_message = (
'Could not extract current activity. Will return nothing. '
f'`am stack list`: {am_stack_list}')
return response
response.get_current_activity.full_activity = matches.group(1)
return response
def _get_orientation(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Fetches current device orientation.
Args:
request: The request with the `.get_orientation` field set.
timeout: Optional time limit in seconds.
Returns:
AdbResponse containing the current device orientation. This is
unused, but it's in the signature so that all calls are uniform.
"""
del request # Unused.
logging.info('Getting orientation...')
response = self._handle_dumpsys(
adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(service='input')),
timeout=timeout)
output = response.dumpsys.output
if not output:
logging.error('Empty dumpsys output.')
response.status = adb_pb2.AdbResponse.Status.INTERNAL_ERROR
response.error_message = 'Failed to execute `dumpsys input`'
return response
output = output.decode('utf-8')
lines = output.split('\n') # Split by lines.
skip_next = False
for line in lines:
# There may be multiple devices in output. An invalid device can be
# identified by negative PhysicalWidth.
physical_width = re.match(r'\s+PhysicalWidth:\s+(-?\d+)px', line)
if physical_width:
skip_next = int(physical_width.group(1)) < 0
surface_orientation = re.match(r'\s+SurfaceOrientation:\s+(\d)', line)
if surface_orientation is not None:
if skip_next:
continue
orientation = surface_orientation.group(1)
logging.info('Done getting orientation: %r', orientation)
response.get_orientation.orientation = int(orientation)
return response
response.status = adb_pb2.AdbResponse.Status.INTERNAL_ERROR
response.error_message = ('Could not find SurfaceOrientation in dumpsys '
'output')
return response
def _push(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Uploads contents to the device.
Args:
request: The request with the contents to push to the device.
timeout: Optional time limit in seconds.
Returns:
An empty AdbResponse.
"""
path = request.push.path
if not path:
return adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.FAILED_PRECONDITION,
error_message='Push.path is empty.')
# Create temporary file with `push` contents.
with tempfile.NamedTemporaryFile(dir=self._tmp_dir, delete=False) as f:
fname = f.name
f.write(request.push.content)
# Issue `adb push` command to upload file.
logging.info('Uploading %r to %r.', fname, path)
response, _ = self._execute_command(['push', fname, path], timeout=timeout)
# Delete it.
os.remove(fname)
return response
def _pull(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Downloads file content from the device.
Args:
request: The request with the information on what to get from the device.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse with the contents of the specified file.
"""
path = request.pull.path
if not path:
return adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.FAILED_PRECONDITION,
error_message='Pull.path is empty.')
# Issue `adb pull` command to copy it to a temporary file.
with tempfile.NamedTemporaryFile(dir=self._tmp_dir, delete=False) as f:
fname = f.name
logging.info('Downloading %r to %r.', path, fname)
response, _ = self._execute_command(['pull', path, fname],
timeout=timeout)
# Read the content of the file.
with open(fname, 'rb') as f:
response.pull.content = f.read()
# Delete it.
os.remove(fname)
return response
def _input_text(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Inserts text as keyboard events.
Args:
request: The external request.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse
"""
text = request.input_text.text
if not text:
return adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.FAILED_PRECONDITION,
error_message='InputText.text is empty.')
response, _ = self._execute_command(['shell', 'input', 'text', text],
timeout=timeout)
return response
def _tap(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Taps the device screen.
Args:
request: The request with information on where to tap the screen.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse
"""
x = request.tap.x
y = request.tap.y
# Check for negative coordinates.
# Notice that zero coordinates are valid coordinates (i.e. the first
# column/row of the screen).
if x < 0 or y < 0:
return adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.FAILED_PRECONDITION,
error_message=(
f'Tap coordinates must be non-negative. Got: {request.tap}.'))
response, _ = self._execute_command(
['shell', 'input', 'tap', str(x),
str(y)], timeout=timeout)
return response
def _handle_settings(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Handles SettingsRequest messages.
Args:
request: The specification of what to do with settings.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse
"""
request = request.settings
response = adb_pb2.AdbResponse()
# Every SettingsRequest should have a namespace.
if request.name_space == adb_pb2.AdbRequest.SettingsRequest.Namespace.UNKNOWN:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
f'Unknown SettingsRequest.name_space. Got: {request}.')
return response
namespace = adb_pb2.AdbRequest.SettingsRequest.Namespace.Name(
request.name_space).lower()
match request.WhichOneof('verb'):
case 'get':
get = request.get
if not get.key:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
f'Empty SettingsRequest.get.key. Got: {request}.'
)
return response
response, command_output = self._execute_command(
['shell', 'settings', 'get', namespace, get.key], timeout=timeout
)
response.settings.output = command_output
case 'put':
put = request.put
if not put.key or not put.value:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
f'Empty SettingsRequest.put key or value. Got: {request}.'
)
return response
response, command_output = self._execute_command(
['shell', 'settings', 'put', namespace, put.key, put.value],
timeout=timeout,
)
response.settings.output = command_output
case 'delete_key':
delete = request.delete_key
if not delete.key:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
f'Empty SettingsRequest.delete_key.key. Got: {request}.'
)
return response
response, command_output = self._execute_command(
['shell', 'settings', 'delete', namespace, delete.key],
timeout=timeout,
)
response.settings.output = command_output
case 'reset':
reset = request.reset
# At least one of `package_name` or `mode` should be given.
if (
not reset.package_name
and reset.mode
== adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.UNKNOWN
):
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
'At least one of SettingsRequest.reset package_name or mode'
f' should be given. Got: {request}.'
)
return response
mode = adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.Name(
reset.mode
).lower()
arg = reset.package_name or mode
response, command_output = self._execute_command(
['shell', 'settings', 'reset', namespace, arg], timeout=timeout
)
response.settings.output = command_output
case 'list':
response, command_output = self._execute_command(
['shell', 'settings', 'list', namespace], timeout=timeout
)
response.settings.output = command_output
case _:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
f'Unknown SettingsRequest.verb. Got: {request}.'
)
return response
def _handle_generic(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Handles GenericRequest messages.
Args:
request: The request with the `.generic` field set indicating what `adb`
shell command to issue
timeout: Optional time limit in seconds.
Returns:
An AdbResponse
"""
response, command_output = self._execute_command(
list(request.generic.args), timeout)
response.generic.output = command_output
return response
def _handle_package_manager(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Handles PackageManagerRequest messages.
Args:
request: The request with the `.package_manager` field set containing the
sub-commands to issue to `adb pm`.
timeout: Optional time limit in seconds.
Returns:
An AdbResponse.
"""
request = request.package_manager
response = adb_pb2.AdbResponse()
match request.WhichOneof('verb'):
case 'list':
what = request.list.WhichOneof('what')
response, output = self._execute_command(
['shell', 'pm', 'list', what], timeout=timeout
)
if output:
items = output.decode('utf-8').split()
# Remove prefix for each item.
prefix = {
'features': 'feature:',
'libraries': 'library:',
'packages': 'package:',
}[what]
items = [x[len(prefix) :] for x in items if x.startswith(prefix)]
response.package_manager.list.items.extend(items)
response.package_manager.output = output
case 'clear':
package_name = request.clear.package_name
if not package_name:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
f'Empty PackageManagerRequest.clear.package_name. Got: {request}.'
)
return response
args = ['shell', 'pm', 'clear', package_name]
if request.clear.user_id:
args.insert(3, '-f')
args.insert(4, request.clear.user_id)
response, response.package_manager.output = self._execute_command(
args, timeout=timeout
)
case 'grant':
grant = request.grant
if not grant.package_name:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = '`grant.package_name` cannot be empty.'
return response
if not grant.permissions:
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = '`grant.permissions` cannot be empty.'
return response
for permission in grant.permissions:
logging.info('Granting permission: %r', permission)
response, response.package_manager.output = self._execute_command(
['shell', 'pm', 'grant', grant.package_name, permission],
timeout=timeout,
)
return response
def _handle_dumpsys(
self, request: adb_pb2.AdbRequest, timeout: float | None = None
) -> adb_pb2.AdbResponse:
"""Handles DumpsysRequest messages.
Args:
request: The request with the `.dumpsys` field set containing
sub-commands to `adb dumpsys` shell command..
timeout: Optional time limit in seconds.
Returns:
An AdbResponse.
"""
request = request.dumpsys
cmd = ['shell', 'dumpsys']
if request.timeout_sec < 0 or request.timeout_ms < 0:
response = adb_pb2.AdbResponse()
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
'DumpsysRequest.timeout_{sec, ms} should be non-negative. '
f'Got: {request}.')
return response
if request.list_only:
# `-l` cannot be combined with the following options.
if request.service or request.args or request.skip_services:
response = adb_pb2.AdbResponse()
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
'DumpsysRequest.list_only cannot be combined with other options. '
f'Got: {request}.')
return response
cmd.append('-l')
if request.timeout_sec > 0:
cmd.append('-t')
cmd.append(str(request.timeout_sec))
elif request.timeout_ms > 0:
cmd.append('-T')
cmd.append(str(request.timeout_ms))
if request.priority != adb_pb2.AdbRequest.DumpsysRequest.PriorityLevel.UNSET:
cmd.append('--priority')
cmd.append(adb_pb2.AdbRequest.DumpsysRequest.PriorityLevel.Name(
request.priority))
if request.skip_services:
if request.service:
response = adb_pb2.AdbResponse()
response.status = adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
response.error_message = (
'DumpsysRequest.skip_services cannot be combined with `service`. '
f'Got: {request}.')
return response
cmd.append('--skip')
cmd.append(','.join(request.skip_services))
if request.service:
cmd.append(request.service)
if request.args:
cmd += list(request.args)
if request.proto:
cmd.append('--proto')
response, response.dumpsys.output = self._execute_command(
cmd, timeout=timeout)
return response
| android_env-main | android_env/components/adb_call_parser.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.app_screen_checker."""
import re
from unittest import mock
from absl.testing import absltest
from android_env.components import adb_call_parser
from android_env.components import app_screen_checker
from android_env.components import errors
from android_env.proto import adb_pb2
from android_env.proto import task_pb2
def _flatten_tree(
tree: app_screen_checker._DumpsysNode, flat_tree: list[str], indent: int = 2
):
"""Appends a list of strings to `flat_tree` from `tree`."""
flat_tree.append(' ' * indent + tree.data)
for c in tree.children:
_flatten_tree(c, flat_tree, indent + 2)
class AppScreenCheckerTest(absltest.TestCase):
# Ensures that build_tree_from_dumpsys_output produces a node whose flat
# representation matches our expectation from an arbitrary hierarchy.
def test_build_tree_from_dumpsys_output(self):
dumpsys_output = """
Queen Elizabeth II
Charles
William
George
Charlotte
Louis
Harry
Archie
Anne
Peter
Savannah
Isla
Zara
Mia
Lena
Andrew
Beatrice
Eugenie
Edward
Louise
James
"""
tree = app_screen_checker.build_tree_from_dumpsys_output(dumpsys_output)
flat_tree = []
_flatten_tree(tree, flat_tree, indent=2)
self.assertEqual(flat_tree, [
' ___root___',
' Queen Elizabeth II',
' Charles',
' William',
' George',
' Charlotte',
' Louis',
' Harry',
' Archie',
' Anne',
' Peter',
' Savannah',
' Isla',
' Zara',
' Mia',
' Lena',
' Andrew',
' Beatrice',
' Eugenie',
' Edward',
' Louise',
' James',
])
# Ensures that build_tree_from_dumpsys_output produces a node whose flat
# representation matches our expectation from an arbitrary hierarchy.
def test_build_forest_from_dumpsys_output(self):
dumpsys_output = """
Tree1
Branch1
Leaf1
Leaf2
Branch2
Leaf3
Leaf4
Leaf5
Tree2
Branch3
Leaf6
Leaf7
Branch4
Leaf8
Leaf9
Leaf10
Leaf11
"""
tree = app_screen_checker.build_tree_from_dumpsys_output(dumpsys_output)
flat_tree = []
_flatten_tree(tree, flat_tree, indent=2)
self.assertEqual(flat_tree, [
' ___root___',
' Tree1',
' Branch1',
' Leaf1',
' Leaf2',
' Branch2',
' Leaf3',
' Leaf4',
' Leaf5',
' Tree2',
' Branch3',
' Leaf6',
' Leaf7',
' Branch4',
' Leaf8',
' Leaf9',
' Leaf10',
' Leaf11',
])
def test_no_view_hierarchy_matches_path(self):
dumpsys_output = """
TASK
ACTIVITY
Missing View Hierarchy
A
B
C
D
E
F
"""
expected_path = ['^A$', 'B$']
expected_view_hierarchy_path = [
re.compile(regex) for regex in expected_path
]
self.assertFalse(
app_screen_checker.matches_path(dumpsys_output,
expected_view_hierarchy_path))
def test_matches_path(self):
dumpsys_output = """
TASK
ACTIVITY
Some node we don't care
Blah
View Hierarchy
Hirohito
Akihito
Naruhito
Aiko
Fumihito
Mako
Kako
Hisahito
Masahito
"""
expected_path = ['^Hirohito$', 'Akihito$', 'Fumihito$', 'Kako$']
expected_view_hierarchy_path = [
re.compile(regex) for regex in expected_path
]
self.assertTrue(
app_screen_checker.matches_path(
dumpsys_output, expected_view_hierarchy_path, max_levels=2))
# Also check that the following path does not match anything in the tree.
expected_path = ['^Hirohito$', 'Akihito$', 'Fumihito$', 'Kenji$']
expected_view_hierarchy_path = [
re.compile(regex) for regex in expected_path
]
self.assertFalse(
app_screen_checker.matches_path(dumpsys_output,
expected_view_hierarchy_path))
def test_matches_path_one_level_deep(self):
dumpsys_output = """
TASK
ACTIVITY
Some node we don't care
Blah
Some intermediate node
View Hierarchy
Hirohito
Akihito
Naruhito
Aiko
Fumihito
Mako
Kako
Hisahito
Masahito
"""
expected_path = ['^Hirohito$', 'Akihito$', 'Fumihito$', 'Kako$']
expected_view_hierarchy_path = [
re.compile(regex) for regex in expected_path
]
self.assertTrue(
app_screen_checker.matches_path(
dumpsys_output, expected_view_hierarchy_path, max_levels=3))
# Also check that the view hierarchy is not found when searching only grand
# children of TASK.
expected_path = ['^Hirohito$', 'Akihito$', 'Fumihito$', 'Kako$']
expected_view_hierarchy_path = [
re.compile(regex) for regex in expected_path
]
self.assertFalse(
app_screen_checker.matches_path(
dumpsys_output, expected_view_hierarchy_path, max_levels=2))
def test_wait_for_app_screen_zero_timeout(self):
"""Ensures that an exception is raised if the timeout is passed."""
app_screen = task_pb2.AppScreen(activity='whatever.MyActivity')
call_parser = mock.create_autospec(adb_call_parser.AdbCallParser)
screen_checker = app_screen_checker.AppScreenChecker(
adb_call_parser=call_parser,
expected_app_screen=app_screen)
# With a zero timeout, the method should never be able to wait for the
# screen to pop up and an exception should be raised.
self.assertRaises(
errors.WaitForAppScreenError,
screen_checker.wait_for_app_screen,
timeout_sec=0.0)
def test_wait_for_app_screen_successful(self):
"""Ensures that with the right conditions, the app screen should pop up."""
app_screen = task_pb2.AppScreen(activity='my.favorite.AwesomeActivity')
call_parser = mock.create_autospec(adb_call_parser.AdbCallParser)
call_parser.parse.return_value = adb_pb2.AdbResponse(
status=adb_pb2.AdbResponse.Status.OK,
get_current_activity=adb_pb2.AdbResponse.GetCurrentActivityResponse(
full_activity='my.favorite.AwesomeActivity'))
screen_checker = app_screen_checker.AppScreenChecker(
call_parser, app_screen)
timeout = 1.0
wait_time = screen_checker.wait_for_app_screen(timeout_sec=timeout)
# The call should not generate an exception and the return value should be
# less than the timeout given.
self.assertLess(wait_time, timeout)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/app_screen_checker_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A ThreadFunction that runs and parses adb dumpsys."""
import concurrent.futures
from absl import logging
from android_env.components import app_screen_checker as app_screen_checker_lib
_Outcome = app_screen_checker_lib.AppScreenChecker.Outcome
class DumpsysThread:
"""A thread that checks if the user is in the expected app screen."""
def __init__(
self,
app_screen_checker: app_screen_checker_lib.AppScreenChecker,
check_frequency: int = 10,
max_failed_current_activity: int = 10,
):
"""Initializes the dumpsys reader thread.
This loops forever checking if the user is in the expected screen dictated
by `app_screen_checker`. These analyses are too expensive to be in the
critical path of AndroidEnv::step() so we consume them async from this
separate thread.
Args:
app_screen_checker: The class that actually determines if the current
screen matches the expected screen.
check_frequency: Integer. We only call dumpsys 1/check_frequency times in
each iteration of the while loop below.
max_failed_current_activity: Integer. We try to fetch the current activity
but sometimes it fails. If it fails more than
`max_failed_current_activity` consecutive times, we declare that the
user has exited `expected_activity`.
"""
self._app_screen_checker = app_screen_checker
self._main_loop_counter = 0
self._check_frequency = check_frequency
self._max_failed_activity_extraction = max_failed_current_activity
self._num_failed_activity_extraction = 0
self._latest_check: concurrent.futures.Future | None = None
def check_user_exited(self, timeout: float | None = None) -> bool:
"""Returns True if the user is not in the expected screen.
Args:
timeout: An optional time in seconds to block waiting for the result of
the (expensive) checking operation. If None, the function will return
immediately with `False`.
Returns:
Whether the user of the Android device has exited the expected screen
determined by `AppScreenChecker` given at __init__().
"""
# Update and check loop_counter against check_frequency.
self._main_loop_counter += 1
if (self._check_frequency <= 0 or
self._main_loop_counter < self._check_frequency):
return False
self._main_loop_counter = 0
# If the latest check is None, perform a check and return.
if self._latest_check is None:
with concurrent.futures.ThreadPoolExecutor() as executor:
self._latest_check = executor.submit(self._check_impl)
return False
# If there's a check in flight, continue only if it's finished.
if not timeout and not self._latest_check.done():
return False
v = self._latest_check.result(timeout=timeout)
self._latest_check = None # Reset the check.
return v
def _check_impl(self) -> bool:
"""The synchronous implementation of Dumpsys."""
outcome = self._app_screen_checker.matches_current_app_screen()
# We were unable to determine the current activity.
if outcome == _Outcome.FAILED_ACTIVITY_EXTRACTION:
self._num_failed_activity_extraction += 1
logging.info('self._num_failed_activity_extraction: %s',
self._num_failed_activity_extraction)
if (self._num_failed_activity_extraction >=
self._max_failed_activity_extraction):
logging.error('Maximum number of failed activity extraction reached.')
self._num_failed_activity_extraction = 0
return True
else:
self._num_failed_activity_extraction = 0
# The current app screen matches all expectations.
if (outcome == _Outcome.SUCCESS or
outcome == _Outcome.EMPTY_EXPECTED_ACTIVITY):
return False
# Player has exited the app. Terminate the episode.
elif outcome == _Outcome.UNEXPECTED_ACTIVITY:
return True
# Player has exited the main game. Terminate the episode.
elif outcome == _Outcome.UNEXPECTED_VIEW_HIERARCHY:
return True
return False
| android_env-main | android_env/components/dumpsys_thread.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for adb_call_parser."""
import builtins
import os
import subprocess
import sys
import tempfile
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
from android_env.components import adb_call_parser
from android_env.components import adb_controller
from android_env.proto import adb_pb2
class AdbCallParserTest(parameterized.TestCase):
def test_unknown_command(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir()
)
request = adb_pb2.AdbRequest()
response = parser.parse(request)
self.assertEqual(
response.status, adb_pb2.AdbResponse.Status.UNKNOWN_COMMAND
)
def test_invalid_timeout(self):
"""AdbRequest.timeout_sec must be positive."""
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir()
)
request = adb_pb2.AdbRequest()
request.tap.x = 123
request.timeout_sec = -5
response = parser.parse(request)
self.assertEqual(
response.status, adb_pb2.AdbResponse.Status.FAILED_PRECONDITION
)
@mock.patch.object(os.path, 'exists', autospec=True)
def test_install_apk_file_not_found(self, mock_exists):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir()
)
request = adb_pb2.AdbRequest()
request.install_apk.filesystem.path = '/my/home/game.apk'
mock_exists.return_value = False
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.INTERNAL_ERROR)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
@mock.patch.object(os.path, 'exists', autospec=True)
def test_install_apk_successful(self, mock_exists):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.install_apk.filesystem.path = '/my/home/game.apk'
mock_exists.return_value = True
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['install', '-r', '-t', '-g', '/my/home/game.apk'], None)
@mock.patch.object(tempfile, 'NamedTemporaryFile', autospec=True)
def test_install_apk_from_blob(self, mock_tempfile):
adb = mock.create_autospec(adb_controller.AdbController)
tmp_dir = absltest.get_default_test_tmpdir()
parser = adb_call_parser.AdbCallParser(adb, tmp_dir=tmp_dir)
request = adb_pb2.AdbRequest()
blob_content = b'A fake blob content'
request.install_apk.blob.contents = blob_content
mock_tempfile.return_value.__enter__.return_value.name = '/my/home/test.apk'
mock_tempfile.return_value.__enter__.return_value.write.return_value = None
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['install', '-r', '-t', '-g', '/my/home/test.apk'], None
)
# pytype: disable=attribute-error
mock_tempfile.assert_has_calls([
mock.call(dir=tmp_dir, suffix='.apk', delete=False), # Constructor
mock.call().__enter__(), # Enter context
mock.call().__enter__().write(blob_content), # Call write function
mock.call().__exit__(None, None, None), # Exit context
])
# pytype: enable=attribute-error
def test_start_activity_empty_full_activity(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.start_activity.extra_args.extend(['blah'])
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
def test_start_activity_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
command_output = (b'Stopping: my.project.SplashActivity\n'
b'Starting: Intent { cmp=my.project.SplashActivity }\n')
adb.execute_command.return_value = command_output
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.start_activity.full_activity = 'my.project.SplashActivity'
request.start_activity.extra_args.extend(['blah'])
request.start_activity.force_stop = True
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_has_calls([
mock.call([
'shell', 'am', 'start', '-S', '-W', '-n',
'my.project.SplashActivity', 'blah'
],
timeout=None),
])
def test_start_activity_successful_no_force_stop(self):
adb = mock.create_autospec(adb_controller.AdbController)
command_output = (b'Stopping: my.project.SplashActivity\n'
b'Starting: Intent { cmp=my.project.SplashActivity }\n')
adb.execute_command.return_value = command_output
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.start_activity.full_activity = 'my.project.SplashActivity'
request.start_activity.extra_args.extend(['blah'])
request.start_activity.force_stop = False
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_has_calls([
mock.call([
'shell', 'am', 'start', '', '-W', '-n', 'my.project.SplashActivity',
'blah'
],
timeout=None),
])
def test_start_activity_error(self):
adb = mock.create_autospec(adb_controller.AdbController)
command_output = (b'Stopping: my.project.SplashActivity\n'
b'Starting: Intent { cmp=my.project.SplashActivity }\n'
b'Error: Activity not started, unknown error code 101\n')
adb.execute_command.return_value = command_output
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.start_activity.full_activity = 'my.project.SplashActivity'
request.start_activity.extra_args.extend(['blah'])
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.INTERNAL_ERROR)
self.assertEqual(
response.error_message,
f'start_activity failed with error: {str(command_output)}')
def test_force_stop(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.force_stop.package_name = 'my.project'
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'am', 'force-stop', 'my.project'], None)
def test_grant_permissions_empty_package_name(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.package_manager.grant.permissions.extend(['perm1', 'perm2'])
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
def test_grant_permissions_empty_permissions(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.package_manager.grant.package_name = 'my.project'
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
def test_grant_permissions_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.package_manager.grant.package_name = 'my.project'
request.package_manager.grant.permissions.extend(['perm1', 'perm2'])
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_has_calls([
mock.call(['shell', 'pm', 'grant', 'my.project', 'perm1'], None),
mock.call(['shell', 'pm', 'grant', 'my.project', 'perm2'], None),
])
def test_press_button_invalid_button(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.press_button.button = 99999
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
def test_press_button_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b''
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
# HOME.
request = adb_pb2.AdbRequest()
request.press_button.button = adb_pb2.AdbRequest.PressButton.Button.HOME
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_with(
['shell', 'input', 'keyevent', 'KEYCODE_HOME'], None)
# BACK.
request = adb_pb2.AdbRequest()
request.press_button.button = adb_pb2.AdbRequest.PressButton.Button.BACK
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_with(
['shell', 'input', 'keyevent', 'KEYCODE_BACK'], None)
# ENTER.
request = adb_pb2.AdbRequest()
request.press_button.button = adb_pb2.AdbRequest.PressButton.Button.ENTER
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_with(
['shell', 'input', 'keyevent', 'KEYCODE_ENTER'], None)
def test_start_screen_pinning_package_not_found(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = (
b' taskId=12345: my.project.AnotherActivity visible=true'
b' topActivity=ComponentInfo{my.project.AnotherActivity}')
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.start_screen_pinning.full_activity = 'my.project.AmazingActivity'
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.INTERNAL_ERROR)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'am', 'stack', 'list'], None)
def test_start_screen_pinning_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = (
b' taskId=12345: my.project.AmazingActivity visible=true'
b' topActivity=ComponentInfo{my.project.AmazingActivity}')
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.start_screen_pinning.full_activity = 'my.project.AmazingActivity'
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_has_calls([
mock.call(['shell', 'am', 'stack', 'list'], None),
mock.call(['shell', 'am', 'task', 'lock', '12345'], None),
])
def test_start_screen_pinning_base_activity(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = (
b' taskId=12345: my.project.MainActivity visible=true'
b' topActivity=ComponentInfo{my.project.TopActivity}')
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.start_screen_pinning.full_activity = 'my.project.MainActivity'
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_has_calls([
mock.call(['shell', 'am', 'stack', 'list'], None),
mock.call(['shell', 'am', 'task', 'lock', '12345'], None),
])
def test_start_screen_pinning_top_activity(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = (
b' taskId=12345: my.project.MainActivity visible=true'
b' topActivity=ComponentInfo{my.project.TopActivity}')
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.start_screen_pinning.full_activity = 'my.project.TopActivity'
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_has_calls([
mock.call(['shell', 'am', 'stack', 'list'], None),
mock.call(['shell', 'am', 'task', 'lock', '12345'], None),
])
def test_send_broadcast_empty_action(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
send_broadcast=adb_pb2.AdbRequest.SendBroadcast())
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
def test_send_broadcast_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.send_broadcast.action = 'SOME-ACTION'
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
def test_uninstall_package_empty_package_name(self):
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.uninstall_package.package_name = ''
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
def test_uninstall_package_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'package:my.package'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest()
request.uninstall_package.package_name = 'my.package'
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
def test_get_current_activity_no_visible_task(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = None
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
get_current_activity=adb_pb2.AdbRequest.GetCurrentActivity())
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.INTERNAL_ERROR)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_has_calls([
mock.call(
['shell', 'am', 'stack', 'list', '|', 'grep', '-E', 'visible=true'],
None),
mock.call(['shell', 'am', 'stack', 'list'], None),
])
def test_get_orientation_empty_dumpsys(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b''
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
get_orientation=adb_pb2.AdbRequest.GetOrientationRequest())
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.INTERNAL_ERROR)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_called_once_with(['shell', 'dumpsys', 'input'],
None)
def test_get_orientation_invalid_device_no_surface_orientation(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b' PhysicalWidth: -123px'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
get_orientation=adb_pb2.AdbRequest.GetOrientationRequest())
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.INTERNAL_ERROR)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_called_once_with(['shell', 'dumpsys', 'input'],
None)
@parameterized.named_parameters(
('rotation_0', b'0', 0),
('rotation_90', b'1', 1),
('rotation_180', b'2', 2),
('rotation_270', b'3', 3),
)
def test_get_orientation_success(self, orientation, expected_orientation):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b"""
SomeRandomKey: 12345
SurfaceOrientation: """ + orientation + b"""
MoreRandomStuff: awesome_value
"""
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
get_orientation=adb_pb2.AdbRequest.GetOrientationRequest())
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
self.assertEqual(response.get_orientation.orientation, expected_orientation)
adb.execute_command.assert_called_once_with(['shell', 'dumpsys', 'input'],
None)
def test_get_current_activity_no_matches(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
get_current_activity=adb_pb2.AdbRequest.GetCurrentActivity())
for platform in ['win32', 'linux']:
with mock.patch.object(
sys, 'platform', autospec=True, return_value=platform):
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.INTERNAL_ERROR)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_has_calls([
mock.call([
'shell', 'am', 'stack', 'list', '|', 'grep', '-E',
'visible=true'
], None),
mock.call(['shell', 'am', 'stack', 'list'], None),
])
def test_get_current_activity_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'{MyAwesomeActivity}'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
get_current_activity=adb_pb2.AdbRequest.GetCurrentActivity())
for platform in ['win32', 'linux']:
with mock.patch.object(
sys, 'platform', autospec=True, return_value=platform):
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
# `execute_command` will be called once for each platform.
adb.execute_command.assert_called_with(
['shell', 'am', 'stack', 'list', '|', 'grep', '-E', 'visible=true'],
None)
self.assertEqual(response.get_current_activity.full_activity,
'MyAwesomeActivity')
def test_push_no_path(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
push=adb_pb2.AdbRequest.Push(content=b'Has content but no path'))
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
def test_push_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
push=adb_pb2.AdbRequest.Push(
content=b'My text.', path='/sdcard/my_file.txt'))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once()
args, kwargs = adb.execute_command.call_args
self.assertLen(args, 1)
cmd_args = args[0]
self.assertLen(cmd_args, 3)
self.assertEqual(cmd_args[0], 'push')
self.assertEqual(cmd_args[2], '/sdcard/my_file.txt')
self.assertIn('timeout', kwargs)
self.assertIsNone(kwargs['timeout'])
def test_pull_no_path(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(pull=adb_pb2.AdbRequest.Pull())
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
@mock.patch.object(builtins, 'open', autospec=True)
def test_pull_successful(self, mock_open):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
mock_open.return_value.__enter__ = mock_open
mock_open.return_value.read.return_value = b'S3cR3t. dO nOt TeLl ANYONE'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
pull=adb_pb2.AdbRequest.Pull(path='/sdcard/my_file.txt'))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
self.assertEqual(response.pull.content, b'S3cR3t. dO nOt TeLl ANYONE')
adb.execute_command.assert_called_once()
args, kwargs = adb.execute_command.call_args
self.assertLen(args, 1)
cmd_args = args[0]
self.assertLen(cmd_args, 3)
self.assertEqual(cmd_args[0], 'pull')
self.assertEqual(cmd_args[1], '/sdcard/my_file.txt')
self.assertIn('timeout', kwargs)
self.assertIsNone(kwargs['timeout'])
def test_input_text_no_text(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(input_text=adb_pb2.AdbRequest.InputText())
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
def test_input_text_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
input_text=adb_pb2.AdbRequest.InputText(
text='The Greatest Text of All Time'))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'input', 'text', 'The Greatest Text of All Time'], None)
@parameterized.named_parameters(
('negative_x_and_negative_y',
adb_pb2.AdbRequest(tap=adb_pb2.AdbRequest.Tap(x=-1, y=-1))),
('negative_x',
adb_pb2.AdbRequest(tap=adb_pb2.AdbRequest.Tap(x=-1, y=123))),
('negative_y',
adb_pb2.AdbRequest(tap=adb_pb2.AdbRequest.Tap(x=456, y=-1))),
)
def test_tap_failed(self, request: adb_pb2.AdbRequest):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
def test_tap_successful(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(tap=adb_pb2.AdbRequest.Tap(x=135, y=246))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'input', 'tap', '135', '246'], None)
@parameterized.named_parameters(
('empty_request', adb_pb2.AdbRequest.SettingsRequest()),
('no_namespace',
adb_pb2.AdbRequest.SettingsRequest(
get=adb_pb2.AdbRequest.SettingsRequest.Get(key='my_key'))),
('get_no_key',
adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
get=adb_pb2.AdbRequest.SettingsRequest.Get())),
('put_no_key',
adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
put=adb_pb2.AdbRequest.SettingsRequest.Put())),
('put_no_value',
adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
put=adb_pb2.AdbRequest.SettingsRequest.Put(key='another_key'))),
('delete_no_key',
adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
delete_key=adb_pb2.AdbRequest.SettingsRequest.Delete())),
('reset_no_package_name_and_no_mode',
adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
reset=adb_pb2.AdbRequest.SettingsRequest.Reset())),
)
def test_settings_failures(self, request):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(settings=request)
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
def test_settings_success_get(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'here it is!'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
get=adb_pb2.AdbRequest.SettingsRequest.Get(key='some_key'))
request = adb_pb2.AdbRequest(settings=request)
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
self.assertEqual(response.settings.output, b'here it is!')
adb.execute_command.assert_called_once_with(
['shell', 'settings', 'get', 'system', 'some_key'], None)
def test_settings_success_put(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'Done for ya!'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SECURE,
put=adb_pb2.AdbRequest.SettingsRequest.Put(key='key1', value='val2'))
request = adb_pb2.AdbRequest(settings=request)
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
self.assertEqual(response.settings.output, b'Done for ya!')
adb.execute_command.assert_called_once_with(
['shell', 'settings', 'put', 'secure', 'key1', 'val2'], None)
def test_settings_success_delete(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'Key deleted.'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.GLOBAL,
delete_key=adb_pb2.AdbRequest.SettingsRequest.Delete(key='useless_key'))
request = adb_pb2.AdbRequest(settings=request)
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
self.assertEqual(response.settings.output, b'Key deleted.')
adb.execute_command.assert_called_once_with(
['shell', 'settings', 'delete', 'global', 'useless_key'], None)
@parameterized.named_parameters(
('mode_untrusted_defaults',
adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.UNTRUSTED_DEFAULTS, '',
'untrusted_defaults'),
('mode_untrusted_clear',
adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.UNTRUSTED_CLEAR, '',
'untrusted_clear'),
('mode_trusted_defaults',
adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.TRUSTED_DEFAULTS, '',
'trusted_defaults'),
# If `package_name` is given, it takes precedence over `mode`.
('mode_unknown_package_given',
adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.UNKNOWN, 'great.package',
'great.package'),
('mode_untrusted_defaults_package_given',
adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.UNTRUSTED_DEFAULTS,
'great.package', 'great.package'),
('mode_untrusted_clear_package_given',
adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.UNTRUSTED_CLEAR,
'great.package', 'great.package'),
('mode_trusted_defaults_package_given',
adb_pb2.AdbRequest.SettingsRequest.Reset.Mode.TRUSTED_DEFAULTS,
'great.package', 'great.package'),
)
def test_settings_success_reset(self, mode, package_name, expected_arg):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'Pkg reset.'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.GLOBAL,
reset=adb_pb2.AdbRequest.SettingsRequest.Reset(
package_name=package_name, mode=mode))
request = adb_pb2.AdbRequest(settings=request)
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
self.assertEqual(response.settings.output, b'Pkg reset.')
adb.execute_command.assert_called_once_with(
['shell', 'settings', 'reset', 'global', expected_arg], None)
def test_settings_success_list(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'volume_ring=5\nvolume_system=7'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest.SettingsRequest(
name_space=adb_pb2.AdbRequest.SettingsRequest.Namespace.SYSTEM,
list=adb_pb2.AdbRequest.SettingsRequest.List())
request = adb_pb2.AdbRequest(settings=request)
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
self.assertEqual(response.settings.output,
b'volume_ring=5\nvolume_system=7')
adb.execute_command.assert_called_once_with(
['shell', 'settings', 'list', 'system'], None)
def test_generic_command(self):
adb = mock.create_autospec(adb_controller.AdbController)
expected_output = b'generic_output'
args = ['shell', 'am', 'broadcast', '-n', 'receiver', '-a', 'action']
adb.execute_command.return_value = expected_output
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
generic_request = adb_pb2.AdbRequest.GenericRequest(args=args)
request = adb_pb2.AdbRequest(generic=generic_request)
response = parser.parse(request)
self.assertEqual(adb_pb2.AdbResponse.Status.OK, response.status)
self.assertEmpty(response.error_message)
self.assertEqual(response.generic.output, expected_output)
adb.execute_command.assert_called_once_with(args, None)
def test_generic_command_adb_error(self):
adb = mock.create_autospec(adb_controller.AdbController)
args = ['shell', 'am', 'broadcast', '-n', 'receiver', '-a', 'action']
adb.execute_command.side_effect = subprocess.CalledProcessError(
cmd='cmd', output='adb_error', returncode=-1)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
generic_request = adb_pb2.AdbRequest.GenericRequest(args=args)
request = adb_pb2.AdbRequest(generic=generic_request)
response = parser.parse(request)
self.assertEqual(adb_pb2.AdbResponse.Status.ADB_ERROR, response.status)
self.assertEqual('adb_error', response.error_message)
self.assertEmpty(response.generic.output)
adb.execute_command.assert_called_once_with(args, None)
def test_generic_command_timeout(self):
adb = mock.create_autospec(adb_controller.AdbController)
args = ['shell', 'am', 'broadcast', '-n', 'receiver', '-a', 'action']
adb.execute_command.side_effect = subprocess.TimeoutExpired(
cmd='cmd', timeout=10)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
generic_request = adb_pb2.AdbRequest.GenericRequest(args=args)
request = adb_pb2.AdbRequest(generic=generic_request)
response = parser.parse(request)
self.assertEqual(adb_pb2.AdbResponse.Status.TIMEOUT, response.status)
self.assertEqual('Timeout', response.error_message)
self.assertEmpty(response.generic.output)
adb.execute_command.assert_called_once_with(args, None)
@parameterized.named_parameters(
('features',
adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
list=adb_pb2.AdbRequest.PackageManagerRequest.List(
features=adb_pb2.AdbRequest.PackageManagerRequest.List
.Features())))),
('libraries',
adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
list=adb_pb2.AdbRequest.PackageManagerRequest.List(
libraries=adb_pb2.AdbRequest.PackageManagerRequest.List
.Libraries())))),
('packages',
adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
list=adb_pb2.AdbRequest.PackageManagerRequest.List(
packages=adb_pb2.AdbRequest.PackageManagerRequest.List
.Packages())))),
)
def test_package_manager_list_bad_output(self, request):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b"""Something irrelevant."""
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
response = parser.parse(request)
response.package_manager.output = b"""Something irrelevant."""
self.assertEmpty(response.package_manager.list.items)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once()
def test_package_manager_list_features(self):
adb = mock.create_autospec(adb_controller.AdbController)
output = b"""
feature:android.hardware.audio.output
feature:android.hardware.bluetooth
feature:android.hardware.camera
feature:android.hardware.fingerprint
feature:android.software.autofill
feature:android.software.backup
feature:android.software.webview
"""
adb.execute_command.return_value = output
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
list=adb_pb2.AdbRequest.PackageManagerRequest.List(
features=adb_pb2.AdbRequest.PackageManagerRequest.List.Features(
))))
response = parser.parse(request)
self.assertEqual(response.package_manager.output, output)
self.assertEqual(response.package_manager.list.items, [
'android.hardware.audio.output',
'android.hardware.bluetooth',
'android.hardware.camera',
'android.hardware.fingerprint',
'android.software.autofill',
'android.software.backup',
'android.software.webview',
])
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'pm', 'list', 'features'], None)
def test_package_manager_list_libraries(self):
adb = mock.create_autospec(adb_controller.AdbController)
output = b"""
library:android.ext.shared
library:android.hidl.base-V1.0-java
library:android.hidl.manager-V1.0-java
library:android.net.ipsec.ike
library:android.test.base
library:android.test.mock
library:android.test.runner
library:androidx.window.sidecar
library:com.android.future.usb.accessory
library:com.android.location.provider
library:com.android.media.remotedisplay
library:com.android.mediadrm.signer
library:com.android.nfc_extras
library:com.google.android.gms
library:com.google.android.trichromelibrary
library:javax.obex
library:org.apache.http.legacy
"""
adb.execute_command.return_value = output
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
list=adb_pb2.AdbRequest.PackageManagerRequest.List(
libraries=adb_pb2.AdbRequest.PackageManagerRequest.List
.Libraries())))
response = parser.parse(request)
self.assertEqual(response.package_manager.output, output)
self.assertEqual(response.package_manager.list.items, [
'android.ext.shared',
'android.hidl.base-V1.0-java',
'android.hidl.manager-V1.0-java',
'android.net.ipsec.ike',
'android.test.base',
'android.test.mock',
'android.test.runner',
'androidx.window.sidecar',
'com.android.future.usb.accessory',
'com.android.location.provider',
'com.android.media.remotedisplay',
'com.android.mediadrm.signer',
'com.android.nfc_extras',
'com.google.android.gms',
'com.google.android.trichromelibrary',
'javax.obex',
'org.apache.http.legacy',
])
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'pm', 'list', 'libraries'], None)
def test_package_manager_list_packages(self):
adb = mock.create_autospec(adb_controller.AdbController)
output = b"""
package:com.android.phone
package:com.awesome.company
package:com.another.great.thingie
"""
adb.execute_command.return_value = output
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
list=adb_pb2.AdbRequest.PackageManagerRequest.List(
packages=adb_pb2.AdbRequest.PackageManagerRequest.List.Packages(
))))
response = parser.parse(request)
self.assertEqual(response.package_manager.output, output)
self.assertEqual(response.package_manager.list.items, [
'com.android.phone',
'com.awesome.company',
'com.another.great.thingie',
])
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'pm', 'list', 'packages'], None)
def test_package_manager_clear_no_package_name(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b"""Something irrelevant."""
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
clear=adb_pb2.AdbRequest.PackageManagerRequest.Clear(
package_name='')))
response = parser.parse(request)
self.assertEmpty(response.package_manager.output)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
def test_package_manager_clear_successful_no_user_id(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b"""Some successful message."""
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
clear=adb_pb2.AdbRequest.PackageManagerRequest.Clear(
package_name='my.package')))
response = parser.parse(request)
self.assertEqual(response.package_manager.output,
b"""Some successful message.""")
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'pm', 'clear', 'my.package'], None)
def test_package_manager_clear_successful_with_user_id(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b"""Some successful message."""
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
clear=adb_pb2.AdbRequest.PackageManagerRequest.Clear(
package_name='my.package', user_id='mrawesome')))
response = parser.parse(request)
self.assertEqual(response.package_manager.output,
b"""Some successful message.""")
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'pm', 'clear', '-f', 'mrawesome', 'my.package'], None)
def test_dumpsys_empty_request(self):
"""An empty `DumpsysRequest` is a valid request."""
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(dumpsys=adb_pb2.AdbRequest.DumpsysRequest())
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(['shell', 'dumpsys'],
timeout=None)
@parameterized.named_parameters(
('negative_timeout_sec',
adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(timeout_sec=-1))),
('negative_timeout_ms',
adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(timeout_ms=-2))),
)
def test_dumpsys_negative_timeouts(self, request):
"""`DumpsysRequest.timeout_{sec, ms}` if passed, should be positive."""
adb = mock.create_autospec(adb_controller.AdbController)
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
@parameterized.named_parameters(
('both_timeouts_zero', 0, 0, ['shell', 'dumpsys']),
('sec_takes_precedence_zero', 123, 0, ['shell', 'dumpsys', '-t', '123']),
('sec_takes_precedence', 123, 456, ['shell', 'dumpsys', '-t', '123']),
('ms_if_no_sec', 0, 456, ['shell', 'dumpsys', '-T', '456']),
)
def test_dumpsys_timeout_successful(self, timeout_sec, timeout_ms, expected):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(
timeout_sec=timeout_sec, timeout_ms=timeout_ms))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(expected, timeout=None)
@parameterized.named_parameters(
('priority_undefined',
adb_pb2.AdbRequest.DumpsysRequest.PriorityLevel.UNSET,
['shell', 'dumpsys']),
('priority_normal',
adb_pb2.AdbRequest.DumpsysRequest.PriorityLevel.NORMAL,
['shell', 'dumpsys', '--priority', 'NORMAL']),
('priority_high', adb_pb2.AdbRequest.DumpsysRequest.PriorityLevel.HIGH,
['shell', 'dumpsys', '--priority', 'HIGH']),
('priority_critical',
adb_pb2.AdbRequest.DumpsysRequest.PriorityLevel.CRITICAL,
['shell', 'dumpsys', '--priority', 'CRITICAL']),
)
def test_dumpsys_priority_timeout_successful(self, priority, expected):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(priority=priority))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(expected, timeout=None)
def test_dumpsys_list_only_cannot_be_combined(self):
"""When passing `-l`, the request cannot contain a few fields."""
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
for d in [
{
'service': 'window'
},
{
'args': ['myoption', 'anotheroption']
},
{
'skip_services': 'usb'
},
]:
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(list_only=True, **d))
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
def test_dumpsys_list_only_success(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(list_only=True))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(['shell', 'dumpsys', '-l'],
timeout=None)
def test_dumpsys_skip_services_cannot_combine_with_service(self):
"""When using `DumpsysRequest.skip_service`, it cannot contain `.service`."""
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(
service='wifi', skip_services=['window', 'usb']))
response = parser.parse(request)
self.assertEqual(response.status,
adb_pb2.AdbResponse.Status.FAILED_PRECONDITION)
self.assertNotEmpty(response.error_message)
adb.execute_command.assert_not_called()
def test_dumpsys_skip_services(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(
skip_services=['window', 'usb']))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'dumpsys', '--skip', 'window,usb'], timeout=None)
def test_dumpsys_single_service(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(service='window'))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(['shell', 'dumpsys', 'window'],
timeout=None)
def test_dumpsys_single_service_with_args(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'whatever'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(
service='window', args=['arg1', 'arg2']))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'dumpsys', 'window', 'arg1', 'arg2'], timeout=None)
def test_dumpsys_single_service_with_proto(self):
adb = mock.create_autospec(adb_controller.AdbController)
adb.execute_command.return_value = b'some binary output'
parser = adb_call_parser.AdbCallParser(
adb, tmp_dir=absltest.get_default_test_tmpdir())
request = adb_pb2.AdbRequest(
dumpsys=adb_pb2.AdbRequest.DumpsysRequest(service='window', proto=True))
response = parser.parse(request)
self.assertEqual(response.status, adb_pb2.AdbResponse.Status.OK)
self.assertEmpty(response.error_message)
adb.execute_command.assert_called_once_with(
['shell', 'dumpsys', 'window', '--proto'], timeout=None)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/adb_call_parser_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.adb_controller."""
import os
import subprocess
import time
from unittest import mock
from absl.testing import absltest
from android_env.components import adb_controller as adb_controller_lib
from android_env.components import errors
# Timeout to be used by default in tests below. Set to a small value to avoid
# hanging on a failed test.
_TIMEOUT = 2
class AdbControllerTest(absltest.TestCase):
def setUp(self):
super().setUp()
# Set two env vars.
os.environ['MY_ENV_VAR'] = '/some/path/'
os.environ['HOME'] = '$MY_ENV_VAR'
self._env_before = os.environ
self._adb_controller = adb_controller_lib.AdbController(
adb_path='my_adb', device_name='awesome_device', adb_server_port=9999)
@mock.patch.object(subprocess, 'check_output', autospec=True)
@mock.patch.object(time, 'sleep', autospec=True)
def test_init_server(self, mock_sleep, mock_check_output):
# Arrange.
adb_controller = adb_controller_lib.AdbController(
adb_path='my_adb', device_name='awesome_device', adb_server_port=9999)
# Act.
adb_controller.init_server(timeout=_TIMEOUT)
# Assert.
expected_env = self._env_before
expected_env['HOME'] = '/some/path/'
mock_check_output.assert_called_once_with(
['my_adb', '-P', '9999', 'devices'],
stderr=subprocess.STDOUT,
timeout=_TIMEOUT,
env=expected_env,
)
mock_sleep.assert_called_once()
@mock.patch.object(subprocess, 'check_output', autospec=True)
@mock.patch.object(time, 'sleep', autospec=True)
def test_restart_server(self, mock_sleep, mock_check_output):
# Arrange.
mock_check_output.side_effect = [
subprocess.CalledProcessError(returncode=1, cmd='blah'),
] + ['fake_output'.encode('utf-8')] * 4
adb_controller = adb_controller_lib.AdbController(
adb_path='my_adb', device_name='awesome_device', adb_server_port=9999)
# Act.
adb_controller.execute_command(['my_command'], timeout=_TIMEOUT)
# Assert.
expected_env = self._env_before
expected_env['HOME'] = '/some/path/'
mock_check_output.assert_has_calls([
mock.call(
['my_adb', '-P', '9999', '-s', 'awesome_device', 'my_command'],
stderr=subprocess.STDOUT,
timeout=_TIMEOUT,
env=expected_env,
),
mock.call(
['my_adb', '-P', '9999', 'kill-server'],
stderr=subprocess.STDOUT,
timeout=_TIMEOUT,
env=expected_env,
),
mock.call(
['my_adb', '-P', '9999', 'start-server'],
stderr=subprocess.STDOUT,
timeout=_TIMEOUT,
env=expected_env,
),
mock.call(
['my_adb', '-P', '9999', 'devices'],
stderr=subprocess.STDOUT,
timeout=_TIMEOUT,
env=expected_env,
),
mock.call(
['my_adb', '-P', '9999', '-s', 'awesome_device', 'my_command'],
stderr=subprocess.STDOUT,
timeout=_TIMEOUT,
env=expected_env,
),
])
mock_sleep.assert_has_calls(
[mock.call(0.2), mock.call(2.0), mock.call(0.2)])
@mock.patch.object(subprocess, 'check_output', autospec=True)
@mock.patch.object(time, 'sleep', autospec=True)
def test_avoid_infinite_recursion(self, mock_sleep, mock_check_output):
del mock_sleep
mock_check_output.side_effect = subprocess.CalledProcessError(
returncode=1, cmd='blah')
adb_controller = adb_controller_lib.AdbController(
adb_path='my_adb', device_name='awesome_device', adb_server_port=9999)
self.assertRaises(
errors.AdbControllerError,
adb_controller.execute_command, ['my_command'], timeout=_TIMEOUT)
class AdbControllerInitTest(absltest.TestCase):
def test_deletes_problem_env_vars(self):
os.environ['ANDROID_HOME'] = '/usr/local/Android/Sdk'
os.environ['ANDROID_ADB_SERVER_PORT'] = '1337'
adb_controller_lib.AdbController(
adb_path='my_adb',
device_name='awesome_device',
adb_server_port=9999,
default_timeout=_TIMEOUT)
self.assertNotIn('ANDROID_HOME', os.environ)
self.assertNotIn('ANDROID_ADB_SERVER_PORT', os.environ)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/adb_controller_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A component that parses and processes SetupSteps."""
import copy
import time
from typing import Any, Sequence
from absl import logging
from android_env.components import adb_call_parser as adb_call_parser_lib
from android_env.components import app_screen_checker
from android_env.components import errors
from android_env.proto import adb_pb2
from android_env.proto import task_pb2
class SetupStepInterpreter:
"""An interpreter for SetupSteps."""
def __init__(self, adb_call_parser: adb_call_parser_lib.AdbCallParser):
"""Initializes this interpreter.
Args:
adb_call_parser: An object to communicate with Android via ADB.
"""
self._adb_call_parser = adb_call_parser
self._stats = {
'error_count_adb_request': 0,
'error_count_wait_for_app_screen': 0,
'error_count_check_install': 0,
'error_count_wait_for_message': 0,
'total_time_waiting_for_app_screen': 0
}
def stats(self) -> dict[str, Any]:
return copy.deepcopy(self._stats)
def interpret(self, setup_steps: Sequence[task_pb2.SetupStep]) -> None:
"""Returns True if parsing and processing `setup_steps` is successful."""
if setup_steps:
logging.info('Executing setup steps: %s', setup_steps)
for step in setup_steps:
self._process_step_command(step)
logging.info('Done executing setup steps.')
def _process_step_command(self, step_cmd: task_pb2.SetupStep) -> None:
"""Processes a single step command from a reset or extra setup."""
if not step_cmd:
logging.info('Empty step_cmd')
return
logging.info('Executing step_cmd: %r', step_cmd)
step_type = step_cmd.WhichOneof('step')
success_condition = step_cmd.success_condition
success_check = success_condition.WhichOneof('check')
assert step_type or success_check, (
'At least one of step and success_condition must be defined.')
num_tries = 0
max_retries = max(success_condition.num_retries, 3)
latest_error = None
while num_tries < max_retries:
num_tries += 1
try:
unused_adb_response = self._execute_step_cmd(step_cmd, step_type)
time.sleep(0.5)
self._check_success(success_check, success_condition)
return
except NotImplementedError:
logging.exception('Not implemented error! Skipping this step command.')
return
except errors.AdbControllerError as error:
latest_error = error
self._stats['error_count_adb_request'] += 1
logging.exception('ADB call [%r] has failed. Try %d of %d.',
step_cmd.adb_request, num_tries, max_retries)
except errors.WaitForAppScreenError as error:
latest_error = error
self._stats['error_count_wait_for_app_screen'] += 1
logging.exception('Failed to wait for app screen. Try %d of %d.',
num_tries, max_retries)
except errors.CheckInstallError as error:
latest_error = error
self._stats['error_count_check_install'] += 1
logging.exception('Package [%r] not installed. Try %d of %d.',
success_condition.check_install.package_name,
num_tries, max_retries)
raise errors.StepCommandError(
f'Step failed: [{step_cmd}]') from latest_error
def _execute_step_cmd(
self, step_cmd: task_pb2.SetupStep, step_type: str | None
) -> adb_pb2.AdbResponse | None:
"""Executes a step command of given type."""
match step_type:
case None:
return None
case 'sleep':
time.sleep(step_cmd.sleep.time_sec)
return None
case 'adb_request':
response = self._adb_call_parser.parse(step_cmd.adb_request)
if response.status != adb_pb2.AdbResponse.Status.OK:
raise errors.AdbControllerError(
f'Failed to execute AdbRequest [{step_cmd.adb_request}].\n'
f'Status: {response.status}\n'
f'Error: {response.error_message}'
)
return response
case _:
raise NotImplementedError(f'No step command of type [{step_type}].')
def _check_success(
self,
success_check: str | None,
success_condition: task_pb2.SuccessCondition,
) -> None:
"""Checks whether the given success condition was met."""
match success_check:
case None:
return None
case 'wait_for_app_screen':
wait_for_app_screen = success_condition.wait_for_app_screen
screen_checker = app_screen_checker.AppScreenChecker(
adb_call_parser=self._adb_call_parser,
expected_app_screen=wait_for_app_screen.app_screen,
)
wait_time = screen_checker.wait_for_app_screen(
timeout_sec=wait_for_app_screen.timeout_sec
)
self._stats['total_time_waiting_for_app_screen'] += wait_time
case 'check_install':
self._check_install(success_condition.check_install)
case _:
raise NotImplementedError(f'No success check called [{success_check}].')
def _check_install(self, check_install: task_pb2.CheckInstall) -> None:
"""Checks that the given package is installed."""
package = check_install.package_name
logging.info('Checking if package is installed: [%r]', package)
request = adb_pb2.AdbRequest(
package_manager=adb_pb2.AdbRequest.PackageManagerRequest(
list=adb_pb2.AdbRequest.PackageManagerRequest.List(
packages=adb_pb2.AdbRequest.PackageManagerRequest.List.Packages(
))))
start_time = time.time()
while time.time() - start_time < check_install.timeout_sec:
response = self._adb_call_parser.parse(request)
if package in response.package_manager.list.items:
logging.info('Done confirming that package is installed.')
return
time.sleep(0.1)
logging.error('Package not found.')
raise errors.CheckInstallError()
| android_env-main | android_env/components/setup_step_interpreter.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for base_simulator."""
from unittest import mock
from absl.testing import absltest
from android_env.components import errors
# fake_simulator.FakeSimulator inherits from BaseSimulator, so there's no need
# to import it here explicitly.
from android_env.components.simulators.fake import fake_simulator
import numpy as np
class BaseSimulatorTest(absltest.TestCase):
def test_launch(self):
simulator = fake_simulator.FakeSimulator(screen_dimensions=(640, 480))
# The simulator should launch and not crash.
simulator.launch()
def test_launch_close(self):
simulator = fake_simulator.FakeSimulator()
# The simulator should launch and not crash.
simulator.launch()
# Closing the simulator should also not crash.
simulator.close()
def test_get_screenshot(self):
simulator = fake_simulator.FakeSimulator(screen_dimensions=(640, 480))
# The simulator should launch and not crash.
simulator.launch()
screenshot = simulator.get_screenshot()
np.testing.assert_equal(screenshot.shape, [640, 480, 3])
def test_print_logs_on_exception(self):
simulator = fake_simulator.FakeSimulator()
with mock.patch.object(simulator, 'get_logs') as mock_get_logs, \
mock.patch.object(simulator, '_launch_impl', autospec=True) as mock_launch:
mock_launch.side_effect = ValueError('Oh no!')
self.assertRaises(errors.SimulatorError, simulator.launch)
mock_get_logs.assert_called_once()
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/simulators/base_simulator_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A base class for talking to different types of Android simulators."""
import abc
from absl import logging
from android_env.components import adb_controller
from android_env.components import errors
from android_env.components import log_stream
from android_env.proto import state_pb2
import numpy as np
def _print_logs_on_exception(func):
"""Decorator function for printing simulator logs upon any exception."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as error:
# Calls self.get_logs since self is the first arg.
for line in args[0].get_logs().splitlines():
logging.error(line)
raise errors.SimulatorError(
'Exception caught in simulator. Please see the simulator logs '
'above for more details.') from error
return wrapper
class BaseSimulator(metaclass=abc.ABCMeta):
"""An interface for communicating with an Android simulator."""
def __init__(self, verbose_logs: bool = False):
"""Instantiates a BaseSimulator object.
The simulator may be an emulator, virtual machine or even a physical device.
Each simulator has its own AdbController that is used for internal
bookkeeping.
Args:
verbose_logs: If true, the log stream of the simulator will be verbose.
"""
self._verbose_logs = verbose_logs
# An increasing number that tracks the attempt at launching the simulator.
self._num_launch_attempts: int = 0
def get_logs(self) -> str:
"""Returns logs recorded by the simulator (if provided)."""
return 'No simulator logs provided.'
@abc.abstractmethod
def adb_device_name(self) -> str:
"""Returns the device name that the adb client will connect to."""
@abc.abstractmethod
def create_adb_controller(self) -> adb_controller.AdbController:
"""Returns an ADB controller which can communicate with this simulator."""
@abc.abstractmethod
def create_log_stream(self) -> log_stream.LogStream:
"""Creates a stream of logs from the simulator."""
@_print_logs_on_exception
def launch(self) -> None:
"""Starts the simulator."""
self._num_launch_attempts += 1
self._launch_impl()
@abc.abstractmethod
def _launch_impl(self) -> None:
"""Platform specific launch implementation."""
@abc.abstractmethod
def send_touch(self, touches: list[tuple[int, int, bool, int]]) -> None:
"""Sends a touch event to be executed on the simulator.
Args:
touches: A list of touch events. Each element in the list corresponds to a
single touch event. Each touch event tuple should have:
0 x: The horizontal coordinate of this event.
1 y: The vertical coordinate of this event.
2 is_down: Whether the finger is touching or not the screen.
3 identifier: Identifies a particular finger in a multitouch event.
"""
@abc.abstractmethod
def send_key(self, keycode: np.int32, event_type: str) -> None:
"""Sends a keyboard event.
Args:
keycode: Represents a specific keyboard key. This is platform and
simulator-specific.
event_type: Type of key event to be sent.
"""
def load_state(
self, request: state_pb2.LoadStateRequest
) -> state_pb2.LoadStateResponse:
"""Loads a state.
Args:
request: A `LoadStateRequest` containing any parameters necessary to
specify how/what state to load.
Returns:
A `LoadStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
raise NotImplementedError('This simulator does not support load_state()')
def save_state(
self, request: state_pb2.SaveStateRequest
) -> state_pb2.SaveStateResponse:
"""Saves a state.
Args:
request: A `SaveStateRequest` containing any parameters necessary to
specify how/what state to save.
Returns:
A `SaveStateResponse` containing the status, error message (if
applicable), and any other relevant information.
"""
raise NotImplementedError('This simulator does not support save_state()')
@abc.abstractmethod
def get_screenshot(self) -> np.ndarray:
"""Returns pixels representing the current screenshot of the simulator.
The output numpy array should have shape [height, width, num_channels] and
can be loaded into PIL using Image.fromarray(img, mode='RGB') and be saved
as a PNG file using my_pil.save('/tmp/my_screenshot.png', 'PNG').
"""
def close(self):
"""Frees up resources allocated by this object."""
| android_env-main | android_env/components/simulators/base_simulator.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| android_env-main | android_env/components/simulators/__init__.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| android_env-main | android_env/components/simulators/fake/__init__.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for fake_simulator."""
import re
from absl.testing import absltest
from android_env.components.simulators.fake import fake_simulator
import numpy as np
class FakeSimulatorTest(absltest.TestCase):
def test_device_name(self):
simulator = fake_simulator.FakeSimulator(screen_dimensions=(320, 480))
self.assertEqual(simulator.adb_device_name(), 'fake_simulator')
def test_launch_close(self):
# The simulator should launch and not crash.
simulator = fake_simulator.FakeSimulator(screen_dimensions=(320, 480))
simulator.launch()
# Closing the simulator should also not crash.
simulator.close()
def test_get_screenshot(self):
simulator = fake_simulator.FakeSimulator(screen_dimensions=(320, 480))
simulator.launch()
screenshot = simulator.get_screenshot()
np.testing.assert_equal(screenshot.shape, [320, 480, 3])
np.testing.assert_equal(screenshot.dtype, np.uint8)
def test_log_stream(self):
simulator = fake_simulator.FakeSimulator(screen_dimensions=(320, 480))
simulator.launch()
log_stream = simulator.create_log_stream()
# Start yielding lines from LogStream.
log_stream.resume_stream()
lines = [
'',
' 1553110400.424 5583 5658 D Tag: reward: 0.5',
' 1553110400.424 5583 5658 D Tag: reward: 1.0',
' 1553110400.424 5583 5658 D Tag: extra: my_extra [1.0]',
' 1553110400.424 5583 5658 D Tag: episode end',
]
for i, line in enumerate(log_stream.get_stream_output()):
self.assertIn(line, lines)
if i > 10:
break
def test_adb_output(self):
simulator = fake_simulator.FakeSimulator(screen_dimensions=(320, 480))
simulator.launch()
adb_controller = simulator.create_adb_controller()
line = adb_controller.execute_command(['shell', 'dumpsys', 'input'])
line = line.decode('utf-8')
matches = re.match(r'\s+SurfaceOrientation:\s+(\d)', line)
self.assertIsNotNone(matches)
orientation = matches.group(1)
self.assertEqual(orientation, '0')
line = adb_controller.execute_command(['shell', 'service', 'check', 'foo'])
line = line.decode('utf-8')
self.assertEqual(line, 'Service foo: found')
line = adb_controller.execute_command(['shell', 'am', 'stack', 'list'])
line = line.decode('utf-8')
self.assertEqual(line, 'taskId=0 fake_activity visible=true '
'topActivity=ComponentInfo{fake_activity}')
def test_send_touch(self):
simulator = fake_simulator.FakeSimulator(screen_dimensions=(320, 480))
simulator.launch()
simulator.send_touch([(0, 1, True, 0)])
simulator.send_touch([(0, 1, False, 0)])
# No assertions, we just want to ensure that `send_touch()` can be called
# without crashing anything.
def test_send_key(self):
simulator = fake_simulator.FakeSimulator(screen_dimensions=(320, 480))
simulator.launch()
simulator.send_key(np.int32(123), 'keydown')
simulator.send_key(np.int32(123), 'keyup')
simulator.send_key(np.int32(123), 'keypress')
# No assertions, we just want to ensure that `send_key()` can be called
# without crashing anything.
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/simulators/fake/fake_simulator_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Fake Simulator for testing AndroidEnv infrastructure."""
import random
import threading
import time
from absl import logging
from android_env.components import adb_controller
from android_env.components import log_stream
from android_env.components.simulators import base_simulator
import numpy as np
class FakeStream:
"""This class simulates the logs coming from ADB."""
def __init__(self):
self._values = [
'',
self._make_stdout('reward: 0.5'),
self._make_stdout('reward: 1.0'),
self._make_stdout('extra: my_extra [1.0]'),
self._make_stdout('episode end'),
]
self._kill = False
self._lock = threading.Lock()
def _make_stdout(self, data):
"""Returns a valid log output with given data as message."""
return f' 1553110400.424 5583 5658 D Tag: {data}'
def kill(self):
self._kill = True
def __iter__(self):
while True:
if self._kill:
return
else:
with self._lock:
next_value = random.choices(
self._values, weights=[0.49, 0.15, 0.15, 0.15, 0.01], k=1)[0]
time.sleep(0.1)
yield next_value
class FakeLogStream(log_stream.LogStream):
"""FakeLogStream class that wraps a FakeStream."""
def __init__(self):
super().__init__(verbose=False)
self.stream = FakeStream()
def _get_stream_output(self):
return self.stream
def stop_stream(self):
self.stream.kill()
class FakeAdbController(adb_controller.AdbController):
"""Fake adb controller for FakeSimulator."""
def execute_command(
self,
args: list[str],
timeout: float | None = None,
device_specific: bool = True,
) -> bytes:
"""Returns fake output for adb commands."""
del timeout, device_specific
# Fake "service is ready" output.
if args[:3] == ['shell', 'service', 'check']:
return f'Service {args[-1]}: found'.encode('utf-8')
# Fake dumpsys output for getting orientation.
if args == ['shell', 'dumpsys', 'input']:
return b' SurfaceOrientation: 0'
# app_screen_checker: fake_task expects 'fake_activity'.
if args[:4] == ['shell', 'am', 'stack', 'list']:
return (b'taskId=0 fake_activity visible=true '
b'topActivity=ComponentInfo{fake_activity}')
return b'fake output'
class FakeSimulator(base_simulator.BaseSimulator):
"""FakeSimulator class."""
def __init__(self,
screen_dimensions: tuple[int, int] = (480, 320),
**kwargs):
"""FakeSimulator class that can replace EmulatorSimulator in AndroidEnv.
Args:
screen_dimensions: desired screen dimensions in pixels. This determines
the shape of the screenshots returned by get_screenshot().
**kwargs: other keyword arguments for the base class.
"""
super().__init__(**kwargs)
self._screen_dimensions = np.array(screen_dimensions)
logging.info('Created FakeSimulator.')
def get_logs(self) -> str:
return 'FakeSimulator: fake logs'
def adb_device_name(self) -> str:
return 'fake_simulator'
def create_adb_controller(self):
return FakeAdbController()
def create_log_stream(self) -> log_stream.LogStream:
return FakeLogStream()
def _launch_impl(self) -> None:
pass
def send_touch(self, touches: list[tuple[int, int, bool, int]]) -> None:
del touches
def send_key(self, keycode: np.int32, event_type: str) -> None:
del keycode, event_type
def get_screenshot(self) -> np.ndarray:
return np.random.randint(
low=0, high=255, size=(*self._screen_dimensions, 3), dtype=np.uint8)
| android_env-main | android_env/components/simulators/fake/fake_simulator.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Prepares and launches an emulator process."""
import glob
import os
import subprocess
import tempfile
from absl import logging
class EmulatorLauncher:
"""Handles launching an emulator."""
def __init__(
self,
adb_path: str,
adb_port: int | None = None,
adb_server_port: int | None = None,
emulator_console_port: int | None = None,
grpc_port: int = -1,
emulator_path: str = '',
android_sdk_root: str = '',
avd_name: str = '',
android_avd_home: str = '',
run_headless: bool = False,
kvm_device: str = '/dev/kvm',
gpu_mode: str = 'swiftshader_indirect',
tmp_dir: str = '',
snapshot_name: str = '',
restrict_network: bool = False,
show_perf_stats: bool = False,
):
"""Launches an emulator.
Args:
adb_path: Filesystem path to `adb` executable binary.
adb_port: ADB port for the Android device.
adb_server_port: Port of the ADB server deamon.
emulator_console_port: Port for telnet communication with the emulator.
grpc_port: Port for gRPC communication with the emulator.
emulator_path: Path to the emulator binary.
android_sdk_root: Root directory of the Android SDK.
avd_name: Name of the AVD.
android_avd_home: Local directory for AVDs.
run_headless: Whether to run in headless mode.
kvm_device: Path to the KVM device.
gpu_mode: GPU mode override. Supported values are listed at:
https://developer.android.com/studio/run/emulator-acceleration#accel-graphics
tmp_dir: Path to directory which will hold temporary files.
snapshot_name: Name of the snapshot to load.
restrict_network: if True, will disable networking on the device. This
option is only available for emulator version > 31.3.9 (June 2022).
show_perf_stats: Whether to set `SHOW_PERF_STATS=1` when launching the
emulator to display performance and memory statistics.
"""
self._adb_path = os.path.expandvars(adb_path)
self._adb_port = adb_port
self._adb_server_port = adb_server_port
self._emulator_console_port = emulator_console_port
self._grpc_port = grpc_port
self._emulator_path = os.path.expandvars(emulator_path)
self._android_sdk_root = os.path.expandvars(android_sdk_root)
self._avd_name = avd_name
self._android_avd_home = android_avd_home
self._run_headless = run_headless
self._kvm_device = kvm_device
self._gpu_mode = gpu_mode
self._snapshot_name = snapshot_name
self._restrict_network = restrict_network
self._show_perf_stats = show_perf_stats
self._emulator = None
self._emulator_output = None
self._is_closed = False
# Create directory for tmp files.
# Note: this will be deleted once EmulatorLauncher instance is cleaned up.
os.makedirs(tmp_dir, exist_ok=True)
self._local_tmp_dir_handle = tempfile.TemporaryDirectory(
dir=tmp_dir, prefix='simulator_instance_')
self._local_tmp_dir = self._local_tmp_dir_handle.name
self._logfile_path = os.path.join(self._local_tmp_dir, 'emulator_output')
logging.info('Simulator local_tmp_dir: %s', self._local_tmp_dir)
def logfile_path(self) -> str:
return self._logfile_path
def launch_emulator_process(self) -> None:
"""Launches the emulator."""
logging.info('Booting new emulator [%s]', self._emulator_path)
# Set necessary environment variables.
base_lib_dir = self._emulator_path[:-8] + 'lib64/'
ld_library_path = ':'.join([
base_lib_dir + 'x11/', base_lib_dir + 'qt/lib/',
base_lib_dir + 'gles_swiftshader/', base_lib_dir
])
extra_env_vars = {
'ANDROID_HOME': '',
'ANDROID_SDK_ROOT': self._android_sdk_root,
'ANDROID_AVD_HOME': self._android_avd_home,
'ANDROID_EMULATOR_KVM_DEVICE': self._kvm_device,
'ANDROID_ADB_SERVER_PORT': str(self._adb_server_port),
'LD_LIBRARY_PATH': ld_library_path,
'QT_XKB_CONFIG_ROOT': str(self._emulator_path[:-8] + 'qt_config/'),
'ANDROID_EMU_ENABLE_CRASH_REPORTING': '1',
'SHOW_PERF_STATS': str(1 if self._show_perf_stats else 0),
}
logging.info('extra_env_vars: %s',
' '.join(f'{k}={v}' for k, v in extra_env_vars.items()))
env_vars = dict(os.environ).copy()
env_vars.update(extra_env_vars)
# Compile command.
grpc_port = ['-grpc', str(self._grpc_port)] if self._grpc_port >= 0 else []
run_headless = ['-no-skin', '-no-window'] if self._run_headless else []
ports = ['-ports', '%s,%s' % (self._emulator_console_port, self._adb_port)]
snapshot = [
'-snapshot', self._snapshot_name, '-feature',
'AllowSnapshotMigration,MigratableSnapshotSave'
]
snapshot = snapshot if self._snapshot_name else ['-no-snapshot']
restrict_network_args = [
'-network-user-mode-options', 'restrict=y', '-wifi-user-mode-options',
'restrict=y'
]
network_args = restrict_network_args if self._restrict_network else []
command = [
self._emulator_path,
'-adb-path',
self._adb_path,
'-gpu',
self._gpu_mode,
'-no-audio',
'-show-kernel',
'-verbose',
'-avd',
self._avd_name,
] + grpc_port + run_headless + ports + snapshot + network_args
logging.info('Emulator launch command: %s', ' '.join(command))
# Prepare logfile.
self._emulator_output = open(self._logfile_path, 'wb')
# Spawn the emulator process.
self._emulator = subprocess.Popen(
command,
env=env_vars,
stdout=self._emulator_output,
stderr=self._emulator_output)
def confirm_shutdown(self) -> None:
"""Shuts down the emulator process."""
if self._emulator is not None:
logging.info('Checking if emulator process has finished...')
try:
self._emulator.wait(timeout=30.0)
except subprocess.TimeoutExpired:
logging.exception(
'The emulator process did not finish after 30s. '
'returncode: %s. Will now try to kill() it.',
self._emulator.returncode)
self._emulator.kill()
self._emulator = None
self._emulator_output.close()
logging.info('The emulator process has finished.')
def close(self):
"""Clean up launcher files and processes."""
if not self._is_closed:
self._local_tmp_dir_handle.cleanup()
self.confirm_shutdown()
self._is_closed = True
def __del__(self):
self.close()
| android_env-main | android_env/components/simulators/emulator/emulator_launcher.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| android_env-main | android_env/components/simulators/emulator/__init__.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.emulator_simulator."""
import builtins
import os
import time
from unittest import mock
from absl.testing import absltest
from android_env.components import adb_call_parser
from android_env.components import adb_controller
from android_env.components.simulators.emulator import emulator_launcher
from android_env.components.simulators.emulator import emulator_simulator
from android_env.proto import state_pb2
import grpc
from PIL import Image
import portpicker
from android_env.proto import emulator_controller_pb2
from android_env.proto import emulator_controller_pb2_grpc
from android_env.proto import snapshot_service_pb2
class EmulatorSimulatorTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.addCleanup(mock.patch.stopall) # Disable previous patches.
self._adb_controller = mock.create_autospec(adb_controller.AdbController)
self._adb_call_parser = mock.create_autospec(adb_call_parser.AdbCallParser)
self._launcher = mock.create_autospec(emulator_launcher.EmulatorLauncher)
self._launcher.logfile_path.return_value = 'logfile_path'
self._emulator_stub = mock.create_autospec(
emulator_controller_pb2_grpc.EmulatorControllerStub)
self._grpc_channel = mock.create_autospec(grpc.Channel)
mock.patch.object(
grpc.aio, 'secure_channel', return_value=self._grpc_channel).start()
mock.patch.object(
grpc, 'secure_channel', return_value=self._grpc_channel).start()
mock.patch.object(
grpc, 'local_channel_credentials',
return_value=self._grpc_channel).start()
self._mock_future = mock.create_autospec(grpc.Future)
mock.patch.object(
grpc, 'channel_ready_future', return_value=self._mock_future).start()
mock.patch.object(time, 'time', return_value=12345).start()
mock.patch.object(
adb_controller, 'AdbController',
return_value=self._adb_controller).start()
mock.patch.object(
adb_call_parser,
'AdbCallParser',
autospec=True,
return_value=self._adb_call_parser).start()
mock.patch.object(
emulator_launcher, 'EmulatorLauncher',
return_value=self._launcher).start()
def test_adb_device_name_not_empty(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
})
self.assertNotEmpty(simulator.adb_device_name())
@mock.patch.object(os.path, 'exists', autospec=True, return_value=True)
@mock.patch.object(builtins, 'open', autospec=True)
def test_logfile_path(self, mock_open, unused_mock_exists):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
logfile_path='fake/logfile/path',
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
})
mock_open.return_value.__enter__.return_value.read.return_value = (
'fake_logs'.encode('utf-8'))
logs = simulator.get_logs()
mock_open.assert_called_once_with('fake/logfile/path', 'rb')
self.assertEqual(logs, 'fake_logs')
@mock.patch.object(portpicker, 'is_port_free', return_value=True)
def test_grpc_port(self, unused_mock_portpicker):
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=absltest.get_default_test_tmpdir(),
emulator_launcher_args={},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
'prompt_regex': 'awesome>',
})
self.assertEqual(simulator._grpc_port, 8554)
@mock.patch.object(portpicker, 'is_port_free', return_value=False)
def test_grpc_port_unavailable(self, unused_mock_portpicker):
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=absltest.get_default_test_tmpdir(),
emulator_launcher_args={},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
'prompt_regex': 'awesome>',
})
self.assertNotEqual(simulator._grpc_port, 8554)
def test_launch(self):
# Make sure that adb_controller is started before Emulator is launched.
call_order = []
self._adb_controller.init_server.side_effect = (
lambda *a, **kw: call_order.append('init_server'))
self._launcher.launch_emulator_process.side_effect = (
lambda *a, **kw: call_order.append('launch_emulator_process'))
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
'prompt_regex': 'awesome>',
})
# The simulator should launch and not crash.
simulator.launch()
self.assertEqual(call_order, ['init_server', 'launch_emulator_process'])
def test_close(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
})
# The simulator should launch and not crash.
simulator.launch()
# For whatever reason clients may want to close the EmulatorSimulator.
# We just want to check that the simulator does not crash and/or leak
# resources.
simulator.close()
def test_value_error_if_launch_attempt_params_incorrect(self):
tmp_dir = absltest.get_default_test_tmpdir()
self.assertRaises(
ValueError,
emulator_simulator.EmulatorSimulator,
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
},
launch_n_times_without_reboot=2,
launch_n_times_without_reinstall=1,
)
def test_launch_attempt_reboot(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
},
launch_n_times_without_reboot=1,
launch_n_times_without_reinstall=2)
# The simulator should launch and not crash.
simulator.launch()
self._launcher.launch_emulator_process.assert_called_once()
self._launcher.reset_mock()
# Launch attempt 2.
simulator.launch()
self._launcher.confirm_shutdown.assert_called_once()
self._launcher.close.assert_not_called()
self._launcher.launch_emulator_process.assert_called_once()
def test_launch_attempt_reinstall_after_zero_attempts(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
},
launch_n_times_without_reboot=0,
launch_n_times_without_reinstall=0)
# The simulator should not reboot or reinstall on its very first launch.
simulator.launch()
self._launcher.launch_emulator_process.assert_called_once()
self._launcher.confirm_shutdown.assert_not_called()
self._launcher.close.assert_not_called()
# Every subsequent attempt should reboot and reinstall.
self._launcher.reset_mock()
simulator.launch()
self._launcher.confirm_shutdown.assert_called_once()
self._launcher.close.assert_called_once() # Now this should `close()`.
self._launcher.launch_emulator_process.assert_called_once()
def test_launch_attempt_reinstall(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
},
launch_n_times_without_reboot=1,
launch_n_times_without_reinstall=2)
# The simulator should launch and not crash.
simulator.launch()
self._launcher.launch_emulator_process.assert_called_once()
# Launch attempt 2.
self._launcher.reset_mock()
simulator.launch()
self._launcher.confirm_shutdown.assert_called_once()
self._launcher.close.assert_not_called() # Reboots don't `close()`.
self._launcher.launch_emulator_process.assert_called_once()
# Launch attempt 3.
self._launcher.reset_mock()
simulator.launch()
self._launcher.confirm_shutdown.assert_called_once()
self._launcher.close.assert_called_once() # Now this should `close()`.
self._launcher.launch_emulator_process.assert_called_once()
def test_get_screenshot(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
})
# The simulator should launch and not crash.
simulator.launch()
simulator._emulator_stub.getScreenshot = mock.MagicMock(
return_value=emulator_controller_pb2.Image(
format=emulator_controller_pb2.ImageFormat(width=5678, height=1234),
image=Image.new('RGBA', (1234, 5678)).tobytes(),
timestampUs=123))
screenshot = simulator.get_screenshot()
# The screenshot should have the same screen dimensions as reported by ADB
# and it should have 3 channels (RGB).
self.assertEqual(screenshot.shape, (1234, 5678, 3))
def test_load_state(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
},
)
# The simulator should launch and not crash.
simulator.launch()
with mock.patch.object(
simulator, '_snapshot_stub', create_autospec=True
) as mock_snapshot_stub:
snapshot_list = snapshot_service_pb2.SnapshotList()
snapshot_list.snapshots.add(snapshot_id='snapshot_name_foo')
snapshot_list.snapshots.add(snapshot_id='snapshot_name_bar')
mock_snapshot_stub.ListSnapshots.return_value = snapshot_list
mock_snapshot_stub.LoadSnapshot.return_value = (
snapshot_service_pb2.SnapshotPackage(success=True)
)
load_response = simulator.load_state(
request=state_pb2.LoadStateRequest(
args={'snapshot_name': 'snapshot_name_foo'}
)
)
self.assertEqual(
load_response.status, state_pb2.LoadStateResponse.Status.OK
)
load_response = simulator.load_state(
request=state_pb2.LoadStateRequest(
args={'snapshot_name': 'snapshot_name_baz'}
)
)
self.assertEqual(
load_response.status, state_pb2.LoadStateResponse.Status.NOT_FOUND
)
mock_snapshot_stub.LoadSnapshot.return_value = (
snapshot_service_pb2.SnapshotPackage(success=False, err=b'error')
)
load_response = simulator.load_state(
request=state_pb2.LoadStateRequest(
args={'snapshot_name': 'snapshot_name_bar'}
)
)
self.assertEqual(
load_response.status, state_pb2.LoadStateResponse.Status.ERROR
)
self.assertEqual(load_response.error_message, 'error')
def test_save_state(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
},
)
# The simulator should launch and not crash.
simulator.launch()
with mock.patch.object(
simulator, '_snapshot_stub', create_autospec=True
) as mock_snapshot_stub:
mock_snapshot_stub.SaveSnapshot.return_value = (
snapshot_service_pb2.SnapshotPackage(success=True)
)
save_response = simulator.save_state(
request=state_pb2.SaveStateRequest(
args={'snapshot_name': 'snapshot_name_foo'}
)
)
self.assertEqual(
save_response.status, state_pb2.SaveStateResponse.Status.OK
)
mock_snapshot_stub.SaveSnapshot.return_value = (
snapshot_service_pb2.SnapshotPackage(success=False, err=b'error')
)
save_response = simulator.save_state(
request=state_pb2.SaveStateRequest(
args={'snapshot_name': 'snapshot_name_bar'}
)
)
self.assertEqual(
save_response.status, state_pb2.SaveStateResponse.Status.ERROR
)
self.assertEqual(save_response.error_message, 'error')
def test_send_touch(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
})
# The simulator should launch and not crash.
simulator.launch()
simulator._emulator_stub.sendTouch = mock.MagicMock(return_value=None)
simulator.send_touch([(123, 456, True, 0), (135, 246, True, 1)])
simulator.send_touch([(1, 2, True, 0), (3, 4, True, 1)])
simulator.send_touch([(321, 654, False, 0), (531, 642, False, 1)])
simulator._emulator_stub.sendTouch.assert_has_calls([
mock.call(
emulator_controller_pb2.TouchEvent(touches=[{
'x': 123,
'y': 456,
'pressure': 1
}, {
'x': 135,
'y': 246,
'pressure': 1,
'identifier': 1
}])),
mock.call(
emulator_controller_pb2.TouchEvent(touches=[{
'x': 1,
'y': 2,
'pressure': 1
}, {
'x': 3,
'y': 4,
'pressure': 1,
'identifier': 1
}])),
mock.call(
emulator_controller_pb2.TouchEvent(touches=[{
'x': 321,
'y': 654,
'pressure': 0
}, {
'x': 531,
'y': 642,
'pressure': 0,
'identifier': 1
}])),
])
def test_send_key(self):
tmp_dir = absltest.get_default_test_tmpdir()
simulator = emulator_simulator.EmulatorSimulator(
tmp_dir=tmp_dir,
emulator_launcher_args={'grpc_port': 1234},
adb_controller_args={
'adb_path': '/my/adb',
'adb_server_port': 5037,
})
# The simulator should launch and not crash.
simulator.launch()
simulator._emulator_stub.sendTouch = mock.MagicMock(return_value=None)
simulator.send_key(123, 'keydown')
simulator.send_key(321, 'keydown')
simulator.send_key(321, 'keyup')
simulator.send_key(123, 'keyup')
simulator.send_key(321, 'keypress')
simulator.send_key(123, 'keypress')
simulator._emulator_stub.sendKey.assert_has_calls([
mock.call(
emulator_controller_pb2.KeyboardEvent(
codeType=emulator_controller_pb2.KeyboardEvent.KeyCodeType.XKB,
eventType=emulator_controller_pb2.KeyboardEvent.KeyEventType
.keydown,
keyCode=123,
)),
mock.call(
emulator_controller_pb2.KeyboardEvent(
codeType=emulator_controller_pb2.KeyboardEvent.KeyCodeType.XKB,
eventType=emulator_controller_pb2.KeyboardEvent.KeyEventType
.keydown,
keyCode=321,
)),
mock.call(
emulator_controller_pb2.KeyboardEvent(
codeType=emulator_controller_pb2.KeyboardEvent.KeyCodeType.XKB,
eventType=emulator_controller_pb2.KeyboardEvent.KeyEventType
.keyup,
keyCode=321,
)),
mock.call(
emulator_controller_pb2.KeyboardEvent(
codeType=emulator_controller_pb2.KeyboardEvent.KeyCodeType.XKB,
eventType=emulator_controller_pb2.KeyboardEvent.KeyEventType
.keyup,
keyCode=123,
)),
mock.call(
emulator_controller_pb2.KeyboardEvent(
codeType=emulator_controller_pb2.KeyboardEvent.KeyCodeType.XKB,
eventType=emulator_controller_pb2.KeyboardEvent.KeyEventType
.keypress,
keyCode=321,
)),
mock.call(
emulator_controller_pb2.KeyboardEvent(
codeType=emulator_controller_pb2.KeyboardEvent.KeyCodeType.XKB,
eventType=emulator_controller_pb2.KeyboardEvent.KeyEventType
.keypress,
keyCode=123,
))
])
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/simulators/emulator/emulator_simulator_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A class that manages an Android Emulator."""
import os
import time
from typing import Any
from absl import logging
from android_env.components import adb_controller
from android_env.components import adb_log_stream
from android_env.components import errors
from android_env.components import log_stream
from android_env.components.simulators import base_simulator
from android_env.components.simulators.emulator import emulator_launcher
from android_env.proto import state_pb2
import grpc
import numpy as np
import portpicker
from android_env.proto import emulator_controller_pb2
from android_env.proto import emulator_controller_pb2_grpc
from android_env.proto import snapshot_service_pb2
from android_env.proto import snapshot_service_pb2_grpc
from google.protobuf import empty_pb2
_DEFAULT_SNAPSHOT_NAME = 'default_snapshot'
def is_existing_emulator_provided(launcher_args: dict[str, Any]) -> bool:
"""Returns true if all necessary args were provided."""
return bool(
launcher_args.get('adb_port') and
launcher_args.get('emulator_console_port') and
launcher_args.get('grpc_port'))
def _pick_adb_port() -> int:
"""Tries to pick a port in the recommended range 5555-5585.
If no such port can be found, will return a random unused port. More info:
https://developer.android.com/studio/command-line/adb#howadbworks.
Returns:
port: an available port for adb.
"""
for p in range(5555, 5587, 2):
if portpicker.is_port_free(p):
return p
return portpicker.pick_unused_port()
def _pick_emulator_grpc_port() -> int:
"""Tries to pick the recommended port for grpc.
If no such port can be found, will return a random unused port. More info:
https://android.googlesource.com/platform/external/qemu/+/emu-master-dev/android/android-grpc/docs/.
Returns:
port: an available port for emulator grpc.
"""
if portpicker.is_port_free(8554):
return 8554
else:
return portpicker.pick_unused_port()
def _reconnect_on_grpc_error(func):
"""Decorator function for reconnecting to emulator upon grpc errors."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs) # pytype: disable=missing-parameter # always-use-return-annotations
except grpc.RpcError:
logging.exception('RpcError caught. Reconnecting to emulator...')
emu = args[0] # The first arg of the function is "self"
emu._emulator_stub, emu._snapshot_stub = emu._connect_to_emulator( # pylint: disable=protected-access
emu._grpc_port # pylint: disable=protected-access
)
return func(*args, **kwargs) # pytype: disable=missing-parameter # always-use-return-annotations
return wrapper
class EmulatorBootError(errors.SimulatorError):
"""Raised when an emulator failed to boot."""
class EmulatorCrashError(errors.SimulatorError):
"""Raised when a simulator crashed."""
class EmulatorSimulator(base_simulator.BaseSimulator):
"""Controls an Android Emulator."""
def __init__(
self,
emulator_launcher_args: dict[str, Any],
adb_controller_args: dict[str, Any],
tmp_dir: str = '/tmp/android_env/simulator',
logfile_path: str | None = None,
launch_n_times_without_reboot: int = 1,
launch_n_times_without_reinstall: int = 2,
**kwargs,
):
"""Instantiates an EmulatorSimulator.
Args:
emulator_launcher_args: Arguments for EmulatorLauncher.
adb_controller_args: Arguments for AdbController.
tmp_dir: Temporary directory to hold simulator files.
logfile_path: Path to file which holds emulator logs. If not provided, it
will be determined by the EmulatorLauncher.
launch_n_times_without_reboot: The number of times to try launching the
emulator before rebooting (reboot on the n+1-st try).
launch_n_times_without_reinstall: The number of times to try launching the
emulator before reinstalling (reinstall on the n+1-st try).
**kwargs: keyword arguments for base class.
"""
# If adb_port, console_port and grpc_port are all already provided,
# we assume the emulator already exists and there's no need to launch.
if is_existing_emulator_provided(emulator_launcher_args):
self._existing_emulator_provided = True
self._adb_port = emulator_launcher_args['adb_port']
self._console_port = emulator_launcher_args['emulator_console_port']
self._grpc_port = emulator_launcher_args['grpc_port']
logging.info('Connecting to existing emulator "%r"',
self.adb_device_name())
else:
self._existing_emulator_provided = False
self._adb_port = _pick_adb_port()
self._console_port = portpicker.pick_unused_port()
self._grpc_port = _pick_emulator_grpc_port()
self._channel = None
self._emulator_stub = None
self._snapshot_stub = None
# Set the image format to RGBA. The width and height of the returned
# screenshots will use the device's width and height.
self._image_format = emulator_controller_pb2.ImageFormat(
format=emulator_controller_pb2.ImageFormat.ImgFormat.RGBA8888)
if launch_n_times_without_reboot > launch_n_times_without_reinstall:
raise ValueError(
f'Number of launch attempts before reboot '
f'({launch_n_times_without_reboot}) should not be greater than '
f'number of launch attempts before reinstall '
f'({launch_n_times_without_reinstall})')
self._launch_n_times_without_reboot = launch_n_times_without_reboot
self._launch_n_times_without_reinstall = launch_n_times_without_reinstall
super().__init__(**kwargs)
# Initialize own ADB controller.
self._adb_controller_args = adb_controller_args
self._adb_controller = self.create_adb_controller()
self._adb_controller.init_server()
logging.info('Initialized simulator with ADB server port %r.',
self._adb_controller_args['adb_server_port'])
# If necessary, create EmulatorLauncher.
if self._existing_emulator_provided:
self._logfile_path = logfile_path or None
self._launcher = None
else:
emulator_launcher_args.update({
'adb_path': self._adb_controller_args['adb_path'],
'adb_port': self._adb_port,
'adb_server_port': self._adb_controller_args['adb_server_port'],
'emulator_console_port': self._console_port,
'grpc_port': self._grpc_port,
'tmp_dir': tmp_dir,
})
self._emulator_launcher_args = emulator_launcher_args
logging.info('emulator_launcher_args: %r', self._emulator_launcher_args)
self._launcher = emulator_launcher.EmulatorLauncher(
**self._emulator_launcher_args)
self._logfile_path = logfile_path or self._launcher.logfile_path()
def get_logs(self) -> str:
"""Returns logs recorded by the emulator."""
if self._logfile_path and os.path.exists(self._logfile_path):
with open(self._logfile_path, 'rb') as f:
return f.read().decode('utf-8')
else:
return f'Logfile does not exist: {self._logfile_path}.'
def adb_device_name(self) -> str:
return 'emulator-%s' % (self._adb_port - 1)
def create_adb_controller(self):
"""Returns an ADB controller which can communicate with this simulator."""
return adb_controller.AdbController(
device_name=self.adb_device_name(), **self._adb_controller_args)
def create_log_stream(self) -> log_stream.LogStream:
return adb_log_stream.AdbLogStream(
adb_command_prefix=self._adb_controller.command_prefix(),
verbose=self._verbose_logs)
def _launch_impl(self) -> None:
"""Prepares an Android Emulator for RL interaction.
The behavior depends on `self._num_launch_attempts`'s value:
* <= self._launch_n_times_without_reboot -> Normal boot behavior.
* > self._launch_n_times_without_reboot but <=
self._launch_n_times_without_reinstall -> reboot (i.e. process is
killed and started again).
* > self._launch_n_times_without_reinstall -> reinstall (i.e. process is
killed, emulator files are deleted and the process started again).
"""
logging.info('Attempt %r at launching the Android Emulator (%r)',
self._num_launch_attempts, self.adb_device_name())
if self._launcher is not None:
# If not the first time, then shutdown the emulator first.
if (self._emulator_stub is not None and
self._num_launch_attempts > self._launch_n_times_without_reboot):
self._shutdown_emulator()
# Subsequent attempts cause the emulator files to be reinstalled.
if self._num_launch_attempts > self._launch_n_times_without_reinstall:
logging.info('Closing emulator (%r)', self.adb_device_name())
self._launcher.close()
self._launcher = emulator_launcher.EmulatorLauncher(
**self._emulator_launcher_args)
self._launcher.launch_emulator_process()
# Establish grpc connection to emulator process.
self._emulator_stub, self._snapshot_stub = self._connect_to_emulator(
self._grpc_port
)
# Confirm booted status.
try:
self._confirm_booted()
except EmulatorCrashError:
logging.exception('Failed to confirm booted status of emulator.')
logging.info('Done booting the Android Emulator.')
def load_state(
self, request: state_pb2.LoadStateRequest
) -> state_pb2.LoadStateResponse:
"""Loads a state using the emulator's snapshotting mechanism.
Args:
request: The `LoadStateRequest`. In this case, `args` should be a dict
containing the key 'snapshot_name', representing the name of the
snapshot to load. If `request.args.snapshot_name` is `None`, a default
snapshot name is used.
Returns:
A response indicating whether the snapshot was successfully loaded.
* If the snapshot was loaded successfully, the status will be `OK`.
* If no snapshot of the given name was found, the status will be
`NOT_FOUND`.
* If an error occurred during the snapshot loading process, the status
will be `ERROR` and the `error_message` field will be filled.
"""
snapshot_name = request.args.get('snapshot_name', _DEFAULT_SNAPSHOT_NAME)
snapshot_list = self._snapshot_stub.ListSnapshots(
snapshot_service_pb2.SnapshotFilter(
statusFilter=snapshot_service_pb2.SnapshotFilter.LoadStatus.All
)
)
if any(
snapshot.snapshot_id == snapshot_name
for snapshot in snapshot_list.snapshots
):
snapshot_result = self._snapshot_stub.LoadSnapshot(
snapshot_service_pb2.SnapshotPackage(snapshot_id=snapshot_name)
)
if snapshot_result.success:
return state_pb2.LoadStateResponse(
status=state_pb2.LoadStateResponse.Status.OK
)
else:
return state_pb2.LoadStateResponse(
status=state_pb2.LoadStateResponse.Status.ERROR,
error_message=snapshot_result.err.decode('utf-8'),
)
else:
return state_pb2.LoadStateResponse(
status=state_pb2.LoadStateResponse.Status.NOT_FOUND
)
def save_state(
self, request: state_pb2.SaveStateRequest
) -> state_pb2.SaveStateResponse:
"""Saves a state using the emulator's snapshotting mechanism.
Args:
request: The `SaveStateRequest`. In this case, `args` should be a dict
containing the key 'snapshot_name', representing the name of the
snapshot to save. If `request.args.snapshot_name` is `None`, a default
snapshot name is used.
Returns:
A response indicating whether the snapshot was successfully saved.
* If the snapshot was saved successfully, the status will be `OK`.
* If an error occurred during the snapshot saving process, the status
will be `ERROR` and the `error_message` field will be filled.
"""
snapshot_name = request.args.get('snapshot_name', _DEFAULT_SNAPSHOT_NAME)
snapshot_result = self._snapshot_stub.SaveSnapshot(
snapshot_service_pb2.SnapshotPackage(snapshot_id=snapshot_name)
)
if snapshot_result.success:
return state_pb2.SaveStateResponse(
status=state_pb2.SaveStateResponse.Status.OK
)
else:
return state_pb2.SaveStateResponse(
status=state_pb2.SaveStateResponse.Status.ERROR,
error_message=snapshot_result.err.decode('utf-8'),
)
def _connect_to_emulator(
self,
grpc_port: int,
timeout_sec: int = 100,
) -> tuple[
emulator_controller_pb2_grpc.EmulatorControllerStub,
snapshot_service_pb2_grpc.SnapshotServiceStub,
]:
"""Connects to an emulator and returns a corresponsing stub."""
logging.info('Creating gRPC channel to the emulator on port %r', grpc_port)
port = f'localhost:{grpc_port}'
options = [('grpc.max_send_message_length', -1),
('grpc.max_receive_message_length', -1)]
creds = grpc.local_channel_credentials()
try:
self._channel = grpc.secure_channel(port, creds, options=options)
grpc.channel_ready_future(self._channel).result(timeout=timeout_sec)
except (grpc.RpcError, grpc.FutureTimeoutError) as grpc_error:
logging.exception('Failed to connect to the emulator.')
raise EmulatorBootError(
'Failed to connect to the emulator.') from grpc_error
logging.info('Added gRPC channel for the Emulator on port %s', port)
emulator_controller_stub = (
emulator_controller_pb2_grpc.EmulatorControllerStub(self._channel)
)
snapshot_stub = snapshot_service_pb2_grpc.SnapshotServiceStub(self._channel)
return emulator_controller_stub, snapshot_stub
@_reconnect_on_grpc_error
def _confirm_booted(self, startup_wait_time_sec: int = 300):
"""Waits until the emulator is fully booted."""
start_time = time.time()
deadline = start_time + startup_wait_time_sec
success = False
while time.time() < deadline:
emu_status = self._emulator_stub.getStatus(empty_pb2.Empty())
logging.info('Waiting for emulator (%r) to start... (%rms)',
self.adb_device_name(), emu_status.uptime)
if emu_status.booted:
success = True
break
time.sleep(5.0)
elapsed_time = time.time() - start_time
if not success:
raise EmulatorCrashError(
f'The emulator failed to boot after {startup_wait_time_sec} seconds')
logging.info('Done booting the emulator (in %f seconds).', elapsed_time)
logging.info('********** Emulator logs **********')
for line in self.get_logs().splitlines():
logging.info(line)
logging.info('******* End of emulator logs *******')
logging.info('See the full emulator logs at %r', self._logfile_path)
@_reconnect_on_grpc_error
def send_touch(self, touches: list[tuple[int, int, bool, int]]) -> None:
"""Sends a touch event to be executed on the simulator.
Args:
touches: A list of touch events. Each element in the list corresponds to a
single touch event. Each touch event tuple should have:
0 x: The horizontal coordinate of this event.
1 y: The vertical coordinate of this event.
2 is_down: Whether the finger is touching or not the screen.
3 identifier: Identifies a particular finger in a multitouch event.
"""
assert self._emulator_stub, 'Emulator stub has not been initialized yet.'
touch_events = [
emulator_controller_pb2.Touch(
x=t[0], y=t[1], pressure=int(t[2]), identifier=t[3])
for t in touches
]
self._emulator_stub.sendTouch(
emulator_controller_pb2.TouchEvent(touches=touch_events))
@_reconnect_on_grpc_error
def send_key(self, keycode: np.int32, event_type: str) -> None:
"""Sends a key event to the emulator.
Args:
keycode: Code representing the desired key press in XKB format.
See the emulator_controller_pb2 for details.
event_type: Type of key event to be sent.
"""
event_types = emulator_controller_pb2.KeyboardEvent.KeyEventType.keys()
if event_type not in event_types:
raise ValueError(
f'Event type must be one of {event_types} but is {event_type}.')
self._emulator_stub.sendKey(
emulator_controller_pb2.KeyboardEvent(
codeType=emulator_controller_pb2.KeyboardEvent.KeyCodeType.XKB,
eventType=emulator_controller_pb2.KeyboardEvent.KeyEventType.Value(
event_type
),
keyCode=int(keycode),
)
)
@_reconnect_on_grpc_error
def get_screenshot(self) -> np.ndarray:
"""Fetches the latest screenshot from the emulator."""
assert self._emulator_stub, 'Emulator stub has not been initialized yet.'
assert self._image_format, 'ImageFormat has not been initialized yet.'
image_proto = self._emulator_stub.getScreenshot(self._image_format)
h, w = image_proto.format.height, image_proto.format.width
image = np.frombuffer(image_proto.image, dtype='uint8', count=h * w * 4)
image.shape = (h, w, 4)
return image[:, :, :3]
@_reconnect_on_grpc_error
def _shutdown_emulator(self):
"""Sends a signal to trigger emulator shutdown."""
if self._emulator_stub is None:
logging.info('Emulator (%r) is not up.', self.adb_device_name())
return
logging.info('Shutting down the emulator (%r)...', self.adb_device_name())
self._emulator_stub.setVmState(
emulator_controller_pb2.VmRunState(
state=emulator_controller_pb2.VmRunState.RunState.SHUTDOWN))
self._launcher.confirm_shutdown()
def close(self):
if self._launcher is not None:
self._shutdown_emulator()
logging.info('Closing emulator (%r)', self.adb_device_name())
self._launcher.close()
self._emulator_stub = None
self._snapshot_stub = None
if self._channel is not None:
self._channel.close()
super().close()
| android_env-main | android_env/components/simulators/emulator/emulator_simulator.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for android_env.components.emulator_launcher."""
import builtins
import os
import subprocess
import tempfile
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
from android_env.components.simulators.emulator import emulator_launcher
class EmulatorLauncherTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self._emulator_path = 'fake/path/emulator'
self._adb_path = 'fake/path/adb'
self._adb_port = 5554
self._adb_server_port = 1234
self._emulator_console_port = 5555
self._avd_name = 'my_avd_name'
self._expected_command = [
self._emulator_path,
'-adb-path',
'fake/path/adb',
'-gpu',
'swiftshader_indirect',
'-no-audio',
'-show-kernel',
'-verbose',
'-avd',
self._avd_name,
]
self._ports = ['-ports', f'{self._emulator_console_port},{self._adb_port}']
self._snapshot = ['-no-snapshot']
base_lib_dir = self._emulator_path[:-8] + 'lib64/'
ld_library_path = ':'.join([
base_lib_dir + 'x11/', base_lib_dir + 'qt/lib/',
base_lib_dir + 'gles_swiftshader/', base_lib_dir
])
self._expected_env_vars = {
'ANDROID_HOME': '',
'ANDROID_SDK_ROOT': '',
'ANDROID_AVD_HOME': '',
'ANDROID_EMULATOR_KVM_DEVICE': '/dev/kvm',
'ANDROID_ADB_SERVER_PORT': '1234',
'LD_LIBRARY_PATH': ld_library_path,
'QT_XKB_CONFIG_ROOT': str(self._emulator_path[:-8] + 'qt_config/'),
'ANDROID_EMU_ENABLE_CRASH_REPORTING': '1',
}
@parameterized.named_parameters([
('hide_perf_stats', False),
('show_perf_stats', True),
])
@mock.patch.object(os, 'makedirs')
@mock.patch.object(os, 'environ', autospec=True, return_value=dict())
@mock.patch.object(tempfile, 'TemporaryDirectory', instance=True)
def test_launch(
self,
show_perf_stats: bool,
mock_tmp_dir,
unused_os_environ,
unused_os_makedirs,
):
mock_tmp_dir.return_value.name.return_value = 'local_tmp_dir'
launcher = emulator_launcher.EmulatorLauncher(
adb_path=self._adb_path,
adb_port=self._adb_port,
adb_server_port=self._adb_server_port,
emulator_console_port=self._emulator_console_port,
emulator_path=self._emulator_path,
avd_name=self._avd_name,
grpc_port=-1,
show_perf_stats=show_perf_stats,
)
expected_env_vars = self._expected_env_vars
expected_env_vars['SHOW_PERF_STATS'] = '1' if show_perf_stats else '0'
with mock.patch.object(
subprocess, 'Popen', autospec=True
) as emulator_init, mock.patch.object(builtins, 'open', autospec=True) as f:
f.return_value.__enter__ = f()
launcher.launch_emulator_process()
emulator_init.assert_called_once_with(
args=self._expected_command + self._ports + self._snapshot,
env=expected_env_vars,
stdout=f(),
stderr=f(),
)
@parameterized.named_parameters([
('hide_perf_stats', False),
('show_perf_stats', True),
])
@mock.patch.object(os, 'makedirs')
@mock.patch.object(os, 'environ', autospec=True, return_value=dict())
@mock.patch.object(tempfile, 'TemporaryDirectory', instance=True)
def test_grpc_port(
self,
show_perf_stats: bool,
mock_tmp_dir,
unused_os_environ,
unused_os_makedirs,
):
mock_tmp_dir.return_value.name.return_value = 'local_tmp_dir'
launcher = emulator_launcher.EmulatorLauncher(
adb_path=self._adb_path,
adb_port=self._adb_port,
adb_server_port=self._adb_server_port,
emulator_console_port=self._emulator_console_port,
emulator_path=self._emulator_path,
avd_name=self._avd_name,
grpc_port=8554,
show_perf_stats=show_perf_stats,
)
expected_env_vars = self._expected_env_vars
expected_env_vars['SHOW_PERF_STATS'] = '1' if show_perf_stats else '0'
with mock.patch.object(
subprocess, 'Popen', autospec=True
) as emulator_init, mock.patch.object(builtins, 'open', autospec=True) as f:
f.return_value.__enter__ = f()
launcher.launch_emulator_process()
emulator_init.assert_called_once_with(
args=self._expected_command
+ ['-grpc', '8554']
+ self._ports
+ self._snapshot,
env=expected_env_vars,
stdout=f(),
stderr=f(),
)
@parameterized.named_parameters([
('hide_perf_stats', False),
('show_perf_stats', True),
])
@mock.patch.object(os, 'makedirs')
@mock.patch.object(os, 'environ', autospec=True, return_value=dict())
@mock.patch.object(tempfile, 'TemporaryDirectory', instance=True)
def test_snapshot(
self,
show_perf_stats: bool,
mock_tmp_dir,
unused_os_environ,
unused_os_makedirs,
):
mock_tmp_dir.return_value.name.return_value = 'local_tmp_dir'
launcher = emulator_launcher.EmulatorLauncher(
adb_path=self._adb_path,
adb_port=self._adb_port,
adb_server_port=self._adb_server_port,
emulator_console_port=self._emulator_console_port,
emulator_path=self._emulator_path,
avd_name=self._avd_name,
grpc_port=-1,
snapshot_name='my_snapshot',
show_perf_stats=show_perf_stats,
)
expected_snapshot = [
'-snapshot', 'my_snapshot', '-feature',
'AllowSnapshotMigration,MigratableSnapshotSave'
]
expected_env_vars = self._expected_env_vars
expected_env_vars['SHOW_PERF_STATS'] = '1' if show_perf_stats else '0'
with mock.patch.object(
subprocess, 'Popen', autospec=True) as emulator_init, \
mock.patch.object(builtins, 'open', autospec=True) as f:
f.return_value.__enter__ = f()
launcher.launch_emulator_process()
emulator_init.assert_called_once_with(
args=self._expected_command + self._ports + expected_snapshot,
env=expected_env_vars,
stdout=f(),
stderr=f(),
)
@parameterized.named_parameters([
('hide_perf_stats', False),
('show_perf_stats', True),
])
@mock.patch.object(os, 'makedirs')
@mock.patch.object(os, 'environ', autospec=True, return_value=dict())
@mock.patch.object(tempfile, 'TemporaryDirectory', instance=True)
def test_network_restrict(
self,
show_perf_stats: bool,
mock_tmp_dir,
unused_os_environ,
unused_os_makedirs,
):
mock_tmp_dir.return_value.name.return_value = 'local_tmp_dir'
launcher = emulator_launcher.EmulatorLauncher(
adb_path=self._adb_path,
adb_port=self._adb_port,
adb_server_port=self._adb_server_port,
emulator_console_port=self._emulator_console_port,
emulator_path=self._emulator_path,
avd_name=self._avd_name,
grpc_port=-1,
restrict_network=True,
show_perf_stats=show_perf_stats,
)
expected_snapshot = ['-no-snapshot']
expected_network_restrict = [
'-network-user-mode-options', 'restrict=y', '-wifi-user-mode-options',
'restrict=y'
]
expected_env_vars = self._expected_env_vars
expected_env_vars['SHOW_PERF_STATS'] = '1' if show_perf_stats else '0'
with mock.patch.object(
subprocess, 'Popen', autospec=True) as emulator_init, \
mock.patch.object(builtins, 'open', autospec=True) as f:
f.return_value.__enter__ = f()
launcher.launch_emulator_process()
emulator_init.assert_called_once_with(
self._expected_command
+ self._ports
+ expected_snapshot
+ expected_network_restrict,
env=expected_env_vars,
stdout=f(),
stderr=f(),
)
if __name__ == '__main__':
absltest.main()
| android_env-main | android_env/components/simulators/emulator/emulator_launcher_test.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Acme DQN agent interacting with AndroidEnv."""
from absl import app
from absl import flags
from absl import logging
import acme
from acme import specs
from acme import wrappers as acme_wrappers
from acme.agents.tf import dqn
from acme.tf import networks
from android_env import loader
from android_env.wrappers import discrete_action_wrapper
from android_env.wrappers import float_pixels_wrapper
from android_env.wrappers import image_rescale_wrapper
# Simulator args
flags.DEFINE_string('avd_name', None, 'Name of AVD to use.')
flags.DEFINE_string('android_avd_home', '~/.android/avd', 'Path to AVD.')
flags.DEFINE_string('android_sdk_root', '~/Android/Sdk', 'Path to SDK.')
flags.DEFINE_string('emulator_path',
'~/Android/Sdk/emulator/emulator', 'Path to emulator.')
flags.DEFINE_string('adb_path',
'~/Android/Sdk/platform-tools/adb', 'Path to ADB.')
# Environment args
flags.DEFINE_string('task_path', None, 'Path to task textproto file.')
# Experiment args
flags.DEFINE_integer('num_episodes', 100, 'Number of episodes.')
FLAGS = flags.FLAGS
def apply_wrappers(env):
"""Applies a series of wrappers to the environment."""
env = discrete_action_wrapper.DiscreteActionWrapper(env, action_grid=(10, 10))
env = image_rescale_wrapper.ImageRescaleWrapper(
env, zoom_factors=(0.25, 0.25))
env = float_pixels_wrapper.FloatPixelsWrapper(env)
env = acme_wrappers.SinglePrecisionWrapper(env)
return env
def main(_):
with loader.load(
emulator_path=FLAGS.emulator_path,
android_sdk_root=FLAGS.android_sdk_root,
android_avd_home=FLAGS.android_avd_home,
avd_name=FLAGS.avd_name,
adb_path=FLAGS.adb_path,
task_path=FLAGS.task_path,
run_headless=False) as env:
env = apply_wrappers(env)
env_spec = specs.make_environment_spec(env)
agent = dqn.DQN(
environment_spec=env_spec,
network=networks.DQNAtariNetwork(
num_actions=env_spec.actions.num_values),
batch_size=10,
samples_per_insert=2,
min_replay_size=10)
loop = acme.EnvironmentLoop(env, agent)
loop.run(num_episodes=FLAGS.num_episodes)
if __name__ == '__main__':
logging.set_verbosity('info')
logging.set_stderrthreshold('info')
flags.mark_flags_as_required(['task_path', 'avd_name'])
app.run(main)
| android_env-main | examples/run_acme_agent.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Example script demonstrating usage of AndroidEnv."""
from absl import app
from absl import flags
from absl import logging
from android_env import loader
from dm_env import specs
import numpy as np
FLAGS = flags.FLAGS
# Simulator args.
flags.DEFINE_string('avd_name', None, 'Name of AVD to use.')
flags.DEFINE_string('android_avd_home', '~/.android/avd', 'Path to AVD.')
flags.DEFINE_string('android_sdk_root', '~/Android/Sdk', 'Path to SDK.')
flags.DEFINE_string('emulator_path',
'~/Android/Sdk/emulator/emulator', 'Path to emulator.')
flags.DEFINE_string('adb_path',
'~/Android/Sdk/platform-tools/adb', 'Path to ADB.')
flags.DEFINE_bool('run_headless', False,
'Whether to display the emulator window.')
# Environment args.
flags.DEFINE_string('task_path', None, 'Path to task textproto file.')
# Experiment args.
flags.DEFINE_integer('num_steps', 1000, 'Number of steps to take.')
def main(_):
with loader.load(
emulator_path=FLAGS.emulator_path,
android_sdk_root=FLAGS.android_sdk_root,
android_avd_home=FLAGS.android_avd_home,
avd_name=FLAGS.avd_name,
adb_path=FLAGS.adb_path,
task_path=FLAGS.task_path,
run_headless=FLAGS.run_headless) as env:
action_spec = env.action_spec()
def get_random_action() -> dict[str, np.ndarray]:
"""Returns a random AndroidEnv action."""
action = {}
for k, v in action_spec.items():
if isinstance(v, specs.DiscreteArray):
action[k] = np.random.randint(low=0, high=v.num_values, dtype=v.dtype)
else:
action[k] = np.random.random(size=v.shape).astype(v.dtype)
return action
_ = env.reset()
for step in range(FLAGS.num_steps):
action = get_random_action()
timestep = env.step(action=action)
reward = timestep.reward
logging.info('Step %r, action: %r, reward: %r', step, action, reward)
if __name__ == '__main__':
logging.set_verbosity('info')
logging.set_stderrthreshold('info')
flags.mark_flags_as_required(['avd_name', 'task_path'])
app.run(main)
| android_env-main | examples/run_random_agent.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Loads an interactive session where a human acts on behalf of an agent."""
import time
from typing import Any
from absl import app
from absl import flags
from absl import logging
from android_env import loader
from android_env.components import action_type
from android_env.components import utils
import dm_env
import numpy as np
import pygame
# Simulator args.
flags.DEFINE_string('avd_name', None, 'Name of AVD to use.')
flags.DEFINE_string('android_avd_home', '~/.android/avd', 'Path to AVD.')
flags.DEFINE_string('android_sdk_root', '~/Android/Sdk', 'Path to SDK.')
flags.DEFINE_string('emulator_path',
'~/Android/Sdk/emulator/emulator', 'Path to emulator.')
flags.DEFINE_string('adb_path',
'~/Android/Sdk/platform-tools/adb', 'Path to ADB.')
flags.DEFINE_boolean('run_headless', True, 'Optionally turn off display.')
# Environment args.
flags.DEFINE_string('task_path', None, 'Path to task textproto file.')
# Pygame args.
flags.DEFINE_list('screen_size', '480,720', 'Screen width, height in pixels.')
flags.DEFINE_float('frame_rate', 1.0/30.0, 'Frame rate in seconds.')
FLAGS = flags.FLAGS
def _get_action_from_event(
event: pygame.event.Event, screen: pygame.Surface, orientation: int
) -> dict[str, Any]:
"""Returns the current action by reading data from a pygame Event object."""
act_type = action_type.ActionType.LIFT
if event.type == pygame.MOUSEBUTTONDOWN:
act_type = action_type.ActionType.TOUCH
return {
'action_type':
np.array(act_type, dtype=np.int32),
'touch_position':
_scale_position(event.pos, screen, orientation),
}
def _get_action_from_mouse(
screen: pygame.Surface, orientation: int
) -> dict[str, Any]:
"""Returns the current action by reading data from the mouse."""
act_type = action_type.ActionType.LIFT
if pygame.mouse.get_pressed()[0]:
act_type = action_type.ActionType.TOUCH
return {
'action_type':
np.array(act_type, dtype=np.int32),
'touch_position':
_scale_position(pygame.mouse.get_pos(), screen, orientation),
}
def _scale_position(position: np.ndarray, screen: pygame.Surface,
orientation: int) -> np.ndarray:
"""AndroidEnv accepts mouse inputs as floats so we need to scale it."""
scaled_pos = np.divide(position, screen.get_size(), dtype=np.float32)
if orientation == 1: # LANDSCAPE_90
scaled_pos = scaled_pos[::-1]
scaled_pos[0] = 1 - scaled_pos[0]
return scaled_pos
def _accumulate_reward(
timestep: dm_env.TimeStep,
episode_return: float) -> float:
"""Accumulates rewards collected over the course of an episode."""
if timestep.reward and timestep.reward != 0:
logging.info('Reward: %s', timestep.reward)
episode_return += timestep.reward
if timestep.first():
episode_return = 0
elif timestep.last():
logging.info('Episode return: %s', episode_return)
return episode_return
def _render_pygame_frame(surface: pygame.Surface, screen: pygame.Surface,
orientation: int, timestep: dm_env.TimeStep) -> None:
"""Displays latest observation on pygame surface."""
frame = timestep.observation['pixels'][:, :, :3] # (H x W x C) (RGB)
frame = utils.transpose_pixels(frame) # (W x H x C)
frame = utils.orient_pixels(frame, orientation)
pygame.surfarray.blit_array(surface, frame)
pygame.transform.smoothscale(surface, screen.get_size(), screen)
pygame.display.flip()
def main(_):
pygame.init()
pygame.display.set_caption('android_human_agent')
with loader.load(
emulator_path=FLAGS.emulator_path,
android_sdk_root=FLAGS.android_sdk_root,
android_avd_home=FLAGS.android_avd_home,
avd_name=FLAGS.avd_name,
adb_path=FLAGS.adb_path,
task_path=FLAGS.task_path,
run_headless=FLAGS.run_headless) as env:
# Reset environment.
first_timestep = env.reset()
orientation = np.argmax(first_timestep.observation['orientation'])
# Create pygame canvas.
screen_size = list(map(int, FLAGS.screen_size)) # (W x H)
obs_shape = env.observation_spec()['pixels'].shape[:2] # (H x W)
if (orientation == 1 or orientation == 3): # LANDSCAPE_90 | LANDSCAPE_270
screen_size = screen_size[::-1]
obs_shape = obs_shape[::-1]
screen = pygame.display.set_mode(screen_size) # takes (W x H)
surface = pygame.Surface(obs_shape[::-1]) # takes (W x H)
# Start game loop.
prev_frame = time.time()
episode_return = 0
while True:
if pygame.key.get_pressed()[pygame.K_ESCAPE]:
return
all_events = pygame.event.get()
for event in all_events:
if event.type == pygame.QUIT:
return
# Filter event queue for mouse click events.
mouse_click_events = [
event for event in all_events
if event.type in [pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP]
]
# Process all mouse click events.
for event in mouse_click_events:
action = _get_action_from_event(event, screen, orientation)
timestep = env.step(action)
episode_return = _accumulate_reward(timestep, episode_return)
_render_pygame_frame(surface, screen, orientation, timestep)
# Sample the current position of the mouse either way.
action = _get_action_from_mouse(screen, orientation)
timestep = env.step(action)
episode_return = _accumulate_reward(timestep, episode_return)
_render_pygame_frame(surface, screen, orientation, timestep)
# Limit framerate.
now = time.time()
frame_time = now - prev_frame
if frame_time < FLAGS.frame_rate:
time.sleep(FLAGS.frame_rate - frame_time)
prev_frame = now
if __name__ == '__main__':
logging.set_verbosity('info')
logging.set_stderrthreshold('info')
flags.mark_flags_as_required(['avd_name', 'task_path'])
app.run(main)
| android_env-main | examples/run_human_agent.py |
# coding=utf-8
# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| android_env-main | examples/__init__.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Configure script to get build parameters from user.
This should be run before building reverb with Bazel. The easiest usage is
`python3 configure.py`. It will use the version of python to suggest the correct
paths to set for the bazel config.
Shamelessly taken from TensorFlow:
htps://github.com/tensorflow/tensorflow/blob/master/configure.py
"""
import argparse
import os
import subprocess
import sys
_REVERB_BAZELRC_FILENAME = '.reverb.bazelrc'
_REVERB_WORKSPACE_ROOT = ''
_REVERB_BAZELRC = ''
def main():
global _REVERB_WORKSPACE_ROOT
global _REVERB_BAZELRC
parser = argparse.ArgumentParser()
parser.add_argument(
'--workspace',
type=str,
default=os.path.abspath(os.path.dirname(__file__)),
help='The absolute path to your active Bazel workspace.')
parser.add_argument(
'--force_defaults',
type=bool,
default=False,
help='Whether to force the usage of default values, skipping manual selection. This can be useful for automated scripts'
)
args = parser.parse_args()
_REVERB_WORKSPACE_ROOT = args.workspace
_REVERB_BAZELRC = os.path.join(_REVERB_WORKSPACE_ROOT,
_REVERB_BAZELRC_FILENAME)
# Make a copy of os.environ to be clear when functions and getting and setting
# environment variables.
environ_cp = dict(os.environ)
reset_configure_bazelrc()
setup_python(environ_cp, args.force_defaults)
def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
var_default):
"""Get var_name either from env, or user or default.
If var_name has been set as environment variable, use the preset value, else
ask for user input. If no input is provided, the default is used.
Args:
environ_cp: copy of the os.environ.
var_name: string for name of environment variable, e.g. "TF_NEED_CUDA".
ask_for_var: string for how to ask for user input.
var_default: default value string.
Returns:
string value for var_name
"""
var = environ_cp.get(var_name)
if not var:
var = _get_input(ask_for_var)
print('\n')
if not var:
var = var_default
return var
def _get_input(question):
try:
try:
answer = raw_input(question)
except NameError:
answer = input(question) # pylint: disable=bad-builtin
except EOFError:
answer = ''
return answer
def setup_python(environ_cp, force_defaults: bool):
"""Setup python related env variables.
Args:
environ_cp: The environment dict, as `dict(os.environ)`.
force_defaults: If True, we won't be asking for user inputs. Suited for
scripts.
"""
# Get PYTHON_BIN_PATH, default is the current running python.
default_python_bin_path = sys.executable
ask_python_bin_path = ('Please specify the location of python. [Default is '
'%s]: ') % default_python_bin_path
while True:
if force_defaults:
python_bin_path = default_python_bin_path
print(f'Using Python binary {python_bin_path}')
else:
python_bin_path = get_from_env_or_user_or_default(
environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
default_python_bin_path)
# Check if the path is valid
if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
break
elif not os.path.exists(python_bin_path):
print('Invalid python path: %s cannot be found.' % python_bin_path)
if force_defaults:
return
else:
print('%s is not executable. Is it the python binary?' % python_bin_path)
if force_defaults:
return
environ_cp['PYTHON_BIN_PATH'] = ''
# Get PYTHON_LIB_PATH
python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
if not python_lib_path:
python_lib_paths = get_python_path(environ_cp, python_bin_path)
if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
python_lib_path = python_lib_paths[0]
else:
print('Found possible Python library paths:\n %s' %
'\n '.join(python_lib_paths))
default_python_lib_path = python_lib_paths[0]
if force_defaults:
python_lib_path = default_python_lib_path
print(f'Using Python lib {default_python_lib_path}')
else:
python_lib_path = _get_input(
'Please input the desired Python library path to use. '
'Default is [%s]\n' % default_python_lib_path)
if not python_lib_path:
python_lib_path = default_python_lib_path
environ_cp['PYTHON_LIB_PATH'] = python_lib_path
# Set-up env variables used by python_configure.bzl
write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
write_to_bazelrc('build --repo_env=PYTHON_BIN_PATH=\"%s"' % python_bin_path)
environ_cp['PYTHON_BIN_PATH'] = python_bin_path
# If choosen python_lib_path is from a path specified in the PYTHONPATH
# variable, need to tell bazel to include PYTHONPATH
if environ_cp.get('PYTHONPATH'):
python_paths = environ_cp.get('PYTHONPATH').split(':')
if python_lib_path in python_paths:
write_action_env_to_bazelrc('PYTHONPATH', environ_cp.get('PYTHONPATH'))
# Write tools/python_bin_path.sh
with open(os.path.join(_REVERB_WORKSPACE_ROOT, 'python_bin_path.sh'),
'w') as f:
f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
def get_python_path(environ_cp, python_bin_path):
"""Get the python site package paths."""
python_paths = []
if environ_cp.get('PYTHONPATH'):
python_paths = environ_cp.get('PYTHONPATH').split(':')
try:
stderr = open(os.devnull, 'wb')
library_paths = run_shell([
python_bin_path, '-c',
'import site; print("\\n".join(site.getsitepackages()))'
],
stderr=stderr).split('\n')
except subprocess.CalledProcessError:
library_paths = [
run_shell([
python_bin_path, '-c',
('from distutils.sysconfig import get_python_lib;'
'print(get_python_lib())')
])
]
all_paths = set(python_paths + library_paths)
paths = []
for path in all_paths:
if os.path.isdir(path):
paths.append(path)
return paths
def run_shell(cmd, allow_non_zero=False, stderr=None):
"""Get var_name either from env, or user or default.
Args:
cmd: copy of the os.environ.
allow_non_zero: string for name of environment variable, e.g. "TF_NEED
stderr: string for how to ask for user input.
Returns:
string value output of the command executed.
"""
if stderr is None:
stderr = sys.stdout
if allow_non_zero:
try:
output = subprocess.check_output(cmd, stderr=stderr)
except subprocess.CalledProcessError as e:
output = e.output
else:
output = subprocess.check_output(cmd, stderr=stderr)
return output.decode('UTF-8').strip()
def write_action_env_to_bazelrc(var_name, var):
write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
def write_to_bazelrc(line):
with open(_REVERB_BAZELRC, 'a') as f:
f.write(line + '\n')
def reset_configure_bazelrc():
"""Reset file that contains customized config settings."""
open(_REVERB_BAZELRC, 'w').close()
if __name__ == '__main__':
main()
| reverb-master | configure.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dataset to stream individual timesteps of uniform trajectories."""
from typing import Any, List, Optional, Union
from reverb import client as reverb_client
from reverb import replay_sample
import tensorflow.compat.v1 as tf
import tree
from reverb.cc.ops import gen_reverb_ops
class TimestepDataset(tf.data.Dataset):
"""A tf.data.Dataset which samples timesteps from a Reverb table.
This dataset returns individual timesteps as they are returned by a Reverb
Sampler. Items are selected from the Reverb table according to the Sampler's
selection strategy (e.g. Uniform, Fifo, etc...). When all of the timesteps
in an item have been returned, a new item is selected and the dataset begins
to return its timesteps.
It is important to note that the dataset does not provide any signal to notify
the end (or start) of an item. This is not an issue if each item only contains
one timestep, but can be problematic if the item contains multiple timesteps
(sequences). A common technique is to use
`TimestepDataset.batch(num_timestep)` where `num_timesteps` is the number of
timesteps contained in each item. Now instead of returning timesteps the
dataset will return sequences of timesteps. However in this scenario it would
be much more efficient (and less error-prone) to use the `TrajectoryDataset`
instead.
This is particularly useful if a batch of trajectories is too large to fit
onto a device's (e.g. GPU or TPU) memory. In that case use the TimestepDataset
to split the trajectories into smaller pieces that can be used on the device.
This would look something like `TimestepDataset.batch(num_timesteps / 2)`.
Note: The dataset returns `ReplaySample` where `data` with the structure of
`dtypes` and `shapes` and where all fields within `info` are scalars.
Note: Uses of Python lists are converted into tuples as nest used by the
tf.data API doesn't have good support for lists.
"""
def __init__(self,
server_address: Union[str, tf.Tensor],
table: Union[str, tf.Tensor],
dtypes: Any,
shapes: Any,
max_in_flight_samples_per_worker: int,
num_workers_per_iterator: int = -1,
max_samples_per_stream: int = -1,
rate_limiter_timeout_ms: int = -1,
max_samples: int = -1):
"""Constructs a new TimestepDataset.
Args:
server_address: Address of gRPC ReverbService.
table: Probability table to sample from.
dtypes: Dtypes of the data output. Can be nested.
shapes: Shapes of the data output. Can be nested.
max_in_flight_samples_per_worker: The number of samples requested in each
batch of samples. Higher values give higher throughput but too big
values can result in skewed sampling distributions as large number of
samples are fetched from single snapshot of the replay (followed by a
period of lower activity as the samples are consumed). A good rule of
thumb is to set this value to 2-3x times the batch size used.
num_workers_per_iterator: (Defaults to -1, i.e. auto selected) The number
of worker threads to create per dataset iterator. When the selected
table uses a FIFO sampler (i.e. a queue) then exactly 1 worker must be
used to avoid races causing invalid ordering of items. For all other
samplers, this value should be roughly equal to the number of threads
available on the CPU.
max_samples_per_stream: (Defaults to -1, i.e. auto selected) The maximum
number of samples to fetch from a stream before a new call is made.
Keeping this number low ensures that the data is fetched uniformly from
all server.
rate_limiter_timeout_ms: (Defaults to -1: infinite). Timeout (in
milliseconds) to wait on the rate limiter when sampling from the table.
If `rate_limiter_timeout_ms >= 0`, this is the timeout passed to
`Table::Sample` describing how long to wait for the rate limiter to
allow sampling. The first time that a request times out (across any of
the workers), the Dataset iterator is closed and the sequence is
considered finished.
max_samples: (Defaults to -1: infinite). The maximum number of samples to
request from the server. Once target number of samples has been fetched
and returned, the iterator is closed. This can be used to avoid the
prefetched added by the dataset.
Raises:
ValueError: If `dtypes` and `shapes` don't share the same structure.
ValueError: If `max_in_flight_samples_per_worker` is not a
positive integer.
ValueError: If `num_workers_per_iterator` is not a positive integer or -1.
ValueError: If `max_samples_per_stream` is not a positive integer or -1.
ValueError: If `rate_limiter_timeout_ms < -1`.
ValueError: If `max_samples` is not a positive integer or -1.
"""
tree.assert_same_structure(dtypes, shapes, False)
if max_in_flight_samples_per_worker < 1:
raise ValueError(
'max_in_flight_samples_per_worker (%d) must be a positive integer' %
max_in_flight_samples_per_worker)
if num_workers_per_iterator < 1 and num_workers_per_iterator != -1:
raise ValueError(
'num_workers_per_iterator (%d) must be a positive integer or -1' %
num_workers_per_iterator)
if max_samples_per_stream < 1 and max_samples_per_stream != -1:
raise ValueError(
'max_samples_per_stream (%d) must be a positive integer or -1' %
max_samples_per_stream)
if rate_limiter_timeout_ms < -1:
raise ValueError('rate_limiter_timeout_ms (%d) must be an integer >= -1' %
rate_limiter_timeout_ms)
if max_samples < 1 and max_samples != -1:
raise ValueError('max_samples (%d) must be a positive integer or -1' %
max_samples)
# Add the info fields (all scalars).
dtypes = replay_sample.ReplaySample(
info=replay_sample.SampleInfo.tf_dtypes(), data=dtypes)
shapes = replay_sample.ReplaySample(
info=replay_sample.SampleInfo.tf_shapes(), data=shapes)
# The tf.data API doesn't fully support lists so we convert all uses of
# lists into tuples.
dtypes = _convert_lists_to_tuples(dtypes)
shapes = _convert_lists_to_tuples(shapes)
self._server_address = server_address
self._table = table
self._dtypes = dtypes
self._shapes = shapes
self._max_in_flight_samples_per_worker = max_in_flight_samples_per_worker
self._num_workers_per_iterator = num_workers_per_iterator
self._max_samples_per_stream = max_samples_per_stream
self._rate_limiter_timeout_ms = rate_limiter_timeout_ms
self._max_samples = max_samples
if _is_tf1_runtime():
# Disabling to avoid errors given the different tf.data.Dataset init args
# between v1 and v2 APIs.
# pytype: disable=wrong-arg-count
super().__init__()
else:
# DatasetV2 requires the dataset as a variant tensor during init.
super().__init__(self._as_variant_tensor())
# pytype: enable=wrong-arg-count
@classmethod
def from_table_signature(cls,
server_address: str,
table: str,
max_in_flight_samples_per_worker: int,
num_workers_per_iterator: int = -1,
max_samples_per_stream: int = -1,
rate_limiter_timeout_ms: int = -1,
get_signature_timeout_secs: Optional[int] = None,
max_samples: int = -1):
"""Constructs a TimestepDataset using the table's signature to infer specs.
Note: The target `Table` must specify a signature that represents a single
timestep (as opposed to an entire trajectory). See `Table.__init__`
(./server.py) for more details.
Args:
server_address: Address of gRPC ReverbService.
table: Table to read the signature and sample from.
max_in_flight_samples_per_worker: See __init__ for details.
num_workers_per_iterator: See __init__ for details.
max_samples_per_stream: See __init__ for details.
rate_limiter_timeout_ms: See __init__ for details.
get_signature_timeout_secs: Timeout in seconds to wait for server to
respond when fetching the table signature. By default no timeout is set
and the call will block indefinitely if the server does not respond.
max_samples: See __init__ for details.
Returns:
TimestepDataset using the specs defined by the table signature to build
`shapes` and `dtypes`.
Raises:
ValueError: If `table` does not exist on server at `server_address`.
ValueError: If `table` does not have a signature.
errors.DeadlineExceededError: If `get_signature_timeout_secs` provided and
exceeded.
ValueError: See __init__.
"""
client = reverb_client.Client(server_address)
info = client.server_info(get_signature_timeout_secs)
if table not in info:
raise ValueError(
f'Server at {server_address} does not contain any table named '
f'{table}. Found: {", ".join(sorted(info.keys()))}.')
if not info[table].signature:
raise ValueError(
f'Table {table} at {server_address} does not have a signature.')
shapes = tree.map_structure(lambda x: x.shape, info[table].signature)
dtypes = tree.map_structure(lambda x: x.dtype, info[table].signature)
return cls(
server_address=server_address,
table=table,
shapes=shapes,
dtypes=dtypes,
max_in_flight_samples_per_worker=max_in_flight_samples_per_worker,
num_workers_per_iterator=num_workers_per_iterator,
max_samples_per_stream=max_samples_per_stream,
rate_limiter_timeout_ms=rate_limiter_timeout_ms,
max_samples=max_samples)
def _as_variant_tensor(self):
return gen_reverb_ops.reverb_timestep_dataset(
server_address=self._server_address,
table=self._table,
dtypes=tree.flatten(self._dtypes),
shapes=tree.flatten(self._shapes),
max_in_flight_samples_per_worker=self._max_in_flight_samples_per_worker,
num_workers_per_iterator=self._num_workers_per_iterator,
max_samples_per_stream=self._max_samples_per_stream,
rate_limiter_timeout_ms=self._rate_limiter_timeout_ms,
max_samples=self._max_samples)
def _inputs(self) -> List[Any]:
return []
@property
def element_spec(self) -> Any:
return tree.map_structure(tf.TensorSpec, self._shapes, self._dtypes)
def _convert_lists_to_tuples(structure: Any) -> Any:
list_to_tuple_fn = lambda s: tuple(s) if isinstance(s, list) else s
# Traverse depth-first, bottom-up
return tree.traverse(list_to_tuple_fn, structure, top_down=False)
def _is_tf1_runtime() -> bool:
"""Returns True if the runtime is executing with TF1.0 APIs."""
# TODO(b/145023272): Update when/if there is a better way.
return hasattr(tf, 'to_float')
| reverb-master | reverb/timestep_dataset.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Python bindings for creating and serving the Reverb ReverbService.
See ./client.py and ./tf_client.py for details of how to interact with the
service.
"""
from __future__ import annotations
import abc
import collections
from typing import Optional, Sequence
from absl import logging
import portpicker
from reverb import client
from reverb import item_selectors
from reverb import pybind
from reverb import rate_limiters
from reverb import reverb_types
from reverb.platform.default import checkpointers
import termcolor
import tree
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.framework import tensor_spec
from tensorflow.python.saved_model import nested_structure_coder
# pylint: enable=g-direct-tensorflow-import
class TableExtensionBase(metaclass=abc.ABCMeta):
"""Abstract base class for Table extensions."""
@abc.abstractmethod
def build_internal_extensions(
self,
table_name: str,
) -> Sequence[pybind.TableExtension]:
"""Constructs the c++ PriorityTableExtensions."""
class Table:
"""Item collection with configurable strategies for insertion and sampling.
A `Table` is the structure used to interact with the data stored on a server.
Each table can contain a limited number of "items" that can be retrieved
according to the strategy defined by the `sampler`. The size of a table, in
terms of number of items, is limited to `max_size`. When items are inserted
into an already full table the `remover` is used to decide which item should
be removed.
In addition to the selection strategies used to select items for retrieval and
removal the flow of data is controlled by a `RateLimiter`. A rate limiter
controlls high level relations between inserts and samples by defining a
target ratio between the two and what level of deviations from the target is
acceptable. This is particularily useful when scaling up from single machine
use cases to distributed systems as the same "logical" throughput can be kept
constant even though the scale has changed by orders of magnitude.
It is important to note that "data elements" and "items" are related but
distinct types of entities.
Data element:
- The actual data written using `Writer.append`.
- Immutable once written.
- Is not stored in a `Table`.
- Can be referenced by items from one or more distinct `Table`.
- Cannot be retrieved in any other way than as a part of an item.
Item:
- The entity stored in a `Table`.
- Inserted using `Writer.create_item`.
- References one or more data elements, creating a "sequence".
The fact that data elements can be referenced by more than one item from one
or multiple tables means thats one has to be careful not to equate the size of
a table (in terms of items) with the amount of data it references. The data
will remain in memory on the server until the last item that references it is
removed from its table. Removing an item from a table does therefore not
neccesarily result in any (significant) change in memory usage and one must be
careful when selecting remover strategies for a multi table server. Consider
for example a server with two tables. One has a FIFO remover and the other
LIFO remover. In this scenario, the two tables would not share any chunks and
would eventually consume twice the amount of memory compared a similar setup
where the two tables share the same type of removal strategy.
"""
def __init__(self,
name: str,
sampler: reverb_types.SelectorType,
remover: reverb_types.SelectorType,
max_size: int,
rate_limiter: rate_limiters.RateLimiter,
max_times_sampled: int = 0,
extensions: Sequence[TableExtensionBase] = (),
signature: Optional[reverb_types.SpecNest] = None):
"""Constructor of the Table.
Args:
name: Name of the priority table.
sampler: The strategy to use when selecting samples.
remover: The strategy to use when selecting which items to remove.
max_size: The maximum number of items which the replay is allowed to hold.
When an item is inserted into an already full priority table the
`remover` is used for selecting which item to remove before proceeding
with the new insert.
rate_limiter: Manages the data flow by limiting the sample and insert
calls.
max_times_sampled: Maximum number of times an item can be sampled before
it is deleted. Any value < 1 is ignored and means there is no limit.
extensions: Optional sequence of extensions used to add extra features to
the table.
signature: Optional nested structure containing `tf.TypeSpec` objects,
describing the schema of items in this table.
Raises:
ValueError: If name is empty.
ValueError: If max_size <= 0.
"""
if not name:
raise ValueError('name must be nonempty')
if max_size <= 0:
raise ValueError('max_size (%d) must be a positive integer' % max_size)
self._sampler = sampler
self._remover = remover
self._rate_limiter = rate_limiter
self._extensions = extensions
self._signature = signature
# Merge the c++ extensions into a single list.
internal_extensions = []
for extension in extensions:
internal_extensions += list(extension.build_internal_extensions(name))
if signature:
flat_signature = tree.flatten(signature)
for s in flat_signature:
if not isinstance(s, tensor_spec.TensorSpec):
raise ValueError(f'Unsupported signature spec: {s}')
signature_proto_str = (
nested_structure_coder.encode_structure(
signature).SerializeToString())
else:
signature_proto_str = None
self.internal_table = pybind.Table(
name=name,
sampler=sampler,
remover=remover,
max_size=max_size,
max_times_sampled=max_times_sampled,
rate_limiter=rate_limiter.internal_limiter,
extensions=internal_extensions,
signature=signature_proto_str)
@classmethod
def queue(cls,
name: str,
max_size: int,
extensions: Sequence[TableExtensionBase] = (),
signature: Optional[reverb_types.SpecNest] = None) -> Table:
"""Constructs a Table which acts like a queue.
Args:
name: Name of the priority table (aka queue).
max_size: Maximum number of items in the priority table (aka queue).
extensions: See documentation in the constructor.
signature: See documentation in the constructor.
Returns:
Table which behaves like a queue of size `max_size`.
"""
return cls(
name=name,
sampler=item_selectors.Fifo(),
remover=item_selectors.Fifo(),
max_size=max_size,
max_times_sampled=1,
rate_limiter=rate_limiters.Queue(max_size),
extensions=extensions,
signature=signature)
@classmethod
def stack(cls,
name: str,
max_size: int,
extensions: Sequence[TableExtensionBase] = (),
signature: Optional[reverb_types.SpecNest] = None) -> Table:
"""Constructs a Table which acts like a stack.
Args:
name: Name of the priority table (aka stack).
max_size: Maximum number of items in the priority table (aka stack).
extensions: See documentation in the constructor.
signature: See documentation in the constructor.
Returns:
Table which behaves like a stack of size `max_size`.
"""
return cls(
name=name,
sampler=item_selectors.Lifo(),
remover=item_selectors.Lifo(),
max_size=max_size,
max_times_sampled=1,
rate_limiter=rate_limiters.Stack(max_size),
extensions=extensions,
signature=signature)
@property
def name(self) -> str:
return self.internal_table.name()
@property
def info(self) -> reverb_types.TableInfo:
proto_string = self.internal_table.info()
return reverb_types.TableInfo.from_serialized_proto(proto_string)
def can_sample(self, num_samples: int) -> bool:
"""Returns True if a sample operation is permitted at the current state."""
return self.internal_table.can_sample(num_samples)
def can_insert(self, num_inserts: int) -> bool:
"""Returns True if an insert operation is permitted at the current state."""
return self.internal_table.can_insert(num_inserts)
def replace(self,
name: Optional[str] = None,
sampler: Optional[reverb_types.SelectorType] = None,
remover: Optional[reverb_types.SelectorType] = None,
max_size: Optional[int] = None,
rate_limiter: Optional[rate_limiters.RateLimiter] = None,
max_times_sampled: Optional[int] = None,
extensions: Optional[Sequence[TableExtensionBase]] = None,
signature: Optional[reverb_types.SpecNest] = None) -> Table:
"""Constructs a new, empty table from the definition of the current one.
All settings needed to construct the table that are not explicitly specified
are copied from the source table.
Args:
name: Name of the table to use, or None to re-use existing table's name.
sampler: The strategy to use when selecting samples, or None to re-use
existing table's sampler.
remover: The strategy to use when selecting which items to remove, or None
to re-use existing table's remover.
max_size: The maximum number of items which the replay is allowed to hold,
or None to re-use existing table's max_size.
rate_limiter: Manages the data flow by limiting the sample and insert
calls. Configuration of the original table is used when not specified.
max_times_sampled: Maximum number of times an item can be sampled before
it is deleted, or None to re-use existing table's max_size.
extensions: Optional sequence of extensions used to add extra features to
the table, or None to re-use existing table's max_size.
signature: Optional nested structure containing `tf.TypeSpec` objects,
describing the schema of items in this table, or None to re-use existing
table's max_size.
Returns:
Table with the same configuration as the original one (modulo overrides).
"""
info = self.info
if not sampler:
sampler = pybind.selector_from_proto(
info.sampler_options.SerializeToString())
if not remover:
remover = pybind.selector_from_proto(
info.remover_options.SerializeToString())
if not rate_limiter:
rate_limiter = rate_limiters.RateLimiter(
samples_per_insert=info.rate_limiter_info.samples_per_insert,
min_size_to_sample=info.rate_limiter_info.min_size_to_sample,
min_diff=info.rate_limiter_info.min_diff,
max_diff=info.rate_limiter_info.max_diff)
pick = lambda a, b: a if a is not None else b
return Table(
name=pick(name, self.name),
sampler=sampler,
remover=remover,
max_size=pick(max_size, info.max_size),
rate_limiter=rate_limiter,
max_times_sampled=pick(max_times_sampled, info.max_times_sampled),
extensions=pick(extensions, self._extensions),
signature=pick(signature, self._signature))
def __repr__(self) -> str:
return repr(self.internal_table)
class Server:
"""Reverb replay server.
The Server hosts the gRPC-service deepmind.reverb.ReverbService (see
reverb_service.proto). See ./client.py and ./tf_client for details of how to
interact with the service.
A Server maintains inserted data and one or more PriorityTables. Multiple
tables can be used to provide different views of the same underlying and since
the operations performed by the Table is relatively inexpensive compared to
operations on the actual data using multiple tables referencing the same data
is encouraged over replicating data.
"""
def __init__(self,
tables: Optional[Sequence[Table]] = None,
port: Optional[int] = None,
checkpointer: Optional[checkpointers.CheckpointerBase] = None):
"""Constructor of Server serving the ReverbService.
Args:
tables: A sequence of tables to host on the server.
port: The port number to serve the gRPC-service on. If `None` (default)
then a port is automatically picked and assigned.
checkpointer: Checkpointer used for storing/loading checkpoints. If None
(default) then `checkpointers.default_checkpointer` is used to
construct the checkpointer.
Raises:
ValueError: If tables is empty.
ValueError: If multiple Table in tables share names.
"""
if not tables:
raise ValueError('At least one table must be provided')
names = collections.Counter(table.name for table in tables)
duplicates = [name for name, count in names.items() if count > 1]
if duplicates:
raise ValueError('Multiple items in tables have the same name: {}'.format(
', '.join(duplicates)))
if port is None:
port = portpicker.pick_unused_port()
if checkpointer is None:
checkpointer = checkpointers.default_checkpointer()
self._server = pybind.Server([table.internal_table for table in tables],
port, checkpointer.internal_checkpointer())
self._port = port
def __del__(self):
"""Stop server and free up the port if was reserved through portpicker."""
if hasattr(self, '_server'):
self.stop()
if hasattr(self, '_port'):
portpicker.return_port(self._port)
def __repr__(self) -> str:
return repr(self._server)
@property
def port(self) -> int:
"""Port the gRPC service is running at."""
return self._port
def stop(self):
"""Request that the ReverbService is terminated and wait for shutdown."""
return self._server.Stop()
def wait(self):
"""Blocks until the service is shut down.
This method will never return unless the server is shut down which will only
happen if:
* `Server.stop` is called by another thread.
* A KeyboardInterrupt is raised (i.e. a SIGINT signal is sent to the
process).
Raises:
KeyboardInterrupt: If the server was killed by a SIGINT.
"""
if self._server.Wait():
raise KeyboardInterrupt
def localhost_client(self) -> client.Client:
"""Creates a client connect to the localhost channel."""
return client.Client(f'localhost:{self._port}')
| reverb-master | reverb/server.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for writer_dataset."""
import numpy as np
from reverb import pattern_dataset
from reverb import replay_sample
from reverb import structured_writer
import tensorflow as tf
# Many things we use in RLDS & tf.data do not support TF1
class PatternDatasetTest(tf.test.TestCase):
def test_apply_pattern_and_condition(self):
pattern = structured_writer.pattern_from_transform(
step_structure=None, transform=lambda x: x[-1])
condition = structured_writer.Condition.step_index() <= 2
config = structured_writer.create_config(
pattern=pattern, table='fake_table', conditions=[condition])
input_dataset = tf.data.Dataset.from_tensor_slices({
'observation': {
'field_0': [0, 1, 2, 3],
'field_1': [0, 1, 2, 3],
},
'action': [0, 1, 2, 3],
'is_last': [False, False, False, False],
})
expected_dataset = tf.data.Dataset.from_tensor_slices([0, 1, 2])
output_dataset = pattern_dataset.PatternDataset(
input_dataset=input_dataset,
configs=[config],
respect_episode_boundaries=True,
is_end_of_episode=lambda x: x['is_last'])
num_elements = 0
for out_step, expected_step in tf.data.Dataset.zip(
(output_dataset, expected_dataset)):
self.assertAllClose(out_step, expected_step)
num_elements += 1
self.assertEqual(num_elements, 3)
def test_apply_pattern_keeps_tensor_shape(self):
input_dataset = tf.data.Dataset.from_tensor_slices([[0, 0], [1, 1], [2, 2],
[3, 3]])
expected_dataset = tf.data.Dataset.from_tensor_slices([[0, 0], [1, 1],
[2, 2]])
ref_step = structured_writer.create_reference_step(
input_dataset.element_spec)
print(input_dataset.element_spec)
pattern = structured_writer.pattern_from_transform(
step_structure=ref_step, transform=lambda x: x[-1])
condition = structured_writer.Condition.step_index() <= 2
config = structured_writer.create_config(
pattern=pattern, table='fake_table', conditions=[condition])
output_dataset = pattern_dataset.PatternDataset(
input_dataset=input_dataset,
configs=[config],
respect_episode_boundaries=True,
is_end_of_episode=lambda x: False)
num_elements = 0
for out_step, expected_step in tf.data.Dataset.zip(
(output_dataset, expected_dataset)):
self.assertAllClose(out_step, expected_step)
num_elements += 1
self.assertEqual(num_elements, 3)
def test_apply_pattern_keeps_batch_dimension(self):
input_dataset = tf.data.Dataset.from_tensor_slices([[0, 0], [1, 1], [2, 2],
[3, 3]])
expected_dataset = tf.data.Dataset.from_tensor_slices([[[0, 0], [1, 1]],
[[1, 1], [2, 2]],
[[2, 2], [3, 3]]])
ref_step = structured_writer.create_reference_step(
input_dataset.element_spec)
pattern = structured_writer.pattern_from_transform(
step_structure=ref_step, transform=lambda x: x[-2:])
config = structured_writer.create_config(
pattern=pattern, table='fake_table')
output_dataset = pattern_dataset.PatternDataset(
input_dataset=input_dataset,
configs=[config],
respect_episode_boundaries=True,
is_end_of_episode=lambda x: False)
num_elements = 0
for out_step, expected_step in tf.data.Dataset.zip(
(output_dataset, expected_dataset)):
self.assertAllClose(out_step, expected_step)
num_elements += 1
self.assertEqual(num_elements, 3)
def test_apply_pattern_nested_result(self):
step_spec = {
'observation': {
'field_0': np.zeros([], np.int64),
'field_1': np.zeros([], np.int64),
},
'action': np.zeros([], np.int64),
'is_last': np.zeros([], bool),
}
ref_step = structured_writer.create_reference_step(step_spec)
pattern = {
'observation': {
'field_0': ref_step['observation']['field_0'][-2],
'field_1': ref_step['observation']['field_1'][-2],
},
'next_observation': {
'field_0': ref_step['observation']['field_0'][-1],
'field_1': ref_step['observation']['field_1'][-1],
},
}
config = structured_writer.create_config(
pattern=pattern, table='fake_table')
input_dataset = tf.data.Dataset.from_tensor_slices({
'observation': {
'field_0': [0, 1, 2, 3],
'field_1': [0, 1, 2, 3],
},
'action': [0, 1, 2, 3],
'is_last': [False, False, False, False],
})
expected_dataset = tf.data.Dataset.from_tensor_slices({
'observation': {
'field_0': [0, 1, 2],
'field_1': [0, 1, 2],
},
'next_observation': {
'field_0': [1, 2, 3],
'field_1': [1, 2, 3],
},
})
output_dataset = pattern_dataset.PatternDataset(
input_dataset=input_dataset,
configs=[config],
respect_episode_boundaries=True,
is_end_of_episode=lambda x: x['is_last'])
num_elements = 0
for out_step, expected_step in tf.data.Dataset.zip(
(output_dataset, expected_dataset)):
self.assertAllClose(out_step, expected_step)
num_elements += 1
self.assertEqual(num_elements, 3)
def test_respects_end_of_episode(self):
step_spec = {
'data': np.zeros([], np.int64),
'is_last': np.zeros([], bool),
}
ref_step = structured_writer.create_reference_step(step_spec)
pattern = {'data': ref_step['data'][-2], 'next': ref_step['data'][-1]}
config = structured_writer.create_config(
pattern=pattern, table='fake_table')
input_dataset = tf.data.Dataset.from_tensor_slices({
'data': [0, 1, 2, 3, 4, 5, 6],
'is_last': [False, False, False, True, False, False, True],
})
# There are no pairs created that span between two episodes
expected_dataset = tf.data.Dataset.from_tensor_slices({
'data': [0, 1, 2, 4, 5],
'next': [1, 2, 3, 5, 6],
})
output_dataset = pattern_dataset.PatternDataset(
input_dataset=input_dataset,
configs=[config],
respect_episode_boundaries=True,
is_end_of_episode=lambda x: x['is_last'])
num_elements = 0
for out_step, expected_step in tf.data.Dataset.zip(
(output_dataset, expected_dataset)):
self.assertAllClose(out_step, expected_step)
num_elements += 1
self.assertEqual(num_elements, 5)
def test_ignores_end_of_episode(self):
step_spec = {
'data': np.zeros([], np.int64),
'is_last': np.zeros([], bool),
}
ref_step = structured_writer.create_reference_step(step_spec)
pattern = {'data': ref_step['data'][-2], 'next': ref_step['data'][-1]}
config = structured_writer.create_config(
pattern=pattern, table='fake_table')
input_dataset = tf.data.Dataset.from_tensor_slices({
'data': [0, 1, 2, 3, 4, 5, 6],
'is_last': [False, False, False, True, False, False, True],
})
# There is one pair with data in the previous episode, and next in the
# next one.
expected_dataset = tf.data.Dataset.from_tensor_slices({
'data': [0, 1, 2, 3, 4, 5],
'next': [1, 2, 3, 4, 5, 6],
})
output_dataset = pattern_dataset.PatternDataset(
input_dataset=input_dataset,
configs=[config],
respect_episode_boundaries=False,
is_end_of_episode=lambda x: x['is_last'])
num_elements = 0
for out_step, expected_step in tf.data.Dataset.zip(
(output_dataset, expected_dataset)):
self.assertAllClose(out_step, expected_step)
num_elements += 1
self.assertEqual(num_elements, 6)
def test_build_replay_sample_adds_sample_info(self):
pattern = structured_writer.pattern_from_transform(
step_structure=None, transform=lambda x: x[-1])
condition = structured_writer.Condition.step_index() <= 2
config = structured_writer.create_config(
pattern=pattern, table='fake_table', conditions=[condition])
input_dataset = tf.data.Dataset.from_tensor_slices({'data': [0, 1, 2, 3]})
expected_dataset = tf.data.Dataset.from_tensor_slices([0, 1, 2])
output_dataset = pattern_dataset.pattern_dataset_with_info(
input_dataset=input_dataset,
configs=[config],
respect_episode_boundaries=True,
is_end_of_episode=lambda _: False)
num_elements = 0
for step, expected_data in tf.data.Dataset.zip(
(output_dataset, expected_dataset)):
self.assertEqual(step.info, replay_sample.SampleInfo.zeros())
self.assertEqual(step.data, expected_data)
num_elements += 1
self.assertEqual(num_elements, 3)
if __name__ == '__main__':
tf.test.main()
| reverb-master | reverb/pattern_dataset_test.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for structured_writer."""
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from reverb import client as client_lib
from reverb import server as server_lib
from reverb import structured_writer
import tree
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.framework import tensor_spec
# pylint: enable=g-direct-tensorflow-import
Condition = structured_writer.Condition
TensorSpec = tensor_spec.TensorSpec
TABLES = tuple(f'queue_{i}' for i in range(5))
STEP_SPEC = {
'a': np.zeros([], np.float32),
'b': {
'c': np.zeros([2, 2], np.int32),
'd': [
np.zeros([3], np.int64),
np.zeros([6], np.int64),
],
},
}
REF_STEP = structured_writer.create_reference_step(STEP_SPEC)
def create_step(idx, structure):
return tree.map_structure(lambda x: np.ones_like(x) * idx, structure)
class StructuredWriterTest(parameterized.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._server = server_lib.Server(
[server_lib.Table.queue(table, 100) for table in TABLES])
def setUp(self):
super().setUp()
self.client = client_lib.Client(f'localhost:{self._server.port}')
def tearDown(self):
super().tearDown()
for table in TABLES:
self.client.reset(table)
@classmethod
def tearDownClass(cls):
super().tearDownClass()
cls._server.stop()
def get_table_content(self, idx: int, structure=None):
info = self.client.server_info(1)
num_items = info[TABLES[idx]].current_size
if num_items == 0:
return []
sampler = self.client.sample(
TABLES[idx], num_samples=num_items, emit_timesteps=False)
flat_samples = [sample.data for sample in sampler]
if structure:
return [tree.unflatten_as(structure, sample) for sample in flat_samples]
return flat_samples
@parameterized.parameters(
{
'condition': Condition.step_index() <= 2,
'num_steps': 10,
'want_steps': [0, 1, 2],
},
{
'condition': Condition.step_index() >= 5,
'num_steps': 10,
'want_steps': [5, 6, 7, 8, 9],
},
{
'condition': Condition.step_index() == 3,
'num_steps': 10,
'want_steps': [3],
},
{
'condition': Condition.step_index() != 3,
'num_steps': 10,
'want_steps': [0, 1, 2, 4, 5, 6, 7, 8, 9],
},
{
'condition': Condition.step_index() % 3 == 0,
'num_steps': 10,
'want_steps': [0, 3, 6, 9],
},
{
'condition': Condition.step_index() % 3 != 0,
'num_steps': 10,
'want_steps': [1, 2, 4, 5, 7, 8],
},
{
'condition': Condition.steps_since_applied() >= 4,
'num_steps': 10,
'want_steps': [3, 7],
},
{
'condition': Condition.steps_since_applied() >= 3,
'num_steps': 10,
'want_steps': [2, 5, 8],
},
{
'condition': Condition.is_end_episode(),
'num_steps': 5,
'want_steps': [4],
},
)
def test_single_condition(self, condition, num_steps, want_steps):
pattern = structured_writer.pattern_from_transform(
step_structure=None, transform=lambda x: x[-1])
config = structured_writer.create_config(
pattern=pattern, table=TABLES[0], conditions=[condition])
writer = self.client.structured_writer([config])
for i in range(num_steps):
writer.append(i)
writer.end_episode()
want = [[step] for step in want_steps]
self.assertEqual(self.get_table_content(0), want)
@parameterized.parameters(
{
'pattern': {
'x': REF_STEP['a'][-3],
'y': REF_STEP['b']['c'][-2:],
'z': REF_STEP['b']['d'][0][-1],
},
'num_steps':
5,
'want': [
{
'x':
np.array(0, np.float32),
'y':
np.array([
np.array([[1, 1], [1, 1]], np.int32),
np.array([[2, 2], [2, 2]], np.int32),
]),
'z':
np.array([2, 2, 2], np.int64),
},
{
'x':
np.array(1, np.float32),
'y':
np.stack([
np.array([[2, 2], [2, 2]], np.int32),
np.array([[3, 3], [3, 3]], np.int32),
]),
'z':
np.array([3, 3, 3], np.int64),
},
{
'x':
np.array(2, np.float32),
'y':
np.stack([
np.array([[3, 3], [3, 3]], np.int32),
np.array([[4, 4], [4, 4]], np.int32),
]),
'z':
np.array([4, 4, 4], np.int64),
},
],
},
{
'pattern': {
'older': REF_STEP['a'][-3:-1],
'last_a': REF_STEP['a'][-1],
},
'num_steps':
5,
'want': [
{
'older': np.array([0, 1], np.float32),
'last_a': np.array(2, np.float32),
},
{
'older': np.array([1, 2], np.float32),
'last_a': np.array(3, np.float32),
},
{
'older': np.array([2, 3], np.float32),
'last_a': np.array(4, np.float32),
},
],
},
{
'pattern': {
'every_second_a': REF_STEP['a'][-5::2]
},
'num_steps':
10,
'want': [
{
'every_second_a': np.array([0, 2, 4], np.float32)
},
{
'every_second_a': np.array([1, 3, 5], np.float32)
},
{
'every_second_a': np.array([2, 4, 6], np.float32)
},
{
'every_second_a': np.array([3, 5, 7], np.float32)
},
{
'every_second_a': np.array([4, 6, 8], np.float32)
},
{
'every_second_a': np.array([5, 7, 9], np.float32)
},
],
},
)
def test_trajectory_patterns(self, pattern, num_steps, want):
config = structured_writer.create_config(
pattern=pattern, table=TABLES[0], conditions=[])
writer = self.client.structured_writer([config])
for i in range(num_steps):
writer.append(create_step(i, STEP_SPEC))
writer.end_episode()
tree.map_structure(np.testing.assert_array_equal, want,
self.get_table_content(0, pattern))
def test_round_robin_into_tables(self):
pattern = structured_writer.pattern_from_transform(
step_structure=None, transform=lambda x: x[-1])
# Create configs which should result in steps being written to available
# tables in a round robin fashion.
configs = []
for i, table in enumerate(TABLES):
configs.append(
structured_writer.create_config(
pattern=pattern,
table=table,
conditions=[Condition.step_index() % len(TABLES) == i]))
# Take enough steps to generate two trajectories for each table.
writer = self.client.structured_writer(configs)
for i in range(len(TABLES) * 2):
writer.append(i)
writer.end_episode()
# Check that steps was inserted into tables in the expected order.
self.assertEqual(self.get_table_content(0), [[0], [5]])
self.assertEqual(self.get_table_content(1), [[1], [6]])
self.assertEqual(self.get_table_content(2), [[2], [7]])
self.assertEqual(self.get_table_content(3), [[3], [8]])
self.assertEqual(self.get_table_content(4), [[4], [9]])
@parameterized.named_parameters(
{
'testcase_name': 'condition_on_unused_column',
'step_spec': {'a': None, 'b': None},
'pattern_fn': lambda x: {'old_a': x['a'][-2]},
'condition_fn': lambda x: x['b'] > 10,
'steps': [
{'a': 1, 'b': 11},
{'a': 2, 'b': 10},
{'a': 3, 'b': 11},
{'a': 4, 'b': 9},
{'a': 5, 'b': 12},
],
'want': [
{'old_a': 2},
{'old_a': 4},
],
},
{
'testcase_name': 'int32_eq',
'step_spec': STEP_SPEC,
'pattern_fn': lambda x: {'last_two_a': x['a'][-2:]},
'condition_fn': lambda x: x['a'] == 3,
'steps': [
{'a': np.array(0, np.int32)},
{'a': np.array(2, np.int32)},
{'a': np.array(3, np.int32)},
{'a': np.array(4, np.int32)},
{'a': np.array(5, np.int32)},
],
'want': [
{'last_two_a': np.array([2, 3], np.int32)},
],
},
{
'testcase_name': 'int64_ne',
'step_spec': STEP_SPEC,
'pattern_fn': lambda x: {'last_two_a': x['a'][-2:]},
'condition_fn': lambda x: x['a'] != 4,
'steps': [
{'a': np.array(1, np.int64)},
{'a': np.array(2, np.int64)},
{'a': np.array(3, np.int64)},
{'a': np.array(4, np.int64)},
{'a': np.array(5, np.int64)},
],
'want': [
{'last_two_a': np.array([1, 2])},
{'last_two_a': np.array([2, 3])},
{'last_two_a': np.array([4, 5])},
],
},
{
'testcase_name': 'bool_eq',
'step_spec': {'a': None, 'b': None},
'pattern_fn': lambda x: {'last_a': x['a'][-1]},
'condition_fn': lambda x: x['b'] == 1,
'steps': [
{'a': 1, 'b': True},
{'a': 2, 'b': False},
{'a': 3, 'b': False},
{'a': 4, 'b': True},
{'a': 5, 'b': False},
],
'want': [
{'last_a': 1},
{'last_a': 4},
],
},
)
def test_data_condition(
self, step_spec, pattern_fn, condition_fn, steps, want):
config = structured_writer.create_config(
pattern=structured_writer.pattern_from_transform(step_spec, pattern_fn),
table=TABLES[0],
conditions=[
condition_fn(structured_writer.Condition.data(step_spec)),
]
)
writer = self.client.structured_writer([config])
for step in steps:
writer.append(step)
writer.flush()
got = self.get_table_content(0, structured_writer.unpack_pattern(config))
tree.map_structure(np.testing.assert_array_equal, want, got)
def test_step_is_open(self):
ref_step = structured_writer.create_reference_step([None, None, None])
pattern = [r[-1] for r in ref_step]
config = structured_writer.create_config(pattern, TABLES[0])
writer = self.client.structured_writer([config])
# The step should not be opened when the writer is first created.
self.assertFalse(writer.step_is_open)
# The step should still not be opened after a full step is appended.
writer.append([1, 1, 1])
self.assertFalse(writer.step_is_open)
# Appending a partial step should make it True.
writer.append([None, 2, None], partial_step=True)
self.assertTrue(writer.step_is_open)
# Appending more partial data to the same step shouldn't change anything.
writer.append([None, None, 2], partial_step=True)
self.assertTrue(writer.step_is_open)
# Completing the step should make it False.
writer.append([2, None, None])
self.assertFalse(writer.step_is_open)
# End episode should finalize the active step if any is open.
writer.append([None, 3, None], partial_step=True)
self.assertTrue(writer.step_is_open)
writer.end_episode()
self.assertFalse(writer.step_is_open)
def test_append_wrong_dtype(self):
config = structured_writer.create_config(
pattern=REF_STEP['b']['c'][-1],
table=TABLES[0])
writer = self.client.structured_writer([config])
writer.append({'a': 1, 'b': {'c': 1.0}})
with self.assertRaisesWithLiteralMatch(
ValueError,
'Tensor of wrong dtype provided for column 1 (path=(\'b\', \'c\')). '
'Got int64 but expected double.'):
writer.append({'a': 2, 'b': {'c': 2}})
def test_append_incompatible_shape(self):
config = structured_writer.create_config(
pattern=REF_STEP['b']['d'][1][-1],
table=TABLES[0])
writer = self.client.structured_writer([config])
writer.append({
'a': 1,
'b': {
'c': 1.0,
'd': [
1,
1,
],
},
})
with self.assertRaisesWithLiteralMatch(
ValueError,
'Tensor of incompatible shape provided for column 3 '
'(path=(\'b\', \'d\', 1)). Got [2,2] which is incompatible with [].'):
writer.append({
'a': 2,
'b': {
'c': 2.0,
'd': [
2,
np.array([[2, 2], [2, 2]]),
],
},
})
def test_append_with_different_structures(self):
config = structured_writer.create_config(
pattern=REF_STEP['b']['c'][-1],
table=TABLES[0])
writer = self.client.structured_writer([config])
writer.append({'a': 1, 'b': {'c': 1}})
with self.assertRaisesWithLiteralMatch(
ValueError,
'Flattened data has an unexpected length, got 4 but wanted 2.'):
writer.append({'a': 2, 'b': {'c': 2, 'd': [2, 2]}})
def test_td_error(self):
step_spec = {'a': None, 'b': None, 'c': None}
pattern_fn = lambda x: {'last_a': x['a'][-1], 'last_c': x['c'][-1]}
configs = structured_writer.create_config(
pattern=structured_writer.pattern_from_transform(step_spec, pattern_fn),
table=TABLES[0],
priority=structured_writer.td_error(
max_priority_weight=.5,
step_structure=step_spec,
get_field_from_step_fn=lambda x: x['c']))
writer = self.client.structured_writer([configs])
for i in range(5):
writer.append({'a': i, 'b': i + 1, 'c': i + 2})
writer.flush()
info = self.client.server_info(1)
num_items = info[TABLES[0]].current_size
self.assertEqual(num_items, 5)
sampler = self.client.sample(TABLES[0], num_samples=5, emit_timesteps=False)
priorities = []
for sample in sampler:
priorities.append(sample.info.priority)
# Each episode only has one step, so the TD error is the value of the
# error in the step (column c).
expected_priorities = [2., 3., 4., 5., 6.]
self.assertSequenceEqual(priorities, expected_priorities)
class TestInferSignature(parameterized.TestCase):
@parameterized.parameters(
{
'patterns': [{
'older': REF_STEP['a'][-3:-1],
'last_a': REF_STEP['a'][-1],
},],
'step_spec': {
'a': np.zeros([3, 3], np.float32),
},
'want': {
'older': TensorSpec([2, 3, 3], np.float32, 'older'),
'last_a': TensorSpec([3, 3], np.float32, 'last_a'),
},
},
{
'patterns': [{
'a_with_step': REF_STEP['a'][-6::2],
'a_slice': REF_STEP['a'][-4:],
'x': {
'y': REF_STEP['b']['c'][-2],
},
},],
'step_spec': {
'a': np.zeros([3, 3], np.float32),
'b': {
'c': np.zeros([], np.int32),
'd': np.zeros([5], np.int8), # Unused.
},
},
'want': {
'a_with_step': TensorSpec([3, 3, 3], np.float32, 'a_with_step'),
'a_slice': TensorSpec([4, 3, 3], np.float32, 'a_slice'),
'x': {
'y': TensorSpec([], np.int32, 'x/y'),
},
},
},
{
'patterns': [
{
'x': REF_STEP['a'][-3:-1],
'y': REF_STEP['a'][-1],
'z': REF_STEP['b']['c'][-4:],
},
{
'x': REF_STEP['a'][-2:],
'y': REF_STEP['a'][-2],
'z': REF_STEP['b']['c'][-8::2],
},
],
'step_spec': {
'a': np.zeros([3, 3], np.float32),
'b': {
'c': np.zeros([2, 2], np.int8),
},
},
'want': {
'x': TensorSpec([2, 3, 3], np.float32, 'x'),
'y': TensorSpec([3, 3], np.float32, 'y'),
'z': TensorSpec([4, 2, 2], np.int8, 'z'),
},
},
{
'patterns': [
{
'x': REF_STEP['a'][-3:-1],
},
{
'x': REF_STEP['a'][-2:],
},
{
'x': REF_STEP['a'][-3:],
},
],
'step_spec': {
'a': np.zeros([3, 3], np.float32),
},
'want': {
'x': TensorSpec([None, 3, 3], np.float32, 'x'),
},
},
)
def test_valid_configs(self, patterns, step_spec, want):
configs = [
structured_writer.create_config(pattern, 'table')
for pattern in patterns
]
got = structured_writer.infer_signature(configs, step_spec)
self.assertEqual(want, got)
def test_requires_same_table(self):
pattern = {'x': REF_STEP['a'][-3:]}
configs = [
structured_writer.create_config(pattern, 'a'),
structured_writer.create_config(pattern, 'b'),
structured_writer.create_config(pattern, 'c'),
]
with self.assertRaisesWithLiteralMatch(
ValueError,
'All configs must target the same table but provided configs included '
'a, b, c.'):
structured_writer.infer_signature(configs, STEP_SPEC)
def test_requires_same_pattern_structure(self):
configs = [
structured_writer.create_config({'x': REF_STEP['a'][-1]}, 'a'),
structured_writer.create_config({'y': REF_STEP['a'][-1]}, 'a'),
]
with self.assertRaisesWithLiteralMatch(
ValueError,
'All configs must have exactly the same pattern_structure.'):
structured_writer.infer_signature(configs, STEP_SPEC)
def test_requires_at_least_one_config(self):
with self.assertRaisesWithLiteralMatch(
ValueError, 'At least one config must be provided.'):
structured_writer.infer_signature([], STEP_SPEC)
def test_requires_same_dtype(self):
step_spec = {
'a': np.zeros([], np.float32),
'b': np.zeros([], np.float64),
}
ref_step = structured_writer.create_reference_step(step_spec)
configs = [
structured_writer.create_config({'x': ref_step['a'][-1]}, 'a'),
structured_writer.create_config({'x': ref_step['b'][-1]}, 'a'),
]
with self.assertRaisesRegex(
ValueError,
r'Configs produce trajectories with multiple dtypes at \(\'x\',\)\. '
r'Got .*'):
structured_writer.infer_signature(configs, step_spec)
def test_requires_same_rank(self):
step_spec = {
'a': np.zeros([], np.float32),
'b': np.zeros([1], np.float32),
}
ref_step = structured_writer.create_reference_step(step_spec)
configs = [
structured_writer.create_config({'x': ref_step['a'][-1]}, 'a'),
structured_writer.create_config({'x': ref_step['b'][-1]}, 'a'),
]
with self.assertRaisesRegex(
ValueError, r'Configs produce trajectories with incompatible shapes at '
r'\(\'x\',\)\. Got .*'):
structured_writer.infer_signature(configs, step_spec)
def test_requires_same_concatable_shapes(self):
step_spec = {
'a': np.zeros([1, 2], np.float32),
'b': np.zeros([1, 3], np.float32),
}
ref_step = structured_writer.create_reference_step(step_spec)
configs = [
structured_writer.create_config({'x': ref_step['a'][-1]}, 'a'),
structured_writer.create_config({'x': ref_step['b'][-1]}, 'a'),
]
with self.assertRaisesRegex(
ValueError, r'Configs produce trajectories with incompatible shapes at '
r'\(\'x\',\)\. Got .*'):
structured_writer.infer_signature(configs, step_spec)
if __name__ == '__main__':
absltest.main()
| reverb-master | reverb/structured_writer_test.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for trajectory_dataset."""
from absl.testing import parameterized
import numpy as np
from reverb import client
from reverb import errors
from reverb import item_selectors
from reverb import rate_limiters
from reverb import replay_sample
from reverb import server as reverb_server
from reverb import trajectory_dataset
import tensorflow.compat.v1 as tf
import tree
from tensorflow.python.framework import tensor_spec # pylint:disable=g-direct-tensorflow-import
TABLE = 'prioritized'
DTYPES = {
'observation': tf.float32,
'reward': tf.int64,
}
SHAPES = {
'observation': tf.TensorShape([1, 3, 3]),
'reward': tf.TensorShape([]),
}
def make_server():
return reverb_server.Server(tables=[
reverb_server.Table(
name=TABLE,
sampler=item_selectors.Prioritized(priority_exponent=1),
remover=item_selectors.Fifo(),
max_size=1000,
rate_limiter=rate_limiters.MinSize(1)),
])
class TrajectoryDatasetTest(tf.test.TestCase, parameterized.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._server = make_server()
cls._client = client.Client(f'localhost:{cls._server.port}')
def tearDown(self):
super().tearDown()
self._client.reset(TABLE)
@classmethod
def tearDownClass(cls):
super().tearDownClass()
cls._server.stop()
def _populate_replay(self):
with self._client.trajectory_writer(1) as writer:
for _ in range(10):
writer.append([np.ones([3, 3], np.float32), 3])
writer.create_item(TABLE, 1.0, {
'observation': writer.history[0][-1:],
'reward': writer.history[1][-1],
})
def _sample_from(self, dataset, num_samples):
iterator = dataset.make_initializable_iterator()
dataset_item = iterator.get_next()
self.evaluate(iterator.initializer)
return [self.evaluate(dataset_item) for _ in range(num_samples)]
@parameterized.named_parameters(
{
'testcase_name': 'default_values',
},
{
'testcase_name': 'num_workers_per_iterator_is_0',
'num_workers_per_iterator': 0,
'want_error': ValueError,
},
{
'testcase_name': 'num_workers_per_iterator_is_1',
'num_workers_per_iterator': 1,
},
{
'testcase_name': 'num_workers_per_iterator_is_minus_1',
'num_workers_per_iterator': -1,
},
{
'testcase_name': 'num_workers_per_iterator_is_minus_2',
'num_workers_per_iterator': -2,
'want_error': ValueError,
},
{
'testcase_name': 'max_samples_per_stream_is_0',
'max_samples_per_stream': 0,
'want_error': ValueError,
},
{
'testcase_name': 'max_samples_per_stream_is_1',
'max_samples_per_stream': 1,
},
{
'testcase_name': 'max_samples_per_stream_is_minus_1',
'max_samples_per_stream': -1,
},
{
'testcase_name': 'max_samples_per_stream_is_minus_2',
'num_workers_per_iterator': -2,
'want_error': ValueError,
},
{
'testcase_name': 'max_in_flight_samples_per_worker_is_0',
'max_in_flight_samples_per_worker': 0,
'want_error': ValueError,
},
{
'testcase_name': 'max_in_flight_samples_per_worker_is_1',
'max_in_flight_samples_per_worker': 1,
},
{
'testcase_name': 'max_in_flight_samples_per_worker_is_minus_1',
'max_in_flight_samples_per_worker': -1,
'want_error': ValueError,
},
)
def test_sampler_parameter_validation(self, **kwargs):
if 'max_in_flight_samples_per_worker' not in kwargs:
kwargs['max_in_flight_samples_per_worker'] = 1
if 'want_error' in kwargs:
error = kwargs.pop('want_error')
with self.assertRaises(error):
trajectory_dataset.TrajectoryDataset(
server_address=self._client.server_address,
table=TABLE,
dtypes=DTYPES,
shapes=SHAPES,
**kwargs)
else:
trajectory_dataset.TrajectoryDataset(
server_address=self._client.server_address,
table=TABLE,
dtypes=DTYPES,
shapes=SHAPES,
**kwargs)
def test_sample_fixed_length_trajectory(self):
self._populate_replay()
dataset = trajectory_dataset.TrajectoryDataset(
tf.constant(self._client.server_address),
table=tf.constant(TABLE),
dtypes=DTYPES,
shapes=SHAPES,
max_in_flight_samples_per_worker=1)
tree.assert_same_structure(
self._sample_from(dataset, 1)[0],
replay_sample.ReplaySample(
info=replay_sample.SampleInfo(
key=1,
probability=1.0,
table_size=10,
priority=0.5,
times_sampled=1,
),
data=SHAPES))
def test_sample_variable_length_trajectory(self):
with self._client.trajectory_writer(10) as writer:
for i in range(10):
writer.append([np.ones([3, 3], np.int32) * i])
writer.create_item(TABLE, 1.0, {
'last': writer.history[0][-1],
'all': writer.history[0][:],
})
dataset = trajectory_dataset.TrajectoryDataset(
tf.constant(self._client.server_address),
table=tf.constant(TABLE),
dtypes={
'last': tf.int32,
'all': tf.int32,
},
shapes={
'last': tf.TensorShape([3, 3]),
'all': tf.TensorShape([None, 3, 3]),
},
max_in_flight_samples_per_worker=1)
# Continue sample until we have observed all the trajectories.
seen_lengths = set()
while len(seen_lengths) < 10:
sample = self._sample_from(dataset, 1)[0]
# The structure should always be the same.
tree.assert_same_structure(
sample,
replay_sample.ReplaySample(
info=replay_sample.SampleInfo(
key=1,
probability=1.0,
table_size=10,
priority=0.5,
times_sampled=1,
),
data={
'last': None,
'all': None
}))
seen_lengths.add(sample.data['all'].shape[0])
self.assertEqual(seen_lengths, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
class FromTableSignatureTest(tf.test.TestCase):
def test_table_not_found(self):
server = reverb_server.Server([
reverb_server.Table.queue('table_a', 10),
reverb_server.Table.queue('table_c', 10),
reverb_server.Table.queue('table_b', 10),
])
address = f'localhost:{server.port}'
with self.assertRaisesWithPredicateMatch(
ValueError,
f'Server at {address} does not contain any table named not_found. '
f'Found: table_a, table_b, table_c.'):
trajectory_dataset.TrajectoryDataset.from_table_signature(
address, 'not_found', 100)
def test_server_not_found(self):
with self.assertRaises(errors.DeadlineExceededError):
trajectory_dataset.TrajectoryDataset.from_table_signature(
'localhost:1234', 'not_found', 100, get_signature_timeout_secs=1)
def test_table_does_not_have_signature(self):
server = make_server()
address = f'localhost:{server.port}'
with self.assertRaisesWithPredicateMatch(
ValueError, f'Table {TABLE} at {address} does not have a signature.'):
trajectory_dataset.TrajectoryDataset.from_table_signature(
address, TABLE, 100)
def test_sets_dtypes_from_signature(self):
signature = {
'a': {
'b': tf.TensorSpec([3, 3], tf.float32),
'c': tf.TensorSpec([], tf.int64),
},
'x': tf.TensorSpec([None], tf.uint64),
}
server = reverb_server.Server(
[reverb_server.Table.queue('queue', 10, signature=signature)])
dataset = trajectory_dataset.TrajectoryDataset.from_table_signature(
f'localhost:{server.port}', 'queue', 100)
self.assertDictEqual(dataset.element_spec.data, signature)
def test_sets_dtypes_from_bounded_spec_signature(self):
bounded_spec_signature = {
'a': {
'b': tensor_spec.BoundedTensorSpec([3, 3], tf.float32, 0, 3),
'c': tensor_spec.BoundedTensorSpec([], tf.int64, 0, 5),
},
}
server = reverb_server.Server([
reverb_server.Table.queue(
'queue', 10, signature=bounded_spec_signature)
])
dataset = trajectory_dataset.TrajectoryDataset.from_table_signature(
f'localhost:{server.port}', 'queue', 100)
self.assertDictEqual(
dataset.element_spec.data, {
'a': {
'b': tf.TensorSpec([3, 3], tf.float32),
'c': tf.TensorSpec([], tf.int64),
},
})
if __name__ == '__main__':
tf.disable_eager_execution()
tf.test.main()
| reverb-master | reverb/trajectory_dataset_test.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""StructuredWriter uses static patterns to build and insert trajectories.
TODO(b/204560248): Expand the documentation.
"""
import copy
import datetime
from typing import Any, Callable, NewType, Optional, Sequence
from reverb import errors
from reverb import pybind
from reverb import reverb_types
import tree
from reverb.cc import patterns_pb2
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.saved_model import nested_structure_coder
# pylint: enable=g-direct-tensorflow-import
# TODO(b/204423296): Expose Python abstractions rather than the raw protos.
Config = patterns_pb2.StructuredWriterConfig
ConditionProto = patterns_pb2.Condition
Pattern = tree.Structure[patterns_pb2.PatternNode]
ReferenceStep = NewType('ReferenceStep', Any)
PatternTransform = Callable[[ReferenceStep], Pattern]
class StructuredWriter:
"""StructuredWriter uses static patterns to build and insert trajectories.
TODO(b/204560248): Expand the documentation.
"""
def __init__(self, cpp_writer: pybind.StructuredWriter):
self._writer = cpp_writer
self._data_structure = None
self._flat_data_length = None
def append(self, data: Any, *, partial_step: bool = False):
"""Appends data to internal buffers and inserts generated trajectories.
NOTE! The data must have exactly the same structure in each step. Leaf nodes
are allowed to be `None` but the structure must be the same.
It is possible to create a "step" using more than one `append` call by
setting the `partial_step` flag. Partial steps can be used when some parts
of the step becomes available only as a result of inserting (and learning
from) trajectories that include the fields available first (e.g learn from
the SARS trajectory to select the next action in an on-policy agent). In the
final `append` call of the step, `partial_step` must be set to `False`.
Failing to "close" the partial step will result in error as the same field
must NOT be provided more than once in the same step.
Args:
data: The (possibly nested) data pushed to internal buffers.
partial_step: If `True` then the step is not considered "done" with this
call. See above for more details. Defaults to `False`.
Raises:
ValueError: If the number of items in the flattened data changes between
calls.
"""
flat_data = tree.flatten(data)
if self._flat_data_length is None:
self._flat_data_length = len(flat_data)
self._data_structure = tree.map_structure(lambda _: None, data)
if len(flat_data) != self._flat_data_length:
raise ValueError(
f'Flattened data has an unexpected length, got {len(flat_data)} '
f'but wanted {self._flat_data_length}.')
try:
if partial_step:
self._writer.AppendPartial(flat_data)
else:
self._writer.Append(flat_data)
except ValueError as e:
parts = str(e).split(' for column ')
# If the error message doesn't have the expected format then we don't want
# to change anything.
if len(parts) != 2:
raise
# Use the structure to find the path that corresponds to the flat index.
col_idx, rest = parts[1].split('. ', 1)
path = tree.flatten_with_path(self._data_structure)[int(col_idx)][0]
raise ValueError(
f'{parts[0]} for column {col_idx} (path={path}). {rest}') from e
def flush(self,
block_until_num_items: int = 0,
timeout_ms: Optional[int] = None):
"""Block until all but `block_until_num_items` confirmed by the server.
There are two ways that an item could be "pending":
1. Some of the data elements referenced by the item have not yet been
finalized (and compressed) as a `ChunkData`.
2. The item has been written to the gRPC stream but the response
confirming the insertion has not yet been received.
Type 1 pending items are transformed into type 2 when flush is called by
forcing (premature) chunk finalization of the data elements referenced by
the items. This will allow the background worker to write the data and items
to the gRPC stream and turn them into type 2 pending items.
The time it takes for type 2 pending items to be confirmed is primarily
due to the state of the table rate limiter. After the items have been
written to the gRPC stream then all we can do is wait (GIL is not held).
Args:
block_until_num_items: If > 0 then this many pending items will be allowed
to remain as type 1. If the number of type 1 pending items is less than
`block_until_num_items` then we simply wait until the total number of
pending items is <= `block_until_num_items`.
timeout_ms: (optional, default is no timeout) Maximum time to block for
before unblocking and raising a `DeadlineExceededError` instead. Note
that although the block is interrupted, the insertion of the items will
proceed in the background.
Raises:
ValueError: If `block_until_num_items` < 0.
DeadlineExceededError: If operation did not complete before the timeout.
"""
if block_until_num_items < 0:
raise ValueError(
f'block_until_num_items must be >= 0, got {block_until_num_items}')
try:
self._writer.Flush(block_until_num_items, timeout_ms)
except RuntimeError as e:
if 'Timeout exceeded' in str(e) and timeout_ms is not None:
raise errors.DeadlineExceededError(
f'Flush call did not complete within provided timeout of '
f'{datetime.timedelta(milliseconds=timeout_ms)}')
raise
def end_episode(self,
clear_buffers: bool = True,
timeout_ms: Optional[int] = None):
"""Flush all pending items and generate a new episode ID.
Configurations that are conditioned to only be appied on episode end are
applied (assuming all other conditions are fulfilled) and the items inserted
before flush is called.
Args:
clear_buffers: Whether the history should be cleared or not. Buffers
should only not be cleared when trajectories spanning multiple episodes
are used.
timeout_ms: (optional, default is no timeout) Maximum time to block for
before unblocking and raising a `DeadlineExceededError` instead. Note
that although the block is interrupted, the buffers and episode ID are
reset all the same and the insertion of the items will proceed in the
background thread.
Raises:
DeadlineExceededError: If operation did not complete before the timeout.
"""
try:
self._writer.EndEpisode(clear_buffers, timeout_ms)
except RuntimeError as e:
if 'Timeout exceeded' in str(e) and timeout_ms is not None:
raise errors.DeadlineExceededError(
f'End episode call did not complete within provided timeout of '
f'{datetime.timedelta(milliseconds=timeout_ms)}')
raise
@property
def step_is_open(self) -> bool:
"""True if `partial_step` was set in the most recent `append`."""
return self._writer.step_is_open
class _RefNode:
"""Helper class to make it easier to build `PatternNode`s."""
def __init__(self, idx: int):
self._idx = idx
def __getitem__(self, key):
if isinstance(key, int):
key = slice(key)
elif not isinstance(key, slice):
raise ValueError(
f'Key must be int or slice by got {key} (type {type(key)}).')
return patterns_pb2.PatternNode(
flat_source_index=self._idx,
start=key.start,
stop=key.stop,
step=key.step)
def create_reference_step(step_structure: tree.Structure[Any]) -> ReferenceStep:
"""Create a reference structure that can be used to build patterns.
```python
step_structure = {
'a': None,
'b': {
'c': None,
'd': None,
}
}
ref_step = create_reference_step(step_structure)
pattern = {
'last_two_a': ref_step['a'][-2:]
'second_to_last_c': ref['b']['c'][-2]
'most_recent_d': ref['b']['d'][-1]
}
```
Args:
step_structure: Structure of the data which will be passed to
`StructuredWriter.append`.
Returns:
An object with the same structure as `step_structure` except leaf nodes have
been replaced with a helper object that builds `patterns_pb2.PatternNode`
objects when __getitem__ is called.
"""
return tree.unflatten_as(
step_structure,
[_RefNode(x) for x in range(len(tree.flatten(step_structure)))])
def pattern_from_transform(
step_structure: tree.Structure[Any],
transform: Callable[[ReferenceStep], Pattern]) -> Pattern:
"""Creates a pattern by invoking a transform from step to output structures.
```python
def my_transform(step):
return {
'last_two_a': step['a'][-2:]
'most_recent_b': tree.map_structure(lambda x: x[-1], step['b']),
}
step_structure = {
'a': None,
'b': {
'c': None,
'd': None,
}
}
pattern = pattern_from_transform(step_structure, my_transform)
```
Args:
step_structure: Structure of the data which will be passed to
`StructuredWriter.append`.
transform: Function that creates the trajectory to be inserted from a
reference structure.
Returns:
A structure with `patterns_pb2.PatternNode` as leaf nodes.
"""
return transform(create_reference_step(step_structure))
def create_config(pattern: Pattern,
table: str,
conditions: Sequence[ConditionProto] = (),
priority: Optional[patterns_pb2.Priority] = None):
structure = tree.map_structure(lambda _: None, pattern)
if priority is None:
priority = constant_priority_fn(1.0)
return patterns_pb2.StructuredWriterConfig(
flat=tree.flatten(pattern),
pattern_structure=nested_structure_coder.encode_structure(structure),
table=table,
priority=priority,
conditions=conditions)
def unpack_pattern(config: Config) -> Pattern:
if not config.HasField('pattern_structure'):
return config.flat
structure = nested_structure_coder.decode_proto(config.pattern_structure)
return tree.unflatten_as(structure, config.flat)
def infer_signature(configs: Sequence[Config],
step_spec: reverb_types.SpecNest) -> reverb_types.SpecNest:
"""Infers the table signature from the configs that generate its items.
Args:
configs: All the configs used to generate items for the table.
step_spec: A structured example of the step that will be appended to the
`StructuredWriter`.
Returns:
A nested structure of `TensorSpec` describing the trajectories of the table.
Raises:
ValueError: If no configs are provided.
ValueError: If configs doesn't produce trajectories of identical structure.
ValueError: If configs targets does not all target the same table.
ValueError: If configs produce trajectories with incompatible tensors (i.e.
tensors cannot be concatenated).
"""
if not configs:
raise ValueError('At least one config must be provided.')
if any(c.pattern_structure != configs[0].pattern_structure for c in configs):
raise ValueError(
'All configs must have exactly the same pattern_structure.')
if any(c.table != configs[0].table for c in configs):
raise ValueError(
f'All configs must target the same table but provided configs '
f'included {", ".join(sorted(set(c.table for c in configs)))}.')
flat_step_spec = tree.flatten(step_spec)
def _validate_and_convert_to_spec(path, *nodes):
# Check that all nodes share the same dtype.
dtypes = [flat_step_spec[node.flat_source_index].dtype for node in nodes]
if any(dtype != dtypes[0] for dtype in dtypes):
raise ValueError(
f'Configs produce trajectories with multiple dtypes at {path}. '
f'Got {dtypes}.')
# Create shapes for all nodes.
shapes = []
for node in nodes:
shape = list(flat_step_spec[node.flat_source_index].shape)
if node.HasField('start'):
length = (node.stop - node.start) // (node.step or 1)
shape = [length, *shape]
shapes.append(tensor_shape.TensorShape(shape))
# Check that all shapes are either completely identical or at least
# identical in all dimensions but the first.
if (any(shape.rank != shapes[0].rank for shape in shapes) or
(shapes[0].rank > 1 and
any(shape[1:] != shapes[0][1:] for shape in shapes))):
raise ValueError(
f'Configs produce trajectories with incompatible shapes at {path}. '
f'Got {shapes}.')
# Merge the shapes into a single shape. If the first dimension varies then
# we set the leading dimension as undefined.
if all(shape == shapes[0] for shape in shapes):
merged_shape = shapes[0]
else:
merged_shape = [None, *shapes[0][1:]]
return tensor_spec.TensorSpec(
shape=merged_shape,
dtype=dtypes[0],
name='/'.join(str(x) for x in path))
patterns = [unpack_pattern(config) for config in configs]
return tree.map_structure_with_path(_validate_and_convert_to_spec, *patterns)
class _ConditionBuilder:
"""Helper class to make it easier to build conditions."""
def __init__(self, incomplete_condition: ConditionProto):
self._incomplete_condition = incomplete_condition
def __mod__(self, cmp: int) -> '_ConditionBuilder':
incomplete_condition = copy.deepcopy(self._incomplete_condition)
incomplete_condition.mod_eq.mod = cmp
return _ConditionBuilder(incomplete_condition)
# pytype: disable=signature-mismatch # overriding-return-type-checks
def __eq__(self, cmp: int) -> ConditionProto:
condition = copy.deepcopy(self._incomplete_condition)
if condition.mod_eq.mod:
condition.mod_eq.eq = cmp
else:
condition.eq = cmp
return condition
def __ne__(self, cmp: int) -> ConditionProto:
condition = self == cmp
condition.inverse = True
return condition
def __gt__(self, cmp: int) -> ConditionProto:
return self >= cmp + 1
def __ge__(self, cmp: int) -> ConditionProto:
condition = copy.deepcopy(self._incomplete_condition)
condition.ge = cmp
return condition
def __lt__(self, cmp: int) -> ConditionProto:
return self <= cmp - 1
def __le__(self, cmp: int) -> ConditionProto:
condition = self > cmp
condition.inverse = True
return condition
# pytype: enable=signature-mismatch # overriding-return-type-checks
class Condition:
"""Building blocks to create conditions from."""
@staticmethod
def step_index():
"""(Zero) index of the most recent appended step within the episode."""
return _ConditionBuilder(ConditionProto(step_index=True))
@staticmethod
def steps_since_applied():
"""Number of added steps since an item was created for this config."""
return _ConditionBuilder(ConditionProto(steps_since_applied=True))
@staticmethod
def is_end_episode():
"""True only when end_episode is called on the writer."""
return ConditionProto(is_end_episode=True, eq=1)
@staticmethod
def data(step_structure: tree.Structure[Any]):
"""Value of a scalar integer or bool in the source data."""
flat = [
_ConditionBuilder(ConditionProto(flat_source_index=i))
for i in range(len(tree.flatten(step_structure)))
]
return tree.unflatten_as(step_structure, flat)
def constant_priority_fn(value: float) -> patterns_pb2.Priority:
"""Builds a priority function that always returns the same value.
Args:
value: constant priority value.
Returns:
Priority function that always returns a constant value.
"""
return patterns_pb2.Priority(
constant_fn=patterns_pb2.Priority.ConstantPriorityFn(value=value))
def td_error(
max_priority_weight: float, step_structure: tree.Structure[Any],
get_field_from_step_fn: Callable[[tree.Structure[Any]], Any]
) -> patterns_pb2.Priority:
"""Builds a td_error priority function.
See details of the TD error in https://openreview.net/pdf?id=r1lyTjAqYX.
The TD error of a trajectory is computed by combining the TD error at each
timestep. If that column is called `td_error`, the computation to obtain the
trajectory TD error is:
```
abs_td_error = jnp.abs(td_error)
max_priority = max_priority_weight * jnp.max(abs_td_error, axis=0)
mean_priority = (1 - max_priority_weight) * jnp.mean(abs_td_error, axis=0)
priority = max_priority + mean_priority
```
Args:
max_priority_weight: max priority weight to use in the TD error computation.
step_structure: structure of the step.
get_field_from_step_fn: This function gets a step and returns the field that
contains the per-step TD error. Note that this field corresponds to the
input step, and has to be present also in the resulting trajectory (if the
trajectory is a dictionary, the name of the field in the trajectory can
change). Besides, this field from the input step should only correspond to
one field in the resulting trajectory, otherwise we cannot guarantee which
one is used to compute the priority.
Returns:
A priority function which computes the priority as the TD error.
"""
def get_flat_index(step_structure):
flat = list(range(len(tree.flatten(step_structure))))
return tree.unflatten_as(step_structure, flat)
index = get_field_from_step_fn(get_flat_index(step_structure))
return patterns_pb2.Priority(
td_error=patterns_pb2.Priority.TDError(
max_priority_weight=max_priority_weight, flat_source_index=index))
| reverb-master | reverb/structured_writer.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of the Python client for Reverb.
`Client` is used to connect and interact with a Reverb server. The client
exposes direct methods for both inserting (i.e `insert`) and sampling (i.e
`sample`) but users should prefer to use `TrajectoryWriter` and
`TrajectoryDataset` directly whenever possible.
"""
from typing import Any, Dict, Generator, List, Optional, Sequence, Union
from absl import logging
import numpy as np
from reverb import errors
from reverb import pybind
from reverb import replay_sample
from reverb import reverb_types
from reverb import structured_writer as structured_writer_lib
from reverb import trajectory_writer as trajectory_writer_lib
import tree
class Writer:
"""Writer is used for streaming data of arbitrary length.
See Client.writer for documentation.
"""
def __init__(self, internal_writer: pybind.Writer):
"""Constructor for Writer (must only be called by Client.writer)."""
self._writer = internal_writer
self._closed = False
def __enter__(self) -> 'Writer':
if self._closed:
raise ValueError('Cannot reuse already closed Writer')
return self
def __exit__(self, *_):
self.flush()
self.close()
def __del__(self):
if not self._closed:
logging.warning(
'Writer-object deleted without calling .close explicitly.')
self.close()
def __repr__(self):
return repr(self._writer) + ', closed: ' + str(self._closed)
def append(self, data: Any):
"""Appends data to the internal buffer.
NOTE: Calling this method alone does not result in anything being inserted
into the replay. To trigger data insertion, `create_item`
must be called so that the resulting sequence includes the data.
Consider the following example:
```python
A, B, C = ...
client = Client(...)
with client.writer(max_sequence_length=2) as writer:
writer.append(A) # A is added to the internal buffer.
writer.append(B) # B is added to the internal buffer.
# The buffer is now full so when this is called C is added and A is
# removed from the internal buffer and since A was never referenced by
# a prioritized item it was never sent to the server.
writer.append(C)
# A sequence of length 1 is created referencing only C and thus C is
# sent to the server.
writer.create_item('my_table', 1, 5.0)
# Writer is now closed and B was never referenced by a prioritized item
# and thus never sent to the server.
```
Args:
data: The (possibly nested) structure to make available for new
items to reference.
"""
self._writer.Append(tree.flatten(data))
def append_sequence(self, sequence: Any):
"""Appends sequence of data to the internal buffer.
Each element in `sequence` must have the same leading dimension [T].
A call to `append_sequence` is equivalent to splitting `sequence` along its
first dimension and calling `append` once for each slice.
For example:
```python
with client.writer(max_sequence_length=2) as writer:
sequence = np.array([[1, 2, 3],
[4, 5, 6]])
# Insert two timesteps.
writer.append_sequence([sequence])
# Create an item that references the step [4, 5, 6].
writer.create_item('my_table', num_timesteps=1, priority=1.0)
# Create an item that references the steps [1, 2, 3] and [4, 5, 6].
writer.create_item('my_table', num_timesteps=2, priority=1.0)
```
Is equivalent to:
```python
with client.writer(max_sequence_length=2) as writer:
# Insert two timesteps.
writer.append([np.array([1, 2, 3])])
writer.append([np.array([4, 5, 6])])
# Create an item that references the step [4, 5, 6].
writer.create_item('my_table', num_timesteps=1, priority=1.0)
# Create an item that references the steps [1, 2, 3] and [4, 5, 6].
writer.create_item('my_table', num_timesteps=2, priority=1.0)
```
Args:
sequence: Batched (possibly nested) structure to make available for items
to reference.
"""
self._writer.AppendSequence(tree.flatten(sequence))
def create_item(self, table: str, num_timesteps: int, priority: float):
"""Creates an item and sends it to the ReverbService.
This method is what effectively makes data available for sampling. See the
docstring of `append` for an illustrative example of the behavior.
Note: The item is not always immediately pushed. To ensure items
are pushed to the service, call `writer.flush()` or `writer.close()`.
Args:
table: Name of the priority table to insert the item into.
num_timesteps: The number of most recently added timesteps that the new
item should reference.
priority: The priority used for determining the sample probability of the
new item.
Raises:
ValueError: If num_timesteps is < 1.
StatusNotOk: If num_timesteps is > than the timesteps currently available
in the buffer.
"""
if num_timesteps < 1:
raise ValueError('num_timesteps (%d) must be a positive integer')
self._writer.CreateItem(table, num_timesteps, priority)
def flush(self):
"""Flushes the stream to the ReverbService.
This method sends any pending items from the local buffer to the service.
Raises:
tf.errors.OpError: If there is trouble packing or sending the data, e.g.
if shapes are inconsistent or if there was data loss.
"""
self._writer.Flush()
def close(self, retry_on_unavailable=True):
"""Closes the stream to the ReverbService.
The method is automatically called when existing the contextmanager scope.
Note: Writer-object must be abandoned after this method called.
Args:
retry_on_unavailable: if true, it will keep trying to connect to the
server if it's unavailable..
Raises:
ValueError: If `close` has already been called once.
tf.errors.OpError: If there is trouble packing or sending the data, e.g.
if shapes are inconsistent or if there was data loss.
"""
if self._closed:
raise ValueError('close() has already been called on Writer.')
self._closed = True
self._writer.Close(retry_on_unavailable)
class Client:
"""Client for interacting with a Reverb ReverbService from Python.
Note: This client should primarily be used when inserting data or prototyping
at very small scale.
Whenever possible, prefer to use TFClient (see ./tf_client.py).
"""
def __init__(self, server_address: str):
"""Constructor of Client.
Args:
server_address: Address to the Reverb ReverbService.
"""
self._server_address = server_address
self._client = pybind.Client(server_address)
self._signature_cache = {}
def __reduce__(self):
return self.__class__, (self._server_address,)
def __repr__(self):
return f'Client, server_address={self._server_address}'
@property
def server_address(self) -> str:
return self._server_address
def insert(self, data, priorities: Dict[str, float]):
"""Inserts a "blob" (e.g. trajectory) into one or more priority tables.
Note: The data is only stored once even if samples are inserted into
multiple priority tables.
Note: When possible, prefer to use the in graph version (see ./tf_client.py)
to avoid stepping through Python.
Args:
data: A (possible nested) structure to insert.
priorities: Mapping from table name to priority value.
Raises:
ValueError: If priorities is empty.
"""
if not priorities:
raise ValueError('priorities must contain at least one item')
with self.writer(max_sequence_length=1) as writer:
writer.append(data)
for table, priority in priorities.items():
writer.create_item(
table=table, num_timesteps=1, priority=priority)
def writer(self,
max_sequence_length: int,
delta_encoded: bool = False,
chunk_length: Optional[int] = None,
max_in_flight_items: Optional[int] = 25) -> Writer:
"""Constructs a writer with a `max_sequence_length` buffer.
NOTE! This method will eventually be deprecated in favor of
`trajectory_writer` so please prefer to use the latter.
The writer can be used to stream data of any length. `max_sequence_length`
controls the size of the internal buffer and ensures that prioritized items
can be created of any length <= `max_sequence_length`.
The writer is stateful and must be closed after the write has finished. The
easiest way to manage this is to use it as a contextmanager:
```python
with client.writer(10) as writer:
... # Write data of any length.
```
If not used as a contextmanager then `.close()` must be called explicitly.
Args:
max_sequence_length: Size of the internal buffer controlling the upper
limit of the number of timesteps which can be referenced in a single
prioritized item. Note that this is NOT a limit of how many timesteps or
items that can be inserted.
delta_encoded: If `True` (False by default) tensors are delta encoded
against the first item within their respective batch before compressed.
This can significantly reduce RAM at the cost of a small amount of CPU
for highly correlated data (e.g frames of video observations).
chunk_length: Number of timesteps grouped together before delta encoding
and compression. Set by default to `min(10, max_sequence_length)` but
can be overridden to achieve better compression rates when using longer
sequences with a small overlap.
max_in_flight_items: The maximum number of items allowed to be "in flight"
at the same time. An item is considered to be "in flight" if it has been
sent to the server but the response confirming that the operation
succeeded has not yet been received. Note that "in flight" items does
NOT include items that are in the client buffer due to the current chunk
not having reached its desired length yet. None results in an unlimited
number of "in flight" items.
Returns:
A `Writer` with `max_sequence_length`.
Raises:
ValueError: If max_sequence_length < 1.
ValueError: if chunk_length > max_sequence_length.
ValueError: if chunk_length < 1.
ValueError: If max_in_flight_items < 1.
"""
if max_sequence_length < 1:
raise ValueError('max_sequence_length (%d) must be a positive integer' %
max_sequence_length)
if chunk_length is None:
chunk_length = min(10, max_sequence_length)
if chunk_length < 1 or chunk_length > max_sequence_length:
raise ValueError(
'chunk_length (%d) must be a positive integer le to max_sequence_length (%d)'
% (chunk_length, max_sequence_length))
if max_in_flight_items is None:
# Mimic 'unlimited' number of "in flight" items with a big value.
max_in_flight_items = 1_000_000
if max_in_flight_items < 1:
raise ValueError(
f'max_in_flight_items ({max_in_flight_items}) must be a '
f'positive integer')
return Writer(
self._client.NewWriter(chunk_length, max_sequence_length, delta_encoded,
max_in_flight_items))
def sample(
self,
table: str,
num_samples: int = 1,
*,
emit_timesteps: bool = True,
unpack_as_table_signature: bool = False,
) -> Generator[Union[List[replay_sample.ReplaySample],
replay_sample.ReplaySample], None, None]:
"""Samples `num_samples` items from table `table` of the Server.
NOTE: This method should NOT be used for real training. TrajectoryDataset
and TimestepDataset should always be preferred over this method.
Note: If data was written using `insert` (e.g when inserting complete
trajectories) then the returned "sequence" will be a list of length 1
containing the trajectory as a single item.
If `num_samples` is greater than the number of items in `table`, (or
a rate limiter is used to control sampling), then the returned generator
will block when an item past the sampling limit is requested. It will
unblock when sufficient additional items have been added to `table`.
Example:
```python
server = Server(..., tables=[queue("queue", ...)])
client = Client(...)
# Don't insert anything into "queue"
generator = client.sample("queue")
generator.next() # Blocks until another thread/process writes to queue.
```
Args:
table: Name of the priority table to sample from.
num_samples: (default to 1) The number of samples to fetch.
emit_timesteps: If True then trajectories are returned as a list of
`ReplaySample`, each representing a single step within the trajectory.
unpack_as_table_signature: If True then the sampled data is unpacked
according to the structure of the table signature. If the table does
not have a signature then flat data is returned.
Yields:
If `emit_timesteps` is `True`:
Lists of timesteps (lists of instances of `ReplaySample`).
If data was inserted into the table via `insert`, then each element
of the generator is a length 1 list containing a `ReplaySample`.
If data was inserted via a writer, then each element is a list whose
length is the sampled trajectory's length.
If emit_timesteps is False:
An instance of `ReplaySample` where the data is unpacked according to
the signature of the table. If the table does not have any signature
then the data is flat, i.e each element is a leaf node of the full
trajectory.
Raises:
ValueError: If `emit_timestep` is True but the trajectory cannot be
decomposed into timesteps.
"""
buffer_size = 1
if unpack_as_table_signature:
signature = self._get_signature_for_table(table)
else:
signature = None
if signature:
unflatten = lambda x: tree.unflatten_as(signature, x)
else:
unflatten = lambda x: x
sampler = self._client.NewSampler(table, num_samples, buffer_size)
for _ in range(num_samples):
sample = sampler.GetNextTrajectory()
info = replay_sample.SampleInfo(
key=int(sample[0]),
probability=float(sample[1]),
table_size=int(sample[2]),
priority=float(sample[3]),
times_sampled=int(sample[4]))
data = sample[len(info):]
if emit_timesteps:
if len(set([len(col) for col in data])) != 1:
raise ValueError(
'Can\'t split non timestep trajectory into timesteps.')
timesteps = []
for i in range(data[0].shape[0]):
timestep = replay_sample.ReplaySample(
info=info,
data=unflatten([np.asarray(col[i], col.dtype) for col in data]))
timesteps.append(timestep)
yield timesteps
else:
yield replay_sample.ReplaySample(info, unflatten(data))
def mutate_priorities(self,
table: str,
updates: Optional[Dict[int, float]] = None,
deletes: Optional[List[int]] = None):
"""Updates and/or deletes existing items in a priority table.
NOTE: Whenever possible, prefer to use `TFClient.update_priorities`
instead to avoid leaving the graph.
Actions are executed in the same order as the arguments are specified.
Args:
table: Name of the priority table to update.
updates: Mapping from priority item key to new priority value. If a key
cannot be found then it is ignored.
deletes: List of keys for priority items to delete. If a key cannot be
found then it is ignored.
"""
if updates is None:
updates = {}
if deletes is None:
deletes = []
self._client.MutatePriorities(table, list(updates.items()), deletes)
def reset(self, table: str):
"""Clears all items of the table and resets its RateLimiter.
Args:
table: Name of the priority table to reset.
"""
self._client.Reset(table)
def server_info(self,
timeout: Optional[int] = None
) -> Dict[str, reverb_types.TableInfo]:
"""Get table metadata information.
Args:
timeout: Timeout in seconds to wait for server response. By default no
deadline is set and call will block indefinetely until server responds.
Returns:
A dictionary mapping table names to their associated `TableInfo`
instances, which contain metadata about the table.
Raises:
errors.DeadlineExceededError: If timeout provided and exceeded.
"""
try:
info_proto_strings = self._client.ServerInfo(timeout or 0)
except RuntimeError as e:
if 'Deadline Exceeded' in str(e) and timeout is not None:
raise errors.DeadlineExceededError(
f'ServerInfo call did not complete within provided timeout of '
f'{timeout}s')
raise
table_infos = {}
for proto_string in info_proto_strings:
table_info = reverb_types.TableInfo.from_serialized_proto(proto_string)
table_infos[table_info.name] = table_info
# Populate the signature cache if this is the first time server_info is
# (successfully) called.
if not self._signature_cache:
self._signature_cache = {
table: info.signature
for table, info in table_infos.items()
}
return table_infos
def checkpoint(self) -> str:
"""Triggers a checkpoint to be created.
Returns:
Absolute path to the saved checkpoint.
"""
return self._client.Checkpoint()
def trajectory_writer(self,
num_keep_alive_refs: int,
*,
validate_items: bool = True):
"""Constructs a new `TrajectoryWriter`.
Note: The chunk length is auto tuned by default. Use
`TrajectoryWriter.configure` to override this behaviour.
See `TrajectoryWriter` for more detailed documentation about the writer
itself.
Args:
num_keep_alive_refs: The size of the circular buffer which each column
maintains for the most recent data appended to it. When a data reference
popped from the buffer it can no longer be referenced by new items. The
value `num_keep_alive_refs` can therefore be interpreted as maximum
number of steps which a trajectory can span.
validate_items: Whether to validate items against the table signature
before they are sent to the server. This requires table signature to be
fetched from the server and cached locally.
Returns:
A `TrajectoryWriter` with auto tuned chunk lengths in each column.
Raises:
ValueError: If num_keep_alive_refs < 1.
"""
if num_keep_alive_refs < 1:
raise ValueError(
f'num_keep_alive_refs ({num_keep_alive_refs}) must be a positive '
f'integer'
)
chunker_options = pybind.AutoTunedChunkerOptions(num_keep_alive_refs, 1.0)
cpp_writer = self._client.NewTrajectoryWriter(chunker_options,
validate_items)
return trajectory_writer_lib.TrajectoryWriter(cpp_writer)
def structured_writer(self, configs: Sequence[structured_writer_lib.Config]):
"""Constructs a new `StructuredWriter`.
See `StructuredWriter` for more detailed documentation.
Args:
configs: Configurations describing how the writer should transform the
sequence of steps into table insertions.
Returns:
A `StructuredWriter` that inserts items according to `configs`.
Raises:
ValueError: If `configs` is empty or contains an invalid config.
"""
if not configs:
raise ValueError('At least one config must be provided.')
serialized_configs = [config.SerializeToString() for config in configs]
cpp_writer = self._client.NewStructuredWriter(serialized_configs)
return structured_writer_lib.StructuredWriter(cpp_writer)
def _get_signature_for_table(self, table: str):
if not self._signature_cache:
self.server_info() # Populates the cache.
if table not in self._signature_cache:
raise ValueError(
f'Could not find table "{table}". The following tables exists: '
f'{", ".join(self._signature_cache.keys())}.')
return self._signature_cache[table]
| reverb-master | reverb/client.py |
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Rate limiters."""
import abc
import sys
from typing import Tuple, Union
from absl import logging
from reverb import pybind
class RateLimiter(metaclass=abc.ABCMeta):
"""Base class for RateLimiters."""
def __init__(self, samples_per_insert: float, min_size_to_sample: int,
min_diff: float, max_diff: float):
self._samples_per_insert = samples_per_insert
self._min_size_to_sample = min_size_to_sample
self._min_diff = min_diff
self._max_diff = max_diff
self.internal_limiter = pybind.RateLimiter(
samples_per_insert=samples_per_insert,
min_size_to_sample=min_size_to_sample,
min_diff=min_diff,
max_diff=max_diff)
def __repr__(self):
return repr(self.internal_limiter)
class MinSize(RateLimiter):
"""Block sample calls unless replay contains `min_size_to_sample`.
This limiter blocks all sample calls when the replay contains less than
`min_size_to_sample` items, and accepts all sample calls otherwise.
"""
def __init__(self, min_size_to_sample: int):
if min_size_to_sample < 1:
raise ValueError(
f'min_size_to_sample ({min_size_to_sample}) must be a positive '
f'integer')
super().__init__(
samples_per_insert=1.0,
min_size_to_sample=min_size_to_sample,
min_diff=-sys.float_info.max,
max_diff=sys.float_info.max)
class SampleToInsertRatio(RateLimiter):
"""Maintains a specified ratio between samples and inserts.
The limiter works in two stages:
Stage 1. Size of table is lt `min_size_to_sample`.
Stage 2. Size of table is ge `min_size_to_sample`.
During stage 1 the limiter works exactly like MinSize, i.e. it allows
all insert calls and blocks all sample calls. Note that it is possible to
transition into stage 1 from stage 2 when items are removed from the table.
During stage 2 the limiter attempts to maintain the `samples_per_insert`
ratio between the samples and inserts. This is done by
measuring the `error`, calculated as:
error = number_of_inserts * samples_per_insert - number_of_samples
and making sure that `error` stays within `allowed_range`. Any operation
which would move `error` outside of the `allowed_range` is blocked.
Such approach allows for small deviation from a target `samples_per_insert`,
which eliminates excessive blocking of insert/sample operations and improves
performance.
If `error_buffer` is a tuple of two numbers then `allowed_range` is defined as
(error_buffer[0], error_buffer[1])
When `error_buffer` is a single number then the range is defined as
(
min_size_to_sample * samples_per_insert - error_buffer,
min_size_to_sample * samples_per_insert + error_buffer
)
"""
def __init__(self, samples_per_insert: float, min_size_to_sample: int,
error_buffer: Union[float, Tuple[float, float]]):
"""Constructor of SampleToInsertRatio.
Args:
samples_per_insert: The average number of times the learner should sample
each item in the replay buffer during the item's entire lifetime.
min_size_to_sample: The minimum number of items that the table must
contain before transitioning into stage 2.
error_buffer: Maximum size of the "error" before calls should be blocked.
When a single value is provided then inferred range is
(
min_size_to_sample * samples_per_insert - error_buffer,
min_size_to_sample * samples_per_insert + error_buffer
)
The offset is added so that the error tracked is for the insert/sample
ratio only takes into account operatons occurring AFTER stage 1. If a
range (two float tuple) then the values are used without any offset.
Raises:
ValueError: If error_buffer is smaller than max(1.0, samples_per_inserts).
"""
if isinstance(error_buffer, float) or isinstance(error_buffer, int):
offset = samples_per_insert * min_size_to_sample
min_diff = offset - error_buffer
max_diff = offset + error_buffer
else:
min_diff, max_diff = error_buffer
if samples_per_insert <= 0:
raise ValueError(f'samples_per_insert ({samples_per_insert}) must be > 0')
if max_diff - min_diff < 2 * max(1.0, samples_per_insert):
raise ValueError(
'The size of error_buffer must be >= max(1.0, samples_per_insert) as '
'smaller values could completely block samples and/or insert calls.'
)
if max_diff < samples_per_insert * min_size_to_sample:
logging.warning(
'The range covered by error_buffer is below '
'samples_per_insert * min_size_to_sample. If the sampler cannot '
'sample concurrently, this will result in a deadlock as soon as '
'min_size_to_sample items have been inserted.')
if min_diff > samples_per_insert * min_size_to_sample:
raise ValueError(
'The range covered by error_buffer is above '
'samples_per_insert * min_size_to_sample. This will result in a '
'deadlock as soon as min_size_to_sample items have been inserted.')
if min_size_to_sample < 1:
raise ValueError(
f'min_size_to_sample ({min_size_to_sample}) must be a positive '
f'integer')
super().__init__(
samples_per_insert=samples_per_insert,
min_size_to_sample=min_size_to_sample,
min_diff=min_diff,
max_diff=max_diff)
class Queue(RateLimiter):
"""Effectively turns the priority table into a queue.
NOTE: Do not use this RateLimiter directly. Use Table.queue instead.
NOTE: Must be used in conjunction with a Fifo sampler and remover.
"""
def __init__(self, size: int):
"""Constructor of Queue (do not use directly).
Args:
size: Maximum size of the queue.
"""
super().__init__(
samples_per_insert=1.0,
min_size_to_sample=1,
min_diff=0.0,
max_diff=size)
class Stack(RateLimiter):
"""Effectively turns the priority table into a stack.
NOTE: Do not use this RateLimiter directly. Use Table.stack instead.
NOTE: Must be used in conjunction with a Lifo sampler and remover.
"""
def __init__(self, size: int):
"""Constructor of Stack (do not use directly).
Args:
size: Maximum size of the stack.
"""
super().__init__(
samples_per_insert=1.0,
min_size_to_sample=1,
min_diff=0.0,
max_diff=size)
| reverb-master | reverb/rate_limiters.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.