Return a list of probabilities proportional to fitnesses.
545440
def _fitnesses_to_probabilities(fitnesses):
    """"""
    # Do not allow negative fitness values
    min_fitness = min(fitnesses)
    if min_fitness < 0.0:
        # Make smallest fitness value 0
        fitnesses = map(lambda f: f - min_fitness, fitnesses)

    fitness_sum = sum(fitnesses)

    # Generate probabilities
    # Creates a list of increasing values.
    # The greater the gap between two values, the greater the probability.
    # Ex. [0.1, 0.23, 0.56, 1.0]
    prob_sum = 0.0
    probabilities = []
    for fitness in fitnesses:
        if fitness < 0:
            raise ValueError(
                "Fitness cannot be negative, fitness = {}.".format(fitness))
        prob_sum += (fitness / fitness_sum)
        probabilities.append(prob_sum)
    probabilities[-1] += 0.0001  # to compensate for rounding errors

    return probabilities
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
1339658
def find_pareto_front(population):
    

    pareto_front = set(range(len(population)))

    for i in range(len(population)):
        if i not in pareto_front:
            continue

        ind1 = population[i]
        for j in range(i + 1, len(population)):
            ind2 = population[j]

            # if individuals are equal on all objectives, mark one of them (the first encountered one) as dominated
            # to prevent excessive growth of the Pareto front
            if ind2.fitness.dominates(ind1.fitness) or ind1.fitness == ind2.fitness:
                pareto_front.discard(i)

            if ind1.fitness.dominates(ind2.fitness):
                pareto_front.discard(j)

    return pareto_front
661861
def eval_fitness(self, chromosome):
        
        score = 0

        number = self.translator.translate_gene(chromosome.genes[0])

        for factor in self.factors:
            if number % factor == 0:
                score += 1
            else:
                score -= 1

        # check for optimal solution
        if score == len(self.factors):
            min_product = functools.reduce(lambda a,b: a * b, self.factors)

            if number + min_product > self.max_encoded_val:
                print("Found best solution:", number)
                self.found_best = True

        # scale number of factors achieved/missed by ratio of
        # the solution number to the maximum possible integer
        # represented by binary strings of the given length
        return score * number / self.max_encoded_val
570716
def rankingEval(self):
		'''
		
		'''
		fitnessAll = numpy.zeros(self.length)
		fitnessNorm = numpy.zeros(self.length)

		for i in range(self.length):
			self.Ind[i].fitnessEval()
			fitnessAll[i] = self.Ind[i].fitness

		maxFitness = fitnessAll.max()
		for i in range(self.length):
			fitnessNorm[i] = (maxFitness - fitnessAll[i]) / maxFitness
		fitnessSorted = fitnessNorm.argsort()

		# Compute the selection probabilities of each individual
		probability = numpy.zeros(self.length)
		S = 2.0
		for i in range(self.length):
			probability[fitnessSorted[i]] = ((2-S)/self.length) + (2*i*(S-1))/(self.length*(self.length-1))
		self.rankingComputed = 1
		self.fitness = 	fitnessAll

		return [fitnessAll, fitnessSorted[::-1], probability]
663267
def SUSSelection(self, mating_pool_size):
		'''
		
		'''
		A = numpy.zeros(self.length)
		mating_pool = numpy.zeros(mating_pool_size)
		r = numpy.random.random()/float(mating_pool_size)
		[F,S,P] = self.rankingEval()
		
		P_Sorted = numpy.zeros(self.length)
		for i in range(self.length):
			P_Sorted[i] = P[S[i]]
	
		for i in range(self.length):
			A[i] = P_Sorted[0:(i+1)].sum()

		i = 0
		j = 0
		while j < mating_pool_size:
			i = 0
			while A[i] <= r:
				i += 1
			mating_pool[j] = S[i]
			j += 1 
			r += (1/float(mating_pool_size))

		return mating_pool
449190
def calcDrawingProbs(self):
        

        wmg = self.wmg
        phi = self.phi

        # We say the weight of the candidate in position i is phi^i.
        weights = []
        for i in range(0, len(wmg.keys())):
            weights.append(phi**i)

        # Calculate the probabilty that an item at each weight is drawn.
        totalWeight = sum(weights)
        for i in range(0, len(wmg.keys())):
            weights[i] = weights[i]/totalWeight

        return weights
1327341
def best_genomes(self, n):
        """"""
        def key(g):
            return g.fitness

        return sorted(self.most_fit_genomes, key=key, reverse=True)[:n]
866581
def _prob_match(self, features):
        

        # compute the probabilities
        probs = self.kernel.predict_proba(features)

        # get the position of match probabilities
        classes = list(self.kernel.classes_)
        match_class_position = classes.index(1)

        return probs[:, match_class_position]
284195
def MakeProbs(self):
        """"""
        for hypo, odds in self.Items():
            self.Set(hypo, Probability(odds))
795243
def probabilities(self) -> bk.BKTensor:
        
        value = bk.absolute(self.tensor)
        return value * value
908449
@Override
	protected double[] probabilities(
		final Seq<Phenotype<G, C>> population,
		final int count
	) {
		assert population != null : "Population must not be null. ";
		assert !population.isEmpty() : "Population is empty.";
		assert count > 0 : "Population to select must be greater than zero. ";

		final double N = population.size();
		final double[] probabilities = new double[population.size()];

		if (N == 1) {
			probabilities[0] = 1;
		} else {
			for (int i = probabilities.length; --i >= 0; ) {
				probabilities[probabilities.length - i - 1] =
					(_nminus + (_nplus - _nminus)*i/(N - 1))/N;
			}
		}

		return probabilities;
	}
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
778281
def convenience_calc_probs(self, params):
        
        orig_nest_coefs, betas = self.convenience_split_params(params)
        natural_nest_coefs = nc.naturalize_nest_coefs(orig_nest_coefs)

        args = [natural_nest_coefs,
                betas,
                self.design,
                self.rows_to_obs,
                self.rows_to_nests]
        kwargs = {"chosen_row_to_obs": self.chosen_row_to_obs,
                  "return_type": "long_and_chosen_probs"}

        probability_results = general_calc_probabilities(*args, **kwargs)

        return probability_results
1247329
def get_distbins(start=100, bins=2500, ratio=1.01):
    
    b = np.ones(bins, dtype="float64")
    b[0] = 100
    for i in range(1, bins):
        b[i] = b[i - 1] * ratio
    bins = np.around(b).astype(dtype="int")
    binsizes = np.diff(bins)
    return bins, binsizes
1140888
def _adjust_probability_vec_best(population, fitnesses, probability_vec,
                                 adjust_rate):
    """"""
    best_solution = max(zip(fitnesses, population))[1]

    # Shift probabilities towards best solution
    return _adjust(probability_vec, best_solution, adjust_rate)
119546
def weighted_choice(self, probabilities, key):
        """"""

        total = sum(x[0] for x in probabilities)
        choice = total * self._random(key)

        for probability, option in probabilities:
            choice -= probability
            if choice <= 0:
                return option