Example #1
0
        public void Visit(IfStmt ifStmt, object[] args)
        {
            ifStmt.BlockList = new List <IfBlock>();
            do
            {
                IfBlock block = new IfBlock();
                block.Content  = new List <Statement>();
                block.Parent   = ifStmt;
                block.Location = new Location(file, reader.LineNumber, reader.LinePosition);

                if (dic[reader.Name] == "else")
                {
                    block.Condition = null;
                }
                else
                {
                    reader.MoveToAttribute("cond");
                    string          condExpr = reader.Value;
                    Expr.Expression expr     = exprParser.ParseExpr(condExpr,
                                                                    new Location(file, reader.LineNumber, reader.LinePosition).Offset(6)); //TODOļ¼šLocation
                    block.Condition = expr;
                }

                visitMainContent(block, block.Content);

                ifStmt.BlockList.Add(block);
            } while (dic[reader.Name] == "elseif" || dic[reader.Name] == "else");
        }
Example #2
0
        public void GPClassificationTest4()
        {
            bool[]   yData = new bool[] { false, false, true, false };
            double[] xData = new double[]
            {
                -1.555555555555556, -1.111111111111111, -0.2222222222222223, 1.555555555555555
            };
            Vector[]             xVec     = Array.ConvertAll(xData, v => Vector.Constant(1, v));
            Vector[]             basis    = new Vector[] { Vector.Zero(1) };
            IKernelFunction      kf       = new SquaredExponential(0.0);
            SparseGPFixed        sgpf     = new SparseGPFixed(kf, basis);
            Variable <bool>      evidence = Variable.Bernoulli(0.5).Named("evidence");
            IfBlock              block    = Variable.If(evidence);
            Variable <IFunction> f        = Variable.Random <IFunction>(new SparseGP(sgpf)).Named("f");
            Range item = new Range(xVec.Length).Named("item");
            VariableArray <Vector> x = Variable.Array <Vector>(item).Named("x");

            x.ObservedValue = xVec;
            VariableArray <bool> y = Variable.Array <bool>(item).Named("y");

            y.ObservedValue = yData;
            VariableArray <double> h = Variable.Array <double>(item).Named("h");

            h[item] = Variable.FunctionEvaluate(f, x[item]);
            y[item] = (h[item] > 0);
            block.CloseBlock();

            InferenceEngine engine        = new InferenceEngine();
            SparseGP        sgp           = engine.Infer <SparseGP>(f);
            Vector          alphaExpected = Vector.FromArray(new double[] { 0.409693797629808 });

            Console.WriteLine("alpha = {0} should be {1}", sgp.Alpha, alphaExpected);
        }
Example #3
0
        // Emits the codedom statement for an if conditional block.
        public static CodeStatement Emit(IfBlock ifBlock)
        {
            // Create the codedom if statement.
            var i = new CodeConditionStatement();

            // Emit the conditional statements for the if block.
            i.Condition = CodeDomEmitter.EmitCodeExpression(ifBlock.Conditional.ChildExpressions[0]);

            // Emit the lists of statements for the true and false bodies of the if block.

            // Comments need to be added in case the bodies are empty: these two properties
            // of the CodeConditionStatement can't be null.
            i.FalseStatements.Add(new CodeCommentStatement("If condition is false, execute these statements."));
            i.TrueStatements.Add(new CodeCommentStatement("If condition is true, execute these statements."));

            // Emit the statements for the true block
            foreach (var e in ifBlock.TrueBlock.ChildExpressions)
            {
                i.TrueStatements.Add(CodeDomEmitter.EmitCodeStatement(e));
            }

            // Emit the statements for the false block.
            foreach (var e in ifBlock.FalseBlock.ChildExpressions)
            {
                i.FalseStatements.Add(CodeDomEmitter.EmitCodeStatement(e));
            }

            return(i);
        }
Example #4
0
        public IfStatement(ScriptLoadingContext lcontext)
            : base(lcontext)
        {
            bool shorthand = false;

            while (lcontext.Lexer.Current.Type != TokenType.Else && lcontext.Lexer.Current.Type != TokenType.End)
            {
                m_Ifs.Add(CreateIfBlock(lcontext, out shorthand));
                if (shorthand)
                {
                    break;
                }
            }

            if (lcontext.Lexer.Current.Type == TokenType.Else)
            {
                m_Else = CreateElseBlock(lcontext, shorthand);
            }

            if (!shorthand)
            {
                m_End = CheckTokenType(lcontext, TokenType.End).GetSourceRef();
                lcontext.Source.Refs.Add(m_End);
            }
        }
Example #5
0
        /// <summary>
        /// Test modified EP updates
        /// </summary>
        internal void StudentIsPositiveTest()
        {
            double shape     = 1;
            Gamma  precPrior = Gamma.FromShapeAndRate(shape, shape);
            // mean=-1 causes improper messages
            double   mean = -1;
            double   evExpected;
            Gaussian xExpected = StudentIsPositiveExact(mean, precPrior, out evExpected);

            Variable <bool>   evidence = Variable.Bernoulli(0.5).Named("evidence");
            IfBlock           block    = Variable.If(evidence);
            Variable <double> prec     = Variable.Random(precPrior).Named("prec");
            Variable <double> x        = Variable.GaussianFromMeanAndPrecision(mean, prec).Named("x");

            Variable.ConstrainPositive(x);
            block.CloseBlock();

            InferenceEngine engine = new InferenceEngine();

            x.AddAttribute(new TraceMessages());
            //x.InitialiseTo(Gaussian.FromMeanAndVariance(-3.719, 4.836));
            //GaussianOp.ForceProper = false;
            //GaussianOp.modified = true;
            //engine.Compiler.GivePriorityTo(typeof(GaussianOp_Laplace));
            //engine.Compiler.GivePriorityTo(typeof(GaussianOp_Slow));
            GaussianOp_Laplace.modified  = true;
            GaussianOp_Laplace.modified2 = true;
            Console.WriteLine("x = {0} should be {1}", engine.Infer(x), xExpected);
            double evActual = System.Math.Exp(engine.Infer <Bernoulli>(evidence).LogOdds);

            Console.WriteLine("evidence = {0} should be {1}", evActual, evExpected);
        }
Example #6
0
        public void Test2()
        {
            var classBlock = new ClassBlock("TestClass");

            var method1 = new MethodBlock("LoopName");

            method1.Parameters = new FieldBlock[]
            {
                new FieldBlock("name", typeof(string).ToDynamic())
            };

            IfBlock   if1   = new IfBlock();
            ElseBlock else1 = new ElseBlock();

            if1.Condition = new OperationBlock(
                new GetterBlock(method1.Parameters[0], new PropertyBlock("Length", null)),
                OperationType.Equal,
                new ValueBlock(3));

            if1.Add(new ReturnBlock(method1.Parameters[0]));

            else1.Add(new ReturnBlock(new ValueBlock("!")));

            method1.Add(if1);
            method1.Add(else1);

            classBlock.AddMethod(method1);
        }
        public override List <Expression> Compile(Scope scope, ParserContext context)
        {
            var list = new List <Expression>();

            //the whole question stuff
            var questionList   = Question.Compile(scope, context.NewContext());
            var questionResult = questionList.Last().Args3;

            list.AddRange(questionList);

            //we first check if questionStuff.Last() is 0
            list.Add(Factory.BranchIfOne(context + "-IfTrue", questionResult)); //goto IfTrue if equal
            list.Add(Factory.Goto(context + "-Else"));                          //gotoelse
            list.Add(Factory.Label(context + "-IfTrue"));                       //IFTrue label

            list.AddRange(IfBlock.Compile(scope, context, "IfTrue"));           //we add the iftrue block

            list.Add(Factory.Goto(context + "-End"));                           //we jump now to end
            list.Add(Factory.Label(context + "-Else"));                         //Else label

            list.AddRange(ElseBlock.Compile(scope, context, "Else"));           //we add stuff

            list.Add(Factory.Label(context + "-End"));                          //end label

            return(list);
        }
Example #8
0
        public IfBlock Build()
        {
            var ifBlock = new IfBlock(_block);

            var if0Block = new If0BlockBuilder(_reader, ifBlock).Build();

            ifBlock.If0Blocks.Add(if0Block);

            while (_reader.HasNext())
            {
                _reader.Next();

                var token = _reader.Current();

                if (token.Value == Keywords.ELIF)
                {
                    ifBlock.If0Blocks.Add(new If0BlockBuilder(_reader, ifBlock).Build());
                }
                else if (token.Value == Keywords.ELSE)
                {
                    ifBlock.ElseBlock = new ElseBlockBuilder(_reader, ifBlock).Build();

                    return(ifBlock);
                }
                else
                {
                    _reader.Back();

                    return(ifBlock);
                }
            }

            return(ifBlock);
        }
        //[Fact]
        internal void GaussianTimesBetaTest2()
        {
            Variable<bool> evidence = Variable.Bernoulli(0.5).Named("evidence");
            IfBlock block = Variable.If(evidence);
            //Variable<double> x = Variable.GaussianFromMeanAndVariance(1.2, 3.4).Named("x");
            //var x = Variable.Constant<double>(1.2).Named("x"); 
            var s = Variable.Beta(5.6, 4.8).Named("s");
            //var s = Variable.GaussianFromMeanAndPrecision(0, 1).Named("s"); 
            Variable<double> y = 1.2*s;
            y.Name = "y";
            Variable.ConstrainEqualRandom(y, new Gaussian(2.7, 0.001));
            block.CloseBlock();

            InferenceEngine engine = new InferenceEngine(new VariationalMessagePassing());
            var ca = engine.GetCompiledInferenceAlgorithm(evidence, s);
            ca.Reset();

            double oldLogEvidence = double.NegativeInfinity;
            for (int i = 0; i < 1000; i++)
            {
                ca.Update(1);
                double logEvidence1 = ca.Marginal<Bernoulli>(evidence.NameInGeneratedCode).LogOdds;
                Console.WriteLine(logEvidence1);
                if (i > 20 && System.Math.Abs(logEvidence1 - oldLogEvidence) < 0.01)
                    break;
                oldLogEvidence = logEvidence1;
            }

            //Gaussian xActual = ca.Marginal<Gaussian>(x);
            Beta sActual = ca.Marginal<Beta>(s.NameInGeneratedCode);
            //Console.WriteLine("x = {0}", xActual);
            Console.WriteLine("s = {0}", sActual);
        }
Example #10
0
        public IfStatement(LuaParser.Stat_ifblockContext context, ScriptLoadingContext lcontext)
            : base(context, lcontext)
        {
            int ecount = context.exp().Length;
            int bcount = context.block().Length;

            for (int i = 0; i < ecount; i++)
            {
                var exp = context.exp()[i];
                var blk = context.block()[i];

                lcontext.Scope.PushBlock();
                var ifblock = new IfBlock()
                {
                    Exp    = NodeFactory.CreateExpression(exp, lcontext),
                    Block  = NodeFactory.CreateStatement(blk, lcontext),
                    Source = BuildSourceRef(
                        i == 0 ? context.IF().Symbol : context.ELSEIF()[i - 1].Symbol
                        , exp.Stop)
                };
                ifblock.StackFrame = lcontext.Scope.PopBlock();

                m_Ifs.Add(ifblock);
            }

            if (bcount > ecount)
            {
                lcontext.Scope.PushBlock();
                m_Else           = NodeFactory.CreateStatement(context.block()[bcount - 1], lcontext);
                m_ElseStackFrame = lcontext.Scope.PopBlock();
                m_ElseRef        = BuildSourceRef(context.ELSE());
            }

            m_End = BuildSourceRef(context.Stop, context.END());
        }
Example #11
0
        /// <summary>
        /// Constructs an LDA model
        /// </summary>
        /// <param name="sizeVocab">Size of vocabulary</param>
        /// <param name="numTopics">Number of topics</param>
        public LDAModel(int sizeVocab, int numTopics)
        {
            SizeVocab     = sizeVocab;
            NumTopics     = numTopics;
            ThetaSparsity = Sparsity.Dense;
            PhiSparsity   = Sparsity.ApproximateWithTolerance(0.00000000001); // Allow for round-off error
            NumDocuments  = Variable.New <int>().Named("NumDocuments");

            //---------------------------------------------
            // The model
            //---------------------------------------------
            Range D = new Range(NumDocuments).Named("D");
            Range W = new Range(SizeVocab).Named("W");
            Range T = new Range(NumTopics).Named("T");

            NumWordsInDoc = Variable.Array <int>(D).Named("NumWordsInDoc");
            Range WInD = new Range(NumWordsInDoc[D]).Named("WInD");

            // Surround model by a stochastic If block so that we can compute model evidence
            Evidence = Variable.Bernoulli(0.5).Named("Evidence");
            IfBlock evidenceBlock = Variable.If(Evidence);

            Theta = Variable.Array <Vector>(D);
            Theta.SetSparsity(ThetaSparsity);
            Theta.SetValueRange(T);
            ThetaPrior = Variable.Array <Dirichlet>(D).Named("ThetaPrior");
            Theta[D]   = Variable <Vector> .Random(ThetaPrior[D]);

            Phi = Variable.Array <Vector>(T);
            Phi.SetSparsity(PhiSparsity);
            Phi.SetValueRange(W);
            PhiPrior = Variable.Array <Dirichlet>(T).Named("PhiPrior");
            Phi[T]   = Variable <Vector> .Random(PhiPrior[T]);

            Words      = Variable.Array(Variable.Array <int>(WInD), D).Named("Words");
            WordCounts = Variable.Array(Variable.Array <double>(WInD), D).Named("WordCounts");
            using (Variable.ForEach(D))
            {
                using (Variable.ForEach(WInD))
                {
                    using (Variable.Repeat(WordCounts[D][WInD]))
                    {
                        Variable <int> topic = Variable.Discrete(Theta[D]).Named("topic");
                        using (Variable.Switch(topic))
                        {
                            Words[D][WInD] = Variable.Discrete(Phi[topic]);
                        }
                    }
                }
            }

            evidenceBlock.CloseBlock();

            ThetaInit = Variable.New <IDistribution <Vector[]> >().Named("ThetaInit");
            Theta.InitialiseTo(ThetaInit);
            Engine = new InferenceEngine(new VariationalMessagePassing());
            Engine.Compiler.ShowWarnings = false;
            Engine.ModelName             = "LDAModel";
        }
        public void VisitElse(IfBlock astNode)
        {
            var truthyContext = state.TruthyStack.Pop();

            truthyContext.Truthy = !truthyContext.Truthy;
            state.TruthyStack.Push(truthyContext);
            state.PushNewBlock();
        }
Example #13
0
        public void GPClassificationTest2()
        {
            bool[]   yData = new bool[] { false, true, false };
            double[] xData = new double[]
            {
                -1.555555555555556, -0.2222222222222223, 1.555555555555555
            };
            Vector[]             xVec     = Array.ConvertAll(xData, v => Vector.Constant(1, v));
            Vector[]             basis    = new Vector[] { Vector.Zero(1) };
            IKernelFunction      kf       = new SquaredExponential(0.0);
            SparseGPFixed        sgpf     = new SparseGPFixed(kf, basis);
            Variable <bool>      evidence = Variable.Bernoulli(0.5).Named("evidence");
            IfBlock              block    = Variable.If(evidence);
            Variable <IFunction> f        = Variable.Random <IFunction>(new SparseGP(sgpf)).Named("f");
            Range item = new Range(xVec.Length).Named("item");
            VariableArray <Vector> x = Variable.Array <Vector>(item).Named("x");

            x.ObservedValue = xVec;
            VariableArray <bool> y = Variable.Array <bool>(item).Named("y");

            y.ObservedValue = yData;
            VariableArray <double> h = Variable.Array <double>(item).Named("h");

            h[item] = Variable.FunctionEvaluate(f, x[item]);
            y[item] = (h[item] > 0);
            block.CloseBlock();

            InferenceEngine engine        = new InferenceEngine();
            SparseGP        sgp           = engine.Infer <SparseGP>(f);
            Vector          alphaExpected = Vector.FromArray(new double[] { 0.573337393823702 });

            Console.WriteLine("alpha = {0} should be {1}", sgp.Alpha, alphaExpected);
            double[] xTest = new double[]
            {
                -2, -1, 0.0
            };
            Vector[] xTestVec  = Array.ConvertAll(xTest, v => Vector.Constant(1, v));
            double[] yMeanTest = new double[]
            {
                0.077592778583272, 0.347746707713812, 0.573337393823702
            };
            double[] yVarTest = new double[]
            {
                0.986784459962251, 0.734558782611933, 0.278455962249970
            };
            for (int i = 0; i < xTestVec.Length; i++)
            {
                Gaussian pred         = sgp.Marginal(xTestVec[i]);
                Gaussian predExpected = new Gaussian(yMeanTest[i], yVarTest[i]);
                Console.WriteLine("f({0}) = {1} should be {2}", xTest[i], pred, predExpected);
                Assert.True(predExpected.MaxDiff(pred) < 1e-4);
            }
            double evExpected = -2.463679892165236;
            double evActual   = engine.Infer <Bernoulli>(evidence).LogOdds;

            Console.WriteLine("evidence = {0} should be {1}", evActual, evExpected);
            Assert.True(MMath.AbsDiff(evExpected, evActual, 1e-6) < 1e-4);
        }
Example #14
0
        public void IfTest2()
        {
            VariableExpression vaexp = new VariableExpression();

            vaexp.Name = "VAR1";
            VariableExpression vaexp2 = new VariableExpression();

            vaexp2.Name = "VAR2";

            ConstExpression cst = new ConstExpression();

            cst.SetValue(true);

            ConstExpression cst2 = new ConstExpression();

            cst2.SetValue(10);

            ConstExpression cst3 = new ConstExpression();

            cst3.SetValue(5);

            ConstExpression cst4 = new ConstExpression();

            cst4.SetValue(7);

            IfBlock     ifblk   = new IfBlock();
            ElseBlock   elseblk = new ElseBlock();
            SetVarBlock setvar1 = new SetVarBlock();
            SetVarBlock setvar2 = new SetVarBlock();
            SetVarBlock setvar3 = new SetVarBlock();

            ifblk.Condition  = cst;
            ifblk.InnerBlock = setvar1;
            ifblk.NextBlock  = elseblk;

            elseblk.InnerBlock = setvar2;
            elseblk.NextBlock  = setvar3;

            setvar1.VarName  = "VAR1";
            setvar1.ValueExp = cst2;

            setvar2.VarName  = "VAR1";
            setvar2.ValueExp = cst3;

            setvar3.VarName  = "VAR2";
            setvar3.ValueExp = cst4;

            ifblk.Execute();

            Assert.AreEqual(vaexp.Value, 10);
            Assert.AreEqual(vaexp2.Value, 7);

            cst.SetValue(false);
            ifblk.Execute();

            Assert.AreEqual(vaexp.Value, 5);
            Assert.AreEqual(vaexp2.Value, 7);
        }
 public void ShouldNotConvertElementBlocksInLessDomToCssDomIfInNestedFalseIfBlock()
 {
     var root = new ElementBlock("*");
     var ifBlock = new IfBlock(new BoolExpression(new List<INode> {new Bool(false)}));
     root.Add(ifBlock);
     ifBlock.Add(GetElementBlock());
     var cssDocument = converter.BuildCssDocument(root);
     Assert.That(cssDocument.Elements.Count, Is.EqualTo(0));
 }
Example #16
0
 public void Verify()
 {
     Condition.Verify();
     VarTab.PushScope();
     IfBlock.ForEach(stmt => stmt.Verify());
     VarTab.PopScope();
     VarTab.PushScope();
     ElseBlock.ForEach(stmt => stmt.Verify());
     VarTab.PopScope();
 }
Example #17
0
        //Evento de callback da thread asincrona para execuĆ§Ć£o dos blocos
        private void CommandsWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i_Block = 0; i_Block < m_Blocks.Count; i_Block++)
            {
                m_Blocks[i_Block].BorderColor = new Pen(Color.Green, 1.0f);
                m_Blocks[i_Block].ForeColor   = new SolidBrush(Color.Green);

                m_MainPanel.Invalidate();

                if (m_Blocks[i_Block].Type == BlockType.Action)
                {
                    m_SpheroConnector.Sphero.SendPacket(m_Blocks[i_Block].Command);
                }
                else if (m_Blocks[i_Block].Type == BlockType.Conditional)
                {
                    if (m_Blocks[i_Block].GetType() == typeof(IfBlock))
                    {
                        IfBlock v_IfBlock = m_Blocks[i_Block] as IfBlock;

                        if (v_IfBlock.Arugment1.SpheroCommand != null)
                        {
                            m_SpheroConnector.Sphero.SendPacket(v_IfBlock.Arugment1.SpheroCommand);
                        }

                        if (v_IfBlock.Arugment2.SpheroCommand != null)
                        {
                            m_SpheroConnector.Sphero.SendPacket(v_IfBlock.Arugment2.SpheroCommand);
                        }

                        if (v_IfBlock.evaluateExpression() == false)
                        {
                            e.Result = i_Block;

                            i_Block = m_Blocks.IndexOf(v_IfBlock.findLastChild(v_IfBlock));
                            continue;
                        }
                    }
                    else if (i_Block.GetType() == typeof(WhileBlock))
                    {
                    }
                    else if (i_Block.GetType() == typeof(ForBlock))
                    {
                    }
                }

                Thread.Sleep(1000);

                m_Blocks[i_Block].BorderColor = new Pen(Color.Black, 1.0f);
                m_Blocks[i_Block].ForeColor   = new SolidBrush(Color.Black);

                m_MainPanel.Invalidate();

                e.Result = i_Block;
            }
        }
Example #18
0
        public void GPClassificationTest1()
        {
            bool[]               yData    = new bool[] { true };
            double[]             xData    = new double[] { -0.2222222222222223 };
            Vector[]             xVec     = Array.ConvertAll(xData, v => Vector.Constant(1, v));
            Vector[]             basis    = new Vector[] { Vector.Zero(1) };
            IKernelFunction      kf       = new SquaredExponential(0.0);
            SparseGPFixed        sgpf     = new SparseGPFixed(kf, basis);
            Variable <bool>      evidence = Variable.Bernoulli(0.5).Named("evidence");
            IfBlock              block    = Variable.If(evidence);
            Variable <IFunction> f        = Variable.Random <IFunction>(new SparseGP(sgpf)).Named("f");
            Range item = new Range(xVec.Length).Named("item");
            VariableArray <Vector> x = Variable.Array <Vector>(item).Named("x");

            x.ObservedValue = xVec;
            VariableArray <bool> y = Variable.Array <bool>(item).Named("y");

            y.ObservedValue = yData;
            VariableArray <double> h = Variable.Array <double>(item).Named("h");

            h[item] = Variable.FunctionEvaluate(f, x[item]);
            y[item] = (h[item] > 0);
            block.CloseBlock();

            InferenceEngine engine        = new InferenceEngine();
            SparseGP        sgp           = engine.Infer <SparseGP>(f);
            Vector          alphaExpected = Vector.FromArray(new double[] { 0.778424938343491 });

            Console.WriteLine("alpha = {0} should be {1}", sgp.Alpha, alphaExpected);
            double[] xTest = new double[]
            {
                -2, -1, 0.0
            };
            Vector[] xTestVec  = Array.ConvertAll(xTest, v => Vector.Constant(1, v));
            double[] yMeanTest = new double[]
            {
                0.105348359509159, 0.472138591390244, 0.778424938343491
            };
            double[] yVarTest = new double[]
            {
                0.988901723148729, 0.777085150520037, 0.394054615364932
            };
            for (int i = 0; i < xTestVec.Length; i++)
            {
                Gaussian pred         = sgp.Marginal(xTestVec[i]);
                Gaussian predExpected = new Gaussian(yMeanTest[i], yVarTest[i]);
                Console.WriteLine("f({0}) = {1} should be {2}", xTest[i], pred, predExpected);
                Assert.True(predExpected.MaxDiff(pred) < 1e-4);
            }
            double evExpected = -0.693147180559945;
            double evActual   = engine.Infer <Bernoulli>(evidence).LogOdds;

            Console.WriteLine("evidence = {0} should be {1}", evActual, evExpected);
            Assert.True(MMath.AbsDiff(evExpected, evActual, 1e-6) < 1e-4);
        }
        public void VisitEnter(IfBlock astNode)
        {
            state.SetCursor(astNode);
            Context context;

            if (astNode.Expr.TryEvaluate(state, out context))
            {
                state.PushNewBlock();
                state.PromiseTruthyCheck(context, astNode.QueryType);
            }
        }
Example #20
0
        public override CssNode CloneNode()
        {
            var block = new IfBlock(Condition);

            foreach (var child in children)
            {
                block.Add(child.CloneNode());
            }

            return(block);
        }
Example #21
0
 private void ProcessEndIf(String currentLine)
 {
     if (m_ifBlockStack.Count > 0)
     {
         IfBlock block = (IfBlock)m_ifBlockStack.Pop();
     }
     else
     {
         throw new PreprocessingException("too much endif's encountered");
     }
 }
Example #22
0
 internal void Execute(Context context)
 {
     if ((dynamic)ConditionCallback(context))
     {
         IfBlock.Execute();
     }
     else
     {
         ElseBlock.Execute();
     }
 }
Example #23
0
        /// <inheritdoc />
        public override void CreateModel(int numTweets, int numClasses, int numVocab = 0, bool withEvidence = true, bool withGoldLabels = false)
        {
            IfBlock block = null;

            if (withEvidence)
            {
                this.Evidence = Variable.Bernoulli(0.5).Named("evidence");
                block         = Variable.If(this.Evidence);
            }

            // Biased community model
            base.CreateModel(numTweets, numClasses, numVocab, false, withGoldLabels);

            // Add in the word generation conditioned on true label variable.
            this.WordsInVocabulary = new Range(numVocab).Named("wordsInVocabulary");
            this.ProbWords         = Variable.Array <Vector>(this.Labels).Named("probWords");
            this.ProbWords.SetValueRange(this.WordsInVocabulary);
            this.ProbWords.SetSparsity(Sparsity.Sparse);
            this.WordCount = Variable.Array <int>(this.Tweets).Named("wordCount");
            this.Words     = new Range(this.WordCount[this.Tweets]).Named("words");
            this.Word      = Variable.Array(Variable.Array <int>(this.Words), this.Tweets).Named("word");

            this.ProbWordsPrior         = Variable.Array <Dirichlet>(this.Labels).Named("probWordsPrior");
            this.ProbWords[this.Labels] = Variable <Vector> .Random(this.ProbWordsPrior[this.Labels]);

            this.LikelihoodExponent = Variable.Array <double>(this.Tweets).Named(nameof(this.LikelihoodExponent));

            using (Variable.ForEach(this.Tweets))
            {
                RepeatBlock repeatBlock = null;
                if (UseRepeatFactor)
                {
                    repeatBlock = Variable.Repeat(this.LikelihoodExponent[this.Tweets]);
                }

                using (Variable.Switch(this.TrueLabel[this.Tweets]))
                {
                    this.Word[this.Tweets][this.Words] = Variable.Discrete(this.ProbWords[this.TrueLabel[this.Tweets]]).ForEach(this.Words);
                }

                if (UseRepeatFactor)
                {
                    repeatBlock?.CloseBlock();
                }
            }

            if (withEvidence)
            {
                block.CloseBlock();
            }

            this.HasEvidence = withEvidence;
        }
Example #24
0
        public void Else()
        {
            IfBlock ifBlk = GetBlock() as IfBlock;

            if (ifBlk == null)
            {
                throw new InvalidOperationException("Else() called without a matching If()");
            }

            blocks.Pop();
            Begin(new ElseBlock(ifBlk));
        }
        public void Else()
        {
            IfBlock ifBlk = GetBlock() as IfBlock;

            if (ifBlk == null)
            {
                throw new InvalidOperationException(Properties.Messages.ErrElseWithoutIf);
            }

            blocks.Pop();
            Begin(new ElseBlock(ifBlk));
        }
Example #26
0
		IfBlock CreateElseBlock(ScriptLoadingContext lcontext)
		{
			Token type = CheckTokenType(lcontext, TokenType.Else);

			lcontext.Scope.PushBlock();

			var ifblock = new IfBlock();
			ifblock.Block = new CompositeStatement(lcontext);
			ifblock.StackFrame = lcontext.Scope.PopBlock();
			ifblock.Source = type.GetSourceRef();
			lcontext.Source.Refs.Add(ifblock.Source);
			return ifblock;
		}
        public void VisitLeave(IfBlock astNode)
        {
            var latestBlock = state.PopBlock();

            if (astNode.HasElseBlock)
            {
                state.DoTruthyCheck(state.PopBlock(), latestBlock, astNode.QueryType);
            }
            else
            {
                state.DoTruthyCheck(latestBlock, ifType: astNode.QueryType);
            }
        }
Example #28
0
        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.Append("if ").Append(Condition).AppendLine(" then ");
            sb.AppendLine(IfBlock.ToString());
            if (ElseBlock != null)
            {
                sb.AppendLine("else").AppendLine(ElseBlock.ToString());
            }
            sb.Append(" end");
            return(sb.ToString());
        }
Example #29
0
        public void GPRegressionTest1()
        {
            double[]             yData    = new double[] { 1.036659040456137 };
            double[]             xData    = new double[] { -0.2222222222222223 };
            Vector[]             xVec     = Array.ConvertAll(xData, v => Vector.Constant(1, v));
            Vector[]             basis    = new Vector[] { xVec[0] };
            IKernelFunction      kf       = new SquaredExponential(System.Math.Log(2.0));
            SparseGPFixed        sgpf     = new SparseGPFixed(kf, basis);
            Variable <bool>      evidence = Variable.Bernoulli(0.5).Named("evidence");
            IfBlock              block    = Variable.If(evidence);
            Variable <IFunction> f        = Variable.Random <IFunction>(new SparseGP(sgpf)).Named("f");
            Range item = new Range(xVec.Length).Named("item");
            VariableArray <Vector> x = Variable.Array <Vector>(item).Named("x");

            x.ObservedValue = xVec;
            VariableArray <double> y = Variable.Array <double>(item).Named("y");

            y.ObservedValue = yData;
            VariableArray <double> h = Variable.Array <double>(item).Named("h");

            h[item] = Variable.FunctionEvaluate(f, x[item]);
            y[item] = Variable.GaussianFromMeanAndVariance(h[item], 0.1);
            block.CloseBlock();

            InferenceEngine engine        = new InferenceEngine();
            SparseGP        sgp           = engine.Infer <SparseGP>(f);
            Vector          alphaExpected = Vector.FromArray(new double[] { 0.942417309505579 });

            Console.WriteLine("alpha = {0} should be {1}", sgp.Alpha, alphaExpected);
            double[] xTest = new double[]
            {
                -2, -1, 0.0
            };
            Vector[] xTestVec = Array.ConvertAll(xTest, v => Vector.Constant(1, v));
            // computed by matlab/MNT/GP/test_gpr.m
            double[] yTest = new double[]
            {
                0.634848540665472, 0.873781982196160, 0.936617836728720
            };
            for (int i = 0; i < xTestVec.Length; i++)
            {
                double pred = sgp.Mean(xTestVec[i]);
                Console.WriteLine("Ef({0}) = {1} should be {2}", xTest[i], pred, yTest[i]);
                Assert.True(MMath.AbsDiff(pred, yTest[i], 1e-6) < 1e-4);
            }
            double evExpected = -1.455076334997490;
            double evActual   = engine.Infer <Bernoulli>(evidence).LogOdds;

            Console.WriteLine("evidence = {0} should be {1}", evActual, evExpected);
            Assert.True(MMath.AbsDiff(evExpected, evActual, 1e-6) < 1e-4);
        }
Example #30
0
        IfBlock CreateElseBlock(ScriptLoadingContext lcontext)
        {
            Token type = CheckTokenType(lcontext, TokenType.Else);

            lcontext.Scope.PushBlock();

            var ifblock = new IfBlock();

            ifblock.Block      = new CompositeStatement(lcontext);
            ifblock.StackFrame = lcontext.Scope.PopBlock();
            ifblock.Source     = type.GetSourceRef();
            lcontext.Source.Refs.Add(ifblock.Source);
            return(ifblock);
        }
Example #31
0
        private IAlgorithmBlock CreateBlockData(BlockData data)
        {
            IAlgorithmBlock result = null;

            switch (data.type)
            {
            case BlockType.Begin:
            {
                BeginBlock block = new BeginBlock();
                block.Data = data;
                result     = block;
            }
            break;

            case BlockType.Action:
            {
                ActionBlock block = new ActionBlock();
                block.Data = data;
                block.Name = data.name;
                result     = block;
            }
            break;

            case BlockType.If:
            {
                IfBlock block = new IfBlock();
                block.Data = data;
                result     = block;
            }
            break;

            case BlockType.While:
            {
                WhileBlock block = new WhileBlock();
                block.Data = data;
                result     = block;
            }
            break;

            case BlockType.Set:
            {
                SetBlock block = new SetBlock();
                block.Data = data;
                result     = block;
            }
            break;
            }

            return(result);
        }
Example #32
0
        internal void FitNegativeBinomial()
        {
            // generate data from the model
            double r = 2;
            double p = 0.3;

            int[] data = new int[] { 1, 4, 5, 14, 0, 3, 2, 18, 0, 1, 8, 1, 4, 3, 6, 4, 9, 5, 1, 10, 5, 9, 2, 3, 3, 9, 14, 3, 5, 12 };
            int   N    = data.Length;

            Variable <bool> evidence = Variable.Bernoulli(0.5).Named("evidence");
            IfBlock         block    = Variable.If(evidence);
            var             rate     = Variable.GammaFromShapeAndRate(1, 1).Named("rate");
            //var shape = Variable.GammaFromShapeAndRate(1,1).Named("shape");
            var   shape  = Variable.GammaFromShapeAndRate(1, 1).Named("shape");
            var   lambda = Variable.GammaFromShapeAndRate(shape, rate).Named("lambda");
            Range Nrange = new Range(N);
            var   y      = Variable.Array <int>(Nrange).Named("y");

            y[Nrange]       = Variable.Poisson(lambda).ForEach(Nrange);
            y.ObservedValue = data;
            block.CloseBlock();
            InferenceEngine ie = new InferenceEngine(new VariationalMessagePassing());

            ie.ShowFactorGraph = true;
            var ca = ie.GetCompiledInferenceAlgorithm(evidence, rate, shape);

            ca.Reset();
            double oldLogEvidence = double.NegativeInfinity;

            for (int i = 0; i < 1000; i++)
            {
                ca.Update(1);
                double logEvidence1 = ca.Marginal <Bernoulli>(evidence.NameInGeneratedCode).LogOdds;
                Console.WriteLine(logEvidence1);
                if (i > 20 && System.Math.Abs(logEvidence1 - oldLogEvidence) < 0.01)
                {
                    break;
                }
                oldLogEvidence = logEvidence1;
            }
            Gamma  shapePost = ca.Marginal <Gamma>(shape.NameInGeneratedCode);
            Gamma  ratePost = ca.Marginal <Gamma>(rate.NameInGeneratedCode);
            double mean, variance;

            shapePost.GetMeanAndVariance(out mean, out variance);
            Console.WriteLine("shape = " + mean + " +/- " + System.Math.Sqrt(variance) + " true= " + r);
            ratePost.GetMeanAndVariance(out mean, out variance);
            Console.WriteLine("rate = " + mean + " +/- " + System.Math.Sqrt(variance) + " true= " + p / (1 - p));
        }
Example #33
0
		public IfStatement(ScriptLoadingContext lcontext)
			: base(lcontext)
		{
			while (lcontext.Lexer.Current.Type != TokenType.Else && lcontext.Lexer.Current.Type != TokenType.End)
			{
				m_Ifs.Add(CreateIfBlock(lcontext));
			}

			if (lcontext.Lexer.Current.Type == TokenType.Else)
			{
				m_Else = CreateElseBlock(lcontext);
			}

			m_End = CheckTokenType(lcontext, TokenType.End).GetSourceRef();
			lcontext.Source.Refs.Add(m_End);
		}
Example #34
0
        private IfBlock CreateIfBlock(ScriptLoadingContext lcontext)
        {
            var type = CheckTokenType(lcontext, TokenType.If, TokenType.ElseIf);

            lcontext.Scope.PushBlock();

            var ifblock = new IfBlock();

            ifblock.Exp = Expression.Expr(lcontext);
            ifblock.Source = type.GetSourceRef(CheckTokenType(lcontext, TokenType.Then));
            ifblock.Block = new CompositeStatement(lcontext);
            ifblock.StackFrame = lcontext.Scope.PopBlock();
            lcontext.Source.Refs.Add(ifblock.Source);


            return ifblock;
        }
Example #35
0
        public void EvaluateIf(IfBlock block, int level = 0)
        {
            var result = EvalulateExpression(block.Condition);

            var i = 0;

            if (ToBoolean(result))
            {
                foreach (var child in block.Children)
                {
                    if (child is CssRule)
                    {
                        if (i > 0) writer.WriteLine();

                        WriteRule((CssRule)child);

                        i++;
                    }
                    else if (child is CssAssignment)
                    {
                        var variable = (CssAssignment)child;

                        scope[variable.Name] = variable.Value;
                    }
                    else if (child is CssDeclaration)
                    {
                        if (i > 0) writer.WriteLine();

                        WriteDeclaration((CssDeclaration)child, level);

                        i++;
                    }
                }
            }
        }
			public ElseBlock(IfBlock ifBlk)
			{
				this.ifBlk = ifBlk;
			}
Example #37
0
        public IfBlock ReadIfRule()
        {
            // @font-face [expression] {

            ReadTrivia();

            var condition = ReadExpression();

            var rule = new IfBlock(condition);

            ReadBlock(rule);

            return rule;
        }
 public void VisitLeave(IfBlock astNode)
 {
     var latestBlock = state.PopBlock();
       if (astNode.HasElseBlock)
     state.DoTruthyCheck(state.PopBlock(), latestBlock, astNode.QueryType);
       else
     state.DoTruthyCheck(latestBlock, ifType: astNode.QueryType);
 }
 public void VisitEnter(IfBlock astNode)
 {
     state.SetCursor(astNode);
       Context context;
       if (astNode.Expr.TryEvaluate(state, out context))
       {
     state.PushNewBlock();
     state.PromiseTruthyCheck(context, astNode.QueryType);
       }
 }
 public void VisitElse(IfBlock astNode)
 {
     var truthyContext = state.TruthyStack.Pop();
       truthyContext.Truthy = !truthyContext.Truthy;
       state.TruthyStack.Push(truthyContext);
       state.PushNewBlock();
 }
 public virtual void Visit(IfBlock ifBlock, object[] args)
 {
     foreach (Statement s in ifBlock.Content)
     {
         s.Accept(this);
     }
 }
 public void Visit(IfBlock ifBlock, object[] args)
 {
 }