Example usage for org.apache.commons.math3.optimization GoalType MINIMIZE

List of usage examples for org.apache.commons.math3.optimization GoalType MINIMIZE

Introduction

In this page you can find the example usage for org.apache.commons.math3.optimization GoalType MINIMIZE.

Prototype

GoalType MINIMIZE

To view the source code for org.apache.commons.math3.optimization GoalType MINIMIZE.

Click Source Link

Document

Minimization goal.

Usage

From source file:com.itemanalysis.psychometrics.polycor.PolychoricTwoStepOLD.java

/**
 * Compute the two-step approximation to the polychoric correlation.
 *
 * @param data two way array of frequency counts
 *//* w w  w .j a  va2  s.  co  m*/
public void compute(double[][] data) {
    loglik = new PolychoricLogLikelihoodTwoStep(data);
    BrentOptimizer brent = new BrentOptimizer(1e-10, 1e-14);
    UnivariatePointValuePair result = brent.optimize(200, loglik, GoalType.MINIMIZE, -1.0, 1.0);
    rhoComputed = true;
    rho = result.getPoint();
}

From source file:gamlss.algorithm.GlobalOptimGAMLSS.java

/**
 * optimises the objective function//from w w  w  .j  a  va 2  s.c o  m
 * @param optim the optimizer such as CMAESOptimizer or BOBYQAOptimizer
 * @param startValues the starting values of the optimisation 
 * @return the point/value pair giving the optimal value for objective function. 
 */
public PointValuePair optimazer(BaseAbstractMultivariateOptimizer<MultivariateFunctionMappingAdapter> optim,
        double[] startValues) {
    PointValuePair results = null;
    try {
        results = optim.optimize(100000, this.objFunction, GoalType.MINIMIZE, startValues);
    } catch (MaxCountExceededException e) {
        System.err.println("more optimisation steps are needed - best results so far are returned");
    }
    return results;
}

From source file:com.itemanalysis.psychometrics.kernel.LeastSquaresCrossValidation.java

public double value() {
    BrentOptimizer brent = new BrentOptimizer(1e-10, 1e-14);
    UnivariatePointValuePair pair;//from w  ww .  j ava 2  s .co  m
    try {
        pair = brent.optimize(400, this, GoalType.MINIMIZE, 0.01, sd);
    } catch (Exception ex) {
        return Double.NaN;
    }
    return pair.getPoint();
}

From source file:edu.stevens.cpe.reservior.readout.CMAES.java

public double[] train(int numberWeightsToTrain) {
    this.epoch = 0;

    //Number of weights to evolve
    final double[] start = new double[numberWeightsToTrain];
    Arrays.fill(start, startValue);
    final double[] lower = new double[numberWeightsToTrain];
    Arrays.fill(lower, lowerBound);
    final double[] upper = new double[numberWeightsToTrain];
    Arrays.fill(upper, upperBound);

    //Set to 1/3 the initial search volume
    final double[] sigma = new double[numberWeightsToTrain];
    Arrays.fill(sigma, insigma);//from ww w .j av a2s.co  m

    int lambda = 4 + (int) (3. * Math.log(numberWeightsToTrain));
    int maxEvals = CMAESOptimizer.DEFAULT_MAXITERATIONS;
    double stopValue = .01;
    boolean isActive = true; //Chooses the covariance matrix update method.
    int diagonalOnly = 0;
    int checkFeasable = 0;
    final CMAESOptimizer optimizer = new CMAESOptimizer(lambda, sigma, CMAESOptimizer.DEFAULT_MAXITERATIONS,
            stopValue, isActive, diagonalOnly, checkFeasable, new MersenneTwister(), false);

    final PointValuePair result = optimizer.optimize(maxEvals, fitnessFuntion, GoalType.MINIMIZE, start, lower,
            upper);
    logger.info(Arrays.toString(result.getPoint()));
    logger.info("Best weights: " + Arrays.toString(bestWeights));

    updateReadoutWeights(result.getPoint());
    logger.info("done training.");
    return bestWeights;
}

From source file:edu.stevens.cpe.reservior.demo.EvolvedReservoir.java

/**
 * Optimize the convolution filter/*  w ww . ja v a2 s .  c  o m*/
 */
public void optimize(int size) {
    this.epoch = 0;

    //Number of weights to evolve
    final double[] start = new double[] { 3, 0, 1, 20, .1 };
    final double[] lower = new double[] { 1, 0, 0, 15, .08 };
    final double[] upper = new double[] { 5, 5, 3, 120, .3 };

    //Set to 1/3 the initial search volume
    final double[] sigma = new double[size];
    Arrays.fill(sigma, insigma);

    int lambda = 4 + (int) (3. * Math.log(size));
    int maxEvals = 100000;//CMAESOptimizer.DEFAULT_MAXITERATIONS;
    double stopValue = .01;
    boolean isActive = true; //Chooses the covariance matrix update method.
    int diagonalOnly = 0;
    int checkFeasable = 0;

    final CMAESOptimizer optimizer = new CMAESOptimizer(lambda, sigma, 100000, //CMAESOptimizer.DEFAULT_MAXITERATIONS,
            stopValue, isActive, diagonalOnly, checkFeasable, new MersenneTwister(), false);

    final PointValuePair result = optimizer.optimize(maxEvals, fitnessFuntion, GoalType.MINIMIZE, start, lower,
            upper);
    logger.info(Arrays.toString(result.getPoint()));

}

From source file:eu.smartenit.sbox.eca.ReferenceVectorCalculator.java

/**
 * Calculates the reference vector using simplex method.
 * //from  w ww.  ja  v  a2 s  .  c o  m
 * @param S1 The DC traffic manipulation freedom 
 * @param S2 The DC traffic manipulation freedom 
 * @param aList The list of candidate areas
 * @param sourceAsNumber The number of the source AS
 * @return Returns an RVector containing the reference vector values.
 */
private LocalRVector calculateReferenceVector(double[] S1, double[] S2, List<Area> aList, int sourceAsNumber) {
    List<PointValuePair> solutionList = new ArrayList<PointValuePair>();
    for (Area a : aList) {

        Long x1Lower = a.getD1().getLowerBound(); // Corresponds to alpha1i
        Long x1Upper = a.getD1().getUpperBound(); // Corresponds to alpha1i+1
        Long x2Lower = a.getD2().getLowerBound(); // Corresponds to alpha2i
        Long x2Upper = a.getD2().getUpperBound(); // Corresponds to alpha2i+1

        Segment segment1 = costFunctionMap1.get(x1Lower); // Corresponds to the suitable cf segment for alpha1
        Segment segment2 = costFunctionMap2.get(x2Lower); // Corresponds to the suitable cf segment for alpha2

        // Function    f:  f1(x1) + f2(x2) + c //c corresponds to the sum of the constant part of f1 and f2
        // Constraints c1: x1       >  alpha1i
        //             c2: x1       <= alpha1i+1 
        //             c3:      x2  >  alpha2j
        //             c4:      x2  <= alpha2j+1
        //             c5: x1 + x2  == X_V[x1] + X_V[x2]
        //            c6: x1       >= X_V[x1] + S1[x1]
        //             c7: x1       <= X_V[x1] + S2[x1]
        //             c8: x2       >= X_V[x2] + S2[x2]
        //              c9: x2       <= X_V[x2] + S1[x2]

        LinearObjectiveFunction f = new LinearObjectiveFunction(
                new double[] { segment1.getB(), segment2.getB() }, (segment1.getA() + segment2.getA())); //f1(x1) + f2(x2)
        Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
        constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, x1Lower.doubleValue()));
        constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, x1Upper.doubleValue()));
        constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, x2Lower.doubleValue()));
        constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, x2Upper.doubleValue()));
        constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, X_V[x1] + X_V[x2]));
        constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, X_V[x1] + S1[x1]));
        constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, X_V[x1] + S2[x1]));
        constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, X_V[x2] + S2[x2]));
        constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, X_V[x2] + S1[x2]));

        try {
            PointValuePair solution = new SimplexSolver().optimize(f, constraints, GoalType.MINIMIZE, true);
            solutionList.add(solution);

            double x = solution.getPoint()[0];
            double y = solution.getPoint()[1];
            double value = solution.getValue();
            logger.info("\n");
            logger.info("Area [" + x1Lower + ", " + x1Upper + ", " + x2Lower + ", " + x2Upper + "]");
            logger.info("Cost function: " + segment1.getB() + "x1 " + segment2.getB() + "x2 " + " + "
                    + (segment1.getA() + segment2.getA()));
            logger.info("Reference vector x1=" + x + " x2=" + y + " f1(x1) + f2(x2)=" + value);
        } catch (NoFeasibleSolutionException e) {
            logger.info("\n");
            logger.info("Area [" + x1Lower + ", " + x1Upper + ", " + x2Lower + ", " + x2Upper + "]");
            logger.info("Cost function: " + segment1.getB() + "x1 " + segment2.getB() + "x2 " + " + "
                    + (segment1.getA() + segment2.getA()));
            logger.error("No feasible solution found: for area " + a);
        }

    }

    PointValuePair minimalSolution = getMinimalSolution(solutionList);
    LocalRVector referenceVector = constructReferenceVector(minimalSolution, sourceAsNumber);

    logger.info("Chosen reference vector: " + referenceVector.getVectorValues().get(0).getValue() + " "
            + referenceVector.getVectorValues().get(1).getValue());

    return referenceVector;
}

From source file:edu.byu.nlp.util.Matrices.java

/**
 * Finds an ordering that minimizes the passed-in loss function.
 * Formulates the problem as an instance of the 'assignment problem' 
 * and solves using a linear solver.//  ww  w.  j a v  a  2  s  .  c  om
 * 
 * @param lossfunction takes as an argument a matrix row, and outputs the 
 * loss associated 
 * 
 * @return a vectors of new row assignments. For example, [0,1,2,3] indicate the trivial re-ordering. 
 */
public static int[] getRowReordering(double[][] mat, RowReorderingLossFunction lossFunction) {
    // In the assignment problem formulation, there will be one variable associated with 
    // each possible row->dst assignment. We calculate the coefficient of each of 
    // these using the passed-in loss function. Our coefficients are therefore a 
    // vectorized form of the loss matrix.
    int n = mat.length;
    double[] objCoeff = new double[n * n];
    for (int src = 0; src < n; src++) {
        for (int dst = 0; dst < n; dst++) {
            double loss = lossFunction.rowAssignmentLoss(mat[src], dst);
            objCoeff[n * src + dst] = loss;
            if (Double.isInfinite(loss) || Double.isNaN(loss)) {
                throw new IllegalArgumentException("loss function returned an invalid number (" + loss + ") "
                        + "when asked to consider \n\trow " + DoubleArrays.toString(mat[src])
                        + " \n\tin position " + dst);
            }
        }
    }

    // objective function
    double offset = 0;
    LinearObjectiveFunction f = new LinearObjectiveFunction(objCoeff, offset);

    // constraints
    Collection<LinearConstraint> constraints = Lists.newArrayList();
    // each src must have exactly one dst 
    for (int src = 0; src < n; src++) {
        double[] constCoeff = DoubleArrays.of(0, n * n);
        Arrays.fill(constCoeff, n * src, n * (src + 1), 1); // single row of 1s
        constraints.add(new LinearConstraint(constCoeff, Relationship.EQ, 1));
    }
    // each dst must have exactly one src
    for (int dst = 0; dst < n; dst++) {
        double[] constCoeff = DoubleArrays.of(0, n * n);
        for (int src = 0; src < n; src++) {
            constCoeff[n * src + dst] = 1; // single col of 1s
        }
        constraints.add(new LinearConstraint(constCoeff, Relationship.EQ, 1));
    }

    // solve
    boolean restrictToNonNegative = true;
    SimplexSolver solver = new SimplexSolver();
    solver.setMaxIterations(10000);
    PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, restrictToNonNegative);
    double[] assignmentMatrix = solution.getPoint();

    // the assignment matrix should be very simple; each x is either 0 or 1, 
    // and there is a single 1 per row and column
    // we can deterministically convert this to an int[]
    int[] result = new int[n];
    for (int src = 0; src < n; src++) {
        int rowNonZeroCount = 0;
        for (int dst = 0; dst < n; dst++) {
            double val = assignmentMatrix[n * src + dst];
            if (Math.abs(val - 1) < 1e-6) {
                result[src] = dst;
                rowNonZeroCount++;
            }
        }
        if (rowNonZeroCount != 1) {
            throw new IllegalStateException(
                    "The assignment problem linear solver returned an assignment matrix with "
                            + "invalid entries. This should never happen! Here is the matrix encoded as a vector "
                            + "with rows of length " + n + ":\n\t" + DoubleArrays.toString(assignmentMatrix));
        }
    }
    return result;
}

From source file:gamlss.smoothing.PB.java

/**
 * GAIC smoothing method.//from  ww w . j a  va  2s  . c  o m
 * @param lambda - smoothing parameter
 * @return fitted values
 */
private ArrayRealVector functionGAIC(Double lambda) {

    //lambda <- nlminb(lambda, fnGAIC,  
    //lower = 1.0e-7, upper = 1.0e7, k=control$k)$par
    lambda = optimizer.optimize(Controls.BOBYQA_MAX_EVAL, nonLinObj, GoalType.MINIMIZE,
            new double[] { lambda, lambda }, new double[] { Double.MIN_VALUE, Double.MIN_VALUE },
            new double[] { Double.MAX_VALUE, Double.MAX_VALUE }).getPoint()[0];

    if (lambda > 1.0e+7) {
        lambda = 1.0e+7;
    }
    if (lambda < 1.0e-7) {
        lambda = 1.0e-7;
    }

    //fit <- regpen(y=y, X=X, w=w, lambda=lambda, D)
    beta = regpen(lambda);

    //fv <- X %*% fit$beta     
    fv = (ArrayRealVector) basisM.operate(beta);

    //assign(startLambdaName, lambda, envir=gamlss.env)
    setLambda(lambda);
    return fv;
}