List of usage examples for org.apache.commons.math3.optimization PointValuePair getPoint
public double[] getPoint()
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./*from w w w .j a v a 2 s .co m*/ * * @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: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 w ww .ja v a 2 s . com 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/* ww w . jav 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:edu.stanford.cfuller.imageanalysistools.fitting.GaussianFitter3D.java
/** * Fits a 3D Gaussian to a supplied object, starting from an initial guess of the parameters of that Gaussian. * * The Gaussian is contrained to be symmetric in the x and y dimensions (that is, it will have equal variance in both dimensions). * * @param toFit The {@link ImageObject} to be fit to a Gaussian. * @param initialGuess The initial guess at the parameters of the Gaussian. These must be supplied in the order: amplitude, x-y stddev, z stddev, x position, y position, z position, background. Positions should be supplied in absolute coordinates from the original image, not relative to the box around the object being fit. * @param ppg The number of photons corresponding to one greylevel in the original image. * @return The best fit Gaussian parameters, in the same order as the initial guess had to be supplied. *//*from w w w . j ava2 s . c o m*/ public RealVector fit(ImageObject toFit, RealVector initialGuess, double ppg) { //parameter ordering: amplitude, stddev x-y, stddev z, x/y/z coords, background double tol = 1.0e-6; SimplexOptimizer nmm = new SimplexOptimizer(tol, tol); NelderMeadSimplex nms = new NelderMeadSimplex(initialGuess.getDimension()); nmm.setSimplex(nms); PointValuePair pvp = nmm.optimize(10000000, new MLObjectiveFunction(toFit, ppg), org.apache.commons.math3.optimization.GoalType.MINIMIZE, initialGuess.toArray()); RealVector result = new ArrayRealVector(pvp.getPoint()); return result; }
From source file:eu.smartenit.sbox.eca.ReferenceVectorCalculator.java
/** * Creates the RVector object from the optimal solution. * //www. j a v a2s .c o m * @param minimalSolution The optimal solution. * @param sourceAsNumber The number of the source AS * @return The RVector object of the optimal solution. */ private LocalRVector constructReferenceVector(PointValuePair minimalSolution, int sourceAsNumber) { LocalVectorValue vvx1 = new LocalVectorValue(Math.round(minimalSolution.getPoint()[0]), link1); LocalVectorValue vvx2 = new LocalVectorValue(Math.round(minimalSolution.getPoint()[1]), link2); List<LocalVectorValue> referenceVectorList = new ArrayList<LocalVectorValue>(); referenceVectorList.add(vvx1); referenceVectorList.add(vvx2); LocalRVector referenceVector = new LocalRVector(referenceVectorList, sourceAsNumber); return referenceVector; }
From source file:eu.smartenit.sbox.eca.ReferenceVectorCalculator.java
/** * Calculates the reference vector using simplex method. * /* www . j av a2 s . c om*/ * @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; }