Exemplo n.º 1
0
        public static void Main(string[] args)
        {
            using (Model M = new Model())
            {
                double[] c = new double[] { 1.5, 2.5, 3.0 };
                double[,]  A = new double[, ] {
                    { 2, 4, 3 },
                    { 3, 2, 3 },
                    { 2, 3, 2 }
                };
                double[] b      = new double[] { 100000.0, 50000.0, 60000.0 };
                int      numvar = c.Length;
                int      numcon = b.Length;

                // Create a model and input data
                Variable   x   = M.Variable(numvar, Domain.GreaterThan(0.0));
                Constraint con = M.Constraint(Expr.Mul(A, x), Domain.LessThan(b));
                M.Objective(ObjectiveSense.Maximize, Expr.Dot(c, x));
                // Solve the problem
                M.Solve();
                printsol(x.Level());

                /************** Change an element of the A matrix ****************/
                con.Index(0).Update(Expr.Mul(3.0, x.Index(0)), x.Index(0));
                M.Solve();
                printsol(x.Level());

                /*************** Add a new variable ******************************/
                // Create a variable and a compound view of all variables
                Variable x3   = M.Variable(Domain.GreaterThan(0.0));
                Variable xNew = Var.Vstack(x, x3);
                // Add to the exising constraint
                con.Update(Expr.Mul(x3, new double[] { 4, 0, 1 }), x3);
                // Change the objective to include x3
                M.Objective(ObjectiveSense.Maximize, Expr.Dot(new double[] { 1.5, 2.5, 3.0, 1.0 }, xNew));
                M.Solve();
                printsol(xNew.Level());

                /**************** Add a new constraint *****************************/
                Constraint con2 = M.Constraint(Expr.Dot(xNew, new double[] { 1, 2, 1, 1 }), Domain.LessThan(30000.0));
                M.Solve();
                printsol(xNew.Level());

                /**************** Change constraint bounds *****************************/
                // Assemble all constraints we previously defined into one
                Constraint cAll = Constraint.Vstack(con, con2);
                // Change bounds by effectively updating fixed terms with the difference
                cAll.Update(new double[] { 20000, 10000, 10000, 8000 });
                M.Solve();
                printsol(xNew.Level());
            }
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            using (Model M = new Model("FacilityLocation"))
            {
                // Variable holding the facility location
                Variable f = M.Variable("facility", Set.Make(1, 2), Domain.Unbounded());
                // Variable defining the euclidian distances to each customer
                Variable d = M.Variable("dist", Set.Make(N, 1), Domain.GreaterThan(0.0));
                // Variable defining the x and y differences to each customer;
                Variable t = M.Variable("t", Set.Make(N, 2), Domain.Unbounded());
                M.Constraint("dist measure",
                             Var.Hstack(new Variable[] { d, t }),
                             Domain.InQCone(N, 3));

                Variable fxy = Var.Repeat(f, N);
                M.Constraint("xy diff", Expr.Add(t, fxy), Domain.EqualsTo(customerloc));

                M.Objective("total_dist", ObjectiveSense.Minimize, Expr.Sum(d));

                M.Solve();
                M.WriteTask("facility_location.task");
                double[] floc = f.Level();
                Console.WriteLine("Facility location = {0},{1}", floc[0], floc[1]);
            }
        }
Exemplo n.º 3
0
        public static void Main(String[] args)
        {
          using (Model M = new Model("alan"))
          {
            Variable x = M.Variable("x",        numsec, Domain.GreaterThan(0.0));
            Variable t = M.Variable("variance", Domain.GreaterThan(0.0));
            M.Objective("minvar", ObjectiveSense.Minimize, t.AsExpr());
            
            // sum securities to 1.0
            M.Constraint("wealth",  Expr.Sum(x), Domain.EqualsTo(1.0));
            // define target expected return 
            M.Constraint("dmean", Expr.Dot(mean, x), Domain.GreaterThan(target));
            
            M.Constraint(Expr.Vstack(Expr.ConstTerm(1,0.5),
                                     t.AsExpr(), 
                                     Expr.Mul(U,x)), 
                         Domain.InRotatedQCone());
            Console.WriteLine("Solve...");
            M.Solve();
            Console.WriteLine("... Solved.");
            double[] solx = x.Level();

            Console.WriteLine("Primal solution = {0}", solx[0]);
            for (int i = 1; i < numsec; ++i)
              Console.Write(", {0}", solx[i]);
            Console.WriteLine("");
          }
        }
Exemplo n.º 4
0
 public static void Main(string[] args)
 {
   Matrix recipe = new DenseMatrix(recipe_data);
   using (Model M = new Model("Recipe"))
   {
     // "production" defines the amount of each product to bake.
     Variable production = M.Variable("production", 
                                      new StringSet(productnames), 
                                      Domain.GreaterThan(0.0));
     // The objective is to maximize the total revenue.
     M.Objective("revenue",
                 ObjectiveSense.Maximize, 
                 Expr.Dot(revenue, production));
     
     // The prodoction is constrained by stock:
     M.Constraint(Expr.Mul(recipe, production), Domain.LessThan(stock));
     M.SetLogHandler(Console.Out);
   
     // We solve and fetch the solution:
     M.Solve();
     double[] res = production.Level();
     Console.WriteLine("Solution:");
     for (int i = 0; i < res.Length; ++i)
     {
       Console.WriteLine(" Number of {0} : {1}", productnames[i], res[i]);
     }
     Console.WriteLine(" Revenue : ${0}", 
                       res[0] * revenue[0] + res[1] * revenue[1]);
   }
 }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Missing argument, syntax is:");
                Console.WriteLine("   opt_server_sync host port");
                return;
            }

            String server = args[0];
            String port   = args[1];

            // Setup a simple test problem
            Model    M = new Model("testOptServer");
            Variable x = M.Variable("x", 3, Domain.GreaterThan(0.0));

            M.Constraint("lc", Expr.Dot(new double[] { 1.0, 1.0, 2.0 }, x), Domain.EqualsTo(1.0));
            M.Objective("obj", ObjectiveSense.Minimize, Expr.Sum(x));

            // Attach log handler
            M.SetLogHandler(Console.Out);

            // Solve the problem on the OptServer
            M.Solve(server, port);

            // Get the solution
            double[] solx = x.Level();
            Console.WriteLine("x1,x2,x3 = {0}, {1}, {2}", solx[0], solx[1], solx[2]);
        }
Exemplo n.º 6
0
        /*
         * Purpose:
         *  Computes the optimal portfolio for a given risk
         *
         * 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
         *
         * Output:
         *  Optimal expected return and the optimal portfolio
         */
        public static double BasicMarkowitz
            (int n,
            double[] mu,
            double[,] GT,
            double[] x0,
            double w,
            double gamma)
        {
            using (Model M = new Model("Basic Markowitz"))
            {
                // Redirect log output from the solver to stdout for debugging.
                // ifuncommented.
                //M.SetLogHandler(Console.Out);

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

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

                // The amount invested  must be identical to intial wealth
                M.Constraint("budget", Expr.Sum(x), Domain.EqualsTo(w + sum(x0)));
                // Imposes a bound on the risk
                M.Constraint("risk", Expr.Vstack(gamma, Expr.Mul(GT, x)), Domain.InQCone());
                // Solves the model.
                M.Solve();

                return(dot(mu, x.Level()));
            }
        }
Exemplo n.º 7
0
        public static void Main(string[] args)
        {
            Matrix recipe = Matrix.Dense(recipe_data);

            using (Model M = new Model("Recipe"))
            {
                // "production" defines the amount of each product to bake.
                Variable production = M.Variable("production",
                                                 new StringSet(productnames),
                                                 Domain.GreaterThan(0.0));
                // The objective is to maximize the total revenue.
                M.Objective("revenue",
                            ObjectiveSense.Maximize,
                            Expr.Dot(revenue, production));

                // The prodoction is constrained by stock:
                M.Constraint(Expr.Mul(recipe, production), Domain.LessThan(stock));
                M.SetLogHandler(Console.Out);

                // We solve and fetch the solution:
                M.Solve();
                double[] res = production.Level();
                Console.WriteLine("Solution:");
                for (int i = 0; i < res.Length; ++i)
                {
                    Console.WriteLine(" Number of {0} : {1}", productnames[i], res[i]);
                }
                Console.WriteLine(" Revenue : ${0}",
                                  res[0] * revenue[0] + res[1] * revenue[1]);
            }
        }
Exemplo n.º 8
0
                public static void Main(string[] argv)
                {
                    int N = 5;
                    var A = new double[][]
                    { new double[] { 0.0, 0.5, -0.1, -0.2, 0.5 },
                      new double[] { 0.5, 1.25, -0.05, -0.1, 0.25 },
                      new double[] { -0.1, -0.05, 0.51, 0.02, -0.05 },
                      new double[] { -0.2, -0.1, 0.02, 0.54, -0.1 },
                      new double[] { 0.5, 0.25, -0.05, -0.1, 1.25 } };

                    // Create a model with the name 'NearestCorrelation
                    using (var M = new Model("NearestCorrelation"))
                    {
                        // Setting up the variables
                        var X = M.Variable("X", Domain.InPSDCone(N));
                        var t = M.Variable("t", 1, Domain.Unbounded());

                        // (t, vec (A-X)) \in Q
                        M.Constraint(Expr.Vstack(t, Vec(Expr.Sub(new DenseMatrix(A), X))), Domain.InQCone());

                        // diag(X) = e
                        M.Constraint(X.Diag(), Domain.EqualsTo(1.0));

                        // Objective: Minimize t
                        M.Objective(ObjectiveSense.Minimize, t);

                        // Solve the problem
                        M.Solve();

                        // Get the solution values
                        Console.WriteLine("X = {0}", arrtostr(X.Level()));

                        Console.WriteLine("t = {0}", arrtostr(t.Level()));
                    }
                }
Exemplo n.º 9
0
                public static void Main(String[] args)
                {
                    using (Model M = new Model("alan"))
                    {
                        Variable x = M.Variable("x", numsec, Domain.GreaterThan(0.0));
                        Variable t = M.Variable("variance", Domain.GreaterThan(0.0));
                        M.Objective("minvar", ObjectiveSense.Minimize, t.AsExpr());

                        // sum securities to 1.0
                        M.Constraint("wealth", Expr.Sum(x), Domain.EqualsTo(1.0));
                        // define target expected return
                        M.Constraint("dmean", Expr.Dot(mean, x), Domain.GreaterThan(target));

                        M.Constraint(Expr.Vstack(Expr.ConstTerm(1, 0.5),
                                                 t.AsExpr(),
                                                 Expr.Mul(U, x)),
                                     Domain.InRotatedQCone());
                        Console.WriteLine("Solve...");
                        M.Solve();
                        Console.WriteLine("... Solved.");
                        double[] solx = x.Level();

                        Console.WriteLine("Primal solution = {0}", solx[0]);
                        for (int i = 1; i < numsec; ++i)
                        {
                            Console.Write(", {0}", solx[i]);
                        }
                        Console.WriteLine("");
                    }
                }
Exemplo n.º 10
0
        public static Tuple <double[], double[]> lownerjohn_inner(double[][] A, double[] b)
        {
            using (Model M = new Model("lownerjohn_inner"))
            {
                int m = A.Length;
                int n = A[0].Length;

                // Setup variables
                Variable t = M.Variable("t", 1, Domain.GreaterThan(0.0));
                Variable C = det_rootn(M, t, n);
                Variable d = M.Variable("d", n, Domain.Unbounded());

                // (bi - ai^T*d, C*ai) \in Q
                for (int i = 0; i < m; ++i)
                {
                    M.Constraint("qc" + i, Expr.Vstack(Expr.Sub(b[i], Expr.Dot(A[i], d)), Expr.Mul(C, A[i])),
                                 Domain.InQCone().Axis(0));
                }

                // Objective: Maximize t
                M.Objective(ObjectiveSense.Maximize, t);
                M.Solve();
                M.WriteTask("LownerJohnInner.ptf");

                return(Tuple.Create(C.Level(), d.Level()));
            }
        }
Exemplo n.º 11
0
        public static void Main(string[] args)
        {
          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  };

          // Create a model with the name 'lo1'
          Model M = new Model("lo1");
            
          // Create variable 'x' of length 3
          Variable x = M.Variable("x", 3, Domain.GreaterThan(0.0));
          // Create variable 'y' of length 1
          Variable y = M.Variable("y", 1, Domain.InRange(0.0, 10.0));
          // Create a variable vector consisting of x and y
          Variable z = Variable.Vstack(x,y);
            
          // Create three constraints
          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));
            
          // Set the objective function to (c^t * x)
          M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(c, z));
                  
          // Solve the problem
          M.Solve();
            
          // Get the solution values
          double[] sol = z.Level();
          Console.WriteLine("x1,x2,x3,y = {0}, {1}, {2}, {3}",sol[0],sol[1],sol[2],sol[3]);
        }
Exemplo n.º 12
0
        public static void Main(string[] argv)
        {
          int N = 5;
          var A = new double[][]
              { new double[] { 0.0,  0.5,  -0.1,  -0.2,   0.5},
                new double[] { 0.5,  1.25, -0.05, -0.1,   0.25},
                new double[] {-0.1, -0.05,  0.51,  0.02, -0.05},
                new double[] {-0.2, -0.1,   0.02,  0.54, -0.1},
                new double[] { 0.5,  0.25, -0.05, -0.1,   1.25} };

          // Create a model with the name 'NearestCorrelation
          using (var M = new Model("NearestCorrelation"))
          {
            // Setting up the variables
            var X = M.Variable("X", Domain.InPSDCone(N));
            var t = M.Variable("t", 1, Domain.Unbounded());

            // (t, vec (A-X)) \in Q
            M.Constraint( Expr.Vstack(t, Vec(Expr.Sub(new DenseMatrix(A),X))), Domain.InQCone() );

            // diag(X) = e
            M.Constraint(X.Diag(), Domain.EqualsTo(1.0));

            // Objective: Minimize t
            M.Objective(ObjectiveSense.Minimize, t);
                              
            // Solve the problem
            M.Solve();

            // Get the solution values
            Console.WriteLine("X = {0}",arrtostr(X.Level()));
            
            Console.WriteLine("t = {0}", arrtostr(t.Level()));
          } 
        }
Exemplo n.º 13
0
        public static void nearestcorr_frobenius(Matrix A)
        {
            int N = A.NumRows();

            using (var M = new Model("NearestCorrelation"))
            {
                // Setting up the variables
                var X = M.Variable("X", Domain.InPSDCone(N));
                var t = M.Variable("t", 1, Domain.Unbounded());

                // (t, vec (A-X)) \in Q
                M.Constraint(Expr.Vstack(t, Vec(Expr.Sub(A, X))), Domain.InQCone());

                // diag(X) = e
                M.Constraint(X.Diag(), Domain.EqualsTo(1.0));

                // Objective: Minimize t
                M.Objective(ObjectiveSense.Minimize, t);

                // Solve the problem
                M.Solve();

                // Get the solution values
                Console.WriteLine("X = \n{0}", mattostr(X.Level(), N));
                Console.WriteLine("t = {0}", mattostr(t.Level(), N));
            }
        }
Exemplo n.º 14
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"));
      }
    }
Exemplo n.º 15
0
        // maximize     h*w*d
        // subjecto to  2*(h*w + h*d) <= Awall
        //              w*d <= Afloor
        //              alpha <= h/w <= beta
        //              gamma <= d/w <= delta
        //
        // Variable substitutions:  h = exp(x), w = exp(y), d = exp(z).
        //
        // maximize     x+y+z
        // subject      log( exp(x+y+log(2/Awall)) + exp(x+z+log(2/Awall)) ) <= 0
        //                              y+z <= log(Afloor)
        //              log( alpha ) <= x-y <= log( beta )
        //              log( gamma ) <= z-y <= log( delta )
        public static double[] max_volume_box(double Aw, double Af,
                                              double alpha, double beta, double gamma, double delta)
        {
            using (Model M = new Model("max_vol_box"))
            {
                Variable xyz = M.Variable(3);
                M.Objective("Objective", ObjectiveSense.Maximize, Expr.Sum(xyz));

                logsumexp(M,
                          new double[, ] {
                    { 1, 1, 0 }, { 1, 0, 1 }
                },
                          xyz,
                          new double[] { System.Math.Log(2.0 / Aw), System.Math.Log(2.0 / Aw) });

                M.Constraint(Expr.Dot(new double[] { 0, 1, 1 }, xyz), Domain.LessThan(System.Math.Log(Af)));
                M.Constraint(Expr.Dot(new double[] { 1, -1, 0 }, xyz), Domain.InRange(System.Math.Log(alpha), System.Math.Log(beta)));
                M.Constraint(Expr.Dot(new double[] { 0, -1, 1 }, xyz), Domain.InRange(System.Math.Log(gamma), System.Math.Log(delta)));

                M.SetLogHandler(Console.Out);
                M.Solve();

                double[] xyzVal = xyz.Level();
                double[] hwdVal = new double[3];
                for (int i = 0; i < 3; i++)
                {
                    hwdVal[i] = System.Math.Exp(xyzVal[i]);
                }

                return(hwdVal);
            }
        }
Exemplo n.º 16
0
        public static void Main(string[] args)
        {
            using (Model M = new Model("pow1"))
            {
                Variable x  = M.Variable("x", 3, Domain.Unbounded());
                Variable x3 = M.Variable();
                Variable x4 = M.Variable();

                // Create the linear constraint
                double[] aval = new double[] { 1.0, 1.0, 0.5 };
                M.Constraint(Expr.Dot(x, aval), Domain.EqualsTo(2.0));

                // Create the exponential conic constraint
                // Create the conic constraints
                M.Constraint(Var.Vstack(x.Slice(0, 2), x3), Domain.InPPowerCone(0.2));
                M.Constraint(Expr.Vstack(x.Index(2), 1.0, x4), Domain.InPPowerCone(0.4));

                // Set the objective function
                double[] cval = new double[] { 1.0, 1.0, -1.0 };
                M.Objective(ObjectiveSense.Maximize, Expr.Dot(cval, Var.Vstack(x3, x4, x.Index(0))));

                // Solve the problem
                M.Solve();

                // Get the linear solution values
                double[] solx = x.Level();
                Console.WriteLine("x,y,z = {0}, {1}, {2}", solx[0], solx[1], solx[2]);
            }
        }
Exemplo n.º 17
0
                public static void Main(string[] args)
                {
                    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 };

                    // Create a model with the name 'lo1'
                    Model M = new Model("lo1");

                    // Create variable 'x' of length 3
                    Variable x = M.Variable("x", 3, Domain.GreaterThan(0.0));
                    // Create variable 'y' of length 1
                    Variable y = M.Variable("y", 1, Domain.InRange(0.0, 10.0));
                    // Create a variable vector consisting of x and y
                    Variable z = Variable.Vstack(x, y);

                    // Create three constraints
                    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));

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

                    // Solve the problem
                    M.Solve();

                    // Get the solution values
                    double[] sol = z.Level();
                    Console.WriteLine("x1,x2,x3,y = {0}, {1}, {2}, {3}", sol[0], sol[1], sol[2], sol[3]);
                }
Exemplo n.º 18
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"));
            }
        }
Exemplo n.º 19
0
        // Model logistic regression (regularized with full 2-norm of theta)
        // X - n x d matrix of data points
        // y - length n vector classifying training points
        // lamb - regularization parameter
        public static Model logisticRegression(double[,]  X,
                                               bool[]     y,
                                               double lamb)
        {
            int n = X.GetLength(0);
            int d = X.GetLength(1); // num samples, dimension

            Model M = new Model();

            Variable theta = M.Variable("theta", d);
            Variable t     = M.Variable(n);
            Variable reg   = M.Variable();

            M.Objective(ObjectiveSense.Minimize, Expr.Add(Expr.Sum(t), Expr.Mul(lamb, reg)));
            M.Constraint(Var.Vstack(reg, theta), Domain.InQCone());

            double[] signs = new double[n];
            for (int i = 0; i < n; i++)
            {
                if (y[i])
                {
                    signs[i] = -1;
                }
                else
                {
                    signs[i] = 1;
                }
            }

            softplus(M, t, Expr.MulElm(Expr.Mul(X, theta), signs));

            return(M);
        }
Exemplo n.º 20
0
 public static void Main(string[] args)
 {
   using (Model M  = new Model("sdo1"))
   {
     // Setting up the variables
     Variable X  = M.Variable("X", Domain.InPSDCone(3));
     Variable x  = M.Variable("x", Domain.InQCone(3));
     
     DenseMatrix C  = new DenseMatrix ( new double[][] { new double[] {2,1,0}, new double[] {1,2,1}, new double[] {0,1,2}} );
     DenseMatrix A1 = new DenseMatrix ( new double[][] { new double[] {1,0,0}, new double[] {0,1,0}, new double[] {0,0,1}} );
     DenseMatrix A2 = new DenseMatrix ( new double[][] { new double[] {1,1,1}, new double[] {1,1,1}, new double[] {1,1,1}} );
     
     // Objective
     M.Objective(ObjectiveSense.Minimize, Expr.Add(Expr.Dot(C, X), x.Index(0)));
     
     // Constraints
     M.Constraint("c1", Expr.Add(Expr.Dot(A1, X), x.Index(0)), Domain.EqualsTo(1.0));
     M.Constraint("c2", Expr.Add(Expr.Dot(A2, X), Expr.Sum(x.Slice(1,3))), Domain.EqualsTo(0.5));
     
     M.Solve();
     
     Console.WriteLine("[{0}]", (new Utils.StringBuffer()).A(X.Level()).ToString());
     Console.WriteLine("[{0}]", (new Utils.StringBuffer()).A(x.Level()).ToString());
   }
 }
Exemplo n.º 21
0
                public static void Main(string[] args)
                {
                    using (Model M = new Model("sdo1"))
                    {
                        // Setting up the variables
                        Variable X = M.Variable("X", Domain.InPSDCone(3));
                        Variable x = M.Variable("x", Domain.InQCone(3));

                        DenseMatrix C  = new DenseMatrix(new double[][] { new double[] { 2, 1, 0 }, new double[] { 1, 2, 1 }, new double[] { 0, 1, 2 } });
                        DenseMatrix A1 = new DenseMatrix(new double[][] { new double[] { 1, 0, 0 }, new double[] { 0, 1, 0 }, new double[] { 0, 0, 1 } });
                        DenseMatrix A2 = new DenseMatrix(new double[][] { new double[] { 1, 1, 1 }, new double[] { 1, 1, 1 }, new double[] { 1, 1, 1 } });

                        // Objective
                        M.Objective(ObjectiveSense.Minimize, Expr.Add(Expr.Dot(C, X), x.Index(0)));

                        // Constraints
                        M.Constraint("c1", Expr.Add(Expr.Dot(A1, X), x.Index(0)), Domain.EqualsTo(1.0));
                        M.Constraint("c2", Expr.Add(Expr.Dot(A2, X), Expr.Sum(x.Slice(1, 3))), Domain.EqualsTo(0.5));

                        M.Solve();

                        Console.WriteLine("[{0}]", (new Utils.StringBuffer()).A(X.Level()).ToString());
                        Console.WriteLine("[{0}]", (new Utils.StringBuffer()).A(x.Level()).ToString());
                    }
                }
Exemplo n.º 22
0
        public static Tuple <double[], double[]> lownerjohn_outer(double[][] x)
        {
            using (Model M = new Model("lownerjohn_outer"))
            {
                int m = x.Length;
                int n = x[0].Length;

                // Setup variables
                Variable t = M.Variable("t", 1, Domain.GreaterThan(0.0));
                Variable P = det_rootn(M, t, n);
                Variable c = M.Variable("c", n, Domain.Unbounded());

                // (1, P(*xi+c)) \in Q
                for (int i = 0; i < m; ++i)
                {
                    M.Constraint("qc" + i, Expr.Vstack(Expr.Ones(1), Expr.Sub(Expr.Mul(P, x[i]), c)),
                                 Domain.InQCone().Axis(0));
                }

                // Objective: Maximize t
                M.Objective(ObjectiveSense.Maximize, t);
                M.Solve();
                M.WriteTask("LownerJohnOuter.ptf");

                return(Tuple.Create(P.Level(), c.Level()));
            }
        }
Exemplo n.º 23
0
        public static void Main(string[] args)
        {
            double[][] A =
            { new double[] { 3.0, 1.0, 2.0, 0.0 },
              new double[]       { 2.0, 1.0, 3.0, 1.0 },
              new double[]       { 0.0, 2.0, 0.0, 3.0 } };
            double[] c = { 3.0, 1.0, 5.0, 1.0 };

            // Create a model with the name 'lo1'
            Model M = new Model("lo1");

            // Create variable 'x' of length 4
            Variable x = M.Variable("x", 4, Domain.GreaterThan(0.0));

            // Create constraints
            M.Constraint(x.Index(1), Domain.LessThan(10.0));
            M.Constraint("c1", Expr.Dot(A[0], x), Domain.EqualsTo(30.0));
            M.Constraint("c2", Expr.Dot(A[1], x), Domain.GreaterThan(15.0));
            M.Constraint("c3", Expr.Dot(A[2], x), Domain.LessThan(25.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("[x0,x1,x2,x3] = [{0}, {1}, {2}, {3} ]", sol[0], sol[1], sol[2], sol[3]);
        }
Exemplo n.º 24
0
                public static void Main(string[] args)
                {
                    using (Model M = new Model("cqo1"))
                    {
                        Variable x = M.Variable("x", 3, Domain.GreaterThan(0.0));
                        Variable y = M.Variable("y", 3, Domain.Unbounded());

                        // Create the aliases
                        //      z1 = [ y[0],x[0],x[1] ]
                        //  and z2 = [ y[1],y[2],x[2] ]
                        Variable z1 = Variable.Vstack(y.Index(0), x.Slice(0, 2));
                        Variable z2 = Variable.Vstack(y.Slice(1, 3), x.Index(2));

                        // Create the constraint
                        //      x[0] + x[1] + 2.0 x[2] = 1.0
                        double[] aval = new double[] { 1.0, 1.0, 2.0 };
                        M.Constraint("lc", Expr.Dot(aval, x), Domain.EqualsTo(1.0));

                        // Create the constraints
                        //      z1 belongs to C_3
                        //      z2 belongs to K_3
                        // where C_3 and K_3 are respectively the quadratic and
                        // rotated quadratic cone of size 3, i.e.
                        //                 z1[0] > sqrt(z1[1]^2 + z1[2]^2)
                        //  and  2.0 z2[0] z2[1] > z2[2]^2
                        Constraint qc1 = M.Constraint("qc1", z1.AsExpr(), Domain.InQCone());
                        Constraint qc2 = M.Constraint("qc2", z2.AsExpr(), Domain.InRotatedQCone());

                        // Set the objective function to (y[0] + y[1] + y[2])
                        M.Objective("obj", ObjectiveSense.Minimize, Expr.Sum(y));

                        // Solve the problem
                        M.Solve();

                        // Get the linearsolution values
                        double[] solx = x.Level();
                        double[] soly = y.Level();

                        Console.WriteLine("x1,x2,x3 = {0}, {1}, {2}", solx[0], solx[1], solx[2]);
                        Console.WriteLine("y1,y2,y3 = {0}, {1}, {2}", soly[0], soly[1], soly[2]);
                        // Get conic solution of qc1
                        double[] qc1lvl = qc1.Level();
                        double[] qc1sn  = qc1.Dual();

                        Console.Write("qc1 levels = {0}", qc1lvl[0]);
                        for (int i = 1; i < qc1lvl.Length; ++i)
                        {
                            Console.Write(", {0}", qc1lvl[i]);
                        }
                        Console.WriteLine();

                        Console.Write("qc1 dual conic var levels = {0}", qc1sn[0]);
                        for (int i = 1; i < qc1sn.Length; ++i)
                        {
                            Console.Write(", {0}", qc1sn[i]);
                        }
                        Console.WriteLine();
                    }
                }
Exemplo n.º 25
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());
            }
        }
Exemplo n.º 26
0
                //TAG:begin-nearestcorr-nucnorm-code
                public static void nearestcorr_nn(Matrix A, double[] gammas, double[] res, int[] rank)
                {
                    int N = A.NumRows();

                    using (var M = new Model("NucNorm"))
                    {
                        // Setup variables
                        var t = M.Variable("t", 1, Domain.Unbounded());
                        var X = M.Variable("X", Domain.InPSDCone(N));
                        var w = M.Variable("w", N, Domain.GreaterThan(0.0));

                        // (t, vec (X + diag(w) - A)) in Q
                        var D = Expr.MulElm(Matrix.Eye(N), Var.Repeat(w, 1, N));

                        M.Constraint(Expr.Vstack(t, Vec(Expr.Sub(Expr.Add(X, D), A))), Domain.InQCone());

                        //M.SetLogHandler(Console.Out);

                        var d = new double[N];
                        for (var k = 0; k < gammas.Length; ++k)
                        {
                            // Objective: Minimize t + gamma*Tr(X)
                            var gamm_trX = Expr.Mul(gammas[k], Expr.Sum(X.Diag()));
                            M.Objective(ObjectiveSense.Minimize, Expr.Add(t, gamm_trX));
                            M.Solve();

                            var Xl = X.Level();
                            var wl = w.Level();


                            var r_sqr = 0.0;
                            for (var j = 0; j < N; ++j)
                            {
                                for (var i = j + 1; i < N; ++i)
                                {
                                    r_sqr += 2 * (A.Get(j, i) - Xl[i + j * N]) * (A.Get(j, i) - Xl[i + j * N]);
                                }
                            }
                            for (var i = 0; i < N; ++i)
                            {
                                r_sqr += (A.Get(i, i) - Xl[i + i * N] - wl[i]) * (A.Get(i, i) - Xl[i + i * N] - wl[i]);
                            }

                            mosek.LinAlg.syeig(mosek.uplo.lo, N, X.Level(), d);

                            var rnk = 0; foreach (var v in d)
                            {
                                if (v > 1e-6)
                                {
                                    ++rnk;
                                }
                            }

                            res[k]  = Math.Sqrt(r_sqr);
                            rank[k] = rnk;
                        }
                    }
                }
Exemplo n.º 27
0
        public static void Main(string[] args)
        {
            using (Model M = new Model())
            {
                double[] c = new double[] { 1.5, 2.5, 3.0 };
                double[,]  A = new double[, ] {
                    { 2, 4, 3 },
                    { 3, 2, 3 },
                    { 2, 3, 2 }
                };
                double[] b      = new double[] { 100000.0, 50000.0, 60000.0 };
                int      numvar = c.Length;
                int      numcon = b.Length;

                // Create a model and input data
                Variable   x   = M.Variable(numvar, Domain.GreaterThan(0.0));
                Constraint con = M.Constraint(Expr.Mul(A, x), Domain.LessThan(b));
                M.Objective(ObjectiveSense.Maximize, Expr.Dot(c, x));
                // Solve the problem
                M.Solve();
                printsol(x.Level());

                /************** Change an element of the A matrix ****************/
                con.Index(0).Add(x.Index(0));
                M.Solve();
                printsol(x.Level());

                /*************** Add a new variable ******************************/
                // Create a variable and a compound view of all variables
                Variable x3   = M.Variable(Domain.GreaterThan(0.0));
                Variable xNew = Var.Vstack(x, x3);
                // Add to the exising constraint
                con.Add(Expr.Mul(x3, new double[] { 4, 0, 1 }));
                // Change the objective to include x3
                M.Objective(ObjectiveSense.Maximize, Expr.Dot(new double[] { 1.5, 2.5, 3.0, 1.0 }, xNew));
                M.Solve();
                printsol(xNew.Level());

                /**************** Add a new constraint *****************************/
                M.Constraint(Expr.Dot(xNew, new double[] { 1, 2, 1, 1 }), Domain.LessThan(30000.0));
                M.Solve();
                printsol(xNew.Level());
            }
        }
Exemplo n.º 28
0
 public static void Main(string[] args)
 {
   using (Model M = new Model("cqo1"))
   {
           
     Variable x = M.Variable("x", 3, Domain.GreaterThan(0.0));
     Variable y = M.Variable("y", 3, Domain.Unbounded());
           
     // Create the aliases 
     //      z1 = [ y[0],x[0],x[1] ]
     //  and z2 = [ y[1],y[2],x[2] ]
     Variable z1 = Variable.Vstack(y.Index(0),  x.Slice(0,2));
     Variable z2 = Variable.Vstack(y.Slice(1,3),x.Index(2));
         
     // Create the constraint
     //      x[0] + x[1] + 2.0 x[2] = 1.0
     double[] aval = new double[] {1.0, 1.0, 2.0};
     M.Constraint("lc", Expr.Dot(aval, x), Domain.EqualsTo(1.0));
         
     // Create the constraints
     //      z1 belongs to C_3
     //      z2 belongs to K_3
     // where C_3 and K_3 are respectively the quadratic and
     // rotated quadratic cone of size 3, i.e.
     //                 z1[0] > sqrt(z1[1]^2 + z1[2]^2)
     //  and  2.0 z2[0] z2[1] > z2[2]^2
     Constraint qc1 = M.Constraint("qc1", z1.AsExpr(), Domain.InQCone());
     Constraint qc2 = M.Constraint("qc2", z2.AsExpr(), Domain.InRotatedQCone());
         
     // Set the objective function to (y[0] + y[1] + y[2])
     M.Objective("obj", ObjectiveSense.Minimize, Expr.Sum(y));
         
     // Solve the problem
     M.Solve();
         
     // Get the linearsolution values
     double[] solx = x.Level();
     double[] soly = y.Level();
         
     Console.WriteLine("x1,x2,x3 = {0}, {1}, {2}",solx[0],solx[1],solx[2]);
     Console.WriteLine("y1,y2,y3 = {0}, {1}, {2}",soly[0],soly[1],soly[2]);
     // Get conic solution of qc1
     double[] qc1lvl = qc1.Level();
     double[] qc1sn  = qc1.Dual();
                 
     Console.Write("qc1 levels = {0}", qc1lvl[0]);
     for (int i = 1; i < qc1lvl.Length; ++i)
       Console.Write(", {0}", qc1lvl[i]);
     Console.WriteLine();
         
     Console.Write("qc1 dual conic var levels = {0}", qc1sn[0]);
     for (int i = 1; i < qc1sn.Length; ++i)
       Console.Write(", {0}", qc1sn[i]);
     Console.WriteLine();
   }
 }
Exemplo n.º 29
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();
                }
Exemplo n.º 30
0
        public static void Main(string[] args)
        {
            long timeout = 5;

            int    n = 200;   // number of binary variables
            int    m = n / 5; // number of constraints
            int    p = n / 5; // Each constraint picks p variables and requires that half of them are 1
            Random R = new Random(1234);

            using (Model M = new Model("SolveBinary"))
            {
                M.SetLogHandler(System.Console.Out);

                //Variable x = M.Variable("x", n, Domain.InRange(0,1));
                Variable x = M.Variable("x", n, Domain.Binary());
                M.Objective(ObjectiveSense.Minimize, Expr.Sum(x));
                //M.SetSolverParam("numThreads",1);

                int[] idxs = new int[n]; for (int i = 0; i < n; ++i)
                {
                    idxs[i] = i;
                }
                int[] cidxs = new int[p];

                for (var i = 0; i < m; ++i)
                {
                    nshuffle(R, idxs, p);
                    Array.Copy(idxs, cidxs, p);
                    M.Constraint(Expr.Sum(x.Pick(cidxs)), Domain.EqualsTo(p / 2));
                }

                var T = new Thread(new ThreadStart(M.Solve));
                T.Start();

                Stopwatch w = new Stopwatch(); w.Start();
                while (true)
                {
                    if (w.ElapsedMilliseconds > timeout * 1000)
                    {
                        Console.WriteLine("Solver terminated due to timeout!");
                        M.BreakSolver();
                        T.Join();
                        break;
                    }
                    if (!T.IsAlive)
                    {
                        Console.WriteLine("Solver terminated before anything happened!");
                        T.Join();
                        break;
                    }
                }

                Console.WriteLine("End.");
            }
        }
Exemplo n.º 31
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
                 *      m: It is assumed that  market impact cost for the j'th asset is
                 *         m_j|x_j-x0_j|^3/2
                 *
                 *  Output:
                 *     Optimal expected return and the optimal portfolio
                 *
                 */
                public static void MarkowitzWithMarketImpact
                    (int n,
                    double[] mu,
                    DenseMatrix GT,
                    double[] x0,
                    double w,
                    double gamma,
                    double[] m,

                    double[] xsol,
                    double[] tsol)
                {
                    using (Model M = new Model("Markowitz portfolio with market impact"))
                    {
                        //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 t = M.Variable("t", n, Domain.Unbounded());
                        Variable z = M.Variable("z", n, Domain.Unbounded());
                        Variable v = M.Variable("v", n, Domain.Unbounded());

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

                        // Invested amount + slippage cost = initial wealth
                        M.Constraint("budget", Expr.Add(Expr.Sum(x), Expr.Dot(m, t)), 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));

                        // t >= z^1.5, z >= 0.0. Needs two rotated quadratic cones to model this term
                        M.Constraint("ta", Expr.Hstack(v.AsExpr(), t.AsExpr(), z.AsExpr()), Domain.InRotatedQCone());

                        M.Constraint("tb", Expr.Hstack(z.AsExpr(), Expr.ConstTerm(n, 1.0 / 8.0), v.AsExpr()),
                                     Domain.InRotatedQCone());
                        M.Solve();

                        if (xsol != null)
                        {
                            Array.Copy(x.Level(), xsol, n);
                        }
                        if (tsol != null)
                        {
                            Array.Copy(t.Level(), tsol, n);
                        }
                    }
                }
Exemplo n.º 32
0
        public static void Main(string[] args)
        {
            int    ncols  = 50;
            int    nrows  = 50;
            int    seed   = 0;
            double sigma  = 1.0;
            int    ncells = nrows * ncols;
            Random gen    = new Random(seed);

            double[] f = new double[ncells];

            //Random signal with Gaussian noise
            for (int i = 0; i < ncells; i++)
            {
                double xx = Math.Sqrt(-2.0 * Math.Log(gen.NextDouble()));
                double yy = Math.Sin(2.0 * Math.PI * gen.NextDouble());
                f[i] = Math.Max(Math.Min(1.0, xx * yy), .0);
            }


            Model M = new Model("TV");

            try
            {
                Variable u = M.Variable(new int[] { nrows + 1, ncols + 1 },
                                        Domain.InRange(0.0, 1.0));
                Variable t = M.Variable(new int[] { nrows, ncols }, Domain.Unbounded());

                Variable ucore = u.Slice(new int[] { 0, 0 }, new int[] { nrows, ncols });

                Expression deltax = Expr.Sub(u.Slice(new int[] { 1, 0 },
                                                     new int[] { nrows + 1, ncols }),
                                             ucore);
                Expression deltay = Expr.Sub(u.Slice(new int[] { 0, 1 },
                                                     new int[] { nrows, ncols + 1 }),
                                             ucore);

                M.Constraint(Expr.Stack(2, t, deltax, deltay), Domain.InQCone().Axis(2));

                Matrix mat_f = Matrix.Dense(nrows, ncols, f);
                M.Constraint(Expr.Vstack(sigma, Expr.Flatten(Expr.Sub(ucore, mat_f))),
                             Domain.InQCone());

                M.SetLogHandler(Console.Out);

                M.Objective(ObjectiveSense.Minimize, Expr.Sum(t));

                M.Solve();
            }
            finally
            {
                M.Dispose();
            }
        }
Exemplo n.º 33
0
        // A direct integer model for minimizing |Ax-b|
        public static Model int_least_squares(int n, Matrix A, double[] b)
        {
            Model M = new Model();

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

            M.Constraint(Expr.Vstack(t, Expr.Sub(Expr.Mul(A, x), b)), Domain.InQCone());
            M.Objective(ObjectiveSense.Minimize, t);

            return(M);
        }
Exemplo n.º 34
0
        // Set up a small artificial conic problem to test with
        public static void SetupExample(Model M)
        {
            Variable x  = M.Variable("x", 3, Domain.GreaterThan(0.0));
            Variable y  = M.Variable("y", 3, Domain.Unbounded());
            Variable z1 = Var.Vstack(y.Index(0), x.Slice(0, 2));
            Variable z2 = Var.Vstack(y.Slice(1, 3), x.Index(2));

            M.Constraint("lc", Expr.Dot(new double[] { 1.0, 1.0, 2.0 }, x), Domain.EqualsTo(1.0));
            M.Constraint("qc1", z1, Domain.InQCone());
            M.Constraint("qc2", z2, Domain.InRotatedQCone());
            M.Objective("obj", ObjectiveSense.Minimize, Expr.Sum(y));
        }
Exemplo n.º 35
0
        public static void Main(string[] args)
        {
            // Sample data in sparse, symmetric triplet format
            int[]    C1_k = { 0, 2 };
            int[]    C1_l = { 0, 2 };
            double[] C1_v = { 1, 6 };
            int[]    A1_k = { 0, 2, 0, 2 };
            int[]    A1_l = { 0, 0, 2, 2 };
            double[] A1_v = { 1, 1, 1, 2 };
            int[]    C2_k = { 0, 1, 0, 1, 2 };
            int[]    C2_l = { 0, 0, 1, 1, 2 };
            double[] C2_v = { 1, -3, -3, 2, 1 };
            int[]    A2_k = { 1, 0, 1, 3 };
            int[]    A2_l = { 0, 1, 1, 3 };
            double[] A2_v = { 1, 1, -1, -3 };
            double   b    = 23;
            double   k    = -3;

            // Convert input data into Fusion sparse matrices
            Matrix C1 = Matrix.Sparse(3, 3, C1_k, C1_l, C1_v);
            Matrix C2 = Matrix.Sparse(4, 4, C2_k, C2_l, C2_v);
            Matrix A1 = Matrix.Sparse(3, 3, A1_k, A1_l, A1_v);
            Matrix A2 = Matrix.Sparse(4, 4, A2_k, A2_l, A2_v);

            using (Model M = new Model("sdo2"))
            {
                // Two semidefinite variables
                Variable X1 = M.Variable(Domain.InPSDCone(3));
                Variable X2 = M.Variable(Domain.InPSDCone(4));

                // Objective
                M.Objective(ObjectiveSense.Minimize, Expr.Add(Expr.Dot(C1, X1), Expr.Dot(C2, X2)));

                // Equality constraint
                M.Constraint(Expr.Add(Expr.Dot(A1, X1), Expr.Dot(A2, X2)), Domain.EqualsTo(b));

                // Inequality constraint
                M.Constraint(X2.Index(new int[] { 0, 1 }), Domain.LessThan(k));

                // Solve
                M.SetLogHandler(Console.Out);
                M.Solve();

                // Print solution
                Console.WriteLine("Solution (vectorized):");
                Console.WriteLine("[{0}]", (new Utils.StringBuffer()).A(X1.Level()).ToString());
                Console.WriteLine("[{0}]", (new Utils.StringBuffer()).A(X2.Level()).ToString());
            }
        }
Exemplo n.º 36
0
        public static double[] fitpoly(double[,] data, int n)
        {
            using (var M = new Model("smooth poly"))
            {
                int      m     = data.GetLength(0);
                double[] Adata = new double[m * (n + 1)];
                for (int j = 0, k = 0; j < m; ++j)
                {
                    for (int i = 0; i < n + 1; ++i, ++k)
                    {
                        Adata[k] = Math.Pow(data[j, 0], i);
                    }
                }

                Matrix   A = Matrix.Dense(m, n + 1, Adata);
                double[] b = new double[m];
                for (int j = 0; j < m; ++j)
                {
                    b[j] = data[j, 1];
                }

                Variable x  = M.Variable("x", n + 1, Domain.Unbounded());
                Variable z  = M.Variable("z", 1, Domain.Unbounded());
                Variable dx = diff(M, x);

                M.Constraint(Expr.Mul(A, x), Domain.EqualsTo(b));

                // z - f'(t) >= 0, for all t \in [a, b]
                Variable ub = M.Variable(n, Domain.Unbounded());
                M.Constraint(Expr.Sub(ub,
                                      Expr.Vstack(Expr.Sub(z, dx.Index(0)), Expr.Neg(dx.Slice(1, n)))),
                             Domain.EqualsTo(0.0));
                nn_finite(M, ub, data[0, 0], data[m - 1, 0]);

                // f'(t) + z >= 0, for all t \in [a, b]
                Variable lb = M.Variable(n, Domain.Unbounded());
                M.Constraint(Expr.Sub(lb,
                                      Expr.Vstack(Expr.Add(z, dx.Index(0)), dx.Slice(1, n).AsExpr())),
                             Domain.EqualsTo(0.0));
                nn_finite(M, lb, data[0, 0], data[m - 1, 0]);

                M.Objective(ObjectiveSense.Minimize, z);
                M.Solve();
                return(x.Level());
            }
        }
Exemplo n.º 37
0
        // A sample problem using functions from the library
        //
        // max -sqrt(x^2 + y^2) + log(y) - x^1.5
        //  st x >= y + 3
        //
        public static void testExample()
        {
            Model    M = new Model();
            Variable x = M.Variable();
            Variable y = M.Variable();
            Variable t = M.Variable(3);

            M.Constraint(Expr.Sub(x, y), Domain.GreaterThan(3.0));
            norm2(M, t.Index(0), Var.Vstack(x, y));
            log(M, t.Index(1), y);
            pow(M, t.Index(2), x, 1.5);

            M.Objective(ObjectiveSense.Maximize, Expr.Dot(t, new double[] { -1, 1, -1 }));

            M.SetLogHandler(Console.Out);
            M.Solve();
        }
Exemplo n.º 38
0
          public static void Main(string[] args) 
          {
              double[][] A =  new double[][] { new double[] { -0.5, 1.0 }  };
              double[]   b =  new double[] { 1.0 };
              double[]   c =  new double[] { 1.0, 1.0 };

              using (Model M = new Model("duality"))
              {
                Variable x = M.Variable("x", 2, Domain.GreaterThan(0.0));

                Constraint con = M.Constraint(Expr.Sub(b, Expr.Mul(new DenseMatrix(A), x)), Domain.EqualsTo(0.0));

                M.Objective("obj", ObjectiveSense.Minimize, Expr.Dot(c, x));

                M.Solve();
                double[] xsol = x.Level();
                double[] ysol = con.Dual();

                Console.WriteLine("x1,x2,y = {0}, {1}, {2}\n",xsol[0],xsol[1],ysol[0]);
              }
          }
Exemplo n.º 39
0
   public static void Main(string[] args)
   {
     // Create a model object
     using (Model M = new Model("simple"))
     {
 
       // Add two variables
       Variable x = M.Variable("x",1,Domain.InRange(0.0,1.0));
       Variable y = M.Variable("y",1,Domain.Unbounded());
   
       // Add a constraint on the variables
       M.Constraint("bound y", Expr.Sub(y,x), Domain.InRange(-1.0, 2.0));
   
       // Define the objective
       M.Objective("obj", ObjectiveSense.Maximize, Expr.Add(x,y));
   
       // Solve the problem
       M.Solve();
   
       // Print the solution
       Console.WriteLine("Solution. x = {0}, y = {1}",x.Level()[0],y.Level()[0]);
     }
   }
Exemplo n.º 40
0
        public static void Main(string[] args)
        {
          using (Model M = new Model("FacilityLocation"))
          {
  // Variable holding the facility location
            Variable f = M.Variable("facility",new NDSet(1,2),Domain.Unbounded());
            // Variable defining the euclidian distances to each customer
            Variable d = M.Variable("dist", new NDSet(N,1), Domain.GreaterThan(0.0));
            // Variable defining the x and y differences to each customer;
            Variable t = M.Variable("t",new NDSet(N,2), Domain.Unbounded());
            M.Constraint("dist measure", 
                         Variable.Stack(new Variable[][] { new Variable[] { d, t }}), 
                         Domain.InQCone(N,3));

            Variable fxy = Variable.Repeat(f, N);
            M.Constraint("xy diff", Expr.Add(t, fxy), Domain.EqualsTo(customerloc));

            M.Objective("total_dist", ObjectiveSense.Minimize, Expr.Sum(d));
            
            M.Solve();
            double[] floc = f.Level();
            Console.WriteLine("Facility location = {0},{1}",floc[0],floc[1]);
          }
        }
Exemplo n.º 41
0
        public static double[] fitpoly(double[,] data, int n)
        {
          using (var M = new Model("smooth poly"))
          {
            int m = data.GetLength(0);
            double[] Adata = new double[m * (n+1)];
            for (int j = 0, k = 0; j < m; ++j)
              for (int i = 0; i < n+1; ++i, ++k)
                 Adata[k] = Math.Pow(data[j,0], i);

            Matrix A = new DenseMatrix(m,n+1,Adata);
            double[] b = new double[m]; 
            for (int j = 0; j < m; ++j)
              b[j] = data[j,1];
                    
            Variable x  = M.Variable("x", n+1, Domain.Unbounded());
            Variable z  = M.Variable("z", 1,   Domain.Unbounded());
            Variable dx = diff(M, x);
                               
            M.Constraint(Expr.Mul(A, x), Domain.EqualsTo(b));
                                
            // z - f'(t) >= 0, for all t \in [a, b]
            Variable ub = M.Variable(n, Domain.Unbounded());
            M.Constraint(Expr.Sub(ub, 
                                  Expr.Vstack(Expr.Sub(z,dx.Index(0)), Expr.Neg(dx.Slice(1,n)))), 
                         Domain.EqualsTo(0.0));            
            nn_finite(M, ub, data[0,0], data[m-1,0]);
                    
            // f'(t) + z >= 0, for all t \in [a, b]
            Variable lb = M.Variable(n, Domain.Unbounded());
            M.Constraint(Expr.Sub(lb, 
                                  Expr.Vstack(Expr.Add(z, dx.Index(0)), dx.Slice(1,n).AsExpr())), 
                         Domain.EqualsTo(0.0));
            nn_finite(M, lb, data[0,0], data[m-1,0]);

            M.Objective(ObjectiveSense.Minimize, z);
            M.Solve();
            return x.Level();
          }
        }
Exemplo n.º 42
0
        /*
          Purpose:
              Computes several portfolios on the optimal portfolios by 

                  for alpha in alphas: 
                      maximize   expected return - alpha * standard deviation
                      subject to the constraints  
              
          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
              alphas: List of the alphas
                          
          Output:
              The efficient frontier as list of tuples (alpha,expected return,risk)
         */ 
        public static void EfficientFrontier
          ( int n,
            double[] mu,
            DenseMatrix GT,
            double[]    x0,
            double      w,
            double[]    alphas,
            
            double[]    frontier_mux,
            double[]    frontier_s)
        {
          using(Model M = new Model("Efficient frontier"))
          {
            //M.SetLogHandler(Console.Out);
       
            // Defines the variables (holdings). Shortselling is not allowed.
            Variable x = M.Variable("x", n, Domain.GreaterThan(0.0)); // Portfolio variables
            Variable s = M.Variable("s", 1, Domain.Unbounded()); // Risk variable

            M.Constraint("budget", Expr.Sum(x), Domain.EqualsTo(w+sum(x0)));

            // Computes the risk
            M.Constraint("risk", Expr.Vstack(s.AsExpr(),Expr.Mul(GT,x)),Domain.InQCone());

            for (int i = 0; i < alphas.Length; ++i)
            {
              //  Define objective as a weighted combination of return and risk
              M.Objective("obj", ObjectiveSense.Maximize, Expr.Sub(Expr.Dot(mu,x),Expr.Mul(alphas[i],s)));

              M.Solve();
             
              frontier_mux[i] = dot(mu,x.Level());
              frontier_s[i]   = s.Level()[0];
            }
          }
        }
Exemplo n.º 43
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
                m: It is assumed that  market impact cost for the j'th asset is
                   m_j|x_j-x0_j|^3/2

            Output:
               Optimal expected return and the optimal portfolio     

        */
        public static void MarkowitzWithMarketImpact
          ( int n,
            double[] mu,
            DenseMatrix GT,
            double[] x0,
            double   w,
            double   gamma,
            double[] m,
            
            double[] xsol,
            double[] tsol)
        {
          using(Model M = new Model("Markowitz portfolio with market impact"))
          {

            //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 t = M.Variable("t", n, Domain.Unbounded());
            Variable z = M.Variable("z", n, Domain.Unbounded());  
            Variable v = M.Variable("v", n, Domain.Unbounded());      

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

            // Invested amount + slippage cost = initial wealth
            M.Constraint("budget", Expr.Add(Expr.Sum(x),Expr.Dot(m,t)), 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));

            // t >= z^1.5, z >= 0.0. Needs two rotated quadratic cones to model this term
            M.Constraint("ta", Expr.Hstack(v.AsExpr(),t.AsExpr(),z.AsExpr()),Domain.InRotatedQCone());

            M.Constraint("tb", Expr.Hstack(z.AsExpr(),Expr.ConstTerm(n,1.0/8.0),v.AsExpr()),
                         Domain.InRotatedQCone());
            M.Solve();  
       
            if (xsol != null) 
              Array.Copy(x.Level(),xsol,n);
            if (tsol != null)
              Array.Copy(t.Level(),tsol,n);
          }
        }
Exemplo n.º 44
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();
          }
        }
Exemplo n.º 45
0
        /*
        Purpose:
            Computes the optimal portfolio for a given risk 
         
        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
         
        Output:
            Optimal expected return and the optimal portfolio     
        */ 
        public static double BasicMarkowitz
          ( int n,
            double[] mu,
            DenseMatrix GT,
            double[] x0,
            double   w,
            double   gamma)
        {
          
          using( Model M = new Model("Basic Markowitz"))
          {

            // Redirect log output from the solver to stdout for debugging. 
            // ifuncommented.
            //M.SetLogHandler(Console.Out);
          
            // Defines the variables (holdings). Shortselling is not allowed.
            Variable x = M.Variable("x", n, Domain.GreaterThan(0.0));
          
            //  Maximize expected return
            M.Objective("obj", ObjectiveSense.Maximize, Expr.Dot(mu,x));

            // The amount invested  must be identical to intial wealth
            M.Constraint("budget", Expr.Sum(x), 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());
            // Solves the model.
            M.Solve();

            return dot(mu,x.Level());
          }
        }
Exemplo n.º 46
0
        public static double[][] lownerjohn_outer(double[][] x)
        {
          using( Model M = new Model("lownerjohn_outer") )
          {
            // Direct log output to the terminal for debugging. 
            M.SetLogHandler(Console.Out);  
            int m = x.Length;
            int n = x[0].Length;

            // Setup variables
            Variable t = M.Variable("t", 1, Domain.GreaterThan(0.0));
            Variable P = M.Variable("P", new NDSet(n,n), Domain.Unbounded());
            Variable c = M.Variable("c", n, Domain.Unbounded());

            // (1, P(*xi+c)) \in Q 
            for (int i = 0; i < m; ++i)
              M.Constraint( "qc" + i, Expr.Vstack(Expr.Ones(1), Expr.Sub(Expr.Mul(P,x[i]), c)), Domain.InQCone() );

            // t <= det(P)^{1/n}
            det_rootn(M, P, t);
                             
            // Objective: Maximize t
            M.Objective(ObjectiveSense.Maximize, t);
            M.Solve();
          
            double[] Plvl = P.Level();
            double[] clvl = c.Level();

            double[][] Pc = new double[n+1][];
            for (int i = 0; i < n; ++i)
            {
              Pc[i] = new double[n];
              System.Array.Copy(Plvl,i*n, Pc[i],0, n);
            }
            Pc[n] = clvl;

            return Pc;
          } 
        }
Exemplo n.º 47
0
        public static double[][] lownerjohn_inner(double[][] A, double[] b)
        {
          using( Model M = new Model("lownerjohn_inner"))
          {
            // Direct log output to the terminal for debugging. 
            M.SetLogHandler(Console.Out);  
            int m = A.Length;
            int n = A[0].Length; 

            // Setup variables
            Variable t = M.Variable("t", 1, Domain.GreaterThan(0.0));   
            Variable C = M.Variable("C", new NDSet(n,n), Domain.Unbounded());
            Variable d = M.Variable("d", n, Domain.Unbounded());        
          
            // (bi - ai^T*d, C*ai) \in Q 
            for (int i = 0; i < m; ++i)
              M.Constraint( "qc" + i, Expr.Vstack(Expr.Sub(b[i],Expr.Dot(A[i],d)), Expr.Mul(C,A[i])), Domain.InQCone() );

            // t <= det(C)^{1/n}
            det_rootn(M, C, t);
                                 
            // Objective: Maximize t
            M.Objective(ObjectiveSense.Maximize, t);
            M.Solve();
          
            double[] Clvl = C.Level();
            double[] dlvl = d.Level();

            double[][] Cres_d = new double[n+1][];
            for (int i = 0; i < n; ++i)
            {
              Cres_d[i] = new double[n];
              System.Array.Copy(Clvl,i*n,Cres_d[i],0, n);
            }
            Cres_d[n] = dlvl;
            return Cres_d;
          }
        }