Exemplo n.º 1
0
        public static void VarianceGammaTimesGaussianMoments2(double a, double m, double v, out double mu, out double vu)
        {
            // compute weights
            Matrix      laplacianMoments = new Matrix(nWeights, nWeights);
            DenseVector exactMoments     = DenseVector.Constant(laplacianMoments.Rows, 1.0);
            // a=10: 7-1
            // a=15: 8-1
            // a=20: 10-1
            // a=21: 10-1
            // a=30: 12-1
            // get best results if the lead term has flat moment ratio
            int jMax = Math.Max(laplacianMoments.Cols, (int)Math.Round(a - 10)) - 1;

            jMax = laplacianMoments.Cols - 1;
            for (int i = 0; i < exactMoments.Count; i++)
            {
                //int ii = jMax-i;
                int    ii        = i;
                double logMoment = MMath.GammaLn(ii + a) - MMath.GammaLn(a) - MMath.GammaLn(ii + 1);
                for (int j = 0; j < laplacianMoments.Cols; j++)
                {
                    int jj = jMax - j;
                    laplacianMoments[i, j] = Math.Exp(MMath.GammaLn(2 * ii + jj + 1) - MMath.GammaLn(2 * ii + 1) - MMath.GammaLn(jj + 1) - logMoment);
                }
            }
            //Console.WriteLine("exactMoments = {0}, laplacianMoments = ", exactMoments);
            //Console.WriteLine(laplacianMoments);
            (new LuDecomposition(laplacianMoments)).Solve(exactMoments);
            DenseVector weights = exactMoments;

            Console.WriteLine("weights = {0}", weights);
            double Z0Plus = 0, Z1Plus = 0, Z2Plus = 0;
            double Z0Minus = 0, Z1Minus = 0, Z2Minus = 0;
            double sqrtV    = Math.Sqrt(v);
            double InvSqrtV = 1 / sqrtV;
            double mPlus    = (m - v) * InvSqrtV;
            double mMinus   = (-m - v) * InvSqrtV;

            for (int j = 0; j < weights.Count; j++)
            {
                int jj = jMax - j;
                Z0Plus  += weights[j] * MMath.NormalCdfMomentRatio(0 + jj, mPlus) * Math.Pow(sqrtV, 0 + jj);
                Z1Plus  += weights[j] * MMath.NormalCdfMomentRatio(1 + jj, mPlus) * (1 + jj) * Math.Pow(sqrtV, 1 + jj);
                Z2Plus  += weights[j] * MMath.NormalCdfMomentRatio(2 + jj, mPlus) * (1 + jj) * (2 + jj) * Math.Pow(sqrtV, 2 + jj);
                Z0Minus += weights[j] * MMath.NormalCdfMomentRatio(0 + jj, mMinus) * Math.Pow(sqrtV, 0 + jj);
                Z1Minus += weights[j] * MMath.NormalCdfMomentRatio(1 + jj, mMinus) * (1 + jj) * Math.Pow(sqrtV, 1 + jj);
                Z2Minus += weights[j] * MMath.NormalCdfMomentRatio(2 + jj, mMinus) * (1 + jj) * (2 + jj) * Math.Pow(sqrtV, 2 + jj);
            }
            double Z0 = Z0Plus + Z0Minus;
            double Z1 = Z1Plus - Z1Minus;
            double Z2 = Z2Plus + Z2Minus;

            mu = Z1 / Z0;
            vu = Z2 / Z0 - mu * mu;
        }
        public void NormalCdfTest()
        {
            /* In python mpmath:
             * from mpmath import *
             * mp.dps = 500
             * mp.pretty = True
             * ncdf(-12.2)
             */
            // In wolfram alpha: (not always accurate)
            // http://www.wolframalpha.com/input/?i=erfc%2813%2Fsqrt%282%29%29%2F2
            // In xcas: (not always accurate)
            // Digits := 30
            // phi(x) := evalf(erfc(-x/sqrt(2))/2);
            double[,] normcdf_pairs = ReadPairs(Path.Combine(TestUtils.DataFolderPath, "SpecialFunctionsValues", "NormalCdf.csv"));
            CheckFunctionValues("NormalCdf", new MathFcn(MMath.NormalCdf), normcdf_pairs);

            Assert.Equal(0.5, MMath.NormalCdf(0));
            Assert.True(MMath.NormalCdf(7.9) <= 1);
            Assert.True(MMath.NormalCdf(-40) >= 0);
            Assert.True(MMath.NormalCdf(-80) >= 0);

            double[,] erfc_pairs = new double[normcdf_pairs.GetLength(0), normcdf_pairs.GetLength(1)];
            for (int i = 0; i < normcdf_pairs.GetLength(0); i++)
            {
                double input  = normcdf_pairs[i, 0];
                double output = normcdf_pairs[i, 1];
                erfc_pairs[i, 0] = -input / MMath.Sqrt2;
                erfc_pairs[i, 1] = 2 * output;
            }
            CheckFunctionValues("Erfc", new MathFcn(MMath.Erfc), erfc_pairs);

            double[,] normcdfinv_pairs = new double[normcdf_pairs.GetLength(0), 2];
            for (int i = 0; i < normcdfinv_pairs.GetLength(0); i++)
            {
                double input  = normcdf_pairs[i, 0];
                double output = normcdf_pairs[i, 1];
                if (!(Double.IsPositiveInfinity(input) || Double.IsNegativeInfinity(input)) && (input <= -10 || input >= 6))
                {
                    normcdfinv_pairs[i, 0] = 0.5;
                    normcdfinv_pairs[i, 1] = 0;
                }
                else
                {
                    normcdfinv_pairs[i, 0] = output;
                    normcdfinv_pairs[i, 1] = input;
                }
            }
            CheckFunctionValues("NormalCdfInv", new MathFcn(MMath.NormalCdfInv), normcdfinv_pairs);

            double[,] normcdfln_pairs = ReadPairs(Path.Combine(TestUtils.DataFolderPath, "SpecialFunctionsValues", "NormalCdfLn.csv"));
            CheckFunctionValues("NormalCdfLn", new MathFcn(MMath.NormalCdfLn), normcdfln_pairs);

            double[,] normcdflogit_pairs = ReadPairs(Path.Combine(TestUtils.DataFolderPath, "SpecialFunctionsValues", "NormalCdfLogit.csv"));
            CheckFunctionValues("NormalCdfLogit", new MathFcn(MMath.NormalCdfLogit), normcdflogit_pairs);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns the largest value x such that GetProbLessThan(x) &lt;= probability.
        /// </summary>
        /// <param name="probability">A real number in [0,1].</param>
        /// <returns></returns>
        public double GetQuantile(double probability)
        {
            if (probability < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(probability), "probability < 0");
            }
            if (probability > 1.0)
            {
                throw new ArgumentOutOfRangeException(nameof(probability), "probability > 1.0");
            }
            // The zero-based index of item in the sorted List<T>, if item is found;
            // otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item
            // or, if there is no larger element, the bitwise complement of Count.
            int index = Array.BinarySearch(probabilities, probability);

            if (index >= 0)
            {
                return(quantiles[index]);
            }
            else
            {
                // Linear interpolation
                int largerIndex = ~index;
                if (largerIndex == 0)
                {
                    return(quantiles[largerIndex]);
                }
                int smallerIndex = largerIndex - 1;
                if (largerIndex == probabilities.Length)
                {
                    return(quantiles[smallerIndex]);
                }
                double upperItem = quantiles[largerIndex];
                double lowerItem = quantiles[smallerIndex];
                double diff      = upperItem - lowerItem;
                if (diff > double.MaxValue)
                {
                    double scale = System.Math.Max(System.Math.Abs(upperItem), System.Math.Abs(lowerItem));
                    double lowerItemOverScale = lowerItem / scale;
                    diff = upperItem / scale - lowerItemOverScale;
                    double slope  = diff / (probabilities[largerIndex] - probabilities[smallerIndex]);
                    double frac   = MMath.LargestDoubleSum(-probabilities[smallerIndex], probability);
                    double offset = MMath.LargestDoubleProduct(frac, slope);
                    return(MMath.LargestDoubleSum(lowerItemOverScale, offset) * scale);
                }
                else
                {
                    double slope = diff / (probabilities[largerIndex] - probabilities[smallerIndex]);
                    // Solve for the largest x such that probabilities[smallerIndex] + (x - quantiles[smallerIndex]) / slope <= probability.
                    double frac   = MMath.LargestDoubleSum(-probabilities[smallerIndex], probability);
                    double offset = MMath.LargestDoubleProduct(frac, slope);
                    return(MMath.LargestDoubleSum(lowerItem, offset));
                }
            }
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
        /// <summary>Evidence message for EP.</summary>
        /// <param name="Double">Incoming message from <c>double</c>.</param>
        /// <param name="Integer">Incoming message from <c>integer</c>.</param>
        /// <returns>Logarithm of the factor's average value across the given argument distributions.</returns>
        /// <remarks>
        ///   <para>The formula for the result is <c>log(sum_(double,integer) p(double,integer) factor(double,integer))</c>.</para>
        /// </remarks>
        public static double LogAverageFactor(Gaussian Double, Discrete Integer)
        {
            double logZ = double.NegativeInfinity;

            for (int i = 0; i < Integer.Dimension; i++)
            {
                double logp = Double.GetLogProb(i) + Integer.GetLogProb(i);
                logZ = MMath.LogSumExp(logZ, logp);
            }
            return(logZ);
        }
Exemplo n.º 6
0
    public Vector3 GetBoundsOnSphere()
    {
        float x = MMath.GetRandomFloat() * zone.width + zone.GetLeftBound();
        float y = MMath.GetRandomFloat() * zone.height + zone.GetBottomBound();
        float z = MMath.GetRandomFloat() * zone.depth + zone.GetFrontBound();

        x = MMath.Clamp(x, zone.GetLeftBound(), zone.GetRightBound());
        y = MMath.Clamp(y, zone.GetBottomBound(), zone.GetTopBound());
        z = MMath.Clamp(z, zone.GetFrontBound(), zone.GetBackBound());
        return(new Vector3(x, y, z));
    }
Exemplo n.º 7
0
    void State_Reset_Start()
    {
        sound.PlayIndependentEvent("C1_PAIN.vente", false, 2);

        //turn off the mesh and move him away
        //cmesh.setEnabled(false);
        gameObject.transform.SetPosition(0, -100, 0);
        Logger.Log("Monster3 has reset");

        resetting.MaxTimeInState = MMath.GetRandomLimitedFloat(18.0f, 30.0f);
    }
 /// <summary>
 /// Computes the logarithm of the normalizer (sum of values of the weight function on all sequences)
 /// of the square of the current weight function.
 /// </summary>
 /// <returns>The logarithm of the normalizer.</returns>
 protected double GetLogNormalizerOfSquare()
 {
     if (Dictionary == null || Dictionary.Count == 0)
     {
         return(double.NegativeInfinity);
     }
     else
     {
         return(MMath.LogSumExp(Dictionary.Values.Select(v => 2 * v.LogValue)));
     }
 }
Exemplo n.º 9
0
        public void WeightedAverageTest()
        {
            Assert.Equal(Environment.Is64BitProcess ? 3.86361619394904E-311 : 3.86361619394162E-311, MMath.WeightedAverage(0.82912896852490248, 2.5484859206000203E-311, 3.50752234977395E-313, 31.087830618727477));
            Assert.Equal(MMath.WeightedAverage(0.1, double.MinValue, 0.01, double.MinValue), double.MinValue);
            Assert.Equal(MMath.WeightedAverage(0.1, -double.Epsilon, double.MaxValue, -double.Epsilon), -double.Epsilon);
            Assert.Equal(MMath.WeightedAverage(1e-100, 2e-250, 1e-100, 4e-250), MMath.Average(2e-250, 4e-250));
            Assert.Equal(MMath.WeightedAverage(1e100, 2e250, 1e100, 4e250), MMath.Average(2e250, 4e250));
            Assert.Equal(MMath.WeightedAverage(0, 0, 0.1, -double.Epsilon), -double.Epsilon);
            Assert.Equal(MMath.WeightedAverage(0.1, -double.Epsilon, 0, double.NegativeInfinity), -double.Epsilon);
            Assert.False(double.IsNaN(MMath.WeightedAverage(1.7976931348623157E+308, double.NegativeInfinity, 4.94065645841247E-324, double.NegativeInfinity)));
            Assert.False(double.IsNaN(MMath.WeightedAverage(0.01, double.NegativeInfinity, double.MaxValue, double.MaxValue)));
            Assert.False(double.IsNaN(MMath.WeightedAverage(0.01, double.NegativeInfinity, double.Epsilon, double.NegativeInfinity)));
            Assert.Equal(double.MaxValue, MMath.WeightedAverage(double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue));
            const int limit = 2_000_000;
            int       count = 0;

            Parallel.ForEach(OperatorTests.DoublesAtLeastZero(), wa =>
            {
                Parallel.ForEach(OperatorTests.DoublesAtLeastZero(), wb =>
                {
                    if (count > limit)
                    {
                        return;
                    }
                    Trace.WriteLine($"wa = {wa}, wb = {wb}");
                    foreach (var a in OperatorTests.Doubles())
                    {
                        if (count > limit)
                        {
                            break;
                        }
                        foreach (var b in OperatorTests.Doubles())
                        {
                            if (count > limit)
                            {
                                break;
                            }
                            if (double.IsNaN(a + b))
                            {
                                continue;
                            }
                            double midpoint = MMath.WeightedAverage(wa, a, wb, b);
                            Assert.True(midpoint >= System.Math.Min(a, b), $"Failed assertion: MMath.WeightedAverage({wa:r}, {a:r}, {wb:r}, {b:r}) {midpoint} >= {System.Math.Min(a, b)}");
                            Assert.True(midpoint <= System.Math.Max(a, b), $"Failed assertion: MMath.WeightedAverage({wa:r}, {a:r}, {wb:r}, {b:r}) {midpoint} <= {System.Math.Max(a, b)}");
                            if (wa == wb)
                            {
                                Assert.Equal(MMath.Average(a, b), midpoint);
                            }
                            Interlocked.Add(ref count, 1);
                        }
                    }
                });
            });
        }
Exemplo n.º 10
0
 public void LogisticGaussianTest2()
 {
     for (int i = 4; i < 100; i++)
     {
         double v   = System.Math.Pow(10, i);
         double f   = MMath.LogisticGaussian(1, v);
         double err = System.Math.Abs(f - 0.5);
         //Console.WriteLine("{0}: {1} {2}", i, f, err);
         Assert.True(err < 2e-2 / i);
     }
 }
Exemplo n.º 11
0
 public void UniformQuadrature2()
 {
     for (int count = 3; count <= 20; count++)
     {
         Vector nodes   = Vector.Zero(count);
         Vector weights = Vector.Zero(count);
         Quadrature.UniformNodesAndWeights(0, 1, nodes, weights);
         double result = (weights * (nodes ^ 5.0)).Sum();
         Assert.True(MMath.AbsDiff(1.0 / 6, result, 1e-10) < 1e-10);
     }
 }
Exemplo n.º 12
0
        // MEarth.ParallelOfLatitude(double)
        /// <summary>
        /// Liefert den Radius des Breitenkreises zur geographischen Breite.
        /// </summary>
        /// <param name="phi">Geographische Breite.</param>
        /// <returns>Radius des Breitenkreises zur geographischen Breite.</returns>
        public static double ParallelOfLatitude(double phi)
        {
            // Lokale Felder einrichten
            double e = 0.081819221;
            double n = 6378.14 * MMath.Cos(phi);
            double h = e * MMath.Sin(phi);
            double d = MMath.Sqr(1.0 - h * h);

            // Längenparallele berechnen
            return(n / d);
        }
Exemplo n.º 13
0
        /// <summary>Evidence message for EP.</summary>
        /// <param name="sample">Constant value for <c>sample</c>.</param>
        /// <param name="logOdds">Incoming message from <c>logOdds</c>. Must be a proper distribution. If uniform, the result will be uniform.</param>
        /// <returns>Logarithm of the factor's average value across the given argument distributions.</returns>
        /// <remarks>
        ///   <para>The formula for the result is <c>log(sum_(logOdds) p(logOdds) factor(sample,logOdds))</c>.</para>
        /// </remarks>
        /// <exception cref="ImproperMessageException">
        ///   <paramref name="logOdds" /> is not a proper distribution.</exception>
        public static double LogAverageFactor(bool sample, [Proper] Gaussian logOdds)
        {
            if (logOdds.IsPointMass)
            {
                return(LogAverageFactor(sample, logOdds.Point));
            }
            double m, v;

            logOdds.GetMeanAndVariance(out m, out v);
            return(Math.Log(MMath.LogisticGaussian(sample ? m : -m, v)));
        }
 /// <summary>
 /// Evidence message for EP
 /// </summary>
 /// <param name="logistic">Constant value for 'logistic'.</param>
 /// <param name="x">Incoming message from 'x'.</param>
 /// <returns>Logarithm of the factor's average value across the given argument distributions</returns>
 /// <remarks><para>
 /// The formula for the result is <c>log(sum_(x) p(x) factor(logistic,x))</c>.
 /// </para></remarks>
 public static double LogAverageFactor(double logistic, Gaussian x)
 {
     if (logistic >= 1.0 || logistic <= 0.0)
     {
         return(x.GetLogProb(MMath.Logit(logistic)));
     }
     // p(y,x) = delta(y - 1/(1+exp(-x))) N(x;mx,vx)
     // x = log(y/(1-y))
     // dx = 1/(y*(1-y))
     return(x.GetLogProb(MMath.Logit(logistic)) / (logistic * (1 - logistic)));
 }
Exemplo n.º 15
0
 /// <summary>Evidence message for VMP.</summary>
 /// <param name="sample">Constant value for <c>sample</c>.</param>
 /// <param name="logOdds">Constant value for <c>logOdds</c>.</param>
 /// <returns>Average of the factor's log-value across the given argument distributions.</returns>
 /// <remarks>
 ///   <para>The formula for the result is <c>log(factor(sample,logOdds))</c>. Adding up these values across all factors and variables gives the log-evidence estimate for VMP.</para>
 /// </remarks>
 public static double AverageLogFactor(bool sample, double logOdds)
 {
     if (sample)
     {
         return(MMath.LogisticLn(logOdds));
     }
     else
     {
         return(MMath.LogisticLn(-logOdds));
     }
 }
Exemplo n.º 16
0
Arquivo: Gamma.cs Projeto: 0xCM/arrows
 /// <summary>
 /// Gets log normalizer
 /// </summary>
 /// <returns></returns>
 public double GetLogNormalizer()
 {
     if (IsProper())
     {
         return(MMath.GammaLn(Shape) - Shape * Math.Log(Rate));
     }
     else
     {
         return(0.0);
     }
 }
Exemplo n.º 17
0
 public void DigammaInvTest()
 {
     for (int i = 0; i < 1000; i++)
     {
         double y     = -3 + i * 0.01;
         double x     = MMath.DigammaInv(y);
         double y2    = MMath.Digamma(x);
         double error = MMath.AbsDiff(y, y2, 1e-8);
         Assert.True(error < 1e-8);
     }
 }
Exemplo n.º 18
0
        // MEarth.Direction(double, double, double, double)
        /// <summary>
        /// Liefert die geographische Richtung zweier Orte auf der Erdoberfläche.
        /// </summary>
        /// <param name="lamdaA">Geographische Länge des Ortes A.</param>
        /// <param name="phiA">Geographische Breite des Ortes A.</param>
        /// <param name="lamdaB">Geographische Länge des Ortes B.</param>
        /// <param name="phiB">Geographische Breite des Ortes B.</param>
        /// <returns>Geographische Richtung zweier Orte auf der Erdoberfläche.</returns>
        public static double Direction(double lamdaA, double phiA, double lamdaB, double phiB)
        {
            // Lokale Felder einrichten
            double d = MMath.Cos(phiA) * MMath.Tan(phiB) - MMath.Sin(phiA) * MMath.Cos(lamdaA - lamdaB);

            // Winkel berechnen und liefern
            if (d == 0.0)
            {
                return(0.0);
            }
            return(MMath.Mod(MMath.ArcTan(MMath.Sin(lamdaA - lamdaB), d), MMath.Pi2));
        }
 static internal double ComputeMeanLogOneMinus(double trueCount, double falseCount)
 {
     if (double.IsPositiveInfinity(falseCount))
     {
         return(Math.Log(1 - trueCount));
     }
     if ((trueCount == 0.0) && (falseCount == 0.0))
     {
         throw new ImproperDistributionException(new Beta(trueCount, falseCount));
     }
     return(MMath.Digamma(falseCount) - MMath.Digamma(trueCount + falseCount));
 }
Exemplo n.º 20
0
 public static int Histogramize(double value, double mean, double deviation, int numberOfBins)
 {
     for (int ii = 1; ii <= numberOfBins; ii++)
     {
         double above = MMath.NormalCdfInv(((double)ii) / ((double)numberOfBins));
         if (((value - mean) / deviation) < above)
         {
             return(ii - 1);
         }
     }
     return(numberOfBins - 1);
 }
Exemplo n.º 21
0
        /// <include file='FactorDocs.xml' path='factor_docs/message_op_class[@name="MultinomialOp"]/message_doc[@name="LogAverageFactor(IList{int}, int, Dirichlet)"]/*'/>
        public static double LogAverageFactor(IList <int> sample, int trialCount, Dirichlet p)
        {
            double result = MMath.GammaLn(trialCount + 1);

            for (int i = 0; i < sample.Count; i++)
            {
                result += MMath.GammaLn(sample[i] + p.PseudoCount[i]) + MMath.GammaLn(p.PseudoCount[i])
                          - MMath.GammaLn(sample[i] + 1);
            }
            result += MMath.GammaLn(p.TotalCount) - MMath.GammaLn(p.TotalCount + trialCount);
            return(result);
        }
Exemplo n.º 22
0
        /// <summary>VMP message to <c>sample</c>.</summary>
        /// <param name="choice">Incoming message from <c>choice</c>.</param>
        /// <param name="probTrue0">Constant value for <c>probTrue0</c>.</param>
        /// <param name="probTrue1">Constant value for <c>probTrue1</c>.</param>
        /// <returns>The outgoing VMP message to the <c>sample</c> argument.</returns>
        /// <remarks>
        ///   <para>The outgoing message is the exponential of the average log-factor value, where the average is over all arguments except <c>sample</c>. The formula is <c>exp(sum_(choice) p(choice) log(factor(sample,choice,probTrue0,probTrue1)))</c>.</para>
        /// </remarks>
        public static Bernoulli SampleAverageLogarithm(Bernoulli choice, double probTrue0, double probTrue1)
        {
            Bernoulli result = new Bernoulli();

            if (choice.IsPointMass)
            {
                return(SampleConditional(choice.Point, probTrue0, probTrue1));
            }
            // log(p(X=true)/p(X=false)) = sum_k p(Y=k) log(ProbTrue[k]/(1-ProbTrue[k]))
            result.LogOdds = choice.GetProbFalse() * MMath.Logit(probTrue0) + choice.GetProbTrue() * MMath.Logit(probTrue1);
            return(result);
        }
Exemplo n.º 23
0
        /// <summary>
        /// The maximum 'difference' between the parameters of this instance and of that instance.
        /// </summary>
        /// <param name="thatd">That distribution</param>
        /// <returns>The resulting maximum difference</returns>
        /// <remarks><c>a.MaxDiff(b) == b.MaxDiff(a)</c></remarks>
        public double MaxDiff(object thatd)
        {
            if (!(thatd is Beta))
            {
                return(Double.PositiveInfinity);
            }
            Beta that = (Beta)thatd;

            // test for equality to catch infinities.
            return(System.Math.Max(MMath.AbsDiff(that.TrueCount, TrueCount),
                                   MMath.AbsDiff(that.FalseCount, FalseCount)));
        }
Exemplo n.º 24
0
        public void WeightedAverage_IsMonotonic2()
        {
            double wa        = double.MaxValue;
            double a         = 1;
            double a2        = 1.0000000000000011;
            double wb        = 0.0010000000000000002;
            double b         = double.MinValue;
            double midpoint  = MMath.WeightedAverage(wa, a, wb, b);
            double midpoint2 = MMath.WeightedAverage(wa, a2, wb, b);

            Assert.True(midpoint2 >= midpoint, $"Failed assertion: {midpoint2} >= {midpoint}, wa={wa:r}, a={a:r}, a2={a2:r}, wb={wb:r}, b={b:r}");
        }
Exemplo n.º 25
0
 /// <include file='FactorDocs.xml' path='factor_docs/message_op_class[@name="GateExitOp{T}"]/message_doc[@name="ExitAverageConditional{TDist}(TDist, IList{Bernoulli}, IList{TDist}, TDist)"]/*'/>
 /// <typeparam name="TDist">The type of the distribution over the variable exiting the gate.</typeparam>
 public static TDist ExitAverageConditional2 <TDist>(
     TDist exit, IList <Bernoulli> cases, [SkipIfAllUniform] IList <TDist> values, TDist result)
     where TDist : SettableTo <TDist>, ICloneable, SettableToProduct <TDist>,
 SettableToRatio <TDist>, SettableToWeightedSum <TDist>
 {
     if (cases.Count != values.Count)
     {
         throw new ArgumentException("cases.Count != values.Count");
     }
     if (cases.Count == 0)
     {
         throw new ArgumentException("cases.Count == 0");
     }
     else if (cases.Count == 1)
     {
         result.SetTo(values[0]);
     }
     else
     {
         result.SetToProduct(exit, values[0]);
         double scale       = cases[0].LogOdds;
         double resultScale = scale;
         // TODO: use pre-allocated buffer
         TDist product = (TDist)exit.Clone();
         for (int i = 1; i < cases.Count; i++)
         {
             scale = cases[i].LogOdds;
             double shift = Math.Max(resultScale, scale);
             // avoid (-Infinity) - (-Infinity)
             if (Double.IsNegativeInfinity(shift))
             {
                 if (i == cases.Count - 1)
                 {
                     throw new AllZeroException();
                 }
                 // do nothing
             }
             else
             {
                 double weight1 = Math.Exp(resultScale - shift);
                 double weight2 = Math.Exp(scale - shift);
                 if (weight2 > 0)
                 {
                     product.SetToProduct(exit, values[i]);
                     result.SetToSum(weight1, result, weight2, product);
                     resultScale = MMath.LogSumExp(resultScale, scale);
                 }
             }
         }
         result.SetToRatio(result, exit, GateEnterOp <T> .ForceProper);
     }
     return(result);
 }
Exemplo n.º 26
0
        public void WeightedAverage_IsMonotonic3()
        {
            double wa        = 1E-05;
            double a         = -1.7976931348623157E+308;
            double a2        = -1.7976931348623155E+308;
            double wb        = 1.0;
            double b         = -1E+287;
            double midpoint  = MMath.WeightedAverage(wa, a, wb, b);
            double midpoint2 = MMath.WeightedAverage(wa, a2, wb, b);

            Assert.True(midpoint2 >= midpoint, $"Failed assertion: {midpoint2} >= {midpoint}, wa={wa:r}, a={a:r}, a2={a2:r}, wb={wb:r}, b={b:r}");
        }
Exemplo n.º 27
0
        public double[] getbsdelta(double strike, double under, double volatility, double t, double rate)//calculate delta
        {
            double d1;

            double[] delta = new double[2];
            d1       = (Math.Log(under / strike) + (rate + Math.Pow(volatility, 2) / 6) * t / 2) / (volatility * Math.Sqrt(t / 3));
            delta[0] = MMath.NormalCdf(d1); //call delta
            delta[1] = delta[0] - 1;        //put delta


            return(delta);
        }
Exemplo n.º 28
0
        public void WeightedAverageTest()
        {
            Assert.Equal(MMath.WeightedAverage(0.1, double.MinValue, 0.01, double.MinValue), double.MinValue);
            Assert.Equal(MMath.WeightedAverage(0.1, -double.Epsilon, double.MaxValue, -double.Epsilon), -double.Epsilon);
            Assert.Equal(MMath.WeightedAverage(1e-100, 2e-250, 1e-100, 4e-250), MMath.Average(2e-250, 4e-250));
            Assert.Equal(MMath.WeightedAverage(1e100, 2e250, 1e100, 4e250), MMath.Average(2e250, 4e250));
            Assert.Equal(MMath.WeightedAverage(0, 0, 0.1, -double.Epsilon), -double.Epsilon);
            Assert.Equal(MMath.WeightedAverage(0.1, -double.Epsilon, 0, double.NegativeInfinity), -double.Epsilon);
            Assert.False(double.IsNaN(MMath.WeightedAverage(1.7976931348623157E+308, double.NegativeInfinity, 4.94065645841247E-324, double.NegativeInfinity)));
            Assert.False(double.IsNaN(MMath.WeightedAverage(0.01, double.NegativeInfinity, double.MaxValue, double.MaxValue)));
            Assert.False(double.IsNaN(MMath.WeightedAverage(0.01, double.NegativeInfinity, double.Epsilon, double.NegativeInfinity)));
            Assert.Equal(double.MaxValue, MMath.WeightedAverage(double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue));
            const int limit = 2_000_000;
            int       count = 0;

            Parallel.ForEach(OperatorTests.DoublesAtLeastZero(), wa =>
            {
                Parallel.ForEach(OperatorTests.DoublesAtLeastZero(), wb =>
                {
                    if (count > limit)
                    {
                        return;
                    }
                    Trace.WriteLine($"wa = {wa}, wb = {wb}");
                    foreach (var a in OperatorTests.Doubles())
                    {
                        if (count > limit)
                        {
                            break;
                        }
                        foreach (var b in OperatorTests.Doubles())
                        {
                            if (count > limit)
                            {
                                break;
                            }
                            if (double.IsNaN(a + b))
                            {
                                continue;
                            }
                            double midpoint = MMath.WeightedAverage(wa, a, wb, b);
                            Assert.True(midpoint >= System.Math.Min(a, b), $"Failed assertion: {midpoint} >= {System.Math.Min(a, b)}, wa={wa:r}, a={a:r}, wb={wb:r}, b={b:r}");
                            Assert.True(midpoint <= System.Math.Max(a, b), $"Failed assertion: {midpoint} <= {System.Math.Max(a, b)}, wa={wa:r}, a={a:r}, wb={wb:r}, b={b:r}");
                            if (wa == wb)
                            {
                                Assert.Equal(MMath.Average(a, b), midpoint);
                            }
                            Interlocked.Add(ref count, 1);
                        }
                    }
                });
            });
        }
Exemplo n.º 29
0
 public double GetLogProb(int value)
 {
     if (value < 0 || value > TrialCount)
     {
         return(double.NegativeInfinity);
     }
     if (IsPointMass)
     {
         return((value == Point) ? 1.0 : 0.0);
     }
     return(MMath.GammaLn(TrialCount + 1) - A * MMath.GammaLn(value + 1) - B * MMath.GammaLn(TrialCount - value + 1) + value * LogOdds + TrialCount * MMath.LogisticLn(-LogOdds));
 }
Exemplo n.º 30
0
    void FindSpawnPoint()
    {
        Vector3 p = MMath.GetRandomPointInCircle(player.transform.position, SPAWNRADIUS);

        gameObject.transform.SetPosition(p);
        if (helper.CheckLights(gameObject))
        {
            gameObject.transform.SetPositionX(-10000);
            smc.SetState(respawning);
            Logger.Log("Monster4 could not spawn, respawning...");
        }
    }