Makes a weighted choice between several options.

        Probabilities is a list of 2-tuples, (probability, option). The
        probabilties don't need to add up to anything, they are automatically
        scaled.
434450
def weighted_choice(self, probabilities, key):
        """"""

        try:
            choice = self.values[key].lower()
        except KeyError:
            # override not set.
            result = super(OverridableParameters, self)\
                .weighted_choice(probabilities, key)
            if hasattr(result, "__call__"):
                self.results[key] = result.__name__
            else:
                self.results[key] = str(result)
            return result

        # Find the matching key (case insensitive)
        for probability, option in probabilities:
            if str(option).lower() == choice:
                self.results[key] = option
                return option

        # for function or class-type choices, also check __name__
        for probability, option in probabilities:
            if option.__name__.lower() == choice:
                self.results[key] = option.__name__
                return option

        assert False, "Invalid value provided"
1184188
def choose(key, *choices)
    all_choices = choices.flatten
    index = (get_unit(key) * all_choices.length).floor
    index = all_choices.length - 1 if index > all_choices.length - 1
    all_choices[index]
  end
413545
def choices(cls):
        
        # "natural" order, aka as given when instantiating
        if not hasattr(cls, '__choices_'):
            cls.__choices_ = tuple([c.choice for c in list(cls)])
        return cls.__choices_
633426
def _is_valid_options_weights_list(value):
    ''''''
    return ((isinstance(value, list)) and
            len(value) > 1 and
            (all(isinstance(opt, tuple) and
                 len(opt) == 2 and
                 isinstance(opt[1], (int, float))
                 for opt in value)))
907157
def choose(s, possibilities, threshold=.6):
    
    if not possibilities: return None
    if s in possibilities: return s
    if s == '': return None
    startswith = [x for x in possibilities if x.lower().startswith(s.lower())]
    if len(startswith) == 1: return startswith[0]
    contained = [x for x in possibilities if s.lower() in x.lower()]
    if len(contained) == 1: return contained[0]
    best = max([(x, Levenshtein.jaro_winkler(s, x, .05)) for x in possibilities], key=itemgetter(1))
    if best[1] < threshold:
        #print 'did you mean %s?' % best[0]
        return None
    return best[0]
358138
def choices(self, choices):
        

        if choices is not None and len(choices) > 0:
            self.has_choices = True

        self._choices = choices
803071
def classify(self, table, weighted_choice=False, transform=None):
        
        assert table.shape[1] == self.numgrp
        if weighted_choice:
            if transform is not None:
                probs = transform_fn(table.copy(), transform)  #
            else:
                probs = table.copy()
            cmprobs = probs.cumsum(1)
            logger.info('Probabilities\n{}'.format(probs))
            r = np.random.random(cmprobs.shape[0])
            search = np.apply_along_axis(np.searchsorted, 1, cmprobs, r) # Not very efficient
            assignment = np.diag(search)
        else:
            probs = table
            assignment = np.where(probs==probs.max(1)[:, np.newaxis])[1]
        logger.info('Assignment\n{}'.format(assignment))
        assignment = self._fill_empty_groups(probs, assignment)  # don't want empty groups
        new_partition = Partition(tuple(assignment))
        self.set_partition(new_partition)
1017538
private SortedClassProbability[] sortByDescendingClassProbability(String[] domainValues, double[] classProbabilities) {
    assert (classProbabilities.length == domainValues.length);
    SortedClassProbability[] arr = new SortedClassProbability[domainValues.length];
    for (int i = 0; i < domainValues.length; i++) {
      arr[i] = new SortedClassProbability();
      arr[i].name = domainValues[i];
      arr[i].probability = classProbabilities[i];
    }
    Arrays.sort(arr, Collections.reverseOrder());
    return arr;
  }
671719
def _convert_choices(self, choices):
        

        # Check that each new constant is unique.
        constants = [c[0] for c in choices]
        constants_doubles = [c for c in constants if constants.count(c) > 1]
        if constants_doubles:
            raise ValueError("You cannot declare two constants with the same constant name. "
                             "Problematic constants: %s " % list(set(constants_doubles)))

        # Check that none of the new constants already exists.
        bad_constants = set(constants).intersection(self.constants)
        if bad_constants:
            raise ValueError("You cannot add existing constants. "
                             "Existing constants: %s." % list(bad_constants))

        # Check that none of the constant is an existing attributes
        bad_constants = [c for c in constants if hasattr(self, c)]
        if bad_constants:
            raise ValueError("You cannot add constants that already exists as attributes. "
                             "Existing attributes: %s." % list(bad_constants))

        # Check that each new value is unique.
        values = [c[1] for c in choices]
        values_doubles = [c for c in values if values.count(c) > 1]
        if values_doubles:
            raise ValueError("You cannot declare two choices with the same name."
                             "Problematic values: %s " % list(set(values_doubles)))

        # Check that none of the new values already exists.
        try:
            bad_values = set(values).intersection(self.values)
        except TypeError:
            raise ValueError("One value cannot be used in: %s" % list(values))
        else:
            if bad_values:
                raise ValueError("You cannot add existing values. "
                                 "Existing values: %s." % list(bad_values))

        # We can now add each choice.
        for choice_tuple in choices:

            # Convert the choice tuple in a ``ChoiceEntry`` instance if it's not already done.
            # It allows to share choice entries between a ``Choices`` instance and its subsets.
            choice_entry = choice_tuple
            if not isinstance(choice_entry, self.ChoiceEntryClass):
                choice_entry = self.ChoiceEntryClass(choice_entry)

            # Append to the main list the choice as expected by django: (value, display name).
            self.append(choice_entry.choice)
            # And the ``ChoiceEntry`` instance to our own internal list.
            self.entries.append(choice_entry)

            # Make the value accessible via an attribute (the constant being its name).
            setattr(self, choice_entry.constant, choice_entry.value)

            # Fill dicts to access the ``ChoiceEntry`` instance by its constant, value or display..
            self.constants[choice_entry.constant] = choice_entry
            self.values[choice_entry.value] = choice_entry
            self.displays[choice_entry.display] = choice_entry

        return constants
578920
def predict_proba(self, L):
        
        n = L.shape[0]
        Y_p = np.random.rand(n, self.k)
        Y_p /= Y_p.sum(axis=1).reshape(-1, 1)
        return Y_p
854442
function selectWithValidation(choices) {
	// Validate argument is an array
	if(!choices || !choices.length) {
		throw new Error("Randomly Select: invalid argument, please provide a non-empty array");
	}

	// Validate that:
	// - each array entry has a 'chance' and 'result' property
	// - each 'chance' field is a number
	// - at least one result has a positive non-zero chance
	let atLeastOneChoiceHasNonZeroChance = false;
	for(let i = 0; i < choices.length; i++) {
		if(!exists(choices[i]) || !exists(choices[i].chance) || !exists(choices[i].result)) {
			throw new Error("Randomly Select: invalid argument, each array entry " +
				"must be an object with 'chance' and 'result' properties");
		} else if(typeof choices[i].chance !== 'number' || choices[i].chance < 0) {
			throw new Error("Randomly Select: invalid argument, 'chance' must be a positive number: " +
				JSON.stringify(choices[i].chance));
		} else if(choices[i].chance > 0) {
			atLeastOneChoiceHasNonZeroChance = true;
		}
	}

	if(!atLeastOneChoiceHasNonZeroChance) {
		throw new Error("Randomly Select: invalid arguments, all results have zero weight");
	}

	// Do the actual random selection and return the result
	return selectWithoutValidation(choices);
}
541809
def options(self, value):
        
        if value is None:
            value = []
        assert isinstance(value, list)
        self._options = value
614882
public List<PermutationSolution<Integer>> doCrossover(double probability, List<PermutationSolution<Integer>> parents) {
    List<PermutationSolution<Integer>> offspring = new ArrayList<>(2);

    offspring.add((PermutationSolution<Integer>) parents.get(0).copy()) ;
    offspring.add((PermutationSolution<Integer>) parents.get(1).copy()) ;

    int permutationLength = parents.get(0).getNumberOfVariables() ;

    if (crossoverRandomGenerator.getRandomValue() < probability) {
      int cuttingPoint1;
      int cuttingPoint2;

      // STEP 1: Get two cutting points
      cuttingPoint1 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);
      cuttingPoint2 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);
      while (cuttingPoint2 == cuttingPoint1)
        cuttingPoint2 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);

      if (cuttingPoint1 > cuttingPoint2) {
        int swap;
        swap = cuttingPoint1;
        cuttingPoint1 = cuttingPoint2;
        cuttingPoint2 = swap;
      }

      // STEP 2: Get the subchains to interchange
      int replacement1[] = new int[permutationLength];
      int replacement2[] = new int[permutationLength];
      for (int i = 0; i < permutationLength; i++)
        replacement1[i] = replacement2[i] = -1;

      // STEP 3: Interchange
      for (int i = cuttingPoint1; i <= cuttingPoint2; i++) {
        offspring.get(0).setVariableValue(i, parents.get(1).getVariableValue(i));
        offspring.get(1).setVariableValue(i, parents.get(0).getVariableValue(i));

        replacement1[parents.get(1).getVariableValue(i)] = parents.get(0).getVariableValue(i) ;
        replacement2[parents.get(0).getVariableValue(i)] = parents.get(1).getVariableValue(i) ;
      }

      // STEP 4: Repair offspring
      for (int i = 0; i < permutationLength; i++) {
        if ((i >= cuttingPoint1) && (i <= cuttingPoint2))
          continue;

        int n1 = parents.get(0).getVariableValue(i);
        int m1 = replacement1[n1];

        int n2 = parents.get(1).getVariableValue(i);
        int m2 = replacement2[n2];

        while (m1 != -1) {
          n1 = m1;
          m1 = replacement1[m1];
        }

        while (m2 != -1) {
          n2 = m2;
          m2 = replacement2[m2];
        }

        offspring.get(0).setVariableValue(i, n1);
        offspring.get(1).setVariableValue(i, n2);
      }
    }

    return offspring;
  }
1146350
def option2tuple(opt):
    """"""

    if isinstance(opt[0], int):
        tup = opt[1], opt[2:]
    else:
        tup = opt[0], opt[1:]

    return tup
1343768
private static int chooseWithProbability(double[] distances,
                                             double sum,
                                             double probability) {
        for (int j = 0; j < distances.length; ++j) {
            double probOfDistance = Math.pow(distances[j], 2) / sum;
            probability -= probOfDistance;
            if (probability <= EPSILON) {
                return j;
            }
        }
        return distances.length-1;
    }
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
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;
	}