当前位置: 首页>>代码示例>>Java>>正文


Java BrentOptimizer类代码示例

本文整理汇总了Java中org.apache.commons.math3.optim.univariate.BrentOptimizer的典型用法代码示例。如果您正苦于以下问题:Java BrentOptimizer类的具体用法?Java BrentOptimizer怎么用?Java BrentOptimizer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


BrentOptimizer类属于org.apache.commons.math3.optim.univariate包,在下文中一共展示了BrentOptimizer类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: optimizeUni

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
public double optimizeUni() throws Exception {
	double maxLh=0;
	
	BrentOptimizer optimizer = new BrentOptimizer(1e-6, 1e-12);
       UnivariatePointValuePair optimum =
               optimizer.optimize(new UnivariateObjectiveFunction(this),
                                  new MaxEval(100),
                                  GoalType.MAXIMIZE,
                                  new SearchInterval(pfBoundsLower[0],pfBoundsUpper[0])); 
	
	
	//double point = optimum.getPoint();
	//System.out.print("--> "+paramName+": "+paramValue+" point= "+point);		
	//System.out.print(" ");
	//System.out.println("value = "+ optimum.getValue());
	maxLh = optimum.getValue();	
	optPoint[0] = optimum.getPoint();
	return maxLh;
}
 
开发者ID:mrc-ide,项目名称:PhyDyn,代码行数:20,代码来源:PhyDynSlice.java

示例2: getStartPointPhase

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
/**
 * 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).
 * 
 * @param Mp number of Fourier coefficient pairs
 * @return start point phase
 */
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
}
 
开发者ID:imagingbook,项目名称:imagingbook-common,代码行数:40,代码来源:FourierDescriptor.java

示例3: getOptimalTime

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
Pair<LocalDateTime, Double> getOptimalTime(Path path,
		TimeRange<LocalDateTime> timeRange, int starts) {

	// the objective function to be passed to the BrentOptimizer
	UnivariateFunction univariateFunction = (x) -> {
		LocalDateTime time = timeRange.getFrom().plusSeconds((long) x);

		Weighting weighting = routingHelper
				.createWeighting(this.weightingType, time);

		OptionalDouble value = objectiveFunctionPath.value(time, path,
				weighting);
		if (value.isPresent()) {
			return value.getAsDouble();
		} else {
			return Double.MAX_VALUE;
		}
	};

	// interval used for optimization is 0 and the duration between the
	// lower and upper bound in seconds
	double lower = 0;
	double upper = timeRange.durationInSeconds() + 1;

	logger.debug("lower = " + lower + ", upper = " + upper);

	BrentOptimizer optimizer = new BrentOptimizer(RELATIVE_THRESHOLD,
			ABSOLUTE_THRESHOLD);
	MultiStartUnivariateOptimizer multiStartOptimizer = new MultiStartUnivariateOptimizer(
			optimizer, starts, rng);
	UnivariatePointValuePair res = multiStartOptimizer.optimize(
			new MaxEval(MAX_EVAL), GOAL_TYPE,
			new SearchInterval(lower, upper),
			new UnivariateObjectiveFunction(univariateFunction));

	return Pair.of(timeRange.getFrom().plusSeconds((long) res.getPoint()),
			res.getValue());
}
 
开发者ID:biggis-project,项目名称:path-optimizer,代码行数:39,代码来源:OptimalTimeFinderHeuristic.java

示例4: calculatePosteriorMode

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
/**
 * Given a list of posterior samples, returns an estimate of the posterior mode (using
 * mllib kernel density estimation in {@link KernelDensity} and {@link BrentOptimizer}).
 * Note that estimate may be poor if number of samples is small (resulting in poor kernel density estimation),
 * or if posterior is not unimodal (or is sufficiently pathological otherwise). If the samples contain
 * {@link Double#NaN}, {@link Double#NaN} will be returned.
 * @param samples   posterior samples, cannot be {@code null} and number of samples must be greater than 0
 * @param ctx       {@link JavaSparkContext} used by {@link KernelDensity} for mllib kernel density estimation
 */
public static double calculatePosteriorMode(final List<Double> samples, final JavaSparkContext ctx) {
    Utils.nonNull(samples);
    Utils.validateArg(samples.size() > 0, "Number of samples must be greater than zero.");

    //calculate sample min, max, mean, and standard deviation
    final double sampleMin = Collections.min(samples);
    final double sampleMax = Collections.max(samples);
    final double sampleMean = new Mean().evaluate(Doubles.toArray(samples));
    final double sampleStandardDeviation = new StandardDeviation().evaluate(Doubles.toArray(samples));

    //if samples are all the same or contain NaN, can simply return mean
    if (sampleStandardDeviation == 0. || Double.isNaN(sampleMean)) {
        return sampleMean;
    }

    //use Silverman's rule to set bandwidth for kernel density estimation from sample standard deviation
    //see https://en.wikipedia.org/wiki/Kernel_density_estimation#Practical_estimation_of_the_bandwidth
    final double bandwidth =
            SILVERMANS_RULE_CONSTANT * sampleStandardDeviation * Math.pow(samples.size(), SILVERMANS_RULE_EXPONENT);

    //use kernel density estimation to approximate posterior from samples
    final KernelDensity pdf = new KernelDensity().setSample(ctx.parallelize(samples, 1)).setBandwidth(bandwidth);

    //use Brent optimization to find mode (i.e., maximum) of kernel-density-estimated posterior
    final BrentOptimizer optimizer =
            new BrentOptimizer(RELATIVE_TOLERANCE, RELATIVE_TOLERANCE * (sampleMax - sampleMin));
    final UnivariateObjectiveFunction objective =
            new UnivariateObjectiveFunction(f -> pdf.estimate(new double[] {f})[0]);
    //search for mode within sample range, start near sample mean
    final SearchInterval searchInterval = new SearchInterval(sampleMin, sampleMax, sampleMean);
    return optimizer.optimize(objective, GoalType.MAXIMIZE, searchInterval, BRENT_MAX_EVAL).getPoint();
}
 
开发者ID:broadinstitute,项目名称:gatk-protected,代码行数:42,代码来源:PosteriorSummaryUtils.java

示例5: optimizeIt

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
private double optimizeIt(final Function<Double, Double> objectiveFxn, final SearchInterval searchInterval) {
    final MaxEval BRENT_MAX_EVAL = new MaxEval(1000);
    final double RELATIVE_TOLERANCE = 0.001;
    final double ABSOLUTE_TOLERANCE = 0.001;
    final BrentOptimizer OPTIMIZER = new BrentOptimizer(RELATIVE_TOLERANCE, ABSOLUTE_TOLERANCE);

    final UnivariateObjectiveFunction objective = new UnivariateObjectiveFunction(x -> objectiveFxn.apply(x));
    return OPTIMIZER.optimize(objective, GoalType.MAXIMIZE, searchInterval, BRENT_MAX_EVAL).getPoint();
}
 
开发者ID:broadinstitute,项目名称:gatk-protected,代码行数:10,代码来源:CNLOHCaller.java

示例6: doLineSearch

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
/**
  * Perform a line search minimization. This function accepts as input:
  *   (a) a starting point (a vector),
  *   (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;
}
 
开发者ID:crisis-economics,项目名称:CRISIS,代码行数:59,代码来源:BrentLineSearch.java

示例7: getOptimalTime

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
/**
 * Helper function to find the optimal point in time.
 * 
 * @param start
 *            the start point
 * @param place
 *            the place to find the optimal time for
 * @param timeRange
 *            the lower and upper interval limits in which should be
 *            searched for the optimal value
 * @param minWalkingTime
 *            minimum time required to walk from {@code start} to
 *            {@code place}
 * @param starts
 *            number of start to be performed by the Brent optimizer
 * @return optimal point in time and the optimal value of the objective
 *         function
 */
Pair<LocalDateTime, Double> getOptimalTime(GHPoint start, GHPoint place,
		TimeRange<LocalDateTime> timeRange, long minWalkingTime,
		int starts) {

	// the objective function to be passed to the BrentOptimizer
	UnivariateFunction univariateFunction = (x) -> {
		LocalDateTime time = timeRange.getFrom().plusSeconds((long) x);
		OptionalDouble value = objectiveFunction.value(time, start, place,
				timeRange, minWalkingTime);
		if (value.isPresent()) {
			return value.getAsDouble();
		} else {
			// if no value is returned by the objectiveFunction than either
			// the constrain has be violated or there is no value available
			logger.debug("constrains violated! (time = " + time
					+ ", timeRange = " + timeRange + ", lastWalkingTime = "
					+ Utils.formatDurationMills(objectiveFunction
							.getLastWalkingTime().getAsLong())
					+ ", start = " + start + ", place = " + place + ")");
			return Double.MAX_VALUE;
		}
	};

	// interval used for optimization is 0 and the duration between the
	// lower and upper bound in seconds
	double lower = 0;
	double upper = timeRange.durationInSeconds() + 1;

	BrentOptimizer optimizer = new BrentOptimizer(RELATIVE_THRESHOLD,
			ABSOLUTE_THRESHOLD);
	MultiStartUnivariateOptimizer multiStartOptimizer = new MultiStartUnivariateOptimizer(
			optimizer, starts, rng);
	UnivariatePointValuePair res = multiStartOptimizer.optimize(
			new MaxEval(MAX_EVAL), GOAL_TYPE,
			new SearchInterval(lower, upper),
			new UnivariateObjectiveFunction(univariateFunction));

	return Pair.of(timeRange.getFrom().plusSeconds((long) res.getPoint()),
			res.getValue());
}
 
开发者ID:biggis-project,项目名称:path-optimizer,代码行数:59,代码来源:OptimalTimeFinder.java

示例8: argmax

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
public static double argmax(final Function<Double, Double> function, final double min, final double max, final double guess,
                            final double relativeTolerance, final double absoluteTolerance, final int maxEvaluations) {
    final BrentOptimizer optimizer = new BrentOptimizer(relativeTolerance, absoluteTolerance);
    final SearchInterval interval = new SearchInterval(min, max, guess);
    return optimizer.optimize(new UnivariateObjectiveFunction(function::apply), GoalType.MAXIMIZE, interval, new MaxEval(maxEvaluations)).getPoint();
}
 
开发者ID:broadinstitute,项目名称:gatk-protected,代码行数:7,代码来源:OptimizationUtils.java

示例9: LineSearch

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
/**
 * The {@code BrentOptimizer} default stopping criterion uses the
 * tolerances to check the domain (point) values, not the function
 * values.
 * The {@code relativeTolerance} and {@code absoluteTolerance}
 * arguments are thus passed to a {@link SimpleUnivariateValueChecker
 * custom checker} that will use the function values.
 *
 * @param optimizer Optimizer on behalf of which the line search
 * be performed.
 * Its {@link MultivariateOptimizer#computeObjectiveValue(double[])
 * computeObjectiveValue} method will be called by the
 * {@link #search(double[],double[]) search} method.
 * @param relativeTolerance Search will stop when the function relative
 * difference between successive iterations is below this value.
 * @param absoluteTolerance Search will stop when the function absolute
 * difference between successive iterations is below this value.
 * @param initialBracketingRange Extent of the initial interval used to
 * find an interval that brackets the optimum.
 * If the optimized function varies a lot in the vicinity of the optimum,
 * it may be necessary to provide a value lower than the distance between
 * successive local minima.
 */
public LineSearch(MultivariateOptimizer optimizer,
                  double relativeTolerance,
                  double absoluteTolerance,
                  double initialBracketingRange) {
    mainOptimizer = optimizer;
    lineOptimizer = new BrentOptimizer(REL_TOL_UNUSED,
                                       ABS_TOL_UNUSED,
                                       new SimpleUnivariateValueChecker(relativeTolerance,
                                                                        absoluteTolerance));
    this.initialBracketingRange = initialBracketingRange;
}
 
开发者ID:biocompibens,项目名称:SME,代码行数:35,代码来源:LineSearch.java

示例10: maximize

import org.apache.commons.math3.optim.univariate.BrentOptimizer; //导入依赖的package包/类
/**
 * 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
 */
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();
}
 
开发者ID:googlegenomics,项目名称:dataflow-java,代码行数:27,代码来源:Solver.java


注:本文中的org.apache.commons.math3.optim.univariate.BrentOptimizer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。