// TODO should we also handle array accesses?

        protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
        {
            var copy = (IMethodInvokeExpression)base.ConvertMethodInvoke(imie);

            for (int i = 0; i < copy.Arguments.Count; i++)
            {
                var arg = copy.Arguments[i] as IMethodInvokeExpression;
                if (arg == null)
                {
                    continue;
                }
                var n = (ITypeReferenceExpression)arg.Method.Target;

                // TODO we should be handling all methods but they cause compiler errors e.g.
                // if(expr) {
                //   Gaussian intermediate = Gaussian.Uniform();
                //   double rv = Factor.Random(intermediate);
                // }
                if (!Recognizer.IsTypeReferenceTo(n, typeof(Factor)))
                {
                    continue;
                }

                copy.Arguments[i] = MakeIntermediateVariable(arg);
            }
            return(copy);
        }
 private static void WriteMethodInvoke(LanguageWriter w, IMethodInvokeExpression exp)
 {
     WriteExpression(w, exp.Method, PREC_MEM_ACCESS > GetExpressionPrecedence(exp.Method));
     w.Write("(");
     w.WriteExpressionCollection(exp.Arguments);
     w.Write(")");
 }
        public override bool Equals(object obj)
        {
            if (this == obj)
            {
                return(true);
            }

            IMethodInvokeExpression expression = obj as IMethodInvokeExpression;

            if (expression == null ||
                !Method.Equals(expression.Method) ||
                Arguments.Count != expression.Arguments.Count)
            {
                return(false);
            }

            for (int i = 0; i < Arguments.Count; i++)
            {
                if (!(Arguments[i].Equals(expression.Arguments[i])))
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #4
0
        protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
        {
            int methodIndex;

            if (analysis.IndexOfMethod.TryGetValue(imie.Method.Method, out methodIndex))
            {
                MethodDetails methodDetails = detailsOfMethod[methodIndex];
                if (!methodDetails.liveFieldsAtEndOfMethod.ContainsAll(liveFields))
                {
                    methodDetails.liveFieldsAtEndOfMethod.AddRange(liveFields);
                    methodsToAnalyze.Add(methodIndex);
                }
                if (methodsToAnalyze.Contains(methodIndex))
                {
                    var liveFieldsAfterInvoke    = (Set <IFieldDeclaration>)liveFields.Clone();
                    var liveVariablesAfterInvoke = (Set <IVariableDeclaration>)liveVariables.Clone();
                    var usedVariablesAfterInvoke = (Set <IVariableDeclaration>)usedVariables.Clone();
                    AnalyzeMethod(methodIndex);
                    liveFields    = liveFieldsAfterInvoke;
                    liveVariables = liveVariablesAfterInvoke;
                    usedVariables = usedVariablesAfterInvoke;
                }
                liveFields.AddRange(methodDetails.fieldsReadBeforeWritten);
                liveFields.Remove(methodDetails.fieldsWrittenBeforeRead);
            }
            return(base.ConvertMethodInvoke(imie));
        }
Beispiel #5
0
        /// <summary>
        /// Modify the argument of Infer to be the marginal channel variable i.e. Infer(a) transforms to Infer(a_marginal)
        /// </summary>
        /// <param name="imie"></param>
        ///
        /// <returns>The modified expression</returns>
        protected IExpression ConvertInfer(IMethodInvokeExpression imie)
        {
            IExpression arg  = imie.Arguments[0];
            object      decl = AddMarginalStatements(arg);
            //if (arg is IArgumentReferenceExpression iare) AddMarginalStatements(iare);
            //else if (arg is IVariableReferenceExpression ivre) decl = ivre.Variable.Resolve();
            //else return imie;
            // Find expression for the marginal of interest
            IVariableDeclaration marginalDecl;
            ExpressionEvaluator  eval  = new ExpressionEvaluator();
            QueryType            query = (imie.Arguments.Count < 3) ? null : (QueryType)eval.Evaluate(imie.Arguments[2]);
            bool isOutput = (query == QueryTypes.MarginalDividedByPrior);

            if (!isOutput || !useOfVariable.TryGetValue(decl, out marginalDecl))
            {
                marginalDecl = marginalOfVariable[decl];
            }
            IMethodInvokeExpression mie = Builder.MethodInvkExpr();

            mie.Method = imie.Method;
            mie.Arguments.Add(Builder.VarRefExpr(marginalDecl));
            for (int i = 1; i < imie.Arguments.Count; i++)
            {
                mie.Arguments.Add(imie.Arguments[i]);
            }
            // move the IsInferred attribute to the marginal channel
            //context.OutputAttributes.Remove<IsInferred>(ivd);
            if (!context.OutputAttributes.Has <IsInferred>(marginalDecl))
            {
                context.OutputAttributes.Set(marginalDecl, new IsInferred());
            }
            return(mie);
        }
Beispiel #6
0
        public ISimpleStatement CallMethod(IMethodInvokeExpression method)
        {
            ISimpleStatement iss = new SimpleStatement(method, this);

            this.Add(iss);
            return(iss);
        }
Beispiel #7
0
        protected void ProcessDefinition(IExpression expr, IVariableDeclaration targetVar, bool isLhs)
        {
            bool targetIsPointMass       = false;
            IMethodInvokeExpression imie = expr as IMethodInvokeExpression;

            if (imie != null)
            {
                // TODO: consider using a method attribute for this
                if (Recognizer.IsStaticGenericMethod(imie, new Models.FuncOut <PlaceHolder, PlaceHolder, PlaceHolder>(Clone.VariablePoint))
                    )
                {
                    targetIsPointMass = true;
                }
                else
                {
                    FactorManager.FactorInfo info = CodeRecognizer.GetFactorInfo(context, imie);
                    targetIsPointMass = info.IsDeterministicFactor && (
                        (info.ReturnedInAllElementsParameterIndex != -1 && ArgumentIsPointMass(imie.Arguments[info.ReturnedInAllElementsParameterIndex])) ||
                        imie.Arguments.All(ArgumentIsPointMass)
                        );
                }
                if (targetIsPointMass)
                {
                    // do this immediately so all uses are updated
                    if (!context.InputAttributes.Has <ForwardPointMass>(targetVar))
                    {
                        context.OutputAttributes.Set(targetVar, new ForwardPointMass());
                    }
                    // the rest is done later
                    List <IMethodInvokeExpression> list;
                    if (!variablesDefinedPointMass.TryGetValue(targetVar, out list))
                    {
                        list = new List <IMethodInvokeExpression>();
                        variablesDefinedPointMass.Add(targetVar, list);
                    }
                    // this code needs to be synchronized with MessageTransform.ConvertMethodInvoke
                    if (Recognizer.IsStaticGenericMethod(imie, new Func <PlaceHolder, int, PlaceHolder[]>(Clone.Replicate)) ||
                        Recognizer.IsStaticGenericMethod(imie, new Func <IReadOnlyList <PlaceHolder>, IReadOnlyList <int>, PlaceHolder[]>(Collection.GetItems)) ||
                        Recognizer.IsStaticGenericMethod(imie, new Func <IReadOnlyList <PlaceHolder>, IReadOnlyList <IReadOnlyList <int> >, PlaceHolder[][]>(Collection.GetJaggedItems)) ||
                        Recognizer.IsStaticGenericMethod(imie, new Func <IReadOnlyList <PlaceHolder>, IReadOnlyList <IReadOnlyList <IReadOnlyList <int> > >, PlaceHolder[][][]>(Collection.GetDeepJaggedItems)) ||
                        Recognizer.IsStaticGenericMethod(imie, new Func <IReadOnlyList <IReadOnlyList <PlaceHolder> >, IReadOnlyList <int>, IReadOnlyList <int>, PlaceHolder[]>(Collection.GetItemsFromJagged)) ||
                        Recognizer.IsStaticGenericMethod(imie, new Func <IReadOnlyList <IReadOnlyList <IReadOnlyList <PlaceHolder> > >, IReadOnlyList <int>, IReadOnlyList <int>, IReadOnlyList <int>, PlaceHolder[]>(Collection.GetItemsFromDeepJagged)) ||
                        Recognizer.IsStaticGenericMethod(imie, new Func <IReadOnlyList <IReadOnlyList <PlaceHolder> >, IReadOnlyList <IReadOnlyList <int> >, IReadOnlyList <IReadOnlyList <int> >, PlaceHolder[][]>(Collection.GetJaggedItemsFromJagged))
                        )
                    {
                        list.Add(imie);
                    }
                }
            }
            if (!targetIsPointMass && !(expr is IArrayCreateExpression))
            {
                variablesDefinedNonPointMass.Add(targetVar);
                if (variablesDefinedPointMass.ContainsKey(targetVar))
                {
                    variablesDefinedPointMass.Remove(targetVar);
                    context.OutputAttributes.Remove <ForwardPointMass>(targetVar);
                }
            }
        }
Beispiel #8
0
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     if (CodeRecognizer.IsInfer(imie))
     {
         return(ConvertInfer(imie));
     }
     return(base.ConvertMethodInvoke(imie));
 }
        protected override IStatement ConvertExpressionStatement(IExpressionStatement ies)
        {
            if (parent == null)
            {
                return(ies);
            }
            bool keepIfStatement = false;
            // Only keep the surrounding if statement when a factor or constraint is being added.
            IExpression expr = ies.Expression;

            if (expr is IMethodInvokeExpression)
            {
                keepIfStatement = true;
                if (CodeRecognizer.IsInfer(expr))
                {
                    keepIfStatement = false;
                }
            }
            else if (expr is IAssignExpression)
            {
                keepIfStatement = false;
                IAssignExpression       iae  = (IAssignExpression)expr;
                IMethodInvokeExpression imie = iae.Expression as IMethodInvokeExpression;
                if (imie != null)
                {
                    keepIfStatement = true;
                    if (imie.Arguments.Count > 0)
                    {
                        // Statements that copy evidence variables should not send evidence messages.
                        IVariableDeclaration ivd    = Recognizer.GetVariableDeclaration(iae.Target);
                        IVariableDeclaration ivdArg = Recognizer.GetVariableDeclaration(imie.Arguments[0]);
                        if (ivd != null && context.InputAttributes.Has <DoNotSendEvidence>(ivd) &&
                            ivdArg != null && context.InputAttributes.Has <DoNotSendEvidence>(ivdArg))
                        {
                            keepIfStatement = false;
                        }
                    }
                }
                else
                {
                    expr = iae.Target;
                }
            }
            if (expr is IVariableDeclarationExpression)
            {
                IVariableDeclarationExpression ivde = (IVariableDeclarationExpression)expr;
                IVariableDeclaration           ivd  = ivde.Variable;
                keepIfStatement = CodeRecognizer.IsStochastic(context, ivd) && !context.InputAttributes.Has <DoNotSendEvidence>(ivd);
            }
            if (!keepIfStatement)
            {
                return(ies);
            }
            IConditionStatement cs = Builder.CondStmt(parent.Condition, Builder.BlockStmt());

            cs.Then.Statements.Add(ies);
            return(cs);
        }
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     if (CodeRecognizer.IsInfer(imie))
     {
         // ignore the variable use
         return(imie);
     }
     return(base.ConvertMethodInvoke(imie));
 }
Beispiel #11
0
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     if (CodeRecognizer.IsInfer(imie))
     {
         return(imie);
     }
     CheckForDuplicateArguments(imie);
     return(base.ConvertMethodInvoke(imie));
 }
Beispiel #12
0
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     // do not count argument of Infer as a use
     if (CodeRecognizer.IsInfer(imie))
     {
         return(imie);
     }
     return(base.ConvertMethodInvoke(imie));
 }
        private void CheckMethodArgumentCount(IMethodInvokeExpression imie)
        {
            MethodInfo method     = (MethodInfo)imie.Method.Method.MethodInfo;
            var        parameters = method.GetParameters();

            if (parameters.Length != imie.Arguments.Count)
            {
                Error($"Method given {imie.Arguments.Count} argument(s) but expected {parameters.Length}");
            }
        }
Beispiel #14
0
        public IMethodInvokeExpression Invoke(IExpression[] arguments)
        {
            IMethodInvokeExpression result = this.Invoke();

            foreach (IExpression ie in arguments)
            {
                result.ArgumentExpressions.Add(ie);
            }
            return(result);
        }
Beispiel #15
0
        internal IExpression GetMethodInvokeExpression(bool inline = false)
        {
            IExpression[] argExprs = new IExpression[args.Count];
            for (int i = 0; i < argExprs.Length; i++)
            {
                argExprs[i] = args[i].GetExpression();
            }
            if (inline || CanBeInlined())
            {
                if (op == Variable.Operator.Plus)
                {
                    return(Builder.BinaryExpr(argExprs[0], BinaryOperator.Add, argExprs[1]));
                }
                else if (op == Variable.Operator.Minus)
                {
                    return(Builder.BinaryExpr(argExprs[0], BinaryOperator.Subtract, argExprs[1]));
                }
                else if (op == Variable.Operator.LessThan)
                {
                    return(Builder.BinaryExpr(argExprs[0], BinaryOperator.LessThan, argExprs[1]));
                }
                else if (op == Variable.Operator.LessThanOrEqual)
                {
                    return(Builder.BinaryExpr(argExprs[0], BinaryOperator.LessThanOrEqual, argExprs[1]));
                }
                else if (op == Variable.Operator.GreaterThan)
                {
                    return(Builder.BinaryExpr(argExprs[0], BinaryOperator.GreaterThan, argExprs[1]));
                }
                else if (op == Variable.Operator.GreaterThanOrEqual)
                {
                    return(Builder.BinaryExpr(argExprs[0], BinaryOperator.GreaterThanOrEqual, argExprs[1]));
                }
                else if (op == Variable.Operator.Equal)
                {
                    return(Builder.BinaryExpr(argExprs[0], BinaryOperator.ValueEquality, argExprs[1]));
                }
                else if (op == Variable.Operator.NotEqual)
                {
                    return(Builder.BinaryExpr(argExprs[0], BinaryOperator.ValueInequality, argExprs[1]));
                }
            }
            IMethodInvokeExpression imie = null;

            if (method.IsGenericMethod && !method.ContainsGenericParameters)
            {
                imie = Builder.StaticGenericMethod(method, argExprs);
            }
            else
            {
                imie = Builder.StaticMethod(method, argExprs);
            }
            return(imie);
        }
Beispiel #16
0
        /// <summary>
        /// Modify the argument of Infer to be the marginal channel variable i.e. Infer(a) transforms to Infer(a_marginal).
        /// </summary>
        /// <param name="imie"></param>
        /// <returns></returns>
        protected IExpression ConvertInfer(IMethodInvokeExpression imie)
        {
            IVariableReferenceExpression ivre = imie.Arguments[0] as IVariableReferenceExpression;

            if (ivre == null)
            {
                //Error("Argument to Infer() must be a variable reference, was " + imie.Arguments[0] + ".");
                return(imie);
            }
            // Find expression for the marginal of interest
            IVariableDeclaration         ivd  = ivre.Variable.Resolve();
            VariableToChannelInformation vtci = context.InputAttributes.Get <VariableToChannelInformation>(ivd);

            if (vtci == null)
            {
                return(imie);              // The argument is constant
            }
            ExpressionEvaluator  eval      = new ExpressionEvaluator();
            QueryType            query     = (QueryType)eval.Evaluate(imie.Arguments[2]);
            IVariableDeclaration inferDecl = null;

            if (query == QueryTypes.Marginal)
            {
                inferDecl = vtci.marginalChannel.decl;
            }
            else if (query == QueryTypes.Samples)
            {
                inferDecl = vtci.samplesChannel.decl;
            }
            else if (query == QueryTypes.Conditionals)
            {
                inferDecl = vtci.conditionalsChannel.decl;
            }
            else
            {
                return(imie); // Error("Unrecognized query '"+query+"'");
            }
            IMethodInvokeExpression mie = Builder.MethodInvkExpr();

            mie.Method = imie.Method;
            mie.Arguments.Add(Builder.VarRefExpr(inferDecl));
            for (int i = 1; i < imie.Arguments.Count; i++)
            {
                mie.Arguments.Add(imie.Arguments[i]);
            }
            // move the IsInferred attribute to the inferred channel
            context.OutputAttributes.Remove <IsInferred>(ivd);
            if (!context.OutputAttributes.Has <IsInferred>(inferDecl))
            {
                context.OutputAttributes.Set(inferDecl, new IsInferred());
                context.OutputAttributes.Add(inferDecl, new QueryTypeCompilerAttribute(query));
            }
            return(mie);
        }
Beispiel #17
0
 /// <summary>
 /// Analyse equality constraints, which appear as static method calls to Constrain.Equal
 /// </summary>
 /// <param name="imie"></param>
 /// <returns></returns>
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     // If this is a constrain equal, then we will add the equality to the equality map.
     if (Recognizer.IsStaticGenericMethod(imie, new Action <PlaceHolder, PlaceHolder>(Constrain.Equal <PlaceHolder>)))
     {
         int node0 = CreateNodeAndEdges(imie.Arguments[0]);
         int node1 = CreateNodeAndEdges(imie.Arguments[1]);
         graph.AddEdge(node0, node1);
         graph.AddEdge(node1, node0);
     }
     return(base.ConvertMethodInvoke(imie));
 }
Beispiel #18
0
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     if (Recognizer.IsStaticGenericMethod(imie, new Models.FuncOut <object, object, object>(LowPriority.SequentialCut)))
     {
         IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(imie.Arguments[1]);
         if (ivd != null)
         {
             cutVariables.Add(ivd);
         }
     }
     return(base.ConvertMethodInvoke(imie));
 }
Beispiel #19
0
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     if (imie.Method.Target is IThisReferenceExpression)
     {
         IMethodDeclaration imd = context.FindAncestor <IMethodDeclaration>();
         int sourceMethod       = GetMethodIndex(imd);
         int targetMethod       = GetMethodIndex(imie.Method.Method);
         MethodGraph.AddEdge(sourceMethod, targetMethod);
         //Trace.WriteLine($"{sourceMethod} {methods[sourceMethod].Name} called {targetMethod} {methods[targetMethod].Name}");
     }
     return(base.ConvertMethodInvoke(imie));
 }
 public override bool Visit(IMethodInvokeExpression expression, object context)
 {
     _stack.Push(expression);
     try
     {
         return(base.Visit(expression, context));
     }
     finally
     {
         _stack.Pop();
     }
 }
        private IForStatement ConvertForWithParallelSchedule(IForStatement ifs, IVariableDeclaration loopVar, ParallelScheduleExpression pse)
        {
            // Convert this loop into for(block) Parallel.For(thread) for(indexInBlock)
            IVariableDeclaration loopVarBlock   = VariableInformation.GenerateLoopVar(context, loopVar.Name + "_Block");
            Sequential           sequentialAttr = new Sequential();

            context.OutputAttributes.Set(loopVarBlock, sequentialAttr);
            IVariableDeclaration loopVarInBlock = VariableInformation.GenerateLoopVar(context, loopVar.Name + "_inBlock");

            context.OutputAttributes.Set(loopVarInBlock, sequentialAttr);
            string paramName   = VariableInformation.GenerateName(context, loopVar.Name + "_thread");
            var    threadParam = Builder.Param(paramName, typeof(int));

            if (!pse.scheduleExpression.GetExpressionType().Equals(typeof(int[][][])))
            {
                Error("argument to ParallelSchedule attribute is not of type int[][][]");
            }
            IExpression   itemsInThread    = Builder.ArrayIndex(pse.scheduleExpression, Builder.ParamRef(threadParam));
            IExpression   itemsInBlock     = Builder.ArrayIndex(itemsInThread, Builder.VarRefExpr(loopVarBlock));
            IExpression   itemCountInBlock = Builder.PropRefExpr(itemsInBlock, typeof(int[]), "Length");
            IExpression   threadCount      = Builder.PropRefExpr(pse.scheduleExpression, typeof(int[][][]), "Length");
            IExpression   zero             = Builder.LiteralExpr(0);
            IExpression   blockCount       = Builder.PropRefExpr(Builder.ArrayIndex(pse.scheduleExpression, zero), typeof(int[][]), "Length");
            IForStatement loopInBlock      = Builder.ForStmt(loopVarInBlock, itemCountInBlock);
            bool          isBackwardLoop   = !Recognizer.IsForwardLoop(ifs);

            if (isBackwardLoop)
            {
                Recognizer.ReverseLoopDirection(loopInBlock);
            }
            var assignLoopVar = Builder.AssignStmt(Builder.VarDeclExpr(loopVar), Builder.ArrayIndex(itemsInBlock, Builder.VarRefExpr(loopVarInBlock)));

            loopInBlock.Body.Statements.Add(assignLoopVar);
            ConvertStatements(loopInBlock.Body.Statements, ifs.Body.Statements);
            //loopInBlock.Body.Statements.AddRange(ifs.Body.Statements);
            IAnonymousMethodExpression bodyDelegate = Builder.AnonMethodExpr(typeof(Action <int>));

            bodyDelegate.Body = Builder.BlockStmt();
            bodyDelegate.Body.Statements.Add(loopInBlock);
            bodyDelegate.Parameters.Add(threadParam);
            Delegate d = new Func <int, int, Action <int>, ParallelLoopResult>(Parallel.For);
            IMethodInvokeExpression parallelFor = Builder.StaticMethod(d, zero, threadCount, bodyDelegate);
            IStatement    loopThread            = Builder.ExprStatement(parallelFor);
            IForStatement loopBlock             = Builder.ForStmt(loopVarBlock, blockCount);

            loopBlock.Body.Statements.Add(loopThread);
            if (isBackwardLoop)
            {
                Recognizer.ReverseLoopDirection(loopBlock);
            }
            return(loopBlock);
        }
Beispiel #22
0
        protected override IExpression ConvertAddressOut(IAddressOutExpression iaoe)
        {
            IVariableDeclaration targetVar = Recognizer.GetVariableDeclaration(iaoe.Expression);

            if (targetVar == null || variablesDefinedNonPointMass.Contains(targetVar))
            {
                return(base.ConvertAddressOut(iaoe));
            }
            IMethodInvokeExpression imie = context.FindAncestor <IMethodInvokeExpression>();

            ProcessDefinition(imie, targetVar, isLhs: false);
            return(base.ConvertAddressOut(iaoe));
        }
Beispiel #23
0
 public override void VisitMethodInvokeExpression(IMethodInvokeExpression value)
 {
     VisitExpression(value.Method);
     _formatter.Write("(");
     foreach (IExpression expression in value.Arguments)
     {
         if (value.Arguments.IndexOf(expression) != 0)
         {
             _formatter.Write(", ");
         }
         VisitExpression(expression);
     }
     _formatter.Write(")");
 }
Beispiel #24
0
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     if (useJaggedSubarrayWithMarginal && Recognizer.IsStaticGenericMethod(imie, new Func <IReadOnlyList <PlaceHolder>, int[][], PlaceHolder[][]>(Collection.JaggedSubarray)))
     {
         IExpression          arrayExpr = imie.Arguments[0];
         IVariableDeclaration ivd       = Recognizer.GetVariableDeclaration(arrayExpr);
         // restrict to IVariableReferenceExpression for simplicity
         if (ivd != null && !context.InputAttributes.Has <PointEstimate>(ivd) && arrayExpr is IVariableReferenceExpression)
         {
             variablesExcludingVariableFactor.Add(ivd);
         }
     }
     return(base.ConvertMethodInvoke(imie));
 }
        /// <summary>
        /// Convert random assignments to derived variables
        /// </summary>
        /// <param name="iae"></param>
        /// <returns></returns>
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            iae = (IAssignExpression)base.ConvertAssign(iae);
            IStatement ist = context.FindAncestor <IStatement>();

            if (!context.InputAttributes.Has <Models.Constraint>(ist) &&
                (iae.Expression is IMethodInvokeExpression))
            {
                IMethodInvokeExpression imie = (IMethodInvokeExpression)iae.Expression;
                IVariableDeclaration    ivd  = Recognizer.GetVariableDeclaration(iae.Target);
                if (ivd != null)
                {
                    bool isDerived = context.InputAttributes.Has <DerivedVariable>(ivd);
                    if (isDerived)
                    {
                        FactorManager.FactorInfo info = CodeRecognizer.GetFactorInfo(context, imie);
                        if (!info.IsDeterministicFactor)
                        {
                            // The variable is derived, but this definition is not derived.
                            // Thus we must convert
                            //   y = sample()
                            // into
                            //   y_random = sample()
                            //   y = Copy(y_random)
                            // where y_random is not derived.
                            VariableInformation varInfo = VariableInformation.GetVariableInformation(context, ivd);
                            IList <IStatement>  stmts   = Builder.StmtCollection();
                            string name = ivd.Name + "_random" + (Count++);
                            List <IList <IExpression> > indices  = Recognizer.GetIndices(iae.Target);
                            IVariableDeclaration        cloneVar = varInfo.DeriveIndexedVariable(stmts, context, name, indices, copyInitializer: true);
                            context.OutputAttributes.Remove <DerivedVariable>(cloneVar);
                            stmts.Add(Builder.AssignStmt(Builder.VarRefExpr(cloneVar), iae.Expression));
                            int ancIndex = context.FindAncestorIndex <IStatement>();
                            context.AddStatementsBeforeAncestorIndex(ancIndex, stmts);
                            Type tp = iae.Target.GetExpressionType();
                            if (tp == null)
                            {
                                Error("Could not determine type of expression: " + iae.Target);
                                return(iae);
                            }
                            IExpression copy = Builder.StaticGenericMethod(new Func <PlaceHolder, PlaceHolder>(Clone.Copy), new Type[] { tp },
                                                                           Builder.VarRefExpr(cloneVar));
                            iae = Builder.AssignExpr(iae.Target, copy);
                        }
                    }
                }
            }
            return(iae);
        }
 protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
 {
     if (CodeRecognizer.IsIsIncreasing(imie))
     {
         IExpression          arg = imie.Arguments[0];
         IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(arg);
         if (backwardLoops.Contains(ivd.Name))
         {
             return(Builder.LiteralExpr(false));
         }
         else
         {
             return(Builder.LiteralExpr(true));
         }
     }
     return(base.ConvertMethodInvoke(imie));
 }
Beispiel #27
0
        public IMethodInvokeExpression Invoke(object[] arguments)
        {
            IMethodInvokeExpression result = this.Invoke();

            foreach (object vt in arguments)
            {
                if (vt is IExpression)
                {
                    result.ArgumentExpressions.Add((IExpression)vt);
                }
                else if (vt is ValueType || vt is string)
                {
                    result.ArgumentExpressions.Add(new PrimitiveExpression(vt));
                }
            }
            return(result);
        }
Beispiel #28
0
        /// <summary>
        /// Converts for loops into parallel for loops.
        /// </summary>
        /// <param name="ifs">The for loop to convert</param>
        /// <returns>The converted statement</returns>
        protected override IStatement ConvertFor(IForStatement ifs)
        {
            if (context.InputAttributes.Has <ConvergenceLoop>(ifs) || context.InputAttributes.Has <HasOffsetIndices>(ifs) || (ifs is IBrokenForStatement))
            {
                return(base.ConvertFor(ifs));
            }
            IVariableDeclaration loopVar = Recognizer.LoopVariable(ifs);

            if (context.InputAttributes.Has <Sequential>(loopVar))
            {
                return(base.ConvertFor(ifs));
            }
            // Convert this loop to a parallel for loop
            IExpression loopSize  = null;
            IExpression loopStart = null;

            if (Recognizer.IsForwardLoop(ifs))
            {
                loopStart = Recognizer.LoopStartExpression(ifs);
                loopSize  = Recognizer.LoopSizeExpression(ifs);
            }
            else if (ifs.Condition is IBinaryExpression)
            {
                IBinaryExpression ibe = (IBinaryExpression)ifs.Condition;
                if (ibe.Operator == BinaryOperator.GreaterThanOrEqual)
                {
                    // loop is "for(int i = end; i >= start; i--)"
                    loopStart = ibe.Right;
                    loopSize  = Builder.BinaryExpr(Recognizer.LoopStartExpression(ifs), BinaryOperator.Add, Builder.LiteralExpr(1));
                }
            }
            if (loopSize == null)
            {
                return(base.ConvertFor(ifs));
            }
            IAnonymousMethodExpression bodyDelegate = Builder.AnonMethodExpr(typeof(Action <int>));

            bodyDelegate.Body = ifs.Body;
            bodyDelegate.Parameters.Add(Builder.Param(loopVar.Name, loopVar.VariableType));
            Delegate d = new Func <int, int, Action <int>, ParallelLoopResult>(Parallel.For);
            IMethodInvokeExpression parallelFor = Builder.StaticMethod(d, loopStart, loopSize, bodyDelegate);
            IStatement st = Builder.ExprStatement(parallelFor);

            return(st);
        }
Beispiel #29
0
        private IStatement ConvertModelMethodCall(IMethodInvokeExpression imie)
        {
            var modelMethodDecl       = imie.Method.Method.Resolve();
            var modelMethodParamDecls = modelMethodDecl.Parameters.ToArray();

            foreach (var var in inferredVariables)
            {
                var inferMethod = new Action <object, string>(InferNet.Infer);
                var call        = Builder.StaticMethod(inferMethod, BuildMemberRefExpr(var), Builder.LiteralExpr(var.Name));
                modelMethodDecl.Body.Statements.Add(Builder.ExprStatement(call));
            }

            foreach (var var in observedVariables)
            {
                modelMethodDecl.Parameters.Add(Builder.Param(var.Name, GetMemberReferenceType(var)));
            }

            var tds = engine.Compiler.GetTransformedDeclaration(originalTypeDecl, imie.Method.Method.MethodInfo, new AttributeRegistry <object, ICompilerAttribute>(true));
            var algorithmTypeDecl = tds.Single();

            // give algorithm a unique name
            algorithmTypeDecl.Name = algorithmTypeDecl.Name + (algorithmTypeDecls.Count + 1);
            algorithmTypeDecls.Add(algorithmTypeDecl);

            // TODO fix shortcomings in the code model
            var newObj = Builder.ObjCreateExpr();

            newObj.Type = algorithmTypeDecl;

            algorithmVar = Builder.VarDecl("algorithm", algorithmTypeDecl);

            // handle model method parameters
            for (int i = 0; i < imie.Arguments.Count; i++)
            {
                var paramExpr     = imie.Arguments[i];
                var paramDecl     = modelMethodParamDecls[i];
                var observeMethod = GetMethodInfo <IGeneratedAlgorithm>(algo => algo.SetObservedValue(null, null));
                var call          = Builder.Method(Builder.VarRefExpr(algorithmVar), observeMethod, Builder.LiteralExpr(paramDecl.Name), paramExpr);
                context.AddStatementAfterCurrent(Builder.ExprStatement(call));
            }

            return(Builder.AssignStmt(Builder.VarDeclExpr(algorithmVar), newObj));
        }
Beispiel #30
0
        protected override IExpression ConvertMethodInvoke(IMethodInvokeExpression imie)
        {
            if (CodeRecognizer.IsInfer(imie))
            {
                return(ConvertInfer(imie));
            }
            foreach (IExpression arg in imie.Arguments)
            {
                if (arg is IAddressOutExpression)
                {
                    IAddressOutExpression iaoe = (IAddressOutExpression)arg;
                    targetsOfCurrentAssignment.Add(iaoe.Expression);
                }
            }
            if (Recognizer.IsStaticGenericMethod(imie, new Func <IList <PlaceHolder>, int[][], PlaceHolder[][]>(Factor.JaggedSubarray)))
            {
                IExpression          arrayExpr = imie.Arguments[0];
                IVariableDeclaration ivd       = Recognizer.GetVariableDeclaration(imie.Arguments[0]);
                if (ivd != null && (arrayExpr is IVariableReferenceExpression) && this.variablesLackingVariableFactor.Contains(ivd) &&
                    !marginalOfVariable.ContainsKey(ivd))
                {
                    VariableInformation vi    = VariableInformation.GetVariableInformation(context, ivd);
                    IList <IStatement>  stmts = Builder.StmtCollection();
                    CreateMarginalChannel(ivd, vi, stmts);

                    Containers defContainers = context.InputAttributes.Get <Containers>(ivd);
                    int        ancIndex      = defContainers.GetMatchingAncestorIndex(context);
                    Containers missing       = defContainers.GetContainersNotInContext(context, ancIndex);
                    stmts = Containers.WrapWithContainers(stmts, missing.outputs);
                    context.AddStatementsBeforeAncestorIndex(ancIndex, stmts);

                    // none of the arguments should need to be transformed
                    IExpression             indicesExpr  = imie.Arguments[1];
                    IExpression             marginalExpr = Builder.VarRefExpr(marginalOfVariable[ivd]);
                    IMethodInvokeExpression mie          = Builder.StaticGenericMethod(new Models.FuncOut <IList <PlaceHolder>, int[][], IList <PlaceHolder>, PlaceHolder[][]>(Factor.JaggedSubarrayWithMarginal),
                                                                                       new Type[] { Utilities.Util.GetElementType(arrayExpr.GetExpressionType()) },
                                                                                       arrayExpr, indicesExpr, marginalExpr);
                    return(mie);
                }
            }
            return(base.ConvertMethodInvoke(imie));
        }
 public virtual void VisitMethodInvokeExpression(IMethodInvokeExpression value)
 {
     this.VisitExpressionCollection(value.Arguments);
     this.VisitExpression(value.Method);
 }
            private void WriteMethodInvokeExpression(IMethodInvokeExpression expression, IFormatter formatter)
            {
                IMethodReferenceExpression methodReferenceExpression = expression.Method as IMethodReferenceExpression;
                if (methodReferenceExpression != null)
                    this.WriteMethodReferenceExpression(methodReferenceExpression, formatter);
                else
                {
                    formatter.Write("(");
                    this.WriteExpression(expression.Method, formatter);
                    formatter.Write("^");
                    formatter.Write(")");
                }

                formatter.Write("(");
                this.WriteExpressionList(expression.Arguments, formatter);
                formatter.Write(")");
            }
 public virtual IExpression TransformMethodInvokeExpression(IMethodInvokeExpression value)
 {
     this.InsituTransformExpressionCollection(value.Arguments);
     value.Method = this.TransformExpression(value.Method);
     return value;
 }