Beispiel #1
0
        static GAMSDatabase ReadFromAccess(GAMSWorkspace ws)
        {
            GAMSDatabase db = ws.AddDatabase();

            // connect to database
            string strAccessConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\..\..\..\Data\transport.accdb";
            OleDbConnection connection = null;
            try
            {
                connection = new OleDbConnection(strAccessConn);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message);
                Environment.Exit(1);
            }

            // read GAMS sets
            ReadSet(connection, db, "SELECT Plant FROM Plant", "i", 1, "canning plants");
            ReadSet(connection, db, "SELECT Market FROM Market", "j", 1, "markets");

            // read GAMS parameters
            ReadParameter(connection, db, "SELECT Plant,Capacity FROM Plant", "a", 1, "capacity of plant i in cases");
            ReadParameter(connection, db, "SELECT Market,Demand FROM Market", "b", 1, "demand at market j in cases");
            ReadParameter(connection, db, "SELECT Plant,Market,Distance FROM Distance", "d", 2, "distance in thousands of miles");

            return db;
        }
Beispiel #2
0
        public void ProcessTask(TaskManager.TaskDetails oTask, out List <string> lsLogs, out string sOutput, out string sStatus)
        {
            // cast input values
            TransportReference oReference = new TransportReference();

            oReference = (TransportReference)oDF.XmlStringToObject(oTask.ReferenceValues, oReference);

            TransportOutput oOutput = new TransportOutput();
            // call processing algorithm
            GAMSWorkspace ws = new GAMSWorkspace();
            // fill GAMSDatabase by reading from Access
            GAMSDatabase db = ReadFromDatabase(ws, oReference.Identifier);

            // run job
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t9 = ws.AddJobFromString(GetModelText());
                opt.Defines.Add("gdxincname", db.Name);
                opt.AllModelTypes = "xpress";
                t9.Run(opt, db);
                foreach (GAMSVariableRecord rec in t9.OutDB.GetVariable("z"))
                {
                    oOutput.TransportCost = rec.Level;
                }
                // write results into Access file
                WriteToDatabase(ws, t9.OutDB, oReference.Identifier);
            }

            // submit results
            sOutput = oDF.ObjectToXmlString(oOutput);
            sStatus = "completed";
            lsLogs  = lsLog;
        }
Beispiel #3
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
            ws.AddJobFromString(GetModelText()).Run(cp);

            Queue <double> bmultQueue = new Queue <double>(new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 });

            // solve multiple model instances in parallel
            Object queueMutex = new Object();
            Object ioMutex    = new Object();

            Parallel.For(0, 2, delegate(int i) { ScenSolve(ws, cp, bmultQueue, queueMutex, ioMutex); });
        }
Beispiel #4
0
        static GAMSDatabase ReadFromAccess(GAMSWorkspace ws)
        {
            GAMSDatabase db = ws.AddDatabase();

            // connect to database
            string          strAccessConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\..\..\..\Data\transport.accdb";
            OleDbConnection connection    = null;

            try
            {
                connection = new OleDbConnection(strAccessConn);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message);
                Environment.Exit(1);
            }

            // read GAMS sets
            ReadSet(connection, db, "SELECT Plant FROM Plant", "i", 1, "canning plants");
            ReadSet(connection, db, "SELECT Market FROM Market", "j", 1, "markets");

            // read GAMS parameters
            ReadParameter(connection, db, "SELECT Plant,Capacity FROM Plant", "a", 1, "capacity of plant i in cases");
            ReadParameter(connection, db, "SELECT Market,Demand FROM Market", "b", 1, "demand at market j in cases");
            ReadParameter(connection, db, "SELECT Plant,Market,Distance FROM Distance", "d", 2, "distance in thousands of miles");

            return(db);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace();
            }
            // fill GAMSDatabase by reading from Access
            GAMSDatabase db = ReadFromAccess(ws);

            // run job
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t9 = ws.AddJobFromString(GetModelText());
                opt.Defines.Add("gdxincname", db.Name);
                opt.AllModelTypes = "xpress";
                t9.Run(opt, db);
                foreach (GAMSVariableRecord rec in t9.OutDB.GetVariable("x"))
                {
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
                }
            }
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace();
            }
            // write an include file containing data with GAMS syntax
            using (StreamWriter writer = new StreamWriter(ws.WorkingDirectory + Path.DirectorySeparatorChar + "tdata.gms"))
            {
                writer.Write(GetDataText());
            }
            // run a job using an instance of GAMSOptions that defines the data include file
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t2 = ws.AddJobFromString(GetModelText());
                opt.Defines.Add("incname", "tdata");
                t2.Run(opt);
                foreach (GAMSVariableRecord rec in t2.OutDB.GetVariable("x"))
                {
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
                }
            }
        }
Beispiel #7
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
            ws.AddJobFromString(GetModelText()).Run(cp);

            double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };

            // create a new GAMSJob that is initialized from the GAMSCheckpoint
            foreach (double b in bmultlist)
            {
                GAMSJob t5 = ws.AddJobFromString("bmult=" + b + "; solve transport min z us lp; ms=transport.modelstat; ss=transport.solvestat;", cp);
                t5.Run();
                Console.WriteLine("Scenario bmult=" + b + ":");
                Console.WriteLine("  Modelstatus: " + t5.OutDB.GetParameter("ms").FindRecord().Value);
                Console.WriteLine("  Solvestatus: " + t5.OutDB.GetParameter("ss").FindRecord().Value);
                Console.WriteLine("  Obj: " + t5.OutDB.GetVariable("z").FindRecord().Level);
            }
        }
Beispiel #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();
            }
            GAMSCheckpoint cp = ws.AddCheckpoint();

            // initialize a GAMSCheckpoint by running a GAMSJob
            ws.AddJobFromString(GetModelText()).Run(cp);

            double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };

            // create a new GAMSJob that is initialized from the GAMSCheckpoint
            foreach (double b in bmultlist)
            {
                GAMSJob t5 = ws.AddJobFromString("bmult=" + b + "; solve transport min z us lp; ms=transport.modelstat; ss=transport.solvestat;", cp);
                t5.Run();
                Console.WriteLine("Scenario bmult=" + b + ":");
                Console.WriteLine("  Modelstatus: " + t5.OutDB.GetParameter("ms").FindRecord().Value);
                Console.WriteLine("  Solvestatus: " + t5.OutDB.GetParameter("ss").FindRecord().Value);
                Console.WriteLine("  Obj: " + t5.OutDB.GetVariable("z").FindRecord().Level);
            }
        }
Beispiel #9
0
        GAMSDatabase ReadFromDatabase(GAMSWorkspace ws, string sInstanceID)
        {
            GAMSDatabase db = ws.AddDatabase();

            // connect to database
            OleDbConnection connection = null;

            try
            {
                connection = new OleDbConnection(strAccessConn);
            }
            catch (Exception ex)
            {
                lsLog.Add("Error: Failed to create a database connection. " + ex.Message);
            }
            string sSuffix = " where InstanceID='" + sInstanceID + "';";

            // read GAMS sets
            ReadSet(connection, db, "SELECT Plant FROM Plant" + sSuffix, "i", 1, "canning plants");
            ReadSet(connection, db, "SELECT Market FROM Market" + sSuffix, "j", 1, "markets");

            // read GAMS parameters
            ReadParameter(connection, db, "SELECT Plant,Capacity FROM Plant" + sSuffix, "a", 1, "capacity of plant i in cases");
            ReadParameter(connection, db, "SELECT Market,Demand FROM Market" + sSuffix, "b", 1, "demand at market j in cases");
            ReadParameter(connection, db, "SELECT Plant,Market,Distance FROM Distance" + sSuffix, "d", 2, "distance in thousands of miles");

            return(db);
        }
Beispiel #10
0
        private static void SolveWarehouse(GAMSWorkspace gmsWS, int NumberOfWarehouses, GAMSDatabase result, Object dbMutex)
        {
            // instantiate GAMSOptions and define some scalars
            GAMSOptions gmsOpt = gmsWS.AddOptions();

            gmsOpt.AllModelTypes = "Gurobi";
            gmsOpt.Defines.Add("Warehouse", NumberOfWarehouses.ToString());
            gmsOpt.Defines.Add("Store", "65");
            gmsOpt.Defines.Add("fixed", "22");
            gmsOpt.Defines.Add("disaggregate", "0");
            gmsOpt.OptCR = 0.0; // Solve to optimality

            // create a GAMSJob from string and write results to the result database
            GAMSJob gmsJ = gmsWS.AddJobFromString(GetModelText());

            gmsJ.Run(gmsOpt);

            // need to lock database write operations
            lock (dbMutex)
                result.GetParameter("objrep").AddRecord(NumberOfWarehouses.ToString()).Value = gmsJ.OutDB.GetVariable("obj").FindRecord().Level;

            foreach (GAMSVariableRecord supplyRec in gmsJ.OutDB.GetVariable("supply"))
            {
                if (supplyRec.Level > 0.5)
                {
                    lock (dbMutex)
                        result.GetSet("supplyMap").AddRecord(NumberOfWarehouses.ToString(), supplyRec.Keys[0], supplyRec.Keys[1]);
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// Runs the specified list data.
        /// </summary>
        /// <param name="listData">The list data.</param>
        /// <returns>List&lt;System.String&gt;[].</returns>
        public List <string>[] Run(List <string>[] listData)
        {
            int sheetNumber = 4;

            string[] setsTemplate = new string[2] {
                "i", "j"
            };
            string[] setsName = new string[2] {
                "所有维修员元素点", "所有任务元素点"
            };
            string[] parametersTemplate = new string[4] {
                "PL", "TL", "Tij", "Tjj"
            };
            string[] parametersName = new string[4] {
                "PLi", "TLj", "Tij", "Tjj"
            };

            GAMSWorkspace ws;

            //if (Environment.GetCommandLineArgs().Length > 1)
            //    ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            //else
            ws = new GAMSWorkspace(workspacePath, null, DebugLevel.Off);
            GAMSDatabase db = ws.AddDatabase();

            GAMSSet[]       gSet = new GAMSSet[sheetNumber];
            GAMSParameter[] gPar = new GAMSParameter[sheetNumber];

            for (int i = 0; i < 2; i++) //前两个表设置
            {
                gSet[i] = db.AddSet(setsTemplate[i], 1, setsName[i]);
                gPar[i] = db.AddParameter(parametersTemplate[i], 1, parametersName[i]);
                for (int j = 0; j < listData[2 * i].Count; j++)
                {
                    gSet[i].AddRecord(listData[2 * i][j]);
                    gPar[i].AddRecord(listData[2 * i][j]).Value = Convert.ToDouble(listData[2 * i + 1][j]);
                }
            }
            for (int i = 2; i < 4; i++)
            {
                gPar[i] = db.AddParameter(parametersTemplate[i], 2, parametersName[i]);
                for (int j = 0; j < listData[3 * i - 2].Count; j++)
                {
                    gPar[i].AddRecord(listData[3 * i - 2][j], listData[3 * i - 1][j]).Value = Convert.ToDouble(listData[3 * i][j]);
                }
            }

            GAMSJob t = ws.AddJobFromString(GetModelText());

            using (GAMSOptions opt = ws.AddOptions())
            {
                opt.Defines.Add("gdxincname", db.Name);
                opt.AllModelTypes = "xpress";
                t.Run(opt, db);
            }
            List <string>[] resultData = GetResultData(t);

            return(resultData);
        }
Beispiel #12
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);
                }
        }
Beispiel #13
0
 public static void PrintAllResultsInPath(GAMSWorkspace ws, string path)
 {
     string[] resultFilenames = GetAllResulFilesForPath(path);
     foreach (var resultFilename in resultFilenames)
     {
         bool         enforcedOrigin = int.Parse(resultFilename.Substring(resultFilename.Length - 5, 1)) == 1;
         GAMSDatabase db             = ws.AddDatabaseFromGDX(resultFilename);
         int          instanceIx     = int.Parse(resultFilename.Replace("output_instance_", "")
                                                 .Replace($"_herkunft_{(enforcedOrigin ? "1" : "0")}.gdx", "")) - 1;
         PrintResults(db, instanceIx, enforcedOrigin);
     }
 }
Beispiel #14
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace();
            }
            ws.GamsLib("trnsport");

            // create a GAMSJob from file and run it with default settings
            GAMSJob t1 = ws.AddJobFromFile("trnsport.gms");

            t1.Run();
            Console.WriteLine("Ran with Default:");
            foreach (GAMSVariableRecord rec in t1.OutDB.GetVariable("x"))
            {
                Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
            }

            // run the job again with another solver
            using (GAMSOptions opt = ws.AddOptions())
            {
                opt.AllModelTypes = "xpress";
                t1.Run(opt);
            }
            Console.WriteLine("Ran with XPRESS:");
            foreach (GAMSVariableRecord rec in t1.OutDB.GetVariable("x"))
            {
                Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
            }

            // run the job with a solver option file
            using (StreamWriter optFile = new StreamWriter(Path.Combine(ws.WorkingDirectory, "xpress.opt")))
                using (GAMSOptions opt = ws.AddOptions())
                {
                    optFile.WriteLine("algorithm=barrier");
                    optFile.Close();
                    opt.AllModelTypes = "xpress";
                    opt.OptFile       = 1;
                    t1.Run(opt);
                }
            Console.WriteLine("Ran with XPRESS with non-default option:");
            foreach (GAMSVariableRecord rec in t1.OutDB.GetVariable("x"))
            {
                Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
            }
        }
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            var sysDir = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Config.WinGamsPath : Config.OsxGamsPath;
            var ws     = new GAMSWorkspace(Directory.GetCurrentDirectory(), sysDir);

            Generator.BatchGenerateInstances(ws, 10);

            //Solver.BatchSolveInstances(ws, 2);
            //Solver.PrintAllResultsInPath(ws, Directory.GetCurrentDirectory());

            Console.WriteLine("Press a key to quit...");
            Console.ReadKey();
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws = new GAMSWorkspace();

            // Use a MIP that needs some time to solve
            ws.GamsLib("lop");
            GAMSJob job = ws.AddJobFromFile("lop.gms");

            // Change the default behaviour of pressing Ctrl+C to send that signal to a running job
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs a) { job.Interrupt(); a.Cancel = true; };

            // Run the job, Pressing Ctrl+C will interrupt the GAMS job, but not this whole application
            job.Run(output: Console.Out);
        }
Beispiel #17
0
        static void RunScenario(GAMSWorkspace ws, GAMSCheckpoint cp, object ioMutex, double b)
        {
            GAMSJob t6 = ws.AddJobFromString("bmult=" + b + "; solve transport min z us lp; ms=transport.modelstat; ss=transport.solvestat;", cp);

            t6.Run();
            // we need to make the ouput a critical section to avoid messed up report information
            lock (ioMutex)
            {
                Console.WriteLine("Scenario bmult=" + b + ":");
                Console.WriteLine("  Modelstatus: " + t6.OutDB.GetParameter("ms").FindRecord().Value);
                Console.WriteLine("  Solvestatus: " + t6.OutDB.GetParameter("ss").FindRecord().Value);
                Console.WriteLine("  Obj: " + t6.OutDB.GetVariable("z").FindRecord().Level);
            }
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws = new GAMSWorkspace();

            // Use a MIP that needs some time to solve
            ws.GamsLib("lop");
            GAMSJob job = ws.AddJobFromFile("lop.gms");

            // Change the default behaviour of pressing Ctrl+C to send that signal to a running job
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs a) { job.Interrupt(); a.Cancel = true; };

            // Run the job, Pressing Ctrl+C will interrupt the GAMS job, but not this whole application
            job.Run(output: Console.Out);
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;

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

            // data from a string with GAMS syntax with explicit export to GDX file
            GAMSJob t3 = ws.AddJobFromString(GetDataText());

            t3.Run();
            t3.OutDB.Export(ws.WorkingDirectory + Path.DirectorySeparatorChar + "tdata.gdx");

            // run a job using an instance of GAMSOptions that defines the data include file
            t3 = ws.AddJobFromString(GetModelText());
            using (GAMSOptions opt = ws.AddOptions())
            {
                opt.Defines.Add("gdxincname", "tdata");
                opt.AllModelTypes = "xpress";
                t3.Run(opt);
                foreach (GAMSVariableRecord rec in t3.OutDB.GetVariable("x"))
                {
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
                }
            }

            // same but with implicit database communication
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t3a = ws.AddJobFromString(GetDataText());
                GAMSJob t3b = ws.AddJobFromString(GetModelText());
                t3a.Run();
                opt.Defines.Add("gdxincname", t3a.OutDB.Name);
                opt.AllModelTypes = "xpress";
                t3b.Run(opt, t3a.OutDB);
                foreach (GAMSVariableRecord rec in t3b.OutDB.GetVariable("x"))
                {
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
                }
            }
        }
Beispiel #20
0
        static void CreateSaveRestart(string cpFileName)
        {
            GAMSWorkspace ws;
            if (Environment.GetCommandLineArgs().Length > 1)
                ws = new GAMSWorkspace(workingDirectory: Path.GetDirectoryName(cpFileName), systemDirectory: Environment.GetCommandLineArgs()[1]);
            else
                ws = new GAMSWorkspace(workingDirectory: Path.GetDirectoryName(cpFileName));
            GAMSJob j1 = ws.AddJobFromString(GetBaseModelText());
            GAMSOptions opt = ws.AddOptions();

            opt.Action = GAMSOptions.EAction.CompileOnly;

            GAMSCheckpoint cp = ws.AddCheckpoint(Path.GetFileName(cpFileName));
            j1.Run(opt, cp);

            opt.Dispose();
        }
Beispiel #21
0
        private void executeGamsJob(string modelo, string directorio)
        {
            List <string> variablesEval = new List <string>();

            if (rbEscenario1.Checked)
            {
                variablesEval = getVariableEval(1);
            }
            else if (rbEscenario2.Checked)
            {
                variablesEval = getVariableEval(2);
            }
            else
            {
                variablesEval = getVariableEval(3);
            }

            GAMSWorkspace ws;

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

            using (GAMSOptions opt = ws.AddOptions())
            {
                opt.AllModelTypes = "LINDOGLOBAL";
                opt.IterLim       = 900000000;
                GAMSJob j1 = ws.AddJobFromString(modelo);
                j1.Run(opt);

                foreach (string variable in variablesEval)
                {
                    foreach (GAMSVariableRecord rec in j1.OutDB.GetVariable(variable))
                    {
                        listResultsConsole.Add("variable " + variable + "=" + rec.Variable.LastRecord().Level.ToString());
                        ListResultsVariable.Add(new Variable(variable, rec.Variable.LastRecord().Level));
                    }
                }
                listResultsConsole.Add("Hora finalizacion: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        }
Beispiel #22
0
        void WriteToDatabase(GAMSWorkspace ws, GAMSDatabase db, string sInstanceID)
        {
            // connect to database
            OleDbConnection connection = null;

            try
            {
                connection = new OleDbConnection(strAccessConn);
            }
            catch (Exception ex)
            {
                lsLog.Add("Error: Failed to create a database connection. " + ex.Message);
            }

            // write levels of variable x
            WriteVariable(sInstanceID, connection, db, "x", "Plant", "Market");
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            GAMSWorkspace gmsWS;

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

            // create a GAMSDatabase for the results
            GAMSDatabase resultDB = gmsWS.AddDatabase();

            resultDB.AddParameter("objrep", 1, "Objective value");
            resultDB.AddSet("supplyMap", 3, "Supply connection with level");

            int status = 1;

            try
            {
                // run multiple parallel jobs
                Object dbLock = new Object();
                System.Threading.Tasks.Parallel.For(10, 22, delegate(int i) { SolveWarehouse(gmsWS, i, resultDB, dbLock); });
                // export the result database to a GDX file
                resultDB.Export("\\tmp\\result.gdx");
                status = 0;
            }
            catch (GAMSException ex)
            {
                Console.WriteLine("GAMSException occured: " + ex.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                resultDB.Dispose();
            }

            Environment.ExitCode = status;
        }
Beispiel #24
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
            ws.AddJobFromString(GetModelText()).Run(cp);

            double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };

            // run multiple parallel jobs using the created GAMSCheckpoint
            Object ioMutex = new Object();
            System.Threading.Tasks.Parallel.ForEach(bmultlist, delegate(double b) { RunScenario(ws, cp, ioMutex, b); });
        }
Beispiel #25
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
            ws.AddJobFromString(GetModelText()).Run(cp);

            Queue<double> bmultQueue = new Queue<double>(new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 });

            // solve multiple model instances in parallel
            Object queueMutex = new Object();
            Object ioMutex = new Object();
            Parallel.For(0, 2, delegate(int i) { ScenSolve(ws, cp, bmultQueue, queueMutex, ioMutex); });
        }
Beispiel #26
0
        /*public static void SolveWithFixedOrderRepairs(GAMSWorkspace ws, List<Order> orders, List<Repair> repairs, int instanceIx)
         * {
         *  using (var options = ws.AddOptions())
         *  {
         *      GAMSCheckpoint cp = ws.AddCheckpoint();
         *      var job = ws.AddJobFromFile($"{Config.ModelDirectoryPath}/{Config.ModelFileName}", jobName: $"JobFuerInstanz{instanceIx + 1}");
         *      job.Run(cp);
         *      var mi = cp.AddModelInstance();
         *      //mi.Instantiate();
         *  }
         *
         * }*/

        public static void BatchSolveInstances(GAMSWorkspace ws, int numInstances)
        {
            using (var options = ws.AddOptions())
            {
                for (var i = 0; i < numInstances; i++)
                {
                    var job = ws.AddJobFromFile($"{Config.ModelDirectoryPath}/{Config.ModelFileName}", jobName: $"JobFuerInstanz{i + 1}");
                    options.Defines["num"] = (i + 1).ToString();

                    options.Defines["herkunft"] = "0";
                    job.Run(options);
                    PrintResults(job.OutDB, i + 1, false);

                    options.Defines["herkunft"] = "1";
                    job.Run(options);
                    PrintResults(job.OutDB, i + 1, true);
                }
            }
        }
Beispiel #27
0
        private void RunGams()
        {
            MethodInvoker action = delegate
            {
                bu_run.Enabled    = false;
                bu_close.Enabled  = false;
                bu_cancel.Enabled = true;
            };

            this.BeginInvoke(action);

            TextBoxBaseWriter tbw = new TextBoxBaseWriter(this.richTextBox1, this);

            GAMSWorkspace ws = new GAMSWorkspace();

            ws.GamsLib("lop");
            currentJob = ws.AddJobFromFile("lop.gms");
            GAMSOptions opt = ws.AddOptions();

            opt.AllModelTypes = "bdmlp";
            opt.SolveLink     = GAMSOptions.ESolveLink.CallModule;

            try
            {
                currentJob.Run(opt, tbw);
            }
            catch (GAMSException e)
            {
                action = delegate
                {
                    richTextBox1.AppendText(e.Message);
                };
            }

            action = delegate
            {
                bu_run.Enabled    = true;
                bu_close.Enabled  = true;
                bu_cancel.Enabled = false;
            };
            this.BeginInvoke(action);
        }
        public static void BatchGenerateInstances(GAMSWorkspace ws, int numInstances)
        {
            for (var i = 0; i < numInstances; i++)
            {
                using (var db = GenerateInstance(ws, new SetSizes
                {
                    ngoods = 4,
                    ncomponents = 3,
                    ndamagepatterns = 3,
                    nperiods = 1000
                }, i + 1))
                {
                    Console.WriteLine($"Writing instance {i + 1}...");
                    db.Export($"instance{i + 1}.gdx");
                }

                Console.WriteLine($"Copying instance {i + 1} to GAMS model directory..");
                File.Copy($"instance{i + 1}.gdx", $"{Config.ModelDirectoryPath}/instance{i + 1}.gdx", true);
            }
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;
            if (Environment.GetCommandLineArgs().Length > 1)
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            else
                ws = new GAMSWorkspace();
            ws.GamsLib("trnsport");

            // create a GAMSJob from file and run it with default settings
            GAMSJob t1 = ws.AddJobFromFile("trnsport.gms");

            t1.Run();
            Console.WriteLine("Ran with Default:");
            foreach (GAMSVariableRecord rec in t1.OutDB.GetVariable("x"))
                Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);

            // run the job again with another solver
            using (GAMSOptions opt = ws.AddOptions())
            {
                opt.AllModelTypes = "xpress";
                t1.Run(opt);
            }
            Console.WriteLine("Ran with XPRESS:");
            foreach (GAMSVariableRecord rec in t1.OutDB.GetVariable("x"))
                Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);

            // run the job with a solver option file
            using (StreamWriter optFile = new StreamWriter(Path.Combine(ws.WorkingDirectory, "xpress.opt")))
            using (GAMSOptions opt = ws.AddOptions())
            {
                optFile.WriteLine("algorithm=barrier");
                optFile.Close();
                opt.AllModelTypes = "xpress";
                opt.OptFile = 1;
                t1.Run(opt);
            }
            Console.WriteLine("Ran with XPRESS with non-default option:");
            foreach (GAMSVariableRecord rec in t1.OutDB.GetVariable("x"))
                Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
        }
Beispiel #30
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;
            if (Environment.GetCommandLineArgs().Length > 1)
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            else
                ws = new GAMSWorkspace();
            // fill GAMSDatabase by reading from Access
            GAMSDatabase db = ReadFromAccess(ws);

            // run job
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t9 = ws.AddJobFromString(GetModelText());
                opt.Defines.Add("gdxincname", db.Name);
                opt.AllModelTypes = "xpress";
                t9.Run(opt, db);
                foreach (GAMSVariableRecord rec in t9.OutDB.GetVariable("x"))
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
            }
        }
Beispiel #31
0
        private void RunGams()
        {
            MethodInvoker action = delegate
            {
                bu_run.Enabled = false;
                bu_close.Enabled = false;
                bu_cancel.Enabled = true;
            };
            this.BeginInvoke(action);

            TextBoxBaseWriter tbw = new TextBoxBaseWriter(this.richTextBox1, this);

            GAMSWorkspace ws = new GAMSWorkspace();
            ws.GamsLib("lop");
            currentJob = ws.AddJobFromFile("lop.gms");
            GAMSOptions opt = ws.AddOptions();
            opt.AllModelTypes = "bdmlp";
            opt.SolveLink = GAMSOptions.ESolveLink.CallModule;

            try
            {
                currentJob.Run(opt, tbw);
            }
            catch (GAMSException e)
            {
                action = delegate
                {
                    richTextBox1.AppendText(e.Message);
                };
            }

            action = delegate
            {
                bu_run.Enabled = true;
                bu_close.Enabled = true;
                bu_cancel.Enabled = false;
            };
            this.BeginInvoke(action);
        }
Beispiel #32
0
        static void Main(string[] args)
        {
            GAMSWorkspace gmsWS;
            if (Environment.GetCommandLineArgs().Length > 1)
                gmsWS = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            else
                gmsWS = new GAMSWorkspace();

            // create a GAMSDatabase for the results
            GAMSDatabase resultDB = gmsWS.AddDatabase();
            resultDB.AddParameter("objrep",1,"Objective value");
            resultDB.AddSet("supplyMap",3,"Supply connection with level");

            int status = 1;
            try
            {
                // run multiple parallel jobs
                Object dbLock = new Object();
                System.Threading.Tasks.Parallel.For(10, 22, delegate(int i) { SolveWarehouse(gmsWS, i, resultDB, dbLock); });
                // export the result database to a GDX file
                resultDB.Export("\\tmp\\result.gdx");
                status = 0;
            }
            catch (GAMSException ex)
            {
                Console.WriteLine("GAMSException occured: " + ex.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                resultDB.Dispose();
            }

            Environment.ExitCode = status;
        }
Beispiel #33
0
        private static void ScenSolve(GAMSWorkspace ws, GAMSCheckpoint cp, Queue <double> bmultQueue, Object queueMutex, Object ioMutex)
        {
            GAMSModelInstance mi = cp.AddModelInstance();

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

            opt.AllModelTypes = "cplexd";
            // 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;

            while (true)
            {
                double b;
                // dynamically get a bmult value from the queue instead of passing it to the different threads at creation time
                lock (queueMutex)
                {
                    if (0 == bmultQueue.Count)
                    {
                        return;
                    }
                    b = bmultQueue.Dequeue();
                }
                bmult.FirstRecord().Value = b;
                mi.Solve();
                // we need to make the ouput a critical section to avoid messed up report informations
                lock (ioMutex)
                {
                    Console.WriteLine("Scenario bmult=" + b + ":");
                    Console.WriteLine("  Modelstatus: " + mi.ModelStatus);
                    Console.WriteLine("  Solvestatus: " + mi.SolveStatus);
                    Console.WriteLine("  Obj: " + mi.SyncDB.GetVariable("z").FindRecord().Level);
                }
            }
        }
        public static GAMSDatabase GenerateInstance(GAMSWorkspace ws, SetSizes sizes, int seed)
        {
            Utils.SetSeed(seed);
            var db              = ws.AddDatabase();
            var setNames        = new[] { "i", "k", "s", "t" };
            var setDescriptions = new[] { "Gueter", "Komponenten", "Schadensbilder", "Perioden" };

            GDXUtils.Sets1D(db, setNames, sizes.ToArray(), setDescriptions);

            var ekt    = Utils.RandomValuesMatrixRowAscendingDiscrete(sizes.ngoods, sizes.ncomponents, 1, 3);
            var eks    = Utils.RandomValuesMatrixDiscrete(sizes.ngoods, sizes.ncomponents, 2, 3);
            var ekreal = Utils.RandomValuesMatrixDiscrete(sizes.ngoods, sizes.ncomponents, 2, 3);

            GDXUtils.Parameter2D(db, "ekt", "i", "k", ekt);
            GDXUtils.Parameter2D(db, "eks", "i", "k", eks);
            GDXUtils.Parameter2D(db, "ekreal", "i", "k", ekreal);

            GDXUtils.Parameter1D(db, "due", "i", Utils.RandomValuesDiscrete(sizes.ngoods, 0, 20), "Liefertermin/Frist");
            GDXUtils.Parameter1D(db, "c", "i", Utils.RandomValues(sizes.ngoods, 0, 150), "Verspaetungskostensatz pro ZE");
            GDXUtils.Parameter1D(db, "rd", "k", Utils.RandomValuesDiscrete(sizes.ncomponents, 1, 4), "Remontagedauer in ZE");
            GDXUtils.Parameter1D(db, "rc", "k", Utils.RandomValuesDiscrete(sizes.ncomponents, 1, 2), "Reparaturkapazitaet in ME");
            GDXUtils.Parameter1D(db, "rmc", "k", Utils.RandomValuesDiscrete(sizes.ncomponents, 4, 6), "Remontagekapazitaet in ME");
            var housingCosts = new double[sizes.ncomponents, sizes.ndamagepatterns];

            for (var k = 0; k < housingCosts.GetUpperBound(0); k++)
            {
                Utils.AssignRow(housingCosts, k, Utils.RandomValuesDescending(sizes.ndamagepatterns, 0.0001, 2.0));
            }
            GDXUtils.Parameter2D(db, "hc", "k", "s", housingCosts, "Lagerkostensatz pro ZE und ME in Zustand");
            GDXUtils.Parameter2D(db, "d", "k", "s", Utils.RandomValuesMatrixRowAscendingDiscrete(sizes.ncomponents, sizes.ndamagepatterns, 0, 62), "Reparaturdauern in ZE");
            GDXUtils.Parameter2D(db, "bd", "k", "s", Utils.RandomValuesMatrixRowAscendingDiscrete(sizes.ncomponents, sizes.ndamagepatterns, 1, 4), "Bestelldauer in ZE");
            GDXUtils.Parameter2D(db, "bc", "k", "s", Utils.RandomValuesMatrixRowAscending(sizes.ncomponents, sizes.ndamagepatterns, 0.5, 16.0), "Bestellkostensatz pro ME in Zustand");

            Console.Write($"Generated instance with seed {seed} and {db.NrSymbols} symbols: ");

            return(db);
        }
Beispiel #35
0
        static void CreateSaveRestart(string cpFileName)
        {
            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(workingDirectory: Path.GetDirectoryName(cpFileName), systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace(workingDirectory: Path.GetDirectoryName(cpFileName));
            }
            GAMSJob     j1  = ws.AddJobFromString(GetBaseModelText());
            GAMSOptions opt = ws.AddOptions();

            opt.Action = GAMSOptions.EAction.CompileOnly;


            GAMSCheckpoint cp = ws.AddCheckpoint(Path.GetFileName(cpFileName));

            j1.Run(opt, cp);

            opt.Dispose();
        }
Beispiel #36
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
            ws.AddJobFromString(GetModelText()).Run(cp);

            double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };

            // run multiple parallel jobs using the created GAMSCheckpoint
            Object ioMutex = new Object();

            System.Threading.Tasks.Parallel.ForEach(bmultlist, delegate(double b) { RunScenario(ws, cp, ioMutex, b); });
        }
Beispiel #37
0
        private static void ScenSolve(GAMSWorkspace ws, GAMSCheckpoint cp, Queue<double> bmultQueue, Object queueMutex, Object ioMutex)
        {
            GAMSModelInstance mi = cp.AddModelInstance();

            GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", 0, "demand multiplier");
            GAMSOptions opt = ws.AddOptions();
            opt.AllModelTypes = "cplexd";
            // 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;

            while (true)
            {
                double b;
                // dynamically get a bmult value from the queue instead of passing it to the different threads at creation time
                lock (queueMutex)
                {
                    if(0 == bmultQueue.Count)
                        return;
                    b = bmultQueue.Dequeue();
                }
                bmult.FirstRecord().Value = b;
                mi.Solve();
                // we need to make the ouput a critical section to avoid messed up report informations
                lock (ioMutex)
                {
                    Console.WriteLine("Scenario bmult=" + b + ":");
                    Console.WriteLine("  Modelstatus: " + mi.ModelStatus);
                    Console.WriteLine("  Solvestatus: " + mi.SolveStatus);
                    Console.WriteLine("  Obj: " + mi.SyncDB.GetVariable("z").FindRecord().Level);
                }
            }
        }
Beispiel #38
0
        private static void SolveWarehouse(GAMSWorkspace gmsWS, int NumberOfWarehouses, GAMSDatabase result, Object dbMutex)
        {
            // instantiate GAMSOptions and define some scalars
            GAMSOptions gmsOpt = gmsWS.AddOptions();
            gmsOpt.AllModelTypes = "Gurobi";
            gmsOpt.Defines.Add("Warehouse", NumberOfWarehouses.ToString());
            gmsOpt.Defines.Add("Store", "65");
            gmsOpt.Defines.Add("fixed", "22");
            gmsOpt.Defines.Add("disaggregate", "0");
            gmsOpt.OptCR = 0.0; // Solve to optimality

            // create a GAMSJob from string and write results to the result database
            GAMSJob gmsJ = gmsWS.AddJobFromString(GetModelText());
            gmsJ.Run(gmsOpt);

            // need to lock database write operations
            lock (dbMutex)
                result.GetParameter("objrep").AddRecord(NumberOfWarehouses.ToString()).Value = gmsJ.OutDB.GetVariable("obj").FindRecord().Level;

            foreach (GAMSVariableRecord supplyRec in gmsJ.OutDB.GetVariable("supply"))
                if (supplyRec.Level > 0.5)
                    lock(dbMutex)
                        result.GetSet("supplyMap").AddRecord(NumberOfWarehouses.ToString(), supplyRec.Keys[0], supplyRec.Keys[1]);
        }
Beispiel #39
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();
        }
Beispiel #40
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();
            }
        }
Beispiel #41
0
        static void Main(string[] args)
        {
            // Reading input data from workbook
            var excelApp = new Excel.Application();

            Excel.Workbook wb = excelApp.Workbooks.Open(Directory.GetCurrentDirectory() + @"\..\..\..\..\Data\transport.xls");

            Excel.Range range;

            Excel.Worksheet capacity = (Excel.Worksheet)wb.Worksheets.get_Item("capacity");
            range = capacity.UsedRange;
            Array capacityData = (Array)range.Cells.Value;
            int   iCount       = capacity.UsedRange.Columns.Count;

            Excel.Worksheet demand = (Excel.Worksheet)wb.Worksheets.get_Item("demand");
            range = demand.UsedRange;
            Array demandData = (Array)range.Cells.Value;
            int   jCount     = range.Columns.Count;

            Excel.Worksheet distance = (Excel.Worksheet)wb.Worksheets.get_Item("distance");
            range = distance.UsedRange;
            Array distanceData = (Array)range.Cells.Value;

            // number of markets/plants have to be the same in all spreadsheets
            Debug.Assert((range.Columns.Count - 1) == jCount && (range.Rows.Count - 1) == iCount,
                         "Size of the spreadsheets doesn't match");
            wb.Close();

            // Creating the GAMSDatabase and fill with the workbook data
            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace();
            }
            GAMSDatabase db = ws.AddDatabase();

            GAMSSet       i             = db.AddSet("i", 1, "Plants");
            GAMSSet       j             = db.AddSet("j", 1, "Markets");
            GAMSParameter capacityParam = db.AddParameter("a", 1, "Capacity");
            GAMSParameter demandParam   = db.AddParameter("b", 1, "Demand");
            GAMSParameter distanceParam = db.AddParameter("d", 2, "Distance");

            for (int ic = 1; ic <= iCount; ic++)
            {
                i.AddRecord((string)capacityData.GetValue(1, ic));
                capacityParam.AddRecord((string)capacityData.GetValue(1, ic)).Value = (double)capacityData.GetValue(2, ic);
            }
            for (int jc = 1; jc <= jCount; jc++)
            {
                j.AddRecord((string)demandData.GetValue(1, jc));
                demandParam.AddRecord((string)demandData.GetValue(1, jc)).Value = (double)demandData.GetValue(2, jc);
                for (int ic = 1; ic <= iCount; ic++)
                {
                    distanceParam.AddRecord((string)distanceData.GetValue(ic + 1, 1), (string)distanceData.GetValue(1, jc + 1)).Value = (double)distanceData.GetValue(ic + 1, jc + 1);
                }
            }

            // Create and run the GAMSJob
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t10 = ws.AddJobFromString(GetModelText());
                opt.Defines.Add("gdxincname", db.Name);
                opt.AllModelTypes = "xpress";
                t10.Run(opt, db);
                foreach (GAMSVariableRecord rec in t10.OutDB.GetVariable("x"))
                {
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
                }
            }
        }
Beispiel #42
0
        static void Main(string[] args)
        {
            // Create a save/restart file usually supplied by an application provider
            // We create it for demonstration purpose
            string wDir = Path.Combine(".", "tmp");
            CreateSaveRestart(Path.Combine(wDir, "tbase"));

            // define some data by using C# data structures
            List<string> plants = new List<string>()
            {
                "Seattle", "San-Diego"
            };
            List<string> markets = new List<string>()
            {
                "New-York", "Chicago", "Topeka"
            };
            Dictionary<string, double> capacity = new Dictionary<string, double>()
            {
                { "Seattle", 350.0 }, { "San-Diego", 600.0 }
            };
            Dictionary<string, double> demand = new Dictionary<string, double>()
            {
                { "New-York", 325.0 }, { "Chicago", 300.0 }, { "Topeka", 275.0 }
            };
            Dictionary<Tuple<string, string>, double> distance = new Dictionary<Tuple<string, string>, double>()
            {
                { new Tuple<string,string> ("Seattle",   "New-York"), 2.5 },
                { new Tuple<string,string> ("Seattle",   "Chicago"),  1.7 },
                { new Tuple<string,string> ("Seattle",   "Topeka"),   1.8 },
                { new Tuple<string,string> ("San-Diego", "New-York"), 2.5 },
                { new Tuple<string,string> ("San-Diego", "Chicago"),  1.8 },
                { new Tuple<string,string> ("San-Diego", "Topeka"),   1.4 }
            };

            GAMSWorkspace ws;
            if (Environment.GetCommandLineArgs().Length > 1)
                ws = new GAMSWorkspace(workingDirectory: wDir, systemDirectory: Environment.GetCommandLineArgs()[1]);
            else
                ws = new GAMSWorkspace(workingDirectory: wDir);
            // prepare a GAMSDatabase with data from the C# data structures
            GAMSDatabase db = ws.AddDatabase();

            GAMSSet i = db.AddSet("i", 1, "canning plants");
            foreach (string p in plants)
                i.AddRecord(p);

            GAMSSet j = db.AddSet("j", 1, "markets");
            foreach (string m in markets)
                j.AddRecord(m);

            GAMSParameter a = db.AddParameter("a", 1, "capacity of plant i in cases");
            foreach (string p in plants)
                a.AddRecord(p).Value = capacity[p];

            GAMSParameter b = db.AddParameter("b", 1, "demand at market j in cases");
            foreach (string m in markets)
                b.AddRecord(m).Value = demand[m];

            GAMSParameter d = db.AddParameter("d", 2, "distance in thousands of miles");
            foreach (Tuple<string, string> t in distance.Keys)
                d.AddRecord(t.Item1, t.Item2).Value = distance[t];

            GAMSParameter f = db.AddParameter("f", 0, "freight in dollars per case per thousand miles");
            f.AddRecord().Value = 90;

            // run a job using data from the created GAMSDatabase
            GAMSCheckpoint cpBase = ws.AddCheckpoint("tbase");
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t4 = ws.AddJobFromString(GetModelText(), cpBase);
                opt.Defines.Add("gdxincname", db.Name);
                opt.AllModelTypes = "xpress";
                t4.Run(opt, db);
                foreach (GAMSVariableRecord rec in t4.OutDB.GetVariable("x"))
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
            }
        }
Beispiel #43
0
        static void Main(string[] args)
        {
            // Reading input data from workbook
            var excelApp = new Excel.Application();
            Excel.Workbook wb = excelApp.Workbooks.Open(Directory.GetCurrentDirectory() + @"\..\..\..\..\Data\transport.xls");

            Excel.Range range;

            Excel.Worksheet capacity = (Excel.Worksheet)wb.Worksheets.get_Item("capacity");
            range = capacity.UsedRange;
            Array capacityData = (Array)range.Cells.Value;
            int iCount = capacity.UsedRange.Columns.Count;

            Excel.Worksheet demand = (Excel.Worksheet)wb.Worksheets.get_Item("demand");
            range = demand.UsedRange;
            Array demandData = (Array)range.Cells.Value;
            int jCount = range.Columns.Count;

            Excel.Worksheet distance = (Excel.Worksheet)wb.Worksheets.get_Item("distance");
            range = distance.UsedRange;
            Array distanceData = (Array)range.Cells.Value;

            // number of markets/plants have to be the same in all spreadsheets
            Debug.Assert((range.Columns.Count - 1) == jCount && (range.Rows.Count - 1) == iCount,
                         "Size of the spreadsheets doesn't match");
            wb.Close();

            // Creating the GAMSDatabase and fill with the workbook data
            GAMSWorkspace ws;
            if (Environment.GetCommandLineArgs().Length > 1)
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            else
                ws = new GAMSWorkspace();
            GAMSDatabase db = ws.AddDatabase();

            GAMSSet i = db.AddSet("i", 1, "Plants");
            GAMSSet j = db.AddSet("j", 1, "Markets");
            GAMSParameter capacityParam = db.AddParameter("a", 1, "Capacity");
            GAMSParameter demandParam = db.AddParameter("b", 1, "Demand");
            GAMSParameter distanceParam = db.AddParameter("d", 2, "Distance");

            for (int ic = 1; ic <= iCount; ic++)
            {
                i.AddRecord((string)capacityData.GetValue(1, ic));
                capacityParam.AddRecord((string)capacityData.GetValue(1, ic)).Value = (double)capacityData.GetValue(2, ic);
            }
            for (int jc = 1; jc <= jCount; jc++)
            {
                j.AddRecord((string)demandData.GetValue(1, jc));
                demandParam.AddRecord((string)demandData.GetValue(1, jc)).Value = (double)demandData.GetValue(2, jc);
                for (int ic = 1; ic <= iCount; ic++)
                {
                    distanceParam.AddRecord((string)distanceData.GetValue(ic + 1, 1), (string)distanceData.GetValue(1, jc + 1)).Value = (double)distanceData.GetValue(ic + 1, jc + 1);
                }
            }

            // Create and run the GAMSJob
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t10 = ws.AddJobFromString(GetModelText());
                opt.Defines.Add("gdxincname", db.Name);
                opt.AllModelTypes = "xpress";
                t10.Run(opt, db);
                foreach (GAMSVariableRecord rec in t10.OutDB.GetVariable("x"))
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
            }
        }
Beispiel #44
0
        static void Main(string[] args)
        {
            // Create a save/restart file usually supplied by an application provider
            // We create it for demonstration purpose
            string wDir = Path.Combine(".", "tmp");

            CreateSaveRestart(Path.Combine(wDir, "tbase"));

            // define some data by using C# data structures
            List <string> plants = new List <string>()
            {
                "Seattle", "San-Diego"
            };
            List <string> markets = new List <string>()
            {
                "New-York", "Chicago", "Topeka"
            };
            Dictionary <string, double> capacity = new Dictionary <string, double>()
            {
                { "Seattle", 350.0 }, { "San-Diego", 600.0 }
            };
            Dictionary <string, double> demand = new Dictionary <string, double>()
            {
                { "New-York", 325.0 }, { "Chicago", 300.0 }, { "Topeka", 275.0 }
            };
            Dictionary <Tuple <string, string>, double> distance = new Dictionary <Tuple <string, string>, double>()
            {
                { new Tuple <string, string> ("Seattle", "New-York"), 2.5 },
                { new Tuple <string, string> ("Seattle", "Chicago"), 1.7 },
                { new Tuple <string, string> ("Seattle", "Topeka"), 1.8 },
                { new Tuple <string, string> ("San-Diego", "New-York"), 2.5 },
                { new Tuple <string, string> ("San-Diego", "Chicago"), 1.8 },
                { new Tuple <string, string> ("San-Diego", "Topeka"), 1.4 }
            };

            GAMSWorkspace ws;

            if (Environment.GetCommandLineArgs().Length > 1)
            {
                ws = new GAMSWorkspace(workingDirectory: wDir, systemDirectory: Environment.GetCommandLineArgs()[1]);
            }
            else
            {
                ws = new GAMSWorkspace(workingDirectory: wDir);
            }
            // prepare a GAMSDatabase with data from the C# data structures
            GAMSDatabase db = ws.AddDatabase();

            GAMSSet i = db.AddSet("i", 1, "canning plants");

            foreach (string p in plants)
            {
                i.AddRecord(p);
            }

            GAMSSet j = db.AddSet("j", 1, "markets");

            foreach (string m in markets)
            {
                j.AddRecord(m);
            }

            GAMSParameter a = db.AddParameter("a", 1, "capacity of plant i in cases");

            foreach (string p in plants)
            {
                a.AddRecord(p).Value = capacity[p];
            }

            GAMSParameter b = db.AddParameter("b", 1, "demand at market j in cases");

            foreach (string m in markets)
            {
                b.AddRecord(m).Value = demand[m];
            }

            GAMSParameter d = db.AddParameter("d", 2, "distance in thousands of miles");

            foreach (Tuple <string, string> t in distance.Keys)
            {
                d.AddRecord(t.Item1, t.Item2).Value = distance[t];
            }

            GAMSParameter f = db.AddParameter("f", 0, "freight in dollars per case per thousand miles");

            f.AddRecord().Value = 90;

            // run a job using data from the created GAMSDatabase
            GAMSCheckpoint cpBase = ws.AddCheckpoint("tbase");

            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t4 = ws.AddJobFromString(GetModelText(), cpBase);
                opt.Defines.Add("gdxincname", db.Name);
                opt.AllModelTypes = "xpress";
                t4.Run(opt, db);
                foreach (GAMSVariableRecord rec in t4.OutDB.GetVariable("x"))
                {
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
                }
            }
        }
Beispiel #45
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;
            if (Environment.GetCommandLineArgs().Length > 1)
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            else
                ws = new GAMSWorkspace();

            // data from a string with GAMS syntax with explicit export to GDX file
            GAMSJob t3 = ws.AddJobFromString(GetDataText());
            t3.Run();
            t3.OutDB.Export(ws.WorkingDirectory + Path.DirectorySeparatorChar + "tdata.gdx");

            // run a job using an instance of GAMSOptions that defines the data include file
            t3 = ws.AddJobFromString(GetModelText());
            using (GAMSOptions opt = ws.AddOptions())
            {
                opt.Defines.Add("gdxincname", "tdata");
                opt.AllModelTypes = "xpress";
                t3.Run(opt);
                foreach (GAMSVariableRecord rec in t3.OutDB.GetVariable("x"))
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
            }

            // same but with implicit database communication
            using (GAMSOptions opt = ws.AddOptions())
            {
                GAMSJob t3a = ws.AddJobFromString(GetDataText());
                GAMSJob t3b = ws.AddJobFromString(GetModelText());
                t3a.Run();
                opt.Defines.Add("gdxincname", t3a.OutDB.Name);
                opt.AllModelTypes = "xpress";
                t3b.Run(opt, t3a.OutDB);
                foreach (GAMSVariableRecord rec in t3b.OutDB.GetVariable("x"))
                    Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
            }
        }
Beispiel #46
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 t12 = ws.AddJobFromString(GetModelText());

            t12.Run(cp);

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

            double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };

            GAMSDatabase db = ws.AddDatabase();

            GAMSSet       scen  = db.AddSet("scen", 1, "");
            GAMSParameter bmult = db.AddParameter("bmultlist", 1, "");
            GAMSParameter zscen = db.AddParameter("zscen", 1, "");

            int i = 0;

            foreach (double b in bmultlist)
            {
                bmult.AddRecord("s" + i).Value = b;
                scen.AddRecord("s" + i++);
            }

            GAMSSet dict = db.AddSet("dict", 3, "");

            dict.AddRecord(scen.Name, "scenario", "");
            dict.AddRecord("bmult", "param", bmult.Name);
            dict.AddRecord("z", "level", zscen.Name);


            GUSSCall(dict, mi, "transport us lp min z");

            foreach (GAMSParameterRecord rec in db.GetParameter(zscen.Name))
            {
                Console.WriteLine(rec.Keys[0] + " obj: " + rec.Value);
            }

            //*******************

            GAMSModelInstance mi2 = cp.AddModelInstance();
            GAMSDatabase      db2 = ws.AddDatabase();

            GAMSSet       scen2  = db2.AddSet("scen", 1, "");
            GAMSParameter zscen2 = db2.AddParameter("zscen", 1, "");
            GAMSParameter xup    = db2.AddParameter("xup", 3, "");

            for (int j = 0; j < 4; j++)
            {
                foreach (GAMSSetRecord irec in t12.OutDB.GetSet("i"))
                {
                    foreach (GAMSSetRecord jrec in t12.OutDB.GetSet("j"))
                    {
                        xup.AddRecord("s" + j, irec.Keys[0], jrec.Keys[0]).Value = j + 1;
                    }
                }
                scen2.AddRecord("s" + j);
            }


            GAMSSet dict2 = db2.AddSet("dict", 3, "");

            dict2.AddRecord(scen2.Name, "scenario", "");
            dict2.AddRecord("x", "lower", xup.Name);
            dict2.AddRecord("z", "level", zscen2.Name);

            GUSSCall(dict2, mi2, "transport us lp min z", output: Console.Out);

            foreach (GAMSParameterRecord rec in db2.GetParameter(zscen2.Name))
            {
                Console.WriteLine(rec.Keys[0] + " obj: " + rec.Value);
            }
        }
Beispiel #47
0
 static void Main(string[] args)
 {
     GAMSWorkspace ws;
     if (Environment.GetCommandLineArgs().Length > 1)
         ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
     else
         ws = new GAMSWorkspace();
     // write an include file containing data with GAMS syntax
     using (StreamWriter writer = new StreamWriter(ws.WorkingDirectory + Path.DirectorySeparatorChar + "tdata.gms"))
     {
         writer.Write(GetDataText());
     }
     // run a job using an instance of GAMSOptions that defines the data include file
     using (GAMSOptions opt = ws.AddOptions())
     {
         GAMSJob t2 = ws.AddJobFromString(GetModelText());
         opt.Defines.Add("incname", "tdata");
         t2.Run(opt);
         foreach (GAMSVariableRecord rec in t2.OutDB.GetVariable("x"))
             Console.WriteLine("x(" + rec.Keys[0] + "," + rec.Keys[1] + "): level=" + rec.Level + " marginal=" + rec.Marginal);
     }
 }
Beispiel #48
0
 static void RunScenario(GAMSWorkspace ws, GAMSCheckpoint cp, object ioMutex, double b)
 {
     GAMSJob t6 = ws.AddJobFromString("bmult=" + b + "; solve transport min z us lp; ms=transport.modelstat; ss=transport.solvestat;", cp);
     t6.Run();
     // we need to make the ouput a critical section to avoid messed up report information
     lock (ioMutex)
     {
         Console.WriteLine("Scenario bmult=" + b + ":");
         Console.WriteLine("  Modelstatus: " + t6.OutDB.GetParameter("ms").FindRecord().Value);
         Console.WriteLine("  Solvestatus: " + t6.OutDB.GetParameter("ss").FindRecord().Value);
         Console.WriteLine("  Obj: " + t6.OutDB.GetVariable("z").FindRecord().Level);
     }
 }
Beispiel #49
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();
        }
Beispiel #50
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 t12 = ws.AddJobFromString(GetModelText());
            t12.Run(cp);

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

            double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };

            GAMSDatabase db = ws.AddDatabase();

            GAMSSet scen = db.AddSet("scen", 1, "");
            GAMSParameter bmult = db.AddParameter("bmultlist", 1, "");
            GAMSParameter zscen = db.AddParameter("zscen", 1, "");

            int i = 0;
            foreach (double b in bmultlist)
            {
                bmult.AddRecord("s" + i).Value = b;
                scen.AddRecord("s" + i++);
            }

            GAMSSet dict = db.AddSet("dict",3,"");
            dict.AddRecord(scen.Name, "scenario", "");
            dict.AddRecord("bmult", "param", bmult.Name);
            dict.AddRecord("z", "level", zscen.Name);

            GUSSCall(dict, mi, "transport us lp min z");

            foreach (GAMSParameterRecord rec in db.GetParameter(zscen.Name))
                Console.WriteLine(rec.Keys[0] + " obj: " + rec.Value);

            //*******************

            GAMSModelInstance mi2 = cp.AddModelInstance();
            GAMSDatabase db2 = ws.AddDatabase();

            GAMSSet scen2 = db2.AddSet("scen", 1, "");
            GAMSParameter zscen2 = db2.AddParameter("zscen", 1, "");
            GAMSParameter xup = db2.AddParameter("xup", 3, "");

            for (int j = 0; j < 4; j++)
            {
                foreach (GAMSSetRecord irec in t12.OutDB.GetSet("i"))
                    foreach (GAMSSetRecord jrec in t12.OutDB.GetSet("j"))
                        xup.AddRecord("s" + j, irec.Keys[0], jrec.Keys[0]).Value = j+1;
                scen2.AddRecord("s" + j);
            }

            GAMSSet dict2 = db2.AddSet("dict", 3, "");
            dict2.AddRecord(scen2.Name, "scenario", "");
            dict2.AddRecord("x", "lower", xup.Name);
            dict2.AddRecord("z", "level", zscen2.Name);

            GUSSCall(dict2, mi2, "transport us lp min z", output: Console.Out);

            foreach (GAMSParameterRecord rec in db2.GetParameter(zscen2.Name))
                Console.WriteLine(rec.Keys[0] + " obj: " + rec.Value);
        }
Beispiel #51
0
        static void Main(string[] args)
        {
            GAMSWorkspace ws;
            if (Environment.GetCommandLineArgs().Length > 1)
                ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
            else
                ws = new GAMSWorkspace();
            // instantiate GAMSOptions and define parameters
            GAMSOptions opt = ws.AddOptions();
            GAMSDatabase cutstockData = ws.AddDatabase("csdata");
            opt.AllModelTypes = "Cplex";
            opt.OptCR = 0.0; // Solve to optimality
            int maxpattern = 35;
            opt.Defines.Add("pmax", maxpattern.ToString());
            opt.Defines.Add("solveMasterAs", "RMIP");

            // define input data
            Dictionary<string, double> d = new Dictionary<string, double>() { { "i1", 97 }, { "i2", 610 }, { "i3", 395 }, { "i4", 211 } };
            Dictionary<string, double> w = new Dictionary<string, double>() { { "i1", 47 }, { "i2", 36 }, { "i3", 31 }, { "i4", 14 } };
            int r = 100; // raw width

            // cutstockData.AddSet("i", 1, "widths").AddRecords(d.Keys);
            // cutstockData.AddParameter("d", 1, "demand").AddRecords(d);
            // cutstockData.AddParameter("w", 1, "width").AddRecords(w);
            // cutstockData.AddParameter("r", 0, "raw width").AddRecord().Value = r;

            GAMSSet widths = cutstockData.AddSet("i", 1, "widths");
            GAMSParameter rawWidth = cutstockData.AddParameter("r", 0, "raw width");
            GAMSParameter demand = cutstockData.AddParameter("d", 1, "demand");
            GAMSParameter width = cutstockData.AddParameter("w", 1, "width");

            rawWidth.AddRecord().Value = r;
            foreach (string i in d.Keys)
                widths.AddRecord(i);
            foreach (KeyValuePair<string, double> t in d)
                demand.AddRecord(t.Key).Value = t.Value;
            foreach (KeyValuePair<string, double> t in w)
                width.AddRecord(t.Key).Value = t.Value;

            // create initial checkpoint
            GAMSCheckpoint masterCP = ws.AddCheckpoint();
            GAMSJob masterInitJob = ws.AddJobFromString(GetMasterModel());
            masterInitJob.Run(opt, masterCP, cutstockData);

            GAMSJob masterJob = ws.AddJobFromString("execute_load 'csdata', aip, pp; solve master min z using %solveMasterAs%;", masterCP);

            GAMSSet pattern = cutstockData.AddSet("pp", 1, "pattern index");
            GAMSParameter patternData = cutstockData.AddParameter("aip", 2, "pattern data");

            // Initial pattern: pattern i hold width i
            int patternCount = 0;
            foreach(KeyValuePair<string,double> t in w)
            {
                patternData.AddRecord(t.Key, pattern.AddRecord((++patternCount).ToString()).Keys[0]).Value = (int)(r / t.Value);
            }

            // create model instance for sub job
            GAMSCheckpoint subCP = ws.AddCheckpoint();
            ws.AddJobFromString(GetSubModel()).Run(opt, subCP, cutstockData);
            GAMSModelInstance subMI = subCP.AddModelInstance();

            // define modifier demdual
            GAMSParameter demandDual = subMI.SyncDB.AddParameter("demdual", 1, "dual of demand from master");
            subMI.Instantiate("pricing min z using mip", opt, new GAMSModifier(demandDual));

            // find new pattern
            bool patternAdded = true;
            do
            {
                masterJob.Run(opt, masterCP, cutstockData);
                // Copy duals into gmssubMI.SyncDB DB
                demandDual.Clear();
                foreach (GAMSEquationRecord dem in masterJob.OutDB.GetEquation("demand"))
                    demandDual.AddRecord(dem.Keys[0]).Value = dem.Marginal;

                subMI.Solve();
                if (subMI.SyncDB.GetVariable("z").FindRecord().Level < -0.00001)
                {
                    if (patternCount == maxpattern)
                    {
                        Console.Out.WriteLine("Out of pattern. Increase maxpattern (currently {0}).", maxpattern);
                        patternAdded = false;
                    }
                    else
                    {
                        Console.WriteLine("New patter! Value: " + subMI.SyncDB.GetVariable("z").FindRecord().Level);
                        GAMSSetRecord s = pattern.AddRecord((++patternCount).ToString());
                        foreach (GAMSVariableRecord y in subMI.SyncDB.GetVariable("y"))
                        {
                            if (y.Level > 0.5)
                            {
                                patternData.AddRecord(y.Keys[0], s.Keys[0]).Value = Math.Round(y.Level);
                            }
                        }
                    }
                }
                else patternAdded = false;
            } while (patternAdded);

            // solve final MIP
            opt.Defines["solveMasterAs"] = "MIP";
            masterJob.Run(opt, cutstockData);
            Console.WriteLine("Optimal Solution: {0}", masterJob.OutDB.GetVariable("z").FindRecord().Level);
            foreach (GAMSVariableRecord xp in masterJob.OutDB.GetVariable("xp"))
            {
                if (xp.Level > 0.5)
                {
                    Console.Out.Write("  pattern {0} {1} times: ", xp.Keys[0], xp.Level);
                    GAMSParameterRecord aip = masterJob.OutDB.GetParameter("aip").FirstRecord(" ", xp.Keys[0]);
                    do
                    {
                        Console.Out.Write(" {0}: {1}", aip.Keys[0], aip.Value);
                    } while (aip.MoveNext());
                    Console.Out.WriteLine();
                }
            }
            // clean up of unmanaged ressources
            cutstockData.Dispose();
            subMI.Dispose();
            opt.Dispose();
        }
Beispiel #52
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();
        }