使用Java API在Cplex中添加不平等约束

时间:2018-08-20 08:31:39

标签: java math mathematical-optimization cplex

我是新来的。我想将以下matlab表达式转换为Java

X = cplexbilp(ObjectiveVector,Aineq,Bineq,Aeq,Beq);

当前,我在Java中使用以下行,但是解决方案与预期的不同(与matlab中的解决方案不同)。

private SimpleMatrix CplexSolver(SimpleMatrix ObjectiveFunction, SimpleMatrix Aineq,SimpleMatrix Bineq , SimpleMatrix Aeq , SimpleMatrix Beq)
{
    SimpleMatrix X = new SimpleMatrix( ObjectiveFunction.numCols(), 1);
    try {
        IloCplex cplex = new IloCplex();
        IloLinearIntExpr objective = cplex.linearIntExpr();
        IloIntVar [] cplexVars = new IloIntVar[ObjectiveFunction.numCols()];



        for (int i = 0 ; i < ObjectiveFunction.numCols() ; i++)
        {
            cplexVars[i] = cplex.boolVar();
            objective.addTerm((int) ObjectiveFunction.get(0, i), cplexVars[i]);
        }
        IloLinearIntExpr exp[] = new IloLinearIntExpr[Aeq.numRows()];

        for (int j = 0 ; j <Aeq.numRows(); j++ )    
        {   
            exp[j] = cplex.linearIntExpr();
            for (int k = 0 ; k<Aeq.numCols(); k++)
            {
                exp[j].addTerm((int) Aeq.get(j, k), cplexVars[k]);
            }

            cplex.addEq(exp[j], Beq.get(j, 0));
        }


        ArrayList<IloRange> Constraints = new ArrayList<IloRange>();
        IloIntVar [][] constVars = new IloIntVar[Aineq.numRows()][Aineq.numCols()];
        IloLinearIntExpr [] constExp = new IloLinearIntExpr [Aineq.numRows()];

        for (int k = 0 ; k < Aineq.numRows() ;k++)
        {
            constExp[k] = cplex.linearIntExpr();

            for (int t = 0 ; t < Aineq.numCols(); t++)
            {
                constVars[k][t] = cplex.boolVar();
                constExp[k].addTerm((int)Aineq.get(k, t), constVars[k][t]);

            }

        }

        for (int c = 0 ; c < Aineq.numRows(); c++) { 
            Constraints.add(cplex.addRange(Double.NEGATIVE_INFINITY, constExp[c], Bineq.get(c, 0)));
            cplex.addToExpr(Constraints.get(c), constExp[c]);
        }

        cplex.addMinimize(objective);

        if(cplex.solve())
        {
            System.out.println("cplex status "+cplex.getCplexStatus().toString());
            for (int i = 0 ; i < cplexVars.length ; i++) {
        System.out.println("value of variable "+(i+1)+" is : "+cplex.getValue(cplexVars[i]) );
                X.set(i, 0, cplex.getValue(cplexVars[i]));
            }

        }else{
            LOG.error("Linear System is not valid to solve uinsg Cplex" );
        }


    } catch (IloException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("X"); 
    for(int l = 0 ; l < X.getNumElements(); l++)
        System.out.println("X("+(l+1)+") :" +XStoch.get(l, 0) );
    return X;

}

我正在使用EJML来处理矩阵。输入数据的详细信息如下。

  • 目标函数有一行n列

  • Aineq有m行和n列

  • Bineq有m行和一个列。

  • Aeq有k行n列

  • Beq有k行和一个列。

预先感谢

0 个答案:

没有答案