_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q249000
Tree.get_leaves
train
def get_leaves(self): """ Get the list of all leaves. """
python
{ "resource": "" }
q249001
Tree.pt2leaf
train
def pt2leaf(self, x): """ Get the leaf which domain contains x. """ if self.leafnode: return self else: if x[self.split_dim] < self.split_value:
python
{ "resource": "" }
q249002
Tree.sample_random
train
def sample_random(self): """ Sample a point in a random leaf. """ if self.sampling_mode['volume']: # Choose a leaf weighted by volume, randomly if self.leafnode: return self.sample_bounds() else: split_ratio =...
python
{ "resource": "" }
q249003
Tree.sample_greedy
train
def sample_greedy(self): """ Sample a point in the leaf with the max progress. """ if self.leafnode: return self.sample_bounds() else: lp = self.lower.max_leaf_progress gp = self.greater.max_leaf_progress maxp =...
python
{ "resource": "" }
q249004
Tree.progress_all
train
def progress_all(self): """ Competence progress of the overall tree. """ return
python
{ "resource": "" }
q249005
Tree.progress_idxs
train
def progress_idxs(self, idxs): """ Competence progress on points of given indexes. """ if self.progress_measure == 'abs_deriv_cov': if len(idxs) <= 1: return 0 else: idxs = sorted(idxs)[- self.progress_win_size:] ...
python
{ "resource": "" }
q249006
Tree.fold_up
train
def fold_up(self, f_inter, f_leaf): """ Apply recursively the function f_inter from leaves to root, begining with function f_leaf on leaves. """ return f_leaf(self) if self.leafnode else f_inter(self,
python
{ "resource": "" }
q249007
F_to_minimize.f
train
def f(self, m): ''' Function to minimize ''' M = reshape(m,self.input_dim) n = M.shape[0] if M.shape[1] != self.input_dim: return 'Wrong input dimension'
python
{ "resource": "" }
q249008
InverseModel.from_forward
train
def from_forward(cls, fmodel, **kwargs): """Construst an inverse model from a forward model and constraints. """
python
{ "resource": "" }
q249009
InverseModel._random_x
train
def _random_x(self): """If the database is empty, generate a random vector."""
python
{ "resource": "" }
q249010
InverseModel.config
train
def config(self): """Return a string with the configuration""" return
python
{ "resource": "" }
q249011
Experiment.run
train
def run(self, n_iter=-1, bg=False): """ Run the experiment. :param int n_iter: Number of run iterations, by default will run until the last evaluation step. :param bool bg: whether to run in background (using a Thread) """ if n_iter == -1: if not self.eval_a...
python
{ "resource": "" }
q249012
Experiment.evaluate_at
train
def evaluate_at(self, eval_at, testcases, mode=None): """ Sets the evaluation interation indices. :param list eval_at: iteration indices where an evaluation should be performed :param numpy.array testcases: testcases used for evaluation """ self.eval_at = eval_at
python
{ "resource": "" }
q249013
CanonicalSystem.rollout
train
def rollout(self, **kwargs): """Generate x for open loop movements. """ if kwargs.has_key('tau'): timesteps = int(self.timesteps / kwargs['tau']) else: timesteps = self.timesteps self.x_track = np.zeros(timesteps)
python
{ "resource": "" }
q249014
discrete_random_draw
train
def discrete_random_draw(data, nb=1): ''' Code from Steve Nguyen''' data = np.array(data) if not data.any(): data = np.ones_like(data) data = data/data.sum()
python
{ "resource": "" }
q249015
OptimizedInverseModel.from_dataset
train
def from_dataset(cls, dataset, constraints = (), **kwargs): """Construct a optimized inverse model from an existing dataset. A LWLR forward model is constructed by default. """
python
{ "resource": "" }
q249016
OptimizedInverseModel._setuplimits
train
def _setuplimits(self, constraints): """Setup the limits for every initialiser.""" self.constraints = tuple(constraints)
python
{ "resource": "" }
q249017
OptimizedInverseModel._error
train
def _error(self, x): """Error function. Once self.y_desired has been defined, compute the error of input x
python
{ "resource": "" }
q249018
OptimizedInverseModel._error_dm
train
def _error_dm(self, m, dm, s): """Error function. Once self.goal has been defined, compute the error of input using the generalized forward model. """
python
{ "resource": "" }
q249019
Gaussian.generate
train
def generate(self, number=None): """Generates vectors from the Gaussian. @param number: optional, if given, generates more than one vector. @returns: generated vector(s), either as a one dimensional array
python
{ "resource": "" }
q249020
Gaussian.log_normal
train
def log_normal(self, x): """ Returns the log density of probability of x or the one dimensional array of all log probabilities if many vectors are given. @param x : may be of (n,) shape """ d = self.mu.shape[0] xc = x - self.mu if len(x.shape) == 1:
python
{ "resource": "" }
q249021
Gaussian.cond_gaussian
train
def cond_gaussian(self, dims, v): """ Returns mean and variance of the conditional probability defined by a set of dimension and at a given vector. @param dims : set of dimension to which respect conditional probability is taken @param v : vector defining the positi...
python
{ "resource": "" }
q249022
Environment.from_configuration
train
def from_configuration(cls, env_name, config_name='default'): """ Environment factory from name and configuration strings. :param str env_name: the name string of the environment :param str config_name: the configuration string for env_name Environment name strings are available using...
python
{ "resource": "" }
q249023
Environment.update
train
def update(self, m_ag, reset=True, log=True): """ Computes sensorimotor values from motor orders. :param numpy.array m_ag: a motor command with shape (self.conf.m_ndims, ) or a set of n motor commands of shape (n, self.conf.m_ndims) :param bool log: emit the motor and sensory values for loggin...
python
{ "resource": "" }
q249024
Databag.reset
train
def reset(self): """Reset the dataset to zero elements.""" self.data = [] self.size
python
{ "resource": "" }
q249025
Databag._build_tree
train
def _build_tree(self): """Build the KDTree for the observed data """ if not self.nn_ready:
python
{ "resource": "" }
q249026
Dataset.from_data
train
def from_data(cls, data): """ Create a dataset from an array of data, infering the dimension from the datapoint """ if len(data) == 0: raise ValueError("data array is
python
{ "resource": "" }
q249027
Dataset.from_xy
train
def from_xy(cls, x_array, y_array): """ Create a dataset from two arrays of data. :note: infering the dimensions for the first elements of each array. """ if len(x_array) == 0: raise ValueError("data array is empty.") dim_x, dim_y = len(x_array[0]), len(y_array[0...
python
{ "resource": "" }
q249028
Dataset.nn_x
train
def nn_x(self, x, k=1, radius=np.inf, eps=0.0, p=2): """Find the k nearest neighbors of x in the observed input data @see Databag.nn() for argument description @return distance and indexes of found nearest neighbors. """ assert len(x) == self.dim_x k_x = min(k,
python
{ "resource": "" }
q249029
Agent.from_classes
train
def from_classes(cls, im_model_cls, im_model_config, expl_dims, sm_model_cls, sm_model_config, inf_dims, m_mins, m_maxs, s_mins, s_maxs, n_bootstrap=0, context_mode=None): """Initialize agent class :param class im_model_cls: a subclass of InterestedMod...
python
{ "resource": "" }
q249030
Agent.choose
train
def choose(self, context_ms=None): """ Returns a point chosen by the interest model """ try: if self.context_mode is None: x = self.interest_model.sample() else: if self.context_mode["mode"] == 'mdmsds': if self.expl_dim...
python
{ "resource": "" }
q249031
Agent.infer
train
def infer(self, expl_dims, inf_dims, x): """ Use the sensorimotor model to compute the expected value on inf_dims given that the value on expl_dims is x. .. note:: This corresponds to a prediction if expl_dims=self.conf.m_dims and inf_dims=self.conf.s_dims and to inverse prediction if expl_dims=self.co...
python
{ "resource": "" }
q249032
PoppyEnvironment.compute_motor_command
train
def compute_motor_command(self, m_ag): """ Compute the motor command by restricting it
python
{ "resource": "" }
q249033
PoppyEnvironment.compute_sensori_effect
train
def compute_sensori_effect(self, m_env): """ Move the robot motors and retrieve the tracked object position. """ pos = {m.name: pos for m, pos in zip(self.motors, m_env)}
python
{ "resource": "" }
q249034
Learner.infer_order
train
def infer_order(self, goal, **kwargs): """Infer an order in order to obtain an effect close to goal, given the observation data of the model. :arg goal: a goal vector compatible with self.Sfeats :rtype:
python
{ "resource": "" }
q249035
Learner.predict_effect
train
def predict_effect(self, order, **kwargs): """Predict the effect of a goal. :arg order: an order vector compatible with self.Mfeats :rtype: same as order (if list, tuple, or pandas.Series, else tuple) """
python
{ "resource": "" }
q249036
ScipyInverseModel._enforce_bounds
train
def _enforce_bounds(self, x): """"Enforce the bounds on x if only infinitesimal violations occurs""" assert len(x) == len(self.bounds) x_enforced = [] for x_i, (lb, ub) in zip(x, self.bounds): if x_i < lb: if x_i > lb - (ub-lb)/1e10: x_enfo...
python
{ "resource": "" }
q249037
HPF.fit
train
def fit(self, counts_df, val_set=None): """ Fit Hierarchical Poisson Model to sparse count data Fits a hierarchical Poisson model to count data using mean-field approximation with either full-batch coordinate-ascent or mini-batch stochastic coordinate-ascent. Note ---- DataFrames and arrays passed to ...
python
{ "resource": "" }
q249038
HPF.predict_factors
train
def predict_factors(self, counts_df, maxiter=10, ncores=1, random_seed=1, stop_thr=1e-3, return_all=False): """ Gets latent factors for a user given her item counts This is similar to obtaining topics for a document in LDA. Note ---- This function will NOT modify any of the item parameters. Note ----...
python
{ "resource": "" }
q249039
JacobianInverseModel.infer_x
train
def infer_x(self, y_desired, **kwargs): """Provide an inversion of yq in the input space @param yq an array of float of length dim_y """ sigma = kwargs.get('sigma', self.sigma) k = kwargs.get('k', self.k) xq = self._guess_x(y_desired, k =...
python
{ "resource": "" }
q249040
ExperimentPool.from_settings_product
train
def from_settings_product(cls, environments, babblings, interest_models, sensorimotor_models, evaluate_at, testcases=None, same_testcases=False): """ Creates a ExperimentPool with the product of all the given settings. ...
python
{ "resource": "" }
q249041
NPendulumEnvironment.compute_sensori_effect
train
def compute_sensori_effect(self, m): """ This function generates the end effector position at the end of the movement. .. note:: The duration of the movement is 1000*self.dt .. note:: To use basis functions rather than step functions, set :use_basis_functions: to 1 """ if self....
python
{ "resource": "" }
q249042
NPendulumEnvironment.animate_pendulum
train
def animate_pendulum(self, m, path="anim_npendulum"): """This function generates few images at different instants in order to animate the pendulum. ..note:: this function destroys and creates the folder :anim_npendulum:. """ if os.path.exists(path): shutil.rmtree(path)
python
{ "resource": "" }
q249043
_fileToMatrix
train
def _fileToMatrix(file_name): """rudimentary method to read in data from a file""" # TODO: np.loadtxt() might be an alternative # try: if 1 < 3: lres = [] for line in open(file_name, 'r').readlines(): if len(line) > 0 and line[0] not in ('%', '#'):
python
{ "resource": "" }
q249044
pprint
train
def pprint(to_be_printed): """nicely formated print""" try: import pprint as pp # generate an instance PrettyPrinter # pp.PrettyPrinter().pprint(to_be_printed) pp.pprint(to_be_printed) except ImportError: if isinstance(to_be_printed, dict): print('{') ...
python
{ "resource": "" }
q249045
felli
train
def felli(x): """unbound test function, needed to test multiprocessor"""
python
{ "resource": "" }
q249046
BestSolution.update
train
def update(self, arx, xarchive=None, arf=None, evals=None): """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 ...
python
{ "resource": "" }
q249047
BoundaryHandlerBase.repair
train
def repair(self, x, copy_if_changed=True, copy_always=False): """projects infeasible values on the domain bound, might be overwritten by derived class """ if copy_always: x = array(x, copy=True) copy = False else: copy = copy_if_changed if self...
python
{ "resource": "" }
q249048
BoundaryHandlerBase.has_bounds
train
def has_bounds(self): """return True, if any variable is bounded""" bounds = self.bounds if bounds in (None, [None, None]): return False for ib, bound in enumerate(bounds):
python
{ "resource": "" }
q249049
BoundaryHandlerBase.is_in_bounds
train
def is_in_bounds(self, x): """not yet tested""" if self.bounds is None: return True for ib in [0, 1]: if self.bounds[ib] is None: continue for i in rglen(x):
python
{ "resource": "" }
q249050
BoundTransform.repair
train
def repair(self, x, copy_if_changed=True, copy_always=False): """transforms ``x`` into the bounded domain. ``copy_always`` option might disappear. """ copy = copy_if_changed if copy_always: x = array(x, copy=True)
python
{ "resource": "" }
q249051
BoundPenalty.repair
train
def repair(self, x, copy_if_changed=True, copy_always=False): """sets out-of-bounds components of ``x`` on the bounds. """ # TODO (old data): CPU(N,lam,iter=20,200,100): 3.3s of 8s for two bounds, 1.8s of 6.5s for one bound # remark: np.max([bounds[0], x]) is about 40 times slower than ...
python
{ "resource": "" }
q249052
BoundPenalty.update
train
def update(self, function_values, es): """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 ...
python
{ "resource": "" }
q249053
BoxConstraintsTransformationBase.initialize
train
def initialize(self): """initialize in base class""" self._lb = [b[0] for b in self.bounds] # can
python
{ "resource": "" }
q249054
BoxConstraintsLinQuadTransformation.is_feasible_i
train
def is_feasible_i(self, x, i): """return True if value ``x`` is in the invertible domain of variable ``i``
python
{ "resource": "" }
q249055
BoxConstraintsLinQuadTransformation._transform_i
train
def _transform_i(self, x, i): """return transform of x in component i""" x = self._shift_or_mirror_into_invertible_i(x, i) lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] if x < lb + al: ...
python
{ "resource": "" }
q249056
BoxConstraintsLinQuadTransformation._inverse_i
train
def _inverse_i(self, y, i): """return inverse of y in component i""" lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] if 1 < 3: if not lb <= y <= ub: raise ValueError('argum...
python
{ "resource": "" }
q249057
GenoPheno.pheno
train
def pheno(self, x, into_bounds=None, copy=True, copy_always=False, archive=None, iteration=None): """maps the genotypic input argument into the phenotypic space, see help for class `GenoPheno` Details ------- If ``copy``, values from ``x`` are copied if changed und...
python
{ "resource": "" }
q249058
GenoPheno.geno
train
def geno(self, y, from_bounds=None, copy_if_changed=True, copy_always=False, repair=None, archive=None): """maps the phenotypic input argument into the genotypic space, that is, computes essentially the inverse of ``pheno``. By default a copy is made only to prevent to...
python
{ "resource": "" }
q249059
OOOptimizer.optimize
train
def optimize(self, objective_fct, iterations=None, min_iterations=1, args=(), verb_disp=None, logger=None, call_back=None): """find minimizer of `objective_fct`. CAVEAT: the return value for `optimize` has changed to ``self``. Arguments --------- `objectiv...
python
{ "resource": "" }
q249060
CMAAdaptSigmaBase._update_ps
train
def _update_ps(self, es): """update the isotropic evolution path :type es: CMAEvolutionStrategy """ if not self.is_initialized_base: self.initialize_base(es) if self._ps_updated_iteration == es.countiter: return if es.countiter <= es.itereigenupda...
python
{ "resource": "" }
q249061
CMAEvolutionStrategy.stop
train
def stop(self, check=True): """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. """ if (check and self.countiter > 0 and self.opts['termination_callback'] an...
python
{ "resource": "" }
q249062
CMAEvolutionStrategy.random_rescale_to_mahalanobis
train
def random_rescale_to_mahalanobis(self, x): """change `x` like for injection, all on genotypic level"""
python
{ "resource": "" }
q249063
CMAEvolutionStrategy.prepare_injection_directions
train
def prepare_injection_directions(self): """provide genotypic directions for TPA and selective mirroring, with no specific length normalization, to be used in the coming iteration. Details: This method is called in the end of `tell`. The result is assigned to ``self.pop_i...
python
{ "resource": "" }
q249064
CMAEvolutionStrategy.inject
train
def inject(self, solutions): """inject a genotypic solution. The solution is used as direction relative to the distribution mean to compute a new candidate solution returned in method `ask_geno` which in turn is used in method `ask`. >>> import cma >>> es = cma.CMAEvolut...
python
{ "resource": "" }
q249065
CMAEvolutionStrategy.result_pretty
train
def result_pretty(self, number_of_runs=0, time_str=None, fbestever=None): """pretty print result. Returns ``self.result()`` """ if fbestever is None: fbestever = self.best.f s = (' after %i restart' + ('s' if number_of_runs > 1 else '')) \ ...
python
{ "resource": "" }
q249066
CMAEvolutionStrategy.clip_or_fit_solutions
train
def clip_or_fit_solutions(self, pop, idx): """make sure that solutions fit to sample distribution, this interface will probably change. In particular the frequency of long vectors appearing
python
{ "resource": "" }
q249067
CMAEvolutionStrategy.repair_genotype
train
def repair_genotype(self, x, copy_if_changed=False): """make sure that solutions fit to the sample distribution, this interface will probably change. In particular the frequency of x - self.mean being long is limited. """ x = array(x, copy=False) mold = array(self.mean, copy=Fa...
python
{ "resource": "" }
q249068
CMAEvolutionStrategy.decompose_C
train
def decompose_C(self): """eigen-decompose self.C and update self.dC, self.C, self.B. Known bugs: this might give a runtime error with CMA_diagonal / separable option on. """ if self.opts['CMA_diagonal']: _print_warning("this might fail with CMA_diagonal option on", ...
python
{ "resource": "" }
q249069
CMAEvolutionStrategy.feedForResume
train
def feedForResume(self, X, function_values): """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 ...
python
{ "resource": "" }
q249070
CMAOptions.defaults
train
def defaults(): """return a dictionary with default option values and description"""
python
{ "resource": "" }
q249071
CMAOptions.check
train
def check(self, options=None): """check for ambiguous keys and move attributes into dict""" self.check_values(options)
python
{ "resource": "" }
q249072
CMAOptions.init
train
def init(self, dict_or_str, val=None, warn=True): """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` ...
python
{ "resource": "" }
q249073
CMAOptions.complement
train
def complement(self): """add all missing options with their default values""" # add meta-parameters, given options have priority
python
{ "resource": "" }
q249074
CMAOptions.settable
train
def settable(self): """return the subset of those options that are settable at any time. Settable options are in `versatile_options()`, but the
python
{ "resource": "" }
q249075
CMAOptions.eval
train
def eval(self, key, default=None, loc=None, correct_key=True): """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. ...
python
{ "resource": "" }
q249076
CMAOptions.evalall
train
def evalall(self, loc=None, defaults=None): """Evaluates all option values in environment `loc`. :See: `eval()` """ self.check() if defaults is None: defaults = cma_default_options # TODO: this needs rather the parameter N instead of loc if 'N' in lo...
python
{ "resource": "" }
q249077
CMAOptions.match
train
def match(self, s=''): """return all options that match, in the name or the description, with string `s`, case is disregarded. Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
python
{ "resource": "" }
q249078
CMADataLogger.data
train
def data(self): """return dictionary with data. If data entries are None or incomplete, consider calling ``.load().data()`` to (re-)load the data from files first. """ d = {}
python
{ "resource": "" }
q249079
CMADataLogger.register
train
def register(self, es, append=None, modulo=None): """register a `CMAEvolutionStrategy` instance for logging, ``append=True`` appends to previous data logged under the same name, by default previous data are overwritten. """
python
{ "resource": "" }
q249080
CMADataLogger.save_to
train
def save_to(self, nameprefix, switch=False): """saves logger data to a different set of files, for ``switch=True`` also the loggers name prefix is switched to the new value """ if not nameprefix or not isinstance(nameprefix, basestring): raise _Error('filename prefix...
python
{ "resource": "" }
q249081
CMADataLogger.select_data
train
def select_data(self, iteration_indices): """keep only data of `iteration_indices`""" dat = self iteridx = iteration_indices dat.f = dat.f[np.where([x in iteridx for x in dat.f[:, 0]])[0], :] dat.D = dat.D[np.where([x in iteridx for x in dat.D[:, 0]])[0], :] try: ...
python
{ "resource": "" }
q249082
CMADataLogger.plot_correlations
train
def plot_correlations(self, iabscissa=1): """spectrum of correlation matrix and largest correlation""" if not hasattr(self, 'corrspec'): self.load() if len(self.corrspec) < 2: return self x = self.corrspec[:, iabscissa] y = self.corrspec[:, 6:] # principl...
python
{ "resource": "" }
q249083
CMADataLogger._enter_plotting
train
def _enter_plotting(self, fontsize=9): """assumes that a figure is open """ # interactive_status = matplotlib.is_interactive() self.original_fontsize = pyplot.rcParams['font.size']
python
{ "resource": "" }
q249084
CMADataLogger.downsampling
train
def downsampling(self, factor=10, first=3, switch=True, verbose=True): """ 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. Return self. Arguments --------- ...
python
{ "resource": "" }
q249085
NoiseHandler.update_measure
train
def update_measure(self): """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 """ lam = len(self.fit) ...
python
{ "resource": "" }
q249086
NoiseHandler.indices
train
def indices(self, fit): """return the set of indices to be reevaluated for noise measurement. Given the first values are the earliest, this is a useful policy also with a time changing objective. """ ## meta_parameters.noise_reeval_multiplier == 1.0 lam_reev = 1...
python
{ "resource": "" }
q249087
Sections.plot
train
def plot(self, plot_cmd=None, tf=lambda y: y): """plot the data we have, return ``self``""" if not plot_cmd: plot_cmd = self.plot_cmd colors = 'bgrcmyk' pyplot.hold(False) res = self.res flatx, flatf = self.flattened() minf = np.inf for i in f...
python
{ "resource": "" }
q249088
Sections.save
train
def save(self, name=None): """save to file""" import pickle name = name if name else self.name
python
{ "resource": "" }
q249089
Sections.load
train
def load(self, name=None): """load from file""" import pickle name = name if
python
{ "resource": "" }
q249090
Misc.loglikelihood
train
def loglikelihood(self, x, previous=False): """return log-likelihood of `x` regarding the current sample distribution""" # testing of original fct: MC integrate must be one: mean(p(x_i)) * volume(where x_i are uniformely sampled) # for i in xrange(3): print mean([cma.likelihood(20*r-10, dim * [0...
python
{ "resource": "" }
q249091
FitnessFunctions.noisysphere
train
def noisysphere(self, x, noise=2.10e-9, cond=1.0, noise_offset=0.10): """noise=10 does not work with default popsize,
python
{ "resource": "" }
q249092
FitnessFunctions.cigar
train
def cigar(self, x, rot=0, cond=1e6, noise=0): """Cigar test objective function""" if rot: x = rotate(x) x = [x] if isscalar(x[0]) else x # scalar into list f =
python
{ "resource": "" }
q249093
FitnessFunctions.tablet
train
def tablet(self, x, rot=0): """Tablet test objective function""" if rot and rot is not fcts.tablet: x = rotate(x)
python
{ "resource": "" }
q249094
FitnessFunctions.elli
train
def elli(self, x, rot=0, xoffset=0, cond=1e6, actuator_noise=0.0, both=False): """Ellipsoid test objective function""" if not isscalar(x[0]): # parallel evaluation return [self.elli(xi, rot) for xi in x] # could save 20% overall if rot: x = rotate(x) N = len(x) ...
python
{ "resource": "" }
q249095
FitnessFunctions.elliconstraint
train
def elliconstraint(self, x, cfac=1e8, tough=True, cond=1e6): """ellipsoid test objective function with "constraints" """ 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]) ...
python
{ "resource": "" }
q249096
FitnessFunctions.rosen
train
def rosen(self, x, alpha=1e2): """Rosenbrock test objective function""" x = [x] if isscalar(x[0]) else x # scalar into list f = [sum(alpha *
python
{ "resource": "" }
q249097
FitnessFunctions.diffpow
train
def diffpow(self, x, rot=0): """Diffpow test objective function""" N = len(x) if rot: x = rotate(x)
python
{ "resource": "" }
q249098
FitnessFunctions.ridgecircle
train
def ridgecircle(self, x, expo=0.5): """happy cat by HG Beyer""" a = len(x)
python
{ "resource": "" }
q249099
FitnessFunctions.rastrigin
train
def rastrigin(self, x): """Rastrigin test objective function""" if not isscalar(x[0]): N = len(x[0]) return [10 *
python
{ "resource": "" }