GreaterThan() public static méthode

Creates a BinaryExpression that represents a "greater than" numeric comparison.
public static GreaterThan ( Expression left, Expression right ) : BinaryExpression
left Expression An to set the property equal to.
right Expression An to set the property equal to.
Résultat BinaryExpression
        public void Factorial()
        {
            var value      = LinqExpression.Parameter(typeof(int), "value");
            var result     = LinqExpression.Parameter(typeof(int), "result");
            var label      = LinqExpression.Label(typeof(int), "label");
            var one        = LinqExpression.Constant(1);
            var expression = LinqExpression.Block(
                new[] { result },
                LinqExpression.Assign(
                    result,
                    one),
                LinqExpression.Loop(
                    LinqExpression.Condition(
                        LinqExpression.GreaterThan(
                            value,
                            one),
                        LinqExpression.MultiplyAssign(
                            result,
                            LinqExpression.PostDecrementAssign(
                                value)),
                        LinqExpression.Break(
                            label,
                            result),
                        typeof(void)),
                    label));

            ShouldRoundrip(expression);
        }
        public void TestWhereComparison()
        {
            // Partial LINQ expression (x => x.Number1)
            var parameter = LinqExpression.Parameter(typeof(NumbersModel), "x");
            var n1        = LinqExpression.Property(parameter, "Number1");

            var l3    = new Func <int, bool>(n => n < 3);
            var le3   = new Func <int, bool>(n => n <= 3);
            var g6    = new Func <int, bool>(n => n > 6);
            var ge6   = new Func <int, bool>(n => n >= 6);
            var e7    = new Func <int, bool>(n => n == 7);
            var ne7   = new Func <int, bool>(n => n != 7);
            var cases = new[] {
                Tuple.Create((LinqExpression)LinqExpression.LessThan(n1, LinqExpression.Constant(3)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)l3, parameter),
                Tuple.Create((LinqExpression)LinqExpression.LessThanOrEqual(n1, LinqExpression.Constant(3)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)le3, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(n1, LinqExpression.Constant(6)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)g6, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThanOrEqual(n1, LinqExpression.Constant(6)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)ge6, parameter),
                Tuple.Create((LinqExpression)LinqExpression.Equal(n1, LinqExpression.Constant(7)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)e7, parameter),
                Tuple.Create((LinqExpression)LinqExpression.NotEqual(n1, LinqExpression.Constant(7)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)ne7, parameter)
            };

            LoadModelNumbers(10);
            Db.Count.Should().Be(10);
            RunTestWithNumbers(new[] { 2, 3, 4, 5, 1, 9 }, cases);
        }
Exemple #3
0
 //See Design/Engine Math Tips for details on these two functions. They are not raw easing.
 public static Func <T, TEx <R> > Ease <T, R>(Func <tfloat, tfloat> easer, float maxTime,
                                              Func <T, TEx <R> > f, Func <T, Ex> t, Func <T, Ex, T> withT)
 // x = f(g(t)), where g(t) = T e(t/T)
 => bpi => Ex.Condition(Ex.GreaterThan(t(bpi), ExC(maxTime)), f(bpi),
                        f(withT(bpi, ExC(maxTime).Mul(
                                    easer(t(bpi).Mul(1f / maxTime))
                                    ))
                          ));
Exemple #4
0
        /// <summary>
        /// Lerp from the target parametric to zero.
        /// </summary>
        /// <param name="from_time">Time to start lerping</param>
        /// <param name="end_time">Time to end lerping</param>
        /// <param name="p">Target parametric</param>
        /// <returns></returns>
        public static ExTP LerpOut(float from_time, float end_time, ExTP p)
        {
            Ex etr    = ExC(1f / (end_time - from_time));
            Ex ex_end = ExC(end_time);

            return(bpi => Ex.Condition(Ex.GreaterThan(bpi.t, ex_end), v20,
                                       Ex.Multiply(p(bpi), Ex.Condition(Ex.LessThan(bpi.t, ExC(from_time)), E1,
                                                                        Ex.Multiply(etr, Ex.Subtract(ex_end, bpi.t))
                                                                        ))
                                       ));
        }
Exemple #5
0
        public void TestIfThen()
        {
            var y  = VF("y");
            var ex = Ex.Block(new[] { y }, Ex.Assign(y, ExC(4f)), Ex.Condition(Ex.GreaterThan(y, ExC(3f)),
                                                                               Ex.Assign(y, ExC(3f)),
                                                                               Ex.Add(y, ExC(1f))
                                                                               ), Ex.Add(y, ExC(2f)));

            AreEqual("((y=4);\nif(y>3){(y=3)}else{(y+1)};\n(y+2);)", ex.Debug());
            ex = Ex.Block(new[] { y }, Ex.Assign(y, ExC(4f)), Ex.Condition(Ex.GreaterThan(y, ExC(3f)),
                                                                           Ex.Add(y, ExC(1f)),
                                                                           Ex.Assign(y, ExC(3f))
                                                                           ), Ex.Add(y, ExC(2f)));
            AreEqual("((y=4);\n5;\n6;)", ex.FlatDebug());
        }
        public void TestWhereAndOr()
        {
            var parameter = LinqExpression.Parameter(typeof(NumbersModel), "x");
            var n1        = LinqExpression.Property(parameter, "Number1");
            var n2        = LinqExpression.Property(parameter, "Number2");
            var cases     = new[] {
                Tuple.Create((LinqExpression)LinqExpression.AndAlso(LinqExpression.GreaterThan(n1, LinqExpression.Constant(3)), LinqExpression.GreaterThan(n2, LinqExpression.Constant(3))),
                             (Func <NumbersModel, object, bool>)TestWhereAndValidator, default(object), parameter),
                Tuple.Create((LinqExpression)LinqExpression.OrElse(LinqExpression.LessThan(n1, LinqExpression.Constant(3)), LinqExpression.LessThan(n2, LinqExpression.Constant(3))),
                             (Func <NumbersModel, object, bool>)TestWhereOrValidator, default(object), parameter)
            };

            LoadModelNumbers(10);
            RunTestWithNumbers(new[] { 3, 5 }, cases);
        }
Exemple #7
0
        public void TestCond()
        {
            var x  = VF("x");
            var yi = VF("y");
            var zi = VF("z");
            var ex = Ex.Condition(Ex.Block(zi.Is(ExC(5f)), ExC(true)),
                                  Ex.Block(new[] { yi },
                                           yi.Is(ExC(5f)),
                                           yi.Add(x)),
                                  ExC(2f)
                                  );

            AreEqual(ex.Linearize().ToCSharpString(), @"
    float linz_0;
    z = (5f);
    if (true) {
        float y;
        y = (5f);
        linz_0 = ((y) + (x));
    } else {
        linz_0 = (2f);
    }
    
    linz_0;;");
            //ternary ok
            var ex2 = Ex.Condition(Ex.Block(zi.Is(ExC(5f)), ExC(true)),
                                   yi.Add(x),
                                   ExC(2f)
                                   );

            AreEqual(ex2.Linearize().ToCSharpString(), @"
    z = (5f);
    (true ?
        (y) + (x) :
        2f);;");
            //cond can be simplified
            var ex3 = Ex.Condition(Ex.GreaterThan(zi, ExC(5f)),
                                   yi.Add(x),
                                   ExC(2f)
                                   );

            AreEqual(ex3.Linearize().ToCSharpString(), @"((z) > (5f) ?
    (y) + (x) :
    2f);");
        }
        public void TestWhereArithmetic()
        {
            var parameter = LinqExpression.Parameter(typeof(NumbersModel), "x");
            var n1        = LinqExpression.Property(parameter, "Number1");
            var n2        = LinqExpression.Property(parameter, "Number2");

            var m2g8   = new Func <int, int, bool>((x1, x2) => x1 * 2 > 8);
            var d2g3   = new Func <int, int, bool>((x1, x2) => x1 / 2 > 3);
            var m2e0   = new Func <int, int, bool>((x1, x2) => (x1 % 2) == 0);
            var a5g10  = new Func <int, int, bool>((x1, x2) => x1 + 5 > 10);
            var s5g0   = new Func <int, int, bool>((x1, x2) => x1 - 5 > 0);
            var mn2g10 = new Func <int, int, bool>((x1, x2) => x1 * x2 > 10);
            var dn1g3  = new Func <int, int, bool>((x1, x2) => x2 / x1 > 3);
            var mn2e0  = new Func <int, int, bool>((x1, x2) => (x1 % x2) == 0);
            var an2e10 = new Func <int, int, bool>((x1, x2) => x1 + x2 == 10);
            var sn2g0  = new Func <int, int, bool>((x1, x2) => x1 - x2 > 0);
            var cases  = new[] {
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(LinqExpression.Multiply(n1, LinqExpression.Constant(2)), LinqExpression.Constant(8)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)m2g8, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(LinqExpression.Divide(n1, LinqExpression.Constant(2)), LinqExpression.Constant(3)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)d2g3, parameter),
                Tuple.Create((LinqExpression)LinqExpression.Equal(LinqExpression.Modulo(n1, LinqExpression.Constant(2)), LinqExpression.Constant(0)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)m2e0, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(LinqExpression.Add(n1, LinqExpression.Constant(5)), LinqExpression.Constant(10)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)a5g10, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(LinqExpression.Subtract(n1, LinqExpression.Constant(5)), LinqExpression.Constant(0)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)s5g0, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(LinqExpression.Multiply(n1, n2), LinqExpression.Constant(10)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)mn2g10, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(LinqExpression.Divide(n2, n1), LinqExpression.Constant(3)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)dn1g3, parameter),
                Tuple.Create((LinqExpression)LinqExpression.Equal(LinqExpression.Modulo(n1, n2), LinqExpression.Constant(0)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)mn2e0, parameter),
                Tuple.Create((LinqExpression)LinqExpression.Equal(LinqExpression.Add(n1, n2), LinqExpression.Constant(10)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)an2e10, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(LinqExpression.Subtract(n1, n2), LinqExpression.Constant(0)),
                             (Func <NumbersModel, object, bool>)TestWhereMathValidator, (object)sn2g0, parameter)
            };

            LoadModelNumbers(10);
            RunTestWithNumbers(new[] { 6, 3, 5, 5, 5, 7, 2, 3, 10, 5 }, cases);
        }
        private BinaryExpression BinaryExpression(
            ExpressionType nodeType, System.Type type, JObject obj)
        {
            var left       = this.Prop(obj, "left", this.Expression);
            var right      = this.Prop(obj, "right", this.Expression);
            var method     = this.Prop(obj, "method", this.Method);
            var conversion = this.Prop(obj, "conversion", this.LambdaExpression);
            var liftToNull = this.Prop(obj, "liftToNull").Value <bool>();

            switch (nodeType)
            {
            case ExpressionType.Add: return(Expr.Add(left, right, method));

            case ExpressionType.AddAssign: return(Expr.AddAssign(left, right, method, conversion));

            case ExpressionType.AddAssignChecked: return(Expr.AddAssignChecked(left, right, method, conversion));

            case ExpressionType.AddChecked: return(Expr.AddChecked(left, right, method));

            case ExpressionType.And: return(Expr.And(left, right, method));

            case ExpressionType.AndAlso: return(Expr.AndAlso(left, right, method));

            case ExpressionType.AndAssign: return(Expr.AndAssign(left, right, method, conversion));

            case ExpressionType.ArrayIndex: return(Expr.ArrayIndex(left, right));

            case ExpressionType.Assign: return(Expr.Assign(left, right));

            case ExpressionType.Coalesce: return(Expr.Coalesce(left, right, conversion));

            case ExpressionType.Divide: return(Expr.Divide(left, right, method));

            case ExpressionType.DivideAssign: return(Expr.DivideAssign(left, right, method, conversion));

            case ExpressionType.Equal: return(Expr.Equal(left, right, liftToNull, method));

            case ExpressionType.ExclusiveOr: return(Expr.ExclusiveOr(left, right, method));

            case ExpressionType.ExclusiveOrAssign: return(Expr.ExclusiveOrAssign(left, right, method, conversion));

            case ExpressionType.GreaterThan: return(Expr.GreaterThan(left, right, liftToNull, method));

            case ExpressionType.GreaterThanOrEqual: return(Expr.GreaterThanOrEqual(left, right, liftToNull, method));

            case ExpressionType.LeftShift: return(Expr.LeftShift(left, right, method));

            case ExpressionType.LeftShiftAssign: return(Expr.LeftShiftAssign(left, right, method, conversion));

            case ExpressionType.LessThan: return(Expr.LessThan(left, right, liftToNull, method));

            case ExpressionType.LessThanOrEqual: return(Expr.LessThanOrEqual(left, right, liftToNull, method));

            case ExpressionType.Modulo: return(Expr.Modulo(left, right, method));

            case ExpressionType.ModuloAssign: return(Expr.ModuloAssign(left, right, method, conversion));

            case ExpressionType.Multiply: return(Expr.Multiply(left, right, method));

            case ExpressionType.MultiplyAssign: return(Expr.MultiplyAssign(left, right, method, conversion));

            case ExpressionType.MultiplyAssignChecked: return(Expr.MultiplyAssignChecked(left, right, method, conversion));

            case ExpressionType.MultiplyChecked: return(Expr.MultiplyChecked(left, right, method));

            case ExpressionType.NotEqual: return(Expr.NotEqual(left, right, liftToNull, method));

            case ExpressionType.Or: return(Expr.Or(left, right, method));

            case ExpressionType.OrAssign: return(Expr.OrAssign(left, right, method, conversion));

            case ExpressionType.OrElse: return(Expr.OrElse(left, right, method));

            case ExpressionType.Power: return(Expr.Power(left, right, method));

            case ExpressionType.PowerAssign: return(Expr.PowerAssign(left, right, method, conversion));

            case ExpressionType.RightShift: return(Expr.RightShift(left, right, method));

            case ExpressionType.RightShiftAssign: return(Expr.RightShiftAssign(left, right, method, conversion));

            case ExpressionType.Subtract: return(Expr.Subtract(left, right, method));

            case ExpressionType.SubtractAssign: return(Expr.SubtractAssign(left, right, method, conversion));

            case ExpressionType.SubtractAssignChecked: return(Expr.SubtractAssignChecked(left, right, method, conversion));

            case ExpressionType.SubtractChecked: return(Expr.SubtractChecked(left, right, method));

            default: throw new NotSupportedException();
            }
        }
Exemple #10
0
        public static Expression CreateLambdaExpression <T, TModel>(IEnumerable <FilterElement> filterElements, Type querytype, ParameterExpression arg)
        {
            Expression expression = Expression.Constant(true);

            foreach (var filterElement in filterElements)
            {
                string[]   props = filterElement.FilterSpecs.DataElement.Split('.');
                Expression propertyExpression = arg;
                var        type = typeof(T);

                Expression notNullExpression = Expression.Constant(true);

                foreach (var property in  props)
                {
                    PropertyInfo pi = type.GetProperty(property);
                    propertyExpression = Expression.Property(propertyExpression, pi);
                    var nullExpression = Expression.Constant(GetNullExpressionForType(pi.PropertyType), pi.PropertyType);
                    notNullExpression = Expression.AndAlso(notNullExpression, Expression.NotEqual(propertyExpression, nullExpression));
                    type = pi.PropertyType;
                }

                var isLiteralType = type.IsEquivalentTo(typeof(string));

                var valueExpression = Expression.Constant(filterElement.FieldValue, filterElement.Property.PropertyType);

                Expression inputExpression, variableExpression;
                if (filterElement.FilterSpecs.CaseSensitive && isLiteralType)
                {
                    variableExpression = Expression.Call(propertyExpression,
                                                         typeof(String).GetMethod("ToUpper", new Type[] { }));

                    inputExpression = Expression.Call(valueExpression,
                                                      typeof(String).GetMethod("ToUpper", new Type[] { }));
                }
                else
                {
                    // special case to handle nullable values
                    if (valueExpression.Type.IsNullable())
                    {
                        valueExpression = Expression.Constant(valueExpression.Value, filterElement.Property.PropertyType.NullableOf());
                    }


                    inputExpression    = valueExpression;
                    variableExpression = propertyExpression;
                }

                BinaryExpression conditionExpression = Expression.Equal(variableExpression, valueExpression);

                switch (filterElement.FilterSpecs.OperatorOption)
                {
                case Operator.Equal:
                    conditionExpression = Expression.Equal(variableExpression, inputExpression);
                    break;

                case Operator.GreaterThan:
                    conditionExpression = Expression.GreaterThan(variableExpression, inputExpression);
                    break;

                case Operator.GreaterThanOrEqualTo:
                    conditionExpression = Expression.GreaterThanOrEqual(variableExpression, inputExpression);
                    break;

                case Operator.LessThan:
                    conditionExpression = Expression.LessThan(variableExpression, inputExpression);
                    break;

                case Operator.LessThanOrEqualTo:
                    conditionExpression = Expression.LessThanOrEqual(variableExpression, inputExpression);
                    break;

                case Operator.Unequal:
                    conditionExpression = Expression.NotEqual(variableExpression, inputExpression);
                    break;

                case Operator.Like:
                    MethodInfo method             = typeof(string).GetMethod("Contains", new[] { typeof(string) });
                    var        containsMethodCall = Expression.Call(variableExpression, method, inputExpression);
                    conditionExpression = Expression.Equal(containsMethodCall, Expression.Constant(true));
                    break;
                }


                var clausePart = Expression.AndAlso(notNullExpression, conditionExpression);

                if (!filterElement.FieldValue.Equals(GetNullExpressionForType(filterElement.Property.PropertyType)))
                {
                    expression = Expression.AndAlso(expression, clausePart);
                }
            }

            return(expression);
        }
Exemple #11
0
        public void Factorial()
        {
            var value    = LinqExpression.Parameter(typeof(int));
            var result   = LinqExpression.Parameter(typeof(int));
            var label    = LinqExpression.Label(typeof(int));
            var expected = LinqExpression.Block(
                new[] { result },
                LinqExpression.Assign(
                    result,
                    LinqExpression.Constant(1)),
                LinqExpression.Loop(
                    LinqExpression.Condition(
                        LinqExpression.GreaterThan(
                            value,
                            LinqExpression.Constant(1)),
                        LinqExpression.MultiplyAssign(
                            result,
                            LinqExpression.PostDecrementAssign(
                                value)),
                        LinqExpression.Break(
                            label,
                            result),
                        typeof(void)),
                    label));

            using var g = new GraphEngine.Graph();
            g.LoadFromString(@"
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix : <http://example.com/> .
@prefix xt: <http://example.com/ExpressionTypes/> .

_:constantValue
    :parameterType [
        :typeName ""System.Int32"" ;
    ] ;
.

_:result
    :parameterType [
        :typeName ""System.Int32"" ;
    ] ;
.

_:label
    :targetType [
        :typeName ""System.Int32"" ;
    ] ;
.

_:one
    :constantValue ""1""^^xsd:int ;
.

:s
    :blockVariables (
        _:result
    ) ;
    :blockExpressions (
        [
            :binaryExpressionType xt:Assign ;
            :binaryLeft _:result ;
            :binaryRight _:one ;
        ]
        [
            :loopBody [
                :conditionTest [
                    :binaryExpressionType xt:GreaterThan ;
                    :binaryLeft _:constantValue ;
                    :binaryRight _:one ;
                ] ;
                :conditionIfTrue [
                    :binaryExpressionType xt:MultiplyAssign ;
                    :binaryLeft _:result ;
                    :binaryRight [
                        :unaryExpressionType xt:PostDecrementAssign ;
                        :unaryOperand _:constantValue ;
                    ] ;
                ] ;
                :conditionIfFalse [
                    a :Break ;
                    :gotoTarget _:label ;
                    :gotoValue _:result ;
                ] ;
                :conditionType [
                    :typeName ""System.Void"" ;
                ] ;
            ] ;
            :loopBreak _:label ;
        ]
    ) ;
.
");
            var s = g.GetUriNode(":s");

            var actual = Expression.Parse(s).LinqExpression;

            Console.WriteLine(actual.GetDebugView());

            actual.Should().Be(expected);
        }
Exemple #12
0
 /// <summary>
 /// 创建大于运算表达式
 /// </summary>
 /// <param name="left">左操作数</param>
 /// <param name="right">右操作数</param>
 public static MicrosoftExpression Greater(this MicrosoftExpression left, MicrosoftExpression right)
 {
     return(MicrosoftExpression.GreaterThan(left, right));
 }
Exemple #13
0
 public static Ex GT0(this Ex me) => Ex.GreaterThan(me, Ex.Constant(0f));
Exemple #14
0
 public static Ex GT(this Ex me, Ex than) => Ex.GreaterThan(me, than);
        // Generate code to perform row reduction.
        private static void RowReduce(CodeGen code, LinqExpr Ab, int M, int N)
        {
            // For each variable in the system...
            for (int j = 0; j + 1 < N; ++j)
            {
                LinqExpr _j  = LinqExpr.Constant(j);
                LinqExpr Abj = code.ReDeclInit <double[]>("Abj", LinqExpr.ArrayAccess(Ab, _j));
                // int pi = j
                LinqExpr pi = code.ReDeclInit <int>("pi", _j);
                // double max = |Ab[j][j]|
                LinqExpr max = code.ReDeclInit <double>("max", Abs(LinqExpr.ArrayAccess(Abj, _j)));

                // Find a pivot row for this variable.
                //code.For(j + 1, M, _i =>
                //{
                for (int i = j + 1; i < M; ++i)
                {
                    LinqExpr _i = LinqExpr.Constant(i);

                    // if(|Ab[i][j]| > max) { pi = i, max = |Ab[i][j]| }
                    LinqExpr maxj = code.ReDeclInit <double>("maxj", Abs(LinqExpr.ArrayAccess(LinqExpr.ArrayAccess(Ab, _i), _j)));
                    code.Add(LinqExpr.IfThen(
                                 LinqExpr.GreaterThan(maxj, max),
                                 LinqExpr.Block(
                                     LinqExpr.Assign(pi, _i),
                                     LinqExpr.Assign(max, maxj))));
                }

                // (Maybe) swap the pivot row with the current row.
                LinqExpr Abpi = code.ReDecl <double[]>("Abpi");
                code.Add(LinqExpr.IfThen(
                             LinqExpr.NotEqual(_j, pi), LinqExpr.Block(
                                 new[] { LinqExpr.Assign(Abpi, LinqExpr.ArrayAccess(Ab, pi)) }.Concat(
                                     Enumerable.Range(j, N + 1 - j).Select(x => Swap(
                                                                               LinqExpr.ArrayAccess(Abj, LinqExpr.Constant(x)),
                                                                               LinqExpr.ArrayAccess(Abpi, LinqExpr.Constant(x)),
                                                                               code.ReDecl <double>("swap")))))));

                //// It's hard to believe this swap isn't faster than the above...
                //code.Add(LinqExpr.IfThen(LinqExpr.NotEqual(_j, pi), LinqExpr.Block(
                //    Swap(LinqExpr.ArrayAccess(Ab, _j), LinqExpr.ArrayAccess(Ab, pi), Redeclare<double[]>(code, "temp")),
                //    LinqExpr.Assign(Abj, LinqExpr.ArrayAccess(Ab, _j)))));

                // Eliminate the rows after the pivot.
                LinqExpr p = code.ReDeclInit <double>("p", LinqExpr.ArrayAccess(Abj, _j));
                //code.For(j + 1, M, _i =>
                //{
                for (int i = j + 1; i < M; ++i)
                {
                    LinqExpr _i  = LinqExpr.Constant(i);
                    LinqExpr Abi = code.ReDeclInit <double[]>("Abi", LinqExpr.ArrayAccess(Ab, _i));

                    // s = Ab[i][j] / p
                    LinqExpr s = code.ReDeclInit <double>("scale", LinqExpr.Divide(LinqExpr.ArrayAccess(Abi, _j), p));
                    // Ab[i] -= Ab[j] * s
                    for (int ji = j + 1; ji < N + 1; ++ji)
                    {
                        code.Add(LinqExpr.SubtractAssign(
                                     LinqExpr.ArrayAccess(Abi, LinqExpr.Constant(ji)),
                                     LinqExpr.Multiply(LinqExpr.ArrayAccess(Abj, LinqExpr.Constant(ji)), s)));
                    }
                }
            }
        }
        // The resulting lambda processes N samples, using buffers provided for Input and Output:
        //  void Process(int N, double t0, double T, double[] Input0 ..., double[] Output0 ...)
        //  { ... }
        private Delegate DefineProcess()
        {
            // Map expressions to identifiers in the syntax tree.
            List <KeyValuePair <Expression, LinqExpr> > inputs  = new List <KeyValuePair <Expression, LinqExpr> >();
            List <KeyValuePair <Expression, LinqExpr> > outputs = new List <KeyValuePair <Expression, LinqExpr> >();

            // Lambda code generator.
            CodeGen code = new CodeGen();

            // Create parameters for the basic simulation info (N, t, Iterations).
            ParamExpr SampleCount = code.Decl <int>(Scope.Parameter, "SampleCount");
            ParamExpr t           = code.Decl(Scope.Parameter, Simulation.t);

            // Create buffer parameters for each input...
            foreach (Expression i in Input)
            {
                inputs.Add(new KeyValuePair <Expression, LinqExpr>(i, code.Decl <double[]>(Scope.Parameter, i.ToString())));
            }

            // ... and output.
            foreach (Expression i in Output)
            {
                outputs.Add(new KeyValuePair <Expression, LinqExpr>(i, code.Decl <double[]>(Scope.Parameter, i.ToString())));
            }

            // Create globals to store previous values of inputs.
            foreach (Expression i in Input.Distinct())
            {
                AddGlobal(i.Evaluate(t_t0));
            }

            // Define lambda body.

            // int Zero = 0
            LinqExpr Zero = LinqExpr.Constant(0);

            // double h = T / Oversample
            LinqExpr h = LinqExpr.Constant(TimeStep / (double)Oversample);

            // Load the globals to local variables and add them to the map.
            foreach (KeyValuePair <Expression, GlobalExpr <double> > i in globals)
            {
                code.Add(LinqExpr.Assign(code.Decl(i.Key), i.Value));
            }

            foreach (KeyValuePair <Expression, LinqExpr> i in inputs)
            {
                code.Add(LinqExpr.Assign(code.Decl(i.Key), code[i.Key.Evaluate(t_t0)]));
            }

            // Create arrays for linear systems.
            int      M   = Solution.Solutions.OfType <NewtonIteration>().Max(i => i.Equations.Count(), 0);
            int      N   = Solution.Solutions.OfType <NewtonIteration>().Max(i => i.UnknownDeltas.Count(), 0) + 1;
            LinqExpr JxF = code.DeclInit <double[][]>("JxF", LinqExpr.NewArrayBounds(typeof(double[]), LinqExpr.Constant(M)));

            for (int j = 0; j < M; ++j)
            {
                code.Add(LinqExpr.Assign(LinqExpr.ArrayAccess(JxF, LinqExpr.Constant(j)), LinqExpr.NewArrayBounds(typeof(double), LinqExpr.Constant(N))));
            }

            // for (int n = 0; n < SampleCount; ++n)
            ParamExpr n = code.Decl <int>("n");

            code.For(
                () => code.Add(LinqExpr.Assign(n, Zero)),
                LinqExpr.LessThan(n, SampleCount),
                () => code.Add(LinqExpr.PreIncrementAssign(n)),
                () =>
            {
                // Prepare input samples for oversampling interpolation.
                Dictionary <Expression, LinqExpr> dVi = new Dictionary <Expression, LinqExpr>();
                foreach (Expression i in Input.Distinct())
                {
                    LinqExpr Va = code[i];
                    // Sum all inputs with this key.
                    IEnumerable <LinqExpr> Vbs = inputs.Where(j => j.Key.Equals(i)).Select(j => j.Value);
                    LinqExpr Vb = LinqExpr.ArrayAccess(Vbs.First(), n);
                    foreach (LinqExpr j in Vbs.Skip(1))
                    {
                        Vb = LinqExpr.Add(Vb, LinqExpr.ArrayAccess(j, n));
                    }

                    // dVi = (Vb - Va) / Oversample
                    code.Add(LinqExpr.Assign(
                                 Decl <double>(code, dVi, i, "d" + i.ToString().Replace("[t]", "")),
                                 LinqExpr.Multiply(LinqExpr.Subtract(Vb, Va), LinqExpr.Constant(1.0 / (double)Oversample))));
                }

                // Prepare output sample accumulators for low pass filtering.
                Dictionary <Expression, LinqExpr> Vo = new Dictionary <Expression, LinqExpr>();
                foreach (Expression i in Output.Distinct())
                {
                    code.Add(LinqExpr.Assign(
                                 Decl <double>(code, Vo, i, i.ToString().Replace("[t]", "")),
                                 LinqExpr.Constant(0.0)));
                }

                // int ov = Oversample;
                // do { -- ov; } while(ov > 0)
                ParamExpr ov = code.Decl <int>("ov");
                code.Add(LinqExpr.Assign(ov, LinqExpr.Constant(Oversample)));
                code.DoWhile(() =>
                {
                    // t += h
                    code.Add(LinqExpr.AddAssign(t, h));

                    // Interpolate the input samples.
                    foreach (Expression i in Input.Distinct())
                    {
                        code.Add(LinqExpr.AddAssign(code[i], dVi[i]));
                    }

                    // Compile all of the SolutionSets in the solution.
                    foreach (SolutionSet ss in Solution.Solutions)
                    {
                        if (ss is LinearSolutions)
                        {
                            // Linear solutions are easy.
                            LinearSolutions S = (LinearSolutions)ss;
                            foreach (Arrow i in S.Solutions)
                            {
                                code.DeclInit(i.Left, i.Right);
                            }
                        }
                        else if (ss is NewtonIteration)
                        {
                            NewtonIteration S = (NewtonIteration)ss;

                            // Start with the initial guesses from the solution.
                            foreach (Arrow i in S.Guesses)
                            {
                                code.DeclInit(i.Left, i.Right);
                            }

                            // int it = iterations
                            LinqExpr it = code.ReDeclInit <int>("it", Iterations);
                            // do { ... --it } while(it > 0)
                            code.DoWhile((Break) =>
                            {
                                // Solve the un-solved system.
                                Solve(code, JxF, S.Equations, S.UnknownDeltas);

                                // Compile the pre-solved solutions.
                                if (S.KnownDeltas != null)
                                {
                                    foreach (Arrow i in S.KnownDeltas)
                                    {
                                        code.DeclInit(i.Left, i.Right);
                                    }
                                }

                                // bool done = true
                                LinqExpr done = code.ReDeclInit("done", true);
                                foreach (Expression i in S.Unknowns)
                                {
                                    LinqExpr v  = code[i];
                                    LinqExpr dv = code[NewtonIteration.Delta(i)];

                                    // done &= (|dv| < |v|*epsilon)
                                    code.Add(LinqExpr.AndAssign(done, LinqExpr.LessThan(LinqExpr.Multiply(Abs(dv), LinqExpr.Constant(1e4)), LinqExpr.Add(Abs(v), LinqExpr.Constant(1e-6)))));
                                    // v += dv
                                    code.Add(LinqExpr.AddAssign(v, dv));
                                }
                                // if (done) break
                                code.Add(LinqExpr.IfThen(done, Break));

                                // --it;
                                code.Add(LinqExpr.PreDecrementAssign(it));
                            }, LinqExpr.GreaterThan(it, Zero));

                            //// bool failed = false
                            //LinqExpr failed = Decl(code, code, "failed", LinqExpr.Constant(false));
                            //for (int i = 0; i < eqs.Length; ++i)
                            //    // failed |= |JxFi| > epsilon
                            //    code.Add(LinqExpr.OrAssign(failed, LinqExpr.GreaterThan(Abs(eqs[i].ToExpression().Compile(map)), LinqExpr.Constant(1e-3))));

                            //code.Add(LinqExpr.IfThen(failed, ThrowSimulationDiverged(n)));
                        }
                    }

                    // Update the previous timestep variables.
                    foreach (SolutionSet S in Solution.Solutions)
                    {
                        foreach (Expression i in S.Unknowns.Where(i => globals.Keys.Contains(i.Evaluate(t_t0))))
                        {
                            code.Add(LinqExpr.Assign(code[i.Evaluate(t_t0)], code[i]));
                        }
                    }

                    // Vo += i
                    foreach (Expression i in Output.Distinct())
                    {
                        LinqExpr Voi = LinqExpr.Constant(0.0);
                        try
                        {
                            Voi = code.Compile(i);
                        }
                        catch (Exception Ex)
                        {
                            Log.WriteLine(MessageType.Warning, Ex.Message);
                        }
                        code.Add(LinqExpr.AddAssign(Vo[i], Voi));
                    }

                    // Vi_t0 = Vi
                    foreach (Expression i in Input.Distinct())
                    {
                        code.Add(LinqExpr.Assign(code[i.Evaluate(t_t0)], code[i]));
                    }

                    // --ov;
                    code.Add(LinqExpr.PreDecrementAssign(ov));
                }, LinqExpr.GreaterThan(ov, Zero));

                // Output[i][n] = Vo / Oversample
                foreach (KeyValuePair <Expression, LinqExpr> i in outputs)
                {
                    code.Add(LinqExpr.Assign(LinqExpr.ArrayAccess(i.Value, n), LinqExpr.Multiply(Vo[i.Key], LinqExpr.Constant(1.0 / (double)Oversample))));
                }

                // Every 256 samples, check for divergence.
                if (Vo.Any())
                {
                    code.Add(LinqExpr.IfThen(LinqExpr.Equal(LinqExpr.And(n, LinqExpr.Constant(0xFF)), Zero),
                                             LinqExpr.Block(Vo.Select(i => LinqExpr.IfThenElse(IsNotReal(i.Value),
                                                                                               ThrowSimulationDiverged(n),
                                                                                               LinqExpr.Assign(i.Value, RoundDenormToZero(i.Value)))))));
                }
            });

            // Copy the global state variables back to the globals.
            foreach (KeyValuePair <Expression, GlobalExpr <double> > i in globals)
            {
                code.Add(LinqExpr.Assign(i.Value, code[i.Key]));
            }

            LinqExprs.LambdaExpression lambda = code.Build();
            Delegate ret = lambda.Compile();

            return(ret);
        }
Exemple #17
0
 /// <summary>
 /// Switch between two parametrics based on time.
 /// </summary>
 /// <param name="at_time">Switch reference</param>
 /// <param name="from">Parametric to return before switch</param>
 /// <param name="to">Parametric to return after switch</param>
 /// <returns></returns>
 public static ExTP Switch(float at_time, ExTP from, ExTP to)
 {
     return(bpi => Ex.Condition(Ex.GreaterThan(bpi.t, ExC(at_time)), to(bpi), from(bpi)));
 }
Exemple #18
0
            private static BinaryExpression GreaterThanExpression(ParameterExpression parameter, string propertyName, object value)
            {
                var(bodyLeft, bodyRight) = GetBodyExpressions(parameter, propertyName, value);

                return(SystemExpression.GreaterThan(bodyLeft, bodyRight));
            }
Exemple #19
0
        private static Expression GetExpression <T>(ParameterExpression param, Filter filter)
        {
            object filterValue = filter.Value;
            Op     operation   = filter.Operation;

            MemberExpression   member = Expression.Property(param, filter.PropertyName);
            ConstantExpression constant;

            #region NULLABLE HANDLING
            if (filterValue != null && IsNullableType(member.Type))
            {
                var targetType    = Nullable.GetUnderlyingType(member.Type);
                var propertyValue = Convert.ChangeType(filterValue, targetType);
                constant = Expression.Constant(propertyValue, member.Type);
            }
            else
            {
                constant = Expression.Constant(filterValue);
            }
            #endregion

            switch (operation)
            {
            case Op.GreaterThan:
                return(Expression.GreaterThan(member, constant));

            case Op.GreaterThanOrEqual:
                return(Expression.GreaterThanOrEqual(member, constant));

            case Op.LessThan:
                return(Expression.LessThan(member, constant));

            case Op.LessThanOrEqual:
                return(Expression.LessThanOrEqual(member, constant));

            case Op.Equals:

                //string equals ignore case comparison
                if (member.Type.TypeHandle.Equals(typeof(string).TypeHandle))
                {
                    var compareExpression = Expression.Call(null, compareMethod, member, constant, Expression.Constant(StringComparison.InvariantCultureIgnoreCase));
                    return(Expression.Equal(compareExpression, Expression.Constant(0)));
                }

                return(Expression.Equal(member, constant));

            case Op.Contains:
                return(Expression.Call(member, containsMethod, constant));

            case Op.StartsWith:
                return(Expression.Call(member, startsWithMethod, constant));

            case Op.EndsWith:
                return(Expression.Call(member, endsWithMethod, constant));

            case Op.NotEqual:
                return(Expression.NotEqual(member, constant));

            case Op.HasFlag:
                constant = Expression.Constant(filter.Value, typeof(Enum));
                return(Expression.Call(member, hasFlagMethod, constant));
            }

            return(null);
        }
Exemple #20
0
 public static Expression GreaterThan(Expression arg0, Expression arg1)
 {
     return(new Expression(LinqExpression.GreaterThan(arg0, arg1)));
 }