code
stringlengths
17
6.64M
class RecurrentCategorical(Distribution): def __init__(self, dim): self._cat = Categorical(dim) self._dim = dim @property def dim(self): return self._dim def kl_sym(self, old_dist_info_vars, new_dist_info_vars): '\n Compute the symbolic KL divergence of two categorical distributions\n ' 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) def kl(self, old_dist_info, new_dist_info): '\n Compute the KL divergence of two categorical distributions\n ' 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) def likelihood_ratio_sym(self, x_var, old_dist_info_vars, new_dist_info_vars): old_prob_var = old_dist_info_vars['prob'] new_prob_var = new_dist_info_vars['prob'] a_dim = x_var.shape[(- 1)] flat_ratios = self._cat.likelihood_ratio_sym(x_var.reshape(((- 1), a_dim)), dict(prob=old_prob_var.reshape(((- 1), a_dim))), dict(prob=new_prob_var.reshape(((- 1), a_dim)))) return flat_ratios.reshape(old_prob_var.shape[:2]) def entropy(self, dist_info): probs = dist_info['prob'] return (- np.sum((probs * np.log((probs + TINY))), axis=2)) def log_likelihood_sym(self, xs, dist_info_vars): probs = dist_info_vars['prob'] a_dim = probs.shape[(- 1)] flat_logli = self._cat.log_likelihood_sym(xs.reshape(((- 1), a_dim)), dict(prob=probs.reshape(((- 1), a_dim)))) return flat_logli.reshape(probs.shape[:2]) def log_likelihood(self, xs, dist_info): probs = dist_info['prob'] a_dim = probs.shape[(- 1)] flat_logli = self._cat.log_likelihood_sym(xs.reshape(((- 1), a_dim)), dict(prob=probs.reshape(((- 1), a_dim)))) return flat_logli.reshape(probs.shape[:2]) @property def dist_info_keys(self): return ['prob']
class Env(object): def step(self, action): "\n Run one timestep of the environment's dynamics. When end of episode\n is reached, reset() should be called to reset the environment's internal state.\n Input\n -----\n action : an action provided by the environment\n Outputs\n -------\n (observation, reward, done, info)\n observation : agent's observation of the current environment\n reward [Float] : amount of reward due to the previous action\n done : a boolean, indicating whether the episode has ended\n info : a dictionary containing other diagnostic information from the previous action\n " raise NotImplementedError def reset(self, reset_args=None): '\n Resets the state of the environment, returning an initial observation.\n Outputs\n -------\n observation : the initial observation of the space. (Initial reward is assumed to be 0.)\n ' raise NotImplementedError @property def action_space(self): '\n Returns a Space object\n :rtype: rllab.spaces.base.Space\n ' raise NotImplementedError @property def observation_space(self): '\n Returns a Space object\n :rtype: rllab.spaces.base.Space\n ' raise NotImplementedError @property def action_dim(self): return self.action_space.flat_dim def render(self): pass def log_diagnostics(self, paths, prefix=''): '\n Log extra information per iteration based on the collected paths\n ' pass @property def spec(self): return EnvSpec(observation_space=self.observation_space, action_space=self.action_space) @property def horizon(self): '\n Horizon of the environment, if it has one\n ' raise NotImplementedError def terminate(self): '\n Clean up operation,\n ' pass
def Step(observation, reward, done, **kwargs): '\n Convenience method creating a namedtuple with the results of the\n environment.step method.\n Put extra diagnostic info in the kwargs\n ' return _Step(observation, reward, done, kwargs)
class Box2DEnv(Env): @autoargs.arg('frame_skip', type=int, help='Number of frames to skip') @autoargs.arg('position_only', type=bool, help='Whether to only provide (generalized) position as the observation (i.e. no velocities etc.)') @autoargs.arg('obs_noise', type=float, help='Noise added to the observations (note: this makes the problem non-Markovian!)') @autoargs.arg('action_noise', type=float, help='Noise added to the controls, which will be proportional to the action bounds') def __init__(self, model_path, frame_skip=1, position_only=False, obs_noise=0.0, action_noise=0.0, template_string=None, template_args=None): self.full_model_path = model_path if (template_string is None): if model_path.endswith('.mako'): with open(model_path) as template_file: template = mako.template.Template(template_file.read()) template_string = template.render(opts=(template_args if (template_args is not None) else {})) else: with open(model_path, 'r') as f: template_string = f.read() (world, extra_data) = world_from_xml(template_string) self.world = world self.extra_data = extra_data self.initial_state = self._state self.viewer = None self.frame_skip = frame_skip self.timestep = self.extra_data.timeStep self.position_only = position_only self.obs_noise = obs_noise self.action_noise = action_noise self._action_bounds = None self._position_ids = None self._cached_obs = None self._cached_coms = {} def model_path(self, file_name): return osp.abspath(osp.join(osp.dirname(__file__), ('models/%s' % file_name))) def _set_state(self, state): splitted = np.array(state).reshape(((- 1), 6)) for (body, body_state) in zip(self.world.bodies, splitted): (xpos, ypos, apos, xvel, yvel, avel) = body_state body.position = (xpos, ypos) body.angle = apos body.linearVelocity = (xvel, yvel) body.angularVelocity = avel @overrides def reset(self): self._set_state(self.initial_state) self._invalidate_state_caches() return self.get_current_obs() def _invalidate_state_caches(self): self._cached_obs = None self._cached_coms = {} @property def _state(self): s = [] for body in self.world.bodies: s.append(np.concatenate([list(body.position), [body.angle], list(body.linearVelocity), [body.angularVelocity]])) return np.concatenate(s) @property @overrides def action_space(self): lb = np.array([control.ctrllimit[0] for control in self.extra_data.controls]) ub = np.array([control.ctrllimit[1] for control in self.extra_data.controls]) return spaces.Box(lb, ub) @property @overrides def observation_space(self): if self.position_only: d = len(self._get_position_ids()) else: d = len(self.extra_data.states) ub = (BIG * np.ones(d)) return spaces.Box((ub * (- 1)), ub) @property def action_bounds(self): return self.action_space.bounds def forward_dynamics(self, action): if (len(action) != self.action_dim): raise ValueError(('incorrect action dimension: expected %d but got %d' % (self.action_dim, len(action)))) (lb, ub) = self.action_bounds action = np.clip(action, lb, ub) for (ctrl, act) in zip(self.extra_data.controls, action): if (ctrl.typ == 'force'): for name in ctrl.bodies: body = find_body(self.world, name) direction = np.array(ctrl.direction) direction = (direction / np.linalg.norm(direction)) world_force = body.GetWorldVector((direction * act)) world_point = body.GetWorldPoint(ctrl.anchor) body.ApplyForce(world_force, world_point, wake=True) elif (ctrl.typ == 'torque'): assert ctrl.joint joint = find_joint(self.world, ctrl.joint) joint.motorEnabled = True if (act > 0): joint.motorSpeed = 100000.0 else: joint.motorSpeed = (- 100000.0) joint.maxMotorTorque = abs(act) else: raise NotImplementedError self.before_world_step(action) self.world.Step(self.extra_data.timeStep, self.extra_data.velocityIterations, self.extra_data.positionIterations) def compute_reward(self, action): '\n The implementation of this method should have two parts, structured\n like the following:\n\n <perform calculations before stepping the world>\n yield\n reward = <perform calculations after stepping the world>\n yield reward\n ' raise NotImplementedError @overrides def step(self, action): '\n Note: override this method with great care, as it post-processes the\n observations, etc.\n ' 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 = self.get_current_obs() return Step(observation=next_obs, reward=reward, done=done) def _filter_position(self, obs): '\n Filter the observation to contain only position information.\n ' return obs[self._get_position_ids()] def get_obs_noise_scale_factor(self, obs): return np.ones_like(obs) def _inject_obs_noise(self, obs): '\n Inject entry-wise noise to the observation. This should not change\n the dimension of the observation.\n ' noise = ((self.get_obs_noise_scale_factor(obs) * self.obs_noise) * np.random.normal(size=obs.shape)) return (obs + noise) def get_current_reward(self, state, xml_obs, action, next_state, next_xml_obs): raise NotImplementedError def is_current_done(self): raise NotImplementedError def _inject_action_noise(self, action): noise = (self.action_noise * np.random.normal(size=action.shape)) (lb, ub) = self.action_bounds noise = ((0.5 * (ub - lb)) * noise) return (action + noise) def get_current_obs(self): '\n This method should not be overwritten.\n ' 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 def _get_position_ids(self): if (self._position_ids is None): self._position_ids = [] for (idx, state) in enumerate(self.extra_data.states): if (state.typ in ['xpos', 'ypos', 'apos', 'dist', 'angle']): self._position_ids.append(idx) return self._position_ids def get_raw_obs(self): '\n Return the unfiltered & noiseless observation. By default, it computes\n based on the declarations in the xml file.\n ' 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 position = body.GetWorldPoint(l) linearVel = body.GetLinearVelocityFromLocalPoint(l) else: position = body.position linearVel = body.linearVelocity if (state.to is not None): to = find_body(self.world, state.to) if (state.typ == 'xpos'): new_obs = position[0] elif (state.typ == 'ypos'): new_obs = position[1] elif (state.typ == 'xvel'): new_obs = linearVel[0] elif (state.typ == 'yvel'): new_obs = linearVel[1] elif (state.typ == 'apos'): new_obs = body.angle elif (state.typ == 'avel'): new_obs = body.angularVelocity elif (state.typ == 'dist'): new_obs = np.linalg.norm((position - to.position)) elif (state.typ == 'angle'): diff = (to.position - position) abs_angle = np.arccos((diff.dot((0, 1)) / np.linalg.norm(diff))) new_obs = (body.angle + abs_angle) else: raise NotImplementedError elif state.joint: joint = find_joint(self.world, state.joint) if (state.typ == 'apos'): new_obs = joint.angle elif (state.typ == 'avel'): new_obs = joint.speed else: raise NotImplementedError elif state.com: com_quant = self._compute_com_pos_vel(*state.com) if (state.typ == 'xpos'): new_obs = com_quant[0] elif (state.typ == 'ypos'): new_obs = com_quant[1] elif (state.typ == 'xvel'): new_obs = com_quant[2] elif (state.typ == 'yvel'): new_obs = com_quant[3] else: print(state.typ) raise NotImplementedError else: raise NotImplementedError if (state.transform is not None): if (state.transform == 'id'): pass elif (state.transform == 'sin'): new_obs = np.sin(new_obs) elif (state.transform == 'cos'): new_obs = np.cos(new_obs) else: raise NotImplementedError obs.append(new_obs) self._cached_obs = np.array(obs) return self._cached_obs def _compute_com_pos_vel(self, *com): com_key = ','.join(sorted(com)) if (com_key in self._cached_coms): return self._cached_coms[com_key] total_mass_quant = 0 total_mass = 0 for body_name in com: body = find_body(self.world, body_name) total_mass_quant += (body.mass * np.array((list(body.worldCenter) + list(body.linearVelocity)))) total_mass += body.mass com_quant = (total_mass_quant / total_mass) self._cached_coms[com_key] = com_quant return com_quant def get_com_position(self, *com): return self._compute_com_pos_vel(*com)[:2] def get_com_velocity(self, *com): return self._compute_com_pos_vel(*com)[2:] @overrides def render(self, states=None, actions=None, pause=False): if (not self.viewer): self.viewer = Box2DViewer(self.world) if (states or actions or pause): raise NotImplementedError if (not self.viewer): self.start_viewer() if self.viewer: self.viewer.loop_once() def before_world_step(self, action): pass def action_from_keys(self, keys): raise NotImplementedError
class PygameDraw(b2DrawExtended): '\n This debug draw class accepts callbacks from Box2D (which specifies what to\n draw) and handles all of the rendering.\n\n If you are writing your own game, you likely will not want to use debug\n drawing. Debug drawing, as its name implies, is for debugging.\n ' surface = None axisScale = 50.0 def __init__(self, test=None, **kwargs): b2DrawExtended.__init__(self, **kwargs) self.flipX = False self.flipY = True self.convertVertices = True self.test = test self.flags = dict(drawShapes=True, convertVertices=True) def StartDraw(self): self.zoom = self.test.viewZoom self.center = self.test.viewCenter self.offset = self.test.viewOffset self.screenSize = self.test.screenSize def EndDraw(self): pass def DrawPoint(self, p, size, color): '\n Draw a single point at point p given a pixel size and color.\n ' self.DrawCircle(p, (size / self.zoom), color, drawwidth=0) def DrawAABB(self, aabb, color): '\n Draw a wireframe around the AABB with the given color.\n ' 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) def DrawSegment(self, p1, p2, color): '\n Draw the line segment from p1-p2 with the specified color.\n ' pygame.draw.aaline(self.surface, color.bytes, p1, p2) def DrawTransform(self, xf): '\n Draw the transform xf on the screen\n ' 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) def DrawCircle(self, center, radius, color, drawwidth=1): '\n Draw a wireframe circle given the center, radius, axis of orientation\n and color.\n ' radius *= self.zoom if (radius < 1): radius = 1 else: radius = int(radius) pygame.draw.circle(self.surface, color.bytes, center, radius, drawwidth) def DrawSolidCircle(self, center, radius, axis, color): '\n Draw a solid circle given the center, radius, axis of orientation and\n color.\n ' 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, ((center[0] - (radius * axis[0])), (center[1] + (radius * axis[1])))) def DrawSolidCapsule(self, p1, p2, radius, color): pass def DrawPolygon(self, vertices, color): '\n Draw a wireframe polygon given the screen vertices with the specified\n color.\n ' 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) def DrawSolidPolygon(self, vertices, color): '\n Draw a filled polygon given the screen vertices with the specified\n color.\n ' 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)
class Box2DViewer(b2ContactListener): def __init__(self, world): super(Box2DViewer, self).__init__() self.world = world self.world.contactListener = self self._reset() pygame.init() caption = 'Box2D Simulator' pygame.display.set_caption(caption) self.screen = pygame.display.set_mode((800, 600)) self.screenSize = b2Vec2(*self.screen.get_size()) self.renderer = PygameDraw(surface=self.screen, test=self) self.world.renderer = self.renderer self.viewCenter = (0, 20.0) self._viewZoom = 100 def _reset(self): self._viewZoom = 10.0 self._viewCenter = None self._viewOffset = None self.screenSize = None self.rMouseDown = False self.textLine = 30 self.font = None def setCenter(self, value): '\n Updates the view offset based on the center of the screen.\n\n Tells the debug draw to update its values also.\n ' self._viewCenter = b2Vec2(*value) self._viewCenter *= self._viewZoom self._viewOffset = (self._viewCenter - (self.screenSize / 2)) def setZoom(self, zoom): self._viewZoom = zoom viewZoom = property((lambda self: self._viewZoom), setZoom, doc='Zoom factor for the display') viewCenter = property((lambda self: (self._viewCenter / self._viewZoom)), setCenter, doc='Screen center in camera coordinates') viewOffset = property((lambda self: self._viewOffset), doc='The offset of the top-left corner of the screen') def checkEvents(self): '\n Check for pygame events (mainly keyboard/mouse events).\n Passes the events onto the GUI also.\n ' 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_Event(event.key, down=False) elif (event.type == MOUSEBUTTONDOWN): if (event.button == 4): self.viewZoom *= 1.1 elif (event.button == 5): self.viewZoom /= 1.1 elif (event.type == MOUSEMOTION): if self.rMouseDown: self.viewCenter -= ((event.rel[0] / 5.0), ((- event.rel[1]) / 5.0)) return True def _Keyboard_Event(self, key, down=True): "\n Internal keyboard event, don't override this.\n\n Checks for the initial keydown of the basic testbed keys. Passes the\n unused ones onto the test via the Keyboard() function.\n " 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) def CheckKeys(self): "\n Check the keys that are evaluated on every main loop iteration.\n I.e., they aren't just evaluated when first pressed down\n " 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 -= (0, 0.5) if keys[pygame.K_HOME]: self.viewZoom = 1.0 self.viewCenter = (0.0, 20.0) def ConvertScreenToWorld(self, x, y): return b2Vec2(((x + self.viewOffset.x) / self.viewZoom), (((self.screenSize.y - y) + self.viewOffset.y) / self.viewZoom)) def loop_once(self): self.checkEvents() self.screen.fill((0, 0, 0)) if (self.renderer is not None): self.renderer.StartDraw() self.world.DrawDebugData() self.renderer.EndDraw() pygame.display.flip() def finish(self): pygame.quit()
class CarParkingEnv(Box2DEnv, Serializable): @autoargs.inherit(Box2DEnv.__init__) @autoargs.arg('random_start', type=bool, help='Randomized starting position by uniforming sampling starting car angleand position from a circle of radius 5') @autoargs.arg('random_start_range', type=float, help='Defaulted to 1. which means possible angles are 1. * 2*pi') def __init__(self, *args, **kwargs): Serializable.__init__(self, *args, **kwargs) self.random_start = kwargs.pop('random_start', True) self.random_start_range = kwargs.pop('random_start_range', 1.0) super(CarParkingEnv, self).__init__(self.model_path('car_parking.xml'), *args, **kwargs) self.goal = find_body(self.world, 'goal') self.car = find_body(self.world, 'car') self.wheels = [body for body in self.world.bodies if ('wheel' in _get_name(body))] self.front_wheels = [body for body in self.wheels if ('front' in _get_name(body))] self.max_deg = 30.0 self.goal_radius = 1.0 self.vel_thres = 0.1 self.start_radius = 5.0 @overrides def before_world_step(self, action): desired_angle = (self.car.angle + ((action[(- 1)] / 180) * np.pi)) for wheel in self.front_wheels: wheel.angle = desired_angle wheel.angularVelocity = 0 for wheel in self.wheels: ortho = wheel.GetWorldVector((1, 0)) lateral_speed = (wheel.linearVelocity.dot(ortho) * ortho) impulse = (wheel.mass * (- lateral_speed)) wheel.ApplyLinearImpulse(impulse, wheel.worldCenter, True) mag = wheel.linearVelocity.dot(wheel.linearVelocity) if (mag != 0): wheel.ApplyLinearImpulse((((0.1 * wheel.mass) * (- wheel.linearVelocity)) / (mag ** 0.5)), wheel.worldCenter, True) @property @overrides def action_dim(self): return (super(CarParkingEnv, self).action_dim + 1) @property @overrides def action_bounds(self): (lb, ub) = super(CarParkingEnv, self).action_bounds return (np.append(lb, (- self.max_deg)), np.append(ub, self.max_deg)) @overrides def reset(self): self._set_state(self.initial_state) self._invalidate_state_caches() if self.random_start: (pos_angle, car_angle) = (((np.random.rand(2) * np.pi) * 2) * self.random_start_range) dis = ((self.start_radius * np.cos(pos_angle)), (self.start_radius * np.sin(pos_angle))) for body in ([self.car] + self.wheels): body.angle = car_angle for wheel in self.wheels: wheel.position = ((wheel.position - self.car.position) + dis) self.car.position = dis self.world.Step(self.extra_data.timeStep, self.extra_data.velocityIterations, self.extra_data.positionIterations) return self.get_current_obs() @overrides def compute_reward(self, action): (yield) not_done = (not self.is_current_done()) dist_to_goal = self.get_current_obs()[(- 3)] (yield (((- 1) * not_done) - (2 * dist_to_goal))) @overrides def is_current_done(self): pos_satified = (np.linalg.norm(self.car.position) <= self.goal_radius) vel_satisfied = (np.linalg.norm(self.car.linearVelocity) <= self.vel_thres) return (pos_satified and vel_satisfied) @overrides def action_from_keys(self, keys): go = np.zeros(self.action_dim) if keys[pygame.K_LEFT]: go[(- 1)] = self.max_deg if keys[pygame.K_RIGHT]: go[(- 1)] = (- self.max_deg) if keys[pygame.K_UP]: go[0] = 10 if keys[pygame.K_DOWN]: go[0] = (- 10) return go
class CartpoleEnv(Box2DEnv, Serializable): @autoargs.inherit(Box2DEnv.__init__) def __init__(self, *args, **kwargs): self.max_pole_angle = 0.2 self.max_cart_pos = 2.4 self.max_cart_speed = 4.0 self.max_pole_speed = 4.0 self.reset_range = 0.05 super(CartpoleEnv, self).__init__(self.model_path('cartpole.xml.mako'), *args, **kwargs) self.cart = find_body(self.world, 'cart') self.pole = find_body(self.world, 'pole') Serializable.__init__(self, *args, **kwargs) @overrides def reset(self, reset_args=None): self._set_state(self.initial_state) self._invalidate_state_caches() bounds = np.array([self.max_cart_pos, self.max_cart_speed, self.max_pole_angle, self.max_pole_speed]) (low, high) = (((- self.reset_range) * bounds), (self.reset_range * bounds)) (xpos, xvel, apos, avel) = np.random.uniform(low, high) self.cart.position = (xpos, self.cart.position[1]) self.cart.linearVelocity = (xvel, self.cart.linearVelocity[1]) self.pole.angle = apos self.pole.angularVelocity = avel return self.get_current_obs() @overrides def compute_reward(self, action): (yield) notdone = (1 - int(self.is_current_done())) ucost = (1e-05 * (action ** 2).sum()) xcost = (1 - np.cos(self.pole.angle)) (yield (((notdone * 10) - (notdone * xcost)) - (notdone * ucost))) @overrides def is_current_done(self): return ((abs(self.cart.position[0]) > self.max_cart_pos) or (abs(self.pole.angle) > self.max_pole_angle))
class CartpoleSwingupEnv(Box2DEnv, Serializable): @autoargs.inherit(Box2DEnv.__init__) def __init__(self, *args, **kwargs): super(CartpoleSwingupEnv, self).__init__(self.model_path('cartpole.xml.mako'), *args, **kwargs) self.max_cart_pos = 3 self.max_reward_cart_pos = 3 self.cart = find_body(self.world, 'cart') self.pole = find_body(self.world, 'pole') Serializable.__init__(self, *args, **kwargs) @overrides def reset(self): self._set_state(self.initial_state) self._invalidate_state_caches() bounds = np.array([[(- 1), (- 2), (np.pi - 1), (- 3)], [1, 2, (np.pi + 1), 3]]) (low, high) = bounds (xpos, xvel, apos, avel) = np.random.uniform(low, high) self.cart.position = (xpos, self.cart.position[1]) self.cart.linearVelocity = (xvel, self.cart.linearVelocity[1]) self.pole.angle = apos self.pole.angularVelocity = avel return self.get_current_obs() @overrides def compute_reward(self, action): (yield) if self.is_current_done(): (yield (- 100)) elif (abs(self.cart.position[0]) > self.max_reward_cart_pos): (yield (- 1)) else: (yield np.cos(self.pole.angle)) @overrides def is_current_done(self): return (abs(self.cart.position[0]) > self.max_cart_pos) @overrides def action_from_keys(self, keys): if keys[pygame.K_LEFT]: return np.asarray([(- 10)]) elif keys[pygame.K_RIGHT]: return np.asarray([(+ 10)]) else: return np.asarray([0])
class DoublePendulumEnv(Box2DEnv, Serializable): @autoargs.inherit(Box2DEnv.__init__) def __init__(self, *args, **kwargs): kwargs['frame_skip'] = kwargs.get('frame_skip', 2) if kwargs.get('template_args', {}).get('noise', False): self.link_len = ((np.random.rand() - 0.5) + 1) else: self.link_len = 1 kwargs['template_args'] = kwargs.get('template_args', {}) kwargs['template_args']['link_len'] = self.link_len super(DoublePendulumEnv, self).__init__(self.model_path('double_pendulum.xml.mako'), *args, **kwargs) self.link1 = find_body(self.world, 'link1') self.link2 = find_body(self.world, 'link2') Serializable.__init__(self, *args, **kwargs) @overrides def reset(self): self._set_state(self.initial_state) self._invalidate_state_caches() stds = np.array([0.1, 0.1, 0.01, 0.01]) (pos1, pos2, v1, v2) = (np.random.randn(*stds.shape) * stds) self.link1.angle = pos1 self.link2.angle = pos2 self.link1.angularVelocity = v1 self.link2.angularVelocity = v2 return self.get_current_obs() def get_tip_pos(self): cur_center_pos = self.link2.position cur_angle = self.link2.angle cur_pos = ((cur_center_pos[0] - (self.link_len * np.sin(cur_angle))), (cur_center_pos[1] - (self.link_len * np.cos(cur_angle)))) return cur_pos @overrides def compute_reward(self, action): (yield) tgt_pos = np.asarray([0, (self.link_len * 2)]) cur_pos = self.get_tip_pos() dist = np.linalg.norm((cur_pos - tgt_pos)) (yield (- dist)) def is_current_done(self): return False
class MountainCarEnv(Box2DEnv, Serializable): @autoargs.inherit(Box2DEnv.__init__) @autoargs.arg('height_bonus_coeff', type=float, help="Height bonus added to each step's reward") @autoargs.arg('goal_cart_pos', type=float, help='Goal horizontal position') def __init__(self, height_bonus=1.0, goal_cart_pos=0.6, *args, **kwargs): super(MountainCarEnv, self).__init__(self.model_path('mountain_car.xml.mako'), *args, **kwargs) self.max_cart_pos = 2 self.goal_cart_pos = goal_cart_pos self.height_bonus = height_bonus self.cart = find_body(self.world, 'cart') Serializable.quick_init(self, locals()) @overrides def compute_reward(self, action): (yield) (yield ((- 1) + (self.height_bonus * self.cart.position[1]))) @overrides def is_current_done(self): return ((self.cart.position[0] >= self.goal_cart_pos) or (abs(self.cart.position[0]) >= self.max_cart_pos)) @overrides def reset(self): self._set_state(self.initial_state) self._invalidate_state_caches() bounds = np.array([[(- 1)], [1]]) (low, high) = bounds xvel = np.random.uniform(low, high) self.cart.linearVelocity = (xvel, self.cart.linearVelocity[1]) return self.get_current_obs() @overrides def action_from_keys(self, keys): if keys[pygame.K_LEFT]: return np.asarray([(- 1)]) elif keys[pygame.K_RIGHT]: return np.asarray([(+ 1)]) else: return np.asarray([0])
class Type(object): def __eq__(self, other): return (self.__class__ == other.__class__) def from_str(self, s): raise NotImplementedError
class Float(Type): def from_str(self, s): return float(s)
class Int(Type): def from_str(self, s): return int(s)
class Hex(Type): def from_str(self, s): assert (s.startswith('0x') or s.startswith('0X')) return int(s, 16)
class Choice(Type): def __init__(self, *options): self._options = options def from_str(self, s): if (s in self._options): return s raise ValueError(('Unexpected value %s: must be one of %s' % (s, ', '.join(self._options))))
class List(Type): def __init__(self, elem_type): self.elem_type = elem_type def __eq__(self, other): return ((self.__class__ == other.__class__) and (self.elem_type == other.elem_type)) def from_str(self, s): if (';' in s): segments = s.split(';') elif (',' in s): segments = s.split(',') else: segments = s.split(' ') return list(map(self.elem_type.from_str, segments))
class Tuple(Type): def __init__(self, *elem_types): self.elem_types = elem_types def __eq__(self, other): return ((self.__class__ == other.__class__) and (self.elem_types == other.elem_types)) def from_str(self, s): if (';' in s): segments = s.split(';') elif (',' in s): segments = s.split(',') else: segments = s.split(' ') if (len(segments) != len(self.elem_types)): raise ValueError(('Length mismatch: expected a tuple of length %d; got %s instead' % (len(self.elem_types), s))) return tuple([typ.from_str(seg) for (typ, seg) in zip(self.elem_types, segments)])
class Either(Type): def __init__(self, *elem_types): self.elem_types = elem_types def from_str(self, s): for typ in self.elem_types: try: return typ.from_str(s) except ValueError: pass raise ValueError('No match found')
class String(Type): def from_str(self, s): return s
class Angle(Type): def from_str(self, s): if s.endswith('deg'): return ((float(s[:(- len('deg'))]) * np.pi) / 180.0) elif s.endswith('rad'): return float(s[:(- len('rad'))]) return ((float(s) * np.pi) / 180.0)
class Bool(Type): def from_str(self, s): return ((s.lower() == 'true') or (s.lower() == '1'))
class XmlBox2D(XmlElem): tag = 'box2d' class Meta(): world = XmlChild('world', (lambda : XmlWorld), required=True) def __init__(self): self.world = None def to_box2d(self, extra_data, world=None): return self.world.to_box2d(extra_data, world=world)
class XmlWorld(XmlElem): tag = 'world' class Meta(): bodies = XmlChildren('body', (lambda : XmlBody)) gravity = XmlAttr('gravity', Point2D()) joints = XmlChildren('joint', (lambda : XmlJoint)) states = XmlChildren('state', (lambda : XmlState)) controls = XmlChildren('control', (lambda : XmlControl)) warmStarting = XmlAttr('warmstart', Bool()) continuousPhysics = XmlAttr('continuous', Bool()) subStepping = XmlAttr('substepping', Bool()) velocityIterations = XmlAttr('velitr', Int()) positionIterations = XmlAttr('positr', Int()) timeStep = XmlAttr('timestep', Float()) def __init__(self): self.bodies = [] self.gravity = None self.joints = [] self.states = [] self.controls = [] self.warmStarting = True self.continuousPhysics = True self.subStepping = False self.velocityIterations = 8 self.positionIterations = 3 self.timeStep = 0.02 def to_box2d(self, extra_data, world=None): if (world is None): world = Box2D.b2World(allow_sleeping=False) world.warmStarting = self.warmStarting world.continuousPhysics = self.continuousPhysics world.subStepping = self.subStepping extra_data.velocityIterations = self.velocityIterations extra_data.positionIterations = self.positionIterations extra_data.timeStep = self.timeStep if self.gravity: world.gravity = self.gravity for body in self.bodies: body.to_box2d(world, self, extra_data) for joint in self.joints: joint.to_box2d(world, self, extra_data) for state in self.states: state.to_box2d(world, self, extra_data) for control in self.controls: control.to_box2d(world, self, extra_data) return world
class XmlBody(XmlElem): tag = 'body' TYPES = ['static', 'kinematic', 'dynamic'] class Meta(): color = XmlAttr('color', List(Float())) name = XmlAttr('name', String()) typ = XmlAttr('type', Choice('static', 'kinematic', 'dynamic'), required=True) fixtures = XmlChildren('fixture', (lambda : XmlFixture)) position = XmlAttr('position', Point2D()) def __init__(self): self.color = None self.name = None self.typ = None self.position = None self.fixtures = [] def to_box2d(self, world, xml_world, extra_data): body = world.CreateBody(type=self.TYPES.index(self.typ)) body.userData = dict(name=self.name, color=self.color) if self.position: body.position = self.position for fixture in self.fixtures: fixture.to_box2d(body, self, extra_data) return body
class XmlFixture(XmlElem): tag = 'fixture' class Meta(): shape = XmlAttr('shape', Choice('polygon', 'circle', 'edge', 'sine_chain'), required=True) vertices = XmlAttr('vertices', List(Point2D())) box = XmlAttr('box', Either(Point2D(), Tuple(Float(), Float(), Point2D(), Angle()))) radius = XmlAttr('radius', Float()) width = XmlAttr('width', Float()) height = XmlAttr('height', Float()) center = XmlAttr('center', Point2D()) angle = XmlAttr('angle', Angle()) position = XmlAttr('position', Point2D()) friction = XmlAttr('friction', Float()) density = XmlAttr('density', Float()) category_bits = XmlAttr('category_bits', Hex()) mask_bits = XmlAttr('mask_bits', Hex()) group = XmlAttr('group', Int()) def __init__(self): self.shape = None self.vertices = None self.box = None self.friction = None self.density = None self.category_bits = None self.mask_bits = None self.group = None self.radius = None self.width = None self.height = None self.center = None self.angle = None def to_box2d(self, body, xml_body, extra_data): attrs = dict() if self.friction: attrs['friction'] = self.friction if self.density: attrs['density'] = self.density if self.group: attrs['groupIndex'] = self.group if self.radius: attrs['radius'] = self.radius if (self.shape == 'polygon'): if self.box: fixture = body.CreatePolygonFixture(box=self.box, **attrs) else: fixture = body.CreatePolygonFixture(vertices=self.vertices, **attrs) elif (self.shape == 'edge'): fixture = body.CreateEdgeFixture(vertices=self.vertices, **attrs) elif (self.shape == 'circle'): if self.center: attrs['pos'] = self.center fixture = body.CreateCircleFixture(**attrs) elif (self.shape == 'sine_chain'): if self.center: attrs['pos'] = self.center m = 100 vs = [((((0.5 / m) * i) * self.width), (self.height * np.sin(((((1.0 / m) * i) - 0.5) * np.pi)))) for i in range((- m), (m + 1))] attrs['vertices_chain'] = vs fixture = body.CreateChainFixture(**attrs) else: assert False return fixture
def _get_name(x): if isinstance(x.userData, dict): return x.userData.get('name') return None
def find_body(world, name): return [body for body in world.bodies if (_get_name(body) == name)][0]
def find_joint(world, name): return [joint for joint in world.joints if (_get_name(joint) == name)][0]
class XmlJoint(XmlElem): tag = 'joint' JOINT_TYPES = {'revolute': Box2D.b2RevoluteJoint, 'friction': Box2D.b2FrictionJoint, 'prismatic': Box2D.b2PrismaticJoint} class Meta(): bodyA = XmlAttr('bodyA', String(), required=True) bodyB = XmlAttr('bodyB', String(), required=True) anchor = XmlAttr('anchor', Tuple(Float(), Float())) localAnchorA = XmlAttr('localAnchorA', Tuple(Float(), Float())) localAnchorB = XmlAttr('localAnchorB', Tuple(Float(), Float())) axis = XmlAttr('axis', Tuple(Float(), Float())) limit = XmlAttr('limit', Tuple(Angle(), Angle())) ctrllimit = XmlAttr('ctrllimit', Tuple(Angle(), Angle())) typ = XmlAttr('type', Choice('revolute', 'friction', 'prismatic'), required=True) name = XmlAttr('name', String()) motor = XmlAttr('motor', Bool()) def __init__(self): self.bodyA = None self.bodyB = None self.anchor = None self.localAnchorA = None self.localAnchorB = None self.limit = None self.ctrllimit = None self.motor = False self.typ = None self.name = None self.axis = None def to_box2d(self, world, xml_world, extra_data): bodyA = find_body(world, self.bodyA) bodyB = find_body(world, self.bodyB) args = dict() if (self.typ == 'revolute'): if self.localAnchorA: args['localAnchorA'] = self.localAnchorA if self.localAnchorB: args['localAnchorB'] = self.localAnchorB if self.anchor: args['anchor'] = self.anchor if self.limit: args['enableLimit'] = True args['lowerAngle'] = self.limit[0] args['upperAngle'] = self.limit[1] elif (self.typ == 'friction'): if self.anchor: args['anchor'] = self.anchor elif (self.typ == 'prismatic'): if self.axis: args['axis'] = self.axis else: raise NotImplementedError userData = dict(ctrllimit=self.ctrllimit, motor=self.motor, name=self.name) joint = world.CreateJoint(type=self.JOINT_TYPES[self.typ], bodyA=bodyA, bodyB=bodyB, **args) joint.userData = userData return joint
class XmlState(XmlElem): tag = 'state' class Meta(): typ = XmlAttr('type', Choice('xpos', 'ypos', 'xvel', 'yvel', 'apos', 'avel', 'dist', 'angle')) transform = XmlAttr('transform', Choice('id', 'sin', 'cos')) body = XmlAttr('body', String()) to = XmlAttr('to', String()) joint = XmlAttr('joint', String()) local = XmlAttr('local', Point2D()) com = XmlAttr('com', List(String())) def __init__(self): self.typ = None self.transform = None self.body = None self.joint = None self.local = None self.com = None self.to = None def to_box2d(self, world, xml_world, extra_data): extra_data.states.append(self)
class XmlControl(XmlElem): tag = 'control' class Meta(): typ = XmlAttr('type', Choice('force', 'torque'), required=True) body = XmlAttr('body', String(), help='name of the body to apply force on') bodies = XmlAttr('bodies', List(String()), help='names of the bodies to apply force on') joint = XmlAttr('joint', String(), help='name of the joint') anchor = XmlAttr('anchor', Point2D(), help='location of the force in local coordinate frame') direction = XmlAttr('direction', Point2D(), help='direction of the force in local coordinate frame') ctrllimit = XmlAttr('ctrllimit', Tuple(Float(), Float()), help='limit of the control input in Newton') def __init__(self): self.typ = None self.body = None self.bodies = None self.joint = None self.anchor = None self.direction = None self.ctrllimit = None def to_box2d(self, world, xml_world, extra_data): if (self.body != None): assert (self.bodies is None), 'Should not set body and bodies at the same time' self.bodies = [self.body] extra_data.controls.append(self)
class ExtraData(object): def __init__(self): self.states = [] self.controls = [] self.velocityIterations = None self.positionIterations = None self.timeStep = None
def world_from_xml(s): extra_data = ExtraData() box2d = XmlBox2D.from_xml(ET.fromstring(s)) world = box2d.to_box2d(extra_data) return (world, extra_data)
def _extract_type(typ): if isinstance(typ, LambdaType): return typ() else: return typ
class AttrDecl(object): pass
class XmlChildren(AttrDecl): def __init__(self, tag, typ): self._tag = tag self._typ = typ def from_xml(self, xml): xml_elems = [child for child in xml if (child.tag == self._tag)] typ = _extract_type(self._typ) return [typ.from_xml(elem) for elem in xml_elems]
class XmlChild(AttrDecl): def __init__(self, tag, typ, required=False): self._tag = tag self._typ = typ self._required = required def from_xml(self, xml): xml_elems = [child for child in xml if (child.tag == self._tag)] if (len(xml_elems) > 1): raise ValueError(('Multiple candidate found for tag %s' % self._tag)) if (len(xml_elems) == 0): if self._required: raise ValueError(('Missing xml element with tag %s' % self._tag)) else: return None elem = xml_elems[0] return _extract_type(self._typ).from_xml(elem)
class XmlAttr(AttrDecl): def __init__(self, name, typ, required=False, *args, **kwargs): self._name = name self._typ = typ self._required = required @property def name(self): return self._name def from_xml(self, xml): if (self._name in xml.attrib): return _extract_type(self._typ).from_str(xml.attrib[self._name]) elif self._required: raise ValueError(('Missing required attribute %s' % self._name)) else: return None
class XmlElem(object): tag = None Meta = None @classmethod def from_xml(cls, xml): if (cls.tag != xml.tag): raise ValueError(('Tag mismatch: expected %s but got %s' % (cls.tag, xml.tag))) attrs = cls.get_attrs() inst = cls() used_attrs = [] for (name, attr) in attrs: val = attr.from_xml(xml) if isinstance(attr, XmlAttr): used_attrs.append(attr.name) if (val is not None): setattr(inst, name, val) for attr in list(xml.attrib.keys()): if (attr not in used_attrs): raise ValueError(('Unrecognized attribute: %s' % attr)) return inst @classmethod def get_attrs(cls): if (not hasattr(cls, '_attrs')): all_attrs = dir(cls.Meta) attrs = [(attr, getattr(cls.Meta, attr)) for attr in all_attrs if isinstance(getattr(cls.Meta, attr), AttrDecl)] cls._attrs = attrs return cls._attrs def __str__(self): attrs = [] for (name, _) in self.__class__.get_attrs(): attrs.append(('%s=%s' % (name, str(getattr(self, name))))) return (((self.__class__.__name__ + '(') + ', '.join(attrs)) + ')') def __repr__(self): return str(self)
class EnvSpec(Serializable): def __init__(self, observation_space, action_space): '\n :type observation_space: Space\n :type action_space: Space\n ' Serializable.quick_init(self, locals()) self._observation_space = observation_space self._action_space = action_space @property def observation_space(self): return self._observation_space @property def action_space(self): return self._action_space
def convert_gym_space(space): if isinstance(space, gym.spaces.Box): return Box(low=space.low, high=space.high) elif isinstance(space, gym.spaces.Discrete): return Discrete(n=space.n) elif isinstance(space, gym.spaces.Tuple): return Product([convert_gym_space(x) for x in space.spaces]) else: raise NotImplementedError
class CappedCubicVideoSchedule(object): def __call__(self, count): return monitor_manager.capped_cubic_video_schedule(count)
class FixedIntervalVideoSchedule(object): def __init__(self, interval): self.interval = interval def __call__(self, count): return ((count % self.interval) == 0)
class NoVideoSchedule(object): def __call__(self, count): return False
class GymEnv(Env, Serializable): def __init__(self, env_name, record_video=True, video_schedule=None, log_dir=None, record_log=True, force_reset=False): if (log_dir is None): if (logger.get_snapshot_dir() is None): logger.log('Warning: skipping Gym environment monitoring since snapshot_dir not configured.') else: log_dir = os.path.join(logger.get_snapshot_dir(), 'gym_log') Serializable.quick_init(self, locals()) env = gym.envs.make(env_name) self.env = env self.env_id = env.spec.id monitor_manager.logger.setLevel(logging.WARNING) assert (not ((not record_log) and record_video)) if ((log_dir is None) or (record_log is False)): self.monitoring = False else: if (not record_video): video_schedule = NoVideoSchedule() elif (video_schedule is None): video_schedule = CappedCubicVideoSchedule() self.env = gym.wrappers.Monitor(self.env, log_dir, video_callable=video_schedule, force=True) self.monitoring = True self._observation_space = convert_gym_space(env.observation_space) self._action_space = convert_gym_space(env.action_space) self._horizon = env.spec.timestep_limit self._log_dir = log_dir self._force_reset = force_reset @property def observation_space(self): return self._observation_space @property def action_space(self): return self._action_space @property def horizon(self): return self._horizon def reset(self, **kwargs): if (self._force_reset and self.monitoring): recorder = self.env._monitor.stats_recorder if (recorder is not None): recorder.done = True return self.env.reset() def step(self, action): (next_obs, reward, done, info) = self.env.step(action) return Step(next_obs, reward, done, **info) def render(self): self.env.render() def terminate(self): if self.monitoring: self.env._close() if (self._log_dir is not None): print(('\n ***************************\n\n Training finished! You can upload results to OpenAI Gym by running the following command:\n\n python scripts/submit_gym.py %s\n\n ***************************\n ' % self._log_dir))
class IdentificationEnv(ProxyEnv, Serializable): def __init__(self, mdp_cls, mdp_args): Serializable.quick_init(self, locals()) self.mdp_cls = mdp_cls self.mdp_args = dict(mdp_args) self.mdp_args['template_args'] = dict(noise=True) mdp = self.gen_mdp() super(IdentificationEnv, self).__init__(mdp) def gen_mdp(self): return self.mdp_cls(**self.mdp_args) @overrides def reset(self): if getattr(self, '_mdp', None): if hasattr(self._wrapped_env, 'release'): self._wrapped_env.release() self._wrapped_env = self.gen_mdp() return super(IdentificationEnv, self).reset()
class NoisyObservationEnv(ProxyEnv, Serializable): @autoargs.arg('obs_noise', type=float, help='Noise added to the observations (note: this makes the problem non-Markovian!)') def __init__(self, env, obs_noise=0.1): super(NoisyObservationEnv, self).__init__(env) Serializable.quick_init(self, locals()) self.obs_noise = obs_noise def get_obs_noise_scale_factor(self, obs): return np.ones_like(obs) def inject_obs_noise(self, obs): '\n Inject entry-wise noise to the observation. This should not change\n the dimension of the observation.\n ' noise = ((self.get_obs_noise_scale_factor(obs) * self.obs_noise) * np.random.normal(size=obs.shape)) return (obs + noise) def get_current_obs(self): return self.inject_obs_noise(self._wrapped_env.get_current_obs()) @overrides def reset(self): obs = self._wrapped_env.reset() return self.inject_obs_noise(obs) @overrides def step(self, action): (next_obs, reward, done, info) = self._wrapped_env.step(action) return Step(self.inject_obs_noise(next_obs), reward, done, **info)
class DelayedActionEnv(ProxyEnv, Serializable): @autoargs.arg('action_delay', type=int, help='Time steps before action is realized') def __init__(self, env, action_delay=3): assert (action_delay > 0), 'Should not use this env transformer' super(DelayedActionEnv, self).__init__(env) Serializable.quick_init(self, locals()) self.action_delay = action_delay self._queued_actions = None @overrides def reset(self): obs = self._wrapped_env.reset() self._queued_actions = np.zeros((self.action_delay * self.action_dim)) return obs @overrides def step(self, action): queued_action = self._queued_actions[:self.action_dim] (next_obs, reward, done, info) = self._wrapped_env.step(queued_action) self._queued_actions = np.concatenate([self._queued_actions[self.action_dim:], action]) return Step(next_obs, reward, done, **info)
class NormalizedEnv(ProxyEnv, Serializable): def __init__(self, env, scale_reward=1.0, normalize_obs=False, normalize_reward=False, obs_alpha=0.001, reward_alpha=0.001): ProxyEnv.__init__(self, env) Serializable.quick_init(self, locals()) self._scale_reward = scale_reward self._normalize_obs = normalize_obs self._normalize_reward = normalize_reward self._obs_alpha = obs_alpha self._obs_mean = np.zeros(env.observation_space.flat_dim) self._obs_var = np.ones(env.observation_space.flat_dim) self._reward_alpha = reward_alpha self._reward_mean = 0.0 self._reward_var = 1.0 def _update_obs_estimate(self, obs): flat_obs = self.wrapped_env.observation_space.flatten(obs) self._obs_mean = (((1 - self._obs_alpha) * self._obs_mean) + (self._obs_alpha * flat_obs)) self._obs_var = (((1 - self._obs_alpha) * self._obs_var) + (self._obs_alpha * np.square((flat_obs - self._obs_mean)))) def _update_reward_estimate(self, reward): self._reward_mean = (((1 - self._reward_alpha) * self._reward_mean) + (self._reward_alpha * reward)) self._reward_var = (((1 - self._reward_alpha) * self._reward_var) + (self._reward_alpha * np.square((reward - self._reward_mean)))) def _apply_normalize_obs(self, obs): self._update_obs_estimate(obs) return ((obs - self._obs_mean) / (np.sqrt(self._obs_var) + 1e-08)) def _apply_normalize_reward(self, reward): self._update_reward_estimate(reward) return (reward / (np.sqrt(self._reward_var) + 1e-08)) def reset(self, reset_args=None): ret = self._wrapped_env.reset(reset_args=reset_args) if self._normalize_obs: return self._apply_normalize_obs(ret) else: return ret def __getstate__(self): d = Serializable.__getstate__(self) d['_obs_mean'] = self._obs_mean d['_obs_var'] = self._obs_var return d def __setstate__(self, d): Serializable.__setstate__(self, d) self._obs_mean = d['_obs_mean'] self._obs_var = d['_obs_var'] @property @overrides def action_space(self): if isinstance(self._wrapped_env.action_space, Box): ub = np.ones(self._wrapped_env.action_space.shape) return spaces.Box(((- 1) * ub), ub) return self._wrapped_env.action_space @overrides def step(self, action): if isinstance(self._wrapped_env.action_space, Box): (lb, ub) = self._wrapped_env.action_space.bounds scaled_action = (lb + (((action + 1.0) * 0.5) * (ub - lb))) scaled_action = np.clip(scaled_action, lb, ub) else: scaled_action = action wrapped_step = self._wrapped_env.step(scaled_action) (next_obs, reward, done, info) = wrapped_step if self._normalize_obs: next_obs = self._apply_normalize_obs(next_obs) if self._normalize_reward: reward = self._apply_normalize_reward(reward) return Step(next_obs, (reward * self._scale_reward), done, **info) def __str__(self): return ('Normalized: %s' % self._wrapped_env)
class ProxyEnv(Env): def __init__(self, wrapped_env): self._wrapped_env = wrapped_env @property def wrapped_env(self): return self._wrapped_env def reset(self, *args, **kwargs): return self._wrapped_env.reset(*args, **kwargs) @property def action_space(self): return self._wrapped_env.action_space @property def observation_space(self): return self._wrapped_env.observation_space def step(self, action): return self._wrapped_env.step(action) def render(self, *args, **kwargs): return self._wrapped_env.render(*args, **kwargs) def log_diagnostics(self, paths, prefix=''): self._wrapped_env.log_diagnostics(paths, prefix=prefix) @property def horizon(self): return self._wrapped_env.horizon def terminate(self): self._wrapped_env.terminate() def get_param_values(self): return self._wrapped_env.get_param_values() def set_param_values(self, params): self._wrapped_env.set_param_values(params)
class SlidingMemEnv(ProxyEnv, Serializable): def __init__(self, env, n_steps=4, axis=0): super().__init__(env) Serializable.quick_init(self, locals()) self.n_steps = n_steps self.axis = axis self.buffer = None def reset_buffer(self, new_): assert (self.axis == 0) self.buffer = np.zeros(self.observation_space.shape, dtype=np.float32) self.buffer[0:] = new_ def add_to_buffer(self, new_): assert (self.axis == 0) self.buffer[1:] = self.buffer[:(- 1)] self.buffer[:1] = new_ @property def observation_space(self): origin = self._wrapped_env.observation_space return Box(*[np.repeat(b, self.n_steps, axis=self.axis) for b in origin.bounds]) @overrides def reset(self): obs = self._wrapped_env.reset() self.reset_buffer(obs) return self.buffer @overrides def step(self, action): (next_obs, reward, done, info) = self._wrapped_env.step(action) self.add_to_buffer(next_obs) return Step(self.buffer, reward, done, **info)
class ExplorationStrategy(object): def get_action(self, t, observation, policy, **kwargs): raise NotImplementedError def reset(self): pass
class GaussianStrategy(ExplorationStrategy, Serializable): '\n This strategy adds Gaussian noise to the action taken by the deterministic policy.\n ' def __init__(self, env_spec, max_sigma=1.0, min_sigma=0.1, decay_period=1000000): assert isinstance(env_spec.action_space, Box) assert (len(env_spec.action_space.shape) == 1) Serializable.quick_init(self, locals()) self._max_sigma = max_sigma self._min_sigma = min_sigma self._decay_period = decay_period self._action_space = env_spec.action_space def get_action(self, t, observation, policy, **kwargs): (action, agent_info) = policy.get_action(observation) sigma = (self._max_sigma - ((self._max_sigma - self._min_sigma) * min(1.0, ((t * 1.0) / self._decay_period)))) return np.clip((action + (np.random.normal(size=len(action)) * sigma)), self._action_space.low, self._action_space.high)
class OUStrategy(ExplorationStrategy, Serializable): '\n This strategy implements the Ornstein-Uhlenbeck process, which adds\n time-correlated noise to the actions taken by the deterministic policy.\n The OU process satisfies the following stochastic differential equation:\n dxt = theta*(mu - xt)*dt + sigma*dWt\n where Wt denotes the Wiener process\n ' def __init__(self, env_spec, mu=0, theta=0.15, sigma=0.3, **kwargs): assert isinstance(env_spec.action_space, Box) assert (len(env_spec.action_space.shape) == 1) Serializable.quick_init(self, locals()) self.mu = mu self.theta = theta self.sigma = sigma self.action_space = env_spec.action_space self.state = (np.ones(self.action_space.flat_dim) * self.mu) self.reset() def __getstate__(self): d = Serializable.__getstate__(self) d['state'] = self.state return d def __setstate__(self, d): Serializable.__setstate__(self, d) self.state = d['state'] @overrides def reset(self): self.state = (np.ones(self.action_space.flat_dim) * self.mu) def evolve_state(self): x = self.state dx = ((self.theta * (self.mu - x)) + (self.sigma * nr.randn(len(x)))) self.state = (x + dx) return self.state @overrides def get_action(self, t, observation, policy, **kwargs): (action, _) = policy.get_action(observation) ou_state = self.evolve_state() return np.clip((action + ou_state), self.action_space.low, self.action_space.high)
def arg(name, type=None, help=None, nargs=None, mapper=None, choices=None, prefix=True): def wrap(fn): assert (fn.__name__ == '__init__') if (not hasattr(fn, '_autoargs_info')): fn._autoargs_info = dict() fn._autoargs_info[name] = dict(type=type, help=help, nargs=nargs, choices=choices, mapper=mapper) return fn return wrap
def prefix(prefix_): def wrap(fn): assert (fn.__name__ == '__init__') fn._autoargs_prefix = prefix_ return fn return wrap
def _get_prefix(cls): from rllab.mdp.base import MDP from rllab.policies.base import Policy from rllab.baselines.base import Baseline from rllab.algos.base import Algorithm if hasattr(cls.__init__, '_autoargs_prefix'): return cls.__init__._autoargs_prefix elif issubclass(cls, MDP): return 'mdp_' elif issubclass(cls, Algorithm): return 'algo_' elif issubclass(cls, Baseline): return 'baseline_' elif issubclass(cls, Policy): return 'policy_' else: return ''
def _get_info(cls_or_fn): if isinstance(cls_or_fn, type): if hasattr(cls_or_fn.__init__, '_autoargs_info'): return cls_or_fn.__init__._autoargs_info return {} else: if hasattr(cls_or_fn, '_autoargs_info'): return cls_or_fn._autoargs_info return {}
def _t_or_f(s): ua = str(s).upper() if (ua == 'TRUE'[:len(ua)]): return True elif (ua == 'FALSE'[:len(ua)]): return False else: raise ValueError(('Unrecognized boolean value: %s' % s))
def add_args(_): def _add_args(cls, parser): args_info = _get_info(cls) prefix_ = _get_prefix(cls) for (arg_name, arg_info) in args_info.items(): type = arg_info['type'] if (type == bool): type = _t_or_f parser.add_argument((('--' + prefix_) + arg_name), help=arg_info['help'], choices=arg_info['choices'], type=type, nargs=arg_info['nargs']) return _add_args
def new_from_args(_): def _new_from_args(cls, parsed_args, *args, **params): silent = params.pop('_silent', False) args_info = _get_info(cls) prefix_ = _get_prefix(cls) for (arg_name, arg_info) in args_info.items(): prefixed_arg_name = (prefix_ + arg_name) if hasattr(parsed_args, prefixed_arg_name): val = getattr(parsed_args, prefixed_arg_name) if (val is not None): if arg_info['mapper']: params[arg_name] = arg_info['mapper'](val) else: params[arg_name] = val if (not silent): print(colorize(('using argument %s with value %s' % (arg_name, val)), 'yellow')) return cls(*args, **params) return _new_from_args
def inherit(base_func): assert (base_func.__name__ == '__init__') def wrap(func): assert (func.__name__ == '__init__') func._autoargs_info = dict(_get_info(base_func), **_get_info(func)) return func return wrap
def get_all_parameters(cls, parsed_args): prefix = _get_prefix(cls) if ((prefix is None) or (len(prefix) == 0)): raise ValueError('Cannot retrieve parameters without prefix') info = _get_info(cls) if inspect.ismethod(cls.__init__): spec = inspect.getargspec(cls.__init__) if (spec.defaults is None): arg_defaults = {} else: arg_defaults = dict(list(zip(spec.args[::(- 1)], spec.defaults[::(- 1)]))) else: arg_defaults = {} all_params = {} for (arg_name, arg_info) in info.items(): prefixed_name = (prefix + arg_name) arg_value = None if hasattr(parsed_args, prefixed_name): arg_value = getattr(parsed_args, prefixed_name) if ((arg_value is None) and (arg_name in arg_defaults)): arg_value = arg_defaults[arg_name] if (arg_value is not None): all_params[arg_name] = arg_value return all_params
def colorize(string, color, bold=False, highlight=False): attr = [] num = color2num[color] if highlight: num += 10 attr.append(str(num)) if bold: attr.append('1') return ('\x1b[%sm%s\x1b[0m' % (';'.join(attr), string))
def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if ((exc.errno == errno.EEXIST) and os.path.isdir(path)): pass else: raise
def log(s): print(s) sys.stdout.flush()
class SimpleMessage(object): def __init__(self, msg, logger=log): self.msg = msg self.logger = logger def __enter__(self): print(self.msg) self.tstart = time.time() def __exit__(self, etype, *args): maybe_exc = ('' if (etype is None) else ' (with exception)') self.logger(('done%s in %.3f seconds' % (maybe_exc, (time.time() - self.tstart))))
class Message(object): def __init__(self, msg): self.msg = msg def __enter__(self): global MESSAGE_DEPTH print(colorize(((('\t' * MESSAGE_DEPTH) + '=: ') + self.msg), 'magenta')) self.tstart = time.time() MESSAGE_DEPTH += 1 def __exit__(self, etype, *args): global MESSAGE_DEPTH MESSAGE_DEPTH -= 1 maybe_exc = ('' if (etype is None) else ' (with exception)') print(colorize((('\t' * MESSAGE_DEPTH) + ('done%s in %.3f seconds' % (maybe_exc, (time.time() - self.tstart)))), 'magenta'))
def prefix_log(prefix, logger=log): return (lambda s: logger((prefix + s)))
def tee_log(file_name): f = open(file_name, 'w+') def logger(s): log(s) f.write(s) f.write('\n') f.flush() return logger
def collect_args(): splitted = shlex.split(' '.join(sys.argv[1:])) return {arg_name[2:]: arg_val for (arg_name, arg_val) in zip(splitted[::2], splitted[1::2])}
def type_hint(arg_name, arg_type): def wrap(f): meta = getattr(f, '__tweak_type_hint_meta__', None) if (meta is None): f.__tweak_type_hint_meta__ = meta = {} meta[arg_name] = arg_type return f return wrap
def tweak(fun_or_val, identifier=None): if isinstance(fun_or_val, collections.Callable): return tweakfun(fun_or_val, identifier) return tweakval(fun_or_val, identifier)
def tweakval(val, identifier): if (not identifier): raise ValueError('Must provide an identifier for tweakval to work') args = collect_args() for (k, v) in args.items(): stripped = k.replace('-', '_') if (stripped == identifier): log(('replacing %s in %s with %s' % (stripped, str(val), str(v)))) return type(val)(v) return val
def tweakfun(fun, alt=None): 'Make the arguments (or the function itself) tweakable from command line.\n See tests/test_misc_console.py for examples.\n\n NOTE: this only works for the initial launched process, since other processes\n will get different argv. What this means is that tweak() calls wrapped in a function\n to be invoked in a child process might not behave properly.\n ' cls = getattr(fun, 'im_class', None) method_name = fun.__name__ if alt: cmd_prefix = alt elif cls: cmd_prefix = ((cls + '.') + method_name) else: cmd_prefix = method_name cmd_prefix = cmd_prefix.lower() args = collect_args() if (cmd_prefix in args): fun = pydoc.locate(args[cmd_prefix]) if (type(fun) == type): argspec = inspect.getargspec(fun.__init__) else: argspec = inspect.getargspec(fun) defaults = dict(list(zip(argspec.args[(- len((argspec.defaults or []))):], (argspec.defaults or [])))) replaced_kwargs = {} cmd_prefix += '-' if (type(fun) == type): meta = getattr(fun.__init__, '__tweak_type_hint_meta__', {}) else: meta = getattr(fun, '__tweak_type_hint_meta__', {}) for (k, v) in args.items(): if k.startswith(cmd_prefix): stripped = k[len(cmd_prefix):].replace('-', '_') if (stripped in meta): log(('replacing %s in %s with %s' % (stripped, str(fun), str(v)))) replaced_kwargs[stripped] = meta[stripped](v) elif (stripped not in argspec.args): raise ValueError(('%s is not an explicit parameter of %s' % (stripped, str(fun)))) elif (stripped not in defaults): raise ValueError(('%s does not have a default value in method %s' % (stripped, str(fun)))) elif (defaults[stripped] is None): raise ValueError(('Cannot infer type of %s in method %s from None value' % (stripped, str(fun)))) else: log(('replacing %s in %s with %s' % (stripped, str(fun), str(v)))) replaced_kwargs[stripped] = type(defaults[stripped])(v) def tweaked(*args, **kwargs): all_kw = dict(((list(zip(argspec[0], args)) + list(kwargs.items())) + list(replaced_kwargs.items()))) return fun(**all_kw) return tweaked
def query_yes_no(question, default='yes'): 'Ask a yes/no question via raw_input() and return their answer.\n\n "question" is a string that is presented to the user.\n "default" is the presumed answer if the user just hits <Enter>.\n It must be "yes" (the default), "no" or None (meaning\n an answer is required of the user).\n\n The "answer" return value is True for "yes" or False for "no".\n ' valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False} if (default is None): prompt = ' [y/n] ' elif (default == 'yes'): prompt = ' [Y/n] ' elif (default == 'no'): prompt = ' [y/N] ' else: raise ValueError(("invalid default answer: '%s'" % default)) while True: sys.stdout.write((question + prompt)) choice = input().lower() if ((default is not None) and (choice == '')): return valid[default] elif (choice in valid): return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
def extract(x, *keys): if isinstance(x, (dict, lazydict)): return tuple((x[k] for k in keys)) elif isinstance(x, list): return tuple(([xi[k] for xi in x] for k in keys)) else: raise NotImplementedError
def extract_dict(x, *keys): return {k: x[k] for k in keys if (k in x)}
def flatten(xs): return [x for y in xs for x in y]
def compact(x): '\n For a dictionary this removes all None values, and for a list this removes\n all None elements; otherwise it returns the input itself.\n ' if isinstance(x, dict): return dict(((k, v) for (k, v) in x.items() if (v is not None))) elif isinstance(x, list): return [elem for elem in x if (elem is not None)] return x
def cached_function(inputs, outputs): import theano with Message('Hashing theano fn'): if hasattr(outputs, '__len__'): hash_content = tuple(map(theano.pp, outputs)) else: hash_content = theano.pp(outputs) cache_key = hex((hash(hash_content) & ((2 ** 64) - 1)))[:(- 1)] cache_dir = Path('~/.hierctrl_cache') cache_dir = cache_dir.expanduser() cache_dir.mkdir_p() cache_file = (cache_dir / ('%s.pkl' % cache_key)) if cache_file.exists(): with Message('unpickling'): with open(cache_file, 'rb') as f: try: return pickle.load(f) except Exception: pass with Message('compiling'): fun = compile_function(inputs, outputs) with Message('picking'): with open(cache_file, 'wb') as f: pickle.dump(fun, f, protocol=pickle.HIGHEST_PROTOCOL) return fun
class lazydict(object): def __init__(self, **kwargs): self._lazy_dict = kwargs self._dict = {} def __getitem__(self, key): if (key not in self._dict): self._dict[key] = self._lazy_dict[key]() return self._dict[key] def __setitem__(self, i, y): self.set(i, y) def get(self, key, default=None): if (key in self._lazy_dict): return self[key] return default def set(self, key, value): self._lazy_dict[key] = value
def iscanl(f, l, base=None): started = False for x in l: if (base or started): base = f(base, x) else: base = x started = True (yield base)
def iscanr(f, l, base=None): started = False for x in list(l)[::(- 1)]: if (base or started): base = f(x, base) else: base = x started = True (yield base)
def scanl(f, l, base=None): return list(iscanl(f, l, base))
def scanr(f, l, base=None): return list(iscanr(f, l, base))
def compile_function(inputs=None, outputs=None, updates=None, givens=None, log_name=None, **kwargs): import theano if log_name: msg = Message(('Compiling function %s' % log_name)) msg.__enter__() ret = theano.function(inputs=inputs, outputs=outputs, updates=updates, givens=givens, on_unused_input='ignore', allow_input_downcast=True, **kwargs) if log_name: msg.__exit__(None, None, None) return ret
def new_tensor(name, ndim, dtype): import theano.tensor as TT return TT.TensorType(dtype, ((False,) * ndim))(name)
def new_tensor_like(name, arr_like): return new_tensor(name, arr_like.ndim, arr_like.dtype)
class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self
def is_iterable(obj): return (isinstance(obj, str) or getattr(obj, '__iter__', False))
def truncate_path(p, t): return dict(((k, p[k][:t]) for k in p))
def concat_paths(p1, p2): import numpy as np return dict(((k1, np.concatenate([p1[k1], p2[k1]])) for k1 in list(p1.keys()) if (k1 in p2)))
def path_len(p): return len(p['states'])
def shuffled(sequence): deck = list(sequence) while len(deck): i = random.randint(0, (len(deck) - 1)) card = deck[i] deck[i] = deck[(- 1)] deck.pop() (yield card)
def set_seed(seed): seed %= 4294967294 global seed_ seed_ = seed import lasagne random.seed(seed) np.random.seed(seed) lasagne.random.set_rng(np.random.RandomState(seed)) try: import tensorflow as tf tf.set_random_seed(seed) except Exception as e: print(e) print(colorize(('using seed %s' % str(seed)), 'green'))
def get_seed(): return seed_
def flatten_hessian(cost, wrt, consider_constant=None, disconnected_inputs='raise', block_diagonal=True): "\n :type cost: Scalar (0-dimensional) Variable.\n :type wrt: Vector (1-dimensional tensor) 'Variable' or list of\n vectors (1-dimensional tensors) Variables\n\n :param consider_constant: a list of expressions not to backpropagate\n through\n\n :type disconnected_inputs: string\n :param disconnected_inputs: Defines the behaviour if some of the variables\n in ``wrt`` are not part of the computational graph computing ``cost``\n (or if all links are non-differentiable). The possible values are:\n - 'ignore': considers that the gradient on these parameters is zero.\n - 'warn': consider the gradient zero, and print a warning.\n - 'raise': raise an exception.\n\n :return: either a instance of Variable or list/tuple of Variables\n (depending upon `wrt`) repressenting the Hessian of the `cost`\n with respect to (elements of) `wrt`. If an element of `wrt` is not\n differentiable with respect to the output, then a zero\n variable is returned. The return value is of same type\n as `wrt`: a list/tuple or TensorVariable in all cases.\n " import theano from theano.tensor import arange import theano.tensor as TT from theano import Variable from theano import grad assert isinstance(cost, Variable), 'tensor.hessian expects a Variable as `cost`' assert (cost.ndim == 0), 'tensor.hessian expects a 0 dimensional variable as `cost`' using_list = isinstance(wrt, list) using_tuple = isinstance(wrt, tuple) if isinstance(wrt, (list, tuple)): wrt = list(wrt) else: wrt = [wrt] hessians = [] if (not block_diagonal): expr = TT.concatenate([grad(cost, input, consider_constant=consider_constant, disconnected_inputs=disconnected_inputs).flatten() for input in wrt]) for input in wrt: assert isinstance(input, Variable), 'tensor.hessian expects a (list of) Variable as `wrt`' if block_diagonal: expr = grad(cost, input, consider_constant=consider_constant, disconnected_inputs=disconnected_inputs).flatten() (hess, updates) = theano.scan((lambda i, y, x: grad(y[i], x, consider_constant=consider_constant, disconnected_inputs='ignore').flatten()), sequences=arange(expr.shape[0]), non_sequences=[expr, input]) assert (not updates), 'Scan has returned a list of updates. This should not happen! Report this to theano-users (also include the script that generated the error)' hessians.append(hess) if block_diagonal: from theano.gradient import format_as return format_as(using_list, using_tuple, hessians) else: return TT.concatenate(hessians, axis=1)
def flatten_tensor_variables(ts): import theano.tensor as TT return TT.concatenate(list(map(TT.flatten, ts)))