Java Code Examples for org.apache.commons.math3.util.Pair#getSecond()

The following examples show how to use org.apache.commons.math3.util.Pair#getSecond() . 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: GaussIntegratorFactory.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs a change of variable so that the integration can be performed
 * on an arbitrary interval {@code [a, b]}.
 * It is assumed that the natural interval is {@code [-1, 1]}.
 *
 * @param rule Original points and weights.
 * @param a Lower bound of the integration interval.
 * @param b Lower bound of the integration interval.
 * @return the points and weights adapted to the new interval.
 */
private static Pair<double[], double[]> transform(Pair<double[], double[]> rule,
                                                  double a,
                                                  double b) {
    final double[] points = rule.getFirst();
    final double[] weights = rule.getSecond();

    // Scaling
    final double scale = (b - a) / 2;
    final double shift = a + scale;

    for (int i = 0; i < points.length; i++) {
        points[i] = points[i] * scale + shift;
        weights[i] *= scale;
    }

    return new Pair<double[], double[]>(points, weights);
}
 
Example 2
Source File: BaseRuleFactory.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Converts the from the actual {@code Number} type to {@code double}
 *
 * @param <T> Type of the number used to represent the points and
 * weights of the quadrature rules.
 * @param rule Points and weights.
 * @return points and weights as {@code double}s.
 */
private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule) {
    final T[] pT = rule.getFirst();
    final T[] wT = rule.getSecond();

    final int len = pT.length;
    final double[] pD = new double[len];
    final double[] wD = new double[len];

    for (int i = 0; i < len; i++) {
        pD[i] = pT[i].doubleValue();
        wD[i] = wT[i].doubleValue();
    }

    return new Pair<double[], double[]>(pD, wD);
}
 
Example 3
Source File: BaseRuleFactory.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Converts the from the actual {@code Number} type to {@code double}
 *
 * @param <T> Type of the number used to represent the points and
 * weights of the quadrature rules.
 * @param rule Points and weights.
 * @return points and weights as {@code double}s.
 */
private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule) {
    final T[] pT = rule.getFirst();
    final T[] wT = rule.getSecond();

    final int len = pT.length;
    final double[] pD = new double[len];
    final double[] wD = new double[len];

    for (int i = 0; i < len; i++) {
        pD[i] = pT[i].doubleValue();
        wD[i] = wT[i].doubleValue();
    }

    return new Pair<double[], double[]>(pD, wD);
}
 
Example 4
Source File: GaussIntegratorFactory.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs a change of variable so that the integration can be performed
 * on an arbitrary interval {@code [a, b]}.
 * It is assumed that the natural interval is {@code [-1, 1]}.
 *
 * @param rule Original points and weights.
 * @param a Lower bound of the integration interval.
 * @param b Lower bound of the integration interval.
 * @return the points and weights adapted to the new interval.
 */
private static Pair<double[], double[]> transform(Pair<double[], double[]> rule,
                                                  double a,
                                                  double b) {
    final double[] points = rule.getFirst();
    final double[] weights = rule.getSecond();

    // Scaling
    final double scale = (b - a) / 2;
    final double shift = a + scale;

    for (int i = 0; i < points.length; i++) {
        points[i] = points[i] * scale + shift;
        weights[i] *= scale;
    }

    return new Pair<double[], double[]>(points, weights);
}
 
Example 5
Source File: BaseRuleFactory.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Converts the from the actual {@code Number} type to {@code double}
 *
 * @param <T> Type of the number used to represent the points and
 * weights of the quadrature rules.
 * @param rule Points and weights.
 * @return points and weights as {@code double}s.
 */
private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule) {
    final T[] pT = rule.getFirst();
    final T[] wT = rule.getSecond();

    final int len = pT.length;
    final double[] pD = new double[len];
    final double[] wD = new double[len];

    for (int i = 0; i < len; i++) {
        pD[i] = pT[i].doubleValue();
        wD[i] = wT[i].doubleValue();
    }

    return new Pair<double[], double[]>(pD, wD);
}
 
Example 6
Source File: JsonTuples.java    From quarks with Apache License 2.0 6 votes vote down vote up
/**
     * Create a JsonObject wrapping a raw {@code Pair<Long msec,T reading>>} sample.
     * @param sample the raw sample
     * @param id the sensor's Id
     * @return the wrapped sample
     */
    public static <T> JsonObject wrap(Pair<Long,T> sample, String id) {
        JsonObject jo = new JsonObject();
        jo.addProperty(KEY_ID, id);
        jo.addProperty(KEY_TS, sample.getFirst());
        T value = sample.getSecond();
        if (value instanceof Number)
            jo.addProperty(KEY_READING, (Number)sample.getSecond());
        else if (value instanceof String)
            jo.addProperty(KEY_READING, (String)sample.getSecond());
        else if (value instanceof Boolean)
            jo.addProperty(KEY_READING, (Boolean)sample.getSecond());
//        else if (value instanceof array) {
//            // TODO cvt to JsonArray
//        }
//        else if (value instanceof Object) {
//            // TODO cvt to JsonObject
//        }
        else {
            Class<?> clazz = value != null ? value.getClass() : Object.class;
            throw new IllegalArgumentException("Unhandled value type: "+ clazz);
        }
        return jo;
    }
 
Example 7
Source File: BaseRuleFactory.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Converts the from the actual {@code Number} type to {@code double}
 *
 * @param <T> Type of the number used to represent the points and
 * weights of the quadrature rules.
 * @param rule Points and weights.
 * @return points and weights as {@code double}s.
 */
private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule) {
    final T[] pT = rule.getFirst();
    final T[] wT = rule.getSecond();

    final int len = pT.length;
    final double[] pD = new double[len];
    final double[] wD = new double[len];

    for (int i = 0; i < len; i++) {
        pD[i] = pT[i].doubleValue();
        wD[i] = wT[i].doubleValue();
    }

    return new Pair<double[], double[]>(pD, wD);
}
 
Example 8
Source File: BaseRuleFactory.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Stores a rule.
 *
 * @param rule Rule to be stored.
 * @throws DimensionMismatchException if the elements of the pair do not
 * have the same length.
 */
protected void addRule(Pair<T[], T[]> rule) throws DimensionMismatchException {
    if (rule.getFirst().length != rule.getSecond().length) {
        throw new DimensionMismatchException(rule.getFirst().length,
                                             rule.getSecond().length);
    }

    pointsAndWeights.put(rule.getFirst().length, rule);
}
 
Example 9
Source File: BaseRuleFactory.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Stores a rule.
 *
 * @param rule Rule to be stored.
 * @throws DimensionMismatchException if the elements of the pair do not
 * have the same length.
 */
protected void addRule(Pair<T[], T[]> rule) throws DimensionMismatchException {
    if (rule.getFirst().length != rule.getSecond().length) {
        throw new DimensionMismatchException(rule.getFirst().length,
                                             rule.getSecond().length);
    }

    pointsAndWeights.put(rule.getFirst().length, rule);
}
 
Example 10
Source File: CouchbaseWriter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private WriteResponse getWriteResponseOrThrow(Pair<WriteResponse, Throwable> writeResponseThrowablePair)
    throws ExecutionException {
  if (writeResponseThrowablePair.getFirst() != null) {
    return writeResponseThrowablePair.getFirst();
  } else if (writeResponseThrowablePair.getSecond() != null) {
    throw new ExecutionException(writeResponseThrowablePair.getSecond());
  } else {
    throw new ExecutionException(new RuntimeException("Could not find non-null WriteResponse pair"));
  }
}
 
Example 11
Source File: GobblinMultiTaskAttempt.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Run {@link #workUnits} assigned in this attempt.
 * @throws IOException
 * @throws InterruptedException
 */
public void run()
    throws IOException, InterruptedException {
  if (!this.workUnits.hasNext()) {
    log.warn("No work units to run in container " + containerIdOptional.or(""));
    return;
  }

  CountUpAndDownLatch countDownLatch = new CountUpAndDownLatch(0);
  Pair<List<Task>, Boolean> executionResult = runWorkUnits(countDownLatch);
  this.tasks = executionResult.getFirst();

  // Indicating task creation failure, propagating exception as it should be noticeable to job launcher
  if (!executionResult.getSecond()) {
    throw new TaskCreationException("Failing in creating task before execution.");
  }

  log.info("Waiting for submitted tasks of job {} to complete in container {}...", jobId, containerIdOptional.or(""));
  try {
    while (countDownLatch.getCount() > 0) {
      if (this.interruptionPredicate.test(this)) {
        log.info("Interrupting task execution due to satisfied predicate.");
        interruptTaskExecution(countDownLatch);
        break;
      }
      log.info(String.format("%d out of %d tasks of job %s are running in container %s", countDownLatch.getCount(),
          countDownLatch.getRegisteredParties(), jobId, containerIdOptional.or("")));
      if (countDownLatch.await(10, TimeUnit.SECONDS)) {
        break;
      }
    }
  } catch (InterruptedException interrupt) {
    log.info("Job interrupted by InterrupedException.");
    interruptTaskExecution(countDownLatch);
  }
  log.info("All assigned tasks of job {} have completed in container {}", jobId, containerIdOptional.or(""));
}
 
Example 12
Source File: SomaticRefContextEnrichment.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
private void addTrinucleotideContext(@NotNull final VariantContext variant,
        @NotNull final Pair<Integer, String> relativePositionAndRef) {
    final int relativePosition = relativePositionAndRef.getFirst();
    final String sequence = relativePositionAndRef.getSecond();
    if (!sequence.isEmpty()) {
        final String tri = sequence.substring(Math.max(0, relativePosition - 1), Math.min(sequence.length(), relativePosition + 2));
        variant.getCommonInfo().putAttribute(TRINUCLEOTIDE_FLAG, tri, true);
    }
}
 
Example 13
Source File: SomaticRefContextEnrichment.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
private void addRepeatContext(@NotNull final VariantContext variant, final Pair<Integer, String> relativePositionAndRef) {
    final int relativePosition = relativePositionAndRef.getFirst();
    final String sequence = relativePositionAndRef.getSecond();

    Optional<RepeatContext> repeatContext = getRepeatContext(variant, relativePosition, sequence);
    if (repeatContext.isPresent()) {

        variant.getCommonInfo().putAttribute(REPEAT_SEQUENCE_FLAG, repeatContext.get().sequence(), true);
        variant.getCommonInfo().putAttribute(REPEAT_COUNT_FLAG, repeatContext.get().count(), true);
    }
}
 
Example 14
Source File: MultivariateNormalMixtureExpectationMaximizationTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Ignore@Test
public void testFit() {
    // Test that the loglikelihood, weights, and models are determined and
    // fitted correctly
    double[][] data = getTestSamples();
    double correctLogLikelihood = -4.292431006791994;
    double[] correctWeights = new double[] { 0.2962324189652912, 0.7037675810347089 };
    MultivariateNormalDistribution[] correctMVNs = new MultivariateNormalDistribution[2];
    correctMVNs[0] = new MultivariateNormalDistribution(new double[] {
                    -1.4213112715121132, 1.6924690505757753 },
                    new double[][] {
                            { 1.739356907285747, -0.5867644251487614 },
                            { -0.5867644251487614, 1.0232932029324642 } });

    correctMVNs[1] = new MultivariateNormalDistribution(new double[] {
                    4.213612224374709, 7.975621325853645 },
                    new double[][] {
                            { 4.245384898007161, 2.5797798966382155 },
                            { 2.5797798966382155, 3.9200272522448367 } });

    MultivariateNormalMixtureExpectationMaximization fitter
        = new MultivariateNormalMixtureExpectationMaximization(data);

    MixtureMultivariateNormalDistribution initialMix
        = MultivariateNormalMixtureExpectationMaximization.estimate(data, 2);
    fitter.fit(initialMix);
    MixtureMultivariateNormalDistribution fittedMix = fitter.getFittedModel();
    List<Pair<Double, MultivariateNormalDistribution>> components = fittedMix.getComponents();

    Assert.assertEquals(correctLogLikelihood,
                        fitter.getLogLikelihood(),
                        Math.ulp(1d));

    int i = 0;
    for (Pair<Double, MultivariateNormalDistribution> component : components) {
        double weight = component.getFirst();
        MultivariateNormalDistribution mvn = component.getSecond();
        Assert.assertEquals(correctWeights[i], weight, Math.ulp(1d));
        Assert.assertEquals(correctMVNs[i], mvn);
        i++;
    }
}
 
Example 15
Source File: MultivariateNormalMixtureExpectationMaximizationTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testFit() {
    // Test that the loglikelihood, weights, and models are determined and
    // fitted correctly
    final double[][] data = getTestSamples();
    final double correctLogLikelihood = -4.292431006791994;
    final double[] correctWeights = new double[] { 0.2962324189652912, 0.7037675810347089 };
    
    final double[][] correctMeans = new double[][]{
        {-1.4213112715121132, 1.6924690505757753},
        {4.213612224374709, 7.975621325853645}
    };
    
    final RealMatrix[] correctCovMats = new Array2DRowRealMatrix[2];
    correctCovMats[0] = new Array2DRowRealMatrix(new double[][] {
        { 1.739356907285747, -0.5867644251487614 },
        { -0.5867644251487614, 1.0232932029324642 } }
            );
    correctCovMats[1] = new Array2DRowRealMatrix(new double[][] {
        { 4.245384898007161, 2.5797798966382155 },
        { 2.5797798966382155, 3.9200272522448367 } });
    
    final MultivariateNormalDistribution[] correctMVNs = new MultivariateNormalDistribution[2];
    correctMVNs[0] = new MultivariateNormalDistribution(correctMeans[0], correctCovMats[0].getData());
    correctMVNs[1] = new MultivariateNormalDistribution(correctMeans[1], correctCovMats[1].getData());

    MultivariateNormalMixtureExpectationMaximization fitter
        = new MultivariateNormalMixtureExpectationMaximization(data);

    MixtureMultivariateNormalDistribution initialMix
        = MultivariateNormalMixtureExpectationMaximization.estimate(data, 2);
    fitter.fit(initialMix);
    MixtureMultivariateNormalDistribution fittedMix = fitter.getFittedModel();
    List<Pair<Double, MultivariateNormalDistribution>> components = fittedMix.getComponents();

    Assert.assertEquals(correctLogLikelihood,
                        fitter.getLogLikelihood(),
                        Math.ulp(1d));

    int i = 0;
    for (Pair<Double, MultivariateNormalDistribution> component : components) {
        final double weight = component.getFirst();
        final MultivariateNormalDistribution mvn = component.getSecond();
        final double[] mean = mvn.getMeans();
        final RealMatrix covMat = mvn.getCovariances();
        Assert.assertEquals(correctWeights[i], weight, Math.ulp(1d));
        Assert.assertTrue(Arrays.equals(correctMeans[i], mean));
        Assert.assertEquals(correctCovMats[i], covMat);
        i++;
    }
}
 
Example 16
Source File: GaussNewtonOptimizer.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
@Override
protected RealVector solve(final RealMatrix jacobian,
                           final RealVector residuals) {
    try {
        final Pair<RealMatrix, RealVector> normalEquation =
                computeNormalMatrix(jacobian, residuals);
        final RealMatrix normal = normalEquation.getFirst();
        final RealVector jTr = normalEquation.getSecond();
        return new LUDecomposition(normal, SINGULARITY_THRESHOLD)
                .getSolver()
                .solve(jTr);
    } catch (SingularMatrixException e) {
        throw new ConvergenceException(LocalizedFormats.UNABLE_TO_SOLVE_SINGULAR_PROBLEM, e);
    }
}
 
Example 17
Source File: GaussIntegrator.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates an integrator from the given pair of points (first element of
 * the pair) and weights (second element of the pair.
 *
 * @param pointsAndWeights Integration points and corresponding weights.
 * @throws org.apache.commons.math3.exception.NonMonotonicSequenceException
 * if the {@code points} are not sorted in increasing order.
 *
 * @see #GaussIntegrator(double[], double[])
 */
public GaussIntegrator(Pair<double[], double[]> pointsAndWeights) {
    this(pointsAndWeights.getFirst(), pointsAndWeights.getSecond());
}
 
Example 18
Source File: SymmetricGaussIntegrator.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates an integrator from the given pair of points (first element of
 * the pair) and weights (second element of the pair.
 *
 * @param pointsAndWeights Integration points and corresponding weights.
 * @throws NonMonotonicSequenceException if the {@code points} are not
 * sorted in increasing order.
 *
 * @see #SymmetricGaussIntegrator(double[], double[])
 */
public SymmetricGaussIntegrator(Pair<double[], double[]> pointsAndWeights)
    throws NonMonotonicSequenceException {
    this(pointsAndWeights.getFirst(), pointsAndWeights.getSecond());
}
 
Example 19
Source File: GaussIntegrator.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates an integrator from the given pair of points (first element of
 * the pair) and weights (second element of the pair.
 *
 * @param pointsAndWeights Integration points and corresponding weights.
 * @throws NonMonotonicSequenceException if the {@code points} are not
 * sorted in increasing order.
 *
 * @see #GaussIntegrator(double[], double[])
 */
public GaussIntegrator(Pair<double[], double[]> pointsAndWeights)
    throws NonMonotonicSequenceException {
    this(pointsAndWeights.getFirst(), pointsAndWeights.getSecond());
}