Exemple #1
0
        private void GetPreviewColumnsData(out string[,] returnTable, GAMSVariable variable, int NumberOfRows = int.MaxValue)
        {
            returnTable = new string[Math.Min(variable.NumberRecords, NumberOfRows), variable.Dim + 5 * 2];
            int j;
            int i = 0;

            foreach (GAMSVariableRecord record in variable)
            {
                j = 0;
                foreach (var key in record.Keys)
                {
                    returnTable[i, j++] = key;
                }

                double[] gms_values = { record.Level, record.Marginal, record.Lower, record.Upper, record.Scale };
                foreach (double value in gms_values)
                {
                    returnTable[i, j++] = NumericValueToStr(value, true, false); // Value
                    returnTable[i, j++] = NumericValueToStr(value, false, true); // Special value
                }

                i++;
                if (i >= NumberOfRows)
                {
                    break;
                }
            }
        }
        public static string GetLevelsStr(GAMSVariable v)
        {
            string[] levels = new string[v.NumberRecords];
            int      ctr    = 0;

            foreach (var symRec in v)
            {
                var varRec = (GAMSVariableRecord)symRec;
                levels[ctr++] = varRec.Level.ToString();
            }
            return(String.Join(";", levels));
        }
Exemple #3
0
        private static int GetRepairStart(GAMSVariable z, int i, int k)
        {
            foreach (var symRec in z)
            {
                var keys = symRec.Keys;
                if (keys[0] == $"i{i + 1}" && keys[1] == $"k{k + 1}")
                {
                    return(int.Parse(keys[3].Replace("t", "")));
                }
            }

            return(-1);
        }
Exemple #4
0
        private static bool InternallyProvided(GAMSVariable xint, int i, int k)
        {
            foreach (var symRec in xint)
            {
                var keys = symRec.Keys;
                var vrec = (GAMSVariableRecord)symRec;
                if (SymIx(keys[0]) == i && SymIx(keys[1]) == k && Math.Abs(vrec.Level - 1.0) < 0.001)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #5
0
        private static int WhenProvided(GAMSVariable x, int i, int k)
        {
            foreach (var symRec in x)
            {
                var keys = symRec.Keys;
                var vrec = (GAMSVariableRecord)symRec;
                if (SymIx(keys[0]) == i && SymIx(keys[1]) == k && Math.Abs(vrec.Level - 1.0) < 0.001)
                {
                    return(SymIx(keys[2]));
                }
            }

            return(-1);
        }
Exemple #6
0
        private static List <Order> GetOrders(GAMSVariable w)
        {
            List <Order> orders = new List <Order>();

            foreach (var symRec in w)
            {
                var keys = symRec.Keys;
                var vrec = (GAMSVariableRecord)symRec;
                if (Math.Abs(vrec.Level - 1.0) < 0.001)
                {
                    orders.Add(new Order(SymIx(keys[0]), SymIx(keys[1]), SymIx(keys[2])));
                }
            }

            return(orders);
        }
Exemple #7
0
        void WriteVariable(string sInstanceID, OleDbConnection connect, GAMSDatabase db, string varName, params string[] Domains)
        {
            try
            {
                GAMSVariable var = db.GetVariable(varName);
                if (Domains.Length != var.Dim)
                {
                    lsLog.Add("Number of column names does not match the dimension of the variable.");
                }

                connect.Open();

                // delete table varName if it exists already
                OleDbCommand cmd   = new OleDbCommand("", connect);
                string       query = "delete from Results where InstanceID = '" + sInstanceID + "';";
                cmd.CommandText = query;
                cmd.ExecuteNonQuery();
                List <string> lsQueries = new List <string>();
                foreach (GAMSVariableRecord rec in var)
                {
                    query = "insert into Results(InstanceID,";
                    foreach (string dom in Domains)
                    {
                        query += dom + ", ";
                    }
                    query += "ShipmentValue) values ('" + sInstanceID + "',";
                    foreach (string key in rec.Keys)
                    {
                        query += "'" + key + "', ";
                    }
                    query += rec.Level + ")";
                    lsQueries.Add(query);
                }
                cmd.CommandText = string.Join(";", lsQueries);
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                lsLog.Add("Error: Failed to write variable to the database." + ex.Message);
            }
            finally
            {
                connect.Close();
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace();
            }
            GAMSJob data = ws.AddJobFromString(GetDataText());

            GAMSOptions optData = ws.AddOptions();

            optData.Defines.Add("useBig", "1");
            optData.Defines.Add("nrScen", "100");

            data.Run(optData);

            optData.Dispose();
            GAMSParameter scenarioData = data.OutDB.GetParameter("ScenarioData");

            GAMSOptions opt = ws.AddOptions();

            opt.Defines.Add("datain", data.OutDB.Name);
            int maxiter = 40;

            opt.Defines.Add("maxiter", maxiter.ToString());
            opt.AllModelTypes = "cplexd";

            GAMSCheckpoint cpMaster = ws.AddCheckpoint();
            GAMSCheckpoint cpSub    = ws.AddCheckpoint();

            ws.AddJobFromString(GetMasterText()).Run(opt, cpMaster, data.OutDB);

            GAMSModelInstance masteri  = cpMaster.AddModelInstance();
            GAMSParameter     cutconst = masteri.SyncDB.AddParameter("cutconst", 1, "Benders optimality cut constant");
            GAMSParameter     cutcoeff = masteri.SyncDB.AddParameter("cutcoeff", 2, "Benders optimality coefficients");
            GAMSVariable      theta    = masteri.SyncDB.AddVariable("theta", 0, VarType.Free, "Future profit function variable");
            GAMSParameter     thetaFix = masteri.SyncDB.AddParameter("thetaFix", 0, "");

            masteri.Instantiate("masterproblem max zmaster using lp", opt, new GAMSModifier(cutconst), new GAMSModifier(cutcoeff), new GAMSModifier(theta, UpdateAction.Fixed, thetaFix));

            ws.AddJobFromString(GetSubText()).Run(opt, cpSub, data.OutDB);

            GAMSModelInstance subi     = cpSub.AddModelInstance();
            GAMSParameter     received = subi.SyncDB.AddParameter("received", 1, "units received from master");
            GAMSParameter     demand   = subi.SyncDB.AddParameter("demand", 1, "stochastic demand");

            subi.Instantiate("subproblem max zsub using lp", opt, new GAMSModifier(received), new GAMSModifier(demand));

            opt.Dispose();

            double lowerbound = double.NegativeInfinity, upperbound = double.PositiveInfinity, objmaster = double.PositiveInfinity;
            int    iter = 1;

            do
            {
                Console.WriteLine("Iteration: " + iter);
                // Solve master
                if (1 == iter) // fix theta for first iteration
                {
                    thetaFix.AddRecord().Value = 0;
                }
                else
                {
                    thetaFix.Clear();
                }

                masteri.Solve(GAMSModelInstance.SymbolUpdateType.BaseCase);
                Console.WriteLine(" Master " + masteri.ModelStatus + " : obj=" + masteri.SyncDB.GetVariable("zmaster").FirstRecord().Level);
                if (1 < iter)
                {
                    upperbound = masteri.SyncDB.GetVariable("zmaster").FirstRecord().Level;
                }
                objmaster = masteri.SyncDB.GetVariable("zmaster").FirstRecord().Level - theta.FirstRecord().Level;

                // Set received from master
                received.Clear();
                foreach (GAMSVariableRecord r in masteri.SyncDB.GetVariable("received"))
                {
                    received.AddRecord(r.Keys).Value = r.Level;
                    cutcoeff.AddRecord(iter.ToString(), r.Keys[0]);
                }

                cutconst.AddRecord(iter.ToString());
                double objsub = 0.0;
                foreach (GAMSSetRecord s in data.OutDB.GetSet("s"))
                {
                    demand.Clear();
                    foreach (GAMSSetRecord j in data.OutDB.GetSet("j"))
                    {
                        demand.AddRecord(j.Keys).Value = scenarioData.FindRecord(s.Keys[0], j.Keys[0]).Value;
                    }

                    subi.Solve(GAMSModelInstance.SymbolUpdateType.BaseCase);
                    Console.WriteLine(" Sub " + subi.ModelStatus + " : obj=" + subi.SyncDB.GetVariable("zsub").FirstRecord().Level);


                    double probability = scenarioData.FindRecord(s.Keys[0], "prob").Value;
                    objsub += probability * subi.SyncDB.GetVariable("zsub").FirstRecord().Level;
                    foreach (GAMSSetRecord j in data.OutDB.GetSet("j"))
                    {
                        cutconst.FindRecord(iter.ToString()).Value            += probability * subi.SyncDB.GetEquation("market").FindRecord(j.Keys).Marginal *demand.FindRecord(j.Keys).Value;
                        cutcoeff.FindRecord(iter.ToString(), j.Keys[0]).Value += probability * subi.SyncDB.GetEquation("selling").FindRecord(j.Keys).Marginal;
                    }
                }
                lowerbound = Math.Max(lowerbound, objmaster + objsub);
                iter++;
                if (iter == maxiter + 1)
                {
                    throw new Exception("Benders out of iterations");
                }

                Console.WriteLine(" lowerbound: " + lowerbound + " upperbound: " + upperbound + " objmaster: " + objmaster);
            } while ((upperbound - lowerbound) >= 0.001 * (1 + Math.Abs(upperbound)));

            masteri.Dispose();
            subi.Dispose();
        }
Exemple #9
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace();
            }
            GAMSJob data = ws.AddJobFromString(GetDataText());

            GAMSOptions optData = ws.AddOptions();

            optData.Defines.Add("useBig", "1");
            optData.Defines.Add("nrScen", "100");

            data.Run(optData);

            optData.Dispose();
            GAMSParameter scenarioData = data.OutDB.GetParameter("ScenarioData");

            GAMSOptions opt = ws.AddOptions();

            opt.Defines.Add("datain", data.OutDB.Name);
            int maxiter = 40;

            opt.Defines.Add("maxiter", maxiter.ToString());
            opt.AllModelTypes = "cplexd";

            GAMSCheckpoint cpMaster = ws.AddCheckpoint();
            GAMSCheckpoint cpSub    = ws.AddCheckpoint();

            ws.AddJobFromString(GetMasterText()).Run(opt, cpMaster, data.OutDB);

            GAMSModelInstance masteri  = cpMaster.AddModelInstance();
            GAMSParameter     cutconst = masteri.SyncDB.AddParameter("cutconst", 1, "Benders optimality cut constant");
            GAMSParameter     cutcoeff = masteri.SyncDB.AddParameter("cutcoeff", 2, "Benders optimality coefficients");
            GAMSVariable      theta    = masteri.SyncDB.AddVariable("theta", 0, VarType.Free, "Future profit function variable");
            GAMSParameter     thetaFix = masteri.SyncDB.AddParameter("thetaFix", 0, "");

            masteri.Instantiate("masterproblem max zmaster using lp", opt, new GAMSModifier(cutconst), new GAMSModifier(cutcoeff), new GAMSModifier(theta, UpdateAction.Fixed, thetaFix));

            ws.AddJobFromString(GetSubText()).Run(opt, cpSub, data.OutDB);

            int numThreads = 2;

            GAMSModelInstance[] subi = new GAMSModelInstance[numThreads];
            Queue <Tuple <string, double, Dictionary <string, double> > > demQueue = new Queue <Tuple <string, double, Dictionary <string, double> > >();

            for (int i = 0; i < numThreads; i++)
            {
                subi[i] = cpSub.AddModelInstance();
                GAMSParameter received = subi[i].SyncDB.AddParameter("received", 1, "units received from first stage solution");
                GAMSParameter demand   = subi[i].SyncDB.AddParameter("demand", 1, "stochastic demand");

                subi[i].Instantiate("subproblem max zsub using lp", opt, new GAMSModifier(received), new GAMSModifier(demand));
            }
            opt.Dispose();

            double lowerbound = double.NegativeInfinity, upperbound = double.PositiveInfinity, objmaster = double.PositiveInfinity;
            int    iter = 1;

            do
            {
                Console.WriteLine("Iteration: " + iter);
                // Solve master
                if (1 == iter) // fix theta for first iteration
                {
                    thetaFix.AddRecord().Value = 0;
                }
                else
                {
                    thetaFix.Clear();
                }

                masteri.Solve(GAMSModelInstance.SymbolUpdateType.BaseCase);
                Console.WriteLine(" Master " + masteri.ModelStatus + " : obj=" + masteri.SyncDB.GetVariable("zmaster").FirstRecord().Level);
                if (1 < iter)
                {
                    upperbound = masteri.SyncDB.GetVariable("zmaster").FirstRecord().Level;
                }
                objmaster = masteri.SyncDB.GetVariable("zmaster").FirstRecord().Level - theta.FirstRecord().Level;

                foreach (GAMSSetRecord s in data.OutDB.GetSet("s"))
                {
                    Dictionary <string, double> demDict = new Dictionary <string, double>();
                    foreach (GAMSSetRecord j in data.OutDB.GetSet("j"))
                    {
                        demDict[j.Keys[0]] = scenarioData.FindRecord(s.Keys[0], j.Keys[0]).Value;
                    }
                    demQueue.Enqueue(new Tuple <string, double, Dictionary <string, double> >(s.Keys[0], scenarioData.FindRecord(s.Keys[0], "prob").Value, demDict));
                }

                for (int i = 0; i < numThreads; i++)
                {
                    subi[i].SyncDB.GetParameter("received").Clear();
                }
                foreach (GAMSVariableRecord r in masteri.SyncDB.GetVariable("received"))
                {
                    cutcoeff.AddRecord(iter.ToString(), r.Keys[0]);
                    for (int i = 0; i < numThreads; i++)
                    {
                        subi[i].SyncDB.GetParameter("received").AddRecord(r.Keys).Value = r.Level;
                    }
                }

                cutconst.AddRecord(iter.ToString());
                double objsubsum = 0.0;

                // solve multiple model instances in parallel
                Object   queueMutex = new Object();
                Object   ioMutex    = new Object();
                double[] objsub     = new double[numThreads];
                Dictionary <string, double>[] coef = new Dictionary <string, double> [numThreads];
                double[] cons = new double[numThreads];

                for (int i = 0; i < numThreads; i++)
                {
                    coef[i] = new Dictionary <string, double>();
                    foreach (GAMSSetRecord j in data.OutDB.GetSet("j"))
                    {
                        coef[i].Add(j.Keys[0], 0.0);
                    }
                }

                Parallel.For(0, numThreads, delegate(int i) { ScenSolve(subi[i], ref cons[i], ref coef[i], demQueue, ref objsub[i], queueMutex, ioMutex); });

                for (int i = 0; i < numThreads; i++)
                {
                    objsubsum += objsub[i];
                    cutconst.FindRecord(iter.ToString()).Value += cons[i];
                    foreach (GAMSSetRecord j in data.OutDB.GetSet("j"))
                    {
                        cutcoeff.FindRecord(iter.ToString(), j.Keys[0]).Value += coef[i][j.Keys[0]];
                    }
                }
                lowerbound = Math.Max(lowerbound, objmaster + objsubsum);

                iter++;
                if (iter == maxiter + 1)
                {
                    throw new Exception("Benders out of iterations");
                }

                Console.WriteLine(" lowerbound: " + lowerbound + " upperbound: " + upperbound + " objmaster: " + objmaster);
            } while ((upperbound - lowerbound) >= 0.001 * (1 + Math.Abs(upperbound)));

            masteri.Dispose();
            foreach (GAMSModelInstance inst in subi)
            {
                inst.Dispose();
            }
        }
Exemple #10
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace();
            }
            GAMSCheckpoint cp = ws.AddCheckpoint();

            // initialize a GAMSCheckpoint by running a GAMSJob
            GAMSJob t7 = ws.AddJobFromString(GetModelText());

            t7.Run(cp);

            // create a GAMSModelInstance and solve it multiple times with different scalar bmult
            GAMSModelInstance mi = cp.AddModelInstance();

            GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", 0, "demand multiplier");
            GAMSOptions   opt   = ws.AddOptions();

            opt.AllModelTypes = "gurobi";

            // instantiate the GAMSModelInstance and pass a model definition and GAMSModifier to declare bmult mutable
            mi.Instantiate("transport us lp min z", opt, new GAMSModifier(bmult));

            bmult.AddRecord().Value = 1.0;
            double[] bmultlist      = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };

            foreach (double b in bmultlist)
            {
                bmult.FirstRecord().Value = b;
                mi.Solve();
                Console.WriteLine("Scenario bmult=" + b + ":");
                Console.WriteLine("  Modelstatus: " + mi.ModelStatus);
                Console.WriteLine("  Solvestatus: " + mi.SolveStatus);
                Console.WriteLine("  Obj: " + mi.SyncDB.GetVariable("z").FindRecord().Level);
            }

            // create a GAMSModelInstance and solve it with single links in the network blocked
            mi = cp.AddModelInstance();

            GAMSVariable  x   = mi.SyncDB.AddVariable("x", 2, VarType.Positive, "");
            GAMSParameter xup = mi.SyncDB.AddParameter("xup", 2, "upper bound on x");

            // instantiate the GAMSModelInstance and pass a model definition and GAMSModifier to declare upper bound of X mutable
            mi.Instantiate("transport us lp min z", modifiers: new GAMSModifier(x, UpdateAction.Upper, xup));

            foreach (GAMSSetRecord i in t7.OutDB.GetSet("i"))
            {
                foreach (GAMSSetRecord j in t7.OutDB.GetSet("j"))
                {
                    xup.Clear();
                    xup.AddRecord(i.Keys[0], j.Keys[0]).Value = 0;
                    mi.Solve();
                    Console.WriteLine("Scenario link blocked: " + i.Keys[0] + " - " + j.Keys[0]);
                    Console.WriteLine("  Modelstatus: " + mi.ModelStatus);
                    Console.WriteLine("  Solvestatus: " + mi.SolveStatus);
                    Console.WriteLine("  Obj: " + mi.SyncDB.GetVariable("z").FindRecord().Level);
                }
            }
        }