Beispiel #1
0
        protected void InitRMPModel()
        {
            cost       = RMPModel.AddMaximize();
            var        = new Dictionary <IALPDecision, INumVar> [Data.TimeHorizon];
            DualValue1 = new double[Data.TimeHorizon][];
            DualValue2 = new double[Data.TimeHorizon];
            lowerbound = new double[Data.TimeHorizon][];
            upperbound = new double[Data.TimeHorizon][];
            #region //////////////生成约束//////////////
            constraint1 = new IRange[Data.TimeHorizon][];
            constraint2 = new IRange[Data.TimeHorizon];
            for (int i = 0; i < Data.TimeHorizon; i++)
            {
                DualValue1[i]  = new double[Data.RS.Count];
                var[i]         = new Dictionary <IALPDecision, INumVar>();
                constraint1[i] = new IRange[Data.RS.Count];
                lowerbound[i]  = new double[Data.RS.Count];
                upperbound[i]  = new double[Data.RS.Count];
                foreach (IALPResource re in Data.RS)
                {
                    constraint1[i][Data.RS.IndexOf(re)] = RMPModel.AddRange(double.MinValue, (Data.InitialState as IALPState)[re]);
                }
                //constraint1[i][0].UB -= 0.3;
                constraint2[i] = RMPModel.AddRange(1, 1);
            }
            #endregion

            RMPModel.SetOut(this.SolverTextWriter);
        }
Beispiel #2
0
        //Affine Funciton Approximation
        public static Cplex Build_CD1_Model(IALPFTMDP aff)
        {
            Cplex model = new Cplex();

            IObjective cost = model.AddMaximize();

            IRange[][] constraint1 = new IRange[aff.TimeHorizon][];
            IRange[]   constraint2 = new IRange[aff.TimeHorizon];

            #region //////////////生成约束//////////////
            for (int i = 0; i < aff.TimeHorizon; i++)
            {
                constraint1[i] = new IRange[aff.RS.Count];
                foreach (IALPResource re in aff.RS)
                {
                    if (i == 0)
                    {
                        constraint1[i][aff.RS.IndexOf(re)] = model.AddRange((aff.InitialState as IALPState)[re], (aff.InitialState as IALPState)[re]);
                    }
                    else
                    {
                        constraint1[i][aff.RS.IndexOf(re)] = model.AddRange(0, 0);
                    }
                }
                constraint2[i] = model.AddRange(1, 1);
            }
            #endregion

            #region //////////////生成变量//////////////
            for (int t = 0; t < aff.TimeHorizon; t++)
            {
                foreach (IALPState s in aff.SS)
                {
                    foreach (IMDPDecision a in aff.GenDecisionSpace(s))
                    {
                        Column col = model.Column(cost, aff.Rt(t, a));
                        foreach (IALPResource re in aff.RS)
                        {
                            col = col.And(model.Column(constraint1[t][aff.RS.IndexOf(re)], (s as IALPState)[re]));
                            if (t < aff.TimeHorizon - 1)
                            {
                                col = col.And(model.Column(constraint1[t + 1][aff.RS.IndexOf(re)], (aff.Qti(t, re, a)) - (s as IALPState)[re]));
                            }
                        }
                        col = col.And(model.Column(constraint2[t], 1));
                        model.NumVar(col, 0, double.MaxValue, NumVarType.Float);
                    }
                }
            }
            #endregion
            return(model);
        }
Beispiel #3
0
        public static Cplex BuildDualModel(IFTMDP Ida)
        {
            Cplex model = new Cplex();

            IObjective cost = model.AddMaximize();

            IRange[][] constraint = new IRange[Ida.TimeHorizon][];

            #region //////////////生成约束//////////////
            for (int i = 0; i < Ida.TimeHorizon; i++)
            {
                constraint[i] = new IRange[Ida.SS.Count];
                foreach (IMDPState s in Ida.SS)
                {
                    if (i == 0 && s.Equals(Ida.InitialState))
                    {
                        constraint[i][Ida.SS.IndexOf(s)] = model.AddRange(1, 1);
                    }
                    else
                    {
                        constraint[i][Ida.SS.IndexOf(s)] = model.AddRange(0, 0);
                    }
                }
            }
            #endregion

            #region //////////////生成变量//////////////
            for (int t = 0; t < Ida.TimeHorizon; t++)
            {
                foreach (IMDPState s in Ida.SS)
                {
                    foreach (IMDPDecision a in Ida.GenDecisionSpace(s))
                    {
                        Column col = model.Column(cost, Ida.Reward(t, s, a));
                        col = col.And(model.Column(constraint[t][Ida.SS.IndexOf(s)], 1));    //插入Aj

                        if (t < Ida.TimeHorizon - 1)
                        {
                            foreach (IMDPState k in Ida.GenStateSpace(s, a))
                            {
                                col = col.And(model.Column(constraint[t + 1][Ida.SS.IndexOf(k)], -Ida.Prob(t, s, k, a)));    //插入Aj
                            }
                        }
                        model.NumVar(col, 0, double.MaxValue, NumVarType.Float);
                    }
                }
            }
            #endregion
            model.SetOut(null);
            return(model);
        }
Beispiel #4
0
        public static Cplex Build_CD3_Model(IALPFTMDP aff)
        {
            Cplex      model = new Cplex();
            IObjective cost  = model.AddMaximize();

            INumVar[][] var = new INumVar[aff.TimeHorizon][];

            #region //////////////生成约束//////////////
            IRange[][] constraint1 = new IRange[aff.TimeHorizon][];
            IRange[]   constraint2 = new IRange[aff.TimeHorizon];
            for (int i = 0; i < aff.TimeHorizon; i++)
            {
                var[i]         = new INumVar[aff.DS.Count];
                constraint1[i] = new IRange[aff.RS.Count];
                foreach (IALPResource re in aff.RS)
                {
                    constraint1[i][aff.RS.IndexOf(re)] = model.AddRange(double.MinValue, (aff.InitialState as IALPState)[re]);
                }
                constraint2[i] = model.AddRange(1, 1);
            }
            #endregion

            #region //////////////生成变量//////////////
            for (int t = 0; t < aff.TimeHorizon; t++)
            {
                foreach (IALPDecision a in aff.DS)
                {
                    //目标函数
                    Column col = model.Column(cost, aff.Rt(t, a));
                    //第一类约束
                    foreach (IALPResource re in aff.RS)
                    {
                        for (int k = t + 1; k < aff.TimeHorizon; k++)
                        {
                            col = col.And(model.Column(constraint1[k][aff.RS.IndexOf(re)], aff.Qti(t, re, a)));
                        }
                        if (a.UseResource(re))
                        {
                            col = col.And(model.Column(constraint1[t][aff.RS.IndexOf(re)], 1));
                        }
                    }
                    //第二类约束
                    col = col.And(model.Column(constraint2[t], 1));
                    var[t][aff.DS.IndexOf(a)] = model.NumVar(col, 0, double.MaxValue, NumVarType.Float);
                }
            }
            #endregion

            return(model);
        }
Beispiel #5
0
 private void InitModel()
 {
     constraint = model.AddRange(1, 1);
     vars       = new INumVar[aff.DS.Count];
     model.SetOut(null);
     //P = new IALPDecision[aff.TimeHorizon];
 }
Beispiel #6
0
        private void InitRMPModel()
        {
            RMPModel.ClearModel();
            cost        = RMPModel.AddMaximize();
            constraint1 = new IRange[Data.TimeHorizon][];
            constraint2 = new IRange[Data.TimeHorizon];
            DualValue1  = new double[Data.TimeHorizon][];
            DualValue2  = new double[Data.TimeHorizon];

            #region //////////////生成约束//////////////
            //Parallel.For(0, Data.TimeHorizon, i =>
            for (int i = 0; i < Data.TimeHorizon; i++)
            {
                lock (RMPModel)
                {
                    constraint1[i] = new IRange[Data.RS.Count];
                    DualValue1[i]  = new double[Data.RS.Count];
                    foreach (IALPResource re in Data.RS)
                    {
                        if (i == 0)
                        {
                            constraint1[i][Data.RS.IndexOf(re)] = RMPModel.AddRange((Data.InitialState as IALPState)[re], (Data.InitialState as IALPState)[re]);
                        }
                        else
                        {
                            constraint1[i][Data.RS.IndexOf(re)] = RMPModel.AddRange(0, 0);
                        }
                    }
                    constraint2[i] = RMPModel.AddRange(1, 1);
                }
            }
            #endregion

            //RMPModel.SetParam(Cplex.LongParam.RootAlgorithm, 1);
            RMPModel.SetOut(SolverTextWriter);
        }
Beispiel #7
0
    public static void Main(string[] args)
    {
        try {
            Cplex cplex = new Cplex();

            INumVar[] inside  = new INumVar[_nbProds];
            INumVar[] outside = new INumVar[_nbProds];

            IObjective obj = cplex.AddMinimize();

            // Must meet demand for each product

            for (int p = 0; p < _nbProds; p++)
            {
                IRange demRange = cplex.AddRange(_demand[p], _demand[p]);
                inside[p] = cplex.NumVar(cplex.Column(obj, _insideCost[p]).And(
                                             cplex.Column(demRange, 1.0)),
                                         0.0, System.Double.MaxValue);

                outside[p] = cplex.NumVar(cplex.Column(obj, _outsideCost[p]).And(
                                              cplex.Column(demRange, 1.0)),
                                          0.0, System.Double.MaxValue);
            }

            // Must respect capacity constraint for each resource

            for (int r = 0; r < _nbResources; r++)
            {
                cplex.AddLe(cplex.ScalProd(_consumption[r], inside), _capacity[r]);
            }

            cplex.Solve();

            if (!cplex.GetStatus().Equals(Cplex.Status.Optimal))
            {
                System.Console.WriteLine("No optimal solution found");
                return;
            }

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            DisplayResults(cplex, inside, outside);
            System.Console.WriteLine("----------------------------------------");
            cplex.End();
        }
        catch (ILOG.Concert.Exception exc) {
            System.Console.WriteLine("Concert exception '" + exc + "' caught");
        }
    }
Beispiel #8
0
    public static void Main( string[] args )
    {
        try {
         Cplex cplex = new Cplex();

         INumVar[]  inside = new INumVar[_nbProds];
         INumVar[] outside = new INumVar[_nbProds];

         IObjective obj = cplex.AddMinimize();

         // Must meet demand for each product

         for(int p = 0; p < _nbProds; p++) {
            IRange demRange = cplex.AddRange(_demand[p], _demand[p]);
            inside[p] = cplex.NumVar(cplex.Column(obj, _insideCost[p]).And(
                                     cplex.Column(demRange, 1.0)),
                                     0.0, System.Double.MaxValue);

            outside[p] = cplex.NumVar(cplex.Column(obj, _outsideCost[p]).And(
                                      cplex.Column(demRange, 1.0)),
                                      0.0, System.Double.MaxValue);
         }

         // Must respect capacity constraint for each resource

         for(int r = 0; r < _nbResources; r++)
            cplex.AddLe(cplex.ScalProd(_consumption[r], inside), _capacity[r]);

         cplex.Solve();

         if ( !cplex.GetStatus().Equals(Cplex.Status.Optimal) ) {
            System.Console.WriteLine("No optimal solution found");
            return;
         }

         System.Console.WriteLine("Solution status = " + cplex.GetStatus());
         DisplayResults(cplex, inside, outside);
         System.Console.WriteLine("----------------------------------------");
         cplex.End();
          }
          catch (ILOG.Concert.Exception exc) {
         System.Console.WriteLine("Concert exception '" + exc + "' caught");
          }
    }
Beispiel #9
0
    public static void Main(string[] args)
    {
        try {
            string datafile = "../../../../examples/data/cutstock.dat";
            if (args.Length > 0)
            {
                datafile = args[0];
            }
            ReadData(datafile);

            /// CUTTING-OPTIMIZATION PROBLEM ///

            Cplex cutSolver = new Cplex();

            IObjective RollsUsed = cutSolver.AddMinimize();
            IRange[]   Fill      = new IRange[_amount.Length];
            for (int f = 0; f < _amount.Length; f++)
            {
                Fill[f] = cutSolver.AddRange(_amount[f], System.Double.MaxValue);
            }

            System.Collections.ArrayList Cut = new System.Collections.ArrayList();

            int nWdth = _size.Length;
            for (int j = 0; j < nWdth; j++)
            {
                Cut.Add(cutSolver.NumVar(cutSolver.Column(RollsUsed, 1.0).And(
                                             cutSolver.Column(Fill[j],
                                                              (int)(_rollWidth / _size[j]))),
                                         0.0, System.Double.MaxValue));
            }

            cutSolver.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal);

            /// PATTERN-GENERATION PROBLEM ///

            Cplex patSolver = new Cplex();

            IObjective ReducedCost = patSolver.AddMinimize();
            INumVar[]  Use         = patSolver.NumVarArray(nWdth,
                                                           0.0, System.Double.MaxValue,
                                                           NumVarType.Int);
            patSolver.AddRange(-System.Double.MaxValue,
                               patSolver.ScalProd(_size, Use),
                               _rollWidth);

            /// COLUMN-GENERATION PROCEDURE ///

            double[] newPatt = new double[nWdth];

            /// COLUMN-GENERATION PROCEDURE ///

            for (;;)
            {
                /// OPTIMIZE OVER CURRENT PATTERNS ///

                cutSolver.Solve();
                Report1(cutSolver, Cut, Fill);

                /// FIND AND ADD A NEW PATTERN ///

                double[] price = cutSolver.GetDuals(Fill);
                ReducedCost.Expr = patSolver.Diff(1.0,
                                                  patSolver.ScalProd(Use, price));

                patSolver.Solve();
                Report2(patSolver, Use);

                if (patSolver.ObjValue > -RC_EPS)
                {
                    break;
                }

                newPatt = patSolver.GetValues(Use);

                Column column = cutSolver.Column(RollsUsed, 1.0);
                for (int p = 0; p < newPatt.Length; p++)
                {
                    column = column.And(cutSolver.Column(Fill[p], newPatt[p]));
                }

                Cut.Add(cutSolver.NumVar(column, 0.0, System.Double.MaxValue));
            }

            for (int i = 0; i < Cut.Count; i++)
            {
                cutSolver.Add(cutSolver.Conversion((INumVar)Cut[i],
                                                   NumVarType.Int));
            }

            cutSolver.Solve();
            System.Console.WriteLine("Solution status = " + cutSolver.GetStatus());
            Report3(cutSolver, Cut);

            cutSolver.End();
            patSolver.End();
        }
        catch (ILOG.Concert.Exception exc) {
            System.Console.WriteLine("Concert exception '" + exc + "' caught");
        }
        catch (System.IO.IOException exc) {
            System.Console.WriteLine("Error reading file " + args[0] + ": " + exc);
        }
        catch (InputDataReader.InputDataReaderException exc) {
            System.Console.WriteLine(exc);
        }
    }
Beispiel #10
0
        static void Main(string[] args)
        {
            double[]   price        = { 170.0, 170.0, 170.0 };
            double[]   priceStorage = { 10.0, 10.0, 10.0 };
            double[]   hardness     = { 8.4, 6.2, 2.0 };
            double[]   hardness3    = { 3, 3, 3 };
            double[]   hardness6    = { 6, 6, 6 };
            double[][] oilCost      = new double[2][];
            oilCost[0] = new double[3] {
                1.159550009798596e+02, 1.018115866059220e+02, 1.128780935294160e+02
            };
            oilCost[1] = new double[3] {
                100, 1.067537671189185e+02, 1.098041326934309e+02
            };

            //oilCost = GenerateRandomVector();

            INumVar[][] oilStore   = new INumVar[3][];
            INumVar[][] oilBuy     = new INumVar[2][];
            INumVar[][] oilProduce = new INumVar[2][]; // [month][A-C]
            Cplex       cplex      = new Cplex();

            for (int i = 0; i < 2; i++) // Initialize oilBuy and oilProduce
            {
                oilBuy[i]     = new INumVar[3];
                oilProduce[i] = new INumVar[3];
            }
            for (int i = 0; i < 3; i++) // Initialize oilStore
            {
                oilStore[i] = new INumVar[3];
                for (int j = 0; j < 3; j++)
                {
                    oilStore[i][j] = cplex.NumVar(0, 800); // Ograniczenia na pojemność magazynu
                }
            }
            for (int i = 0; i < 2; i++)     // Ograniczenia na miesiące
            {
                for (int j = 0; j < 3; j++) // Ograniczenia na możliwości rafinacji
                {
                    if (j != 2)
                    {
                        oilProduce[i][j] = cplex.NumVar(0, 220); // Rafinacja roślinnego
                    }
                    else
                    {
                        oilProduce[i][j] = cplex.NumVar(0, 270); // Rafinacja nie-roślinnego
                    }
                    oilBuy[i][j] = cplex.NumVar(0, 1070);
                }
                cplex.AddRange(0, cplex.Sum(oilProduce[i][0], oilProduce[i][1]), 220);
                cplex.AddGe(cplex.ScalProd(hardness, oilProduce[i]), cplex.ScalProd(hardness3, oilProduce[i]));     // Hardness greater than 3
                cplex.AddLe(cplex.ScalProd(hardness, oilProduce[i]), cplex.ScalProd(hardness6, oilProduce[i]));     // Hardness less than 6
            }
            for (int i = 0; i < 3; i++)                                                                             // Ograniczenia na oleje
            {
                cplex.AddEq(oilStore[0][i], 200.0);                                                                 // Ograniczenie na stan magazynu w grudniu
                cplex.AddEq(oilStore[2][i], 200.0);                                                                 // Ograniczenie na stan magazynu w lutym
                cplex.AddEq(oilStore[1][i], cplex.Sum(cplex.Diff(oilBuy[0][i], oilProduce[0][i]), oilStore[0][i])); // (Kupowane + zmagazynowane - produkowane) w tym miesiacu = zmagazynowane w nastepnym miesiacu
                cplex.AddEq(oilStore[2][i], cplex.Sum(cplex.Diff(oilBuy[1][i], oilProduce[1][i]), oilStore[1][i]));
            }

            // Funkcja Celu: zyski ze sprzedaży - koszta magazynowania - koszta kupowania materiału do produkcji
            cplex.AddMaximize(
                cplex.Diff(
                    cplex.Diff(
                        cplex.Sum(
                            cplex.ScalProd(price, oilProduce[0]),
                            cplex.ScalProd(price, oilProduce[1])),
                        cplex.Sum(
                            cplex.ScalProd(priceStorage, oilStore[1]),
                            cplex.ScalProd(priceStorage, oilStore[2]))),
                    cplex.Sum(
                        cplex.ScalProd(oilCost[0], oilBuy[0]),
                        cplex.ScalProd(oilCost[1], oilBuy[1]))));


            if (cplex.Solve())
            {
                System.Console.WriteLine();
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine();
                System.Console.WriteLine("  = " + cplex.ObjValue);
                Console.WriteLine();
                for (int i = 0; i < 2; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        Console.WriteLine(" oilCost[" + i + "][" + j + "] = " + oilCost[i][j]);
                    }
                }

                Console.WriteLine();
                for (int j = 0; j < 2; j++)
                {
                    double hardnessTotal = 0;
                    double sum           = 0;
                    for (int i = 0; i < 3; i++)
                    {
                        System.Console.WriteLine(" oilProduce[" + j + "][" + i + "] = " + cplex.GetValue(oilProduce[j][i]));
                        hardnessTotal += cplex.GetValue(oilProduce[j][i]) * hardness[i];
                        sum           += cplex.GetValue(oilProduce[j][i]);
                    }
                    System.Console.WriteLine(" hardnessTotal[" + j + "] = " + hardnessTotal / sum);
                    Console.WriteLine();
                }

                for (int j = 0; j < 2; j++)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        System.Console.WriteLine(" oilBuy[" + j + "][" + i + "] = " + cplex.GetValue(oilBuy[j][i]));
                    }
                }
                Console.WriteLine();
                for (int j = 0; j < 3; j++)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        System.Console.WriteLine(" oilStore[" + j + "][" + i + "] = " + cplex.GetValue(oilStore[j][i]));
                    }
                }

                System.Console.WriteLine();
            }
            Console.ReadKey();
        }
Beispiel #11
0
        public static Cplex Build_CD2_Model(IALPFTMDP aff)
        {
            Cplex      model = new Cplex();
            IObjective cost  = model.AddMaximize();

            #region //////////////生成约束//////////////
            IRange[][] constraint1 = new IRange[aff.TimeHorizon][];
            IRange[][] constraint2 = new IRange[aff.TimeHorizon][];
            IRange[]   constraint3 = new IRange[aff.TimeHorizon];
            for (int i = 0; i < aff.TimeHorizon; i++)
            {
                constraint1[i] = new IRange[aff.RS.Count];
                constraint2[i] = new IRange[aff.RS.Count];
                foreach (IALPResource re in aff.RS)
                {
                    if (i == 0)
                    {
                        constraint1[i][aff.RS.IndexOf(re)] = model.AddRange((aff.InitialState as IALPState)[re], (aff.InitialState as IALPState)[re]);
                        constraint2[i][aff.RS.IndexOf(re)] = model.AddRange(double.MinValue, 0);
                    }
                    else
                    {
                        constraint1[i][aff.RS.IndexOf(re)] = model.AddRange(0, 0);
                        constraint2[i][aff.RS.IndexOf(re)] = model.AddRange(double.MinValue, 0);
                    }
                }
                constraint3[i] = model.AddRange(1, 1);
            }
            #endregion

            #region //////////////生成变量//////////////
            //生成h
            for (int t = 0; t < aff.TimeHorizon; t++)
            {
                foreach (IALPDecision a in aff.DS)
                {
                    //目标函数
                    Column col = model.Column(cost, aff.Rt(t, a));
                    foreach (IALPResource re in aff.RS)
                    {
                        //第一类约束
                        if (t < aff.TimeHorizon - 1)
                        {
                            col = col.And(model.Column(constraint1[t + 1][aff.RS.IndexOf(re)], aff.Qti(t + 1, re, a)));
                        }
                        //第二类约束
                        if (a.UseResource(re))
                        {
                            col = col.And(model.Column(constraint2[t][aff.RS.IndexOf(re)], 1));
                        }
                    }
                    //第三类约束
                    col = col.And(model.Column(constraint3[t], 1));
                    model.NumVar(col, 0, double.MaxValue, NumVarType.Float);
                }
                foreach (IALPResource r in aff.RS)
                {
                    Column col = model.Column(cost, 0);// cost, aff.Rt(t, a));
                    if (t < aff.TimeHorizon - 1)
                    {
                        col = col.And(model.Column(constraint1[t + 1][aff.RS.IndexOf(r)], -1));
                    }
                    col = col.And(model.Column(constraint1[t][aff.RS.IndexOf(r)], 1));
                    col = col.And(model.Column(constraint2[t][aff.RS.IndexOf(r)], -1));
                    model.NumVar(col, 0, double.MaxValue, NumVarType.Float);
                }
            }
            ///);
            #endregion

            return(model);
        }
Beispiel #12
0
        //Piece-Wise Function Approximation
        public static Cplex Build_Dual_PW_Model(IALPFTMDP aff)
        {
            Cplex      model = new Cplex();
            IObjective cost  = model.AddMaximize();

            #region //////////////生成约束//////////////
            IRange[][][] constraint1 = new IRange[aff.TimeHorizon][][];
            IRange[]     constraint2 = new IRange[aff.TimeHorizon];
            for (int i = 0; i < aff.TimeHorizon; i++)
            {
                constraint1[i] = new IRange[aff.RS.Count][];
                foreach (IALPResource re in aff.RS)
                {
                    constraint1[i][aff.RS.IndexOf(re)] = new IRange[(aff.InitialState as IALPState)[re]];
                    for (int k = 1; k < (aff.InitialState as IALPState)[re]; k++)
                    {
                        if (i == 0)
                        {
                            constraint1[i][aff.RS.IndexOf(re)][k - 1] = model.AddRange(1, 1);
                        }
                        else
                        {
                            constraint1[i][aff.RS.IndexOf(re)][k - 1] = model.AddRange(0, 0);
                        }
                    }
                }
                constraint2[i] = model.AddRange(1, 1);
            }
            #endregion

            #region //////////////生成变量//////////////
            //System.Threading.Tasks.Parallel.For(0, aff.TimeHorizon, (t) =>
            for (int t = 0; t < aff.TimeHorizon; t++)
            {
                foreach (IALPState s in aff.SS)
                {
                    foreach (IMDPDecision a in aff.GenDecisionSpace(s))
                    {
                        //目标函数
                        Column col = model.Column(cost, aff.Reward(t, s, a));
                        // System.Console.WriteLine(aff.Reward(t, s, a));
                        //第一类约束
                        foreach (IALPResource re in aff.RS)
                        {
                            for (int k = 1; k < (aff.InitialState as IALPState)[re]; k++)
                            {
                                if (s[re] >= k)
                                {
                                    col = col.And(model.Column(constraint1[t][aff.RS.IndexOf(re)][k - 1], 1));
                                    if (t < aff.TimeHorizon - 1)
                                    {
                                        col = col.And(model.Column(constraint1[t + 1][aff.RS.IndexOf(re)][k - 1], -1));
                                        if (s[re] == k)
                                        {
                                            col = col.And(model.Column(constraint1[t + 1][aff.RS.IndexOf(re)][k - 1], (aff.Qti(t, re, a))));
                                        }
                                    }
                                }
                            }
                        }
                        //第二类约束
                        col = col.And(model.Column(constraint2[t], 1));
                        model.NumVar(col, 0, double.MaxValue, NumVarType.Float);
                    }
                }
            }
            ///);
            #endregion

            model.SetOut(null);
            return(model);
        }
Beispiel #13
0
    public static void Main( string[] args )
    {
        try {
         string datafile = "../../../../examples/data/cutstock.dat";
         if (args.Length > 0)
            datafile = args[0];
         ReadData(datafile);

         /// CUTTING-OPTIMIZATION PROBLEM ///

         Cplex cutSolver = new Cplex();

         IObjective RollsUsed = cutSolver.AddMinimize();
         IRange[]   Fill = new IRange[_amount.Length];
         for (int f = 0; f < _amount.Length; f++ ) {
            Fill[f] = cutSolver.AddRange(_amount[f], System.Double.MaxValue);
         }

         System.Collections.ArrayList Cut = new System.Collections.ArrayList();

         int nWdth = _size.Length;
         for (int j = 0; j < nWdth; j++)
            Cut.Add(cutSolver.NumVar(cutSolver.Column(RollsUsed, 1.0).And(
                                     cutSolver.Column(Fill[j],
                                                      (int)(_rollWidth/_size[j]))),
                                     0.0, System.Double.MaxValue));

         cutSolver.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal);

         /// PATTERN-GENERATION PROBLEM ///

         Cplex patSolver = new Cplex();

         IObjective ReducedCost = patSolver.AddMinimize();
         INumVar[] Use = patSolver.NumVarArray(nWdth,
                                               0.0, System.Double.MaxValue,
                                               NumVarType.Int);
         patSolver.AddRange(-System.Double.MaxValue,
                            patSolver.ScalProd(_size, Use),
                            _rollWidth);

         /// COLUMN-GENERATION PROCEDURE ///

         double[] newPatt = new double[nWdth];

         /// COLUMN-GENERATION PROCEDURE ///

         for (;;) {
            /// OPTIMIZE OVER CURRENT PATTERNS ///

            cutSolver.Solve();
            Report1(cutSolver, Cut, Fill);

            /// FIND AND ADD A NEW PATTERN ///

            double[] price = cutSolver.GetDuals(Fill);
            ReducedCost.Expr = patSolver.Diff(1.0,
                                              patSolver.ScalProd(Use, price));

            patSolver.Solve();
            Report2 (patSolver, Use);

            if ( patSolver.ObjValue > -RC_EPS )
               break;

            newPatt = patSolver.GetValues(Use);

            Column column = cutSolver.Column(RollsUsed, 1.0);
            for ( int p = 0; p < newPatt.Length; p++ )
               column = column.And(cutSolver.Column(Fill[p], newPatt[p]));

            Cut.Add( cutSolver.NumVar(column, 0.0, System.Double.MaxValue) );
         }

         for ( int i = 0; i < Cut.Count; i++ ) {
            cutSolver.Add(cutSolver.Conversion((INumVar)Cut[i],
                                               NumVarType.Int));
         }

         cutSolver.Solve();
         System.Console.WriteLine("Solution status = " + cutSolver.GetStatus());
         Report3 (cutSolver, Cut);

         cutSolver.End();
         patSolver.End();
          }
          catch ( ILOG.Concert.Exception exc ) {
         System.Console.WriteLine("Concert exception '" + exc + "' caught");
          }
          catch (System.IO.IOException exc) {
         System.Console.WriteLine("Error reading file " + args[0] + ": " + exc);
          }
          catch (InputDataReader.InputDataReaderException exc ) {
         System.Console.WriteLine(exc);
          }
    }
Beispiel #14
0
        static void Main(string[] args)
        {
            int nSamples     = 0; // Number of samples
            int nMutGenes    = 0; // Number of mutation genes
            int nExpGenes    = 0; // Number of expression genes
            int nVar         = 0; // Number of variables in MILP
            int nPathways    = 5; // Number of pathways
            int nConstraints = 0; // Number of constraints in MILP

            Data data = new Data();

            // Loads input data.
            data.ReadData("../../inputFile.txt");

            nSamples  = data.mutMatrix.Length;
            nMutGenes = data.mutMatrix[0].Length;
            nExpGenes = data.connectMat.Length;

            // Total number of decision variables:
            // pM --> nMutGenes * nPathways
            // pE --> nExpGenes * nPathways
            // aM --> nSamples * nPathways
            // fM --> nSamples * nPathways
            nVar = (nMutGenes * nPathways) + (nExpGenes * nPathways) + 2 * (nSamples * nPathways);

            // Instance of cplex model.
            Cplex cplex = new Cplex();

            /* We were having issues with "Out of Memory" errors as we increased the number of samples and number of genes
             * To address this, we set parameter NodeFileInd = 3 --> this indicates that node info from MIP optimizer will be compressed
             * and written to files instead of accessing the computer memory during the simulation run
             *
             * */
            cplex.SetParam(Cplex.IntParam.NodeFileInd, 3);

            // Sets names of decision variables.
            string[] name = new string[nVar];

            for (int i = 1; i <= nVar; i++)
            {
                name[i - 1] = "x" + i.ToString();
            }

            // Sets type, lower and upper bound of decision variables.
            NumVarType[] varType = new NumVarType[nVar];
            double[]     lb      = new double[nVar];
            double[]     ub      = new double[nVar];

            for (int i = 0; i < nMutGenes * nPathways; i++)
            {
                // Variable pM is binary.
                varType[i] = NumVarType.Bool;
                lb[i]      = 0;
                ub[i]      = 1;
            }

            for (int i = nMutGenes * nPathways; i < (nMutGenes * nPathways) + (nExpGenes * nPathways); i++)
            {
                // Variable pE is real number.
                varType[i] = NumVarType.Float;
                lb[i]      = 0;
                ub[i]      = System.Double.MaxValue;
            }

            for (int i = (nMutGenes * nPathways) + (nExpGenes * nPathways); i < nVar; i++)
            {
                // Variables aM and fM are binary.
                varType[i] = NumVarType.Bool;
                lb[i]      = 0;
                ub[i]      = 1;
            }


            // Decision Variables.
            INumVar[] x = cplex.NumVarArray(nVar, lb, ub, varType, name);

            // Coeficients of objective function.
            double[] objvals = new double[nVar];

            int contobjvals = 0;
            int idMap       = 0; // Mapping index.

            // Variable pM.
            int[][] pM = new int[nMutGenes][]; // Mapping matrix pM.
            for (int i = 0; i < nMutGenes; i++)
            {
                pM[i] = new int[nPathways];
                for (int j = 0; j < nPathways; j++)
                {
                    // Mapping....
                    pM[i][j] = idMap;
                    idMap++;

                    objvals[contobjvals] = 0;
                    for (int k = 0; k < nSamples; k++)
                    {
                        // Weight associated with first component of objective function = 0.1.
                        objvals[contobjvals] += 0.1 * data.mutMatrix[k][i];
                    }

                    contobjvals++;
                }
            }

            // Variable pE.
            int[][] pE = new int[nExpGenes][];
            for (int i = 0; i < nExpGenes; i++)
            {
                pE[i] = new int[nPathways];
                for (int j = 0; j < nPathways; j++)
                {
                    // Mapping....
                    pE[i][j] = idMap;
                    idMap++;

                    // Weight associated with second component of objective function = 0.9.
                    objvals[contobjvals] = -0.9;
                    contobjvals++;
                }
            }

            // Variable aM.
            int[][] aM = new int[nSamples][];
            for (int i = 0; i < nSamples; i++)
            {
                aM[i] = new int[nPathways];
                for (int j = 0; j < nPathways; j++)
                {
                    // Mapping....
                    aM[i][j] = idMap;
                    idMap++;

                    // Weight associated with first component of objective function = 0.1.
                    objvals[contobjvals] = -0.1;
                    contobjvals++;
                }
            }

            // Variable fM.
            int[][] fM = new int[nSamples][];
            for (int i = 0; i < nSamples; i++)
            {
                fM[i] = new int[nPathways];
                for (int j = 0; j < nPathways; j++)
                {
                    // Mapping....
                    fM[i][j] = idMap;
                    idMap++;

                    // Weight associated with first component of objective function = 0.1.
                    objvals[contobjvals] = 0.1;
                    contobjvals++;
                }
            }

            // Defines the cost function as a minimization of decision variables with corresponding cost coefficients.
            cplex.Add(cplex.Minimize(cplex.ScalProd(x, objvals)));

            nConstraints = nMutGenes + nExpGenes + 2 * nPathways + nSamples * (nPathways - 1) + (nSamples * nPathways) + (nPathways * nExpGenes); // Total number of constraints.
            IRange[] constraint      = new IRange[nConstraints];
            int      contconstraints = 0;

            INumExpr[] Expr = null;

            // Constraints C1.
            Expr = new INumExpr[nPathways];
            for (int i = 0; i < nMutGenes; i++)
            {
                for (int j = 0; j < nPathways; j++)
                {
                    Expr[j] = x[pM[i][j]];
                }

                // Constraints of the form sum(pM) = 1.
                constraint[contconstraints]      = cplex.AddRange(1, 1); // Defines right hand side (= 1).
                constraint[contconstraints].Expr = cplex.Sum(Expr);      // Defines left hand side (sum(pM)).
                contconstraints++;
            }

            // Constraints C2.
            Expr = new INumExpr[nPathways];
            for (int i = 0; i < nExpGenes; i++)
            {
                for (int j = 0; j < nPathways; j++)
                {
                    Expr[j] = x[pE[i][j]];
                }

                // Constraints of the form sum(pE) > 0.
                constraint[contconstraints]      = cplex.AddRange(0.000001, System.Double.MaxValue); // Defines right hand side (> 0).
                constraint[contconstraints].Expr = cplex.Sum(Expr);                                  // Defines left hand side (sum(pE)).
                contconstraints++;
            }

            // Constraints C3.
            Expr = new INumExpr[nMutGenes];
            for (int i = 0; i < nPathways; i++)
            {
                for (int j = 0; j < nMutGenes; j++)
                {
                    Expr[j] = x[pM[j][i]];
                }

                // Constraints of the form sum(pM) >= 1.
                constraint[contconstraints]      = cplex.AddRange(1, System.Double.MaxValue); // Defines right hand side (>= 1).
                constraint[contconstraints].Expr = cplex.Sum(Expr);                           // Defines left hand side (sum(pM)).
                contconstraints++;
            }

            // Constraints C4.
            int id = nMutGenes * nPathways;

            Expr = new INumExpr[nExpGenes];
            for (int i = 0; i < nPathways; i++)
            {
                for (int j = 0; j < nExpGenes; j++)
                {
                    Expr[j] = x[pE[j][i]];
                }

                // Constraints of the form sum(pE) > 0.
                constraint[contconstraints]      = cplex.AddRange(0.000001, System.Double.MaxValue); // Defines right hand side (> 0).
                constraint[contconstraints].Expr = cplex.Sum(Expr);                                  // Defines left hand side (sum(pE)).
                contconstraints++;
            }

            // Constraints C5.
            id = nMutGenes * nPathways + nExpGenes * nPathways;
            for (int i = 0; i < nSamples; i++)
            {
                // Constraints of the form aM - aM >= 0.
                for (int j = 0; j < (nPathways - 1); j++)
                {
                    constraint[contconstraints]      = cplex.AddRange(0, System.Double.MaxValue);                                  // Defines right hand side (>= 0).
                    constraint[contconstraints].Expr = cplex.Sum(cplex.Prod(1.0, x[aM[i][j]]), cplex.Prod(-1.0, x[aM[i][j + 1]])); // Defines left hand side (aM - aM).
                    contconstraints++;
                }
            }

            // Constraints C6.
            Expr = new INumExpr[nMutGenes + 2];
            for (int i = 0; i < nSamples; i++) // Goes along lines of mutation matrix.
            {
                for (int k = 0; k < nPathways; k++)
                {
                    for (int j = 0; j < nMutGenes; j++) // Goes along columns of mutation matrix.
                    {
                        Expr[j] = cplex.Prod(data.mutMatrix[i][j], x[pM[j][k]]);
                    }

                    Expr[nMutGenes]     = cplex.Prod(1.0, x[fM[i][k]]);
                    Expr[nMutGenes + 1] = cplex.Prod(-1.0, x[aM[i][k]]);

                    // Constraints of the form sum(mutMat*pM) + fM - aM >= 0.
                    constraint[contconstraints]      = cplex.AddRange(0, System.Double.MaxValue); // Defines right hand side (>= 0).
                    constraint[contconstraints].Expr = cplex.Sum(Expr);                           // Defines left hand side (sum(mutMat*pM) + fM - aM).
                    contconstraints++;
                }
            }

            // Constraints C7.
            Expr = new INumExpr[nMutGenes + 1];
            for (int i = 0; i < nPathways; i++)
            {
                for (int j = 0; j < nExpGenes; j++)
                {
                    for (int k = 0; k < nMutGenes; k++)
                    {
                        Expr[k] = cplex.Prod(-data.connectMat[j][k], x[pM[k][i]]);
                    }

                    Expr[nMutGenes] = cplex.Prod(1.0, x[pE[j][i]]);

                    // Constraints of the form pE - sum(connectMat*pM) = 0.
                    constraint[contconstraints]      = cplex.AddRange(0, 0); // Defines right hand side (= 0).
                    constraint[contconstraints].Expr = cplex.Sum(Expr);      // Defines left hand side (pE - sum(connectMat*pM)).
                    contconstraints++;
                }
            }

            // Writes file with MILP model formulation.
            cplex.ExportModel("MILP.lp");

            try
            {
                if (cplex.Solve())
                {
                    // Retrieves optimal values of decision variables.
                    double[] xx = cplex.GetValues(x);

                    // Displays solution info on command window.
                    cplex.Output().WriteLine("Solution status=" + cplex.GetStatus());
                    cplex.Output().WriteLine("Solution value = " + cplex.ObjValue);

                    // Writes output to txt file.
                    StreamWriter objWriter = new StreamWriter("Result.txt");
                    int          cont      = 0;
                    string       sLine     = "";
                    int          nvars     = xx.Length;

                    objWriter.WriteLine("Total cost");
                    objWriter.WriteLine(cplex.ObjValue.ToString());
                    objWriter.WriteLine("");

                    objWriter.WriteLine("Matrix pM");
                    objWriter.WriteLine("");
                    for (int i = 0; i < nMutGenes; i++)
                    {
                        sLine = "";
                        for (int j = 0; j < nPathways; j++)
                        {
                            sLine += xx[cont].ToString() + "\t";
                            cont++;
                        }

                        objWriter.WriteLine(sLine);
                    }

                    // Value of second term of objective function (sum of pE's).
                    double sumPE = 0.0;

                    objWriter.WriteLine("");
                    objWriter.WriteLine("Matrix pE");
                    objWriter.WriteLine("");
                    for (int i = 0; i < nExpGenes; i++)
                    {
                        sLine = "";
                        for (int j = 0; j < nPathways; j++)
                        {
                            sLine += xx[cont].ToString() + "\t";
                            cont++;

                            // Computes running sum of pE's.
                            sumPE = sumPE + xx[cont];
                        }

                        objWriter.WriteLine(sLine);
                    }

                    objWriter.WriteLine("");
                    objWriter.WriteLine("Sum pE");
                    objWriter.WriteLine(sumPE.ToString());
                    objWriter.WriteLine("");

                    objWriter.WriteLine("");
                    objWriter.WriteLine("Matrix aM");
                    objWriter.WriteLine("");
                    for (int i = 0; i < nSamples; i++)
                    {
                        sLine = "";
                        for (int j = 0; j < nPathways; j++)
                        {
                            sLine += xx[cont].ToString() + "\t";
                            cont++;
                        }

                        objWriter.WriteLine(sLine);
                    }

                    objWriter.WriteLine("");
                    objWriter.WriteLine("Matrix fM");
                    objWriter.WriteLine("");
                    for (int i = 0; i < nSamples; i++)
                    {
                        sLine = "";
                        for (int j = 0; j < nPathways; j++)
                        {
                            sLine += xx[cont].ToString() + "\t";
                            cont++;
                        }

                        objWriter.WriteLine(sLine);
                    }

                    objWriter.Close();

                    // Writes optimal solution info to file.
                    cplex.WriteSolution("solution");
                }
                else
                {
                    cplex.GetCplexStatus();
                }
                cplex.End();
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception '" + e + "' caught");
            }
        }
        static void Main(string[] args)
        {
            double BinCap = 0;
            var    dict   = InputReader.ReadDataFile(ref BinCap);

            Cplex cplex = new Cplex();
            Dictionary <string, INumVar> dictvariables   = new Dictionary <string, INumVar>();
            Dictionary <string, IRange>  dictconstraints = new Dictionary <string, IRange>();
            IObjective objective = cplex.AddMinimize();

            foreach (var vari in dict.Keys)
            {
                var cname = "C" + vari;
                dictconstraints.Add(cname, cplex.AddRange(1, Int32.MaxValue, cname));
            }

            Dictionary <int, Set> InitialSets = new Dictionary <int, Set>();;

            InitialSets.Add(1, new Set(new List <int> {
                1, 5
            }));
            InitialSets.Add(2, new Set(new List <int> {
                2, 5
            }));
            InitialSets.Add(3, new Set(new List <int> {
                3, 5
            }));
            InitialSets.Add(4, new Set(new List <int> {
                4, 5
            }));

            //Add intial sets to the model
            foreach (var vari in InitialSets)
            {
                var    setID  = vari.Key.ToString();
                Column VarSet = cplex.Column(objective, 1);
                foreach (var members in vari.Value.member)
                {
                    var cname = "C" + members;
                    VarSet = VarSet.And(cplex.Column(dictconstraints[cname], 1));
                }

                dictvariables.Add(setID, cplex.NumVar(VarSet, 0, 1, NumVarType.Float));
            }
            cplex.Solve();
            var duals    = getDuals(cplex, dictconstraints);
            var solution = getSolution(cplex, dictvariables);

            Console.WriteLine("The objective value is {0}", cplex.GetObjValue());

            int piter     = 0;
            int fixediter = 0;
            Dictionary <string, INumVar> Fixedvar = new Dictionary <string, INumVar>();

            while (true)
            {
                //Formulate Pricing Problem
                Cplex      pcplex     = new Cplex();
                IObjective pobjective = pcplex.AddMaximize();
                piter++;
                //Add Bin Capacity Constraint
                IRange Knapsack = pcplex.AddRange(0, BinCap, "Bin");
                Dictionary <string, INumVar> pdictvar = new Dictionary <string, INumVar>();
                foreach (var vari in dict.Keys)
                {
                    var    varname  = vari.ToString();
                    var    objcoeff = duals["C" + varname];
                    Column item     = pcplex.Column(pobjective, objcoeff);
                    item = item.And(pcplex.Column(Knapsack, dict[vari]));
                    pdictvar.Add(varname, pcplex.NumVar(item, 0, 1, NumVarType.Int));
                }

                pcplex.Solve();
                if (pcplex.GetObjValue() > 1)
                {
                    Console.WriteLine("Pricing Iteration: {0} and obj value is {1} ", piter, pcplex.GetObjValue());
                    var        psolution = getSolution(pcplex, pdictvar);
                    List <int> sol       = new List <int>();
                    foreach (var vari in psolution.Keys)
                    {
                        sol.Add(Convert.ToInt32(vari));
                    }
                    InitialSets.Add(InitialSets.Count + 1, new Set(sol));

                    var    setID   = (InitialSets.Count).ToString();
                    Column VarSet1 = cplex.Column(objective, 1);
                    foreach (var members in sol)
                    {
                        var cname = "C" + members;
                        VarSet1 = VarSet1.And(cplex.Column(dictconstraints[cname], 1));
                    }

                    dictvariables.Add(setID, cplex.NumVar(VarSet1, 0, 1, NumVarType.Float));

                    cplex.Solve();
                    Console.WriteLine("The objective value of cplex after adding column  is {0}", cplex.GetObjValue());
                    duals    = getDuals(cplex, dictconstraints);
                    solution = getSolution(cplex, dictvariables);
                }
                else
                {
                    fixediter++;
                    bool fixedsomething = false;
                    //fix variables above 0.5
                    foreach (var val in solution)
                    {
                        if (val.Value > 0.5 && !Fixedvar.ContainsKey(val.Key))
                        {
                            Fixedvar.Add(val.Key, dictvariables[val.Key]);
                            dictvariables[val.Key].LB = 1;
                            fixedsomething            = true;
                        }
                    }
                    if (!fixedsomething)
                    {
                        break;
                    }
                    cplex.Solve();
                    Console.WriteLine("The Fixing iterations is {0}", cplex.GetObjValue());
                    duals = getDuals(cplex, dictconstraints);
                }
            }

            foreach (var vari in Fixedvar.Values)
            {
                vari.LB = 0;
            }
            IConversion IP = cplex.Conversion(dictvariables.Values.ToArray(), NumVarType.Int);

            cplex.Add(IP);
            cplex.SetParam(Cplex.DoubleParam.TiLim, 600);
            cplex.Solve();

            solution = getSolution(cplex, dictvariables);
            Console.WriteLine("The objective value is {0}", cplex.GetObjValue());
        }