desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.Options().match(\'verb\')`` returns the verbosity options.'
| def match(self, s=''):
| match = s.lower()
res = {}
for k in sorted(self):
s = (((str(k) + "='") + str(self[k])) + "'")
if (match in s.lower()):
res[k] = self[k]
return Options(res)
|
'Compute strategy parameters, mainly depending on
dimension and population size, by calling `set`'
| def __init__(self, N, opts, ccovfac=1, verbose=True):
| self.N = N
if (ccovfac == 1):
ccovfac = opts['CMA_on']
self.set(opts, ccovfac=ccovfac, verbose=verbose)
|
'Compute strategy parameters as a function
of dimension and population size'
| def set(self, opts, popsize=None, ccovfac=1, verbose=True):
| alpha_cc = 1.0
def cone(df, mu, N, alphacov=2.0):
'rank one update learning rate, ``df`` is disregarded and obsolete, reduce alphacov on noisy problems, say to 0.5'
return (alphacov / (((N + 1.3) ** 2) + mu))
def cmu(df, mu, alphamu=0.0, alp... |
'update the dictionary'
| def __call__(self, es):
| return self._update(es)
|
'Test termination criteria and update dictionary.'
| def _update(self, es):
| if (es.countiter == self.lastiter):
if (es.countiter == 0):
self.__init__()
return self
try:
if (es == self.es):
return self
except:
pass
self.lastiter = es.countiter
self.es = es
self.stoplist = []
N = es.N
... |
'abstract method, add a "data point" from the state of `optim` into the
logger, the argument `optim` can be omitted if it was `register()`-ed before,
acts like an event handler'
| def add(self, optim=None, more_data=[]):
| raise NotImplementedError()
|
'abstract method, register an optimizer `optim`, only needed if `add()` is
called without a value for the `optim` argument'
| def register(self, optim):
| self.optim = optim
|
'display some data trace (not implemented)'
| def disp(self):
| print(('method BaseDataLogger.disp() not implemented, to be done in subclass ' + str(type(self))))
|
'plot data (not implemented)'
| def plot(self):
| print(('method BaseDataLogger.plot() is not implemented, to be done in subclass ' + str(type(self))))
|
'return logged data in a dictionary (not implemented)'
| def data(self):
| print(('method BaseDataLogger.data() is not implemented, to be done in subclass ' + str(type(self))))
|
'abstract method, add a "data point" from the state of `optim` into the
logger, the argument `optim` can be omitted if it was `register()`-ed before,
acts like an event handler'
| def add(self, optim=None, more_data=[]):
| raise NotImplementedError()
|
'abstract method, register an optimizer `optim`, only needed if `add()` is
called without a value for the `optim` argument'
| def register(self, optim):
| self.optim = optim
|
'display some data trace (not implemented)'
| def disp(self):
| print(('method BaseDataLogger.disp() not implemented, to be done in subclass ' + str(type(self))))
|
'plot data (not implemented)'
| def plot(self):
| print(('method BaseDataLogger.plot() is not implemented, to be done in subclass ' + str(type(self))))
|
'return logged data in a dictionary (not implemented)'
| def data(self):
| print(('method BaseDataLogger.data() is not implemented, to be done in subclass ' + str(type(self))))
|
'initialize logging of data from a `CMAEvolutionStrategy` instance,
default modulo expands to 1 == log with each call'
| def __init__(self, name_prefix=default_prefix, modulo=1, append=False):
| self.file_names = ('axlen', 'fit', 'stddev', 'xmean', 'xrecentbest')
self.key_names = ('D', 'f', 'std', 'xmean', 'xrecent')
self.key_names_with_annotation = ('std', 'xmean', 'xrecent')
self.modulo = modulo
self.append = append
self.counter = 0
self.name_prefix = (name_prefix if name_prefix e... |
'register a `CMAEvolutionStrategy` instance for logging,
``append=True`` appends to previous data logged under the same name,
by default previous data are overwritten.'
| def register(self, es, append=None, modulo=None):
| if (type(es) != CMAEvolutionStrategy):
raise TypeError('only class CMAEvolutionStrategy can be registered for logging')
self.es = es
if (append is not None):
self.append = append
if (modulo is not None):
self.modulo = modulo
if ((not self.append) and (sel... |
'reset logger, overwrite original files, `modulo`: log only every modulo call'
| def initialize(self, modulo=None):
| if (modulo is not None):
self.modulo = modulo
try:
es = self.es
except AttributeError:
pass
raise _Error('call register() before initialize()')
self.counter = 0
fn = (self.name_prefix + 'fit.dat')
strseedtime = ('seed=%d, %s' % (es.opts['seed'], time.a... |
'loads data from files written and return a data dictionary, *not*
a prerequisite for using `plot()` or `disp()`.
Argument `filenameprefix` is the filename prefix of data to be loaded (five files),
by default ``\'outcmaes\'``.
Return data dictionary with keys `xrecent`, `xmean`, `f`, `D`, `std`'
| def load(self, filenameprefix=None):
| if (not filenameprefix):
filenameprefix = self.name_prefix
for i in xrange(len(self.file_names)):
fn = ((filenameprefix + self.file_names[i]) + '.dat')
try:
self.__dict__[self.key_names[i]] = _fileToMatrix(fn)
except:
print((('WARNING: reading from ... |
'append some logging data from `CMAEvolutionStrategy` class instance `es`,
if ``number_of_times_called % modulo`` equals to zero, never if ``modulo==0``.
The sequence ``more_data`` must always have the same length.
When used for a different optimizer class, this function can be
(easily?) adapted by changing the assignm... | def add(self, es=None, more_data=[], modulo=None):
| self.counter += 1
mod = (modulo if (modulo is not None) else self.modulo)
if ((mod == 0) or ((self.counter > 3) and (self.counter % mod))):
return
if (es is None):
try:
es = self.es
except AttributeError:
raise _Error('call `add` with argument ... |
'saves logger data to a different set of files, for
``switch=True`` also the loggers name prefix is switched to
the new value'
| def save(self, nameprefix, switch=False):
| if ((not nameprefix) or (type(nameprefix) is not str)):
_Error('filename prefix must be a nonempty string')
if (nameprefix == self.default_prefix):
_Error((('cannot save to default name "' + nameprefix) + '...", chose another name'))
if (nameprefix =... |
'plot data from a `CMADataLogger` (using the files written by the logger).
Arguments
`fig`
figure number, by default 325
`iabscissa`
``0==plot`` versus iteration count,
``1==plot`` versus function evaluation number
`iteridx`
iteration indices to plot
Return `CMADataLogger` itself.
Examples
import cma
logger = cma.CMADa... | def plot(self, fig=None, iabscissa=1, iteridx=None, plot_mean=True, foffset=1e-19, x_opt=None, fontsize=10):
| dat = self.load(self.name_prefix)
try:
from matplotlib.pylab import figure, ioff, ion, subplot, semilogy, hold, plot, grid, axis, title, text, xlabel, isinteractive, draw, gcf
except ImportError:
ImportError('could not find matplotlib.pylab module, function plot() is ... |
'helper function for `plot()` that plots all what is
in the upper left subplot like fitness, sigma, etc.
Arguments
`iabscissa` in ``(0,1)``
0==versus fevals, 1==versus iteration
`foffset`
offset to fitness for log-plot
:See: `plot()`'
| @staticmethod
def plotdivers(dat, iabscissa, foffset):
| from matplotlib.pylab import semilogy, hold, grid, axis, title, text
fontsize = pylab.rcParams['font.size']
hold(False)
dfit = (dat.f[:, 5] - min(dat.f[:, 5]))
dfit[(dfit < 1e-98)] = np.NaN
if (dat.f.shape[1] > 7):
semilogy(dat.f[:, iabscissa], (abs(dat.f[:, [6, 7]]) + foffset), '-k')
... |
'rude downsampling of a `CMADataLogger` data file by `factor`, keeping
also the first `first` entries. This function is a stump and subject
to future changes.
Arguments
- `factor` -- downsampling factor
- `first` -- keep first `first` entries
- `switch` -- switch the new logger name to oldname+\'down\'
Details
``self.n... | def downsampling(self, factor=10, first=3, switch=True):
| newprefix = (self.name_prefix + 'down')
for name in CMADataLogger.names:
f = open(((newprefix + name) + '.dat'), 'w')
iline = 0
cwritten = 0
for line in open(((self.name_prefix + name) + '.dat')):
if ((iline < first) or ((iline % factor) == 0)):
f.writ... |
'displays selected data from (files written by) the class `CMADataLogger`.
Arguments
`idx`
indices corresponding to rows in the data file;
if idx is a scalar (int), the first two, then every idx-th,
and the last three rows are displayed. Too large index values are removed.
Example
>>> import cma, numpy as np
>>> res = ... | def disp(self, idx=100):
| filenameprefix = self.name_prefix
def printdatarow(dat, iteration):
'print data of iteration i'
i = np.where((dat.f[:, 0] == iteration))[0][0]
j = np.where((dat.std[:, 0] == iteration))[0][0]
print((((((('%5d' % int(dat.f[(i, 0)])) + (' %6d' % int(dat.f[(i, 1)]))) ... |
'initialize logging of data from a `CMAEvolutionStrategy` instance,
default modulo expands to 1 == log with each call'
| def __init__(self, name_prefix=default_prefix, modulo=1, append=False):
| self.counter = 0
self.best_fitness = np.inf
self.modulo = modulo
self.append = append
self.name_prefix = (name_prefix if name_prefix else CMADataLogger.default_prefix)
if (type(self.name_prefix) == CMAEvolutionStrategy):
self.name_prefix = self.name_prefix.opts.eval('verb_filenameprefix'... |
'register a `CMAEvolutionStrategy` instance for logging,
``append=True`` appends to previous data logged under the same name,
by default previous data are overwritten.'
| def register(self, es, append=None, modulo=None):
| self.es = es
if (append is not None):
self.append = append
if (modulo is not None):
self.modulo = modulo
if ((not self.append) and (self.modulo != 0)):
self.initialize()
self.registered = True
return self
|
'reset logger, overwrite original files, `modulo`: log only every modulo call'
| def initialize(self, modulo=None):
| if (modulo is not None):
self.modulo = modulo
try:
es = self.es
except AttributeError:
pass
raise _Error('call register() before initialize()')
fn = (self.name_prefix + 'fit.dat')
if (11 < 3):
strseedtime = ('seed=%d, %s' % (es.opts['seed'], time.a... |
'loads data from files written and return a data dictionary, *not*
a prerequisite for using `plot()` or `disp()`.
Argument `filenameprefix` is the filename prefix of data to be loaded (five files),
by default ``\'outcmaes\'``.
Return data dictionary with keys `xrecent`, `xmean`, `f`, `D`, `std`'
| def load(self, filenameprefix=None):
| if (not filenameprefix):
filenameprefix = self.name_prefix
dat = self
dat.xmean = _fileToMatrix((filenameprefix + 'xmean.dat'))
dat.std = _fileToMatrix(((filenameprefix + 'stddev') + '.dat'))
for key in ['xmean', 'std']:
dat.__dict__[key].append(dat.__dict__[key][(-1)])
dat._... |
'append some logging data from `CMAEvolutionStrategy` class instance `es`,
if ``number_of_times_called % modulo`` equals to zero, never if ``modulo==0``.
The sequence ``more_data`` must always have the same length.'
| def add(self, fitness_values, es=None, more_data=[], modulo=None):
| self.counter += 1
fitness_values = np.sort(fitness_values)
if (fitness_values[0] < self.best_fitness):
self.best_fitness = fitness_values[0]
mod = (modulo if (modulo is not None) else self.modulo)
if ((mod == 0) or ((self.counter > 3) and (self.counter % mod))):
return
if (es is ... |
'saves logger data to a different set of files, for
``switch=True`` also the loggers name prefix is switched to
the new value'
| def save(self, nameprefix, switch=False):
| if ((not nameprefix) or (type(nameprefix) is not str)):
_Error('filename prefix must be a nonempty string')
if (nameprefix == self.default_prefix):
_Error((('cannot save to default name "' + nameprefix) + '...", chose another name'))
if (nameprefix =... |
'plot data from a `CMADataLogger` (using the files written by the logger).
Arguments
`fig`
figure number, by default 325
`iabscissa`
``0==plot`` versus iteration count,
``1==plot`` versus function evaluation number
`iteridx`
iteration indices to plot
Return `CMADataLogger` itself.
Examples
import cma
logger = cma.CMADa... | def plot(self, fig=None, iabscissa=1, iteridx=None, plot_mean=True, foffset=1e-19, x_opt=None, fontsize=10):
| dat = self.load(self.name_prefix)
try:
from matplotlib.pylab import figure, ioff, ion, subplot, semilogy, hold, plot, grid, axis, title, text, xlabel, isinteractive, draw, gcf
except ImportError:
ImportError('could not find matplotlib.pylab module, function plot() is ... |
'helper function for `plot()` that plots all what is
in the upper left subplot like fitness, sigma, etc.
Arguments
`iabscissa` in ``(0,1)``
0==versus fevals, 1==versus iteration
`foffset`
offset to fitness for log-plot
:See: `plot()`'
| @staticmethod
def plotdivers(dat, iabscissa, foffset):
| from matplotlib.pylab import semilogy, hold, grid, axis, title, text
fontsize = pylab.rcParams['font.size']
hold(False)
dfit = (dat.f[:, 5] - min(dat.f[:, 5]))
dfit[(dfit < 1e-98)] = np.NaN
if (dat.f.shape[1] > 7):
semilogy(dat.f[:, iabscissa], (abs(dat.f[:, [6, 7]]) + foffset), '-k')
... |
'rude downsampling of a `CMADataLogger` data file by `factor`, keeping
also the first `first` entries. This function is a stump and subject
to future changes.
Arguments
- `factor` -- downsampling factor
- `first` -- keep first `first` entries
- `switch` -- switch the new logger name to oldname+\'down\'
Details
``self.n... | def downsampling(self, factor=10, first=3, switch=True):
| newprefix = (self.name_prefix + 'down')
for name in CMADataLogger.names:
f = open(((newprefix + name) + '.dat'), 'w')
iline = 0
cwritten = 0
for line in open(((self.name_prefix + name) + '.dat')):
if ((iline < first) or ((iline % factor) == 0)):
f.writ... |
'displays selected data from (files written by) the class `CMADataLogger`.
Arguments
`idx`
indices corresponding to rows in the data file;
if idx is a scalar (int), the first two, then every idx-th,
and the last three rows are displayed. Too large index values are removed.
If ``len(idx) == 1``, only a single row is dis... | def disp(self, idx=100):
| filenameprefix = self.name_prefix
def printdatarow(dat, iteration):
'print data of iteration i'
i = np.where((dat.f[:, 0] == iteration))[0][0]
j = np.where((dat.std[:, 0] == iteration))[0][0]
print((((((('%5d' % int(dat.f[(i, 0)])) + (' %6d' % int(dat.f[(i, 1)]))) ... |
'TODO: check scaling of r-learing: seems worse than linear: 9e3 25e3 65e3 (10,20,40-D)'
| def __init__(self, x0, sigma0, randn=np.random.randn):
| self.N = len(x0)
N = self.N
self.dampi = (4 * N)
self.eta_r = ((0 / N) / 3)
self.mu = 1
self.use_abs_sigma = 1
self.use_abs_sigma_r = 1
self.randn = randn
self.x0 = array(x0, copy=True)
self.sigma0 = sigma0
self.cs = (1 / (N ** 0.5))
self.damps = 1
self.use_sign = 0
... |
'alias ``reset``, set all state variables to initial values'
| def initialize(self):
| N = self.N
self.mean = array(self.x0, copy=True)
self.sigma = self.sigma0
self.sigmai = np.ones(N)
self.ps = np.zeros(N)
self.r = np.zeros(N)
self.pr = 0
self.sigma_r = 0
|
'update'
| def tell(self, X, f):
| mu = (1 if self.mu else int((len(f) / 4)))
idx = np.argsort(f)[:mu]
zr = [self.zr[i] for i in idx]
Z = [self.Z[i] for i in idx]
X = [X[i] for i in idx]
xmean = np.mean(X, axis=0)
self.ps *= (1 - self.cs)
self.ps += ((((self.cs * (2 - self.cs)) ** 0.5) * (mu ** 0.5)) * np.mean(Z, axis=0))... |
'parameters are
`N`
dimension
`maxevals`
maximal value for ``self.evaluations``, where
``self.evaluations`` function calls are aggregated for
noise treatment. With ``maxevals == 0`` the noise
handler is (temporarily) "switched off". If `maxevals`
is a list, min value and (for >2 elements) median are
used to define mini... | def __init__(self, N, maxevals=10, aggregate=np.median, reevals=None, epsilon=1e-07, parallel=False):
| self.lam_reeval = reevals
self.epsilon = epsilon
self.parallel = parallel
self.theta = 0.5
self.cum = 0.3
self.alphasigma = (1 + (2 / (N + 10)))
self.alphaevals = (1 + (2 / (N + 10)))
self.alphaevalsdown = (self.alphaevals ** (-0.25))
self.evaluations = 1
self.minevals = 1
se... |
'proceed with noise measurement, set anew attributes ``evaluations``
(proposed number of evaluations to "treat" noise) and ``evaluations_just_done``
and return a factor for increasing sigma.
Parameters
`X`
a list/sequence/vector of solutions
`fit`
the respective list of function values
`func`
the objective function, ``... | def __call__(self, X, fit, func, ask=None, args=()):
| self.evaluations_just_done = 0
if ((not self.maxevals) or (self.lam_reeval == 0)):
return 1.0
res = self.reeval(X, fit, func, ask, args)
if (not len(res)):
return 1.0
self.update_measure()
return self.treat()
|
'return ``self.evaluations``, the number of evalutions to get a single fitness measurement'
| def get_evaluations(self):
| return self.evaluations
|
'adapt self.evaluations depending on the current measurement value
and return ``sigma_fac in (1.0, self.alphasigma)``'
| def treat(self):
| if (self.noiseS > 0):
self.evaluations = min(((self.evaluations * self.alphaevals), self.maxevals))
return self.alphasigma
else:
self.evaluations = max(((self.evaluations * self.alphaevalsdown), self.minevals))
return 1.0
|
'store two fitness lists, `fit` and ``fitre`` reevaluating some
solutions in `X`.
``self.evaluations`` evaluations are done for each reevaluated
fitness value.
See `__call__()`, where `reeval()` is called.'
| def reeval(self, X, fit, func, ask, args=()):
| self.fit = list(fit)
self.fitre = list(fit)
self.idx = self.indices(fit)
if (not len(self.idx)):
return self.idx
evals = (int(self.evaluations) if self.f_aggregate else 1)
fagg = (np.median if (self.f_aggregate is None) else self.f_aggregate)
for i in self.idx:
if self.epsilo... |
'updated noise level measure using two fitness lists ``self.fit`` and
``self.fitre``, return ``self.noiseS, all_individual_measures``.
Assumes that `self.idx` contains the indices where the fitness
lists differ'
| def update_measure(self):
| lam = len(self.fit)
idx = np.argsort((self.fit + self.fitre))
ranks = np.argsort(idx).reshape((2, lam))
rankDelta = ((ranks[0] - ranks[1]) - np.sign((ranks[0] - ranks[1])))
r = np.arange(1, (2 * lam))
limits = [(0.5 * (Mh.prctile(np.abs((r - ((ranks[(0, i)] + 1) - (ranks[(0, i)] > ranks[(1, i)])... |
'return the set of indices to be reevaluted for noise measurement,
taking the ``lam_reeval`` best from the first ``2 * lam_reeval + 2``
values.
Given the first values are the earliest, this is a useful policy also
with a time changing objective.'
| def indices(self, fit):
| lam = (self.lam_reeval if self.lam_reeval else (2 + (len(fit) / 20)))
reev = (int(lam) + ((lam % 1) > np.random.rand()))
return np.argsort(array(fit, copy=False)[:(2 * (reev + 1))])[:reev]
|
'Parameters
`func`
objective function
`x`
point in search space, middle point of the sections
`args`
arguments passed to `func`
`basis`
evaluated points are ``func(x + locations[j] * basis[i]) for i in len(basis) for j in len(locations)``,
see `do()`
`name`
filename where to save the result
`plot_cmd`
command used to p... | def __init__(self, func, x, args=(), basis=None, name=None, plot_cmd=(pylab.plot if pylab else None), load=True):
| self.func = func
self.args = args
self.x = x
self.name = (name if name else str(func).replace(' ', '_').replace('>', '').replace('<', ''))
self.plot_cmd = plot_cmd
self.basis = (np.eye(len(x)) if (basis is None) else basis)
try:
self.load()
if any((self.res['x'] != x)):
... |
'generates, plots and saves function values ``func(y)``,
where ``y`` is \'close\' to `x` (see `__init__()`). The data are stored in
the ``res`` attribute and the class instance is saved in a file
with (the weired) name ``str(func)``.
Parameters
`repetitions`
for each point, only for noisy functions is >1 useful. For
``... | def do(self, repetitions=1, locations=np.arange((-0.5), 0.6, 0.2), plot=True):
| if (not repetitions):
self.plot()
return
res = self.res
for i in range(len(self.basis)):
if (i not in res):
res[i] = {}
for dx in locations:
xx = (self.x + (dx * self.basis[i]))
xkey = dx
if (xkey not in res[i]):
... |
'plot the data we have, return ``self``'
| def plot(self, plot_cmd=None, tf=(lambda y: y)):
| if (not plot_cmd):
plot_cmd = self.plot_cmd
colors = 'bgrcmyk'
pylab.hold(False)
res = self.res
(flatx, flatf) = self.flattened()
minf = np.inf
for i in flatf:
minf = min((minf, min(flatf[i])))
addf = ((1e-09 - minf) if (minf <= 0) else 0)
for i in sorted(res.keys()):... |
'return flattened data ``(x, f)`` such that for the sweep through
coordinate ``i`` we have for data point ``j`` that ``f[i][j] == func(x[i][j])``'
| def flattened(self):
| flatx = {}
flatf = {}
for i in self.res:
if (type(i) is int):
flatx[i] = []
flatf[i] = []
for x in sorted(self.res[i]):
for d in sorted(self.res[i][x]):
flatx[i].append(x)
flatf[i].append(d)
return (flatx... |
'save to file'
| def save(self, name=None):
| import pickle
name = (name if name else self.name)
fun = self.func
del self.func
pickle.dump(self, open((name + '.pkl'), 'wb'))
self.func = fun
return self
|
'load from file'
| def load(self, name=None):
| import pickle
name = (name if name else self.name)
s = pickle.load(open((name + '.pkl'), 'rb'))
self.res = s.res
return self
|
'matrix exponential for a symmetric matrix'
| @staticmethod
def expms(A, eig=np.linalg.eigh):
| (D, B) = eig(A)
return np.dot(B, (np.exp(D) * B).T)
|
'clips argument (scalar or array) from below at lower'
| @staticmethod
def apos(x, lower=0):
| if (lower == 0):
return ((x > 0) * x)
else:
return (lower + ((x > lower) * (x - lower)))
|
'``prctile(data, 50)`` returns the median, but p_vals can
also be a sequence.
Provides for small samples better values than matplotlib.mlab.prctile,
however also slower.'
| @staticmethod
def prctile(data, p_vals=[0, 25, 50, 75, 100], sorted_=False):
| ps = ([p_vals] if np.isscalar(p_vals) else p_vals)
if (not sorted_):
data = sorted(data)
n = len(data)
d = []
for p in ps:
fi = (((p * n) / 100) - 0.5)
if (fi <= 0):
d.append(data[0])
elif (fi >= (n - 1)):
d.append(data[(-1)])
else:
... |
'return stochastic round: floor(nb) + (rand()<remainder(nb))'
| @staticmethod
def sround(nb):
| return ((nb // 1) + (np.random.rand(1)[0] < (nb % 1)))
|
'return likelihood of x for the normal density N(m, sigma**2 * Cinv**-1)'
| @staticmethod
def likelihood(x, m=None, Cinv=None, sigma=1, detC=None):
| if (m is None):
dx = x
else:
dx = (x - m)
n = len(x)
s2pi = ((2 * np.pi) ** (n / 2.0))
if (Cinv is None):
return ((exp((((- sum((dx ** 2))) / (sigma ** 2)) / 2)) / s2pi) / (sigma ** n))
if (detC is None):
detC = (1.0 / np.linalg.linalg.det(Cinv))
return (((exp... |
'return log-likelihood of `x` regarding the current sample distribution'
| @staticmethod
def loglikelihood(self, x, previous=False):
| if (previous and hasattr(self, 'lastiter')):
sigma = self.lastiter.sigma
Crootinv = self.lastiter._Crootinv
xmean = self.lastiter.mean
D = self.lastiter.D
elif (previous and (self.countiter > 1)):
raise _Error('no previous distribution parameters stored, ch... |
'eigendecomposition of a symmetric matrix, much slower than
`numpy.linalg.eigh`, return ``(EVals, Basis)``, the eigenvalues
and an orthonormal basis of the corresponding eigenvectors, where
``Basis[i]``
the i-th row of ``Basis``
columns of ``Basis``, ``[Basis[j][i] for j in range(len(Basis))]``
the i-th eigenvector wit... | @staticmethod
def eig(C):
| def tred2(n, V, d, e):
num_opt = False
for j in range(n):
d[j] = V[(n - 1)][j]
for i in range((n - 1), 0, (-1)):
h = 0.0
if (not num_opt):
scale = 0.0
for k in range(i):
scale = (scale + abs(d[k]))
... |
'Rotates the input array `x` with a fixed rotation matrix
(``self.dicMatrices[\'str(len(x))\']``)'
| def __call__(self, x, inverse=False):
| N = x.shape[0]
if (str(N) not in self.dicMatrices):
B = np.random.randn(N, N)
for i in xrange(N):
for j in xrange(0, i):
B[i] -= (np.dot(B[i], B[j]) * B[j])
B[i] /= (sum((B[i] ** 2)) ** 0.5)
self.dicMatrices[str(N)] = B
if inverse:
retu... |
'returns ``fun(rotation(x), *args)``, ie. `fun` applied to a rotated argument'
| def rot(self, x, fun, rot=1, args=()):
| if (len(np.shape(array(x))) > 1):
res = []
for x in x:
res.append(self.rot(x, fun, rot, args))
return res
if rot:
return fun(rotate(x, *args))
else:
return fun(x)
|
'returns sometimes np.NaN, otherwise fun(x)'
| def somenan(self, x, fun, p=0.1):
| if (np.random.rand(1) < p):
return np.NaN
else:
return fun(x)
|
'Random test objective function'
| def rand(self, x):
| return np.random.random(1)[0]
|
'Sphere (squared norm) test objective function'
| def sphere(self, x):
| return sum(((x + 0) ** 2))
|
'noise=10 does not work with default popsize, noise handling does not help'
| def noisysphere(self, x, noise=4.0, cond=1.0):
| return (self.elli(x, cond=cond) * (1 + ((noise * np.random.randn()) / len(x))))
|
'Sphere (squared norm) with sum x_i = 1 test objective function'
| def spherew(self, x):
| return (((-0.01) * x[0]) + ((abs(x[0]) ** (-2)) * sum((x[1:] ** 2))))
|
'Sphere (squared norm) test objective function'
| def partsphere(self, x):
| self.counter += 1
dim = len(x)
x = array([x[(i % dim)] for i in range((2 * dim))])
N = 8
i = (self.counter % dim)
f = sum((x[np.random.randint(dim, size=N)] ** 2))
return f
|
'asymmetric Sphere (squared norm) test objective function'
| def sectorsphere(self, x):
| return (sum((x ** 2)) + ((1000000.0 - 1) * sum((x[(x < 0)] ** 2))))
|
'Sphere (squared norm) test objective function constraint to the corner'
| def cornersphere(self, x):
| nconstr = (len(x) - 0)
if any((x[:nconstr] < 1)):
return np.NaN
return (sum((x ** 2)) - nconstr)
|
''
| def cornerelli(self, x):
| if any((x < 1)):
return np.NaN
return (self.elli(x) - self.elli(np.ones(len(x))))
|
''
| def cornerellirot(self, x):
| if any((x < 1)):
return np.NaN
return self.ellirot(x)
|
'Cigar test objective function'
| def cigar(self, x, rot=0, cond=1000000.0):
| if rot:
x = rotate(x)
x = ([x] if np.isscalar(x[0]) else x)
f = [((x[0] ** 2) + (cond * sum((x[1:] ** 2)))) for x in x]
return (f if (len(f) > 1) else f[0])
|
'Tablet test objective function'
| def tablet(self, x, rot=0):
| if rot:
x = rotate(x)
x = ([x] if np.isscalar(x[0]) else x)
f = [((1000000.0 * (x[0] ** 2)) + sum((x[1:] ** 2))) for x in x]
return (f if (len(f) > 1) else f[0])
|
'Cigtab test objective function'
| def cigtab(self, y):
| X = ([y] if np.isscalar(y[0]) else y)
f = [(((0.0001 * (x[0] ** 2)) + (10000.0 * (x[1] ** 2))) + sum((x[2:] ** 2))) for x in X]
return (f if (len(f) > 1) else f[0])
|
'Cigtab test objective function'
| def twoaxes(self, y):
| X = ([y] if np.isscalar(y[0]) else y)
N2 = (len(X[0]) // 2)
f = [((1000000.0 * sum((x[0:N2] ** 2))) + sum((x[N2:] ** 2))) for x in X]
return (f if (len(f) > 1) else f[0])
|
'Ellipsoid test objective function'
| def elli(self, x, rot=0, xoffset=0, cond=1000000.0, actuator_noise=0.0, both=False):
| if (not np.isscalar(x[0])):
return [self.elli(xi, rot) for xi in x]
if rot:
x = rotate(x)
N = len(x)
if actuator_noise:
x = (x + (actuator_noise * np.random.randn(N)))
ftrue = sum(((cond ** (np.arange(N) / (N - 1.0))) * ((x + xoffset) ** 2)))
alpha = (0.49 + (1.0 / N))
... |
'ellipsoid test objective function with "constraints"'
| def elliconstraint(self, x, cfac=100000000.0, tough=True, cond=1000000.0):
| N = len(x)
f = sum(((cond ** (np.arange(N)[(-1)::(-1)] / (N - 1))) * (x ** 2)))
cvals = ((x[0] + 1), ((x[0] + 1) + (100 * x[1])), ((x[0] + 1) - (100 * x[1])))
if tough:
f += (cfac * sum((max(0, c) for c in cvals)))
else:
f += (cfac * sum(((max(0, (c + 0.001)) ** 2) for c in cvals)))
... |
'Rosenbrock test objective function'
| def rosen(self, x, alpha=100.0):
| x = ([x] if np.isscalar(x[0]) else x)
f = [sum(((alpha * (((x[:(-1)] ** 2) - x[1:]) ** 2)) + ((1.0 - x[:(-1)]) ** 2))) for x in x]
return (f if (len(f) > 1) else f[0])
|
'Diffpow test objective function'
| def diffpow(self, x, rot=0):
| N = len(x)
if rot:
x = rotate(x)
return (sum((np.abs(x) ** (2.0 + ((4.0 * np.arange(N)) / (N - 1.0))))) ** 0.5)
|
'happy cat by HG Beyer'
| def ridgecircle(self, x, expo=0.5):
| a = len(x)
s = sum((x ** 2))
return (((((s - a) ** 2) ** (expo / 2)) + (s / a)) + (sum(x) / a))
|
'Rastrigin test objective function'
| def rastrigin(self, x):
| if (not np.isscalar(x[0])):
N = len(x[0])
return [((10 * N) + sum(((xi ** 2) - (10 * np.cos(((2 * np.pi) * xi)))))) for xi in x]
N = len(x)
return ((10 * N) + sum(((x ** 2) - (10 * np.cos(((2 * np.pi) * x))))))
|
'Schaffer function x0 in [-100..100]'
| def schaffer(self, x):
| N = len(x)
s = ((x[0:(N - 1)] ** 2) + (x[1:N] ** 2))
return sum(((s ** 0.25) * ((np.sin((50 * (s ** 0.1))) ** 2) + 1)))
|
'multimodal Schwefel function with domain -500..500'
| def schwefelmult(self, x, pen_fac=10000.0):
| y = ([x] if np.isscalar(x[0]) else x)
N = len(y[0])
f = array([((((418.9829 * N) - (1.27275661e-05 * N)) - sum((x * np.sin((np.abs(x) ** 0.5))))) + (pen_fac * sum(((abs(x) > 500) * ((abs(x) - 500) ** 2))))) for x in y])
return (f if (len(f) > 1) else f[0])
|
'ridge like linear function with one linear constraint'
| def lincon(self, x, theta=0.01):
| if (x[0] < 0):
return np.NaN
return ((theta * x[1]) + x[0])
|
'needs exponential number of steps in a non-increasing f-sequence.
x_0 = (-1,1,...,1)
See Jarre (2011) "On Nesterov\'s Smooth Chebyshev-Rosenbrock Function"'
| def rosen_nesterov(self, x, rho=100):
| f = (0.25 * ((x[0] - 1) ** 2))
f += (rho * sum((((x[1:] - (2 * (x[:(-1)] ** 2))) + 1) ** 2)))
return f
|
'Submit a job for local execution.'
| def submit_job(self, job):
| name = ('%s-%08d' % (job.name, job.id))
locker = Locker()
locker.unlock(grid_for(job))
proc = multiprocessing.Process(target=job_runner, args=[job])
proc.start()
if proc.is_alive():
log(('Submitted job as process: %d' % proc.pid))
return proc.pid
else:
log... |
'Schedule a job for execution.'
| def submit_job(job):
| pass
|
'Check on the status of executing jobs.'
| def is_proc_alive(job_ids):
| pass
|
'Notify any listeners for this user of a new event from an
event source.
Args:
stream_key(str): The stream the event came from.
stream_id(str): The new id for the stream the event came from.
time_now_ms(int): The current time in milliseconds.'
| def notify(self, stream_key, stream_id, time_now_ms):
| self.current_token = self.current_token.copy_and_advance(stream_key, stream_id)
self.last_notified_token = self.current_token
self.last_notified_ms = time_now_ms
noify_deferred = self.notify_deferred
users_woken_by_stream_counter.inc(stream_key)
with PreserveLoggingContext():
self.notify... |
'Remove this listener from all the indexes in the Notifier
it knows about.'
| def remove(self, notifier):
| for room in self.rooms:
lst = notifier.room_to_user_streams.get(room, set())
lst.discard(self)
notifier.user_to_user_stream.pop(self.user_id)
|
'Returns a deferred that is resolved when there is a new token
greater than the given token.
Args:
token: The token from which we are streaming from, i.e. we shouldn\'t
notify for things that happened before this.'
| def new_listener(self, token):
| if self.last_notified_token.is_after(token):
return _NotificationListener(defer.succeed(self.current_token))
else:
return _NotificationListener(self.notify_deferred.observe())
|
'Add a callback that will be called when some new data is available.
Callback is not given any arguments.'
| def add_replication_callback(self, cb):
| self.replication_callbacks.append(cb)
|
'Used by handlers to inform the notifier something has happened
in the room, room event wise.
This triggers the notifier to wake up any listeners that are
listening to the room, and any listeners for the users in the
`extra_users` param.
The events can be peristed out of order. The notifier will wait
until all previous... | def on_new_room_event(self, event, room_stream_id, max_room_stream_id, extra_users=[]):
| self.pending_new_room_events.append((room_stream_id, event, extra_users))
self._notify_pending_new_room_events(max_room_stream_id)
self.notify_replication()
|
'Notify for the room events that were queued waiting for a previous
event to be persisted.
Args:
max_room_stream_id(int): The highest stream_id below which all
events have been persisted.'
| def _notify_pending_new_room_events(self, max_room_stream_id):
| pending = self.pending_new_room_events
self.pending_new_room_events = []
for (room_stream_id, event, extra_users) in pending:
if (room_stream_id > max_room_stream_id):
self.pending_new_room_events.append((room_stream_id, event, extra_users))
else:
self._on_new_room_ev... |
'Notify any user streams that are interested in this room event'
| def _on_new_room_event(self, event, room_stream_id, extra_users=[]):
| preserve_fn(self.appservice_handler.notify_interested_services)(room_stream_id)
if self.federation_sender:
preserve_fn(self.federation_sender.notify_new_events)(room_stream_id)
if ((event.type == EventTypes.Member) and (event.membership == Membership.JOIN)):
self._user_joined_room(event.stat... |
'Used to inform listeners that something has happend event wise.
Will wake up all listeners for the given users and rooms.'
| def on_new_event(self, stream_key, new_token, users=[], rooms=[]):
| with PreserveLoggingContext():
with Measure(self.clock, 'on_new_event'):
user_streams = set()
for user in users:
user_stream = self.user_to_user_stream.get(str(user))
if (user_stream is not None):
user_streams.add(user_stream)
... |
'Used to inform replication listeners that something has happend
without waking up any of the normal user event streams'
| def on_new_replication_data(self):
| with PreserveLoggingContext():
self.notify_replication()
|
'Wait until the callback returns a non empty response or the
timeout fires.'
| @defer.inlineCallbacks
def wait_for_events(self, user_id, timeout, callback, room_ids=None, from_token=StreamToken.START):
| user_stream = self.user_to_user_stream.get(user_id)
if (user_stream is None):
current_token = (yield self.event_sources.get_current_token())
if (room_ids is None):
room_ids = (yield self.store.get_rooms_for_user(user_id))
user_stream = _NotifierUserStream(user_id=user_id, roo... |
'For the given user and rooms, return any new events for them. If
there are no new events wait for up to `timeout` milliseconds for any
new events to happen before returning.
If `only_keys` is not None, events from keys will be sent down.
If explicit_room_id is not set, the user\'s joined rooms will be polled
for event... | @defer.inlineCallbacks
def get_events_for(self, user, pagination_config, timeout, only_keys=None, is_guest=False, explicit_room_id=None):
| from_token = pagination_config.from_token
if (not from_token):
from_token = (yield self.event_sources.get_current_token())
limit = pagination_config.limit
(room_ids, is_joined) = (yield self._get_room_ids(user, explicit_room_id))
is_peeking = (not is_joined)
@defer.inlineCallbacks
de... |
'Notify the any replication listeners that there\'s a new event'
| def notify_replication(self):
| with PreserveLoggingContext():
deferred = self.replication_deferred
self.replication_deferred = ObservableDeferred(defer.Deferred())
deferred.callback(None)
for cb in self.replication_callbacks:
preserve_fn(cb)()
|
'Wait for an event to happen.
Args:
callback: Gets called whenever an event happens. If this returns a
truthy value then ``wait_for_replication`` returns, otherwise
it waits for another event.
timeout: How many milliseconds to wait for callback return a truthy
value.
Returns:
A deferred that resolves with the value ret... | @defer.inlineCallbacks
def wait_for_replication(self, callback, timeout):
| listener = _NotificationListener(None)
end_time = (self.clock.time_msec() + timeout)
while True:
listener.deferred = self.replication_deferred.observe()
result = (yield callback())
if result:
break
now = self.clock.time_msec()
if (end_time <= now):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.