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.
553695
def weighted_choice(self, probabilities, key):
        """"""

        try:
            choice = self.values[key].lower()
        except KeyError:
            # override not set.
            return super(RecordingParameters, self)\
                .weighted_choice(probabilities, key)

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

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

        assert False, "Invalid value provided"
443940
private String getName(List<? extends Name> list, double probability) {
        Name name = getNameObject(list, probability * getMax(list));
        return name.getValue();
    }
358138
def choices(self, choices):
        

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

        self._choices = choices
600355
public double getProbability() {
    if (WordForm_Type.featOkTst && ((WordForm_Type)jcasType).casFeat_probability == null)
      jcasType.jcas.throwFeatMissing("probability", "com.digitalpebble.rasp.WordForm");
    return jcasType.ll_cas.ll_getDoubleValue(addr, ((WordForm_Type)jcasType).casFeatCode_probability);}
580210
def weighted_choice(self, board: Union[chess.Board, int], *, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
        
        total_weights = sum(entry.weight for entry in self.find_all(board, exclude_moves=exclude_moves))
        if not total_weights:
            raise IndexError()

        choice = random.randint(0, total_weights - 1)

        current_sum = 0
        for entry in self.find_all(board, exclude_moves=exclude_moves):
            current_sum += entry.weight
            if current_sum > choice:
                return entry

        assert False
152848
def weighted(weights, sample_size, with_replacement=False):
        
        assert sample_size <= len(weights), "The sample size must be smaller \
than or equal to the number of weights it's taken from."

        # Convert weights to floats
        weights = [float(w) for w in weights]
        weight_indexes = list(range(0, len(weights)))

        samples = []
        while len(samples) < sample_size:
            # Choice a weight
            sample = OneOf.weighted(weights)

            # Add the choosen weight to our samples
            samples.append(weight_indexes[sample])

            if not with_replacement:
                # Remove the weight from the list of weights we can select from
                del weights[sample]
                del weight_indexes[sample]

        return samples
354223
def choice(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
        
        chosen_entry = None

        for i, entry in enumerate(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves)):
            if chosen_entry is None or random.randint(0, i) == i:
                chosen_entry = entry

        if chosen_entry is None:
            raise IndexError()

        return chosen_entry
422034
def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100):
    '''
    
    '''
    outputs = None

    if check_feasibility(x_bounds, lowerbound, upperbound) is True:
        # Order parameters by their range size. We want the smallest range first,
        # because the corresponding parameter has less numbers to choose from
        x_idx_sorted = []
        for i, _ in enumerate(x_bounds):
            if x_types[i] == "discrete_int":
                x_idx_sorted.append([i, len(x_bounds[i])])
            elif (x_types[i] == "range_int") or (x_types[i] == "range_continuous"):
                x_idx_sorted.append([i, math.floor(x_bounds[i][1] - x_bounds[i][0])])
        x_idx_sorted = sorted(x_idx_sorted, key=itemgetter(1))

        for _ in range(max_retries):
            budget_allocated = 0
            outputs = [None] * len(x_bounds)

            for i, _ in enumerate(x_idx_sorted):
                x_idx = x_idx_sorted[i][0]
                # The amount of unallocated space that we have
                budget_max = upperbound - budget_allocated
                # NOT the Last x that we need to assign a random number
                if i < (len(x_idx_sorted) - 1):
                    if x_bounds[x_idx][0] <= budget_max:
                        if x_types[x_idx] == "discrete_int":
                            # Note the valid integer
                            temp = []
                            for j in x_bounds[x_idx]:
                                if j <= budget_max:
                                    temp.append(j)
                            # Randomly pick a number from the integer array
                            if temp:
                                outputs[x_idx] = temp[random.randint(0, len(temp) - 1)]

                        elif (x_types[x_idx] == "range_int") or \
                                    (x_types[x_idx] == "range_continuous"):
                            outputs[x_idx] = random.randint(x_bounds[x_idx][0],
                                                            min(x_bounds[x_idx][-1], budget_max))

                else:
                    # The last x that we need to assign a random number
                    randint_lowerbound = lowerbound - budget_allocated
                    randint_lowerbound = 0 if randint_lowerbound < 0 else randint_lowerbound

                    # This check:
                    # is our smallest possible value going to overflow the available budget space,
                    # and is our largest possible value going to underflow the lower bound
                    if (x_bounds[x_idx][0] <= budget_max) and \
                            (x_bounds[x_idx][-1] >= randint_lowerbound):
                        if x_types[x_idx] == "discrete_int":
                            temp = []
                            for j in x_bounds[x_idx]:
                                # if (j <= budget_max) and (j >= randint_lowerbound):
                                if randint_lowerbound <= j <= budget_max:
                                    temp.append(j)
                            if temp:
                                outputs[x_idx] = temp[random.randint(0, len(temp) - 1)]
                        elif (x_types[x_idx] == "range_int") or \
                                (x_types[x_idx] == "range_continuous"):
                            outputs[x_idx] = random.randint(randint_lowerbound,
                                                            min(x_bounds[x_idx][1], budget_max))
                if outputs[x_idx] is None:
                    break
                else:
                    budget_allocated += outputs[x_idx]
            if None not in outputs:
                break
    return outputs
184276
def probabilities(self, angles: List[float]) -> np.ndarray:
        
        if isinstance(angles, list):
            angles = np.array(angles)

        assert angles.shape[0] == 2 * self.steps, "angles must be 2 * steps"

        param_prog = self.get_parameterized_program()
        prog = param_prog(angles)
        wf = WavefunctionSimulator().wavefunction(prog)
        wf = wf.amplitudes.reshape((-1, 1))
        probs = np.zeros_like(wf)
        for xx in range(2 ** len(self.qubits)):
            probs[xx] = np.conj(wf[xx]) * wf[xx]
        return probs
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)
1183039
def convenience_calc_probs(self, params):
        
        shapes, intercepts, betas = self.convenience_split_params(params)

        prob_args = (betas,
                     self.design_3d,
                     self.alt_id_vector,
                     self.rows_to_obs,
                     self.rows_to_alts,
                     self.utility_transform)
        prob_kwargs = {"chosen_row_to_obs": self.chosen_row_to_obs,
                       "return_long_probs": True}
        probability_results = general_calc_probabilities(*prob_args,
                                                         **prob_kwargs)

        return probability_results
210222
def computeScaledProbabilities(
        listOfScales=[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],
        listofkValues=[64, 128, 256],
        kw=32,
        n=1000,
        numWorkers=10,
        nTrials=1000,
  ):
  
  # Create arguments for the possibilities we want to test
  args = []
  theta, _ = getTheta(kw)
  for ki, k in enumerate(listofkValues):
    for si, s in enumerate(listOfScales):
      args.append({
          "k": k, "kw": kw, "n": n, "theta": theta,
          "nTrials": nTrials, "inputScaling": s,
          "errorIndex": [ki, si],
          })

  result = computeMatchProbabilityParallel(args, numWorkers)

  errors = np.zeros((len(listofkValues), len(listOfScales)))
  for r in result:
    errors[r["errorIndex"][0], r["errorIndex"][1]] = r["pctMatches"]

  print("Errors using scaled inputs, for kw=", kw)
  print(repr(errors))
  plotScaledMatches(listofkValues, listOfScales, errors,
              "images/scalar_effect_of_scale_kw" + str(kw) + ".pdf")
712432
public final boolean nextBoolean(final double probability)
        {
        int y;
        int z;

        if (probability < 0.0 || probability > 1.0)
            throw new IllegalArgumentException ("probability must be between 0.0 and 1.0 inclusive.");
        if (probability==0.0) return false;             // fix half-open issues
        else if (probability==1.0) return true; // fix half-open issues
        if (mti >= N)   // generate N words at one time
            {
            int kk;
            @SuppressWarnings("hiding")
			final int[] mt = this.mt; // locals are slightly faster 
            @SuppressWarnings("hiding")
			final int[] mag01 = this.mag01; // locals are slightly faster 
            
            for (kk = 0; kk < N - M; kk++)
                {
                y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
                mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1];
                }
            for (; kk < N-1; kk++)
                {
                y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
                mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1];
                }
            y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
            mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1];

            mti = 0;
            }
  
        y = mt[mti++];
        y ^= y >>> 11;                          // TEMPERING_SHIFT_U(y)
        y ^= (y << 7) & TEMPERING_MASK_B;       // TEMPERING_SHIFT_S(y)
        y ^= (y << 15) & TEMPERING_MASK_C;      // TEMPERING_SHIFT_T(y)
        y ^= (y >>> 18);                        // TEMPERING_SHIFT_L(y)

        if (mti >= N)   // generate N words at one time
            {
            int kk;
            @SuppressWarnings("hiding")
			final int[] mt = this.mt; // locals are slightly faster 
            @SuppressWarnings("hiding")
			final int[] mag01 = this.mag01; // locals are slightly faster 
            
            for (kk = 0; kk < N - M; kk++)
                {
                z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
                mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1];
                }
            for (; kk < N-1; kk++)
                {
                z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
                mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1];
                }
            z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
            mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1];
            
            mti = 0;
            }
        
        z = mt[mti++];
        z ^= z >>> 11;                          // TEMPERING_SHIFT_U(z)
        z ^= (z << 7) & TEMPERING_MASK_B;       // TEMPERING_SHIFT_S(z)
        z ^= (z << 15) & TEMPERING_MASK_C;      // TEMPERING_SHIFT_T(z)
        z ^= (z >>> 18);                        // TEMPERING_SHIFT_L(z)
        
        /* derived from nextDouble documentation in jdk 1.2 docs, see top */
        return ((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53) < probability;
        }
545349
def weighted_card_choice(source, weights: List[int], card_sets: List[str], count: int):
	

	chosen_cards = []

	# sum all the weights
	cum_weights = []
	totalweight = 0
	for i, w in enumerate(weights):
		totalweight += w * len(card_sets[i])
		cum_weights.append(totalweight)

	# for each card
	for i in range(count):
		# choose a set according to weighting
		chosen_set = bisect(cum_weights, random.random() * totalweight)

		# choose a random card from that set
		chosen_card_index = random.randint(0, len(card_sets[chosen_set]) - 1)

		chosen_cards.append(card_sets[chosen_set].pop(chosen_card_index))
		totalweight -= weights[chosen_set]
		cum_weights[chosen_set:] = [x - weights[chosen_set] for x in cum_weights[chosen_set:]]

	return [source.controller.card(card, source=source) for card in chosen_cards]
534978
def print_probabilities(state: State, ndigits: int = 4,
                        file: TextIO = None) -> None:
    
    prob = bk.evaluate(state.probabilities())
    for index, prob in np.ndenumerate(prob):
        prob = round(prob, ndigits)
        if prob == 0.0:
            continue
        ket = "".join([str(n) for n in index])
        print(ket, ":", prob, file=file)
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_
740739
def calculate_probabilities(tokens)
      # P(class|words) = P(w1,...,wn|class) * P(class) / P(w1,...,wn)
      #                = argmax P(w1,...,wn|class) * P(class)
      #
      # P(wi|class) = (count(wi, class) + k)/(count(w,class) + kV)
      prob_numerator = {}
      v_size = vocab.size

      cat_prob = Math.log(1 / data.categories.count.to_f)
      total_example_count = data.total_examples.to_f

      data.each do |category|
        unless assume_uniform
          cat_prob = Math.log(data.example_count(category) / total_example_count)
        end

        log_probs = 0
        denominator = (data.token_count(category) + @k * v_size).to_f
        tokens.each do |token|
          numerator = data.count_of_token_in_category(category, token) + @k
          log_probs += Math.log( numerator / denominator )
        end
        prob_numerator[category] = log_probs + cat_prob
      end
      normalize(prob_numerator)
    end