class TestQfDerivedPolicy(TfGraphTestCase): def setUp(self): super().setUp() self.env = TfEnv(DummyDiscreteEnv()) self.qf = SimpleQFunction(self.env.spec) self.policy = DiscreteQfDerivedPolicy( env_spec=self.env.spec, qf=self.qf) self.sess.run(tf.global_variables_initializer()) self.env.reset() def test_discrete_qf_derived_policy(self): obs, _, _, _ = self.env.step(1) action = self.policy.get_action(obs) assert self.env.action_space.contains(action) actions = self.policy.get_actions([obs]) for action in actions: assert self.env.action_space.contains(action) def test_is_pickleable(self): with tf.variable_scope('SimpleQFunction/SimpleMLPModel', reuse=True): return_var = tf.get_variable('return_var') # assign it to all one return_var.load(tf.ones_like(return_var).eval()) obs, _, _, _ = self.env.step(1) action1 = self.policy.get_action(obs) p = pickle.dumps(self.policy) with tf.Session(graph=tf.Graph()): policy_pickled = pickle.loads(p) action2 = policy_pickled.get_action(obs) assert action1 == action2
class TestGrayscale(unittest.TestCase): def setUp(self): self.env = TfEnv(DummyDiscretePixelEnv(random=False)) self.env_g = TfEnv(Grayscale(DummyDiscretePixelEnv(random=False))) def tearDown(self): self.env.close() self.env_g.close() def test_gray_scale_invalid_environment_type(self): with self.assertRaises(ValueError): self.env.observation_space = Discrete(64) Grayscale(self.env) def test_gray_scale_invalid_environment_shape(self): with self.assertRaises(ValueError): self.env.observation_space = Box( low=0, high=255, shape=(4, ), dtype=np.uint8) Grayscale(self.env) def test_grayscale_observation_space(self): assert self.env_g.observation_space.shape == ( self.env.observation_space.shape[:-1]) def test_grayscale_reset(self): """ RGB to grayscale conversion using scikit-image. Weights used for conversion: Y = 0.2125 R + 0.7154 G + 0.0721 B Reference: http://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.rgb2grey """ gray_scale_output = np.round( np.dot(self.env.reset()[:, :, :3], [0.2125, 0.7154, 0.0721])).astype(np.uint8) np.testing.assert_array_almost_equal(gray_scale_output, self.env_g.reset()) def test_grayscale_step(self): self.env.reset() self.env_g.reset() obs, _, _, _ = self.env.step(1) obs_g, _, _, _ = self.env_g.step(1) gray_scale_output = np.round( np.dot(obs[:, :, :3], [0.2125, 0.7154, 0.0721])).astype(np.uint8) np.testing.assert_array_almost_equal(gray_scale_output, obs_g)
def test_is_pickleable(self, obs_dim, action_dim, mock_rand): mock_rand.return_value = 0 env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'categorical_mlp_policy_with_model.MLPModel'), new=SimpleMLPModel): policy = CategoricalMLPPolicyWithModel(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) expected_prob = np.full(action_dim, 0.5) p = pickle.dumps(policy) with tf.Session(graph=tf.Graph()): policy_pickled = pickle.loads(p) action, prob = policy_pickled.get_action(obs) assert env.action_space.contains(action) assert action == 0 assert np.array_equal(prob['prob'], expected_prob) prob1 = policy.dist_info([obs.flatten()]) prob2 = policy_pickled.dist_info([obs.flatten()]) assert np.array_equal(prob1['prob'], prob2['prob']) assert np.array_equal(prob2['prob'][0], expected_prob)
def test_is_pickleable(self, obs_dim, action_dim): """Test if ContinuousMLPPolicy is pickleable""" env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'continuous_mlp_policy.MLPModel'), new=SimpleMLPModel): policy = ContinuousMLPPolicy(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) with tf.compat.v1.variable_scope('ContinuousMLPPolicy/MLPModel', reuse=True): return_var = tf.compat.v1.get_variable('return_var') # assign it to all one return_var.load(tf.ones_like(return_var).eval()) output1 = self.sess.run( policy.model.outputs, feed_dict={policy.model.input: [obs.flatten()]}) p = pickle.dumps(policy) with tf.compat.v1.Session(graph=tf.Graph()) as sess: policy_pickled = pickle.loads(p) output2 = sess.run( policy_pickled.model.outputs, feed_dict={policy_pickled.model.input: [obs.flatten()]}) assert np.array_equal(output1, output2)
def test_is_pickleable(self, obs_dim, action_dim, mock_rand): mock_rand.return_value = 0 env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'categorical_mlp_policy_with_model.MLPModel'), new=SimpleMLPModel): policy = CategoricalMLPPolicyWithModel(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) with tf.variable_scope('CategoricalMLPPolicy/MLPModel', reuse=True): return_var = tf.get_variable('return_var') # assign it to all one return_var.load(tf.ones_like(return_var).eval()) output1 = self.sess.run( policy.model.outputs, feed_dict={policy.model.input: [obs.flatten()]}) p = pickle.dumps(policy) with tf.Session(graph=tf.Graph()) as sess: policy_pickled = pickle.loads(p) output2 = sess.run( policy_pickled.model.outputs, feed_dict={policy_pickled.model.input: [obs.flatten()]}) assert np.array_equal(output1, output2)
def test_is_pickleable(self, obs_dim, action_dim): env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.q_functions.' 'discrete_mlp_q_function.MLPModel'), new=SimpleMLPModel): qf = DiscreteMLPQFunction(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) with tf.variable_scope( 'discrete_mlp_q_function/discrete_mlp_q_function', reuse=True): return_var = tf.get_variable('return_var') # assign it to all one return_var.load(tf.ones_like(return_var).eval()) output1 = self.sess.run(qf.q_vals, feed_dict={qf.input: [obs]}) h_data = pickle.dumps(qf) with tf.Session(graph=tf.Graph()) as sess: qf_pickled = pickle.loads(h_data) input_var = tf.placeholder(tf.float32, shape=(None, ) + obs_dim) q_vals = qf_pickled.get_qval_sym(input_var, 'another') output2 = sess.run(q_vals, feed_dict={input_var: [obs]}) assert np.array_equal(output1, output2)
class TestResize(unittest.TestCase): @overrides def setUp(self): self.width = 16 self.height = 16 self.env = TfEnv(DummyDiscrete2DEnv()) self.env_r = TfEnv( Resize(DummyDiscrete2DEnv(), width=self.width, height=self.height)) def test_resize_invalid_environment_type(self): with self.assertRaises(ValueError): self.env.observation_space = Discrete(64) Resize(self.env, width=self.width, height=self.height) def test_resize_invalid_environment_shape(self): with self.assertRaises(ValueError): self.env.observation_space = Box(low=0, high=255, shape=(4, ), dtype=np.uint8) Resize(self.env, width=self.width, height=self.height) def test_resize_output_observation_space(self): assert self.env_r.observation_space.shape == (self.width, self.height) def test_resize_output_reset(self): assert self.env_r.reset().shape == (self.width, self.height) def test_resize_output_step(self): self.env_r.reset() obs_r, _, _, _ = self.env_r.step(1) assert obs_r.shape == (self.width, self.height)
def test_dist_info(self, obs_dim, embedding_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=embedding_dim)) with mock.patch(('garage.tf.embeddings.' 'gaussian_mlp_encoder.GaussianMLPModel'), new=SimpleGaussianMLPModel): embedding_spec = InOutSpec(input_space=env.spec.observation_space, output_space=env.spec.action_space) embedding = GaussianMLPEncoder(embedding_spec) env.reset() obs, _, _, _ = env.step(1) obs_dim = env.spec.observation_space.flat_dim obs_ph = tf.compat.v1.placeholder(tf.float32, shape=(None, obs_dim)) dist1_sym = embedding.dist_info_sym(obs_ph, name='p1_sym') # flatten output expected_mean = [np.full(np.prod(embedding_dim), 0.5)] expected_log_std = [np.full(np.prod(embedding_dim), np.log(0.5))] prob0 = embedding.dist_info(obs.flatten()) prob1 = self.sess.run(dist1_sym, feed_dict={obs_ph: [obs.flatten()]}) assert np.array_equal(prob0['mean'].flatten(), expected_mean[0]) assert np.array_equal(prob0['log_std'].flatten(), expected_log_std[0]) assert np.array_equal(prob1['mean'], expected_mean) assert np.array_equal(prob1['log_std'], expected_log_std)
def test_get_action(self, mock_rand, obs_dim, action_dim, filter_dims, filter_sizes, strides, padding, hidden_sizes): mock_rand.return_value = 0 env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'categorical_cnn_policy.MLPModel'), new=SimpleMLPModel): with mock.patch(('garage.tf.policies.' 'categorical_cnn_policy.CNNModel'), new=SimpleCNNModel): policy = CategoricalCNNPolicy(env_spec=env.spec, conv_filters=filter_dims, conv_filter_sizes=filter_sizes, conv_strides=strides, conv_pad=padding, hidden_sizes=hidden_sizes) env.reset() obs, _, _, _ = env.step(1) action, prob = policy.get_action(obs) expected_prob = np.full(action_dim, 0.5) assert env.action_space.contains(action) assert action == 0 assert np.array_equal(prob['prob'], expected_prob) actions, probs = policy.get_actions([obs, obs, obs]) for action, prob in zip(actions, probs['prob']): assert env.action_space.contains(action) assert action == 0 assert np.array_equal(prob, expected_prob)
def test_is_pickleable(self, mock_rand, obs_dim, action_dim): mock_rand.return_value = 0 env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'categorical_cnn_policy.MLPModel'), new=SimpleMLPModel): with mock.patch(('garage.tf.policies.' 'categorical_cnn_policy.CNNModel'), new=SimpleCNNModel): policy = CategoricalCNNPolicy(env_spec=env.spec, conv_filters=(32, ), conv_filter_sizes=(3, ), conv_strides=(1, ), conv_pad='SAME', hidden_sizes=(4, )) env.reset() obs, _, _, _ = env.step(1) with tf.compat.v1.variable_scope( 'CategoricalCNNPolicy/Sequential/MLPModel', reuse=True): return_var = tf.compat.v1.get_variable('return_var') # assign it to all one return_var.load(tf.ones_like(return_var).eval()) output1 = self.sess.run(policy.model.outputs, feed_dict={policy.model.input: [obs]}) p = pickle.dumps(policy) with tf.compat.v1.Session(graph=tf.Graph()) as sess: policy_pickled = pickle.loads(p) output2 = sess.run(policy_pickled.model.outputs, feed_dict={policy_pickled.model.input: [obs]}) assert np.array_equal(output1, output2)
def test_get_qval_max_pooling(self, filter_dims, num_filters, strides, pool_strides, pool_shapes): env = TfEnv(DummyDiscretePixelEnv()) obs = env.reset() with mock.patch(('garage.tf.models.' 'cnn_mlp_merge_model.CNNModelWithMaxPooling'), new=SimpleCNNModelWithMaxPooling): with mock.patch(('garage.tf.models.' 'cnn_mlp_merge_model.MLPMergeModel'), new=SimpleMLPMergeModel): qf = ContinuousCNNQFunction(env_spec=env.spec, filter_dims=filter_dims, num_filters=num_filters, strides=strides, max_pooling=True, pool_strides=pool_strides, pool_shapes=pool_shapes) action_dim = env.action_space.shape obs, _, _, _ = env.step(1) act = np.full(action_dim, 0.5) expected_output = np.full((1, ), 0.5) outputs = qf.get_qval([obs], [act]) assert np.array_equal(outputs[0], expected_output) outputs = qf.get_qval([obs, obs, obs], [act, act, act]) for output in outputs: assert np.array_equal(output, expected_output)
def test_dist_info_sym(self, obs_dim, action_dim, filter_dims, filter_sizes, strides, padding, hidden_sizes): env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'categorical_cnn_policy.MLPModel'), new=SimpleMLPModel): with mock.patch(('garage.tf.policies.' 'categorical_cnn_policy.CNNModel'), new=SimpleCNNModel): policy = CategoricalCNNPolicy(env_spec=env.spec, conv_filters=filter_dims, conv_filter_sizes=filter_sizes, conv_strides=strides, conv_pad=padding, hidden_sizes=hidden_sizes) env.reset() obs, _, _, _ = env.step(1) expected_prob = np.full(action_dim, 0.5) obs_dim = env.spec.observation_space.shape state_input = tf.compat.v1.placeholder(tf.float32, shape=(None, ) + obs_dim) dist1 = policy.dist_info_sym(state_input, name='policy2') prob = self.sess.run(dist1['prob'], feed_dict={state_input: [obs]}) assert np.array_equal(prob[0], expected_prob)
def test_is_pickleable(self, obs_dim, action_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'gaussian_mlp_policy_with_model.GaussianMLPModel'), new=SimpleGaussianMLPModel): policy = GaussianMLPPolicyWithModel(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) obs_dim = env.spec.observation_space.flat_dim with tf.variable_scope('GaussianMLPPolicyWithModel/GaussianMLPModel', reuse=True): return_var = tf.get_variable('return_var') # assign it to all one return_var.load(tf.ones_like(return_var).eval()) output1 = self.sess.run( policy.model.outputs[:-1], feed_dict={policy.model.input: [obs.flatten()]}) p = pickle.dumps(policy) with tf.Session(graph=tf.Graph()) as sess: policy_pickled = pickle.loads(p) output2 = sess.run( policy_pickled.model.outputs[:-1], feed_dict={policy_pickled.model.input: [obs.flatten()]}) assert np.array_equal(output1, output2)
def test_get_action(self, obs_dim, task_num, latent_dim, action_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim)) embedding_spec = InOutSpec( input_space=akro.Box(low=np.zeros(task_num), high=np.ones(task_num)), output_space=akro.Box(low=np.zeros(latent_dim), high=np.ones(latent_dim))) encoder = GaussianMLPEncoder(embedding_spec) policy = GaussianMLPTaskEmbeddingPolicy(env_spec=env.spec, encoder=encoder) env.reset() obs, _, _, _ = env.step(1) latent = np.random.random((latent_dim, )) task = np.zeros(task_num) task[0] = 1 action1, _ = policy.get_action_given_latent(obs, latent) action2, _ = policy.get_action_given_task(obs, task) action3, _ = policy.get_action(np.concatenate([obs.flatten(), task])) assert env.action_space.contains(action1) assert env.action_space.contains(action2) assert env.action_space.contains(action3) obses, latents, tasks = [obs] * 3, [latent] * 3, [task] * 3 aug_obses = [np.concatenate([obs.flatten(), task])] * 3 action1n, _ = policy.get_actions_given_latents(obses, latents) action2n, _ = policy.get_actions_given_tasks(obses, tasks) action3n, _ = policy.get_actions(aug_obses) for action in chain(action1n, action2n, action3n): assert env.action_space.contains(action)
def test_get_action(self, obs_dim, action_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'gaussian_mlp_policy_with_model.GaussianMLPModel'), new=SimpleGaussianMLPModel): policy = GaussianMLPPolicyWithModel(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) action, prob = policy.get_action(obs) expected_action = np.full(action_dim, 0.75) expected_mean = np.full(action_dim, 0.5) expected_log_std = np.full(action_dim, 0.5) assert env.action_space.contains(action) assert np.array_equal(action, expected_action) assert np.array_equal(prob['mean'], expected_mean) assert np.array_equal(prob['log_std'], expected_log_std) actions, probs = policy.get_actions([obs, obs, obs]) for action, mean, log_std in zip(actions, probs['mean'], probs['log_std']): assert env.action_space.contains(action) assert np.array_equal(action, expected_action) assert np.array_equal(prob['mean'], expected_mean) assert np.array_equal(prob['log_std'], expected_log_std)
def test_get_action(self, mock_rand, filter_dims, num_filters, strides, padding, hidden_sizes): mock_rand.return_value = 0 env = TfEnv(DummyDiscretePixelEnv()) policy = CategoricalCNNPolicy2(env_spec=env.spec, filter_dims=filter_dims, num_filters=num_filters, strides=strides, padding=padding, hidden_sizes=hidden_sizes) obs_var = tf.compat.v1.placeholder(tf.float32, shape=(None, ) + env.observation_space.shape, name='obs') policy.build(obs_var) env.reset() obs, _, _, _ = env.step(1) action, _ = policy.get_action(obs) assert env.action_space.contains(action) actions, _ = policy.get_actions([obs, obs, obs]) for action in actions: assert env.action_space.contains(action)
def test_get_qval_sym(self, obs_dim, action_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.q_functions.' 'continuous_mlp_q_function.MLPMergeModel'), new=SimpleMLPMergeModel): qf = ContinuousMLPQFunction(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) obs = obs.flatten() act = np.full(action_dim, 0.5).flatten() output1 = qf.get_qval([obs], [act]) input_var1 = tf.compat.v1.placeholder(tf.float32, shape=(None, obs.shape[0])) input_var2 = tf.compat.v1.placeholder(tf.float32, shape=(None, act.shape[0])) q_vals = qf.get_qval_sym(input_var1, input_var2, 'another') output2 = self.sess.run(q_vals, feed_dict={ input_var1: [obs], input_var2: [act] }) expected_output = np.full((1, ), 0.5) assert np.array_equal(output1, output2) assert np.array_equal(output2[0], expected_output)
def test_is_pickleable(self, obs_dim, action_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.q_functions.' 'continuous_mlp_q_function.MLPMergeModel'), new=SimpleMLPMergeModel): qf = ContinuousMLPQFunction(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) obs = obs.flatten() act = np.full(action_dim, 0.5).flatten() with tf.compat.v1.variable_scope( 'ContinuousMLPQFunction/SimpleMLPMergeModel', reuse=True): return_var = tf.compat.v1.get_variable('return_var') # assign it to all one return_var.load(tf.ones_like(return_var).eval()) output1 = qf.get_qval([obs], [act]) h_data = pickle.dumps(qf) with tf.compat.v1.Session(graph=tf.Graph()): qf_pickled = pickle.loads(h_data) output2 = qf_pickled.get_qval([obs], [act]) assert np.array_equal(output1, output2)
def test_is_pickleable(self, obs_dim, embedding_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=embedding_dim)) with mock.patch(('garage.tf.embeddings.' 'gaussian_mlp_encoder.GaussianMLPModel'), new=SimpleGaussianMLPModel): embedding_spec = InOutSpec(input_space=env.spec.observation_space, output_space=env.spec.action_space) embedding = GaussianMLPEncoder(embedding_spec) env.reset() obs, _, _, _ = env.step(1) obs_dim = env.spec.observation_space.flat_dim with tf.compat.v1.variable_scope('GaussianMLPEncoder/GaussianMLPModel', reuse=True): return_var = tf.compat.v1.get_variable('return_var') # assign it to all one return_var.load(tf.ones_like(return_var).eval()) output1 = self.sess.run( embedding.model.outputs[:-1], feed_dict={embedding.model.input: [obs.flatten()]}) p = pickle.dumps(embedding) with tf.compat.v1.Session(graph=tf.Graph()) as sess: embedding_pickled = pickle.loads(p) output2 = sess.run( embedding_pickled.model.outputs[:-1], feed_dict={embedding_pickled.model.input: [obs.flatten()]}) assert np.array_equal(output1, output2)
class TestStackFrames(unittest.TestCase): def setUp(self): self.n_frames = 4 self.env = TfEnv(DummyDiscrete2DEnv(random=False)) self.env_s = TfEnv( StackFrames( DummyDiscrete2DEnv(random=False), n_frames=self.n_frames)) self.width, self.height = self.env.observation_space.shape def tearDown(self): self.env.close() self.env_s.close() def test_stack_frames_invalid_environment_type(self): with self.assertRaises(ValueError): self.env.observation_space = Discrete(64) StackFrames(self.env, n_frames=4) def test_stack_frames_invalid_environment_shape(self): with self.assertRaises(ValueError): self.env.observation_space = Box( low=0, high=255, shape=(4, ), dtype=np.uint8) StackFrames(self.env, n_frames=4) def test_stack_frames_output_observation_space(self): assert self.env_s.observation_space.shape == (self.width, self.height, self.n_frames) def test_stack_frames_for_reset(self): frame_stack = self.env.reset() for i in range(self.n_frames - 1): frame_stack = np.dstack((frame_stack, self.env.reset())) np.testing.assert_array_equal(self.env_s.reset(), frame_stack) def test_stack_frames_for_step(self): self.env.reset() self.env_s.reset() frame_stack = np.empty((self.width, self.height, self.n_frames)) for i in range(10): frame_stack = frame_stack[:, :, 1:] obs, _, _, _ = self.env.step(1) frame_stack = np.dstack((frame_stack, obs)) obs_stack, _, _, _ = self.env_s.step(1) np.testing.assert_array_equal(obs_stack, frame_stack)
class TestRepeatAction(unittest.TestCase): @overrides def setUp(self): self.env = TfEnv(DummyDiscreteEnv(random=False)) self.env_r = TfEnv( RepeatAction(DummyDiscreteEnv(random=False), n_frame_to_repeat=4)) def test_repeat_action_reset(self): np.testing.assert_array_equal(self.env.reset(), self.env_r.reset()) def test_repeat_action_step(self): self.env.reset() self.env_r.reset() obs_repeat, _, _, _ = self.env_r.step(1) for i in range(4): obs, _, _, _ = self.env.step(1) np.testing.assert_array_equal(obs, obs_repeat)
class TestNormalizedGym(unittest.TestCase): @overrides def setUp(self): self.env = TfEnv( normalize(gym.make('Pendulum-v0'), normalize_reward=True, normalize_obs=True, flatten_obs=True)) def test_does_not_modify_action(self): a = self.env.action_space.sample() a_copy = a self.env.reset() self.env.step(a) self.assertEquals(a, a_copy) self.env.close() def test_flatten(self): for _ in range(10): self.env.reset() for _ in range(5): self.env.render() action = self.env.action_space.sample() next_obs, _, done, _ = self.env.step(action) self.assertEqual(next_obs.shape, self.env.observation_space.low.shape) if done: break self.env.close() def test_unflatten(self): for _ in range(10): self.env.reset() for _ in range(5): action = self.env.action_space.sample() next_obs, _, done, _ = self.env.step(action) self.assertEqual( self.env.observation_space.flatten(next_obs).shape, self.env.observation_space.flat_dim) if done: break self.env.close()
def test_output_shape(self, obs_dim, action_dim): env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.q_functions.' 'discrete_mlp_q_function.MLPModel'), new=SimpleMLPModel): qf = DiscreteMLPQFunction(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) outputs = self.sess.run(qf.q_vals, feed_dict={qf.input: [obs]}) assert outputs.shape == (1, action_dim)
class TestNormalizedGym: def setup_method(self): self.env = TfEnv( normalize(gym.make('Pendulum-v0'), normalize_reward=True, normalize_obs=True, flatten_obs=True)) def teardown_method(self): self.env.close() def test_does_not_modify_action(self): a = self.env.action_space.sample() a_copy = a self.env.reset() self.env.step(a) assert a == a_copy def test_flatten(self): for _ in range(10): self.env.reset() for _ in range(5): self.env.render() action = self.env.action_space.sample() next_obs, _, done, _ = self.env.step(action) assert next_obs.shape == self.env.observation_space.low.shape if done: break def test_unflatten(self): for _ in range(10): self.env.reset() for _ in range(5): action = self.env.action_space.sample() next_obs, _, done, _ = self.env.step(action) # yapf: disable assert (self.env.observation_space.flatten(next_obs).shape == self.env.observation_space.flat_dim) # yapf: enable if done: break
def test_output_shape(self, obs_dim, action_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.q_functions.' 'continuous_mlp_q_function.MLPMergeModel'), new=SimpleMLPMergeModel): qf = ContinuousMLPQFunction(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) obs = obs.flatten() act = np.full(action_dim, 0.5).flatten() outputs = qf.get_qval([obs], [act]) assert outputs.shape == (1, 1)
def test_dist_info(self, obs_dim, action_dim): env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'categorical_mlp_policy_with_model.MLPModel'), new=SimpleMLPModel): policy = CategoricalMLPPolicyWithModel(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) expected_prob = np.full(action_dim, 0.5) policy_probs = policy.dist_info([obs.flatten()]) assert np.array_equal(policy_probs['prob'][0], expected_prob)
def test_get_embedding(self, obs_dim, embedding_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=embedding_dim)) embedding_spec = InOutSpec(input_space=env.spec.observation_space, output_space=env.spec.action_space) embedding = GaussianMLPEncoder(embedding_spec) task_input = tf.compat.v1.placeholder(tf.float32, shape=(None, None, embedding.input_dim)) embedding.build(task_input) env.reset() obs, _, _, _ = env.step(1) latent, _ = embedding.forward(obs) assert env.action_space.contains(latent)
class TestQfDerivedPolicy(TfGraphTestCase): def setUp(self): super().setUp() self.env = TfEnv(DummyDiscreteEnv()) self.qf = SimpleQFunction(self.env.spec) self.policy = DiscreteQfDerivedPolicy( env_spec=self.env.spec, qf=self.qf) self.sess.run(tf.global_variables_initializer()) self.env.reset() def test_discrete_qf_derived_policy(self): obs, _, _, _ = self.env.step(1) action = self.policy.get_action(obs) assert self.env.action_space.contains(action) actions = self.policy.get_actions([obs]) for action in actions: assert self.env.action_space.contains(action)
def test_is_pickleable(self, obs_dim, action_dim): env = TfEnv(DummyBoxEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.policies.' 'deterministic_mlp_policy_with_model.MLPModel'), new=SimpleMLPModel): policy = DeterministicMLPPolicyWithModel(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) action1, _ = policy.get_action(obs) p = pickle.dumps(policy) with tf.Session(graph=tf.Graph()): policy_pickled = pickle.loads(p) action2, _ = policy_pickled.get_action(obs) assert env.action_space.contains(action2) assert np.array_equal(action1, action2)
def test_get_action(self, obs_dim, action_dim): env = TfEnv(DummyDiscreteEnv(obs_dim=obs_dim, action_dim=action_dim)) with mock.patch(('garage.tf.q_functions.' 'discrete_mlp_q_function.MLPModel'), new=SimpleMLPModel): qf = DiscreteMLPQFunction(env_spec=env.spec) env.reset() obs, _, _, _ = env.step(1) expected_output = np.full(action_dim, 0.5) outputs = self.sess.run(qf.q_vals, feed_dict={qf.input: [obs]}) assert np.array_equal(outputs[0], expected_output) outputs = self.sess.run(qf.q_vals, feed_dict={qf.input: [obs, obs, obs]}) for output in outputs: assert np.array_equal(output, expected_output)