List of usage examples for org.apache.commons.math.optimization.linear Relationship GEQ
Relationship GEQ
To view the source code for org.apache.commons.math.optimization.linear Relationship GEQ.
Click Source Link
From source file:fi.smaa.libror.UTAGMSSolverTest.java
@Test public void testBuildRORConstraints() { List<LinearConstraint> c = solver.buildRORConstraints(); // constraint for the preferences LinearConstraint con1 = c.get(0);// ww w. ja v a 2 s. c o m assertArrayEquals(new double[] { 0.0, 0.0, 1.0, -1.0, 0.0, -1.0, 1.0, -1.0 }, con1.getCoefficients().getData(), 0.001); assertEquals(Relationship.GEQ, con1.getRelationship()); assertEquals(0.0, con1.getValue(), 0.0001); // constraints for the monotonicity int cIndex = 1; int cInIndex = 1; for (int i = 0; i < solver.getModel().getNrCriteria(); i++) { for (int j = 0; j < solver.getModel().getPerfMatrix().getLevels()[i].getDimension() - 1; j++) { LinearConstraint lc = c.get(cIndex); double[] vals = new double[8]; vals[cInIndex - 1] = 1.0; vals[cInIndex] = -1.0; assertArrayEquals(vals, lc.getCoefficients().getData(), 0.0001); assertEquals(Relationship.LEQ, lc.getRelationship()); cIndex++; cInIndex += 1; } cInIndex += 1; } // constraints for first level being 0 int offset = 0; for (int i = 0; i < solver.getModel().getNrCriteria(); i++) { LinearConstraint lc = c.get(cIndex); assertEquals(Relationship.EQ, lc.getRelationship()); assertEquals(0.0, lc.getValue(), 0.000001); double[] vals = new double[8]; vals[offset] = 1.0; offset += solver.getModel().getPerfMatrix().getLevels()[i].getDimension(); assertArrayEquals(vals, lc.getCoefficients().getData(), 0.00001); cIndex++; } // constraints for best levels summing to unity LinearConstraint lc = c.get(cIndex); cIndex++; assertEquals(Relationship.EQ, lc.getRelationship()); assertEquals(1.0, lc.getValue(), 0.000001); double[] vals = new double[8]; vals[1] = 1.0; vals[3] = 1.0; vals[6] = 1.0; assertArrayEquals(vals, lc.getCoefficients().getData(), 0.00001); }
From source file:com.polytech4A.cuttingstock.core.method.LinearResolutionMethod.java
/** * Update current context's constraints using the solution. * * @param solution Solution used to update the constraints. *///from ww w . j av a 2s. c o m public void updateConstraints(Solution solution) { ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); double[] coefficients; int i; for (Box ctxBox : context.getBoxes()) { coefficients = new double[solution.getPatterns().size()]; i = 0; for (Pattern p : solution.getPatterns()) { for (Box box : p.getAmounts()) { if (box.equals(ctxBox)) { coefficients[i] = box.getAmount(); ++i; } } } constraints.add(new LinearConstraint(coefficients, Relationship.GEQ, ctxBox.getAmount())); } this.constraints = constraints; }
From source file:fi.smaa.libror.UTAGMSSolver.java
private LinearConstraint buildEpsilonStrictlyPositiveConstraint() { double[] lhsVars = new double[getNrLPVariables()]; lhsVars[lhsVars.length - 1] = 1.0;//from w w w . j a va 2 s. c om return new LinearConstraint(lhsVars, Relationship.GEQ, MIN_EPSILON); }
From source file:com.polytech4A.cuttingstock.core.method.LinearResolutionMetodTest.java
@Test public void testUpdateConstraints() throws NoSuchFieldException, IllegalAccessException { LinearResolutionMethod method = new LinearResolutionMethod(context); method.updateConstraints(solution);/*from w ww. j a v a 2 s .c om*/ // To avoid set attributes in public, we get the field function. Field field = method.getClass().getDeclaredField("constraints"); field.setAccessible(true); ArrayList<LinearConstraint> constraints = (ArrayList<LinearConstraint>) field.get(method); // Test of value of each constraint's value. int i = 0; for (LinearConstraint c : constraints) { double[] coefficients = c.getCoefficients().getData(); int j = 0; for (Pattern p : solution.getPatterns()) { Box b = p.getAmounts().get(i); assertEquals((double) p.getAmounts().get(i).getAmount(), coefficients[j]); j++; } i++; assertEquals(c.getRelationship(), Relationship.GEQ); } }
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 .j a v a 2 s. c o 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:net.sf.tweety.math.opt.solver.ApacheCommonsSimplex.java
@Override public Map<Variable, Term> solve(ConstraintSatisfactionProblem problem) { if (!problem.isLinear()) throw new IllegalArgumentException("Simplex algorithm is for linear problems only."); //this.log.info("Wrapping optimization problem for calling the Apache Commons Simplex algorithm."); // 1.) bring all constraints in linear and normalized form Set<Statement> constraints = new HashSet<Statement>(); for (Statement s : problem) constraints.add(s.toNormalizedForm().toLinearForm()); // 2.) for every constraint we need an extra variable int numVariables = problem.getVariables().size(); // 3.) define mappings from variables to indices int index = 0; Map<Variable, Integer> origVars2Idx = new HashMap<Variable, Integer>(); for (Variable v : problem.getVariables()) origVars2Idx.put(v, index++);/*from www . j av a2s. c o m*/ // 4.) Check for target function (for constraint satisfaction problems // its empty double[] coefficientsTarget = new double[numVariables]; int i = 0; for (; i < numVariables; i++) coefficientsTarget[i] = 0; double constTerm = 0; if (problem instanceof OptimizationProblem) { // bring target function in linear form Sum t = ((OptimizationProblem) problem).getTargetFunction().toLinearForm(); for (Term summand : t.getTerms()) { // as t is in linear form every summand is a product Product p = (Product) summand; if (p.getTerms().size() == 1) { // p consists of just a constant term Constant c = (Constant) p.getTerms().get(0); if (c instanceof FloatConstant) constTerm += ((FloatConstant) c).getValue(); else constTerm += ((IntegerConstant) c).getValue(); } else { // p consists of a variable and a constant Variable v = (Variable) ((p.getTerms().get(0) instanceof Variable) ? (p.getTerms().get(0)) : (p.getTerms().get(1))); Constant c = (Constant) ((p.getTerms().get(0) instanceof Constant) ? (p.getTerms().get(0)) : (p.getTerms().get(1))); double coefficient = (c instanceof FloatConstant) ? (((FloatConstant) c).getValue()) : (((IntegerConstant) c).getValue()); coefficientsTarget[origVars2Idx.get(v)] += coefficient; } } } LinearObjectiveFunction target = new LinearObjectiveFunction(coefficientsTarget, constTerm); // 5.) Represent the constraints Set<LinearConstraint> finalConstraints = new HashSet<LinearConstraint>(); for (Statement s : constraints) { double[] coefficientsConstraint = new double[numVariables]; for (i = 0; i < numVariables; i++) coefficientsConstraint[i] = 0; // as s is in linear form go through the summands Sum leftTerm = (Sum) s.getLeftTerm(); double rest = 0; for (Term summand : leftTerm.getTerms()) { // as s is in linear form every summand is a product Product p = (Product) summand; if (p.getTerms().size() == 1) { // p consists of just a constant term Constant c = (Constant) p.getTerms().get(0); if (c instanceof FloatConstant) rest += ((FloatConstant) c).getValue(); else rest += ((IntegerConstant) c).getValue(); } else { // p consists of a variable and a constant Variable v = (Variable) ((p.getTerms().get(0) instanceof Variable) ? (p.getTerms().get(0)) : (p.getTerms().get(1))); Constant c = (Constant) ((p.getTerms().get(0) instanceof Constant) ? (p.getTerms().get(0)) : (p.getTerms().get(1))); double coefficient = (c instanceof FloatConstant) ? (((FloatConstant) c).getValue()) : (((IntegerConstant) c).getValue()); coefficientsConstraint[origVars2Idx.get(v)] += coefficient; } } Relationship r = Relationship.EQ; if (s instanceof Inequation) r = Relationship.GEQ; finalConstraints.add(new LinearConstraint(coefficientsConstraint, r, -rest)); } // 6.) Optimize. try { //this.log.info("Calling the Apache Commons Simplex algorithm."); SimplexSolver solver = new SimplexSolver(0.01); solver.setMaxIterations(this.MAXITERATIONS); RealPointValuePair r = null; if (problem instanceof OptimizationProblem) { int type = ((OptimizationProblem) problem).getType(); r = solver.optimize(target, finalConstraints, (type == OptimizationProblem.MINIMIZE) ? (GoalType.MINIMIZE) : (GoalType.MAXIMIZE), this.onlyPositive); } else r = solver.optimize(target, finalConstraints, GoalType.MINIMIZE, this.onlyPositive); //this.log.info("Parsing output from the Apache Commons Simplex algorithm."); Map<Variable, Term> result = new HashMap<Variable, Term>(); for (Variable v : origVars2Idx.keySet()) result.put(v, new FloatConstant(r.getPoint()[origVars2Idx.get(v)])); return result; } catch (OptimizationException e) { //log.error(e.getMessage()); throw new ProblemInconsistentException(); } }
From source file:fi.smaa.libror.UTAGMSSolver.java
/** * a is strictly preferred to b (v(a) >= v(b) + epsilon) * @param a/*from w ww .jav a 2s .co m*/ * @param b * @return */ private LinearConstraint buildStrictlyPreferredConstraint(int a, int b) { double[] lhsVars = new double[getNrLPVariables()]; double[] rhsVars = new double[getNrLPVariables()]; setVarsPositive(lhsVars, a); setVarsPositive(rhsVars, b); // set epsilon rhsVars[rhsVars.length - 1] = 1.0; return new LinearConstraint(lhsVars, 0.0, Relationship.GEQ, rhsVars, 0.0); }
From source file:fi.smaa.libror.UTAGMSSolver.java
private LinearConstraint buildWeaklyPreferredConstraint(int a, int b) { double[] lhsVars = new double[getNrLPVariables()]; double[] rhsVars = new double[getNrLPVariables()]; setVarsPositive(lhsVars, a);//from w w w . j a v a 2 s . c o m setVarsPositive(rhsVars, b); return new LinearConstraint(lhsVars, 0.0, Relationship.GEQ, rhsVars, 0.0); }
From source file:emlab.role.AbstractEnergyProducerRole.java
/** * The fuel mix is calculated with a linear optimization model of the possible fuels and the requirements. * /* w w w.j a va 2s. 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.rascalmpl.library.analysis.linearprogramming.LinearProgramming.java
private static Relationship convertConstraintType(IConstructor c) { if (c.getConstructorType() == ConstraintType_leq) { return Relationship.LEQ; } else if (c.getConstructorType() == ConstraintType_eq) { return Relationship.EQ; } else {//from ww w . ja v a2s. c o m return Relationship.GEQ; } }