Calculates Standard Deviation for Xbar for finite population size

@param std
@param sampleN
@param populationN
@return
969540
public static double xbarStd(double std, int sampleN, int populationN) {
        return Math.sqrt(xbarVariance(std*std, sampleN, populationN));
    }
390811
def sample_double_norm(mean, std_upper, std_lower, size):
    """"""
    from scipy.special import erfinv

    # There's probably a better way to do this. We first draw percentiles
    # uniformly between 0 and 1. We want the peak of the distribution to occur
    # at `mean`. However, if we assign 50% of the samples to the lower half
    # and 50% to the upper half, the side with the smaller variance will be
    # overrepresented because of the 1/sigma normalization of the Gaussian
    # PDF. Therefore we need to divide points between the two halves with a
    # fraction `cutoff` (defined below) going to the lower half. Having
    # partitioned them this way, we can then use the standard Gaussian
    # quantile function to go from percentiles to sample values -- except that
    # we must remap from [0, cutoff] to [0, 0.5] and from [cutoff, 1] to [0.5,
    # 1].

    samples = np.empty(size)
    percentiles = np.random.uniform(0., 1., size)
    cutoff = std_lower / (std_lower + std_upper)

    w = (percentiles < cutoff)
    percentiles[w] *= 0.5 / cutoff
    samples[w] = mean + np.sqrt(2) * std_lower * erfinv(2 * percentiles[w] - 1)

    w = ~w
    percentiles[w] = 1 - (1 - percentiles[w]) * 0.5 / (1 - cutoff)
    samples[w] = mean + np.sqrt(2) * std_upper * erfinv(2 * percentiles[w] - 1)

    return samples
980300
def _sample_variant_file_in_population(x):
    """
    '"""
    if "population" in x:
        a = _get_project_vcf(x)
        b = _get_variant_file(x, ("vrn_file",))
        decomposed = tz.get_in(("population", "decomposed"), x)
        if (a and b and not decomposed and len(a) > 0 and len(b) > 0 and
              vcfutils.get_samples(a[0]["path"]) == vcfutils.get_samples(b[0]["path"])):
            return True
    return False
926167
public double getPopulationVariance() {
      if (getCount() <= 0) {
         return Double.NaN;
      } else if (getCount() == 1) {
         return 0d;
      }
      return Math.abs(getSumOfSquares() - getAverage() * getSum()) / getCount();
   }
1004393
def stochastic_selection(population, fitnesses):
    """"""
    pop_size = len(population)
    probabilities = _fitnesses_to_probabilities(fitnesses)

    # Create selection list (for stochastic universal sampling)
    selection_list = []
    selection_spacing = 1.0 / pop_size
    selection_start = random.uniform(0.0, selection_spacing)
    for i in range(pop_size):
        selection_list.append(selection_start + selection_spacing * i)

    # Select intermediate population according to selection list
    intermediate_population = []
    for selection in selection_list:
        for (i, probability) in enumerate(probabilities):
            if probability >= selection:
                intermediate_population.append(population[i])
                break
    random.shuffle(intermediate_population)

    return intermediate_population
332510
private DoubleMinMax sampleMinMax(Relation<O> relation, DistanceQuery<O> distFunc) {
    int size = relation.size();
    Random rnd = new Random();
    // estimate minimum and maximum.
    int k = (int) Math.max(25, FastMath.pow(relation.size(), 0.2));
    TreeSet<DoubleDBIDPair> minhotset = new TreeSet<>();
    TreeSet<DoubleDBIDPair> maxhotset = new TreeSet<>(Collections.reverseOrder());

    int randomsize = (int) Math.max(25, FastMath.pow(relation.size(), 0.2));
    double rprob = ((double) randomsize) / size;
    ArrayModifiableDBIDs randomset = DBIDUtil.newArray(randomsize);

    DBIDIter iter = relation.iterDBIDs();
    if(!iter.valid()) {
      throw new EmptyDataException();
    }
    DBID firstid = DBIDUtil.deref(iter);
    iter.advance();
    minhotset.add(DBIDUtil.newPair(Double.MAX_VALUE, firstid));
    maxhotset.add(DBIDUtil.newPair(Double.MIN_VALUE, firstid));
    for(; iter.valid(); iter.advance()) {
      // generate candidates for min distance.
      ArrayList<DoubleDBIDPair> np = new ArrayList<>(k * 2 + randomsize * 2);
      for(DoubleDBIDPair pair : minhotset) {
        // skip the object itself
        if(DBIDUtil.equal(iter, pair)) {
          continue;
        }
        double d = distFunc.distance(iter, pair);
        np.add(DBIDUtil.newPair(d, iter));
        np.add(DBIDUtil.newPair(d, pair));
      }
      for(DBIDIter iter2 = randomset.iter(); iter2.valid(); iter2.advance()) {
        double d = distFunc.distance(iter, iter2);
        np.add(DBIDUtil.newPair(d, iter));
        np.add(DBIDUtil.newPair(d, iter2));
      }
      minhotset.addAll(np);
      shrinkHeap(minhotset, k);

      // generate candidates for max distance.
      ArrayList<DoubleDBIDPair> np2 = new ArrayList<>(k * 2 + randomsize * 2);
      for(DoubleDBIDPair pair : minhotset) {
        // skip the object itself
        if(DBIDUtil.equal(iter, pair)) {
          continue;
        }
        double d = distFunc.distance(iter, pair);
        np2.add(DBIDUtil.newPair(d, iter));
        np2.add(DBIDUtil.newPair(d, pair));
      }
      for(DBIDIter iter2 = randomset.iter(); iter2.valid(); iter2.advance()) {
        double d = distFunc.distance(iter, iter2);
        np.add(DBIDUtil.newPair(d, iter));
        np.add(DBIDUtil.newPair(d, iter2));
      }
      maxhotset.addAll(np2);
      shrinkHeap(maxhotset, k);

      // update random set
      if(randomset.size() < randomsize) {
        randomset.add(iter);
      }
      else if(rnd.nextDouble() < rprob) {
        randomset.set((int) Math.floor(rnd.nextDouble() * randomsize), iter);
      }
    }
    return new DoubleMinMax(minhotset.first().doubleValue(), maxhotset.first().doubleValue());
  }
684011
private function calculateStatistics(string $label, array $samples): void
    {
        $this->std[$label] = array_fill(0, $this->featureCount, 0);
        $this->mean[$label] = array_fill(0, $this->featureCount, 0);
        $this->dataType[$label] = array_fill(0, $this->featureCount, self::CONTINUOS);
        $this->discreteProb[$label] = array_fill(0, $this->featureCount, self::CONTINUOS);
        for ($i = 0; $i < $this->featureCount; ++$i) {
            // Get the values of nth column in the samples array
            // Mean::arithmetic is called twice, can be optimized
            $values = array_column($samples, $i);
            $numValues = count($values);
            // if the values contain non-numeric data,
            // then it should be treated as nominal/categorical/discrete column
            if ($values !== array_filter($values, 'is_numeric')) {
                $this->dataType[$label][$i] = self::NOMINAL;
                $this->discreteProb[$label][$i] = array_count_values($values);
                $db = &$this->discreteProb[$label][$i];
                $db = array_map(function ($el) use ($numValues) {
                    return $el / $numValues;
                }, $db);
            } else {
                $this->mean[$label][$i] = Mean::arithmetic($values);
                // Add epsilon in order to avoid zero stdev
                $this->std[$label][$i] = 1e-10 + StandardDeviation::population($values, false);
            }
        }
    }
775121
@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()];

		final double b = (_c - 1.0)/(pow(_c, N) - 1.0);
		for (int i = 0; i < probabilities.length; ++i) {
			probabilities[i] = pow(_c, i)*b;
		}

		return probabilities;
	}
1102643
public double[][] sample(int n) {
        double[][] samples = new double[2 * n][];

        MultivariateGaussianDistribution[] gauss = new MultivariateGaussianDistribution[k];
        for (int i = 0; i < k; i++) {
            gauss[i] = new MultivariateGaussianDistribution(m[i], v);
        }

        for (int i = 0; i < n; i++) {
            samples[i] = gauss[Math.random(prob)].rand();
        }

        for (int i = 0; i < k; i++) {
            gauss[i] = new MultivariateGaussianDistribution(m[k + i], v);
        }

        for (int i = 0; i < n; i++) {
            samples[n + i] = gauss[Math.random(prob)].rand();
        }

        return samples;
    }
597687
@Override
	public ISeq<Phenotype<G, N>> select(
		final Seq<Phenotype<G, N>> population,
		final int count,
		final Optimize opt
	) {
		requireNonNull(population, "Population");
		if (count < 0) {
			throw new IllegalArgumentException(
				"Selection count must be greater or equal then zero, but was " +
				count
			);
		}

		if (count == 0 || population.isEmpty()) {
			return ISeq.empty();
		}

		final MSeq<Phenotype<G, N>> selection = MSeq.ofLength(count);

		final Seq<Phenotype<G, N>> pop = _sorted
			? population.asISeq().copy().sort(POPULATION_COMPARATOR)
			: population;

		final double[] probabilities = probabilities(pop, count, opt);
		assert  pop.size() == probabilities.length;

		//Calculating the equally spaces random points.
		final double delta = 1.0/count;
		final double[] points = new double[count];
		points[0] = RandomRegistry.getRandom().nextDouble()*delta;
		for (int i = 1; i < count; ++i) {
			points[i] = delta*i;
		}

		int j = 0;
		double prop = 0;
		for (int i = 0; i < count; ++i) {
			while (points[i] > prop) {
				prop += probabilities[j];
				++j;
			}

			selection.set(i, pop.get(j%pop.size()));
		}

		return selection.toISeq();
	}
995027
private int computePixelSize(final SampleModel sampleModel) {
        int size = 0;

        for (int i = 0; i < sampleModel.getNumBands(); i++) {
            size += sampleModel.getSampleSize(i);
        }

        return size;
    }
264230
public static float[] stddev (int[] values, int start, int length)
    {
        // first we need the mean
        float mean = 0f;
        for (int ii = start, end = start + length; ii < end; ii++) {
            mean += values[ii];
        }
        mean /= length;

        // next we compute the variance
        float variance = 0f;
        for (int ii = start, end = start + length; ii < end; ii++) {
            float value = values[ii] - mean;
            variance += value * value;
        }
        variance /= (length - 1);

        // the standard deviation is the square root of the variance
        return new float[] { mean, variance, (float)Math.sqrt(variance) };
    }
924021
function sampleSizeFraction(num, total, withReplacement) {
  const minSamplingRate = 1e-10;        // Limited by RNG's resolution
  const delta = 1e-4;                   // To have 0.9999 success rate
  const fraction = num / total;
  let upperBound;

  if (withReplacement) {
    // Poisson upper bound for Pr(num successful poisson trials) > (1-delta)
    let numStd = num < 6 ? 12 : num < 16 ? 9 : 6;
    upperBound = Math.max(num + numStd * Math.sqrt(num), minSamplingRate) / total;
  } else {
    // Binomial upper bound for Pr(num successful bernoulli trials) > (1-delta)
    let gamma = - Math.log(delta) / total;
    upperBound = Math.min(1, Math.max(minSamplingRate, fraction + gamma + Math.sqrt(gamma * gamma + 2 * gamma * fraction)));
  }
  return upperBound;
}
1163728
public static int sampleFromDistribution(double[] d, Random random) {
    // sample from the uniform [0,1]
    double r = random.nextDouble();
    // now compare its value to cumulative values to find what interval it falls in
    double total = 0;
    for (int i = 0; i < d.length - 1; i++) {
      if (Double.isNaN(d[i])) {
        throw new RuntimeException("Can't sample from NaN");
      }
      total += d[i];
      if (r < total) {
        return i;
      }
    }
    return d.length - 1; // in case the "double-math" didn't total to exactly 1.0
  }
76478
public final double sampleSigma(int n)
  {
    synchronized (_lock) {
      long count = _count.get();
      long lastCount = _lastStdCount;
      _lastStdCount = count;

      double sum = _sum.get();
      double lastSum = _lastStdSum;
      _lastStdSum = sum;

      double sumSquare = _sumSquare;
      _sumSquare = 0;

      if (count == lastCount)
        return 0;

      double avg = (sum - lastSum) / (count - lastCount);
      double part = (count - lastCount) * sumSquare - sum * sum;

      if (part < 0)
        part = 0;

      double std = Math.sqrt(part) / (count - lastCount);

      return _scale * (avg + n * std);
    }
  }
345451
function(n, loc, scale) {
                    n = this._v(n, "n");
                    loc = this._v(loc, "r", 0);
                    scale = this._v(scale, "nn", 1);

                    var toReturn = [];

                    for(var i=0; i<n; i++) {
                        var core = this.sample([-1,1])[0] * ln(this.prng());

                        var x = loc - scale * core;

                        toReturn[i] = x;
                    }

                    return toReturn
                }
780138
def _scalar_type_std_res(self, counts, total, colsum, rowsum):
        
        expected_counts = expected_freq(counts)
        residuals = counts - expected_counts
        variance = (
            np.outer(rowsum, colsum)
            * np.outer(total - rowsum, total - colsum)
            / total ** 3
        )
        return residuals / np.sqrt(variance)