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); }
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) { 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); }
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); }