Example usage for org.apache.commons.math3.optim.univariate BrentOptimizer BrentOptimizer

List of usage examples for org.apache.commons.math3.optim.univariate BrentOptimizer BrentOptimizer

Introduction

In this page you can find the example usage for org.apache.commons.math3.optim.univariate BrentOptimizer BrentOptimizer.

Prototype

public BrentOptimizer(double rel, double abs) 

Source Link

Document

The arguments are used for implementing the original stopping criterion of Brent's algorithm.

Usage

From source file:com.google.cloud.genomics.dataflow.functions.verifybamid.Solver.java

/**
 * Maximizes a univariate function using a grid search followed by Brent's algorithm.
 *
 * @param fn the likelihood function to minimize
 * @param gridStart the lower bound for the grid search
 * @param gridEnd the upper bound for the grid search
 * @param gridStep step size for the grid search
 * @param relErr relative error tolerance for Brent's algorithm
 * @param absErr absolute error tolerance for Brent's algorithm
 * @param maxIter maximum # of iterations to perform in Brent's algorithm
 * @param maxEval maximum # of Likelihood function evaluations in Brent's algorithm
 *
 * @return the value of the parameter that maximizes the function
 *///from   w ww  . ja  va  2  s .c  o m
public static double maximize(UnivariateFunction fn, double gridStart, double gridEnd, double gridStep,
        double relErr, double absErr, int maxIter, int maxEval) {
    Interval interval = gridSearch(fn, gridStart, gridEnd, gridStep);
    BrentOptimizer bo = new BrentOptimizer(relErr, absErr);
    UnivariatePointValuePair max = bo.optimize(new MaxIter(maxIter), new MaxEval(maxEval),
            new SearchInterval(interval.getInf(), interval.getSup()), new UnivariateObjectiveFunction(fn),
            GoalType.MAXIMIZE);
    return max.getPoint();
}

From source file:com.itemanalysis.psychometrics.irt.equating.IrtScaleLinking.java

public void computeCoefficients() {
    raschFamily = checkRaschModel();//from w w  w. j av  a2s  .co  m

    ms.setPrecision(precision);
    mm.setPrecision(precision);
    hb.setPrecision(precision);
    sl.setPrecision(precision);

    if (raschFamily) {

        double[] sv = { mm.getIntercept() };

        UnivariateOptimizer underlying = new BrentOptimizer(1e-10, 1e-14);
        JDKRandomGenerator g = new JDKRandomGenerator();

        //Haebara method
        MultiStartUnivariateOptimizer optimizer = new MultiStartUnivariateOptimizer(underlying, 5, g);//Five random starts to Brent optimizer.
        UnivariatePointValuePair hbPair = optimizer.optimize(new MaxEval(500),
                new UnivariateObjectiveFunction(hb), GoalType.MINIMIZE, new SearchInterval(-4, 4),
                new InitialGuess(sv));
        hb.setIntercept(hbPair.getPoint());
        hb.setScale(1.0);
        fHB = hbPair.getValue();

        //Stocking-Lord method
        UnivariatePointValuePair slPair = optimizer.optimize(new MaxEval(500),
                new UnivariateObjectiveFunction(sl), GoalType.MINIMIZE, new SearchInterval(-4, 4),
                new InitialGuess(sv));
        sl.setIntercept(slPair.getPoint());
        sl.setScale(1.0);
        fSL = slPair.getValue();

    } else {

        double[] hbStartValues = { mm.getIntercept(), mm.getScale() };
        double[] slStartValues = { mm.getIntercept(), mm.getScale() };

        if (useUncmin) {
            DefaultUncminOptimizer optimizer = new DefaultUncminOptimizer();

            try {

                optimizer.minimize(hb, hbStartValues);
                double[] param = optimizer.getParameters();
                fHB = optimizer.getFunctionValue();
                hb.setIntercept(param[0]);

                if (param.length > 1) {
                    hb.setScale(param[1]);
                } else {
                    hb.setScale(1.0);//Rasch family of models
                }

                optimizer.minimize(sl, slStartValues);
                param = optimizer.getParameters();
                fSL = optimizer.getFunctionValue();
                sl.setIntercept(param[0]);

                if (param.length > 1) {
                    sl.setScale(param[1]);
                } else {
                    sl.setScale(1.0);//Rasch family of models
                }

            } catch (UncminException ex) {
                ex.printStackTrace();
            }
        } else {

            int numIterpolationPoints = 2 * 2;//two dimensions A and B
            BOBYQAOptimizer underlying = new BOBYQAOptimizer(numIterpolationPoints);
            RandomGenerator g = new JDKRandomGenerator();
            RandomVectorGenerator generator = new UncorrelatedRandomVectorGenerator(2,
                    new GaussianRandomGenerator(g));
            MultiStartMultivariateOptimizer optimizer = new MultiStartMultivariateOptimizer(underlying, 10,
                    generator);
            PointValuePair hbOptimum = optimizer.optimize(new MaxEval(1000), new ObjectiveFunction(hb),
                    GoalType.MINIMIZE, SimpleBounds.unbounded(2), new InitialGuess(hbStartValues));

            double[] hbCoefficients = hbOptimum.getPoint();
            hb.setIntercept(hbCoefficients[0]);
            hb.setScale(hbCoefficients[1]);
            fHB = hbOptimum.getValue();

            PointValuePair slOptimum = optimizer.optimize(new MaxEval(1000), new ObjectiveFunction(sl),
                    GoalType.MINIMIZE, SimpleBounds.unbounded(2), new InitialGuess(slStartValues));

            double[] slCoefficients = slOptimum.getPoint();
            sl.setIntercept(slCoefficients[0]);
            sl.setScale(slCoefficients[1]);
            fSL = slOptimum.getValue();

        }

    }

}

From source file:edu.uchc.octane.GaussianFitAstigmatism.java

/**
 * calculate the Z coordinate based on astigmatism
 *///  www  . ja  v  a2s . c om
void calculateZ() {

    if (calibration_ == null) {
        z_ = 0;
        return;
    }

    UnivariateFunction func = new UnivariateFunction() {
        @Override
        public double value(double z) {
            double sigmax = FastMath.sqrt(pvp_.getPoint()[3] / 2);
            double sigmay = FastMath.sqrt(pvp_.getPoint()[4] / 2);
            double vx = calibration_[0] + (z - calibration_[1]) * (z - calibration_[1]) * calibration_[2]
                    - sigmax;
            double vy = calibration_[3] + (z - calibration_[4]) * (z - calibration_[4]) * calibration_[5]
                    - sigmay;
            return vx * vx + vy * vy;
        }
    };

    BrentOptimizer optimizer = new BrentOptimizer(1e-4, 1e-4);

    UnivariatePointValuePair upvp = optimizer.optimize(new UnivariateObjectiveFunction(func), GoalType.MINIMIZE,
            MaxEval.unlimited(), new SearchInterval(2 * z0min_ - z0max_, 2 * z0max_ - z0min_));

    if (upvp.getValue() > errTol_) {
        throw (new ConvergenceException());
    }

    z_ = upvp.getPoint();
}

From source file:eu.crisis_economics.abm.algorithms.optimization.BrentLineSearch.java

/**
  * Perform a line search minimization. This function accepts as input:
  *   (a) a starting point (a vector),/*from   w w  w .  j a  va 2s . co  m*/
  *   (b) a direction in which to travel (a vector),
  *   (c) limits on the total distance to travel along (b).
  *   
  * With these inputs the function attempts to find the minimum of a
  * scalar-valued multivariate function along the line starting at 
  * (a) and pointing in the direction of (b).
  * 
  * @param function
  *        A scalar-valued multivariate function to minimize,
  * @param startingPoint
  *        A vector starting point from which to begin the minimization (P),
  * @param vectorDirection
  *        A vector direction along which to travel from P, (V)
  * @param maximumDistanceToTravel
  *        The maximum distance to travel in the direction of V,
  * @param maximumEvaluations
  *        The maximum number of function evaluations to identify the minimum,
  * @param relativeErrorGoal
  *        The relative error target of the minimization,
  * @param absoluteErrorGoal
  *        The absolute error target of the minimization.
  * @return
  *        A lightweight immutable struct containing the vector solution and
  *        the evaluation of the function at this point.
  */
static public LineSearchResult doLineSearch(final MultivariateFunction function, final double[] startingPoint,
        final double[] vectorDirection, final double maximumDistanceToTravel, final int maximumEvaluations,
        final double relativeErrorGoal, final double absoluteErrorGoal) {
    Preconditions.checkArgument(maximumEvaluations > 0);
    Preconditions.checkArgument(relativeErrorGoal > 0. || absoluteErrorGoal > 0.);
    Preconditions.checkArgument(maximumDistanceToTravel > 0.);
    final LineSearchObjectiveFunction lineSearcher = new LineSearchObjectiveFunction(function, startingPoint,
            vectorDirection);
    final UnivariateOptimizer optimizer = new BrentOptimizer(relativeErrorGoal, absoluteErrorGoal);
    UnivariatePointValuePair result = optimizer.optimize(new MaxEval(maximumEvaluations),
            new UnivariateObjectiveFunction(lineSearcher), GoalType.MINIMIZE,
            new SearchInterval(0, maximumDistanceToTravel, 0));
    final double[] vectorSolution = new double[startingPoint.length];
    for (int i = 0; i < vectorDirection.length; ++i)
        vectorSolution[i] = lineSearcher.startingPoint[i]
                + lineSearcher.normalizedDirection[i] * result.getPoint();
    final LineSearchResult solution = new LineSearchResult(vectorSolution, result.getValue());
    return solution;
}

From source file:com.itemanalysis.psychometrics.irt.estimation.IrtExaminee.java

/**
 * Maximum likelihood estimate (MLE) of examinee ability.
 *
 * @param thetaMin smallest possible ability estimate (lower bound on BrentOptimizer)
 * @param thetaMax largest possible ability estimate (upper bound on BrentOptimizer)
 * @return MLE of examinee ability//from   w  w  w.j  a  va 2 s  .  c  o m
 */
public double maximumLikelihoodEstimate(double thetaMin, double thetaMax) {
    method = EstimationMethod.ML;
    UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
    UnivariatePointValuePair pair = optimizer.optimize(new MaxEval(100), new UnivariateObjectiveFunction(this),
            GoalType.MAXIMIZE, new SearchInterval(thetaMin, thetaMax));
    estimatedTheta = pair.getPoint();
    return estimatedTheta;
}

From source file:com.wwidesigner.modelling.PlayingRange.java

/**
 * Construct a playing-range calculator for a specified fingering.
 * @param calculator//  www  . j  a  v  a  2  s  .c om
 * @param fingering
 */
public PlayingRange(InstrumentCalculator calculator, Fingering fingering) {
    this.calculator = calculator;
    this.fingering = fingering;
    this.reactance = new Reactance();
    this.zMagnitude = new ZMagnitude();
    this.gainOne = new Gain();
    this.zRatio = new ZRatio();
    this.solver = new BrentSolver();
    this.optimizer = new BrentOptimizer(0.0001, 0.0001); // Approximate minimum is sufficient.
}

From source file:com.itemanalysis.psychometrics.irt.estimation.IrtExaminee.java

/**
 * Maximum a Posteriori (MAP) estimate of examinee ability using a normal prior
 * distribution.//w  ww  .  j av  a  2s .c om
 *
 * @param mean mean of normal prior distribution
 * @param sd standard deviation of prior distribution
 * @param thetaMin smallest possible ability estimate (lower bound on BrentOptimizer)
 * @param thetaMax largest possible ability estimate (upper bound on BrentOptimizer)
 * @return MAP estimate of examinee ability
 */
public double mapEstimate(double mean, double sd, double thetaMin, double thetaMax) {
    mapPrior = new NormalDistribution(mean, sd);
    method = EstimationMethod.MAP;
    UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
    UnivariatePointValuePair pair = optimizer.optimize(new MaxEval(100), new UnivariateObjectiveFunction(this),
            GoalType.MAXIMIZE, new SearchInterval(thetaMin, thetaMax));
    estimatedTheta = pair.getPoint();
    return estimatedTheta;
}

From source file:com.wwidesigner.optimization.ObjectiveFunctionOptimizer.java

protected static PointValuePair doSingleStart(BaseObjectiveFunction objective, double[] startPoint,
        int maxEvaluations, double[] nextStart) {
    singleRunEvaluations = 0;/*ww w  .ja va2s . c o  m*/
    PointValuePair result = null;
    try {
        int numVariables = objective.getNrDimensions();
        if (numVariables > 1) // Use BOBYQA
        {
            double trustRegion = objective.getInitialTrustRegionRadius(nextStart);
            double stoppingTrustRegion = objective.getStoppingTrustRegionRadius();
            BOBYQAOptimizer optimizer = new BOBYQAOptimizer(objective.getNrInterpolations(), trustRegion,
                    stoppingTrustRegion);
            result = runBobyqa(optimizer, objective, nextStart, maxEvaluations);
            singleRunEvaluations = optimizer.getEvaluations();
        } else
        // Use Brent
        {
            BrentOptimizer optimizer = new BrentOptimizer(1.e-6, 1.e-14);
            UnivariatePointValuePair outcome = runBrent(optimizer, objective, startPoint);
            result = new PointValuePair(new double[] { outcome.getPoint() }, outcome.getValue());
            singleRunEvaluations = optimizer.getEvaluations();
        }
        double value = result.getValue();
        if (value == Double.POSITIVE_INFINITY) {
            System.out.print("no valid solution found");
        } else {
            System.out.print("optimum " + result.getValue());
        }
    } catch (TooManyEvaluationsException e) {
        System.out.println("Exception: " + e.getMessage());
    }
    // Thrown by BOBYQA for no apparent reason: a bug?
    catch (NoSuchElementException e) {
        System.out.println("no valid solution found");
    } catch (OperationCancelledException e) {
        // Restore starting point.
        objective.setGeometryPoint(startPoint);
        // Re-throw the exception to give up the whole multi-start
        // optimization.
        throw new OperationCancelledException(e.getMessage());
    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
        // e.printStackTrace();
    } finally {
        System.out.println(" at start point " + Arrays.toString(nextStart));
    }

    return result;
}

From source file:imagingbook.pub.fd.FourierDescriptor.java

/** 
 * Calculates the 'canonical' start point. This version uses 
 * (a) a coarse search for a global maximum of fp() and subsequently 
 * (b) a numerical optimization using Brent's method
 * (implemented with Apache Commons Math).
 *//*  w ww. j  a  va  2  s  .co m*/
public double getStartPointPhase(int Mp) {
    Mp = Math.min(Mp, (G.length - 1) / 2);
    UnivariateFunction fp = new TargetFunction(Mp);
    // search for the global maximum in coarse steps
    double cmax = Double.NEGATIVE_INFINITY;
    int kmax = -1;
    int K = 25; // number of steps over 180 degrees
    for (int k = 0; k < K; k++) {
        final double phi = Math.PI * k / K; // phase to evaluate
        final double c = fp.value(phi);
        if (c > cmax) {
            cmax = c;
            kmax = k;
        }
    }
    // optimize using previous and next point as the bracket.
    double minPhi = Math.PI * (kmax - 1) / K;
    double maxPhi = Math.PI * (kmax + 1) / K;

    UnivariateOptimizer optimizer = new BrentOptimizer(1E-4, 1E-6);
    int maxIter = 20;
    UnivariatePointValuePair result = optimizer.optimize(new MaxEval(maxIter),
            new UnivariateObjectiveFunction(fp), GoalType.MAXIMIZE, new SearchInterval(minPhi, maxPhi));
    double phi0 = result.getPoint();
    return phi0; // the canonical start point phase
}

From source file:com.wwidesigner.optimization.ObjectiveFunctionOptimizer.java

protected static UnivariatePointValuePair runBrent(BaseObjectiveFunction objective, double[] startPoint)
        throws TooManyEvaluationsException {
    BrentOptimizer optimizer = new BrentOptimizer(1.e-6, 1.e-14);

    return runBrent(optimizer, objective, startPoint);
}