/// <summary> /// Perform one iteration of searching for a root with Newton-Raphson method /// </summary> /// <param name="f"></param> /// <param name="df"></param> /// <param name="value"></param> /// <param name="precision"></param> /// <returns></returns> private static ComplexNumber NewtonIter(FastExpression f, FastExpression df, ComplexNumber value, int precision) { ComplexNumber prev = value; int minCheckIters = (int)Math.Sqrt(precision); for (int i = 0; i < precision; i++) { if (i == precision - 1) { prev = value.Copy(); } try // TODO: remove try catch in for { value -= (f.Substitute(value) / df.Substitute(value)) as ComplexNumber; } catch (MathSException) { throw new MathSException("Two or more variables in SolveNt is forbidden"); } if (i > minCheckIters && prev == value) { return(value); } } if (Number.Abs(prev - value) > MathS.Settings.PrecisionErrorCommon) { return(RealNumber.NaN()); } else { return(value); } }
public static Expression <Func <Tuple, bool> > BuildFilterLambda(int startIndex, IReadOnlyList <Type> keyColumnTypes, Parameter <Tuple> keyParameter) { Expression filterExpression = null; var tupleParameter = Expression.Parameter(WellKnownOrmTypes.Tuple, "tuple"); var valueProperty = WellKnownOrmTypes.ParameterOfTuple .GetProperty(nameof(Parameter <Tuple> .Value), WellKnownOrmTypes.Tuple); var keyValue = Expression.Property(Expression.Constant(keyParameter), valueProperty); for (var i = 0; i < keyColumnTypes.Count; i++) { var getValueMethod = WellKnownMembers.Tuple.GenericAccessor.MakeGenericMethod(keyColumnTypes[i]); var tupleParameterFieldAccess = Expression.Call( tupleParameter, getValueMethod, Expression.Constant(startIndex + i)); var keyParameterFieldAccess = Expression.Call( keyValue, getValueMethod, Expression.Constant(i)); if (filterExpression == null) { filterExpression = Expression.Equal(tupleParameterFieldAccess, keyParameterFieldAccess); } else { filterExpression = Expression.And(filterExpression, Expression.Equal(tupleParameterFieldAccess, keyParameterFieldAccess)); } } return(FastExpression.Lambda <Func <Tuple, bool> >(filterExpression, tupleParameter)); }
private static MethodCallExpression AddProjectionPrefetch(Expression source, LambdaExpression projection) { var itemType = QueryHelper.GetSequenceElementType(source.Type); var projectionType = projection.Body.Type; var wrapperType = typeof(ProjectionWrapper <,>).MakeGenericType(itemType, projectionType); var wrapperItemProperty = wrapperType.GetProperty("Item"); var wrapperProjectedProperty = wrapperType.GetProperty("Projected"); var wrapperProjectionParameter = projection.Parameters[0]; var wrapperProjectionLambda = FastExpression.Lambda( Expression.MemberInit( Expression.New(wrapperType), Expression.Bind(wrapperItemProperty, wrapperProjectionParameter), Expression.Bind(wrapperProjectedProperty, projection.Body) ), wrapperProjectionParameter); var wrapperProjection = QueryFactory.Select(source, wrapperProjectionLambda); var resultProjectionParameter = Expression.Parameter(wrapperType, "wrapper"); var resultProjectionLambda = FastExpression.Lambda( Expression.MakeMemberAccess(resultProjectionParameter, wrapperItemProperty), resultProjectionParameter); var resultProjection = QueryFactory.Select(wrapperProjection, resultProjectionLambda); return(resultProjection); }
BuildMaterializer(ProjectionExpression projection, IEnumerable <Parameter <Tuple> > tupleParameters) { var tupleReader = Expression.Parameter(typeof(RecordSetReader), "tupleReader"); var session = Expression.Parameter(typeof(Session), "session"); var parameterContext = Expression.Parameter(WellKnownOrmTypes.ParameterContext, "parameterContext"); var itemProjector = projection.ItemProjector; var materializationInfo = itemProjector.Materialize(context, tupleParameters); var elementType = itemProjector.Item.Type; var materializeMethod = MaterializationHelper.MaterializeMethodInfo.MakeGenericMethod(elementType); var itemMaterializerFactoryMethod = elementType.IsNullable() ? MaterializationHelper.CreateNullableItemMaterializerMethodInfo.MakeGenericMethod( elementType.GetGenericArguments()[0]) : MaterializationHelper.CreateItemMaterializerMethodInfo.MakeGenericMethod(elementType); var itemMaterializer = itemMaterializerFactoryMethod.Invoke( null, new object[] { materializationInfo.Expression, itemProjector.AggregateType }); Expression <Func <Session, int, MaterializationContext> > materializationContextCtor = (s, entityCount) => new MaterializationContext(s, entityCount); var materializationContextExpression = materializationContextCtor .BindParameters(session, Expression.Constant(materializationInfo.EntitiesInRow)); Expression body = Expression.Call( materializeMethod, tupleReader, materializationContextExpression, parameterContext, Expression.Constant(itemMaterializer)); var projectorExpression = FastExpression.Lambda <Func <RecordSetReader, Session, ParameterContext, object> >( body, tupleReader, session, parameterContext); return(new Materializer(projectorExpression.CachingCompile())); }
/// <summary> /// Intepreting real values of func as X, /// imaginary as Y we iterate on range [from; to] /// </summary> /// <param name="func"></param> /// <param name="from"></param> /// <param name="to"></param> public void PlotIterativeComplex(FastExpression func, ComplexNumber from, ComplexNumber to) { Func <int, double> X = it => func.Call(((from + to) / (pointCount - 1) * it).AsComplex()).Real; Func <int, double> Y = it => func.Call(((from + to) / (pointCount - 1) * it).AsComplex()).Imaginary; BuildData(X, Y); destination.plt.PlotScatter(dataX, dataY); }
public static LambdaExpression MakeLambda(Expression expression, TranslatorContext context) { var tupleParameter = Expression.Parameter(typeof(Tuple), "tuple"); var visitor = new ExpressionMaterializer(tupleParameter, context, null, EnumerableUtils <Parameter <Tuple> > .Empty); var processedExpression = OwnerRemover.RemoveOwner(expression); return(FastExpression.Lambda(visitor.Visit(processedExpression), tupleParameter)); }
/// <summary>Intepreting real values of func as X, imaginary as Y we iterate on range [from; to]</summary> public void PlotIterativeComplex(FastExpression func, Entity.Number.Complex from, Entity.Number.Complex to) { double X(int it) => func.Call(((from + to) / (pointCount - 1) * it).ToNumerics()).Real; double Y(int it) => func.Call(((from + to) / (pointCount - 1) * it).ToNumerics()).Imaginary; BuildData(X, Y); destination.plt.PlotScatter(dataX, dataY); }
private static T Evaluate <T>(Expression expression) { if (expression.NodeType == ExpressionType.Constant) { return((T)((ConstantExpression)expression).Value); } return(FastExpression.Lambda <Func <T> >(expression).CachingCompile().Invoke()); }
public CompiledFuncTest() { multiFuncNotCompiled = (MathS.Log(3, x) + MathS.Sqr(x)) * MathS.Sin(x + MathS.Cosec(x)); multiFunc = multiFuncNotCompiled.Compile(x); Expression <Func <Complex, Complex> > expr = x => (Complex.Log(x, 3) + Complex.Pow(x, 2)) * Complex.Sin(x + 1 / Complex.Sin(x)); linqFunc = expr.Compile(); }
public override Expression <Func <IEnumerable <Tuple> > > GetEnumerable() { var call = Expression.Call(Expression.Constant(enumerableFunc.Target), enumerableFunc.Method); MethodInfo selectMethod = WellKnownMembers.Enumerable.Select.MakeGenericMethod(typeof(TItem), typeof(Tuple)); var select = Expression.Call(selectMethod, call, Expression.Constant(converter)); return(FastExpression.Lambda <Func <IEnumerable <Tuple> > >(select)); }
public CacheCompiledFunc() { notCompiled = MathS.Sin(MathS.Sqr(x)) + MathS.Cos(MathS.Sqr(x)) + MathS.Sqr(x) + MathS.Sin(MathS.Sqr(x)); complexFunc = notCompiled.Compile(x); Expression <Func <Complex, Complex> > linqExpr = x => Complex.Sin(Complex.Pow(x, 2)) + Complex.Cos(Complex.Pow(x, 2)) + Complex.Pow(x, 2) + Complex.Sin(Complex.Pow(x, 2)); linqComp = linqExpr.Compile(); }
public override Expression <Func <ParameterContext, IEnumerable <Tuple> > > GetEnumerable() { var paramContext = Expression.Parameter(WellKnownOrmTypes.ParameterContext, "context"); var call = Expression.Call(Expression.Constant(enumerableFunc.Target), enumerableFunc.Method, paramContext); var selectMethod = WellKnownMembers.Enumerable.Select.MakeGenericMethod(typeof(TItem), WellKnownOrmTypes.Tuple); var select = Expression.Call(selectMethod, call, Expression.Constant(converter)); return(FastExpression.Lambda <Func <ParameterContext, IEnumerable <Tuple> > >(select, paramContext)); }
private MappingEntry CreateMappingEntry(Expression expression) { var tupleAccess = expression.StripCasts().AsTupleAccess(); if (tupleAccess != null) { return(new MappingEntry(tupleAccess.GetTupleAccessArgument())); } return(new MappingEntry(FastExpression.Lambda(expression, calculatedColumnParameter))); }
/// <summary> /// Plots from an expression over variable x /// </summary> /// <param name="expr"> /// Expression to build /// </param> /// <param name="from"> /// Low bound /// </param> /// <param name="to"> /// High bound /// </param> public void PlotScatter(FastExpression func, ComplexNumber from, ComplexNumber to) { Func <int, double> inner = it => ((to - from) / (pointCount - 1) * it).Real; Clear(); BuildData(inner, it => func.Call(new Complex((double)inner(it), 0)).Real); destination.plt.PlotScatter(dataX, dataY); destination.Render(); }
/// <summary>Plots from an expression over variable x</summary> /// <param name="expr">Expression to build</param> /// <param name="from">Low bound</param> /// <param name="to">High bound</param> public void PlotScatter(FastExpression func, Entity.Number.Complex from, Entity.Number.Complex to) { double inner(int it) => ((to - from) / (pointCount - 1) * it).RealPart.EDecimal.ToDouble(); Clear(); BuildData(inner, it => func.Call(new Complex((double)inner(it), 0)).Real); destination.plt.PlotScatter(dataX, dataY); destination.Render(); }
public Expression <Func <Tuple, Tuple, bool> > Rewrite(Expression <Func <Tuple, bool> > predicate, ColumnCollection predicateColumns, ColumnCollection currentColumns) { Initialize(predicate, predicateColumns, currentColumns); leftTupleParameter = Expression.Parameter(typeof(Tuple), "leftTuple"); var visited = Visit(predicate.Body); return((Expression <Func <Tuple, Tuple, bool> >)FastExpression .Lambda(visited, leftTupleParameter, predicate.Parameters[0])); }
public Expression <Func <Tuple, bool> > CreatePredicatesConjunction( Expression <Func <Tuple, bool> > newPredicate, Expression <Func <Tuple, bool> > oldPredicate) { var oldParameter = oldPredicate.Parameters[0]; var newParameter = newPredicate.Parameters[0]; var result = (Expression <Func <Tuple, bool> >)parameterRewriter .Replace(oldPredicate, oldParameter, newParameter); return((Expression <Func <Tuple, bool> >)FastExpression.Lambda(Expression .AndAlso(result.Body, newPredicate.Body), newParameter)); }
public static MaterializationInfo MakeMaterialization(ItemProjectorExpression projector, TranslatorContext context, IEnumerable <Parameter <Tuple> > tupleParameters) { var tupleParameter = Expression.Parameter(typeof(Tuple), "tuple"); var materializationContextParameter = Expression.Parameter(typeof(ItemMaterializationContext), "mc"); var visitor = new ExpressionMaterializer(tupleParameter, context, materializationContextParameter, tupleParameters); var lambda = FastExpression.Lambda(visitor.Visit(projector.Item), tupleParameter, materializationContextParameter); var count = visitor.entityRegistry.Count; return(new MaterializationInfo(count, lambda)); }
public Expression <Func <ParameterContext, T> > BindToParameterContext(Expression parameterExpression) { var body = Visit(parameterExpression); var resultType = typeof(T); if (resultType != body.Type) { body = Expression.Convert(body, resultType); } return(FastExpression.Lambda <Func <ParameterContext, T> >(body, parameterContextArgument)); }
public static void BuildFilter(IndexInfo index) { ArgumentValidator.EnsureArgumentNotNull(index, "index"); var parameter = Expression.Parameter(WellKnownOrmTypes.Tuple, "tuple"); var builder = new PartialIndexFilterBuilder(index, parameter); var body = builder.Visit(index.FilterExpression.Body); var filter = new PartialIndexFilterInfo { Expression = FastExpression.Lambda(body, parameter), Fields = builder.usedFields, }; index.Filter = filter; }
private static Expression <Func <IEnumerable <Tuple> > > RemapRawProviderSource(Expression <Func <IEnumerable <Tuple> > > source, MapTransform mappingTransform) { var selectMethodInfo = typeof(Enumerable) .GetMethods() .Single(methodInfo => methodInfo.Name == "Select" && methodInfo.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Func <,>)) .MakeGenericMethod(typeof(Tuple), typeof(Tuple)); Func <Tuple, Tuple> selector = tuple => mappingTransform.Apply(TupleTransformType.Auto, tuple); var newExpression = Expression.Call(selectMethodInfo, source.Body, Expression.Constant(selector)); return((Expression <Func <IEnumerable <Tuple> > >)FastExpression.Lambda(newExpression)); }
private Expression VisitQuerySingle(MethodCallExpression mc) { var returnType = mc.Method.ReturnType; var argument = mc.Arguments[0]; var queryAll = Expression.Call(null, WellKnownMembers.Query.All.MakeGenericMethod(returnType)); var source = ConstructQueryable(queryAll); var parameter = Expression.Parameter(returnType, "entity"); var keyAccessor = Expression.MakeMemberAccess(parameter, WellKnownMembers.IEntityKey); var equility = Expression.Equal(keyAccessor, argument); var lambda = FastExpression.Lambda(equility, parameter); return(VisitFirstSingle(source, lambda, mc.Method, false)); }
public IQueryable SelectPropertySwitchingToGeneric(IQueryable queryable, string propertyName) { Type entityType = queryable.ElementType; var propertyInfo = entityType.GetProperty(propertyName); var parameter = Expression.Parameter(entityType, "paramName"); var body = Expression.MakeMemberAccess(parameter, propertyInfo); var lambda = FastExpression.Lambda(body, parameter); // paramName=>paramName.Name var getPropertyValuesMethodInfo = typeof(MiscTest).GetMethod("SelectPropertyGeneric"); var genericMethod = getPropertyValuesMethodInfo.MakeGenericMethod(entityType, propertyInfo.PropertyType); return((IQueryable)genericMethod.Invoke(null, new object[] { queryable, lambda })); }
public void AddValues() { foreach (SetDescriptor descriptor in Descriptors) { var addContext = new AddValueContext { Descriptor = descriptor, Lambda = FastExpression.Lambda( WellKnownMembers.FuncOfTArgTResultType.MakeGenericType(typeof(T), descriptor.Expression.Type), descriptor.Expression, descriptor.Parameter), Statement = Statement }; descriptor.Expression.Visit( delegate(ParameterExpression p) { // ReSharper disable AccessToModifiedClosure if (p == descriptor.Parameter) { // ReSharper restore AccessToModifiedClosure addContext.EntityParamExists = true; } return(p); }); addContext.SubqueryExists = descriptor.Expression.IsContainsQuery(); addContext.Field = descriptor.Field; if (addContext.Field.IsEntitySet) { throw new NotSupportedException("EntitySets are not supported"); } if (addContext.Field.IsEntity) { AddEntityValue(addContext); continue; } if (!addContext.EntityParamExists && addContext.SubqueryExists) { AddComputedStaticExpression(addContext); } else if (addContext.EntityParamExists || addContext.SubqueryExists) { AddComputedExpression(addContext); } else { AddConstantValue(addContext); } } }
private Func <IEnumerable <Tuple>, Session, Dictionary <Parameter <Tuple>, Tuple>, ParameterContext, TResult> BuildMaterializer <TResult>( ProjectionExpression projection, IEnumerable <Parameter <Tuple> > tupleParameters) { var rs = Expression.Parameter(typeof(IEnumerable <Tuple>), "rs"); var session = Expression.Parameter(typeof(Session), "session"); var tupleParameterBindings = Expression.Parameter(typeof(Dictionary <Parameter <Tuple>, Tuple>), "tupleParameterBindings"); var parameterContext = Expression.Parameter(typeof(ParameterContext), "parameterContext"); var itemProjector = projection.ItemProjector; var materializationInfo = itemProjector.Materialize(context, tupleParameters); var elementType = itemProjector.Item.Type; var materializeMethod = MaterializationHelper.MaterializeMethodInfo .MakeGenericMethod(elementType); var compileMaterializerMethod = MaterializationHelper.CompileItemMaterializerMethodInfo .MakeGenericMethod(elementType); var itemMaterializer = compileMaterializerMethod.Invoke(null, new[] { materializationInfo.Expression }); Expression <Func <Session, int, MaterializationContext> > materializationContextCtor = (s, n) => new MaterializationContext(s, n); var materializationContextExpression = materializationContextCtor .BindParameters( session, Expression.Constant(materializationInfo.EntitiesInRow)); Expression body = Expression.Call( materializeMethod, rs, materializationContextExpression, parameterContext, Expression.Constant(itemMaterializer), tupleParameterBindings); if (projection.IsScalar) { var scalarMethodName = projection.ResultType.ToString(); var enumerableMethod = typeof(Enumerable) .GetMethods(BindingFlags.Static | BindingFlags.Public) .First(m => m.Name == scalarMethodName && m.GetParameters().Length == 1) .MakeGenericMethod(elementType); body = Expression.Call(enumerableMethod, body); } body = body.Type == typeof(TResult) ? body : Expression.Convert(body, typeof(TResult)); var projectorExpression = FastExpression.Lambda <Func <IEnumerable <Tuple>, Session, Dictionary <Parameter <Tuple>, Tuple>, ParameterContext, TResult> >(body, rs, session, tupleParameterBindings, parameterContext); return(projectorExpression.CachingCompile()); }
/// <summary> /// Extracts the parameter. /// </summary> /// <param name="expression">The expression.</param> public Expression <Func <T> > ExtractParameter <T>(Expression expression) { if (expression.NodeType == ExpressionType.Lambda) { return((Expression <Func <T> >)expression); } Type type = expression.Type; if (type.IsValueType) { expression = Expression.Convert(expression, typeof(T)); } var lambda = FastExpression.Lambda <Func <T> >(expression); return(lambda); }
public static bool TryRewrite(LambdaExpression resultSelector, ParameterExpression sourceParameter, ParameterExpression targetParameter, out LambdaExpression result) { var parameters = resultSelector.Parameters .Select(p => p == sourceParameter ? targetParameter : p) .ToArray(); var rewriter = new SelectManySelectorRewriter(sourceParameter, targetParameter); var body = rewriter.Visit(resultSelector.Body); if (rewriter.processingFailed) { result = null; return(false); } result = FastExpression.Lambda(body, parameters); return(true); }
private void AddConstantValue(AddValueContext addContext) { SqlTableColumn column = SqlDml.TableColumn(addContext.Statement.Table, addContext.Field.Column.Name); SqlExpression value; object constant = FastExpression.Lambda(addContext.Lambda.Body).Compile().DynamicInvoke(); if (constant == null) { value = SqlDml.Null; } else { QueryParameterBinding binding = parent.QueryBuilder.CreateParameterBinding(constant.GetType(), context => constant); parent.Bindings.Add(binding); value = binding.ParameterReference; } addContext.Statement.AddValue(column, value); }
/// <summary> /// Perform one iteration of searching for a root with Newton-Raphson method /// </summary> /// <param name="f"></param> /// <param name="df"></param> /// <param name="value"></param> /// <param name="precision"></param> /// <returns></returns> private static ComplexNumber NewtonIter(FastExpression f, FastExpression df, Complex value, int precision) { Complex prev = value; Complex ChooseGood() { if (Complex.Abs(prev - value) > (double)MathS.Settings.PrecisionErrorCommon.Value) { return(double.NaN); } else { return(value); } } int minCheckIters = (int)Math.Sqrt(precision); for (int i = 0; i < precision; i++) { if (i == precision - 1) { prev = value; //.Copy(); } try // TODO: remove try catch in for { var dfv = df.Substitute(value); if (dfv == 0) { return(ChooseGood()); } value -= f.Substitute(value) / dfv; } catch (OverflowException) { return(ChooseGood()); } if (i > minCheckIters && prev == value) { return(value); } } return(ChooseGood()); }
/// <summary> /// Compiles from strings (see Compile for more details) /// </summary> /// <param name="func"></param> /// <param name="variables"></param> /// <returns></returns> internal static FastExpression Compile(Entity func, params string[] variables) { var varNamespace = new Dictionary <string, int>(); int id = 0; foreach (var varName in variables) { varNamespace[varName] = id; id++; } func = func.SubstituteConstants(); var res = new FastExpression(variables.Length, func); func.UpdateHash(); // Count hash for O(N) Entity.HashOccurancesUpdate(func); // Update occurances for each node for O(N) instead of O(N^2) InnerCompile(func, res, variables, varNamespace); res.Seal(); // Creates stack return(res); }