/// <summary> /// Generates a random vector of observations from the current distribution. /// </summary> /// /// <param name="samples">The number of samples to generate.</param> /// /// <returns>A random vector of observations drawn from this distribution.</returns> /// public double[][] Generate(int samples) { if (chol == null) { throw new NonPositiveDefiniteMatrixException("Covariance matrix is not positive definite."); } var r = new StandardGenerator(BestCS.Math.Tools.Random.Next()); double[,] A = chol.LeftTriangularFactor; double[][] data = new double[samples][]; for (int i = 0; i < data.Length; i++) { double[] sample = new double[Dimension]; for (int j = 0; j < sample.Length; j++) { sample[j] = r.Next(); } data[i] = A.Multiply(sample).Add(Mean); } return(data); }
/// <summary> /// Initializes a new instance of the <see cref="GaussianGenerator"/> class. /// </summary> /// /// <param name="mean">Mean value.</param> /// <param name="stdDev">Standard deviation value.</param> /// <param name="seed">Seed value to initialize random numbers generator.</param> /// public GaussianGenerator(double mean, double stdDev, int seed) { this.mean = mean; this.stdDev = stdDev; rand = new StandardGenerator(seed); }
public void PairPowerUpsPairsPairedPowerUps() { var random = new StandardGenerator(784653); var floor = new Floor(80, 31, 0, random); var serialized = Serializer.Serialize(floor); var deserialized = Serializer.Deserialize <Floor>(serialized); // Sanity Assert.That(deserialized.PowerUps[0].PairedTo, Is.EqualTo(deserialized.PowerUps[1])); Assert.That(deserialized.PowerUps[1].PairedTo, Is.EqualTo(deserialized.PowerUps[0])); // Act deserialized.PairPowerUps(); // Assert. This doesn't work on deserialized.PowerUps. // It looks like JSON.net is not equating the references, because PowerUps[0] != PairedPowerUps[0]. // And yet, this works in practice: new game, save, quit, load, get powerup => destroys paired one. // ¯\_(ツ)_/¯ var p1 = deserialized.PairedPowerUps[0]; var p2 = deserialized.PairedPowerUps[1]; Assert.That(p1.PairedTo, Is.EqualTo(p2)); Assert.That(p2.PairedTo, Is.EqualTo(p1)); // https://trello.com/c/zT3IX8nh/147-unpaired-power-ups-again // Make sure paired power-ups have PickUpCallback specified Assert.That(deserialized.PowerUps.Where(p => p.PairedTo != null).All(p => p.PickUpCallback != null)); }
/// <summary> /// Initializes a new instance of the <see cref="GaussianGenerator"/> class. /// </summary> /// /// <param name="mean">Mean value.</param> /// <param name="stdDev">Standard deviation value.</param> /// <param name="seed">Seed value to initialize random numbers generator.</param> /// public GaussianGenerator(float mean, float stdDev, int seed) { this.mean = mean; this.stdDev = stdDev; rand = new StandardGenerator(seed); }
public void GenreateMapGeneratesBacktrackingChasmsOneFloorBeforeTeleporterWithPairedPowerUps() { RestrictRuntime(() => { const int InstaTeleporterFloor = 8; // B8 var random = new StandardGenerator(357); var noPowerUps = new List <PowerUp>(); var floor = new Floor(30, 30, InstaTeleporterFloor - 2, random); Assert.That(floor.Chasms.Any()); // Chasms don't have a "backtracking" property. Instead, Check that all the chasms are in one room. // Well, we can't check that either; so check that they're all adjacent to two other chasms. /shrug foreach (var chasm in floor.Chasms) { var adjacencies = floor.Chasms.Where(c => c != chasm && Math.Sqrt(Math.Pow(c.X - chasm.X, 2) + Math.Pow(c.Y - chasm.Y, 2)) == 1); Assert.That(adjacencies.Count(), Is.EqualTo(2)); } // Make sure the power-ups are backtracking and paired var powerUps = floor.PowerUps.Where(p => p.IsBacktrackingPowerUp).ToArray(); Assert.That(powerUps.Count(), Is.EqualTo(2)); var p1 = powerUps[0]; var p2 = powerUps[1]; Assert.That(p1.PairedTo, Is.EqualTo(p2)); Assert.That(p2.PairedTo, Is.EqualTo(p1)); // Generated in a new room, make sure it's accessible var firstChasm = floor.Chasms.First(); var firstChasmCoordinates = new GoRogue.Coord(firstChasm.X, firstChasm.Y); var pathFinder = new AStar(floor.Map, GoRogue.Distance.EUCLIDEAN); var path = pathFinder.ShortestPath(floor.StairsUpLocation, firstChasmCoordinates, true); }); }
public void CreateExplosionCreatesTilesAroundAndIncludingMissileEpicenter() { var generator = new StandardGenerator(313821775); var floor = new Floor(80, 28, 0, generator); var epicenter = new GoRogue.Coord(5, 5); var radius = Floor.ExplosionRadius; floor.CreateExplosion(epicenter.X, epicenter.Y); // Just for clarity, yes it's redundant Assert.That(floor.EffectEntities.Any(e => e.X == epicenter.X && e.Y == epicenter.Y && e is Explosion), $"Didn't find explosion at epicenter!"); for (var y = epicenter.Y - radius; y <= epicenter.Y + radius; y++) { for (var x = epicenter.X - radius; x <= epicenter.X + radius; x++) { var distance = Math.Sqrt(Math.Pow(x - epicenter.X, 2) + Math.Pow(y - epicenter.Y, 2)); if (distance <= radius) { Assert.That(floor.EffectEntities.Any(e => e.X == x && e.Y == y && e is Explosion), $"Didn't find explosion at {x}, {y}"); } } } }
public void TestCellAutoConnectivityAndEnclosure() { var random = new StandardGenerator(); var map = new ArrayMap <bool>(80, 50); Generators.CellularAutomataGenerator.Generate(map, random, 40, 7, 4); for (int i = 0; i < 500; i++) { Generators.CellularAutomataGenerator.Generate(map, random, 40, 7, 4); // Ensure it's connected var areas = MapAreaFinder.MapAreasFor(map, Distance.MANHATTAN).ToList(); Assert.AreEqual(1, areas.Count); // Ensure it's enclosed for (int x = 0; x < map.Width; x++) { Assert.AreEqual(false, map[x, 0]); Assert.AreEqual(false, map[x, map.Height - 1]); } for (int y = 0; y < map.Height; y++) { Assert.AreEqual(false, map[0, y]); Assert.AreEqual(false, map[map.Width - 1, y]); } } }
/// <summary> /// Initializes a new instance of the <see cref="GaussianGenerator"/> class. /// </summary> /// /// <param name="mean">Mean value.</param> /// <param name="stdDev">Standard deviation value.</param> /// <param name="seed">Seed value to initialize random numbers generator.</param> /// public GaussianGenerator(double mean, double stdDev, int seed) { this.mean = mean; this.stdDev = stdDev; rand = new StandardGenerator(seed); }
public void GenerateMonstersGeneratesMonstersOnAppropriateFloorsOnly() { RestrictRuntime(() => { // Slinks on B2, TenLegs on B4, Zugs on B6 var random = new StandardGenerator(1021); var width = 50; var height = 40; var floors = new List <Floor>(); // i => B1, B2, etc. base 1) for (var i = 1; i <= 8; i++) { floors.Add(new Floor(width, height, i - 1, random)); } // Assert, starting with B1 Assert.That(floors[0].Monsters.All(m => m.Name == "Fuseling")); Assert.That(floors[1].Monsters.All(m => m.Name == "Fuseling" || m.Name == "Slink")); Assert.That(floors[2].Monsters.All(m => m.Name == "Fuseling" || m.Name == "Slink")); Assert.That(floors[3].Monsters.All(m => m.Name == "Fuseling" || m.Name == "Slink" || m.Name == "TenLegs")); Assert.That(floors[4].Monsters.All(m => m.Name == "Fuseling" || m.Name == "Slink" || m.Name == "TenLegs")); Assert.That(floors[5].Monsters.All(m => m.Name == "Fuseling" || m.Name == "Slink" || m.Name == "TenLegs" || m.Name == "Zug")); Assert.That(floors[6].Monsters.All(m => m.Name == "Fuseling" || m.Name == "Slink" || m.Name == "TenLegs" || m.Name == "Zug")); }); }
public void GenerateFloorGeneratesUpAndDownStairsAppropraitely(int floorNum, bool expectStairsDown, bool expectStairsUp) { RestrictRuntime(() => { var globalRandom = new StandardGenerator(10201); var floor = new Floor(35, 25, floorNum, globalRandom); if (expectStairsDown) { Assert.That(floor.StairsDownLocation, Is.Not.EqualTo(GoRogue.Coord.NONE)); } else { Assert.That(floor.StairsDownLocation, Is.EqualTo(GoRogue.Coord.NONE)); } if (expectStairsUp) { Assert.That(floor.StairsUpLocation, Is.Not.EqualTo(GoRogue.Coord.NONE)); } else { Assert.That(floor.StairsUpLocation, Is.EqualTo(GoRogue.Coord.NONE)); } }); }
public void GenerateMapGeneratesBacktrackingLockedDoorsOnZapperFloorMinusOneWithPairedPowerUps() { RestrictRuntime(() => { const int ZapperFloor = 4; // B4 var random = new StandardGenerator(355); var noPowerUps = new List <PowerUp>(); var floor = new Floor(30, 30, ZapperFloor - 2, random); Assert.That(floor.Doors.Any(d => d.IsLocked && d.IsBacktrackingDoor)); Assert.That(floor.Doors.Count(d => d.IsLocked && !d.IsBacktrackingDoor), Is.EqualTo(0)); // Make sure the power-ups are backtracking and paired var powerUps = floor.PowerUps.Where(p => p.IsBacktrackingPowerUp).ToArray(); Assert.That(powerUps.Count(), Is.EqualTo(2)); var p1 = powerUps[0]; var p2 = powerUps[1]; Assert.That(p1.PairedTo, Is.EqualTo(p2)); Assert.That(p2.PairedTo, Is.EqualTo(p1)); // Generated in a new room, make sure it's accessible var firstLock = floor.Doors.First(d => d.IsLocked && d.IsBacktrackingDoor); var firstLockCoordinates = new GoRogue.Coord(firstLock.X, firstLock.Y); var pathFinder = new AStar(floor.Map, GoRogue.Distance.EUCLIDEAN); var path = pathFinder.ShortestPath(floor.StairsUpLocation, firstLockCoordinates, true); }); }
public void ShipCoreOnlyGeneratesOnFinalFloor() { RestrictRuntime(() => { var generator = new StandardGenerator(562365745); for (var i = 0; i < 10; i++) { var floor = new Floor(80, 28, i, generator); var expectDrive = i == 9; if (expectDrive) { Assert.That(floor.ShipCore, Is.Not.Null); for (var x = floor.ShipCore.X - 1; x <= floor.ShipCore.X + 1; x++) { for (var y = floor.ShipCore.Y - 1; y <= floor.ShipCore.Y + 1; y++) { if (x != floor.ShipCore.X && y != floor.ShipCore.Y) { // There should be a fake wall there. If not, it's because there's a real wall there (stairs is next to a wall). Assert.That(floor.FakeWalls.Any(f => f.X == x && f.Y == y), $"Core is at {floor.ShipCore.X}, {floor.ShipCore.Y}. Expected fake wall at {x}, {y} but there wasn't one."); } } } } else { Assert.That(floor.ShipCore, Is.Null); } } }); }
public void GenerateMapGeneratesBacktrackingGravityWavesOneFloorAboveGravityCannonWithPairedPowerUps() { RestrictRuntime(() => { const int GravityCannonFloor = 6; // B6 var random = new StandardGenerator(356); var noPowerUps = new List <PowerUp>(); var floor = new Floor(30, 30, GravityCannonFloor - 2, random); Assert.That(floor.GravityWaves.Any()); Assert.That(floor.GravityWaves.All(g => g.IsBacktrackingWave)); // Make sure the power-ups are backtracking and paired var powerUps = floor.PowerUps.Where(p => p.IsBacktrackingPowerUp).ToArray(); Assert.That(powerUps.Count(), Is.EqualTo(2)); var p1 = powerUps[0]; var p2 = powerUps[1]; Assert.That(p1.PairedTo, Is.EqualTo(p2)); Assert.That(p2.PairedTo, Is.EqualTo(p1)); // Generated in a new room, make sure it's accessible var firstGravity = floor.GravityWaves.First(); var firstGravityCoordinates = new GoRogue.Coord(firstGravity.X, firstGravity.Y); var pathFinder = new AStar(floor.Map, GoRogue.Distance.EUCLIDEAN); var path = pathFinder.ShortestPath(floor.StairsUpLocation, firstGravityCoordinates, true); }); }
public void BossGeneratesOnB10() { var generator = new StandardGenerator(6846452); var floor = new Floor(80, 28, 9, generator); Assert.That(floor.Monsters.Where(m => m is Ameer).Count(), Is.EqualTo(1)); }
public static int[] GetStats(int height, int width, int tries, ArrayMap <bool> pattern) { StandardGenerator random = new StandardGenerator(); var wMap = new ArrayMap <bool>(height, width); int[] hits = new int[tries]; for (int i = 0; i < tries; i++) { QuickGenerators.GenerateCellularAutomataMap(wMap, random); var pMap = new ArrayMap <bool>(height, width); while (TryGetFirstPatternMatch(wMap, pMap, pattern, out Coord coord)) { foreach (var pos in pattern.Positions()) { pMap[pos.X + coord.X, pos.Y + coord.Y] = true; } hits[i] += 1; } } return(hits); }
public void ConstructorSymmetricallyPairsPowerUps() { var generator = new StandardGenerator(12311); var p1 = PowerUp.Generate(generator); var p2 = new PowerUp(0, 0, 'P', true, 99, 88, 77, 66, p1); Assert.That(p2.PairedTo, Is.EqualTo(p1)); Assert.That(p1.PairedTo, Is.EqualTo(p2)); }
public static void Shuffle(SortingArray array) { for (int i = 0; i < array.Length; i++) { StandardGenerator rand = new StandardGenerator(); int pos = rand.Next(0, array.Length); array.Swap(i, pos); Updated(array); } }
public void ManualTestRandomRoomsGen() { var random = new StandardGenerator(); var map = new ArrayMap <bool>(30, 30); Generators.RandomRoomsGenerator.Generate(map, random, 7, 4, 7, 5); displayMap(map); // TODO: Some assert here }
public void ManualTestRandomRoomsGen() { var random = new StandardGenerator(); var map = new ArrayMap <bool>(80, 50); QuickGenerators.GenerateRandomRoomsMap(map, random, 10, 4, 15, 5); displayMap(map); // TODO: Some assert here }
public static void GenerateRandom(SortingArray array) { for (int i = 0; i < array.Length; i++) { StandardGenerator rand = new StandardGenerator(); int val = rand.Next(1, array.Length + 1); array.Modify(i, val); Updated(array); } }
private Bounds GenerateReactionConditions(IReaction chemObj, Color fg, double scale) { var title = chemObj.GetProperty <string>(CDKPropertyName.ReactionConditions); if (string.IsNullOrEmpty(title)) { return(new Bounds()); } return(new Bounds(MarkedElement.Markup(StandardGenerator.EmbedText(font, emSize, title, fg, 1 / scale), "conditions"))); }
public static void GenerateRandomAscending(SortingArray array) { for (int i = 0; i < array.Length; i++) { StandardGenerator rand = new StandardGenerator(); int value = rand.Next(i, array.Length) + 1; array.Modify(i, value); Updated(array); } }
//[Fact] // This algorithm is too slow for Rosenbrock test. It does converge though. public static void TestBinaryGA() { int seed = 1; var rng = new StandardGenerator(seed); //var rng = RandomNumberGenerationUtilities.troschuetzRandom; // Define optim problem OptimizationProblem problem = new Rosenbrock(); // Define optim algorithm var optimBuilder = new BinaryGeneticAlgorithmBuilder(problem); optimBuilder.Logger = new BestOfIterationLogger(); // Setup logging //optimBuilder.Logger = new EmptyLogger(); // Define convergence criteria optimBuilder.ConvergenceCriterion = new MaxFunctionEvaluations(1000000); // Define encoding optimBuilder.Encoding = new GrayCoding(problem, 16, 8); // Initialization optimBuilder.Initializer = new RealUniformRandomInitializer(problem, rng); // Define population size optimBuilder.PopulationSize = 100; // Define selection strategy //optimBuilder.Selection = new RouletteWheelSelection<bool>(new InverseRankScaling<bool>(0.5)); //optimBuilder.Selection = new TournamentSelection<bool>(2, false); //optimBuilder.Selection = new StochasticUniversalSampling<bool>(new InverseRankScaling<bool>(2.0 //optimBuilder.Selection = new RemainderStochasticSamplingWithReplacement<bool>(new InverseRankScaling<bool>(1.0)); optimBuilder.Selection = new TruncationSelection <bool>(rng, 0.5); // Define recombination strategy optimBuilder.Recombination = new SinglePointCrossover <bool>(rng); // Define mutation strategy optimBuilder.Mutation = new BitFlipMutation(0.05, rng); // Start optimization GeneticAlgorithm <bool> optimAlgorithm = optimBuilder.BuildAlgorithm(); optimAlgorithm.Solve(); // Check results double expectedFitness = 0.0; var expectedDesign = Vector.CreateWithValue(problem.Dimension, 1.0); Assert.Equal(expectedFitness, optimAlgorithm.BestFitness, 10); Assert.True(Vector.CreateFromArray(optimAlgorithm.BestPosition).Equals(expectedDesign, 1E-6)); }
public void GenerateMapGeneratesLockedDoorsAfterZapperFloor() { RestrictRuntime(() => { const int ZapperFloor = 4; // B4 var random = new StandardGenerator(355); var noPowerUps = new List <PowerUp>(); var floor = new Floor(30, 30, ZapperFloor - 1, random); Assert.That(floor.Doors.Any(d => d.IsLocked && !d.IsBacktrackingDoor)); }); }
public void GenerateWeaponPickUpGeneratesWeaponsOnAppropriateFloor(int basementNumber, Weapon expectedWeapon) { RestrictRuntime(() => { var random = new StandardGenerator(93524); var floor = new Floor(30, 30, basementNumber - 1, random); Assert.That(floor.WeaponPickUp, Is.Not.Null); Assert.That(floor.WeaponPickUp.Weapon, Is.EqualTo(expectedWeapon)); }); }
public static void TestRealCodedGA() { int seed = 2; var rng = new StandardGenerator(seed); RandomNumberGenerationUtilities.troschuetzRandom = rng; // hack to make sure the same seed is used everwhere in the GA. TODO: Find out which part of the GA messes up. // Define optim problem OptimizationProblem problem = new Sphere(); // Define optim algorithm var optimBuilder = new RealCodedGeneticAlgorithmBuilder(problem); optimBuilder.Logger = new BestOfIterationLogger(); // Setup logging //optimBuilder.Logger = new EmptyLogger(); // Initialization optimBuilder.Initializer = new RealUniformRandomInitializer(problem, rng); // Define convergence criteria optimBuilder.ConvergenceCriterion = CompositeCriteria.OR(new MaxIterations(200), new MaxFunctionEvaluations(1000000)); // Define population size optimBuilder.PopulationSize = 100; // Define selection strategy //optimBuilder.Selection = new RouletteWheelSelection<double>(new InverseRankScaling<double>(0.5)); optimBuilder.Selection = new TournamentSelection <double>(rng, 2, false); //optimBuilder.Selection = new StochasticUniversalSampling<double>(new InverseRankScaling<double>(2.0 //optimBuilder.Selection = new RemainderStochasticSamplingWithReplacement<double>(new InverseRankScaling<double>(1.0)); //optimBuilder.Selection = new TruncationSelection<double>(0.5); // Define recombination strategy //optimBuilder.Recombination = new UniformCrossover<double>(); optimBuilder.Recombination = new IntermediateCrossover(rng); // Define mutation strategy //optimBuilder.Mutation = new ConstantGaussianMutation(problem, 1.0); optimBuilder.Mutation = new UniformMutation(problem, 0.01, rng); // Start optimization GeneticAlgorithm <double> optimAlgorithm = optimBuilder.BuildAlgorithm(); optimAlgorithm.Solve(); // Check results double expectedFitness = 0.0; var expectedDesign = Vector.CreateWithValue(problem.Dimension, 0.0); Assert.Equal(expectedFitness, optimAlgorithm.BestFitness, 2); Assert.True(Vector.CreateFromArray(optimAlgorithm.BestPosition).Equals(expectedDesign, 1E-1)); }
public void ManualTestDungeonMazeGen() { var random = new StandardGenerator(12345); var map = new ArrayMap <bool>(80, 50); QuickGenerators.GenerateDungeonMazeMap(map, random, minRooms: 4, maxRooms: 10, roomMinSize: 4, roomMaxSize: 7, maxTrimIterations: 20); displayMap(map); // TODO: Some assert here }
public void ManualTestCellAutoGen() { var random = new StandardGenerator(); var map = new ArrayMap <bool>(80, 50); Generators.CellularAutomataGenerator.Generate(map, random, 40, 7, 4); displayMap(map); // TODO: Asserts }
/// <summary> /// Generate a bound element that is the title of the provided molecule. If title /// is not specified an empty bounds is returned. /// </summary> /// <param name="chemObj">molecule or reaction</param> /// <returns>bound element</returns> private Bounds GenerateTitle(RendererModel model, IChemObject chemObj, double scale) { var title = chemObj.GetProperty <string>(CDKPropertyName.Title); if (string.IsNullOrEmpty(title)) { return(new Bounds()); } scale = 1 / scale * model.GetTitleFontScale(); return(new Bounds(MarkedElement.Markup(StandardGenerator.EmbedText(font, emSize, title, model.GetTitleColor(), scale), "title"))); }
public void BossDoesntGenerateBeforeB10() { RestrictRuntime(() => { var generator = new StandardGenerator(4653256); for (var i = 0; i < 9; i++) { var floor = new Floor(80, 28, i, generator); Assert.That(floor.Monsters.All(m => !(m is Ameer))); } }); }
public void GenerateMapGeneratesGravityWavesAfterGravityCannonFloor() { RestrictRuntime(() => { const int GravityCannonFloor = 6; // B6 var random = new StandardGenerator(356); var noPowerUps = new List <PowerUp>(); var floor = new Floor(80, 28, GravityCannonFloor - 1, random); Assert.That(floor.GravityWaves.Any()); Assert.That(floor.GravityWaves.All(g => !g.IsBacktrackingWave)); }); }
/// <summary> /// Set seed of the random numbers generator. /// </summary> /// /// <param name="seed">Seed value.</param> /// /// <remarks>Resets random numbers generator initializing it with /// specified seed value.</remarks> /// public void SetSeed( int seed ) { rand = new StandardGenerator( seed ); }
/// <summary> /// Initializes a new instance of the <see cref="GaussianGenerator"/> class. /// </summary> /// /// <param name="mean">Mean value.</param> /// <param name="stdDev">Standard deviation value.</param> /// <param name="seed">Seed value to initialize random numbers generator.</param> /// public GaussianGenerator( float mean, float stdDev, int seed ) { this.mean = mean; this.stdDev = stdDev; rand = new StandardGenerator( seed ); }