public void Post_Game_ReturnsSimulationResults(int NumberOfSimulations, int nrWins) { var simulationResultObj = new SimulationResult() { wins = nrWins, percentageOfWins = (decimal)(nrWins / NumberOfSimulations), losses = NumberOfSimulations - nrWins, NumberOfDoors = 3, }; var mockSimulationService = new Mock <ISimulationService>(); mockSimulationService.Setup(service => service.RunSimulation(It.IsAny <int>(), It.IsAny <Boolean>(), It.IsAny <int>())).Returns(simulationResultObj); var sut = new SimulationController(mockSimulationService.Object); var result = sut.Post(new Game() { NumberOfSimulations = NumberOfSimulations }) as OkObjectResult; Assert.IsInstanceOf <OkObjectResult>(result); var simulationResult = result.Value as SimulationResult; Assert.GreaterOrEqual(simulationResult.wins, nrWins); Assert.GreaterOrEqual(simulationResult.losses, simulationResultObj.losses); Assert.GreaterOrEqual(simulationResult.percentageOfWins, simulationResultObj.percentageOfWins); Assert.AreEqual(simulationResult.NumberOfDoors, simulationResultObj.NumberOfDoors); }
public SimulationResult MapToSimulationResult(List <Unit> units, uint playerId, uint numberOfIterations, Map map) { var result = new SimulationResult(); result.PlayerId = playerId; result.Map = map; for (int ind = 0; ind < numberOfIterations; ind++) { var iteration = result.UnitMovements.FirstOrDefault(um => um.Iteration == ind); if (iteration == null) { iteration = new UnitMovement() { Iteration = (uint)ind }; result.UnitMovements.Add(iteration); } foreach (var unit in units) { foreach (var positionLog in unit.PositionsLog.Where(p => p.Iteration == ind)) { iteration.UnitLogs.Add(new UnitLog(unit.Id, positionLog.X, positionLog.Y, positionLog.Index)); } } } return(result); }
public double CalculateTotalScore(SimulationResult result) { //return (result.ReachedToTheEnd > 0 ? (result.ReachedToTheEnd) : 0) * 30.0 + // -Math.Pow(result.TotalPrice / (_preferredMoneyToSpend / 3.0), 4); return((result.DamagesToEnemyBase > 0 ? (Math.Min(result.DamagesToEnemyBase, 50)) : 0) * 30.0 + -Math.Pow(result.TotalPrice / (_preferredMoneyToSpend / 3.0), 4)); }
public void MeanRevertingModel() { var testDate = new DateTime(2015, 12, 1); var graph = new SimulationGraph(StorageLocation.Host, testDate); var identifiers = CreateTestWeightsProvider(graph.Context, WeightsType.Cholesky); var factor = graph.RegisterFactor <MeanRevertingNormal>(identifiers[0]); var runner = graph.ToSimulationRunner(); // prepare to simulate runner.Prepare(); var intervals = graph.Context.Settings.SimulationIntervals; var percentiles = new double[] { 1, 10, 50, 90, 99 }; var result = new SimulationResult(percentiles.Select(p => new PercentileMeasure(p))); // simulate to the first time point; factors will hold values used to simulate across the specified interval //VectorAccelerator.Plot.PlotHelper.QuickPlot(new double[] { 1, 2, 3 }, new double[] { 1.2, 5.6, 2.3 }); while (runner.StepNext()) { var values = NMath.Percentiles(factor.Value, percentiles).ToList(); } }
private static void WriteActualAndSimulationResults(PipExecutionData data, SimulationResult actualSimulation) { // write results actual File.WriteAllLines(resultsFormat.FormatWith("actual.durations.csv"), data.Spans.Where(ps => data.GetPipType(ps.Id) == PipType.Process).Select(ps => string.Join(",", data.GetName(ps.Id), ps.Duration.ToMinutes().ToString()))); File.WriteAllLines(resultsFormat.FormatWith("actual.durations.txt"), data.Spans.Select(ps => ps.Duration.ToMinutes().ToString())); File.WriteAllLines(resultsFormat.FormatWith("actual.starts.txt"), data.Spans.Select(ps => ps.StartTime.ToMinutes().ToString())); File.WriteAllLines(resultsFormat.FormatWith("actual.ends.txt"), data.Spans.Select(ps => ps.EndTime.ToMinutes().ToString())); // write simulation actual File.WriteAllLines(resultsFormat.FormatWith("actualSimulation.durations.txt"), actualSimulation.GetSpans().Select(ps => ps.Duration.ToMinutes().ToString())); File.WriteAllLines(resultsFormat.FormatWith("actualSimulation.starts.txt"), actualSimulation.GetSpans().Select(ps => ps.StartTime.ToMinutes().ToString())); File.WriteAllLines(resultsFormat.FormatWith("actualSimulation.ends.txt"), actualSimulation.GetSpans().Select(ps => ps.EndTime.ToMinutes().ToString())); File.WriteAllLines(resultsFormat.FormatWith("heights.txt"), data.Spans.Where(ps => data.GetPipType(ps.Id) == PipType.Process) .Select(ps => data.DataflowGraph.GetNodeHeight(ps.Id)) .GroupBy(i => i) .OrderBy(g => g.Key) .Select(g => $"Height: {g.Key}, Count: {g.Count()}")); // information on each process during simulation string csvFormat = "{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}"; File.WriteAllLines(resultsFormat.FormatWith("actualSimulation.txt"), new string[] { csvFormat.FormatWith("Id", "Thread", "Minimum Start Time", "Start Time", "End Time", "Duration", "Incoming", "Outgoing") }.Concat(actualSimulation.GetSpans().Select(ps => csvFormat.FormatWith( ps.Id.Value, ps.Thread, actualSimulation.MinimumStartTimes[ps.Id].ToMinutes(), ps.StartTime.ToMinutes(), ps.EndTime.ToMinutes(), ps.Duration.ToMinutes(), data.DataflowGraph.GetIncomingEdgesCount(ps.Id), data.DataflowGraph.GetIncomingEdgesCount(ps.Id))))); }
/// <summary> /// Exports the results to the specified path. /// </summary> /// <param name="path"></param> /// <param name="result"></param> private void ExportResults(string path, SimulationResult result) { //Dump snapshots if enabled if (_conf.ExportSnapshots) { var snapshotsFile = new StreamWriter(path + "/snapshots.csv", false); var csv = new CsvWriter(snapshotsFile); csv.Configuration.Delimiter = ";"; csv.WriteHeader <StatisticSnapshot>(); csv.NextRecord(); csv.WriteRecords(_statisticSnapshots); csv.NextRecord(); csv.Flush(); snapshotsFile.Flush(); } //Dump routing tables if enabled if (_conf.EnableDumpRoutingTables) { _constellation.PrintRoutingTables(path); } ResultOutputter.DumpResults(new List <SimulationResult> { result }, path, "/statistics.txt"); _conf.ExportConfiguration(path); }
public void Test_RunWithSimpleCharacters() { List <Character> characters = new List <Character>(); characters.Add( builder.WithBasicStats("helga", 100, 7).Build() ); List <Character> enemies = new List <Character>(); enemies.Add( builder.WithBasicStats("hugo", 50, 20).Build() ); SimulationResult result = Engine.Simulate( characters, enemies, true, CombatBehavior.Default(), CombatBehavior.Random() ); Assert.False(result.PartyVictorious); Assert.True(someoneIsAlive(result.Enemies)); Assert.False(someoneIsAlive(result.Party)); }
public void CallSimulationEnded(SimulationResult result) { if (this.SimulationEnded != null) { this.SimulationEnded(new SimulationEndedEventArgs(result)); } }
/// <summary> /// Starts backtesting /// </summary> private void RunBackTests() { if (_candles == null || _candles.Count == 0) { ErrorHelper.DisplayErrorMessage("Not enough data to run the simulation"); return; } int i = 0; var strategy = TradingStrategy; foreach (var candle in _candles) { var temp = _candles.Take(i++); strategy.OnTick(temp.ToList()); } var pair = chartSelector.SelectedPair; var res = strategy.GetResult(); var nbUnitsItem2 = res.BalanceItem1 * _candles.Last().Close; lblResult.Text = string.Format("{0:0.00} {3} - {1:0.00} {4} - Total: {2:0.00} {5}", res.BalanceItem2, res.BalanceItem1, res.BalanceItem2 + nbUnitsItem2, pair.Item2, pair.Item1, pair.Item2); var actions = strategy.Actions; var simRes = new SimulationResult { Actions = actions }; chartCtrl.NotifySimulationResult(simRes); }
public void Test_VeryLongRun() { List <Character> characters = new List <Character>(); characters.Add( builder.WithBasicStats("helga", (long)1.0E6, 1).Build() ); List <Character> enemies = new List <Character>(); enemies.Add( builder.WithBasicStats("hugo", (long)5.0E5, 4).Build() ); SimulationResult result = Engine.Simulate( characters, enemies, true, CombatBehavior.Default(), CombatBehavior.Random() ); Assert.False(result.PartyVictorious); Assert.True(someoneIsAlive(result.Enemies)); Assert.False(someoneIsAlive(result.Party)); }
static SimulationResult SimulateRun(RealProductionSimulator productionSimulator) { var result = new SimulationResult(); productionSimulator.Controller.RealTime = -300; var plannedRealProcessingTime = GetPlanedTime(productionSimulator.Controller.ProductionState.FutureProductionPlan.Count); while (productionSimulator.Controller.ProductionState.FutureProductionPlan.Count > 0) { productionSimulator.NextStep(); //Console.WriteLine(productionSimulator.Controller.StepLog.Last()); //Console.WriteLine($"{productionSimulator.Controller.RealTime}; {productionSimulator.Controller.Delay}; {productionSimulator.Controller.ProductionState.FutureProductionPlan.Count}"); if (productionSimulator.Controller.Delay > 0 && result.FirstDelayProductionPlanCount == 0) { result.FirstDelayProductionPlanCount = productionSimulator.Controller.ProductionState.FutureProductionPlan.Count; } if (productionSimulator.Controller.RealTime <= plannedRealProcessingTime) { result.PlannedTimeProductionPlanCount = productionSimulator.Controller.ProductionState.FutureProductionPlan.Count; } } // problem with last step of async controller bool missingGet = productionSimulator.Controller.ProductionState.ProductionHistory.Count > 64; // TODO: add constant result.DelayTime = productionSimulator.Controller.Delay; return(result); }
private static void CalculateFaRRaw(long[] simulationsIds, string path) { var result = new List <SimulationResult>(); using (var dbContext = GetDbContext()) { var periods = dbContext.Periods.ToArray(); foreach (var simulationId in simulationsIds) { var lossSimulation = dbContext.LossSimulations.Single(q => q.Id == simulationId); var simulatedFaR = dbContext.FileKnowledgeables.Where(q => q.HasReviewed && q.TotalKnowledgeables < 2 && q.LossSimulationId == simulationId). GroupBy(q => q.PeriodId). Select(q => new { Count = q.Count(), PeriodId = q.Key }) .ToArray(); var simulationResult = new SimulationResult() { LossSimulation = lossSimulation }; foreach (var simulatedFaRPeriod in simulatedFaR) { simulationResult.Results.Add((simulatedFaRPeriod.PeriodId, simulatedFaRPeriod.Count)); } simulationResult.Results.AddRange(periods.Where(q => !simulationResult.Results.Any(r => r.PeriodId == q.Id)).Select(q => (q.Id, 0.0))); simulationResult.Results = simulationResult.Results.OrderBy(q => q.PeriodId).ToList(); result.Add(simulationResult); } } }
public void Save(Guid simulationId, SimulationResult simulationResult) { var dbModel = ConvertToDb(simulationId, simulationResult); _context.SimulationResults.Add(dbModel); _context.SaveChanges(); }
public async Task ExecuteAsync() { var stopwatch = Stopwatch.StartNew(); const long AmountOfRuns = 10000000; var simulationTasks = new List <Task <SimulationRunResult> >(); for (var i = 0; i < AmountOfRuns; i++) { simulationTasks.Add(_simulationService.RunSimulationAsync()); } var simulationResults = await Task.WhenAll(simulationTasks); var foundSixThree = simulationResults.Sum(f => f.AmountSixThreeCombinations); var foundSevenTwo = simulationResults.Sum(f => f.AmountSevenTwoCombinations); var totalRuns = simulationResults.Length; var result = new SimulationResult(totalRuns, foundSixThree, foundSevenTwo); _consoleWriter.WriteLine($"Calculation took {stopwatch.Elapsed.Minutes} Minutes.", ConsoleColor.Black, ConsoleColor.Green); _consoleWriter.WriteLine( $"Total Runs: {result.TotalRuns}. Seven Twos: {result.SevenTwoCombinationAmount}. Six Threes: {result.SixThreeCombinationAmount}.", ConsoleColor.Black, ConsoleColor.DarkYellow); _consoleWriter.WriteLine(result.PercentDescriptionOfSevenTwo, ConsoleColor.Black, ConsoleColor.Yellow); _consoleWriter.WriteLine(result.PercentDescriptionOfSixThree, ConsoleColor.Black, ConsoleColor.Yellow); }
private static void SimulateActual(PipExecutionData data, int actualConcurrency, MultiWriter writers) { // simulate with actual concurrency Console.WriteLine("Simulating actual build"); SimulationResult actualSimulation = new SimulationResult(data, data.AggregateCosts); actualSimulation.Simulate(actualConcurrency); Console.WriteLine("Done"); Console.WriteLine(); WriteActualAndSimulationResults(data, actualSimulation); writers.WriteLine("Edge Count: {0}", data.DataflowGraph.EdgeCount); writers.WriteLine("Pip Type Counts:"); foreach (var pipType in EnumTraits <PipType> .EnumerateValues()) { writers.WriteLine("{0}: {1}", data.PipTypeCounts[(int)pipType].ToString().PadLeft(10), pipType); } writers.WriteLine("Processes with timing information:{0} ", data.DataflowGraph.Nodes.Where(node => data.GetPipType(node) == PipType.Process && data.StartTimes[node] != 0).Count()); writers.WriteLine("Actual Total Build Time: {0} min", data.TotalDuration.ToMinutes()); writers.WriteLine("Actual Concurrency: {0}", data.ActualConcurrency); writers.WriteLine("Simulated total build time (using actual concurrency): {0} min", actualSimulation.TotalTime.ToMinutes()); // write down info for each critical path ulong criticalPathCost = WriteCriticalPathToResult(writers, data, actualSimulation); }
private SimulationResult calculateExtinction(SpectrumUnit freq, SimulationParameters parameters) { var pulseFourier = this.pulse.FourierPulse.Select(x => x.Transform(freq, parameters.TimeStep).Magnitude).ToArray(); double extinction = this.iterator.Sum(parameters.Indices, (i, j, k) => { var medium = parameters.Medium[i, j, k]; if (!medium.IsBody) { return(0); } Complex eps = medium.Permittivity.GetPermittivity(freq); double pulseMultiplier = 1 / pulseFourier[j]; var complex = eps.Imaginary * pulseMultiplier * this.fields.FourierField[i, j, k].Transform(freq, parameters.TimeStep).Norm; return(complex); }); double area = this.calculateArea(parameters); var resu = new SimulationResult(); double waveNumber = freq.ToType(SpectrumUnitType.WaveNumber); extinction = extinction * parameters.CellSize * waveNumber; double areamult = 1 / area; resu.EffectiveCrossSectionAbsorption = (extinction * areamult); resu.CrossSectionAbsorption = extinction * Math.Pow(parameters.CellSize, 2); return(resu); }
private void PresentarResultados(SimulationResult results, bool error = false) { var resultados = results as ResultadoSimulador; lbTiempoSimulacion.Invoke(new Action(() => { lbTiempoSimulacion.Text = resultados.SimulationTime.ToString(); })); lbTiempoSimulado.Text = "<= " + resultados.SimulatedTime.ToString(); lbSumatoriaTiempoPermanenciaSistema.Text = resultados.SumatoriaTiempoPermanenciaSistema.ToString(); lbSumatoriaVehiculosAtendidos.Text = $"{resultados.SumatoriaVehiculosAtendidos} (Motocicletas: {resultados.SumatoriaMotocicletasAtendidas}, Automóviles: {resultados.SumatoriaAutomovilesAtendidos}, Camionetas: {resultados.SumatoriaCamionetasAtendidas})"; lbTiempoPromedioPermanenciaSistema.Text = resultados.TiempoPromedioPermanenciaSistema.ToString(); lbMostrarDatos.Text = resultados.ShowableStateVectorsFromTo; lbTiempoSimulacion.Text = resultados.SimulationTime.ToString(); dgvVector.DataSource = _simulador.GetShowableStateVectorsAsDataTable(); lbRowCount.Text = dgvVector.Rows.Count.ToString(); foreach (var item in _simulador.GetShowableStateVectorDataGridConfiguration()) { dgvVector.Columns[item.Key].DefaultCellStyle.Alignment = (DataGridViewContentAlignment)item.Value; } if (error) { if (dgvVector.Rows.Count > 0) { dgvVector.Rows[dgvVector.Rows.Count - 1].DefaultCellStyle.ForeColor = Color.Red; } } mainTabControl.SelectedIndex = 1; }
public double CalculateTotalScore(SimulationResult result) { var _preferredMoneyToSpend = Math.Max((result.ArcherTowersCount + result.CannonTowersCount) * 150, 300); return((result.ReachedToTheEnd > 0 ? 1 : 0) * 100.0 + Math.Pow(CalculateDeadScore(result), 1.1) * 10.0 + -Math.Pow(result.TotalPrice / (_preferredMoneyToSpend / 3.0), 4)); }
public SummarySectionViewModel(IReadOnlyList<IAsyncResult<IResultAnalyzer>> analyzers, SimulationResult result) { this.analyzers = analyzers; this.result = result; this.Groups = new ReadOnlyCollection<SummaryGroupViewModel>( analyzers.Select(a => new SummaryGroupViewModel(a, result)).ToList()); }
public OutputWindow(SimulationResult simulation) { InitializeComponent(); txtMin.Text = simulation.MinValue.ToString(); txtMax.Text = simulation.MaxValue.ToString(); txtMean.Text = simulation.MeanValue.ToString(); txtStdDev.Text = simulation.StdDev.ToString(); }
private static void CalculateWorkloadRaw(long[] simulationsIds, int topReviewers, string path) { var result = new List <SimulationResult>(); using (var dbContext = GetDbContext()) { var periods = dbContext.Periods.ToArray(); var pullRequests = dbContext.PullRequests.ToDictionary(q => q.Number); foreach (var simulationId in simulationsIds) { var lossSimulation = dbContext.LossSimulations.Single(q => q.Id == simulationId); var simulatedSelectedReviewers = dbContext.RecommendedPullRequestReviewers.Where(q => q.LossSimulationId == simulationId).ToArray(); var simulatedWorkload = new Dictionary <long, Dictionary <string, int> >(); foreach (var simulatedSelectedReviewer in simulatedSelectedReviewers) { var prDateTime = pullRequests[(int)simulatedSelectedReviewer.PullRequestNumber].CreatedAtDateTime; var period = periods.Single(q => q.FromDateTime <= prDateTime && q.ToDateTime >= prDateTime); if (!simulatedWorkload.ContainsKey(period.Id)) { simulatedWorkload[period.Id] = new Dictionary <string, int>(); } if (!simulatedWorkload[period.Id].ContainsKey(simulatedSelectedReviewer.NormalizedReviewerName)) { simulatedWorkload[period.Id][simulatedSelectedReviewer.NormalizedReviewerName] = 0; } simulatedWorkload[period.Id][simulatedSelectedReviewer.NormalizedReviewerName]++; } var simulationResult = new SimulationResult() { LossSimulation = lossSimulation }; foreach (var simulatedWorkloadPeriod in simulatedWorkload) { var periodId = simulatedWorkloadPeriod.Key; var simulatedTop10Workload = simulatedWorkloadPeriod.Value.OrderByDescending(q => q.Value).Take(10).Sum(q => q.Value); var value = simulatedTop10Workload; simulationResult.Results.Add((periodId, value)); } simulationResult.Results.AddRange(periods.Where(q => !simulationResult.Results.Any(r => r.PeriodId == q.Id)).Select(q => (q.Id, 0.0))); simulationResult.Results = simulationResult.Results.OrderBy(q => q.PeriodId).ToList(); result.Add(simulationResult); } } result = result.OrderBy(q => q.LossSimulation.KnowledgeShareStrategyType).ToList(); Write(result, Path.Combine(path, "workload_raw.csv")); }
/// <summary> /// Initialize and execute the simulation /// </summary> /// <param name="token"></param> /// <param name="agentId"></param> public void Run(IJobCancellationToken token, long?agentId = null) { try { Initialize(agentId); if (Agent == null) { return; } Simulate(token); using (var DbContext = new DeepQStockContext()) { var agentParameters = DbContext.DeepRLAgentParameters.Single(a => a.Id == agentId.Value); agentParameters.Status = AgentStatus.Completed; // We need this assignation here because the simulation complete when the current state is null, and // now we need to store some of the values of the last State. CurrentState = PreviousState; var result = new SimulationResult() { AgentId = Agent.Parameters.Id, AnnualProfits = AnnualProfits, AnnualRent = AnnualRent, NetCapital = NetCapital, Profits = Profits, Earnings = Earnings, Symbol = Agent.Parameters.StockExchange.Symbol, CreatedOn = DateTime.Now, TransactionCost = TransactionCost }; DbContext.SimulationResults.Add(result); DbContext.SaveChanges(); RedisManager.Publish(RedisPubSubChannels.OnSimulationComplete, JsonConvert.SerializeObject(new OnSimulationComplete() { AgentId = agentParameters.Id })); } } catch (JobAbortedException) { } catch (Exception e) { Console.WriteLine(e); } finally { Shutdown(); } }
public SummaryGroupViewModel(IAsyncResult<IResultAnalyzer> analyzer, SimulationResult result) { this.Name = "Loading ..."; this.LoadState = AsyncState.Running; this.analyzer = analyzer; this.result = result; this.dispatcher = Dispatcher.CurrentDispatcher; analyzer.AddCallback(x => HandleAnalyzerLoaded()); }
public double CalculateTotalScore(SimulationResult result) { var totalCount = result.ArcherTowersCount + result.CannonTowersCount; var _preferredMoneyToSpend = totalCount * 180 + Math.Max(0, (totalCount - 20) * 250); _preferredMoneyToSpend = Math.Max(500, _preferredMoneyToSpend); return((result.DamagesToEnemyBase > 0 ? (Math.Min(result.DamagesToEnemyBase, 50)) : 0) * 30.0 + -Math.Pow(result.TotalPrice / (_preferredMoneyToSpend / 3.0), 4)); }
public SimulationResult SimulateFlight(Airport fromAirport, Airport toAirport, Aircraft aircraft) { var distance = Distance(fromAirport.Latitude, fromAirport.Longitude, toAirport.Latitude, toAirport.Longitude, 'K'); var r = new SimulationResult(); r.Distance = (int)distance; r.FuelConsumption = (int)(aircraft.FuelConsumption * distance / 100); r.Timespan = new TimeSpan(0, 0, (int)distance * 3600 / aircraft.Speed); return(r); }
public void RefreshSimResult(SimulationResult res) { lblMinDps.Text = res.MinDps.ToString(); lblMaxDps.Text = res.MaxDps.ToString(); lblAvrgDps.Text = res.AvrgDps.ToString(); lblMinDps.Refresh(); lblMaxDps.Refresh(); lblAvrgDps.Refresh(); }
public void CalculateFaRReduction(long actualId, long[] simulationsIds, string path) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var result = new List <SimulationResult>(); using (var dbContext = GetDbContext()) { var actualFaR = dbContext.FileKnowledgeables.Where(q => q.HasReviewed && q.TotalKnowledgeables < 2 && q.LossSimulationId == actualId). GroupBy(q => q.PeriodId). Select(q => new { Count = q.Count(), PeriodId = q.Key }) .ToArray(); var lastPeriod = actualFaR.Max(q => q.PeriodId); actualFaR = actualFaR.Where(q => q.PeriodId != lastPeriod) .ToArray(); foreach (var simulationId in simulationsIds) { var lossSimulation = dbContext.LossSimulations.Single(q => q.Id == simulationId); var simulatedFaR = dbContext.FileKnowledgeables.Where(q => q.HasReviewed && q.TotalKnowledgeables < 2 && q.LossSimulationId == simulationId). GroupBy(q => q.PeriodId). Select(q => new { Count = q.Count(), PeriodId = q.Key }) .ToArray(); var simulationResult = new SimulationResult() { LossSimulation = lossSimulation }; foreach (var simulatedFaRPeriod in simulatedFaR) { var actualValue = actualFaR.SingleOrDefault(q => q.PeriodId == simulatedFaRPeriod.PeriodId); if (actualValue == null) { continue; } var value = CalculateIncreasePercentage(simulatedFaRPeriod.Count, actualValue.Count); simulationResult.Results.Add((simulatedFaRPeriod.PeriodId, value)); } simulationResult.Results.AddRange(actualFaR.Where(q => !simulationResult.Results.Any(r => r.PeriodId == q.PeriodId)).Select(q => (q.PeriodId, 100.0))); result.Add(simulationResult); } } Write(result, Path.Combine(path, "far.csv")); }
// Answers whether you should reset, assuming that reset times for the next segments were calculated already private bool ShouldReset(int segment, TimeSpan currentTime, TimeSpan targetPBTime) { SimulationResult result = GetSimulationResult(segment, currentTime); // If we play a no-reset run, then with a probability of (1 - pbProbability) it would reset. // If we reset now, we will save (on average) AverageResetTimeSave. // But we can lose the time to get a PB (if we reset a run that would otherwise PB). TimeSpan resetTimeSave = result.AverageResetTimeSave; TimeSpan pbTimeLoss = Multiply(targetPBTime, result.PbProbability); bool shouldReset = (resetTimeSave > pbTimeLoss); return(shouldReset); }
public SimulationResultViewModel Create(SimulationResult result) { var analyzerList = loadAnalyzersService.Load(); return new SimulationResultViewModel( new ISectionViewModel[] { new EquityViewModel(result), new SummarySectionViewModel(analyzerList,result), new OutputViewModel(result) }, new IstLight.Excel.Concrete.SimulationResultExcelExporter()); }
private SimulationResult UpdateResult(SimulationResult intermediateResult, Deck winningDeck) { if (winningDeck.IsPlayer) { intermediateResult.NumberOfPlayerWins++; } else { intermediateResult.NumberOfPlayerLosses++; } return(intermediateResult); }
private void UpdateSimulationResults(int segment, TimeSpan newResetTime) // Call when we calculated a reset time for a split { // calculate the probabilities for each possible case int attemptsCount = segments[segment].Count; TimeSpan minTime = minSplitTimes.ElementAtOrDefault(segment - 1); TimeSpan maxTime = maxSplitTimes.ElementAtOrDefault(segment - 1); for (TimeSpan curTime = minTime; curTime <= maxTime; curTime += TimeSpan.FromMilliseconds(100)) { // calculating the probabilities: if at the end of segment {segment - 1} the timer shows {curTime}, what are our chances? SimulationResult simulationResult = new SimulationResult(); TimeSpan timeBeforeResetSum = TimeSpan.Zero; // calculating average time before reset foreach (TimeSpan?segmentAttempt in segments[segment]) { TimeSpan?timeIfNotReset = null; if (segmentAttempt != null) { timeIfNotReset = curTime + segmentAttempt; } if (segmentAttempt == null || timeIfNotReset >= newResetTime) { // it's a reset TimeSpan timeBeforeReset = newResetTime - curTime + TimeSpan.FromSeconds(settings.TimeToReset); timeBeforeResetSum += timeBeforeReset; } else { if (segment == segments.Length - 1) { // This was the last split. We would've reset if it didn't PB. simulationResult.PbProbability += 1; } else { SimulationResult whatHappenedNext = GetSimulationResult(segment, timeIfNotReset.Value); timeBeforeResetSum += whatHappenedNext.AverageResetTimeSave; simulationResult.PbProbability += whatHappenedNext.PbProbability; } } } // we're calculating the average of all the possible cases - have to divide by attemptsCount. simulationResult.PbProbability /= attemptsCount; simulationResult.AverageResetTimeSave = Divide(timeBeforeResetSum, attemptsCount); SetSimulationResult(segment - 1, curTime, simulationResult); } }
public EquityRowViewModel(SimulationResult result, int barIndex) { var resultQuote = result[barIndex]; this.Date = resultQuote.Date; this.Cash = resultQuote.Cash; this.Interest = resultQuote.Interest; this.Total = resultQuote.Equity(result.SyncTickers); this.Portfolio = Total - Cash; this.Commissions = resultQuote.Transactions.Select(t => t.Commission).Sum(); this.TransactionCount = resultQuote.Transactions.Count; this.TransactionTotal = resultQuote.Transactions.Select(t => t.CashFlow).Sum(); this.Bar = barIndex + 1; }
private void SimulationDryRun(out SimulationResult simResult) { simResult = default; simResult.Active = false; if (_gridPhysicsComponent == null || _gridPhysicsComponent.IsStatic || !TryFindEdge(out simResult.FindEdgeResult)) { return; } using (VRage.Library.Collections.PoolManager.Get(out HashSet <RailPhysicsNode> forRemoval)) { PhysicsNode.GetNeighbors(forRemoval); // Add neighbor edges to the nearby node var searchNode = simResult.FindEdgeResult.EdgeFactor < 0.5 ? simResult.FindEdgeResult.Edge.From : simResult.FindEdgeResult.Edge.To; foreach (var edge in searchNode.Edges) { var physicsNode = RailSegmentFor(edge)?.PhysicsNode; if (physicsNode != null && !forRemoval.Remove(physicsNode)) { PhysicsNode.Link(physicsNode); } } // Don't remove anything within two hops foreach (var neighbor1 in searchNode.Neighbors) { foreach (var edge in neighbor1.Edges) { if (forRemoval.Count == 0) { break; } var physicsNode = RailSegmentFor(edge)?.PhysicsNode; if (physicsNode != null) { forRemoval.Remove(physicsNode); } } } foreach (var removal in forRemoval) { PhysicsNode.Unlink(removal); } } simResult.Active = true; ref var edgeResult = ref simResult.FindEdgeResult;
static void RunSimulations(Dictionary <string, RealProductionSimulator> simulationsDict, List <SimulationResult> simulationResults) { int simulationCounter = 0; foreach (var simulation in simulationsDict) { var simulationName = simulation.Key; var simulator = simulation.Value; SimulationResult res = SimulateRun(simulator); res.Name = simulationName; simulationResults.Add(res); Console.WriteLine(res); } }
public static SimulationResultResponse Convert(SimulationResult result) { var personResults = result.PersonResults.Select(x => { return(new PersonResultResponse() { VariantAmount = x.VariantAmount, BaseAmount = x.BaseAmount, Person = Convert((MaternityBenefitsPerson)x.Person) }); }).ToList(); return(new SimulationResultResponse() { PersonResults = personResults }); }
public static SimulationResult Simulate(Deck deck1, Deck deck2, int maxTurnsPerGame = 100, int maxSearchDepth = 16, int maxTargetsCount = 2) { var stopwatch = new Stopwatch(); stopwatch.Start(); var result = new SimulationResult(); while (result.Deck1WinCount < 2 && result.Deck2WinCount < 2) { SimulateGame(deck1, deck2, result, maxTurnsPerGame, maxSearchDepth, maxTargetsCount); } stopwatch.Stop(); result.Duration = stopwatch.Elapsed; return result; }
private static void SimulateGame(Deck deck1, Deck deck2, SimulationResult result, int maxTurnsPerGame, int maxSearchDepth, int maxTargetsCount) { var stopwatch = new Stopwatch(); var game = new Game(GameParameters.Simulation(deck1, deck2, new SearchParameters(maxSearchDepth, maxTargetsCount, SearchPartitioningStrategies.SingleThreaded))); game.Ai.SearchStarted += delegate { result.TotalSearchCount++; stopwatch.Start(); }; game.Ai.SearchFinished += delegate { stopwatch.Stop(); if (stopwatch.Elapsed > result.MaxSearchTime) { result.MaxSearchTime = stopwatch.Elapsed; } stopwatch.Reset(); }; game.Start(numOfTurns: maxTurnsPerGame); result.TotalTurnCount += game.Turn.TurnCount; if (game.Players.BothHaveLost) return; if (game.Players.Player1.Score > -game.Players.Player2.Score) { result.Deck1WinCount++; return; } result.Deck2WinCount++; return; }
public IAsyncResult<IReadOnlyList<KeyValuePair<string, string>>> Analyze(SimulationResult result) { return executor.SafeExecuteAsync<IReadOnlyList<KeyValuePair<string, string>>>(engine => ((KeyValuePair<string,string>[])engine.GetVariable("Analyze")(result)).AsReadOnlyList()); }
public SimulationException(SimulationResult result, string message) : base(message) { this.result = result; }
public EquityViewModel(SimulationResult result) { this.result = result; this.Rows = result.Select((x, i) => new EquityRowViewModel(result, i)).ToArray(); }
public OutputViewModel(SimulationResult result) { this.Rows = result.Select((q, i) => new OutputRowViewModel(q.Output, i, q.Date)).Where(r => r.Text != null); }