public static CompletedSimulation ChooseWorst(CompletedSimulation first, CompletedSimulation second) { if (first == null) { return(second); } if (second == null) { return(first); } if (first.HasError) { return(first); } if (second.HasError) { return(second); } if (first.Stats.SamplesTransmitted <= second.Stats.SamplesTransmitted) { return(first); } return(second); }
internal async Task <(Dictionary <IAiFactory, (Double meanMoves, Double meanPower, Double meanSamples, Double sampleStdDev)> aggregates, CompletedSimulation worstSim, IAiFactory worstAi)> Simulate(IList <IAiFactory> aiFactories, Int32 runCount) { var aggregates = new Dictionary <IAiFactory, (Double meanMoves, Double meanPower, Double meanSamples, Double sampleStdDev)>(); CompletedSimulation worstSim = null; IAiFactory worstAi = null; Int32 levelSeed = Rando.Next(Int32.MinValue, Int32.MaxValue); foreach (var aiFactory in aiFactories) { var levelRand = new Random(levelSeed); var levelGeneratorFactory = new OpenCheckingGeneratorFactory(new DefaultLevelGeneratorFactory(), 6); var roverFactory = new DefaultRoverFactory(); var simulator = new Simulator(levelGeneratorFactory, roverFactory, aiFactory); using (Completer completer = Completer.Create(Path.Combine(OutputDirectory, $"RoverSim-{aiFactory.Name}.csv"))) { await simulator.SimulateAsync(runCount, completer.Consume); aggregates[aiFactory] = completer.GetAggregates(); worstSim = Completer.ChooseWorst(worstSim, completer.WorstSim); if (worstSim == completer.WorstSim) { worstAi = aiFactory; } } } return(aggregates, worstSim, worstAi); }
public void Consume(CompletedSimulation sim) { RoverStats stats = sim.Stats; // Write CSV _csv.WriteField(stats.MovesLeft.ToString()); _csv.WriteField(stats.Power.ToString()); _csv.WriteField(stats.SamplesCollected.ToString()); _csv.WriteField(stats.SamplesProcessed.ToString()); _csv.WriteField(stats.SamplesTransmitted.ToString()); _csv.WriteField(stats.MoveCount.ToString()); _csv.WriteField(stats.MoveCallCount.ToString()); _csv.WriteField(stats.CollectPowerCallCount.ToString()); _csv.WriteField(stats.CollectSampleCallCount.ToString()); _csv.WriteField(stats.ProcessSamplesCallCount.ToString()); _csv.WriteField(stats.TransmitCallCount.ToString()); _csv.WriteField(sim.ProtoLevel.Seed); _csv.NextRecord(); // Update stats _moves += stats.MovesLeft; _power += stats.Power; _count++; Double delta = stats.SamplesTransmitted - _meanSamples; _meanSamples += delta / _count; Double delta2 = stats.SamplesTransmitted - _meanSamples; _mean2Samples += delta * delta2; // Update Worst Sim WorstSim = ChooseWorst(WorstSim, sim); _progress.Report(1); }
public RenderViewModel(IAiFactory ai, CompletedSimulation simulation) { Ai = ai ?? throw new ArgumentNullException(nameof(ai)); Simulation = simulation ?? throw new ArgumentNullException(nameof(simulation)); Tiles = Simulation.OriginalLevel.AsMutable().Terrain; RoverX = Simulation.Parameters.InitialPosition.X; RoverY = Simulation.Parameters.InitialPosition.Y; }
public RenderForm(CompletedSimulation demoResult, IAiFactory demoAi) { DemoResult = demoResult ?? throw new ArgumentNullException(nameof(demoResult)); DemoAi = demoAi ?? throw new ArgumentNullException(nameof(demoAi)); OutputDirectory = Path.Combine(Directory.GetCurrentDirectory(), DemoAi.Name); InitializeComponent(); RenderControl.VisibleState = VisibleState.GenerateBlank(DemoResult.Parameters); }
private static void ExportFrames(CompletedSimulation sim, IAiFactory aiFactory, String outputDir) { const Int32 tileSize = 10; IAi ai = aiFactory.Create(sim.Parameters); Level level = sim.ProtoLevel.Generate(); Rover rover = new Rover(level, sim.Parameters); VisibleState state = VisibleState.GenerateBlank(level.BottomRight, rover.Position); using var actionEnumerator = ai.Simulate(rover.Accessor).GetEnumerator(); Int32 maxFrameCount = sim.Parameters.InitialMovesLeft; Int32 filenameDigits = (Int32)Math.Ceiling(Math.Log10(maxFrameCount)) + 1; String fileBase = Path.Combine(outputDir, $"frame-{sim.ProtoLevel.Seed}-"); DirectoryInfo dir = new DirectoryInfo(outputDir); if (dir.Exists) { foreach (var file in dir.EnumerateFiles()) { file.Delete(); } } else { dir.Create(); } Int32 width = level.Width * tileSize; Int32 height = level.Height * tileSize; using Bitmap bitmap = new Bitmap(width, height); using Graphics surface = Graphics.FromImage(bitmap); Update update = new Update(terrain: rover.Adjacent); Int32 frameIndex = 0; do { if (!state.Apply(update)) { continue; } GdiRenderer.Draw(surface, width, height, state); String suffix = frameIndex.ToString().PadLeft(filenameDigits, '0'); String filename = fileBase + suffix + ".png"; bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Png); frameIndex++; }while (actionEnumerator.MoveNext() && rover.Perform(actionEnumerator.Current, out update)); }
private async void SimulateButton_Click(object sender, EventArgs e) { if (!running) { running = true; } else { return; } if (!Int32.TryParse(RunCount.Text, out Int32 runCount)) { return; } WorkManager manager = new WorkManager(); List <IAiFactory> selectedAis = aiFactories.Where(t => AiList.SelectedItems.ContainsKey(t.Name)).ToList(); TimeUsed.Text = "Working..."; var stopwatch = Stopwatch.StartNew(); (var results, var worstSim, var worstAi) = await manager.Simulate(selectedAis, runCount); stopwatch.Stop(); TimeUsed.Text = stopwatch.Elapsed.TotalSeconds.ToString(); _renderSim = worstSim; _renderAiFactory = worstAi; if (_renderSim != null && _renderSim.HasError) { MessageBox.Show("ERROR"); } foreach (var aiFactory in results.Keys) { var stat = results[aiFactory]; if (Results.Rows.Count == 0) { DataGridViewRow row = new DataGridViewRow(); Results.Rows.Add(row); } (var meanMoves, var meanPower, var meanSamples, var sampleStdDev) = stat; Results.Rows[0].SetValues(aiFactory.Name, meanMoves.ToString("F2"), meanPower.ToString("F2"), meanSamples.ToString("F2"), sampleStdDev.ToString("F2")); } running = false; }
public RenderViewModel(IAiFactory aiFactory, CompletedSimulation simulation) { Ai = aiFactory ?? throw new ArgumentNullException(nameof(aiFactory)); Simulation = simulation ?? throw new ArgumentNullException(nameof(simulation)); Start = ReactiveCommand.CreateFromObservable(() => { IAi ai = Ai.Create(Simulation.Parameters); Level level = Simulation.ProtoLevel.Generate(); Rover rover = new Rover(level, Simulation.Parameters); return(Observable.Create <(RoverAction action, Update update)>(obs => { return Task.Run(async() => { var actionEnumerator = ai.Simulate(rover.Accessor).GetEnumerator(); while (actionEnumerator.MoveNext() && rover.Perform(actionEnumerator.Current, out Update update)) { obs.OnNext((actionEnumerator.Current, update)); Int32 delay = actionEnumerator.Current.Instruction switch { Instruction.Move => 75, Instruction.CollectSample => 50, _ => 0 }; if (delay != 0) { await Task.Delay(delay); } } }); })); }); Stats = Start.Aggregate(RoverStats.Create(Simulation.Parameters), (s, update) => s.Add(update.action, update.update)); State = this .WhenAnyObservable(m => m.Start) .Select(update => update.update) .Scan(VisibleState.GenerateBlank(Simulation.Parameters), (state, update) => { state.Apply(update); return(state); }); }
public RenderForm(CompletedSimulation demoResult, IAiFactory demoAi) { DemoResult = demoResult ?? throw new ArgumentNullException(nameof(demoResult)); DemoAi = demoAi ?? throw new ArgumentNullException(nameof(demoAi)); InitializeComponent(); }
public SimulationRowViewModel(IAiFactory ai, CompletedSimulation simulation) { Ai = ai ?? throw new ArgumentNullException(nameof(ai)); Simulation = simulation ?? throw new ArgumentNullException(nameof(simulation)); }