Java Code Examples for com.google.common.primitives.Doubles#asList()

The following examples show how to use com.google.common.primitives.Doubles#asList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TensorUtil.java    From jpmml-tensorflow with GNU Affero General Public License v3.0 7 votes vote down vote up
static
public List<?> getValues(Tensor tensor){
	DataType dataType = tensor.dataType();

	switch(dataType){
		case FLOAT:
			return Floats.asList(TensorUtil.toFloatArray(tensor));
		case DOUBLE:
			return Doubles.asList(TensorUtil.toDoubleArray(tensor));
		case INT32:
			return Ints.asList(TensorUtil.toIntArray(tensor));
		case INT64:
			return Longs.asList(TensorUtil.toLongArray(tensor));
		case STRING:
			return Arrays.asList(TensorUtil.toStringArray(tensor));
		case BOOL:
			return Booleans.asList(TensorUtil.toBooleanArray(tensor));
		default:
			throw new IllegalArgumentException();
	}
}
 
Example 2
Source File: GLMNetConverter.java    From jpmml-r with GNU Affero General Public License v3.0 6 votes vote down vote up
static
public List<Double> getCoefficients(S4Object beta, int column){
	RIntegerVector i = beta.getIntegerAttribute("i");
	RIntegerVector p = beta.getIntegerAttribute("p");
	RIntegerVector dim = beta.getIntegerAttribute("Dim");
	RDoubleVector x = beta.getDoubleAttribute("x");

	double[] result = new double[dim.getValue(0)];

	int begin = p.getValue(column);
	int end = p.getValue(column + 1);

	for(int index = begin; index < end; index++){
		result[i.getValue(index)] = x.getValue(index);
	}

	return Doubles.asList(result);
}
 
Example 3
Source File: Plots.java    From java-timeseries with MIT License 6 votes vote down vote up
/**
 * Plot a time series, connecting the observation times to the measurements.
 *
 * @param timeSeries the series to plot.
 * @param title      the title of the plot.
 * @param seriesName the name of the series to display.
 */
public static void plot(final TimeSeries timeSeries, final String title, final String seriesName) {
    Thread plotThread = new Thread(() -> {
        final List<Date> xAxis = new ArrayList<>(timeSeries.observationTimes().size());
        for (Time time : timeSeries.observationTimes()) {
            xAxis.add(Date.from(time.toInstant()));
        }
        List<Double> seriesList = Doubles.asList(round(timeSeries.asArray(), 2));
        final XYChart chart = new XYChartBuilder().theme(Styler.ChartTheme.GGPlot2)
                                                  .height(600)
                                                  .width(800)
                                                  .title(title)
                                                  .build();
        XYSeries residualSeries = chart.addSeries(seriesName, xAxis, seriesList);
        residualSeries.setXYSeriesRenderStyle(XYSeries.XYSeriesRenderStyle.Scatter);
        residualSeries.setMarker(new Circle()).setMarkerColor(Color.RED);

        JPanel panel = new XChartPanel<>(chart);
        JFrame frame = new JFrame(title);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    });
    plotThread.start();
}
 
Example 4
Source File: MinibatchSliceSamplerUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Tests slice sampling of a normal posterior = uniform prior x normal likelihood from 1000 data points.
 * Checks that input mean and standard deviation are recovered from the posterior of the mean parameter
 * by 500 burn-in samples + 1000 samples to a relative error of 1% and 5%, respectively.
 */
@Test
public void testSliceSamplingOfNormalPosterior() {
    rng.setSeed(RANDOM_SEED);

    final double mean = 5.;
    final double standardDeviation = 0.75;
    final NormalDistribution normalDistribution = new NormalDistribution(rng, mean, standardDeviation);
    final BiFunction<Double, Double, Double> normalLogLikelihood =
            (d, x) -> new NormalDistribution(null, x, standardDeviation).logDensity(d);
    final List<Double> data = Doubles.asList(normalDistribution.sample(NUM_DATA_POINTS));

    final double xInitial = 1.;
    final double xMin = Double.NEGATIVE_INFINITY;
    final double xMax = Double.POSITIVE_INFINITY;
    final double width = 0.5;
    final int numBurnInSamples = 500;
    final int numSamples = 1500;
    final MinibatchSliceSampler<Double> normalSampler = new MinibatchSliceSampler<>(
            rng, data, UNIFORM_LOG_PRIOR, normalLogLikelihood,
            xMin, xMax, width, MINIBATCH_SIZE, APPROX_THRESHOLD);
    final double[] samples = Doubles.toArray(normalSampler.sample(xInitial, numSamples).subList(numBurnInSamples, numSamples));

    final double sampleMean = new Mean().evaluate(samples);
    final double sampleStandardDeviation = new StandardDeviation().evaluate(samples);
    Assert.assertEquals(relativeError(sampleMean, mean), 0., 0.01);
    Assert.assertEquals(relativeError(sampleStandardDeviation, standardDeviation / Math.sqrt(NUM_DATA_POINTS)), 0., 0.05);
}
 
Example 5
Source File: GamaFloatMatrix.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Method iterator()
 *
 * @see msi.gama.util.matrix.GamaMatrix#iterator()
 */
// @Override
// public Iterator<Double> iterator() {
// return Doubles.asList(getMatrix()).iterator();
// }

@Override
public java.lang.Iterable<Double> iterable(final IScope scope) {
	return Doubles.asList(getMatrix());
}
 
Example 6
Source File: AlleleFractionHMMUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void logPriorTest() {
    final List<Double> weights = Doubles.asList(MathUtils.normalizeFromRealSpace(new double[] {0.2, 0.2, 0.6, 0.1, 0.9, 0.1}));
    final List<Double> minorAlleleFractions = Arrays.asList(0.1, 0.2, 0.3, 0.4, 0.5, 0.33);
    final double memoryLength = 5e6;
    final AlleleFractionHMM model = new AlleleFractionHMM(minorAlleleFractions, weights,
            memoryLength, AllelicPanelOfNormals.EMPTY_PON, NO_BIAS_OR_OUTLIERS_PARAMS);

    final SimpleInterval position1 = new SimpleInterval("chr1", 100, 100);
    final SimpleInterval position2 = new SimpleInterval("chr2", 20000, 20000);
    for (int n = 0; n < weights.size(); n++) {
        Assert.assertEquals(model.logPriorProbability(n, position1), Math.log(weights.get(n)));
        Assert.assertEquals(model.logPriorProbability(n, position2), Math.log(weights.get(n)));
    }
}
 
Example 7
Source File: AlleleFractionHMMUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testTransitionProbabilities() {
    final List<Double> weights = Doubles.asList(MathUtils.normalizeFromRealSpace(new double[] {0.2, 0.2, 0.6, 0.1, 0.9, 0.1}));
    final List<Double> minorAlleleFractions = Arrays.asList(0.1, 0.2, 0.3, 0.4, 0.23, 0.11);
    final double memoryLength = 5e6;
    final AlleleFractionHMM model = new AlleleFractionHMM(minorAlleleFractions, weights,
            memoryLength, AllelicPanelOfNormals.EMPTY_PON, NO_BIAS_OR_OUTLIERS_PARAMS);

    final int pos1 = 100;
    final int pos2 = (int) (pos1 + 100*memoryLength);  // really far!!!
    final int pos3 = (int) (pos1 + memoryLength/1000);  // really close!!!
    final SimpleInterval position1 = new SimpleInterval("chr1", pos1, pos1);
    final SimpleInterval position2 = new SimpleInterval("chr1", pos2, pos2);
    final SimpleInterval position3 = new SimpleInterval("chr1", pos3, pos3);

    for (int fromState = 0; fromState < weights.size(); fromState++) {
        for (int toState = 0; toState < weights.size(); toState++) {
            // long distances
            Assert.assertEquals(model.logTransitionProbability(fromState, position1, toState, position2),
                    model.logPriorProbability(toState, position2), 1e-3);

            //short distances
            if (toState == fromState) {
                Assert.assertEquals(model.logTransitionProbability(fromState, position1, toState, position3),
                        Math.log(1), 1e-3);
            } else {
                Assert.assertTrue(model.logTransitionProbability(fromState, position1, toState, position3) < Math.log(1e-3));
            }
        }
    }
}
 
Example 8
Source File: LocalDateDoubleTimeSeriesBuilderTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_putAll_toBuilder() {
  Collection<LocalDate> dates = Arrays.asList(date(2013, 1, 1), date(2014, 1, 1));
  Collection<Double> values = Doubles.asList(2d, 3d);
  LocalDateDoubleTimeSeries base = LocalDateDoubleTimeSeries.builder().putAll(dates, values).build();

  LocalDateDoubleTimeSeriesBuilder test = LocalDateDoubleTimeSeries.builder();
  test.put(date(2012, 1, 1), 0d);
  test.put(date(2013, 1, 1), 1d);
  test.putAll(base.toBuilder());

  assertThat(test.get(date(2012, 1, 1))).hasValue(0d);
  assertThat(test.get(date(2013, 1, 1))).hasValue(2d);
  assertThat(test.get(date(2014, 1, 1))).hasValue(3d);
}
 
Example 9
Source File: LocalDateDoubleTimeSeriesBuilderTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_putAll_collections() {
  Collection<LocalDate> dates = Arrays.asList(date(2013, 1, 1), date(2014, 1, 1));
  Collection<Double> values = Doubles.asList(2d, 3d);
  LocalDateDoubleTimeSeriesBuilder test = LocalDateDoubleTimeSeries.builder();
  test.putAll(dates, values);

  assertThat(test.get(date(2013, 1, 1))).hasValue(2d);
  assertThat(test.get(date(2014, 1, 1))).hasValue(3d);
}
 
Example 10
Source File: CopyRatioSegmenter.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * evenly-spaced log-2 copy ratios
 * @param K the initial number of hidden states
 */
private static List<Double> initialNonConstantLog2CopyRatios(final int K) {
    ParamUtils.isPositive(K, "must have at least one non-constant state");
    final double spacing = (MAX_INITIAL_LOG_2_COPY_RATIO  - MIN_INITIAL_LOG_2_COPY_RATIO) / (K + 1);
    final int numNegativeStates = K / 2;
    final int numPositiveStates = K - numNegativeStates;
    final List<Double> negativeStates = Doubles.asList(GATKProtectedMathUtils.createEvenlySpacedPoints(MIN_INITIAL_LOG_2_COPY_RATIO, spacing, numNegativeStates));
    final List<Double> positiveStates = Doubles.asList(GATKProtectedMathUtils.createEvenlySpacedPoints(spacing, MAX_INITIAL_LOG_2_COPY_RATIO, numPositiveStates));
    return ListUtils.union(negativeStates, positiveStates);
}
 
Example 11
Source File: LocalDateDoubleTimeSeriesBuilderTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_putAll_stream() {
  Collection<LocalDate> dates = Arrays.asList(date(2013, 1, 1), date(2014, 1, 1));
  Collection<Double> values = Doubles.asList(2d, 3d);
  LocalDateDoubleTimeSeries base = LocalDateDoubleTimeSeries.builder().putAll(dates, values).build();

  LocalDateDoubleTimeSeriesBuilder test = LocalDateDoubleTimeSeries.builder();
  test.put(date(2012, 1, 1), 0d);
  test.put(date(2013, 1, 1), 1d);
  test.putAll(base.stream());

  assertThat(test.get(date(2012, 1, 1))).hasValue(0d);
  assertThat(test.get(date(2013, 1, 1))).hasValue(2d);
  assertThat(test.get(date(2014, 1, 1))).hasValue(3d);
}
 
Example 12
Source File: ClusteringGenomicHMM.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ClusteringGenomicHMM(final List<HIDDEN> hiddenStateValues, final List<Double> weights, final double memoryLength) {
    this.hiddenStateValues = new ArrayList<>(Utils.nonNull(hiddenStateValues));
    Utils.nonNull(weights);
    weights.forEach(w -> ParamUtils.isPositiveOrZero(w, "weights may not be negative."));
    Utils.nonEmpty(hiddenStateValues, "must have at least one hidden state");

    this.weights = Doubles.asList(MathUtils.normalizeFromRealSpace(weights.stream().mapToDouble(x->x).toArray()));
    this.memoryLength = ParamUtils.isPositive(memoryLength, "CNV memory length must be positive");
}
 
Example 13
Source File: VectorUtil.java    From jpmml-sparkml with GNU Affero General Public License v3.0 5 votes vote down vote up
static
public List<Double> toList(Vector vector){
	DenseVector denseVector = vector.toDense();

	double[] values = denseVector.values();

	return Doubles.asList(values);
}
 
Example 14
Source File: DoubleVec.java    From kudu-ts with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list view of the vector.
 * The vector should not be concurrently modified while the list is in use.
 * @return a list view of the vector
 */
public List<Double> asList() {
  List<Double> list = Doubles.asList(data);
  if (len < data.length) return list.subList(0, len);
  return list;
}
 
Example 15
Source File: Range.java    From java-timeseries with MIT License 4 votes vote down vote up
public List<Double> asList() {
    return Doubles.asList(this.range.clone());
}
 
Example 16
Source File: RDoubleVector.java    From jpmml-r with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<Double> getValues(){
	return Doubles.asList(this.values);
}
 
Example 17
Source File: SomaticClusteringModel.java    From gatk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void initializeClusters() {
    Utils.validate(!clustersHaveBeenInitialized, "Clusters have already been initialized.");

    final double[] somaticProbs = data.stream().mapToDouble(this::probabilityOfSomaticVariant).toArray();

    double previousBIC = Double.NEGATIVE_INFINITY;

    for (int cluster = 0; cluster < MAX_BINOMIAL_CLUSTERS; cluster++) {
        final double[] oldLogClusterWeights = Arrays.copyOf(logClusterWeights, logClusterWeights.length);

        final double[] backgroundProbsGivenSomatic = data.stream().mapToDouble(datum -> backgroundProbGivenSomatic(datum.getTotalCount(), datum.getAltCount())).toArray();
        final double[] backGroundProbs = MathArrays.ebeMultiply(somaticProbs, backgroundProbsGivenSomatic);
        final double[] alleleFractionQuantiles = calculateAlleleFractionQuantiles();

        // calculate how much total probability is assigned to the background cluster, then split off a peak from the background
        final double[] totalQuantileBackgroundResponsibilities = calculateQuantileBackgroundResponsibilities(alleleFractionQuantiles, backGroundProbs);

        final List<Pair<Double, Double>> peaksAndMasses = calculatePeaksAndMasses(alleleFractionQuantiles, totalQuantileBackgroundResponsibilities);

        if (peaksAndMasses.isEmpty()) {
            break;
        }

        final Pair<Double, Double> biggestPeakAndMass = peaksAndMasses.stream().sorted(Comparator.comparingDouble(Pair<Double, Double>::getRight).reversed()).findFirst().get();

        if (biggestPeakAndMass.getLeft() < alleleFractionQuantiles[Math.min(MIN_QUANTILE_INDEX_FOR_MAKING_CLUSTER, alleleFractionQuantiles.length-1)]) {
            break;
        }

        final double totalMass = peaksAndMasses.stream().mapToDouble(Pair::getRight).sum();
        final double fractionOfBackgroundToSplit = Math.min(MAX_FRACTION_OF_BACKGROUND_TO_SPLIT_OFF, biggestPeakAndMass.getRight() / totalMass);
        final double newClusterLogWeight = Math.log(fractionOfBackgroundToSplit) + logClusterWeights[0];
        final double newBackgroundWeight = Math.log1p(fractionOfBackgroundToSplit) + logClusterWeights[0];

        clusters.add(new BinomialCluster(biggestPeakAndMass.getLeft()));

        final List<Double> newLogWeights = new ArrayList<>(Doubles.asList(logClusterWeights));
        newLogWeights.add(newClusterLogWeight);
        newLogWeights.set(0, newBackgroundWeight);
        logClusterWeights = Doubles.toArray(newLogWeights);

        for (int n = 0; n < NUM_ITERATIONS; n++) {
            performEMIteration(false);
        }

        final double[] logLikelihoodsGivenSomatic = data.stream().mapToDouble(datum -> logLikelihoodGivenSomatic(datum.getTotalCount(), datum.getAltCount())).toArray();

        final double weightedLogLikelihood = MathUtils.sum(MathArrays.ebeMultiply(somaticProbs, logLikelihoodsGivenSomatic));
        final double effectiveSomaticCount = MathUtils.sum(somaticProbs);
        final double numParameters = 2 * clusters.size();


        // if splitting off the peak worsened the BIC score, remove the new peak and we're done
        final double currentBIC = weightedLogLikelihood - numParameters * Math.log(effectiveSomaticCount);
        if (currentBIC < previousBIC) {
            clusters.remove(clusters.size() - 1);
            logClusterWeights = oldLogClusterWeights;
            break;
        }
        previousBIC = currentBIC;
    }

    clustersHaveBeenInitialized = true;
}
 
Example 18
Source File: DoubleFunctions.java    From java-timeseries with MIT License 2 votes vote down vote up
/**
 * Create a new list of boxed Doubles from the given array of primitive doubles.
 *
 * @param data the data to populate the new list with.
 * @return a new list of boxed Doubles from the given array of primitive doubles.
 */
public static List<Double> listFrom(final double... data) {
    return Doubles.asList(data.clone());
}
 
Example 19
Source File: ArrayUtil.java    From j360-dubbo-app-all with Apache License 2.0 2 votes vote down vote up
/**
 * Arrays.asList()的加强版, 返回一个底层为原始类型double的List
 *
 * 与保存Double相比节约空间,同时也避免了AutoBoxing.
 *
 * @see Arrays#asList(Object...)
 * @see com.google.common.primitives.Doubles#asList(double...)
 */
public static List<Double> doubleAsList(double... backingArray) {
	return Doubles.asList(backingArray);
}
 
Example 20
Source File: ArrayUtil.java    From vjtools with Apache License 2.0 2 votes vote down vote up
/**
 * Arrays.asList()的加强版, 返回一个底层为原始类型double的List
 * 
 * 与保存Double相比节约空间,同时也避免了AutoBoxing.
 * 
 * @see java.util.Arrays#asList(Object...)
 * @see com.google.common.primitives.Doubles#asList(double...)
 */
public static List<Double> doubleAsList(double... backingArray) {
	return Doubles.asList(backingArray);
}