Example usage for com.google.common.primitives Doubles toArray

List of usage examples for com.google.common.primitives Doubles toArray

Introduction

In this page you can find the example usage for com.google.common.primitives Doubles toArray.

Prototype

public static double[] toArray(Collection<? extends Number> collection) 

Source Link

Document

Returns an array containing each value of collection , converted to a double value in the manner of Number#doubleValue .

Usage

From source file:com.sop4j.SimpleStatistics.java

public static void main(String[] args) {
    final MersenneTwister rng = new MersenneTwister(); // used for RNG... READ THE DOCS!!!
    final int[] values = new int[NUM_VALUES];

    final DescriptiveStatistics descriptiveStats = new DescriptiveStatistics(); // stores values
    final SummaryStatistics summaryStats = new SummaryStatistics(); // doesn't store values
    final Frequency frequency = new Frequency();

    // add numbers into our stats
    for (int i = 0; i < NUM_VALUES; ++i) {
        values[i] = rng.nextInt(MAX_VALUE);

        descriptiveStats.addValue(values[i]);
        summaryStats.addValue(values[i]);
        frequency.addValue(values[i]);/*from   w  w w.j av a2 s . c o m*/
    }

    // print out some standard stats
    System.out.println("MIN: " + summaryStats.getMin());
    System.out.println("AVG: " + String.format("%.3f", summaryStats.getMean()));
    System.out.println("MAX: " + summaryStats.getMax());

    // get some more complex stats only offered by DescriptiveStatistics
    System.out.println("90%: " + descriptiveStats.getPercentile(90));
    System.out.println("MEDIAN: " + descriptiveStats.getPercentile(50));
    System.out.println("SKEWNESS: " + String.format("%.4f", descriptiveStats.getSkewness()));
    System.out.println("KURTOSIS: " + String.format("%.4f", descriptiveStats.getKurtosis()));

    // quick and dirty stats (need a little help from Guava to convert from int[] to double[])
    System.out.println("MIN: " + StatUtils.min(Doubles.toArray(Ints.asList(values))));
    System.out.println("AVG: " + String.format("%.4f", StatUtils.mean(Doubles.toArray(Ints.asList(values)))));
    System.out.println("MAX: " + StatUtils.max(Doubles.toArray(Ints.asList(values))));

    // some stats based upon frequencies
    System.out.println("NUM OF 7s: " + frequency.getCount(7));
    System.out.println("CUMULATIVE FREQUENCY OF 7: " + frequency.getCumFreq(7));
    System.out.println("PERCENTAGE OF 7s: " + frequency.getPct(7));
}

From source file:DifferentalEvolution.java

public static void main(String[] args) {
    solutions = new ArrayList<Double>(ControlVariables.RUNS_PER_FUNCTION);

    /* An array of the benchmark functions to evalute */
    benchmarkFunctions = new ArrayList<FitnessFunction>();
    benchmarkFunctions.add(new DeJong());
    benchmarkFunctions.add(new HyperEllipsoid());
    benchmarkFunctions.add(new Schwefel());
    benchmarkFunctions.add(new RosenbrocksValley());
    benchmarkFunctions.add(new Rastrigin());

    /* Apply the differential evolution algorithm to each benchmark function */
    for (FitnessFunction benchmarkFunction : benchmarkFunctions) {
        /* Set the fitness function for the current benchmark function */
        fitnessFunction = benchmarkFunction;

        /* Execute the differential evolution algorithm a number of times per function */
        for (int runs = 0; runs < ControlVariables.RUNS_PER_FUNCTION; ++runs) {
            int a;
            int b;
            int c;
            boolean validVector = false;
            Vector noisyVector = null;

            /* Reset the array of the best values found */
            prevAmount = 0;//from ww w . j  av a2  s. c om
            lowestFit = new LinkedHashMap<Integer, Double>();
            lowestFit.put(prevAmount, Double.MAX_VALUE);

            initPopulation(fitnessFunction.getBounds());

            /* Reset the fitness function NFC each time */
            fitnessFunction.resetNFC();

            while (fitnessFunction.getNFC() < ControlVariables.MAX_FUNCTION_CALLS) {
                for (int i = 0; i < ControlVariables.POPULATION_SIZE; i++) {
                    // Select 3 Mutually Exclusive Parents i != a != b != c
                    while (!validVector) {
                        do {
                            a = getRandomIndex();
                        } while (a == i);

                        do {
                            b = getRandomIndex();
                        } while (b == i || b == a);

                        do {
                            c = getRandomIndex();
                        } while (c == i || c == a || c == b);

                        // Catch invalid vectors
                        try {
                            validVector = true;
                            noisyVector = VectorOperations.mutation(population.get(c), population.get(b),
                                    population.get(a));
                        } catch (IllegalArgumentException e) {
                            validVector = false;
                        }
                    }

                    validVector = false;

                    Vector trialVector = VectorOperations.crossover(population.get(i), noisyVector, random);

                    trialVector.setFitness(fitnessFunction.evaluate(trialVector));

                    population.set(i, VectorOperations.selection(population.get(i), trialVector));

                    /* Get the best fitness value found so far */
                    if (population.get(i).getFitness() < lowestFit.get(prevAmount)) {
                        prevAmount = fitnessFunction.getNFC();
                        bestValue = population.get(i).getFitness();
                        lowestFit.put(prevAmount, bestValue);
                    }
                }
            }

            /* save the best value found for the entire DE algorithm run */
            solutions.add(bestValue);
        }

        /* Display the mean and standard deviation */
        System.out.println("\nResults for " + fitnessFunction.getName());
        DescriptiveStatistics stats = new DescriptiveStatistics(Doubles.toArray(solutions));
        System.out.println("AVERAGE BEST FITNESS: " + stats.getMean());
        System.out.println("STANDARD DEVIATION:   " + stats.getStandardDeviation());

        /* Set the last value (NFC) to the best value found */
        lowestFit.put(ControlVariables.MAX_FUNCTION_CALLS, bestValue);

        /* Plot the best value found vs. NFC */
        PerformanceGraph.plot(lowestFit, fitnessFunction.getName());

        /* Reset the results for the next benchmark function to be evaluated */
        solutions.clear();
        lowestFit.clear();
        bestValue = Double.MAX_VALUE;
    }
}

From source file:jflowmap.util.ArrayUtils.java

public static double[] toArrayOfPrimitives(Iterable<Double> data) {
    if (data instanceof Collection) {
        return Doubles.toArray((Collection<Double>) data);
    } else {//from w  w w. j av  a2s . c  o m
        return Doubles.toArray(ImmutableList.copyOf(data));
    }
}

From source file:com.davidbracewell.ml.regression.Regression.java

/**
 * Pearson's correlation coefficient.//from   w ww .  j av a 2  s  . c om
 *
 * @param model the model
 * @param data  the data
 * @return the double
 */
public static double correlationCoefficient(RegressionModel model, List<Instance> data) {
    PearsonsCorrelation correlation = new PearsonsCorrelation();
    List<Double> gold = Lists.newArrayList();
    List<Double> pred = Lists.newArrayList();
    for (Instance instance : data) {
        if (instance.hasTargetValue()) {
            gold.add(instance.getTargetValue());
            pred.add(model.estimate(instance));
        }
    }
    return correlation.correlation(Doubles.toArray(gold), Doubles.toArray(pred));
}

From source file:bb.mcmc.analysis.ConvergeStatUtils.java

public static HashMap<String, double[]> traceInfoToArrays(HashMap<String, ArrayList<Double>> traceInfo,
        int burnin) {

    HashMap<String, double[]> newValues = new HashMap<String, double[]>();
    final Set<String> names = traceInfo.keySet();

    for (String key : names) {
        final List<Double> t = getSubList(traceInfo.get(key), burnin);
        newValues.put(key, Doubles.toArray(t));
    }//  w  w  w . ja  v  a 2s  .c o m
    return newValues;
}

From source file:org.terasology.persistence.typeHandling.coreTypes.NumberTypeHandler.java

@Override
public PersistedData serializeCollection(Collection<Number> value, SerializationContext context) {
    return context.create(Doubles.toArray(value));
}

From source file:sklearn.tree.Tree.java

public double[] getThreshold() {
    return Doubles.toArray(getNodeAttribute("threshold"));
}

From source file:org.jpmml.evaluator.RegressionAggregator.java

static double median(List<Double> values) {
    double[] data = Doubles.toArray(values);

    // The data must be ordered
    Arrays.sort(data);//from   ww w. j  a v  a2  s  .  c  o m

    Percentile percentile = new Percentile();
    percentile.setData(data);

    return percentile.evaluate(50);
}

From source file:net.larry1123.elec.util.config.fieldhanders.doubles.DoubleArrayListFieldHandler.java

/**
 * {@inheritDoc}//from   w w  w. j  a  v  a2  s .co m
 */
@Override
public void setToFile(ArrayList<Double> value) {
    if (CollectionUtils.isNotEmpty(value)) {
        getPropertiesFile().setDoubleArray(getPropertyKey(), Doubles.toArray(value), getSpacer());
    }
}

From source file:sklearn.tree.Tree.java

public double[] getValues() {
    List<? extends Number> values = (List<? extends Number>) ClassDictUtil.getArray(this, "values");

    return Doubles.toArray(values);
}