desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return the symbolic distribution information about the actions. :param obs_var: symbolic variable for observations :param state_info_vars: a dictionary whose values should contain information about the state of the policy at the time it received the observation :return:'
def dist_info_sym(self, obs_var, state_info_vars):
raise NotImplementedError
'Return the distribution information about the actions. :param obs_var: observation values :param state_info_vars: a dictionary whose values should contain information about the state of the policy at the time it received the observation :return:'
def dist_info(self, obs, state_infos):
raise NotImplementedError
':param env_spec: A spec for the mdp. :param hidden_sizes: list of sizes for the fully connected hidden layers :param hidden_nonlinearity: nonlinearity used for each hidden layer :param prob_network: manually specified network for this policy, other network params are ignored :return:'
def __init__(self, name, env_spec, conv_filters, conv_filter_sizes, conv_strides, conv_pads, hidden_sizes=[], hidden_nonlinearity=tf.nn.relu, output_nonlinearity=tf.nn.softmax, prob_network=None):
Serializable.quick_init(self, locals()) assert isinstance(env_spec.action_space, Discrete) self._env_spec = env_spec if (prob_network is None): prob_network = ConvNetwork(input_shape=env_spec.observation_space.shape, output_dim=env_spec.action_space.n, conv_filters=conv_filters, conv_filter_size...
':param env_spec: A spec for the env. :param hidden_dim: dimension of hidden layer :param hidden_nonlinearity: nonlinearity used for each hidden layer :return:'
def __init__(self, name, env_spec, hidden_dim=32, feature_network=None, state_include_action=True, hidden_nonlinearity=tf.tanh, gru_layer_cls=L.GRULayer):
with tf.variable_scope(name): assert isinstance(env_spec.action_space, Discrete) Serializable.quick_init(self, locals()) super(CategoricalGRUPolicy, self).__init__(env_spec) obs_dim = env_spec.observation_space.flat_dim action_dim = env_spec.action_space.flat_dim if s...
':param env_spec: :param hidden_sizes: list of sizes for the fully-connected hidden layers :param learn_std: Is std trainable :param init_std: Initial std :param adaptive_std: :param std_share_network: :param std_hidden_sizes: list of sizes for the fully-connected layers for std :param min_std: whether to make sure tha...
def __init__(self, name, env_spec, hidden_sizes=(32, 32), learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_hidden_sizes=(32, 32), min_std=1e-06, std_hidden_nonlinearity=tf.nn.tanh, hidden_nonlinearity=tf.nn.tanh, output_nonlinearity=None, mean_network=None, std_network=None, std_parametriz...
Serializable.quick_init(self, locals()) assert isinstance(env_spec.action_space, Box) with tf.variable_scope(name): obs_dim = env_spec.observation_space.flat_dim action_dim = env_spec.action_space.flat_dim if (mean_network is None): mean_network = MLP(name='mean_network',...
'Given observations, old actions, and distribution of old actions, return a symbolically reparameterized representation of the actions in terms of the policy parameters :param obs_var: :param action_var: :param old_dist_info_vars: :return:'
def get_reparam_action_sym(self, obs_var, action_var, old_dist_info_vars):
new_dist_info_vars = self.dist_info_sym(obs_var, action_var) (new_mean_var, new_log_std_var) = (new_dist_info_vars['mean'], new_dist_info_vars['log_std']) (old_mean_var, old_log_std_var) = (old_dist_info_vars['mean'], old_dist_info_vars['log_std']) epsilon_var = ((action_var - old_mean_var) / (tf.exp(ol...
':param env_spec: A spec for the env. :param hidden_dim: dimension of hidden layer :param hidden_nonlinearity: nonlinearity used for each hidden layer :return:'
def __init__(self, name, env_spec, hidden_dim=32, feature_network=None, prob_network=None, state_include_action=True, hidden_nonlinearity=tf.tanh, forget_bias=1.0, use_peepholes=False, lstm_layer_cls=L.LSTMLayer):
with tf.variable_scope(name): assert isinstance(env_spec.action_space, Discrete) Serializable.quick_init(self, locals()) super(CategoricalLSTMPolicy, self).__init__(env_spec) obs_dim = env_spec.observation_space.flat_dim action_dim = env_spec.action_space.flat_dim if ...
':param env_spec: A spec for the env. :param hidden_dim: dimension of hidden layer :param hidden_nonlinearity: nonlinearity used for each hidden layer :return:'
def __init__(self, name, env_spec, hidden_dim=32, feature_network=None, state_include_action=True, hidden_nonlinearity=tf.tanh, gru_layer_cls=L.GRULayer, learn_std=True, init_std=1.0, output_nonlinearity=None):
with tf.variable_scope(name): Serializable.quick_init(self, locals()) super(GaussianGRUPolicy, self).__init__(env_spec) obs_dim = env_spec.observation_space.flat_dim action_dim = env_spec.action_space.flat_dim if state_include_action: input_dim = (obs_dim + action...
':param env_spec: A spec for the mdp. :param hidden_sizes: list of sizes for the fully connected hidden layers :param hidden_nonlinearity: nonlinearity used for each hidden layer :param prob_network: manually specified network for this policy, other network params are ignored :return:'
def __init__(self, name, env_spec, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, prob_network=None):
Serializable.quick_init(self, locals()) assert isinstance(env_spec.action_space, Discrete) with tf.variable_scope(name): if (prob_network is None): prob_network = MLP(input_shape=(env_spec.observation_space.flat_dim,), output_dim=env_spec.action_space.n, hidden_sizes=hidden_sizes, hidden...
':param env: Environment :param policy: Policy :type policy: Policy :param baseline: Baseline :param scope: Scope for identifying the algorithm. Must be specified if running multiple algorithms simultaneously, each using different environments and policies :param n_itr: Number of iterations. :param start_itr: Starting ...
def __init__(self, env, policy, baseline, scope=None, n_itr=500, start_itr=0, batch_size=5000, max_path_length=500, discount=0.99, gae_lambda=1, plot=False, pause_for_plot=False, center_adv=True, positive_adv=False, store_paths=False, whole_paths=True, fixed_horizon=False, sampler_cls=None, sampler_args=None, force_bat...
self.env = env self.policy = policy self.baseline = baseline self.scope = scope self.n_itr = n_itr self.start_itr = start_itr self.batch_size = batch_size self.max_path_length = max_path_length self.discount = discount self.gae_lambda = gae_lambda self.plot = plot self.pa...
'Initialize the optimization procedure. If using tensorflow, this may include declaring all the variables and compiling functions'
def init_opt(self):
raise NotImplementedError
'Returns all the data that should be saved in the snapshot for this iteration.'
def get_itr_snapshot(self, itr, samples_data):
raise NotImplementedError
':param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. ...
def __init__(self, name, input_shape, output_dim, mean_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, optimizer=None, use_trust_region=True, step_size=0.01, learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_hidden_sizes=(32, 32), std_nonlinearity=None, normalize_inputs...
Serializable.quick_init(self, locals()) with tf.variable_scope(name): if (optimizer is None): if use_trust_region: optimizer = PenaltyLbfgsOptimizer('optimizer') else: optimizer = LbfgsOptimizer('optimizer') self._optimizer = optimizer ...
'Return the maximum likelihood estimate of the predicted y. :param xs: :return:'
def predict(self, xs):
return self._f_predict(xs)
'Sample one possible output from the prediction distribution. :param xs: :return:'
def sample_predict(self, xs):
(means, log_stds) = self._f_pdists(xs) return self._dist.sample(dict(mean=means, log_std=log_stds))
':param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. ...
def __init__(self, name, input_shape, output_dim, prob_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, optimizer=None, tr_optimizer=None, use_trust_region=True, step_size=0.01, normalize_inputs=True, no_initial_trust_region=True):
Serializable.quick_init(self, locals()) with tf.variable_scope(name): if (optimizer is None): optimizer = LbfgsOptimizer(name='optimizer') if (tr_optimizer is None): tr_optimizer = ConjugateGradientOptimizer() self.output_dim = output_dim self.optimizer = ...
':param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood.'...
def __init__(self, name, input_shape, output_dim, network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, output_nonlinearity=None, optimizer=None, normalize_inputs=True):
Serializable.quick_init(self, locals()) with tf.variable_scope(name): if (optimizer is None): optimizer = LbfgsOptimizer(name='optimizer') self.output_dim = output_dim self.optimizer = optimizer if (network is None): network = MLP(input_shape=input_shape, ...
':param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. ...
def __init__(self, input_shape, output_dim, name, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.relu, optimizer=None, tr_optimizer=None, use_trust_region=True, step_size=0.01, normalize_inputs=True, no_initial_trust_region=True):
Serializable.quick_init(self, locals()) with tf.variable_scope(name): if (optimizer is None): optimizer = LbfgsOptimizer(name='optimizer') if (tr_optimizer is None): tr_optimizer = ConjugateGradientOptimizer() self.output_dim = output_dim self.optimizer = ...
'Internal method to be implemented which does not perform caching'
def get_params_internal(self, **tags):
raise NotImplementedError
'Get the list of parameters, filtered by the provided tags. Some common tags include \'regularizable\' and \'trainable\''
def get_params(self, **tags):
tag_tuple = tuple(sorted(list(tags.items()), key=(lambda x: x[0]))) if (tag_tuple not in self._cached_params): self._cached_params[tag_tuple] = self.get_params_internal(**tags) return self._cached_params[tag_tuple]
'Compute the symbolic KL divergence of two distributions'
def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
raise NotImplementedError
'Compute the KL divergence of two distributions'
def kl(self, old_dist_info, new_dist_info):
raise NotImplementedError
'Compute the symbolic KL divergence of two categorical distributions'
def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
old_prob_var = old_dist_info_vars['prob'] new_prob_var = new_dist_info_vars['prob'] return TT.sum((old_prob_var * (TT.log((old_prob_var + TINY)) - TT.log((new_prob_var + TINY)))), axis=2)
'Compute the KL divergence of two categorical distributions'
def kl(self, old_dist_info, new_dist_info):
old_prob = old_dist_info['prob'] new_prob = new_dist_info['prob'] return np.sum((old_prob * (np.log((old_prob + TINY)) - np.log((new_prob + TINY)))), axis=2)
'Compute the symbolic KL divergence of two categorical distributions'
def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
old_prob_var = old_dist_info_vars['prob'] new_prob_var = new_dist_info_vars['prob'] return TT.sum((old_prob_var * (TT.log((old_prob_var + TINY)) - TT.log((new_prob_var + TINY)))), axis=(-1))
'Compute the KL divergence of two categorical distributions'
def kl(self, old_dist_info, new_dist_info):
old_prob = old_dist_info['prob'] new_prob = new_dist_info['prob'] return np.sum((old_prob * (np.log((old_prob + TINY)) - np.log((new_prob + TINY)))), axis=(-1))
'Draw a single point at point p given a pixel size and color.'
def DrawPoint(self, p, size, color):
self.DrawCircle(p, (size / self.zoom), color, drawwidth=0)
'Draw a wireframe around the AABB with the given color.'
def DrawAABB(self, aabb, color):
points = [(aabb.lowerBound.x, aabb.lowerBound.y), (aabb.upperBound.x, aabb.lowerBound.y), (aabb.upperBound.x, aabb.upperBound.y), (aabb.lowerBound.x, aabb.upperBound.y)] pygame.draw.aalines(self.surface, color, True, points)
'Draw the line segment from p1-p2 with the specified color.'
def DrawSegment(self, p1, p2, color):
pygame.draw.aaline(self.surface, color.bytes, p1, p2)
'Draw the transform xf on the screen'
def DrawTransform(self, xf):
p1 = xf.position p2 = self.to_screen((p1 + (self.axisScale * xf.R.x_axis))) p3 = self.to_screen((p1 + (self.axisScale * xf.R.y_axis))) p1 = self.to_screen(p1) pygame.draw.aaline(self.surface, (255, 0, 0), p1, p2) pygame.draw.aaline(self.surface, (0, 255, 0), p1, p3)
'Draw a wireframe circle given the center, radius, axis of orientation and color.'
def DrawCircle(self, center, radius, color, drawwidth=1):
radius *= self.zoom if (radius < 1): radius = 1 else: radius = int(radius) pygame.draw.circle(self.surface, color.bytes, center, radius, drawwidth)
'Draw a solid circle given the center, radius, axis of orientation and color.'
def DrawSolidCircle(self, center, radius, axis, color):
radius *= self.zoom if (radius < 1): radius = 1 else: radius = int(radius) pygame.draw.circle(self.surface, ((color / 2).bytes + [127]), center, radius, 0) pygame.draw.circle(self.surface, color.bytes, center, radius, 1) pygame.draw.aaline(self.surface, (255, 0, 0), center, ((cen...
'Draw a wireframe polygon given the screen vertices with the specified color.'
def DrawPolygon(self, vertices, color):
if (not vertices): return if (len(vertices) == 2): pygame.draw.aaline(self.surface, color.bytes, vertices[0], vertices) else: pygame.draw.polygon(self.surface, color.bytes, vertices, 1)
'Draw a filled polygon given the screen vertices with the specified color.'
def DrawSolidPolygon(self, vertices, color):
if (not vertices): return if (len(vertices) == 2): pygame.draw.aaline(self.surface, color.bytes, vertices[0], vertices[1]) else: pygame.draw.polygon(self.surface, ((color / 2).bytes + [127]), vertices, 0) pygame.draw.polygon(self.surface, color.bytes, vertices, 1)
'Updates the view offset based on the center of the screen. Tells the debug draw to update its values also.'
def setCenter(self, value):
self._viewCenter = b2Vec2(*value) self._viewCenter *= self._viewZoom self._viewOffset = (self._viewCenter - (self.screenSize / 2))
'Check for pygame events (mainly keyboard/mouse events). Passes the events onto the GUI also.'
def checkEvents(self):
for event in pygame.event.get(): if ((event.type == QUIT) or ((event.type == KEYDOWN) and (event.key == pygame.K_ESCAPE))): return False elif (event.type == KEYDOWN): self._Keyboard_Event(event.key, down=True) elif (event.type == KEYUP): self._Keyboard_Eve...
'Internal keyboard event, don\'t override this. Checks for the initial keydown of the basic testbed keys. Passes the unused ones onto the test via the Keyboard() function.'
def _Keyboard_Event(self, key, down=True):
if down: if (key == pygame.K_z): self.viewZoom = min((2 * self.viewZoom), 500.0) elif (key == pygame.K_x): self.viewZoom = max((0.9 * self.viewZoom), 0.02)
'Check the keys that are evaluated on every main loop iteration. I.e., they aren\'t just evaluated when first pressed down'
def CheckKeys(self):
pygame.event.pump() self.keys = keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.viewCenter -= (0.5, 0) elif keys[pygame.K_RIGHT]: self.viewCenter += (0.5, 0) if keys[pygame.K_UP]: self.viewCenter += (0, 0.5) elif keys[pygame.K_DOWN]: self.viewCenter -...
'The implementation of this method should have two parts, structured like the following: <perform calculations before stepping the world> yield reward = <perform calculations after stepping the world> yield reward'
def compute_reward(self, action):
raise NotImplementedError
'Note: override this method with great care, as it post-processes the observations, etc.'
@overrides def step(self, action):
reward_computer = self.compute_reward(action) action = self._inject_action_noise(action) for _ in range(self.frame_skip): self.forward_dynamics(action) next(reward_computer) reward = next(reward_computer) self._invalidate_state_caches() done = self.is_current_done() next_obs = se...
'Filter the observation to contain only position information.'
def _filter_position(self, obs):
return obs[self._get_position_ids()]
'Inject entry-wise noise to the observation. This should not change the dimension of the observation.'
def _inject_obs_noise(self, obs):
noise = ((self.get_obs_noise_scale_factor(obs) * self.obs_noise) * np.random.normal(size=obs.shape)) return (obs + noise)
'This method should not be overwritten.'
def get_current_obs(self):
raw_obs = self.get_raw_obs() noisy_obs = self._inject_obs_noise(raw_obs) if self.position_only: return self._filter_position(noisy_obs) return noisy_obs
'Return the unfiltered & noiseless observation. By default, it computes based on the declarations in the xml file.'
def get_raw_obs(self):
if (self._cached_obs is not None): return self._cached_obs obs = [] for state in self.extra_data.states: new_obs = None if state.body: body = find_body(self.world, state.body) if (state.local is not None): l = state.local positi...
':type observation_space: Space :type action_space: Space'
def __init__(self, observation_space, action_space):
Serializable.quick_init(self, locals()) self._observation_space = observation_space self._action_space = action_space
'Inject entry-wise noise to the observation. This should not change the dimension of the observation.'
def inject_obs_noise(self, obs):
noise = ((self.get_obs_noise_scale_factor(obs) * self.obs_noise) * np.random.normal(size=obs.shape)) return (obs + noise)
'Run one timestep of the environment\'s dynamics. When end of episode is reached, reset() should be called to reset the environment\'s internal state. Input action : an action provided by the environment Outputs (observation, reward, done, info) observation : agent\'s observation of the current environment reward [Floa...
def step(self, action):
raise NotImplementedError
'Resets the state of the environment, returning an initial observation. Outputs observation : the initial observation of the space. (Initial reward is assumed to be 0.)'
def reset(self):
raise NotImplementedError
'Returns a Space object :rtype: rllab.spaces.base.Space'
@property def action_space(self):
raise NotImplementedError
'Returns a Space object :rtype: rllab.spaces.base.Space'
@property def observation_space(self):
raise NotImplementedError
'Log extra information per iteration based on the collected paths'
def log_diagnostics(self, paths):
pass
'Horizon of the environment, if it has one'
@property def horizon(self):
raise NotImplementedError
'Clean up operation,'
def terminate(self):
pass
'First it tries to use a get_ori from the wrapped env. If not successfull, falls back to the default based on the ORI_IND specified in Maze (not accurate for quaternions)'
def get_ori(self):
obj = self.wrapped_env while ((not hasattr(obj, 'get_ori')) and hasattr(obj, 'wrapped_env')): obj = obj.wrapped_env try: return obj.get_ori() except (NotImplementedError, AttributeError) as e: pass return self.wrapped_env.model.data.qpos[self.__class__.ORI_IND]
'When parallel processing, don\'t want each worker to generate its own terrain. This method ensures that one worker generates the terrain, which is then used by other workers. It\'s still possible to have each worker use their own terrain by passing each worker a different hfield and texture dir.'
def _iam_terrain_generator(self, regen):
if (not os.path.exists(self.hfield_dir)): os.makedirs(self.hfield_dir) terrain_path = os.path.join(self.hfield_dir, self.HFIELD_FNAME) lock_path = self._get_lock_path() if (regen or ((not regen) and (not os.path.exists(terrain_path)))): if (not os.path.exists(lock_path)): wit...
'Subclasses can override this to modify hfield'
def _mod_hfield(self, hfield):
return hfield
'First it tries to use a get_ori from the wrapped env. If not successfull, falls back to the default based on the ORI_IND specified in Maze (not accurate for quaternions)'
def get_ori(self):
obj = self.wrapped_env while ((not hasattr(obj, 'get_ori')) and hasattr(obj, 'wrapped_env')): obj = obj.wrapped_env try: return obj.get_ori() except (NotImplementedError, AttributeError) as e: pass return self.wrapped_env.model.data.qpos[self.__class__.ORI_IND]
'Return the action corresponding to the given direction. This is a helper method for debugging and testing purposes. :return: the action index corresponding to the given direction'
@staticmethod def action_from_direction(d):
return dict(left=0, down=1, right=2, up=3)[d]
'action map: 0: left 1: down 2: right 3: up :param action: should be a one-hot vector encoding the action :return:'
def step(self, action):
possible_next_states = self.get_possible_next_states(self.state, action) probs = [x[1] for x in possible_next_states] next_state_idx = np.random.choice(len(probs), p=probs) next_state = possible_next_states[next_state_idx][0] next_x = (next_state // self.n_col) next_y = (next_state % self.n_col)...
'Given the state and action, return a list of possible next states and their probabilities. Only next states with nonzero probabilities will be returned :param state: start state :param action: action :return: a list of pairs (s\', p(s\'|s,a))'
def get_possible_next_states(self, state, action):
x = (state // self.n_col) y = (state % self.n_col) coords = np.array([x, y]) increments = np.array([[0, (-1)], [1, 0], [0, 1], [(-1), 0]]) next_coords = np.clip((coords + increments[action]), [0, 0], [(self.n_row - 1), (self.n_col - 1)]) next_state = ((next_coords[0] * self.n_col) + next_coords[...
':param sensor_idx: list or ndarray of indices to be shown. Other indices will be occluded. Can be either list of integer indices or boolean mask.'
def __init__(self, env, sensor_idx):
Serializable.quick_init(self, locals()) self._set_sensor_mask(env, sensor_idx) super(OcclusionEnv, self).__init__(env) self._dt = 1 if isinstance(env, MujocoEnv): self._dt = (env.model.opt.timestep * env.frame_skip)
'Log extra information per iteration based on the collected paths'
def log_diagnostics(self, paths):
pass
'Initialize the sampler, e.g. launching parallel workers if necessary.'
def start_worker(self):
raise NotImplementedError
'Collect samples for the given iteration number. :param itr: Iteration number. :return: A list of paths.'
def obtain_samples(self, itr):
raise NotImplementedError
'Return processed sample data (typically a dictionary of concatenated tensors) based on the collected paths. :param itr: Iteration number. :param paths: A list of collected paths. :return: Processed sample data.'
def process_samples(self, itr, paths):
raise NotImplementedError
'Terminate workers if necessary.'
def shutdown_worker(self):
raise NotImplementedError
':type algo: BatchPolopt'
def __init__(self, algo):
self.algo = algo
'Run the method on each worker process, and collect the result of execution. The runner method will receive \'G\' as its first argument, followed by the arguments in the args_list, if any :return:'
def run_each(self, runner, args_list=None):
if (args_list is None): args_list = ([tuple()] * self.n_parallel) assert (len(args_list) == self.n_parallel) if (self.n_parallel > 1): results = self.pool.map_async(_worker_run_each, [(runner, args) for args in args_list]) for i in range(self.n_parallel): self.worker_queu...
'Run the collector method using the worker pool. The collect_once method will receive \'G\' as its first argument, followed by the provided args, if any. The method should return a pair of values. The first should be the object to be collected, and the second is the increment to be added. This will continue until the t...
def run_collect(self, collect_once, threshold, args=None, show_prog_bar=True):
if (args is None): args = tuple() if self.pool: manager = mp.Manager() counter = manager.Value('i', 0) lock = manager.RLock() results = self.pool.map_async(_worker_run_collect, ([(collect_once, counter, lock, threshold, args)] * self.n_parallel)) if show_prog_bar:...
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon. :param inputs:...
def update_opt(self, loss, target, inputs, extra_inputs=None, gradients=None, *args, **kwargs):
self._target = target def get_opt_output(gradients): if (gradients is None): gradients = theano.grad(loss, target.get_params(trainable=True)) flat_grad = flatten_tensor_variables(gradients) return [loss.astype('float64'), flat_grad.astype('float64')] if (extra_inputs is N...
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon. :param inputs:...
def update_opt(self, loss, target, leq_constraint, inputs, constraint_name='constraint', *args, **kwargs):
(constraint_term, constraint_value) = leq_constraint penalty_var = TT.scalar('penalty') penalized_loss = (loss + (penalty_var * constraint_term)) self._target = target self._max_constraint_val = constraint_value self._constraint_name = constraint_name def get_opt_output(): flat_grad ...
':param cg_iters: The number of CG iterations used to calculate A^-1 g :param reg_coeff: A small value so that A -> A + reg*I :param subsample_factor: Subsampling factor to reduce samples when using "conjugate gradient. Since the computation time for the descent direction dominates, this can greatly reduce the overall ...
def __init__(self, cg_iters=10, reg_coeff=1e-05, subsample_factor=1.0, backtrack_ratio=0.8, max_backtracks=15, accept_violation=False, hvp_approach=None, num_slices=1):
Serializable.quick_init(self, locals()) self._cg_iters = cg_iters self._reg_coeff = reg_coeff self._subsample_factor = subsample_factor self._backtrack_ratio = backtrack_ratio self._max_backtracks = max_backtracks self._num_slices = num_slices self._opt_fun = None self._target = None...
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon. :param inputs:...
def update_opt(self, loss, target, leq_constraint, inputs, extra_inputs=None, constraint_name='constraint', *args, **kwargs):
inputs = tuple(inputs) if (extra_inputs is None): extra_inputs = tuple() else: extra_inputs = tuple(extra_inputs) (constraint_term, constraint_value) = leq_constraint params = target.get_params(trainable=True) grads = theano.grad(loss, wrt=params, disconnected_inputs='warn') ...
':param max_epochs: :param tolerance: :param update_method: :param batch_size: None or an integer. If None the whole dataset will be used. :param callback: :param kwargs: :return:'
def __init__(self, update_method=lasagne.updates.adam, learning_rate=0.001, max_epochs=1000, tolerance=1e-06, batch_size=32, callback=None, verbose=False, **kwargs):
Serializable.quick_init(self, locals()) self._opt_fun = None self._target = None self._callback = callback update_method = partial(update_method, learning_rate=learning_rate) self._update_method = update_method self._max_epochs = max_epochs self._tolerance = tolerance self._batch_siz...
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon. :param inputs:...
def update_opt(self, loss, target, inputs, extra_inputs=None, gradients=None, **kwargs):
self._target = target if (gradients is None): gradients = theano.grad(loss, target.get_params(trainable=True), disconnected_inputs='ignore') updates = self._update_method(gradients, target.get_params(trainable=True)) updates = OrderedDict([(k, v.astype(k.dtype)) for (k, v) in updates.items()]) ...
':param loss: Symbolic expression for the loss function. :param target: A parameterized object to optimize over. It should implement methods of the :class:`rllab.core.paramerized.Parameterized` class. :param inputs: A list of symbolic variables as inputs :return: No return value.'
def update_opt(self, loss, target, inputs, network_outputs, extra_inputs=None):
self._target = target if (extra_inputs is None): extra_inputs = list() self._hf_optimizer = hf_optimizer(_p=target.get_params(trainable=True), inputs=(inputs + extra_inputs), s=network_outputs, costs=[loss]) self._opt_fun = lazydict(f_loss=(lambda : compile_function((inputs + extra_inputs), loss...
'Wraps a nested python sequence.'
def wrap(self, video_mode):
(size, bits, self.refresh_rate) = video_mode (self.width, self.height) = size (self.red_bits, self.green_bits, self.blue_bits) = bits
'Returns a nested python sequence.'
def unwrap(self):
size = (self.width, self.height) bits = (self.red_bits, self.green_bits, self.blue_bits) return (size, bits, self.refresh_rate)
'Wraps a nested python sequence.'
def wrap(self, gammaramp):
(red, green, blue) = gammaramp size = min(len(red), len(green), len(blue)) array_type = (ctypes.c_ushort * size) self.size = ctypes.c_uint(size) self.red_array = array_type() self.green_array = array_type() self.blue_array = array_type() for i in range(self.size): self.red_array[...
'Returns a nested python sequence.'
def unwrap(self):
red = [(self.red[i] / 65535.0) for i in range(self.size)] green = [(self.green[i] / 65535.0) for i in range(self.size)] blue = [(self.blue[i] / 65535.0) for i in range(self.size)] return (red, green, blue)
'Return (qposadr, qveladr, dof) for the given joint name. If dof is 4 or 7, then the last 4 degrees of freedom in qpos represent a unit quaternion.'
def joint_adr(self, joint_name):
jntadr = mjlib.mj_name2id(self.ptr, C.mjOBJ_JOINT, joint_name) assert (jntadr >= 0) dofmap = {C.mjJNT_FREE: 7, C.mjJNT_BALL: 4, C.mjJNT_SLIDE: 1, C.mjJNT_HINGE: 1} qposadr = self.jnt_qposadr[jntadr][0] qveladr = self.jnt_dofadr[jntadr][0] dof = dofmap[self.jnt_type[jntadr][0]] return (qposad...
'Set go_fast=True to run at full speed instead of waiting for the 60 Hz monitor refresh init_width and init_height set window size. On Mac Retina displays, they are in nominal pixels but .render returns an array of device pixels, so the array will be twice as big as you expect.'
def __init__(self, visible=True, init_width=500, init_height=500, go_fast=False):
self.visible = visible self.init_width = init_width self.init_height = init_height self.go_fast = ((not visible) or go_fast) self.last_render_time = 0 self.objects = mjcore.MJVOBJECTS() self.cam = mjcore.MJVCAMERA() self.vopt = mjcore.MJVOPTION() self.ropt = mjcore.MJROPTION() se...
'returns a tuple (width, height)'
def get_dimensions(self):
if self.window: return glfw.get_framebuffer_size(self.window) return (self.init_width, self.init_height)
'returns a tuple (data, width, height), where: - data is a string with raw bytes representing the pixels in 3-channel RGB (i.e. every three bytes = 1 pixel) - width is the width of the image - height is the height of the image'
def get_image(self):
(width, height) = self.get_dimensions() gl.glReadBuffer(gl.GL_BACK) data = gl.glReadPixels(0, 0, width, height, gl.GL_RGB, gl.GL_UNSIGNED_BYTE) return (data, width, height)
'returns a Framebuffer Object to support offscreen rendering. http://learnopengl.com/#!Advanced-OpenGL/Framebuffers'
def _init_framebuffer_object(self):
fbo = gl.glGenFramebuffers(1) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, fbo) rbo = gl.glGenRenderbuffers(1) gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, rbo) gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, gl.GL_RGBA, self.init_width, self.init_height) gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, gl....
'Indicates whether the policy is recurrent. :return:'
@property def recurrent(self):
return False
'Log extra information per iteration based on the collected paths'
def log_diagnostics(self, paths):
pass
'Return keys for the information related to the policy\'s state when taking an action. :return:'
@property def state_info_keys(self):
return list()
'Clean up operation'
def terminate(self):
pass
':rtype Distribution'
@property def distribution(self):
raise NotImplementedError
'Return the symbolic distribution information about the actions. :param obs_var: symbolic variable for observations :param state_info_vars: a dictionary whose values should contain information about the state of the policy at the time it received the observation :return:'
def dist_info_sym(self, obs_var, state_info_vars):
raise NotImplementedError
'Return the distribution information about the actions. :param obs_var: observation values :param state_info_vars: a dictionary whose values should contain information about the state of the policy at the time it received the observation :return:'
def dist_info(self, obs, state_infos):
raise NotImplementedError
':param env_spec: A spec for the mdp. :param hidden_sizes: list of sizes for the fully connected hidden layers :param hidden_nonlinearity: nonlinearity used for each hidden layer :param prob_network: manually specified network for this policy, other network params are ignored :return:'
def __init__(self, name, env_spec, conv_filters, conv_filter_sizes, conv_strides, conv_pads, hidden_sizes=[], hidden_nonlinearity=NL.rectify, output_nonlinearity=NL.softmax, prob_network=None):
Serializable.quick_init(self, locals()) assert isinstance(env_spec.action_space, Discrete) self._env_spec = env_spec if (prob_network is None): prob_network = ConvNetwork(input_shape=env_spec.observation_space.shape, output_dim=env_spec.action_space.n, conv_filters=conv_filters, conv_filter_size...
':param env_spec: A spec for the env. :param hidden_dim: dimension of hidden layer :param hidden_nonlinearity: nonlinearity used for each hidden layer :return:'
def __init__(self, env_spec, hidden_dim=32, feature_network=None, state_include_action=True, hidden_nonlinearity=NL.tanh):
assert isinstance(env_spec.action_space, Discrete) Serializable.quick_init(self, locals()) super(CategoricalGRUPolicy, self).__init__(env_spec) obs_dim = env_spec.observation_space.flat_dim action_dim = env_spec.action_space.flat_dim if state_include_action: input_dim = (obs_dim + action...
':param env_spec: :param hidden_sizes: list of sizes for the fully-connected hidden layers :param learn_std: Is std trainable :param init_std: Initial std :param adaptive_std: :param std_share_network: :param std_hidden_sizes: list of sizes for the fully-connected layers for std :param min_std: whether to make sure tha...
def __init__(self, env_spec, hidden_sizes=(32, 32), learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_hidden_sizes=(32, 32), min_std=1e-06, std_hidden_nonlinearity=NL.tanh, hidden_nonlinearity=NL.tanh, output_nonlinearity=None, mean_network=None, std_network=None, dist_cls=DiagonalGaussian)...
Serializable.quick_init(self, locals()) assert isinstance(env_spec.action_space, Box) obs_dim = env_spec.observation_space.flat_dim action_dim = env_spec.action_space.flat_dim if (mean_network is None): mean_network = MLP(input_shape=(obs_dim,), output_dim=action_dim, hidden_sizes=hidden_siz...
'Given observations, old actions, and distribution of old actions, return a symbolically reparameterized representation of the actions in terms of the policy parameters :param obs_var: :param action_var: :param old_dist_info_vars: :return:'
def get_reparam_action_sym(self, obs_var, action_var, old_dist_info_vars):
new_dist_info_vars = self.dist_info_sym(obs_var, action_var) (new_mean_var, new_log_std_var) = (new_dist_info_vars['mean'], new_dist_info_vars['log_std']) (old_mean_var, old_log_std_var) = (old_dist_info_vars['mean'], old_dist_info_vars['log_std']) epsilon_var = ((action_var - old_mean_var) / (TT.exp(ol...
':param env_spec: A spec for the env. :param hidden_sizes: list of sizes for the fully connected hidden layers :param hidden_nonlinearity: nonlinearity used for each hidden layer :return:'
def __init__(self, env_spec, hidden_sizes=(32,), state_include_action=True, hidden_nonlinearity=NL.tanh, learn_std=True, init_std=1.0, output_nonlinearity=None):
Serializable.quick_init(self, locals()) super(GaussianGRUPolicy, self).__init__(env_spec) assert (len(hidden_sizes) == 1) if state_include_action: obs_dim = (env_spec.observation_space.flat_dim + env_spec.action_space.flat_dim) else: obs_dim = env_spec.observation_space.flat_dim ...
':param env_spec: A spec for the mdp. :param hidden_sizes: list of sizes for the fully connected hidden layers :param hidden_nonlinearity: nonlinearity used for each hidden layer :param prob_network: manually specified network for this policy, other network params are ignored :return:'
def __init__(self, env_spec, hidden_sizes=(32, 32), hidden_nonlinearity=NL.tanh, num_seq_inputs=1, prob_network=None):
Serializable.quick_init(self, locals()) assert isinstance(env_spec.action_space, Discrete) if (prob_network is None): prob_network = MLP(input_shape=((env_spec.observation_space.flat_dim * num_seq_inputs),), output_dim=env_spec.action_space.n, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_no...
':param epsilon: Max KL divergence between new policy and old policy. :param L2_reg_dual: Dual regularization :param L2_reg_loss: Loss regularization :param max_opt_itr: Maximum number of batch optimization iterations. :param optimizer: Module path to the optimizer. It must support the same interface as scipy.optimize....
def __init__(self, epsilon=0.5, L2_reg_dual=0.0, L2_reg_loss=0.0, max_opt_itr=50, optimizer=scipy.optimize.fmin_l_bfgs_b, **kwargs):
Serializable.quick_init(self, locals()) super(REPS, self).__init__(**kwargs) self.epsilon = epsilon self.L2_reg_dual = L2_reg_dual self.L2_reg_loss = L2_reg_loss self.max_opt_itr = max_opt_itr self.optimizer = optimizer self.opt_info = None
':param n_itr: Number of iterations. :param max_path_length: Maximum length of a single rollout. :param batch_size: # of samples from trajs from param distribution, when this is set, n_samples is ignored :param discount: Discount. :param plot: Plot evaluation run after each iteration. :param sigma0: Initial std for par...
def __init__(self, env, policy, n_itr=500, max_path_length=500, discount=0.99, sigma0=1.0, batch_size=None, plot=False, **kwargs):
Serializable.quick_init(self, locals()) self.env = env self.policy = policy self.plot = plot self.sigma0 = sigma0 self.discount = discount self.max_path_length = max_path_length self.n_itr = n_itr self.batch_size = batch_size