示例#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);
        }
        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);
        }
示例#3
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);
        }
        /// <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);
        }