Java源码示例:org.apache.commons.math.FunctionEvaluationException

示例1
@Test
public void testMath283()
    throws FunctionEvaluationException, OptimizationException {
    // fails because MultiDirectional.iterateSimplex is looping forever
    // the while(true) should be replaced with a convergence check
    MultiDirectional multiDirectional = new MultiDirectional();
    multiDirectional.setMaxIterations(100);
    multiDirectional.setMaxEvaluations(1000);

    final Gaussian2D function = new Gaussian2D(0.0, 0.0, 1.0);

    RealPointValuePair estimate = multiDirectional.optimize(function,
                                  GoalType.MAXIMIZE, function.getMaximumPosition());

    final double EPSILON = 1e-5;

    final double expectedMaximum = function.getMaximum();
    final double actualMaximum = estimate.getValue();
    Assert.assertEquals(expectedMaximum, actualMaximum, EPSILON);

    final double[] expectedPosition = function.getMaximumPosition();
    final double[] actualPosition = estimate.getPoint();
    Assert.assertEquals(expectedPosition[0], actualPosition[0], EPSILON );
    Assert.assertEquals(expectedPosition[1], actualPosition[1], EPSILON );

}
 
示例2
/** Fit a curve.
 * <p>This method compute the coefficients of the curve that best
 * fit the sample of observed points previously given through calls
 * to the {@link #addObservedPoint(WeightedObservedPoint)
 * addObservedPoint} method.</p>
 * @param f parametric function to fit
 * @param initialGuess first guess of the function parameters
 * @return fitted parameters
 * @exception FunctionEvaluationException if the objective function throws one during
 * the search
 * @exception OptimizationException if the algorithm failed to converge
 * @exception IllegalArgumentException if the start point dimension is wrong
 */
public double[] fit(final ParametricRealFunction f,
                    final double[] initialGuess)
    throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {

    // prepare least squares problem
    double[] target  = new double[observations.size()];
    double[] weights = new double[observations.size()];
    int i = 0;
    for (WeightedObservedPoint point : observations) {
        target[i]  = point.getY();
        weights[i] = point.getWeight();
        ++i;
    }

    // perform the fit
    VectorialPointValuePair optimum =
        optimizer.optimize(new TheoreticalValuesFunction(f), target, weights, initialGuess);

    // extract the coefficients
    return optimum.getPointRef();

}
 
示例3
/** {@inheritDoc} */
public RealPointValuePair optimize(final DifferentiableMultivariateRealFunction f,
                                     final GoalType goalType,
                                     final double[] startPoint)
    throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {

    // reset counters
    iterations          = 0;
    evaluations         = 0;
    gradientEvaluations = 0;

    // store optimization problem characteristics
    function = f;
    gradient = f.gradient();
    goal     = goalType;
    point    = startPoint.clone();

    return doOptimize();

}
 
示例4
public void testRedundantEquations() throws FunctionEvaluationException, OptimizationException {
    LinearProblem problem = new LinearProblem(new double[][] {
            { 1.0,  1.0 },
            { 1.0, -1.0 },
            { 1.0,  3.0 }
    }, new double[] { 3.0, 1.0, 5.0 });

    NonLinearConjugateGradientOptimizer optimizer =
        new NonLinearConjugateGradientOptimizer(ConjugateGradientFormula.POLAK_RIBIERE);
    optimizer.setMaxIterations(100);
    optimizer.setConvergenceChecker(new SimpleScalarValueChecker(1.0e-6, 1.0e-6));
    RealPointValuePair optimum =
        optimizer.optimize(problem, GoalType.MINIMIZE, new double[] { 1, 1 });
    assertEquals(2.0, optimum.getPoint()[0], 1.0e-8);
    assertEquals(1.0, optimum.getPoint()[1], 1.0e-8);

}
 
示例5
/**
 * Compute the n-th stage integral.
 * @param f the integrand function
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param n number of steps
 * @return the value of n-th stage integral
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 */
private double stage(final UnivariateRealFunction f,
                     final double min, final double max, final int n)
    throws FunctionEvaluationException {

    // set up the step for the current stage
    final double step     = (max - min) / n;
    final double halfStep = step / 2.0;

    // integrate over all elementary steps
    double midPoint = min + halfStep;
    double sum = 0.0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < abscissas.length; ++j) {
            sum += weights[j] * f.value(midPoint + halfStep * abscissas[j]);
        }
        midPoint += step;
    }

    return halfStep * sum;

}
 
示例6
/**
 * Compute the n-th stage integral.
 * @param f the integrand function
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param n number of steps
 * @return the value of n-th stage integral
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 */
private double stage(final UnivariateRealFunction f,
                     final double min, final double max, final int n)
    throws FunctionEvaluationException {

    // set up the step for the current stage
    final double step     = (max - min) / n;
    final double halfStep = step / 2.0;

    // integrate over all elementary steps
    double midPoint = min + halfStep;
    double sum = 0.0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < abscissas.length; ++j) {
            sum += weights[j] * f.value(midPoint + halfStep * abscissas[j]);
        }
        midPoint += step;
    }

    return halfStep * sum;

}
 
示例7
@Test
public void testMath283()
    throws FunctionEvaluationException, OptimizationException {
    // fails because MultiDirectional.iterateSimplex is looping forever
    // the while(true) should be replaced with a convergence check
    MultiDirectional multiDirectional = new MultiDirectional();
    multiDirectional.setMaxIterations(100);
    multiDirectional.setMaxEvaluations(1000);

    final Gaussian2D function = new Gaussian2D(0.0, 0.0, 1.0);

    RealPointValuePair estimate = multiDirectional.optimize(function,
                                  GoalType.MAXIMIZE, function.getMaximumPosition());

    final double EPSILON = 1e-5;

    final double expectedMaximum = function.getMaximum();
    final double actualMaximum = estimate.getValue();
    Assert.assertEquals(expectedMaximum, actualMaximum, EPSILON);

    final double[] expectedPosition = function.getMaximumPosition();
    final double[] actualPosition = estimate.getPoint();
    Assert.assertEquals(expectedPosition[0], actualPosition[0], EPSILON );
    Assert.assertEquals(expectedPosition[1], actualPosition[1], EPSILON );

}
 
示例8
public void testExactIntegration()
    throws ConvergenceException, FunctionEvaluationException {
    Random random = new Random(86343623467878363l);
    for (int n = 2; n < 6; ++n) {
        LegendreGaussIntegrator integrator =
            new LegendreGaussIntegrator(n, 64);

        // an n points Gauss-Legendre integrator integrates 2n-1 degree polynoms exactly
        for (int degree = 0; degree <= 2 * n - 1; ++degree) {
            for (int i = 0; i < 10; ++i) {
                double[] coeff = new double[degree + 1];
                for (int k = 0; k < coeff.length; ++k) {
                    coeff[k] = 2 * random.nextDouble() - 1;
                }
                PolynomialFunction p = new PolynomialFunction(coeff);
                double result    = integrator.integrate(p, -5.0, 15.0);
                double reference = exactIntegration(p, -5.0, 15.0);
                assertEquals(n + " " + degree + " " + i, reference, result, 1.0e-12 * (1.0 + Math.abs(reference)));
            }
        }

    }
}
 
示例9
/**
 * Find a real root in the given interval with initial value.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f function to solve (must be polynomial)
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param initial the start value to use
 * @return the point at which the function value is zero
 * @throws ConvergenceException if the maximum iteration count is exceeded
 * or the solver detects convergence problems otherwise
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 * @throws IllegalArgumentException if any parameters are invalid
 */
public double solve(final UnivariateRealFunction f,
                    final double min, final double max, final double initial)
    throws ConvergenceException, FunctionEvaluationException {

    // check for zeros before verifying bracketing
    if (f.value(min) == 0.0) {
        return min;
    }
    if (f.value(max) == 0.0) {
        return max;
    }
    if (f.value(initial) == 0.0) {
        return initial;
    }

    verifyBracketing(min, max, f);
    verifySequence(min, initial, max);
    if (isBracketing(min, initial, f)) {
        return solve(f, min, initial);
    } else {
        return solve(f, initial, max);
    }

}
 
示例10
public void testColumnsPermutation() throws FunctionEvaluationException, OptimizationException {

        LinearProblem problem =
            new LinearProblem(new double[][] { { 1.0, -1.0 }, { 0.0, 2.0 }, { 1.0, -2.0 } },
                              new double[] { 4.0, 6.0, 1.0 });

        NonLinearConjugateGradientOptimizer optimizer =
            new NonLinearConjugateGradientOptimizer(ConjugateGradientFormula.POLAK_RIBIERE);
        optimizer.setMaxIterations(100);
        optimizer.setConvergenceChecker(new SimpleScalarValueChecker(1.0e-6, 1.0e-6));
        RealPointValuePair optimum =
            optimizer.optimize(problem, GoalType.MINIMIZE, new double[] { 0, 0 });
        assertEquals(7.0, optimum.getPoint()[0], 1.0e-10);
        assertEquals(3.0, optimum.getPoint()[1], 1.0e-10);
        assertEquals(0.0, optimum.getValue(), 1.0e-10);

    }
 
示例11
/**
 * Guess the errors in optimized parameters.
 * <p>Guessing is covariance-based, it only gives rough order of magnitude.</p>
 * @return errors in optimized parameters
 * @exception FunctionEvaluationException if the function jacobian cannot b evaluated
 * @exception OptimizationException if the covariances matrix cannot be computed
 * or the number of degrees of freedom is not positive (number of measurements
 * lesser or equal to number of parameters)
 */
public double[] guessParametersErrors()
    throws FunctionEvaluationException, OptimizationException {
    if (rows <= cols) {
        throw new OptimizationException(
                "no degrees of freedom ({0} measurements, {1} parameters)",
                rows, cols);
    }
    double[] errors = new double[cols];
    final double c = Math.sqrt(getChiSquare() / (rows - cols));
    double[][] covar = getCovariances();
    for (int i = 0; i < errors.length; ++i) {
        errors[i] = Math.sqrt(covar[i][i]) * c;
    }
    return errors;
}
 
示例12
@Test
public void testMath283()
    throws FunctionEvaluationException, OptimizationException {
    // fails because MultiDirectional.iterateSimplex is looping forever
    // the while(true) should be replaced with a convergence check
    MultiDirectional multiDirectional = new MultiDirectional();
    multiDirectional.setMaxIterations(100);
    multiDirectional.setMaxEvaluations(1000);

    final Gaussian2D function = new Gaussian2D(0.0, 0.0, 1.0);

    RealPointValuePair estimate = multiDirectional.optimize(function,
                                  GoalType.MAXIMIZE, function.getMaximumPosition());

    final double EPSILON = 1e-5;

    final double expectedMaximum = function.getMaximum();
    final double actualMaximum = estimate.getValue();
    Assert.assertEquals(expectedMaximum, actualMaximum, EPSILON);

    final double[] expectedPosition = function.getMaximumPosition();
    final double[] actualPosition = estimate.getPoint();
    Assert.assertEquals(expectedPosition[0], actualPosition[0], EPSILON );
    Assert.assertEquals(expectedPosition[1], actualPosition[1], EPSILON );

}
 
示例13
public void testTwoSets() throws FunctionEvaluationException, OptimizationException {
    double epsilon = 1.0e-7;
    LinearProblem problem = new LinearProblem(new double[][] {
            {  2,  1,   0,  4,       0, 0 },
            { -4, -2,   3, -7,       0, 0 },
            {  4,  1,  -2,  8,       0, 0 },
            {  0, -3, -12, -1,       0, 0 },
            {  0,  0,   0,  0, epsilon, 1 },
            {  0,  0,   0,  0,       1, 1 }
    }, new double[] { 2, -9, 2, 2, 1 + epsilon * epsilon, 2});

    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    VectorialPointValuePair optimum =
        optimizer.optimize(problem, problem.target, new double[] { 1, 1, 1, 1, 1, 1 },
                           new double[] { 0, 0, 0, 0, 0, 0 });
    assertEquals(0, optimizer.getRMS(), 1.0e-10);
    assertEquals( 3.0, optimum.getPoint()[0], 1.0e-10);
    assertEquals( 4.0, optimum.getPoint()[1], 1.0e-10);
    assertEquals(-1.0, optimum.getPoint()[2], 1.0e-10);
    assertEquals(-2.0, optimum.getPoint()[3], 1.0e-10);
    assertEquals( 1.0 + epsilon, optimum.getPoint()[4], 1.0e-10);
    assertEquals( 1.0 - epsilon, optimum.getPoint()[5], 1.0e-10);

}
 
示例14
public void testMath199() throws FunctionEvaluationException {
    try {
        QuadraticProblem problem = new QuadraticProblem();
        problem.addPoint (0, -3.182591015485607);
        problem.addPoint (1, -2.5581184967730577);
        problem.addPoint (2, -2.1488478161387325);
        problem.addPoint (3, -1.9122489313410047);
        problem.addPoint (4, 1.7785661310051026);
        LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
        optimizer.setQRRankingThreshold(0);
        optimizer.optimize(problem,
                           new double[] { 0, 0, 0, 0, 0 },
                           new double[] { 0.0, 4.4e-323, 1.0, 4.4e-323, 0.0 },
                           new double[] { 0, 0, 0 });
        fail("an exception should have been thrown");
    } catch (ConvergenceException ee) {
        // expected behavior
    }

}
 
示例15
public void testRedundantEquations() throws FunctionEvaluationException, OptimizationException {
    LinearProblem problem = new LinearProblem(new double[][] {
            { 1.0,  1.0 },
            { 1.0, -1.0 },
            { 1.0,  3.0 }
    }, new double[] { 3.0, 1.0, 5.0 });

    GaussNewtonOptimizer optimizer = new GaussNewtonOptimizer(true);
    optimizer.setMaxIterations(100);
    optimizer.setConvergenceChecker(new SimpleVectorialValueChecker(1.0e-6, 1.0e-6));
    VectorialPointValuePair optimum =
        optimizer.optimize(problem, problem.target, new double[] { 1, 1, 1 },
                           new double[] { 1, 1 });
    assertEquals(0, optimizer.getRMS(), 1.0e-10);
    assertEquals(2.0, optimum.getPoint()[0], 1.0e-8);
    assertEquals(1.0, optimum.getPoint()[1], 1.0e-8);

}
 
示例16
/**
 * Find a root in the given interval with initial value.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param initial the start value to use
 * @return the point at which the function value is zero
 * @throws MaxIterationsExceededException if the maximum iteration count is exceeded
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 * @throws IllegalArgumentException if any parameters are invalid
 */
public double solve(final UnivariateRealFunction f,
                    final double min, final double max, final double initial)
    throws MaxIterationsExceededException, FunctionEvaluationException {

    // check for zeros before verifying bracketing
    if (f.value(min) == 0.0) { return min; }
    if (f.value(max) == 0.0) { return max; }
    if (f.value(initial) == 0.0) { return initial; }

    verifyBracketing(min, max, f);
    verifySequence(min, initial, max);
    if (isBracketing(min, initial, f)) {
        return solve(f, min, initial);
    } else {
        return solve(f, initial, max);
    }
}
 
示例17
/**
 * Return a function adding a constant term to the instance.
 * @param a term to add
 * @return a new function which computes {@code this.value(x) + a}
 */
public ComposableFunction add(final double a) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(x) + a;
        }
    };
}
 
示例18
/**
 * Poor data: right of peak is missing.
 *
 * @throws OptimizationException in the event of a test case error
 * @throws FunctionEvaluationException in the event of a test case error
 */
@Test
public void testFit06()
throws OptimizationException, FunctionEvaluationException {
    GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
    addDatasetToGaussianFitter(DATASET4, fitter);
    GaussianFunction fitFunction = fitter.fit();
    assertEquals(530.3649792355617, fitFunction.getA(), 1e-4);
    assertEquals(284517.0835567514, fitFunction.getB(), 1e-4);
    assertEquals(-13.5355534565105, fitFunction.getC(), 1e-4);
    assertEquals(1.512353018625465, fitFunction.getD(), 1e-4);
}
 
示例19
/** {@inheritDoc} */
public RealVector mapAsinToSelf() {
    try {
        return mapToSelf(ComposableFunction.ASIN);
    } catch (FunctionEvaluationException e) {
        throw new IllegalArgumentException(e);
    }
}
 
示例20
/**
 * Return a function dividing the instance by another function.
 * @param f function to combine with the instance
 * @return a new function which computes {@code this.value(x) / f.value(x)}
 */
public ComposableFunction divide(final UnivariateRealFunction f) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(x) / f.value(x);
        }
    };
}
 
示例21
public void testInconsistentEquations() throws FunctionEvaluationException, OptimizationException {
    LinearProblem problem = new LinearProblem(new double[][] {
            { 1.0,  1.0 },
            { 1.0, -1.0 },
            { 1.0,  3.0 }
    }, new double[] { 3.0, 1.0, 4.0 });

    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    optimizer.optimize(problem, problem.target, new double[] { 1, 1, 1 }, new double[] { 1, 1 });
    assertTrue(optimizer.getRMS() > 0.1);

}
 
示例22
public void testMoreEstimatedParametersSimple() throws FunctionEvaluationException, OptimizationException {

        LinearProblem problem = new LinearProblem(new double[][] {
                { 3.0, 2.0,  0.0, 0.0 },
                { 0.0, 1.0, -1.0, 1.0 },
                { 2.0, 0.0,  1.0, 0.0 }
        }, new double[] { 7.0, 3.0, 5.0 });

        LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
        optimizer.optimize(problem, problem.target, new double[] { 1, 1, 1 },
                new double[] { 7, 6, 5, 4 });
        assertEquals(0, optimizer.getRMS(), 1.0e-10);

    }
 
示例23
/** Precompose the instance with another function.
 * <p>
 * The composed function h created by {@code h = g.of(f)} is such
 * that {@code h.value(x) == g.value(f.value(x))} for all x.
 * </p>
 * @param f function to compose with
 * @return a new function which computes {@code this.value(f.value(x))}
 * @see #postCompose(UnivariateRealFunction)
 */
public ComposableFunction of(final UnivariateRealFunction f) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(f.value(x));
        }
    };
}
 
示例24
/** {@inheritDoc} */
public double integrate(final UnivariateRealFunction f,
        final double min, final double max)
    throws ConvergenceException,  FunctionEvaluationException, IllegalArgumentException {
    
    clearResult();
    verifyInterval(min, max);
    verifyIterationCount();

    // compute first estimate with a single step
    double oldt = stage(f, min, max, 1);

    int n = 2;
    for (int i = 0; i < maximalIterationCount; ++i) {

        // improve integral with a larger number of steps
        final double t = stage(f, min, max, n);

        // estimate error
        final double delta = Math.abs(t - oldt);
        final double limit =
            Math.max(absoluteAccuracy,
                     relativeAccuracy * (Math.abs(oldt) + Math.abs(t)) * 0.5);

        // check convergence
        if ((i + 1 >= minimalIterationCount) && (delta <= limit)) {
            setResult(t, i);
            return result;
        }

        // prepare next iteration
        double ratio = Math.min(4, Math.pow(delta / limit, 0.5 / abscissas.length));
        n = Math.max((int) (ratio * n), n + 1);
        oldt = t;

    }

    throw new MaxIterationsExceededException(maximalIterationCount);

}
 
示例25
/** {@inheritDoc} */
public RealVector mapSignumToSelf() {
    try {
        return mapToSelf(ComposableFunction.SIGNUM);
    } catch (FunctionEvaluationException e) {
        throw new IllegalArgumentException(e);
    }
}
 
示例26
/** {@inheritDoc} */
public RealVector mapSinToSelf() {
    try {
        return mapToSelf(ComposableFunction.SIN);
    } catch (FunctionEvaluationException e) {
        throw new IllegalArgumentException(e);
    }
}
 
示例27
/**
 * Return a function subtracting another function from the instance.
 * @param f function to combine with the instance
 * @return a new function which computes {@code this.value(x) - f.value(x)}
 */
public ComposableFunction subtract(final UnivariateRealFunction f) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(x) - f.value(x);
        }
    };
}
 
示例28
/**
 * Return a function adding a constant term to the instance.
 * @param a term to add
 * @return a new function which computes {@code this.value(x) + a}
 */
public ComposableFunction add(final double a) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(x) + a;
        }
    };
}
 
示例29
/**
 * Find a zero near the value <code>startValue</code>.
 *
 * @param f the function to solve
 * @param min the lower bound for the interval (ignored).
 * @param max the upper bound for the interval (ignored).
 * @param startValue the start value to use.
 * @return the value where the function is zero
 * @throws MaxIterationsExceededException if the maximum iteration count is exceeded
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function or derivative
 * @throws IllegalArgumentException if startValue is not between min and max or
 * if function is not a {@link DifferentiableUnivariateRealFunction} instance
 */
public double solve(final UnivariateRealFunction f,
                    final double min, final double max, final double startValue)
    throws MaxIterationsExceededException, FunctionEvaluationException {

    try {

        final UnivariateRealFunction derivative =
            ((DifferentiableUnivariateRealFunction) f).derivative();
        clearResult();
        verifySequence(min, startValue, max);

        double x0 = startValue;
        double x1;

        int i = 0;
        while (i < maximalIterationCount) {

            x1 = x0 - (f.value(x0) / derivative.value(x0));
            if (Math.abs(x1 - x0) <= absoluteAccuracy) {
                setResult(x1, i);
                return x1;
            }

            x0 = x1;
            ++i;
        }

        throw new MaxIterationsExceededException(maximalIterationCount);
    } catch (ClassCastException cce) {
        throw MathRuntimeException.createIllegalArgumentException("function is not differentiable");
    }
}
 
示例30
/** Get a composable function by fixing the second argument of the instance.
 * @param fixedY fixed value of the second argument
 * @return a function such that {@code f.value(x) == value(x, fixedY)}
 */
public ComposableFunction fix2ndArgument(final double fixedY) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return BinaryFunction.this.value(x, fixedY);
        }
    };
}