com.google.common.primitives.Doubles Java Examples

The following examples show how to use com.google.common.primitives.Doubles. 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: GBTClassificationModelConverter.java    From jpmml-sparkml with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public MiningModel encodeModel(Schema schema){
	GBTClassificationModel model = getTransformer();

	String lossType = model.getLossType();
	switch(lossType){
		case "logistic":
			break;
		default:
			throw new IllegalArgumentException("Loss function " + lossType + " is not supported");
	}

	Schema segmentSchema = schema.toAnonymousRegressorSchema(DataType.DOUBLE);

	List<TreeModel> treeModels = TreeModelUtil.encodeDecisionTreeEnsemble(this, segmentSchema);

	MiningModel miningModel = new MiningModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(segmentSchema.getLabel()))
		.setSegmentation(MiningModelUtil.createSegmentation(Segmentation.MultipleModelMethod.WEIGHTED_SUM, treeModels, Doubles.asList(model.treeWeights())))
		.setOutput(ModelUtil.createPredictedOutput(FieldName.create("gbtValue"), OpType.CONTINUOUS, DataType.DOUBLE));

	return MiningModelUtil.createBinaryLogisticClassification(miningModel, 2d, 0d, RegressionModel.NormalizationMethod.LOGIT, false, schema);
}
 
Example #3
Source File: SliceSamplerUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Tests slice sampling of a monotonic beta distribution as an example of sampling of a bounded random variable.
 * Checks that input mean and variance are recovered by 10000 samples to a relative error of 0.5% and 2%,
 * respectively.
 */
@Test
public void testSliceSamplingOfMonotonicBetaDistribution() {
    rng.setSeed(RANDOM_SEED);

    final double alpha = 10.;
    final double beta = 1.;
    final BetaDistribution betaDistribution = new BetaDistribution(alpha, beta);
    final Function<Double, Double> betaLogPDF = betaDistribution::logDensity;
    final double mean = betaDistribution.getNumericalMean();
    final double variance = betaDistribution.getNumericalVariance();

    final double xInitial = 0.5;
    final double xMin = 0.;
    final double xMax = 1.;
    final double width = 0.1;
    final int numSamples = 10000;
    final SliceSampler betaSampler = new SliceSampler(rng, betaLogPDF, xMin, xMax, width);
    final double[] samples = Doubles.toArray(betaSampler.sample(xInitial, numSamples));

    final double sampleMean = new Mean().evaluate(samples);
    final double sampleVariance = new Variance().evaluate(samples);
    Assert.assertEquals(relativeError(sampleMean, mean), 0., 0.005);
    Assert.assertEquals(relativeError(sampleVariance, variance), 0., 0.02);
}
 
Example #4
Source File: IntensityPlotDataset.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
public Number getStdDevValue(int row, int column) {
  Feature[] peaks = getPeaks(xValues[column], selectedRows[row]);

  // if we have only 1 peak, there is no standard deviation
  if (peaks.length == 1)
    return 0;

  HashSet<Double> values = new HashSet<Double>();
  for (int i = 0; i < peaks.length; i++) {
    if (peaks[i] == null)
      continue;
    if (yAxisValueSource == YAxisValueSource.HEIGHT)
      values.add(peaks[i].getHeight());
    if (yAxisValueSource == YAxisValueSource.AREA)
      values.add(peaks[i].getArea());
    if (yAxisValueSource == YAxisValueSource.RT)
      values.add(peaks[i].getRT());
  }
  double doubleValues[] = Doubles.toArray(values);
  double std = MathUtils.calcStd(doubleValues);
  return std;
}
 
Example #5
Source File: SliceSamplerUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test slice sampling of a monotonic beta distribution as an example of sampling of a bounded random variable.
 * Checks that input mean and variance are recovered by 10000 samples to a relative error of 0.5% and 2%,
 * respectively.
 */
@Test
public void testSliceSamplingOfMonotonicBetaDistribution() {
    rng.setSeed(RANDOM_SEED);

    final double alpha = 10.;
    final double beta = 1.;
    final BetaDistribution betaDistribution = new BetaDistribution(alpha, beta);
    final Function<Double, Double> betaLogPDF = betaDistribution::logDensity;

    final double xInitial = 0.5;
    final double xMin = 0.;
    final double xMax = 1.;
    final double width = 0.1;
    final int numSamples = 10000;
    final SliceSampler betaSampler = new SliceSampler(rng, betaLogPDF, xMin, xMax, width);
    final double[] samples = Doubles.toArray(betaSampler.sample(xInitial, numSamples));

    final double mean = betaDistribution.getNumericalMean();
    final double variance = betaDistribution.getNumericalVariance();
    final double sampleMean = new Mean().evaluate(samples);
    final double sampleVariance = new Variance().evaluate(samples);
    Assert.assertEquals(relativeError(sampleMean, mean), 0., 0.005);
    Assert.assertEquals(relativeError(sampleVariance, variance), 0., 0.02);
}
 
Example #6
Source File: HttpResponseAssert.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that the Http Response contains a numeric value at the given Json Pointer (JavaScript Object Notation
 * (JSON) Pointer). The Json Pointer syntax is described in the
 * <a href="https://tools.ietf.org/html/rfc6901">RFC 6901</a>.
 *
 * @param path  the Json Pointer
 * @param value the expected value
 * @return the current {@link HttpResponseAssert}
 */
public HttpResponseAssert<T> hasJsonNumericField(String path, double value) {
    isNotNull();
    isJson();

    final JsonNode node = ((JsonNode) actual.body()).at(path);
    if (node.isMissingNode()) {
        failWithMessage("Expected node pointed by <%s> to be present in <%s>", path, actual.body().toString());
    }
    // We cannot compare double directly as it may lead to precision issues.
    if (Doubles.compare(node.asDouble(), value) == 0) {
        failWithMessage("Expected node pointed by <%s> to be <%s> but was <%s>", path, value, node.asDouble());
    }

    return this;
}
 
Example #7
Source File: QueryTest.java    From phoenix with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testScanByUnsigned_DoubleValue() throws Exception {
    String query = "SELECT a_string, b_string, a_unsigned_double FROM aTable WHERE ?=organization_id and ?=a_unsigned_double";
    Properties props = new Properties(TEST_PROPERTIES);
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 2
    Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        statement.setDouble(2, 0.0001);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertEquals(rs.getString(1), A_VALUE);
        assertEquals(rs.getString("B_string"), B_VALUE);
        assertTrue(Doubles.compare(rs.getDouble(3), 0.0001) == 0);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example #8
Source File: NotQueryIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotEqualsByDouble() throws Exception {
    String query = "SELECT a_double -- and here comment\n" + 
    "FROM " + tableName + " WHERE organization_id=? and a_double != CAST(0.0001 AS DOUBLE) and a_double <= CAST(0.0002 AS DOUBLE)";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertTrue(Doubles.compare(rs.getDouble(1), 0.0002) == 0);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example #9
Source File: NotQueryIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotEqualsByDouble() throws Exception {
    String query = "SELECT a_double -- and here comment\n" + 
    "FROM aTable WHERE organization_id=? and a_double != 0.0001d and a_double <= 0.0002d";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 2
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertTrue(Doubles.compare(rs.getDouble(1), 0.0002) == 0);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example #10
Source File: Jaccard.java    From termsuite-core with Apache License 2.0 6 votes vote down vote up
@Override
protected double getValue(ContextVector source, ContextVector target, Explanation expl) {
	double infSum = 0;
	double supSum = 0;
	Set<Term> terms = Sets.newHashSet();
	terms.addAll(source.terms());
	terms.addAll(target.terms());
	double sourceValue;
	double targetValue;
	double partialInf;
	double partialSup;
	for (Term term : terms) {
		sourceValue = source.getAssocRate(term);
		targetValue = target.getAssocRate(term);
		partialInf = Doubles.min(sourceValue, targetValue);
		partialSup = Doubles.max(sourceValue, targetValue);
		infSum += partialInf;
		supSum += partialSup;
		if(partialInf > 0)
			expl.addExplanation(term, partialInf);
	}
	return supSum == 0 ? 0 : infSum / supSum;
}
 
Example #11
Source File: ATM.java    From TimeIsMoney with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new atm instance with the {@link de.Linus122.TimeIsMoney.Main} class.
 *
 * @param plugin The {@link de.Linus122.TimeIsMoney.Main} class that implements {@link org.bukkit.plugin.java.JavaPlugin}.
 */
public ATM(Main plugin) {
	this.plugin = plugin;
	plugin.getServer().getPluginManager().registerEvents(this, plugin);
	plugin.getCommand("atm").setExecutor(this);
	
	if (!bankAccountsFile.exists()) {
		try {
			bankAccountsFile.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	bankAccountsConfig = YamlConfiguration.loadConfiguration(bankAccountsFile);
	
	worths = Doubles.toArray(Main.finalconfig.getDoubleList("atm_worth_gradation"));
}
 
Example #12
Source File: IntensityPlotDataset.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
public Number getMeanValue(int row, int column) {
  Feature[] peaks = getPeaks(xValues[column], selectedRows[row]);
  HashSet<Double> values = new HashSet<Double>();
  for (int i = 0; i < peaks.length; i++) {
    if (peaks[i] == null)
      continue;
    if (yAxisValueSource == YAxisValueSource.HEIGHT)
      values.add(peaks[i].getHeight());
    if (yAxisValueSource == YAxisValueSource.AREA)
      values.add(peaks[i].getArea());
    if (yAxisValueSource == YAxisValueSource.RT)
      values.add(peaks[i].getRT());
  }
  double doubleValues[] = Doubles.toArray(values);
  if (doubleValues.length == 0)
    return 0;
  double mean = MathUtils.calcAvg(doubleValues);
  return mean;
}
 
Example #13
Source File: SliceSamplerUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Tests slice sampling of a peaked beta distribution as an example of sampling of a bounded random variable.
 * Checks that input mean and variance are recovered by 10000 samples to a relative error of 0.5% and 2%,
 * respectively.
 */
@Test
public void testSliceSamplingOfPeakedBetaDistribution() {
    rng.setSeed(RANDOM_SEED);

    final double alpha = 10.;
    final double beta = 4.;
    final BetaDistribution betaDistribution = new BetaDistribution(alpha, beta);
    final Function<Double, Double> betaLogPDF = betaDistribution::logDensity;
    final double mean = betaDistribution.getNumericalMean();
    final double variance = betaDistribution.getNumericalVariance();

    final double xInitial = 0.5;
    final double xMin = 0.;
    final double xMax = 1.;
    final double width = 0.1;
    final int numSamples = 10000;
    final SliceSampler betaSampler = new SliceSampler(rng, betaLogPDF, xMin, xMax, width);
    final double[] samples = Doubles.toArray(betaSampler.sample(xInitial, numSamples));

    final double sampleMean = new Mean().evaluate(samples);
    final double sampleVariance = new Variance().evaluate(samples);
    Assert.assertEquals(relativeError(sampleMean, mean), 0., 0.005);
    Assert.assertEquals(relativeError(sampleVariance, variance), 0., 0.02);
}
 
Example #14
Source File: LocalVerCodeParseServiceImpl.java    From baidu-chain-dog with GNU General Public License v3.0 6 votes vote down vote up
private StringBuilder doPredict(List<String> svmTest) {
    StringBuilder result = new StringBuilder();
    for(String line : svmTest) {
        StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
        Double target = Doubles.tryParse(st.nextToken());
        Preconditions.checkNotNull(target);
        int m = st.countTokens() / 2;
        svm_node[] x = new svm_node[m];
        for (int j = 0; j < m; j++) {
            x[j] = new svm_node();
            Integer index = Ints.tryParse(st.nextToken());
            Double value = Doubles.tryParse(st.nextToken());
            Preconditions.checkNotNull(index);
            Preconditions.checkNotNull(value);
            x[j].index = index;
            x[j].value = value;
        }

        double v = svm.svm_predict(model, x);
        result.append(labels.get((int)v));

    }
    return result;
}
 
Example #15
Source File: PosteriorSummaryUtils.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Given a list of posterior samples, returns an estimate of the posterior mode (using
 * mllib kernel density estimation in {@link KernelDensity} and {@link BrentOptimizer}).
 * Note that estimate may be poor if number of samples is small (resulting in poor kernel density estimation),
 * or if posterior is not unimodal (or is sufficiently pathological otherwise). If the samples contain
 * {@link Double#NaN}, {@link Double#NaN} will be returned.
 * @param samples   posterior samples, cannot be {@code null} and number of samples must be greater than 0
 * @param ctx       {@link JavaSparkContext} used by {@link KernelDensity} for mllib kernel density estimation
 */
public static double calculatePosteriorMode(final List<Double> samples, final JavaSparkContext ctx) {
    Utils.nonNull(samples);
    Utils.validateArg(samples.size() > 0, "Number of samples must be greater than zero.");

    //calculate sample min, max, mean, and standard deviation
    final double sampleMin = Collections.min(samples);
    final double sampleMax = Collections.max(samples);
    final double sampleMean = new Mean().evaluate(Doubles.toArray(samples));
    final double sampleStandardDeviation = new StandardDeviation().evaluate(Doubles.toArray(samples));

    //if samples are all the same or contain NaN, can simply return mean
    if (sampleStandardDeviation == 0. || Double.isNaN(sampleMean)) {
        return sampleMean;
    }

    //use Silverman's rule to set bandwidth for kernel density estimation from sample standard deviation
    //see https://en.wikipedia.org/wiki/Kernel_density_estimation#Practical_estimation_of_the_bandwidth
    final double bandwidth =
            SILVERMANS_RULE_CONSTANT * sampleStandardDeviation * Math.pow(samples.size(), SILVERMANS_RULE_EXPONENT);

    //use kernel density estimation to approximate posterior from samples
    final KernelDensity pdf = new KernelDensity().setSample(ctx.parallelize(samples, 1)).setBandwidth(bandwidth);

    //use Brent optimization to find mode (i.e., maximum) of kernel-density-estimated posterior
    final BrentOptimizer optimizer =
            new BrentOptimizer(RELATIVE_TOLERANCE, RELATIVE_TOLERANCE * (sampleMax - sampleMin));
    final UnivariateObjectiveFunction objective =
            new UnivariateObjectiveFunction(f -> pdf.estimate(new double[] {f})[0]);
    //search for mode within sample range, start near sample mean
    final SearchInterval searchInterval = new SearchInterval(sampleMin, sampleMax, sampleMean);
    return optimizer.optimize(objective, GoalType.MAXIMIZE, searchInterval, BRENT_MAX_EVAL).getPoint();
}
 
Example #16
Source File: MutableDistribution.java    From java-monitoring-client-library with Apache License 2.0 6 votes vote down vote up
/** Constructs an empty Distribution with the specified {@link DistributionFitter}. */
public MutableDistribution(DistributionFitter distributionFitter) {
  this.distributionFitter = checkNotNull(distributionFitter);
  ImmutableSortedSet<Double> boundaries = distributionFitter.boundaries();

  checkArgument(boundaries.size() > 0);
  checkArgument(Ordering.natural().isOrdered(boundaries));

  this.intervalCounts = TreeRangeMap.create();

  double[] boundariesArray = Doubles.toArray(distributionFitter.boundaries());

  // Add underflow and overflow intervals
  this.intervalCounts.put(Range.lessThan(boundariesArray[0]), 0L);
  this.intervalCounts.put(Range.atLeast(boundariesArray[boundariesArray.length - 1]), 0L);

  // Add finite intervals
  for (int i = 1; i < boundariesArray.length; i++) {
    this.intervalCounts.put(Range.closedOpen(boundariesArray[i - 1], boundariesArray[i]), 0L);
  }
}
 
Example #17
Source File: TimeSeries.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
void parseToken(int i, String token) {
    if (dataTypes[i - 2] == null) {
        // test double parsing, in case of error we consider it a string time series
        if (Doubles.tryParse(token) != null) {
            dataTypes[i - 2] = TimeSeriesDataType.DOUBLE;
            TDoubleArrayList doubleValues = createDoubleValues();
            doubleValues.add(parseDouble(token));
            values[i - 2] = doubleValues;
        } else {
            dataTypes[i - 2] = TimeSeriesDataType.STRING;
            List<String> stringValues = createStringValues();
            stringValues.add(checkString(token));
            values[i - 2] = stringValues;
        }
    } else {
        if (dataTypes[i - 2] == TimeSeriesDataType.DOUBLE) {
            ((TDoubleArrayList) values[i - 2]).add(parseDouble(token));
        } else if (dataTypes[i - 2] == TimeSeriesDataType.STRING) {
            ((List<String>) values[i - 2]).add(checkString(token));
        } else {
            throw assertDataType(dataTypes[i - 2]);
        }
    }
}
 
Example #18
Source File: ArithmeticQueryIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testSumDouble() throws Exception {
    initSumDoubleValues(null, getUrl());
    String query = "SELECT SUM(d) FROM SumDoubleTest";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertTrue(Doubles.compare(rs.getDouble(1), 0.015)==0);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example #19
Source File: SegmentMergeUtils.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Given a segment specified by an index, returns a pair of scores for adjacent segments based on the
 * Hodges-Lehmann estimators between the observed target coverages; except for edge cases,
 * the sum of the scores will be unity. All segments are assumed to be on the same chromosome.
 * If any of the three segments is missing targets, both scores are Double.NEGATIVE_INFINITY.
 * @param segments  list of segments
 * @param targets   target-coverage data to be segmented
 * @param index     index of the center segment to consider
 * @return          scores for adjacent segments based on Hodges-Lehmann estimators
 */
private static Pair<Double, Double> calculateTargetScores(final List<SimpleInterval> segments,
                                                          final TargetCollection<ReadCountRecord.SingleSampleRecord> targets,
                                                          final int index) {
    final SimpleInterval leftSegment = segments.get(index - 1);
    final SimpleInterval centerSegment = segments.get(index);
    final SimpleInterval rightSegment = segments.get(index + 1);

    //check if any segment is missing targets
    if (targets.targetCount(leftSegment) == 0 || targets.targetCount(centerSegment) == 0 ||
            targets.targetCount(rightSegment) == 0) {
        return Pair.of(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
    }

    final double[] leftCoverages = Doubles.toArray(makeCoverageList(leftSegment, targets));
    final double[] centerCoverages = Doubles.toArray(makeCoverageList(centerSegment, targets));
    final double[] rightCoverages = Doubles.toArray(makeCoverageList(rightSegment, targets));

    return calculateHodgesLehmannScores(leftCoverages, centerCoverages, rightCoverages);
}
 
Example #20
Source File: NotQueryIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotInListOfDouble() throws Exception {
    String query = "SELECT a_double FROM " + tableName + " WHERE organization_id=? and a_double NOT IN (?,?,?,?,?,?)";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        statement.setDouble(2, 0.0001);
        statement.setDouble(3, 0.0002);
        statement.setDouble(4, 0.0003);
        statement.setDouble(5, 0.0004);
        statement.setDouble(6, 0.0005);
        statement.setDouble(7, 0.0006);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertTrue(Doubles.compare(rs.getDouble(1), 0.0007)==0);
        assertTrue (rs.next());
        assertTrue(Doubles.compare(rs.getDouble(1), 0.0008)==0);
        assertTrue (rs.next());
        assertTrue(Doubles.compare(rs.getDouble(1), 0.0009)==0);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example #21
Source File: GraphAnalyses.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
static void boxPlot(Map<String, List<Double>> systemToScores, GnuPlotRenderer renderer,
    String title, String yAxisLabel, File outputFile) throws IOException {
  final BoxPlot.Whiskers whiskers = BoxPlot.Whiskers.builder()
      .setExtentMode(BoxPlot.Whiskers.Fraction.of(0.95)).build();

  final Axis yAxis =
      Axis.yAxis().setLabel(yAxisLabel).setRange(Range.closed(0.0, 60.0)).build();
  final BoxPlot.Builder plot = BoxPlot.builder().hideKey()
      .setTitle(title)
      .setXAxis(X_AXIS)
      .setYAxis(yAxis)
      .setGrid(GRID)
      .setWhiskers(whiskers);
  for (final Map.Entry<String, List<Double>> entry : systemToScores.entrySet()) {
    plot.addDataset(
        BoxPlot.Dataset.createCopyingData(entry.getKey(), Doubles.toArray(entry.getValue())));
  }
  renderer.renderTo(plot.build(), outputFile);
}
 
Example #22
Source File: NotQueryIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotEqualsByUnsignedDouble() throws Exception {
    String query = "SELECT a_unsigned_double -- and here comment\n" + 
    "FROM aTable WHERE organization_id=? and a_unsigned_double != 0.0001d and a_unsigned_double <= 0.0002d";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 2
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertTrue(Doubles.compare(rs.getDouble(1), 0.0002) == 0);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example #23
Source File: FunctionProperties.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * This method converts this FunctionProperties instance to FlatBuffers representation
 * @param bufferBuilder
 * @return
 */
public int asFlatProperties(FlatBufferBuilder bufferBuilder) {
    int iname = bufferBuilder.createString(name);
    int ii = FlatProperties.createIVector(bufferBuilder, Ints.toArray(i));
    int il = FlatProperties.createLVector(bufferBuilder, Longs.toArray(l));
    int id = FlatProperties.createDVector(bufferBuilder, Doubles.toArray(d));

    int arrays[] = new int[a.size()];
    int cnt = 0;
    for (val array: a) {
        int off = array.toFlatArray(bufferBuilder);
        arrays[cnt++] = off;
    }

    int ia = FlatProperties.createAVector(bufferBuilder, arrays);

    return FlatProperties.createFlatProperties(bufferBuilder, iname, ii, il, id, ia);
}
 
Example #24
Source File: GeneralizedLeastSquare.java    From Strata with Apache License 2.0 6 votes vote down vote up
/**
 * Generalised least square with penalty on (higher-order) finite differences of weights.
 * @param <T> The type of the independent variables (e.g. Double, double[], DoubleArray etc)
 * @param x independent variables
 * @param y dependent (scalar) variables
 * @param sigma (Gaussian) measurement error on dependent variables
 * @param basisFunctions set of basis functions - the fitting function is formed by these basis functions times a set of weights
 * @param lambda strength of penalty function
 * @param differenceOrder difference order between weights used in penalty function
 * @return the results of the least square
 */
public <T> GeneralizedLeastSquareResults<T> solve(
    T[] x, double[] y, double[] sigma, List<Function<T, Double>> basisFunctions,
    double lambda, int differenceOrder) {
  ArgChecker.notNull(x, "x null");
  ArgChecker.notNull(y, "y null");
  ArgChecker.notNull(sigma, "sigma null");
  ArgChecker.notEmpty(basisFunctions, "empty basisFunctions");
  int n = x.length;
  ArgChecker.isTrue(n > 0, "no data");
  ArgChecker.isTrue(y.length == n, "y wrong length");
  ArgChecker.isTrue(sigma.length == n, "sigma wrong length");

  ArgChecker.isTrue(lambda >= 0.0, "negative lambda");
  ArgChecker.isTrue(differenceOrder >= 0, "difference order");

  List<T> lx = Lists.newArrayList(x);
  List<Double> ly = Lists.newArrayList(Doubles.asList(y));
  List<Double> lsigma = Lists.newArrayList(Doubles.asList(sigma));

  return solveImp(lx, ly, lsigma, basisFunctions, lambda, differenceOrder);
}
 
Example #25
Source File: ConvertCollectionToArray.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void convert_collection_of_objects_to_primitive_array_with_guava () {
	
	List<Double> searchEngineMarketShare = Lists.newArrayList();
	searchEngineMarketShare.add(67.1);
	searchEngineMarketShare.add(16.9);
	searchEngineMarketShare.add(11.8);
	searchEngineMarketShare.add(2.7);
	searchEngineMarketShare.add(1.6);

	double[] searchEngineMarketShareArray = Doubles.toArray(searchEngineMarketShare);
	
	logger.info(Arrays.toString(searchEngineMarketShareArray));
	
	assertEquals(5, searchEngineMarketShareArray.length);
	
}
 
Example #26
Source File: ProperHeadMatchSieve.java    From baleen with Apache License 2.0 5 votes vote down vote up
private List<Double> extractNumbers(String text) {
  final List<Double> list = new LinkedList<>();
  final Matcher matcher = NUMBER.matcher(text);
  while (matcher.find()) {
    final Double d = Doubles.tryParse(matcher.group().replaceAll(",", ""));
    if (d != null) {
      list.add(d);
    }
  }
  return list;
}
 
Example #27
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 #28
Source File: CopyRatioSegmentedData.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
CopyRatioState.SegmentMeans estimateSegmentMeans() {
    final List<Double> means = IntStream.range(0, segments.size()).boxed()
            .map(s -> new Mean().evaluate(Doubles.toArray(
                    getIndexedCopyRatiosInSegment(s).stream()
                            .map(IndexedCopyRatio::getLog2CopyRatioValue)
                            .collect(Collectors.toList()))))
            .collect(Collectors.toList());
    return new CopyRatioState.SegmentMeans(means);
}
 
Example #29
Source File: BaseSparseNDArrayCOO.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * Return a copy of the values included in the array.
 * /!\ Change this DataBuffer won't change the ndarray!
 * @return an array containing the values
 * */
public DataBuffer getIncludedValues() {
    List<Double> val = new ArrayList<>();

    for (int i = 0; i < values.length(); i++) {
        boolean isIn = true;
        int idxNotFixed = 0;
        int[] idx = getUnderlyingIndicesOf(i).asInt();
        for (int dim = 0; dim < idx.length; dim++) {
            if (flags()[dim] == 1) {
                if (sparseOffsets()[dim] != idx[dim]) {
                    isIn = false;
                    break;
                }
            } else {
                int lowerBound = sparseOffsets()[dim];
                long upperBound = sparseOffsets()[dim] + shape()[idxNotFixed];
                if (!(idx[dim] >= lowerBound && idx[dim] < upperBound)) {
                    isIn = false;
                    break;
                }
                idxNotFixed++;
            }
        }
        if (isIn) {
            val.add(values.getDouble(i));
        }
    }
    return Nd4j.createBuffer(Doubles.toArray(val));
}
 
Example #30
Source File: BaseNewtonVectorRootFinder.java    From Strata with Apache License 2.0 5 votes vote down vote up
private boolean getNextPosition(
    Function<DoubleArray, DoubleArray> function,
    DoubleMatrix estimate,
    DataBundle data) {

  DoubleArray p = _directionFunction.getDirection(estimate, data.getY());
  if (data.getLambda0() < 1.0) {
    data.setLambda0(1.0);
  } else {
    data.setLambda0(data.getLambda0() * BETA);
  }
  updatePosition(p, function, data);
  double g1 = data.getG1();
  if (!Doubles.isFinite(g1)) {
    bisectBacktrack(p, function, data);
  }
  if (data.getG1() > data.getG0() / (1 + ALPHA * data.getLambda0())) {
    quadraticBacktrack(p, function, data);
    int count = 0;
    while (data.getG1() > data.getG0() / (1 + ALPHA * data.getLambda0())) {
      if (count > 5) {
        return false;
      }
      cubicBacktrack(p, function, data);
      count++;
    }
  }
  DoubleArray deltaX = data.getDeltaX();
  DoubleArray deltaY = data.getDeltaY();
  data.setG0(data.getG1());
  data.setX((DoubleArray) _algebra.add(data.getX(), deltaX));
  data.setY((DoubleArray) _algebra.add(data.getY(), deltaY));
  return true;
}