code
stringlengths
17
6.64M
def get_time(): '\n Returns the value of the GLFW timer.\n\n Wrapper for:\n double glfwGetTime(void);\n ' return _glfw.glfwGetTime()
def set_time(time): '\n Sets the GLFW timer.\n\n Wrapper for:\n void glfwSetTime(double time);\n ' _glfw.glfwSetTime(time)
def make_context_current(window): '\n Makes the context of the specified window current for the calling\n thread.\n\n Wrapper for:\n void glfwMakeContextCurrent(GLFWwindow* window);\n ' _glfw.glfwMakeContextCurrent(window)
def get_current_context(): '\n Returns the window whose context is current on the calling thread.\n\n Wrapper for:\n GLFWwindow* glfwGetCurrentContext(void);\n ' return _glfw.glfwGetCurrentContext()
def swap_buffers(window): '\n Swaps the front and back buffers of the specified window.\n\n Wrapper for:\n void glfwSwapBuffers(GLFWwindow* window);\n ' _glfw.glfwSwapBuffers(window)
def swap_interval(interval): '\n Sets the swap interval for the current context.\n\n Wrapper for:\n void glfwSwapInterval(int interval);\n ' _glfw.glfwSwapInterval(interval)
def extension_supported(extension): '\n Returns whether the specified extension is available.\n\n Wrapper for:\n int glfwExtensionSupported(const char* extension);\n ' return _glfw.glfwExtensionSupported(_to_char_p(extension))
def get_proc_address(procname): '\n Returns the address of the specified function for the current\n context.\n\n Wrapper for:\n GLFWglproc glfwGetProcAddress(const char* procname);\n ' return _glfw.glfwGetProcAddress(_to_char_p(procname))
def append_objects(cur, extra): for i in range(cur.ngeom, (cur.ngeom + extra.ngeom)): cur.geoms[i] = extra.geoms[(i - cur.ngeom)] cur.ngeom = (cur.ngeom + extra.ngeom) if (cur.ngeom > cur.maxgeom): raise ValueError('buffer limit exceeded!')
class MJCONTACT(Structure): _fields_ = [('dist', c_double), ('pos', (c_double * 3)), ('frame', (c_double * 9)), ('includemargin', c_double), ('friction', (c_double * 5)), ('solref', (c_double * 2)), ('solimp', (c_double * 3)), ('mu', c_double), ('coef', (c_double * 5)), ('zone', c_int), ('dim', c_int), ('geom1', ...
class MJRRECT(Structure): _fields_ = [('left', c_int), ('bottom', c_int), ('width', c_int), ('height', c_int)]
class MJVCAMERAPOSE(Structure): _fields_ = [('head_pos', (c_double * 3)), ('head_right', (c_double * 3)), ('window_pos', (c_double * 3)), ('window_right', (c_double * 3)), ('window_up', (c_double * 3)), ('window_normal', (c_double * 3)), ('window_size', (c_double * 2)), ('scale', c_double), ('ipd', c_double)]
class MJROPTION(Structure): _fields_ = [('stereo', c_ubyte), ('flags', (c_ubyte * 6))]
class MJRCONTEXT(Structure): _fields_ = [('linewidth', c_float), ('znear', c_float), ('zfar', c_float), ('shadowclip', c_float), ('shadowscale', c_float), ('shadowsize', c_int), ('offwidth', c_uint), ('offheight', c_uint), ('offFBO', c_uint), ('offColor', c_uint), ('offDepthStencil', c_uint), ('shadowFBO', c_uint...
class MJVCAMERA(Structure): _fields_ = [('fovy', c_double), ('camid', c_int), ('trackbodyid', c_int), ('lookat', (c_double * 3)), ('azimuth', c_double), ('elevation', c_double), ('distance', c_double), ('pose', MJVCAMERAPOSE), ('VR', c_ubyte)]
class MJVOPTION(Structure): _fields_ = [('label', c_int), ('frame', c_int), ('geomgroup', (c_ubyte * 5)), ('sitegroup', (c_ubyte * 5)), ('flags', (c_ubyte * 18))]
class MJVGEOM(Structure): _fields_ = [('type', c_int), ('dataid', c_int), ('objtype', c_int), ('objid', c_int), ('category', c_int), ('texid', c_int), ('texuniform', c_int), ('texrepeat', (c_float * 2)), ('size', (c_float * 3)), ('pos', (c_float * 3)), ('mat', (c_float * 9)), ('rgba', (c_float * 4)), ('emission',...
class MJVLIGHT(Structure): _fields_ = [('pos', (c_float * 3)), ('dir', (c_float * 3)), ('attenuation', (c_float * 3)), ('cutoff', c_float), ('exponent', c_float), ('ambient', (c_float * 3)), ('diffuse', (c_float * 3)), ('specular', (c_float * 3)), ('headlight', c_ubyte), ('directional', c_ubyte), ('castshadow', c...
class MJVOBJECTS(Structure): _fields_ = [('nlight', c_int), ('ngeom', c_int), ('maxgeom', c_int), ('lights', (MJVLIGHT * 8)), ('geoms', POINTER(MJVGEOM)), ('geomorder', POINTER(c_int))]
class MJOPTION(Structure): _fields_ = [('timestep', c_double), ('apirate', c_double), ('tolerance', c_double), ('impratio', c_double), ('gravity', (c_double * 3)), ('wind', (c_double * 3)), ('magnetic', (c_double * 3)), ('density', c_double), ('viscosity', c_double), ('o_margin', c_double), ('o_solref', (c_double...
class MJVISUAL(Structure): class ANON_GLOBAL(Structure): _fields_ = [('fovy', c_float), ('ipd', c_float), ('linewidth', c_float), ('glow', c_float), ('offwidth', c_int), ('offheight', c_int)] class ANON_QUALITY(Structure): _fields_ = [('shadowsize', c_int), ('numSlices', c_int), ('numStacks'...
class MJSTATISTIC(Structure): _fields_ = [('meanmass', c_double), ('meansize', c_double), ('extent', c_double), ('center', (c_double * 3))]
class MJDATA(Structure): _fields_ = [('nstack', c_int), ('nbuffer', c_int), ('pstack', c_int), ('maxstackuse', c_int), ('ne', c_int), ('nf', c_int), ('nefc', c_int), ('ncon', c_int), ('nwarning', (c_int * 8)), ('warning_info', (c_int * 8)), ('timer_duration', (c_double * 14)), ('timer_ncall', (c_double * 14)), ('...
class MJMODEL(Structure): _fields_ = [('nq', c_int), ('nv', c_int), ('nu', c_int), ('na', c_int), ('nbody', c_int), ('njnt', c_int), ('ngeom', c_int), ('nsite', c_int), ('ncam', c_int), ('nlight', c_int), ('nmesh', c_int), ('nmeshvert', c_int), ('nmeshface', c_int), ('nmeshgraph', c_int), ('nhfield', c_int), ('nh...
class MjContactWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def dist(self): ...
class MjrRectWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def left(self): ...
class MjvCameraPoseWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def head_pos(...
class MjrOptionWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def stereo(self):...
class MjrContextWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def linewidth(se...
class MjvCameraWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def fovy(self): ...
class MjvOptionWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def label(self): ...
class MjvGeomWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def type(self): ...
class MjvLightWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def pos(self): ...
class MjvObjectsWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def nlight(self)...
class MjOptionWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def timestep(self)...
class MjVisualWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def global_(self):...
class MjStatisticWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def meanmass(se...
class MjDataWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def nstack(self): ...
class MjModelWrapper(object): def __init__(self, wrapped, size_src=None): self._wrapped = wrapped self._size_src = size_src @property def ptr(self): return self._wrapped @property def obj(self): return self._wrapped.contents @property def nq(self): ...
def _glfw_error_callback(e, d): logger.error('GLFW error: %s, desc: %s', e, d)
class MjViewer(object): def __init__(self, visible=True, init_width=500, init_height=500, go_fast=False): '\n Set go_fast=True to run at full speed instead of waiting for the 60 Hz monitor refresh\n init_width and init_height set window size. On Mac Retina displays, they are in nominal\n ...
class UserString(): def __init__(self, seq): if isinstance(seq, basestring): self.data = seq elif isinstance(seq, UserString): self.data = seq.data[:] else: self.data = str(seq) def __str__(self): return str(self.data) def __repr__(sel...
class MutableString(UserString): "mutable string objects\n\n Python strings are immutable objects. This has the advantage, that\n strings may be used as dictionary keys. If this property isn't needed\n and you insist on changing string values in place instead, you may cheat\n and use MutableString.\...
class String(MutableString, Union): _fields_ = [('raw', POINTER(c_char)), ('data', c_char_p)] def __init__(self, obj=''): if isinstance(obj, six.text_type): self.data = obj.encode('ascii') elif isinstance(obj, six.binary_type): self.data = obj elif isinstance(o...
def ReturnString(obj, func=None, arguments=None): return String.from_param(obj)
class PerlmutterHvp(Serializable): def __init__(self, num_slices=1): Serializable.quick_init(self, locals()) self.target = None self.reg_coeff = None self.opt_fun = None self._num_slices = num_slices def update_opt(self, f, target, inputs, reg_coeff): self.tar...
class FiniteDifferenceHvp(Serializable): def __init__(self, base_eps=1e-08, symmetric=True, grad_clip=None, num_slices=1): Serializable.quick_init(self, locals()) self.base_eps = base_eps self.symmetric = symmetric self.grad_clip = grad_clip self._num_slices = num_slices ...
class ConjugateGradientOptimizer(Serializable): '\n Performs constrained optimization via line search. The search direction is computed using a conjugate gradient\n algorithm, which gives x = A^{-1}g, where A is a second order approximation of the constraint and g is the gradient\n of the loss function.\...
class FirstOrderOptimizer(Serializable): '\n Performs (stochastic) gradient descent, possibly using fancier methods like adam etc.\n ' 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): ...
class HessianFreeOptimizer(Serializable): '\n Performs unconstrained optimization via Hessian-Free Optimization\n ' def __init__(self, max_opt_itr=20, batch_size=32, cg_batch_size=100, callback=None): Serializable.quick_init(self, locals()) self._max_opt_itr = max_opt_itr self._...
def gauss_newton_product(cost, p, v, s): if (not isinstance(s, (list, tuple))): s = [s] sum_Gv = None for si in s: Jv = T.Rop(si, p, v) HJv = T.grad(T.sum((T.grad(cost, si, disconnected_inputs='ignore') * Jv)), si, consider_constant=[Jv], disconnected_inputs='ignore') Gv = ...
class hf_optimizer(): 'Black-box Theano-based Hessian-free optimizer.\n See (Martens, ICML 2010) and (Martens & Sutskever, ICML 2011) for details.\n\n Useful functions:\n __init__ :\n Compiles necessary Theano functions from symbolic expressions.\n train :\n Performs HF optimization foll...
class SequenceDataset(): 'Slices, shuffles and manages a small dataset for the HF optimizer.' def __init__(self, data, batch_size, number_batches, minimum_size=10): 'SequenceDataset __init__\n\n data : list of lists of numpy arrays\n Your dataset will be provided as a list (one list for e...
class LbfgsOptimizer(Serializable): '\n Performs unconstrained optimization via L-BFGS.\n ' def __init__(self, max_opt_itr=20, callback=None): Serializable.quick_init(self, locals()) self._max_opt_itr = max_opt_itr self._opt_fun = None self._target = None self._c...
class BatchDataset(object): def __init__(self, inputs, batch_size, extra_inputs=None): self._inputs = [i for i in inputs] if (extra_inputs is None): extra_inputs = [] self._extra_inputs = extra_inputs self._batch_size = batch_size if (batch_size is not None): ...
class PenaltyLbfgsOptimizer(Serializable): '\n Performs constrained optimization via penalized L-BFGS. The penalty term is adaptively adjusted to make sure that\n the constraint is satisfied.\n ' def __init__(self, max_opt_itr=20, initial_penalty=1.0, min_penalty=0.01, max_penalty=1000000.0, increas...
def _worker_start(): env = None policy = None max_length = None try: while True: msgs = {} while True: try: msg = queue.get_nowait() msgs[msg[0]] = msg[1:] except Empty: break ...
def _shutdown_worker(): if process: queue.put(['stop']) queue.close() process.join()
def init_worker(): global process, queue queue = Queue() process = Process(target=_worker_start) process.start() atexit.register(_shutdown_worker)
def init_plot(env, policy): queue.put(['update', env, policy])
def update_plot(policy, max_length=np.inf): queue.put(['demo', policy.get_param_values(), max_length])
class Policy(Parameterized): def __init__(self, env_spec): Parameterized.__init__(self) self._env_spec = env_spec def get_action(self, observation): raise NotImplementedError def reset(self): pass @property def observation_space(self): return self._env_s...
class StochasticPolicy(Policy): @property def distribution(self): '\n :rtype Distribution\n ' raise NotImplementedError def dist_info_sym(self, obs_var, state_info_vars): '\n Return the symbolic distribution information about the actions.\n :param obs_...
class CategoricalConvPolicy(StochasticPolicy, LasagnePowered, Serializable): 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): '\n :param env_spec: A spec...
class CategoricalGRUPolicy(StochasticPolicy, LasagnePowered, Serializable): def __init__(self, env_spec, hidden_dim=32, feature_network=None, state_include_action=True, hidden_nonlinearity=NL.tanh): '\n :param env_spec: A spec for the env.\n :param hidden_dim: dimension of hidden layer\n ...
class CategoricalMLPPolicy(StochasticPolicy, LasagnePowered, Serializable): def __init__(self, env_spec, hidden_sizes=(32, 32), hidden_nonlinearity=NL.tanh, num_seq_inputs=1, prob_network=None): '\n :param env_spec: A spec for the mdp.\n :param hidden_sizes: list of sizes for the fully conn...
class DeterministicMLPPolicy(Policy, LasagnePowered, Serializable): def __init__(self, env_spec, hidden_sizes=(32, 32), hidden_nonlinearity=NL.rectify, hidden_W_init=LI.HeUniform(), hidden_b_init=LI.Constant(0.0), output_nonlinearity=NL.tanh, output_W_init=LI.Uniform((- 0.003), 0.003), output_b_init=LI.Uniform((...
class GaussianGRUPolicy(StochasticPolicy, LasagnePowered, Serializable): 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): '\n :param env_spec: A spec for the env.\n :param hidden...
class GaussianMLPPolicy(StochasticPolicy, LasagnePowered, Serializable): 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_no...
class UniformControlPolicy(Policy, Serializable): def __init__(self, env_spec): Serializable.quick_init(self, locals()) super(UniformControlPolicy, self).__init__(env_spec=env_spec) @overrides def get_action(self, observation): return (self.action_space.sample(), dict()) def...
class QFunction(Parameterized): pass
class ContinuousMLPQFunction(QFunction, LasagnePowered, Serializable): def __init__(self, env_spec, hidden_sizes=(32, 32), hidden_nonlinearity=NL.rectify, hidden_W_init=lasagne.init.HeUniform(), hidden_b_init=lasagne.init.Constant(0.0), action_merge_layer=(- 2), output_nonlinearity=None, output_W_init=lasagne.in...
class CategoricalMLPRegressor(LasagnePowered, Serializable): '\n A class for performing regression (or classification, really) by fitting a categorical distribution to the outputs.\n Assumes that the outputs will be always a one hot vector.\n ' def __init__(self, input_shape, output_dim, prob_networ...
class GaussianConvRegressor(LasagnePowered, Serializable): '\n A class for performing regression by fitting a Gaussian distribution to the outputs.\n ' def __init__(self, name, input_shape, output_dim, hidden_sizes, conv_filters, conv_filter_sizes, conv_strides, conv_pads, hidden_nonlinearity=NL.rectif...
class GaussianMLPRegressor(LasagnePowered, Serializable): '\n A class for performing regression by fitting a Gaussian distribution to the outputs.\n ' def __init__(self, input_shape, output_dim, mean_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=NL.rectify, optimizer=None, use_trust_region=T...
class ProductRegressor(Serializable): '\n A class for performing MLE regression by fitting a product distribution to the outputs. A separate regressor will\n be trained for each individual input distribution.\n ' def __init__(self, regressors): '\n :param regressors: List of individua...
def _worker_init(G, id): if (singleton_pool.n_parallel > 1): import os os.environ['THEANO_FLAGS'] = 'device=cpu' os.environ['CUDA_VISIBLE_DEVICES'] = '' G.worker_id = id
def initialize(n_parallel): singleton_pool.initialize(n_parallel) singleton_pool.run_each(_worker_init, [(id,) for id in range(singleton_pool.n_parallel)])
def _get_scoped_G(G, scope): if (scope is None): return G if (not hasattr(G, 'scopes')): G.scopes = dict() if (scope not in G.scopes): G.scopes[scope] = SharedGlobal() G.scopes[scope].worker_id = G.worker_id return G.scopes[scope]
def _worker_populate_task(G, env, policy, scope=None): G = _get_scoped_G(G, scope) G.env = pickle.loads(env) G.policy = pickle.loads(policy)
def _worker_terminate_task(G, scope=None): G = _get_scoped_G(G, scope) if getattr(G, 'env', None): G.env.terminate() G.env = None if getattr(G, 'policy', None): G.policy.terminate() G.policy = None
def populate_task(env, policy, scope=None): logger.log('Populating workers...') if (singleton_pool.n_parallel > 1): singleton_pool.run_each(_worker_populate_task, ([(pickle.dumps(env), pickle.dumps(policy), scope)] * singleton_pool.n_parallel)) else: G = _get_scoped_G(singleton_pool.G, sco...
def terminate_task(scope=None): singleton_pool.run_each(_worker_terminate_task, ([(scope,)] * singleton_pool.n_parallel))
def _worker_set_seed(_, seed): logger.log(('Setting seed to %d' % seed)) ext.set_seed(seed)
def set_seed(seed): singleton_pool.run_each(_worker_set_seed, [((seed + i),) for i in range(singleton_pool.n_parallel)])
def _worker_set_policy_params(G, params, scope=None): G = _get_scoped_G(G, scope) G.policy.set_param_values(params)
def _worker_set_env_params(G, params, scope=None): G = _get_scoped_G(G, scope) G.env.set_param_values(params)
def _worker_collect_one_path(G, max_path_length, scope=None, reset_arg=None): G = _get_scoped_G(G, scope) path = rollout(G.env, G.policy, max_path_length, reset_arg=reset_arg) return (path, len(path['rewards']))
def sample_paths(policy_params, max_samples, max_path_length=np.inf, env_params=None, scope=None, reset_arg=None, show_prog_bar=True, multi_task=False): '\n :param policy_params: parameters for the policy. This will be updated on each worker process\n :param max_samples: desired maximum number of samples to...
def truncate_paths(paths, max_samples): '\n Truncate the list of paths so that the total number of samples is exactly equal to max_samples. This is done by\n removing extra paths at the end of the list, and make the last path shorter if necessary\n :param paths: a list of paths\n :param max_samples: t...
class ProgBarCounter(object): def __init__(self, total_count): self.total_count = total_count self.max_progress = 1000000 self.cur_progress = 0 self.cur_count = 0 if (not logger.get_log_tabular_only()): self.pbar = pyprind.ProgBar(self.max_progress) els...
class SharedGlobal(object): pass
class StatefulPool(object): def __init__(self): self.n_parallel = 1 self.pool = None self.queue = None self.worker_queue = None self.G = SharedGlobal() def initialize(self, n_parallel): self.n_parallel = n_parallel if (self.pool is not None): ...
def _worker_run_each(all_args): try: (runner, args) = all_args singleton_pool.worker_queue.put(None) singleton_pool.queue.get() return runner(singleton_pool.G, *args) except Exception: raise Exception(''.join(traceback.format_exception(*sys.exc_info())))
def _worker_run_collect(all_args): try: (collect_once, counter, lock, threshold, args) = all_args collected = [] while True: with lock: if (counter.value >= threshold): return collected (result, inc) = collect_once(singleton_pool....
def _worker_run_map(all_args): try: (runner, args) = all_args return runner(singleton_pool.G, *args) except Exception: raise Exception(''.join(traceback.format_exception(*sys.exc_info())))
def rollout(env, agent, max_path_length=np.inf, noise=None, task_idx=0, animated=False, speedup=1, save_video=False, video_filename='sim_out.mp4', reset_arg=None): observations = [] actions = [] rewards = [] agent_infos = [] env_infos = [] images = [] noises = [] task_idxs = [] o =...
def rollout_prior(env, agent, max_path_length=np.inf, task_idx=0, noise=None, animated=False, speedup=1, save_video=True, video_filename='sim_out.mp4', reset_arg=None): observations = [] actions = [] rewards = [] agent_infos = [] env_infos = [] images = [] noises = [] task_idxs = [] ...
def rollout_prior_discrete(env, agent, max_path_length=np.inf, task_idx=0, noise=None, animated=False, speedup=1, save_video=True, video_filename='sim_out.mp4', reset_arg=None): observations = [] actions = [] rewards = [] agent_infos = [] env_infos = [] images = [] noises = [] task_idx...
class Space(object): '\n Provides a classification state spaces and action spaces,\n so you can write generic code that applies to any Environment.\n E.g. to choose a random action.\n ' def sample(self, seed=0): '\n Uniformly randomly sample a random elemnt of this space\n '...