List of usage examples for org.apache.commons.math.optimization.linear SimplexSolver SimplexSolver
public SimplexSolver()
From source file:com.polytech4A.cuttingstock.core.method.LinearResolutionMethod.java
/** * Resolve linear programming problem when minimizing the equation with current constraints. Returns * * @param solution Solution to minimize the objective the function from. * @return Number of printings and cost value. *//*from w ww . j a v a 2s . c o m*/ public Result minimize(Solution solution) { updateFunction(solution); updateConstraints(solution); try { RealPointValuePair result = new SimplexSolver().optimize(function, constraints, GoalType.MINIMIZE, true); double[] point = result.getPoint(); if (result.getValue() < 0) { return null; } for (int i = 0; i < point.length; ++i) { if (point[i] < 0) { return null; } } return new Result(point, context.getSheetCost(), context.getPatternCost()); } catch (OptimizationException e) { logger.debug("LinearResolutionMethod.minimize: " + e.getMessage()); } return null; }
From source file:circdesigna.DesignSequenceConstraints.java
private void solveSimplex() { //Closest-To-Origin objective double[] ones = new double[Std.monomer.getNumMonomers()]; for (int i = 0; i < ones.length; i++) { ones[i] = 1;//from w w w . ja va 2 s.co m } LinearObjectiveFunction f = new LinearObjectiveFunction(ones, 0); List<LinearConstraint> constraints = new ArrayList(); for (Constraint d : maxConstituents) { if (d.constraintValue == -1) { continue; } double[] ei = new double[Std.monomer.getNumMonomers()]; for (int i = 0; i < ei.length; i++) { if (d.regulates[i]) { ei[i] = 1; } } constraints.add(new LinearConstraint(ei, Relationship.LEQ, d.constraintValue)); } for (Constraint d : minConstituents) { if (d.constraintValue == -1) { continue; } double[] ei = new double[Std.monomer.getNumMonomers()]; for (int i = 0; i < ei.length; i++) { if (d.regulates[i]) { ei[i] = 1; } } constraints.add(new LinearConstraint(ei, Relationship.GEQ, d.constraintValue)); } try { RealPointValuePair optimize = new SimplexSolver().optimize(f, constraints, GoalType.MINIMIZE, true); simplexSolution = optimize.getPoint(); //System.out.println(Arrays.toString(simplexSolution)); } catch (Throwable e) { throw new RuntimeException("Constraints are too strict: " + e.getMessage()); } }
From source file:emlab.role.AbstractEnergyProducerRole.java
/** * The fuel mix is calculated with a linear optimization model of the possible fuels and the requirements. * /*from w w w. j a va 2 s . com*/ * @param substancePriceMap * contains the possible fuels and their market prices * @param minimumFuelMixQuality * is the minimum fuel quality needed for the power plant to work * @param efficiency * of the plant determines the need for fuel per MWhe * @param co2TaxLevel * is part of the cost for CO2 * @param co2AuctionPrice * is part of the cost for CO2 * @return the fuel mix */ public Set<SubstanceShareInFuelMix> calculateFuelMix(PowerPlant plant, Map<Substance, Double> substancePriceMap, double co2Price) { double efficiency = plant.getActualEfficiency(); Set<SubstanceShareInFuelMix> fuelMix = (plant.getFuelMix() == null) ? new HashSet<SubstanceShareInFuelMix>() : plant.getFuelMix(); int numberOfFuels = substancePriceMap.size(); if (numberOfFuels == 0) { logger.info("No fuels, so no operation mode is set. Empty fuel mix is returned"); return new HashSet<SubstanceShareInFuelMix>(); } else if (numberOfFuels == 1) { SubstanceShareInFuelMix ssifm = null; if (!fuelMix.isEmpty()) { ssifm = fuelMix.iterator().next(); } else { ssifm = new SubstanceShareInFuelMix().persist(); fuelMix.add(ssifm); } Substance substance = substancePriceMap.keySet().iterator().next(); ssifm.setShare(calculateFuelConsumptionWhenOnlyOneFuelIsUsed(substance, efficiency)); ssifm.setSubstance(substance); logger.info("Setting fuel consumption for {} to {}", ssifm.getSubstance().getName(), ssifm.getShare()); return fuelMix; } else { double minimumFuelMixQuality = plant.getTechnology().getMinimumFuelQuality(); double[] fuelAndCO2Costs = new double[numberOfFuels]; double[] fuelDensities = new double[numberOfFuels]; double[] fuelQuality = new double[numberOfFuels]; int i = 0; for (Substance substance : substancePriceMap.keySet()) { fuelAndCO2Costs[i] = substancePriceMap.get(substance) + substance.getCo2Density() * (co2Price); fuelDensities[i] = substance.getEnergyDensity(); fuelQuality[i] = substance.getQuality() - minimumFuelMixQuality; i++; } logger.info("Fuel prices: {}", fuelAndCO2Costs); logger.info("Fuel densities: {}", fuelDensities); logger.info("Fuel purities: {}", fuelQuality); // Objective function = minimize fuel cost (fuel // consumption*fuelprices // + CO2 intensity*co2 price/tax) LinearObjectiveFunction function = new LinearObjectiveFunction(fuelAndCO2Costs, 0d); List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); // Constraint 1: total fuel density * fuel consumption should match // required energy input constraints.add(new LinearConstraint(fuelDensities, Relationship.EQ, (1 / efficiency))); // Constraint 2&3: minimum fuel quality (times fuel consumption) // required // The equation is derived from (example for 2 fuels): q1 * x1 / (x1+x2) + q2 * x2 / (x1+x2) >= qmin // so that the fuelquality weighted by the mass percentages is greater than the minimum fuel quality. constraints.add(new LinearConstraint(fuelQuality, Relationship.GEQ, 0)); try { SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(function, constraints, GoalType.MINIMIZE, true); logger.info("Succesfully solved a linear optimization for fuel mix"); int f = 0; Iterator<SubstanceShareInFuelMix> iterator = plant.getFuelMix().iterator(); for (Substance substance : substancePriceMap.keySet()) { double share = solution.getPoint()[f]; SubstanceShareInFuelMix ssifm; if (iterator.hasNext()) { ssifm = iterator.next(); } else { ssifm = new SubstanceShareInFuelMix().persist(); fuelMix.add(ssifm); } double fuelConsumptionPerMWhElectricityProduced = convertFuelShareToMassVolume(share); logger.info("Setting fuel consumption for {} to {}", substance.getName(), fuelConsumptionPerMWhElectricityProduced); ssifm.setShare(fuelConsumptionPerMWhElectricityProduced); ssifm.setSubstance(substance); f++; } logger.info("If single fired, it would have been: {}", calculateFuelConsumptionWhenOnlyOneFuelIsUsed(substancePriceMap.keySet().iterator().next(), efficiency)); return fuelMix; } catch (OptimizationException e) { logger.warn( "Failed to determine the correct fuel mix. Adding only fuel number 1 in fuel mix out of {} substances and minimum quality of {}", substancePriceMap.size(), minimumFuelMixQuality); logger.info("The fuel added is: {}", substancePriceMap.keySet().iterator().next().getName()); // Override the old one fuelMix = new HashSet<SubstanceShareInFuelMix>(); SubstanceShareInFuelMix ssifm = new SubstanceShareInFuelMix().persist(); Substance substance = substancePriceMap.keySet().iterator().next(); ssifm.setShare(calculateFuelConsumptionWhenOnlyOneFuelIsUsed(substance, efficiency)); ssifm.setSubstance(substance); logger.info("Setting fuel consumption for {} to {}", ssifm.getSubstance().getName(), ssifm.getShare()); fuelMix.add(ssifm); return fuelMix; } } }
From source file:org.eclipse.recommenders.jayes.transformation.LatentDeterministicDecomposition.java
@Override protected double[] toLatentSpace(double[] v, List<double[]> basis) throws DecompositionFailedException { // we can assume here that equals works, we canonized everything before! int ind = basis.indexOf(v); if (ind != -1) { double[] l = new double[v.length]; l[ind] = 1;//from w w w.j av a 2s . c o m return l; } // have to figure out a suitable non-negative linear combination of the base vectors // -> use simplex List<double[]> transposedBasis = transpose(basis); List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); for (int i = 0; i < v.length; i++) { LinearConstraint c = new LinearConstraint(transposedBasis.get(i), Relationship.EQ, v[i]); constraints.add(c); } LinearObjectiveFunction obj = new LinearObjectiveFunction(new double[v.length], 0); RealPointValuePair result; try { result = new SimplexSolver().optimize(obj, constraints, GoalType.MINIMIZE, true); } catch (OptimizationException e) { throw new DecompositionFailedException(e); } return result.getPoint(); }
From source file:org.rascalmpl.library.analysis.linearprogramming.LinearProgramming.java
public IValue llOptimize(IBool minimize, IBool nonNegative, ISet constraints, IConstructor f) { SimplexSolver solver = new SimplexSolver(); ArrayList<LinearConstraint> constraintsJ = new ArrayList<LinearConstraint>(constraints.size()); for (IValue v : constraints) { constraintsJ.add(convertConstraint((IConstructor) v)); }// www. ja v a 2 s .com LinearObjectiveFunction fJ = convertLinObjFun(f); GoalType goal = minimize.getValue() ? GoalType.MINIMIZE : GoalType.MAXIMIZE; IValueFactory vf = values; boolean nonNegativeJ = nonNegative.getValue(); try { RealPointValuePair res = solver.optimize(fJ, constraintsJ, goal, nonNegativeJ); return vf.constructor(Maybe.Maybe_just, vf.constructor(LLSolution_llSolution, convertToRealList(res.getPoint(), vf), vf.real(res.getValue()))); } catch (Exception e) { return vf.constructor(Maybe.Maybe_nothing); } }
From source file:rb.app.RBSCMSystem.java
/** * @return the SCM lower bound for the current parameters. *//*from w w w .jav a 2 s.c o m*/ public double get_SCM_LB() { double min_J_obj = 0.; try { // First, declare the constraints Collection constraints = new ArrayList(); // Add bounding box constraints for the get_Q_a() variables for (int q = 0; q < get_Q_a(); q++) { double[] index = new double[get_Q_a()]; index[q] = 1.; constraints.add(new LinearConstraint(index, Relationship.GEQ, B_min[q])); constraints.add(new LinearConstraint(index, Relationship.LEQ, B_max[q])); } // Sort the indices of C_J based on distance from current_parameters List<Integer> sortedIndices = getSorted_CJ_Indices(); // Save the current_parameters since we'll change them in the loop below save_current_parameters(); // Add the constraint rows int n_rows = Math.min(SCM_M, C_J.size()); int count = 1; if (n_rows > 0) { for (Iterator it = sortedIndices.iterator(); it.hasNext();) { Integer mu_index = (Integer) it.next(); get_current_parameters_from_C_J(mu_index); // current_parameters = C_J.get(mu_index); double[] constraint_row = new double[get_Q_a()]; for (int q = 0; q < get_Q_a(); q++) { constraint_row[q] = eval_theta_q_a(q); } constraints.add( new LinearConstraint(constraint_row, Relationship.GEQ, C_J_stability_vector[mu_index])); if (count >= n_rows) break; count++; } } // Now load the original parameters back into current_parameters // in order to set the coefficients of the objective function reload_current_parameters(); // Create objective function object double[] objectiveFn = new double[get_Q_a()]; for (int q = 0; q < get_Q_a(); q++) { objectiveFn[q] = eval_theta_q_a(q); } LinearObjectiveFunction f = new LinearObjectiveFunction(objectiveFn, 0.); SimplexSolver solver = new SimplexSolver(); RealPointValuePair opt_pair = solver.optimize(f, constraints, GoalType.MINIMIZE, false); min_J_obj = opt_pair.getValue(); } catch (OptimizationException e) { Log.e("DEBUG_TAG", "Optimal solution not found"); e.printStackTrace(); } catch (Exception e) { Log.e("DEBUG_TAG", "Exception occurred during SCM_LB calculation"); e.printStackTrace(); } Log.d(DEBUG_TAG, "SCM val = " + min_J_obj); return min_J_obj; }