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 newSequence(self):
"""Marks the beginning of a new sequence. this function does nothing if
called at the very start of the data set. Otherwise, it starts a new
sequence. Empty sequences are not allowed, and an EmptySequenceError
exception will be raised."""
length = self.getL... | Marks the beginning of a new sequence. this function does nothing if
called at the very start of the data set. Otherwise, it starts a new
sequence. Empty sequences are not allowed, and an EmptySequenceError
exception will be raised. | newSequence | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def _getSequenceField(self, index, field):
"""Return a sequence of one single field given by `field` and indexed by
`index`."""
seq = ravel(self.getField('sequence_index'))
if len(seq) == index + 1:
# user wants to access the last sequence, return until end of data
... | Return a sequence of one single field given by `field` and indexed by
`index`. | _getSequenceField | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def endOfSequence(self, index):
"""Return True if the marker was moved over the last element of
sequence `index`, False otherwise.
Mostly used like .endOfData() with while loops."""
seq = ravel(self.getField('sequence_index'))
if len(seq) == index + 1:
# user wants t... | Return True if the marker was moved over the last element of
sequence `index`, False otherwise.
Mostly used like .endOfData() with while loops. | endOfSequence | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def gotoSequence(self, index):
"""Move the internal marker to the beginning of sequence `index`."""
try:
self.index = ravel(self.getField('sequence_index'))[index]
except IndexError:
raise IndexError('sequence does not exist') | Move the internal marker to the beginning of sequence `index`. | gotoSequence | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def getCurrentSequence(self):
"""Return the current sequence, according to the marker position."""
seq = ravel(self.getField('sequence_index'))
return len(seq) - sum(seq > self.index) - 1 | Return the current sequence, according to the marker position. | getCurrentSequence | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def getSequenceLength(self, index):
"""Return the length of the given sequence. If `index` is pointing
to the last sequence, the sequence is considered to go until the end
of the dataset."""
seq = ravel(self.getField('sequence_index'))
if len(seq) == index + 1:
# user... | Return the length of the given sequence. If `index` is pointing
to the last sequence, the sequence is considered to go until the end
of the dataset. | getSequenceLength | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def removeSequence(self, index):
"""Remove the `index`'th sequence from the dataset and places the
marker to the sample following the removed sequence."""
if index >= self.getNumSequences():
# sequence doesn't exist, raise exception
raise IndexError('sequence does not exi... | Remove the `index`'th sequence from the dataset and places the
marker to the sample following the removed sequence. | removeSequence | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def evaluateModuleMSE(self, module, averageOver=1, **args):
"""Evaluate the predictions of a module on a sequential dataset
and return the MSE (potentially average over a number of epochs)."""
res = 0.
for dummy in range(averageOver):
ponderation = 0.
totalError =... | Evaluate the predictions of a module on a sequential dataset
and return the MSE (potentially average over a number of epochs). | evaluateModuleMSE | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def splitWithProportion(self, proportion=0.5):
"""Produce two new datasets, each containing a part of the sequences.
The first dataset will have a fraction given by `proportion` of the
dataset."""
l = self.getNumSequences()
leftIndices = sample(list(range(l)), int(l * proportion... | Produce two new datasets, each containing a part of the sequences.
The first dataset will have a fraction given by `proportion` of the
dataset. | splitWithProportion | python | pybrain/pybrain | pybrain/datasets/sequential.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py | BSD-3-Clause |
def __init__(self, inp, target):
"""Initialize an empty supervised dataset.
Pass `inp` and `target` to specify the dimensions of the input and
target vectors."""
DataSet.__init__(self)
if isscalar(inp):
# add input and target fields and link them
self.add... | Initialize an empty supervised dataset.
Pass `inp` and `target` to specify the dimensions of the input and
target vectors. | __init__ | python | pybrain/pybrain | pybrain/datasets/supervised.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py | BSD-3-Clause |
def setField(self, label, arr, **kwargs):
"""Set the given array `arr` as the new array of the field specfied by
`label`."""
DataSet.setField(self, label, arr, **kwargs)
# refresh dimensions, in case any of these fields were modified
if label == 'input':
self.indim = ... | Set the given array `arr` as the new array of the field specfied by
`label`. | setField | python | pybrain/pybrain | pybrain/datasets/supervised.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py | BSD-3-Clause |
def evaluateMSE(self, f, **args):
"""Evaluate the predictions of a function on the dataset and return the
Mean Squared Error, incorporating importance."""
ponderation = 0.
totalError = 0
for seq in self._provideSequences():
e, p = self._evaluateSequence(f, seq, **args... | Evaluate the predictions of a function on the dataset and return the
Mean Squared Error, incorporating importance. | evaluateMSE | python | pybrain/pybrain | pybrain/datasets/supervised.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py | BSD-3-Clause |
def _evaluateSequence(self, f, seq, verbose = False):
"""Return the ponderated MSE over one sequence."""
totalError = 0.
ponderation = 0.
for input, target in seq:
res = f(input)
e = 0.5 * sum((target-res).flatten()**2)
totalError += e
pond... | Return the ponderated MSE over one sequence. | _evaluateSequence | python | pybrain/pybrain | pybrain/datasets/supervised.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py | BSD-3-Clause |
def evaluateModuleMSE(self, module, averageOver = 1, **args):
"""Evaluate the predictions of a module on a dataset and return the MSE
(potentially average over a number of epochs)."""
res = 0.
for dummy in range(averageOver):
module.reset()
res += self.evaluateMSE... | Evaluate the predictions of a module on a dataset and return the MSE
(potentially average over a number of epochs). | evaluateModuleMSE | python | pybrain/pybrain | pybrain/datasets/supervised.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py | BSD-3-Clause |
def splitWithProportion(self, proportion = 0.5):
"""Produce two new datasets, the first one containing the fraction given
by `proportion` of the samples."""
indicies = random.permutation(len(self))
separator = int(len(self) * proportion)
leftIndicies = indicies[:separator]
... | Produce two new datasets, the first one containing the fraction given
by `proportion` of the samples. | splitWithProportion | python | pybrain/pybrain | pybrain/datasets/supervised.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py | BSD-3-Clause |
def __init__(self, dim):
"""Initialize an empty unsupervised dataset.
Pass `dim` to specify the dimensionality of the samples."""
super(UnsupervisedDataSet, self).__init__()
self.addField('sample', dim)
self.linkFields(['sample'])
self.dim = dim
# reset the inde... | Initialize an empty unsupervised dataset.
Pass `dim` to specify the dimensionality of the samples. | __init__ | python | pybrain/pybrain | pybrain/datasets/unsupervised.py | https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/unsupervised.py | BSD-3-Clause |
def _learnStep(self):
""" generate a new evaluable by mutation, compare them, and keep the best. """
# re-evaluate the current individual in case the evaluator is noisy
if self.evaluatorIsNoisy:
self.bestEvaluation = self._oneEvaluation(self.bestEvaluable)
# hill-climbing
... | generate a new evaluable by mutation, compare them, and keep the best. | _learnStep | python | pybrain/pybrain | pybrain/optimization/hillclimber.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/hillclimber.py | BSD-3-Clause |
def __init__(self, evaluator = None, initEvaluable = None, **kwargs):
""" The evaluator is any callable object (e.g. a lambda function).
Algorithm parameters can be set here if provided as keyword arguments. """
# set all algorithm-specific parameters in one go:
self.__minimize = None
... | The evaluator is any callable object (e.g. a lambda function).
Algorithm parameters can be set here if provided as keyword arguments. | __init__ | python | pybrain/pybrain | pybrain/optimization/optimizer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py | BSD-3-Clause |
def _setMinimize(self, flag):
""" Minimization vs. maximization: priority to algorithm requirements,
then evaluator, default = maximize."""
self.__minimize = flag
opp = False
if flag is True:
if self.mustMaximize:
opp = True
self.__min... | Minimization vs. maximization: priority to algorithm requirements,
then evaluator, default = maximize. | _setMinimize | python | pybrain/pybrain | pybrain/optimization/optimizer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py | BSD-3-Clause |
def setEvaluator(self, evaluator, initEvaluable = None):
""" If not provided upon construction, the objective function can be given through this method.
If necessary, also provide an initial evaluable."""
# default settings, if provided by the evaluator:
if isinstance(evaluator,... | If not provided upon construction, the objective function can be given through this method.
If necessary, also provide an initial evaluable. | setEvaluator | python | pybrain/pybrain | pybrain/optimization/optimizer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py | BSD-3-Clause |
def learn(self, additionalLearningSteps = None):
""" The main loop that does the learning. """
assert self.__evaluator is not None, "No evaluator has been set. Learning cannot start."
if additionalLearningSteps is not None:
self.maxLearningSteps = self.numLearningSteps + additionalLe... | The main loop that does the learning. | learn | python | pybrain/pybrain | pybrain/optimization/optimizer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py | BSD-3-Clause |
def _bestFound(self):
""" return the best found evaluable and its associated fitness. """
bestE = self.bestEvaluable.params.copy() if self._wasWrapped else self.bestEvaluable
if self._wasOpposed and isscalar(self.bestEvaluation):
bestF = -self.bestEvaluation
else:
... | return the best found evaluable and its associated fitness. | _bestFound | python | pybrain/pybrain | pybrain/optimization/optimizer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py | BSD-3-Clause |
def _oneEvaluation(self, evaluable):
""" This method should be called by all optimizers for producing an evaluation. """
if self._wasUnwrapped:
self.wrappingEvaluable._setParameters(evaluable)
res = self.__evaluator(self.wrappingEvaluable)
elif self._wasWrapped: ... | This method should be called by all optimizers for producing an evaluation. | _oneEvaluation | python | pybrain/pybrain | pybrain/optimization/optimizer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py | BSD-3-Clause |
def _notify(self):
""" Provide some feedback during the run. """
if self.verbose:
print(('Step:', self.numLearningSteps, 'best:', self.bestEvaluation))
if self.listener is not None:
self.listener(self.bestEvaluable, self.bestEvaluation) | Provide some feedback during the run. | _notify | python | pybrain/pybrain | pybrain/optimization/optimizer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py | BSD-3-Clause |
def _setInitEvaluable(self, evaluable):
""" If the parameters are wrapped, we keep track of the wrapper explicitly. """
if isinstance(evaluable, ParameterContainer):
self.wrappingEvaluable = evaluable.copy()
self._wasUnwrapped = True
elif not (evaluable is None
... | If the parameters are wrapped, we keep track of the wrapper explicitly. | _setInitEvaluable | python | pybrain/pybrain | pybrain/optimization/optimizer.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py | BSD-3-Clause |
def sorti(vect):
""" sort, but also return the indices-changes """
tmp = sorted([(x_y[1], x_y[0]) for x_y in enumerate(ravel(vect))])
res1 = array([x[0] for x in tmp])
res2 = array([int(x[1]) for x in tmp])
return res1, res2 | sort, but also return the indices-changes | sorti | python | pybrain/pybrain | pybrain/optimization/distributionbased/cmaes.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/cmaes.py | BSD-3-Clause |
def _generateConformingBatch(self):
""" Generate a batch of samples that conforms to the current distribution.
If importance mixing is enabled, this can reuse old samples. """ | Generate a batch of samples that conforms to the current distribution.
If importance mixing is enabled, this can reuse old samples. | _generateConformingBatch | python | pybrain/pybrain | pybrain/optimization/distributionbased/distributionbased.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/distributionbased.py | BSD-3-Clause |
def _produceNewSample(self):
""" returns a new sample, its fitness and its densities """
chosenOne = drawIndex(self.alphas, True)
mu = self.mus[chosenOne]
if self.useAnticipatedMeanShift:
if len(self.allsamples) % 2 == 1 and len(self.allsamples) > 1:
if not(s... | returns a new sample, its fitness and its densities | _produceNewSample | python | pybrain/pybrain | pybrain/optimization/distributionbased/fem.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/fem.py | BSD-3-Clause |
def _computeUpdateSize(self, densities, sampleIndex):
""" compute the the center-update-size for each sample
using transformed fitnesses """
# determine (transformed) fitnesses
transformedfitnesses = self.shapingFunction(self.fitnesses)
# force renormaliziation
transfor... | compute the the center-update-size for each sample
using transformed fitnesses | _computeUpdateSize | python | pybrain/pybrain | pybrain/optimization/distributionbased/fem.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/fem.py | BSD-3-Clause |
def _updateShaping(self):
""" Daan: "This won't work. I like it!" """
assert self.numberOfCenters == 1
possible = self.shapingFunction.getPossibleParameters(self.windowSize)
matchValues = []
pdfs = [multivariateNormalPdf(s, self.mus[0], self.sigmas[0])
for s in s... | Daan: "This won't work. I like it!" | _updateShaping | python | pybrain/pybrain | pybrain/optimization/distributionbased/fem.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/fem.py | BSD-3-Clause |
def _logDerivsFactorSigma(self, samples, mu, invSigma, factorSigma):
""" Compute the log-derivatives w.r.t. the factorized covariance matrix components.
This implementation should be faster than the one in Vanilla. """
res = zeros((len(samples), self.numDistrParams - self.numParameters))
... | Compute the log-derivatives w.r.t. the factorized covariance matrix components.
This implementation should be faster than the one in Vanilla. | _logDerivsFactorSigma | python | pybrain/pybrain | pybrain/optimization/distributionbased/nes.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/nes.py | BSD-3-Clause |
def _produceSamples(self):
""" Append batch size new samples and evaluate them. """
tmp = [self._sample2base(self._produceSample()) for _ in range(self.batchSize)]
list(map(self._oneEvaluation, tmp))
self._pointers = list(range(len(self._allEvaluated) - self.batchSize, len(se... | Append batch size new samples and evaluate them. | _produceSamples | python | pybrain/pybrain | pybrain/optimization/distributionbased/rank1.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/rank1.py | BSD-3-Clause |
def test():
""" Rank-1 NEX easily solves high-dimensional Rosenbrock functions. """
from pybrain.rl.environments.functions.unimodal import RosenbrockFunction
dim = 40
f = RosenbrockFunction(dim)
x0 = -ones(dim)
l = Rank1NES(f, x0, verbose=True, verboseGaps=500)
l.learn() | Rank-1 NEX easily solves high-dimensional Rosenbrock functions. | test | python | pybrain/pybrain | pybrain/optimization/distributionbased/rank1.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/rank1.py | BSD-3-Clause |
def _produceSamples(self):
""" Append batchsize new samples and evaluate them. """
if self.numLearningSteps == 0 or not self.importanceMixing:
for _ in range(self.batchSize):
self._produceNewSample()
self.allGenerated.append(self.batchSize + self.allGenerated[-1])... | Append batchsize new samples and evaluate them. | _produceSamples | python | pybrain/pybrain | pybrain/optimization/distributionbased/ves.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/ves.py | BSD-3-Clause |
def _hasConverged(self):
""" When the largest eigenvalue is smaller than 10e-20, we assume the
algorithms has converged. """
eigs = abs(diag(self.factorSigma))
return min(eigs) < 1e-10 | When the largest eigenvalue is smaller than 10e-20, we assume the
algorithms has converged. | _hasConverged | python | pybrain/pybrain | pybrain/optimization/distributionbased/ves.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/ves.py | BSD-3-Clause |
def _revertToSafety(self):
""" When encountering a bad matrix, this is how we revert to a safe one. """
self.factorSigma = eye(self.numParameters)
self.x = self.bestEvaluable
self.allFactorSigmas[-1][:] = self.factorSigma
self.sigma = dot(self.factorSigma.T, self.factorSigma) | When encountering a bad matrix, this is how we revert to a safe one. | _revertToSafety | python | pybrain/pybrain | pybrain/optimization/distributionbased/ves.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/ves.py | BSD-3-Clause |
def _learnStep(self):
""" calls the gradient calculation function and executes a step in direction
of the gradient, scaled with a small learning rate alpha. """
# initialize matrix D and vector R
D = ones((self.batchSize, self.numParameters))
R = zeros((self.batchSize, 1))
... | calls the gradient calculation function and executes a step in direction
of the gradient, scaled with a small learning rate alpha. | _learnStep | python | pybrain/pybrain | pybrain/optimization/finitedifference/fd.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/finitedifference/fd.py | BSD-3-Clause |
def _learnStep(self):
""" calculates the gradient and executes a step in the direction
of the gradient, scaled with a learning rate alpha. """
deltas = self.perturbation()
#reward of positive and negative perturbations
reward1 = self._oneEvaluation(self.current + deltas) ... | calculates the gradient and executes a step in the direction
of the gradient, scaled with a learning rate alpha. | _learnStep | python | pybrain/pybrain | pybrain/optimization/finitedifference/pgpe.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/finitedifference/pgpe.py | BSD-3-Clause |
def switchMutations(self):
""" interchange the mutate() and topologyMutate() operators """
tm = self._initEvaluable.__class__.topologyMutate
m = self._initEvaluable.__class__.mutate
self._initEvaluable.__class__.topologyMutate = m
self._initEvaluable.__class__.mutate = tm | interchange the mutate() and topologyMutate() operators | switchMutations | python | pybrain/pybrain | pybrain/optimization/memetic/memetic.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/memetic/memetic.py | BSD-3-Clause |
def crossOverOld(self, parents, nbChildren):
""" generate a number of children by doing 1-point cross-over """
xdim = self.numParameters
children = []
for _ in range(nbChildren):
p1 = choice(parents)
if xdim < 2:
children.append(p1)
els... | generate a number of children by doing 1-point cross-over | crossOverOld | python | pybrain/pybrain | pybrain/optimization/populationbased/ga.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py | BSD-3-Clause |
def mutatedOld(self, indiv):
""" mutate some genes of the given individual """
res = indiv.copy()
for i in range(self.numParameters):
if random() < self.mutationProb:
res[i] = indiv[i] + gauss(0, self.mutationStdDev)
return res | mutate some genes of the given individual | mutatedOld | python | pybrain/pybrain | pybrain/optimization/populationbased/ga.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py | BSD-3-Clause |
def select(self):
""" select some of the individuals of the population, taking into account their fitnesses
:return: list of selected parents """
if not self.tournament:
tmp = list(zip(self.fitnesses, self.currentpop))
tmp.sort(key = lambda x: x[0])
tmp2 = li... | select some of the individuals of the population, taking into account their fitnesses
:return: list of selected parents | select | python | pybrain/pybrain | pybrain/optimization/populationbased/ga.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py | BSD-3-Clause |
def produceOffspring(self):
""" produce offspring by selection, mutation and crossover. """
parents = self.select()
es = min(self.eliteSize, self.selectionSize)
self.currentpop = parents[:es]
'''Modified by JPQ '''
nbchildren = self.populationSize - es
if self.pop... | produce offspring by selection, mutation and crossover. | produceOffspring | python | pybrain/pybrain | pybrain/optimization/populationbased/ga.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py | BSD-3-Clause |
def best(self, particlelist):
"""Return the particle with the best fitness from a list of particles.
"""
picker = min if self.minimize else max
return picker(particlelist, key=lambda p: p.fitness) | Return the particle with the best fitness from a list of particles.
| best | python | pybrain/pybrain | pybrain/optimization/populationbased/pso.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/pso.py | BSD-3-Clause |
def __init__(self, start, minimize):
"""Initialize a Particle at the given start vector."""
self.minimize = minimize
self.dim = scipy.size(start)
self.position = start
self.velocity = scipy.zeros(scipy.size(start))
self.bestPosition = scipy.zeros(scipy.size(start))
... | Initialize a Particle at the given start vector. | __init__ | python | pybrain/pybrain | pybrain/optimization/populationbased/pso.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/pso.py | BSD-3-Clause |
def __init__(self, relEvaluator, seeds, **args):
"""
:arg relevaluator: an anti-symmetric function that can evaluate 2 elements
:arg seeds: a list of initial guesses
"""
# set parameters
self.setArgs(**args)
self.relEvaluator = relEvaluator
if self.tournam... |
:arg relevaluator: an anti-symmetric function that can evaluate 2 elements
:arg seeds: a list of initial guesses
| __init__ | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def learn(self, maxSteps=None):
""" Toplevel function, can be called iteratively.
:return: best evaluable found in the last generation. """
if maxSteps != None:
maxSteps += self.steps
while True:
if maxSteps != None and self.steps + self._stepsPerGeneration() > m... | Toplevel function, can be called iteratively.
:return: best evaluable found in the last generation. | learn | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def _extendPopulation(self, seeds, size):
""" build a population, with mutated copies from the provided
seed pool until it has the desired size. """
res = seeds[:]
for dummy in range(size - len(seeds)):
chosen = choice(seeds)
tmp = chosen.copy()
tmp.mu... | build a population, with mutated copies from the provided
seed pool until it has the desired size. | _extendPopulation | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def _selectAndReproduce(self, pop, fits):
""" apply selection and reproduction to host population, according to their fitness."""
# combine population with their fitness, then sort, only by fitness
s = list(zip(fits, pop))
shuffle(s)
s.sort(key=lambda x:-x[0])
# select...... | apply selection and reproduction to host population, according to their fitness. | _selectAndReproduce | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def _beats(self, h, p):
""" determine the empirically observed score of p playing opp (starting or not).
If they never played, assume 0. """
if (h, p) not in self.allResults:
return 0
else:
hpgames, hscore = self.allResults[(h, p)][1:3]
phgames, pscore... | determine the empirically observed score of p playing opp (starting or not).
If they never played, assume 0. | _beats | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def _doTournament(self, pop1, pop2, tournamentSize=None):
""" Play a tournament.
:key tournamentSize: If unspecified, play all-against-all
"""
# TODO: Preferably select high-performing opponents?
for p in pop1:
pop3 = pop2[:]
while p in pop3:
... | Play a tournament.
:key tournamentSize: If unspecified, play all-against-all
| _doTournament | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def _globalScore(self, p):
""" The average score over all evaluations for a player. """
if p not in self.allOpponents:
return 0.
scoresum, played = 0., 0
for opp in self.allOpponents[p]:
scoresum += self.allResults[(p, opp)][2]
played += self.allResult... | The average score over all evaluations for a player. | _globalScore | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def _sharedSampling(self, numSelect, selectFrom, relativeTo):
""" Build a shared sampling set of opponents """
if numSelect < 1:
return []
# determine the player of selectFrom with the most wins against players from relativeTo (and which ones)
tmp = {}
for p in select... | Build a shared sampling set of opponents | _sharedSampling | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def _relEval(self, p, opp):
""" a single relative evaluation (in one direction) with the involved bookkeeping."""
if p not in self.allOpponents:
self.allOpponents[p] = []
self.allOpponents[p].append(opp)
if (p, opp) not in self.allResults:
self.allResults[(p, opp)... | a single relative evaluation (in one direction) with the involved bookkeeping. | _relEval | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/coevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py | BSD-3-Clause |
def _competitiveSharedFitness(self, hosts, parasites):
""" determine the competitive shared fitness for the population of hosts, w.r. to
the population of parasites. """
if len(parasites) == 0:
return [0] * len(hosts)
# determine beat-sum for parasites (nb of games lost)
... | determine the competitive shared fitness for the population of hosts, w.r. to
the population of parasites. | _competitiveSharedFitness | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/competitivecoevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/competitivecoevolution.py | BSD-3-Clause |
def _initPopulation(self, seeds):
""" one part of the seeds for each population, if there's not enough: randomize. """
for s in seeds:
s.parent = None
while len(seeds) < self.numPops:
tmp = choice(seeds).copy()
tmp.randomize()
seeds.append(tmp)
... | one part of the seeds for each population, if there's not enough: randomize. | _initPopulation | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/multipopulationcoevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/multipopulationcoevolution.py | BSD-3-Clause |
def _evaluatePopulation(self):
"""Each individual in main pop plays against
tournSize others of each other population (the best part of them). """
for other in self.pops:
if other == self.pop:
continue
# TODO: parametrize
bestPart = len(other)/... | Each individual in main pop plays against
tournSize others of each other population (the best part of them). | _evaluatePopulation | python | pybrain/pybrain | pybrain/optimization/populationbased/coevolution/multipopulationcoevolution.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/multipopulationcoevolution.py | BSD-3-Clause |
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 = const_non_dominated_sort(population,
key=lambda x: fitnesses[... | 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/constnsga2.py | https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/multiobjective/constnsga2.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 m... |
: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... | 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
... | 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 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
... | 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:
... | 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.... | 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 vic... | 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 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:
resul... | 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.appe... | 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... |
: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 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.s... | 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
... | 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 origi... | 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 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).
"""
... | 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 = C... | 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:
... | @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)
... | 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... | 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
... | 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 / no... | 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:
... | 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.per... | 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) == ... | 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
... | 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
... | 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 ... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.