Exemple #1
0
        public VariableArray2D <double> GetPopulationForIteration(int Iterations, double CatPopulation, double MousePopulation)
        {
            Variable <int> numTimes = Variable.Observed(Iterations);
            Range          time     = new Range(numTimes);
            Range          cols     = new Range(2); // frist is Cats and second Mice

            VariableArray2D <double> days = Variable.Array <double>(time, cols);

            using (ForEachBlock rowBlock = Variable.ForEach(time))
            {
                var day = rowBlock.Index;
                using (Variable.If(day == 0))
                {
                    Cat.SetNewPopulation(CatPopulation);
                    Mouse.SetNewPopulation(MousePopulation);
                    days[day, 0] = Cat.GetPopulation();
                    days[day, 1] = Mouse.GetPopulation();
                }
                using (Variable.If(day > 0))
                {
                    days[day, 0] = days[day - 1, 0] + GetCatPopulationChange();
                    days[day, 1] = days[day - 1, 1] + GetMousePopulationChange();
                }
            }

            return(days);
        }
Exemple #2
0
 public void ForNSEW(int x, int y, int z, ForEachBlock predicate)
 {
     predicate(X + x - 1, y, Z + z);
     predicate(X + x + 1, y, Z + z);
     predicate(X + x, y, Z + z - 1);
     predicate(X + x, y, Z + z + 1);
 }
Exemple #3
0
        public void PottsGridTest()
        {
            int   size = 10;
            Range rows = new Range(size).Named("rows");
            Range cols = new Range(size).Named("cols");

            var states = Variable.Array <bool>(rows, cols).Named("states");

            Bernoulli[,] unary = new Bernoulli[size, size];
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    var  xdist  = System.Math.Abs(i - size / 2) / ((double)size);
                    var  ydist  = System.Math.Abs(j - size / 2) / ((double)size);
                    bool inrect = (xdist < 0.2) && (ydist < 0.2);
                    unary[i, j] = new Bernoulli(inrect ? 0.8 : 0.2);
                }
            }

            var p = Variable.Observed(unary, rows, cols);

            states[rows, cols] = Variable.Random <bool, Bernoulli>(p[rows, cols]);

            double logCost = 0;

            using (ForEachBlock rowBlock = Variable.ForEach(rows))
            {
                using (ForEachBlock colBlock = Variable.ForEach(cols))
                {
                    using (Variable.If(rowBlock.Index >= 1))
                    {
                        Variable.Potts(states[rowBlock.Index, colBlock.Index],
                                       states[rowBlock.Index + -1, colBlock.Index], logCost);
                    }

                    using (Variable.If(colBlock.Index >= 1))
                    {
                        Variable.Potts(states[rowBlock.Index, colBlock.Index],
                                       states[rowBlock.Index, colBlock.Index + -1], logCost);
                    }
                }
            }

            InferenceEngine engine = new InferenceEngine();

            engine.Algorithm          = new MaxProductBeliefPropagation();
            engine.ShowTimings        = true;
            engine.NumberOfIterations = 20;
            var result = engine.Infer <Bernoulli[, ]>(states);

            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)
                {
                    Console.Write("{0:f5} ", result[i, j].GetProbTrue());
                }
                Console.WriteLine();
            }
        }
Exemple #4
0
 public void ForEach(ForEachBlock predicate)
 {
     for (int x = 0; x < 16; x++)
         for (int z = 0; z < 16; z++)
             for (int y = 0; y < 128; y++)
                 predicate(x, y, z);
 }
Exemple #5
0
 public void ForNSEW(UniversalCoords coords, ForEachBlock predicate)
 {
     predicate(UniversalCoords.FromWorld(coords.WorldX - 1, coords.WorldY, coords.WorldZ));
     predicate(UniversalCoords.FromWorld(coords.WorldX + 1, coords.WorldY, coords.WorldZ));
     predicate(UniversalCoords.FromWorld(coords.WorldX, coords.WorldY, coords.WorldZ - 1));
     predicate(UniversalCoords.FromWorld(coords.WorldX, coords.WorldY, coords.WorldZ + 1));
 }
Exemple #6
0
 public void ForAdjacentSameChunk(int x, int y, int z, ForEachBlock predicate)
 {
     if (x > 0)
     {
         predicate(x - 1, y, z);
     }
     if (x < 15)
     {
         predicate(x + 1, y, z);
     }
     if (y > 0)
     {
         predicate(x, y - 1, z);
     }
     if (y < 127)
     {
         predicate(x, y + 1, z);
     }
     if (z > 0)
     {
         predicate(x, y, z - 1);
     }
     if (z < 15)
     {
         predicate(x, y, z + 1);
     }
 }
Exemple #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MultiPlayer" /> class.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="showFactorGraph">if set to <c>true</c> [show factor graph].</param>
        /// <param name="trainingModel">if set to <c>true</c> [training model].</param>
        public MultiPlayer(IModelParameters parameters, bool showFactorGraph = false, bool trainingModel = true) : base(parameters)
        {
            //The factor graph of this model slightly differs from the one from the book
            //because this model is generic and uses arrays to support any number of players.
            this.numberOfPlayers = Variable.New <int>().Named("numberOfPlayers").Attrib(new DoNotInfer());
            var dynamicsVariance    = Variable.Observed(this.Parameters.DynamicsVariance).Named("dynamicsVariance");
            var performanceVariance = Variable.Observed(this.Parameters.PerformanceVariance).Named("performanceVariance");

            Range player = new Range(this.numberOfPlayers).Named("player");

            this.playersPerGame = Variable.New <int>().Named("playersPerGame").Attrib(new DoNotInfer());
            Range gamePlayer = new Range(this.playersPerGame).Named("gamePlayer");

            this.skillPriors    = Variable.Array <Gaussian>(player).Named("skillPriors").Attrib(new DoNotInfer());
            this.skills         = Variable.Array <double>(player).Named("skills");
            this.skills[player] = Variable.GaussianFromMeanAndVariance(Variable <double> .Random(this.skillPriors[player]), dynamicsVariance);

            this.drawMargin      = Variable.New <double>().Named("drawMargin");
            this.drawMarginPrior = Variable.New <Gaussian>().Named("drawMarginPrior");
            this.drawMargin.SetTo(Variable <double> .Random(this.drawMarginPrior));
            Variable.ConstrainTrue(this.drawMargin > 0);

            this.playerIndices = Variable.Array <int>(gamePlayer).Named("playerIndices").Attrib(new DoNotInfer());
            this.performances  = Variable.Array <double>(gamePlayer).Named("performances");

            var gameSkills = Variable.Subarray(this.skills, this.playerIndices).Named("gameSkills");

            if (trainingModel)
            {
                this.scores = Variable.Array <int>(gamePlayer).Named("scores").Attrib(new DoNotInfer());
            }

            using (ForEachBlock gp = Variable.ForEach(gamePlayer))
            {
                this.performances[gamePlayer] = Variable.GaussianFromMeanAndVariance(gameSkills[gamePlayer], performanceVariance);

                if (trainingModel)
                {
                    using (Variable.If(gp.Index > 0))
                    {
                        var diff = (this.performances[gp.Index - 1] - this.performances[gp.Index]).Named("diff");

                        using (Variable.If(this.scores[gp.Index - 1] == this.scores[gp.Index]))
                        {
                            Variable.ConstrainBetween(diff, -this.drawMargin, this.drawMargin);
                        }

                        using (Variable.IfNot(this.scores[gp.Index - 1] == this.scores[gp.Index]))
                        {
                            Variable.ConstrainTrue(diff > this.drawMargin);
                        }
                    }
                }
            }

            this.engine = Utils.GetDefaultEngine(showFactorGraph);
        }
Exemple #8
0
        static void Main(string[] args)
        {
            /* Original data with missing values
             * int[] disaster_data = new int[] {4, 5, 4, 0, 1, 4, 3, 4, 0, 6, 3, 3, 4, 0, 2, 6,
             *                               3, 3, 5, 4, 5, 3, 1, 4, 4, 1, 5, 5, 3, 4, 2, 5,
             *                               2, 2, 3, 4, 2, 1, 3, -999, 2, 1, 1, 1, 1, 3, 0, 0,
             *                               1, 0, 1, 1, 0, 0, 3, 1, 0, 3, 2, 2, 0, 1, 1, 1,
             *                               0, 1, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 1, 1, 0, 2,
             *                               3, 3, 1, -999, 2, 1, 1, 1, 1, 2, 4, 2, 0, 0, 1, 4,
             *                               0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 };
             */

            int[] disaster_data = { 4, 5, 4, 0, 1, 4, 3, 4, 0, 6, 3, 3, 4, 0, 2, 6,
                                    3, 3, 5, 4, 5, 3, 1, 4, 4, 1, 5, 5, 3, 4, 2, 5,
                                    2, 2, 3, 4, 2, 1, 3, 2, 2, 1, 1, 1, 1, 3, 0, 0,
                                    1, 0, 1, 1, 0, 0, 3, 1, 0, 3, 2, 2, 0, 1, 1, 1,
                                    0, 1, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 1, 1, 0, 2,
                                    3, 3, 1, 2, 2, 1, 1, 1, 1, 2, 4, 2, 0, 0, 1, 4,
                                    0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 };

            Range n = new Range(disaster_data.Length).Named("years_idx");

            var switchpoint = Variable.DiscreteUniform(n.Clone()).Named("switchpoint");

            switchpoint.Name = nameof(switchpoint);

            var data = Variable.Array <int>(n).Named("data");

            using (Variable.Switch(switchpoint))
            {
                var early_rate = Variable.GammaFromShapeAndRate(2.0, 2.0).Named("early_rate");
                var late_rate  = Variable.GammaFromShapeAndRate(2.0, 2.0).Named("late_rate");
                using (ForEachBlock block = Variable.ForEach(n))
                {
                    using (Variable.If(switchpoint > block.Index))
                        data[n] = Variable.Poisson(early_rate);
                    using (Variable.IfNot(switchpoint > block.Index))
                        data[n] = Variable.Poisson(late_rate);
                }
            }


            data.ObservedValue = disaster_data;

            InferenceEngine engine = new InferenceEngine();

            engine.Compiler.GenerateInMemory        = false;
            engine.Compiler.WriteSourceFiles        = true;
            engine.Compiler.IncludeDebugInformation = true;

            var switchpointMarginal = engine.Infer <Discrete>(switchpoint);

            Console.WriteLine(switchpointMarginal);

            Console.ReadKey();
        }
Exemple #9
0
 public void ForAdjacent(int x, int y, int z, ForEachBlock predicate)
 {
     predicate(X + x - 1, y, Z + z);
     predicate(X + x + 1, y, Z + z);
     predicate(X + x, y, Z + z - 1);
     predicate(X + x, y, Z + z + 1);
     if (y > 0)
         predicate(X + x, y - 1, Z + z);
     if (y < 127)
         predicate(X + x, y + 1, Z + z);
 }
Exemple #10
0
 public void ForAdjacent(UniversalCoords coords, ForEachBlock predicate)
 {
     predicate(UniversalCoords.FromWorld(coords.WorldX - 1, coords.WorldY, coords.WorldZ));
     predicate(UniversalCoords.FromWorld(coords.WorldX + 1, coords.WorldY, coords.WorldZ));
     predicate(UniversalCoords.FromWorld(coords.WorldX, coords.WorldY, coords.WorldZ - 1));
     predicate(UniversalCoords.FromWorld(coords.WorldX, coords.WorldY, coords.WorldZ + 1));
     if (coords.BlockY > 0)
         predicate(UniversalCoords.FromWorld(coords.WorldX, coords.WorldY - 1, coords.WorldZ));
     if (coords.BlockY < 127)
         predicate(UniversalCoords.FromWorld(coords.WorldX, coords.WorldY + 1, coords.WorldZ));
 }
Exemple #11
0
 public void ForEach(ForEachBlock predicate)
 {
     for (int x = 0; x < 16; x++)
     {
         for (int z = 0; z < 16; z++)
         {
             for (int y = 0; y < 128; y++)
             {
                 predicate(x, y, z);
             }
         }
     }
 }
Exemple #12
0
 public void ForAdjacent(int x, int y, int z, ForEachBlock predicate)
 {
     int chunkWorldX = (X << 4);
     int chunkWorldZ = (Z << 4);
     predicate(chunkWorldX + x - 1, y, chunkWorldZ + z);
     predicate(chunkWorldX + x + 1, y, chunkWorldZ + z);
     predicate(chunkWorldX + x, y, chunkWorldZ + z - 1);
     predicate(chunkWorldX + x, y, chunkWorldZ + z + 1);
     if (y > 0)
         predicate(chunkWorldX + x, y - 1, chunkWorldZ + z);
     if (y < 127)
         predicate(chunkWorldX + x, y + 1, chunkWorldZ + z);
 }
Exemple #13
0
 public void ForAdjacentSameChunk(int x, int y, int z, ForEachBlock predicate)
 {
     if (x > 0)
         predicate(x - 1, y, z);
     if (x < 15)
         predicate(x + 1, y, z);
     if (y > 0)
         predicate(x, y - 1, z);
     if (y < 127)
         predicate(x, y + 1, z);
     if (z > 0)
         predicate(x, y, z - 1);
     if (z < 15)
         predicate(x, y, z + 1);
 }
Exemple #14
0
        private CSharpName GetEarlyExitNameIfRequired(ForEachBlock forEachBlock, ScopeAccessInformation scopeAccessInformation)
        {
            if (forEachBlock == null)
            {
                throw new ArgumentNullException("forEachBlock");
            }
            if (scopeAccessInformation == null)
            {
                throw new ArgumentNullException("scopeAccessInformation");
            }

            if (!forEachBlock.ContainsLoopThatContainsMismatchedExitThatMustBeHandledAtThisLevel())
            {
                return(null);
            }

            return(_tempNameGenerator(new CSharpName("exitFor"), scopeAccessInformation));
        }
Exemple #15
0
 public void ForEach(ForEachBlock predicate)
 {
     for (int x = 0; x < 16; x++)
         for (int z = 0; z < 16; z++)
             for (int y = 127; y >=0; --y)
                 predicate(x, y, z);
 }
Exemple #16
0
        /*public void SetAllBlocks(byte[] data)
        {
            Types = data;
        }*/

        internal void ForEach(ForEachBlock predicate)
        {
            for (int x = 0; x < 16; x++)
                for (int z = 0; z < 16; z++)
                    for (int y = 127; y >= 0; --y)
                        predicate(UniversalCoords.FromBlock(Coords.ChunkX, Coords.ChunkZ, x, y, z));
        }
Exemple #17
0
 public void ForNSEW(int x, int y, int z, ForEachBlock predicate)
 {
     int chunkWorldX = (X << 4);
     int chunkWorldZ = (Z << 4);
     predicate(chunkWorldX + x - 1, y, chunkWorldZ + z);
     predicate(chunkWorldX + x + 1, y, chunkWorldZ + z);
     predicate(chunkWorldX + x, y, chunkWorldZ + z - 1);
     predicate(chunkWorldX + x, y, chunkWorldZ + z + 1);
 }
Exemple #18
0
        public TrainModel(int dimFeatures)
        {
            //
            // Dataset size
            //

            numExamples = Variable.New <int>();
            example     = new Range(numExamples);

            //
            // Jagged 1-D arrays of arrays for item scores and features
            //

            exampleSize = Variable.Array <int>(example);
            item        = new Range(exampleSize[example]);

            scores   = Variable.Array(Variable.Array <double>(item), example);
            features = Variable.Array(Variable.Array <Vector>(item), example);

            //
            // Jagged 1-D arrays for pairwise item ranks
            //

            rankSize = Variable.Array <int>(example);
            pair     = new Range(rankSize[example]);

            ranks = Variable.Array(Variable.Array <bool>(pair), example);

            //
            // Model parameters
            //

            w = Variable.VectorGaussianFromMeanAndVariance(Vector.Zero(dimFeatures),
                                                           PositiveDefiniteMatrix.Identity(dimFeatures)).Named("w");

            //
            // Model
            //

            scoresNoise = Variable.GammaFromShapeAndScale(1.0, 3.0);

            using (Variable.ForEach(example))
            {
                using (Variable.ForEach(item))
                {
                    var mean = Variable.InnerProduct(w, features[example][item]);
                    scores[example][item] = Variable.GaussianFromMeanAndPrecision(mean, scoresNoise);
                }

                using (ForEachBlock pairBlock = Variable.ForEach(pair))
                {
                    var idx = pairBlock.Index;

                    var diff = scores[example][idx + 1] - scores[example][idx];

                    using (Variable.If(diff > 0))
                        ranks[example][pair] = true;
                    using (Variable.IfNot(diff > 0))
                        ranks[example][pair] = false;
                }
            }

            //
            // Inference engine
            //

            engine = new InferenceEngine();
            engine.NumberOfIterations           = 50;
            engine.Compiler.UseParallelForLoops = true;
        }
Exemple #19
0
        public virtual void CreateModel(int numGenes)
        {
            NumGenes = Variable.New <int>();
            NumGenes.ObservedValue = numGenes;

            Range geneRange       = new Range(NumGenes).Named("geneRange");
            Range geneWeightRange = new Range(NumGenes - 1).Named("geneWeightRange");

            genesT1Prior = Variable.Array <Gaussian>(geneRange).Named("genesT1Prior");;
            alphaPrior   = Variable.Array <Gaussian>(geneRange).Named("alphaPrior");;
            betaPrior    = Variable.Array <Gaussian>(geneRange).Named("betaPrior");
            wPrior       = Variable.Array(Variable.Array <Gaussian>(geneWeightRange), geneRange).Named("wPrior");

            genesT1 = Variable.Array <double>(geneRange).Named("genesT1");
            genesT2 = Variable.Array <double>(geneRange).Named("genesT2");

            var indicesArray = Variable.Array(Variable.Array <int>(geneWeightRange), geneRange).Named("indicesArray");

            //genesT1[geneRange] = Variable.Random<double, Gaussian>(genesT1Prior).ForEach(geneRange);
            genesT1[geneRange] = Variable <double> .Random(genesT1Prior[geneRange]);

            int[][] indices = new int[NumGenes.ObservedValue][];
            for (int i = 0; i < NumGenes.ObservedValue; i++)
            {
                indices[i] = new int[NumGenes.ObservedValue - 1];
                int j = 0, ind = 0;
                while (j < NumGenes.ObservedValue)
                {
                    if (i == j)
                    {
                        j++; continue;
                    }
                    indices[i][ind] = j;
                    j++;
                    ind++;
                }
            }
            for (int i = 0; i < NumGenes.ObservedValue; i++)
            {
                for (int j = 0; j < NumGenes.ObservedValue - 1; j++)
                {
                    Console.WriteLine(indices[i][j]);
                }
            }
            indicesArray.ObservedValue = indices;

            alpha = Variable.Array <double>(geneRange).Named("alpha");
            beta  = Variable.Array <double>(geneRange).Named("beta");
            //alpha[geneRange] = Variable.Random<double, Gaussian>(alphaPrior).ForEach(geneRange);
            alpha[geneRange] = Variable <double> .Random(alphaPrior[geneRange]);

            //beta[geneRange] = Variable.Random<double, Gaussian>(betaPrior).ForEach(geneRange);
            beta[geneRange] = Variable <double> .Random(betaPrior[geneRange]);

            w = Variable.Array(Variable.Array <double>(geneWeightRange), geneRange).Named("w");
            w[geneRange][geneWeightRange] = Variable.Random <double, Gaussian>(wPrior[geneRange][geneWeightRange]); // Laplace distribution
            //w[geneRange][geneWeightRange] = Variable.GaussianFromMeanAndVariance(0, Variable.GammaFromShapeAndRate(1, 1)).ForEach(geneRange, geneWeightRange);


            VariableArray <double> genesubarray = Variable.Array <double>(geneWeightRange).Named("genesubarray");

            using (ForEachBlock firstBlock = Variable.ForEach(geneRange))
            {
                Variable <double>      selfEffect = -(alpha[geneRange] * genesT1[geneRange]);
                VariableArray <double> weightSum  = Variable.Array <double>(geneWeightRange).Named("weightSum");
                Console.WriteLine("summing " + geneRange + " + " + geneWeightRange);
                genesubarray = Variable.Subarray(genesT1, indicesArray[geneRange]);
                weightSum[geneWeightRange] = w[geneRange][geneWeightRange] * genesubarray[geneWeightRange]; //genesT1[geneRange2]
                Variable <double> othersEffect = beta[geneRange] * Variable.Sum(weightSum);                 // Variable.Logistic(Variable.Sum(weightSum));// Variable.Sum(weightSum); //Variable.Logistic(innerproduct);
                genesT2[geneRange] = selfEffect + othersEffect;
            }

            if (InferenceEngine == null)
            {
                InferenceEngine = new InferenceEngine();
            }
        }
Exemple #20
0
        public TranslationResult Translate(ForEachBlock forEachBlock, ScopeAccessInformation scopeAccessInformation, int indentationDepth)
        {
            if (forEachBlock == null)
            {
                throw new ArgumentNullException("forEachBlock");
            }
            if (scopeAccessInformation == null)
            {
                throw new ArgumentNullException("scopeAccessInformation");
            }
            if (indentationDepth < 0)
            {
                throw new ArgumentOutOfRangeException("indentationDepth", "must be zero or greater");
            }

            // The approach here is to get an IEnumerator reference and then loop over it in a "while (true)" loop, exiting when there are no more items. It would
            // feel more natural to use a C# foreach loop but the loop variable may not be restricted in scope to the loop (in fact, in VBScript this is very unlikely)
            // and so a "Type and identifier are both required in a foreach statement" compile error would result - "foreach (i in a)" is not valid, it must be of the
            // form "foreach (var i in a)" which only works if "i" is limited in scope to that loop. The "while (true)" structure also works better when error-trapping
            // may be enabled since the call-MoveNext-and-set-loop-variable-to-enumerator-Current-value-if-not-reached-end-of-data can be bypassed entirely if an error
            // was caught while evaluating the enumerator (in which case the loop should be processed once but the loop variable not set).

            // Note: The looped-over content must be of type "Reference" since VBScript won't enumerate over strings, for example, whereas C# would be happy to.
            // However, to make the output marginally easier to read, the ENUMERABLE method will deal with this logic and so the ExpressionReturnTypeOptions
            // value passed to the statement translator is "NotSpecified".

            var loopSourceContent = _statementTranslator.Translate(forEachBlock.LoopSrc, scopeAccessInformation, ExpressionReturnTypeOptions.NotSpecified, _logger.Warning);
            var undeclaredVariablesInLoopSourceContent = loopSourceContent.GetUndeclaredVariablesAccessed(scopeAccessInformation, _nameRewriter);

            foreach (var undeclaredVariable in undeclaredVariablesInLoopSourceContent)
            {
                _logger.Warning("Undeclared variable: \"" + undeclaredVariable.Content + "\" (line " + (undeclaredVariable.LineIndex + 1) + ")");
            }
            var translationResult = TranslationResult.Empty.AddUndeclaredVariables(undeclaredVariablesInLoopSourceContent);
            var enumerationContentVariableName  = _tempNameGenerator(new CSharpName("enumerationContent"), scopeAccessInformation);
            var enumeratorInitialisationContent = string.Format(
                "{0} = {1}.ENUMERABLE({2}).GetEnumerator();",
                enumerationContentVariableName.Name,
                _supportRefName.Name,
                loopSourceContent.TranslatedContent
                );

            if (!scopeAccessInformation.IsDeclaredReference(forEachBlock.LoopVar, _nameRewriter))
            {
                translationResult = translationResult.AddUndeclaredVariables(new[] { forEachBlock.LoopVar });
            }
            var rewrittenLoopVarName   = _nameRewriter.GetMemberAccessTokenName(forEachBlock.LoopVar);
            var loopVarTargetContainer = scopeAccessInformation.GetNameOfTargetContainerIfAnyRequired(forEachBlock.LoopVar, _envRefName, _outerRefName, _nameRewriter);

            if (loopVarTargetContainer != null)
            {
                rewrittenLoopVarName = loopVarTargetContainer.Name + "." + rewrittenLoopVarName;
            }
            if (scopeAccessInformation.ErrorRegistrationTokenIfAny == null)
            {
                translationResult = translationResult.Add(new TranslatedStatement(
                                                              "var " + enumeratorInitialisationContent,
                                                              indentationDepth,
                                                              forEachBlock.LoopVar.LineIndex
                                                              ));
            }
            else
            {
                // If ON ERROR RESUME NEXT wraps a FOR EACH loop and there is an error in evaluating the enumerator, then the loop will be entered once. The
                // loop variable will not be altered - eg.
                //
                //   On Error Resume Next
                //   Dim i: For Each i in "12"
                //     WScript.Echo "We're in the loop! i is " & TypeName(i)
                //   Next
                //
                // VBScript can not enumerate a string, so the loop errors. But the ON ERROR RESUME NEXT causes the loop to be processed - only once. This is
                // approached by calling _.ENUMERABLE before the loop construct, setting a temporary variable to be the returned enumerable inside a call to
                // "HANDLEERROR" - meaning that it will be left as null if it fails. Null values are replaced with a single-item array, where the element is
                // the current value of the loop variable - so its value is not altered when the loop is entered.
                // - Note: The "error-trapping" wrapper functions ("HANDLEERROR") are used around code that MAY have error-trapping enabled (there are cases
                //   where we can't know at translation time whether it will have been turned off with ON ERROR GOTO 0 or not - and there are probably some
                //   cases that could be picked up if the translation process was more intelligent). If the above example had an ON ERROR GOTO 0 between the
                //   ON ERROR RESUME NEXT and the FOR EACH loop then the error (about trying to enumerate a string) would be raised and so the FOR EACH would
                //   not be entered, and so the single-element "fallback array" would never come to exist. If errors WERE still being captured, then the
                //   translated FOR EACH loop WOULD be entered and enumerated through once (without the value of the loop variable being altered, as
                //   is consistent with VBScript)
                translationResult = translationResult
                                    .Add(new TranslatedStatement(
                                             string.Format(
                                                 "IEnumerator {0} = null;",
                                                 enumerationContentVariableName.Name
                                                 ),
                                             indentationDepth,
                                             forEachBlock.LoopVar.LineIndex
                                             ))
                                    .Add(new TranslatedStatement(
                                             string.Format(
                                                 "{0}.HANDLEERROR({1}, () => {{",
                                                 _supportRefName.Name,
                                                 scopeAccessInformation.ErrorRegistrationTokenIfAny.Name
                                                 ),
                                             indentationDepth,
                                             forEachBlock.LoopVar.LineIndex
                                             ))
                                    .Add(new TranslatedStatement(
                                             enumeratorInitialisationContent,
                                             indentationDepth + 1,
                                             forEachBlock.LoopVar.LineIndex
                                             ))
                                    .Add(new TranslatedStatement("});", indentationDepth, forEachBlock.LoopVar.LineIndex));
            }
            translationResult = translationResult
                                .Add(new TranslatedStatement("while (true)", indentationDepth, forEachBlock.LoopVar.LineIndex))
                                .Add(new TranslatedStatement("{", indentationDepth, forEachBlock.LoopVar.LineIndex));
            if (scopeAccessInformation.ErrorRegistrationTokenIfAny != null)
            {
                // If error-trapping is enabled and an error was indeed trapped while trying evaluate the enumerator, then the enumerator will be null.
                // In this case, the loop should be executed once but the loop variable not set to anything. When this happens, there is no point trying
                // to call MoveNext (since the enumerator is null) and the loop-variable-setting should be skipped. So an is-null check is wrapper around
                // that work. If error-trapping is not enabled then this check is not required and a level of nesting in the translated output can be
                // avoided.
                translationResult = translationResult
                                    .Add(new TranslatedStatement(
                                             string.Format(
                                                 "if ({0} != null)",
                                                 enumerationContentVariableName.Name
                                                 ),
                                             indentationDepth + 1,
                                             forEachBlock.LoopVar.LineIndex
                                             ))
                                    .Add(new TranslatedStatement("{", indentationDepth + 1, forEachBlock.LoopVar.LineIndex));
                indentationDepth++;
            }
            translationResult = translationResult
                                .Add(new TranslatedStatement(string.Format(
                                                                 "if (!{0}.MoveNext())",
                                                                 enumerationContentVariableName.Name
                                                                 ),
                                                             indentationDepth + 1,
                                                             forEachBlock.LoopVar.LineIndex
                                                             ))
                                .Add(new TranslatedStatement("break;", indentationDepth + 2, forEachBlock.LoopVar.LineIndex))
                                .Add(new TranslatedStatement(
                                         string.Format(
                                             "{0} = {1}.Current;",
                                             rewrittenLoopVarName,
                                             enumerationContentVariableName.Name
                                             ),
                                         indentationDepth + 1,
                                         forEachBlock.LoopVar.LineIndex
                                         ));
            if (scopeAccessInformation.ErrorRegistrationTokenIfAny != null)
            {
                // If error-trapping may be enabled then the above MoveNext and set-to-Current work was wrapped in a condition which must be closed
                translationResult = translationResult.Add(new TranslatedStatement("}", indentationDepth, forEachBlock.LoopVar.LineIndex));
                indentationDepth--;
            }
            var earlyExitNameIfAny = GetEarlyExitNameIfRequired(forEachBlock, scopeAccessInformation);

            if (earlyExitNameIfAny != null)
            {
                translationResult = translationResult.Add(new TranslatedStatement(
                                                              string.Format("var {0} = false;", earlyExitNameIfAny.Name),
                                                              indentationDepth + 1,
                                                              forEachBlock.LoopVar.LineIndex
                                                              ));
            }
            translationResult = translationResult.Add(
                Translate(
                    forEachBlock.Statements.ToNonNullImmutableList(),
                    scopeAccessInformation.SetParent(forEachBlock),
                    earlyExitNameIfAny,
                    indentationDepth + 1
                    )
                );
            if (scopeAccessInformation.ErrorRegistrationTokenIfAny != null)
            {
                // If error-trapping was enabled and an error caught, then the loop should be processed once and only once. The enumerator reference
                // will be null - so check for that and exit if so. If there is no chance that error-trapping is enabled then this condition is not
                // required and there is no point emitting it.
                translationResult = translationResult
                                    .Add(new TranslatedStatement(
                                             string.Format(
                                                 "if ({0} == null)",
                                                 enumerationContentVariableName.Name
                                                 ),
                                             indentationDepth + 1,
                                             forEachBlock.LoopVar.LineIndex
                                             ))
                                    .Add(new TranslatedStatement("break;", indentationDepth + 2, forEachBlock.LoopVar.LineIndex));
            }
            translationResult = translationResult.Add(new TranslatedStatement("}", indentationDepth, forEachBlock.LoopVar.LineIndex));

            var earlyExitFlagNamesToCheck = scopeAccessInformation.StructureExitPoints
                                            .Where(e => e.ExitEarlyBooleanNameIfAny != null)
                                            .Select(e => e.ExitEarlyBooleanNameIfAny.Name);

            if (earlyExitFlagNamesToCheck.Any())
            {
                // Perform early-exit checks for any scopeAccessInformation.StructureExitPoints - if this is FOR loop inside a DO..LOOP loop and an
                // EXIT DO was encountered within the FOR that must refer to the containing DO, then the FOR loop will have been broken out of, but
                // also a flag set that means that we must break further to get out of the DO loop.
                translationResult = translationResult
                                    .Add(new TranslatedStatement(
                                             "if (" + string.Join(" || ", earlyExitFlagNamesToCheck) + ")",
                                             indentationDepth,
                                             forEachBlock.LoopVar.LineIndex
                                             ))
                                    .Add(new TranslatedStatement(
                                             "break;",
                                             indentationDepth + 1,
                                             forEachBlock.LoopVar.LineIndex
                                             ));
            }
            return(translationResult);
        }
Exemple #21
0
        public PredictModel()
        {
            //
            // Dataset size
            //

            numExamples = Variable.New <int>();
            example     = new Range(numExamples);

            //
            // Jagged arrays for (items, features)
            //

            exampleSize = Variable.Array <int>(example);
            item        = new Range(exampleSize[example]);

            scores   = Variable.Array(Variable.Array <double>(item), example);
            features = Variable.Array(Variable.Array <Vector>(item), example);

            //
            // Jagged array for item pair ranks
            //

            rankSize = Variable.Array <int>(example);
            rank     = new Range(rankSize[example]);

            ranks = Variable.Array(Variable.Array <bool>(rank), example);

            //
            // Model parameters
            //

            wPrior = Variable.New <VectorGaussian>();
            w      = Variable.Random <Vector, VectorGaussian>(wPrior);

            //
            // Model
            //

            scoresNoisePrior = Variable.New <Gamma>();
            scoresNoise      = Variable.Random <double, Gamma>(scoresNoisePrior);

            using (Variable.ForEach(example))
            {
                using (Variable.ForEach(item))
                {
                    var mean = Variable.InnerProduct(w, features[example][item]);
                    scores[example][item] = Variable.GaussianFromMeanAndPrecision(mean, scoresNoise);
                }

                using (ForEachBlock pairBlock = Variable.ForEach(rank))
                {
                    var idx  = pairBlock.Index;
                    var diff = scores[example][idx + 1] - scores[example][idx];

                    var positiveDiff = diff > 0;

                    using (Variable.If(positiveDiff))
                        ranks[example][rank].SetTo(Variable.Bernoulli(0.999));
                    using (Variable.IfNot(positiveDiff))
                        ranks[example][rank].SetTo(Variable.Bernoulli(0.001));
                }
            }

            //
            // Inference engine
            //

            engine = new InferenceEngine();
            engine.NumberOfIterations           = 5;
            engine.Compiler.UseParallelForLoops = false;
        }