org.apache.commons.math3.util.MathArrays Java Examples

The following examples show how to use org.apache.commons.math3.util.MathArrays. 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: MultivariateNormalMixtureExpectationMaximization.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an object to fit a multivariate normal mixture model to data.
 *
 * @param data Data to use in fitting procedure
 * @throws NotStrictlyPositiveException if data has no rows
 * @throws DimensionMismatchException if rows of data have different numbers
 *             of columns
 * @throws NumberIsTooSmallException if the number of columns in the data is
 *             less than 2
 */
public MultivariateNormalMixtureExpectationMaximization(double[][] data)
    throws NotStrictlyPositiveException,
           DimensionMismatchException,
           NumberIsTooSmallException {
    if (data.length < 1) {
        throw new NotStrictlyPositiveException(data.length);
    }

    this.data = new double[data.length][data[0].length];

    for (int i = 0; i < data.length; i++) {
        if (data[i].length != data[0].length) {
            // Jagged arrays not allowed
            throw new DimensionMismatchException(data[i].length,
                                                 data[0].length);
        }
        if (data[i].length < 2) {
            throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_TOO_SMALL,
                                                data[i].length, 2, true);
        }
        this.data[i] = MathArrays.copyOf(data[i], data[i].length);
    }
}
 
Example #2
Source File: Array2DRowFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public T[] operate(final T[] v) throws DimensionMismatchException {
    final int nRows = this.getRowDimension();
    final int nCols = this.getColumnDimension();
    if (v.length != nCols) {
        throw new DimensionMismatchException(v.length, nCols);
    }
    final T[] out = MathArrays.buildArray(getField(), nRows);
    for (int row = 0; row < nRows; row++) {
        final T[] dataRow = data[row];
        T sum = getField().getZero();
        for (int i = 0; i < nCols; i++) {
            sum = sum.add(dataRow[i].multiply(v[i]));
        }
        out[row] = sum;
    }
    return out;
}
 
Example #3
Source File: Cardumen_00229_t.java    From coming with 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
Source File: AbstractFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public T[] preMultiply(final T[] v) throws DimensionMismatchException {

    final int nRows = getRowDimension();
    final int nCols = getColumnDimension();
    if (v.length != nRows) {
        throw new DimensionMismatchException(v.length, nRows);
    }

    final T[] out = MathArrays.buildArray(field, nCols);
    for (int col = 0; col < nCols; ++col) {
        T sum = field.getZero();
        for (int i = 0; i < nRows; ++i) {
            sum = sum.add(getEntry(i, col).multiply(v[i]));
        }
        out[col] = sum;
    }

    return out;
}
 
Example #5
Source File: RandomDataGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * This method calls {@link MathArrays#shuffle(int[],RandomGenerator)
 * MathArrays.shuffle} in order to create a random shuffle of the set
 * of natural numbers {@code { 0, 1, ..., n - 1 }}.
 *
 * @throws NumberIsTooLargeException if {@code k > n}.
 * @throws NotStrictlyPositiveException if {@code k <= 0}.
 */
public int[] nextPermutation(int n, int k)
    throws NumberIsTooLargeException, NotStrictlyPositiveException {
    if (k > n) {
        throw new NumberIsTooLargeException(LocalizedFormats.PERMUTATION_EXCEEDS_N,
                                            k, n, true);
    }
    if (k <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.PERMUTATION_SIZE,
                                               k);
    }

    int[] index = MathArrays.natural(n);
    MathArrays.shuffle(index, getRandomGenerator());

    // Return a new array containing the first "k" entries of "index".
    return MathArrays.copyOf(index, k);
}
 
Example #6
Source File: AbstractFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public FieldVector<T> operate(final FieldVector<T> v)
    throws DimensionMismatchException {
    try {
        return new ArrayFieldVector<T>(field, operate(((ArrayFieldVector<T>) v).getDataRef()), false);
    } catch (ClassCastException cce) {
        final int nRows = getRowDimension();
        final int nCols = getColumnDimension();
        if (v.getDimension() != nCols) {
            throw new DimensionMismatchException(v.getDimension(), nCols);
        }

        final T[] out = MathArrays.buildArray(field, nRows);
        for (int row = 0; row < nRows; ++row) {
            T sum = field.getZero();
            for (int i = 0; i < nCols; ++i) {
                sum = sum.add(getEntry(row, i).multiply(v.getEntry(i)));
            }
            out[row] = sum;
        }

        return new ArrayFieldVector<T>(field, out, false);
    }
}
 
Example #7
Source File: Array2DRowFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add {@code m} to this matrix.
 *
 * @param m Matrix to be added.
 * @return {@code this} + m.
 * @throws MatrixDimensionMismatchException if {@code m} is not the same
 * size as this matrix.
 */
public Array2DRowFieldMatrix<T> add(final Array2DRowFieldMatrix<T> m)
    throws MatrixDimensionMismatchException {
    // safety check
    checkAdditionCompatible(m);

    final int rowCount    = getRowDimension();
    final int columnCount = getColumnDimension();
    final T[][] outData = MathArrays.buildArray(getField(), rowCount, columnCount);
    for (int row = 0; row < rowCount; row++) {
        final T[] dataRow    = data[row];
        final T[] mRow       = m.data[row];
        final T[] outDataRow = outData[row];
        for (int col = 0; col < columnCount; col++) {
            outDataRow[col] = dataRow[col].add(mRow[col]);
        }
    }

    return new Array2DRowFieldMatrix<T>(getField(), outData, false);
}
 
Example #8
Source File: Arja_00127_s.java    From coming with 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 #9
Source File: Arja_0085_s.java    From coming with 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 #10
Source File: PolynomialSplineFunction.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a polynomial spline function with the given segment delimiters
 * and interpolating polynomials.
 * The constructor copies both arrays and assigns the copies to the knots
 * and polynomials properties, respectively.
 *
 * @param knots Spline segment interval delimiters.
 * @param polynomials Polynomial functions that make up the spline.
 * @throws NullArgumentException if either of the input arrays is {@code null}.
 * @throws NumberIsTooSmallException if knots has length less than 2.
 * @throws DimensionMismatchException if {@code polynomials.length != knots.length - 1}.
 * @throws org.apache.commons.math3.exception.NonMonotonicSequenceException if
 * the {@code knots} array is not strictly increasing.
 *
 */
public PolynomialSplineFunction(double knots[], PolynomialFunction polynomials[]) {
    if (knots == null ||
        polynomials == null) {
        throw new NullArgumentException();
    }
    if (knots.length < 2) {
        throw new NumberIsTooSmallException(LocalizedFormats.NOT_ENOUGH_POINTS_IN_SPLINE_PARTITION,
                                            2, knots.length, false);
    }
    if (knots.length - 1 != polynomials.length) {
        throw new DimensionMismatchException(polynomials.length, knots.length);
    }
    MathArrays.checkOrder(knots);

    this.n = knots.length -1;
    this.knots = new double[n + 1];
    System.arraycopy(knots, 0, this.knots, 0, n + 1);
    this.polynomials = new PolynomialFunction[n];
    System.arraycopy(polynomials, 0, this.polynomials, 0, n);
}
 
Example #11
Source File: DerivativeStructure.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc}
 * @exception DimensionMismatchException if number of free parameters
 * or orders do not match
 */
public DerivativeStructure linearCombination(final DerivativeStructure a1, final DerivativeStructure b1,
                                             final DerivativeStructure a2, final DerivativeStructure b2,
                                             final DerivativeStructure a3, final DerivativeStructure b3)
    throws DimensionMismatchException {

    // compute an accurate value, taking care of cancellations
    final double accurateValue = MathArrays.linearCombination(a1.getValue(), b1.getValue(),
                                                              a2.getValue(), b2.getValue(),
                                                              a3.getValue(), b3.getValue());

    // compute a simple value, with all partial derivatives
    final DerivativeStructure simpleValue = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3));

    // create a result with accurate value and all derivatives (not necessarily as accurate as the value)
    final double[] all = simpleValue.getAllDerivatives();
    all[0] = accurateValue;
    return new DerivativeStructure(getFreeParameters(), getOrder(), all);

}
 
Example #12
Source File: MillerUpdatingRegression.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds an observation to the regression model.
 * @param x the array with regressor values
 * @param y  the value of dependent variable given these regressors
 * @exception ModelSpecificationException if the length of {@code x} does not equal
 * the number of independent variables in the model
 */
public void addObservation(final double[] x, final double y)
throws ModelSpecificationException {

    if ((!this.hasIntercept && x.length != nvars) ||
           (this.hasIntercept && x.length + 1 != nvars)) {
        throw new ModelSpecificationException(LocalizedFormats.INVALID_REGRESSION_OBSERVATION,
                x.length, nvars);
    }
    if (!this.hasIntercept) {
        include(MathArrays.copyOf(x, x.length), 1.0, y);
    } else {
        final double[] tmp = new double[x.length + 1];
        System.arraycopy(x, 0, tmp, 1, x.length);
        tmp[0] = 1.0;
        include(tmp, 1.0, y);
    }
    ++nobs;

}
 
Example #13
Source File: BlockFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public FieldVector<T> getColumnVector(final int column)
    throws OutOfRangeException {
    checkColumnIndex(column);
    final T[] outData = MathArrays.buildArray(getField(), rows);

    // perform copy block-wise, to ensure good cache behavior
    final int jBlock  = column / BLOCK_SIZE;
    final int jColumn = column - jBlock * BLOCK_SIZE;
    final int jWidth  = blockWidth(jBlock);
    int outIndex      = 0;
    for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
        final int iHeight = blockHeight(iBlock);
        final T[] block = blocks[iBlock * blockColumns + jBlock];
        for (int i = 0; i < iHeight; ++i) {
            outData[outIndex++] = block[i * jWidth + jColumn];
        }
    }

    return new ArrayFieldVector<T>(getField(), outData, false);
}
 
Example #14
Source File: JGenProg2017_0035_t.java    From coming with 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 #15
Source File: NonMonotonicSequenceException.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct the exception.
 *
 * @param wrong Value that did not match the requirements.
 * @param previous Previous value in the sequence.
 * @param index Index of the value that did not match the requirements.
 * @param direction Strictly positive for a sequence required to be
 * increasing, negative (or zero) for a decreasing sequence.
 * @param strict Whether the sequence must be strictly increasing or
 * decreasing.
 */
public NonMonotonicSequenceException(Number wrong,
                                     Number previous,
                                     int index,
                                     MathArrays.OrderDirection direction,
                                     boolean strict) {
    super(direction == MathArrays.OrderDirection.INCREASING ?
          (strict ?
           LocalizedFormats.NOT_STRICTLY_INCREASING_SEQUENCE :
           LocalizedFormats.NOT_INCREASING_SEQUENCE) :
          (strict ?
           LocalizedFormats.NOT_STRICTLY_DECREASING_SEQUENCE :
           LocalizedFormats.NOT_DECREASING_SEQUENCE),
          wrong, previous, index, index - 1);

    this.direction = direction;
    this.strict = strict;
    this.index = index;
    this.previous = previous;
}
 
Example #16
Source File: PolynomialSplineFunction.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a polynomial spline function with the given segment delimiters
 * and interpolating polynomials.
 * The constructor copies both arrays and assigns the copies to the knots
 * and polynomials properties, respectively.
 *
 * @param knots Spline segment interval delimiters.
 * @param polynomials Polynomial functions that make up the spline.
 * @throws NullArgumentException if either of the input arrays is {@code null}.
 * @throws NumberIsTooSmallException if knots has length less than 2.
 * @throws DimensionMismatchException if {@code polynomials.length != knots.length - 1}.
 * @throws NonMonotonicSequenceException if the {@code knots} array is not strictly increasing.
 *
 */
public PolynomialSplineFunction(double knots[], PolynomialFunction polynomials[])
    throws NullArgumentException, NumberIsTooSmallException,
           DimensionMismatchException, NonMonotonicSequenceException{
    if (knots == null ||
        polynomials == null) {
        throw new NullArgumentException();
    }
    if (knots.length < 2) {
        throw new NumberIsTooSmallException(LocalizedFormats.NOT_ENOUGH_POINTS_IN_SPLINE_PARTITION,
                                            2, knots.length, false);
    }
    if (knots.length - 1 != polynomials.length) {
        throw new DimensionMismatchException(polynomials.length, knots.length);
    }
    MathArrays.checkOrder(knots);

    this.n = knots.length -1;
    this.knots = new double[n + 1];
    System.arraycopy(knots, 0, this.knots, 0, n + 1);
    this.polynomials = new PolynomialFunction[n];
    System.arraycopy(polynomials, 0, this.polynomials, 0, n);
}
 
Example #17
Source File: DerivativeStructure.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc}
 * @exception DimensionMismatchException if number of free parameters
 * or orders do not match
 * @since 3.2
 */
public DerivativeStructure linearCombination(final double[] a, final DerivativeStructure[] b)
    throws DimensionMismatchException {

    // compute an accurate value, taking care of cancellations
    final double[] bDouble = new double[b.length];
    for (int i = 0; i < b.length; ++i) {
        bDouble[i] = b[i].getValue();
    }
    final double accurateValue = MathArrays.linearCombination(a, bDouble);

    // compute a simple value, with all partial derivatives
    DerivativeStructure simpleValue = b[0].getField().getZero();
    for (int i = 0; i < a.length; ++i) {
        simpleValue = simpleValue.add(b[i].multiply(a[i]));
    }

    // create a result with accurate value and all derivatives (not necessarily as accurate as the value)
    final double[] all = simpleValue.getAllDerivatives();
    all[0] = accurateValue;
    return new DerivativeStructure(simpleValue.getFreeParameters(), simpleValue.getOrder(), all);

}
 
Example #18
Source File: AbstractFieldMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public FieldVector<T> operate(final FieldVector<T> v)
    throws DimensionMismatchException {
    try {
        return new ArrayFieldVector<T>(field, operate(((ArrayFieldVector<T>) v).getDataRef()), false);
    } catch (ClassCastException cce) {
        final int nRows = getRowDimension();
        final int nCols = getColumnDimension();
        if (v.getDimension() != nCols) {
            throw new DimensionMismatchException(v.getDimension(), nCols);
        }

        final T[] out = MathArrays.buildArray(field, nRows);
        for (int row = 0; row < nRows; ++row) {
            T sum = field.getZero();
            for (int i = 0; i < nCols; ++i) {
                sum = sum.add(getEntry(row, i).multiply(v.getEntry(i)));
            }
            out[row] = sum;
        }

        return new ArrayFieldVector<T>(field, out, false);
    }
}
 
Example #19
Source File: PolynomialFunctionLagrangeForm.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Evaluate the Lagrange polynomial using
 * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html">
 * Neville's Algorithm</a>. It takes O(n^2) time.
 *
 * @param x Interpolating points array.
 * @param y Interpolating values array.
 * @param z Point at which the function value is to be computed.
 * @return the function value.
 * @throws DimensionMismatchException if {@code x} and {@code y} have
 * different lengths.
 * @throws NonMonotonicSequenceException
 * if {@code x} is not sorted in strictly increasing order.
 * @throws NumberIsTooSmallException if the size of {@code x} is less
 * than 2.
 */
public static double evaluate(double x[], double y[], double z)
    throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException {
    if (verifyInterpolationArray(x, y, false)) {
        return evaluateInternal(x, y, z);
    }

    // Array is not sorted.
    final double[] xNew = new double[x.length];
    final double[] yNew = new double[y.length];
    System.arraycopy(x, 0, xNew, 0, x.length);
    System.arraycopy(y, 0, yNew, 0, y.length);

    MathArrays.sortInPlace(xNew, yNew);
    // Second check in case some abscissa is duplicated.
    verifyInterpolationArray(xNew, yNew, true);
    return evaluateInternal(xNew, yNew, z);
}
 
Example #20
Source File: FieldRotation.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Build the rotation that transforms a pair of vector into another pair.

     * <p>Except for possible scale factors, if the instance were applied to
     * the pair (u<sub>1</sub>, u<sub>2</sub>) it will produce the pair
     * (v<sub>1</sub>, v<sub>2</sub>).</p>

     * <p>If the angular separation between u<sub>1</sub> and u<sub>2</sub> is
     * not the same as the angular separation between v<sub>1</sub> and
     * v<sub>2</sub>, then a corrected v'<sub>2</sub> will be used rather than
     * v<sub>2</sub>, the corrected vector will be in the (v<sub>1</sub>,
     * v<sub>2</sub>) plane.</p>

     * @param u1 first vector of the origin pair
     * @param u2 second vector of the origin pair
     * @param v1 desired image of u1 by the rotation
     * @param v2 desired image of u2 by the rotation
     * @exception MathArithmeticException if the norm of one of the vectors is zero,
     * or if one of the pair is degenerated (i.e. the vectors of the pair are colinear)
     */
    public FieldRotation(FieldVector3D<T> u1, FieldVector3D<T> u2, FieldVector3D<T> v1, FieldVector3D<T> v2)
        throws MathArithmeticException {

        // build orthonormalized base from u1, u2
        // this fails when vectors are null or colinear, which is forbidden to define a rotation
        final FieldVector3D<T> u3 = FieldVector3D.crossProduct(u1, u2).normalize();
        u2 = FieldVector3D.crossProduct(u3, u1).normalize();
        u1 = u1.normalize();

        // build an orthonormalized base from v1, v2
        // this fails when vectors are null or colinear, which is forbidden to define a rotation
        final FieldVector3D<T> v3 = FieldVector3D.crossProduct(v1, v2).normalize();
        v2 = FieldVector3D.crossProduct(v3, v1).normalize();
        v1 = v1.normalize();

        // buid a matrix transforming the first base into the second one
        final T[][] array = MathArrays.buildArray(u1.getX().getField(), 3, 3);
        array[0][0] = u1.getX().multiply(v1.getX()).add(u2.getX().multiply(v2.getX())).add(u3.getX().multiply(v3.getX()));
        array[0][1] = u1.getY().multiply(v1.getX()).add(u2.getY().multiply(v2.getX())).add(u3.getY().multiply(v3.getX()));
        array[0][2] = u1.getZ().multiply(v1.getX()).add(u2.getZ().multiply(v2.getX())).add(u3.getZ().multiply(v3.getX()));
        array[1][0] = u1.getX().multiply(v1.getY()).add(u2.getX().multiply(v2.getY())).add(u3.getX().multiply(v3.getY()));
        array[1][1] = u1.getY().multiply(v1.getY()).add(u2.getY().multiply(v2.getY())).add(u3.getY().multiply(v3.getY()));
        array[1][2] = u1.getZ().multiply(v1.getY()).add(u2.getZ().multiply(v2.getY())).add(u3.getZ().multiply(v3.getY()));
        array[2][0] = u1.getX().multiply(v1.getZ()).add(u2.getX().multiply(v2.getZ())).add(u3.getX().multiply(v3.getZ()));
        array[2][1] = u1.getY().multiply(v1.getZ()).add(u2.getY().multiply(v2.getZ())).add(u3.getY().multiply(v3.getZ()));
        array[2][2] = u1.getZ().multiply(v1.getZ()).add(u2.getZ().multiply(v2.getZ())).add(u3.getZ().multiply(v3.getZ()));

        T[] quat = mat2quat(array);
        q0 = quat[0];
        q1 = quat[1];
        q2 = quat[2];
        q3 = quat[3];

    }
 
Example #21
Source File: ArrayFieldVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Element-by-element multiplication.
 * @param v vector by which instance elements must be multiplied
 * @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}
 */
public ArrayFieldVector<T> ebeMultiply(ArrayFieldVector<T> v)
    throws DimensionMismatchException {
    checkVectorDimensions(v.data.length);
    T[] out = MathArrays.buildArray(field, data.length);
    for (int i = 0; i < data.length; i++) {
        out[i] = data[i].multiply(v.data[i]);
    }
    return new ArrayFieldVector<T>(field, out, false);
}
 
Example #22
Source File: ConvexHull2D.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks whether the given hull vertices form a convex hull.
 * @param hullVertices the hull vertices
 * @return {@code true} if the vertices form a convex hull, {@code false} otherwise
 */
private boolean isConvex(final Vector2D[] hullVertices) {
    if (hullVertices.length < 3) {
        return true;
    }

    int sign = 0;
    for (int i = 0; i < hullVertices.length; i++) {
        final Vector2D p1 = hullVertices[i == 0 ? hullVertices.length - 1 : i - 1];
        final Vector2D p2 = hullVertices[i];
        final Vector2D p3 = hullVertices[i == hullVertices.length - 1 ? 0 : i + 1];

        final Vector2D d1 = p2.subtract(p1);
        final Vector2D d2 = p3.subtract(p2);

        final double crossProduct = MathArrays.linearCombination(d1.getX(), d2.getY(), -d1.getY(), d2.getX());
        final int cmp = Precision.compareTo(crossProduct, 0.0, tolerance);
        // in case of collinear points the cross product will be zero
        if (cmp != 0.0) {
            if (sign != 0.0 && cmp != sign) {
                return false;
            }
            sign = cmp;
        }
    }

    return true;
}
 
Example #23
Source File: FieldVector3D.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the vector coordinates as a dimension 3 array.
 * @return vector coordinates
 * @see #FieldVector3D(RealFieldElement[])
 */
public T[] toArray() {
    final T[] array = MathArrays.buildArray(x.getField(), 3);
    array[0] = x;
    array[1] = y;
    array[2] = z;
    return array;
}
 
Example #24
Source File: ArrayFieldVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public FieldVector<T> mapAdd(T d) throws NullArgumentException {
    T[] out = MathArrays.buildArray(field, data.length);
    for (int i = 0; i < data.length; i++) {
        out[i] = data[i].add(d);
    }
    return new ArrayFieldVector<T>(field, out, false);
}
 
Example #25
Source File: Vector3D.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Compute the cross-product of the instance with another vector.
 * @param v other vector
 * @return the cross product this ^ v as a new Vector3D
 */
public Vector3D crossProduct(final Vector<Euclidean3D> v) {
    final Vector3D v3 = (Vector3D) v;
    return new Vector3D(MathArrays.linearCombination(y, v3.z, -z, v3.y),
                        MathArrays.linearCombination(z, v3.x, -x, v3.z),
                        MathArrays.linearCombination(x, v3.y, -y, v3.x));
}
 
Example #26
Source File: ArrayFieldVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public FieldVector<T> append(T in) {
    final T[] out = MathArrays.buildArray(field, data.length + 1);
    System.arraycopy(data, 0, out, 0, data.length);
    out[data.length] = in;
    return new ArrayFieldVector<T>(field, out, false);
}
 
Example #27
Source File: Array2DRowFieldMatrix.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void setSubMatrix(final T[][] subMatrix, final int row,
                         final int column)
    throws OutOfRangeException, NullArgumentException, NoDataException,
    DimensionMismatchException {
    if (data == null) {
        if (row > 0) {
            throw new MathIllegalStateException(LocalizedFormats.FIRST_ROWS_NOT_INITIALIZED_YET, row);
        }
        if (column > 0) {
            throw new MathIllegalStateException(LocalizedFormats.FIRST_COLUMNS_NOT_INITIALIZED_YET, column);
        }
        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);
        }
        data = MathArrays.buildArray(getField(), subMatrix.length, nCols);
        for (int i = 0; i < data.length; ++i) {
            if (subMatrix[i].length != nCols) {
                throw new DimensionMismatchException(nCols, subMatrix[i].length);
            }
            System.arraycopy(subMatrix[i], 0, data[i + row], column, nCols);
        }
    } else {
        super.setSubMatrix(subMatrix, row, column);
    }

}
 
Example #28
Source File: DerivativeStructure.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc}
 * @exception DimensionMismatchException if number of free parameters
 * or orders do not match
 * @since 3.2
 */
public DerivativeStructure linearCombination(final DerivativeStructure[] a, final DerivativeStructure[] b)
    throws DimensionMismatchException {

    // compute an accurate value, taking care of cancellations
    final double[] aDouble = new double[a.length];
    for (int i = 0; i < a.length; ++i) {
        aDouble[i] = a[i].getValue();
    }
    final double[] bDouble = new double[b.length];
    for (int i = 0; i < b.length; ++i) {
        bDouble[i] = b[i].getValue();
    }
    final double accurateValue = MathArrays.linearCombination(aDouble, bDouble);

    // compute a simple value, with all partial derivatives
    DerivativeStructure simpleValue = a[0].getField().getZero();
    for (int i = 0; i < a.length; ++i) {
        simpleValue = simpleValue.add(a[i].multiply(b[i]));
    }

    // create a result with accurate value and all derivatives (not necessarily as accurate as the value)
    final double[] all = simpleValue.getAllDerivatives();
    all[0] = accurateValue;
    return new DerivativeStructure(simpleValue.getFreeParameters(), simpleValue.getOrder(), all);

}
 
Example #29
Source File: JacobiPreconditioner.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public RealVector operate(final RealVector x) {
    // Dimension check is carried out by ebeDivide
    return new ArrayRealVector(MathArrays.ebeDivide(x.toArray(),
                                                    diag.toArray()),
                               false);
}
 
Example #30
Source File: ExtendedFieldElementAbstractTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testLinearCombinationFF4() {
    RandomGenerator r = new Well1024a(0xff4l);
    for (int i = 0; i < 50; ++i) {
        double[] aD = generateDouble(r, 4);
        double[] bD = generateDouble(r, 4);
        T[] aF      = toFieldArray(aD);
        T[] bF      = toFieldArray(bD);
        checkRelative(MathArrays.linearCombination(aD[0], bD[0], aD[1], bD[1], aD[2], bD[2], aD[3], bD[3]),
                      aF[0].linearCombination(aF[0], bF[0], aF[1], bF[1], aF[2], bF[2], aF[3], bF[3]));
    }
}