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);
}
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);
}
}
}
}
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);
}
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;
}
Aggregations