Calculates Standard Deviation for Pbar for finite population size

@param pbar
@param sampleN
@param populationN
@return
423224
public static double pbarStd(double pbar, int sampleN, int populationN) {
        return Math.sqrt(pbarVariance(pbar, sampleN, populationN));
    }
903680
private int sampleLine(ResultPoint p1, ResultPoint p2, int size) {
    int result = 0;

    float d = distance(p1, p2);
    float moduleSize = d / size;
    float px = p1.getX();
    float py = p1.getY();
    float dx = moduleSize * (p2.getX() - p1.getX()) / d;
    float dy = moduleSize * (p2.getY() - p1.getY()) / d;
    for (int i = 0; i < size; i++) {
      if (image.get(MathUtils.round(px + i * dx), MathUtils.round(py + i * dy))) {
        result |= 1 << (size - i - 1);
      }
    }
    return result;
  }
926167
public double getPopulationVariance() {
      if (getCount() <= 0) {
         return Double.NaN;
      } else if (getCount() == 1) {
         return 0d;
      }
      return Math.abs(getSumOfSquares() - getAverage() * getSum()) / getCount();
   }
1118266
public UpdatableSketchBuilder<U, S> setSamplingProbability(final float samplingProbability) {
    if ((samplingProbability < 0) || (samplingProbability > 1f)) {
      throw new SketchesArgumentException("sampling probability must be between 0 and 1");
    }
    samplingProbability_ = samplingProbability;
    return this;
  }
1176215
@Override
	public double getInclusionProbability(Instance instance) {
		Iterator<Map.Entry<DensityGrid, Boolean>> gridIter = grids.entrySet().iterator();
		
		while(gridIter.hasNext())
		{
			Map.Entry<DensityGrid, Boolean> grid = gridIter.next();
			DensityGrid dg = grid.getKey();
			if(dg.getInclusionProbability(instance) == 1.0)
				return 1.0;
		}
		
		return 0.0;
	}
10997
def experimentVaryingSynapseSampling(expParams,
                                     sampleSizeDistalList,
                                     sampleSizeProximalList):
  
  numRpts = 20
  df = None
  args = []
  for sampleSizeProximal in sampleSizeProximalList:
    for sampleSizeDistal in sampleSizeDistalList:

      for rpt in range(numRpts):
        l4Params = getL4Params()
        l2Params = getL2Params()
        l2Params["sampleSizeProximal"] = sampleSizeProximal
        l2Params["minThresholdProximal"] = sampleSizeProximal
        l2Params["sampleSizeDistal"] = sampleSizeDistal
        l2Params["activationThresholdDistal"] = sampleSizeDistal

        args.append(
          {
            "numObjects": expParams['numObjects'],
            "numLocations": expParams['numLocations'],
            "numFeatures": expParams['numFeatures'],
            "numColumns": expParams['numColumns'],
            "trialNum": rpt,
            "l4Params": l4Params,
            "l2Params": l2Params,
            "profile": True,
            "objectSeed": rpt,
          }
        )

  pool = Pool(processes=expParams['numWorkers'])
  result = pool.map(runExperiment, args)

  #
  #       if df is None:
  #         df = pd.DataFrame.from_dict(result, orient='index')
  #       else:
  #         df = pd.concat([df, pd.DataFrame.from_dict(result, orient='index')], axis=1)
  #
  # df = df.transpose()
  return result
386364
def calculate_sample_mean(self, Data_sample_or_site):
        '''
        
        '''

        pars = {}
        tmp_B = []
        for spec in list(Data_sample_or_site.keys()):
            if 'B' in list(Data_sample_or_site[spec].keys()):
                tmp_B.append(Data_sample_or_site[spec]['B'])
        if len(tmp_B) < 1:
            pars['N'] = 0
            pars['pass_or_fail'] = 'fail'
            return pars

        tmp_B = np.array(tmp_B)
        pars['pass_or_fail'] = 'pass'
        pars['N'] = len(tmp_B)
        pars['B_uT'] = np.mean(tmp_B)
        if len(tmp_B) > 1:
            pars['B_std_uT'] = np.std(tmp_B, ddof=1)
            pars['B_std_perc'] = 100 * (pars['B_std_uT'] / pars['B_uT'])
        else:
            pars['B_std_uT'] = 0
            pars['B_std_perc'] = 0
        pars['sample_int_interval_uT'] = (max(tmp_B) - min(tmp_B))
        pars['sample_int_interval_perc'] = 100 * \
            (pars['sample_int_interval_uT'] / pars['B_uT'])
        pars['fail_list'] = []
        # check if pass criteria
        #----------
        # int_n
        if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
            average_by_sample_or_site = 'sample'
        else:
            average_by_sample_or_site = 'site'

        if average_by_sample_or_site == 'sample':
            cutoff_value = self.acceptance_criteria['sample_int_n']['value']
        else:
            cutoff_value = self.acceptance_criteria['site_int_n']['value']
        if cutoff_value != -999:
            if pars['N'] < cutoff_value:
                pars['pass_or_fail'] = 'fail'
                pars['fail_list'].append("int_n")
        #----------
        # int_sigma ; int_sigma_perc
        pass_sigma, pass_sigma_perc = False, False
        if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
            sigma_cutoff_value = self.acceptance_criteria['sample_int_sigma']['value']
        else:
            sigma_cutoff_value = self.acceptance_criteria['site_int_sigma']['value']

        if sigma_cutoff_value != -999:
            if pars['B_std_uT'] * 1e-6 <= sigma_cutoff_value:
                pass_sigma = True

        if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
            sigma_perc_cutoff_value = self.acceptance_criteria['sample_int_sigma_perc']['value']
        else:
            sigma_perc_cutoff_value = self.acceptance_criteria['site_int_sigma_perc']['value']
        if sigma_perc_cutoff_value != -999:
            if pars['B_std_perc'] <= sigma_perc_cutoff_value:
                pass_sigma_perc = True

        if not (sigma_cutoff_value == -999 and sigma_perc_cutoff_value == -999):
            if not (pass_sigma or pass_sigma_perc):
                pars['pass_or_fail'] = 'fail'
                pars['fail_list'].append("int_sigma")

        pass_int_interval, pass_int_interval_perc = False, False
        if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
            cutoff_value = self.acceptance_criteria['sample_int_interval_uT']['value']
            if cutoff_value != -999:
                if pars['sample_int_interval_uT'] <= cutoff_value:
                    pass_int_interval = True

            cutoff_value_perc = self.acceptance_criteria['sample_int_interval_perc']['value']
            if cutoff_value_perc != -999:
                if pars['sample_int_interval_perc'] <= cutoff_value_perc:
                    pass_int_interval_perc = True

            if not (cutoff_value == -999 and cutoff_value_perc == -999):
                if not (pass_int_interval or pass_int_interval_perc):
                    pars['pass_or_fail'] = 'fail'
                    pars['fail_list'].append("int_interval")

            # if cutoff_value != -999 or cutoff_value_perc != -999:
            #    if not (pass_int_interval or pass_int_interval_perc):
            #        pars['pass_or_fail']='fail'
            #        pars['fail_list'].append("int_interval")

            #
            #
            #
            #
            # if (acceptance_criteria['sample_int_sigma_uT']==0 and acceptance_criteria['sample_int_sigma_perc']==0) or\
            #    (pars['B_uT'] <= acceptance_criteria['sample_int_sigma_uT'] or pars['B_std_perc'] <= acceptance_criteria['sample_int_sigma_perc']):
            #        if ( pars['sample_int_interval_uT'] <= acceptance_criteria['sample_int_interval_uT'] or pars['sample_int_interval_perc'] <= acceptance_criteria['sample_int_interval_perc']):
            #            pars['pass_or_fail']='pass'
        return(pars)
867771
def sample(self, size=None):
        
        self._recompute()
        if size is None:
            n = np.random.randn(len(self._t))
        else:
            n = np.random.randn(len(self._t), size)
        n = self.solver.dot_L(n)
        if size is None:
            return self.mean.get_value(self._t) + n[:, 0]
        return self.mean.get_value(self._t)[None, :] + n.T
910013
def sample(self, n=100, seed=None):
        
        if n < 1:
            raise ValueError("Number of samples must be larger than 0, got '%g'" % n)

        if seed is None:
            seed = random.randint(0, 2 ** 32)

        if self.mode == 'spark':
            result = asarray(self.values.tordd().values().takeSample(False, n, seed))

        else:
            basedims = [self.shape[d] for d in self.baseaxes]
            inds = [unravel_index(int(k), basedims) for k in random.rand(n) * prod(basedims)]
            result = asarray([self.values[tupleize(i) + (slice(None, None),)] for i in inds])

        return self._constructor(result, index=self.index)
140497
private static double calculate_MDEF_norm(Node sn, Node cg) {
    // get the square sum of the counting neighborhoods box counts
    long sq = sn.getSquareSum(cg.getLevel() - sn.getLevel());
    /*
     * if the square sum is equal to box count of the sampling Neighborhood then
     * n_hat is equal one, and as cg needs to have at least one Element mdef
     * would get zero or lower than zero. This is the case when all of the
     * counting Neighborhoods contain one or zero Objects. Additionally, the
     * cubic sum, square sum and sampling Neighborhood box count are all equal,
     * which leads to sig_n_hat being zero and thus mdef_norm is either negative
     * infinite or undefined. As the distribution of the Objects seem quite
     * uniform, a mdef_norm value of zero ( = no outlier) is appropriate and
     * circumvents the problem of undefined values.
     */
    if(sq == sn.getCount()) {
      return 0.0;
    }
    // calculation of mdef according to the paper and standardization as done in
    // LOCI
    long cb = sn.getCubicSum(cg.getLevel() - sn.getLevel());
    double n_hat = (double) sq / sn.getCount();
    double sig_n_hat = FastMath.sqrt(cb * sn.getCount() - (sq * sq)) / sn.getCount();
    // Avoid NaN - correct result 0.0?
    if(sig_n_hat < Double.MIN_NORMAL) {
      return 0.0;
    }
    double mdef = n_hat - cg.getCount();
    return mdef / sig_n_hat;
  }
1226916
def Sample(self, n):
        
        size = n,
        return numpy.random.beta(self.alpha, self.beta, size)
795689
public List<T> generateInitialPopulation(int populationSize,
                                             Collection<T> seedCandidates,
                                             Random rng)
    {
        if (seedCandidates.size() > populationSize)
        {
            throw new IllegalArgumentException("Too many seed candidates for specified population size.");
        }
        List<T> population = new ArrayList<T>(populationSize);
        population.addAll(seedCandidates);
        for (int i = seedCandidates.size(); i < populationSize; i++)
        {
            population.add(generateRandomCandidate(rng));
        }
        return Collections.unmodifiableList(population);
    }
1326955
public static Gaussian fromBinomial(final double probability,
    final long totalPopulation) {
    if (0. >= totalPopulation) {
      throw new IllegalArgumentException();
    }
    if (0. >= probability) {
      throw new IllegalArgumentException();
    }
    if (1. <= probability) {
      throw new IllegalArgumentException();
    }
    if (Double.isNaN(probability)) {
      throw new IllegalArgumentException();
    }
    if (Double.isInfinite(probability)) {
      throw new IllegalArgumentException();
    }
    return new Gaussian(
      probability * totalPopulation,
      Math.sqrt(totalPopulation * probability * (1 - probability)));
  }
379164
public double randNormal(double mean, double standardDeviation) {
    double x1, x2, w, y1;

    do {
      x1 = 2.0 * randomGenerator.nextDouble() - 1.0;
      x2 = 2.0 * randomGenerator.nextDouble() - 1.0;
      w = x1 * x1 + x2 * x2;
    } while (w >= 1.0);

    w = Math.sqrt((-2.0 * Math.log(w)) / w);
    y1 = x1 * w;
    y1 = y1 * standardDeviation + mean;
    return y1;
  }
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();
	}
1362961
def sample(self, n):
        
        rg = self._ctx._jvm.org.apache.commons.math3.random.JDKRandomGenerator()
        return _java2py(self._ctx, self._jmodel.sample(n, rg))
1034875
@Override
    public double inverseCumulativeProbability(final double p) throws OutOfRangeException {
        if (p < 0.0 || p > 1.0) {
            throw new OutOfRangeException(p, 0, 1);
        }
        if (means != null)
            throw new IllegalStateException("Unable to sample from more than one mean");

        return mean + standardDeviation * SQRT2 * Erf.erfInv(2 * p - 1);
    }