Example usage for org.apache.commons.math3.distribution NormalDistribution NormalDistribution

List of usage examples for org.apache.commons.math3.distribution NormalDistribution NormalDistribution

Introduction

In this page you can find the example usage for org.apache.commons.math3.distribution NormalDistribution NormalDistribution.

Prototype

public NormalDistribution(double mean, double sd) throws NotStrictlyPositiveException 

Source Link

Document

Create a normal distribution using the given mean and standard deviation.

Usage

From source file:gedi.util.math.stat.distributions.NormalMixtureDistribution.java

public static NormalMixtureDistribution init(final double[] data, final int numComponents)
        throws NotStrictlyPositiveException, DimensionMismatchException {

    if (numComponents == 1)
        return new NormalMixtureDistribution(new NormalDistribution[] {
                new NormalDistribution(new Mean().evaluate(data), new StandardDeviation().evaluate(data)) },
                new double[] { 1 });

    if (data.length < 2) {
        throw new NotStrictlyPositiveException(data.length);
    }/*from   w  ww.jav  a 2 s  . c  om*/
    if (numComponents < 1) {
        throw new NumberIsTooSmallException(numComponents, 2, true);
    }
    if (numComponents > data.length) {
        throw new NumberIsTooLargeException(numComponents, data.length, true);
    }

    final int numRows = data.length;
    double[] sortedData = data.clone();
    Arrays.sort(sortedData);

    // components of mixture model to be created
    double[] mixing = new double[numComponents];
    NormalDistribution[] comp = new NormalDistribution[numComponents];

    // create a component based on data in each bin
    for (int k = 0; k < numComponents; k++) {
        // minimum index (inclusive) from sorted data for this bin
        final int minIndex = (k * numRows) / numComponents;

        // maximum index (exclusive) from sorted data for this bin
        final int maxIndex = Math.min(numRows, ((k + 1) * numRows) / numComponents);

        double m = new Mean().evaluate(sortedData, minIndex, maxIndex - minIndex);
        double sd = new StandardDeviation().evaluate(sortedData, minIndex, maxIndex - minIndex);
        mixing[k] = 1d / numComponents;
        comp[k] = new NormalDistribution(m, sd);
    }

    return new NormalMixtureDistribution(comp, mixing);
}

From source file:com.itemanalysis.psychometrics.irt.estimation.IrtExaminee.java

/**
 * Maximum a Posteriori (MAP) estimate of examinee ability using a normal prior
 * distribution./*  www.  java 2s . c  o  m*/
 *
 * @param mean mean of normal prior distribution
 * @param sd standard deviation of prior distribution
 * @param thetaMin smallest possible ability estimate (lower bound on BrentOptimizer)
 * @param thetaMax largest possible ability estimate (upper bound on BrentOptimizer)
 * @return MAP estimate of examinee ability
 */
public double mapEstimate(double mean, double sd, double thetaMin, double thetaMax) {
    mapPrior = new NormalDistribution(mean, sd);
    method = EstimationMethod.MAP;
    UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
    UnivariatePointValuePair pair = optimizer.optimize(new MaxEval(100), new UnivariateObjectiveFunction(this),
            GoalType.MAXIMIZE, new SearchInterval(thetaMin, thetaMax));
    estimatedTheta = pair.getPoint();
    return estimatedTheta;
}

From source file:com.ibm.bi.dml.runtime.functionobjects.ParameterizedBuiltin.java

/**
 * Helper function to compute distribution-specific cdf (both lowertail and uppertail) and inverse cdf.
 * //  w  w  w  . j  a  v  a  2  s.c om
 * @param dcode
 * @param params
 * @param inverse
 * @return
 * @throws MathArithmeticException
 * @throws DMLRuntimeException
 */
private double computeFromDistribution(ProbabilityDistributionCode dcode, HashMap<String, String> params,
        boolean inverse) throws MathArithmeticException, DMLRuntimeException {

    // given value is "quantile" when inverse=false, and it is "probability" when inverse=true
    double val = Double.parseDouble(params.get("target"));

    boolean lowertail = true;
    if (params.get("lower.tail") != null) {
        lowertail = Boolean.parseBoolean(params.get("lower.tail"));
    }

    AbstractRealDistribution distFunction = null;

    switch (dcode) {
    case NORMAL:

        double mean = 0.0, sd = 1.0; // default values for mean and sd

        String mean_s = params.get("mean"), sd_s = params.get("sd");
        if (mean_s != null)
            mean = Double.parseDouble(mean_s);
        if (sd_s != null)
            sd = Double.parseDouble(sd_s);

        if (sd <= 0)
            throw new DMLRuntimeException(
                    "Standard deviation for Normal distribution must be positive (" + sd + ")");

        distFunction = new NormalDistribution(mean, sd);
        break;

    case EXP:
        double exp_rate = 1.0; // default value for 1/mean or rate

        if (params.get("rate") != null)
            exp_rate = Double.parseDouble(params.get("rate"));
        if (exp_rate <= 0) {
            throw new DMLRuntimeException(
                    "Rate for Exponential distribution must be positive (" + exp_rate + ")");
        }
        // For exponential distribution: mean = 1/rate
        distFunction = new ExponentialDistribution(1.0 / exp_rate);
        break;

    case CHISQ:
        if (params.get("df") == null) {
            throw new DMLRuntimeException(
                    "" + "Degrees of freedom must be specified for chi-squared distribution "
                            + "(e.g., q=qchisq(0.5, df=20); p=pchisq(target=q, df=1.2))");
        }
        int df = UtilFunctions.parseToInt(params.get("df"));

        if (df <= 0) {
            throw new DMLRuntimeException(
                    "Degrees of Freedom for chi-squared distribution must be positive (" + df + ")");
        }
        distFunction = new ChiSquaredDistribution(df);
        break;

    case F:
        if (params.get("df1") == null || params.get("df2") == null) {
            throw new DMLRuntimeException("" + "Degrees of freedom must be specified for F distribution "
                    + "(e.g., q = qf(target=0.5, df1=20, df2=30); p=pf(target=q, df1=20, df2=30))");
        }
        int df1 = UtilFunctions.parseToInt(params.get("df1"));
        int df2 = UtilFunctions.parseToInt(params.get("df2"));
        if (df1 <= 0 || df2 <= 0) {
            throw new DMLRuntimeException(
                    "Degrees of Freedom for F distribution must be positive (" + df1 + "," + df2 + ")");
        }
        distFunction = new FDistribution(df1, df2);
        break;

    case T:
        if (params.get("df") == null) {
            throw new DMLRuntimeException(
                    "" + "Degrees of freedom is needed to compute probabilities from t distribution "
                            + "(e.g., q = qt(target=0.5, df=10); p = pt(target=q, df=10))");
        }
        int t_df = UtilFunctions.parseToInt(params.get("df"));
        if (t_df <= 0) {
            throw new DMLRuntimeException(
                    "Degrees of Freedom for t distribution must be positive (" + t_df + ")");
        }
        distFunction = new TDistribution(t_df);
        break;

    default:
        throw new DMLRuntimeException("Invalid distribution code: " + dcode);

    }

    double ret = Double.NaN;
    if (inverse) {
        // inverse cdf
        ret = distFunction.inverseCumulativeProbability(val);
    } else if (lowertail) {
        // cdf (lowertail)
        ret = distFunction.cumulativeProbability(val);
    } else {
        // cdf (upper tail)

        // TODO: more accurate distribution-specific computation of upper tail probabilities 
        ret = 1.0 - distFunction.cumulativeProbability(val);
    }

    return ret;
}

From source file:edu.cudenver.bios.matrix.DesignEssenceMatrix.java

/**
 * Fills in a random column in the full design matrix
 *
 * @param randomColumn column index in random submatrix
 * @param fullColumn column index in full design matrix
 * @param fullDesign full design matrix//w ww.j ava  2  s .co  m
 */
private void fillRandomColumn(int randomColumn, int fullColumn, RealMatrix fullDesign) {
    // if the column represents a random predictor, build a normal distribution
    // from which to pull random values
    NormalDistribution dist = null;
    // note, the jsc library takes a standard deviation, not a variance so
    // we take the square root
    dist = new NormalDistribution(randomColMetaData[randomColumn].getMean(),
            Math.sqrt(randomColMetaData[randomColumn].getVariance()));
    dist.reseedRandomGenerator(randomSeed);

    for (int row = 0; row < fullDesign.getRowDimension(); row++) {
        // fill in the data
        fullDesign.setEntry(row, fullColumn, dist.sample());
    }
}

From source file:cloudnet.examples.elasticity.bn.DistrHelper.java

private static double[] getWorkloadDistrByAverageValue(double time) {

    double[] result = new double[WorkloadLevel.AllWithOverusage().length];
    int index = 0;
    double levelStep = (100.0 / WorkloadLevel.All().length);

    // get percent
    double percent = (100 * time) / (double) MaxSlaViolationTime;
    //specify distr
    NormalDistribution d = new NormalDistribution(percent / 2, percent / 6);

    // get probabilites
    double[] probabilities = new double[WorkloadLevel.AllWithOverusage().length];
    double maxp = 0.0d;
    for (int l = 0; l < WorkloadLevel.AllWithOverusage().length - 1; l++) {
        double p = d.probability(l * levelStep, (l + 1) * levelStep);
        probabilities[l] = p;/*from w w w.j a va 2s.co  m*/
        maxp = FastMath.max(maxp, p);
    }
    probabilities[WorkloadLevel.AllWithOverusage().length - 1] = d
            .probability(WorkloadLevel.AllWithOverusage().length * levelStep, Double.POSITIVE_INFINITY);

    if (maxp != 0.0d) {

        // and insert their normalized values into result array 
        double sum = 1.0d;
        for (int l = 0; l < probabilities.length - 1; l++) {
            double newValue = FastMath.min(sum, probabilities[l] / maxp);
            result[index++] = newValue;
            sum -= newValue;
        }
        result[index++] = sum;
        Ensure.GreaterThanOrEquals(sum, 0d, "sum of probabilities");
    } else {
        // if no max probability found, just put 1.0 for the closest level
        // let say, if percent = 42 and there are 10 levels, levelIndex = would be 4
        int levelIndex = (int) FastMath.floor(percent / levelStep);
        if (levelIndex > WorkloadLevel.All().length) {
            levelIndex = WorkloadLevel.AllWithOverusage().length - 1;
        }
        Ensure.GreaterThanOrEquals(levelIndex, 0, "levelIndex");
        for (int l = 0; l < WorkloadLevel.AllWithOverusage().length; l++) {
            if (l == levelIndex) {
                result[index++] = 1.0d;
            } else {
                result[index++] = 0.0d;
            }
        }
    }

    return result;
}

From source file:com.gs.obevo.schemagen.SchemaGenerator.java

private MinMaxSupplier getMinMaxSupplier(int min, int max, int mean, int sd) {
    final NormalDistribution distribution = new NormalDistribution(mean, sd);
    return new MinMaxSupplier(new DoubleFunction0() {
        @Override/*from   ww w . jav a2s.  c o m*/
        public double value() {
            return distribution.sample();
        }
    }, min, max);
}

From source file:bide.simulation.Simulation.java

public static void diffLim(double gap, int noOfData, String simdata) {

    double limDet = -8.67;
    double meanDiff = Precision.round(globalSd * gap, 3);
    double halfMeanDiff = Precision.round(meanDiff / 2, 3);
    double smallMean = EMPIRICAL_MEAN - halfMeanDiff;
    System.out.println(meanDiff + "\t" + smallMean + "\t");

    for (int i = 1; i < 12; i++) {

        StringBuilder sb = new StringBuilder(System.getProperty("user.dir")).append(FILE_SEP).append(simdata)
                .append(FILE_SEP).append("DiffLim_").append(i).append(".csv");

        String simFile = sb.toString();
        GelSetting g = new GelSetting(noSpotPerGroup, smallMean, meanDiff, 50, 0, globalSd);
        g.gelSetP(1, 1);/*from w w  w. j  a  v  a 2 s  .c om*/
        NormalDistribution nd = new NormalDistribution(smallMean, globalSd);

        System.out.println(sb.toString());

        try {

            limDet = nd.inverseCumulativeProbability(0.05 * (i - 1));
            System.out.println(simFile + "\t" + limDet);
            g.setLimDet(limDet);
            generateSimDataFile(simFile, g, totalSpot);
        }

        catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:DataPreProcess.ConvertedTrace.java

private void fill_activity(int row, int st, int ed) {
    int mid = (ed + st) / 2;
    double sd = (double) (ed - st) / 4;
    NormalDistribution ND = new NormalDistribution(mid, sd);
    for (int col = 0; col < Length; col++) {
        double pro_density = ND.density(col);
        Matrix[row][col] += pro_density;
    }/*from   w w w  .  j  a  v  a 2  s  . co  m*/
    //        for (int col = st; col < ed; col++) {
    //            Matrix[row][col] = 1;
    //        }
}

From source file:it.uniroma2.sag.kelp.learningalgorithm.classification.scw.SoftConfidenceWeightedClassification.java

/**
 * Set the <code>eta</code> parameter and update <code>phi</code>,
 * <code>psi</code> and <code>epsilon</code> parameters
 * //  w w  w. j ava  2s. com
 * @param eta
 *            The <code>eta</code> parameter
 * 
 */
private void setConfidence(float eta) {
    this.eta = eta;

    this.phi = (float) new NormalDistribution(0f, 1f).inverseCumulativeProbability(eta);

    this.psi = 1 + (phi * phi) / 2f;

    this.epsilon = 1 + phi * phi;
}

From source file:com.wormsim.utils.Utils.java

/**
 * Returns the distribution associated with the specified string. See the
 * handbook for details of what is accepted. Or the code...
 *
 * @param str The string representing a distribution
 *
 * @return The distribution// w  w w  .  ja  v  a  2  s.  c  om
 */
public static RealDistribution readRealDistribution(String str) {
    if (str.matches("[0-9]+(.[0-9]*)?")) {
        // I.E. a number
        return new ConstantRealDistribution(Double.valueOf(str));
    } else {
        int index = str.indexOf('(');
        String prefix = str.substring(0, index).toLowerCase(Locale.ROOT);
        switch (prefix) {
        case "n":
        case "norm":
        case "normal": {
            int comma_index = str.indexOf(',', index);
            return new NormalDistribution(Double.valueOf(str.substring(index + 1, comma_index).trim()),
                    Double.valueOf(str.substring(comma_index + 1, str.length() - 2).trim()));
        }
        case "u":
        case "uni":
        case "uniform": {
            int comma_index = str.indexOf(',', index);
            return new UniformRealDistribution(Double.valueOf(str.substring(index + 1, comma_index - 1)),
                    Double.valueOf(str.substring(comma_index).trim()));
        }
        default:
            throw new IllegalArgumentException(
                    "Unrecognised distribution form, see handbook for details. " + "Provided \"" + str + "\".");
        }
    }
}