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 _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... | 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... | 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 sen... | 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 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 ... | 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:
... | 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):
s... | 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:
... | 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_cal... | 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
... | 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
glutInitWi... | 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()
... | 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:
... | 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... | 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 __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... | 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... | 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.na... | 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 ... | 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)
... | 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:
sel... | 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)
# fi... | 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 = []
... | 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),... | 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 ref... | 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 a... | 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.
St... | 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.... | 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'])
# .... | 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')
... | 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... | 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', 'bo... | 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.05197861269... | 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'... | 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', 'bo... | 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], p... | 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... | 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 _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 ... |
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)
Episod... |
: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 |
def step(self):
""" integrate state using simple rectangle rule """
thrust = float(self.action[0])
rudder = float(self.action[1])
h, hdot, v = self.sensors
rnd = random.normal(0, 1.0, size=3)
thrust = min(max(thrust, -1), +2)
rudder = min(max(rudder, -90), +90)
... | integrate state using simple rectangle rule | step | python | pybrain/pybrain | pybrain/rl/environments/shipsteer/shipsteer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/shipsteer/shipsteer.py | BSD-3-Clause |
def reset(self):
""" re-initializes the environment, setting the ship to rest at a random orientation.
"""
# [h, hdot, v]
self.sensors = [random.uniform(-30., 30.), 0.0, 0.0]
if self.render:
if self.server.clients > 0:
... | re-initializes the environment, setting the ship to rest at a random orientation.
| reset | python | pybrain/pybrain | pybrain/rl/environments/shipsteer/shipsteer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/shipsteer/shipsteer.py | BSD-3-Clause |
def performAction(self, action):
""" stores the desired action for the next time step.
"""
self.action = action
self.step()
if self.render:
if self.updateDone:
self.updateRenderer()
if self.server.clients > 0:
sleep(... | stores the desired action for the next time step.
| performAction | python | pybrain/pybrain | pybrain/rl/environments/shipsteer/shipsteer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/shipsteer/shipsteer.py | BSD-3-Clause |
def __init__(self, size, suicideenabled=True):
""" the size of the board is generally between 3 and 19. """
self.size = size
self.suicideenabled = suicideenabled
self.reset() | the size of the board is generally between 3 and 19. | __init__ | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def _iterPos(self):
""" an iterator over all the positions of the board. """
for i in range(self.size):
for j in range(self.size):
yield (i, j) | an iterator over all the positions of the board. | _iterPos | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def getBoardArray(self):
""" an array with two boolean values per position, indicating
'white stone present' and 'black stone present' respectively. """
a = zeros(self.outdim)
for i, p in enumerate(self._iterPos()):
if self.b[p] == self.WHITE:
a[2 * i] = 1
... | an array with two boolean values per position, indicating
'white stone present' and 'black stone present' respectively. | getBoardArray | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def doMove(self, c, pos):
""" the action is a (color, position) tuple, for the next stone to move.
returns True if the move was legal. """
self.movesDone += 1
if pos == 'resign':
self.winner = -c
return True
elif not self.isLegal(c, pos):
retur... | the action is a (color, position) tuple, for the next stone to move.
returns True if the move was legal. | doMove | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def _setStone(self, c, pos):
""" set stone, and update liberties and groups. """
self.b[pos] = c
merge = False
self.groups[pos] = self.size * pos[0] + pos[1]
freen = [n for n in self._neighbors(pos) if self.b[n] == self.EMPTY]
self.liberties[self.groups[pos]] = set(freen)... | set stone, and update liberties and groups. | _setStone | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def _suicide(self, c, pos):
""" would putting a stone here be suicide for c? """
# any free neighbors?
for n in self._neighbors(pos):
if self.b[n] == self.EMPTY:
return False
# any friendly neighbor with extra liberties?
for n in self._neighbors(pos):... | would putting a stone here be suicide for c? | _suicide | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def _capture(self, c, pos):
""" would putting a stone here lead to a capture? """
for n in self._neighbors(pos):
if self.b[n] == -c:
if len(self.liberties[self.groups[n]]) == 1:
return True
return False | would putting a stone here lead to a capture? | _capture | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def getLiberties(self, pos):
""" how many liberties does the stone at pos have? """
if self.b[pos] == self.EMPTY:
return None
return len(self.liberties[self.groups[pos]]) | how many liberties does the stone at pos have? | getLiberties | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def getGroupSize(self, pos):
""" what size is the worm that this stone is part of? """
if self.b[pos] == self.EMPTY:
return None
g = self.groups[pos]
return len([x for x in list(self.groups.values()) if x == g]) | what size is the worm that this stone is part of? | getGroupSize | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def randomBoard(self, nbmoves):
""" produce a random, undecided and legal capture-game board, after at most nbmoves.
:return: the number of moves actually done. """
c = self.BLACK
self.reset()
for i in range(nbmoves):
l = set(self.getAcceptable(c))
l.diffe... | produce a random, undecided and legal capture-game board, after at most nbmoves.
:return: the number of moves actually done. | randomBoard | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def playToTheEnd(self, p1, p2):
""" alternate playing moves between players until the game is over. """
assert p1.color == -p2.color
i = 0
p1.game = self
p2.game = self
players = [p1, p2]
while not self.gameOver():
p = players[i]
self.perfo... | alternate playing moves between players until the game is over. | playToTheEnd | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegame.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegame.py | BSD-3-Clause |
def __init__(self, size):
""" the size of the board is a tuple, where each dimension must be minimum 5. """
self.size = size
assert size[0] >= 5
assert size[1] >= 5
self.reset() | the size of the board is a tuple, where each dimension must be minimum 5. | __init__ | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def _fiveRow(self, color, pos):
""" Is this placement the 5th in a row? """
# TODO: more efficient...
for dir in [(0, 1), (1, 0), (1, 1), (1, -1)]:
found = 1
for d in [-1, 1]:
for i in range(1, 5):
next = (pos[0] + dir[0] * i * d, pos[1... | Is this placement the 5th in a row? | _fiveRow | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def getBoardArray(self):
""" an array with thow boolean values per position, indicating
'white stone present' and 'black stone present' respectively. """
a = zeros(self.outdim)
for i, p in enumerate(self._iterPos()):
if self.b[p] == self.WHITE:
a[2 * i] = 1
... | an array with thow boolean values per position, indicating
'white stone present' and 'black stone present' respectively. | getBoardArray | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/gomoku.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/gomoku.py | BSD-3-Clause |
def getKilling(self, c):
""" return all legal positions for a color that immediately kill the opponent. """
res = GomokuGame.getKilling(self, c)
for p in self.getLegals(c):
k = self._killsWhich(c, p)
if self.pairsTaken[c] + len(k) / 2 >= 5:
res.append(p)
... | return all legal positions for a color that immediately kill the opponent. | getKilling | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/pente.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/pente.py | BSD-3-Clause |
def _killsWhich(self, c, pos):
""" placing a stone of color c at pos would kill which enemy stones? """
res = []
for dir in [(0, 1), (1, 0), (1, 1), (1, -1)]:
for d in [-1, 1]:
killcands = []
for i in [1, 2, 3]:
next = (pos[0] + dir... | placing a stone of color c at pos would kill which enemy stones? | _killsWhich | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/pente.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/pente.py | BSD-3-Clause |
def _setStone(self, c, pos, tokill=None):
""" set stone, and potentially kill stones. """
if tokill == None:
tokill = self._killsWhich(c, pos)
GomokuGame._setStone(self, c, pos)
for p in tokill:
self.b[p] = self.EMPTY
self.pairsTaken[c] += len(tokill) // 2 | set stone, and potentially kill stones. | _setStone | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/pente.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/pente.py | BSD-3-Clause |
def getAction(self):
""" get suggested action, return them if they are legal, otherwise choose randomly. """
ba = self.game.getBoardArray()
# network is given inputs with self/other as input, not black/white
if self.color != CaptureGame.BLACK:
# invert values
tmp ... | get suggested action, return them if they are legal, otherwise choose randomly. | getAction | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegameplayers/moduledecision.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegameplayers/moduledecision.py | BSD-3-Clause |
def _legalizeIt(self, a):
""" draw index from an array of values, filtering out illegal moves. """
if not min(a) >= 0:
print(a)
print((min(a)))
print((self.module.params))
print((self.module.inputbuffer))
print((self.module.outputbuffer))
... | draw index from an array of values, filtering out illegal moves. | _legalizeIt | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/capturegameplayers/moduledecision.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/capturegameplayers/moduledecision.py | BSD-3-Clause |
def getReward(self):
""" Final positive reward for winner, negative for loser. """
if self.isFinished():
win = (self.env.winner != self.opponent.color)
moves = self.env.movesDone
res = self.winnerReward - self.numMovesCoeff * (moves -self.minmoves)/(self.maxmoves-self... | Final positive reward for winner, negative for loser. | getReward | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/capturetask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/capturetask.py | BSD-3-Clause |
def f(self, x):
""" If a module is given, wrap it into a ModuleDecidingAgent before evaluating it.
Also, if applicable, average the result over multiple games. """
if isinstance(x, Module):
agent = ModuleDecidingPlayer(x, self.env, greedySelection = True)
elif isinstance(x, C... | If a module is given, wrap it into a ModuleDecidingAgent before evaluating it.
Also, if applicable, average the result over multiple games. | f | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/capturetask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/capturetask.py | BSD-3-Clause |
def goUp(self, h):
""" ready to go up one handicap? """
if self.results[h][1] >= self.minEvals:
return self.winProp(h) > 0.6
return False | ready to go up one handicap? | goUp | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/handicaptask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/handicaptask.py | BSD-3-Clause |
def goDown(self, h):
""" have to go down one handicap? """
if self.results[h][1] >= self.minEvals:
return self.winProp(h) < -0.6
return False | have to go down one handicap? | goDown | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/handicaptask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/handicaptask.py | BSD-3-Clause |
def _oneGame(self, preset = None):
""" a single black stone can be set as the first move. """
self.env.reset()
if preset != None:
self.env._setStone(GomokuGame.BLACK, preset)
self.env.movesDone += 1
self.env.playToTheEnd(self.opponent, self.player)
els... | a single black stone can be set as the first move. | _oneGame | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/relativegomokutask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/relativegomokutask.py | BSD-3-Clause |
def _fixedStartingPos(self):
""" a list of starting positions, not along the border, and respecting symmetry. """
res = []
if self.size < 3:
return res
for x in range(1, (self.size + 1) // 2):
for y in range(x, (self.size + 1) // 2):
res.append((x,... | a list of starting positions, not along the border, and respecting symmetry. | _fixedStartingPos | python | pybrain/pybrain | pybrain/rl/environments/twoplayergames/tasks/relativetask.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/environments/twoplayergames/tasks/relativetask.py | BSD-3-Clause |
def doInteractionsAndLearn(self, number = 1):
""" Execute a number of steps while learning continuously.
no reset is performed, such that consecutive calls to
this function can be made.
"""
for _ in range(number):
self._oneInteraction()
self.agent.... | Execute a number of steps while learning continuously.
no reset is performed, such that consecutive calls to
this function can be made.
| doInteractionsAndLearn | python | pybrain/pybrain | pybrain/rl/experiments/continuous.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/continuous.py | BSD-3-Clause |
def _oneInteraction(self):
""" Do an interaction between the Task and the Agent. """
if self.doOptimization:
raise Exception('When using a black-box learning algorithm, only full episodes can be done.')
else:
return Experiment._oneInteraction(self) | Do an interaction between the Task and the Agent. | _oneInteraction | python | pybrain/pybrain | pybrain/rl/experiments/episodic.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/episodic.py | BSD-3-Clause |
def doEpisodes(self, number = 1):
""" Do one episode, and return the rewards of each step as a list. """
if self.doOptimization:
self.optimizer.maxEvaluations += number
self.optimizer.learn()
else:
all_rewards = []
for dummy in range(number):
... | Do one episode, and return the rewards of each step as a list. | doEpisodes | python | pybrain/pybrain | pybrain/rl/experiments/episodic.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/episodic.py | BSD-3-Clause |
def doInteractions(self, number = 1):
""" The default implementation directly maps the methods of the agent and the task.
Returns the number of interactions done.
"""
for _ in range(number):
self._oneInteraction()
return self.stepid | The default implementation directly maps the methods of the agent and the task.
Returns the number of interactions done.
| doInteractions | python | pybrain/pybrain | pybrain/rl/experiments/experiment.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/experiment.py | BSD-3-Clause |
def _oneInteraction(self):
""" Give the observation to the agent, takes its resulting action and returns
it to the task. Then gives the reward to the agent again and returns it.
"""
self.stepid += 1
self.agent.integrateObservation(self.task.getObservation())
self.task... | Give the observation to the agent, takes its resulting action and returns
it to the task. Then gives the reward to the agent again and returns it.
| _oneInteraction | python | pybrain/pybrain | pybrain/rl/experiments/experiment.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/experiment.py | BSD-3-Clause |
def _produceAllPairs(self):
""" produce a list of all pairs of agents (assuming ab <> ba)"""
res = []
for a in self.agents:
for b in self.agents:
if a != b:
res.append((a, b))
return res | produce a list of all pairs of agents (assuming ab <> ba) | _produceAllPairs | python | pybrain/pybrain | pybrain/rl/experiments/tournament.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/tournament.py | BSD-3-Clause |
def _oneGame(self, p1, p2):
""" play one game between two agents p1 and p2."""
self.numGames += 1
self.env.reset()
players = (p1, p2)
p1.color = self.startcolor
p2.color = -p1.color
p1.newEpisode()
p2.newEpisode()
i = 0
while not self.env.g... | play one game between two agents p1 and p2. | _oneGame | python | pybrain/pybrain | pybrain/rl/experiments/tournament.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/tournament.py | BSD-3-Clause |
def organize(self, repeat=1):
""" have all agents play all others in all orders, and repeat. """
for dummy in range(repeat):
self.rounds += 1
for p1, p2 in self._produceAllPairs():
self._oneGame(p1, p2)
return self.results | have all agents play all others in all orders, and repeat. | organize | python | pybrain/pybrain | pybrain/rl/experiments/tournament.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/tournament.py | BSD-3-Clause |
def eloScore(self, startingscore=1500, k=32):
""" compute the elo score of all the agents, given the games played in the tournament.
Also checking for potentially initial scores among the agents ('elo' variable). """
# initialize
elos = {}
for a in self.agents:
if 'el... | compute the elo score of all the agents, given the games played in the tournament.
Also checking for potentially initial scores among the agents ('elo' variable). | eloScore | python | pybrain/pybrain | pybrain/rl/experiments/tournament.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/experiments/tournament.py | BSD-3-Clause |
def _setSigma(self, sigma):
""" Wrapper method to set the sigmas (the parameters of the module) to a
certain value.
"""
assert len(sigma) == self.dim
self._params *= 0
self._params += sigma | Wrapper method to set the sigmas (the parameters of the module) to a
certain value.
| _setSigma | python | pybrain/pybrain | pybrain/rl/explorers/continuous/normal.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/continuous/normal.py | BSD-3-Clause |
def activate(self, state, action):
""" The super class commonly ignores the state and simply passes the
action through the module. implement _forwardImplementation()
in subclasses.
"""
self.state = state
return Module.activate(self, action) | The super class commonly ignores the state and simply passes the
action through the module. implement _forwardImplementation()
in subclasses.
| activate | python | pybrain/pybrain | pybrain/rl/explorers/continuous/sde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/continuous/sde.py | BSD-3-Clause |
def activate(self, state, action):
""" The super class ignores the state and simply passes the
action through the module. implement _forwardImplementation()
in subclasses.
"""
self._state = state
return DiscreteExplorer.activate(self, state, action) | The super class ignores the state and simply passes the
action through the module. implement _forwardImplementation()
in subclasses.
| activate | python | pybrain/pybrain | pybrain/rl/explorers/discrete/boltzmann.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/boltzmann.py | BSD-3-Clause |
def _forwardImplementation(self, inbuf, outbuf):
""" Draws a random number between 0 and 1. If the number is less
than epsilon, a random action is chosen. If it is equal or
larger than epsilon, the greedy action is returned.
"""
assert self.module
values = self.m... | Draws a random number between 0 and 1. If the number is less
than epsilon, a random action is chosen. If it is equal or
larger than epsilon, the greedy action is returned.
| _forwardImplementation | python | pybrain/pybrain | pybrain/rl/explorers/discrete/boltzmann.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/boltzmann.py | BSD-3-Clause |
def _setModule(self, module):
""" Tells the explorer the module (which has to be ActionValueTable). """
# removed: cause for circular import
# assert isinstance(module, ActionValueInterface)
self._module = module | Tells the explorer the module (which has to be ActionValueTable). | _setModule | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discrete.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discrete.py | BSD-3-Clause |
def __init__(self, epsilon = 0.2, decay = 0.9998):
""" TODO: the epsilon and decay parameters are currently
not implemented.
"""
DiscreteExplorer.__init__(self)
self.state = None | TODO: the epsilon and decay parameters are currently
not implemented.
| __init__ | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discretesde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discretesde.py | BSD-3-Clause |
def activate(self, state, action):
""" Save the current state for state-dependent exploration. """
self.state = state
return DiscreteExplorer.activate(self, state, action) | Save the current state for state-dependent exploration. | activate | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discretesde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discretesde.py | BSD-3-Clause |
def _forwardImplementation(self, inbuf, outbuf):
""" Activate the copied module instead of the original and
feed it with the current state.
"""
if random.random() < 0.001:
outbuf[:] = array([random.randint(self.module.numActions)])
else:
outbuf[:] = se... | Activate the copied module instead of the original and
feed it with the current state.
| _forwardImplementation | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discretesde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discretesde.py | BSD-3-Clause |
def newEpisode(self):
""" Inform the explorer about the start of a new episode. """
self.explorerModule = deepcopy(self.module)
if isinstance(self.explorerModule, ActionValueNetwork):
self.explorerModule.network.mutationStd = 0.01
self.explorerModule.network.mutate()
... | Inform the explorer about the start of a new episode. | newEpisode | python | pybrain/pybrain | pybrain/rl/explorers/discrete/discretesde.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/explorers/discrete/discretesde.py | BSD-3-Clause |
def _setModule(self, module):
""" initialize gradient descender with module parameters and
the loglh dataset with the outdim of the module. """
self._module = module
# initialize explorer
self._explorer = NormalExplorer(module.outdim)
# build network
self._i... | initialize gradient descender with module parameters and
the loglh dataset with the outdim of the module. | _setModule | python | pybrain/pybrain | pybrain/rl/learners/directsearch/policygradient.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/policygradient.py | BSD-3-Clause |
def _setExplorer(self, explorer):
""" assign non-standard explorer to the policy gradient learner.
requires the module to be set beforehand.
"""
assert self._module
self._explorer = explorer
# build network
self._initializeNetwork() | assign non-standard explorer to the policy gradient learner.
requires the module to be set beforehand.
| _setExplorer | python | pybrain/pybrain | pybrain/rl/learners/directsearch/policygradient.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/policygradient.py | BSD-3-Clause |
def _initializeNetwork(self):
""" build the combined network consisting of the module and
the explorer and initializing the log likelihoods dataset.
"""
self.network = FeedForwardNetwork()
self.network.addInputModule(self._module)
self.network.addOutputModule(self._ex... | build the combined network consisting of the module and
the explorer and initializing the log likelihoods dataset.
| _initializeNetwork | python | pybrain/pybrain | pybrain/rl/learners/directsearch/policygradient.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/policygradient.py | BSD-3-Clause |
def greedyEpisode(self):
""" run one episode with greedy decisions, return the list of rewards recieved."""
rewards = []
self.task.reset()
self.net.reset()
while not self.task.isFinished():
obs = self.task.getObservation()
act = self.net.activate(obs)
... | run one episode with greedy decisions, return the list of rewards recieved. | greedyEpisode | python | pybrain/pybrain | pybrain/rl/learners/directsearch/rwr.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/directsearch/rwr.py | BSD-3-Clause |
def trueFeatureStats(T, R, fMap, discountFactor, stateProp=1, MAT_LIMIT=1e8):
""" Gather the statistics needed for LSTD,
assuming infinite data (true probabilities).
Option: if stateProp is < 1, then only a proportion of all
states will be seen as starting state for transitions """
dim = len(fMap)... | Gather the statistics needed for LSTD,
assuming infinite data (true probabilities).
Option: if stateProp is < 1, then only a proportion of all
states will be seen as starting state for transitions | trueFeatureStats | python | pybrain/pybrain | pybrain/rl/learners/modelbased/leastsquares.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/leastsquares.py | BSD-3-Clause |
def LSTD_Qvalues(Ts, policy, R, fMap, discountFactor):
""" LSTDQ is like LSTD, but with features replicated
once for each possible action.
Returns Q-values in a 2D array. """
numA = len(Ts)
dim = len(Ts[0])
numF = len(fMap)
fMapRep = zeros((numF * numA, dim * numA))
for a in range(... | LSTDQ is like LSTD, but with features replicated
once for each possible action.
Returns Q-values in a 2D array. | LSTD_Qvalues | python | pybrain/pybrain | pybrain/rl/learners/modelbased/leastsquares.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/leastsquares.py | BSD-3-Clause |
def LSPI_policy(fMap, Ts, R, discountFactor, initpolicy=None, maxIters=20):
""" LSPI is like policy iteration, but Q-values are estimated based
on the feature map.
Returns the best policy found. """
if initpolicy is None:
policy, _ = randomPolicy(Ts)
else:
policy = initpolicy
... | LSPI is like policy iteration, but Q-values are estimated based
on the feature map.
Returns the best policy found. | LSPI_policy | python | pybrain/pybrain | pybrain/rl/learners/modelbased/leastsquares.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/leastsquares.py | BSD-3-Clause |
def LSTD_PI_policy(fMap, Ts, R, discountFactor, initpolicy=None, maxIters=20):
""" Alternative version of LSPI using value functions
instead of state-action values as intermediate.
"""
def veval(T):
return LSTD_values(T, R, fMap, discountFactor)
return policyIteration(Ts, R, discountFactor, ... | Alternative version of LSPI using value functions
instead of state-action values as intermediate.
| LSTD_PI_policy | python | pybrain/pybrain | pybrain/rl/learners/modelbased/leastsquares.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/leastsquares.py | BSD-3-Clause |
def trueValues(T, R, discountFactor):
""" Compute the true discounted value function for each state,
given a policy (encoded as collapsed transition matrix). """
assert discountFactor < 1
distr = T.copy()
res = dot(T, R)
for i in range(1, int(10 / (1. - discountFactor))):
distr = dot(dis... | Compute the true discounted value function for each state,
given a policy (encoded as collapsed transition matrix). | trueValues | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def trueQValues(Ts, R, discountFactor, policy):
""" The true Q-values, given a model and a policy. """
T = collapsedTransitions(Ts, policy)
V = trueValues(T, R, discountFactor)
Vnext = V*discountFactor+R
numA = len(Ts)
dim = len(R)
Qs = zeros((dim, numA))
for si in range(dim):
fo... | The true Q-values, given a model and a policy. | trueQValues | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def collapsedTransitions(Ts, policy):
""" Collapses a list of transition matrices (one per action) and a list
of action probability vectors into a single transition matrix."""
res = zeros_like(Ts[0])
dim = len(Ts[0])
for ai, ap in enumerate(policy.T):
res += Ts[ai] * repmat(ap, dim, 1).... | Collapses a list of transition matrices (one per action) and a list
of action probability vectors into a single transition matrix. | collapsedTransitions | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def greedyPolicy(Ts, R, discountFactor, V):
""" Find the greedy policy, (soft tie-breaking)
given a value function and full transition model. """
dim = len(V)
numA = len(Ts)
Vnext = V*discountFactor+R
policy = zeros((dim, numA))
for si in range(dim):
actions = all_argmax([dot(T[si, :... | Find the greedy policy, (soft tie-breaking)
given a value function and full transition model. | greedyPolicy | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
def greedyQPolicy(Qs):
""" Find the greedy deterministic policy,
given the Q-values. """
dim = len(Qs)
numA = len(Qs[0])
policy = zeros((dim, numA))
for si in range(dim):
actions = all_argmax(Qs[si])
for a in actions:
policy[si, a] = 1. / len(actions)
return ... | Find the greedy deterministic policy,
given the Q-values. | greedyQPolicy | python | pybrain/pybrain | pybrain/rl/learners/modelbased/policyiteration.py | https://github.com/pybrain/pybrain/blob/master/pybrain/rl/learners/modelbased/policyiteration.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.