Exemple #1
0
        public static int Main(string[] args)
        {
            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            // Create an AMPL instance
            using (AMPL ampl = new AMPL())
            {
                ampl.Eval("set CITIES; set LINKS within (CITIES cross CITIES);");
                ampl.Eval("param cost {LINKS} >= 0; param capacity {LINKS} >= 0;");
                ampl.Eval("data; set CITIES := PITT NE SE BOS EWR BWI ATL MCO;");

                double[] cost      = { 2.5, 3.5, 1.7, 0.7, 1.3, 1.3, 0.8, 0.2, 2.1 };
                double[] capacity  = { 250, 250, 100, 100, 100, 100, 100, 100, 100 };
                string[] LinksFrom = { "PITT", "PITT", "NE", "NE", "NE", "SE", "SE", "SE", "SE" };
                string[] LinksTo   = { "NE", "SE", "BOS", "EWR", "BWI", "EWR", "BWI", "ATL", "MCO" };

                DataFrame df = new DataFrame(2, "LINKSFrom", "LINKSTo", "cost", "capacity");
                df.SetColumn("LINKSFrom", LinksFrom);
                df.SetColumn("LINKSTo", LinksTo);
                df.SetColumn("cost", cost);
                df.SetColumn("capacity", capacity);
                Console.WriteLine(df.ToString());

                ampl.SetData(df, "LINKS");
            }
            return(0);
        }
Exemple #2
0
        public static int Main(string[] args)
        {
            string modelDirectory = ((args != null) && (args.Length > 0)) ? args[0]
             : "../../models";
            string solver = ((args != null) && (args.Length > 1)) ? args[1] : null;

            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            using (AMPL ampl = new AMPL())
            {
                if (solver != null)
                {
                    ampl.SetOption("solver", solver);
                }
                ampl.SetOption("reset_initial_guesses", true);
                ampl.SetOption("send_statuses", false);
                ampl.SetOption("relax_integrality", true);

                // Load the AMPL model from file
                ampl.Read(modelDirectory + "/qpmv/qpmv.mod");
                ampl.Read(modelDirectory + "/qpmv/qpmvbit.run");

                // set tables directory (parameter used in the script above)
                ampl.GetParameter("data_dir").Set(modelDirectory + "/qpmv");
                // Read tables
                ampl.ReadTable("assetstable");
                ampl.ReadTable("astrets");

                // set the output handler to accumulate the output messages
                ampl.Output += Ampl_Output;

                // Create the callback object
                Console.WriteLine("Main thread: Model setup complete. Solve on worker thread.");
                // Initiate the async solution process, passing the callback as a parameter. The Action
                // below will be executed by the AMPL API when the solution process will be completed.
                ampl.SolveAsync(() => Callback());

                // Wait for the solution to complete (achieved by waiting on the AutoResetEvent waitHandle
                Console.WriteLine("Main thread: Waiting for solution to end...\n");
                var start = DateTime.Now;
                waitHandle.WaitOne();
                var duration = DateTime.Now - start;

                Console.WriteLine("Main thread: done waiting.");

                // At this stage, the AMPL process is done, the message "Solution process ended." has been
                // printed on the console by the callback and we print a second confirmation from the main thread
                Console.WriteLine("Main thread: waited for {0}", duration.ToString());
                // Print the objective value
                Console.WriteLine("Main thread: cost: {0}", ampl.GetValue("cst").Dbl);
            }
            return(0);
        }
        public static int Main(string[] args)
        {
            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            // Create an AMPL instance
            using (var ampl = new AMPL())
            {
                ampl.Eval("var x{1..3};");
                ampl.Eval("maximize z: sum{i in 1..3} x[i];");

                // *** Output redirection *** Enable output redirection
                ampl.EnableOutputRouting();
                // Assign handler: Method 1: using method
                ampl.Output += HandleOutput;
                ampl.Eval("display x;");
                ampl.Eval("let {i in 1..3} x[i] := i;");
                ampl.Eval("display x;");
                // Unassign output handler
                ampl.Output -= HandleOutput;
                // print all outputs
                foreach (var t in outputs)
                {
                    Console.Write("{0} - Kind: {1} - Msg:\n{2}", t.Date,
                                  t.Kind, t.Msg);
                }

                // Method 2: Using lambda expression
                ampl.Output += (kind, message) => Console.Write("Got AMPL message:\n{0}\n", message);
                // Test it
                ampl.Eval("display x,x;");

                // *** Error redirection *** Enable error and warnings redirection
                ampl.EnableErrorAndWarningRouting();
                // Register handlers
                ampl.Error   += HandleError;
                ampl.Warning += HandleWarning;
                // Normally throws exception, will just be printed on screen
                ampl.Eval("var x;");
                // Create an obvious infeasibility
                ampl.Eval("c1: x[1]>=1; c2: x[1]<=0;");
                // Solve the model, issuing a warning
                ampl.Solve();
            }
            return(0);
        }
Exemple #4
0
        public DataTable GetInputGenData(string sPath)
        {
            DataTable result;

            using (AMPL data = new AMPL())
            {
                data.Read("D:/CMetis/Metis/models/ParamIndex.mod");
                data.ReadData(sPath);
                int iNumGenUnits = Convert.ToInt16(data.GetSet("GENERATORS").Size.ToString());
                int iNumParams   = Convert.ToInt16(data.GetSet("GENPARAMS").Size.ToString());
                result = extract_gen_data(data.GetParameter("Copy_GenData").GetValues(), iNumGenUnits, iNumParams);
            }

            return(result);
        }
Exemple #5
0
        public DataTable GetInputESData(string sPath)
        {
            DataTable result;

            using (AMPL data = new AMPL())
            {
                data.Read("D:/CMetis/Metis/models/ParamIndex.mod");
                data.ReadData(sPath);
                try
                {
                    int iNumESUnits = Convert.ToInt16(data.GetSet("ENERGY_ST").Size.ToString());
                    int iNumParams  = Convert.ToInt16(data.GetSet("ES_PARAMS").Size.ToString());
                    result = extract_ES_data(data.GetParameter("Copy_ES_Data").GetValues(), iNumESUnits, iNumParams);
                }
                catch
                {
                    result = null;
                }
            }
            return(result);
        }
        public static int Main(string[] args)
        {
            string modelDirectory = ((args != null) && (args.Length > 0)) ? args[0]
      : "../../models";
            string solver = ((args != null) && (args.Length > 1)) ? args[1] : null;

            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            // Create an AMPL instance
            using (AMPL a = new AMPL())
            {
                if (solver != null)
                {
                    a.SetOption("solver", solver);
                }
                // Interpret the two files
                a.Read(System.IO.Path.Combine(modelDirectory, "diet/diet.mod"));
                a.ReadData(System.IO.Path.Combine(modelDirectory, "diet/diet.dat"));

                // Solve
                a.Solve();

                // Get objective entity by AMPL name
                Objective totalcost = a.GetObjective("Total_Cost");
                // Print it
                Console.WriteLine("ObjectiveInstance is: {0}", totalcost.Value);
                // Reassign data - specific instances
                Parameter cost = a.GetParameter("cost");
                cost.SetValues(ampl.Tuple.FromArray("BEEF", "HAM"),
                               new double[] { 5.01, 4.55 });
                Console.WriteLine("Increased costs of beef and ham.");

                // ReSolve and display objective
                a.Solve();
                Console.WriteLine("Objective value: {0}", totalcost.Value);

                // Reassign data - all instances
                cost.SetValues(new double[] { 3, 5, 5, 6, 1, 2, 5.01, 4.55 });
                Console.WriteLine("Updated all costs");
                // ReSolve and display objective
                a.Solve();
                Console.WriteLine("New objective value: {0}", totalcost.Value);

                // Get the values of the variable Buy in a dataframe object
                Variable Buy = a.GetVariable("Buy");
                // Access a specific instance (method 1)
                Console.WriteLine(Buy.Get("FISH").ToString());
                // Access a specific instance (method 2)
                Console.WriteLine(Buy[new ampl.Tuple("FISH")].ToString());
                DataFrame df = Buy.GetValues();
                // Print them
                Console.WriteLine(df);

                // Get the values of an expression into a DataFrame object
                DataFrame df2 = a.GetData("{j in FOOD} 100*Buy[j]/Buy[j].ub");
                // Print them
                Console.WriteLine(df2);
            }
            return(0);
        }
        /// <summary>
        /// This example shows a simple AMPL iterative procedure implemented in AMPL
        /// </summary>
        /// <param name="args">
        /// </param>
        public static int Main(string[] args)
        {
            string modelDirectory = ((args != null) && (args.Length > 0)) ? args[0]
            : "../../models";
            string solver = ((args != null) && (args.Length > 1)) ? args[1] : null;

            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            // Create an AMPL instance
            using (AMPL ampl = new AMPL())
            {
                if (solver != null)
                {
                    ampl.SetOption("solver", solver);
                }
                modelDirectory += "/tracking";

                // Load the AMPL model from file
                ampl.Read(modelDirectory + "/tracking.mod");
                // Read data
                ampl.ReadData(modelDirectory + "/tracking.dat");
                // Read table declarations
                ampl.Read(modelDirectory + "/trackingbit.run");
                // set tables directory (parameter used in the script above)
                ampl.GetParameter("data_dir").Set(modelDirectory);
                // Read tables
                ampl.ReadTable("assets");
                ampl.ReadTable("indret");
                ampl.ReadTable("returns");

                var       hold         = ampl.GetVariable("hold");
                Parameter ifinuniverse = ampl.GetParameter("ifinuniverse");

                // Relax the integrality
                ampl.SetOption("relax_integrality", true);
                // Solve the problem
                ampl.Solve();
                Console.Write("QP objective value {0}\n",
                              ampl.GetObjectives().First().Value);

                double lowcutoff  = 0.04;
                double highcutoff = 0.1;

                // Get the variable representing the (relaxed) solution vector
                DataFrame     holdvalues = hold.GetValues();
                List <double> toHold     = new List <double>(holdvalues.NumRows);
                // For each asset, if it was held by more than the highcutoff, forces it in the model, if
                // less than lowcutoff, forces it out
                foreach (var value in holdvalues.GetColumn("hold"))
                {
                    if (value.Dbl < lowcutoff)
                    {
                        toHold.Add(0);
                    }
                    else if (value.Dbl > highcutoff)
                    {
                        toHold.Add(2);
                    }
                    else
                    {
                        toHold.Add(1);
                    }
                }
                // uses those values for the parameter ifinuniverse, which controls which stock is included
                // or not in the solution
                ifinuniverse.SetValues(toHold.ToArray());

                // Get back to the integer problem
                ampl.SetOption("relax_integrality", false);
                // Solve the (integer) problem
                ampl.Solve();
                Console.Write("QMIP objective value {0}\n",
                              ampl.GetObjectives().First().Value);
            }
            return(0);
        }
Exemple #8
0
        public static int Main(string[] args)
        {
            string modelDirectory = ((args != null) && (args.Length > 0)) ? args[0]
            : "../../models";
            string solver = ((args != null) && (args.Length > 1)) ? args[1] : null;
            // Create first dataframe (for data indexed over NUTR) Add data row by row
            DataFrame df1 = new DataFrame(1, "NUTR", "n_min", "n_max");

            df1.AddRow("A", 700, 20000);
            df1.AddRow("B1", 700, 20000);
            df1.AddRow("B2", 700, 20000);
            df1.AddRow("C", 700, 20000);
            df1.AddRow("CAL", 16000, 24000);
            df1.AddRow("NA", 0.0, 50000);

            // Create second dataframe (for data indexed over FOOD) Add column by column
            DataFrame df2 = new DataFrame(1, "FOOD");

            string[] foods = { "BEEF", "CHK", "FISH", "HAM",
                               "MCH",  "MTL", "SPG",  "TUR" };
            df2.SetColumn("FOOD", foods);
            double[] contents = new double[8];
            for (int j = 0; j < 8; j++)
            {
                contents[j] = 2;
            }
            df2.AddColumn("f_min", contents);
            for (int j = 0; j < 8; j++)
            {
                contents[j] = 10;
            }
            df2.AddColumn("f_max", contents);
            double[] costs = { 3.19, 2.59, 2.29, 2.89, 1.89,
                               1.99, 1.99, 2.49 };
            df2.AddColumn("cost", costs);

            // Create third dataframe, to assign data to the AMPL entity param amt{NUTR, FOOD};
            DataFrame df3 = new DataFrame(2, "NUTR", "FOOD");

            // Populate the set columns
            string[] nutrWithMultiplicity = new string[48];
            string[] foodWithMultiplicity = new string[48];
            int      i = 0;

            for (int n = 0; n < 6; n++)
            {
                for (int f = 0; f < 8; f++)
                {
                    nutrWithMultiplicity[i]   = df1.GetRowByIndex(n)[0].Str;
                    foodWithMultiplicity[i++] = foods[f];
                }
            }
            df3.SetColumn("NUTR", nutrWithMultiplicity);
            df3.SetColumn("FOOD", foodWithMultiplicity);

            // Populate with all these values
            double[] values = { 60,     8,   8,  40,   15,  70,   25,  60,  10,  20,  15,
                                35,    15,  15,  25,   15,  15,   20,  10,  10,  15,  15,  15,  10, 20, 0, 10,
                                40,    35,  30,  50,   20, 295,  770, 440, 430, 315, 400, 370, 450,
                                968, 2180, 945, 278, 1182, 896, 1329, 1397 };
            df3.AddColumn("amt", values);

            // Create an AMPL instance
            using (AMPL ampl = new AMPL())
            {
                if (solver != null)
                {
                    ampl.SetOption("solver", solver);
                }
                // Read model only
                ampl.Read(modelDirectory + "/diet/diet.mod");
                // Assign data to NUTR, n_min and n_max
                ampl.SetData(df1, "NUTR");
                // Assign data to FOOD, f_min, f_max and cost
                ampl.SetData(df2, "FOOD");
                // Assign data to amt
                ampl.SetData(df3);
                // Solve the model
                ampl.Solve();

                // Print out the result
                Console.Write("Objective function value: {0}\n",
                              ampl.GetObjective("Total_Cost").Value);

                // Get the values of the variable Buy in a dataframe
                DataFrame results = ampl.GetVariable("Buy").GetValues();
                // Print
                Console.WriteLine(results.ToString());
            }
            return(0);
        }
        public static int Main(string[] args)
        {
            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            // Create an AMPL instance
            using (AMPL ampl = new AMPL())
            {
                // Get the value of the option preSolve and print
                int presolve = ampl.GetIntOption("presolve").Value;
                Console.Write("AMPL preSolve is {0}\n", presolve);

                // set the value to false (maps to 0)
                ampl.SetOption("presolve", false);

                // Get the value of the option preSolve and print
                presolve = ampl.GetIntOption("presolve").Value;
                Console.Write("AMPL preSolve is now {0}\n", presolve);

                // Check whether an option with a specified name exists
                string value = ampl.GetOption("Solver");
                if (value != null)
                {
                    Console.WriteLine("Option Solver exists and has value: " + value);
                }

                // Check again, this time failing
                value = ampl.GetOption("s_o_l_v_e_r");
                if (value == null)
                {
                    Console.WriteLine("Option s_o_l_v_e_r does not exists!");
                }

                // Using nullables (for bool, int and double options)
                double?dblvalue = ampl.GetDblOption("does_not_exist");
                if (dblvalue.HasValue)
                {
                    Console.WriteLine("Surprisingly, \"does_not_exist\" has a value!");
                }
                else
                {
                    Console.WriteLine("\"does_not_exist\" does not have a value!");
                }

                // Error if accessing value
                try
                {
                    Console.WriteLine(dblvalue.Value);
                }
                catch (InvalidOperationException ex)
                {
                    Console.WriteLine("Error while accessing not existing value:");
                    Console.WriteLine(ex.Message);
                }
            }
            return(0);
        }
Exemple #10
0
        public static int Main(string[] args)
        {
            string modelDirectory = ((args != null) && (args.Length > 0)) ? args[0]
           : "../../models";
            string solver = ((args != null) && (args.Length > 1)) ? args[1] : null;

            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            // Create an AMPL instance
            using (var ampl = new AMPL())
            {
                if (solver != null)
                {
                    ampl.SetOption("solver", solver);
                }
                // Read the model file
                ampl.Read(modelDirectory + "/diet/diet.mod");

                string[] foods = { "BEEF", "CHK", "FISH", "HAM",
                                   "MCH",  "MTL", "SPG",  "TUR" };
                double[] costs = { 3.59, 2.59, 2.29, 2.89, 1.89, 1.99, 1.99, 2.49 };
                double[] fmin  = { 2, 2, 2, 2, 2, 2, 2, 2 };
                double[] fmax  = { 10, 10, 10, 10, 10, 10, 10, 10 };

                DataFrame df = new DataFrame(1, "FOOD");
                df.SetColumn("FOOD", foods);
                df.AddColumn("cost", costs);
                df.AddColumn("f_min", fmin);
                df.AddColumn("f_max", fmax);
                ampl.SetData(df, "FOOD");

                string[] nutrients = { "A", "C", "B1", "B2", "NA", "CAL" };
                double[] nmin      = { 700, 700, 700, 700, 0, 16000 };
                double[] nmax      = { 20000, 20000, 20000, 20000, 50000, 24000 };
                df = new DataFrame(1, "NUTR");
                df.SetColumn("NUTR", nutrients);
                df.AddColumn("n_min", nmin);
                df.AddColumn("n_max", nmax);
                ampl.SetData(df, "NUTR");

                double[,] amounts =
                {
                    {  60,    8,   8,  40,   15,  70,   25,   60 },
                    {  20,    0,  10,  40,   35,  30,   50,   20 },
                    {  10,   20,  15,  35,   15,  15,   25,   15 },
                    {  15,   20,  10,  10,   15,  15,   15,   10 },
                    { 928, 2180, 945, 278, 1182, 896, 1329, 1397 },
                    { 295,  770, 440, 430,  315, 400,  379,  450 }
                };
                df = new DataFrame(2, "NUTR", "FOOD", "amt");
                df.SetMatrix(nutrients, foods, amounts);
                ampl.SetData(df);

                ampl.Solve();

                Console.WriteLine(string.Format("Objective: {0}",
                                                ampl.GetObjective("Total_Cost").Value));
            }
            return(0);
        }
Exemple #11
0
        public static int Main(string[] args)
        {
            string modelDirectory = ((args != null) && (args.Length > 0)) ? args[0]
            : "../../models";

            modelDirectory += "/qpmv";
            string solver = ((args != null) && (args.Length > 1)) ? args[1] : null;

            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            // Create an AMPL instance
            using (AMPL ampl = new AMPL())
            {
                // Number of steps of the efficient frontier
                const int steps = 10;
                if (solver != null)
                {
                    ampl.SetOption("solver", solver);
                }
                ampl.SetOption("reset_initial_guesses", true);
                ampl.SetOption("send_statuses", false);
                ampl.SetOption("Solver", "cplex");

                // Load the AMPL model from file
                ampl.Read(modelDirectory + "/qpmv.mod");
                ampl.Read(modelDirectory + "/qpmvbit.run");

                // set tables directory (parameter used in the script above)
                ampl.GetParameter("data_dir").Set(modelDirectory);
                // Read tables
                ampl.ReadTable("assetstable");
                ampl.ReadTable("astrets");

                Variable  portfolioReturn = ampl.GetVariable("portret");
                Parameter averageReturn   = ampl.GetParameter("averret");
                Parameter targetReturn    = ampl.GetParameter("targetret");
                Objective variance        = ampl.GetObjective("cst");

                // Relax the integrality
                ampl.SetOption("relax_integrality", true);
                // Solve the problem
                ampl.Solve();
                // Calibrate the efficient frontier range
                double           minret = portfolioReturn.Value;
                DataFrame        values = averageReturn.GetValues();
                DataFrame.Column col    = values.GetColumn("averret");

                double   maxret    = col.Max().Dbl;
                double   stepsize  = (maxret - minret) / steps;
                double[] returns   = new double[steps];
                double[] variances = new double[steps];

                for (int i = 0; i < steps; i++)
                {
                    Console.WriteLine(string.Format("Solving for return = {0}",
                                                    maxret - (i - 1) * stepsize));
                    // set target return to the desired point
                    targetReturn.Set(maxret - (i - 1) * stepsize);
                    ampl.Eval("let stockopall:={};let stockrun:=stockall;");
                    // Relax integrality
                    ampl.SetOption("relax_integrality", true);
                    ampl.Solve();
                    Console.WriteLine(string.Format("QP result = {0}",
                                                    variance.Value));
                    // Adjust included stocks
                    ampl.Eval("let stockrun:={i in stockrun:weights[i]>0};");
                    ampl.Eval("let stockopall:={i in stockrun:weights[i]>0.5};");
                    // set integrality back
                    ampl.SetOption("relax_integrality", false);
                    ampl.Solve();
                    Console.WriteLine(string.Format("QMIP result = {0}",
                                                    variance.Value));
                    // Store data of corrent frontier point
                    returns[i]   = maxret - (i - 1) * stepsize;
                    variances[i] = variance.Value;
                }

                // Display efficient frontier points
                Console.WriteLine("    RETURN    VARIANCE");
                for (int i = 0; i < steps; i++)
                {
                    Console.WriteLine(string.Format("{0,10:0.00000}  {1,10:0.00000}", returns[i], variances[i]));
                }
            }
            return(0);
        }
Exemple #12
0
        public void Run(int iModel, string sModelPath, string sDataPath)
        {
            ResultsWindow resWindow = new ResultsWindow();

            // Create an AMPL instance
            using (AMPL a = new AMPL())
            {
                DataFrame Gens;
                DataFrame P;

                a.SetOption("solver", "gurobi");
                a.Read(sModelPath);
                a.ReadData(sDataPath);

                // Solve
                a.Solve();

                // Get objective entity by AMPL name
                string sTotalCost   = a.GetObjective("Total_Cost").Value.ToString("0.00");
                int    iNumGenUnits = Convert.ToInt16(a.GetSet("GENERATORS").Size.ToString());
                if (iModel == CTUC_ES | iModel == CTUC_NON_MARKET_ES)
                {
                    int iNumESUnits = a.GetSet("ENERGY_ST").Size;
                }
                switch (iModel)
                {
                case DTUC:
                    Gens = a.GetParameter("GenData").GetValues();
                    P    = a.GetVariable("P").GetValues();
                    DataTable dtP     = generate_DT_2D_table(P);
                    DataTable dtPRamp = calculate_ramping(dtP, true);
                    DataTable dtI     = generate_DT_2D_table(a.GetVariable("I").GetValues());
                    DataTable dtLMP   = generate_1D_table(a.GetConstraint("Power_Balance").GetValues());

                    resWindow.ProcessDTUCResults(dtP, dtI, dtLMP, sTotalCost, dtPRamp);
                    break;

                case CTUC:
                    DataTable CTUC_dtP = array2d_to_datatable(
                        CT_P_Post_Mortem(Dataframe_to_3d_array(a.GetVariable("G_H").GetValues(), iNumGenUnits, 24, 4),
                                         iNumGenUnits)
                        );
                    DataTable CTUC_dtLamda = array1d_to_datatable(
                        CT_Price_Post_Mortem(Dataframe_to_2d_array(a.GetConstraint("Load_Balance1").GetValues(), 24, 4, true),
                                             Dataframe_to_2d_array(a.GetConstraint("Load_Balance2").GetValues(), 24, 4, true),
                                             iNumGenUnits)
                        );
                    DataTable CTUC_dtPRamp = calculate_ramping1(
                        CT_P_Post_Mortem(
                            Dataframe_to_3d_array(a.GetVariable("G_H").GetValues(), iNumGenUnits, 24, 4),
                            iNumGenUnits)
                        );
                    DataTable CTUC_dtI = generate_DT_2D_table(a.GetVariable("I").GetValues());
                    resWindow.ProcessCTUCResults(CTUC_dtP, CTUC_dtPRamp, CTUC_dtLamda, sTotalCost, CTUC_dtI);
                    break;

                case CTUC_ES:
                    double[,] arr_G_cont = CT_P_Post_Mortem(
                        Dataframe_to_3d_array(a.GetVariable("G_H").GetValues(), iNumGenUnits, 24, 4),
                        iNumGenUnits);

                    double[] arr_Lambda_cont = CT_Price_Post_Mortem(
                        Dataframe_to_2d_array(a.GetConstraint("Load_Balance1").GetValues(), 24, 4, true),
                        Dataframe_to_2d_array(a.GetConstraint("Load_Balance2").GetValues(), 24, 4, true),
                        iNumGenUnits);

                    double[,] arr_ES_G_cont = CT_ES_CH_DIS_Post_Mortem(
                        Dataframe_to_3d_array(a.GetVariable("D_H_S").GetValues(), iNumGenUnits, 24, 4),
                        iNumESUnits);
                    double[,] arr_ES_D_cont = CT_ES_CH_DIS_Post_Mortem(
                        Dataframe_to_3d_array(a.GetVariable("G_H_S").GetValues(), iNumGenUnits, 24, 4),
                        iNumESUnits);

                    double[,] arr_ES_E_cont = CT_ES_Energy_Post_Mortem(
                        Dataframe_to_3d_array(a.GetVariable("E_B_S").GetValues(), iNumGenUnits, 24, 5),
                        iNumESUnits);

                    double[,] arr_Gamma_E_cont = CT_ES_Gamma_Post_Mortem(
                        Dataframe_to_3d_array(a.GetConstraint("Integral1_INI").GetValues(), iNumGenUnits, 24, 5),
                        Dataframe_to_3d_array(a.GetConstraint("ES_minE").GetValues(), iNumGenUnits, 24, 5),
                        Dataframe_to_3d_array(a.GetConstraint("ES_maxE").GetValues(), iNumGenUnits, 24, 5),
                        iNumESUnits);

                    DataTable dtCTUC_ES_P     = array2d_to_datatable(arr_G_cont);
                    DataTable dtCTUC_ES_Lamda = array1d_to_datatable(arr_Lambda_cont);
                    DataTable dtCTUC_ES_PRamp = calculate_ramping1(arr_G_cont);
                    DataTable dtCTUC_ES_I     = generate_DT_2D_table(a.GetVariable("I").GetValues());

                    DataTable dtCTUC_ES_CHP   = array2d_to_datatable(arr_ES_G_cont);
                    DataTable dtCTUC_ES_CHPR  = calculate_ramping1(arr_ES_G_cont);
                    DataTable dtCTUC_ES_DISP  = array2d_to_datatable(arr_ES_D_cont);
                    DataTable dtCTUC_ES_DISPR = calculate_ramping1(arr_ES_D_cont);

                    DataTable dtCTUC_ES_E     = array2d_to_datatable(arr_ES_E_cont);
                    DataTable dtCTUC_ES_NISSE = array2d_to_datatable(arr_Gamma_E_cont);

                    resWindow.ProcessCTUCwithES_MarketResults(dtCTUC_ES_P,
                                                              dtCTUC_ES_I,
                                                              dtCTUC_ES_Lamda,
                                                              sTotalCost,
                                                              dtCTUC_ES_PRamp,
                                                              dtCTUC_ES_CHP,
                                                              dtCTUC_ES_CHPR,
                                                              dtCTUC_ES_DISP,
                                                              dtCTUC_ES_DISPR,
                                                              dtCTUC_ES_NISSE,
                                                              dtCTUC_ES_E);
                    break;

                case CTUC_NON_MARKET_ES:
                    double[,] arr_G_cont_NM = CT_P_Post_Mortem(
                        Dataframe_to_3d_array(a.GetVariable("G_H").GetValues(), iNumGenUnits, 24, 4),
                        iNumGenUnits);

                    double[] arr_Lambda_cont_NM = CT_Price_Post_Mortem(
                        Dataframe_to_2d_array(a.GetConstraint("Load_Balance1").GetValues(), 24, 4, true),
                        Dataframe_to_2d_array(a.GetConstraint("Load_Balance2").GetValues(), 24, 4, true),
                        iNumGenUnits);

                    double[,] arr_ES_G_cont_NM = CT_ES_CH_DIS_Post_Mortem(
                        Dataframe_to_3d_array(a.GetVariable("D_H_S").GetValues(), iNumGenUnits, 24, 4),
                        iNumESUnits);
                    double[,] arr_ES_D_cont_NM = CT_ES_CH_DIS_Post_Mortem(
                        Dataframe_to_3d_array(a.GetVariable("G_H_S").GetValues(), iNumGenUnits, 24, 4),
                        iNumESUnits);

                    double[,] arr_ES_E_cont_NM = CT_ES_Energy_Post_Mortem(
                        Dataframe_to_3d_array(a.GetVariable("E_B_S").GetValues(), iNumGenUnits, 24, 5),
                        iNumESUnits);

                    double[,] arr_Gamma_E_cont_NM = CT_ES_Gamma_Post_Mortem(
                        Dataframe_to_3d_array(a.GetConstraint("Integral1_INI").GetValues(), iNumGenUnits, 24, 5),
                        Dataframe_to_3d_array(a.GetConstraint("ES_minE").GetValues(), iNumGenUnits, 24, 5),
                        Dataframe_to_3d_array(a.GetConstraint("ES_maxE").GetValues(), iNumGenUnits, 24, 5),
                        iNumESUnits);

                    DataTable dtCTUC_ES_NM_P     = array2d_to_datatable(arr_G_cont_NM);
                    DataTable dtCTUC_ES_NM_Lamda = array1d_to_datatable(arr_Lambda_cont_NM);
                    DataTable dtCTUC_ES_NM_PRamp = calculate_ramping1(arr_G_cont_NM);
                    DataTable dtCTUC_ES_NM_I     = generate_DT_2D_table(a.GetVariable("I").GetValues());

                    DataTable dtCTUC_ES_NM_CHP   = array2d_to_datatable(arr_ES_G_cont_NM);
                    DataTable dtCTUC_ES_NM_CHPR  = calculate_ramping1(arr_ES_G_cont_NM);
                    DataTable dtCTUC_ES_NM_DISP  = array2d_to_datatable(arr_ES_D_cont_NM);
                    DataTable dtCTUC_ES_NM_DISPR = calculate_ramping1(arr_ES_D_cont_NM);

                    DataTable dtCTUC_ES_NM_E     = array2d_to_datatable(arr_ES_E_cont_NM);
                    DataTable dtCTUC_ES_NM_NISSE = array2d_to_datatable(arr_Gamma_E_cont_NM);

                    resWindow.ProcessCTUCwithES_MarketResults(dtCTUC_ES_NM_P,
                                                              dtCTUC_ES_NM_I,
                                                              dtCTUC_ES_NM_Lamda,
                                                              sTotalCost,
                                                              dtCTUC_ES_NM_PRamp,
                                                              dtCTUC_ES_NM_CHP,
                                                              dtCTUC_ES_NM_CHPR,
                                                              dtCTUC_ES_NM_DISP,
                                                              dtCTUC_ES_NM_DISPR,
                                                              dtCTUC_ES_NM_NISSE,
                                                              dtCTUC_ES_NM_E);
                    break;

                default:
                    P = a.GetVariable("P").GetValues();
                    break;
                }
            }
        }
        /// <summary>
        /// This example shows a simple AMPL iterative procedure implemented in AMPL.
        /// Must be executed with a solver supporting the suffix dunbdd
        /// </summary>
        /// <param name="args">
        /// The first string, if present, should point to the models directory
        /// </param>
        public static int Main(string[] args)
        {
            string modelDirectory = ((args != null) && (args.Length > 0)) ? args[0]
         : "../../models";

            /*
             * // If the AMPL installation directory is not in the system search path:
             * ampl.Environment env = new ampl.Environment(
             * "full path to the AMPL installation directory");
             * // Create an AMPL instance
             * using (AMPL a = new AMPL(env)) {}
             */

            // Create an AMPL instance
            using (AMPL ampl = new AMPL())
            {
                // Must be solved with a solver supporting the suffix dunbdd
                ampl.SetOption("solver", "cplex");

                modelDirectory += "/locationtransportation";
                ampl.SetOption("presolve", false);
                ampl.SetOption("omit_zero_rows", true);

                // Read the model.
                ampl.Read(modelDirectory + "/trnloc2.mod");
                ampl.ReadData(modelDirectory + "/trnloc.dat"); // TODO: set data
                                                               // programmatically

                // Get references to AMPL's model entities for easy access.
                Objective  shipCost    = ampl.GetObjective("Ship_Cost");
                Variable   maxShipCost = ampl.GetVariable("Max_Ship_Cost");
                Variable   buildVar    = ampl.GetVariable("Build");
                Constraint supply      = ampl.GetConstraint("Supply");
                Constraint demand      = ampl.GetConstraint("Demand");
                Parameter  numCutParam = ampl.GetParameter("nCUT");
                Parameter  cutType     = ampl.GetParameter("cut_type");
                Parameter  buildParam  = ampl.GetParameter("build");
                Parameter  supplyPrice = ampl.GetParameter("supply_price");
                Parameter  demandPrice = ampl.GetParameter("demand_price");

                numCutParam.Set(0);
                maxShipCost.Value = 0;
                double[] initialBuild = new double[ampl.GetSet("ORIG").Size];
                for (int i = 0; i < initialBuild.Length; i++)
                {
                    initialBuild[i] = 1;
                }
                buildParam.SetValues(initialBuild);
                int numCuts;
                for (numCuts = 1; ; numCuts++)
                {
                    Console.WriteLine("Iteration {0}", numCuts);
                    ampl.Display("build");
                    // Solve the subproblem.
                    ampl.Eval("solve Sub;");
                    string result = shipCost.Result;

                    if (result.Equals("infeasible"))
                    {
                        // Add a feasibility cut.
                        numCutParam.Set(numCuts);
                        cutType.Set(new ampl.Tuple(numCuts), "ray");
                        DataFrame dunbdd = supply.GetValues("dunbdd");
                        foreach (var row in dunbdd)
                        {
                            supplyPrice.Set(new ampl.Tuple(row[0], numCuts), row[1].Dbl);
                        }
                        dunbdd = demand.GetValues("dunbdd");
                        foreach (var row in dunbdd)
                        {
                            demandPrice.Set(new ampl.Tuple(row[0], numCuts), row[1].Dbl);
                        }
                    }
                    else if (shipCost.Value > maxShipCost.Value + 0.00001)
                    {
                        // Add an optimality cut.
                        numCutParam.Set(numCuts);
                        cutType.Set(new ampl.Tuple(numCuts), "point");
                        ampl.Display("Ship");
                        DataFrame duals = supply.GetValues();
                        foreach (var row in duals)
                        {
                            supplyPrice.Set(new ampl.Tuple(row[0], numCuts), row[1].Dbl);
                        }
                        duals = demand.GetValues();
                        foreach (var row in duals)
                        {
                            demandPrice.Set(new ampl.Tuple(row[0], numCuts), row[1].Dbl);
                        }
                    }
                    else
                    {
                        break;
                    }

                    // Re-solve the master problem.
                    Console.WriteLine("RE-SOLVING MASTER PROBLEM");
                    ampl.Eval("solve Master;");

                    // Copy the data from the Build variable used in the master problem
                    // to the build parameter used in the subproblem.
                    DataFrame data = buildVar.GetValues();
                    buildParam.SetValues(data);
                }
                ampl.Display("Ship");
            }
            return(0);
        }