code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def nsga2select(population, fitnesses, survivors, allowequality = True): """The NSGA-II selection strategy (Deb et al., 2002). The number of individuals that survive is given by the survivors parameter.""" fronts = non_dominated_sort(population, key=lambda x: fitnesses[x], allowequality = allowequality) individuals = set() for front in fronts: remaining = survivors - len(individuals) if not remaining > 0: break if len(front) > remaining: # If the current front does not fit in the spots left, use those # that have the biggest crowding distance. crowd_dist = crowding_distance(front, fitnesses) front = sorted(front, key=lambda x: crowd_dist[x], reverse=True) front = set(front[:remaining]) individuals |= front return list(individuals)
The NSGA-II selection strategy (Deb et al., 2002). The number of individuals that survive is given by the survivors parameter.
nsga2select
python
pybrain/pybrain
pybrain/optimization/populationbased/multiobjective/nsga2.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/multiobjective/nsga2.py
BSD-3-Clause
def __init__(self, module, learner = None): """ :key module: the acting module :key learner: the learner (optional) """ LoggingAgent.__init__(self, module.indim, module.outdim) self.module = module self.learner = learner # if learner is available, tell it the module and data if self.learner is not None: self.learner.module = self.module self.learner.dataset = self.history self.learning = True
:key module: the acting module :key learner: the learner (optional)
__init__
python
pybrain/pybrain
pybrain/rl/agents/learning.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/learning.py
BSD-3-Clause
def _setLearning(self, flag): """ Set whether or not the agent should learn from its experience """ if self.learner is not None: self.__learning = flag else: self.__learning = False
Set whether or not the agent should learn from its experience
_setLearning
python
pybrain/pybrain
pybrain/rl/agents/learning.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/learning.py
BSD-3-Clause
def getAction(self): """ Activate the module with the last observation, add the exploration from the explorer object and store the result as last action. """ LoggingAgent.getAction(self) self.lastaction = self.module.activate(self.lastobs) if self.learning: self.lastaction = self.learner.explore(self.lastobs, self.lastaction) return self.lastaction
Activate the module with the last observation, add the exploration from the explorer object and store the result as last action.
getAction
python
pybrain/pybrain
pybrain/rl/agents/learning.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/learning.py
BSD-3-Clause
def newEpisode(self): """ Indicate the beginning of a new episode in the training cycle. """ # reset the module when a new episode starts. self.module.reset() if self.logging: self.history.newSequence() # inform learner about the start of a new episode if self.learning: self.learner.newEpisode()
Indicate the beginning of a new episode in the training cycle.
newEpisode
python
pybrain/pybrain
pybrain/rl/agents/learning.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/learning.py
BSD-3-Clause
def reset(self): """ Clear the history of the agent and resets the module and learner. """ LoggingAgent.reset(self) self.module.reset() if self.learning: self.learner.reset()
Clear the history of the agent and resets the module and learner.
reset
python
pybrain/pybrain
pybrain/rl/agents/learning.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/learning.py
BSD-3-Clause
def newEpisode(self): """ Indicate the beginning of a new episode in the training cycle. """ if self.logging: self.history.newSequence() if self.learning and not self.learner.batchMode: self.learner.newEpisode() else: self._temperature *= self.temperature_decay self._expl_proportion *= self.exploration_decay self.learner.newEpisode()
Indicate the beginning of a new episode in the training cycle.
newEpisode
python
pybrain/pybrain
pybrain/rl/agents/linearfa.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/linearfa.py
BSD-3-Clause
def integrateObservation(self, obs): """Step 1: store the observation received in a temporary variable until action is called and reward is given. """ self.lastobs = obs self.lastaction = None self.lastreward = None
Step 1: store the observation received in a temporary variable until action is called and reward is given.
integrateObservation
python
pybrain/pybrain
pybrain/rl/agents/logging.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/logging.py
BSD-3-Clause
def getAction(self): """Step 2: store the action in a temporary variable until reward is given. """ assert self.lastobs != None assert self.lastaction == None assert self.lastreward == None # implement getAction in subclass and set self.lastaction
Step 2: store the action in a temporary variable until reward is given.
getAction
python
pybrain/pybrain
pybrain/rl/agents/logging.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/logging.py
BSD-3-Clause
def giveReward(self, r): """Step 3: store observation, action and reward in the history dataset. """ # step 3: assume that state and action have been set assert self.lastobs != None assert self.lastaction != None assert self.lastreward == None self.lastreward = r # store state, action and reward in dataset if logging is enabled if self.logging: self.history.addSample(self.lastobs, self.lastaction, self.lastreward)
Step 3: store observation, action and reward in the history dataset.
giveReward
python
pybrain/pybrain
pybrain/rl/agents/logging.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/logging.py
BSD-3-Clause
def reset(self): """ Clear the history of the agent. """ self.lastobs = None self.lastaction = None self.lastreward = None self.history.clear()
Clear the history of the agent.
reset
python
pybrain/pybrain
pybrain/rl/agents/logging.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/agents/logging.py
BSD-3-Clause
def addReward(self): """ A filtered mapping towards performAction of the underlying environment. """ # by default, the cumulative reward is just the sum over the episode if self.discount: self.cumreward += power(self.discount, self.samples) * self.getReward() else: self.cumreward += self.getReward()
A filtered mapping towards performAction of the underlying environment.
addReward
python
pybrain/pybrain
pybrain/rl/environments/episodic.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/episodic.py
BSD-3-Clause
def f(self, x): """ An episodic task can be used as an evaluation function of a module that produces actions from observations, or as an evaluator of an agent. """ r = 0. for _ in range(self.batchSize): if isinstance(x, Module): x.reset() self.reset() while not self.isFinished(): self.performAction(x.activate(self.getObservation())) elif isinstance(x, Agent): EpisodicExperiment(self, x).doEpisodes() else: raise ValueError(self.__class__.__name__+' cannot evaluate the fitness of '+str(type(x))) r += self.getTotalReward() return r / float(self.batchSize)
An episodic task can be used as an evaluation function of a module that produces actions from observations, or as an evaluator of an agent.
f
python
pybrain/pybrain
pybrain/rl/environments/episodic.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/episodic.py
BSD-3-Clause
def __init__(self, environment): """ All tasks are coupled to an environment. """ self.env = environment # limits for scaling of sensors and actors (None=disabled) self.sensor_limits = None self.actor_limits = None self.clipping = True
All tasks are coupled to an environment.
__init__
python
pybrain/pybrain
pybrain/rl/environments/task.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/task.py
BSD-3-Clause
def setScaling(self, sensor_limits, actor_limits): """ Expects scaling lists of 2-tuples - e.g. [(-3.14, 3.14), (0, 1), (-0.001, 0.001)] - one tuple per parameter, giving min and max for that parameter. The functions normalize and denormalize scale the parameters between -1 and 1 and vice versa. To disable this feature, use 'None'. """ self.sensor_limits = sensor_limits self.actor_limits = actor_limits
Expects scaling lists of 2-tuples - e.g. [(-3.14, 3.14), (0, 1), (-0.001, 0.001)] - one tuple per parameter, giving min and max for that parameter. The functions normalize and denormalize scale the parameters between -1 and 1 and vice versa. To disable this feature, use 'None'.
setScaling
python
pybrain/pybrain
pybrain/rl/environments/task.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/task.py
BSD-3-Clause
def performAction(self, action): """ A filtered mapping towards performAction of the underlying environment. """ if self.actor_limits: action = self.denormalize(action) self.env.performAction(action)
A filtered mapping towards performAction of the underlying environment.
performAction
python
pybrain/pybrain
pybrain/rl/environments/task.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/task.py
BSD-3-Clause
def getObservation(self): """ A filtered mapping to getSensors of the underlying environment. """ sensors = self.env.getSensors() if self.sensor_limits: sensors = self.normalize(sensors) return sensors
A filtered mapping to getSensors of the underlying environment.
getObservation
python
pybrain/pybrain
pybrain/rl/environments/task.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/task.py
BSD-3-Clause
def normalize(self, sensors): """ The function scales the parameters to be between -1 and 1. e.g. [(-pi, pi), (0, 1), (-0.001, 0.001)] """ assert(len(self.sensor_limits) == len(sensors)) result = [] for l, s in zip(self.sensor_limits, sensors): if not l: result.append(s) else: result.append((s - l[0]) / (l[1] - l[0]) * 2 - 1.0) if self.clipping: clip(result, -1, 1) return asarray(result)
The function scales the parameters to be between -1 and 1. e.g. [(-pi, pi), (0, 1), (-0.001, 0.001)]
normalize
python
pybrain/pybrain
pybrain/rl/environments/task.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/task.py
BSD-3-Clause
def denormalize(self, actors): """ The function scales the parameters from -1 and 1 to the given interval (min, max) for each actor. """ assert(len(self.actor_limits) == len(actors)) result = [] for l, a in zip(self.actor_limits, actors): if not l: result.append(a) else: r = (a + 1.0) / 2 * (l[1] - l[0]) + l[0] if self.clipping: r = clip(r, l[0], l[1]) result.append(r) return result
The function scales the parameters from -1 and 1 to the given interval (min, max) for each actor.
denormalize
python
pybrain/pybrain
pybrain/rl/environments/task.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/task.py
BSD-3-Clause
def __init__(self, env=None, maxsteps=1000, desiredValue = 0): """ :key env: (optional) an instance of a CartPoleEnvironment (or a subclass thereof) :key maxsteps: maximal number of steps (default: 1000) """ self.desiredValue = desiredValue if env == None: env = CartPoleEnvironment() EpisodicTask.__init__(self, env) self.N = maxsteps self.t = 0 # scale position and angle, don't scale velocities (unknown maximum) self.sensor_limits = [(-3, 3)] for i in range(1, self.outdim): if isinstance(self.env, NonMarkovPoleEnvironment) and i % 2 == 0: self.sensor_limits.append(None) else: self.sensor_limits.append((-pi, pi)) # self.sensor_limits = [None] * 4 # actor between -10 and 10 Newton self.actor_limits = [(-50, 50)]
:key env: (optional) an instance of a CartPoleEnvironment (or a subclass thereof) :key maxsteps: maximal number of steps (default: 1000)
__init__
python
pybrain/pybrain
pybrain/rl/environments/cartpole/balancetask.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/balancetask.py
BSD-3-Clause
def __init__(self, env=None, maxsteps=1000): """ :key env: (optional) an instance of a CartPoleEnvironment (or a subclass thereof) :key maxsteps: maximal number of steps (default: 1000) """ if env == None: env = CartPoleEnvironment() EpisodicTask.__init__(self, env) self.N = maxsteps self.t = 0 # no scaling of sensors self.sensor_limits = [None] * self.env.outdim # scale actor self.actor_limits = [(-50, 50)]
:key env: (optional) an instance of a CartPoleEnvironment (or a subclass thereof) :key maxsteps: maximal number of steps (default: 1000)
__init__
python
pybrain/pybrain
pybrain/rl/environments/cartpole/balancetask.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/balancetask.py
BSD-3-Clause
def getObservation(self): """ a filtered mapping to getSample of the underlying environment. """ sensors = self.env.getSensors() if self.sensor_limits: sensors = self.normalize(sensors) return sensors
a filtered mapping to getSample of the underlying environment.
getObservation
python
pybrain/pybrain
pybrain/rl/environments/cartpole/balancetask.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/balancetask.py
BSD-3-Clause
def __init__(self, env=None, maxsteps=1000): """ :key env: (optional) an instance of a CartPoleEnvironment (or a subclass thereof) :key maxsteps: maximal number of steps (default: 1000) """ if env == None: env = CartPoleEnvironment() EpisodicTask.__init__(self, env) self.N = maxsteps self.t = 0 # no scaling of sensors self.sensor_limits = [None] * 2 # scale actor self.actor_limits = [(-50, 50)]
:key env: (optional) an instance of a CartPoleEnvironment (or a subclass thereof) :key maxsteps: maximal number of steps (default: 1000)
__init__
python
pybrain/pybrain
pybrain/rl/environments/cartpole/balancetask.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/balancetask.py
BSD-3-Clause
def getObservation(self): """ a filtered mapping to getSample of the underlying environment. """ sensors = [self.env.getSensors()[0], self.env.getSensors()[2]] if self.sensor_limits: sensors = self.normalize(sensors) return sensors
a filtered mapping to getSample of the underlying environment.
getObservation
python
pybrain/pybrain
pybrain/rl/environments/cartpole/balancetask.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/balancetask.py
BSD-3-Clause
def reset(self): """ re-initializes the environment, setting the cart back in a random position. """ if self.randomInitialization: angle = random.uniform(-0.2, 0.2) pos = random.uniform(-0.5, 0.5) else: angle = -0.2 pos = 0.2 self.sensors = (angle, 0.0, pos, 0.0)
re-initializes the environment, setting the cart back in a random position.
reset
python
pybrain/pybrain
pybrain/rl/environments/cartpole/cartpole.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/cartpole.py
BSD-3-Clause
def _derivs(self, x, t): """ This function is needed for the Runge-Kutta integration approximation method. It calculates the derivatives of the state variables given in x. for each variable in x, it returns the first order derivative at time t. """ F = self.action (theta, theta_, _s, s_) = x u = theta_ sin_theta = sin(theta) cos_theta = cos(theta) mp = self.mp mc = self.mc l = self.l u_ = (self.g * sin_theta * (mc + mp) - (F + mp * l * theta_ ** 2 * sin_theta) * cos_theta) / (4 / 3 * l * (mc + mp) - mp * l * cos_theta ** 2) v = s_ v_ = (F - mp * l * (u_ * cos_theta - (theta_ ** 2 * sin_theta))) / (mc + mp) return (u, u_, v, v_)
This function is needed for the Runge-Kutta integration approximation method. It calculates the derivatives of the state variables given in x. for each variable in x, it returns the first order derivative at time t.
_derivs
python
pybrain/pybrain
pybrain/rl/environments/cartpole/cartpole.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/cartpole.py
BSD-3-Clause
def getSensors(self): """ returns the state one step (dt) ahead in the future. stores the state in self.sensors because it is needed for the next calculation. The sensor return vector has 6 elements: theta1, theta1', theta2, theta2', s, s' (s being the distance from the origin). """ s1 = self.p1.getSensors() s2 = self.p2.getSensors() self.sensors = (s1[0], s1[1], s2[0], s2[1], s2[2], s2[3]) return self.sensors
returns the state one step (dt) ahead in the future. stores the state in self.sensors because it is needed for the next calculation. The sensor return vector has 6 elements: theta1, theta1', theta2, theta2', s, s' (s being the distance from the origin).
getSensors
python
pybrain/pybrain
pybrain/rl/environments/cartpole/doublepole.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/doublepole.py
BSD-3-Clause
def reset(self): """ re-initializes the environment, setting the cart back in a random position. """ self.p1.reset() self.p2.reset() # put cart in the same place: self.p2.sensors = (self.p2.sensors[0], self.p2.sensors[1], self.p1.sensors[2], self.p1.sensors[3]) self.getSensors()
re-initializes the environment, setting the cart back in a random position.
reset
python
pybrain/pybrain
pybrain/rl/environments/cartpole/doublepole.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/doublepole.py
BSD-3-Clause
def getSensors(self): """ returns the state one step (dt) ahead in the future. stores the state in self.sensors because it is needed for the next calculation. The sensor return vector has 3 elements: theta1, theta2, s (s being the distance from the origin). """ tmp = DoublePoleEnvironment.getSensors(self) return (tmp[0], tmp[2], tmp[4])
returns the state one step (dt) ahead in the future. stores the state in self.sensors because it is needed for the next calculation. The sensor return vector has 3 elements: theta1, theta2, s (s being the distance from the origin).
getSensors
python
pybrain/pybrain
pybrain/rl/environments/cartpole/nonmarkovdoublepole.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/nonmarkovdoublepole.py
BSD-3-Clause
def getSensors(self): """ returns the state one step (dt) ahead in the future. stores the state in self.sensors because it is needed for the next calculation. The sensor return vector has 2 elements: theta, s (s being the distance from the origin). """ tmp = CartPoleEnvironment.getSensors(self) return (tmp[0], tmp[2])
returns the state one step (dt) ahead in the future. stores the state in self.sensors because it is needed for the next calculation. The sensor return vector has 2 elements: theta, s (s being the distance from the origin).
getSensors
python
pybrain/pybrain
pybrain/rl/environments/cartpole/nonmarkovpole.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/nonmarkovpole.py
BSD-3-Clause
def __init__(self, numPoles=1, markov=True, verbose=False, extraObservations=False, extraRandoms=0, maxSteps=100000): """ @extraObservations: if this flag is true, the observations include the Cartesian coordinates of the pole(s). """ if self.__single != None: raise Exception('Singleton class - there is already an instance around', self.__single) self.__single = self impl.init(markov, numPoles, maxSteps) self.markov = markov self.numPoles = numPoles self.verbose = verbose self.extraObservations = extraObservations self.extraRandoms = extraRandoms self.desiredValue = maxSteps self.reset()
@extraObservations: if this flag is true, the observations include the Cartesian coordinates of the pole(s).
__init__
python
pybrain/pybrain
pybrain/rl/environments/cartpole/fast_version/cartpoleenv.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/cartpole/fast_version/cartpoleenv.py
BSD-3-Clause
def performAction(self, action): """ a filtered mapping towards performAction of the underlying environment. """ # scaling self.incStep() action = (action + 1.0) / 2.0 * self.dif + self.env.fraktMin * self.env.dists[0] #Clipping the maximal change in actions (max force clipping) action = clip(action, self.action - self.maxSpeed, self.action + self.maxSpeed) EpisodicTask.performAction(self, action) self.action = action.copy()
a filtered mapping towards performAction of the underlying environment.
performAction
python
pybrain/pybrain
pybrain/rl/environments/flexcube/tasks.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/flexcube/tasks.py
BSD-3-Clause
def drawScene(self): ''' This methode describes the complete scene.''' # clear the buffer if self.zDis < 10: self.zDis += 0.25 if self.lastz > 200: self.lastz -= self.zDis glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() # Point of view glRotatef(self.lastx, 0.0, 1.0, 0.0) glRotatef(self.lasty, 1.0, 0.0, 0.0) #glRotatef(15, 0.0, 0.0, 1.0) # direction of view is aimed to the center of gravity of the cube glTranslatef(-self.centerOfGrav[0], -self.centerOfGrav[1] - 50.0, -self.centerOfGrav[2] - self.lastz) #Objects #Target Ball glColor3f(1, 0.25, 0.25) glPushMatrix() glTranslate(self.target[0], 0.0, self.target[2]) glutSolidSphere(1.5, 8, 8) glPopMatrix() #Massstab for lk in range(41): if float(lk - 20) / 10.0 == (lk - 20) / 10: glColor3f(0.75, 0.75, 0.75) glPushMatrix() glRotatef(90, 1, 0, 0) glTranslate(self.worldRadius / 40.0 * float(lk) - self.worldRadius / 2.0, -40.0, -30) quad = gluNewQuadric() gluCylinder(quad, 2, 2, 60, 4, 1); glPopMatrix() else: if float(lk - 20) / 5.0 == (lk - 20) / 5: glColor3f(0.75, 0.75, 0.75) glPushMatrix() glRotatef(90, 1, 0, 0) glTranslate(self.worldRadius / 40.0 * float(lk) - self.worldRadius / 2.0, -40.0, -15.0) quad = gluNewQuadric() gluCylinder(quad, 1, 1, 30, 4, 1); glPopMatrix() else: glColor3f(0.75, 0.75, 0.75) glPushMatrix() glRotatef(90, 1, 0, 0) glTranslate(self.worldRadius / 40.0 * float(lk) - self.worldRadius / 2.0, -40.0, -7.5) quad = gluNewQuadric() gluCylinder(quad, 0.5, 0.5, 15, 4, 1); glPopMatrix() #Mirror Center Ball glColor3f(1, 1, 1) glPushMatrix() glTranslate(self.centerOfGrav[0], -self.centerOfGrav[1], self.centerOfGrav[2]) glutSolidSphere(1.5, 8, 8) glPopMatrix() #Mirror Cube glEnable (GL_BLEND) glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glColor4f(0.5, 0.75, 0.5, 0.75) glPushMatrix() glTranslatef(0, -0.05, 0) self.object.drawMirCreat(self.points, self.centerOfGrav) glPopMatrix() # Floor tile = self.worldRadius / 40.0 glEnable (GL_BLEND) glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) for xF in range(40): for yF in range(40): if float(xF + yF) / 2.0 == (xF + yF) / 2: glColor3f(0.8, 0.8, 0.7) else: glColor4f(0.8, 0.8, 0.8, 0.7) glPushMatrix() glTranslatef(0.0, -0.03, 0.0) glBegin(GL_QUADS) glNormal(0.0, 1.0, 0.0) for i in range(2): for k in range(2): glVertex3f((i + xF - 20) * tile, 0.0, ((k ^ i) + yF - 20) * tile); glEnd() glPopMatrix() #Center Ball glColor3f(1, 1, 1) glPushMatrix() glTranslate(self.centerOfGrav[0], self.centerOfGrav[1], self.centerOfGrav[2]) glutSolidSphere(1.5, 8, 8) glPopMatrix() # Cube glEnable (GL_BLEND) glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glColor4f(0.5, 0.75, 0.5, 0.75) glPushMatrix() self.object.drawCreature(self.points, self.centerOfGrav) glPopMatrix() glEnable (GL_BLEND) glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # Cubes shadow glColor4f(0, 0, 0, 0.5) glPushMatrix() self.object.drawShadow(self.points, self.centerOfGrav) glPopMatrix() # swap the buffer glutSwapBuffers()
This methode describes the complete scene.
drawScene
python
pybrain/pybrain
pybrain/rl/environments/flexcube/viewer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/flexcube/viewer.py
BSD-3-Clause
def getSensors(self): """ the one sensor is the function result. """ tmp = self.result assert tmp is not None self.result = None return array([tmp])
the one sensor is the function result.
getSensors
python
pybrain/pybrain
pybrain/rl/environments/functions/function.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/functions/function.py
BSD-3-Clause
def _exampleConfig(self, numatoms, noise=0.05, edge=2.): """ Arranged in an approximate cube of certain edge length. """ assert numatoms % 8 == 0 x0 = randn(3, 2, 2, 2, numatoms / 8) * noise * edge - edge / 2 x0[0, 0] += edge x0[1, :, 0] += edge x0[2, :, :, 0] += edge x0 = x0.reshape(3, numatoms).T return x0.flatten()
Arranged in an approximate cube of certain edge length.
_exampleConfig
python
pybrain/pybrain
pybrain/rl/environments/functions/lennardjones.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/functions/lennardjones.py
BSD-3-Clause
def __init__(self, basef, distance=0.1, offset=None): """ by default the offset is random, with a distance of 0.1 to the old one """ FunctionEnvironment.__init__(self, basef.xdim, basef.xopt) if offset == None: self._offset = rand(basef.xdim) self._offset *= distance / norm(self._offset) else: self._offset = offset self.xopt += self._offset self.desiredValue = basef.desiredValue self.toBeMinimized = basef.toBeMinimized def tf(x): if isinstance(x, ParameterContainer): x = x.params return basef.f(x - self._offset) self.f = tf
by default the offset is random, with a distance of 0.1 to the old one
__init__
python
pybrain/pybrain
pybrain/rl/environments/functions/transformations.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/functions/transformations.py
BSD-3-Clause
def __init__(self, basef, rotMat=None): """ by default the rotation matrix is random. """ FunctionEnvironment.__init__(self, basef.xdim, basef.xopt) if rotMat == None: # make a random orthogonal rotation matrix self._M = orth(rand(basef.xdim, basef.xdim)) else: self._M = rotMat self.desiredValue = basef.desiredValue self.toBeMinimized = basef.toBeMinimized self.xopt = dot(inv(self._M), self.xopt) def rf(x): if isinstance(x, ParameterContainer): x = x.params return basef.f(dot(x, self._M)) self.f = rf
by default the rotation matrix is random.
__init__
python
pybrain/pybrain
pybrain/rl/environments/functions/transformations.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/functions/transformations.py
BSD-3-Clause
def _freePos(self): """ produce a list of the free positions. """ res = [] for i, row in enumerate(self.mazeTable): for j, p in enumerate(row): if p == False: res.append((i, j)) return res
produce a list of the free positions.
_freePos
python
pybrain/pybrain
pybrain/rl/environments/mazes/maze.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/mazes/maze.py
BSD-3-Clause
def __str__(self): """ Ascii representation of the maze, with the current state """ s = '' for r, row in reversed(list(enumerate(self.mazeTable))): for c, p in enumerate(row): if (r, c) == self.goal: s += '*' elif (r, c) == self.perseus: s += '@' elif p == True: s += '#' else: s += ' ' s += '\n' return s
Ascii representation of the maze, with the current state
__str__
python
pybrain/pybrain
pybrain/rl/environments/mazes/maze.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/mazes/maze.py
BSD-3-Clause
def getObservation(self): """ observations are encoded in a 1-n encoding of possible wall combinations. """ res = zeros(7) obs = self.env.getSensors() if self.env.perseus == self.env.goal: res[6] = 1 elif sum(obs) == 3: res[0] = 1 elif sum(obs) == 1: res[5] = 1 elif obs[0] == obs[1]: res[1] = 1 elif obs[0] == obs[3]: res[2] = 1 elif obs[0] == obs[2]: if obs[0] == 1: res[3] = 1 else: res[4] = 1 return res
observations are encoded in a 1-n encoding of possible wall combinations.
getObservation
python
pybrain/pybrain
pybrain/rl/environments/mazes/tasks/cheesemaze.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/mazes/tasks/cheesemaze.py
BSD-3-Clause
def getObservation(self): """only walls on w, E, both or neither are observed. """ res = zeros(4) all = self.env.getSensors() res[0] = all[3] res[1] = all[1] res[2] = all[3] and all[1] res[3] = not all[3] and not all[1] return res
only walls on w, E, both or neither are observed.
getObservation
python
pybrain/pybrain
pybrain/rl/environments/mazes/tasks/maze4x3.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/mazes/tasks/maze4x3.py
BSD-3-Clause
def getReward(self): """ compute and return the current reward (i.e. corresponding to the last action performed) """ if self.env.goal == self.env.perseus: self.env.reset() reward = 1. else: reward = 0. return reward
compute and return the current reward (i.e. corresponding to the last action performed)
getReward
python
pybrain/pybrain
pybrain/rl/environments/mazes/tasks/mdp.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/mazes/tasks/mdp.py
BSD-3-Clause
def performAction(self, action): """ POMDP tasks, as they have discrete actions, can me used by providing either an index, or an array with a 1-in-n coding (which can be stochastic). """ if type(action) == ndarray: action = drawIndex(action, tolerant = True) self.steps += 1 EpisodicTask.performAction(self, action)
POMDP tasks, as they have discrete actions, can me used by providing either an index, or an array with a 1-in-n coding (which can be stochastic).
performAction
python
pybrain/pybrain
pybrain/rl/environments/mazes/tasks/pomdp.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/mazes/tasks/pomdp.py
BSD-3-Clause
def getObservation(self): """ do we think we heard something on the left or on the right? """ if self.tigerLeft: obs = array([1, 0]) else: obs = array([0, 1]) if random() < self.stochObs: obs = 1 - obs return obs
do we think we heard something on the left or on the right?
getObservation
python
pybrain/pybrain
pybrain/rl/environments/mazes/tasks/tiger.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/mazes/tasks/tiger.py
BSD-3-Clause
def __init__(self, render=True, realtime=True, ip="127.0.0.1", port="21590", buf='16384'): """ initializes the virtual world, variables, the frame rate and the callback functions.""" print("ODEEnvironment -- based on Open Dynamics Engine.") # initialize base class self.render = render if self.render: self.updateDone = True self.updateLock = threading.Lock() self.server = UDPServer(ip, port) self.realtime = realtime # initialize attributes self.resetAttributes() # initialize the textures dictionary self.textures = {} # initialize sensor and exclude list self.sensors = [] self.excludesensors = [] #initialize actuators list self.actuators = [] # A joint group for the contact joints that are generated whenever two bodies collide self.contactgroup = ode.JointGroup() self.dt = 0.01 self.FricMu = 8.0 self.stepsPerAction = 1 self.stepCounter = 0
initializes the virtual world, variables, the frame rate and the callback functions.
__init__
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def resetAttributes(self): """resets the class attributes to their default values""" # initialize root node self.root = None # A list with (body, geom) tuples self.body_geom = []
resets the class attributes to their default values
resetAttributes
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def reset(self): """resets the model and all its parameters to their original values""" self.loadXODE(self._currentXODEfile, reload=True) self.stepCounter = 0
resets the model and all its parameters to their original values
reset
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def _setWorldParameters(self): """ sets parameters for ODE world object: gravity, error correction (ERP, default=0.2), constraint force mixing (CFM, default=1e-5). """ self.world.setGravity((0, -9.81, 0)) # self.world.setERP(0.2) # self.world.setCFM(1e-9)
sets parameters for ODE world object: gravity, error correction (ERP, default=0.2), constraint force mixing (CFM, default=1e-5).
_setWorldParameters
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def _create_box(self, space, density, lx, ly, lz): """Create a box body and its corresponding geom.""" # Create body and mass body = ode.Body(self.world) M = ode.Mass() M.setBox(density, lx, ly, lz) body.setMass(M) body.name = None # Create a box geom for collision detection geom = ode.GeomBox(space, lengths=(lx, ly, lz)) geom.setBody(body) geom.name = None return (body, geom)
Create a box body and its corresponding geom.
_create_box
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def _create_sphere(self, space, density, radius): """Create a sphere body and its corresponding geom.""" # Create body and mass body = ode.Body(self.world) M = ode.Mass() M.setSphere(density, radius) body.setMass(M) body.name = None # Create a sphere geom for collision detection geom = ode.GeomSphere(space, radius) geom.setBody(body) geom.name = None return (body, geom)
Create a sphere body and its corresponding geom.
_create_sphere
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def drop_object(self): """Drops a random object (box, sphere) into the scene.""" # choose between boxes and spheres if random.uniform() > 0.5: (body, geom) = self._create_sphere(self.space, 10, 0.4) else: (body, geom) = self._create_box(self.space, 10, 0.5, 0.5, 0.5) # randomize position slightly body.setPosition((random.normal(-6.5, 0.5), 6.0, random.normal(-6.5, 0.5))) # body.setPosition( (0.0, 3.0, 0.0) ) # randomize orientation slightly #theta = random.uniform(0,2*pi) #ct = cos (theta) #st = sin (theta) # rotate body and append to (body,geom) tuple list # body.setRotation([ct, 0., -st, 0., 1., 0., st, 0., ct]) self.body_geom.append((body, geom))
Drops a random object (box, sphere) into the scene.
drop_object
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def addSensor(self, sensor): """ adds a sensor object to the list of sensors """ if not isinstance(sensor, sensors.Sensor): raise TypeError("the given sensor is not an instance of class 'Sensor'.") # add sensor to sensors list self.sensors.append(sensor) # connect sensor and give it the virtual world object sensor._connect(self)
adds a sensor object to the list of sensors
addSensor
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def addActuator(self, actuator): """ adds a sensor object to the list of sensors """ if not isinstance(actuator, actuators.Actuator): raise TypeError("the given actuator is not an instance of class 'Actuator'.") # add sensor to sensors list self.actuators.append(actuator) # connect actuator and give it the virtual world object actuator._connect(self)
adds a sensor object to the list of sensors
addActuator
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def loadXODE(self, filename, reload=False): """ loads an XODE file (xml format) and parses it. """ f = open(filename) self._currentXODEfile = filename p = xode.parser.Parser() self.root = p.parseFile(f) f.close() try: # filter all xode "world" objects from root, take only the first one world = filter(lambda x: isinstance(x, xode.parser.World), self.root.getChildren())[0] except IndexError: # malicious format, no world tag found print(("no <world> tag found in " + filename + ". quitting.")) sys.exit() self.world = world.getODEObject() self._setWorldParameters() try: # filter all xode "space" objects from world, take only the first one space = filter(lambda x: isinstance(x, xode.parser.Space), world.getChildren())[0] except IndexError: # malicious format, no space tag found print(("no <space> tag found in " + filename + ". quitting.")) sys.exit() self.space = space.getODEObject() # load bodies and geoms for painting self.body_geom = [] self._parseBodies(self.root) if self.verbosity > 0: print("-------[body/mass list]-----") for (body, _) in self.body_geom: try: print((body.name, body.getMass())) except AttributeError: print("<Nobody>") # now parse the additional parameters at the end of the xode file self.loadConfig(filename, reload)
loads an XODE file (xml format) and parses it.
loadXODE
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def _parseBodies(self, node): """ parses through the xode tree recursively and finds all bodies and geoms for drawing. """ # body (with nested geom) if isinstance(node, xode.body.Body): body = node.getODEObject() body.name = node.getName() try: # filter all xode geom objects and take the first one xgeom = filter(lambda x: isinstance(x, xode.geom.Geom), node.getChildren())[0] except IndexError: return() # no geom object found, skip this node # get the real ode object geom = xgeom.getODEObject() # if geom doesn't have own name, use the name of its body geom.name = node.getName() self.body_geom.append((body, geom)) # geom on its own without body elif isinstance(node, xode.geom.Geom): try: node.getFirstAncestor(ode.Body) except xode.node.AncestorNotFoundError: body = None geom = node.getODEObject() geom.name = node.getName() self.body_geom.append((body, geom)) # special cases for joints: universal, fixed, amotor elif isinstance(node, xode.joint.Joint): joint = node.getODEObject() if type(joint) == ode.UniversalJoint: # insert an additional AMotor joint to read the angles from and to add torques # amotor = ode.AMotor(self.world) # amotor.attach(joint.getBody(0), joint.getBody(1)) # amotor.setNumAxes(3) # amotor.setAxis(0, 0, joint.getAxis2()) # amotor.setAxis(2, 0, joint.getAxis1()) # amotor.setMode(ode.AMotorEuler) # xode_amotor = xode.joint.Joint(node.getName() + '[amotor]', node.getParent()) # xode_amotor.setODEObject(amotor) # node.getParent().addChild(xode_amotor, None) pass if type(joint) == ode.AMotor: # do the euler angle calculations automatically (ref. ode manual) joint.setMode(ode.AMotorEuler) if type(joint) == ode.FixedJoint: # prevent fixed joints from bouncing to center of first body joint.setFixed() # recursive call for all child nodes for c in node.getChildren(): self._parseBodies(c)
parses through the xode tree recursively and finds all bodies and geoms for drawing.
_parseBodies
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def performAction(self, action): """ sets the values for all actuators combined. """ pointer = 0 for a in self.actuators: val = a.getNumValues() a._update(action[pointer:pointer + val]) pointer += val for _ in range(self.stepsPerAction): self.step()
sets the values for all actuators combined.
performAction
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def _near_callback(self, args, geom1, geom2): """Callback function for the collide() method. This function checks if the given geoms do collide and creates contact joints if they do.""" # only check parse list, if objects have name if geom1.name != None and geom2.name != None: # Preliminary checking, only collide with certain objects for p in self.passpairs: g1 = False g2 = False for x in p: g1 = g1 or (geom1.name.find(x) != -1) g2 = g2 or (geom2.name.find(x) != -1) if g1 and g2: return() # Check if the objects do collide contacts = ode.collide(geom1, geom2) # Create contact joints world, contactgroup = args for c in contacts: p = c.getContactGeomParams() # parameters from Niko Wolf c.setBounce(0.2) c.setBounceVel(0.05) #Set the minimum incoming velocity necessary for bounce c.setSoftERP(0.6) #Set the contact normal "softness" parameter c.setSoftCFM(0.00005) #Set the contact normal "softness" parameter c.setSlip1(0.02) #Set the coefficient of force-dependent-slip (FDS) for friction direction 1 c.setSlip2(0.02) #Set the coefficient of force-dependent-slip (FDS) for friction direction 2 c.setMu(self.FricMu) #Set the Coulomb friction coefficient j = ode.ContactJoint(world, contactgroup, c) j.name = None j.attach(geom1.getBody(), geom2.getBody())
Callback function for the collide() method. This function checks if the given geoms do collide and creates contact joints if they do.
_near_callback
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def step(self): """ Here the ode physics is calculated by one step. """ # call additional callback functions for all kinds of tasks (e.g. printing) self._printfunc() # Detect collisions and create contact joints self.space.collide((self.world, self.contactgroup), self._near_callback) # Simulation step self.world.step(float(self.dt)) # Remove all contact joints self.contactgroup.empty() # update all sensors for s in self.sensors: s._update() # update clients if self.render and self.updateDone: self.updateClients() if self.server.clients > 0 and self.realtime: time.sleep(self.dt) # increase step counter self.stepCounter += 1 return self.stepCounter
Here the ode physics is calculated by one step.
step
python
pybrain/pybrain
pybrain/rl/environments/ode/environment.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/environment.py
BSD-3-Clause
def _connect(self, world): """ Connects the sensor to the world and initializes the value list. """ Sensor._connect(self, world) # initialize object list - this should not change during runtime self._joints = [] self._parseJoints() # do initial update to get numValues self._update() self._numValues = len(self._values)
Connects the sensor to the world and initializes the value list.
_connect
python
pybrain/pybrain
pybrain/rl/environments/ode/sensors.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/sensors.py
BSD-3-Clause
def _connect(self, world): """ Connects the sensor to the world and initializes the value list. """ Sensor._connect(self, world) # initialize object list - this should not change during runtime self._joints = [] self._parseJoints() # do initial update to get numValues self._update() self._numValues = len(self._values)
Connects the sensor to the world and initializes the value list.
_connect
python
pybrain/pybrain
pybrain/rl/environments/ode/sensors.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/sensors.py
BSD-3-Clause
def _connect(self, world): """ Connects the sensor to the world and initializes the value list. """ Sensor._connect(self, world) # initialize object list - this should not change during runtime self._bodies = [] self._parseBodies() # do initial update to get numValues self._update() self._numValues = len(self._values)
Connects the sensor to the world and initializes the value list.
_connect
python
pybrain/pybrain
pybrain/rl/environments/ode/sensors.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/sensors.py
BSD-3-Clause
def init_GL(self, width=800, height=600): """ initialize OpenGL. This function has to be called only once before drawing. """ glutInit([]) # Open a window glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH) self.width = width self.height = height glutInitWindowPosition (500, 0) glutInitWindowSize (self.width, self.height) self._myWindow = glutCreateWindow ("ODE Viewer") # Initialize Viewport and Shading glViewport(0, 0, self.width, self.height) glShadeModel(GL_SMOOTH) glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) glClearColor(1.0, 1.0, 1.0, 0.0) # Initialize Depth Buffer glClearDepth(1.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) # Initialize Lighting glEnable(GL_LIGHTING) glLightfv(GL_LIGHT1, GL_AMBIENT, [0.5, 0.5, 0.5, 1.0]) glLightfv(GL_LIGHT1, GL_DIFFUSE, [1.0, 1.0, 1.0, 1.0]) glLightfv(GL_LIGHT1, GL_POSITION, [0.0, 5.0, 5.0, 1.0]) glEnable(GL_LIGHT1) # enable material coloring glEnable(GL_COLOR_MATERIAL) glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE) glEnable(GL_NORMALIZE)
initialize OpenGL. This function has to be called only once before drawing.
init_GL
python
pybrain/pybrain
pybrain/rl/environments/ode/viewer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/viewer.py
BSD-3-Clause
def prepare_GL(self): """Prepare drawing. This function is called in every step. It clears the screen and sets the new camera position""" # Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Projection mode glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective (45, 1.3333, 0.2, 500) # Initialize ModelView matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() # View transformation (if "centerOn(...)" is set, keep camera to specific object) if self.centerObj is not None: (centerX, centerY, centerZ) = self.centerObj.getPosition() else: centerX = centerY = centerZ = 0 # use the mouse to shift eye sensor on a hemisphere eyeX = self.viewDistance * self.lastx eyeY = self.viewDistance * self.lasty + centerY eyeZ = self.viewDistance * self.lastz gluLookAt (eyeX, eyeY, eyeZ, centerX, centerY, centerZ, 0, 1, 0)
Prepare drawing. This function is called in every step. It clears the screen and sets the new camera position
prepare_GL
python
pybrain/pybrain
pybrain/rl/environments/ode/viewer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/viewer.py
BSD-3-Clause
def draw_item(self, item): """ draws an object (spere, cube, plane, ...) """ glDisable(GL_TEXTURE_2D) glPushMatrix() if item['type'] in ['GeomBox', 'GeomSphere', 'GeomCylinder', 'GeomCCylinder']: # set color of object (currently dark gray) if 'color' in item: glEnable (GL_BLEND) glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glColor4f(*(item['color'])) else: glColor3f(0.1, 0.1, 0.1) # transform (rotate, translate) body accordingly (x, y, z) = item['position'] R = item['rotation'] rot = [R[0], R[3], R[6], 0.0, R[1], R[4], R[7], 0.0, R[2], R[5], R[8], 0.0, x, y, z, 1.0] glMultMatrixd(rot) # switch different geom objects if item['type'] == 'GeomBox': # cube (sx, sy, sz) = item['scale'] glScaled(sx, sy, sz) glutSolidCube(1) elif item['type'] == 'GeomSphere': # sphere glutSolidSphere(item['radius'], 20, 20) elif item['type'] == 'GeomCCylinder': quad = gluNewQuadric() # draw cylinder and two spheres, one at each end glTranslate(0.0, 0.0, -item['length'] / 2) gluCylinder(quad, item['radius'], item['radius'], item['length'], 32, 32) glutSolidSphere(item['radius'], 20, 20) glTranslate(0.0, 0.0, item['length']) glutSolidSphere(item['radius'], 20, 20) elif item['type'] == 'GeomCylinder': glTranslate(0.0, 0.0, -item['length'] / 2) quad = gluNewQuadric() gluDisk(quad, 0, item['radius'], 32, 1) quad = gluNewQuadric() gluCylinder(quad, item['radius'], item['radius'], item['length'], 32, 32) glTranslate(0.0, 0.0, item['length']) quad = gluNewQuadric() gluDisk(quad, 0, item['radius'], 32, 1) else: # TODO: add other geoms here pass elif item['type'] == 'GeomPlane': # set color of plane (currently green) if self.isFloorGreen: glColor3f(0.2, 0.6, 0.3) else: glColor3f(0.2, 0.3, 0.8) # for planes, we need a Quadric object quad = gluNewQuadric() gluQuadricTexture(quad, GL_TRUE) p = item['normal'] # the normal vector to the plane d = item['distance'] # the distance to the origin q = (0.0, 0.0, 1.0) # the normal vector of default gluDisks (z=0 plane) # calculate the cross product to get the rotation axis c = crossproduct(p, q) # calculate the angle between default normal q and plane normal p theta = acos(dotproduct(p, q) / (norm(p) * norm(q))) / pi * 180 # rotate the plane glPushMatrix() glTranslate(d * p[0], d * p[1], d * p[2]) glRotate(-theta, c[0], c[1], c[2]) gluDisk(quad, 0, 20, 20, 1) glPopMatrix() glPopMatrix()
draws an object (spere, cube, plane, ...)
draw_item
python
pybrain/pybrain
pybrain/rl/environments/ode/viewer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/viewer.py
BSD-3-Clause
def _screenshot(self, path_prefix='.', format='PNG'): """Saves a screenshot of the current frame buffer. The save path is <path_prefix>/.screenshots/shot<num>.png The path is automatically created if it does not exist. Shots are automatically numerated based on how many files are already in the directory.""" if self.counter == self.frameT: self.counter = 1 dir = os.path.join(path_prefix, 'screenshots') if not os.path.exists(dir): os.makedirs(dir) num_present = len(os.listdir(dir)) num_digits = len(str(num_present)) index = '0' * (5 - num_digits) + str(num_present) path = os.path.join(dir, 'shot' + index + '.' + format.lower()) glPixelStorei(GL_PACK_ALIGNMENT, 1) data = glReadPixels(0, 0, self.width, self.height, GL_RGB, GL_UNSIGNED_BYTE) image = Image.fromstring("RGB", (self.width, self.height), data) image = image.transpose(Image.FLIP_TOP_BOTTOM) image.save(path, format) print(('Image saved to %s' % (os.path.basename(path)))) else: self.counter += 1 self.isCapturing = False
Saves a screenshot of the current frame buffer. The save path is <path_prefix>/.screenshots/shot<num>.png The path is automatically created if it does not exist. Shots are automatically numerated based on how many files are already in the directory.
_screenshot
python
pybrain/pybrain
pybrain/rl/environments/ode/viewer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/viewer.py
BSD-3-Clause
def _near_callback(self, args, geom1, geom2): """Callback function for the collide() method. This function checks if the given geoms do collide and creates contact joints if they do.""" # only check parse list, if objects have name if geom1.name != None and geom2.name != None: # Preliminary checking, only collide with certain objects for p in self.passpairs: g1 = False g2 = False for x in p: g1 = g1 or (geom1.name.find(x) != -1) g2 = g2 or (geom2.name.find(x) != -1) if g1 and g2: return() # Check if the objects do collide contacts = ode.collide(geom1, geom2) tmpStr = geom2.name[:-2] handStr = geom1.name[:-1] if geom1.name == 'plate' and tmpStr != 'objectP': self.tableSum += len(contacts) if tmpStr == 'objectP' and handStr == 'pressLeft': if len(contacts) > 0: self.glasSum += 1 tmpStr = geom1.name[:-2] handStr = geom2.name[:-1] if geom2.name == 'plate' and tmpStr != 'objectP': self.tableSum += len(contacts) if tmpStr == 'objectP' and handStr == 'pressLeft': if len(contacts) > 0: self.glasSum += 1 # Create contact joints world, contactgroup = args for c in contacts: p = c.getContactGeomParams() # parameters from Niko Wolf c.setBounce(0.2) c.setBounceVel(0.05) #Set the minimum incoming velocity necessary for bounce c.setSoftERP(0.6) #Set the contact normal "softness" parameter c.setSoftCFM(0.00005) #Set the contact normal "softness" parameter c.setSlip1(0.02) #Set the coefficient of force-dependent-slip (FDS) for friction direction 1 c.setSlip2(0.02) #Set the coefficient of force-dependent-slip (FDS) for friction direction 2 c.setMu(self.FricMu) #Set the Coulomb friction coefficient j = ode.ContactJoint(world, contactgroup, c) j.name = None j.attach(geom1.getBody(), geom2.getBody())
Callback function for the collide() method. This function checks if the given geoms do collide and creates contact joints if they do.
_near_callback
python
pybrain/pybrain
pybrain/rl/environments/ode/instances/ccrl.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/instances/ccrl.py
BSD-3-Clause
def loadXODE(self, filename, reload=False): """ loads an XODE file (xml format) and parses it. """ f = open(filename) self._currentXODEfile = filename p = xode.parser.Parser() self.root = p.parseFile(f) f.close() try: # filter all xode "world" objects from root, take only the first one world = filter(lambda x: isinstance(x, xode.parser.World), self.root.getChildren())[0] except IndexError: # malicious format, no world tag found print(("no <world> tag found in " + filename + ". quitting.")) sys.exit() self.world = world.getODEObject() self._setWorldParameters() try: # filter all xode "space" objects from world, take only the first one space = filter(lambda x: isinstance(x, xode.parser.Space), world.getChildren())[0] except IndexError: # malicious format, no space tag found print(("no <space> tag found in " + filename + ". quitting.")) sys.exit() self.space = space.getODEObject() # load bodies and geoms for painting self.body_geom = [] self._parseBodies(self.root) for (body, _) in self.body_geom: if hasattr(body, 'name'): tmpStr = body.name[:-2] if tmpStr == "objectP": body.setPosition(body.getPosition() + self.pert) if self.verbosity > 0: print("-------[body/mass list]-----") for (body, _) in self.body_geom: try: print((body.name, body.getMass())) except AttributeError: print("<Nobody>") # now parse the additional parameters at the end of the xode file self.loadConfig(filename, reload)
loads an XODE file (xml format) and parses it.
loadXODE
python
pybrain/pybrain
pybrain/rl/environments/ode/instances/ccrl.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/instances/ccrl.py
BSD-3-Clause
def getObservation(self): """ a filtered mapping to getSample of the underlying environment. """ sensors = self.env.getSensors() #Sensor hand to target object for i in range(3): self.dist[i] = ((sensors[self.env.obsLen - 9 + i] + sensors[self.env.obsLen - 6 + i] + sensors[self.env.obsLen - 3 + i]) / 3.0 - (sensors[self.env.obsLen - 12 + i] + self.dif[i])) * 4.0 #sensors[self.env.obsLen-12+i] #Sensor hand angle to horizontal plane X-Axis for i in range(3): self.dist[i + 3] = (sensors[self.env.obsLen - 3 + i] - sensors[self.env.obsLen - 6 + i]) * 5.0 #Sensor hand angle to horizontal plane Y-Axis for i in range(3): self.dist[i + 6] = ((sensors[self.env.obsLen - 3 + i] + sensors[self.env.obsLen - 6 + i]) / 2.0 - sensors[self.env.obsLen - 9 + i]) * 10.0 if self.sensor_limits: sensors = self.normalize(sensors) sens = [] for i in range(self.env.obsLen - 12): sens.append(sensors[i]) for i in range(9): sens.append(self.dist[i]) for i in self.oldAction: sens.append(i) return sens
a filtered mapping to getSample of the underlying environment.
getObservation
python
pybrain/pybrain
pybrain/rl/environments/ode/tasks/ccrl.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tasks/ccrl.py
BSD-3-Clause
def getObservation(self): """ a filtered mapping to getSample of the underlying environment. """ sensors = self.env.getSensors() sensSort = [] #Angle and angleVelocity for i in range(32): sensSort.append(sensors[i]) #Angles wanted (old action) for i in self.oldAction: sensSort.append(i) #Hand position for i in range(3): sensSort.append((sensors[38 + i] + sensors[41 + i]) / 2) #Hand orientation (Hack - make correkt!!!!) sensSort.append((sensors[38] - sensors[41]) / 2 - sensors[35]) #pitch sensSort.append((sensors[38 + 1] - sensors[41 + 1]) / 2 - sensors[35 + 1]) #yaw sensSort.append((sensors[38 + 1] - sensors[41 + 1])) #roll #Target position for i in range(3): sensSort.append(self.target[i]) #Target orientation for i in range(3): sensSort.append(0.0) #Object type (start with random) sensSort.append(float(random.randint(-1, 1))) #roll #normalisation if self.sensor_limits: sensors = self.normalize(sensors) sens = [] for i in range(32): sens.append(sensors[i]) for i in range(29): sens.append(sensSort[i + 32]) #calc dist to target self.dist = array([(sens[54] - sens[48]), (sens[55] - sens[49]), (sens[56] - sens[50]), sens[51], sens[52], sens[53], sens[15]]) return sens
a filtered mapping to getSample of the underlying environment.
getObservation
python
pybrain/pybrain
pybrain/rl/environments/ode/tasks/ccrl.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tasks/ccrl.py
BSD-3-Clause
def getObservation(self): """ a filtered mapping to getSample of the underlying environment. """ sensors = self.env.getSensors() sensSort = [] #Angle and angleVelocity for i in range(32): sensSort.append(sensors[i]) #Angles wanted (old action) for i in self.oldAction: sensSort.append(i) #Hand position for i in range(3): sensSort.append((sensors[38 + i] + sensors[41 + i]) / 2) #Hand orientation (Hack - make correkt!!!!) sensSort.append((sensors[38] - sensors[41]) / 2 - sensors[35]) #pitch sensSort.append((sensors[38 + 1] - sensors[41 + 1]) / 2 - sensors[35 + 1]) #yaw sensSort.append((sensors[38 + 1] - sensors[41 + 1])) #roll #Target position for i in range(3): sensSort.append(self.target[i]) #Target orientation for i in range(3): sensSort.append(0.0) #Object type (start with random) sensSort.append(float(random.randint(-1, 1))) #roll #normalisation if self.sensor_limits: sensors = self.normalize(sensors) sens = [] for i in range(32): sens.append(sensors[i]) for i in range(29): sens.append(sensSort[i + 32]) #calc dist to target self.dist = array([(sens[54] - sens[48]) * 10.0, (sens[55] - sens[49]) * 10.0, (sens[56] - sens[50]) * 10.0, sens[51], sens[52], sens[53], 1.0 + sens[15]]) return sens
a filtered mapping to getSample of the underlying environment.
getObservation
python
pybrain/pybrain
pybrain/rl/environments/ode/tasks/ccrl.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tasks/ccrl.py
BSD-3-Clause
def __init__(self, name, attr=None): """create a new tag at the topmost level using given name and (optional) attribute dictionary""" # XML tag structure is a dictionary containing all attributes plus # two special tags: # myName = name of the tag # Icontain = list of XML tags this one encloses self.tag = {} self.tag['myName'] = name if attr is not None: self.tag.update(attr) # to traverse the XML hierarchy, store the current tag and # the previously visited ones. Start at the top level. self.top()
create a new tag at the topmost level using given name and (optional) attribute dictionary
__init__
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def insert(self, name, attr=None): """Insert a new tag into the current one. The name can be either the new tag name or an XMLstruct object (in which case attr is ignored). Unless name is None, we descend into the new tag as a side effect. A dictionary is expected for attr.""" if not self.current.hasSubtag(): self.current.tag['Icontain'] = [] if name == None: # empty subtag list inserted, return now # (this produces <tag></tag> in the output) return elif type(name) == str: # create a new subtag with given name and attributes newtag = XMLstruct(name, attr) else: # input assumed to be a tag structure newtag = name self.current.tag['Icontain'].append(newtag) self.stack.append(self.current) self.current = newtag
Insert a new tag into the current one. The name can be either the new tag name or an XMLstruct object (in which case attr is ignored). Unless name is None, we descend into the new tag as a side effect. A dictionary is expected for attr.
insert
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def insertMulti(self, attrlist): """Inserts multiple subtags at once. A list of XMLstruct objects must be given; the tag hierarchy is not descended into.""" if not self.current.hasSubtag(): self.current.tag['Icontain'] = [] self.current.tag['Icontain'] += attrlist
Inserts multiple subtags at once. A list of XMLstruct objects must be given; the tag hierarchy is not descended into.
insertMulti
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def downTo(self, name, stack=None, current=None): """Traverse downward from current tag, until given named tag is found. Returns true if found and sets stack and current tag correspondingly.""" if stack is None: stack = self.stack current = self.current if self.name == name: return(True) else: if not self.hasSubtag(): return(False) else: # descend one level stack.append(self) found = self.getSubtag(name) if found is None: # no subtag of correct name found; recursively check whether # any of the subtags contain the looked for tag for subtag in self.tag['Icontain']: found = subtag.downTo(name, stack, current) if found: # everything was updated recursively, need only return return(True) # nothing found, revert stack and return stack.pop() return(False) else: current.setCurrent(found) return(True)
Traverse downward from current tag, until given named tag is found. Returns true if found and sets stack and current tag correspondingly.
downTo
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def up(self, steps=1): """traverse upward a number of steps in tag stack""" for _ in range(steps): if self.stack != []: self.current = self.stack.pop()
traverse upward a number of steps in tag stack
up
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def hasSubtag(self, name=None): """determine whether current tag contains other tags, and returns the tag with a matching name (if name is given) or True (if not)""" if 'Icontain' in self.tag: if name is None: return(True) else: for subtag in self.tag['Icontain']: if subtag.name == name: return(True) return(False)
determine whether current tag contains other tags, and returns the tag with a matching name (if name is given) or True (if not)
hasSubtag
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def getSubtag(self, name=None): """determine whether current tag contains other tags, and returns the tag with a matching name (if name is given) or None (if not)""" if 'Icontain' in self.tag: for subtag in self.tag['Icontain']: if subtag.name == name: return(subtag) return(None)
determine whether current tag contains other tags, and returns the tag with a matching name (if name is given) or None (if not)
getSubtag
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def nbAttributes(self): """return number of user attributes the current tag has""" nAttr = len(list(self.tag.keys())) - 1 if self.hasSubtag(): nAttr -= 1 return nAttr
return number of user attributes the current tag has
nbAttributes
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def scale(self, sc, scaleset=set([]), exclude=set([])): """for all tags not in the exclude set, scale all attributes whose names are in scaleset by the given factor""" if self.name not in exclude: for name, val in self.tag.items(): if name in scaleset: self.tag[name] = val * sc if self.hasSubtag(): for subtag in self.tag['Icontain']: subtag.scale(sc, scaleset, exclude)
for all tags not in the exclude set, scale all attributes whose names are in scaleset by the given factor
scale
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def write(self, file, depth=0): """parse XML structure recursively and append to the output fileID, increasing the offset (tabs) while descending into the tree""" if 'myName' not in self.tag: print("Error parsing XML structure: Tag name missing!") sys.exit(1) # find number of attributes (disregarding special keys) nAttr = self.nbAttributes() endmark = '/>' if self.hasSubtag(): endmark = '>' # print(start tag, with attributes if present) if nAttr > 0: file.write(self._tab * depth + "<" + self.tag['myName'] + " " + \ ' '.join([name + '="' + str(val) + '"' for name, val in self.tag.items() \ if name != 'myName' and name != 'Icontain']) + endmark + '\n') else: file.write(self._tab * depth + "<" + self.tag['myName'] + ">\n") # print(enclosed tags, if any) if self.hasSubtag(): for subtag in self.tag['Icontain']: subtag.write(file, depth=depth + 1) # finalize tag file.write(self._tab * depth + "</" + self.tag['myName'] + ">\n")
parse XML structure recursively and append to the output fileID, increasing the offset (tabs) while descending into the tree
write
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xmltools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xmltools.py
BSD-3-Clause
def __init__(self, name, **kwargs): """initialize the XODE structure with a name and the world and space tags""" self._xodename = name self._centerOn = None self._affixToEnvironment = None # sensors is a list of ['type', [args], {kwargs}] self.sensors = [] # sensor elements is a list of joints to be used as pressure sensors self.sensorElements = [] self._nSensorElements = 0 self._pass = {} # dict of sets containing objects allowed to pass self._colors = [] # list of tuples ('name', (r,g,b)) XMLstruct.__init__(self, 'world') self.insert('space') # TODO: insert palm, support, etc. (derived class)
initialize the XODE structure with a name and the world and space tags
__init__
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def insertBody(self, bname, shape, size, density, pos=[0, 0, 0], passSet=None, euler=None, mass=None, color=None): """Inserts a body with the given custom name and one of the standard shapes. The size and pos parameters are given as xyz-lists or tuples. euler are three rotation angles (degrees), if mass is given, density is calculated automatically""" self.insert('body', {'name': bname}) if color is not None: self._colors.append((bname, color)) self.insert('transform') self.insert('position', {'x':pos[0], 'y':pos[1], 'z':pos[2]}) if euler is not None: self.up() self.insert('rotation') self.insert('euler', {'x':euler[0], 'y':euler[1], 'z':euler[2], 'aformat':'degrees'}) self.up() self.up(2) self.insert('mass') if shape == 'box': dims = {'sizex':size[0], 'sizey':size[1], 'sizez':size[2]} elif shape == 'cylinder' or shape == 'cappedCylinder': dims = {'radius':size[0], 'length':size[1]} elif shape == 'sphere': dims = {'radius':size[0]} else: print(("Unknown shape: " + shape + " not implemented!")) sys.exit(1) if mass is not None: density = self._mass2dens(shape, size, mass) self.insert('mass_shape', {'density': density}) self.insert(shape, dims) self.up(3) self.insert('geom') self.insert(shape, dims) self.up(3) # add the body to a matching pass set if passSet is not None: for pset in passSet: try: self._pass[pset].add(bname) except KeyError: self._pass[pset] = set([bname])
Inserts a body with the given custom name and one of the standard shapes. The size and pos parameters are given as xyz-lists or tuples. euler are three rotation angles (degrees), if mass is given, density is calculated automatically
insertBody
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def insertJoint(self, body1, body2, type, axis=None, anchor=(0, 0, 0), rel=False, name=None): """Inserts a joint of given type linking the two bodies. Default name is a "_"-concatenation of the body names. The anchor is a xyz-tuple, rel is a boolean specifying whether the anchor coordinates refer to the body's origin, axis parameters have to be provided as a dictionary.""" if name is None: name = body1 + "_" + body2 if rel: abs = 'false' else: abs = 'true' self.insert('joint', {'name': name }) self.insert('link1', {'body': body1}) self.up() self.insert('link2', {'body': body2}) self.up() self.insert(type) if type == 'fixed': self.insert(None) # empty subtag, seems to be needed by xode parser elif type == 'ball': self.insert('anchor', {'x':anchor[0], 'y':anchor[1], 'z':anchor[2], 'absolute':abs}) self.up() elif type == 'slider': self.insert('axis', axis) self.up() elif type == 'hinge': self.insert('axis', axis) self.up() self.insert('anchor', {'x':anchor[0], 'y':anchor[1], 'z':anchor[2], 'absolute':abs}) self.up() else: print(("Sorry, joint type " + type + " not yet implemented!")) sys.exit() self.up(2) return name
Inserts a joint of given type linking the two bodies. Default name is a "_"-concatenation of the body names. The anchor is a xyz-tuple, rel is a boolean specifying whether the anchor coordinates refer to the body's origin, axis parameters have to be provided as a dictionary.
insertJoint
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def insertFloor(self, y= -0.5): """inserts a bodiless floor at given y offset""" self.insert('geom', {'name': 'floor'}) self.insert('plane', {'a': 0, 'b': 1, 'c': 0, 'd': y}) self.up(2)
inserts a bodiless floor at given y offset
insertFloor
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def insertPressureSensorElement(self, parent, name=None, shape='cappedCylinder', size=[0.16, 0.5], pos=[0, 0, 0], euler=[0, 0, 0], dens=1, \ mass=None, passSet=[], stiff=10.0): """Insert one single pressure sensor element of the given shape, size, density, etc. The sliding axis is by default oriented along the z-axis, which is also the default for cylinder shapes. You have to rotate the sensor into the correct orientation - the sliding axis will be rotated accordingly. Stiffness of the sensor's spring is set via stiff, whereby damping is calculated automatically to prevent oscillations.""" if name is None: name = 'psens' + str(self._nSensorElements) if mass is None: mass = self._dens2mass(shape, size, dens) else: dens = self._mass2dens(shape, size, mass) self._nSensorElements += 1 h = 0.02 # temporal stepwidth self.insertBody(name, shape, size, dens, pos=pos, euler=euler, passSet=passSet) # In the aperiodic limit case, we have # kp = a kd^2 / 4m i.e. kd = 2 sqrt(m kp/a) # where kp is the spring constant, kd is the dampening constant, and m is the mass of the oscillator. # For practical purposes, it is often better if kp is a few percent stronger such that the sensor # resets itself faster (but still does not oscillate a lot), thus a~=1.02. # ERP = h kp / (h kp + kd) # CFM = 1 / (h kp + kd) = ERP / h kp # For assumed mass of finger of 0.5kg, kp=10, kd=4.5 is approx. the non-oscillatory case. kd = 2.0 * sqrt(mass * stiff / 1.02) ERP = h * stiff / (h * stiff + kd) CFM = ERP / (h * stiff) # Furthermore, compute the sliding axis direction from the Euler angles (x-convention, see # http://mathworld.wolfram.com/EulerAngles.html): Without rotation, the axis is along # the z axis, just like a cylinder's axis w = array(euler) * pi / 180 #A = matrix([[cos(w[0]), sin(w[0]), 0], [-sin(w[0]),cos(w[0]),0],[0,0,1]]) #A = matrix([[1,0,0], [0,cos(w[1]), sin(w[1])], [0, -sin(w[1]),cos(w[1])]]) * A #A = matrix([[cos(w[2]), sin(w[2]), 0], [-sin(w[2]),cos(w[2]),0],[0,0,1]]) * A # hmmm, it seems XODE is rather using the y-convention here: A = matrix([[-sin(w[0]), cos(w[0]), 0], [-cos(w[0]), -sin(w[0]), 0], [0, 0, 1]]) A = matrix([[1, 0, 0], [0, cos(w[1]), sin(w[1])], [0, -sin(w[1]), cos(w[1])]]) * A A = matrix([[sin(w[2]), -cos(w[2]), 0], [cos(w[2]), sin(w[2]), 0], [0, 0, 1]]) * A ax = ((A * matrix([0, 0, 1]).getT()).flatten().tolist())[0] jname = self.insertJoint(name, parent, 'slider', \ axis={'x':ax[0], 'y':ax[1], 'z':ax[2], "HiStop":0.0, "LowStop":0.0, "StopERP":ERP, "StopCFM":CFM }) self.sensorElements.append(jname) return name
Insert one single pressure sensor element of the given shape, size, density, etc. The sliding axis is by default oriented along the z-axis, which is also the default for cylinder shapes. You have to rotate the sensor into the correct orientation - the sliding axis will be rotated accordingly. Stiffness of the sensor's spring is set via stiff, whereby damping is calculated automatically to prevent oscillations.
insertPressureSensorElement
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def merge(self, xodefile, joinLevel='space'): """Merge a second XODE file into this one, at the specified level (which must exist in both files). The passpair lists are also joined. Upon return, the current tag for both objects is the one given.""" self.top() if not self.downTo(joinLevel): print(("Error: Cannot merge " + self.name + " at level " + joinLevel)) xodefile.top() if not xodefile.downTo(joinLevel): print(("Error: Cannot merge " + xodefile.name + " at level " + joinLevel)) self.insertMulti(xodefile.getCurrentSubtags()) self._pass.update(xodefile.getPassList())
Merge a second XODE file into this one, at the specified level (which must exist in both files). The passpair lists are also joined. Upon return, the current tag for both objects is the one given.
merge
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def scaleModel(self, sc): """scales all spatial dimensions by the given factor FIXME: quaternions may cause problems, which are currently ignored""" # scale these attributes... scaleset = set(['x', 'y', 'z', 'a', 'b', 'c', 'd', 'sizex', 'sizey', 'sizez', 'length', 'radius']) # ... unless contained in these tags (in which case they specify angles) exclude = set(['euler', 'finiteRotation', 'axisangle']) self.scale(sc, scaleset, exclude)
scales all spatial dimensions by the given factor FIXME: quaternions may cause problems, which are currently ignored
scaleModel
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def writeCustomParameters(self, f): """writes our custom parameters into an XML comment""" f.write('<!--odeenvironment parameters\n') if len(self._pass) > 0: f.write('<passpairs>\n') for pset in self._pass.values(): f.write(str(tuple(pset)) + '\n') if self._centerOn is not None: f.write('<centerOn>\n') f.write(self._centerOn + '\n') if self._affixToEnvironment is not None: f.write('<affixToEnvironment>\n') f.write(self._affixToEnvironment + '\n') if self._nSensorElements > 0: f.write('<sensors>\n') f.write("SpecificJointSensor(" + str(self.sensorElements) + ",name='PressureElements')\n") # compile all sensor commands for sensor in self.sensors: outstr = sensor[0] + "(" for val in sensor[1]: outstr += ',' + repr(val) for key, val in sensor[2].items(): outstr += ',' + key + '=' + repr(val) outstr = outstr.replace('(,', '(') + ")\n" f.write(outstr) if self._colors: f.write('<colors>\n') for col in self._colors: f.write(str(col) + "\n") f.write('<end>\n') f.write('-->\n')
writes our custom parameters into an XML comment
writeCustomParameters
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def writeXODE(self, filename=None): """writes the created structure (plus header and footer) to file with the given basename (.xode is appended)""" if filename is None: filename = self._xodename f = open(filename + '.xode', 'wb') # <-- wb here ensures Linux compatibility f.write('<?xml version="1.0" encoding="UTF-8"?>\n') f.write('<xode version="1.0r23" name="' + self._xodename + '"\n') f.write('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://tanksoftware.com/xode/1.0r23/xode.xsd">\n\n') self.write(f) f.write('</xode>\n') self.writeCustomParameters(f) f.close() print(("Wrote " + filename + '.xode'))
writes the created structure (plus header and footer) to file with the given basename (.xode is appended)
writeXODE
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def __init__(self, name, **kwargs): """Creates one finger on a fixed palm, and adds some sensors""" XODEfile.__init__(self, name, **kwargs) # create the hand and finger self.insertBody('palm', 'box', [10, 2, 10], 5, pos=[3.75, 4, 0], passSet=['pal']) self.insertBody('sample', 'box', [10, 0.2, 40], 5, pos=[0, 0.4, 0], passSet=['sam']) self.insertJoint('palm', 'sample', 'fixed', name='palm_support') self.insertJoint('palm', 'sample', 'slider', axis={'x':0, 'y':0, 'z':1, 'FMax':11000.0, "HiStop":100.0, "LowStop":-100.0}) self.insertBody('finger1_link0', 'cappedCylinder', [1, 7.5], 5, pos=[0, 4, 8.75], passSet=['pal', 'f1']) self.insertBody('finger1_link1', 'cappedCylinder', [1, 4], 5, pos=[0, 4, 14.5], passSet=['f1', 'f2']) self.insertBody('fingertip', 'cappedCylinder', [1, 2.9], 5, pos=[0, 4, 17.95], passSet=['f2', 'haptic']) self.insertJoint('palm', 'finger1_link0', 'hinge', \ axis={'x':-1, 'y':0, 'z':0, "HiStop":8, "LowStop":0.0}, anchor=(0, 4, 5)) self.insertJoint('finger1_link0', 'finger1_link1', 'hinge', \ axis={'x':-1, 'y':0, 'z':0, "HiStop":15, "LowStop":0.0}, anchor=(0, 4, 12.5)) self.insertJoint('finger1_link1', 'fingertip', 'hinge', \ axis={'x':-1, 'y':0, 'z':0, "HiStop":15, "LowStop":0.0}, anchor=(0, 4, 16.5)) self.centerOn('fingertip') self.affixToEnvironment('palm_support') self.insertFloor() # add one group of haptic sensors self._nSensorElements = 0 self.sensorElements = [] self.sensorGroupName = None self.insertHapticSensors() # give some structure to the sample self.insertSampleStructure(**kwargs)
Creates one finger on a fixed palm, and adds some sensors
__init__
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def insertHapticSensorsRandom(self): """insert haptic sensors at random locations""" self.sensorGroupName = 'haptic' for _ in range(5): self.insertHapticSensor(dx=random.uniform(-0.65, 0.65), dz=random.uniform(-0.4, 0.2)) ##self.insertHapticSensor(dx=-0.055)
insert haptic sensors at random locations
insertHapticSensorsRandom
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def insertHapticSensors(self): """insert haptic sensors at predetermined locations (check using testhapticsensorslocations.py)""" self.sensorGroupName = 'haptic' x = [0.28484253596392306, -0.59653176701550947, -0.36877718203650889, 0.50549219349016294, -0.22467390532644882, 0.051978612692656596, -0.18287341960589126, 0.40477910340060383, 0.56041266484490182, -0.47806390012776134] z = [-0.20354546253333045, -0.23178541627964597, 0.04632154813480549, -0.27525024891443889, -0.20352571063065863, -0.07930554411063101, 0.025260779785407084, 0.091906227805625964, -0.031751424859005839, -0.0034220681106161277] nSens = len(x) for _ in range(nSens): self.insertHapticSensor(dx=x.pop(), dz=z.pop())
insert haptic sensors at predetermined locations (check using testhapticsensorslocations.py)
insertHapticSensors
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def __init__(self, name, **kwargs): """Creates hand with fingertip and palm sensors -- palm up""" XODEfile.__init__(self, name, **kwargs) # create the hand and finger self.insertBody('palm', 'box', [10, 2, 10], 30, pos=[0, 0, 0], passSet=['pal']) self.insertBody('pressure', 'box', [8, 0.5, 8], 30, pos=[0, 1, 0], passSet=['pal']) self.insertBody('finger0_link0', 'cappedCylinder', [1, 7.5], 5, pos=[-8.75, 0, -2.5], euler=[0, 90, 0], passSet=['pal', 'f01']) self.insertBody('finger0_link1', 'cappedCylinder', [1, 4], 5, pos=[-14.5, 0, -2.5], euler=[0, 90, 0], passSet=['f01', 'f02']) self.insertBody('finger0_link2', 'cappedCylinder', [1, 2.9], 5, pos=[-17.95, 0, -2.5], euler=[0, 90, 0], passSet=['f02', 'f03']) self.insertBody('finger0_link3', 'sphere', [1], 5, pos=[-19, 0, -2.5], passSet=['f03']) self.insertBody('finger1_link0', 'cappedCylinder', [1, 7.5], 5, pos=[-3.75, 0, 8.75], passSet=['pal', 'f11']) self.insertBody('finger1_link1', 'cappedCylinder', [1, 4], 5, pos=[-3.75, 0, 14.5], passSet=['f11', 'f12']) self.insertBody('finger1_link2', 'cappedCylinder', [1, 2.9], 5, pos=[-3.75, 0, 17.95], passSet=['f12', 'f13']) self.insertBody('finger1_link3', 'sphere', [1], 5, pos=[-3.75, 0, 19], passSet=['f13']) self.insertBody('finger2_link0', 'cappedCylinder', [1, 7.5], 5, pos=[0, 0, 8.75], passSet=['pal', 'f21']) self.insertBody('finger2_link1', 'cappedCylinder', [1, 4], 5, pos=[0, 0, 14.5], passSet=['f21', 'f22']) self.insertBody('finger2_link2', 'cappedCylinder', [1, 2.9], 5, pos=[0, 0, 17.95], passSet=['f22', 'f23']) self.insertBody('finger2_link3', 'sphere', [1], 5, pos=[0, 0, 19], passSet=['f23']) self.insertBody('finger3_link0', 'cappedCylinder', [1, 7.5], 5, pos=[3.75, 0, 8.75], passSet=['pal', 'f31']) self.insertBody('finger3_link1', 'cappedCylinder', [1, 4], 5, pos=[3.75, 0, 14.5], passSet=['f31', 'f32']) self.insertBody('finger3_link2', 'cappedCylinder', [1, 2.9], 5, pos=[3.75, 0, 17.95], passSet=['f32', 'f33']) self.insertBody('finger3_link3', 'sphere', [1], 5, pos=[3.75, 0, 19], passSet=['f33']) self.insertJoint('palm', 'pressure', 'slider', axis={'x':0, 'y':1, 'z':0, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.insertJoint('palm', 'finger0_link0', 'hinge', axis={'x':0, 'y':0, 'z':1, "HiStop":1.5, "LowStop":0.0}, anchor=(-5, 0, -2.5)) self.insertJoint('finger0_link0', 'finger0_link1', 'hinge', axis={'x':0, 'y':0, 'z':1, "HiStop":1.5, "LowStop":0.0}, anchor=(-12.5, 0, -2.5)) self.insertJoint('finger0_link1', 'finger0_link2', 'hinge', axis={'x':0, 'y':0, 'z':1, "HiStop":1.5, "LowStop":0.0}, anchor=(-16.5, 0, -2.5)) self.insertJoint('finger0_link2', 'finger0_link3', 'slider', axis={'x':1, 'y':0, 'z':0, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.insertJoint('palm', 'finger1_link0', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(3.75, 0, 5)) self.insertJoint('finger1_link0', 'finger1_link1', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(3.75, 0, 12.5)) self.insertJoint('finger1_link1', 'finger1_link2', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(3.75, 0, 16.5)) self.insertJoint('finger1_link2', 'finger1_link3', 'slider', axis={'x':0, 'y':0, 'z':1, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.insertJoint('palm', 'finger2_link0', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(0, 0, 5)) self.insertJoint('finger2_link0', 'finger2_link1', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(0, 0, 12.5)) self.insertJoint('finger2_link1', 'finger2_link2', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(0, 0, 16.5)) self.insertJoint('finger2_link2', 'finger2_link3', 'slider', axis={'x':0, 'y':0, 'z':1, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.insertJoint('palm', 'finger3_link0', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(-3.75, 0, 5)) self.insertJoint('finger3_link0', 'finger3_link1', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(-3.75, 0, 12.5)) self.insertJoint('finger3_link1', 'finger3_link2', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(-3.75, 0, 16.5)) self.insertJoint('finger3_link2', 'finger3_link3', 'slider', axis={'x':0, 'y':0, 'z':1, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.centerOn('palm') self.insertFloor(y= -1) # add one group of haptic sensors self._nSensorElements = 0 self.sensorElements = [] self.sensorGroupName = None
Creates hand with fingertip and palm sensors -- palm up
__init__
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def __init__(self, name, **kwargs): """Creates hand with fingertip and palm sensors -- palm down""" XODEfile.__init__(self, name, **kwargs) # create the hand and finger self.insertBody('palm', 'box', [10, 2, 10], 10, pos=[0, 0, 0], passSet=['pal']) self.insertBody('pressure', 'box', [8, 0.5, 8], 10, pos=[0, -1, 0], passSet=['pal']) self.insertBody('finger0_link0', 'cappedCylinder', [1, 7.5], 5, pos=[-8.75, 0, -2.5], euler=[0, 90, 0], passSet=['pal', 'f01']) self.insertBody('finger0_link1', 'cappedCylinder', [1, 4], 5, pos=[-14.5, 0, -2.5], euler=[0, 90, 0], passSet=['f01', 'f02']) self.insertBody('finger0_link2', 'cappedCylinder', [1, 2.9], 5, pos=[-17.95, 0, -2.5], euler=[0, 90, 0], passSet=['f02', 'f03']) self.insertBody('finger0_link3', 'sphere', [1], 5, pos=[-19, 0, -2.5], passSet=['f03']) self.insertBody('finger1_link0', 'cappedCylinder', [1, 7.5], 5, pos=[-3.75, 0, 8.75], passSet=['pal', 'f11']) self.insertBody('finger1_link1', 'cappedCylinder', [1, 4], 5, pos=[-3.75, 0, 14.5], passSet=['f11', 'f12']) self.insertBody('finger1_link2', 'cappedCylinder', [1, 2.9], 5, pos=[-3.75, 0, 17.95], passSet=['f12', 'f13']) self.insertBody('finger1_link3', 'sphere', [1], 5, pos=[-3.75, 0, 19], passSet=['f13']) self.insertBody('finger2_link0', 'cappedCylinder', [1, 7.5], 5, pos=[0, 0, 8.75], passSet=['pal', 'f21']) self.insertBody('finger2_link1', 'cappedCylinder', [1, 4], 5, pos=[0, 0, 14.5], passSet=['f21', 'f22']) self.insertBody('finger2_link2', 'cappedCylinder', [1, 2.9], 5, pos=[0, 0, 17.95], passSet=['f22', 'f23']) self.insertBody('finger2_link3', 'sphere', [1], 5, pos=[0, 0, 19], passSet=['f23']) self.insertBody('finger3_link0', 'cappedCylinder', [1, 7.5], 5, pos=[3.75, 0, 8.75], passSet=['pal', 'f31']) self.insertBody('finger3_link1', 'cappedCylinder', [1, 4], 5, pos=[3.75, 0, 14.5], passSet=['f31', 'f32']) self.insertBody('finger3_link2', 'cappedCylinder', [1, 2.9], 5, pos=[3.75, 0, 17.95], passSet=['f32', 'f33']) self.insertBody('finger3_link3', 'sphere', [1], 5, pos=[3.75, 0, 19], passSet=['f33']) ## funny finger config with bestNetwork provided (try it ;) ##self.insertJoint('palm','pressure','slider', axis={'x':0,'y':-1,'z':0,"HiStop":0,"LowStop":-0.5, "StopERP":0.999,"StopCFM":0.002}) self.insertJoint('palm', 'pressure', 'slider', axis={'x':0, 'y':1, 'z':0, "HiStop":0, "LowStop":0, "StopERP":0.999, "StopCFM":0.002}) self.insertJoint('palm', 'finger0_link0', 'hinge', axis={'x':0, 'y':0, 'z':-1, "HiStop":1.5, "LowStop":0.0}, anchor=(-5, 0, -2.5)) self.insertJoint('finger0_link0', 'finger0_link1', 'hinge', axis={'x':0, 'y':0, 'z':-1, "HiStop":1.5, "LowStop":0.0}, anchor=(-12.5, 0, -2.5)) self.insertJoint('finger0_link1', 'finger0_link2', 'hinge', axis={'x':0, 'y':0, 'z':-1, "HiStop":1.5, "LowStop":0.0}, anchor=(-16.5, 0, -2.5)) self.insertJoint('finger0_link2', 'finger0_link3', 'slider', axis={'x':1, 'y':0, 'z':0, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.insertJoint('palm', 'finger1_link0', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(3.75, 0, 5)) self.insertJoint('finger1_link0', 'finger1_link1', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(3.75, 0, 12.5)) self.insertJoint('finger1_link1', 'finger1_link2', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(3.75, 0, 16.5)) self.insertJoint('finger1_link2', 'finger1_link3', 'slider', axis={'x':0, 'y':0, 'z':1, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.insertJoint('palm', 'finger2_link0', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(0, 0, 5)) self.insertJoint('finger2_link0', 'finger2_link1', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(0, 0, 12.5)) self.insertJoint('finger2_link1', 'finger2_link2', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(0, 0, 16.5)) self.insertJoint('finger2_link2', 'finger2_link3', 'slider', axis={'x':0, 'y':0, 'z':1, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.insertJoint('palm', 'finger3_link0', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(-3.75, 0, 5)) self.insertJoint('finger3_link0', 'finger3_link1', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(-3.75, 0, 12.5)) self.insertJoint('finger3_link1', 'finger3_link2', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(-3.75, 0, 16.5)) self.insertJoint('finger3_link2', 'finger3_link3', 'slider', axis={'x':0, 'y':0, 'z':1, "HiStop":0, "LowStop":-0.5, "StopERP":0.999, "StopCFM":0.002}) self.centerOn('palm') self.insertFloor(y= -1.25) # add one group of haptic sensors self._nSensorElements = 0 self.sensorElements = [] self.sensorGroupName = None
Creates hand with fingertip and palm sensors -- palm down
__init__
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def insertSampleStructure(self, angle=30, std=0.05, dist=0.9, **kwargs): """create some ridges on the sample""" for i in range(16): name = 'ridge' + str(i) self.insertBody(name, 'cappedCylinder', [0.2, 10], 5, pos=[0, 0.5, random.gauss(15 - dist * i, std)], euler=[0, angle, 0], passSet=['sam']) self.insertJoint('sample', name, 'fixed')
create some ridges on the sample
insertSampleStructure
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def insertSampleStructure(self, xoffs=0.0, std=0.025, dist=0.9, **kwargs): """create four rows of spheres on the sample""" dx = [dist * k for k in [-1, 0, 1]] dz = [dist * k * 0.5 for k in [0, 1, 0]] for i in range(16): for k in range(3): x = random.gauss(dx[k] + xoffs, std) z = random.gauss(15 - dist * i + dz[k], std) name = 'sphere' + str(i) + str(k) self.insertBody(name, 'sphere', [0.2], 5, pos=[x, 0.5, z], passSet=['sam']) self.insertJoint('sample', name, 'fixed')
create four rows of spheres on the sample
insertSampleStructure
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def __init__(self, name, **kwargs): """Creates hand with fingertip and palm sensors -- palm up""" XODEfile.__init__(self, name, **kwargs) # create the hand and finger self.insertBody('palm', 'box', [4.12, 3.0, 2], 30, pos=[0, 0, 0], passSet=['total'], mass=3.356) self.insertBody('neck', 'cappedCylinder', [0.25, 5.6], 5, pos=[0, 2.8, 0], euler=[90, 0, 0], passSet=['total'], mass=0.1) self.insertBody('head', 'box', [3.0, 1.2, 1.5], 30, pos=[0, 4.0, 0], passSet=['total'], mass=0.1) self.insertBody('arm_left', 'cappedCylinder', [0.25, 7.5], 5, pos=[2.06, -2.89, 0], euler=[90, 0, 0], passSet=['total'], mass=2.473) self.insertBody('arm_right', 'cappedCylinder', [0.25, 7.5], 5, pos=[-2.06, -2.89, 0], euler=[90, 0, 0], passSet=['total'], mass=2.473) self.insertBody('hip', 'cappedCylinder', [0.25, 3.2], 5, pos=[0, -1.6, 0], euler=[90, 0, 0], passSet=['total'], mass=0.192) self.insertBody('pelvis', 'cappedCylinder', [0.25, 2.4], 5, pos=[0, -3.2, 0], euler=[0, 90, 0], passSet=['total'], mass=1.0) self.insertBody('pelLeft', 'cappedCylinder', [0.25, 0.8], 5, pos=[1.2, -3.6, 0], euler=[90, 0, 0], passSet=['total'], mass=2.567) self.insertBody('pelRight', 'cappedCylinder', [0.25, 0.8], 5, pos=[-1.2, -3.6, 0], euler=[90, 0, 0], passSet=['total'], mass=2.567) self.insertBody('tibiaLeft', 'cappedCylinder', [0.25, 4.4], 5, pos=[1.2, -6.2, 0], euler=[90, 0, 0], passSet=['total'], mass=5.024) self.insertBody('tibiaRight', 'cappedCylinder', [0.25, 4.4], 5, pos=[-1.2, -6.2, 0], euler=[90, 0, 0], passSet=['total'], mass=5.024) self.insertBody('sheenLeft', 'cappedCylinder', [0.25, 3.8], 5, pos=[1.2, -10.3, 0], euler=[90, 0, 0], passSet=['total'], mass=3.236) self.insertBody('sheenRight', 'cappedCylinder', [0.25, 3.8], 5, pos=[-1.2, -10.3, 0], euler=[90, 0, 0], passSet=['total'], mass=3.236) self.insertBody('footLeft', 'box', [2.2, 0.4, 2.6], 3, pos=[1.2, -12.2, 0.75], passSet=['total'], mass=1.801) self.insertBody('footRight', 'box', [2.2, 0.4, 2.6], 3, pos=[-1.2, -12.2, 0.75], passSet=['total'], mass=1.801) self.insertJoint('palm', 'neck', 'fixed', axis={'x':0, 'y':0, 'z':0}, anchor=(0, 0, 0)) self.insertJoint('neck', 'head', 'fixed', axis={'x':0, 'y':0, 'z':0}, anchor=(0, 2.8, 0)) self.insertJoint('palm', 'arm_left', 'hinge', axis={'x':1, 'y':0, 'z':0}, anchor=(2.06, 0.86, 0)) self.insertJoint('palm', 'arm_right', 'hinge', axis={'x':1, 'y':0, 'z':0}, anchor=(-2.06, 0.86, 0)) self.insertJoint('palm', 'hip', 'hinge', axis={'x':0, 'y':1, 'z':0, "HiStop":0.5, "LowStop":-0.5}, anchor=(0, -1.6, 0)) self.insertJoint('hip', 'pelvis', 'fixed', axis={'x':0, 'y':0, 'z':0}, anchor=(0, -3.2, 0)) self.insertJoint('pelvis', 'pelLeft', 'hinge', axis={'x':0, 'y':0, 'z':-1, "HiStop":0.5, "LowStop":0.0}, anchor=(1.2, -3.2, 0)) self.insertJoint('pelvis', 'pelRight', 'hinge', axis={'x':0, 'y':0, 'z':1, "HiStop":0.5, "LowStop":0.0}, anchor=(-1.2, -3.2, 0)) self.insertJoint('pelLeft', 'tibiaLeft', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(1.2, -4.0, 0)) self.insertJoint('pelRight', 'tibiaRight', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(-1.2, -4.0, 0)) self.insertJoint('tibiaLeft', 'sheenLeft', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(1.2, -8.4, 0)) self.insertJoint('tibiaRight', 'sheenRight', 'hinge', axis={'x':-1, 'y':0, 'z':0, "HiStop":1.5, "LowStop":0.0}, anchor=(-1.2, -8.4, 0)) self.insertJoint('sheenLeft', 'footLeft', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":0.25, "LowStop":-0.25}, anchor=(1.2, -12.2, 0)) self.insertJoint('sheenRight', 'footRight', 'hinge', axis={'x':1, 'y':0, 'z':0, "HiStop":0.25, "LowStop":-0.25}, anchor=(-1.2, -12.2, 0)) self.centerOn('palm') self.insertFloor(y= -12.7) # add one group of haptic sensors self._nSensorElements = 0 self.sensorElements = [] self.sensorGroupName = None
Creates hand with fingertip and palm sensors -- palm up
__init__
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def __init__(self, name, **kwargs): """Creates hand with fingertip and palm sensors -- palm up""" XODEfile.__init__(self, name, **kwargs) # create the hand and finger self.insertBody('body', 'box', [7.0, 16.0, 10.0], 30, pos=[0, 0, 2.0], passSet=['total'], mass=15.0, color=(0.5, 0.5, 0.4, 1.0)) #right arm self.insertBody('shoulderUpRight', 'cappedCylinder', [0.5, 2.0], 5, pos=[2.5, 7.0, -3.5], euler=[0, 90, 0], passSet=['rightSh', 'total'], mass=0.25) self.insertBody('shoulderLRRight', 'cappedCylinder', [0.5, 2.0], 5, pos=[3.5, 6.0, -3.5], euler=[90, 0, 0], passSet=['rightSh'], mass=0.25) self.insertBody('shoulderPRRight', 'cappedCylinder', [0.5, 2.0], 5, pos=[3.5, 4.0, -3.5], euler=[90, 0, 0], passSet=['rightSh'], mass=0.25) self.insertBody('armUpRight', 'cappedCylinder', [0.5, 2.0], 5, pos=[3.5, 2.0, -3.5], euler=[90, 0, 0], passSet=['rightAr', 'rightSh'], mass=0.25) self.insertBody('armPRRight', 'cappedCylinder', [0.5, 2.0], 5, pos=[3.5, 0.0, -3.5], euler=[90, 0, 0], passSet=['rightAr'], mass=0.25) self.insertBody('handUpRight', 'cappedCylinder', [0.5, 2.0], 5, pos=[3.5, -2.0, -3.5], euler=[90, 0, 0], passSet=['rightAr', 'rightHa'], mass=0.25) #right hand self.insertBody('palmRight', 'box', [1.5, 0.25, 0.5], 30, pos=[3.5, -3.0, -3.5], passSet=['rightHa'], mass=0.1, color=(0.6, 0.6, 0.3, 1.0)) self.insertBody('fingerRight1', 'box', [0.25, 1.0, 0.5], 30, pos=[4.0, -3.5, -3.5], passSet=['rightHa'], mass=0.1, color=(0.6, 0.6, 0.3, 1.0)) self.insertBody('fingerRight2', 'box', [0.25, 1.0, 0.5], 30, pos=[3.0, -3.5, -3.5], passSet=['rightHa'], mass=0.1, color=(0.6, 0.6, 0.3, 1.0)) #left arm self.insertBody('shoulderUpLeft', 'cappedCylinder', [0.5, 2.0], 5, pos=[-2.5, 7.0, -3.5], euler=[0, 90, 0], passSet=['leftSh', 'total'], mass=0.25) self.insertBody('shoulderLRLeft', 'cappedCylinder', [0.5, 2.0], 5, pos=[-3.5, 6.0, -3.5], euler=[90, 0, 0], passSet=['leftSh'], mass=0.25) self.insertBody('shoulderPRLeft', 'cappedCylinder', [0.5, 2.0], 5, pos=[-3.5, 4.0, -3.5], euler=[90, 0, 0], passSet=['leftSh'], mass=0.25) self.insertBody('armUpLeft', 'cappedCylinder', [0.5, 2.0], 5, pos=[-3.5, 2.0, -3.5], euler=[90, 0, 0], passSet=['leftAr', 'leftSh'], mass=0.25) self.insertBody('armPRLeft', 'cappedCylinder', [0.5, 2.0], 5, pos=[-3.5, 0.0, -3.5], euler=[90, 0, 0], passSet=['leftAr'], mass=0.25) self.insertBody('handUpLeft', 'cappedCylinder', [0.5, 2.0], 5, pos=[-3.5, -2.0, -3.5], euler=[90, 0, 0], passSet=['leftAr', 'leftHa'], mass=0.25) #left hand self.insertBody('palmLeft', 'box', [1.5, 0.25, 0.5], 30, pos=[-3.5, -3.0, -3.5], passSet=['leftHa'], mass=0.1, color=(0.6, 0.6, 0.3, 1.0)) self.insertBody('fingerLeft1', 'box', [0.25, 1.0, 0.5], 30, pos=[-4.0, -3.5, -3.5], passSet=['leftHa'], mass=0.1, color=(0.6, 0.6, 0.3, 1.0)) self.insertBody('fingerLeft2', 'box', [0.25, 1.0, 0.5], 30, pos=[-3.0, -3.5, -3.5], passSet=['leftHa'], mass=0.1, color=(0.6, 0.6, 0.3, 1.0)) #Joints right self.insertJoint('body', 'shoulderUpRight', 'hinge', axis={'x':1, 'y':0, 'z':0}, anchor=(2.5, 7.0, -3.5)) self.insertJoint('shoulderUpRight', 'shoulderLRRight', 'hinge', axis={'x':0, 'y':0, 'z':1}, anchor=(3.5, 7.0, -3.5)) self.insertJoint('shoulderLRRight', 'shoulderPRRight', 'hinge', axis={'x':0, 'y':1, 'z':0}, anchor=(3.5, 5.0, -3.5)) self.insertJoint('shoulderPRRight', 'armUpRight', 'hinge', axis={'x':1, 'y':0, 'z':0}, anchor=(3.5, 3.0, -3.5)) self.insertJoint('armUpRight', 'armPRRight', 'hinge', axis={'x':0, 'y':1, 'z':0}, anchor=(3.5, 1.0, -3.5)) self.insertJoint('armPRRight', 'handUpRight', 'hinge', axis={'x':1, 'y':0, 'z':0}, anchor=(3.5, -1.0, -3.5)) self.insertJoint('handUpRight', 'palmRight', 'hinge', axis={'x':0, 'y':1, 'z':0}, anchor=(3.5, -3.0, -3.5)) self.insertJoint('palmRight', 'fingerRight1', 'fixed', axis={'x':0, 'y':0, 'z':0}, anchor=(4.0, -3.5, -3.5)) self.insertJoint('palmRight', 'fingerRight2', 'hinge', axis={'x':0, 'y':0, 'z':1}, anchor=(3.0, -3.0, -3.5)) #Joints left self.insertJoint('body', 'shoulderUpLeft', 'hinge', axis={'x':1, 'y':0, 'z':0}, anchor=(-2.5, 7.0, -3.5)) self.insertJoint('shoulderUpLeft', 'shoulderLRLeft', 'hinge', axis={'x':0, 'y':0, 'z':1}, anchor=(-3.5, 7.0, -3.5)) self.insertJoint('shoulderLRLeft', 'shoulderPRLeft', 'hinge', axis={'x':0, 'y':1, 'z':0}, anchor=(-3.5, 5.0, -3.5)) self.insertJoint('shoulderPRLeft', 'armUpLeft', 'hinge', axis={'x':1, 'y':0, 'z':0}, anchor=(-3.5, 3.0, -3.5)) self.insertJoint('armUpLeft', 'armPRLeft', 'hinge', axis={'x':0, 'y':1, 'z':0}, anchor=(-3.5, 1.0, -3.5)) self.insertJoint('armPRLeft', 'handUpLeft', 'hinge', axis={'x':1, 'y':0, 'z':0}, anchor=(-3.5, -1.0, -3.5)) self.insertJoint('handUpLeft', 'palmLeft', 'hinge', axis={'x':0, 'y':1, 'z':0}, anchor=(-3.5, -3.0, -3.5)) self.insertJoint('palmLeft', 'fingerLeft1', 'fixed', axis={'x':0, 'y':0, 'z':0}, anchor=(-4.0, -3.5, -3.5)) self.insertJoint('palmLeft', 'fingerLeft2', 'hinge', axis={'x':0, 'y':0, 'z':1}, anchor=(-3.0, -3.0, -3.5)) self.centerOn('body') self.insertFloor(y= -8.0) # add one group of haptic sensors self._nSensorElements = 0 self.sensorElements = [] self.sensorGroupName = None
Creates hand with fingertip and palm sensors -- palm up
__init__
python
pybrain/pybrain
pybrain/rl/environments/ode/tools/xodetools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/tools/xodetools.py
BSD-3-Clause
def _setObject(self, kclass, **kwargs): """ Create the Geom object and apply transforms. Only call for placeable Geoms. """ if (self._body is None): # The Geom is independant so it can have its own transform kwargs['space'] = self._space obj = kclass(**kwargs) t = self.getTransform() obj.setPosition(t.getPosition()) obj.setRotation(t.getRotation()) self.setODEObject(obj) elif (self._transformed): # The Geom is attached to a body so to transform it, it must # by placed in a GeomTransform and its transform is relative # to the body. kwargs['space'] = None obj = kclass(**kwargs) t = self.getTransform(self._body) obj.setPosition(t.getPosition()) obj.setRotation(t.getRotation()) trans = ode.GeomTransform(self._space) trans.setGeom(obj) trans.setBody(self._body.getODEObject()) self.setODEObject(trans) else: kwargs['space'] = self._space obj = kclass(**kwargs) obj.setBody(self._body.getODEObject()) self.setODEObject(obj)
Create the Geom object and apply transforms. Only call for placeable Geoms.
_setObject
python
pybrain/pybrain
pybrain/rl/environments/ode/xode_changes/geom.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/ode/xode_changes/geom.py
BSD-3-Clause
def __init__(self, env=None, maxsteps=1000): """ :key env: (optional) an instance of a ShipSteeringEnvironment (or a subclass thereof) :key maxsteps: maximal number of steps (default: 1000) """ if env == None: env = ShipSteeringEnvironment(render=False) EpisodicTask.__init__(self, env) self.N = maxsteps self.t = 0 # scale sensors # [h, hdot, v] self.sensor_limits = [(-180.0, +180.0), (-180.0, +180.0), (-10.0, +40.0)] # actions: thrust, rudder self.actor_limits = [(-1.0, +2.0), (-90.0, +90.0)] # scale reward over episode, such that max. return = 100 self.rewardscale = 100. / maxsteps / self.sensor_limits[2][1]
:key env: (optional) an instance of a ShipSteeringEnvironment (or a subclass thereof) :key maxsteps: maximal number of steps (default: 1000)
__init__
python
pybrain/pybrain
pybrain/rl/environments/shipsteer/northwardtask.py
https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/shipsteer/northwardtask.py
BSD-3-Clause