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

The following examples show how to use org.apache.commons.math3.exception.MathIllegalArgumentException. 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: BinaryMutation.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Mutate the given chromosome. Randomly changes one gene.
 *
 * @param original the original chromosome.
 * @return the mutated chromosome.
 * @throws MathIllegalArgumentException if <code>original</code> is not an instance of {@link BinaryChromosome}.
 */
public Chromosome mutate(Chromosome original) throws MathIllegalArgumentException {
    if (!(original instanceof BinaryChromosome)) {
        throw new MathIllegalArgumentException(LocalizedFormats.INVALID_BINARY_CHROMOSOME);
    }

    BinaryChromosome origChrom = (BinaryChromosome) original;
    List<Integer> newRepr = new ArrayList<Integer>(origChrom.getRepresentation());

    // randomly select a gene
    int geneIndex = GeneticAlgorithm.getRandomGenerator().nextInt(origChrom.getLength());
    // and change it
    newRepr.set(geneIndex, origChrom.getRepresentation().get(geneIndex) == 0 ? 1 : 0);

    Chromosome newChrom = origChrom.newFixedLengthChromosome(newRepr);
    return newChrom;
}
 
Example #2
Source File: BlockFieldMatrixTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testPremultiply() {
    FieldMatrix<Fraction> m3 = new BlockFieldMatrix<Fraction>(d3);
    FieldMatrix<Fraction> m4 = new BlockFieldMatrix<Fraction>(d4);
    FieldMatrix<Fraction> m5 = new BlockFieldMatrix<Fraction>(d5);
    TestUtils.assertEquals(m4.preMultiply(m3), m5);

    BlockFieldMatrix<Fraction> m = new BlockFieldMatrix<Fraction>(testData);
    BlockFieldMatrix<Fraction> mInv = new BlockFieldMatrix<Fraction>(testDataInv);
    BlockFieldMatrix<Fraction> identity = new BlockFieldMatrix<Fraction>(id);
    TestUtils.assertEquals(m.preMultiply(mInv), identity);
    TestUtils.assertEquals(mInv.preMultiply(m), identity);
    TestUtils.assertEquals(m.preMultiply(identity), m);
    TestUtils.assertEquals(identity.preMultiply(mInv), mInv);
    try {
        m.preMultiply(new BlockFieldMatrix<Fraction>(bigSingular));
        Assert.fail("Expecting illegalArgumentException");
    } catch (MathIllegalArgumentException ex) {
        // ignored
    }
}
 
Example #3
Source File: RootsOfUnity.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the real part of the {@code k}-th {@code n}-th root of unity.
 *
 * @param k index of the {@code n}-th root of unity
 * @return real part of the {@code k}-th {@code n}-th root of unity
 * @throws MathIllegalStateException if no roots of unity have been
 * computed yet
 * @throws MathIllegalArgumentException if {@code k} is out of range
 */
public synchronized double getReal(int k)
        throws MathIllegalStateException, MathIllegalArgumentException {

    if (omegaCount == 0) {
        throw new MathIllegalStateException(
                LocalizedFormats.ROOTS_OF_UNITY_NOT_COMPUTED_YET);
    }
    if ((k < 0) || (k >= omegaCount)) {
        throw new OutOfRangeException(
                LocalizedFormats.OUT_OF_RANGE_ROOT_OF_UNITY_INDEX,
                Integer.valueOf(k),
                Integer.valueOf(0),
                Integer.valueOf(omegaCount - 1));
    }

    return omegaReal[k];
}
 
Example #4
Source File: RotationTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testQuaternion() throws MathIllegalArgumentException {

  Rotation r1 = new Rotation(new Vector3D(2, -3, 5), 1.7);
  double n = 23.5;
  Rotation r2 = new Rotation(n * r1.getQ0(), n * r1.getQ1(),
                             n * r1.getQ2(), n * r1.getQ3(),
                             true);
  for (double x = -0.9; x < 0.9; x += 0.2) {
    for (double y = -0.9; y < 0.9; y += 0.2) {
      for (double z = -0.9; z < 0.9; z += 0.2) {
        Vector3D u = new Vector3D(x, y, z);
        checkVector(r2.applyTo(u), r1.applyTo(u));
      }
    }
  }

  r1 = new Rotation( 0.288,  0.384,  0.36,  0.8, false);
  checkRotation(r1, -r1.getQ0(), -r1.getQ1(), -r1.getQ2(), -r1.getQ3());

}
 
Example #5
Source File: ResizableDoubleArray.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This function allows you to control the number of elements contained
 * in this array, and can be used to "throw out" the last n values in an
 * array. This function will also expand the internal array as needed.
 *
 * @param i a new number of elements
 * @throws MathIllegalArgumentException if <code>i</code> is negative.
 */
public synchronized void setNumElements(int i)
    throws MathIllegalArgumentException {
    // If index is negative thrown an error.
    if (i < 0) {
        throw new MathIllegalArgumentException(
                LocalizedFormats.INDEX_NOT_POSITIVE,
                i);
    }

    // Test the new num elements, check to see if the array needs to be
    // expanded to accommodate this new number of elements.
    final int newSize = startIndex + i;
    if (newSize > internalArray.length) {
        expandTo(newSize);
    }

    // Set the new number of elements to new value.
    numElements = i;
}
 
Example #6
Source File: FastFourierTransformerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testTransformComplexSizeNotAPowerOfTwo() {
    final int n = 127;
    final Complex[] x = createComplexData(n);
    final DftNormalization[] norm;
    norm = DftNormalization.values();
    final TransformType[] type;
    type = TransformType.values();
    for (int i = 0; i < norm.length; i++) {
        for (int j = 0; j < type.length; j++) {
            final FastFourierTransformer fft;
            fft = new FastFourierTransformer(norm[i]);
            try {
                fft.transform(x, type[j]);
                Assert.fail(norm[i] + ", " + type[j] +
                    ": MathIllegalArgumentException was expected");
            } catch (MathIllegalArgumentException e) {
                // Expected behaviour
            }
        }
    }
}
 
Example #7
Source File: ListUnivariateImpl.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public double getElement(int index) {

    double value = Double.NaN;

    int calcIndex = index;

    final int wSize = getWindowSize();
    if (wSize != DescriptiveStatistics.INFINITE_WINDOW && wSize < list.size()) {
        calcIndex = (list.size() - wSize) + index;
    }


    try {
        value = transformer.transform(list.get(calcIndex));
    } catch (MathIllegalArgumentException e) {
        e.printStackTrace();
    }

    return value;
}
 
Example #8
Source File: BinaryMutation.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Mutate the given chromosome. Randomly changes one gene.
 *
 * @param original the original chromosome.
 * @return the mutated chromosome.
 * @throws MathIllegalArgumentException if <code>original</code> is not an instance of {@link BinaryChromosome}.
 */
public Chromosome mutate(Chromosome original) throws MathIllegalArgumentException {
    if (!(original instanceof BinaryChromosome)) {
        throw new MathIllegalArgumentException(LocalizedFormats.INVALID_BINARY_CHROMOSOME);
    }

    BinaryChromosome origChrom = (BinaryChromosome) original;
    List<Integer> newRepr = new ArrayList<Integer>(origChrom.getRepresentation());

    // randomly select a gene
    int geneIndex = GeneticAlgorithm.getRandomGenerator().nextInt(origChrom.getLength());
    // and change it
    newRepr.set(geneIndex, origChrom.getRepresentation().get(geneIndex) == 0 ? 1 : 0);

    Chromosome newChrom = origChrom.newFixedLengthChromosome(newRepr);
    return newChrom;
}
 
Example #9
Source File: DescriptiveStatistics.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the implementation to be used by {@link #getPercentile(double)}.
 * The supplied <code>UnivariateStatistic</code> must provide a
 * <code>setQuantile(double)</code> method; otherwise
 * <code>IllegalArgumentException</code> is thrown.
 *
 * @param percentileImpl the percentileImpl to set
 * @throws MathIllegalArgumentException if the supplied implementation does not
 *  provide a <code>setQuantile</code> method
 * @since 1.2
 */
public synchronized void setPercentileImpl(UnivariateStatistic percentileImpl)
throws MathIllegalArgumentException {
    try {
        percentileImpl.getClass().getMethod(SET_QUANTILE_METHOD_NAME,
                new Class[] {Double.TYPE}).invoke(percentileImpl,
                        new Object[] {Double.valueOf(50.0d)});
    } catch (NoSuchMethodException e1) {
        throw new MathIllegalArgumentException(
              LocalizedFormats.PERCENTILE_IMPLEMENTATION_UNSUPPORTED_METHOD,
              percentileImpl.getClass().getName(), SET_QUANTILE_METHOD_NAME);
    } catch (IllegalAccessException e2) {
        throw new MathIllegalArgumentException(
              LocalizedFormats.PERCENTILE_IMPLEMENTATION_CANNOT_ACCESS_METHOD,
              SET_QUANTILE_METHOD_NAME, percentileImpl.getClass().getName());
    } catch (InvocationTargetException e3) {
        throw new IllegalArgumentException(e3.getCause());
    }
    this.percentileImpl = percentileImpl;
}
 
Example #10
Source File: SparseFieldMatrixTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** test operate */
@Test
public void testOperate() {
    FieldMatrix<Fraction> m = createSparseMatrix(id);
    assertClose("identity operate", testVector, m.operate(testVector),
            entryTolerance);
    assertClose("identity operate", testVector, m.operate(
            new ArrayFieldVector<Fraction>(testVector)).toArray(), entryTolerance);
    m = createSparseMatrix(bigSingular);
    try {
        m.operate(testVector);
        Assert.fail("Expecting illegalArgumentException");
    } catch (MathIllegalArgumentException ex) {
        // ignored
    }
}
 
Example #11
Source File: RandomDataTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** test failure modes and distribution of nextGaussian() */
@Test
public void testNextGaussian() {
    try {
        randomData.nextGaussian(0, 0);
        Assert.fail("zero sigma -- MathIllegalArgumentException expected");
    } catch (MathIllegalArgumentException ex) {
        // ignored
    }
    SummaryStatistics u = new SummaryStatistics();
    for (int i = 0; i < largeSampleSize; i++) {
        u.addValue(randomData.nextGaussian(0, 1));
    }
    double xbar = u.getMean();
    double s = u.getStandardDeviation();
    double n = u.getN();
    /*
     * t-test at .001-level TODO: replace with externalized t-test, with
     * test statistic defined in TestStatistic
     */
    Assert.assertTrue(FastMath.abs(xbar) / (s / FastMath.sqrt(n)) < 3.29);
}
 
Example #12
Source File: Covariance.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compute a covariance matrix from a matrix whose columns represent
 * covariates.
 * @param matrix input matrix (must have at least one column and two rows)
 * @param biasCorrected determines whether or not covariance estimates are bias-corrected
 * @return covariance matrix
 * @throws MathIllegalArgumentException if the matrix does not contain sufficient data
 */
protected RealMatrix computeCovarianceMatrix(RealMatrix matrix, boolean biasCorrected)
throws MathIllegalArgumentException {
    int dimension = matrix.getColumnDimension();
    Variance variance = new Variance(biasCorrected);
    RealMatrix outMatrix = new BlockRealMatrix(dimension, dimension);
    for (int i = 0; i < dimension; i++) {
        for (int j = 0; j < i; j++) {
          double cov = covariance(matrix.getColumn(i), matrix.getColumn(j), biasCorrected);
          outMatrix.setEntry(i, j, cov);
          outMatrix.setEntry(j, i, cov);
        }
        outMatrix.setEntry(i, i, variance.evaluate(matrix.getColumn(i)));
    }
    return outMatrix;
}
 
Example #13
Source File: DescriptiveStatistics.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the implementation to be used by {@link #getPercentile(double)}.
 * The supplied <code>UnivariateStatistic</code> must provide a
 * <code>setQuantile(double)</code> method; otherwise
 * <code>IllegalArgumentException</code> is thrown.
 *
 * @param percentileImpl the percentileImpl to set
 * @throws MathIllegalArgumentException if the supplied implementation does not
 *  provide a <code>setQuantile</code> method
 * @since 1.2
 */
public synchronized void setPercentileImpl(UnivariateStatistic percentileImpl)
throws MathIllegalArgumentException {
    try {
        percentileImpl.getClass().getMethod(SET_QUANTILE_METHOD_NAME,
                new Class[] {Double.TYPE}).invoke(percentileImpl,
                        new Object[] {Double.valueOf(50.0d)});
    } catch (NoSuchMethodException e1) {
        throw new MathIllegalArgumentException(
              LocalizedFormats.PERCENTILE_IMPLEMENTATION_UNSUPPORTED_METHOD,
              percentileImpl.getClass().getName(), SET_QUANTILE_METHOD_NAME);
    } catch (IllegalAccessException e2) {
        throw new MathIllegalArgumentException(
              LocalizedFormats.PERCENTILE_IMPLEMENTATION_CANNOT_ACCESS_METHOD,
              SET_QUANTILE_METHOD_NAME, percentileImpl.getClass().getName());
    } catch (InvocationTargetException e3) {
        throw new IllegalArgumentException(e3.getCause());
    }
    this.percentileImpl = percentileImpl;
}
 
Example #14
Source File: FractionFormat.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats an object and appends the result to a StringBuffer. <code>obj</code> must be either a
 * {@link Fraction} object or a {@link Number} object.  Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws FractionConversionException if the number cannot be converted to a fraction
 * @throws MathIllegalArgumentException if <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(final Object obj,
                           final StringBuffer toAppendTo, final FieldPosition pos)
    throws FractionConversionException, MathIllegalArgumentException {
    StringBuffer ret = null;

    if (obj instanceof Fraction) {
        ret = format((Fraction) obj, toAppendTo, pos);
    } else if (obj instanceof Number) {
        ret = format(new Fraction(((Number) obj).doubleValue()), toAppendTo, pos);
    } else {
        throw new MathIllegalArgumentException(LocalizedFormats.CANNOT_FORMAT_OBJECT_TO_FRACTION);
    }

    return ret;
}
 
Example #15
Source File: SparseFieldMatrixTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** test multiply */
@Test
public void testMultiply() {
    SparseFieldMatrix<Fraction> m = createSparseMatrix(testData);
    SparseFieldMatrix<Fraction> mInv = createSparseMatrix(testDataInv);
    SparseFieldMatrix<Fraction> identity = createSparseMatrix(id);
    SparseFieldMatrix<Fraction> m2 = createSparseMatrix(testData2);
    assertClose("inverse multiply", m.multiply(mInv), identity,
            entryTolerance);
    assertClose("inverse multiply", m.multiply(new Array2DRowFieldMatrix<Fraction>(FractionField.getInstance(), testDataInv)), identity,
                entryTolerance);
    assertClose("inverse multiply", mInv.multiply(m), identity,
            entryTolerance);
    assertClose("identity multiply", m.multiply(identity), m,
            entryTolerance);
    assertClose("identity multiply", identity.multiply(mInv), mInv,
            entryTolerance);
    assertClose("identity multiply", m2.multiply(identity), m2,
            entryTolerance);
    try {
        m.multiply(createSparseMatrix(bigSingular));
        Assert.fail("Expecting illegalArgumentException");
    } catch (MathIllegalArgumentException ex) {
        // ignored
    }
}
 
Example #16
Source File: ListUnivariateImpl.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public double getElement(int index) {

    double value = Double.NaN;

    int calcIndex = index;

    final int wSize = getWindowSize();
    if (wSize != DescriptiveStatistics.INFINITE_WINDOW && wSize < list.size()) {
        calcIndex = (list.size() - wSize) + index;
    }


    try {
        value = transformer.transform(list.get(calcIndex));
    } catch (MathIllegalArgumentException e) {
        e.printStackTrace();
    }

    return value;
}
 
Example #17
Source File: BlockFieldMatrixTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** test multiply */
@Test
public void testMultiply() {
    BlockFieldMatrix<Fraction> m = new BlockFieldMatrix<Fraction>(testData);
    BlockFieldMatrix<Fraction> mInv = new BlockFieldMatrix<Fraction>(testDataInv);
    BlockFieldMatrix<Fraction> identity = new BlockFieldMatrix<Fraction>(id);
    BlockFieldMatrix<Fraction> m2 = new BlockFieldMatrix<Fraction>(testData2);
    TestUtils.assertEquals(m.multiply(mInv), identity);
    TestUtils.assertEquals(mInv.multiply(m), identity);
    TestUtils.assertEquals(m.multiply(identity), m);
    TestUtils.assertEquals(identity.multiply(mInv), mInv);
    TestUtils.assertEquals(m2.multiply(identity), m2);
    try {
        m.multiply(new BlockFieldMatrix<Fraction>(bigSingular));
        Assert.fail("Expecting illegalArgumentException");
    } catch (MathIllegalArgumentException ex) {
        // expected
    }
}
 
Example #18
Source File: FieldMatrixImplTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testPremultiply() {
    FieldMatrix<Fraction> m3 = new Array2DRowFieldMatrix<Fraction>(d3);
    FieldMatrix<Fraction> m4 = new Array2DRowFieldMatrix<Fraction>(d4);
    FieldMatrix<Fraction> m5 = new Array2DRowFieldMatrix<Fraction>(d5);
    TestUtils.assertEquals(m4.preMultiply(m3), m5);

    Array2DRowFieldMatrix<Fraction> m = new Array2DRowFieldMatrix<Fraction>(testData);
    Array2DRowFieldMatrix<Fraction> mInv = new Array2DRowFieldMatrix<Fraction>(testDataInv);
    Array2DRowFieldMatrix<Fraction> identity = new Array2DRowFieldMatrix<Fraction>(id);
    TestUtils.assertEquals(m.preMultiply(mInv), identity);
    TestUtils.assertEquals(mInv.preMultiply(m), identity);
    TestUtils.assertEquals(m.preMultiply(identity), m);
    TestUtils.assertEquals(identity.preMultiply(mInv), mInv);
    try {
        m.preMultiply(new Array2DRowFieldMatrix<Fraction>(bigSingular));
        Assert.fail("Expecting illegalArgumentException");
    } catch (MathIllegalArgumentException ex) {
        // ignored
    }
}
 
Example #19
Source File: LineTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testTransform() throws MathIllegalArgumentException {

    Line l1 = new Line(new Vector2D(1.0 ,1.0), new Vector2D(4.0 ,1.0), 1.0e-10);
    Transform<Euclidean2D, Euclidean1D> t1 =
        Line.getTransform(new AffineTransform(0.0, 0.5, -1.0, 0.0, 1.0, 1.5));
    Assert.assertEquals(0.5 * FastMath.PI,
                        ((Line) t1.apply(l1)).getAngle(),
                        1.0e-10);

    Line l2 = new Line(new Vector2D(0.0, 0.0), new Vector2D(1.0, 1.0), 1.0e-10);
    Transform<Euclidean2D, Euclidean1D> t2 =
        Line.getTransform(new AffineTransform(0.0, 0.5, -1.0, 0.0, 1.0, 1.5));
    Assert.assertEquals(FastMath.atan2(1.0, -2.0),
                        ((Line) t2.apply(l2)).getAngle(),
                        1.0e-10);

}
 
Example #20
Source File: FractionFormat.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats an object and appends the result to a StringBuffer. <code>obj</code> must be either a
 * {@link Fraction} object or a {@link Number} object.  Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws FractionConversionException if the number cannot be converted to a fraction
 * @throws MathIllegalArgumentException if <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(final Object obj,
                           final StringBuffer toAppendTo, final FieldPosition pos)
    throws FractionConversionException, MathIllegalArgumentException {
    StringBuffer ret = null;

    if (obj instanceof Fraction) {
        ret = format((Fraction) obj, toAppendTo, pos);
    } else if (obj instanceof Number) {
        ret = format(new Fraction(((Number) obj).doubleValue()), toAppendTo, pos);
    } else {
        throw new MathIllegalArgumentException(LocalizedFormats.CANNOT_FORMAT_OBJECT_TO_FRACTION);
    }

    return ret;
}
 
Example #21
Source File: Line.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Build an affine line transform from a n {@code AffineTransform}.
 * @param transform transform to use (must be invertible otherwise
 * the {@link LineTransform#apply(Hyperplane)} method would work
 * only for some lines, and fail for other ones)
 * @exception MathIllegalArgumentException if the transform is non invertible
 */
public LineTransform(final AffineTransform transform) throws MathIllegalArgumentException {

    final double[] m = new double[6];
    transform.getMatrix(m);
    cXX = m[0];
    cXY = m[2];
    cX1 = m[4];
    cYX = m[1];
    cYY = m[3];
    cY1 = m[5];

    c1Y = cXY * cY1 - cYY * cX1;
    c1X = cXX * cY1 - cYX * cX1;
    c11 = cXX * cYY - cYX * cXY;

    if (FastMath.abs(c11) < 1.0e-20) {
        throw new MathIllegalArgumentException(LocalizedFormats.NON_INVERTIBLE_TRANSFORM);
    }

}
 
Example #22
Source File: RandomDataGeneratorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** test failure modes and distribution of nextGaussian() */
@Test
public void testNextGaussian() {
    try {
        randomData.nextGaussian(0, 0);
        Assert.fail("zero sigma -- MathIllegalArgumentException expected");
    } catch (MathIllegalArgumentException ex) {
        // ignored
    }
    double[] quartiles = TestUtils.getDistributionQuartiles(new NormalDistribution(0,1));
    long[] counts = new long[4];
    randomData.reSeed(1000);
    for (int i = 0; i < 1000; i++) {
        double value = randomData.nextGaussian(0, 1);
        TestUtils.updateCounts(value, counts, quartiles);
    }
    TestUtils.assertChiSquareAccept(expected, counts, 0.001);
}
 
Example #23
Source File: FieldMatrixImplTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** test multiply */
@Test
 public void testMultiply() {
    Array2DRowFieldMatrix<Fraction> m = new Array2DRowFieldMatrix<Fraction>(testData);
    Array2DRowFieldMatrix<Fraction> mInv = new Array2DRowFieldMatrix<Fraction>(testDataInv);
    Array2DRowFieldMatrix<Fraction> identity = new Array2DRowFieldMatrix<Fraction>(id);
    Array2DRowFieldMatrix<Fraction> m2 = new Array2DRowFieldMatrix<Fraction>(testData2);
    TestUtils.assertEquals(m.multiply(mInv), identity);
    TestUtils.assertEquals(mInv.multiply(m), identity);
    TestUtils.assertEquals(m.multiply(identity), m);
    TestUtils.assertEquals(identity.multiply(mInv), mInv);
    TestUtils.assertEquals(m2.multiply(identity), m2);
    try {
        m.multiply(new Array2DRowFieldMatrix<Fraction>(bigSingular));
        Assert.fail("Expecting illegalArgumentException");
    } catch (MathIllegalArgumentException ex) {
        // ignored
    }
}
 
Example #24
Source File: NPEfix_00183_t.java    From coming with MIT License 5 votes vote down vote up
/** Reset the instance as if built from two points.
 * @param p1 first point belonging to the line (this can be any point)
 * @param p2 second point belonging to the line (this can be any point, different from p1)
 * @exception MathIllegalArgumentException if the points are equal
 */
public void reset(final Vector3D p1, final Vector3D p2) throws MathIllegalArgumentException {
    final Vector3D delta = p2.subtract(p1);
    final double norm2 = delta.getNormSq();
    if (norm2 == 0.0) {
        throw new MathIllegalArgumentException(LocalizedFormats.ZERO_NORM);
    }
    this.direction = new Vector3D(1.0 / FastMath.sqrt(norm2), delta);
    zero = new Vector3D(1.0, p1, -p1.dotProduct(delta) / norm2, delta);
}
 
Example #25
Source File: SemiVariance.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
  * <p>Returns the {@link SemiVariance} of the designated values against the cutoff
  * in the given direction with the provided bias correction.</p>
  *
  * <p>Returns <code>NaN</code> if the array is empty and throws
  * <code>IllegalArgumentException</code> if the array is null.</p>
  *
  * @param values the input array
  * @param cutoff the reference point
  * @param direction the {@link Direction} of the semivariance
  * @param corrected the BiasCorrection flag
  * @param start index of the first array element to include
  * @param length the number of elements to include
  * @return the SemiVariance
  * @throws MathIllegalArgumentException if the parameters are not valid
  *
  */
public double evaluate (final double[] values, final double cutoff, final Direction direction,
        final boolean corrected, final int start, final int length) throws MathIllegalArgumentException {

    test(values, start, length);
    if (values.length == 0) {
        return Double.NaN;
    } else {
        if (values.length == 1) {
            return 0.0;
        } else {
            final boolean booleanDirection = direction.getDirection();

            double dev = 0.0;
            double sumsq = 0.0;
            for (int i = start; i < length; i++) {
                if ((values[i] > cutoff) == booleanDirection) {
                   dev = values[i] - cutoff;
                   sumsq += dev * dev;
                }
            }

            if (corrected) {
                return sumsq / (length - 1.0);
            } else {
                return sumsq / length;
            }
        }
    }
}
 
Example #26
Source File: UniformCrossoverTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected = MathIllegalArgumentException.class)
public void testCrossoverInvalidFixedLengthChromosomeFirst() {
    @SuppressWarnings("boxing")
    final Integer[] p1 = new Integer[] {1,0,1,0,0,1,0,1,1};
    final BinaryChromosome p1c = new DummyBinaryChromosome(p1);
    final Chromosome p2c = new Chromosome() {
        public double fitness() {
            // Not important
            return 0;
        }
    };

    final CrossoverPolicy cp = new UniformCrossover<Integer>(0.5d);
    cp.crossover(p1c, p2c);
}
 
Example #27
Source File: MathArrays.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Normalizes an array to make it sum to a specified value.
 * Returns the result of the transformation <pre>
 *    x |-> x * normalizedSum / sum
 * </pre>
 * applied to each non-NaN element x of the input array, where sum is the
 * sum of the non-NaN entries in the input array.</p>
 *
 * <p>Throws IllegalArgumentException if {@code normalizedSum} is infinite
 * or NaN and ArithmeticException if the input array contains any infinite elements
 * or sums to 0.</p>
 *
 * <p>Ignores (i.e., copies unchanged to the output array) NaNs in the input array.</p>
 *
 * @param values Input array to be normalized
 * @param normalizedSum Target sum for the normalized array
 * @return the normalized array.
 * @throws MathArithmeticException if the input array contains infinite
 * elements or sums to zero.
 * @throws MathIllegalArgumentException if the target sum is infinite or {@code NaN}.
 * @since 2.1
 */
public static double[] normalizeArray(double[] values, double normalizedSum)
    throws MathIllegalArgumentException, MathArithmeticException {
    if (Double.isInfinite(normalizedSum)) {
        throw new MathIllegalArgumentException(LocalizedFormats.NORMALIZE_INFINITE);
    }
    if (Double.isNaN(normalizedSum)) {
        throw new MathIllegalArgumentException(LocalizedFormats.NORMALIZE_NAN);
    }
    double sum = 0d;
    final int len = values.length;
    double[] out = new double[len];
    for (int i = 0; i < len; i++) {
        if (Double.isInfinite(values[i])) {
            throw new MathIllegalArgumentException(LocalizedFormats.INFINITE_ARRAY_ELEMENT, values[i], i);
        }
        if (!Double.isNaN(values[i])) {
            sum += values[i];
        }
    }
    if (sum == 0) {
        throw new MathArithmeticException(LocalizedFormats.ARRAY_SUMS_TO_ZERO);
    }
    for (int i = 0; i < len; i++) {
        if (Double.isNaN(values[i])) {
            out[i] = Double.NaN;
        } else {
            out[i] = values[i] * normalizedSum / sum;
        }
    }
    return out;
}
 
Example #28
Source File: StatUtilsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPopulationVariance() {
    double[] x = null;

    try {
        StatUtils.variance(x, 0, 4);
        Assert.fail("null is not a valid data array.");
    } catch (MathIllegalArgumentException ex) {
        // success
    }

    // test empty
    x = new double[] {};
    TestUtils.assertEquals(Double.NaN, StatUtils.populationVariance(x, 0, 0), tolerance);

    // test one
    x = new double[] {two};
    TestUtils.assertEquals(0.0, StatUtils.populationVariance(x, 0, 1), tolerance);

    // test many
    x = new double[] {one, two, two, three};
    TestUtils.assertEquals(0.25, StatUtils.populationVariance(x, 0, 2), tolerance);

    // test precomputed mean
    x = new double[] {one, two, two, three};
    TestUtils.assertEquals(0.25, StatUtils.populationVariance(x, 2.5, 2, 2), tolerance);
}
 
Example #29
Source File: CycleCrossoverTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected = MathIllegalArgumentException.class)
public void testCrossoverInvalidFixedLengthChromosomeFirst() {
    final Integer[] p1 = new Integer[] { 1, 0, 1, 0, 0, 1, 0, 1, 1 };
    final BinaryChromosome p1c = new DummyBinaryChromosome(p1);
    final Chromosome p2c = new Chromosome() {
        public double fitness() {
            // Not important
            return 0;
        }
    };

    final CrossoverPolicy cp = new CycleCrossover<Integer>();
    cp.crossover(p1c, p2c);
}
 
Example #30
Source File: GaussianFitterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Two points is not enough observed points.
 */
@Test(expected=MathIllegalArgumentException.class)
public void testFit03() {
    GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
    addDatasetToGaussianFitter(new double[][] {
        {4.0254623,  531026.0},
        {4.02804905, 664002.0}},
        fitter);
    fitter.fit();
}