Assigns fitnesses to parameters.

        Notes
        -----
        Uses `self.eval_fn` to evaluate each member of target.
        Parameters
        ---------

        targets
            Parameter values for each member of the population.
340747
def assign_fitnesses(self, targets):
        
        self._evals = len(targets)
        px_parameters = zip([self.specification] * len(targets),
                            [self.sequences] * len(targets),
                            [self.parse_individual(x) for x in targets])
        if (self._cores == 1) or (self.mp_disabled):
            models = map(self.build_fn, px_parameters)
            fitnesses = map(self.eval_fn, models)
        else:
            with futures.ProcessPoolExecutor(
                    max_workers=self._cores) as executor:
                models = executor.map(self.build_fn, px_parameters)
                fitnesses = executor.map(self.eval_fn, models)
        tars_fits = list(zip(targets, fitnesses))
        if self._store_params:
            self.parameter_log.append(
                [(self.parse_individual(x[0]), x[1]) for x in tars_fits])
        for ind, fit in tars_fits:
            ind.fitness.values = (fit,)
        return
1233430
void assignToRangeVariable(RangeVariable rangeVar, int rangeVarIndex,
                               HsqlArrayList exprList, boolean isJoin) {

        if (exprList.isEmpty()) {
            return;
        }

        colIndexSetEqual.clear();
        colIndexSetOther.clear();

        for (int j = 0, size = exprList.size(); j < size; j++) {
            Expression e = (Expression) exprList.get(j);

            if (rangeVar.hasIndexCondition()) {
                rangeVar.addCondition(e, isJoin);
                exprList.set(j, null);

                continue;
            }

            if (e.getIndexableExpression(rangeVar) == null) {
                rangeVar.addCondition(e, isJoin);
                exprList.set(j, null);

                continue;
            }

            // can use index
            int type = e.getType();

            switch (type) {

                default : {
                    int colIndex = e.getLeftNode().getColumnIndex();

                    colIndexSetOther.add(colIndex);

                    break;
                }
                case OpTypes.EQUAL :
                    if (e.exprSubType == OpTypes.ANY_QUANTIFIED) {
                        Index index = rangeVar.rangeTable.getIndexForColumn(
                            e.getLeftNode().nodes[0].getColumnIndex());

// code to disable IN optimisation
//                        index = null;
                        if (index != null
                                && inExpressions[rangeVarIndex] == null) {
                            inExpressions[rangeVarIndex] = e;

                            inExpressionCount++;
                        } else {
                            rangeVar.addCondition(e, isJoin);
                        }

                        exprList.set(j, null);

                        continue;
                    }

                // $FALL-THROUGH$
                case OpTypes.IS_NULL : {
                    int colIndex = e.getLeftNode().getColumnIndex();

                    colIndexSetEqual.add(colIndex);

                    break;
                }
                case OpTypes.NOT : {
                    int colIndex =
                        e.getLeftNode().getLeftNode().getColumnIndex();

                    colIndexSetOther.add(colIndex);

                    break;
                }
            }
        }

        boolean isEqual = true;
        Index   idx = rangeVar.rangeTable.getIndexForColumns(colIndexSetEqual);

        if (idx == null) {
            isEqual = false;
            idx     = rangeVar.rangeTable.getIndexForColumns(colIndexSetOther);
        }

        // different procedure for subquery tables
        if (idx == null && rangeVar.rangeTable.isSessionBased) {
            if (!colIndexSetEqual.isEmpty()) {
                int[] cols = colIndexSetEqual.toArray();

                idx = rangeVar.rangeTable.getIndexForColumns(cols);
            }

            if (idx == null && !colIndexSetOther.isEmpty()) {
                int[] cols = colIndexSetOther.toArray();

                idx = rangeVar.rangeTable.getIndexForColumns(cols);
            }
        }

        // no index found
        if (idx == null) {
            for (int j = 0, size = exprList.size(); j < size; j++) {
                Expression e = (Expression) exprList.get(j);

                if (e != null) {
                    rangeVar.addCondition(e, isJoin);
                }
            }

            return;
        }

        // index found
        int[] cols     = idx.getColumns();
        int   colCount = cols.length;

        if (isEqual && colCount > 1) {
            Expression[] firstRowExpressions = new Expression[cols.length];

            for (int j = 0; j < exprList.size(); j++) {
                Expression e = (Expression) exprList.get(j);

                if (e == null) {
                    continue;
                }

                int type = e.getType();

                if (type == OpTypes.EQUAL) {
                    int offset =
                        ArrayUtil.find(cols, e.getLeftNode().getColumnIndex());

                    if (offset != -1 && firstRowExpressions[offset] == null) {
                        firstRowExpressions[offset] = e;

                        exprList.set(j, null);

                        continue;
                    }
                }

                // not used in index lookup
                rangeVar.addCondition(e, isJoin);
                exprList.set(j, null);
            }

            boolean hasNull = false;

            for (int i = 0; i < firstRowExpressions.length; i++) {
                Expression e = firstRowExpressions[i];

                if (e == null) {
                    if (colCount == cols.length) {
                        colCount = i;
                    }

                    hasNull = true;

                    continue;
                }

                if (hasNull) {
                    rangeVar.addCondition(e, isJoin);

                    firstRowExpressions[i] = null;
                }
            }

            rangeVar.addIndexCondition(firstRowExpressions, idx, colCount,
                                       isJoin);

            return;
        }

        for (int j = 0; j < exprList.size(); j++) {
            Expression e = (Expression) exprList.get(j);

            if (e == null) {
                continue;
            }

            if (rangeVar.hasIndexCondition()) {
                rangeVar.addCondition(e, isJoin);
                exprList.set(j, null);

                continue;
            }

            boolean isIndexed = false;

            if (e.getType() == OpTypes.NOT
                    && cols[0]
                       == e.getLeftNode().getLeftNode().getColumnIndex()) {
                isIndexed = true;
            }

            if (cols[0] == e.getLeftNode().getColumnIndex()) {
                if (e.getRightNode() != null
                        && !e.getRightNode().isCorrelated()) {
                    isIndexed = true;
                }

                if (e.getType() == OpTypes.IS_NULL) {
                    isIndexed = true;
                }
            }

            if (isIndexed) {
                rangeVar.addIndexCondition(e, idx, isJoin);
            } else {
                rangeVar.addCondition(e, isJoin);
            }

            exprList.set(j, null);
        }
    }
739754
def set_weights(params, new_params):
        
        for param, new_param in zip(params, new_params):
            param.data.copy_(new_param.data)
1058292
def set_parameters(self):
        
        for key in (ADMITTED_STR_PARAMETERS + ADMITTED_FLOAT_PARAMETERS +
                    ADMITTED_SET_PARAMETERS):
            try:
                val = getattr(self.gmpe, key)
            except AttributeError:
                pass
            else:
                setattr(self, key, val)
650011
def get_fitness(self, chromosome):
        
        fitness = self.fitness_cache.get(chromosome.dna)

        if fitness is None:
            fitness = self.eval_fitness(chromosome)
            self.fitness_cache[chromosome.dna] = fitness

        return fitness
400757
def _initialize_pop(self, pop_size):
        """"""
        self.toolbox.register("individual", self._generate)
        self.toolbox.register("population", tools.initRepeat,
                              list, self.toolbox.individual)
        self.population = self.toolbox.population(n=pop_size)
        self.assign_fitnesses(self.population)
        self._model_count += len(self.population)
        return
252212
def optimize_ordering(fwtour, clm, phase, cpus):
    
    from .chic import score_evaluate_M

    # Prepare input files
    tour_contigs = clm.active_contigs
    tour_sizes = clm.active_sizes
    tour_M = clm.M
    tour = clm.tour
    signs = clm.signs
    oo = clm.oo

    def callback(tour, gen, phase, oo):
        fitness = tour.fitness if hasattr(tour, "fitness") else None
        label = "GA{}-{}".format(phase, gen)
        if fitness:
            fitness = "{0}".format(fitness).split(",")[0].replace("(", "")
            label += "-" + fitness
        if gen % 20 == 0:
            print_tour(fwtour, tour, label, tour_contigs, oo, signs=signs)
        return tour

    callbacki = partial(callback, phase=phase, oo=oo)
    toolbox = GA_setup(tour)
    toolbox.register("evaluate", score_evaluate_M,
                     tour_sizes=tour_sizes, tour_M=tour_M)
    tour, tour_fitness = GA_run(toolbox, ngen=1000, npop=100, cpus=cpus,
                                callback=callbacki)
    clm.tour = tour

    return tour
629438
def evaluator(self, candidates, args):
        """"""
        fitness = []
        if self._use_ants:
            for candidate in candidates:
                total = 0
                for c in candidate:
                    total += c.value
                fitness.append(total)
        else:
            for candidate in candidates:
                total_value = 0
                total_weight = 0
                for c, i in zip(candidate, self.items):
                    total_weight += c * i[0]
                    total_value += c * i[1]
                if total_weight > self.capacity:
                    fitness.append(self.capacity - total_weight)
                else:
                    fitness.append(total_value)
        return fitness
672080
def add_parameters(parser):
    """"""
    group = parser.add_argument_group('Evaluation arguments')

    group.add_argument('--eval-batch-size', type=int, default=1024)

    # Datasets
    group.add_argument(
        '--similarity-datasets', type=str,
        default=nlp.data.word_embedding_evaluation.word_similarity_datasets,
        nargs='*',
        help='Word similarity datasets to use for intrinsic evaluation.')
    group.add_argument(
        '--similarity-functions', type=str,
        default=nlp.embedding.evaluation.list_evaluation_functions(
            'similarity'), nargs='+',
        help='Word similarity functions to use for intrinsic evaluation.')
    group.add_argument(
        '--analogy-datasets', type=str, default=['GoogleAnalogyTestSet'],
        nargs='*',
        help='Word similarity datasets to use for intrinsic evaluation.')
    group.add_argument(
        '--analogy-functions', type=str,
        default=nlp.embedding.evaluation.list_evaluation_functions('analogy'),
        nargs='+',
        help='Word analogy functions to use for intrinsic evaluation. ')

    ## Analogy evaluation specific arguments
    group.add_argument(
        '--analogy-dont-exclude-question-words', action='store_true',
        help=('Exclude input words from valid output analogies.'
              'The performance of word embeddings on the analogy task '
              'is around 0% accuracy if input words are not excluded.'))
401565
def _set_parameters(self, parameters):
        """"""
        for theta in self.variables['theta']:
            val = 1.0
            # TODO: improve approach for initializing parameters.
            if parameters is not None:
                if theta.name in parameters:
                    val = parameters[theta.name]
            # Add parameter.
            
            self.link_parameters(Param(theta.name, val, None))
691518
def calculate_fitness(self):
        """"""
        if self.fitness is not None:
            raise Exception(
                "You are calculating the fitness of agent {}, ".format(self.id)
                + "but they already have a fitness"
            )

        said_blue = self.infos(type=Meme)[0].contents == "blue"

        proportion = float(
            max(
                self.network.nodes(type=RogersEnvironment)[0].infos(),
                key=attrgetter("id"),
            ).contents
        )
        self.proportion = proportion
        is_blue = proportion > 0.5

        if said_blue is is_blue:
            self.score = 1
        else:
            self.score = 0

        is_asocial = self.infos(type=LearningGene)[0].contents == "asocial"

        e = 2
        b = 1
        c = 0.3 * b
        baseline = c + 0.0001

        self.fitness = (baseline + self.score * b - is_asocial * c) ** e
362606
def run_opt(self, popsize, numgen, processors,
                plot=False, log=False, **kwargs):
        
        self._params['popsize'] = popsize
        self._params['numgen'] = numgen
        self._params['processors'] = processors
        self._params['plot'] = plot
        self._params['log'] = log
        # allows us to pass in additional arguments e.g. neighbours
        self._params.update(**kwargs)
        self.halloffame = tools.HallOfFame(1)
        self.stats = tools.Statistics(lambda thing: thing.fitness.values)
        self.stats.register("avg", numpy.mean)
        self.stats.register("std", numpy.std)
        self.stats.register("min", numpy.min)
        self.stats.register("max", numpy.max)
        self.logbook = tools.Logbook()
        self.logbook.header = ["gen", "evals"] + self.stats.fields
        self._params['model_count'] = 0
        start_time = datetime.datetime.now()
        self.initialize_pop()
        for g in range(self._params['numgen']):
            self.update_pop()
            self.halloffame.update(self.population)
            self.logbook.record(gen=g, evals=self._params['evals'],
                                **self.stats.compile(self.population))
            print(self.logbook.stream)
        end_time = datetime.datetime.now()
        time_taken = end_time - start_time
        self._params['time_taken'] = time_taken
        print("Evaluated {0} models in total".format(
            self._params['model_count']))
        print("Best fitness is {0}".format(self.halloffame[0].fitness))
        print("Best parameters are {0}".format(self.parse_individual(
            self.halloffame[0])))
        for i, entry in enumerate(self.halloffame[0]):
            if entry > 0.95:
                print(
                    "Warning! Parameter {0} is at or near maximum allowed "
                    "value\n".format(i + 1))
            elif entry < -0.95:
                print(
                    "Warning! Parameter {0} is at or near minimum allowed "
                    "value\n".format(i + 1))
        if self._params['log']:
            self.log_results()
        if self._params['plot']:
            print('----Minimisation plot:')
            plt.figure(figsize=(5, 5))
            plt.plot(range(len(self.logbook.select('min'))),
                     self.logbook.select('min'))
            plt.xlabel('Iteration', fontsize=20)
            plt.ylabel('Score', fontsize=20)
632801
def fitness(self, v):
        ""
        base = self._base
        if base._classifier:
            if base._multiple_outputs:
                hy = SparseArray.argmax(v.hy)
                fit_func = base._fitness_function
                if fit_func == 'macro-F1' or fit_func == 'a_F1':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.a_F1(base._y_klass, hy, base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'DotF1' or fit_func == 'g_F1':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.g_F1(base._y_klass, hy, base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'DotRecallDotPrecision' or fit_func == 'g_g_recall_precision':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.g_g_recall_precision(base._y_klass, hy,
                                                               base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'BER' or fit_func == 'a_recall':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.a_recall(base._y_klass, hy, base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'DotRecall' or fit_func == 'g_recall':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.g_recall(base._y_klass, hy,
                                                   base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'macro-Precision' or fit_func == 'a_precision':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.a_precision(base._y_klass, hy,
                                                      base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'DotPrecision' or fit_func == 'g_precision':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.g_precision(base._y_klass, hy,
                                                      base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'accDotMacroF1':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.accDotMacroF1(base._y_klass, hy,
                                                        base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'macro-RecallF1':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.macroRecallF1(base._y_klass, hy,
                                                        base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'F1':
                    f1_score = self.score
                    f1_index = self._base._F1_index
                    index = self.min_class if f1_index < 0 else f1_index
                    mf1, mf1_v = f1_score.F1(index, base._y_klass,
                                             hy, base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'RecallDotPrecision' or fit_func == 'g_recall_precision':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.g_recall_precision(self.min_class,
                                                             base._y_klass,
                                                             hy, base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                elif fit_func == 'ER' or fit_func == 'accuracy':
                    f1_score = self.score
                    mf1, mf1_v = f1_score.accuracy(base._y_klass,
                                                   hy, base._mask_ts.index)
                    v._error = mf1_v - 1
                    v.fitness = mf1 - 1
                else:
                    raise RuntimeError('Unknown fitness function %s' % base._fitness_function)
            else:
                v.fitness = -base._ytr.SSE(v.hy * base._mask)
        else:
            if base._multiple_outputs:
                _ = np.mean([a.SAE(b.mul(c)) for a, b, c in zip(base._ytr, v.hy, base._mask)])
                v.fitness = - _
            else:
                v.fitness = -base._ytr.SAE(v.hy * base._mask)
849672
def calc_fitness(self,X,labels,fit_choice,sel):
        

        if 'lexicase' in sel:
            # return list(map(lambda yhat: self.f_vec[fit_choice](labels,yhat),X))
            return np.asarray(
                              [self.proper(self.f_vec[fit_choice](labels,
                                                        yhat)) for yhat in X],
                                                        order='F')
            # return list(Parallel(n_jobs=-1)(delayed(self.f_vec[fit_choice])(labels,yhat) for yhat in X))
        else:
            # return list(map(lambda yhat: self.f[fit_choice](labels,yhat),X))
            return np.asarray([self.f[fit_choice](labels,yhat) for yhat in X],
                            order='F').reshape(-1)
1113452
def set(self, instance, value, **kwargs):
        
        value = self.preprocess_value(value)
        existing_uids = self.get_backreferences_for(instance)

        if not value and not existing_uids:
            logger.warning("Field and value is empty!")
            return

        if not self.multiValued and len(value) > 1:
            raise ValueError("Multiple values given for single valued field {}"
                             .format(repr(self)))

        set_uids = []
        for val in value:
            if api.is_uid(val):
                set_uids.append(val)
            elif api.is_object(val):
                set_uids.append(api.get_uid(val))
            else:
                logger.error("Target has no UID: %s/%s" % (val, value))

        sub = filter(lambda uid: uid not in set_uids, existing_uids)
        add = filter(lambda uid: uid not in existing_uids, set_uids)

        for uid in set(existing_uids + set_uids):
            # The object to link
            target = api.get_object(uid)
            # Add reference to object
            if uid in add:
                __traceback_info__ = (instance, uid, value, existing_uids)
                self.add_reference(instance, target, **kwargs)
            # Delete reference to object
            elif uid in sub:
                self.del_reference(instance, target, **kwargs)
407672
def eval_objfn(self):
        

        fval = self.obfn_f(self.X)
        gval = self.obfn_g(self.X)
        obj = fval + gval
        return (obj, fval, gval)
263153
def set_prob_type(cls, problem_type, classification_type, eval_type):
        
        assert problem_type in problem_type_list, 'Need to set Problem Type'
        if problem_type == 'classification':
            assert classification_type in classification_type_list,\
                                            'Need to set Classification Type'
        assert eval_type in eval_type_list, 'Need to set Evaluation Type'
        
        cls.problem_type = problem_type
        cls.classification_type = classification_type
        cls.eval_type = eval_type
        
        if cls.problem_type == 'classification':
            print 'Setting Problem:{}, Type:{}, Eval:{}'.format(cls.problem_type,
                                                                cls.classification_type,
                                                                cls.eval_type)

        elif cls.problem_type == 'regression':
            print 'Setting Problem:{}, Eval:{}'.format(cls.problem_type,
                                                        cls.eval_type)

        return