Search in sources :

Example 16 with UnivariateFunction

use of org.apache.commons.math3.analysis.UnivariateFunction in project GDSC-SMLM by aherbert.

the class BoundedNonLinearConjugateGradientOptimizer method findUpperBoundWithChecks.

/**
	 * Finds the upper bound b ensuring bracketing of a root between a and b.
	 *
	 * @param f
	 *            function whose root must be bracketed.
	 * @param a
	 *            lower bound of the interval.
	 * @param h
	 *            initial step to try.
	 * @return b such that f(a) and f(b) have opposite signs.
	 * @throws MathIllegalStateException
	 *             if no bracket can be found.
	 */
@SuppressWarnings("unused")
private double findUpperBoundWithChecks(final UnivariateFunction f, final double a, final double h) {
    noBracket = false;
    final double yA = f.value(a);
    // Check we have a gradient. This should be true unless something slipped by.
    if (Double.isNaN(yA))
        throw new MathIllegalStateException(LocalizedFormats.UNABLE_TO_BRACKET_OPTIMUM_IN_LINE_SEARCH);
    double yB = yA;
    double lastB = Double.NaN;
    for (double step = h; step < Double.MAX_VALUE; step *= FastMath.max(2, yA / yB)) {
        double b = a + step;
        yB = f.value(b);
        if (yA * yB <= 0) {
            return b;
        }
        if (Double.isNaN(yB)) {
            // We have moved along the vector to a point where we have no gradient.
            // Bracketing is impossible.
            noBracket = true;
            // Check we made at least one step to a place with a new gradient
            if (lastB != Double.NaN)
                // Return the point we reached as the minimum
                return lastB;
            // with a valid gradient
            for (step *= 0.1; step > Double.MIN_VALUE; step *= 0.1) {
                b = a + step;
                yB = f.value(b);
                if (yA * yB <= 0) {
                    return b;
                }
                if (!Double.isNaN(yB)) {
                    lastB = b;
                }
            }
            if (lastB != Double.NaN)
                // Return the point we reached as the minimum
                return lastB;
            throw new MathIllegalStateException(LocalizedFormats.UNABLE_TO_BRACKET_OPTIMUM_IN_LINE_SEARCH);
        }
        lastB = b;
    }
    throw new MathIllegalStateException(LocalizedFormats.UNABLE_TO_BRACKET_OPTIMUM_IN_LINE_SEARCH);
}
Also used : MathIllegalStateException(org.apache.commons.math3.exception.MathIllegalStateException)

Example 17 with UnivariateFunction

use of org.apache.commons.math3.analysis.UnivariateFunction in project GDSC-SMLM by aherbert.

the class JumpDistanceAnalysisTest method canIntegrateProbabilityToCumulativeWithMixedPopulation.

// Commented out as this test always passes
//@Test
public void canIntegrateProbabilityToCumulativeWithMixedPopulation() {
    JumpDistanceAnalysis jd = new JumpDistanceAnalysis();
    jd.setMinD(0);
    jd.setMinFraction(0);
    SimpsonIntegrator si = new SimpsonIntegrator(1e-3, 1e-8, 2, SimpsonIntegrator.SIMPSON_MAX_ITERATIONS_COUNT);
    for (double d : D) {
        for (double f : new double[] { 0, 0.1, 0.2, 0.4, 0.7, 0.9, 1 }) {
            final double[] params = new double[] { f, d, 1 - f, d * 0.1 };
            final MixedJumpDistanceFunction fp = jd.new MixedJumpDistanceFunction(null, d, 2);
            MixedJumpDistanceCumulFunction fc = jd.new MixedJumpDistanceCumulFunction(null, null, d, 2);
            double x = d / 8;
            UnivariateFunction func = new UnivariateFunction() {

                public double value(double x) {
                    return fp.evaluate(x, params);
                }
            };
            for (int i = 1; i < 10; i++, x *= 2) {
                double e = fc.evaluate(x, params);
                // Integrate
                double o = si.integrate(10000, func, 0, x);
                //log("Integrate d=%.1f, f=%.1f : x=%.1f, e=%f, o=%f, iter=%d, eval=%d\n", d, f, x, e, o,
                //		si.getIterations(), si.getEvaluations());
                Assert.assertEquals("Failed to integrate", e, o, e * 1e-2);
            }
        }
    }
}
Also used : SimpsonIntegrator(org.apache.commons.math3.analysis.integration.SimpsonIntegrator) MixedJumpDistanceCumulFunction(gdsc.smlm.fitting.JumpDistanceAnalysis.MixedJumpDistanceCumulFunction) MixedJumpDistanceFunction(gdsc.smlm.fitting.JumpDistanceAnalysis.MixedJumpDistanceFunction) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction)

Example 18 with UnivariateFunction

use of org.apache.commons.math3.analysis.UnivariateFunction in project gatk by broadinstitute.

the class RobustBrentSolverUnitTest method simpleTest.

/**
     * Test on a 4th degree polynomial with 4 real roots at x = 0, 1, 2, 3. This objective function is positive for
     * large enough positive and negative values of its arguments. Therefore, the simple Brent solver complains that
     * the search interval does not bracket a root. The robust Brent solver, however, subdivides the given search
     * interval and finds a bracketing sub-interval.
     *
     * The "best" root according to the given merit function (set to the anti-derivative of the objective function)
     * is in fact the one at x = 0. We require the robust solver to output x = 0, and the simple solver to fail.
     */
@Test
public void simpleTest() {
    final UnivariateFunction objFunc = x -> 30 * x * (x - 1) * (x - 2) * (x - 3);
    final UnivariateFunction meritFunc = x -> 6 * FastMath.pow(x, 5) - 45 * FastMath.pow(x, 4) + 110 * FastMath.pow(x, 3) - 90 * FastMath.pow(x, 2);
    final RobustBrentSolver solverRobust = new RobustBrentSolver(DEF_REL_ACC, DEF_REL_ACC, DEF_F_ACC, meritFunc, 4, 1);
    final BrentSolver solverSimple = new BrentSolver(DEF_REL_ACC, DEF_REL_ACC, DEF_F_ACC);
    final double xRobust = solverRobust.solve(100, objFunc, -1, 4);
    Assert.assertEquals(xRobust, 0, DEF_ABS_ACC);
    boolean simpleSolverFails = false;
    try {
        /* this will fail */
        solverSimple.solve(100, objFunc, -1, 4);
    } catch (final NoBracketingException ex) {
        simpleSolverFails = true;
    }
    Assert.assertTrue(simpleSolverFails);
}
Also used : List(java.util.List) Assert(org.testng.Assert) BaseTest(org.broadinstitute.hellbender.utils.test.BaseTest) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) FastMath(org.apache.commons.math3.util.FastMath) Test(org.testng.annotations.Test) BrentSolver(org.apache.commons.math3.analysis.solvers.BrentSolver) NoBracketingException(org.apache.commons.math3.exception.NoBracketingException) BrentSolver(org.apache.commons.math3.analysis.solvers.BrentSolver) NoBracketingException(org.apache.commons.math3.exception.NoBracketingException) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) BaseTest(org.broadinstitute.hellbender.utils.test.BaseTest) Test(org.testng.annotations.Test)

Example 19 with UnivariateFunction

use of org.apache.commons.math3.analysis.UnivariateFunction in project dhis2-core by dhis2.

the class DefaultChartService method getJFreeChartHistory.

@Override
public JFreeChart getJFreeChartHistory(DataElement dataElement, DataElementCategoryOptionCombo categoryOptionCombo, DataElementCategoryOptionCombo attributeOptionCombo, Period lastPeriod, OrganisationUnit organisationUnit, int historyLength, I18nFormat format) {
    lastPeriod = periodService.reloadPeriod(lastPeriod);
    List<Period> periods = periodService.getPeriods(lastPeriod, historyLength);
    MinMaxDataElement minMax = minMaxDataElementService.getMinMaxDataElement(organisationUnit, dataElement, categoryOptionCombo);
    UnivariateInterpolator interpolator = new SplineInterpolator();
    Integer periodCount = 0;
    List<Double> x = new ArrayList<>();
    List<Double> y = new ArrayList<>();
    // ---------------------------------------------------------------------
    // DataValue, MinValue and MaxValue DataSets
    // ---------------------------------------------------------------------
    DefaultCategoryDataset dataValueDataSet = new DefaultCategoryDataset();
    DefaultCategoryDataset metaDataSet = new DefaultCategoryDataset();
    for (Period period : periods) {
        ++periodCount;
        period.setName(format.formatPeriod(period));
        DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
        double value = 0;
        if (dataValue != null && dataValue.getValue() != null && MathUtils.isNumeric(dataValue.getValue())) {
            value = Double.parseDouble(dataValue.getValue());
            x.add(periodCount.doubleValue());
            y.add(value);
        }
        dataValueDataSet.addValue(value, dataElement.getShortName(), period.getName());
        if (minMax != null) {
            metaDataSet.addValue(minMax.getMin(), "Min value", period.getName());
            metaDataSet.addValue(minMax.getMax(), "Max value", period.getName());
        }
    }
    if (// minimum 3 points required for interpolation
    x.size() >= 3) {
        periodCount = 0;
        double[] xa = getArray(x);
        int min = MathUtils.getMin(xa).intValue();
        int max = MathUtils.getMax(xa).intValue();
        try {
            UnivariateFunction function = interpolator.interpolate(xa, getArray(y));
            for (Period period : periods) {
                if (++periodCount >= min && periodCount <= max) {
                    metaDataSet.addValue(function.value(periodCount), "Regression value", period.getName());
                }
            }
        } catch (MathRuntimeException ex) {
            throw new RuntimeException("Failed to interpolate", ex);
        }
    }
    // ---------------------------------------------------------------------
    // Plots
    // ---------------------------------------------------------------------
    CategoryPlot plot = getCategoryPlot(dataValueDataSet, getBarRenderer(), PlotOrientation.VERTICAL, CategoryLabelPositions.UP_45);
    plot.setDataset(1, metaDataSet);
    plot.setRenderer(1, getLineRenderer());
    JFreeChart jFreeChart = getBasicJFreeChart(plot);
    return jFreeChart;
}
Also used : MathRuntimeException(org.apache.commons.math3.exception.MathRuntimeException) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) DataValue(org.hisp.dhis.datavalue.DataValue) Period(org.hisp.dhis.period.Period) JFreeChart(org.jfree.chart.JFreeChart) MathRuntimeException(org.apache.commons.math3.exception.MathRuntimeException) MinMaxDataElement(org.hisp.dhis.minmax.MinMaxDataElement) SplineInterpolator(org.apache.commons.math3.analysis.interpolation.SplineInterpolator) UnivariateInterpolator(org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator) DefaultCategoryDataset(org.jfree.data.category.DefaultCategoryDataset)

Aggregations

UnivariateFunction (org.apache.commons.math3.analysis.UnivariateFunction)17 TooManyEvaluationsException (org.apache.commons.math3.exception.TooManyEvaluationsException)7 SimpsonIntegrator (org.apache.commons.math3.analysis.integration.SimpsonIntegrator)6 NoBracketingException (org.apache.commons.math3.exception.NoBracketingException)6 FastMath (org.apache.commons.math3.util.FastMath)6 VisibleForTesting (com.google.common.annotations.VisibleForTesting)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 IntStream (java.util.stream.IntStream)4 Nonnull (javax.annotation.Nonnull)4 Nullable (javax.annotation.Nullable)4 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)4 ImmutableTriple (org.apache.commons.lang3.tuple.ImmutableTriple)4 UnivariateIntegrator (org.apache.commons.math3.analysis.integration.UnivariateIntegrator)4 RobustBrentSolver (org.broadinstitute.hellbender.tools.coveragemodel.math.RobustBrentSolver)4 Utils (org.broadinstitute.hellbender.utils.Utils)4 ParamUtils (org.broadinstitute.hellbender.utils.param.ParamUtils)4 INDArray (org.nd4j.linalg.api.ndarray.INDArray)4 Nd4j (org.nd4j.linalg.factory.Nd4j)4 NDArrayIndex (org.nd4j.linalg.indexing.NDArrayIndex)4