'use client' // SPDX-License-Identifier: GPL-3.0-or-later // Part of the megafund simulator, ported from dfagnan/RBOMatlab (Fagnan et al.), GPL-3.0-or-later; this file is GPL // because it ships in one bundle with lib/megafund/sim.ts. Its source is offered at // udgamlabs.com/tools/megafund#source (files copied by scripts/megafund/sync_source.mjs). // The Open Megafund simulator, running in the reader's browser. Engine: lib/megafund/sim.ts, a port of the lab's // Python sim.py, checked against it fund by fund on the same random stream and against results/step3.json at 10,000 // runs (scripts/megafund/GATE.md). Inputs: lib/megafund/params.json, exported from the lab's parameter files and step 3 // rate sets. Nothing leaves the device and nothing is counted. import { useEffect, useMemo, useRef, useState } from 'react' import { Fund, makeRng, summarise, annualise, type RunResult, type Summary } from '@/lib/megafund/sim' import params from '@/lib/megafund/params.json' type FundId = 'A' | 'B' type SetId = '2012' | 'wong' | 'open' | 'corrected' const STEP = 1000 // runs per click: about a second on a mid-range phone [ESTIMATE]; 10,000 at most const MAX_RUNS = 10000 const SLICE = 200 // runs between screen updates const SEED = 1 const FUNDS: { id: FundId; name: string; line: string }[] = [ { id: 'A', name: 'Fund A', line: 'Sells its drugs once they reach phase 2' }, { id: 'B', name: 'Fund B', line: 'Holds its drugs to approval' }, ] const SETS: { id: SetId; name: string; rates: [string, string, string] }[] = [ { id: '2012', name: '2012 megafund inputs', rates: ['72.3%', '45.2%', 'about 56%'] }, { id: 'wong', name: '2019 paid data (Wong, Siah and Lo)', rates: ['57.6%', '32.7%', '35.5%'] }, { id: 'open', name: 'Public data (ours)', rates: ['77.9%', '42.8%', '54.9%'] }, { id: 'corrected', name: 'Public data, approvals corrected', rates: ['77.9%', '42.8%', '41.5%'] }, ] const P = params as unknown as { funds: Record[0]> step3: Record> step3_keys: Record } function makeFund(fp: ConstructorParameters[0] & { trans_prob_by_set: Record }, set: SetId, rho: number) { return new Fund(fp, fp.trans_prob_by_set[set], rho) } const pct = (x: number, d = 1) => `${(x * 100).toFixed(d).replace('-', '−')}%` const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ink' type State = { runs: RunResult[]; horizon: number; key: string; target: number } export default function MegafundSimulator({ compact = false }: { compact?: boolean } = {}) { const [fund, setFund] = useState('B') const [set, setSet] = useState('open') const [rho, setRho] = useState(0) const [state, setState] = useState({ runs: [], horizon: 15, key: '', target: STEP }) const [busy, setBusy] = useState(false) const [ms, setMs] = useState(null) const job = useRef(0) const sim = useRef<{ key: string; fund: Fund; rng: ReturnType } | null>(null) const key = `${fund}|${set}|${rho.toFixed(2)}` // Runs `target` funds in total for the current settings, in slices so the page stays responsive. function run(target: number, fresh: boolean) { const id = ++job.current if (fresh || !sim.current || sim.current.key !== key) { sim.current = { key, fund: makeFund(P.funds[fund], set, rho), rng: makeRng(SEED) } } const s = sim.current const runs: RunResult[] = fresh ? [] : state.runs.slice() setBusy(true) const t0 = performance.now() const startCount = runs.length const tick = () => { if (id !== job.current) return const stop = Math.min(target, runs.length + SLICE) while (runs.length < stop) runs.push(s.fund.runOne(s.rng)) setState({ runs: runs.slice(), horizon: s.fund.horizon, key, target }) if (runs.length < target) setTimeout(tick, 0) else { setBusy(false) setMs(((performance.now() - t0) / (runs.length - startCount)) * 1000) } } setTimeout(tick, 0) } // A change of fund, rates or correlation starts a fresh run of STEP funds (after the slider settles). useEffect(() => { const t = setTimeout(() => run(STEP, true), 120) return () => clearTimeout(t) // eslint-disable-next-line react-hooks/exhaustive-deps }, [key]) const summary: Summary | null = state.runs.length > 1 ? summarise(state.runs, state.horizon) : null const ref = useMemo(() => { const r = Math.abs(rho) < 1e-9 ? '0.0' : Math.abs(rho - 0.26) < 1e-9 ? '0.26' : null return r ? P.step3[fund][`${P.step3_keys[set]} | trans_rho=${r}`] : null }, [fund, set, rho]) const stale = state.key !== key return (
{/* Controls */}
Fund
{FUNDS.map((f) => ( ))}
Success rates
{SETS.map((s) => ( ))}
How much failures cluster
{rho.toFixed(2)}
setRho(Number(e.target.value))} className={`mt-2 w-full accent-ink ${focusRing}`} />
{[ [0, '0 (as in 2012)'], [0.2, '0.2 (papers’ assumption)'], [0.26, '0.26 (our estimate)'], [0.5, '0.5'], ].map(([v, label]) => ( ))}

Our estimate has a wide interval, 0 to 0.48, and is an exploration. Values above it are what-ifs.

{/* Results */}
{busy ? 'Running…' : 'Result'} · {state.runs.length.toLocaleString('en-GB')} simulated funds
{summary ? :
}
{ms !== null && ms > 0 ? ( {(ms / 1000).toFixed(2)} ms per fund on this device ) : null}
{ref ? (

The lab note’s 10,000-run figure for this setting: {pct(ref.roe_ann_mean)} a year, equity loss{' '} {pct(ref.p_equity_loss, 0)}, junior bond default {pct(ref.p_default_A2, 2)}.

) : (

The lab note reports correlations 0 and 0.26 only; other values are not in the note.

)}
) } function Stat({ label, value, note, big = false }: { label: string; value: string; note: string; big?: boolean }) { return (
{label}
{value}
{note}
) } // Distribution of each simulated fund's yearly equity return, in 2-point bins from −30% to +40%; the ends collect // everything beyond. One thin signal line marks 0%, where equity holders start losing money. function Histogram({ runs, horizon }: { runs: RunResult[]; horizon: number }) { const LO = -30, HI = 40, W = 2 const nb = (HI - LO) / W const bins = new Array(nb).fill(0) for (const r of runs) { const a = annualise(r.roe, horizon) * 100 const i = Math.min(nb - 1, Math.max(0, Math.floor((a - LO) / W))) bins[i]++ } const max = Math.max(...bins, 1) const VW = 600, VH = 180, PADB = 22, PADT = 8 const bw = VW / nb const x = (v: number) => ((v - LO) / (HI - LO)) * VW return (
{bins.map((c, i) => { const h = ((VH - PADB - PADT) * c) / max const below = LO + i * W < 0 return ( ) })} {[-30, -20, -10, 0, 10, 20, 30, 40].map((v) => ( {v === LO ? '≤ −30%' : v === HI ? '40%+' : `${v > 0 ? '+' : v < 0 ? '−' : ''}${Math.abs(v)}%`} ))}
Yearly equity return of each simulated fund. Grey bars lose money; the red line is break-even.
) }