Exemple #1
0
    public static void Main(string[] args)
    {
      double[][] A = 
        { new double[] { 50.0, 31.0 },
          new double[] { 3.0,  -2.0 } };
      double[] c = { 1.0, 0.64 };
      using (Model M = new Model("milo1"))
      {
        Variable x = M.Variable("x", 2, Domain.GreaterThan(0.0), Domain.IsInteger());

        // Create the constraints
        //      50.0 x[0] + 31.0 x[1] <= 250.0
        //       3.0 x[0] -  2.0 x[1] >= -4.0
        M.Constraint("c1", Expr.Dot(A[0], x), Domain.LessThan(250.0));
        M.Constraint("c2", Expr.Dot(A[1], x), Domain.GreaterThan(-4.0));

        // Set max solution time
        M.SetSolverParam("mioMaxTime", 60.0);
        // Set max relative gap (to its default value)
        M.SetSolverParam("mioTolRelGap", 1e-4);
        // Set max absolute gap (to its default value)
        M.SetSolverParam("mioTolAbsGap", 0.0);

        // Set the objective function to (c^T * x)
        M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(c, x));

        // Solve the problem
        M.Solve();

        // Get the solution values
        double[] sol = x.Level();
        Console.WriteLine("x1,x2 = {0}, {1}", sol[0], sol[1]);
        Console.WriteLine("MIP rel gap = {0} ({0})",M.GetSolverDoubleInfo("mioObjRelGap"),M.GetSolverDoubleInfo("mioObjAbsGap"));
      }
    }
Exemple #2
0
        public static void Main(string[] args)
        {
            double[][] A =
            { new double[] { 50.0, 31.0 },
              new double[]     {  3.0, -2.0 } };
            double[] c = { 1.0, 0.64 };
            using (Model M = new Model("milo1"))
            {
                Variable x = M.Variable("x", 2, Domain.GreaterThan(0.0), Domain.IsInteger());

                // Create the constraints
                //      50.0 x[0] + 31.0 x[1] <= 250.0
                //       3.0 x[0] -  2.0 x[1] >= -4.0
                M.Constraint("c1", Expr.Dot(A[0], x), Domain.LessThan(250.0));
                M.Constraint("c2", Expr.Dot(A[1], x), Domain.GreaterThan(-4.0));

                // Set max solution time
                M.SetSolverParam("mioMaxTime", 60.0);
                // Set max relative gap (to its default value)
                M.SetSolverParam("mioTolRelGap", 1e-4);
                // Set max absolute gap (to its default value)
                M.SetSolverParam("mioTolAbsGap", 0.0);

                // Set the objective function to (c^T * x)
                M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(c, x));

                // Solve the problem
                M.Solve();

                // Get the solution values
                double[] sol = x.Level();
                Console.WriteLine("x1,x2 = {0}, {1}", sol[0], sol[1]);
                Console.WriteLine("MIP rel gap = {0} ({0})", M.GetSolverDoubleInfo("mioObjRelGap"), M.GetSolverDoubleInfo("mioObjAbsGap"));
            }
        }
Exemple #3
0
                public static void Main(string[] args)
                {
                    string slvr = "intpnt";

                    if (args.Length < 1)
                    {
                        Console.WriteLine("Usage: callback ( psim | dsim | intpnt )");
                    }

                    if (args.Length >= 1)
                    {
                        slvr = args[0];
                    }

                    double[][] A =
                    { new double[] { 3.0, 2.0, 0.0, 1.0 },
                      new double[]       { 2.0, 3.0, 1.0, 1.0 },
                      new double[]       { 0.0, 0.0, 3.0, 2.0 } };
                    double[] c = { 3.0, 5.0, 1.0, 1.0 };

                    double maxtime = 0.01;

                    Model M = new Model("callback");

                    Variable x = M.Variable("x", 3, Domain.GreaterThan(0.0));
                    Variable y = M.Variable("y", 1, Domain.InRange(0.0, 10.0));
                    Variable z = Var.Vstack(x, y);

                    M.Constraint("c1", Expr.Dot(A[0], z), Domain.EqualsTo(30.0));
                    M.Constraint("c2", Expr.Dot(A[1], z), Domain.GreaterThan(15.0));
                    M.Constraint("c3", Expr.Dot(A[2], z), Domain.LessThan(25.0));

                    M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(c, z));


                    if (slvr == "psim")
                    {
                        M.SetSolverParam("optimizer", "primal_simplex");
                    }
                    else if (slvr == "dsim")
                    {
                        M.SetSolverParam("optimizer", "dual_simplex");
                    }
                    else if (slvr == "intpnt")
                    {
                        M.SetSolverParam("optimizer", "intpnt");
                    }

                    /*TAG:begin-callback-handler*/
                    M.SetCallbackHandler(new myCallback(maxtime, M));
                    /*TAG:end-callback-handler*/
                    M.SetSolverParam("log", 0);

                    M.Solve();
                }
Exemple #4
0
        /*
         *  Description:
         *      Extends the basic Markowitz model with a market cost term.
         *
         *  Input:
         *      n: Number of assets
         *      mu: An n dimmensional vector of expected returns
         *      GT: A matrix with n columns so (GT")*GT  = covariance matrix"
         *      x0: Initial holdings
         *      w: Initial cash holding
         *      gamma: Maximum risk (=std. dev) accepted
         *      f: If asset j is traded then a fixed cost f_j must be paid
         *      g: If asset j is traded then a cost g_j must be paid for each unit traded
         *
         *  Output:
         *     Optimal expected return and the optimal portfolio
         *
         */
        public static double[] MarkowitzWithTransactionsCost
            (int n,
            double[] mu,
            double[,] GT,
            double[] x0,
            double w,
            double gamma,
            double[] f,
            double[] g)
        {
            // Upper bound on the traded amount
            double[] u = new double[n];
            {
                double v = w + sum(x0);
                for (int i = 0; i < n; ++i)
                {
                    u[i] = v;
                }
            }

            using (Model M = new Model("Markowitz portfolio with transaction costs"))
            {
                //M.SetLogHandler(Console.Out);

                // Defines the variables. No shortselling is allowed.
                Variable x = M.Variable("x", n, Domain.GreaterThan(0.0));

                // Addtional "helper" variables
                Variable z = M.Variable("z", n, Domain.Unbounded());
                // Binary varables
                Variable y = M.Variable("y", n, Domain.Binary());

                //  Maximize expected return
                M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(mu, x));

                // Invest amount + transactions costs = initial wealth
                M.Constraint("budget", Expr.Add(Expr.Add(Expr.Sum(x), Expr.Dot(f, y)), Expr.Dot(g, z)),
                             Domain.EqualsTo(w + sum(x0)));

                // Imposes a bound on the risk
                M.Constraint("risk", Expr.Vstack(gamma, Expr.Mul(GT, x)), Domain.InQCone());

                // z >= |x-x0|
                M.Constraint("buy", Expr.Sub(z, Expr.Sub(x, x0)), Domain.GreaterThan(0.0));
                M.Constraint("sell", Expr.Sub(z, Expr.Sub(x0, x)), Domain.GreaterThan(0.0));

                //M.constraint("trade", Expr.hstack(z,Expr.sub(x,x0)), Domain.inQcone())"

                // Consraints for turning y off and on. z-diag(u)*y<=0 i.e. z_j <= u_j*y_j
                M.Constraint("y_on_off", Expr.Sub(z, Expr.Mul(Matrix.Diag(u), y)), Domain.LessThan(0.0));

                // Integer optimization problems can be very hard to solve so limiting the
                // maximum amount of time is a valuable safe guard
                M.SetSolverParam("mioMaxTime", 180.0);
                M.Solve();
                return(x.Level());
            }
        }
Exemple #5
0
        public static void Main(string[] args)
        {
            double[] c        = { 7.0, 10.0, 1.0, 5.0 };
            double[] init_sol = { 0.0, 2.0, 0.0, 1.0 };
            int      n        = 4;

            using (Model M = new Model("mioinitsol"))
            {
                Variable x = M.Variable("x", n, Domain.Integral(Domain.GreaterThan(0.0)));

                // Create the constraint
                M.Constraint(Expr.Sum(x), Domain.LessThan(2.5));

                // Set max solution time
                M.SetSolverParam("mioMaxTime", 60.0);
                // Set max relative gap (to its default value)
                M.SetSolverParam("mioTolRelGap", 1e-4);
                // Set max absolute gap (to its default value)
                M.SetSolverParam("mioTolAbsGap", 0.0);

                // Set the objective function to (c^T * x)
                M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(c, x));

                x.SetLevel(init_sol);

                // Solve the problem
                M.Solve();

                // Get the solution values
                double[] sol = x.Level();
                Console.Write("x = [");
                for (int i = 0; i < n; i++)
                {
                    Console.Write("{0}, ", sol[i]);
                }
                Console.WriteLine("]");
                double miorelgap = M.GetSolverDoubleInfo("mioObjRelGap");
                double mioabsgap = M.GetSolverDoubleInfo("mioObjAbsGap");
                Console.WriteLine("MIP rel gap = {0} ({0})", miorelgap, mioabsgap);
            }
        }
Exemple #6
0
        public static void Main(string[] args)
        {
            // Create the Model
            using (Model M = new Model()) {
                Console.WriteLine("Test MOSEK parameter get/set functions");

                // Set log level (integer parameter)
                M.SetSolverParam("log", 1);
                // Select interior-point optimizer... (parameter with symbolic string values)
                M.SetSolverParam("optimizer", "intpnt");
                // ... without basis identification (parameter with symbolic string values)
                M.SetSolverParam("intpntBasis", "never");
                // Set relative gap tolerance (double parameter)
                M.SetSolverParam("intpntCoTolRelGap", 1.0e-7);

                // The same in a different way
                // M.SetSolverParam("intpntCoTolRelGap", "1.0e-7");

                // Incorrect value
                try {
                    M.SetSolverParam("intpntCoTolRelGap", -1);
                }
                catch (mosek.fusion.ParameterError e) {
                    Console.WriteLine("Wrong parameter value");
                }


                // Define and solve an optimization problem here
                // M.Solve()
                // After optimization:

                Console.WriteLine("Get MOSEK information items");

                double tm = M.GetSolverDoubleInfo("optimizerTime");
                int    it = M.GetSolverIntInfo("intpntIter");

                Console.WriteLine("Time: " + tm);
                Console.WriteLine("Iterations: " + it);
            }
        }
Exemple #7
0
                public static void Main(string [] args)
                {
                    double lb   = 1.0;
                    int    m    = 4;
                    int    n    = 15;
                    int    seed = 0;
                    double ub   = 5.0;

                    double[] T = new double[n];

                    Random gen = new Random(seed);

                    for (int i = 0; i < n; i++)
                    {
                        T[i] = gen.NextDouble() * (ub - lb) + lb;
                    }

                    Array.Sort <double>(T);

                    //TAG:begin-model
                    Model M = new Model("Multi-processor scheduling");

                    Variable x = M.Variable("x", new int[] { m, n }, Domain.Binary());

                    Variable t = M.Variable("t", 1, Domain.Unbounded());

                    M.Constraint(Expr.Sum(x, 0), Domain.EqualsTo(1.0));

                    //TAG:begin-repeat
                    M.Constraint(Expr.Sub(Var.Repeat(t, m), Expr.Mul(x, T)), Domain.GreaterThan(0.0));
                    //TAG:end-repeat

                    M.Objective(ObjectiveSense.Minimize, t);
                    //TAG:end-model

                    //TAG:begin-lpt
                    double [] init     = new double[n * m];
                    double [] schedule = new double[m];


                    for (int i = 0; i < n; i++)
                    {
                        int next = 0;
                        for (int j = 1; j < m; j++)
                        {
                            if (schedule[j] < schedule[next])
                            {
                                next = j;
                            }
                        }

                        schedule[next]    += T[i];
                        init[next * n + i] = 1;
                    }
                    //TAG:end-lpt

                    M.SetLogHandler(Console.Out);

                    M.WriteTask("dump.opf");

                    M.SetSolverParam("mioTolRelGap", .01);
                    M.Solve();

                    try
                    {
                        Console.WriteLine("\n\nInitial solution: ");
                        for (int i = 0; i < m; i++)
                        {
                            Console.Write("M {0} [", i);
                            for (int y = 0; y < n; y++)
                            {
                                Console.Write(init[i * n + y] + ", ");
                            }
                            Console.WriteLine("]");
                        }
                        //TAG:begin-sol-input
                        x.SetLevel(init);
                        //TAG:end-sol-input


                        Console.WriteLine("\n\nMOSEK solution:");
                        for (int i = 0; i < m; i++)
                        {
                            Console.Write("M {0} [", i);
                            for (int y = 0; y < n; y++)
                            {
                                double value = x.Index(i, y).Level()[0];
                                Console.Write("{0}, ", (int)value);
                            }
                            Console.WriteLine("]");
                        }
                    }
                    catch (SolutionError e)
                    {
                        //must do something about....
                    }
                }
Exemple #8
0
        public static void Main(string[] args)
        {
            string slvr = "intpnt";

            if (args.Length < 1)
            {
                Console.WriteLine("Usage: callback ( psim | dsim | intpnt )");
            }

            if (args.Length >= 1)
            {
                slvr = args[0];
            }

            // We create a large linear problem
            int n = 150;
            int m = 700;

            double[] A = new double[m * n];
            double[] b = new double[m];
            double[] c = new double[n];

            Random rnd = new Random();

            for (int i = 0; i < m * n; i++)
            {
                A[i] = rnd.NextDouble();
            }
            for (int i = 0; i < m; i++)
            {
                b[i] = rnd.NextDouble();
            }
            for (int i = 0; i < n; i++)
            {
                c[i] = rnd.NextDouble();
            }

            double maxtime = 0.07;

            Model M = new Model("callback");

            Variable x = M.Variable(n, Domain.Unbounded());

            M.Constraint(Expr.Mul(Matrix.Dense(m, n, A), x), Domain.LessThan(b));
            M.Objective(ObjectiveSense.Maximize, Expr.Dot(c, x));

            if (slvr == "psim")
            {
                M.SetSolverParam("optimizer", "primalSimplex");
            }
            else if (slvr == "dsim")
            {
                M.SetSolverParam("optimizer", "dualSimplex");
            }
            else if (slvr == "intpnt")
            {
                M.SetSolverParam("optimizer", "intpnt");
            }

            M.SetDataCallbackHandler(new myCallback(maxtime, M));

            M.Solve();
        }
Exemple #9
0
        /*
            Description:
                Extends the basic Markowitz model with a market cost term.

            Input:
                n: Number of assets
                mu: An n dimmensional vector of expected returns
                GT: A matrix with n columns so (GT")*GT  = covariance matrix"
                x0: Initial holdings 
                w: Initial cash holding
                gamma: Maximum risk (=std. dev) accepted
                f: If asset j is traded then a fixed cost f_j must be paid
                g: If asset j is traded then a cost g_j must be paid for each unit traded

            Output:
               Optimal expected return and the optimal portfolio     

        */
        public static double[] MarkowitzWithTransactionsCost
          ( int n, 
            double[] mu,
            DenseMatrix GT,
            double[] x0,
            double   w,
            double   gamma,
            double[] f,
            double[] g)
        {

          // Upper bound on the traded amount
          double[] u = new double[n];
          {
            double v = w+sum(x0);
            for (int i = 0; i < n; ++i) u[i] = v;
          }

          using( Model M = new Model("Markowitz portfolio with transaction costs") )
          {
            Console.WriteLine("\n-------------------------------------------------------------------------");
            Console.WriteLine("Markowitz portfolio optimization with transaction cost\n");
            Console.WriteLine("------------------------------------------------------------------------\n");
          
            //M.SetLogHandler(Console.Out);

            // Defines the variables. No shortselling is allowed.
            Variable x = M.Variable("x", n, Domain.GreaterThan(0.0));

            // Addtional "helper" variables 
            Variable z = M.Variable("z", n, Domain.Unbounded());
            // Binary varables
            Variable y = M.Variable("y", n, Domain.InRange(0.0,1.0), Domain.IsInteger());

            //  Maximize expected return
            M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(mu,x));

            // Invest amount + transactions costs = initial wealth
            M.Constraint("budget", Expr.Add(Expr.Add(Expr.Sum(x),Expr.Dot(f,y)),Expr.Dot(g,z)),
                         Domain.EqualsTo(w+sum(x0)));

            // Imposes a bound on the risk
            M.Constraint("risk", Expr.Vstack(Expr.ConstTerm(new double[] {gamma}),Expr.Mul(GT,x)), Domain.InQCone());

            // z >= |x-x0| 
            M.Constraint("buy",  Expr.Sub(z,Expr.Sub(x,x0)),Domain.GreaterThan(0.0));
            M.Constraint("sell", Expr.Sub(z,Expr.Sub(x0,x)),Domain.GreaterThan(0.0));

            //M.constraint("trade", Expr.hstack(z.asExpr(),Expr.sub(x,x0)), Domain.inQcone())"

            // Consraints for turning y off and on. z-diag(u)*y<=0 i.e. z_j <= u_j*y_j
            M.Constraint("y_on_off", Expr.Sub(z,Expr.Mul(Matrix.Diag(u),y)), Domain.LessThan(0.0));

            // Integer optimization problems can be very hard to solve so limiting the 
            // maximum amount of time is a valuable safe guard
            M.SetSolverParam("mioMaxTime", 180.0);
            M.Solve();
            Console.WriteLine("Expected return: {0:e4} Std. deviation: {1:e4} Transactions cost: {2:e4}",
                   dot(mu, x.Level()), gamma, dot(f, y.Level()) + dot(g, z.Level()));
            return x.Level();
          }
        }
Exemple #10
0
        public static void Main(string [] args)
        {
            int n = 30;      //Number of tasks
            int m = 6;       //Number of processors

            double lb = 1.0; //The range of lengths of short tasks
            double ub = 5.0;

            double sh      = 0.8; //The proportion of short tasks
            int    n_short = (int)(n * sh);
            int    n_long  = n - n_short;

            double[] T   = new double[n];
            Random   gen = new Random(0);

            for (int i = 0; i < n_short; i++)
            {
                T[i] = gen.NextDouble() * (ub - lb) + lb;
            }
            for (int i = n_short; i < n; i++)
            {
                T[i] = 20 * (gen.NextDouble() * (ub - lb) + lb);
            }
            Array.Sort <double>(T);

            Model M = new Model("Multi-processor scheduling");

            Variable x = M.Variable("x", new int[] { m, n }, Domain.Binary());
            Variable t = M.Variable("t", 1, Domain.Unbounded());

            M.Constraint(Expr.Sum(x, 0), Domain.EqualsTo(1.0));
            M.Constraint(Expr.Sub(Var.Repeat(t, m), Expr.Mul(x, T)), Domain.GreaterThan(0.0));

            M.Objective(ObjectiveSense.Minimize, t);

            //Computing LPT solution
            double [] init     = new double[n * m];
            double [] schedule = new double[m];

            for (int i = n - 1; i >= 0; i--)
            {
                int next = 0;
                for (int j = 1; j < m; j++)
                {
                    if (schedule[j] < schedule[next])
                    {
                        next = j;
                    }
                }
                schedule[next]    += T[i];
                init[next * n + i] = 1;
            }

            //Comment this line to switch off feeding in the initial LPT solution
            x.SetLevel(init);

            M.SetLogHandler(Console.Out);

            M.SetSolverParam("mioTolRelGap", 0.01);
            M.Solve();

            try
            {
                Console.Write("initial solution: \n");
                for (int i = 0; i < m; i++)
                {
                    Console.Write("M {0} [", i);
                    for (int y = 0; y < n; y++)
                    {
                        Console.Write("{0}, ", (int)init[i * n + y]);
                    }
                    Console.Write("]\n");
                }
                Console.Write("MOSEK solution:\n");
                for (int i = 0; i < m; i++)
                {
                    Console.Write("M {0} [", i);
                    for (int y = 0; y < n; y++)
                    {
                        Console.Write("{0}, ", (int)x.Index(i, y).Level()[0]);
                    }
                    Console.Write("]\n");
                }
            }
            catch (SolutionError e) {}
        }