List of usage examples for org.apache.commons.math3.optim.nonlinear.scalar MultivariateFunctionPenaltyAdapter MultivariateFunctionPenaltyAdapter
public MultivariateFunctionPenaltyAdapter(final MultivariateFunction bounded, final double[] lower, final double[] upper, final double offset, final double[] scale)
From source file:uk.ac.diamond.scisoft.analysis.diffraction.FittingUtils.java
/** * Optimize given function/* ww w .ja v a 2 s . c om*/ * @param f * @param opt * @param min * @return residual */ public static double optimize(FitFunction f, MultivariateOptimizer opt, double min) { double res = Double.NaN; try { PointValuePair result; if (opt instanceof BOBYQAOptimizer) { result = opt.optimize(new InitialGuess(f.getInitial()), GoalType.MINIMIZE, new ObjectiveFunction(f), new MaxEval(MAX_EVAL), f.getBounds()); } else if (opt instanceof CMAESOptimizer) { int p = (int) Math.ceil(4 + Math.log(f.getN())) + 1; logger.trace("Population size: {}", p); result = opt.optimize(new InitialGuess(f.getInitial()), GoalType.MINIMIZE, new ObjectiveFunction(f), new CMAESOptimizer.Sigma(f.getSigma()), new CMAESOptimizer.PopulationSize(p), new MaxEval(MAX_EVAL), f.getBounds()); } else { int n = f.getN(); double offset = 1e12; double[] scale = new double[n]; for (int i = 0; i < n; i++) { scale[i] = offset * 0.25; } SimpleBounds bnds = f.getBounds(); MultivariateFunctionPenaltyAdapter of = new MultivariateFunctionPenaltyAdapter(f, bnds.getLower(), bnds.getUpper(), offset, scale); result = opt.optimize(new InitialGuess(f.getInitial()), GoalType.MINIMIZE, new ObjectiveFunction(of), new MaxEval(MAX_EVAL), new MultiDirectionalSimplex(n)); // new NelderMeadSimplex(n)); } // logger.info("Q-space fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare()); double ires = f.value(opt.getStartPoint()); logger.trace("Residual: {} from {}", result.getValue(), ires); res = result.getValue(); if (res < min) f.setParameters(result.getPoint()); logger.trace("Used {} evals and {} iters", opt.getEvaluations(), opt.getIterations()); // System.err.printf("Used %d evals and %d iters\n", opt.getEvaluations(), opt.getIterations()); // logger.info("Q-space fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare()); } catch (IllegalArgumentException e) { logger.error("Start point has wrong dimension", e); // should not happen! } catch (TooManyEvaluationsException e) { throw new IllegalArgumentException("Could not fit as optimizer did not converge"); // logger.error("Convergence problem: max iterations ({}) exceeded", opt.getMaxIterations()); } return res; }
From source file:uk.ac.diamond.scisoft.analysis.fitting.functions.AFunction.java
/** * Generate a Apache MultivariateFunctionPenaltyAdapter from the function * @param inputValues A dataset containing the data values for the optimisation * @param inputCoords A dataset containing the coordinates for the optimization * @return the bounded MultivariateFunctionPenaltyAdapter *//*www .jav a2 s.c o m*/ public MultivariateFunctionPenaltyAdapter getApacheMultivariateFunction(IDataset inputValues, IDataset[] inputCoords) { final AFunction function = this; final IDataset values = inputValues; final IDataset[] coords = inputCoords; MultivariateFunction multivariateFunction = new MultivariateFunction() { @Override public double value(double[] arg0) { function.setParameterValuesNoFixed(arg0); double result = function.residual(true, values, null, coords); return result; } }; double offset = 1e12; double[] lowerb = getLowerBoundsNoFixed(); double[] upperb = getUpperBoundsNoFixed(); double[] scale = new double[lowerb.length]; for (int i = 0; i < scale.length; i++) { scale[i] = offset * 0.25; } MultivariateFunctionPenaltyAdapter multivariateFunctionPenaltyAdapter = new MultivariateFunctionPenaltyAdapter( multivariateFunction, lowerb, upperb, offset, scale); return multivariateFunctionPenaltyAdapter; }
From source file:uk.ac.diamond.scisoft.analysis.optimize.ApacheOptimizer.java
private void internalScalarOptimize() { MultivariateOptimizer opt = createOptimizer(); SimpleBounds bd = createBounds();// w w w.j ava 2 s . co m double offset = 1e12; double[] scale = new double[n]; for (int i = 0; i < n; i++) { scale[i] = offset * 0.25; } MultivariateFunction fn = createFunction(); if (optimizer == Optimizer.SIMPLEX_MD || optimizer == Optimizer.SIMPLEX_NM) { fn = new MultivariateFunctionPenaltyAdapter(fn, bd.getLower(), bd.getUpper(), offset, scale); } ObjectiveFunction of = new ObjectiveFunction(fn); InitialGuess ig = new InitialGuess(getParameterValues()); MaxEval me = new MaxEval(MAX_EVAL); double min = Double.POSITIVE_INFINITY; double res = Double.NaN; try { PointValuePair result; switch (optimizer) { case CONJUGATE_GRADIENT: // af = new MultivariateFunctionPenaltyAdapter(fn, bd.getLower(), bd.getUpper(), offset, scale); result = opt.optimize(ig, GoalType.MINIMIZE, of, me, new ObjectiveFunctionGradient(createGradientFunction())); break; case BOBYQA: result = opt.optimize(ig, GoalType.MINIMIZE, of, me, bd); break; case CMAES: double[] sigma = new double[n]; for (int i = 0; i < n; i++) { IParameter p = params.get(i); double v = p.getValue(); double r = Math.max(p.getUpperLimit() - v, v - p.getLowerLimit()); sigma[i] = r * 0.05; // 5% of range } int p = (int) Math.ceil(4 + Math.log(n)) + 1; logger.trace("Population size: {}", p); result = opt.optimize(ig, GoalType.MINIMIZE, of, me, bd, new CMAESOptimizer.Sigma(sigma), new CMAESOptimizer.PopulationSize(p)); break; case SIMPLEX_MD: result = opt.optimize(ig, GoalType.MINIMIZE, of, me, new MultiDirectionalSimplex(n)); break; case SIMPLEX_NM: result = opt.optimize(ig, GoalType.MINIMIZE, of, me, new NelderMeadSimplex(n)); break; default: throw new IllegalStateException("Should not be called"); } // logger.info("Q-space fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare()); double ires = calculateResidual(opt.getStartPoint()); logger.trace("Residual: {} from {}", result.getValue(), ires); res = result.getValue(); if (res < min) setParameterValues(result.getPoint()); logger.trace("Used {} evals and {} iters", opt.getEvaluations(), opt.getIterations()); // System.err.printf("Used %d evals and %d iters\n", opt.getEvaluations(), opt.getIterations()); // logger.info("Q-space fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare()); } catch (IllegalArgumentException e) { logger.error("Start point has wrong dimension", e); // should not happen! } catch (TooManyEvaluationsException e) { throw new IllegalArgumentException("Could not fit as optimizer did not converge"); // logger.error("Convergence problem: max iterations ({}) exceeded", opt.getMaxIterations()); } }