public void AddNodeToBaGraph() { // Get list of nodes before new node is added var currNodes = _nodesDictionary.Values.ToList(); // we will choose M nodes from this list GraphNode newNode = NewGraphNode("n" + nextId++); // Create a "pool" of the sum of all degrees var totalDegrees = currNodes.Sum(n => Math.Pow(n.Degree, Exp)); // now choose its neighbors per the BA algorithm: for (int i = 0; i < M; i++) { double val = random.NextDouble() * totalDegrees; // Some point in this "pool" // Move throgh the "pool" node by node until we get to the node that is at this number's location double curr = 0; GraphNode selectedNode = null; foreach (var n in currNodes) { if (curr <= val && curr + Math.Pow(n.Degree, Exp) > val) { selectedNode = (GraphNode)n; totalDegrees -= Math.Pow(selectedNode.Degree, Exp); AddEdge(selectedNode, newNode); currNodes.Remove(selectedNode); break; } curr += Math.Pow(n.Degree, Exp); } } }
public ParticleSet PerceptionUpdate(string perception, IRandomizer r) { // compute Particle Weight foreach (Particle p in particles) { double particleWeight = hmm.SensorModel.Get(p.State, perception); p.Weight = particleWeight; } // weighted sample to create new ParticleSet ParticleSet result = new ParticleSet(hmm); while (result.Count != Count) { foreach (Particle p in particles) { double probability = r.NextDouble(); if (probability <= p.Weight) { if (result.Count < Count) { result.Add(new Particle(p.State, p.Weight)); } } } } return(result); }
public double[] LikelihoodWeighting(string X, Dictionary <string, bool?> evidence, int numberOfSamples, IRandomizer r) { var retval = new double[2]; for (int i = 0; i < numberOfSamples; i++) { var x = new Dictionary <string, bool?>(); var w = 1.0; var bayesNetNodes = this.GetVariableNodes(); foreach (BayesNetNode node in bayesNetNodes) { if (evidence[node.Variable] != null) { w *= node.ProbabilityOf(x); x[node.Variable] = evidence[node.Variable]; } else { x[node.Variable] = node.IsTrueFor(r.NextDouble(), x); } } bool?queryValue = (x[X]); if (queryValue == true) { retval[0] += w; } else { retval[1] += w; } } return(Util.Util.Normalize(retval)); }
/// <summary> /// Products destroyed by decay. /// </summary> /// <param name="amount">The amount being checked against.</param> /// <param name="MaintenanceMet">The percent of maintenance met.</param> /// <returns>The number of failed products.</returns> public double FailedProducts(double amount, double MaintenanceMet) { if (amount <= 0) { throw new ArgumentOutOfRangeException("Amount bust be greater than 0."); } if (MaintenanceMet < 0 || MaintenanceMet > 1) { throw new ArgumentOutOfRangeException("Maintenance Met must be between 0 and 1."); } // get the current failure chance, modified by maintenance met. var currentFailChance = DailyFailureChance * (2 - MaintenanceMet); // Get the percent of failure today, // stopping at zero so new items don't magically come into existance. var normalizedFailure = Math.Max(randomizer.Normal(1, 1) * currentFailChance, 0); // How many failed today. var randFailures = Math.Floor(normalizedFailure * amount); // Get an additional base chance that something break to push towards failure. var baseResult = randomizer.NextDouble() >= currentFailChance ? 0 : 1; // Return the sum of our random Failures and our base, capping at the total amount for safety. return(Math.Min(amount, randFailures + baseResult)); }
public MoveList Get(IRandomizer r) { var d = Math.Round(r.NextDouble() * 100, 2, MidpointRounding.AwayFromZero); var ml = _items.Single(t => t.LowerIndex <= d && t.HigherIndex >= d).MoveList; _moves.Remove(ml); CalculateFitnesses(); return(ml); }
private bool TruthValue(double[] ds, IRandomizer r) { double value = r.NextDouble(); if (value < ds[0]) { return(true); } return(false); }
public Dictionary <string, bool?> GetPriorSample(IRandomizer r) { var h = new Dictionary <string, bool?>(); var bayesNetNodes = this.GetVariableNodes(); foreach (var node in bayesNetNodes) { h[node.Variable] = node.IsTrueFor(r.NextDouble(), h); } return(h); }
public ParticleSet ToParticleSet(HiddenMarkovModel hmm, IRandomizer randomizer, int numberOfParticles) { ParticleSet result = new ParticleSet(hmm); for (int i = 0; i < numberOfParticles; i++) { double rvalue = randomizer.NextDouble(); string state = this.GetStateForRandomNumber(rvalue); result.Add(new Particle(state, 0)); } return(result); }
private Particle GenerateNewParticleWithRandomVelocity(Vector2 position, float height, float width, Vector2 gravity, Color[] colors, TimeSpan lifeTime) { var velocity = new Vector2( 75f * (_randomizer.NextDouble() * 2 - 1), 75f * (_randomizer.NextDouble() * 2 - 1)); return(GenerateNewParticle(position, height, width, velocity, gravity, colors, lifeTime)); }
public ParticleSet GenerateParticleSetForPredictedState(string action, IRandomizer randomizer) { ParticleSet predictedParticleSet = new ParticleSet(this.hmm); foreach (Particle p in particles) { string newState = hmm.TransitionModel.GetStateForProbability( p.State, action, randomizer.NextDouble()); Particle generatedParticle = new Particle(newState); predictedParticleSet.Add(generatedParticle); } return(predictedParticleSet); }
private Dictionary <string, bool> CreateRandomEvent(IList <string> nonEvidenceVariables, Dictionary <string, bool> evidence, IRandomizer r) { var table = new Dictionary <string, bool>(); var variables = this.GetVariables(); foreach (var variable in variables) { if (nonEvidenceVariables.Contains(variable)) { var value = r.NextDouble() <= 0.5 ? true : false; table[variable] = value; } else { table[variable] = evidence[variable]; } } return(table); }
/// <summary> /// Randomly selects an item from a dictionary based on a certain probability per item. /// </summary> /// <typeparam name="T">The type of the item to select.</typeparam> /// <param name="probabilities">The items with the given probabilities.</param> /// <param name="randomizer">The randomizer instance to use.</param> /// <returns>A randomly selected item.</returns> public static T DrawRandomly <T>(IDictionary <T, double> probabilities, IRandomizer randomizer) { // Get random value double randomValue = randomizer.NextDouble(); // Select one just in case T selectedElement = probabilities.Keys.OrderBy(e => probabilities[e]).First(); // Randomly select an element foreach (var prob in probabilities.OrderBy(p => p.Value)) { if (prob.Value > randomValue) { selectedElement = prob.Key; break; } randomValue -= prob.Value; } // Return the randomly selected element return(selectedElement); }
/// <summary> /// Returns a random double greater or equal to 0 and less /// than double.MaxValue /// </summary> /// <param name="r"></param> /// <returns></returns> public static double NextDouble(this IRandomizer r) => r.NextDouble(0, double.MaxValue);
/// <summary> /// Grows the population, prioritizing those which are happiest/most successful over others. /// </summary> public void PopGrowth() { // The average growth we achieve each day. var popGrowth = 0.01; // to be divided later represents one year growth average. // Get the success of the total populous. var lifeSat = Populous.LifeNeedsSatisfaction(); var dailySat = Populous.DailyNeedsSatisfaction(); // modify growth by satisfaction. if (lifeSat >= 0.99) { // Effectively totally satisfied. // The higher the Daily need Satisfaction, the greater the pop growth. popGrowth += 0.01 * dailySat; } else { // Life sat not satisfied, remove 3 times the missing life need satisfaction. popGrowth -= 0.03 * (1 - lifeSat); // This bottoms out at -0.02. } // Randomize growth today. var variance = rand.NextDouble(-0.01, 0.01); // -0.01 to 0.01 popGrowth += variance; // Get the new pops to add (divide by our year length) var newPops = TotalPopulation * popGrowth / 360; // add fractional pops to the carryover growth carryoverGrowth += newPops % 1; // remove fraction from newPops newPops -= newPops % 1; // if carry over growth greater than 1 (positive or negative) if (Math.Abs(carryoverGrowth) > 1) { // add (or remove) the whole number value of carry over. newPops += carryoverGrowth - (carryoverGrowth % 1); // update carryoverGrowth carryoverGrowth = carryoverGrowth % 1; } // Get pops ordered by success (descending order) var popsBySuccess = Populous.Pops.OrderByDescending(x => x.Success()); // get total weight of the populous (all positive values, no negatives) double totalWeight = 0; foreach (var pop in popsBySuccess) { // get the success totalWeight += pop.Success(); } // Now, we figure out where to put the pops. foreach (var pop in popsBySuccess) { // get pop's success again var success = pop.Success(); // if pop is not successful, regardless of reason, GTFO, failing pops don't grow // and if the pop is not successful, no following pops will be either. if (success <= 0.5) { break; } // get pop growth, divided by weight, and multiplied by success var born = newPops / totalWeight * success; // modify up or down by 50% born *= (0.5 + rand.NextDouble()); // remove hanging decimals born -= born % 1; // add new pops to group pop.AddPop(born); // remove born from new pops newPops -= born; // remove the success from the total weight totalWeight -= success; } // any remainder pop, just add to the most successful pop. popsBySuccess.First().AddPop(newPops - (newPops % 1)); // any extra just drop. }
public void Deploy() { if (!isInitialized) throw new InvalidOperationException("RandomDeployer not initialized!"); List<XYDoubleLocation> pointList = new List<XYDoubleLocation>(); rand = randFactory.CreateRandomizer(); bool continueFlag; XYDoubleLocation initial, final, current; initial = (XYDoubleLocation)field[0]; final = (XYDoubleLocation)field[1]; current = new XYDoubleLocation(); // Sink current = new XYDoubleLocation(final.X, (final.Y - initial.Y)/2); current.SetField(field); nodes.AddNode(nodeFactory.CreateNode(current)); pointList.Add(current); nodes.GetNodeByID(0).IsSink = true; // Sources for (int i = 1; i < 6; i++) { current = new XYDoubleLocation(initial.X, (i-1)*(final.Y-initial.Y)/4); current.SetField(field); nodes.AddNode(nodeFactory.CreateNode(current)); pointList.Add(current); } // Node Field for (int i = 6; i < numNodes; i++) { continueFlag = false; while (!continueFlag) { continueFlag = true; current = new XYDoubleLocation( rand.NextDouble() * (final.X - initial.X - 2 * padding) + initial.X + padding, rand.NextDouble() * (final.Y - initial.Y - 2 * padding) + initial.Y + padding); foreach (XYDoubleLocation point in pointList) { if (current.Distance(point) < minDistance) continueFlag = false; } } pointList.Add(current); current.SetField(field); nodes.AddNode(nodeFactory.CreateNode(current)); } }
private String DetermineDirectionOfActualMovement( String commandedDirection, IRandomizer r) { return(DetermineDirectionOfActualMovement(commandedDirection, r .NextDouble())); }
/// <summary> /// Returns a random double greater or equal to the supplied minValue and less /// than the supplied maxValue /// </summary> /// <param name="r"></param> /// <param name="minValue"></param> /// <param name="maxValue"></param> /// <returns></returns> public static long NextLong(this IRandomizer r, long minValue, long maxValue) => Convert.ToInt64((maxValue * 1.0 - minValue * 1.0) * r.NextDouble(0, 1) + minValue * 1.0);
/// <summary> /// Returns a random double greater or equal to 0 and less /// than the supplied maxValue /// </summary> /// <param name="r"></param> /// <param name="maxValue"></param> /// <returns></returns> public static double NextDouble(this IRandomizer r, double maxValue) => r.NextDouble(0, maxValue);