List of usage examples for org.apache.commons.math3.optim MaxEval MaxEval
public MaxEval(int max)
From source file:eu.crisis_economics.abm.markets.clearing.heterogeneous.NelderMeadClearingAlgorithm.java
@Override public double applyToNetwork(final MixedClearingNetwork network) { Preconditions.checkNotNull(network); final SimplexOptimizer optimizer = new SimplexOptimizer(relErrorTarget, absErrorTarget); final ResidualCostFunction aggregateCostFunction = super.getResidualScalarCostFunction(network); final RealVector start = new ArrayRealVector(network.getNumberOfEdges()); for (int i = 0; i < network.getNumberOfEdges(); ++i) start.setEntry(i, network.getEdges().get(i).getMaximumRateAdmissibleByBothParties()); start.set(1.);/*from w ww . j a v a 2 s .c o m*/ final PointValuePair result = optimizer.optimize(new MaxEval(maximumEvaluations), new ObjectiveFunction(aggregateCostFunction), GoalType.MINIMIZE, new InitialGuess(start.toArray()), new NelderMeadSimplex(network.getNumberOfEdges())); final double residualCost = result.getValue(); System.out.println("Network cleared: residual cost: " + residualCost + "."); return residualCost; }
From source file:edu.utexas.cs.tactex.tariffoptimization.OptimizerWrapperApacheBOBYQA.java
@Override public TreeMap<Double, TariffSpecification> findOptimum(TariffUtilityEstimate tariffUtilityEstimate, int NUM_RATES, int numEval) { double[] startingVertex = new double[NUM_RATES]; // start from the fixed-rate tariff's offset Arrays.fill(startingVertex, 0.0); //Arrays.fill(startingVertex, 0.5 * INITIAL_TRUST_REGION_RADIUS); //Arrays.fill(startingVertex, 1 * INITIAL_TRUST_REGION_RADIUS); final int numIterpolationPoints = 2 * NUM_RATES + 1; // BOBYQA recommends 2n+1 points BOBYQAOptimizer optimizer = new BOBYQAOptimizer(numIterpolationPoints, INITIAL_TRUST_REGION_RADIUS, STOPPING_TRUST_REGION_RADIUS); // needed since one optimization found positive // charges (paying customer to consume...) double[][] boundaries = createBoundaries(NUM_RATES); final PointValuePair optimum = optimizer.optimize(new MaxEval(numEval), new ObjectiveFunction(new OptimizerWrapperApacheObjective(tariffUtilityEstimate)), GoalType.MAXIMIZE, new InitialGuess(startingVertex), //new SimpleBounds(boundaries[0], boundaries[1])); SimpleBounds.unbounded(NUM_RATES)); TreeMap<Double, TariffSpecification> eval2TOUTariff = new TreeMap<Double, TariffSpecification>(); eval2TOUTariff.put(optimum.getValue(), tariffUtilityEstimate.getCorrespondingSpec(optimum.getKey())); return eval2TOUTariff; }
From source file:com.itemanalysis.psychometrics.factoranalysis.MaximumLikelihoodMethod.java
public double estimateParameters() { MLObjectiveFunction objectiveFunction = new MLObjectiveFunction(); // System.out.println("START VALUES: " + Arrays.toString(getStartValues())); optimizer = new NonLinearConjugateGradientOptimizer( NonLinearConjugateGradientOptimizer.Formula.POLAK_RIBIERE, new SimpleValueChecker(1e-8, 1e-8)); solution = optimizer.optimize(new MaxEval(1000), objectiveFunction.getObjectiveFunction(), objectiveFunction.getObjectiveFunctionGradient(), GoalType.MINIMIZE, new InitialGuess(getStartValues())); computeFactorLoadings(solution.getPoint()); return solution.getValue(); }
From source file:edu.uchc.octane.GaussianFitAstigmatism.java
@Override public double[] doFit() { double[] initParameters; if (bPreprocessBg_) { initParameters = new double[] { 0, 0, pixelValue(0, 0) - bg_, sigma2_, sigma2_ }; } else {//from w ww.ja v a2 s .c om initParameters = new double[] { 0, 0, pixelValue(0, 0) - bg_, sigma2_, sigma2_, bg_ }; } PowellOptimizer optimizer = new PowellOptimizer(1e-4, 1e-1); MultivariateFunction func = new MultivariateFunction() { @Override public double value(double[] point) { double bg = bPreprocessBg_ ? 0 : point[3]; double v = 0; for (int xi = -windowSize_; xi < windowSize_; xi++) { for (int yi = -windowSize_; yi < windowSize_; yi++) { double delta = getValueExcludingBackground(xi, yi, point) + bg - pixelValue(xi, yi); v += delta * delta; } } return v; } }; pvp_ = optimizer.optimize(new ObjectiveFunction(func), new InitialGuess(initParameters), new MaxEval(10000), GoalType.MINIMIZE); // double sigmax = pvp.getPoint()[3]; // double sigmay = pvp.getPoint()[4]; // if (calibration_ != null) { // double [] pn = new double[4]; // pn[0] = p1_; // pn[1] = p2_; // pn[2] = p3_ + 2 * calibration_[2] * (calibration_[0] - sigmax) + 2 * calibration_[5] * (calibration_[3] - sigmay); // pn[3] = calibration_[1] * (calibration_[0] - sigmax) + calibration_[4] * (calibration_[3] - sigmay); // // Complex [] roots = new LaguerreSolver().solveAllComplex(pn, 0); // // int minIndex = -1; // double minV = Double.MAX_VALUE; // for (int i = 0; i < 3; i ++) { // double v; // if (FastMath.abs(roots[i].getImaginary()) < 1e-7) { // double z = roots[i].getReal(); // double vx = calibration_[0] + calibration_[1] * z + calibration_[2] * z * z - sigmax; // double vy = calibration_[3] + calibration_[4] * z + calibration_[5] * z * z - sigmay; // v = vx * vx + vy * vy; // if (v < minV) { // minV = v; // minIndex = i; // } // } // } // // if (minV > errTol_) { // return null; // } // // z_ = roots[minIndex].getReal(); // } if (calibration_ != null) { calculateZ(); } return pvp_.getPoint(); }
From source file:gdsc.smlm.fitting.nonlinear.ApacheLVMFitter.java
public FitStatus fit(int n, double[] y, double[] y_fit, double[] a, double[] a_dev, double[] error, double noise) { numberOfFittedPoints = n;/*from ww w . j a va2 s .c om*/ try { // Different convergence thresholds seem to have no effect on the resulting fit, only the number of // iterations for convergence final double initialStepBoundFactor = 100; final double costRelativeTolerance = 1e-10; final double parRelativeTolerance = 1e-10; final double orthoTolerance = 1e-10; final double threshold = Precision.SAFE_MIN; // Extract the parameters to be fitted final double[] initialSolution = getInitialSolution(a); // TODO - Pass in more advanced stopping criteria. // Create the target and weight arrays final double[] yd = new double[n]; final double[] w = new double[n]; for (int i = 0; i < n; i++) { yd[i] = y[i]; w[i] = 1; } LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(initialStepBoundFactor, costRelativeTolerance, parRelativeTolerance, orthoTolerance, threshold); PointVectorValuePair optimum = optimizer.optimize(new MaxIter(getMaxEvaluations()), new MaxEval(Integer.MAX_VALUE), new ModelFunctionJacobian(new MultivariateMatrixFunctionWrapper(f, a, n)), new ModelFunction(new MultivariateVectorFunctionWrapper(f, a, n)), new Target(yd), new Weight(w), new InitialGuess(initialSolution)); final double[] parameters = optimum.getPoint(); setSolution(a, parameters); iterations = optimizer.getIterations(); evaluations = optimizer.getEvaluations(); if (a_dev != null) { double[][] covar = optimizer.computeCovariances(parameters, threshold); setDeviations(a_dev, covar); } // Compute fitted function if desired if (y_fit != null) { f.initialise(a); for (int i = 0; i < n; i++) y_fit[i] = f.eval(i); } residualSumOfSquares = error[0] = optimizer.getChiSquare(); totalSumOfSquares = getSumOfSquares(n, y); } catch (TooManyEvaluationsException e) { return FitStatus.FAILED_TO_CONVERGE; } catch (ConvergenceException e) { // Occurs when QR decomposition fails - mark as a singular non-linear model (no solution) return FitStatus.SINGULAR_NON_LINEAR_MODEL; } catch (Exception e) { // TODO - Find out the other exceptions from the fitter and add return values to match. return FitStatus.UNKNOWN; } return FitStatus.OK; }
From source file:edu.uchc.octane.GaussianFit2D.java
@Override public double[] doFit() { double[] initParameters; if (floatingSigma_) { if (bPreprocessBg_) { initParameters = new double[] { 0, 0, pixelValue(0, 0) - bg_, sigma2_ }; } else {//from ww w . j av a2 s . c o m initParameters = new double[] { 0, 0, pixelValue(0, 0) - bg_, bg_, sigma2_ }; } } else { if (bPreprocessBg_) { initParameters = new double[] { 0, 0, pixelValue(0, 0) - bg_ }; } else { initParameters = new double[] { 0, 0, pixelValue(0, 0) - bg_, bg_ }; } } PowellOptimizer optimizer = new PowellOptimizer(1e-4, 1e-1); MultivariateFunction func = new MultivariateFunction() { @Override public double value(double[] point) { //initParameters = point; double bg = bPreprocessBg_ ? 0 : point[3]; double v = 0; for (int xi = -windowSize_; xi < windowSize_; xi++) { for (int yi = -windowSize_; yi < windowSize_; yi++) { double delta = getValueExcludingBackground(xi, yi, point) + bg - pixelValue(xi, yi); v += delta * delta; } } return v; } }; pvp_ = optimizer.optimize(new ObjectiveFunction(func), new InitialGuess(initParameters), new MaxEval(10000), GoalType.MINIMIZE); return pvp_.getPoint(); }
From source file:edu.cmu.tetrad.sem.SemOptimizerPowell.java
public void optimize(SemIm semIm) { double min = Double.POSITIVE_INFINITY; double[] point = null; for (int count = 0; count < numRestarts + 1; count++) { System.out.println("Trial " + (count + 1)); SemIm _sem2 = new SemIm(semIm); List<Parameter> freeParameters = _sem2.getFreeParameters(); double[] p = new double[freeParameters.size()]; for (int i = 0; i < freeParameters.size(); i++) { if (freeParameters.get(i).getType() == ParamType.VAR) { p[i] = RandomUtil.getInstance().nextUniform(0, 1); } else { p[i] = RandomUtil.getInstance().nextUniform(-1, 1); }/* w w w. ja v a2 s .c o m*/ } _sem2.setFreeParamValues(p); MultivariateOptimizer search = new PowellOptimizer(1e-7, 1e-7); PointValuePair pair = search.optimize(new InitialGuess(_sem2.getFreeParamValues()), new ObjectiveFunction(fittingFunction(semIm)), GoalType.MINIMIZE, new MaxEval(100000)); double chisq = _sem2.getChiSquare(); System.out.println("chisq = " + chisq); if (chisq < min) { min = chisq; point = pair.getPoint(); } } System.arraycopy(point, 0, semIm.getFreeParamValues(), 0, point.length); }
From source file:edu.cmu.tetrad.regression.LogisticRegression2.java
public void regress(int[] target, int numValues, double[][] regressors) { try {/*from w w w. j a v a 2 s . c o m*/ int numParams = regressors.length + 1; double[] coefficients = new double[(numValues - 1) * numParams]; // Apparently this needs to be fairly loose. int tolerance = 250; MultivariateOptimizer search = new PowellOptimizer(tolerance, tolerance); PointValuePair pair = search.optimize(new InitialGuess(coefficients), new ObjectiveFunction(new FittingFunction(target, regressors)), GoalType.MAXIMIZE, new MaxEval(1000000)); this.likelihood = pair.getValue(); } catch (TooManyEvaluationsException e) { e.printStackTrace(); this.likelihood = Double.NaN; } }
From source file:net.sf.tweety.math.opt.solver.ApacheCommonsNonLinearConjugateGradientOptimizer.java
@Override public Map<Variable, Term> solve(ConstraintSatisfactionProblem problem) throws GeneralMathException { // only optimization problems if (!(problem instanceof OptimizationProblem)) throw new IllegalArgumentException("Only optimization problems allowed for this solver."); OptimizationProblem p = (OptimizationProblem) problem; // no constraints allowed if (!p.isEmpty()) throw new IllegalArgumentException( "Only optimization problems without constraints allowed for this solver."); final Term target = p.getTargetFunction(); final List<Variable> vars = new ArrayList<Variable>(target.getVariables()); MultivariateFunction acTarget = new MultivariateFunction() { @Override// w w w.ja va 2 s. co m public double value(double[] arg0) { return target.replaceAllTerms(arg0, vars).doubleValue(); } }; final Term[] targetGradient = new Term[vars.size()]; for (int i = 0; i < vars.size(); i++) targetGradient[i] = target.derive(vars.get(i)); MultivariateVectorFunction acTargetGradient = new MultivariateVectorFunction() { @Override public double[] value(double[] arg0) throws IllegalArgumentException { double[] result = new double[arg0.length]; for (int i = 0; i < arg0.length; i++) result[i] = targetGradient[i].replaceAllTerms(arg0, vars).doubleValue(); return result; } }; // create solver NonLinearConjugateGradientOptimizer optimizer = new NonLinearConjugateGradientOptimizer( NonLinearConjugateGradientOptimizer.Formula.FLETCHER_REEVES, new SimplePointChecker<PointValuePair>(this.precision, this.precision)); double[] s = new double[vars.size()]; for (int i = 0; i < vars.size(); i++) s[i] = 0.5; PointValuePair val = optimizer.optimize(new ObjectiveFunction(acTarget), new ObjectiveFunctionGradient(acTargetGradient), new InitialGuess(s), p.getType() == OptimizationProblem.MAXIMIZE ? GoalType.MAXIMIZE : GoalType.MINIMIZE, new MaxEval(this.maxEval)); Map<Variable, Term> result = new HashMap<Variable, Term>(); for (int i = 0; i < vars.size(); i++) result.put(vars.get(i), new FloatConstant(val.getPoint()[i])); return result; }
From source file:de.bund.bfr.math.MultivariateOptimization.java
@Override public Result optimize(int nParameterSpace, int nOptimizations, boolean stopWhenSuccessful, Map<String, Double> minStartValues, Map<String, Double> maxStartValues, int maxIterations, DoubleConsumer progessListener, ExecutionContext exec) throws CanceledExecutionException { if (exec != null) { exec.checkCanceled();//from ww w . j a v a 2s . com } progessListener.accept(0.0); List<ParamRange> ranges = MathUtils.getParamRanges(parameters, minStartValues, maxStartValues, nParameterSpace); ranges.set(parameters.indexOf(sdParam), new ParamRange(1.0, 1, 1.0)); List<StartValues> startValuesList = MathUtils.createStartValuesList(ranges, nOptimizations, values -> optimizerFunction.value(Doubles.toArray(values)), progress -> progessListener.accept(0.5 * progress), exec); Result result = new Result(); AtomicInteger currentIteration = new AtomicInteger(); SimplexOptimizer optimizer = new SimplexOptimizer(new SimpleValueChecker(1e-10, 1e-10) { @Override public boolean converged(int iteration, PointValuePair previous, PointValuePair current) { if (super.converged(iteration, previous, current)) { return true; } return currentIteration.incrementAndGet() >= maxIterations; } }); int count = 0; for (StartValues startValues : startValuesList) { if (exec != null) { exec.checkCanceled(); } progessListener.accept(0.5 * count++ / startValuesList.size() + 0.5); try { PointValuePair optimizerResults = optimizer.optimize(new MaxEval(Integer.MAX_VALUE), new MaxIter(maxIterations), new InitialGuess(Doubles.toArray(startValues.getValues())), new ObjectiveFunction(optimizerFunction), GoalType.MAXIMIZE, new NelderMeadSimplex(parameters.size())); double logLikelihood = optimizerResults.getValue() != null ? optimizerResults.getValue() : Double.NaN; if (result.logLikelihood == null || logLikelihood > result.logLikelihood) { result = getResults(optimizerResults); if (result.logLikelihood == 0.0 || stopWhenSuccessful) { break; } } } catch (TooManyEvaluationsException | TooManyIterationsException | ConvergenceException e) { } } return result; }