List of usage examples for org.apache.commons.math3.optim.linear LinearConstraint LinearConstraint
public LinearConstraint(final RealVector coefficients, final Relationship relationship, final double value)
From source file:fr.imag.ppplib.calc.opti.ACMLinearProgrammingSolver.java
@Override public void solve(double[] dir) { /* Check the dimension of the vectorspace where lives dir */ if (dir.length != d) throw new LinearProgrammingSolverException(dddirMessage); /* Update the constraints set of the simplex solver if modification */ if (lcListModified) { List<LinearConstraint> lcList = new ArrayList<LinearConstraint>(); int n = dirList.size(); for (int i = 0; i < n; i++) lcList.add(new LinearConstraint(dirList.get(i), Relationship.LEQ, valList.get(i))); lcSet = new LinearConstraintSet(lcList); }// w w w.j a v a 2 s. co m /* Evaluation */ PointValuePair res = solver.optimize(new LinearObjectiveFunction(dir, 0), lcSet, GoalType.MAXIMIZE); /* Update the results and the flags */ point = res.getPoint(); value = res.getSecond(); evaluated = true; lcListModified = false; }
From source file:edu.mit.isos.app.water.WaterControllerState.java
@Override public void iterateTick(ElementImpl element, long duration) { Set<WaterPlant> plants = new HashSet<WaterPlant>(); Set<WaterPipeline> pipelines = new HashSet<WaterPipeline>(); Set<WaterElementImpl> systems = new HashSet<WaterElementImpl>(); for (ElementImpl e : elements) { if (e instanceof WaterPlant && ((WaterPlant) e).isOperating()) { plants.add((WaterPlant) e);//w w w .j a v a 2 s. c o m } if (e instanceof WaterPipeline) { pipelines.add((WaterPipeline) e); } if (e instanceof WaterElementImpl) { systems.add((WaterElementImpl) e); } } List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); double[] costCoefficients = new double[elements.size()]; double[] initialValues = new double[elements.size()]; for (WaterElementImpl e : systems) { // cost of lifting aquifer is 1 costCoefficients[elements.indexOf(e)] = 1; initialValues[elements.indexOf(e)] = ((WaterElementState) e.getState()).getProduced(e, duration) .getQuantity(ResourceType.WATER); } for (WaterPlant e : plants) { initialValues[elements.indexOf(e)] = e.getOperatingState().getProduced(e, duration) .getQuantity(ResourceType.WATER); double[] productionCoefficients = new double[elements.size()]; productionCoefficients[elements.indexOf(e)] = 1; constraints.add(new LinearConstraint(productionCoefficients, Relationship.LEQ, e.getOperatingState().productionCapacity.multiply(duration).getQuantity(ResourceType.WATER))); } for (WaterPipeline e : pipelines) { initialValues[elements.indexOf(e)] = e.getOperatingState().getOutput(e, duration) .getQuantity(ResourceType.WATER); double[] outputCoefficients = new double[elements.size()]; outputCoefficients[elements.indexOf(e)] = 1; constraints.add(new LinearConstraint(outputCoefficients, Relationship.LEQ, e.getOperatingState().outputCapacity.multiply(duration).getQuantity(ResourceType.WATER))); } for (WaterElementImpl e : systems) { double[] flowCoefficients = new double[elements.size()]; flowCoefficients[elements.indexOf(e)] = 1; // system production for (WaterPlant plant : plants) { if (plant.getLocation().equals(e.getLocation())) { flowCoefficients[elements.indexOf(plant)] = 1; // plant production } } for (WaterPipeline pipeline : pipelines) { if (pipeline.getLocation().getOrigin().equals(e.getLocation().getOrigin())) { flowCoefficients[elements.indexOf(pipeline)] = -1 / pipeline.getOperatingState().eta; // pipeline input } else if (pipeline.getLocation().getDestination().equals(e.getLocation().getOrigin())) { flowCoefficients[elements.indexOf(pipeline)] = 1; // pipeline output } } constraints.add(new LinearConstraint(flowCoefficients, Relationship.EQ, ((WaterElementState) e.getState()).getSent(e, duration).getQuantity(ResourceType.WATER))); } try { // Run optimization and get results. PointValuePair output = new SimplexSolver().optimize(GoalType.MINIMIZE, new MaxIter(1000), new NonNegativeConstraint(true), new LinearConstraintSet(constraints), new LinearObjectiveFunction(costCoefficients, 0d), new InitialGuess(initialValues)); for (WaterElementImpl e : systems) { e.getOperatingState().setProduced(e, ResourceFactory.create(ResourceType.WATER, output.getPoint()[elements.indexOf(e)]), duration); } for (WaterPlant e : plants) { e.getOperatingState().setProduced(e, ResourceFactory.create(ResourceType.WATER, output.getPoint()[elements.indexOf(e)]), duration); } for (WaterPipeline e : pipelines) { e.getOperatingState().setOutput(e, ResourceFactory.create(ResourceType.WATER, output.getPoint()[elements.indexOf(e)]), duration); } } catch (TooManyIterationsException ignore) { // Don't overwrite existing values. ignore.printStackTrace(); } catch (NoFeasibleSolutionException ignore) { // Don't overwrite existing values. ignore.printStackTrace(); } for (WaterElementImpl system : systems) { Resource received = system.getOperatingState().getConsumed(system, duration) .get(ResourceType.ELECTRICITY); for (WaterPlant plant : plants) { if (plant.getLocation().equals(system.getLocation())) { received = received.add( plant.getOperatingState().getConsumed(plant, duration).get(ResourceType.ELECTRICITY)); } } for (WaterPipeline pipeline : pipelines) { if (pipeline.getLocation().getOrigin().equals(system.getLocation().getOrigin())) { received = received.add(pipeline.getOperatingState().getInput(pipeline, duration) .get(ResourceType.ELECTRICITY)); } } system.getOperatingState().setReceived(system, received, duration); } }
From source file:com.datumbox.framework.core.mathematics.linearprogramming.LPSolver.java
/** * Solves the LP problem and returns the result. * // w w w.j av a2 s . co m * @param linearObjectiveFunction * @param linearConstraintsList * @param nonNegative * @param maximize * @return */ public static LPResult solve(double[] linearObjectiveFunction, List<LPSolver.LPConstraint> linearConstraintsList, boolean nonNegative, boolean maximize) { int m = linearConstraintsList.size(); List<LinearConstraint> constraints = new ArrayList<>(m); for (LPSolver.LPConstraint constraint : linearConstraintsList) { String sign = constraint.getSign(); Relationship relationship = null; if (LPSolver.GEQ.equals(sign)) { relationship = Relationship.GEQ; } else if (LPSolver.LEQ.equals(sign)) { relationship = Relationship.LEQ; } else if (LPSolver.EQ.equals(sign)) { relationship = Relationship.EQ; } constraints .add(new LinearConstraint(constraint.getContraintBody(), relationship, constraint.getValue())); } SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(new LinearObjectiveFunction(linearObjectiveFunction, 0.0), new LinearConstraintSet(constraints), maximize ? GoalType.MAXIMIZE : GoalType.MINIMIZE, new NonNegativeConstraint(nonNegative), PivotSelectionRule.BLAND); LPResult result = new LPResult(); result.setObjectiveValue(solution.getValue()); result.setVariableValues(solution.getPoint()); return result; }
From source file:org.aika.experiments.ComputeWeightsExperiment.java
@Test public void testOptimization() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0); LinearConstraintSet constraints = new LinearConstraintSet( new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0), new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0), new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0), new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0), new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE); Assert.assertEquals(10.0, solution.getValue(), .0000001); }
From source file:org.aika.experiments.ComputeWeightsExperiment.java
@Test public void testOptimization2() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0); LinearConstraintSet constraints = new LinearConstraintSet( new LinearConstraint(new double[] { 1, 1, 1, 0 }, Relationship.GEQ, 0.5), new LinearConstraint(new double[] { 1, 0, 1, 1 }, Relationship.GEQ, 0.5), new LinearConstraint(new double[] { 0, 1, 0, 1 }, Relationship.LEQ, -0.5), new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, -0.5), new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, -0.5)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE); Assert.assertEquals(10.0, solution.getValue(), .0000001); }
From source file:org.aika.experiments.ComputeWeightsExperiment.java
@Test public void testOptimization1() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 0, 0, 0, 0, 0 }, 0); LinearConstraintSet constraints = new LinearConstraintSet( new LinearConstraint(new double[] { 1, 1, 1, 0, 1, 1 }, Relationship.GEQ, 0.5), new LinearConstraint(new double[] { 1, 1, 1, 1, 0, 1 }, Relationship.GEQ, 0.5), new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 1 }, Relationship.LEQ, -0.5), new LinearConstraint(new double[] { 1, 1, 0, 0, 1, 1 }, Relationship.LEQ, -0.5), new LinearConstraint(new double[] { 1, 1, 1, 0, 0, 1 }, Relationship.LEQ, -0.5), new LinearConstraint(new double[] { 1, 1, 1, 0, 1, 0 }, Relationship.LEQ, -0.5), new LinearConstraint(new double[] { 1, 0, 1, 1, 0, 1 }, Relationship.LEQ, -0.5), new LinearConstraint(new double[] { 1, 1, 0, 1, 0, 1 }, Relationship.LEQ, -0.5), new LinearConstraint(new double[] { 1, 1, 1, 1, 0, 0 }, Relationship.LEQ, -0.5)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, new NonNegativeConstraint(false)); Assert.assertEquals(10.0, solution.getValue(), .0000001); }
From source file:org.aika.network.neuron.lattice.AndNode.java
private Neuron computeNeuron(TreeSet<AndNode> significantLowerBound, TreeSet<Node> nonSignificantUpperBound) { Map<InputNode, Integer> indexes = new TreeMap<>(); ArrayList<InputNode> revIndexes = new ArrayList<>(); for (AndNode n : significantLowerBound) { for (InputNode in : n.parents.keySet()) { if (!indexes.containsKey(in)) { indexes.put(in, indexes.size()); revIndexes.add(in);//w w w. ja v a 2 s.com } } } double[] objF = new double[indexes.size() + 1]; objF[0] = 1; LinearObjectiveFunction f = new LinearObjectiveFunction(objF, 0); LinearConstraint[] constraintArr = new LinearConstraint[significantLowerBound.size() + nonSignificantUpperBound.size()]; int i = 0; for (AndNode n : significantLowerBound) { double[] c = new double[indexes.size() + 1]; c[0] = 1; for (InputNode in : n.parents.keySet()) { c[indexes.get(in) + 1] = in.key.isNeg ? -1 : 1; } constraintArr[i] = new LinearConstraint(c, Relationship.GEQ, 0.5); i++; } for (Node n : nonSignificantUpperBound) { double[] c = new double[indexes.size() + 1]; c[0] = 1; if (n instanceof InputNode) { c[indexes.get(n) + 1] = ((InputNode) n).key.isNeg ? -1 : 1; } else if (n instanceof AndNode) { for (InputNode in : ((AndNode) n).parents.keySet()) { c[indexes.get(in) + 1] = in.key.isNeg ? -1 : 1; } } constraintArr[i] = new LinearConstraint(c, Relationship.LEQ, -0.5); i++; } LinearConstraintSet constraints = new LinearConstraintSet(constraintArr); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, new NonNegativeConstraint(false)); double bias = solution.getKey()[0]; TreeSet<Synapse> synapses = new TreeSet<>(); for (int j = 1; j < solution.getKey().length; j++) { InputNode in = revIndexes.get(j - 1); Synapse s = new Synapse(in.inputNeuron, in.key.posDelta); s.w = (float) solution.getKey()[j]; synapses.add(s); } return Neuron.createNeuron(new Neuron(), bias, synapses, false); }
From source file:org.arrowhead.wp5.market.impl.Market.java
public void clear(List<Bid> demList, List<Bid> supList, List<Bid> winningDemandBids, List<Bid> winningSupplyBids) { if (demList.isEmpty() || supList.isEmpty()) { logger.debug("Empty list, no clearing."); return;//from www . j a v a2 s.c om } List<Bid> demandList = new ArrayList<Bid>(); demandList.addAll(demList); List<Bid> supplyList = new ArrayList<Bid>(); supplyList.addAll(supList); long totalDemand = getTotalQuantity(demandList); long totalSupply = getTotalQuantity(supplyList); long minQuantity = Math.min(totalDemand, totalSupply); Bid fakeBid = new Bid(0, totalSupply - totalDemand, true, "", ""); if (totalDemand < totalSupply) { demandList.add(fakeBid); totalDemand = getTotalQuantity(demandList); totalSupply = getTotalQuantity(supplyList); minQuantity = Math.min(totalDemand, totalSupply); } int numDemand = demandList.size(); int numSupply = supplyList.size(); int demandIdx = 0; int supplyIdx = numDemand; int total = numDemand + numSupply; logger.debug("demand: {} supply: {} total: {}", numDemand, numSupply, total); double[] demand = getPrice(demandList); double[] supply = getPrice(supplyList); logger.debug("demand: {}", Arrays.toString(demand)); logger.debug("supply: {}", Arrays.toString(supply)); double[] empty = new double[total]; double[] objective = empty.clone(); System.arraycopy(demand, 0, objective, demandIdx, numDemand); System.arraycopy(supply, 0, objective, supplyIdx, numSupply); for (int i = 0; i < supply.length; i++) { objective[supplyIdx + i] = -supply[i]; } logger.debug("Empty: {} - obj: {}", Arrays.toString(empty), Arrays.toString(objective)); // describe the optimization problem LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); for (int i = 0; i < demandList.size(); i++) { generateConstraint(demandList, demandIdx, total, constraints, i, Relationship.LEQ); } for (int i = 0; i < supplyList.size(); i++) { generateConstraint(supplyList, supplyIdx, total, constraints, i, Relationship.GEQ); } double[] constraint = empty.clone(); for (int i = 0; i < demandList.size(); i++) { constraint[i + demandIdx] = 1; } logger.debug("Total quantity constraint: {} {} {}", Arrays.toString(constraint), Relationship.LEQ, minQuantity); constraints.add(new LinearConstraint(constraint, Relationship.LEQ, minQuantity)); constraint = empty.clone(); for (int i = 0; i < supplyList.size(); i++) { constraint[i + supplyIdx] = 1; } logger.debug("Total quantity constraint: {} {} {}", Arrays.toString(constraint), Relationship.LEQ, minQuantity); constraints.add(new LinearConstraint(constraint, Relationship.LEQ, minQuantity)); for (int i = 0; i < demandList.size(); i++) { constraint = empty.clone(); constraint[i + demandIdx] = 1; logger.debug("Non zero constraint: {} {} {}", Arrays.toString(constraint), Relationship.GEQ, 0); constraints.add(new LinearConstraint(constraint, Relationship.GEQ, 0)); } for (int i = 0; i < supplyList.size(); i++) { constraint = empty.clone(); constraint[i + supplyIdx] = 1; logger.debug("Non zero constraint: {} {} {}", Arrays.toString(constraint), Relationship.GEQ, 0); constraints.add(new LinearConstraint(constraint, Relationship.GEQ, 0)); } constraint = empty.clone(); for (int i = 0; i < demandList.size(); i++) { constraint[i + demandIdx] = 1; } for (int i = 0; i < supplyList.size(); i++) { constraint[i + supplyIdx] = -1; } // logger.debug("Equilibrium constraint: {} {} {}", Arrays.toString(constraint), Relationship.LEQ, totalSupply-totalDemand); // constraints.add(new LinearConstraint(constraint, Relationship.LEQ, totalSupply-totalDemand)); LinearConstraintSet set = new LinearConstraintSet(constraints); // create and run the solver PointValuePair solution; try { solution = new SimplexSolver().optimize(f, set, GoalType.MAXIMIZE); } catch (NoFeasibleSolutionException e) { logger.info("No feasuble solution!!"); return; } // get the solution logger.debug("solution: "); double[] solutionPoint = solution.getPoint(); List<Bid> all = new ArrayList<Bid>(); all.addAll(demandList); all.addAll(supplyList); for (int i = 0; i < solutionPoint.length; i++) { logger.debug("{} - {} - {}", solutionPoint[i], all.get(i).getQuantity(), all.get(i).getPrice()); } double max = solution.getValue(); logger.debug("value: {}", max); demandList.remove(fakeBid); double price = findPrice(demandList, supplyList, solutionPoint); logger.debug("win price: {}", price); for (int i = 0; i < demandList.size(); i++) { if (solutionPoint[i + demandIdx] > 0) { Bid d = demandList.get(i); if (d == fakeBid) { continue; } if (price <= d.getPrice()) { d.setWinPrice(price); // d.setWinQuantity(solutionPoint[i+demandIdx]); logger.debug("Win d: p: {} - q: {} - wq: {}", d.getWinPrice(), d.getQuantity(), d.getWinQuantity()); winningDemandBids.add(d); } } } for (int i = 0; i < supplyList.size(); i++) { if (solutionPoint[i + supplyIdx] > 0) { Bid d = supplyList.get(i); if (price >= d.getPrice()) { d.setWinPrice(price); // d.setWinQuantity(solutionPoint[i+supplyIdx]); logger.debug("Win s: p: {} - q: {} - wq: {}", d.getWinPrice(), d.getQuantity(), d.getWinQuantity()); winningSupplyBids.add(d); } } } logger.debug("winning demand: {} - total quantity: {}", winningDemandBids, getTotalWinQuantity(winningDemandBids)); logger.debug("winning supply: {} - total quantity: {}", winningSupplyBids, getTotalWinQuantity(winningSupplyBids)); }
From source file:org.arrowhead.wp5.market.impl.Market.java
private void generateConstraint(List<Bid> list, int idx, int total, Collection<LinearConstraint> constraints, int i, Relationship rel) { double[] constraint = new double[total]; long quantity = list.get(i).getQuantity(); constraint[i + idx] = 1;// w w w .j a v a2 s .co m // Relationship rel = Relationship.LEQ; logger.debug("Individual quantity constraint: {} {} {}", Arrays.toString(constraint), rel, quantity); constraints.add(new LinearConstraint(constraint, rel, quantity)); }
From source file:org.lightjason.agentspeak.action.buildin.math.linearprogram.CValueConstraint.java
@Override public final IFuzzyValue<Boolean> execute(final IContext p_context, final boolean p_parallel, final List<ITerm> p_argument, final List<ITerm> p_return, final List<ITerm> p_annotation) { final List<ITerm> l_arguments = CCommon.flatcollection(p_argument).collect(Collectors.toList()); // create linear constraint based on a value l_arguments.get(0).<Pair<LinearObjectiveFunction, Collection<LinearConstraint>>>raw().getRight() .add(new LinearConstraint( l_arguments.stream().limit(l_arguments.size() - 2).skip(1) .mapToDouble(i -> i.<Number>raw().doubleValue()).toArray(), this.getRelation(l_arguments.get(l_arguments.size() - 2).<String>raw()), l_arguments.get(l_arguments.size() - 1).<Number>raw().doubleValue())); return CFuzzyValue.from(true); }