Subtract() public static method

Creates a BinaryExpression that represents an arithmetic subtraction operation that does not have overflow checking.
public static Subtract ( Expression left, Expression right ) : BinaryExpression
left Expression An to set the property equal to.
right Expression An to set the property equal to.
return BinaryExpression
Ejemplo n.º 1
0
        // Define a function for running the simulation of a population system S with timestep
        // dt. The number of timesteps and the data buffer are parameters of the defined function.
        static Func <int, double[, ], int> DefineSimulate(double dt, PopulationSystem S)
        {
            CodeGen code = new CodeGen();

            // Define a parameter for the current population x, and define mappings to the
            // expressions defined above.
            LinqExpr N    = code.Decl <int>(Scope.Parameter, "N");
            LinqExpr Data = code.Decl <double[, ]>(Scope.Parameter, "Data");

            // Loop over the sample range requested. Note that this loop is a 'runtime' loop,
            // while the rest of the loops nested in the body of this loop are 'compile time' loops.
            LinqExpr n = code.DeclInit <int>("n", 1);

            code.For(
                () => { },
                LinqExpr.LessThan(n, N),
                () => code.Add(LinqExpr.PostIncrementAssign(n)),
                () =>
            {
                // Define expressions representing the population of each species.
                List <Expression> x = new List <Expression>();
                for (int i = 0; i < S.N; ++i)
                {
                    // Define a variable xi.
                    Expression xi = "x" + i.ToString();
                    x.Add(xi);
                    // xi = Data[n, i].
                    code.DeclInit(xi, LinqExpr.ArrayAccess(Data, LinqExpr.Subtract(n, LinqExpr.Constant(1)), LinqExpr.Constant(i)));
                }

                for (int i = 0; i < S.N; ++i)
                {
                    // This list is the elements of the sum representing the i'th
                    // row of f, i.e. r_i + (A*x)_i.
                    Expression dx_dt = 1;
                    for (int j = 0; j < S.N; ++j)
                    {
                        dx_dt -= S.A[i, j] * x[j];
                    }

                    // Define dx_i/dt = x_i * f_i(x), as per the Lotka-Volterra equations.
                    dx_dt *= x[i] * S.r[i];

                    // Euler's method for x(t) is: x(t) = x(t - h) + h * x'(t - h).
                    Expression integral = x[i] + dt * dx_dt;

                    // Data[n, i] = Data[n - 1, i] + dt * dx_dt;
                    code.Add(LinqExpr.Assign(
                                 LinqExpr.ArrayAccess(Data, n, LinqExpr.Constant(i)),
                                 code.Compile(integral)));
                }
            });

            code.Return(N);

            // Compile the generated code.
            LinqExprs.Expression <Func <int, double[, ], int> > expr = code.Build <Func <int, double[, ], int> >();
            return(expr.Compile());
        }
Ejemplo n.º 2
0
 public static ExCoordF CartesianRot(ExTP erv) => (c, s, bpi, nrv, fxy) => {
     var v2 = new TExV2();
     return(Ex.Block(new ParameterExpression[] { v2 },
                     Ex.Assign(v2, erv(bpi)),
                     fxy(Ex.Subtract(Ex.Multiply(c, v2.x), Ex.Multiply(s, v2.y)),
                         Ex.Add(Ex.Multiply(s, v2.x), Ex.Multiply(c, v2.y))),
                     Expression.Empty()
                     ));
 };
Ejemplo n.º 3
0
        public static ExCoordF Polar2(ExTP radThetaDeg)
        {
            var rt     = new TExV2();
            var lookup = new TExV2();

            return((c, s, bpi, nrv, fxy) => Ex.Block(new ParameterExpression[] { rt, lookup },
                                                     Ex.Assign(rt, radThetaDeg(bpi)),
                                                     Ex.Assign(lookup, ExM.CosSinDeg(rt.y)),
                                                     fxy(Ex.Subtract(Ex.Multiply(c, lookup.x), Ex.Multiply(s, lookup.y)).Mul(rt.x),
                                                         Ex.Add(Ex.Multiply(s, lookup.x), Ex.Multiply(c, lookup.y)).Mul(rt.x)),
                                                     Expression.Empty()
                                                     ));
        }
Ejemplo n.º 4
0
        public static ExCoordF Polar(ExBPY r, ExBPY theta)
        {
            var vr     = ExUtils.VFloat();
            var lookup = new TExV2();

            return((c, s, bpi, nrv, fxy) => Ex.Block(new[] { vr, lookup },
                                                     Ex.Assign(lookup, ExM.CosSinDeg(theta(bpi))),
                                                     Ex.Assign(vr, r(bpi)),
                                                     fxy(Ex.Subtract(Ex.Multiply(c, lookup.x), Ex.Multiply(s, lookup.y)).Mul(vr),
                                                         Ex.Add(Ex.Multiply(s, lookup.x), Ex.Multiply(c, lookup.y)).Mul(vr)),
                                                     Expression.Empty()
                                                     ));
        }
Ejemplo n.º 5
0
 public static Func <TExArgCtx, TEx <T> > Pivot <S, T>(Func <TExArgCtx, TEx <float> > pivot, Func <TExArgCtx, TEx <T> > f1, Func <TExArgCtx, TEx <T> > f2, Func <TExArgCtx, TEx> pivotVar)
     where S : TEx, new() => t => {
     var pv     = VFloat();
     var pivotT = t.MakeCopyForType <S>(out var currEx, out var pivotEx);
     return(Ex.Block(new[] { pv },
                     pv.Is(pivot(t)),
                     Ex.Condition(pv.LT(pivotVar(t)),
                                  Ex.Block(new ParameterExpression[] { pivotEx },
                                           Ex.Assign(pivotEx, currEx),
                                           Ex.Assign(pivotVar(pivotT), pv),
                                           Ex.Add(f1(pivotT), Ex.Subtract(f2(t), f2(pivotT)))
                                           ),
                                  f1(t)
                                  )
                     ));
 };
Ejemplo n.º 6
0
        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);
        }
Ejemplo n.º 7
0
        public static void Main()
        {
            Expression <Func <double, double> > Substratlänge = (Produktlänge) => (Math.Max(Produktlänge, 200) - 115);
            var exp = Substratlänge.Compile();

            // Parameter/Constants
            var parameter = Exp.Parameter(typeof(double), "Produktlänge");
            var constant1 = Exp.Constant(200.0, typeof(double));
            var constant2 = Exp.Constant(115.0, typeof(double));

            // Math.Max()
            var maxMethod      = typeof(Math).GetMethod("Max", new Type[] { typeof(double), typeof(double) });
            var callExpression = Exp.Call(null, maxMethod, new Exp[] { parameter, constant1 });

            // Substract
            var substractExpression = Exp.Subtract(callExpression, constant2);

            // t.Total == 100.00M
            var func = Exp.Lambda <Func <double, double> >(substractExpression, parameter).Compile();

            Console.WriteLine($"Expr => {exp(238.7)}");
            Console.WriteLine($"Lbda => {func(238.7)}");
        }
Ejemplo n.º 8
0
        public override SysExpr ToExpression()
        {
            switch (NodeType)
            {
            case ExpressionType.Add:
                return(SysExpr.Add(Left.ToExpression(), Right.ToExpression()));

            case ExpressionType.Subtract:
                return(SysExpr.Subtract(Left.ToExpression(), Right.ToExpression()));

            case ExpressionType.Multiply:
                return(SysExpr.Multiply(Left.ToExpression(), Right.ToExpression()));

            case ExpressionType.Divide:
                return(SysExpr.Divide(Left.ToExpression(), Right.ToExpression()));

            case ExpressionType.Coalesce:
                return(SysExpr.Coalesce(Left.ToExpression(), Right.ToExpression()));

            default:
                throw new NotSupportedException($"Not a valid {NodeType} for arithmetic binary expression.");
            }
        }
Ejemplo n.º 9
0
 public static Expression Subtract(Expression arg0, Expression arg1)
 {
     return(new Expression(LinqExpression.Subtract(arg0, arg1)));
 }
        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();
            }
        }
Ejemplo n.º 11
0
        // Use homotopy method with newton's method to find a solution for F(x) = 0.
        private static List <Arrow> NSolve(List <Expression> F, List <Arrow> x0, double Epsilon, int MaxIterations)
        {
            int M = F.Count;
            int N = x0.Count;

            // Compute JxF, the Jacobian of F.
            List <Dictionary <Expression, Expression> > JxF = Jacobian(F, x0.Select(i => i.Left)).ToList();

            // Define a function to evaluate JxH(x), where H = F(x) - s*F(x0).
            CodeGen code = new CodeGen();

            ParamExpr _JxH = code.Decl <double[, ]>(Scope.Parameter, "JxH");
            ParamExpr _x0  = code.Decl <double[]>(Scope.Parameter, "x0");
            ParamExpr _s   = code.Decl <double>(Scope.Parameter, "s");

            // Load x_j from the input array and add them to the map.
            for (int j = 0; j < N; ++j)
            {
                code.DeclInit(x0[j].Left, LinqExpr.ArrayAccess(_x0, LinqExpr.Constant(j)));
            }

            LinqExpr error = code.Decl <double>("error");

            // Compile the expressions to assign JxH
            for (int i = 0; i < M; ++i)
            {
                LinqExpr _i = LinqExpr.Constant(i);
                for (int j = 0; j < N; ++j)
                {
                    code.Add(LinqExpr.Assign(
                                 LinqExpr.ArrayAccess(_JxH, _i, LinqExpr.Constant(j)),
                                 code.Compile(JxF[i][x0[j].Left])));
                }
                // e = F(x) - s*F(x0)
                LinqExpr e = code.DeclInit <double>("e", LinqExpr.Subtract(code.Compile(F[i]), LinqExpr.Multiply(LinqExpr.Constant((double)F[i].Evaluate(x0)), _s)));
                code.Add(LinqExpr.Assign(LinqExpr.ArrayAccess(_JxH, _i, LinqExpr.Constant(N)), e));
                // error += e * e
                code.Add(LinqExpr.AddAssign(error, LinqExpr.Multiply(e, e)));
            }

            // return error
            code.Return(error);

            Func <double[, ], double[], double, double> JxH = code.Build <Func <double[, ], double[], double, double> >().Compile();

            double[] x = new double[N];

            // Remember where we last succeeded/failed.
            double s0 = 0.0;
            double s1 = 1.0;

            do
            {
                try
                {
                    // H(F, s) = F - s*F0
                    NewtonsMethod(M, N, JxH, s0, x, Epsilon, MaxIterations);

                    // Success at this s!
                    s1 = s0;
                    for (int i = 0; i < N; ++i)
                    {
                        x0[i] = Arrow.New(x0[i].Left, x[i]);
                    }

                    // Go near the goal.
                    s0 = Lerp(s0, 0.0, 0.9);
                }
                catch (FailedToConvergeException)
                {
                    // Go near the last success.
                    s0 = Lerp(s0, s1, 0.9);

                    for (int i = 0; i < N; ++i)
                    {
                        x[i] = (double)x0[i].Right;
                    }
                }
            } while (s0 > 0.0 && s1 >= s0 + 1e-6);

            // Make sure the last solution is at F itself.
            if (s0 != 0.0)
            {
                NewtonsMethod(M, N, JxH, 0.0, x, Epsilon, MaxIterations);
                for (int i = 0; i < N; ++i)
                {
                    x0[i] = Arrow.New(x0[i].Left, x[i]);
                }
            }

            return(x0);
        }
Ejemplo n.º 12
0
 public static Ex SubAssign(Ex into, Ex from) => Ex.Assign(into, Ex.Subtract(into, from));
Ejemplo n.º 13
0
 private static Expression sSubtract(double a, [NotNull] Expression b) => sAdd(Expression.Subtract(Expression.Constant(a), b));
Ejemplo n.º 14
0
 private static Expression sSubtract([NotNull] Expression a, double b) => sAdd(Expression.Subtract(a, Expression.Constant(b)));
Ejemplo n.º 15
0
        // 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);
        }
Ejemplo n.º 16
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))
                                                                        ))
                                       ));
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Overshoot 1 and then ease back.
 /// </summary>
 /// <param name="p1">Parameter controlling overshoot</param>
 /// <param name="x">0-1 time</param>
 public static tfloat EOutBack(efloat p1, efloat x) => EEx.Resolve <float, float>(p1, Ex.Subtract(x, E1), (a, y) =>
                                                                                  E1.Add(a.Add(E1).Mul(y).Mul(y).Mul(y)).Add(a.Mul(y).Mul(y))
                                                                                  );
Ejemplo n.º 18
0
 public static BinaryExpression Subtract(Expression left, Expression right) => Expression.Subtract(left, right);
Ejemplo n.º 19
0
 public static BinaryExpression Subtract(Expression left, Expression right, MethodInfo method) => Expression.Subtract(left, right, method);