Exemplo n.º 1
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);
        }
        /// <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);
        }
Exemplo n.º 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);
        }