desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Attach a callback to a hook.'
def add(self, name, func):
if (name not in self.hooks): raise ValueError(('Unknown hook name %s' % name)) was_empty = self._empty() self.hooks[name].append(func) if (self.app and was_empty and (not self._empty())): self.app.reset()
'Remove a callback from a hook.'
def remove(self, name, func):
if (name not in self.hooks): raise ValueError(('Unknown hook name %s' % name)) was_empty = self._empty() self.hooks[name].remove(func) if (self.app and (not was_empty) and self._empty()): self.app.reset()
'Create a virtual package that redirects imports (see PEP 302).'
def __init__(self, name, impmask):
self.name = name self.impmask = impmask self.module = sys.modules.setdefault(name, imp.new_module(name)) self.module.__dict__.update({'__file__': '<virtual>', '__path__': [], '__all__': [], '__loader__': self}) sys.meta_path.append(self)
'Return the current value for a key. The third `index` parameter defaults to -1 (last value).'
def get(self, key, default=None, index=(-1)):
if ((key in self.dict) or (default is KeyError)): return self.dict[key][index] return default
'Add a new value to the list of values for this key.'
def append(self, key, value):
self.dict.setdefault(key, []).append(value)
'Replace the list of values with a single value.'
def replace(self, key, value):
self.dict[key] = [value]
'Return a (possibly empty) list of values for a key.'
def getall(self, key):
return (self.dict.get(key) or [])
'Translate header field name to CGI/WSGI environ key.'
def _ekey(self, key):
key = key.replace('-', '_').upper() if (key in self.cgikeys): return key return ('HTTP_' + key)
'Return the header value as is (may be bytes or unicode).'
def raw(self, key, default=None):
return self.environ.get(self._ekey(key), default)
'Return the current default application.'
def __call__(self):
return self[(-1)]
'Add a new :class:`Bottle` instance to the stack'
def push(self, value=None):
if (not isinstance(value, Bottle)): value = Bottle() self.append(value) return value
'Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter s...
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
self.name = name self.source = (source.read() if hasattr(source, 'read') else source) self.filename = (source.filename if hasattr(source, 'filename') else None) self.lookup = map(os.path.abspath, lookup) self.encoding = encoding self.settings = self.settings.copy() self.settings.update(setti...
'Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.'
@classmethod def search(cls, name, lookup=[]):
if os.path.isfile(name): return name for spath in lookup: fname = os.path.join(spath, name) if os.path.isfile(fname): return fname for ext in cls.extentions: if os.path.isfile(('%s.%s' % (fname, ext))): return ('%s.%s' % (fname, ext))
'This reads or sets the global settings stored in class.settings.'
@classmethod def global_config(cls, key, *args):
if args: cls.settings[key] = args[0] else: return cls.settings[key]
'Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings.'
def prepare(self, **options):
raise NotImplementedError
'Render the template with the specified local variables and return a single byte or unicode string. If it is a byte string, the encoding must match self.encoding. This method must be thread-safe! Local variables may be provided in dictionaries (*args) or directly, as keywords (**kwargs).'
def render(self, *args, **kwargs):
raise NotImplementedError
'This matches comments and all kinds of quoted strings but does NOT match comments (#...) within quoted strings. (trust me)'
@lazy_attribute def re_pytokens(cls):
return re.compile('\n (\'\'(?!\')|""(?!")|\'{6}|"{6} # Empty strings (all 4 types)\n |\'(?:[^\\\\\']|\\\\.)+?\' # Single quotes (\')\n ...
'Removes comments (#...) from python code.'
@classmethod def split_comment(cls, code):
if ('#' not in code): return code subf = (lambda m: ('' if (m.group(0)[0] == '#') else m.group(0))) return re.sub(cls.re_pytokens, subf, code)
'Render the template using keyword arguments as local variables.'
def render(self, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg) stdout = [] self.execute(stdout, kwargs) return ''.join(stdout)
'Test to ensure new conf is properly merge with different servicegroup definition The first conf has all its servicegroup defined servicegroups.cfg and services.cfg The second conf has both, so that servicegroups defined ins services.cfg are genretaed by Shinken This lead to another generated id witch should be handled...
def test_reversed_list(self):
sg = self.sched.servicegroups.find_by_name('servicegroup_01') prev_id = sg.id reg = Regenerator() data = {'instance_id': 0} b = Brok('program_status', data) b.prepare() reg.manage_program_status_brok(b) reg.all_done_linking(0) self.setup_with_file('etc/shinken_reversed_list.cfg') ...
'Return the log messages stored as Broks into the collector. This also tests whether all objects collected by the collector are log entries.'
def _get_brok_log_messages(self, collector):
for obj in collector.list: self.assertIsInstance(obj, Brok) self.assertEqual(obj.type, 'log') data = cPickle.loads(obj.data) self.assertEqual(data.keys(), ['log']) (yield data['log'])
'test output using the human timestamp format'
def test_human_timestamp_format(self):
logger = self._prepare_logging() logger.setLevel(logging.INFO) logger.set_human_format(True) loglist = self.generic_tst(logger.info, 'Some ] log-message', [1, 1], ['^\\[\\d+\\] INFO:\\s+Some \\] log-message\\n$', '^\\[[^\\]]+] INFO:\\s+Some \\] log-message$']) time.strptime(l...
'test output after switching of the human timestamp format'
def test_reset_human_timestamp_format(self):
self.test_human_timestamp_format() logger.set_human_format(False) self.test_basic_logging_info()
'test output using the human timestamp format'
def test_human_timestamp_format(self):
shinken_logger.setLevel(INFO) self._collector = Collector() sys.stdout = StringIO() shinken_logger.handlers[0].stream = sys.stdout shinken_logger.load_obj(self._collector) shinken_logger.set_human_format(True) if isinstance(shinken_logger.handlers[0], ColorStreamHandler): loglist = s...
'test output after switching of the human timestamp format'
def test_reset_human_timestamp_format(self):
self.test_human_timestamp_format() logger.set_human_format(False) self.test_basic_logging_info_colored()
'test output after switching of the human timestamp format'
def test_reset_human_timestamp_format(self):
self.test_human_timestamp_format() logger.set_human_format(False) self.test_basic_logging_info()
'arbiter is always a bit special ..'
def create_daemon(self):
cls = self.daemon_cls return cls(daemons_config[cls], False, True, False, False, None, '')
'$HOSTOUTPUT$, $HOSTPERFDATA$, $HOSTACKAUTHOR$, $HOSTACKCOMMENT$, $SERVICEOUTPUT$, $SERVICEPERFDATA$, $SERVICEACKAUTHOR$, and $SERVICEACKCOMMENT$'
def test_illegal_macro_output_chars(self):
mr = self.get_mr() (svc, hst) = self.get_hst_svc() data = svc.get_data_for_checks() illegal_macro_output_chars = self.sched.conf.illegal_macro_output_chars print 'Illegal macros caracters:', illegal_macro_output_chars hst.output = 'monculcestdupoulet' dummy_call = 'special_macro!$HOSTO...
'Create a temporary input file and a temporary output-file.'
def __setup(self, inputlines):
outputfile = NamedTemporaryFile('w', suffix='.json', delete=False) outputfile.write('--- empty marker ---') outputfile.close() self.output_filename = outputfile.name time.sleep(1) inputfile = NamedTemporaryFile('w', suffix='.txt', delete=False) for line in inputlines: inputf...
'Cleanup the temporary files.'
def __cleanup(self):
os.remove(self.input_filename) os.remove(self.output_filename)
'https://github.com/naparuba/shinken/issues/1385'
def test_issue_1385(self):
tp = Timeperiod() tp.timeperiod_name = 'mercredi2-22-02' tp.resolve_daterange(tp.dateranges, 'wednesday 2 00:00-02:00,22:00-24:00') tp.resolve_daterange(tp.dateranges, 'thursday 2 ...
'Check that it is allowed to have a host with the "__ANTI-VIRG__" substring in its hostname'
def test_hostname_antivirg(self):
self.assertTrue(self.conf.conf_is_correct) hst = self.conf.hosts.find_by_name('test__ANTI-VIRG___0') self.assertIsNotNone(hst, "host 'test__ANTI-VIRG___0' not found") self.assertTrue(hst.is_correct(), ("config of host '%s' is not true" % hst.get_name()))
'Check that the semicolon is a comment delimiter'
def test_parsing_comment(self):
self.assertTrue(self.conf.conf_is_correct, 'config is not correct') hst = self.conf.hosts.find_by_name('test_host_1') self.assertIsNotNone(hst, "host 'test_host_1' not found") self.assertTrue(hst.is_correct(), ("config of host '%s' is not true" % hst.get_name()))
'Check that it is possible to have a host with a semicolon in its hostname The consequences of this aren\'t tested. We try just to send a command but I think that others programs which send commands don\'t think to escape the semicolon.'
def test_escaped_semicolon(self):
self.assertTrue(self.conf.conf_is_correct) hst = self.conf.hosts.find_by_name('test_host_2;with_semicolon') self.assertIsNotNone(hst, "host 'test_host_2;with_semicolon' not found") self.assertTrue(hst.is_correct(), ("config of host '%s' is not true" % hst.get_name())) comm...
'This is the main function that is called in the CONFIGURATION phase.'
def get_objects(self):
print '[Dummy] ask me for objects to return' r = {'hosts': []} h = {'name': 'dummy host from dummy arbiter module', 'register': '0'} r['hosts'].append(h) print '[Dummy] Returning to Arbiter the hosts:', r return r
'Build an init packet 00-127: IV 128-131: unix timestamp'
def send_init_packet(self, socket):
iv = ''.join([chr(self.rng.randrange(256)) for i in xrange(128)]) init_packet = struct.pack('!128sI', iv, int(time.mktime(time.gmtime()))) socket.send(init_packet) return iv
'Read the check result 00-01: Version 02-05: CRC32 06-09: Timestamp 10-11: Return code 12-75: hostname 76-203: service 204-715: output of the plugin 716-720: padding'
def read_check_result(self, data, iv):
if (len(data) != 720): return None if (self.encryption_method == 1): data = decrypt_xor(data, self.password) data = decrypt_xor(data, iv) (version, pad1, crc32, timestamp, rc, hostname_dirty, service_dirty, output_dirty, pad2) = struct.unpack('!hhIIh64s128s512sh', data) hostname ...
'Send a check result command to the arbiter'
def post_command(self, timestamp, rc, hostname, service, output):
if (len(service) == 0): extcmd = ('[%lu] PROCESS_HOST_CHECK_RESULT;%s;%d;%s\n' % (timestamp, hostname, rc, output)) else: extcmd = ('[%lu] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n' % (timestamp, hostname, service, rc, output)) print 'want to send', extcmd
'This is the main loop of the process when in \'external\' mode.'
def main(self):
self.interrupted = False backlog = 5 size = 8192 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect((self.host, self.port)) input = [server] databuffer = {} IVs = {} init = server.recv(size) print 'got init', init (iv, t) = struct.unpack('!128sI', in...
'defines self[key] = value'
def __setitem__(self, key, value):
self.data[key] = value
'defines self[key]'
def __getitem__(self, key):
return self.data[key]
'defines self[key] = value'
def __setitem__(self, key, value):
key = self.key(key) if (key in self.data_with_same_key): self.data_with_same_key[key] += [self.data[key]] elif (key in self.data): self.data_with_same_key[key] = [self.data[key]] self.data[key] = value
'defines self[key]'
def __getitem__(self, key):
return self.data[self.key(key)]
'remove only most current key-entry'
def __delitem__(self, key):
key = self.key(key) if (key in self.data_with_same_key): if (len(self.data_with_same_key[key]) == 1): self.data[key] = self.data_with_same_key.pop(key)[0] else: self.data[key] = self.data_with_same_key[key].pop((-1)) else: del self.data[key]
'compute the hash key of ``x``'
def key(self, x):
return tuple(x)
'initialize the best solution with `x`, `f`, and `evals`. Better solutions have smaller `f`-values.'
def __init__(self, x=None, f=np.inf, evals=None):
self.x = x self.x_geno = None self.f = (f if ((f is not None) and (f is not np.nan)) else np.inf) self.evals = evals self.evalsall = evals self.last = BlancClass() self.last.x = x self.last.f = f
'checks for better solutions in list `arx`, based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solutio...
def update(self, arx, xarchive=None, arf=None, evals=None):
if (arf is not None): minidx = np.nanargmin(arf) if (minidx is np.nan): return minarf = arf[minidx] if (type(arx) == BestSolution): if (self.evalsall is None): self.evalsall = arx.evalsall elif (arx.evalsall is not None): self.evalsall ...
'return ``(x, f, evals)``'
def get(self):
return (self.x, self.f, self.evals, self.x_geno)
'Argument bounds can be `None` or ``bounds[0]`` and ``bounds[1]`` are lower and upper domain boundaries, each is either `None` or a scalar or a list or array of appropriate size.'
def __init__(self, bounds=None):
self.bounds = bounds self.gamma = 1 self.weights_initialized = False self.hist = []
'return True, if any variable is bounded'
def has_bounds(self):
bounds = self.bounds if (bounds in (None, [None, None])): return False for i in xrange(bounds[0]): if ((bounds[0][i] is not None) and (bounds[0][i] > (- np.inf))): return True for i in xrange(bounds[1]): if ((bounds[1][i] is not None) and (bounds[1][i] < np.inf)): ...
'sets out-of-bounds components of ``x`` on the bounds. Arguments `bounds` can be `None`, in which case the "default" bounds are used, or ``[lb, ub]``, where `lb` and `ub` represent lower and upper domain bounds respectively that can be `None` or a scalar or a list or array of length ``len(self)`` code is more or less c...
def repair(self, x, bounds=None, copy=False, copy_always=False):
if (bounds is None): bounds = self.bounds if copy_always: x_out = array(x, copy=True) if (bounds not in (None, [None, None], (None, None))): x_out = (array(x, copy=True) if (copy and (not copy_always)) else x) if (bounds[0] is not None): if np.isscalar(bounds[0]):...
'returns the boundary violation penalty for `x` ,where `x` is a single solution or a list or array of solutions. If `bounds` is not `None`, the values in `bounds` are used, see `__init__`'
def __call__(self, x, archive, gp):
if (x in (None, (), [])): return x if (gp.bounds in (None, [None, None], (None, None))): return (0.0 if np.isscalar(x[0]) else ([0.0] * len(x))) x_is_single_vector = np.isscalar(x[0]) x = ([x] if x_is_single_vector else x) pen = [] for xi in x: xpheno = gp.pheno(archive[x...
'counts for each coordinate the number of feasible values in ``solutions`` and returns an array of length ``len(solutions[0])`` with the ratios. `solutions` is a list or array of repaired `Solution` instances'
def feasible_ratio(self, solutions):
count = np.zeros(len(solutions[0])) for x in solutions: count += (x.unrepaired == x) return (count / float(len(solutions)))
'updates the weights for computing a boundary penalty. Arguments `function_values` all function values of recent population of solutions `es` `CMAEvolutionStrategy` object instance, in particular the method `into_bounds` of the attribute `gp` of type `GenoPheno` is used. `bounds` not (yet) in use other than for ``bound...
def update(self, function_values, es, bounds=None):
if (bounds is None): bounds = self.bounds if ((bounds is None) or ((bounds[0] is None) and (bounds[1] is None))): return self N = es.N varis = ((es.sigma ** 2) * array(((N * [es.C]) if np.isscalar(es.C) else (es.C if np.isscalar(es.C[0]) else [es.C[i][i] for i in xrange(N)])))) dmean...
'return `GenoPheno` instance with fixed dimension `dim`. Keyword Arguments `scaling` the diagonal of a scaling transformation matrix, multipliers in the genotyp-phenotyp transformation, see `typical_x` `typical_x` ``pheno = scaling*geno + typical_x`` `bounds` (obsolete, might disappear) list with two elements, lower an...
def __init__(self, dim, scaling=None, typical_x=None, bounds=None, fixed_values=None, tf=None):
self.N = dim self.bounds = bounds self.fixed_values = fixed_values if (tf is not None): self.tf_pheno = tf[0] self.tf_geno = tf[1] print('WARNING in class GenoPheno: user defined transformations have not been tested thoroughly') else: ...
'Argument `y` is a phenotypic vector, return `y` put into boundaries, as a copy iff ``y != into_bounds(y)``. Note: this code is duplicated in `Solution.repair` and might disappear in future.'
def into_bounds(self, y, bounds=None, copy_never=False, copy_always=False):
bounds = (bounds if (bounds is not None) else self.bounds) if (bounds in (None, [None, None])): return (y if (not copy_always) else array(y, copy=True)) if (bounds[0] is not None): if (len(bounds[0]) not in (1, len(y))): raise ValueError((((('len(bounds[0]) = ' + str(len(bo...
'maps the genotypic input argument into the phenotypic space, boundaries are only applied if argument ``bounds is not None``, see help for class `GenoPheno`'
def pheno(self, x, bounds=None, copy=True, copy_always=False):
if (copy_always and (not copy)): raise ValueError((((('arguments copy_always=' + str(copy_always)) + ' and copy=') + str(copy)) + ' have inconsistent values')) if (self.isidentity and (bounds in (None, [None, None], (None, None)))): return (x if (not copy_always) else array(x, ...
'maps the phenotypic input argument into the genotypic space. If `bounds` are given, first `y` is projected into the feasible domain. In this case ``copy==False`` leads to a copy. by default a copy is made only to prevent to modify ``y`` method geno is only needed if external solutions are injected (geno(initial_soluti...
def geno(self, y, bounds=None, copy=True, copy_always=False, archive=None):
if ((archive is not None) and (bounds is not None)): try: return archive[y]['geno'] except: pass x = array(y, copy=((copy and (not self.isidentity)) or copy_always)) if (bounds is not None): x = self.into_bounds(x, bounds) if self.isidentity: retur...
'``xstart`` is a mandatory argument'
def __init__(self, xstart, **more_args):
self.xstart = xstart self.more_args = more_args self.initialize()
'(re-)set to the initial state'
def initialize(self):
self.countiter = 0 self.xcurrent = self.xstart[:] raise NotImplementedError('method initialize() must be implemented in derived class')
'abstract method, AKA "get" or "sample_distribution", deliver new candidate solution(s), a list of "vectors"'
def ask(self):
raise NotImplementedError('method ask() must be implemented in derived class')
'abstract method, AKA "update", prepare for next iteration'
def tell(self, solutions, function_values):
self.countiter += 1 raise NotImplementedError('method tell() must be implemented in derived class')
'abstract method, return satisfied termination conditions in a dictionary like ``{\'termination reason\': value, ...}``, for example ``{\'tolfun\': 1e-12}``, or the empty dictionary ``{}``. The implementation of `stop()` should prevent an infinite loop.'
def stop(self):
raise NotImplementedError('method stop() is not implemented')
'abstract method, display some iteration infos if ``self.iteration_counter % modulo == 0``'
def disp(self, modulo=None):
raise NotImplementedError('method disp() is not implemented')
'abstract method, return ``(x, f(x), ...)``, that is, the minimizer, its function value, ...'
def result(self):
raise NotImplementedError('method result() is not implemented')
'find minimizer of `objectivefct` by iterating over `OOOptimizer` `self` with verbosity `verb_disp`, using `BaseDataLogger` `logger` with at most `iterations` iterations. :: return self.result() + (self.stop(), self, logger) Example >>> import cma >>> res = cma.CMAEvolutionStrategy(7 * [0.1], 0.5).optimize(cma.fcts.ros...
def optimize(self, objectivefct, logger=None, verb_disp=20, iterations=None):
if (logger is None): if hasattr(self, 'logger'): logger = self.logger citer = 0 while (not self.stop()): if ((iterations is not None) and (citer >= iterations)): return self.result() citer += 1 X = self.ask() fitvals = [objectivefct(x) for x in...
'number of samples by default returned by` ask()`'
@property def popsize(self):
return self.sp.popsize
'return a dictionary with the termination status. With ``check==False``, the termination conditions are not checked and the status might not reflect the current situation.'
def stop(self, check=True):
if (check and (self.countiter > 0) and self.opts['termination_callback'] and (self.opts['termination_callback'] != str(self.opts['termination_callback']))): self.callbackstop = self.opts['termination_callback'](self) return self.stopdict((self if check else None))
'see class `CMAEvolutionStrategy`'
def __init__(self, x0, sigma0, inopts={}):
self.inputargs = dict(locals()) del self.inputargs['self'] self.inopts = inopts opts = Options(inopts).complement() if (opts['noise_handling'] and eval(opts['noise_handling'])): raise ValueError('noise_handling not available with class CMAEvolutionStrategy, use function ...
'get new candidate solutions, sampled from a multi-variate normal distribution and transformed to f-representation (phenotype) to be evaluated. Arguments `number` number of returned solutions, by default the population size ``popsize`` (AKA ``lambda``). `xmean` distribution mean `sigma` multiplier for internal sample w...
def ask(self, number=None, xmean=None, sigma_fac=1):
pop_geno = self.ask_geno(number, xmean, sigma_fac) pop_pheno = [self.gp.pheno(x, copy=True, bounds=self.gp.bounds) for x in pop_geno] if ((not self.gp.isidentity) or use_sent_solutions): if (((self.countiter % 30) / (self.popsize ** 0.5)) < 1): self.sent_solutions.truncate(0, ((self.coun...
'get new candidate solutions in genotyp, sampled from a multi-variate normal distribution. Arguments are `number` number of returned solutions, by default the population size `popsize` (AKA lambda). `xmean` distribution mean `sigma_fac` multiplier for internal sample width (standard deviation) `ask_geno` returns a list...
def ask_geno(self, number=None, xmean=None, sigma_fac=1):
if ((number is None) or (number < 1)): number = self.sp.popsize if (xmean is None): xmean = self.mean if (self.countiter == 0): self.tic = time.clock() self.elapsed_time = ElapsedTime() if self.opts['CMA_AII']: if (self.countiter == 0): self.aii = AII(...
'return ``pheno(self.mean - (geno(x) - self.mean))``. TODO: this implementation is yet experimental. Selectively mirrored sampling improves to a moderate extend but overadditively with active CMA for quite understandable reasons. Optimal number of mirrors are suprisingly small: 1,2,3 for maxlam=7,13,20 however note tha...
def get_mirror(self, x):
try: dx = (self.sent_solutions[x]['geno'] - self.mean) except: print('WARNING: use of geno is depreciated') dx = (self.gp.geno(x, copy=True) - self.mean) dx *= ((sum((self.randn(self.N) ** 2)) ** 0.5) / self.mahalanobisNorm(dx)) x = (self.mean - dx) y = self.gp...
'obsolete and subject to removal (TODO), return modified f-values such that for each mirror one becomes worst. This function is useless when selective mirroring is applied with no more than (lambda-mu)/2 solutions. Mirrors are leading and trailing values in ``f_values``.'
def mirror_penalized(self, f_values, idx):
assert (len(f_values) >= (2 * len(idx))) m = np.max(np.abs(f_values)) for i in len(idx): if (f_values[idx[i]] > f_values[((-1) - i)]): f_values[idx[i]] += m else: f_values[((-1) - i)] += m return f_values
'obsolete and subject to removal (TODO), return indices for negative ("active") update of the covariance matrix assuming that ``f_values[idx1[i]]`` and ``f_values[-1-i]`` are the corresponding mirrored values computes the index of the worse solution sorted by the f-value of the better solution. TODO: when the actual mi...
def mirror_idx_cov(self, f_values, idx1):
idx2 = np.arange((len(f_values) - 1), ((len(f_values) - 1) - len(idx1)), (-1)) f = [] for i in xrange(len(idx1)): f.append(min((f_values[idx1[i]], f_values[idx2[i]]))) return idx2[np.argsort(f)][(-1)::(-1)]
'samples `number` solutions and evaluates them on `func`, where each solution `s` is resampled until ``func(s) not in (numpy.NaN, None)``. Arguments `func` objective function `args` additional parameters for `func` `number` number of solutions to be sampled, by default population size ``popsize`` (AKA lambda) `xmean` m...
def ask_and_eval(self, func, args=(), number=None, xmean=None, sigma_fac=1, evaluations=1, aggregation=np.median):
popsize = self.sp.popsize if (number is not None): popsize = number selective_mirroring = True nmirrors = self.sp.lam_mirr if (popsize != self.sp.popsize): nmirrors = Mh.sround(((popsize * self.sp.lam_mirr) / self.sp.popsize)) assert (nmirrors <= (popsize // 2)) self.mirrors_...
'pass objective function values to prepare for next iteration. This core procedure of the CMA-ES algorithm updates all state variables, in particular the two evolution paths, the distribution mean, the covariance matrix and a step-size. Arguments `solutions` list or array of candidate solution points (of type `numpy.nd...
def tell(self, solutions, function_values, check_points=None, copy=False):
if self.flgtelldone: raise _Error('tell should only be called once per iteration') lam = len(solutions) if (lam != array(function_values).shape[0]): raise _Error(('for each candidate solution ' + 'a function value must be provided')) if ((l...
'return ``(xbest, f(xbest), evaluations_xbest, evaluations, iterations, pheno(xmean), effective_stds)``'
def result(self):
return (self.best.get() + (self.countevals, self.countiter, self.gp.pheno(self.mean), (((self.gp.scales * self.sigma) * self.sigma_vec) * (self.dC ** 0.5))))
'make sure that solutions fit to sample distribution, this interface will probably change. In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited.'
def clip_or_fit_solutions(self, pop, idx):
for k in idx: self.repair_genotype(pop[k])
'make sure that solutions fit to sample distribution, this interface will probably change. In particular the frequency of x - self.mean being long is limited.'
def repair_genotype(self, x):
mold = self.mean if (1 < 3): upper_length = ((self.N ** 0.5) + ((2 * self.N) / (self.N + 2))) fac = (self.mahalanobisNorm((x - mold)) / upper_length) if (fac > 1): x = (((x - mold) / fac) + mold) elif (11 < 3): return exp((np.tanh((((((upper_length * fac) ...
'update internal variables for sampling the distribution with the current covariance matrix C. This method is O(N^3), if C is not diagonal.'
def updateBD(self):
if (self.itereigenupdated == self.countiter): return if self.sp.neg.cmuexp: self.update_exponential(self.Zneg, (- self.sp.neg.cmuexp)) self.Zneg = np.zeros((self.N, self.N)) if ((self.sigma_vec is not 1) and (not np.all((self.sigma_vec == 1)))): self.C = dot(dot(np.diag(self....
'multiply C with a scalar and update all related internal variables (dC, D,...)'
def multiplyC(self, alpha):
self.C *= alpha if (self.dC is not self.C): self.dC *= alpha self.D *= (alpha ** 0.5)
'exponential update of C that guarantees positive definiteness, that is, instead of the assignment ``C = C + eta * Z``, C gets C**.5 * exp(eta * C**-.5 * Z * C**-.5) * C**.5. Parameter Z should have expectation zero, e.g. sum(w[i] * z[i] * z[i].T) - C if E z z.T = C. This function conducts two eigendecompositions, assu...
def update_exponential(self, Z, eta, BDpair=None):
if (eta == 0): return if BDpair: (B, D) = BDpair else: (D, B) = self.opts['CMA_eigenmethod'](self.C) D **= 0.5 Csi = dot(B, (B / D).T) Cs = dot(B, (B * D).T) self.C = dot(Cs, dot(Mh.expms((eta * dot(Csi, dot(Z, Csi))), self.opts['CMA_eigenmethod']), Cs))
'not yet implemented'
def _updateCholesky(self, A, Ainv, p, alpha, beta):
raise _Error('not yet implemented') alpha = float(alpha) beta = float(beta) y = np.dot(Ainv, p) y_sum = sum((y ** 2)) tmp = sqrt((1 + ((beta * y_sum) / alpha))) fac = ((sqrt(alpha) / sum((y ** 2))) * (tmp - 1)) facinv = ((1.0 / (sqrt(alpha) * sum((y ** 2)))) * (1 - (1.0 / tmp))) ...
'Given all "previous" candidate solutions and their respective function values, the state of a `CMAEvolutionStrategy` object can be reconstructed from this history. This is the purpose of function `feedForResume`. Arguments `X` (all) solution points in chronological order, phenotypic representation. The number of point...
def feedForResume(self, X, function_values):
if (self.countiter > 0): print('WARNING: feed should generally be used with a new object instance') if (len(X) != len(function_values)): raise _Error((((('number of solutions ' + str(len(X))) + ' and number function values ') + str(len(functi...
'reads dynamic parameters from property file (not implemented)'
def readProperties(self):
print('not yet implemented')
'compute the Mahalanobis norm that is induced by the adapted covariance matrix C times sigma**2. Argument A *genotype* difference `dx`. Example >>> import cma, numpy >>> es = cma.CMAEvolutionStrategy(numpy.ones(10), 1) >>> xx = numpy.random.randn(2, 10) >>> d = es.mahalanobisNorm(es.gp.geno(xx[0]-xx[1])) `d` is the dis...
def mahalanobisNorm(self, dx):
return (sqrt(sum((((self.D ** (-1)) * np.dot(self.B.T, dx)) ** 2))) / self.sigma)
'return C**0.5 times mat, where mat can be a vector or matrix. Not functional, because _Croot=C**0.5 is never computed (should be in updateBD)'
def timesCroot(self, mat):
print('WARNING: timesCroot is not yet tested') if ((self.opts['CMA_diagonal'] is True) or (self.countiter <= self.opts['CMA_diagonal'])): res = (self._Croot * mat.T).T else: res = np.dot(self._Croot, mat) return res
'return C**-1/2 times mat, where mat can be a vector or matrix'
def divCroot(self, mat):
print('WARNING: divCroot is not yet tested') if ((self.opts['CMA_diagonal'] is True) or (self.countiter <= self.opts['CMA_diagonal'])): res = (self._Crootinv * mat.T).T else: res = np.dot(self._Crootinv, mat) return res
'print annotation for `disp()`'
def disp_annotation(self):
print('Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec') sys.stdout.flush()
'prints some infos according to `disp_annotation()`, if ``iteration_counter % modulo == 0``'
def disp(self, modulo=None):
if (modulo is None): modulo = self.opts['verb_disp'] if modulo: if (((self.countiter - 1) % (10 * modulo)) < 1): self.disp_annotation() if ((self.countiter > 0) and (self.stop() or (self.countiter < 4) or ((self.countiter % modulo) < 1))): if self.opts['verb_time'...
'return a dictionary with default option values and description, calls `fmin([], [])`'
@staticmethod def defaults():
return fmin([], [])
'return list of options that can be changed at any time (not only be initialized), however the list might not be entirely up to date. The string \' #v \' in the default value indicates a \'versatile\' option that can be changed any time.'
@staticmethod def versatileOptions():
return tuple(sorted((i[0] for i in list(Options.defaults().items()) if (i[1].find(' #v ') > 0))))
'return an `Options` instance, either with the default options, if ``s is None``, or with all options whose name or description contains `s`, if `s` is a string (case is disregarded), or with entries from dictionary `s` as options, not complemented with default options or settings Returns: see above.'
def __init__(self, s=None, unchecked=False):
if (s is None): super(Options, self).__init__(Options.defaults()) elif (type(s) is str): super(Options, self).__init__(Options().match(s)) else: super(Options, self).__init__(s) if (not unchecked): for key in list(self.keys()): if (key not in Options.defaults(...
'initialize one or several options. Arguments `dict_or_str` a dictionary if ``val is None``, otherwise a key. If `val` is provided `dict_or_str` must be a valid key. `val` value for key Details Only known keys are accepted. Known keys are in `Options.defaults()`'
def init(self, dict_or_str, val=None, warn=True):
dic = dict_or_str if (val is not None): dic = {dict_or_str: val} for (key, val) in list(dic.items()): if (key not in Options.defaults()): if warn: print((('Warning in cma.Options.init(): key ' + str(key)) + ' ignored')) else: sel...
'set can assign versatile options from `Options.versatileOptions()` with a new value, use `init()` for the others. Arguments `dic` either a dictionary or a key. In the latter case, val must be provided `val` value for key `warn` bool, print a warning if the option cannot be changed and is therefore omitted This method ...
def set(self, dic, val=None, warn=True):
if (val is not None): dic = {dic: val} for (key, val) in list(dic.items()): if (key in Options.versatileOptions()): self[key] = val elif warn: print((('Warning in cma.Options.set(): key ' + str(key)) + ' ignored')) return self
'add all missing options with their default values'
def complement(self):
for key in Options.defaults(): if (key not in self): self[key] = Options.defaults()[key] return self
'return the subset of those options that are settable at any time. Settable options are in `versatileOptions()`, but the list might be incomlete.'
def settable(self):
return Options([i for i in list(self.items()) if (i[0] in Options.versatileOptions())])
'evaluate and return the value of option `key` on the fly, or returns those options whose name or description contains `key`, case disregarded. Details Keys that contain `filename` are not evaluated. For ``loc==None``, `self` is used as environment but this does not define `N`. :See: `eval()`, `evalall()`'
def __call__(self, key, default=None, loc=None):
try: val = self[key] except: return self.match(key) if (loc is None): loc = self try: if (type(val) is str): val = val.split('#')[0].strip() if ((type(val) == type('')) and (key.find('filename') < 0) and (key.find('mindx') < 0)): va...
'Evaluates and sets the specified option value in environment `loc`. Many options need `N` to be defined in `loc`, some need `popsize`. Details Keys that contain \'filename\' are not evaluated. For `loc` is None, the self-dict is used as environment :See: `evalall()`, `__call__`'
def eval(self, key, default=None, loc=None):
self[key] = self(key, default, loc) return self[key]
'Evaluates all option values in environment `loc`. :See: `eval()`'
def evalall(self, loc=None):
if ('N' in list(loc.keys())): popsize = self('popsize', Options.defaults()['popsize'], loc) for k in list(self.keys()): self.eval(k, Options.defaults()[k], {'N': loc['N'], 'popsize': popsize}) return self