Exemplo n.º 1
0
        /// <summary>
        ///     Given a random model
        ///     set the weights : an array fill of random float ranging [-1; 1]
        ///     representing the detailed Belief of an agent
        /// </summary>
        /// <param name="model"></param>
        /// <param name="length"></param>
        /// <param name="beliefWeightLevel"></param>
        /// <returns></returns>
        public void InitializeWeights(RandomGenerator model, byte length, BeliefWeightLevel beliefWeightLevel)
        {
            float[] beliefBits;
            switch (beliefWeightLevel)
            {
            case BeliefWeightLevel.NoWeight:
                beliefBits = DiscreteUniform.Samples(length, 0, 0);
                break;

            case BeliefWeightLevel.RandomWeight:
                beliefBits = model == RandomGenerator.RandomUniform
                        ? ContinuousUniform.Samples(length, 0, RangeMax)
                        : DiscreteUniform.Samples(length, 0, RangeMax);
                break;

            case BeliefWeightLevel.FullWeight:
                beliefBits = DiscreteUniform.Samples(length, 1, 1);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(beliefWeightLevel), beliefWeightLevel, null);
            }

            Weights = new Bits(beliefBits, 0);
        }
Exemplo n.º 2
0
        /// Generates samples with weightings that are integral and compares that to the unweighted statistics result. Doesn't correspond with the
        /// higher order sample statistics because our weightings represent reliability weights, *not* frequency weights, and the Bessel correction is
        /// calculated appropriately - so don't let the construction of the test mislead you.
        public void ConsistentWithUnweighted(string dataSet)
        {
            var data    = _data[dataSet].Data.ToArray();
            var gen     = new DiscreteUniform(1, 5);
            var weights = new int[data.Length];

            gen.Samples(weights);

            var stats  = new RunningWeightedStatistics(data.Select((x, i) => System.Tuple.Create((double)weights[i], x)));
            var stats2 = new RunningStatistics();

            for (int i = 0; i < data.Length; ++i)
            {
                for (int j = 0; j < weights[i]; ++j)
                {
                    stats2.Push(data[i]);
                }
            }
            var sumWeights = weights.Sum();

            Assert.That(stats.TotalWeight, Is.EqualTo(sumWeights), "TotalWeight");
            Assert.That(stats.Count, Is.EqualTo(weights.Length), "Count");
            Assert.That(stats2.Minimum, Is.EqualTo(stats.Minimum), "Minimum");
            Assert.That(stats2.Maximum, Is.EqualTo(stats.Maximum), "Maximum");
            Assert.That(stats2.Mean, Is.EqualTo(stats.Mean).Within(1e-8), "Mean");
            Assert.That(stats2.PopulationVariance, Is.EqualTo(stats.PopulationVariance).Within(1e-9), "PopulationVariance");
            Assert.That(stats2.PopulationStandardDeviation, Is.EqualTo(stats.PopulationStandardDeviation).Within(1e-9), "PopulationStandardDeviation");
            Assert.That(stats2.PopulationSkewness, Is.EqualTo(stats.PopulationSkewness).Within(1e-8), "PopulationSkewness");
            Assert.That(stats2.PopulationKurtosis, Is.EqualTo(stats.PopulationKurtosis).Within(1e-8), "PopulationKurtosis");
        }
Exemplo n.º 3
0
        public double[] getSamples(int num) // 获取指定个数的样本
        {
            double[] ret     = new double[num];
            int[]    ret_int = new int[num];
            switch (DistributionName)
            {
            case "Normal":
                normalDis.Samples(ret);
                break;

            case "ContinuousUniform":
                continuousUniformDis.Samples(ret);
                break;

            case "Triangular":
                triangularDis.Samples(ret);
                break;

            case "StudentT":
                studentTDis.Samples(ret);
                break;

            case "DiscreteUniform":
                discreteUniform.Samples(ret_int);
                for (int i = 0; i < num; i++)
                {
                    ret[i] = ret_int[i];
                }
                break;
            }
            return(ret);
        }
Exemplo n.º 4
0
        public void CanSampleSequence()
        {
            var n   = new DiscreteUniform(0, 10);
            var ied = n.Samples();

            GC.KeepAlive(ied.Take(5).ToArray());
        }
Exemplo n.º 5
0
        protected void Generate()
        {
            var amount = poisson.Sample();
            var array  = new int[amount];

            DiscreteUniform.Samples(array, 0, Constants.ONE_SECOND_TIME - 1);
            samples = new HashSet <int>(array);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Gets a list of amiability levels
        /// </summary>
        /// <param name="quantity">How many levels are requested</param>
        /// <returns></returns>
        public List <AmiabilityLevel> GetUniformAmiabilityList(int quantity)
        {
            int[] distArray = new int[quantity];
            uniformDist.Samples(distArray);

            List <AmiabilityLevel> amiabilityList = new List <AmiabilityLevel>(quantity);

            foreach (int value in distArray)
            {
                amiabilityList.Add((AmiabilityLevel)value);
            }
            return(amiabilityList);
        }
Exemplo n.º 7
0
        private static List <Troop> GenerateTroops(int minTier, int maxTier, int size)
        {
            var dist    = new DiscreteUniform(minTier, maxTier);
            var samples = new int[size];

            dist.Samples(samples);
            var result = new List <Troop>();

            for (var i = 0; i < size; i++)
            {
                result.Add(new Troop(new UniqueTroopDescriptor(UniqueTroopId), new CharacterObject(samples[i]), true));
            }
            return(result);
        }
Exemplo n.º 8
0
        public static ITSLType GenerateArrayType(this TSLGeneratorContext context)
        {
            var elementType = context.GenerateRandomArrayElementType();
            var dimension   = DiscreteUniform.Sample(
                context.MasterRandom,
                ContainerProbabilities.Array.MinDimension,
                ContainerProbabilities.Array.MaxDimension);
            var dimensions =
                DiscreteUniform.Samples(context.MasterRandom,
                                        ContainerProbabilities.Array.MinDimensionLength,
                                        ContainerProbabilities.Array.MaxDimensionLength)
                .Take(dimension);

            return(new ArrayType(elementType, dimensions.ToArray()));
        }
Exemplo n.º 9
0
        public static IEnumerable <TSLProtocol> GetRandomDistinctProtocols(this TSLGeneratorContext context, int number)
        {
            if (context.Protocols.Count == 0)
            {
                return(Enumerable.Empty <TSLProtocol>());
            }
            if (number > context.Protocols.Count)
            {
                number = context.Protocols.Count;
            }
            var protocols = DiscreteUniform.Samples(context.MasterRandom, 0, context.Protocols.Count - 1)
                            .Take(number)
                            .Distinct()                 // may return fewer than number of protocols
                            .Select(i => context.Protocols[i]);

            return(protocols);
        }
Exemplo n.º 10
0
        public static Task GenerateOrders(ProductionDomainContext context, SimulationConfiguration simConfig, int simulationNumber)
        {
            return(Task.Run(() =>
            {
                var time = 0;
                var samples = simConfig.OrderQuantity;
                var seed = new Random(simConfig.Seed + simulationNumber);
                var productIds = context.ArticleBoms.Where(b => b.ArticleParentId == null).Select(a => a.ArticleChildId)
                                 .ToList();

                var dist = new Exponential(rate: simConfig.OrderRate, randomSource: seed);
                //get equal distribution from 0 to 1
                var norml = new DiscreteUniform(0, productIds.Count() - 1, seed);
                //get equal distribution for duetime
                var normalDuetime = new DiscreteUniform(1160, 1600, seed); //2160,3600

                double[] exponential = new double[samples];                //new Exponential(0.25, seed);
                int[] prodVariation = new int[samples];
                int[] duetime = new int[samples];
                dist.Samples(exponential);
                norml.Samples(prodVariation);
                normalDuetime.Samples(duetime);
                //get products by searching for articles without parents
                for (int i = 0; i < samples; i++)
                {
                    //define the time between each new order
                    time += (int)Math.Round(exponential[i] * 10, MidpointRounding.AwayFromZero);
                    //get which product is to be ordered
                    var productId = productIds.ElementAt(prodVariation[i]);

                    //create order and orderpart, duetime is creationtime + 1 day
                    context.Orders.Add(context.CreateNewOrder(productId, 1, time, time + duetime[i]));
                }
                context.SaveChangesAsync();
            }));
        }
Exemplo n.º 11
0
 public void FailSampleSequenceStatic()
 {
     Assert.That(() => DiscreteUniform.Samples(new System.Random(0), 20, 10).First(), Throws.ArgumentException);
 }
Exemplo n.º 12
0
        public void CanSampleSequenceStatic()
        {
            var ied = DiscreteUniform.Samples(new System.Random(0), 0, 10);

            GC.KeepAlive(ied.Take(5).ToArray());
        }
 public void FailSampleSequenceStatic()
 {
     var ied = DiscreteUniform.Samples(new Random(), 20, 10).First();
 }
 public void CanSampleSequenceStatic()
 {
     var ied = DiscreteUniform.Samples(new Random(), 0, 10);
     var arr = ied.Take(5).ToArray();
 }
Exemplo n.º 15
0
        public double[] GetSampleData(string distType, double mostLikelyEstimate,
                                      double lowEstimate, double highEstimate)
        {
            if (Iterations > 10000)
            {
                Iterations = 10000;
            }
            if (Iterations <= 2)
            {
                Iterations = 1000;
            }
            if (this.CILevel < 10)
            {
                this.CILevel = 90;
            }
            if (this.CILevel > 99)
            {
                this.CILevel = 99;
            }
            Random rnd = new Random(Random);

            mostLikelyEstimate = Math.Round(mostLikelyEstimate, 4);
            lowEstimate        = Math.Round(lowEstimate, 4);
            highEstimate       = Math.Round(highEstimate, 4);
            var sampledata = new double[Iterations];

            if (distType == Calculator1.RUC_TYPES.triangle.ToString())
            {
                if (lowEstimate >= mostLikelyEstimate || lowEstimate == 0)
                {
                    //arbitrary rules (25%)
                    lowEstimate = mostLikelyEstimate * .75;
                    //no errors: lowEstimate = 0 is often the case
                    //sb.AppendLine(Errors.GetMessage("DATA_BADDISTRIBUTION"));
                }
                if (highEstimate <= mostLikelyEstimate || highEstimate == 0)
                {
                    //arbitrary rules (25%)
                    highEstimate = mostLikelyEstimate * 1.25;
                }
                if (Random != 0)
                {
                    //generate samples of the Triangular(low, high, mode) distribution;
                    Triangular.Samples(rnd, sampledata, lowEstimate, highEstimate, mostLikelyEstimate);
                }
                else
                {
                    //generate samples of the Triangular(low, high, mode) distribution;
                    Triangular.Samples(sampledata, lowEstimate, highEstimate, mostLikelyEstimate);
                }
            }
            else if (distType == Calculator1.RUC_TYPES.normal.ToString())
            {
                //generate samples of the Normal(mean, sd) distribution;
                if (Random != 0)
                {
                    Normal.Samples(rnd, sampledata, lowEstimate, highEstimate);
                }
                else
                {
                    Normal.Samples(sampledata, lowEstimate, highEstimate);
                }
            }
            else if (distType == Calculator1.RUC_TYPES.lognormal.ToString())
            {
                if (Random != 0)
                {
                    LogNormal.Samples(rnd, sampledata, lowEstimate, highEstimate);
                }
                else
                {
                    LogNormal.Samples(sampledata, lowEstimate, highEstimate);
                }
            }
            else if (distType == Calculator1.RUC_TYPES.weibull.ToString())
            {
                if (Random != 0)
                {
                    Weibull.Samples(rnd, sampledata, lowEstimate, highEstimate);
                }
                else
                {
                    Weibull.Samples(sampledata, lowEstimate, highEstimate);
                }
            }
            else if (distType == Calculator1.RUC_TYPES.beta.ToString())
            {
                if (Random != 0)
                {
                    Beta.Samples(rnd, sampledata, lowEstimate, highEstimate);
                }
                else
                {
                    Beta.Samples(sampledata, lowEstimate, highEstimate);
                }
            }
            else if (distType == Calculator1.RUC_TYPES.pareto.ToString())
            {
                if (Random != 0)
                {
                    Pareto.Samples(rnd, sampledata, lowEstimate, highEstimate);
                }
                else
                {
                    Pareto.Samples(sampledata, lowEstimate, highEstimate);
                }
            }
            else if (distType == Calculator1.RUC_TYPES.uniform.ToString())
            {
                var sampleints = new int[Iterations];
                int iLower     = CalculatorHelpers.ConvertStringToInt(lowEstimate.ToString());
                int iUpper     = CalculatorHelpers.ConvertStringToInt(highEstimate.ToString());
                if (Random != 0)
                {
                    DiscreteUniform.Samples(rnd, sampleints, iLower, iUpper);
                }
                else
                {
                    DiscreteUniform.Samples(sampleints, iLower, iUpper);
                }
                for (int i = 0; i < sampleints.Count(); i++)
                {
                    sampledata[i] = sampleints[i];
                }
            }
            else if (distType == Calculator1.RUC_TYPES.bernoulli.ToString())
            {
                var sampleints = new int[Iterations];
                if (Random != 0)
                {
                    Bernoulli.Samples(rnd, sampleints, lowEstimate);
                }
                else
                {
                    Bernoulli.Samples(sampleints, lowEstimate);
                }
                for (int i = 0; i < sampleints.Count(); i++)
                {
                    sampledata[i] = sampleints[i];
                }
            }
            else if (distType == Calculator1.RUC_TYPES.poisson.ToString())
            {
                var sampleints = new int[Iterations];
                if (Random != 0)
                {
                    Poisson.Samples(rnd, sampleints, lowEstimate);
                }
                else
                {
                    Poisson.Samples(sampleints, lowEstimate);
                }
                for (int i = 0; i < sampleints.Count(); i++)
                {
                    sampledata[i] = sampleints[i];
                }
            }
            else if (distType == Calculator1.RUC_TYPES.binomial.ToString())
            {
                var sampleints     = new int[Iterations];
                int iUpperEstimate = CalculatorHelpers.ConvertStringToInt(highEstimate.ToString());
                if (Random != 0)
                {
                    Binomial.Samples(rnd, sampleints, lowEstimate, iUpperEstimate);
                }
                else
                {
                    Binomial.Samples(sampleints, lowEstimate, iUpperEstimate);
                }
                for (int i = 0; i < sampleints.Count(); i++)
                {
                    sampledata[i] = sampleints[i];
                }
            }
            else if (distType == Calculator1.RUC_TYPES.gamma.ToString())
            {
                //generate samples of the Gamma(shape, scale) distribution;
                if (Random != 0)
                {
                    Gamma.Samples(rnd, sampledata, lowEstimate, highEstimate);
                }
                else
                {
                    Gamma.Samples(sampledata, lowEstimate, highEstimate);
                }
            }
            else
            {
                //don't force them to use distribution
            }
            //hold for possible infernet use
            //else if (distType == Calculator1.RUC_TYPES.dirichlet.ToString())
            //{
            //    //generate samples of the Dirichlet(random, alpha) distribution;
            //    Dirichlet.Sample(sampledata, lowEstimate);
            //}
            //else if (distType == Calculator1.RUC_TYPES.wishart.ToString())
            //{
            //    //generate samples of the Wishart(random, degrees of freedom, scale) distribution;
            //    Wishart.Sample(sampledata, lowEstimate, highEstimate);
            //}

            //the mathlibrary supports more than a dozen additional distributions

            return(sampledata);
        }
Exemplo n.º 16
0
 public void FailSampleSequenceStatic()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => DiscreteUniform.Samples(new Random(), 20, 10).First());
 }
Exemplo n.º 17
0
 public void CanSampleSequence()
 {
     var n = new DiscreteUniform(0, 10);
     var ied = n.Samples();
     ied.Take(5).ToArray();
 }
        /// <summary>
        /// Run example
        /// </summary>
        /// <a href="http://en.wikipedia.org/wiki/Discrete_uniform">DiscreteUniform distribution</a>
        public void Run()
        {
            // 1. Initialize the new instance of the DiscreteUniform distribution class with parameters LowerBound = 2, UpperBound = 10
            var discreteUniform = new DiscreteUniform(2, 10);

            Console.WriteLine(@"1. Initialize the new instance of the DiscreteUniform distribution class with parameters LowerBound = {0}, UpperBound = {1}", discreteUniform.LowerBound, discreteUniform.UpperBound);
            Console.WriteLine();

            // 2. Distributuion properties:
            Console.WriteLine(@"2. {0} distributuion properties:", discreteUniform);

            // Cumulative distribution function
            Console.WriteLine(@"{0} - Сumulative distribution at location '3'", discreteUniform.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));

            // Probability density
            Console.WriteLine(@"{0} - Probability mass at location '3'", discreteUniform.Probability(3).ToString(" #0.00000;-#0.00000"));

            // Log probability density
            Console.WriteLine(@"{0} - Log probability mass at location '3'", discreteUniform.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));

            // Entropy
            Console.WriteLine(@"{0} - Entropy", discreteUniform.Entropy.ToString(" #0.00000;-#0.00000"));

            // Largest element in the domain
            Console.WriteLine(@"{0} - Largest element in the domain", discreteUniform.Maximum.ToString(" #0.00000;-#0.00000"));

            // Smallest element in the domain
            Console.WriteLine(@"{0} - Smallest element in the domain", discreteUniform.Minimum.ToString(" #0.00000;-#0.00000"));

            // Mean
            Console.WriteLine(@"{0} - Mean", discreteUniform.Mean.ToString(" #0.00000;-#0.00000"));

            // Median
            Console.WriteLine(@"{0} - Median", discreteUniform.Median.ToString(" #0.00000;-#0.00000"));

            // Mode
            Console.WriteLine(@"{0} - Mode", discreteUniform.Mode.ToString(" #0.00000;-#0.00000"));

            // Variance
            Console.WriteLine(@"{0} - Variance", discreteUniform.Variance.ToString(" #0.00000;-#0.00000"));

            // Standard deviation
            Console.WriteLine(@"{0} - Standard deviation", discreteUniform.StdDev.ToString(" #0.00000;-#0.00000"));

            // Skewness
            Console.WriteLine(@"{0} - Skewness", discreteUniform.Skewness.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine();

            // 3. Generate 10 samples of the DiscreteUniform distribution
            Console.WriteLine(@"3. Generate 10 samples of the DiscreteUniform distribution");
            for (var i = 0; i < 10; i++)
            {
                Console.Write(discreteUniform.Sample().ToString("N05") + @" ");
            }

            Console.WriteLine();
            Console.WriteLine();

            // 4. Generate 100000 samples of the DiscreteUniform(2, 10) distribution and display histogram
            Console.WriteLine(@"4. Generate 100000 samples of the DiscreteUniform(2, 10) distribution and display histogram");
            var data = new int[100000];

            DiscreteUniform.Samples(data, 2, 10);
            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 5. Generate 100000 samples of the DiscreteUniform(-10, 10) distribution and display histogram
            Console.WriteLine(@"5. Generate 100000 samples of the DiscreteUniform(-10, 10) distribution and display histogram");
            DiscreteUniform.Samples(data, -10, 10);
            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 6. Generate 100000 samples of the DiscreteUniform(0, 40) distribution and display histogram
            Console.WriteLine(@"6. Generate 100000 samples of the DiscreteUniform(0, 40) distribution and display histogram");
            DiscreteUniform.Samples(data, 0, 40);
            ConsoleHelper.DisplayHistogram(data);
        }