Skip to content

Commit

Permalink
displaying first results of the monte carlo simulation
Browse files Browse the repository at this point in the history
  • Loading branch information
mario meltzow committed Aug 21, 2024
1 parent 55e1fd1 commit 72689b9
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 25 deletions.
14 changes: 5 additions & 9 deletions src/app/components/layout/layout.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,24 +75,20 @@ export class LayoutComponent implements OnInit {
selectedDatasource: number | undefined;

onDatasourceChange(event: any) {
this.storageService.getDatasource(event.value).then((dataset: Datasource) => {
this.storageService.getDatasource(event.value).then(async (dataset: Datasource) => {
this.toastr.success('Selected datasource: ' + dataset.name);
this.selectedDatasource = dataset.id!;
this.storageService.saveAppSettings({selectedDatasourceId: dataset.id!});
await this.storageService.saveAppSettings({selectedDatasourceId: dataset.id!});
});
}

ngOnInit(): void {
this.refreshDatasources();
}

refreshDatasources(): void {
this.storageService.getAllDatasources().then((datasource: Datasource[]) => {
this.datasources = datasource;
if (this.datasources.length > 0) {
this.selectedDatasource = this.datasources[0].id!;
}
});
async refreshDatasources() {
this.datasources = await this.storageService.getAllDatasources();
this.selectedDatasource = (await this.storageService.getAppSettings()).selectedDatasourceId;
}

async login() {
Expand Down
15 changes: 15 additions & 0 deletions src/app/components/monte-carlo/monte-carlo-page.component.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
<div>
<h1>Monte Carlo Simulation Results</h1>
<h2>Steps</h2>
<ul>
<li>
Step 1: Read the throughput value from the last 20 days
</li>
<li>
Step 2: Simulate one time the next 14 days: Select 14 random values from step 1 and compute the sum of them
</li>
<li>
Step 3: repeat Step 2 10.000 times
</li>
<li>
Step 4: Plot the histogram of the 10.000 values from step 3
</li>
</ul>
<canvas baseChart
[data]="chartData"
[options]="chartOptions"
Expand Down
55 changes: 40 additions & 15 deletions src/app/components/monte-carlo/monte-carlo-page.component.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Component, OnInit } from '@angular/core';
import {Component, OnInit, ViewChild} from '@angular/core';
import { ChartData, ChartOptions } from 'chart.js';
import { StorageService } from '../../services/storage.service';
import {BaseChartDirective} from "ng2-charts";
import {BaseChartDirective} from 'ng2-charts';

@Component({
selector: 'app-monte-carlo-page',
Expand All @@ -14,6 +14,10 @@ import {BaseChartDirective} from "ng2-charts";
})
export class MonteCarloPageComponent implements OnInit {
results: number[] = [];
counts: number[] = [];

@ViewChild(BaseChartDirective) chart?: BaseChartDirective;

chartData: ChartData<'bar'> = {
labels: [],
datasets: [
Expand All @@ -30,10 +34,17 @@ export class MonteCarloPageComponent implements OnInit {
responsive: true,
scales: {
x: {

title: {
display: true,
text: 'Sum Value'
}
},
y: {
beginAtZero: true
beginAtZero: true,
title: {
display: true,
text: 'Occurrences'
}
}
}
};
Expand All @@ -42,39 +53,53 @@ export class MonteCarloPageComponent implements OnInit {

async ngOnInit(): Promise<void> {
const simulationResult = await this.runSimulation(1000);
this.results = simulationResult.results;
console.log(`Counts for each sum: ${simulationResult.counts}`);
this.results = Array.from(simulationResult.keys()).sort((a, b) => a - b);
this.counts = this.results.map(result => simulationResult.get(result) || 0);
this.updateChartData();
}

updateChartData(): void {
// Update chart data
this.chartData.labels = this.results.map((_, index) => index.toString());
this.chartData.datasets[0].data = this.results;
this.chartData.datasets[0].data = this.counts;
this.chart?.update();
}

private async runSimulation(number: number): Promise<{ results: number[], counts: number[] }> {
private async runSimulation(number: number): Promise<Map<number, number>> {
// Step 1: Read the throughputs from the last 20 days
const throughputs = await this.getThroughputsFromLast20Days();

const results: number[] = [];
const counts: number[] = new Array(number).fill(0);
const sumFrequency: Map<number, number> = new Map();

for (let i = 0; i < number; i++) {
// Step 2: Select 14 random values and sum them
const sum = this.getRandomSum(throughputs, 14);
// Step 3: Save the sum and increment the counter
results.push(sum);
counts[sum] = (counts[sum] || 0) + 1;
sumFrequency.set(sum, (sumFrequency.get(sum) || 0) + 1);
}

// Step 4: Return the results and the counts
return { results, counts };
return sumFrequency;
}

private async getThroughputsFromLast20Days(): Promise<number[]> {
const throughputEntries = await this.storageService.getThroughputData();
const last20DaysThroughputs = throughputEntries
.sort((a, b) => b.date.getTime() - a.date.getTime())
.slice(0, 20)
.map(entry => entry.throughput);
const today = new Date();
const last20DaysThroughputs: number[] = [];

for (let i = 0; i < 20; i++) {
const date = new Date(today);
date.setDate(today.getDate() - i);
const entry = throughputEntries.find(entry =>
entry.date.getFullYear() === date.getFullYear() &&
entry.date.getMonth() === date.getMonth() &&
entry.date.getDate() === date.getDate()
);
last20DaysThroughputs.push(entry ? entry.throughput : 0);
}

return last20DaysThroughputs;
}

Expand Down
2 changes: 1 addition & 1 deletion src/app/services/storage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ export class StorageService {

async getAppSettings(): Promise<AppSettings> {
this.dbService.selectDb(dbConfigCore.name);
return firstValueFrom(this.dbService.getAll<AppSettings>(TableNames.APP_SETTINGS)).then(datasets => datasets[0]);
return firstValueFrom(this.dbService.getAll<AppSettings>(TableNames.APP_SETTINGS)).then(settings => settings[0]);
}

async deleteIssueDatabase() {
Expand Down

0 comments on commit 72689b9

Please sign in to comment.