org.apache.commons.math3.exception.DimensionMismatchException Java Examples

The following examples show how to use org.apache.commons.math3.exception.DimensionMismatchException. 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: Array2DRowRealMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public double[] operate(final double[] v)
    throws DimensionMismatchException {
    final int nRows = this.getRowDimension();
    final int nCols = this.getColumnDimension();
    if (v.length != nCols) {
        throw new DimensionMismatchException(v.length, nCols);
    }
    final double[] out = new double[nRows];
    for (int row = 0; row < nRows; row++) {
        final double[] dataRow = data[row];
        double sum = 0;
        for (int i = 0; i < nCols; i++) {
            sum += dataRow[i] * v[i];
        }
        out[row] = sum;
    }
    return out;
}
 
Example #2
Source File: AbstractLeastSquaresOptimizerAbstractTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=DimensionMismatchException.class)
public void testInconsistentSizes1() {
    LinearProblem problem
        = new LinearProblem(new double[][] { { 1, 0 }, { 0, 1 } },
                            new double[] { -1, 1 });
    AbstractLeastSquaresOptimizer optimizer = createOptimizer();
    PointVectorValuePair optimum =
        optimizer.optimize(new MaxEval(100),
                           problem.getModelFunction(),
                           problem.getModelFunctionJacobian(),
                           problem.getTarget(),
                           new Weight(new double[] { 1, 1 }),
                           new InitialGuess(new double[] { 0, 0 }));
    Assert.assertEquals(0, optimizer.getRMS(), 1e-10);
    Assert.assertEquals(-1, optimum.getPoint()[0], 1e-10);
    Assert.assertEquals(1, optimum.getPoint()[1], 1e-10);

    optimizer.optimize(new MaxEval(100),
                       problem.getModelFunction(),
                       problem.getModelFunctionJacobian(),
                       problem.getTarget(),
                       new Weight(new double[] { 1 }),
                       new InitialGuess(new double[] { 0, 0 }));
}
 
Example #3
Source File: RandomKey.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a representation of a permutation corresponding to a
 * permutation which yields <code>permutedData</code> when applied to
 * <code>originalData</code>.
 *
 * This method can be viewed as an inverse to {@link #decode(List)}.
 *
 * @param <S> type of the data
 * @param originalData the original, unpermuted data
 * @param permutedData the data, somehow permuted
 * @return representation of a permutation corresponding to the permutation
 *   <code>originalData -> permutedData</code>
 * @throws DimensionMismatchException iff the length of <code>originalData</code>
 *   and <code>permutedData</code> lists are not equal
 * @throws MathIllegalArgumentException iff the <code>permutedData</code> and
 *   <code>originalData</code> lists contain different data
 */
public static <S> List<Double> inducedPermutation(final List<S> originalData,
                                                  final List<S> permutedData)
    throws DimensionMismatchException, MathIllegalArgumentException {

    if (originalData.size() != permutedData.size()) {
        throw new DimensionMismatchException(permutedData.size(), originalData.size());
    }
    int l = originalData.size();

    List<S> origDataCopy = new ArrayList<S> (originalData);

    Double[] res = new Double[l];
    for (int i=0; i<l; i++) {
        int index = origDataCopy.indexOf(permutedData.get(i));
        if (index == -1) {
            throw new MathIllegalArgumentException(LocalizedFormats.DIFFERENT_ORIG_AND_PERMUTED_DATA);
        }
        res[index] = (double) i / l;
        origDataCopy.set(index, null);
    }
    return Arrays.asList(res);
}
 
Example #4
Source File: StatUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the variance of the (signed) differences between corresponding elements of the
 * input arrays -- i.e., var(sample1[i] - sample2[i]).
 *
 * @param sample1  the first array
 * @param sample2  the second array
 * @param meanDifference   the mean difference between corresponding entries
 * @see #meanDifference(double[],double[])
 * @return variance of paired differences
 * @throws DimensionMismatchException if the arrays do not have the same
 * length.
 * @throws NumberIsTooSmallException if the arrays length is less than 2.
 */
public static double varianceDifference(final double[] sample1,
                                        final double[] sample2,
                                        double meanDifference) {
    double sum1 = 0d;
    double sum2 = 0d;
    double diff = 0d;
    int n = sample1.length;
    if (n != sample2.length) {
        throw new DimensionMismatchException(n, sample2.length);
    }
    if (n < 2) {
        throw new NumberIsTooSmallException(n, 2, true);
    }
    for (int i = 0; i < n; i++) {
        diff = sample1[i] - sample2[i];
        sum1 += (diff - meanDifference) *(diff - meanDifference);
        sum2 += diff - meanDifference;
    }
    return (sum1 - (sum2 * sum2 / n)) / (n - 1);
}
 
Example #5
Source File: TransformUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds a new array of {@link Complex} from the specified two dimensional
 * array of real and imaginary parts. In the returned array {@code dataC},
 * the data is laid out as follows
 * <ul>
 * <li>{@code dataC[i].getReal() = dataRI[0][i]},</li>
 * <li>{@code dataC[i].getImaginary() = dataRI[1][i]}.</li>
 * </ul>
 *
 * @param dataRI the array of real and imaginary parts to be transformed
 * @return an array of {@link Complex} with specified real and imaginary parts.
 * @throws DimensionMismatchException if the number of rows of the specified
 *   array is not two, or the array is not rectangular
 */
public static Complex[] createComplexArray(final double[][] dataRI)
    throws DimensionMismatchException{

    if (dataRI.length != 2) {
        throw new DimensionMismatchException(dataRI.length, 2);
    }
    final double[] dataR = dataRI[0];
    final double[] dataI = dataRI[1];
    if (dataR.length != dataI.length) {
        throw new DimensionMismatchException(dataI.length, dataR.length);
    }

    final int n = dataR.length;
    final Complex[] c = new Complex[n];
    for (int i = 0; i < n; i++) {
        c[i] = new Complex(dataR[i], dataI[i]);
    }
    return c;
}
 
Example #6
Source File: MultistepIntegrator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Start the integration.
 * <p>This method computes one step using the underlying starter integrator,
 * and initializes the Nordsieck vector at step start. The starter integrator
 * purpose is only to establish initial conditions, it does not really change
 * time by itself. The top level multistep integrator remains in charge of
 * handling time propagation and events handling as it will starts its own
 * computation right from the beginning. In a sense, the starter integrator
 * can be seen as a dummy one and so it will never trigger any user event nor
 * call any user step handler.</p>
 * @param t0 initial time
 * @param y0 initial value of the state vector at t0
 * @param t target time for the integration
 * (can be set to a value smaller than <code>t0</code> for backward integration)
 * @exception DimensionMismatchException if arrays dimension do not match equations settings
 * @exception NumberIsTooSmallException if integration step is too small
 * @exception MaxCountExceededException if the number of functions evaluations is exceeded
 * @exception NoBracketingException if the location of an event cannot be bracketed
 */
protected void start(final double t0, final double[] y0, final double t)
    throws DimensionMismatchException, NumberIsTooSmallException,
           MaxCountExceededException, NoBracketingException {

    // make sure NO user event nor user step handler is triggered,
    // this is the task of the top level integrator, not the task
    // of the starter integrator
    starter.clearEventHandlers();
    starter.clearStepHandlers();

    // set up one specific step handler to extract initial Nordsieck vector
    starter.addStepHandler(new NordsieckInitializer(nSteps, y0.length));

    // start integration, expecting a InitializationCompletedMarkerException
    try {
        starter.integrate(new CountingDifferentialEquations(y0.length),
                          t0, y0, t, new double[y0.length]);
    } catch (InitializationCompletedMarkerException icme) { // NOPMD
        // this is the expected nominal interruption of the start integrator
    }

    // remove the specific step handler
    starter.clearStepHandlers();

}
 
Example #7
Source File: AbstractSimplex.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build an initial simplex.
 *
 * @param startPoint First point of the simplex.
 * @throws DimensionMismatchException if the start point does not match
 * simplex dimension.
 */
public void build(final double[] startPoint) {
    if (dimension != startPoint.length) {
        throw new DimensionMismatchException(dimension, startPoint.length);
    }

    // Set first vertex.
    simplex = new PointValuePair[dimension + 1];
    simplex[0] = new PointValuePair(startPoint, Double.NaN);

    // Set remaining vertices.
    for (int i = 0; i < dimension; i++) {
        final double[] confI = startConfiguration[i];
        final double[] vertexI = new double[dimension];
        for (int k = 0; k < dimension; k++) {
            vertexI[k] = startPoint[k] + confI[k];
        }
        simplex[i + 1] = new PointValuePair(vertexI, Double.NaN);
    }
}
 
Example #8
Source File: HarmonicOscillator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Computes the value of the gradient at {@code x}.
 * The components of the gradient vector are the partial
 * derivatives of the function with respect to each of the
 * <em>parameters</em> (amplitude, angular frequency and phase).
 *
 * @param x Value at which the gradient must be computed.
 * @param param Values of amplitude, angular frequency and phase.
 * @return the gradient vector at {@code x}.
 * @throws NullArgumentException if {@code param} is {@code null}.
 * @throws DimensionMismatchException if the size of {@code param} is
 * not 3.
 */
public double[] gradient(double x, double ... param)
    throws NullArgumentException,
           DimensionMismatchException {
    validateParameters(param);

    final double amplitude = param[0];
    final double omega = param[1];
    final double phase = param[2];

    final double xTimesOmegaPlusPhase = omega * x + phase;
    final double a = HarmonicOscillator.value(xTimesOmegaPlusPhase, 1);
    final double p = -amplitude * FastMath.sin(xTimesOmegaPlusPhase);
    final double w = p * x;

    return new double[] { a, w, p };
}
 
Example #9
Source File: HilbertMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public RealVector operate(final RealVector x) {
    if (x.getDimension() != n) {
        throw new DimensionMismatchException(x.getDimension(), n);
    }
    final double[] y = new double[n];
    for (int i = 0; i < n; i++) {
        double pos = 0.;
        double neg = 0.;
        for (int j = 0; j < n; j++) {
            final double xj = x.getEntry(j);
            final double coeff = 1. / (i + j + 1.);
            // Positive and negative values are sorted out in order to limit
            // catastrophic cancellations (do not forget that Hilbert
            // matrices are *very* ill-conditioned!
            if (xj > 0.) {
                pos += coeff * xj;
            } else {
                neg += coeff * xj;
            }
        }
        y[i] = pos + neg;
    }
    return new ArrayRealVector(y, false);
}
 
Example #10
Source File: AbstractLeastSquaresOptimizerAbstractTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=DimensionMismatchException.class)
public void testInconsistentSizes1() {
    LinearProblem problem
        = new LinearProblem(new double[][] { { 1, 0 }, { 0, 1 } },
                            new double[] { -1, 1 });
    AbstractLeastSquaresOptimizer optimizer = createOptimizer();
    PointVectorValuePair optimum =
        optimizer.optimize(new MaxEval(100),
                           problem.getModelFunction(),
                           problem.getModelFunctionJacobian(),
                           problem.getTarget(),
                           new Weight(new double[] { 1, 1 }),
                           new InitialGuess(new double[] { 0, 0 }));
    Assert.assertEquals(0, optimizer.getRMS(), 1e-10);
    Assert.assertEquals(-1, optimum.getPoint()[0], 1e-10);
    Assert.assertEquals(1, optimum.getPoint()[1], 1e-10);

    optimizer.optimize(new MaxEval(100),
                       problem.getModelFunction(),
                       problem.getModelFunctionJacobian(),
                       problem.getTarget(),
                       new Weight(new double[] { 1 }),
                       new InitialGuess(new double[] { 0, 0 }));
}
 
Example #11
Source File: OpenMapRealVector.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Optimized method to subtract OpenMapRealVectors.
 *
 * @param v Vector to subtract from {@code this}.
 * @return the difference of {@code this} and {@code v}.
 * @throws DimensionMismatchException if the dimensions do not match.
 */
public OpenMapRealVector subtract(OpenMapRealVector v)
    throws DimensionMismatchException {
    checkVectorDimensions(v.getDimension());
    OpenMapRealVector res = copy();
    Iterator iter = v.getEntries().iterator();
    while (iter.hasNext()) {
        iter.advance();
        int key = iter.key();
        if (entries.containsKey(key)) {
            res.setEntry(key, entries.get(key) - iter.value());
        } else {
            res.setEntry(key, -iter.value());
        }
    }
    return res;
}
 
Example #12
Source File: CorrelatedRandomVectorGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds a correlated random vector generator from its mean
 * vector and covariance matrix.
 *
 * @param mean Expected mean values for all components.
 * @param covariance Covariance matrix.
 * @param small Diagonal elements threshold under which  column are
 * considered to be dependent on previous ones and are discarded
 * @param generator underlying generator for uncorrelated normalized
 * components.
 * @throws org.apache.commons.math3.linear.NonPositiveDefiniteMatrixException
 * if the covariance matrix is not strictly positive definite.
 * @throws DimensionMismatchException if the mean and covariance
 * arrays dimensions do not match.
 */
public CorrelatedRandomVectorGenerator(double[] mean,
                                       RealMatrix covariance, double small,
                                       NormalizedRandomGenerator generator) {
    int order = covariance.getRowDimension();
    if (mean.length != order) {
        throw new DimensionMismatchException(mean.length, order);
    }
    this.mean = mean.clone();

    final RectangularCholeskyDecomposition decomposition =
        new RectangularCholeskyDecomposition(covariance, small);
    root = decomposition.getRootMatrix();

    this.generator = generator;
    normalized = new double[decomposition.getRank()];

}
 
Example #13
Source File: JacobianMatrices.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void computeMainStateJacobian(double t, double[] y, double[] yDot, double[][] dFdY)
    throws MaxCountExceededException, DimensionMismatchException {

    final int n = ode.getDimension();
    final double[] tmpDot = new double[n];

    for (int j = 0; j < n; ++j) {
        final double savedYj = y[j];
        y[j] += hY[j];
        ode.computeDerivatives(t, y, tmpDot);
        for (int i = 0; i < n; ++i) {
            dFdY[i][j] = (tmpDot[i] - yDot[i]) / hY[j];
        }
        y[j] = savedYj;
    }
}
 
Example #14
Source File: GraggBulirschStoerIntegratorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testVariableSteps()
    throws DimensionMismatchException, NumberIsTooSmallException,
           MaxCountExceededException, NoBracketingException {

  final TestProblem3 pb = new TestProblem3(0.9);
  double minStep        = 0;
  double maxStep        = pb.getFinalTime() - pb.getInitialTime();
  double absTolerance   = 1.0e-8;
  double relTolerance   = 1.0e-8;
  FirstOrderIntegrator integ =
    new GraggBulirschStoerIntegrator(minStep, maxStep,
                                     absTolerance, relTolerance);
  integ.addStepHandler(new VariableStepHandler());
  double stopTime = integ.integrate(pb,
                                    pb.getInitialTime(), pb.getInitialState(),
                                    pb.getFinalTime(), new double[pb.getDimension()]);
  Assert.assertEquals(pb.getFinalTime(), stopTime, 1.0e-10);
  Assert.assertEquals("Gragg-Bulirsch-Stoer", integ.getName());
}
 
Example #15
Source File: ExpandableStatefulODE.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Set the complete current state.
 * @param completeState complete current state to copy data from
 * @throws DimensionMismatchException if the dimension of the complete state does not
 * match the complete equations sets dimension
 */
public void setCompleteState(final double[] completeState)
    throws DimensionMismatchException {

    // safety checks
    if (completeState.length != getTotalDimension()) {
        throw new DimensionMismatchException(completeState.length, getTotalDimension());
    }

    // set the data
    primaryMapper.extractEquationData(completeState, primaryState);
    for (final SecondaryComponent component : components) {
        component.mapper.extractEquationData(completeState, component.state);
    }

}
 
Example #16
Source File: ArrayRealVector.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public ArrayRealVector combineToSelf(double a, double b, RealVector y)
    throws DimensionMismatchException {
    if (y instanceof ArrayRealVector) {
        final double[] yData = ((ArrayRealVector) y).data;
        checkVectorDimensions(yData.length);
        for (int i = 0; i < this.data.length; i++) {
            data[i] = a * data[i] + b * yData[i];
        }
    } else {
        checkVectorDimensions(y);
        for (int i = 0; i < this.data.length; i++) {
            data[i] = a * data[i] + b * y.getEntry(i);
        }
    }
    return this;
}
 
Example #17
Source File: AbstractLeastSquaresOptimizerAbstractTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=DimensionMismatchException.class)
public void testInconsistentSizes1() {
    LinearProblem problem
        = new LinearProblem(new double[][] { { 1, 0 }, { 0, 1 } },
                            new double[] { -1, 1 });
    AbstractLeastSquaresOptimizer optimizer = createOptimizer();
    PointVectorValuePair optimum =
        optimizer.optimize(new MaxEval(100),
                           problem.getModelFunction(),
                           problem.getModelFunctionJacobian(),
                           problem.getTarget(),
                           new Weight(new double[] { 1, 1 }),
                           new InitialGuess(new double[] { 0, 0 }));
    Assert.assertEquals(0, optimizer.getRMS(), 1e-10);
    Assert.assertEquals(-1, optimum.getPoint()[0], 1e-10);
    Assert.assertEquals(1, optimum.getPoint()[1], 1e-10);

    optimizer.optimize(new MaxEval(100),
                       problem.getModelFunction(),
                       problem.getModelFunctionJacobian(),
                       problem.getTarget(),
                       new Weight(new double[] { 1 }),
                       new InitialGuess(new double[] { 0, 0 }));
}
 
Example #18
Source File: SymmLQ.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @param x not meaningful in this implementation; should not be considered
 * as an initial guess (<a href="#initguess">more</a>)
 * @throws NonSelfAdjointOperatorException if {@link #getCheck()} is
 * {@code true}, and {@code a} is not self-adjoint
 * @throws IllConditionedOperatorException if {@code a} is ill-conditioned
 */
@Override
public RealVector solve(final RealLinearOperator a, final RealVector b,
    final RealVector x) throws NullArgumentException,
    NonSquareOperatorException, DimensionMismatchException,
    NonSelfAdjointOperatorException, IllConditionedOperatorException,
    MaxCountExceededException {
    MathUtils.checkNotNull(x);
    return solveInPlace(a, null, b, x.copy(), false, 0.);
}
 
Example #19
Source File: DormandPrince853IntegratorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testIncreasingTolerance()
    throws DimensionMismatchException, NumberIsTooSmallException,
           MaxCountExceededException, NoBracketingException {

  int previousCalls = Integer.MAX_VALUE;
  AdaptiveStepsizeIntegrator integ =
      new DormandPrince853Integrator(0, Double.POSITIVE_INFINITY,
                                     Double.NaN, Double.NaN);
  for (int i = -12; i < -2; ++i) {
    TestProblem1 pb = new TestProblem1();
    double minStep = 0;
    double maxStep = pb.getFinalTime() - pb.getInitialTime();
    double scalAbsoluteTolerance = FastMath.pow(10.0, i);
    double scalRelativeTolerance = 0.01 * scalAbsoluteTolerance;
    integ.setStepSizeControl(minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance);

    TestProblemHandler handler = new TestProblemHandler(pb, integ);
    integ.addStepHandler(handler);
    integ.integrate(pb,
                    pb.getInitialTime(), pb.getInitialState(),
                    pb.getFinalTime(), new double[pb.getDimension()]);

    // the 1.3 factor is only valid for this test
    // and has been obtained from trial and error
    // there is no general relation between local and global errors
    Assert.assertTrue(handler.getMaximalValueError() < (1.3 * scalAbsoluteTolerance));
    Assert.assertEquals(0, handler.getMaximalTimeError(), 1.0e-12);

    int calls = pb.getCalls();
    Assert.assertEquals(integ.getEvaluations(), calls);
    Assert.assertTrue(calls <= previousCalls);
    previousCalls = calls;

  }

}
 
Example #20
Source File: Logistic.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validates parameters to ensure they are appropriate for the evaluation of
 * the {@link #value(double,double[])} and {@link #gradient(double,double[])}
 * methods.
 *
 * @param param Values for {@code k}, {@code m}, {@code b}, {@code q},
 * {@code a} and {@code n}.
 * @throws NullArgumentException if {@code param} is {@code null}.
 * @throws DimensionMismatchException if the size of {@code param} is
 * not 6.
 * @throws NotStrictlyPositiveException if {@code param[5] <= 0}.
 */
private void validateParameters(double[] param)
    throws NullArgumentException,
           DimensionMismatchException,
           NotStrictlyPositiveException {
    if (param == null) {
        throw new NullArgumentException();
    }
    if (param.length != 6) {
        throw new DimensionMismatchException(param.length, 6);
    }
    if (param[5] <= 0) {
        throw new NotStrictlyPositiveException(param[5]);
    }
}
 
Example #21
Source File: GraggBulirschStoerIntegratorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testTooLargeFirstStep()
    throws DimensionMismatchException, NumberIsTooSmallException,
           MaxCountExceededException, NoBracketingException {

    AdaptiveStepsizeIntegrator integ =
            new GraggBulirschStoerIntegrator(0, Double.POSITIVE_INFINITY, Double.NaN, Double.NaN);
    final double start = 0.0;
    final double end   = 0.001;
    FirstOrderDifferentialEquations equations = new FirstOrderDifferentialEquations() {

        public int getDimension() {
            return 1;
        }

        public void computeDerivatives(double t, double[] y, double[] yDot) {
            Assert.assertTrue(t >= FastMath.nextAfter(start, Double.NEGATIVE_INFINITY));
            Assert.assertTrue(t <= FastMath.nextAfter(end,   Double.POSITIVE_INFINITY));
            yDot[0] = -100.0 * y[0];
        }

    };

    integ.setStepSizeControl(0, 1.0, 1.0e-6, 1.0e-8);
    integ.integrate(equations, start, new double[] { 1.0 }, end, new double[1]);

}
 
Example #22
Source File: Gaussian.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validates parameters to ensure they are appropriate for the evaluation of
 * the {@link #value(double,double[])} and {@link #gradient(double,double[])}
 * methods.
 *
 * @param param Values of norm, mean and standard deviation.
 * @throws NullArgumentException if {@code param} is {@code null}.
 * @throws DimensionMismatchException if the size of {@code param} is
 * not 3.
 * @throws NotStrictlyPositiveException if {@code param[2]} is negative.
 */
private void validateParameters(double[] param) {
    if (param == null) {
        throw new NullArgumentException();
    }
    if (param.length != 3) {
        throw new DimensionMismatchException(param.length, 3);
    }
    if (param[2] <= 0) {
        throw new NotStrictlyPositiveException(param[2]);
    }
}
 
Example #23
Source File: GaussIntegrator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an integrator from the given {@code points} and {@code weights}.
 * The integration interval is defined by the first and last value of
 * {@code points} which must be sorted in increasing order.
 *
 * @param points Integration points.
 * @param weights Weights of the corresponding integration nodes.
 * @throws NonMonotonicSequenceException if the {@code points} are not
 * sorted in increasing order.
 * @throws DimensionMismatchException if points and weights don't have the same length
 */
public GaussIntegrator(double[] points,
                       double[] weights)
    throws NonMonotonicSequenceException, DimensionMismatchException {
    if (points.length != weights.length) {
        throw new DimensionMismatchException(points.length,
                                             weights.length);
    }

    MathArrays.checkOrder(points, MathArrays.OrderDirection.INCREASING, true, true);

    this.points = points.clone();
    this.weights = weights.clone();
}
 
Example #24
Source File: Logistic.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validates parameters to ensure they are appropriate for the evaluation of
 * the {@link #value(double,double[])} and {@link #gradient(double,double[])}
 * methods.
 *
 * @param param Values for {@code k}, {@code m}, {@code b}, {@code q},
 * {@code a} and  {@code n}.
 * @throws NullArgumentException if {@code param} is {@code null}.
 * @throws DimensionMismatchException if the size of {@code param} is
 * not 6.
 */
private void validateParameters(double[] param) {
    if (param == null) {
        throw new NullArgumentException();
    }
    if (param.length != 6) {
        throw new DimensionMismatchException(param.length, 6);
    }
    if (param[5] <= 0) {
        throw new NotStrictlyPositiveException(param[5]);
    }
}
 
Example #25
Source File: StepNormalizerOutputTestBase.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testIncNeitherRev()
    throws DimensionMismatchException, NumberIsTooSmallException,
           MaxCountExceededException, NoBracketingException {
    double[] exp = getArray(getExpIncRev(), getO()[1][0], getO()[1][1]);
    doTest(StepNormalizerMode.INCREMENT, StepNormalizerBounds.NEITHER, exp, true);
}
 
Example #26
Source File: AbstractRealMatrix.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void setSubMatrix(final double[][] subMatrix, final int row, final int column)
    throws NoDataException, DimensionMismatchException, NullArgumentException {
    MathUtils.checkNotNull(subMatrix);
    final int nRows = subMatrix.length;
    if (nRows == 0) {
        throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
    }

    final int nCols = subMatrix[0].length;
    if (nCols == 0) {
        throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
    }

    for (int r = 1; r < nRows; ++r) {
        if (subMatrix[r].length != nCols) {
            throw new DimensionMismatchException(nCols, subMatrix[r].length);
        }
    }

    MatrixUtils.checkRowIndex(this, row);
    MatrixUtils.checkColumnIndex(this, column);
    MatrixUtils.checkRowIndex(this, nRows + row - 1);
    MatrixUtils.checkColumnIndex(this, nCols + column - 1);

    for (int i = 0; i < nRows; ++i) {
        for (int j = 0; j < nCols; ++j) {
            setEntry(row + i, column + j, subMatrix[i][j]);
        }
    }
}
 
Example #27
Source File: Sigmoid.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validates parameters to ensure they are appropriate for the evaluation of
 * the {@link #value(double,double[])} and {@link #gradient(double,double[])}
 * methods.
 *
 * @param param Values for lower and higher asymptotes.
 * @throws NullArgumentException if {@code param} is {@code null}.
 * @throws DimensionMismatchException if the size of {@code param} is
 * not 2.
 */
private void validateParameters(double[] param)
    throws NullArgumentException,
           DimensionMismatchException {
    if (param == null) {
        throw new NullArgumentException();
    }
    if (param.length != 2) {
        throw new DimensionMismatchException(param.length, 2);
    }
}
 
Example #28
Source File: MatTests.java    From clust4j with Apache License 2.0 5 votes vote down vote up
@Test(expected=DimensionMismatchException.class)
public void testMultiArrayBooleanUniformity3() {
	boolean[][] a = new boolean[][]{
		new boolean[]{true, true},
		new boolean[]{true, true}
	};
	
	boolean[][] b = new boolean[][]{
		new boolean[]{false, false, false},
		new boolean[]{true, true, true}
	};
	
	MatUtils.checkDimsForUniformity(a, b);
}
 
Example #29
Source File: ArrayFieldVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Element-by-element division.
 * @param v vector by which instance elements must be divided
 * @return a vector containing {@code this[i] / v[i]} for all {@code i}
 * @throws DimensionMismatchException if {@code v} is not the same size as
 * {@code this}
 * @throws MathArithmeticException if one entry of {@code v} is zero.
 */
public ArrayFieldVector<T> ebeDivide(ArrayFieldVector<T> v)
    throws DimensionMismatchException, MathArithmeticException {
    checkVectorDimensions(v.data.length);
    T[] out = MathArrays.buildArray(field, data.length);
    for (int i = 0; i < data.length; i++) {
        try {
            out[i] = data[i].divide(v.data[i]);
        } catch (final MathArithmeticException e) {
            throw new MathArithmeticException(LocalizedFormats.INDEX, i);
        }
    }
    return new ArrayFieldVector<T>(field, out, false);
}
 
Example #30
Source File: EventFilterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testTwoOppositeFilters()
    throws DimensionMismatchException, NumberIsTooSmallException,
           MaxCountExceededException, NoBracketingException {
    double e = 1e-15;
    FirstOrderIntegrator integrator;
    integrator = new DormandPrince853Integrator(1.0e-3, 100.0, 1e-7, 1e-7);
    Event allEvents = new Event(true, true);
    integrator.addEventHandler(allEvents, 0.1, e, 1000,
                               new BracketingNthOrderBrentSolver(1.0e-7, 5));
    Event onlyIncreasing = new Event(false, true);
    integrator.addEventHandler(new EventFilter(onlyIncreasing,
                                               FilterType.TRIGGER_ONLY_INCREASING_EVENTS),
                               0.1, e, 1000,
                               new BracketingNthOrderBrentSolver(1.0e-7, 5));
    Event onlyDecreasing = new Event(true, false);
    integrator.addEventHandler(new EventFilter(onlyDecreasing,
                                               FilterType.TRIGGER_ONLY_DECREASING_EVENTS),
                               0.1, e, 1000,
                               new BracketingNthOrderBrentSolver(1.0e-7, 5));
    double t0 = 0.5 * FastMath.PI;
    double tEnd = 5.5 * FastMath.PI;
    double[] y = { 0.0, 1.0 };
    Assert.assertEquals(tEnd,
                        integrator.integrate(new SineCosine(), t0, y, tEnd, y),
                        1.0e-7);

    Assert.assertEquals(5, allEvents.getEventCount());
    Assert.assertEquals(2, onlyIncreasing.getEventCount());
    Assert.assertEquals(3, onlyDecreasing.getEventCount());

}