A local-first personal finance app
:bar_chart: Monte carlo performance improvement (#8988)
Michael Clarkaa8df6eca943
diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsxindex 7657b1ee42..3bd4e7710b 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import { useParams } from 'react-router';@@ -106,7 +106,9 @@ export function MonteCarlo() {setSelectionsInitialized(true);}, [selectionsInitialized, isLoading, widget?.meta]);- const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();+ // Only the stable `mutate` is kept: the mutation result is a new object+ // every render, and closing over it would defeat memoisation below+ const { mutate: updateWidget } = useUpdateDashboardWidgetMutation();async function onSaveWidget() {// The save button only renders when a widget exists@@ -114,7 +116,7 @@ export function MonteCarlo() {return;}- updateDashboardWidgetMutation.mutate(+ updateWidget({widget: {id: widget.id,@@ -149,7 +151,7 @@ export function MonteCarlo() {}const name = newName || t('Monte Carlo Analysis');- updateDashboardWidgetMutation.mutate({+ updateWidget({widget: {id: widget.id,meta: {@@ -160,30 +162,44 @@ export function MonteCarlo() {});};- if (isLoading || !selectionsInitialized) {- return <LoadingIndicator />;- }+ // The simulation is the expensive part of this page (thousands of+ // runs on the main thread), so it is memoised by hand on its actual+ // inputs: view switches, run selection and other UI state must not+ // re-run it. Nothing runs until the saved config has been loaded+ const simulation = useMemo(() => {+ if (!selectionsInitialized) {+ return null;+ }+ const params = {+ ...resolvedConfig,+ horizonYears: getMonteCarloHorizonYears(resolvedConfig),+ deflateToTodaysMoney: showTodaysMoney,+ };+ return { params, result: runMonteCarloSimulation(params) };+ }, [resolvedConfig, showTodaysMoney, selectionsInitialized]);- const simulationParams = {- ...resolvedConfig,- horizonYears: getMonteCarloHorizonYears(resolvedConfig),- deflateToTodaysMoney: showTodaysMoney,- };- const result = runMonteCarloSimulation(simulationParams);+ // The worst-first ranking shared by the runs table and the cashflow+ // view's percentile picker, sorted once per simulation+ const rankedRunIndices = useMemo(+ () =>+ simulation == null+ ? null+ : rankSimulationsWorstFirst(+ simulation.result.endingBalances,+ simulation.result.depletionYearBySimulation,+ ),+ [simulation],+ );- // The cashflow view charts one run picked by percentile of the same- // worst-first ranking the runs table shows- let cashflowRunIndex: number | null = null;- if (resultsView === 'cashflow') {- const rankedRunIndices = rankSimulationsWorstFirst(- result.endingBalances,- result.depletionYearBySimulation,- );- const scenarioRank = Math.round(- cashflowPercentile * (result.simulationCount - 1),- );- cashflowRunIndex = rankedRunIndices[scenarioRank];- }+ // The cashflow view charts one run picked by percentile of the ranking+ const cashflowRunIndex =+ resultsView === 'cashflow' && simulation != null && rankedRunIndices != null+ ? rankedRunIndices[+ Math.round(+ cashflowPercentile * (simulation.result.simulationCount - 1),+ )+ ]+ : null;// The run whose year-by-year detail is on screen: the cashflow view's// scenario, or the drill-in's selection from the runs table@@ -191,14 +207,29 @@ export function MonteCarlo() {resultsView === 'cashflow' ? cashflowRunIndex : selectedRunIndex;// Runs are seeded, so re-running with a capture index reproduces the- // selected run exactly; only computed while a run is being inspected- const runDetailRows =- detailRunIndex != null- ? runMonteCarloSimulation({- ...simulationParams,- captureRunDetail: detailRunIndex,- }).runDetail- : null;+ // selected run exactly; only computed while a run is being inspected,+ // and once per run rather than on every render+ const runDetailRows = useMemo(+ () =>+ simulation == null || detailRunIndex == null+ ? null+ : runMonteCarloSimulation({+ ...simulation.params,+ captureRunDetail: detailRunIndex,+ }).runDetail,+ [simulation, detailRunIndex],+ );++ if (+ isLoading ||+ !selectionsInitialized ||+ simulation == null ||+ rankedRunIndices == null+ ) {+ return <LoadingIndicator />;+ }++ const { result } = simulation;// After a failure the capture continues with synthetic unfunded years// for the cashflow chart; the year-by-year table ends at the failureconst fundedRunDetailRows =@@ -581,6 +612,7 @@ export function MonteCarlo() {/>) : (<MonteCarloRunsTable+ rankedIndices={rankedRunIndices}endingBalances={result.endingBalances}depletionYearBySimulation={result.depletionYearBySimulation}totalWithdrawnBySimulation={result.totalWithdrawnBySimulation}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsxindex ae0795e223..627f87d8bb 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useMemo, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import { Block } from '@actual-app/components/block';@@ -43,13 +43,19 @@ export function MonteCarloCard({const [nameMenuOpen, setNameMenuOpen] = useState(false);const [isCardHovered, setIsCardHovered] = useState(false);- const config = monteCarloConfigFromMeta(meta);+ // Memoised by hand so hovering the card (which toggles state) doesn't+ // re-run thousands of simulations+ const config = useMemo(() => monteCarloConfigFromMeta(meta), [meta]);const resolvedConfig = useResolvedMonteCarloConfig(config);- const result = runMonteCarloSimulation({- ...resolvedConfig,- horizonYears: getMonteCarloHorizonYears(resolvedConfig),- deflateToTodaysMoney: true,- });+ const result = useMemo(+ () =>+ runMonteCarloSimulation({+ ...resolvedConfig,+ horizonYears: getMonteCarloHorizonYears(resolvedConfig),+ deflateToTodaysMoney: true,+ }),+ [resolvedConfig],+ );const endAge = config.currentAge + result.horizonYears;const successPercent = Math.round(result.successRate * 1000) / 10;diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsxindex 3248150c04..8a8414c636 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsx@@ -9,7 +9,6 @@ import { View } from '@actual-app/components/view';import { FinancialText } from '#components/FinancialText';import { PrivacyFilter } from '#components/PrivacyFilter';-import { rankSimulationsWorstFirst } from '#components/reports/reports/monte-carlo/monteCarloSimulation';import { GROUP_HEADING_STYLE } from '#components/reports/reports/monte-carlo/monteCarloStyles';import { useFormat } from '#hooks/useFormat';@@ -35,6 +34,8 @@ export function getRunPercentileOptions(}type MonteCarloRunsTableProps = {+ /** Every run's index, worst outcome first (ranked once by the parent) */+ rankedIndices: number[];endingBalances: Float64Array;depletionYearBySimulation: Int32Array;totalWithdrawnBySimulation: Float64Array;@@ -43,6 +44,7 @@ type MonteCarloRunsTableProps = {};export function MonteCarloRunsTable({+ rankedIndices,endingBalances,depletionYearBySimulation,totalWithdrawnBySimulation,@@ -56,7 +58,7 @@ export function MonteCarloRunsTable({const [page, setPage] = useState(0);const [highlightedRank, setHighlightedRank] = useState<number | null>(null);- const simulationCount = endingBalances.length;+ const simulationCount = rankedIndices.length;// Jump straight to a given percentile of the ranked outcomes (0 = worst,// 1 = best), landing on its page and highlighting the exact run@@ -70,18 +72,20 @@ export function MonteCarloRunsTable({setHighlightedRank(rank);}- const rankedIndices = rankSimulationsWorstFirst(- endingBalances,- depletionYearBySimulation,- );- if (sortOrder === 'best-first') {- rankedIndices.reverse();- }-const pageCount = Math.max(1, Math.ceil(simulationCount / PAGE_SIZE));const currentPage = Math.min(page, pageCount - 1);const pageStart = currentPage * PAGE_SIZE;- const pageIndices = rankedIndices.slice(pageStart, pageStart + PAGE_SIZE);+ // Best-first reads the same ranking from the other end, so no copy of+ // the full list is made for either order+ const pageIndices = Array.from(+ { length: Math.max(0, Math.min(PAGE_SIZE, simulationCount - pageStart)) },+ (_, offset) => {+ const rank = pageStart + offset;+ return rankedIndices[+ sortOrder === 'best-first' ? simulationCount - 1 - rank : rank+ ];+ },+ );return (<View>diff --git a/upcoming-release-notes/monte-carlo-avoid-resimulating.md b/upcoming-release-notes/monte-carlo-avoid-resimulating.mdnew file mode 100644index 0000000000..106661f3e2--- /dev/null+++ b/upcoming-release-notes/monte-carlo-avoid-resimulating.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [MikesGlitch]+---++Make the Monte Carlo report respond faster when switching between the chart, cashflow and runs views