public void AddShotNoise() { // this really needs checking. the average noise should = sqrt(signal). that can be tested.. for (var x = 0; x < Image.Width; x++) { for (var y = 0; y < Image.Height; y++) { var value = Image.At <ushort>(y, x); if (value > 0) { var poisson = new Poisson(value); var noised = poisson.Sample(); if (noised > ushort.MaxValue) { noised = ushort.MaxValue; } Image.Set(y, x, (ushort)noised); } } } }
public DistribucionPoisson(double lambda) { this.generador = new GeneradorProvistoPorElLenguaje(); this.lambda = lambda; var entero = new Poisson(lambda); num = entero.Sample(); }
private void generateAttributes(Character character) { foreach (Attribute attribute in attributes.Select(x => x.Value)) { int value = Poisson.Sample(StoreConfig.MODIFIER_LAMBDA * 2.0d); character.setAttribute(attribute, value); } }
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); }
/// <summary> /// Determine the number of arrivals in time window (15 minutes) and their arrival times /// </summary> /// <param name="mean">Average number of arrivals</param> /// <returns></returns> public static int[] arrivingPassengers(double mean) { var arrivals = Poisson.Sample(mean); var times = new int[arrivals]; for (int i = 0; i < arrivals; i++) { times[i] = DiscreteUniform.Sample(0, 899); } return(times); }
public int SamplePoisson(double lambda) { if (lambda <= 0d) { throw new ArgumentException("Lambda parameter for Poisson distribution must be > 0"); } var distribution = new Poisson(lambda, RandomSource); return(distribution.Sample()); }
/// <summary> /// Randomly create true theta and phi arrays /// </summary> /// <param name="numVocab">Vocabulary size</param> /// <param name="numTopics">Number of topics</param> /// <param name="numDocs">Number of documents</param> /// <param name="averageDocLength">Average document length</param> /// <param name="averageWordsPerTopic">Average number of words per topic</param> /// <param name="trueTheta">Theta array (output)</param> /// <param name="truePhi">Phi array (output)</param> public static void CreateTrueThetaAndPhi( int numVocab, int numTopics, int numDocs, int averageDocLength, int averageWordsPerTopic, out Dirichlet[] trueTheta, out Dirichlet[] truePhi) { truePhi = new Dirichlet[numTopics]; for (int i = 0; i < numTopics; i++) { truePhi[i] = Dirichlet.Uniform(numVocab); truePhi[i].PseudoCount.SetAllElementsTo(0.0); // Draw the number of unique words in the topic. int numUniqueWordsPerTopic = Poisson.Sample((double)averageWordsPerTopic); if (numUniqueWordsPerTopic >= numVocab) { numUniqueWordsPerTopic = numVocab; } if (numUniqueWordsPerTopic < 1) { numUniqueWordsPerTopic = 1; } double expectedRepeatOfWordInTopic = ((double)numDocs) * averageDocLength / numUniqueWordsPerTopic; int[] shuffledWordIndices = Rand.Perm(numVocab); for (int j = 0; j < numUniqueWordsPerTopic; j++) { int wordIndex = shuffledWordIndices[j]; // Draw the count for that word int cnt = Poisson.Sample(expectedRepeatOfWordInTopic); truePhi[i].PseudoCount[wordIndex] = cnt + 1.0; } } trueTheta = new Dirichlet[numDocs]; for (int i = 0; i < numDocs; i++) { trueTheta[i] = Dirichlet.Uniform(numTopics); trueTheta[i].PseudoCount.SetAllElementsTo(0.0); // Draw the number of unique topics in the doc. int numUniqueTopicsPerDoc = Math.Min(1 + Poisson.Sample(1.0), numTopics); double expectedRepeatOfTopicInDoc = averageDocLength / numUniqueTopicsPerDoc; int[] shuffledTopicIndices = Rand.Perm(numTopics); for (int j = 0; j < numUniqueTopicsPerDoc; j++) { int topicIndex = shuffledTopicIndices[j]; // Draw the count for that topic int cnt = Poisson.Sample(expectedRepeatOfTopicInDoc); trueTheta[i].PseudoCount[topicIndex] = cnt + 1.0; } } }
private void generateAttributes(Equipment equipment) { foreach (KeyValuePair <int, Attribute> entry in this.attributes) { bool success = Bernoulli.Sample(StoreConfig.ATTRIBUTE_PROB) == 1; if (success) { int modifier = Poisson.Sample(StoreConfig.MODIFIER_LAMBDA) - 1; // Clamp modifier in [1,inf) equipment.setAttributeBonus(entry.Value, modifier > 0 ? modifier : 1); } } }
//Generate Processes private void ProcessGenerator() { Normal ATNormal = new Normal(ATmean, ATstdDev); Normal BTNormal = new Normal(BTmean, BTstdDev); Poisson PriPoisson = new Poisson(PriGamma); using (StreamWriter sw = new StreamWriter("Processes.txt")) { sw.WriteLine(N); double randomValue; for (int i = 1; i <= N; ++i) { string line = ""; line += i.ToString(); line += " "; randomValue = ATNormal.Sample(); if (randomValue < 0) // no negative AT { --i; continue; } line += randomValue.ToString(); line += " "; randomValue = BTNormal.Sample(); if (randomValue <= 0) // no negative or zero BT { --i; continue; } line += randomValue.ToString(); line += " "; randomValue = PriPoisson.Sample(); if (randomValue < 0) // no negative priority { --i; continue; } line += randomValue.ToString(); sw.WriteLine(line); } } MessageBox.Show("Processes Generated Successfully", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); }
public void generateEquipment(double lambda) { int count = Poisson.Sample(lambda); int countClamped = count > 1 ? count : 1; Equipment[] newEquipment = Enumerable .Range(1, countClamped) .Select(i => this.generateEquipment()) .ToArray(); foreach (Equipment eq in newEquipment) { this.equipment.Add(eq.id, eq); } }
public void TestMeanAndVariacneConsistency() { const int numSamples = 100000; double mean, stdev; RunningStat rs = new RunningStat(); Random defaultrs = new Random(); Poisson poisson = new Poisson(); rs.Clear(); mean = 2000; stdev = Math.Sqrt(2000); poisson.Lambda = 2000; for (int i = 0; i < numSamples; ++i) { rs.Push(poisson.Sample(defaultrs)); } PrintResult.CompareMeanAndVariance("Poisson Discrete", mean, stdev * stdev, rs.Mean(), rs.Variance()); }
/// Generate LDA data - returns an array of dictionaries mapping unique word index /// to word count per document. /// <param name="trueTheta">Known Theta</param> /// <param name="truePhi">Known Phi</param> /// <param name="averageNumWords">Average number of words to sample per doc</param> /// <returns></returns> public static Dictionary <int, int>[] GenerateLDAData(Dirichlet[] trueTheta, Dirichlet[] truePhi, int averageNumWords) { int numVocab = truePhi[0].Dimension; int numTopics = truePhi.Length; int numDocs = trueTheta.Length; // Sample from the model Vector[] topicDist = new Vector[numDocs]; Vector[] wordDist = new Vector[numTopics]; for (int i = 0; i < numDocs; i++) { topicDist[i] = trueTheta[i].Sample(); } for (int i = 0; i < numTopics; i++) { wordDist[i] = truePhi[i].Sample(); } var wordCounts = new Dictionary <int, int> [numDocs]; for (int i = 0; i < numDocs; i++) { int LengthOfDoc = Poisson.Sample((double)averageNumWords); var counts = new Dictionary <int, int>(); for (int j = 0; j < LengthOfDoc; j++) { int topic = Discrete.Sample(topicDist[i]); int w = Discrete.Sample(wordDist[topic]); if (!counts.ContainsKey(w)) { counts.Add(w, 1); } else { counts[w] = counts[w] + 1; } } wordCounts[i] = counts; } return(wordCounts); }
private IDistribution <Vector[]> GetInitialisation(double initMaxPseudoCount, double initWordsPerTopic, Sparsity sparsity, double beta) { Dirichlet[] initPhi = new Dirichlet[TotalTopics.ObservedValue]; Random r = new Random(12347); for (int i = 0; i < TotalTopics.ObservedValue; i++) { Vector v = Vector.Constant(TotalWords.ObservedValue, beta, sparsity); int[] perm = Rand.Perm(TotalWords.ObservedValue); int numWords = Poisson.Sample(initWordsPerTopic); for (int j = 0; j < numWords; j++) { v[perm[j]] += initMaxPseudoCount * r.NextDouble(); } initPhi[i] = new Dirichlet(v); } return(Distribution <Vector> .Array(initPhi)); }
//Calculate the amount of passengers entering the tram at a given station, given the station, last tram arrival at that station of a previous tram and the current time static public Queue <TimeSpan> getPassengersIn(Station station, Direction direction, TimeSpan lastArrival, TimeSpan now) { Queue <TimeSpan> passengers = new Queue <TimeSpan>(); if ((station.stationNumber == 1 && direction == Direction.UtrechtCentraal) || (station.stationNumber == 9 && direction == Direction.Uithof)) { return(passengers); } //empty queue } if (lastArrival.Hours < 6) { lastArrival = TimeSpan.FromHours(6); } int firstInterval = (int)(lastArrival.TotalMinutes - 360) / 15; int lastInterval = (int)(now.TotalMinutes - 360) / 15; double rate; for (int n = firstInterval; n <= lastInterval; n++) { if (direction == Direction.Uithof) { rate = double.Parse(enteringRatesA[n + 1][station.stationNumber - 1], System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo); } else { rate = double.Parse(enteringRatesB[n + 1][9 - station.stationNumber], System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo); } double minutesInInterval = Math.Min(now.TotalMinutes, (n + 1) * 15 + 360) - (Math.Max(lastArrival.TotalMinutes, (n * 15) + 360)); //Get the amount of passengers using the rate and time in this current interval if (rate > 0 && minutesInInterval > 0) { int pii = Poisson.Sample(rate * minutesInInterval); for (int i = 0; i < pii; i++) { passengers.Enqueue(TimeSpan.FromMinutes( (Math.Max(lastArrival.TotalMinutes, (n * 15) + 360)) + minutesInInterval / 2)); } } } return(passengers); }
public static int[] SampleData(int N, double pi, double lambda) { int[] data = new int[N]; Bernoulli coin = new Bernoulli(pi); Poisson poisson = new Poisson(lambda); for (int i = 0; i < N; i++) { bool coin_value = coin.Sample(); if (coin_value) { data[i] = 0; } else { data[i] = poisson.Sample(); } } return(data); }
public void Generate() { String[] line = new String[6]; StreamReader sr = new StreamReader(@"C:\\Users\\egypt2\\source\\repos\\WindowsFormsApp2\\input.txt"); line[0] = sr.ReadLine(); int i = 1; while (line != null) { if (i == 4) { break; } line[i] = sr.ReadLine(); i++; } string[] ArrivalParams = line[1].Split(null); string[] BurstParams = line[2].Split(null); sr.Close(); var poisson = new Poisson(Convert.ToDouble(line[3])); var arrivalTimeNormal = new Normal(Convert.ToDouble(ArrivalParams[0]), Convert.ToDouble(ArrivalParams[1])); var burstTimeNormal = new Normal(Convert.ToDouble(BurstParams[0]), Convert.ToDouble(BurstParams[1])); string[] text = new string[Convert.ToInt32(line[0]) + 1]; text[0] = Convert.ToString(line[0]); for (i = 1; i <= Convert.ToInt32(line[0]); i++) { var arrivalT = Math.Abs(arrivalTimeNormal.Sample()); var burstT = Math.Abs(burstTimeNormal.Sample()); var prior = poisson.Sample(); text[i] = Convert.ToString(i) + " " + Convert.ToString(arrivalT) + " " + Convert.ToString(burstT) + " " + Convert.ToString(prior); } System.IO.File.WriteAllLines(@"C:\\Users\\egypt2\\source\\repos\\WindowsFormsApp2\\output.txt", text); }
/// <summary> /// Run example /// </summary> /// <a href="http://en.wikipedia.org/wiki/Poisson_distribution">Poisson distribution</a> public void Run() { // 1. Initialize the new instance of the Poisson distribution class with parameter Lambda = 1 var poisson = new Poisson(1); Console.WriteLine(@"1. Initialize the new instance of the Poisson distribution class with parameter Lambda = {0}", poisson.Lambda); Console.WriteLine(); // 2. Distributuion properties: Console.WriteLine(@"2. {0} distributuion properties:", poisson); // Cumulative distribution function Console.WriteLine(@"{0} - Сumulative distribution at location '3'", poisson.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density Console.WriteLine(@"{0} - Probability mass at location '3'", poisson.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density Console.WriteLine(@"{0} - Log probability mass at location '3'", poisson.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy Console.WriteLine(@"{0} - Entropy", poisson.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain Console.WriteLine(@"{0} - Largest element in the domain", poisson.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain Console.WriteLine(@"{0} - Smallest element in the domain", poisson.Minimum.ToString(" #0.00000;-#0.00000")); // Mean Console.WriteLine(@"{0} - Mean", poisson.Mean.ToString(" #0.00000;-#0.00000")); // Median Console.WriteLine(@"{0} - Median", poisson.Median.ToString(" #0.00000;-#0.00000")); // Mode Console.WriteLine(@"{0} - Mode", poisson.Mode.ToString(" #0.00000;-#0.00000")); // Variance Console.WriteLine(@"{0} - Variance", poisson.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation Console.WriteLine(@"{0} - Standard deviation", poisson.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness Console.WriteLine(@"{0} - Skewness", poisson.Skewness.ToString(" #0.00000;-#0.00000")); Console.WriteLine(); // 3. Generate 10 samples of the Poisson distribution Console.WriteLine(@"3. Generate 10 samples of the Poisson distribution"); for (var i = 0; i < 10; i++) { Console.Write(poisson.Sample().ToString("N05") + @" "); } Console.WriteLine(); Console.WriteLine(); // 4. Generate 100000 samples of the Poisson(1) distribution and display histogram Console.WriteLine(@"4. Generate 100000 samples of the Poisson(1) distribution and display histogram"); var data = new double[100000]; for (var i = 0; i < data.Length; i++) { data[i] = poisson.Sample(); } ConsoleHelper.DisplayHistogram(data); Console.WriteLine(); // 5. Generate 100000 samples of the Poisson(4) distribution and display histogram Console.WriteLine(@"5. Generate 100000 samples of the Poisson(4) distribution and display histogram"); poisson.Lambda = 4; for (var i = 0; i < data.Length; i++) { data[i] = poisson.Sample(); } ConsoleHelper.DisplayHistogram(data); Console.WriteLine(); // 6. Generate 100000 samples of the Poisson(10) distribution and display histogram Console.WriteLine(@"6. Generate 100000 samples of the Poisson(10) distribution and display histogram"); poisson.Lambda = 10; for (var i = 0; i < data.Length; i++) { data[i] = poisson.Sample(); } ConsoleHelper.DisplayHistogram(data); }
public override void ExecuteExample() { // <a href="http://en.wikipedia.org/wiki/Binomial_distribution">Binomial distribution</a> MathDisplay.WriteLine("<b>Binomial distribution</b>"); // 1. Initialize the new instance of the Binomial distribution class with parameters P = 0.2, N = 20 var binomial = new Binomial(0.2, 20); MathDisplay.WriteLine(@"1. Initialize the new instance of the Binomial distribution class with parameters P = {0}, N = {1}", binomial.P, binomial.N); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", binomial); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", binomial.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", binomial.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", binomial.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", binomial.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", binomial.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", binomial.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", binomial.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", binomial.Median.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", binomial.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", binomial.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", binomial.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", binomial.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Binomial distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Binomial distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(binomial.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Bernoulli_distribution">Bernoulli distribution</a> MathDisplay.WriteLine("<b>Bernoulli distribution</b>"); // 1. Initialize the new instance of the Bernoulli distribution class with parameter P = 0.2 var bernoulli = new Bernoulli(0.2); MathDisplay.WriteLine(@"1. Initialize the new instance of the Bernoulli distribution class with parameter P = {0}", bernoulli.P); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", bernoulli); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", bernoulli.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", bernoulli.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", bernoulli.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", bernoulli.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", bernoulli.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", bernoulli.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", bernoulli.Mean.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", bernoulli.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", bernoulli.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", bernoulli.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", bernoulli.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Bernoulli distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Bernoulli distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(bernoulli.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Categorical_distribution">Categorical distribution</a> MathDisplay.WriteLine("<b>Categorical distribution</b>"); // 1. Initialize the new instance of the Categorical distribution class with parameters P = (0.1, 0.2, 0.25, 0.45) var binomialC = new Categorical(new[] { 0.1, 0.2, 0.25, 0.45 }); MathDisplay.WriteLine(@"1. Initialize the new instance of the Categorical distribution class with parameters P = (0.1, 0.2, 0.25, 0.45)"); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", binomialC); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", binomialC.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", binomialC.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", binomialC.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", binomialC.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", binomialC.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", binomialC.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", binomialC.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", binomialC.Median.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", binomialC.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", binomialC.StdDev.ToString(" #0.00000;-#0.00000")); // 3. Generate 10 samples of the Categorical distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Categorical distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(binomialC.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Conway%E2%80%93Maxwell%E2%80%93Poisson_distribution">ConwayMaxwellPoisson distribution</a> MathDisplay.WriteLine("<b>Conway Maxwell Poisson distribution</b>"); // 1. Initialize the new instance of the ConwayMaxwellPoisson distribution class with parameters Lambda = 2, Nu = 1 var conwayMaxwellPoisson = new ConwayMaxwellPoisson(2, 1); MathDisplay.WriteLine(@"1. Initialize the new instance of the ConwayMaxwellPoisson distribution class with parameters Lambda = {0}, Nu = {1}", conwayMaxwellPoisson.Lambda, conwayMaxwellPoisson.Nu); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", conwayMaxwellPoisson); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", conwayMaxwellPoisson.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", conwayMaxwellPoisson.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", conwayMaxwellPoisson.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", conwayMaxwellPoisson.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", conwayMaxwellPoisson.Mean.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", conwayMaxwellPoisson.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", conwayMaxwellPoisson.StdDev.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the ConwayMaxwellPoisson distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the ConwayMaxwellPoisson distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(conwayMaxwellPoisson.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Discrete_uniform">DiscreteUniform distribution</a> MathDisplay.WriteLine("<b>Discrete Uniform distribution</b>"); // 1. Initialize the new instance of the DiscreteUniform distribution class with parameters LowerBound = 2, UpperBound = 10 var discreteUniform = new DiscreteUniform(2, 10); MathDisplay.WriteLine(@"1. Initialize the new instance of the DiscreteUniform distribution class with parameters LowerBound = {0}, UpperBound = {1}", discreteUniform.LowerBound, discreteUniform.UpperBound); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", discreteUniform); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", discreteUniform.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", discreteUniform.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", discreteUniform.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", discreteUniform.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", discreteUniform.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", discreteUniform.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", discreteUniform.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", discreteUniform.Median.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", discreteUniform.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", discreteUniform.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", discreteUniform.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", discreteUniform.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the DiscreteUniform distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the DiscreteUniform distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(discreteUniform.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Geometric_distribution">Geometric distribution</a> MathDisplay.WriteLine("<b>Geometric distribution</b>"); // 1. Initialize the new instance of the Geometric distribution class with parameter P = 0.2 var geometric = new Geometric(0.2); MathDisplay.WriteLine(@"1. Initialize the new instance of the Geometric distribution class with parameter P = {0}", geometric.P); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", geometric); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", geometric.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", geometric.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", geometric.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", geometric.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", geometric.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", geometric.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", geometric.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", geometric.Median.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", geometric.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", geometric.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", geometric.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", geometric.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Geometric distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Geometric distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(geometric.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Hypergeometric_distribution">Hypergeometric distribution</a> MathDisplay.WriteLine("<b>Hypergeometric distribution</b>"); // 1. Initialize the new instance of the Hypergeometric distribution class with parameters PopulationSize = 10, M = 2, N = 8 var hypergeometric = new Hypergeometric(30, 15, 10); MathDisplay.WriteLine(@"1. Initialize the new instance of the Hypergeometric distribution class with parameters Population = {0}, Success = {1}, Draws = {2}", hypergeometric.Population, hypergeometric.Success, hypergeometric.Draws); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", hypergeometric); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", hypergeometric.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", hypergeometric.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", hypergeometric.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", hypergeometric.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", hypergeometric.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", hypergeometric.Mean.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", hypergeometric.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", hypergeometric.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", hypergeometric.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", hypergeometric.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Hypergeometric distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Hypergeometric distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(hypergeometric.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Negative_binomial">NegativeBinomial distribution</a> MathDisplay.WriteLine("<b>Negative Binomial distribution</b>"); // 1. Initialize the new instance of the NegativeBinomial distribution class with parameters P = 0.2, R = 20 var negativeBinomial = new NegativeBinomial(20, 0.2); MathDisplay.WriteLine(@"1. Initialize the new instance of the NegativeBinomial distribution class with parameters P = {0}, N = {1}", negativeBinomial.P, negativeBinomial.R); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", negativeBinomial); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", negativeBinomial.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", negativeBinomial.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", negativeBinomial.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", negativeBinomial.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", negativeBinomial.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", negativeBinomial.Mean.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", negativeBinomial.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", negativeBinomial.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", negativeBinomial.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", negativeBinomial.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the NegativeBinomial distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the NegativeBinomial distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(negativeBinomial.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Poisson_distribution">Poisson distribution</a> MathDisplay.WriteLine("<b>Poisson distribution</b>"); // 1. Initialize the new instance of the Poisson distribution class with parameter Lambda = 1 var poisson = new Poisson(1); MathDisplay.WriteLine(@"1. Initialize the new instance of the Poisson distribution class with parameter Lambda = {0}", poisson.Lambda); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", poisson); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", poisson.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", poisson.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", poisson.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", poisson.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", poisson.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", poisson.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", poisson.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", poisson.Median.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", poisson.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", poisson.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", poisson.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", poisson.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Poisson distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Poisson distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(poisson.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Zipf_distribution">Zipf distribution</a> MathDisplay.WriteLine("<b>Zipf distribution</b>"); // 1. Initialize the new instance of the Zipf distribution class with parameters S = 5, N = 10 var zipf = new Zipf(5, 10); MathDisplay.WriteLine(@"1. Initialize the new instance of the Zipf distribution class with parameters S = {0}, N = {1}", zipf.S, zipf.N); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", zipf); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", zipf.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", zipf.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", zipf.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", zipf.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", zipf.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", zipf.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", zipf.Mean.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", zipf.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", zipf.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", zipf.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", zipf.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Zipf distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Zipf distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(zipf.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); }
public void CanSample() { var d = new Poisson(0.3); d.Sample(); }
public int GetEmbarkingPassengers(Tram tram, int time) { // Find the index in the array of lambdas for the poisson process. var currDT = Utils.SecondsToDateTime(time); int index = FindAppropriateInterval(currDT); var lambda = 0.0; var direction = 1; // CS -> P+R Direction 1 if (Id == 0 && tram.PreviousTerminal.Id == 8) { // If for any reason we are delayed, we have to go back to the data that we know. if (index > RouteCStoPR.GetLength(0) - 1) { index = RouteCStoPR.GetLength(0) - 1; } lambda = RouteCStoPR[index, Id]; // Special case we are Centraal (id = 0) but we came from P+R } else if (Id < 8) { direction = 1; // If for any reason we are delayed, we have to go back to the data that we know. if (index > RouteCStoPR.GetLength(0) - 1) { index = RouteCStoPR.GetLength(0) - 1; } lambda = RouteCStoPR[index, Id]; } else if (Id >= 8) { direction = 0; // If for any reason we are delayed, we have to go back to the data that we know. if (index > RoutePRtoCS.GetLength(0) - 1) { index = RoutePRtoCS.GetLength(0) - 1; } lambda = RoutePRtoCS[index, Id - 8]; } else // Depot { return(0); } if (lambda == 0.0) { lambda = 0.01; } // Generate the number of new arrival events *n* that will occur. var pd = new Poisson(lambda); var n = pd.Sample(); var my_index = GetIndex(time); // Deduct from the expected people the n we computed. var shouldEnter = 0; if (direction == 0) { shouldEnter = (int)ComingDistrubutions[my_index].PassIn; if (shouldEnter - n >= 0) { ComingDistrubutions[my_index].PassIn -= n; } else { // in direction zero take from this collection n = (int)ComingDistrubutions[my_index].PassIn; ComingDistrubutions[my_index].PassIn = 0; } } else { shouldEnter = (int)GoingDistrubutions[my_index].PassIn; if (shouldEnter - n >= 0) { GoingDistrubutions[my_index].PassIn -= n; } else { // in direction 1 take from this collection n = (int)GoingDistrubutions[my_index].PassIn; GoingDistrubutions[my_index].PassIn = 0; } } // Initialize an array to store the arrival times t_i, i = {1,2,..., n}. var arrivals = new int[n]; // We will get the arrival times from the uniform distribution. U[0,T] var last = 0; if (TimeOfLastTram.HasValue) { last = TimeOfLastTram.Value; } var ud = new DiscreteUniform(last, time); for (int i = 0; i < n; ++i) { arrivals[i] = ud.Sample(); } // Compute the total waiting time for the new passengers given the array arrivals. we also need to keep track of the people already waiting. var total_waiting_time = 0; for (int i = 0; i < n; ++i) { total_waiting_time += time - arrivals[i]; } TotalWaitingTime += total_waiting_time; return(n); }
static void Main(string[] args) { Poisson order_num = new Poisson(9.375); Bernoulli corn_bread = new Bernoulli(0.56667); Bernoulli orange_cake = new Bernoulli(0.26667); Bernoulli choco_cake = new Bernoulli(0.46667); Bernoulli three_milks = new Bernoulli(0.43333); Bernoulli turkey = new Bernoulli(0.73333); Bernoulli pork_leg = new Bernoulli(0.8); int corn_total = 0; int orange_total = 0; int choco_total = 0; int milk_total = 0; int turkey_total = 0; int pork_total = 0; List <Order> orders = new List <Order>(); Console.WriteLine("Order List:\n-------------------------"); for (int i = 0; i <= order_num.Sample(); i++) { Console.WriteLine("Order #" + (i + 1) + ":"); orders.Add(new Order(new List <Food>())); if (Convert.ToBoolean(corn_bread.Sample())) { Console.WriteLine("* Corn Bread"); orders[i].Add_item(new Food("Corn Bread", 50, "salt", 1)); corn_total++; } if (Convert.ToBoolean(orange_cake.Sample())) { Console.WriteLine("* Orange Cake"); orders[i].Add_item(new Food("Orange Cake", 60, "sweet", 1)); orange_total++; } if (Convert.ToBoolean(choco_cake.Sample())) { Console.WriteLine("* Chocolate Cake"); orders[i].Add_item(new Food("Chocolate Cake", 60, "sweet", 1)); choco_total++; } if (Convert.ToBoolean(three_milks.Sample())) { Console.WriteLine("* Tres Leches"); orders[i].Add_item(new Food("Tres Leches", 40, "sweet", 1)); milk_total++; } if (Convert.ToBoolean(turkey.Sample())) { Console.WriteLine("* Turkey"); orders[i].Add_item(new Food("Turkey", 270, "salt", 2)); turkey_total++; } if (Convert.ToBoolean(pork_leg.Sample())) { Console.WriteLine("* Pork Leg"); orders[i].Add_item(new Food("Pork Leg", 270, "salt", 2)); pork_total++; } Console.WriteLine(); } Console.WriteLine("\nTotals:\n-------------------------"); Console.WriteLine("* Corn Bread: " + corn_total); Console.WriteLine("* Orange Cake: " + orange_total); Console.WriteLine("* Chocolate Cake: " + choco_total); Console.WriteLine("* Tres Leches: " + milk_total); Console.WriteLine("* Turkey: " + turkey_total); Console.WriteLine("* Pork Leg: " + pork_total); Console.WriteLine("\n\n3-slot Oven Test:\n-------------------------"); //3-spot oven test Food slot_1 = new Food("", 0, "", 1); Food slot_2 = new Food("", 0, "", 1); Food slot_3 = new Food("", 0, "", 1); double option_a_time = 0; int next_step = 0; while (turkey_total > 0 || pork_total > 0 || corn_total > 0 || orange_total > 0 || choco_total > 0 || milk_total > 0 || next_step != 0) { if (slot_1.Cooktime_left == 0 && slot_1.Type != "") { Console.WriteLine(slot_1.Name + " comes out of Slot 1"); slot_1 = new Food("", 0, "", 1); } if (slot_2.Cooktime_left == 0 && slot_2.Type != "") { Console.WriteLine(slot_2.Name + " comes out of Slot 2"); slot_2 = new Food("", 0, "", 1); } if (slot_3.Cooktime_left == 0 && slot_3.Type != "") { Console.WriteLine(slot_3.Name + " comes out of Slot 3"); slot_3 = new Food("", 0, "", 1); } if (turkey_total > 0) { if (turkey_total > 0 && slot_1.Type == "" && slot_2.Type == "" && slot_3.Type != "sweet") { turkey_total--; slot_1 = new Food("Turkey A", 270, "salt", 2); Console.WriteLine(slot_1.Name + " goes into Slot 1. " + turkey_total + " turkeys still left to cook..."); slot_2 = new Food("Turkey B", 270, "salt", 2); Console.WriteLine(slot_2.Name + " goes into Slot 2. " + turkey_total + " turkeys still left to cook..."); } if (turkey_total > 0 && slot_1.Type != "sweet" && slot_2.Type == "" && slot_3.Type == "") { turkey_total--; slot_2 = new Food("Turkey A", 270, "salt", 2); Console.WriteLine(slot_2.Name + " goes into Slot 2. " + turkey_total + " turkeys still left to cook..."); slot_3 = new Food("Turkey B", 270, "salt", 2); Console.WriteLine(slot_3.Name + " goes into Slot 3. " + turkey_total + " turkeys still left to cook..."); } if (turkey_total > 0 && slot_1.Type == "" && slot_2.Type == "salt" && slot_3.Type == "") { slot_3 = slot_2; slot_2 = new Food("", 0, "", 1); Console.WriteLine(slot_3.Name + " was swapped over from slot 2 to slot 3"); turkey_total--; slot_1 = new Food("Turkey A", 270, "salt", 2); Console.WriteLine(slot_1.Name + " goes into Slot 1. " + turkey_total + " turkeys still left to cook..."); slot_2 = new Food("Turkey B", 270, "salt", 2); Console.WriteLine(slot_1.Name + " goes into Slot 2. " + turkey_total + " turkeys still left to cook..."); } } if (pork_total > 0) { if (pork_total > 0 && slot_1.Type == "" && slot_2.Type == "" && slot_3.Type != "sweet") { pork_total--; slot_1 = new Food("Pork Leg A", 270, "salt", 2); Console.WriteLine(slot_1.Name + " goes into Slot 1. " + pork_total + " pork legs still left to cook..."); slot_2 = new Food("Pork Leg B", 270, "salt", 2); Console.WriteLine(slot_2.Name + " goes into Slot 2. " + pork_total + " pork legs still left to cook..."); } if (pork_total > 0 && slot_1.Type != "sweet" && slot_2.Type == "" && slot_3.Type == "") { pork_total--; slot_2 = new Food("Pork Leg A", 270, "salt", 2); Console.WriteLine(slot_2.Name + " goes into Slot 2. " + pork_total + " pork legs still left to cook..."); slot_3 = new Food("Pork Leg B", 270, "salt", 2); Console.WriteLine(slot_3.Name + " goes into Slot 3. " + pork_total + " pork legs still left to cook..."); } if (pork_total > 0 && slot_1.Type == "" && slot_2.Type == "salt" && slot_3.Type == "") { slot_3 = slot_2; slot_2 = new Food("", 0, "", 1); Console.WriteLine(slot_3.Name + " was swapped over from slot 2 to slot 3"); pork_total--; slot_1 = new Food("Pork Leg A", 270, "salt", 2); Console.WriteLine(slot_1.Name + " goes into Slot 1. " + pork_total + " pork legs still left to cook..."); slot_2 = new Food("Pork Leg B", 270, "salt", 2); Console.WriteLine(slot_1.Name + " goes into Slot 2. " + pork_total + " pork legs still left to cook..."); } } if (corn_total > 0) { if (corn_total > 0 && slot_1.Type == "" && slot_2.Type != "sweet" && slot_3.Type != "sweet") { corn_total--; slot_1 = new Food("Corn Bread", 50, "salt", 1); Console.WriteLine("Corn Bread goes into Slot 1. " + corn_total + " corn breads still left to cook..."); } if (corn_total > 0 && slot_1.Type != "sweet" && slot_2.Type == "" && slot_3.Type != "sweet") { corn_total--; slot_2 = new Food("Corn Bread", 50, "salt", 1); Console.WriteLine("Corn Bread goes into Slot 2. " + corn_total + " corn breads still left to cook..."); } if (corn_total > 0 && slot_1.Type != "sweet" && slot_2.Type != "sweet" && slot_3.Type == "") { corn_total--; slot_3 = new Food("Corn Bread", 50, "salt", 1); Console.WriteLine("Corn Bread goes into Slot 3. " + corn_total + " corn breads still left to cook..."); } } if (orange_total > 0) { if (orange_total > 0 && slot_1.Type == "" && slot_2.Type != "salt" && slot_3.Type != "salt") { orange_total--; slot_1 = new Food("Orange Cake", 60, "sweet", 1); Console.WriteLine("Orange Cake goes into Slot 1. " + orange_total + " orange cakes still left to cook..."); } if (orange_total > 0 && slot_1.Type != "salt" && slot_2.Type == "" && slot_3.Type != "salt") { orange_total--; slot_2 = new Food("Orange Cake", 60, "sweet", 1); Console.WriteLine("Orange Cake goes into Slot 2. " + orange_total + " orange cakes still left to cook..."); } if (orange_total > 0 && slot_1.Type != "salt" && slot_2.Type != "salt" && slot_3.Type == "") { orange_total--; slot_3 = new Food("Orange Cake", 60, "sweet", 1); Console.WriteLine("Orange Cake goes into Slot 3. " + orange_total + " orange cakes still left to cook..."); } } if (choco_total > 0) { if (choco_total > 0 && slot_1.Type == "" && slot_2.Type != "salt" && slot_3.Type != "salt") { choco_total--; slot_1 = new Food("Chocolate Cake", 60, "sweet", 1); Console.WriteLine("Chocolate Cake goes into Slot 1. " + choco_total + " chocolate cakes still left to cook..."); } if (choco_total > 0 && slot_1.Type != "salt" && slot_2.Type == "" && slot_3.Type != "salt") { choco_total--; slot_2 = new Food("Chocolate Cake", 60, "sweet", 1); Console.WriteLine("Chocolate Cake goes into Slot 2. " + choco_total + " chocolate cakes still left to cook..."); } if (choco_total > 0 && slot_1.Type != "salt" && slot_2.Type != "salt" && slot_3.Type == "") { choco_total--; slot_3 = new Food("Chocolate Cake", 60, "sweet", 1); Console.WriteLine("Chocolate Cake goes into Slot 3. " + choco_total + " chocolate cakes still left to cook..."); } } if (milk_total > 0) { if (milk_total > 0 && slot_1.Type == "" && slot_2.Type != "salt" && slot_3.Type != "salt") { milk_total--; slot_1 = new Food("Tres Leches", 40, "sweet", 1); Console.WriteLine("Tres Leches goes into Slot 1. " + milk_total + " tres leches still left to cook..."); } if (milk_total > 0 && slot_1.Type != "salt" && slot_2.Type == "" && slot_3.Type != "salt") { milk_total--; slot_2 = new Food("Tres Leches", 40, "sweet", 1); Console.WriteLine("Tres Leches goes into Slot 2. " + milk_total + " tres leches still left to cook..."); } if (milk_total > 0 && slot_1.Type != "salt" && slot_2.Type != "salt" && slot_3.Type == "") { milk_total--; slot_3 = new Food("Tres Leches", 40, "sweet", 1); Console.WriteLine("Tres Leches goes into Slot 3. " + milk_total + " tres leches still left to cook..."); } } next_step = Convert.ToInt16(slot_1.Cooktime_left); if (next_step > slot_2.Cooktime_left && slot_2.Cooktime_left != 0) { next_step = Convert.ToInt16(slot_2.Cooktime_left); } if (next_step > slot_3.Cooktime_left && slot_3.Cooktime_left != 0) { next_step = Convert.ToInt16(slot_3.Cooktime_left); } if (slot_1.Cooktime_left > 0) { slot_1.Cooktime_left = slot_1.Cooktime_left - next_step; } if (slot_2.Cooktime_left > 0) { slot_2.Cooktime_left = slot_2.Cooktime_left - next_step; } if (slot_3.Cooktime_left > 0) { slot_3.Cooktime_left = slot_3.Cooktime_left - next_step; } option_a_time = option_a_time + next_step; Console.WriteLine(next_step + " minutes pass..."); } Console.WriteLine("Total Cook-time using 3-slot Oven: " + option_a_time + " Minutes (" + (option_a_time / 60) + " Hours or " + (option_a_time / 60 / 24) + " Days)"); for (int i = 0; i < orders.Count; i++) { for (int j = 0; j < orders[i].Contents.Count; j++) { switch (orders[i].Contents[j].Name) { case "Turkey": turkey_total++; break; case "Pork Leg": pork_total++; break; case "Corn Bread": corn_total++; break; case "Orange Cake": orange_total++; break; case "Chocolate Cake": choco_total++; break; case "Tres Leches": milk_total++; break; default: break; } } } //Secondhand Oven Test Console.WriteLine("\n\nSecondhand Oven Test:\n-------------------------"); Food slot_4 = new Food("", 0, "", 1); double option_b_time = 0; while (turkey_total > 0 || pork_total > 0 || corn_total > 0 || orange_total > 0 || choco_total > 0 || milk_total > 0 || next_step != 0) { if (slot_1.Cooktime_left == 0 && slot_1.Type != "") { Console.WriteLine(slot_1.Name + " comes out of Regular Oven Slot 1"); slot_1 = new Food("", 0, "", 1); } if (slot_2.Cooktime_left == 0 && slot_2.Type != "") { Console.WriteLine(slot_2.Name + " comes out of Regular Oven Slot 2"); slot_2 = new Food("", 0, "", 1); } if (slot_3.Cooktime_left == 0 && slot_3.Type != "") { Console.WriteLine(slot_3.Name + " comes out of Secondhand Oven Slot 1"); slot_3 = new Food("", 0, "", 1); } if (slot_4.Cooktime_left == 0 && slot_4.Type != "") { Console.WriteLine(slot_4.Name + " comes out of Secondhand Oven Slot 2"); slot_4 = new Food("", 0, "", 1); } if (turkey_total > 0) { if (turkey_total > 0 && ((slot_1.Type == "" && slot_2.Type != "sweet") || (slot_2.Type == "" && slot_1.Type != "sweet"))) { turkey_total--; slot_1 = new Food("Turkey A", 270, "salt", 2); Console.WriteLine(slot_1.Name + " goes into Regular Oven Slot 1. " + turkey_total + " turkeys still left to cook..."); slot_2 = new Food("Turkey B", 270, "salt", 2); Console.WriteLine(slot_2.Name + " goes into Regular Oven Slot 2. " + turkey_total + " turkeys still left to cook..."); } if (turkey_total > 0 && ((slot_3.Type != "sweet" && slot_4.Type == "") || (slot_4.Type != "sweet" && slot_3.Type == ""))) { turkey_total--; slot_3 = new Food("Turkey A", 290, "salt", 2); Console.WriteLine(slot_3.Name + " goes into Secondhand Oven Slot 1. " + turkey_total + " turkeys still left to cook..."); slot_4 = new Food("Turkey B", 290, "salt", 2); Console.WriteLine(slot_4.Name + " goes into Secondhand Oven Slot 2. " + turkey_total + " turkeys still left to cook..."); } } if (pork_total > 0) { if (pork_total > 0 && ((slot_1.Type == "" && slot_2.Type != "sweet") || (slot_2.Type == "" && slot_1.Type != "sweet"))) { pork_total--; slot_1 = new Food("Pork Leg A", 270, "salt", 2); Console.WriteLine(slot_1.Name + " goes into Regular Oven Slot 1. " + pork_total + " pork legs still left to cook..."); slot_2 = new Food("Pork Leg B", 270, "salt", 2); Console.WriteLine(slot_2.Name + " goes into Regular Oven Slot 2. " + pork_total + " pork legs still left to cook..."); } if (pork_total > 0 && ((slot_3.Type != "sweet" && slot_4.Type == "") || (slot_4.Type != "sweet" && slot_3.Type == ""))) { pork_total--; slot_3 = new Food("Pork Leg A", 290, "salt", 2); Console.WriteLine(slot_3.Name + " goes into Secondhand Oven Slot 1. " + pork_total + " pork legs still left to cook..."); slot_4 = new Food("Pork Leg B", 290, "salt", 2); Console.WriteLine(slot_4.Name + " goes into Secondhand Oven Slot 2. " + pork_total + " pork legs still left to cook..."); } } if (corn_total > 0) { if (corn_total > 0 && slot_1.Type == "" && slot_2.Type != "sweet") { corn_total--; slot_1 = new Food("Corn Bread", 50, "salt", 1); Console.WriteLine("Corn Bread goes into Regular Oven Slot 1. " + corn_total + " corn breads still left to cook..."); } if (corn_total > 0 && slot_1.Type != "sweet" && slot_2.Type == "") { corn_total--; slot_2 = new Food("Corn Bread", 50, "salt", 1); Console.WriteLine("Corn Bread goes into Regular Oven Slot 2. " + corn_total + " corn breads still left to cook..."); } if (corn_total > 0 && slot_3.Type == "" && slot_4.Type != "sweet") { corn_total--; slot_3 = new Food("Corn Bread", 70, "salt", 1); Console.WriteLine("Corn Bread goes into Secondhand Oven Slot 1. " + corn_total + " corn breads still left to cook..."); } if (corn_total > 0 && slot_3.Type != "sweet" && slot_4.Type == "") { corn_total--; slot_3 = new Food("Corn Bread", 70, "salt", 1); Console.WriteLine("Corn Bread goes into Secondhand Oven Slot 2. " + corn_total + " corn breads still left to cook..."); } } if (orange_total > 0) { if (orange_total > 0 && slot_1.Type == "" && slot_2.Type != "salt") { orange_total--; slot_1 = new Food("Orange Cake", 60, "sweet", 1); Console.WriteLine("Orange Cake goes into Regular Oven Slot 1. " + orange_total + " orange cakes still left to cook..."); } if (orange_total > 0 && slot_1.Type != "salt" && slot_2.Type == "") { orange_total--; slot_2 = new Food("Orange Cake", 60, "sweet", 1); Console.WriteLine("Orange Cake goes into Regular Oven Slot 2. " + orange_total + " orange cakes still left to cook..."); } if (orange_total > 0 && slot_3.Type == "" && slot_4.Type != "salt") { orange_total--; slot_3 = new Food("Orange Cake", 80, "sweet", 1); Console.WriteLine("Orange Cake goes into Secondhand Oven Slot 1. " + orange_total + " orange cakes still left to cook..."); } if (orange_total > 0 && slot_4.Type == "" && slot_3.Type != "salt") { orange_total--; slot_4 = new Food("Orange Cake", 80, "sweet", 1); Console.WriteLine("Orange Cake goes into Secondhand Oven Slot 2. " + orange_total + " orange cakes still left to cook..."); } } if (choco_total > 0) { if (choco_total > 0 && slot_1.Type == "" && slot_2.Type != "salt") { choco_total--; slot_1 = new Food("Chocolate Cake", 60, "sweet", 1); Console.WriteLine("Chocolate Cake goes into Regular Oven Slot 1. " + choco_total + " chocolate cakes still left to cook..."); } if (choco_total > 0 && slot_1.Type != "salt" && slot_2.Type == "") { choco_total--; slot_2 = new Food("Chocolate Cake", 60, "sweet", 1); Console.WriteLine("Chocolate Cake goes into Regular Oven Slot 2. " + choco_total + " chocolate cakes still left to cook..."); } if (choco_total > 0 && slot_3.Type == "" && slot_4.Type != "salt") { choco_total--; slot_3 = new Food("Chocolate Cake", 80, "sweet", 1); Console.WriteLine("Chocolate Cake goes into Secondhand Oven Slot 1. " + choco_total + " chocolate cakes still left to cook..."); } if (choco_total > 0 && slot_4.Type == "" && slot_3.Type != "salt") { choco_total--; slot_4 = new Food("Chocolate Cake", 80, "sweet", 1); Console.WriteLine("Chocolate Cake goes into Secondhand Oven Slot 2. " + choco_total + " chocolate cakes still left to cook..."); } } if (milk_total > 0) { if (milk_total > 0 && slot_1.Type == "" && slot_2.Type != "salt") { milk_total--; slot_1 = new Food("Tres Leches", 40, "sweet", 1); Console.WriteLine("Tres Leches goes into Regular Oven Slot 1. " + milk_total + " tres leches still left to cook..."); } if (milk_total > 0 && slot_1.Type != "salt" && slot_2.Type == "") { milk_total--; slot_2 = new Food("Tres Leches", 40, "sweet", 1); Console.WriteLine("Tres Leches goes into Regular Oven Slot 2. " + milk_total + " tres leches still left to cook..."); } if (milk_total > 0 && slot_3.Type == "" && slot_4.Type != "salt") { milk_total--; slot_3 = new Food("Tres Leches", 60, "sweet", 1); Console.WriteLine("Tres Leches goes into Secondhand Oven Slot 1. " + milk_total + " tres leches still left to cook..."); } if (milk_total > 0 && slot_4.Type == "" && slot_3.Type != "salt") { milk_total--; slot_4 = new Food("Tres Leches", 60, "sweet", 1); Console.WriteLine("Tres Leches goes into Secondhand Oven Slot 2. " + milk_total + " tres leches still left to cook..."); } } next_step = Convert.ToInt16(slot_1.Cooktime_left); if (next_step > slot_2.Cooktime_left && slot_2.Cooktime_left != 0) { next_step = Convert.ToInt16(slot_2.Cooktime_left); } if (next_step > slot_3.Cooktime_left && slot_3.Cooktime_left != 0) { next_step = Convert.ToInt16(slot_3.Cooktime_left); } if (slot_1.Cooktime_left > 0) { slot_1.Cooktime_left = slot_1.Cooktime_left - next_step; } if (slot_2.Cooktime_left > 0) { slot_2.Cooktime_left = slot_2.Cooktime_left - next_step; } if (slot_3.Cooktime_left > 0) { slot_3.Cooktime_left = slot_3.Cooktime_left - next_step; } if (slot_4.Cooktime_left > 0) { slot_4.Cooktime_left = slot_4.Cooktime_left - next_step; } option_b_time = option_b_time + next_step; Console.WriteLine(next_step + " minutes pass..."); } Console.WriteLine("Total Cook-time using 2 2-slot Ovens: " + option_b_time + " Minutes (" + (option_b_time / 60) + " Hours or " + (option_b_time / 60 / 24) + " Days)\n\n"); Console.WriteLine("Conclusions:\n-------------------------"); Console.WriteLine("Time using 3-slot Oven: " + option_a_time + " Minutes"); Console.WriteLine("Time using a Secondhand Oven: " + option_b_time + " Minutes"); double difference = Math.Abs(option_a_time - option_b_time); Console.WriteLine("Difference: " + difference + " Minutes"); Console.Read(); }
static uint serverCapacity = 5816; // Number of simulataneous requests a server can handle static void Main(string[] args) { for (uint requestCount = requestsPerMonthMin; requestCount < requestsPerMonthMax; requestCount += requestsPerMonthStep) { double avgRequestRate = (requestCount * 2d) / (60 * 60 * 9 * 21); // Average requests per second // Initialize a Matrix Representing Available Capacity List <double>[] serverUsage = new List <double> [serverCount]; for (int i = 0; i < serverCount; i++) { serverUsage[i] = new List <double>(); } // Initialize Request Distributions Poisson arrivalDist = new Poisson(avgRequestRate); // Initialize Variables for Simulating Round-Robin Load Balancing int nextServerToUse = 0; // Next Server to Receive a Request // Initialize Measurement Variables int requestsRejectedByServer = 0; int totalRequestsInSimulation = 0; // Iterate through Simulation Rounds for (int round = 0; round < simulationTime; round++) { // Add New Requests to the Servers int requestsThisRound = arrivalDist.Sample(); totalRequestsInSimulation += requestsThisRound; for (int request = 0; request < requestsThisRound; request++) { // Determine if the Next Server can handle the Request double requestServiceTime = avgServiceTime; if (serverUsage[nextServerToUse].Count >= serverCapacity) { requestsRejectedByServer++; } else { serverUsage[nextServerToUse].Add(requestServiceTime); } // Use Round-Robin to Select Next Server if (nextServerToUse == serverCount - 1) { nextServerToUse = 0; } else { nextServerToUse++; } } for (int server = 0; server < serverCount; server++) { // Calculate Remaining Time needed for Requests for (int request = 0; request < serverUsage[server].Count; request++) { serverUsage[server][request] -= 1d; } // Remove Completed Requests from the Servers serverUsage[server].RemoveAll(requestTime => requestTime <= 0); } // Render Output if (round % (int)Math.Round(simulationTime / 10d) == 0) { Console.SetCursorPosition(0, 0); Console.ResetColor(); Console.WriteLine("Round {0}/{1} ({2}%)", round, simulationTime, Math.Round((double)round * 100d / (double)simulationTime, 2)); for (int server = 0; server < serverCount; server++) { if (serverUsage[server].Count >= serverCapacity) { Console.ForegroundColor = ConsoleColor.Red; } else { Console.ForegroundColor = ConsoleColor.Green; } Console.WriteLine("Server {0}: [{1}]", server.ToString(), String.Empty .PadRight(serverUsage[server].Count, '|') .PadRight((int)serverCapacity)); } } } Console.WriteLine("Testing Monthly Request Count: " + requestCount); Console.WriteLine("Simulated Request Count: " + totalRequestsInSimulation); Console.WriteLine("Requests Rejected By Server: " + requestsRejectedByServer); if (requestsRejectedByServer > 0) { Console.WriteLine("Found a Rejection at {0} Requests/Mo.", requestCount); Console.ReadKey(true); } totalRequestsInSimulation = requestsRejectedByServer = 0; // Console.ReadKey(true); } }
// Generate toy data - returns indices into vocab for each doc private int[][] GenerateToyLDAData( int numTopics, int numVocab, int numDocs, int expectedDocLength, out Dirichlet[] trueTheta, out Dirichlet[] truePhi) { truePhi = new Dirichlet[numTopics]; for (int i = 0; i < numTopics; i++) { truePhi[i] = Dirichlet.Uniform(numVocab); truePhi[i].PseudoCount.SetAllElementsTo(0.0); // Draw the number of unique words in the topic int numUniqueWordsPerTopic = Poisson.Sample((double)numVocab / numTopics); if (numUniqueWordsPerTopic >= numVocab) { numUniqueWordsPerTopic = numVocab; } double expectedRepeatOfWordInTopic = ((double)numDocs) * expectedDocLength / numUniqueWordsPerTopic; int[] shuffledWordIndices = Rand.Perm(numVocab); for (int j = 0; j < numUniqueWordsPerTopic; j++) { int wordIndex = shuffledWordIndices[j]; // Draw the count for that word int cnt = Poisson.Sample(expectedRepeatOfWordInTopic); truePhi[i].PseudoCount[wordIndex] = cnt + 1.0; } } trueTheta = new Dirichlet[numDocs]; for (int i = 0; i < numDocs; i++) { trueTheta[i] = Dirichlet.Uniform(numTopics); trueTheta[i].PseudoCount.SetAllElementsTo(0.0); // Draw the number of unique topics in the doc. We expect this to be // very sparse int numUniqueTopicsPerDoc = System.Math.Min(1 + Poisson.Sample(1.0), numTopics); double expectedRepeatOfTopicInDoc = expectedDocLength / numUniqueTopicsPerDoc; int[] shuffledTopicIndices = Rand.Perm(numTopics); for (int j = 0; j < numUniqueTopicsPerDoc; j++) { int topicIndex = shuffledTopicIndices[j]; // Draw the count for that topic int cnt = Poisson.Sample(expectedRepeatOfTopicInDoc); trueTheta[i].PseudoCount[topicIndex] = cnt + 1.0; } } // Sample from the model Vector[] topicDist = new Vector[numDocs]; Vector[] wordDist = new Vector[numTopics]; for (int i = 0; i < numDocs; i++) { topicDist[i] = trueTheta[i].Sample(); } for (int i = 0; i < numTopics; i++) { wordDist[i] = truePhi[i].Sample(); } int[][] wordsInDoc = new int[numDocs][]; for (int i = 0; i < numDocs; i++) { int LengthOfDoc = Poisson.Sample((double)expectedDocLength); wordsInDoc[i] = new int[LengthOfDoc]; for (int j = 0; j < LengthOfDoc; j++) { int topic = Discrete.Sample(topicDist[i]); wordsInDoc[i][j] = Discrete.Sample(wordDist[topic]); } } return(wordsInDoc); }
public void GeneratePackage() { _package = Poisson.Sample(); }
public void CanSample() { var d = new Poisson(0.3); var s = d.Sample(); }