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

The following examples show how to use org.apache.commons.math3.util.Pair#getFirst() . 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: 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 4
Source File: LeastSquaresFactory.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public Evaluation evaluate(final RealVector point) {
    // Copy so optimizer can change point without changing our instance.
    final RealVector p = paramValidator == null ?
        point.copy() :
        paramValidator.validate(point.copy());

    if (lazyEvaluation) {
        return new LazyUnweightedEvaluation((ValueAndJacobianFunction) model,
                                            target,
                                            p);
    } else {
        // Evaluate value and jacobian in one function call.
        final Pair<RealVector, RealMatrix> value = model.value(p);
        return new UnweightedEvaluation(value.getFirst(),
                                        value.getSecond(),
                                        target,
                                        p);
    }
}
 
Example 5
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 6
Source File: AbstractEvaluatorToPartitionStrategy.java    From reef with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the locations of the splits where we'd like to be loaded into.
 * Sets all the splits to unallocated
 *
 * @param splitsPerPartition
 *          a map containing the input splits per data partition
 */
private void init(final Map<DistributedDataSetPartition, InputSplit[]> splitsPerPartition) {
  final Pair<InputSplit[], DistributedDataSetPartition[]>
                                    splitsAndPartitions = getSplitsAndPartitions(splitsPerPartition);
  final InputSplit[] splits = splitsAndPartitions.getFirst();
  final DistributedDataSetPartition[] partitions = splitsAndPartitions.getSecond();
  Validate.isTrue(splits.length == partitions.length);
  for (int splitNum = 0; splitNum < splits.length; splitNum++) {
    LOG.log(Level.FINE, "Processing split: " + splitNum);
    final InputSplit split = splits[splitNum];
    final NumberedSplit<InputSplit> numberedSplit = new NumberedSplit<>(split, splitNum,
        partitions[splitNum]);
    unallocatedSplits.add(numberedSplit);
    updateLocations(numberedSplit);
  }
  if (LOG.isLoggable(Level.FINE)) {
    for (final Map.Entry<String, BlockingQueue<NumberedSplit<InputSplit>>> locSplit : locationToSplits.entrySet()) {
      LOG.log(Level.FINE, locSplit.getKey() + ": " + locSplit.getValue().toString());
    }
  }
}
 
Example 7
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 8
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 9
Source File: GaussNewtonOptimizer.java    From astor with GNU General Public License v2.0 5 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 CholeskyDecomposition(
                normal, SINGULARITY_THRESHOLD, SINGULARITY_THRESHOLD)
                .getSolver()
                .solve(jTr);
    } catch (NonPositiveDefiniteMatrixException e) {
        throw new ConvergenceException(LocalizedFormats.UNABLE_TO_SOLVE_SINGULAR_PROBLEM, e);
    }
}
 
Example 10
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 11
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 12
Source File: Intervals.java    From microMathematics with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Procedure returns declared interval if this root formula represents an interval
 */
public void getInterval(EquationArrayResult arrayResult, CalculaterTask thread) throws CancelException
{
    Pair<Unit, Integer> units = compareUnits(new TermField[]{ minValueTerm, nextValueTerm, maxValueTerm });
    if (units.getFirst() != null && units.getSecond() != 3)
    {
        return;
    }

    minValue.processRealTerm(thread, minValueTerm);
    nextValue.processRealTerm(thread, nextValueTerm);
    maxValue.processRealTerm(thread, maxValueTerm);
    if (minValue.isNaN() || nextValue.isNaN() || maxValue.isNaN())
    {
        return;
    }
    final CalculatedValue calcDelta = getDelta(minValue.getReal(), nextValue.getReal(), maxValue.getReal());
    if (calcDelta.isNaN())
    {
        return;
    }
    final int N = getNumberOfPoints(minValue.getReal(), maxValue.getReal(), calcDelta.getReal());
    arrayResult.resize1D(N + 1);
    for (int idx = 0; idx <= N; idx++)
    {
        if (thread != null)
        {
            thread.checkCancelation();
        }
        final CalculatedValue cv = arrayResult.getValue1D(idx);
        if (idx == 0)
        {
            cv.setValue(minValue.getReal(), units.getFirst());
        }
        else if (idx == N)
        {
            cv.setValue(maxValue.getReal(), units.getFirst());
        }
        else
        {
            final double val = minValue.getReal() + calcDelta.getReal() * (double) idx;
            cv.setValue(val, units.getFirst());
        }
    }
}
 
Example 13
Source File: NumericalConstraint.java    From DNC with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public String toString() {
	StringBuffer result_str = new StringBuffer();
	
	for( Pair<Operator,FlowLocationTime> flow_term : flow_shape_terms ) {
		switch( flow_term.getFirst() ) {
			case PLUS:
			default:
				result_str.append( " + " );
				break;
			case MINUS:
				result_str.append( " - " );
				break;
		}
		
		result_str.append( flow_term.getSecond().toString() );
	}
	
	switch( relation ) {
		case L:
			result_str.append( " < " );
			break;
		case LE:
		default:
			result_str.append( " <= " );
			break;
		case E:
			result_str.append( " = " );
			break;
		case GE:
			result_str.append( " >= " );
			break;
		case G:
			result_str.append( " > " );
			break;
	}

	for( NumericalTerm term : num_terms ) {
		result_str.append( term.toString() );
	}
	
	return result_str.toString();
}
 
Example 14
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 15
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 16
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 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 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());
}
 
Example 18
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());
}
 
Example 19
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());
}