Java Code Examples for org.apache.commons.math3.util.Pair

The following examples show how to use org.apache.commons.math3.util.Pair. These examples are extracted from open source projects. 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
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function enumeration.
 *
 * @param rng random number generator.
 * @param singletons array of random variable values.
 * @param probabilities array of probabilities.
 * @throws DimensionMismatchException if
 * {@code singletons.length != probabilities.length}
 * @throws NotPositiveException if any of the probabilities are negative.
 * @throws NotFiniteNumberException if any of the probabilities are infinite.
 * @throws NotANumberException if any of the probabilities are NaN.
 * @throws MathArithmeticException all of the probabilities are 0.
 */
public EnumeratedRealDistribution(final RandomGenerator rng,
                                final double[] singletons, final double[] probabilities)
    throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
           NotFiniteNumberException, NotANumberException {
    super(rng);
    if (singletons.length != probabilities.length) {
        throw new DimensionMismatchException(probabilities.length, singletons.length);
    }

    List<Pair<Double, Double>> samples = new ArrayList<Pair<Double, Double>>(singletons.length);

    for (int i = 0; i < singletons.length; i++) {
        samples.add(new Pair<Double, Double>(singletons[i], probabilities[i]));
    }

    innerDistribution = new EnumeratedDistribution<Double>(rng, samples);
}
 
Example 2
@Test
public void testNonUnitWeightSum() {
    final double[] weights = { 1, 2 };
    final double[][] means = { { -1.5, 2.0 },
                               { 4.0, 8.2 } };
    final double[][][] covariances = { { { 2.0, -1.1 },
                                         { -1.1, 2.0 } },
                                       { { 3.5, 1.5 },
                                         { 1.5, 3.5 } } };
    final MultivariateNormalMixtureModelDistribution d
        = create(weights, means, covariances);

    final List<Pair<Double, MultivariateNormalDistribution>> comp = d.getComponents();

    Assert.assertEquals(1d / 3, comp.get(0).getFirst().doubleValue(), Math.ulp(1d));
    Assert.assertEquals(2d / 3, comp.get(1).getFirst().doubleValue(), Math.ulp(1d));
}
 
Example 3
Source Project: coming   Source File: Cardumen_00229_t.java    License: MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example 4
@Test
public void testNonUnitWeightSum() {
    final double[] weights = { 1, 2 };
    final double[][] means = { { -1.5, 2.0 },
                               { 4.0, 8.2 } };
    final double[][][] covariances = { { { 2.0, -1.1 },
                                         { -1.1, 2.0 } },
                                       { { 3.5, 1.5 },
                                         { 1.5, 3.5 } } };
    final MultivariateNormalMixtureModelDistribution d
        = create(weights, means, covariances);

    final List<Pair<Double, MultivariateNormalDistribution>> comp = d.getComponents();

    Assert.assertEquals(1d / 3, comp.get(0).getFirst(), Math.ulp(1d));
    Assert.assertEquals(2d / 3, comp.get(1).getFirst(), Math.ulp(1d));
}
 
Example 5
/**
 * {@inheritDoc}
 */
@Override
public double inverseCumulativeProbability(final double p) throws OutOfRangeException {
    if (p < 0.0 || p > 1.0) {
        throw new OutOfRangeException(p, 0, 1);
    }

    double probability = 0;
    double x = getSupportLowerBound();
    for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
        if (sample.getValue() == 0.0) {
            continue;
        }

        probability += sample.getValue();
        x = sample.getKey();

        if (probability >= p) {
            break;
        }
    }

    return x;
}
 
Example 6
Source Project: astor   Source File: MapUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Finds the two neurons that best match the given features.
 *
 * @param features Data.
 * @param neurons List of neurons to scan. If the list is empty
 * {@code null} will be returned.
 * @param distance Distance function. The neuron's features are
 * passed as the first argument to {@link DistanceMeasure#compute(double[],double[])}.
 * @return the two neurons whose features are closest to the given data.
 * @throws org.apache.commons.math3.exception.DimensionMismatchException
 * if the size of the input is not compatible with the neurons features
 * size.
 */
public static Pair<Neuron, Neuron> findBestAndSecondBest(double[] features,
                                                         Iterable<Neuron> neurons,
                                                         DistanceMeasure distance) {
    Neuron[] best = { null, null };
    double[] min = { Double.POSITIVE_INFINITY,
                     Double.POSITIVE_INFINITY };
    for (final Neuron n : neurons) {
        final double d = distance.compute(n.getFeatures(), features);
        if (d < min[0]) {
            // Replace second best with old best.
            min[1] = min[0];
            best[1] = best[0];

            // Store current as new best.
            min[0] = d;
            best[0] = n;
        } else if (d < min[1]) {
            // Replace old second best with current.
            min[1] = d;
            best[1] = n;
        }
    }

    return new Pair<Neuron, Neuron>(best[0], best[1]);
}
 
Example 7
Source Project: coming   Source File: Cardumen_00127_t.java    License: MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example 8
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param singletons array of random variable values.
 * @param probabilities array of probabilities.
 * @throws DimensionMismatchException if
 * {@code singletons.length != probabilities.length}
 * @throws NotPositiveException if any of the probabilities are negative.
 * @throws NotFiniteNumberException if any of the probabilities are infinite.
 * @throws NotANumberException if any of the probabilities are NaN.
 * @throws MathArithmeticException all of the probabilities are 0.
 */
public EnumeratedIntegerDistribution(final RandomGenerator rng,
                                   final int[] singletons, final double[] probabilities)
    throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
            NotFiniteNumberException, NotANumberException {
    super(rng);
    if (singletons.length != probabilities.length) {
        throw new DimensionMismatchException(probabilities.length, singletons.length);
    }

    final List<Pair<Integer, Double>> samples = new ArrayList<Pair<Integer, Double>>(singletons.length);

    for (int i = 0; i < singletons.length; i++) {
        samples.add(new Pair<Integer, Double>(singletons[i], probabilities[i]));
    }

    innerDistribution = new EnumeratedDistribution<Integer>(rng, samples);
}
 
Example 9
Source Project: astor   Source File: BaseRuleFactoryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected Pair<Double[], Double[]> computeRule(int order) {
    // Tracks whether this computation has been called more than once.
    nCalls.getAndIncrement();

    try {
        // Sleep to simulate computation time.
        Thread.sleep(20);
    } catch (InterruptedException e) {
        Assert.fail("Unexpected interruption");
    }

     // Dummy rule (but contents must exist).
    final Double[] p = new Double[order];
    final Double[] w = new Double[order];
    for (int i = 0; i < order; i++) {
        p[i] = new Double(i);
        w[i] = new Double(i);
    }
    return new Pair<Double[], Double[]>(p, w);
}
 
Example 10
Source Project: cf4j   Source File: ColumnPlot.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected String[][] getDataContent(String xAxisTicksFormat, String yAxisTicksFormat) {
  DecimalFormat ydf = new DecimalFormat(yAxisTicksFormat, new DecimalFormatSymbols(Locale.US));

  String[][] content = new String[this.columns.size()][2];

  for (int i = 0; i < this.columns.size(); i++) {
    Pair<String, Double> column = this.columns.get(i);

    String name = column.getKey();
    content[i][0] = name;

    double value = column.getValue();
    content[i][1] = ydf.format(value);
  }

  return content;
}
 
Example 11
Source Project: coming   Source File: JGenProg2017_0035_t.java    License: MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example 12
Source Project: astor   Source File: BaseRuleFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets a copy of the quadrature rule with given number of integration points.
 *
 * @param numberOfPoints Number of integration points.
 * @return a copy of the integration rule.
 */
public Pair<double[], double[]> getRule(int numberOfPoints) {
    // Try to obtain the rule from the cache.
    Pair<double[], double[]> cached = pointsAndWeightsDouble.get(numberOfPoints);

    if (cached == null) {
        // Rule not computed yet.

        // Compute the rule.
        final Pair<T[], T[]> rule = getRuleInternal(numberOfPoints);
        cached = convertToDouble(rule);

        // Cache it.
        pointsAndWeightsDouble.put(numberOfPoints, cached);
    }

    // Return a copy.
    return new Pair<double[], double[]>(cached.getFirst().clone(),
                                        cached.getSecond().clone());
}
 
Example 13
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function enumeration.
 *
 * @param rng random number generator.
 * @param singletons array of random variable values.
 * @param probabilities array of probabilities.
 * @throws DimensionMismatchException if
 * {@code singletons.length != probabilities.length}
 * @throws NotPositiveException if any of the probabilities are negative.
 * @throws NotFiniteNumberException if any of the probabilities are infinite.
 * @throws NotANumberException if any of the probabilities are NaN.
 * @throws MathArithmeticException all of the probabilities are 0.
 */
public EnumeratedRealDistribution(final RandomGenerator rng,
                                final double[] singletons, final double[] probabilities)
    throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
           NotFiniteNumberException, NotANumberException {
    super(rng);
    if (singletons.length != probabilities.length) {
        throw new DimensionMismatchException(probabilities.length, singletons.length);
    }

    List<Pair<Double, Double>> samples = new ArrayList<Pair<Double, Double>>(singletons.length);

    for (int i = 0; i < singletons.length; i++) {
        samples.add(new Pair<Double, Double>(singletons[i], probabilities[i]));
    }

    innerDistribution = new EnumeratedDistribution<Double>(rng, samples);
}
 
Example 14
Source Project: astor   Source File: BaseRuleFactoryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected Pair<Double[], Double[]> computeRule(int order) {
    // Tracks whether this computation has been called more than once.
    nCalls.getAndIncrement();

    try {
        // Sleep to simulate computation time.
        Thread.sleep(20);
    } catch (InterruptedException e) {
        Assert.fail("Unexpected interruption");
    }

     // Dummy rule (but contents must exist).
    final Double[] p = new Double[order];
    final Double[] w = new Double[order];
    for (int i = 0; i < order; i++) {
        p[i] = new Double(i);
        w[i] = new Double(i);
    }
    return new Pair<Double[], Double[]>(p, w);
}
 
Example 15
Source Project: coming   Source File: Arja_00127_t.java    License: MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example 16
Source Project: astor   Source File: BaseRuleFactoryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests that a given rule rule will be computed and added once to the cache
 * whatever the number of times this rule is called concurrently.
 */
@Test
    public void testConcurrentCreation() throws InterruptedException,
                                                ExecutionException {
    // Number of times the same rule will be called.
    final int numTasks = 20;

    final ThreadPoolExecutor exec
        = new ThreadPoolExecutor(3, numTasks, 1, TimeUnit.SECONDS,
                                 new ArrayBlockingQueue<Runnable>(2));

    final List<Future<Pair<double[], double[]>>> results
        = new ArrayList<Future<Pair<double[], double[]>>>();
    for (int i = 0; i < numTasks; i++) {
        results.add(exec.submit(new RuleBuilder()));
    }

    // Ensure that all computations have completed.
    for (Future<Pair<double[], double[]>> f : results) {
        f.get();
    }

    // Assertion would fail if "getRuleInternal" were not "synchronized".
    final int n = RuleBuilder.getNumberOfCalls();
    Assert.assertEquals("Rule computation was called " + n + " times", 1, n);
}
 
Example 17
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example 18
Source Project: coming   Source File: Math_8_DiscreteDistribution_t.java    License: MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example 19
Source Project: coming   Source File: Arja_0045_t.java    License: MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example 20
@NotNull
static Pair<Integer, String> relativePositionAndRef(@NotNull final IndexedFastaSequenceFile reference, @NotNull final VariantContext variant) {
    final int refLength = variant.getReference().getBaseString().length();
    @Nullable
    final SAMSequenceRecord samSequenceRecord = reference.getSequenceDictionary().getSequence(variant.getContig());
    if (samSequenceRecord == null) {
        LOGGER.warn("Unable to locate contig {} in ref genome", variant.getContig());
        return new Pair<>(-1, Strings.EMPTY);
    }

    final int chromosomeLength = samSequenceRecord.getSequenceLength();
    long positionBeforeEvent = variant.getStart();

    long start = Math.max(positionBeforeEvent - 100, 1);
    long end = Math.min(positionBeforeEvent + refLength + 100 - 1, chromosomeLength - 1);
    int relativePosition = (int) (positionBeforeEvent - start);
    final String sequence;
    if (start < chromosomeLength && end < chromosomeLength) {
        sequence = reference.getSubsequenceAt(variant.getContig(), start, end).getBaseString();
    } else {
        sequence = Strings.EMPTY;
        LOGGER.warn("Requested base sequence outside of chromosome region!");
    }
    return new Pair<>(relativePosition, sequence);
}
 
Example 21
static Pair<List<ColumnMeta>, List<Operator>> gen(
        GeneratorContext ctx, 
        Planner planner, 
        TableMeta table,  
        List<Update_stmt_setContext> rules) {
    List<ColumnMeta> columns = new ArrayList<ColumnMeta>();
    List<Operator> exprs = new ArrayList<Operator>();
    for (Update_stmt_setContext i:rules) {
        String columnName = Utils.getIdentifier(i.column_name().identifier());
        ColumnMeta column = table.getColumn(columnName);
        if (column == null) {
            throw new OrcaException("column is not found: " + columnName);
        }
        Operator op = ExprGenerator.gen(ctx, planner, i.expr());
        if (!column.isNullable()) {
            op = new NotNullCheck(op, column);
        }
        columns.add(column);
        exprs.add(op);
    }
    return new Pair<>(columns, exprs);
}
 
Example 22
Source Project: coming   Source File: Cardumen_00179_s.java    License: MIT License 6 votes vote down vote up
/**
 * Create a discrete distribution using the given random number generator
 * and probability mass function definition.
 *
 * @param rng random number generator.
 * @param samples definition of probability mass function in the format of
 * list of pairs.
 * @throws NotPositiveException if probability of at least one value is
 * negative.
 * @throws MathArithmeticException if the probabilities sum to zero.
 * @throws MathIllegalArgumentException if probability of at least one value
 * is infinite.
 */
public DiscreteDistribution(final RandomGenerator rng, final List<Pair<T, Double>> samples)
    throws NotPositiveException, MathArithmeticException, MathIllegalArgumentException {
    random = rng;

    singletons = new ArrayList<T>(samples.size());
    final double[] probs = new double[samples.size()];

    for (int i = 0; i < samples.size(); i++) {
        final Pair<T, Double> sample = samples.get(i);
        singletons.add(sample.getKey());
        if (sample.getValue() < 0) {
            throw new NotPositiveException(sample.getValue());
        }
        probs[i] = sample.getValue();
    }

    probabilities = MathArrays.normalizeArray(probs, 1.0);
}
 
Example 23
Source Project: astor   Source File: BaseRuleFactoryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests that a given rule rule will be computed and added once to the cache
 * whatever the number of times this rule is called concurrently.
 */
@Test
    public void testConcurrentCreation() throws InterruptedException,
                                                ExecutionException {
    // Number of times the same rule will be called.
    final int numTasks = 20;

    final ThreadPoolExecutor exec
        = new ThreadPoolExecutor(3, numTasks, 1, TimeUnit.SECONDS,
                                 new ArrayBlockingQueue<Runnable>(2));

    final List<Future<Pair<double[], double[]>>> results
        = new ArrayList<Future<Pair<double[], double[]>>>();
    for (int i = 0; i < numTasks; i++) {
        results.add(exec.submit(new RuleBuilder()));
    }

    // Ensure that all computations have completed.
    for (Future<Pair<double[], double[]>> f : results) {
        f.get();
    }

    // Assertion would fail if "getRuleInternal" were not "synchronized".
    final int n = RuleBuilder.getNumberOfCalls();
    Assert.assertEquals("Rule computation was called " + n + " times", 1, n);
}
 
Example 24
Source Project: coming   Source File: Arja_0045_t.java    License: MIT License 5 votes vote down vote up
/**
 * Return the definition of probability mass function in the format of list
 * of pairs.
 *
 * @return definition of probability mass function.
 */
public List<Pair<T, Double>> getSamples() {
    final List<Pair<T, Double>> samples = new ArrayList<Pair<T, Double>>(probabilities.length);

    for (int i = 0; i < probabilities.length; i++) {
        samples.add(new Pair<T, Double>(singletons.get(i), probabilities[i]));
    }

    return samples;
}
 
Example 25
Source Project: astor   Source File: EvaluationTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testComputeValueAndJacobian() {
    //setup
    final RealVector point = new ArrayRealVector(new double[]{1, 2});
    Evaluation evaluation = new LeastSquaresBuilder()
            .weight(new DiagonalMatrix(new double[]{16, 4}))
            .model(new MultivariateJacobianFunction() {
                public Pair<RealVector, RealMatrix> value(RealVector actualPoint) {
                    //verify correct values passed in
                    Assert.assertArrayEquals(
                            point.toArray(), actualPoint.toArray(), Precision.EPSILON);
                    //return values
                    return new Pair<RealVector, RealMatrix>(
                            new ArrayRealVector(new double[]{3, 4}),
                            MatrixUtils.createRealMatrix(new double[][]{{5, 6}, {7, 8}})
                    );
                }
            })
            .target(new double[2])
            .build()
            .evaluate(point);

    //action
    RealVector residuals = evaluation.getResiduals();
    RealMatrix jacobian = evaluation.getJacobian();

    //verify
    Assert.assertArrayEquals(evaluation.getPoint().toArray(), point.toArray(), 0);
    Assert.assertArrayEquals(new double[]{-12, -8}, residuals.toArray(), Precision.EPSILON);
    TestUtils.assertEquals(
            "jacobian",
            jacobian,
            MatrixUtils.createRealMatrix(new double[][]{{20, 24},{14, 16}}),
            Precision.EPSILON);
}
 
Example 26
@Override
public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit)
    throws SchemaConversionException {
  Pair<Schema, List<AvroUtils.SchemaEntry>> results = AvroUtils.dropRecursiveFields(inputSchema);
  List<AvroUtils.SchemaEntry> recursiveFields = results.getSecond();
  if (!recursiveFields.isEmpty()) {
    log.warn("Schema {} is recursive. Will drop fields [{}]", inputSchema.getFullName(),
        recursiveFields.stream().map(entry -> entry.getFieldName()).collect(Collectors.joining(",")));
    log.debug("Projected Schema = {}", results.getFirst());
  }
  return results.getFirst();
}
 
Example 27
Source Project: coming   Source File: Cardumen_00179_t.java    License: MIT License 5 votes vote down vote up
/**
 * Return the definition of probability mass function in the format of list
 * of pairs.
 *
 * @return definition of probability mass function.
 */
public List<Pair<T, Double>> getSamples() {
    final List<Pair<T, Double>> samples = new ArrayList<Pair<T, Double>>(probabilities.length);

    for (int i = 0; i < probabilities.length; i++) {
        samples.add(new Pair<T, Double>(singletons.get(i), probabilities[i]));
    }

    return samples;
}
 
Example 28
@Test
public void testIssue942() {
    List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>();
    list.add(new Pair<Object, Double>(new Object() {}, new Double(0)));
    list.add(new Pair<Object, Double>(new Object() {}, new Double(1)));
    Assert.assertEquals(1, new EnumeratedDistribution<Object>(list).sample(1).length);
}
 
Example 29
Source Project: astor   Source File: GaussIntegratorTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGetPoints() {
    final double[] points = { 0, 1.2, 3.4 };
    final double[] weights = { 9.8, 7.6, 5.4 };

    final GaussIntegrator integrator
        = new GaussIntegrator(new Pair<double[], double[]>(points, weights));

    Assert.assertEquals(points.length, integrator.getNumberOfPoints());

    for (int i = 0; i < integrator.getNumberOfPoints(); i++) {
        Assert.assertEquals(points[i], integrator.getPoint(i), 0d);
    }
}
 
Example 30
Source Project: coming   Source File: Cardumen_0060_s.java    License: MIT License 5 votes vote down vote up
/**
 * Return the definition of probability mass function in the format of list
 * of pairs.
 *
 * @return definition of probability mass function.
 */
public List<Pair<T, Double>> getSamples() {
    final List<Pair<T, Double>> samples = new ArrayList<Pair<T, Double>>(probabilities.length);

    for (int i = 0; i < probabilities.length; i++) {
        samples.add(new Pair<T, Double>(singletons.get(i), probabilities[i]));
    }

    return samples;
}