Search in sources :

Example 1 with Expression

use of org.ojalgo.optimisation.Expression in project cogcomp-nlp by CogComp.

the class OJalgoHook method addLessThanConstraint.

public void addLessThanConstraint(int[] i, double[] a, double b) {
    if (log) {
        System.out.print("OJalgoHook: addLessThanConstraint(");
        for (int idx = 0; idx < i.length; idx++) System.out.print("(i=" + i[idx] + ", a=" + a[idx] + ") ");
        System.out.println("b= " + b + ")");
    }
    numConstraints++;
    Expression constraint = model.addExpression("LessThanConstraint: " + Integer.toString(numConstraints));
    constraint.upper(b);
    for (int ind = 0; ind < i.length; ind++) {
        constraint.setLinearFactor(i[ind], a[ind]);
    // in jdk8:
    // constraint.set(i[ind], a[ind]);
    }
}
Also used : Expression(org.ojalgo.optimisation.Expression)

Example 2 with Expression

use of org.ojalgo.optimisation.Expression in project ojAlgo by optimatika.

the class ComPictetPamBamTest method setupModel.

/**
 * @param numberOfVars greater than 6
 */
void setupModel(final int numberOfVars) {
    if (numberOfVars < 6) {
        throw new IllegalArgumentException("numberOfVars must be >= 6 !!!");
    }
    // 
    // variables
    // 
    vars = new Variable[numberOfVars];
    vars[0] = new Variable("x0").lower(new BigDecimal(00.0)).upper(new BigDecimal(15.0));
    vars[1] = new Variable("x1").lower(new BigDecimal(17.0)).upper(new BigDecimal(27.0));
    vars[2] = new Variable("x2").lower(new BigDecimal(19.0)).upper(new BigDecimal(34.0));
    vars[3] = new Variable("x3").lower(new BigDecimal(25.0)).upper(new BigDecimal(48.0));
    vars[4] = new Variable("x4").lower(new BigDecimal(05.0)).upper(new BigDecimal(18.0));
    vars[5] = new Variable("x5").lower(new BigDecimal(02.0)).upper(new BigDecimal(09.0));
    for (int i = 6; i < numberOfVars; ++i) {
        vars[i] = new Variable("x" + i).level(BigMath.ZERO);
    }
    // 
    // minimise distance to this point
    // 
    point = new BigDecimal[numberOfVars];
    point[0] = new BigDecimal(1.0);
    point[1] = new BigDecimal(25.0);
    point[2] = new BigDecimal(33.0);
    point[3] = new BigDecimal(29.0);
    point[4] = new BigDecimal(9.0);
    point[5] = new BigDecimal(2.0);
    for (int i = 6; i < numberOfVars; ++i) {
        point[i] = new BigDecimal(0.0);
    }
    // 
    // model
    // 
    model = new ExpressionsBasedModel(vars);
    // 
    // objective function
    // 
    {
        final int tmpLength = model.countVariables();
        final Expression retVal = model.addExpression("objective");
        for (int ij = 0; ij < tmpLength; ij++) {
            retVal.set(ij, ij, ONE);
        }
        final BigDecimal tmpLinearWeight = TWO.negate();
        for (int i = 0; i < tmpLength; i++) {
            retVal.set(i, Arrays.asList(point).get(i).multiply(tmpLinearWeight));
        }
        final Expression e = retVal;
        e.weight(BigMath.HALF);
    }
    // 
    // sum(xi) = 100.0
    // 
    {
        final int tmpLength = model.countVariables();
        final Expression retVal = model.addExpression("sum(xi) = 100.0");
        for (int i = 0; i < tmpLength; i++) {
            retVal.set(i, ONE);
        }
        final Expression e = retVal;
        e.level(BigMath.HUNDRED);
    }
    // 
    // x1 + x2 <= 45
    // 
    {
        final Expression e = model.addExpression("x1 + x2 <= 45.0");
        e.set(1, BigMath.ONE);
        e.set(2, BigMath.ONE);
        e.lower(BigMath.ZERO).upper(new BigDecimal(45.0));
    }
    // 
    // x4 - 2*x5 = 0
    // 
    {
        final Expression e = model.addExpression("x4 - 2*x5 = 0");
        e.set(4, BigMath.ONE);
        e.set(5, BigMath.TWO.negate());
        e.level(BigMath.ZERO);
    }
// model.options.debug(ConvexSolver.class);
}
Also used : Variable(org.ojalgo.optimisation.Variable) Expression(org.ojalgo.optimisation.Expression) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) BigDecimal(java.math.BigDecimal)

Example 3 with Expression

use of org.ojalgo.optimisation.Expression in project ojAlgo by optimatika.

the class ConvexProblems method doEarly2008.

static void doEarly2008(final Variable[] variables, final Access2D<?> covariances, final Access1D<?> expected) {
    final ExpressionsBasedModel tmpModel = new ExpressionsBasedModel(variables);
    final Expression tmpVariance = tmpModel.addExpression("Variance");
    tmpVariance.setQuadraticFactors(tmpModel.getVariables(), covariances);
    tmpVariance.weight(BigMath.PI.multiply(BigMath.E).multiply(BigMath.HALF));
    final Expression tmpBalance = tmpModel.addExpression("Balance");
    tmpBalance.setLinearFactorsSimple(tmpModel.getVariables());
    tmpBalance.level(BigMath.ONE);
    // tmpModel.options.debug(ConvexSolver.class);
    // tmpModel.options.validate = false;
    final Result tmpActualResult = tmpModel.minimise();
    final NumberContext tmpAccuracy = StandardType.PERCENT.newPrecision(5);
    TestUtils.assertTrue(tmpModel.validate(Array1D.BIG.copy(expected), tmpAccuracy));
    TestUtils.assertTrue(tmpModel.validate(tmpActualResult, tmpAccuracy));
    final TwiceDifferentiable<Double> tmpObjective = tmpModel.objective().toFunction();
    final double tmpExpObjFuncVal = tmpObjective.invoke(Access1D.asPrimitive1D(expected));
    final double tmpActObjFuncVal = tmpObjective.invoke(Access1D.asPrimitive1D(tmpActualResult));
    TestUtils.assertEquals(tmpExpObjFuncVal, tmpActObjFuncVal, tmpAccuracy);
    TestUtils.assertEquals(expected, tmpActualResult, tmpAccuracy);
    // Test that the LinearSolver can determine feasibility
    final ExpressionsBasedModel relaxedModel = tmpModel.relax(false);
    final Optimisation.Result tmpLinearResult = relaxedModel.minimise();
    TestUtils.assertStateNotLessThanFeasible(tmpLinearResult);
    OptimisationConvexTests.assertDirectAndIterativeEquals(tmpModel, tmpAccuracy);
}
Also used : Expression(org.ojalgo.optimisation.Expression) Result(org.ojalgo.optimisation.Optimisation.Result) Optimisation(org.ojalgo.optimisation.Optimisation) NumberContext(org.ojalgo.type.context.NumberContext) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) Result(org.ojalgo.optimisation.Optimisation.Result)

Example 4 with Expression

use of org.ojalgo.optimisation.Expression in project ojAlgo by optimatika.

the class ConvexProblems method testP20111129.

/**
 * ojAlgo could not solve this, but LOQO (and others) could. I re-implemented the problem code just to
 * verify there was no problem there. http://bugzilla.optimatika.se/show_bug.cgi?id=11
 */
@Test
public void testP20111129() {
    final Variable x1 = new Variable("X1");
    final Variable x2 = new Variable("X2").lower(BigMath.HUNDRED.negate()).upper(BigMath.HUNDRED);
    final Variable x3 = new Variable("X3").lower(BigMath.ZERO);
    final Variable x4 = new Variable("X4").lower(BigMath.ZERO);
    final Variable[] tmpVariables = new Variable[] { x1, x2, x3, x4 };
    final ExpressionsBasedModel tmpModel = new ExpressionsBasedModel(tmpVariables);
    final Expression tmpObjExpr = tmpModel.addExpression("Objective");
    tmpModel.setMinimisation();
    tmpObjExpr.set(2, 2, BigMath.HALF);
    tmpObjExpr.set(3, 3, BigMath.TWO);
    tmpObjExpr.set(2, 3, BigMath.TWO.negate());
    tmpObjExpr.set(0, BigMath.THREE);
    tmpObjExpr.set(1, BigMath.TWO.negate());
    tmpObjExpr.set(2, BigMath.ONE);
    tmpObjExpr.set(3, BigMath.FOUR.negate());
    tmpObjExpr.weight(BigMath.ONE);
    Expression tmpConstrExpr;
    tmpConstrExpr = tmpModel.addExpression("C1").lower(BigMath.FOUR);
    tmpConstrExpr.set(0, BigMath.ONE);
    tmpConstrExpr.set(1, BigMath.ONE);
    tmpConstrExpr.set(2, BigMath.FOUR.negate());
    tmpConstrExpr.set(3, BigMath.TWO);
    tmpConstrExpr = tmpModel.addExpression("C2").upper(BigMath.SIX);
    tmpConstrExpr.set(0, BigMath.THREE.negate());
    tmpConstrExpr.set(1, BigMath.ONE);
    tmpConstrExpr.set(2, BigMath.TWO.negate());
    tmpConstrExpr = tmpModel.addExpression("C3").level(BigMath.NEG);
    tmpConstrExpr.set(1, BigMath.ONE);
    tmpConstrExpr.set(3, BigMath.NEG);
    tmpConstrExpr = tmpModel.addExpression("C4").level(BigMath.ZERO);
    tmpConstrExpr.set(0, BigMath.ONE);
    tmpConstrExpr.set(1, BigMath.ONE);
    tmpConstrExpr.set(2, BigMath.NEG);
    // tmpModel.options.debug(ConvexSolver.class);
    final Result tmpResult = tmpModel.minimise();
    final double tmpObjFuncVal = tmpResult.getValue();
    TestUtils.assertEquals(-5.281249989, tmpObjFuncVal, new NumberContext(7, 6));
    final double[] tmpExpected = new double[] { -1.1875, 1.5625, 0.375, 2.5625 };
    for (int i = 0; i < tmpExpected.length; i++) {
        TestUtils.assertEquals(tmpExpected[i], tmpVariables[i].getValue().doubleValue(), new NumberContext(5, 4));
    }
    OptimisationConvexTests.assertDirectAndIterativeEquals(tmpModel, null);
}
Also used : Variable(org.ojalgo.optimisation.Variable) Expression(org.ojalgo.optimisation.Expression) NumberContext(org.ojalgo.type.context.NumberContext) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) Result(org.ojalgo.optimisation.Optimisation.Result) Test(org.junit.jupiter.api.Test)

Example 5 with Expression

use of org.ojalgo.optimisation.Expression in project ojAlgo by optimatika.

the class P20150720 method buildModel3.

/**
 * Sent in 2015-09-03
 */
public static ExpressionsBasedModel buildModel3() {
    /*
         * 5 Products with associated Qty.
         */
    final Map<String, Integer> constraintsProduct = new HashMap<>();
    constraintsProduct.put("PRODUCT_1", 296_000);
    constraintsProduct.put("PRODUCT_2", 888_000);
    constraintsProduct.put("PRODUCT_3", 636_000);
    constraintsProduct.put("PRODUCT_4", 220_000);
    constraintsProduct.put("PRODUCT_5", 0);
    final double stockTotal = constraintsProduct.values().stream().mapToDouble(e -> e.doubleValue()).sum();
    // BasicLogger.debug("STOCK_TOTAL " + stockTotal);
    /*
         * Demand of each Customers
         */
    final Map<String, Integer> constraintsCustomer = new LinkedHashMap<>();
    constraintsCustomer.put("CUSTOMER_A_1", 72_000);
    constraintsCustomer.put("CUSTOMER_A_2", 44_000);
    constraintsCustomer.put("CUSTOMER_A_3", 12_000);
    constraintsCustomer.put("CUSTOMER_A_4", 36_000);
    constraintsCustomer.put("CUSTOMER_A_5", 0);
    constraintsCustomer.put("CUSTOMER_A_6", 36_000);
    constraintsCustomer.put("CUSTOMER_A_7", 12_000);
    constraintsCustomer.put("CUSTOMER_A_8", 0);
    constraintsCustomer.put("CUSTOMER_A_9", 0);
    constraintsCustomer.put("CUSTOMER_A_10", 12_000);
    constraintsCustomer.put("CUSTOMER_A_11", 12_000);
    constraintsCustomer.put("CUSTOMER_A_12", 0);
    constraintsCustomer.put("CUSTOMER_A_13", 0);
    constraintsCustomer.put("CUSTOMER_A_14", 0);
    constraintsCustomer.put("CUSTOMER_B_1", 24_000);
    constraintsCustomer.put("CUSTOMER_B_2", 12_000);
    constraintsCustomer.put("CUSTOMER_B_3", 300);
    constraintsCustomer.put("CUSTOMER_C_1", 24_000);
    constraintsCustomer.put("CUSTOMER_D_1", 20_000);
    constraintsCustomer.put("CUSTOMER_E_1", 12_000);
    constraintsCustomer.put("CUSTOMER_F_1", 12_000);
    constraintsCustomer.put("CUSTOMER_G_1", 72_000);
    constraintsCustomer.put("CUSTOMER_H_1", 28_000);
    constraintsCustomer.put("CUSTOMER_I_1", 24_000);
    constraintsCustomer.put("CUSTOMER_J_1", 16_000);
    constraintsCustomer.put("CUSTOMER_K_1", 24_000);
    constraintsCustomer.put("CUSTOMER_L_1", 56_000);
    final double demandTotal = constraintsCustomer.values().stream().mapToDouble(e -> e.doubleValue()).sum();
    // BasicLogger.debug("DEMAND_TOTAL " + demandTotal);
    /*
         * User constraint. In this case, user want to allocate 236_000 Qty on Customer_A_*
         */
    final double userConstraintQty = 236_000;
    final List<String> userConstraint = new ArrayList<>();
    userConstraint.add("CUSTOMER_A_1|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_2|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_3|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_4|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_5|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_6|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_7|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_8|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_9|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_10|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_11|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_12|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_13|PRODUCT_2");
    userConstraint.add("CUSTOMER_A_14|PRODUCT_2");
    // List of Variable Names
    final List<String> variablesName = new ArrayList<>();
    variablesName.add("CUSTOMER_A_1|PRODUCT_2");
    variablesName.add("CUSTOMER_A_2|PRODUCT_2");
    variablesName.add("CUSTOMER_A_3|PRODUCT_2");
    variablesName.add("CUSTOMER_A_4|PRODUCT_2");
    variablesName.add("CUSTOMER_A_5|PRODUCT_2");
    variablesName.add("CUSTOMER_A_6|PRODUCT_2");
    variablesName.add("CUSTOMER_A_7|PRODUCT_2");
    variablesName.add("CUSTOMER_A_8|PRODUCT_2");
    variablesName.add("CUSTOMER_A_9|PRODUCT_2");
    variablesName.add("CUSTOMER_A_10|PRODUCT_2");
    variablesName.add("CUSTOMER_A_11|PRODUCT_2");
    variablesName.add("CUSTOMER_A_12|PRODUCT_2");
    variablesName.add("CUSTOMER_A_13|PRODUCT_2");
    variablesName.add("CUSTOMER_A_14|PRODUCT_2");
    variablesName.add("CUSTOMER_B_1|PRODUCT_2");
    variablesName.add("CUSTOMER_B_1|PRODUCT_3");
    variablesName.add("CUSTOMER_B_2|PRODUCT_2");
    variablesName.add("CUSTOMER_B_2|PRODUCT_3");
    variablesName.add("CUSTOMER_B_3|PRODUCT_2");
    variablesName.add("CUSTOMER_B_3|PRODUCT_3");
    variablesName.add("CUSTOMER_C_1|PRODUCT_2");
    variablesName.add("CUSTOMER_C_1|PRODUCT_3");
    variablesName.add("CUSTOMER_D_1|PRODUCT_4");
    variablesName.add("CUSTOMER_D_1|PRODUCT_5");
    variablesName.add("CUSTOMER_D_1|PRODUCT_2");
    variablesName.add("CUSTOMER_D_1|PRODUCT_3");
    variablesName.add("CUSTOMER_E_1|PRODUCT_1");
    variablesName.add("CUSTOMER_F_1|PRODUCT_4");
    variablesName.add("CUSTOMER_F_1|PRODUCT_5");
    variablesName.add("CUSTOMER_F_1|PRODUCT_2");
    variablesName.add("CUSTOMER_F_1|PRODUCT_3");
    variablesName.add("CUSTOMER_G_1|PRODUCT_4");
    variablesName.add("CUSTOMER_G_1|PRODUCT_5");
    variablesName.add("CUSTOMER_G_1|PRODUCT_2");
    variablesName.add("CUSTOMER_G_1|PRODUCT_3");
    variablesName.add("CUSTOMER_H_1|PRODUCT_4");
    variablesName.add("CUSTOMER_H_1|PRODUCT_5");
    variablesName.add("CUSTOMER_H_1|PRODUCT_2");
    variablesName.add("CUSTOMER_H_1|PRODUCT_3");
    variablesName.add("CUSTOMER_I_1|PRODUCT_4");
    variablesName.add("CUSTOMER_I_1|PRODUCT_5");
    variablesName.add("CUSTOMER_I_1|PRODUCT_2");
    variablesName.add("CUSTOMER_I_1|PRODUCT_3");
    variablesName.add("CUSTOMER_J_1|PRODUCT_4");
    variablesName.add("CUSTOMER_J_1|PRODUCT_5");
    variablesName.add("CUSTOMER_J_1|PRODUCT_2");
    variablesName.add("CUSTOMER_J_1|PRODUCT_3");
    variablesName.add("CUSTOMER_K_1|PRODUCT_4");
    variablesName.add("CUSTOMER_K_1|PRODUCT_5");
    variablesName.add("CUSTOMER_K_1|PRODUCT_2");
    variablesName.add("CUSTOMER_K_1|PRODUCT_3");
    variablesName.add("CUSTOMER_L_1|PRODUCT_1");
    /*
         *
         */
    final ExpressionsBasedModel model = new ExpressionsBasedModel();
    final List<Variable> variables = new ArrayList<>();
    /*
         * Create All Variables:
         */
    // BasicLogger.debug("---- Variable creation ------");
    variablesName.forEach(name -> {
        final Variable var = Variable.make(name).lower(0.0).weight(1.0);
        model.addVariable(var);
        variables.add(var);
    // BasicLogger.debug(var);
    });
    // BasicLogger.debug("---- Constraints customers ------");
    // Apply Customers constraints.
    // CUSTOMER_A of Demand constraint because managed by user constraints.
    constraintsCustomer.entrySet().stream().filter(e -> !e.getKey().startsWith("CUSTOMER_A")).forEach(entry -> {
        final List<Variable> linked = variables.stream().filter(v -> v.getName().startsWith(entry.getKey())).collect(Collectors.toList());
        final Expression constraint = model.addExpression("CONSTRAINTS_" + entry.getKey());
        constraint.upper(entry.getValue().doubleValue());
        constraint.setLinearFactorsSimple(linked);
    // BasicLogger.debug(constraint);
    });
    // BasicLogger.debug("---- User Constraints Customers ------");
    // Apply Product Type constraints.
    final List<Variable> userLinked = variables.stream().filter(v -> userConstraint.contains(v.getName())).collect(Collectors.toList());
    final Expression constraintUser = model.addExpression("CONSTRAINTS_USER_CUSTOMER_A");
    constraintUser.level(userConstraintQty);
    constraintUser.setLinearFactorsSimple(userLinked);
    // BasicLogger.debug(constraintUser);
    // BasicLogger.debug("---- Constraints Product ------");
    // Apply Product Type constraints.
    constraintsProduct.entrySet().forEach(entry -> {
        final List<Variable> linked = variables.stream().filter(v -> v.getName().endsWith(entry.getKey())).collect(Collectors.toList());
        final Expression constraint = model.addExpression("CONSTRAINTS_" + entry.getKey());
        constraint.upper(entry.getValue().doubleValue());
        constraint.setLinearFactorsSimple(linked);
    // BasicLogger.debug(constraint);
    });
    /*
         * Objective expression. - Maximize the Sum of all variables - Minimize the Sum of square error vs
         * proportionality.
         */
    // BasicLogger.debug("---- Objective  ------");
    final Expression objective = model.addExpression("OBJECTIVE").weight(-1.0);
    // - Maximize the Sum of all variables
    // objective.setLinearFactorsSimple(variables);
    // BasicLogger.debug("---- Error formula ------");
    /*
         * Example: x1, x2, x3 linked variables for Customer X Error = ( (x1+x2+x3) / Target - 1 )^2 * ratio
         */
    constraintsCustomer.entrySet().forEach(entry -> {
        final List<Variable> linked = variables.stream().filter(v -> v.getName().startsWith(entry.getKey())).collect(Collectors.toList());
        if (!linked.isEmpty() && (entry.getValue().doubleValue() > 0)) {
            final double demand = entry.getValue();
            final double ratio = demand / demandTotal;
            final double target = stockTotal * ratio;
            linked.forEach(v1 -> {
                linked.forEach(v2 -> {
                    objective.set(v1, v2, ratio / (target * target));
                });
                objective.set(v1, (-2.0 * ratio) / target);
            });
        }
    });
    return model;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) Result(org.ojalgo.optimisation.Optimisation.Result) Expression(org.ojalgo.optimisation.Expression) Map(java.util.Map) BasicLogger(org.ojalgo.netio.BasicLogger) BigDenseStore(org.ojalgo.matrix.store.BigDenseStore) Variable(org.ojalgo.optimisation.Variable) HashMap(java.util.HashMap) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Variable(org.ojalgo.optimisation.Variable) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ExpressionsBasedModel(org.ojalgo.optimisation.ExpressionsBasedModel) LinkedHashMap(java.util.LinkedHashMap) Expression(org.ojalgo.optimisation.Expression)

Aggregations

Expression (org.ojalgo.optimisation.Expression)49 ExpressionsBasedModel (org.ojalgo.optimisation.ExpressionsBasedModel)45 Variable (org.ojalgo.optimisation.Variable)44 Result (org.ojalgo.optimisation.Optimisation.Result)27 Test (org.junit.jupiter.api.Test)23 BigDecimal (java.math.BigDecimal)18 Optimisation (org.ojalgo.optimisation.Optimisation)18 ArrayList (java.util.ArrayList)9 BasicMatrix (org.ojalgo.matrix.BasicMatrix)9 NumberContext (org.ojalgo.type.context.NumberContext)9 List (java.util.List)5 Map (java.util.Map)5 Collectors (java.util.stream.Collectors)5 HashMap (java.util.HashMap)4 LinkedHashMap (java.util.LinkedHashMap)4 BasicLogger (org.ojalgo.netio.BasicLogger)4 IntIndex (org.ojalgo.access.Structure1D.IntIndex)3 BigArray (org.ojalgo.array.BigArray)3 BigDenseStore (org.ojalgo.matrix.store.BigDenseStore)3 File (java.io.File)1