C#調用CPLEX求解簡單線性規劃問題樣例

這次用的例子是《運籌學 第四版》清華大學出版社 上的例子

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Drawing.Drawing2D; 
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using ILOG.Concert;
using ILOG.CPLEX;


public class CTransportProblem//節點
{
    public int m_nSupply;//行數
    public int m_nDemand;//列數
    public double[,] Cost=null;
    public double[] x = null;
    public double[] Supply;

    public CTransportProblem()
    {        
        
    }
    public void SetParameters()
    {
        m_nSupply = 3;
        m_nDemand = 3;
        Supply = new double[m_nSupply];
        Cost = Matrix.LoadData("TPCost.txt", '\t');
        //Cost = {{ 1,-2,1 },
        //{ -4,1,2 },
        //{ -2,0,1 }
        //};//決策變量係數
        Supply[0] = 11;Supply[1] = 3;Supply[2] = 1;
        x = new double[m_nDemand];
    }
    public double SolveTransportProblembyGurobi()
    {
        int i, j;
        double[] Coef = {-3,1,1 };//改動
        double MaxKeyNumber = 0;
        Cplex cplexModel = new Cplex();
        //定義變量,逐維度new
        INumVar[] varX = new INumVar[m_nSupply];
        NumVarType[] TypeVar = new NumVarType[m_nDemand];

        //變量下界與上界
        double LbVar = 0.0;
        double UbVar = double.MaxValue;
        for (j = 0; j < m_nDemand; j++)
        {
            TypeVar[j] = NumVarType.Float;
            varX[j] = cplexModel.NumVar( LbVar, UbVar, TypeVar[j]);
        }
        //目標函數
        ILinearNumExpr expr = cplexModel.LinearNumExpr();
       
        for (j = 0; j < m_nDemand; j++)
        {
            expr.AddTerm(varX[j], Coef[j]);
        }
        
        cplexModel.AddMinimize(expr);
        //約束條件       
        expr = cplexModel.LinearNumExpr();
        for (j = 0; j < m_nDemand; j++)
        {
            expr.AddTerm(varX[j], Cost[0,j]);
        }
        cplexModel.AddLe(expr, Supply[0]);

        expr = cplexModel.LinearNumExpr();
        for (j = 0; j < m_nDemand; j++)
        {
            expr.AddTerm(varX[j], Cost[1, j]);
        }
        cplexModel.AddGe(expr, Supply[1]);

        expr = cplexModel.LinearNumExpr();
        for (j = 0; j < m_nDemand; j++)
        {
            expr.AddTerm(varX[j], Cost[2, j]);
        }
        cplexModel.AddEq(expr, Supply[2]);

        //求解
        double objvalue = double.MaxValue;
        if (cplexModel.Solve())
        {
            //最後求的目標函數的值
            objvalue = cplexModel.ObjValue;
            for (j = 0; j < m_nDemand; j++)
            {
                x[j] = cplexModel.GetValue(varX[j]);
            }

            //Matrix.Output(x, '\t', "x.txt");
        }
        cplexModel.End();
        return objvalue;
    }
}

寫的比較匆忙,添加約束條件呢裏直接複製粘貼的...有些粗糙 見諒...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章