turns the results into a probability distribution.
771145
@Override protected double score1( Chunk chks[], double weight, double offset, double fs[/*nclass*/], int row ) {
    double sum = 0;
    if (_nclass > 2 || (_nclass == 2 && !_model.binomialOpt())) {
      for (int k = 0; k < _nclass; k++)
        sum += (fs[k+1] = weight * chk_tree(chks, k).atd(row) / chk_oobt(chks).atd(row));
    }
    else if (_nclass==2 && _model.binomialOpt()) {
      fs[1] = weight * chk_tree(chks, 0).atd(row) / chk_oobt(chks).atd(row);
      if (fs[1]>1 && fs[1]<=ONEBOUND)
        fs[1] = 1.0;
      else if (fs[1]<0 && fs[1]>=ZEROBOUND)
        fs[1] = 0.0;
      assert(fs[1] >= 0 && fs[1] <= 1);
      fs[2] = 1. - fs[1];
    }
    else { //regression
      // average per trees voted for this row (only trees which have row in "out-of-bag"
      sum += (fs[0] = weight * chk_tree(chks, 0).atd(row) / chk_oobt(chks).atd(row) );
      fs[1] = 0;
    }
    return sum;
  }


}
352798
def make_data(n,m):
    """"""
    p = {}
    for i in range(1,m+1):
        for j in range(1,n+1):
            p[i,j] = random.randint(1,10)
    return p
43558
def _pdf(self, x, dist, cache):
        """"""
        output = evaluation.evaluate_density(dist, numpy.arccosh(x), cache=cache)
        output /= numpy.where(x != 1, numpy.sqrt(x*x-1), numpy.inf)
        return output
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
1196006
def downsample(data, percent):
    
    n_genes = data.shape[0]
    n_cells = data.shape[1]
    new_data = data.copy()
    total_count = float(data.sum())
    to_remove = total_count*percent
    # sum of read counts per cell
    cell_sums = data.sum(0).astype(float)
    # probability of selecting genes per cell
    cell_gene_probs = data/cell_sums
    # probability of selecting cells
    cell_probs = np.array(cell_sums/total_count).flatten()
    cells_selected = np.random.multinomial(to_remove, pvals=cell_probs)
    for i, num_selected in enumerate(cells_selected):
        cell_gene = np.array(cell_gene_probs[:,i]).flatten()
        genes_selected = np.random.multinomial(num_selected, pvals=cell_gene)
        if sparse.issparse(data):
            genes_selected = sparse.csc_matrix(genes_selected).T
        new_data[:,i] -= genes_selected
    new_data[new_data < 0] = 0
    return new_data
956899
function(distribution, coverageAlpha) {
        if (distribution.numTrials < 1000) {
            // don't even bother trying to optimize for small-ish sample sizes
            return [0, distribution.numTrials];
        } else {
            return [
                Math.floor(distribution.inverseCdf(coverageAlpha / 2)),
                Math.ceil(distribution.inverseSurvival(coverageAlpha / 2))
            ];
        }
    }
1013061
def results_to_table(self):
        """"""
        # Get Labels
        baseline_labels = self.nearest_targets['origin_id'].values
        mcf_labels = self.results['model_labels']['labels'].values

        # Create the outcomes
        outcome = pd.DataFrame({
                'the_geom': [
                    'SRID=4326;Point({lng} {lat})'.format(lng=v[0], lat=v[1])
                    for v in zip(self.results['model_labels']['lng'].values, self.results['model_labels']['lat'].values)],
                'target_lng': self.results['model_labels']['lng'].values,
                'target_lng': self.results['model_labels']['lat'].values,
                'origin_lng': self.origins.reindex(baseline_labels)['lng'].values,
                'origin_lat': self.origins.reindex(baseline_labels)['lat'].values,
                'target_id': self.results['model_labels'].target_id,
                'sales': self.results['model_labels'][self.demand_col].values,
                'labels': baseline_labels
            }
        )

        outcomes2 = pd.DataFrame({
                'the_geom': [
                    'SRID=4326;Point({lng} {lat})'.format(lng=v[0], lat=v[1])
                    for v in zip(
                        self.results['model_labels']['lng'].values,
                        self.results['model_labels']['lat'].values
                    )
                ],
                'target_lng': self.results['model_labels']['lng'].values,
                'target_lat': self.results['model_labels']['lat'].values,
                'origin_lng': self.origins.reindex(mcf_labels)['lng'].values,
                'origin_lat': self.origins.reindex(mcf_labels)['lat'].values,
                'target_id': self.results['model_labels'].target_id,
                'sales': self.results['model_labels'][self.demand_col].values,
                'labels': mcf_labels
            },
            index=self.results['model_labels'].target_id
        )
        now = datetime.datetime.now()
        out_table = 'mincostflow_{}'.format(now.strftime("%Y_%m_%d_%H_%M_%S"))
        logging.info('Writing output to {}'.format(out_table))
        self.context.write(outcomes2.reset_index(drop=True), out_table)
        logging.info('Table {} written to CARTO'.format(out_table))
        return out_table
128016
def generateAmplitudes(k):
    """"""
    res = np.array([np.random.random() for i in range(k)])
    return res/res.sum()
284195
def MakeProbs(self):
        """"""
        for hypo, odds in self.Items():
            self.Set(hypo, Probability(odds))
903721
def run_all(logdir, verbose=False, num_summaries=400):
  """"""
  del verbose

  tf.compat.v1.set_random_seed(0)

  k = tf.compat.v1.placeholder(tf.float32)

  # Make a normal distribution, with a shifting mean
  mean_moving_normal = tf.random.normal(shape=[1000], mean=(5*k), stddev=1)
  # Record that distribution into a histogram summary
  histogram_summary.op("normal/moving_mean",
                       mean_moving_normal,
                       description="A normal distribution whose mean changes "
                                   "over time.")

  # Make a normal distribution with shrinking variance
  shrinking_normal = tf.random.normal(shape=[1000], mean=0, stddev=1-(k))
  # Record that distribution too
  histogram_summary.op("normal/shrinking_variance", shrinking_normal,
                       description="A normal distribution whose variance "
                                   "shrinks over time.")

  # Let's combine both of those distributions into one dataset
  normal_combined = tf.concat([mean_moving_normal, shrinking_normal], 0)
  # We add another histogram summary to record the combined distribution
  histogram_summary.op("normal/bimodal", normal_combined,
                       description="A combination of two normal distributions, "
                                   "one with a moving mean and one with  "
                                   "shrinking variance. The result is a "
                                   "distribution that starts as unimodal and "
                                   "becomes more and more bimodal over time.")

  # Add a gamma distribution
  gamma = tf.random.gamma(shape=[1000], alpha=k)
  histogram_summary.op("gamma", gamma,
                       description="A gamma distribution whose shape "
                                   "parameter, α, changes over time.")

  # And a poisson distribution
  poisson = tf.compat.v1.random_poisson(shape=[1000], lam=k)
  histogram_summary.op("poisson", poisson,
                       description="A Poisson distribution, which only "
                                   "takes on integer values.")

  # And a uniform distribution
  uniform = tf.random.uniform(shape=[1000], maxval=k*10)
  histogram_summary.op("uniform", uniform,
                       description="A simple uniform distribution.")

  # Finally, combine everything together!
  all_distributions = [mean_moving_normal, shrinking_normal,
                       gamma, poisson, uniform]
  all_combined = tf.concat(all_distributions, 0)
  histogram_summary.op("all_combined", all_combined,
                       description="An amalgamation of five distributions: a "
                                   "uniform distribution, a gamma "
                                   "distribution, a Poisson distribution, and "
                                   "two normal distributions.")

  summaries = tf.compat.v1.summary.merge_all()

  # Setup a session and summary writer
  sess = tf.compat.v1.Session()
  writer = tf.summary.FileWriter(logdir)

  # Setup a loop and write the summaries to disk
  N = num_summaries
  for step in xrange(N):
    k_val = step/float(N)
    summ = sess.run(summaries, feed_dict={k: k_val})
    writer.add_summary(summ, global_step=step)
612107
def _prepare_results(self, results):
        
        # if we want a result sorted by a score, and if we have a full result
        # (no slice), we can do it know, by creating keys for each values with
        # the sorted set score, and sort on them
        if self._sort_by_sortedset_after and (len(results) > 1 or self._values):
            conn = self.cls.get_connection()

            sort_params = {}
            base_tmp_key, tmp_keys = self._prepare_sort_by_score(results, sort_params)

            # compose the set to sort
            final_set = '%s_final_set' % base_tmp_key
            conn.sadd(final_set, *results)

            # apply the sort
            results = conn.sort(final_set, **sort_params)

            # finally delete all temporary keys
            conn.delete(*(tmp_keys + [final_set, base_tmp_key]))

        if self._store:
            # if store, redis doesn't return result, so don't return anything here
            return

        if self._values and self._values['mode'] != 'flat':
            results = self._to_values(results)

        return super(ExtendedCollectionManager, self)._prepare_results(results)
127271
def split_by_proportions(total, proportions, mininum_values):
    """"""
    assert(len(proportions) == len(mininum_values))
    assert(total >= sum(mininum_values))
    assert(min(proportions) > 0)
    num = len(proportions)
    sumProportions = float(sum(proportions))
    fractions = [p / sumProportions for p in proportions]
    result = [max(m, int(round(total * f)))
              for f, m in zip(fractions, mininum_values)]
    delta = sum(result) - total
    correct = -1 if delta > 0 else 1
    i = 0
    while delta != 0:
        if result[i] + correct >= mininum_values[i]:
            result[i] += correct
            delta += correct
        i = (i + 1) % num

    assert(sum(result) == total)
    return result
164626
private Collection<LicenseHistogramDataPoint> createLicenseHistogram(BaseCheckPoliciesResult result) {
        Collection<LicenseHistogramDataPoint> dataPoints = new ArrayList<LicenseHistogramDataPoint>();

        // create distribution histogram
        Map<String, Integer> licenseHistogram = new HashMap<String, Integer>();
        for (Map.Entry<String, Collection<ResourceInfo>> entry : result.getProjectNewResources().entrySet()) {
            for (ResourceInfo resource : entry.getValue()) {
                for (String license : resource.getLicenses()) {
                    licenseHistogram.put(license, MapUtils.getInteger(licenseHistogram, license, 0) + 1);
                }
            }
        }

        // sort by count descending
        List<Map.Entry<String, Integer>> licenses = new ArrayList<Map.Entry<String, Integer>>(licenseHistogram.entrySet());
        Collections.sort(licenses, new ValueComparator());

        // create data points
        if (!licenses.isEmpty()) {
            // first licenses
            for (Map.Entry<String, Integer> entry : licenses.subList(0, Math.min(LICENSE_LIMIT, licenses.size()))) {
                dataPoints.add(new LicenseHistogramDataPoint(entry.getKey(), entry.getValue()));
            }

            // aggregation of histogram tail
            int tailSize = licenses.size() - LICENSE_LIMIT;
            int tailSum = 0;
            if (tailSize > 0) {
                for (Map.Entry<String, Integer> entry : licenses.subList(LICENSE_LIMIT, licenses.size())) {
                    tailSum += entry.getValue();
                }
                dataPoints.add(new LicenseHistogramDataPoint(OTHER_LICENSE + " (" + tailSize + ")", tailSum));
            }

            // normalize bar height
            float factor = MAX_BAR_HEIGHT / (float) Math.max(tailSum, licenses.get(0).getValue());
            for (LicenseHistogramDataPoint dataPoint : dataPoints) {
                dataPoint.setHeight((int) (factor * dataPoint.getOccurrences()));
            }
        }

        return dataPoints;
    }
664990
def rvs(self, size=1):
        

        # create output FieldArray
        out = record.FieldArray(size, dtype=[(arg, float)
                                    for arg in self.variable_args])

        # loop until enough samples accepted
        n = 0
        while n < size:

            # draw samples
            samples = {}
            for dist in self.distributions:
                draw = dist.rvs(1)
                for param in dist.params:
                    samples[param] = draw[param][0]
            vals = numpy.array([samples[arg] for arg in self.variable_args])

            # determine if all parameter values are in prior space
            # if they are then add to output
            if self(**dict(zip(self.variable_args, vals))) > -numpy.inf:
                out[n] = vals
                n += 1

        return out
1320133
def _sample(probabilities, population_size):
    """"""
    population = []
    for _ in range(population_size):
        solution = []
        for probability in probabilities:
            # probability of 1.0: always 1
            # probability of 0.0: always 0
            if random.uniform(0.0, 1.0) < probability:
                solution.append(1)
            else:
                solution.append(0)
        population.append(solution)
    return population
932198
private static int selectWithProb(double probs[]) {
	double cutoff = Math.random();
	double curProbSum = 0.0;

	for (int i = 0; i < probs.length; i++) {
            curProbSum += probs[i];
            // NOTE: the assert is slightly larger than 1 to allow for marginal
            // accumulation due to double round-off errors
            assert curProbSum <= 1.0001
                : "sum of probabilities > 1: " + curProbSum;
            if (curProbSum >= cutoff)
                return i;
        }
        throw new IllegalStateException("Probablilities do not sum to 1");
    }
268957
def combine(pmaps):
    
    shape = get_shape(pmaps)
    res = ProbabilityMap(shape[1], shape[2])
    for pmap in pmaps:
        res |= pmap
    return res