List of usage examples for org.apache.commons.math3.optim.linear SimplexSolver SimplexSolver
public SimplexSolver()
From source file:com.datumbox.framework.core.mathematics.linearprogramming.LPSolver.java
/** * Solves the LP problem and returns the result. * // ww w .java 2 s . c o 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: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);/*from w w w . j a v a2 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: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);//from www. java 2s . 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;// w ww .j a v a 2 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.lightjason.agentspeak.action.buildin.math.linearprogram.CSolve.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) { // first argument is the LP pair object, second argument is the goal-type (maximize / minimize), // third & fourth argument can be the number of iterations or string with "non-negative" variables final List<OptimizationData> l_settings = new LinkedList<>(); final Pair<LinearObjectiveFunction, Collection<LinearConstraint>> l_default = p_argument.get(0).raw(); l_settings.add(l_default.getLeft()); l_settings.add(new LinearConstraintSet(l_default.getRight())); p_argument.subList(1, p_argument.size()).stream().map(i -> { if (CCommon.rawvalueAssignableTo(i, Number.class)) return new MaxIter(i.raw()); if (CCommon.rawvalueAssignableTo(i, String.class)) switch (i.<String>raw().trim().toLowerCase()) { case "non-negative": return new NonNegativeConstraint(true); case "maximize": return GoalType.MAXIMIZE; case "minimize": return GoalType.MINIMIZE; default: return null; }//from ww w . jav a 2 s. co m return null; }).filter(Objects::nonNull).forEach(l_settings::add); // optimze and return final SimplexSolver l_lp = new SimplexSolver(); final PointValuePair l_result = l_lp.optimize(l_settings.toArray(new OptimizationData[l_settings.size()])); p_return.add(CRawTerm.from(l_result.getValue())); p_return.add(CRawTerm.from(l_result.getPoint().length)); Arrays.stream(l_result.getPoint()).boxed().map(CRawTerm::from).forEach(p_return::add); return CFuzzyValue.from(true); }
From source file:org.lightjason.agentspeak.action.builtin.math.linearprogram.CSolve.java
@Nonnull @Override/*from w ww .j a va 2 s . c o m*/ public final IFuzzyValue<Boolean> execute(final boolean p_parallel, @Nonnull final IContext p_context, @Nonnull final List<ITerm> p_argument, @Nonnull final List<ITerm> p_return) { // first argument is the LP pair object, second argument is the goal-type (maximize / minimize), // third & fourth argument can be the number of iterations or string with "non-negative" variables final List<OptimizationData> l_settings = new LinkedList<>(); final Pair<LinearObjectiveFunction, Collection<LinearConstraint>> l_default = p_argument.get(0).raw(); l_settings.add(l_default.getLeft()); l_settings.add(new LinearConstraintSet(l_default.getRight())); p_argument.subList(1, p_argument.size()).stream().map(i -> { if (CCommon.rawvalueAssignableTo(i, Number.class)) return new MaxIter(i.raw()); if (CCommon.rawvalueAssignableTo(i, String.class)) switch (i.<String>raw().trim().toLowerCase()) { case "non-negative": return new NonNegativeConstraint(true); case "maximize": return GoalType.MAXIMIZE; case "minimize": return GoalType.MINIMIZE; default: return null; } return null; }).filter(Objects::nonNull).forEach(l_settings::add); // optimze and return final SimplexSolver l_lp = new SimplexSolver(); final PointValuePair l_result = l_lp.optimize(l_settings.toArray(new OptimizationData[l_settings.size()])); p_return.add(CRawTerm.from(l_result.getValue())); p_return.add(CRawTerm.from(l_result.getPoint().length)); Arrays.stream(l_result.getPoint()).boxed().map(CRawTerm::from).forEach(p_return::add); return CFuzzyValue.from(true); }
From source file:uk.ac.tgac.metaopt.external.Apache.java
@Override protected Solution internalOptimise(Problem problem) { // Create the objective function LinearObjectiveFunction f = this.convertObjective(problem.getObjective(), problem.getVariables()); // Setup collection for constraints Collection<LinearConstraint> constraints = new ArrayList<>(); // Add the decision variable constraints (i.e. upper and lower bounds) this.addDecisionVariables(constraints, problem); // Add the regular constraints this.addRegularConstraints(constraints, problem); // Create the solver SimplexSolver solver = new SimplexSolver(); /* //The latest version of apache has some options for non-linear solving... I should get this working when I get some //time//from w ww.j a v a2 s.com final int maxIterations = problem.getMaxIterations() > 0 ? problem.getMaxIterations() : DEFAULT_MAX_ITERATIONS; final double tolerance = problem.getTolerance() != 0.0 ? problem.getTolerance() : DEFAULT_TOLERANCE; CMAESOptimizer solver = new CMAESOptimizer(maxIterations, tolerance, true, // Active CMA... do we want this??? problem.getNbVariables() > 100 ? 1 : 0, // diagonal only... speeds things up for high dimensional problems 0, new JDKRandomGenerator(), false, new SimpleValueChecker(-1.0, tolerance, maxIterations) );*/ // Run the solver PointValuePair pvp = solver.optimize(f, new LinearConstraintSet(constraints), convertObjectiveDirection(problem.getObjective().getDirection())); // Return results return this.createSolution(pvp, problem.getVariables()); }