Esempio n. 1
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);
        }
Esempio n. 2
0
        /// <summary>
        /// Expands the foreach loop if it iterates over a numeric range.
        /// </summary>
        private NodeBase expandRange(Context ctx)
        {
            var signVar = ctx.Scope.DeclareImplicit(ctx, _VariableType, false);
            var idxVar  = ctx.Scope.DeclareImplicit(ctx, _VariableType, false);

            return(Expr.Block(
                       Expr.Set(idxVar, RangeStart),
                       Expr.Set(
                           signVar,
                           Expr.Invoke(
                               "Math",
                               "Sign",
                               Expr.Sub(RangeEnd, Expr.Get(idxVar))
                               )
                           ),
                       Expr.While(
                           Expr.NotEqual(Expr.Get(idxVar), RangeEnd),
                           Expr.Block(
                               getIndexAssignment(Expr.Get(idxVar)),
                               Body,
                               Expr.Set(
                                   idxVar,
                                   Expr.Add(
                                       Expr.Get(idxVar),
                                       Expr.Get(signVar)
                                       )
                                   )
                               )
                           )
                       ));
        }
Esempio n. 3
0
        public void ConstantDeclaration()
        {
            var src    = @"let v = 1 + 1";
            var result = Expr.Let("v", Expr.Add(Expr.Int(1), Expr.Int(1)));

            TestParser(src, result);
        }
Esempio n. 4
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());
                    }
                }
Esempio n. 5
0
        public void OperatorPriority2()
        {
            var src    = "1 + 2 - 3 * 4 / 5 % 6 ** 7";
            var result = Expr.Sub(
                Expr.Add(
                    Expr.Int(1),
                    Expr.Int(2)
                    ),
                Expr.Mod(
                    Expr.Div(
                        Expr.Mult(
                            Expr.Int(3),
                            Expr.Int(4)
                            ),
                        Expr.Int(5)
                        ),
                    Expr.Pow(
                        Expr.Int(6),
                        Expr.Int(7)
                        )
                    )
                );

            TestParser(src, result);
        }
Esempio n. 6
0
        /// <summary>
        /// Expands the foreach loop if it iterates over T[].
        /// </summary>
        private NodeBase expandArray(Context ctx)
        {
            var arrayVar = ctx.Scope.DeclareImplicit(ctx, IterableExpression.Resolve(ctx), false);
            var idxVar   = ctx.Scope.DeclareImplicit(ctx, typeof(int), false);
            var lenVar   = ctx.Scope.DeclareImplicit(ctx, typeof(int), false);

            return(Expr.Block(
                       Expr.Set(idxVar, Expr.Int(0)),
                       Expr.Set(arrayVar, IterableExpression),
                       Expr.Set(lenVar, Expr.GetMember(Expr.Get(arrayVar), "Length")),
                       Expr.While(
                           Expr.Less(
                               Expr.Get(idxVar),
                               Expr.Get(lenVar)
                               ),
                           Expr.Block(
                               getIndexAssignment(
                                   Expr.GetIdx(
                                       Expr.Get(arrayVar),
                                       Expr.Get(idxVar)
                                       )
                                   ),
                               Expr.Set(
                                   idxVar,
                                   Expr.Add(Expr.Get(idxVar), Expr.Int(1))
                                   ),
                               Body
                               )
                           )
                       ));
        }
Esempio n. 7
0
        // Models the cone of nonnegative polynomials on the finite interval [a,b]
        public static void nn_finite(Model M, Variable x, double a, double b)
        {
            //assert(a < b)
            int m = (int)x.GetSize() - 1;
            int n = m / 2;

            if (m == 2 * n)
            {
                Variable X1 = M.Variable(Domain.InPSDCone(n + 1));
                Variable X2 = M.Variable(Domain.InPSDCone(n));

                // x_i = Tr H(n,i)*X1 + (a+b)*Tr H(n-1,i-1) * X2 - a*b*Tr H(n-1,i)*X2 - Tr H(n-1,i-2)*X2, i=0,...,m
                for (int i = 0; i < m + 1; ++i)
                {
                    M.Constraint(Expr.Sub(x.Index(i),
                                          Expr.Add(Expr.Sub(Expr.Dot(Hankel(n, i, 1.0), X1), Expr.Dot(Hankel(n - 1, i, a * b), X2)),
                                                   Expr.Sub(Expr.Dot(Hankel(n - 1, i - 1, a + b), X2), Expr.Dot(Hankel(n - 1, i - 2, 1.0), X2)))),
                                 Domain.EqualsTo(0.0));
                }
            }
            else
            {
                Variable X1 = M.Variable(Domain.InPSDCone(n + 1));
                Variable X2 = M.Variable(Domain.InPSDCone(n + 1));

                // x_i = Tr H(n,i-1)*X1 - a*Tr H(n,i)*X1 + b*Tr H(n,i)*X2 - Tr H(n,i-1)*X2, i=0,...,m
                for (int i = 0; i < m + 1; ++i)
                {
                    M.Constraint(Expr.Sub(x.Index(i),
                                          Expr.Add(Expr.Sub(Expr.Dot(Hankel(n, i - 1, 1.0), X1), Expr.Dot(Hankel(n, i, a), X1)),
                                                   Expr.Sub(Expr.Dot(Hankel(n, i, b), X2), Expr.Dot(Hankel(n, i - 1, 1.0), X2)))),
                                 Domain.EqualsTo(0.0));
                }
            }
        }
Esempio n. 8
0
        public void Algebraic2()
        {
            var src = @"
type TestType
    Small of int
    Large of int
var a = new Small 1
var b = new Large 100
a.Tag + b.Tag";

            var result = new NodeBase[]
            {
                Expr.Type(
                    "TestType",
                    Expr.Label("Small", "int"),
                    Expr.Label("Large", "int")
                    ),

                Expr.Var("a", Expr.New("Small", Expr.Int(1))),
                Expr.Var("b", Expr.New("Large", Expr.Int(100))),
                Expr.Add(
                    Expr.GetMember(Expr.Get("a"), "Tag"),
                    Expr.GetMember(Expr.Get("b"), "Tag")
                    )
            };

            TestParser(src, result);
        }
Esempio n. 9
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]);
            }
        }
Esempio n. 10
0
        public void VariableDeclaration()
        {
            var src    = @"var v = 1 + 1";
            var result = Expr.Var("v", Expr.Add(Expr.Int(1), Expr.Int(1)));

            TestParser(src, result);
        }
Esempio n. 11
0
        public void ParseTest()
        {
            AssertExpr(Expr.Constant(0.5),
                       Parser.Parse("0.5"));

            AssertExpr(Expr.Constant(1.0),
                       Parser.Parse("(((((1)))))"));

            AssertExpr(Expr.UnaryPlus(Expr.Constant(1.0)),
                       Parser.Parse("+1"));

            AssertExpr(Expr.Negate(Expr.UnaryPlus(Expr.UnaryPlus(Expr.Constant(0.5)))),
                       Parser.Parse("-++0.5"));

            AssertExpr(Expr.Add(Expr.Constant(1.0), Expr.Constant(2.0)),
                       Parser.Parse("1+2"));

            AssertExpr(Expr.Add(
                           Expr.Constant(1.0),
                           Expr.Add(
                               Expr.Constant(2.0),
                               Expr.Add(
                                   Expr.Constant(3.0),
                                   Expr.Constant(4.0)))),
                       Parser.Parse("1+2+3+4"));

            AssertExpr(Expr.Multiply(Expr.Constant(1.0), Expr.Constant(2.0)),
                       Parser.Parse("1*2"));

            AssertExpr(Expr.Add(
                           Expr.Constant(1.0),
                           Expr.Multiply(
                               Expr.Constant(2.0),
                               Expr.Constant(3.0))),
                       Parser.Parse("1+2*3"));

            AssertExpr(Expr.Multiply(
                           Expr.Add(
                               Expr.Constant(1.0),
                               Expr.Constant(2.0)),
                           Expr.Constant(3.0)),
                       Parser.Parse("(1+2)*3"));

            AssertExpr(Expr.Function("do", new Expr[] { }),
                       Parser.Parse("do()"));

            AssertExpr(Expr.Add(
                           Expr.Constant(1.0),
                           Expr.Function("PI", new Expr[] { })),
                       Parser.Parse("1 + PI()"));

            AssertExpr(Expr.Function("print", new Expr[] {
                Expr.Function("plus", new Expr[] {
                    Expr.Constant(1.0),
                    Expr.Constant(1.0)
                })
            }),
                       Parser.Parse("print(plus(1, 1))"));
        }
Esempio n. 12
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;
                        }
                    }
                }
Esempio n. 13
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());
            }
        }
Esempio n. 14
0
        public void ExpressionResultShouldBeSixDueToMultiplicationOperationPriority()
        {
            // Arrange
            var tokenParser = makeTokenParser(Language.JavaStyle);
            var reservedOp  = tokenParser.ReservedOp;

            // Natural parser
            var natural = from n in tokenParser.Natural
                          select Expr.Natural(n);

            // Binary operator expression factory
            Func <Expr, Expr, Expr> binaryOp(string op) =>
            (Expr lhs, Expr rhs) =>
            op == "+" ? Expr.Add(lhs, rhs)
                  : op == "-" ? Expr.Sub(lhs, rhs)
                  : op == "/" ? Expr.Div(lhs, rhs)
                  : op == "*" ? Expr.Mul(lhs, rhs)
                  : throw new NotSupportedException();

            // Binary operator parser builder
            Operator <Expr> binary(string op, Assoc assoc) =>
            Operator.Infix(assoc,
                           from x in reservedOp(op)
                           select binaryOp(op));

            // Operator table
            Operator <Expr>[][] table =
            {
                new[] { binary("+", Assoc.Left), binary("-", Assoc.Left) },
                new[] { binary("*", Assoc.Left), binary("/", Assoc.Left) }
            };

            // Null because it will be not null later and can be used by the lazyp parser
            Parser <Expr> expr = null;

            // Build up the expression term
            var term = either(
                attempt(natural),
                tokenParser.Parens(lazyp(() => expr)));

            // Build the expression parser
            expr = buildExpressionParser(table, term).label("expression");


            var expression      = "2 + 2 * 2";
            var exprectedResult = 6;

            // Act
            var actualResult = parse(expr, expression)
                               .ToOption()
                               .Map(ex => ex.Eval())
                               .IfNone(0);

            // Assert
            Assert.Equal(exprectedResult, actualResult);
        }
Esempio n. 15
0
        private Expr ComputeExpr(Expr ptrExpr, Expr access)
        {
            Expr result = null;

            if (access is NAryExpr)
            {
                var a = (access as NAryExpr).Args[1];
                if (ptrExpr is NAryExpr)
                {
                    var ptr = ptrExpr as NAryExpr;
                    if (!(ptr.Args[1] is LiteralExpr) || !(a is LiteralExpr))
                    {
                        return(result);
                    }

                    int l = (ptr.Args[1] as LiteralExpr).asBigNum.ToInt;
                    int r = (a as LiteralExpr).asBigNum.ToInt;

                    if (ptr.Fun.FunctionName == "$add" || ptr.Fun.FunctionName == "+")
                    {
                        if ((access as NAryExpr).Fun.FunctionName == "$add" ||
                            (access as NAryExpr).Fun.FunctionName == "+")
                        {
                            result = Expr.Add(ptr.Args[0], new LiteralExpr(Token.NoToken, BigNum.FromInt(l + r)));
                        }
                    }
                }
                else if (ptrExpr is IdentifierExpr)
                {
                    if (this.AC.GetNumOfEntryPointRelatedFunctions(this.EP.Name) >
                        WhoopCommandLineOptions.Get().EntryPointFunctionCallComplexity)
                    {
                        return(result);
                    }

                    var ptr = ptrExpr as IdentifierExpr;
                    if (!ptr.Type.IsInt)
                    {
                        return(result);
                    }

                    if ((access as NAryExpr).Fun.FunctionName == "$add" ||
                        (access as NAryExpr).Fun.FunctionName == "+")
                    {
                        result = Expr.Add(ptr, new LiteralExpr(Token.NoToken, (a as LiteralExpr).asBigNum));
                    }
                }
            }
            else
            {
                result = ptrExpr;
            }

            return(result);
        }
Esempio n. 16
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);
                        }
                    }
                }
Esempio n. 17
0
        public void SetDynamicMember2()
        {
            var src    = "(1 + 2).someShit = a";
            var result = Expr.SetMember(
                Expr.Add(Expr.Int(1), Expr.Int(2)),
                "someShit",
                Expr.Get("a")
                );

            TestParser(src, result);
        }
Esempio n. 18
0
        public void ArrayDeclaration()
        {
            var src    = @"new [1; 2; 1 + 2]";
            var result = Expr.Array(
                Expr.Int(1),
                Expr.Int(2),
                Expr.Add(Expr.Int(1), Expr.Int(2))
                );

            TestParser(src, result);
        }
Esempio n. 19
0
        // t >= log( 1 + exp(u) ) coordinatewise
        public static void softplus(Model M,
                                    Expression t,
                                    Expression u)
        {
            int      n  = t.GetShape()[0];
            Variable z1 = M.Variable(n);
            Variable z2 = M.Variable(n);

            M.Constraint(Expr.Add(z1, z2), Domain.EqualsTo(1));
            M.Constraint(Expr.Hstack(z1, Expr.ConstTerm(n, 1.0), Expr.Sub(u, t)), Domain.InPExpCone());
            M.Constraint(Expr.Hstack(z2, Expr.ConstTerm(n, 1.0), Expr.Neg(t)), Domain.InPExpCone());
        }
Esempio n. 20
0
        public void InvocationTestParser()
        {
            var result = Expr.Invoke(
                Expr.Get("sqrt"),
                Expr.Add(
                    Expr.Get("sq1"),
                    Expr.Get("sq2")
                    )
                );

            TestParser("sqrt (sq1 + sq2)", result);
        }
        public void Should_iterate_n_times()
        {
            var loc  = Expr.LocalVariable(typeof(int), "i");
            var func = CreateFunc <int, int>(
                Expr.DeclareLocal(loc, Expr.Constant(0)),
                Expr.Loop(Expr.IfThenElse(
                              Expr.Equal(Expr.ReadLocal(loc), Expr.Parameter(0, typeof(int))),
                              Expr.LoopBreak(),
                              Expr.WriteLocal(loc, Expr.Add(Expr.ReadLocal(loc), Expr.Constant(1))))),
                Expr.Return(Expr.ReadLocal(loc)));

            Assert.That(func(5), Is.EqualTo(5));
        }
Esempio n. 22
0
        // Models log(sum(exp(Ax+b))) <= 0.
        // Each row of [A b] describes one of the exp-terms
        public static void logsumexp(Model M,
                                     double[,]  A,
                                     Variable x,
                                     double[]   b)
        {
            int      k = A.GetLength(0);
            Variable u = M.Variable(k);

            M.Constraint(Expr.Sum(u), Domain.EqualsTo(1.0));
            M.Constraint(Expr.Hstack(u,
                                     Expr.ConstTerm(k, 1.0),
                                     Expr.Add(Expr.Mul(A, x), b)), Domain.InPExpCone());
        }
Esempio n. 23
0
        public void SimpleAdd()
        {
            var constant  = new LiteralExpr(Token.NoToken, BigNum.FromInt(18)); // Integer
            var constant2 = new LiteralExpr(Token.NoToken, BigNum.FromInt(19)); // Integer
            var add       = Expr.Add(constant, constant2);

            var add2 = Expr.Add(constant, constant2);

            Assert.AreNotSame(constant, constant2);                 // These are different references
            Assert.AreNotSame(add, add2);                           // These are different references

            Assert.IsTrue(add.Equals(add2));                        // These are "structurally equal"
            Assert.AreEqual(add.GetHashCode(), add2.GetHashCode()); // If the .Equals() is true then hash codes must be the same
        }
Esempio n. 24
0
        public void Should_allow_break_in_catch_block()
        {
            var loc  = Expr.LocalVariable(typeof(int), "i");
            var func = CreateFunc <int>(
                Expr.WriteLocal(loc, Expr.Constant(0)),
                Expr.Loop(Expr.TryCatch(
                              Expr.Block(
                                  Expr.WriteLocal(loc, Expr.Add(Expr.ReadLocal(loc), Expr.Constant(1))),
                                  Expr.Throw(Expr.New(typeof(Exception)))),
                              new CatchBlock(Expr.LoopBreak()))),
                Expr.Return(Expr.ReadLocal(loc)));

            Assert.That(func(), Is.EqualTo(2));
        }
Esempio n. 25
0
        public static Expr ComputeLiteralsInExpr(Expr expr)
        {
            if (!(expr is NAryExpr) || !((expr as NAryExpr).Args[0] is NAryExpr))
            {
                return(expr);
            }

            int l1 = ((expr as NAryExpr).Args[1] as LiteralExpr).asBigNum.ToInt;
            int l2 = (((expr as NAryExpr).Args[0] as NAryExpr).Args[1] as LiteralExpr).asBigNum.ToInt;

            Expr result = ((expr as NAryExpr).Args[0] as NAryExpr).Args[0];

            return(Expr.Add(result, new LiteralExpr(Token.NoToken, BigNum.FromInt(l1 + l2))));
        }
Esempio n. 26
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());
            }
        }
Esempio n. 27
0
        public static Expr increment(Variable v1)
        {
            if (useIntArithmetic)
            {
                return(Expr.Add(Expr.Ident(v1), Expr.Literal(1)));
            }
            else
            {
                var args = new List <Expr>();
                args.Add(Expr.Ident(v1));
                args.Add(new LiteralExpr(Token.NoToken, Microsoft.BaseTypes.BigNum.FromInt(1), 32));

                return(new NAryExpr(Token.NoToken,
                                    new FunctionCall(getBvAdd()), args));
            }
        }
Esempio n. 28
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());
            }
        }
Esempio n. 29
0
        public void PureFunction()
        {
            var src = @"pure fun add:int (x:int y:int) -> x + y";

            var result = Expr.Fun(
                "add",
                "int",
                true,
                new[] { Expr.Arg("x", "int"), Expr.Arg("y", "int") },
                Expr.Add(
                    Expr.Get("x"),
                    Expr.Get("y")
                    )
                );

            TestParser(src, result);
        }
Esempio n. 30
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,
            double[,] 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));

                // Variables computing market impact
                Variable t = M.Variable("t", 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(gamma, Expr.Mul(GT, x)), Domain.InQCone());

                // t >= |x-x0|^1.5 using a power cone
                M.Constraint("tz", Expr.Hstack(t, Expr.ConstTerm(n, 1.0), Expr.Sub(x, x0)), Domain.InPPowerCone(2.0 / 3.0));

                M.Solve();

                if (xsol != null)
                {
                    Array.Copy(x.Level(), xsol, n);
                }
                if (tsol != null)
                {
                    Array.Copy(t.Level(), tsol, n);
                }
            }
        }