Repository Public
1import type { Locale } from "@/schema";2import { linspace, normalCdf, normalPdf, studentTCdf, studentTPdf } from "../core";3import { option, optionError, param, type ParamDef, type SimConfig, type SimDef } from "../types";4import { fmt } from "../ui/format";5import { Plot } from "../ui/Plot";6import { Readouts } from "../ui/Readouts";78export const FAMILIES = ["normal", "student", "lognormal", "exponential", "uniform"] as const;9export type Family = (typeof FAMILIES)[number];1011interface FamilyDef {12 domain: [number, number];13 params: ParamDef[];14 pdf(x: number, p: Readonly<Record<string, number>>): number;15 cdf(x: number, p: Readonly<Record<string, number>>): number;16 mean(p: Readonly<Record<string, number>>): number | null;17 variance(p: Readonly<Record<string, number>>): number | null;18}19const ab = (lo: number, hi: number, a: number, b: number): ParamDef[] => [20 param("a", "Borne a", "Bound a", lo, hi, 0.1, a), param("b", "Borne b", "Bound b", lo, hi, 0.1, b),21];22export const FAMILY_DEFS: Record<Family, FamilyDef> = {23 normal: {24 domain: [-8, 8],25 params: [param("mu", "Moyenne μ", "Mean μ", -3, 3, 0.1, 0), param("sigma", "Écart-type σ", "Standard deviation σ", 0.3, 3, 0.1, 1), ...ab(-8, 8, -1, 1)],26 pdf: (x, p) => normalPdf(x, p.mu, p.sigma), cdf: (x, p) => normalCdf(x, p.mu, p.sigma),27 mean: (p) => p.mu, variance: (p) => p.sigma * p.sigma,28 },29 student: {30 domain: [-8, 8],31 params: [param("df", "Degrés de liberté ν", "Degrees of freedom ν", 1, 30, 1, 4), ...ab(-8, 8, -2, 2)],32 pdf: (x, p) => studentTPdf(x, p.df), cdf: (x, p) => studentTCdf(x, p.df),33 mean: (p) => (p.df > 1 ? 0 : null), variance: (p) => (p.df > 2 ? p.df / (p.df - 2) : null),34 },35 lognormal: {36 domain: [0, 10],37 params: [param("mu", "μ de ln X", "μ of ln X", -1, 1.5, 0.1, 0.5), param("sigma", "σ de ln X", "σ of ln X", 0.1, 1.5, 0.05, 0.5), ...ab(0, 10, 1, 3)],38 pdf: (x, p) => (x > 0 ? normalPdf(Math.log(x), p.mu, p.sigma) / x : 0),39 cdf: (x, p) => (x > 0 ? normalCdf(Math.log(x), p.mu, p.sigma) : 0),40 mean: (p) => Math.exp(p.mu + (p.sigma * p.sigma) / 2),41 variance: (p) => (Math.exp(p.sigma * p.sigma) - 1) * Math.exp(2 * p.mu + p.sigma * p.sigma),42 },43 exponential: {44 domain: [0, 10],45 params: [param("lambda", "Taux λ", "Rate λ", 0.2, 5, 0.1, 1), ...ab(0, 10, 0, 1)],46 pdf: (x, p) => (x >= 0 ? p.lambda * Math.exp(-p.lambda * x) : 0), cdf: (x, p) => (x > 0 ? 1 - Math.exp(-p.lambda * x) : 0),47 mean: (p) => 1 / p.lambda, variance: (p) => 1 / (p.lambda * p.lambda),48 },49 uniform: {50 domain: [-6, 9],51 params: [param("low", "Minimum", "Minimum", -5, 3, 0.1, 0), param("width", "Largeur", "Width", 0.5, 5, 0.1, 2), ...ab(-6, 9, 0.5, 1.5)],52 pdf: (x, p) => (x >= p.low && x <= p.low + p.width ? 1 / p.width : 0),53 cdf: (x, p) => Math.min(1, Math.max(0, (x - p.low) / p.width)),54 mean: (p) => p.low + p.width / 2, variance: (p) => (p.width * p.width) / 12,55 },56};5758export interface DistributionModel {59 family: Family;60 domain: [number, number];61 curve: { x: number; y: number }[];62 /** Interval after ordering the two bounds. */63 a: number; b: number;64 /** Density over [a, b], for the shaded area. */65 shade: { x: number; lo: number; hi: number }[];66 /** P(a ≤ X ≤ b) = F(b) − F(a), from the closed-form distribution function. */67 probability: number;68 mean: number | null; sd: number | null;69}7071export function computeDistribution(p: Readonly<Record<string, number>>, config: SimConfig): DistributionModel {72 const family = option(config, "family", FAMILIES);73 const F = FAMILY_DEFS[family];74 const a = Math.min(p.a, p.b), b = Math.max(p.a, p.b);75 const grid = linspace(F.domain[0], F.domain[1], 321);76 let curve = grid.map((x) => ({ x, y: F.pdf(x, p) }));77 if (family === "uniform") {78 const h = 1 / p.width, hi = p.low + p.width;79 curve = [{ x: F.domain[0], y: 0 }, { x: p.low, y: 0 }, { x: p.low, y: h }, { x: hi, y: h }, { x: hi, y: 0 }, { x: F.domain[1], y: 0 }];80 }81 const inside = [a, ...grid.filter((x) => x > a && x < b), b];82 const variance = F.variance(p);83 return {84 family, domain: F.domain, curve, a, b,85 shade: inside.map((x) => ({ x, lo: 0, hi: F.pdf(x, p) })),86 probability: Math.max(0, F.cdf(b, p) - F.cdf(a, p)),87 mean: F.mean(p), sd: variance === null ? null : Math.sqrt(variance),88 };89}9091const NAMES: Record<Family, { fr: string; en: string }> = {92 normal: { fr: "Loi normale", en: "Normal distribution" }, student: { fr: "Loi de Student", en: "Student-t distribution" },93 lognormal: { fr: "Loi log-normale", en: "Log-normal distribution" }, exponential: { fr: "Loi exponentielle", en: "Exponential distribution" },94 uniform: { fr: "Loi uniforme", en: "Uniform distribution" },95};96const TXT = {97 fr: { density: "densité f(x)", area: "P(a ≤ X ≤ b)", prob: "P(a ≤ X ≤ b)", mean: "Espérance", sd: "Écart-type", family: "Loi", none: "non définie" },98 en: { density: "density f(x)", area: "P(a ≤ X ≤ b)", prob: "P(a ≤ X ≤ b)", mean: "Mean", sd: "Standard deviation", family: "Distribution", none: "undefined" },99} as const;100101function DistributionView({ model: m, locale, idPrefix }: { model: DistributionModel; locale: Locale; idPrefix: string }) {102 const L = TXT[locale];103 return (104 <>105 <Plot locale={locale} idPrefix={idPrefix} spec={{106 title: NAMES[m.family][locale], xLabel: "x", yLabel: L.density, xDomain: m.domain, yFromZero: true,107 layers: [108 { type: "band", points: m.shade, tone: "blue", name: L.area, opacity: 0.28 },109 { type: "line", points: m.curve, tone: "blue", name: L.density },110 { type: "vline", x: m.a, tone: "neutral", label: "a" }, { type: "vline", x: m.b, tone: "neutral", label: "b" },111 ],112 }} />113 <Readouts items={[114 { label: L.family, value: NAMES[m.family][locale] },115 { label: L.prob, value: fmt(locale, m.probability, 4), tone: "blue" },116 { label: L.mean, value: m.mean === null ? L.none : fmt(locale, m.mean, 3) },117 { label: L.sd, value: m.sd === null ? L.none : fmt(locale, m.sd, 3) },118 ]} />119 </>120 );121}122123export const distribution: SimDef<DistributionModel> = {124 kind: "distribution",125 title: { fr: "Loi de probabilité et probabilité d'un intervalle", en: "Probability distribution and interval probability" },126 description: {127 fr: "Densité de la loi choisie et probabilité $P(a \\le X \\le b) = F(b) - F(a)$, calculée avec la fonction de répartition exacte (aucun tirage). L'espérance et l'écart-type sont ceux de la loi ; pour Student ils n'existent que si $\\nu > 1$ et $\\nu > 2$.",128 en: "Density of the chosen distribution and the probability $P(a \\le X \\le b) = F(b) - F(a)$, computed from the exact distribution function (no random draw). Mean and standard deviation are those of the distribution; for Student-t they exist only when $\\nu > 1$ and $\\nu > 2$.",129 },130 params: FAMILY_DEFS.normal.params,131 stochastic: false,132 configKeys: ["family"],133 paramsFor: (c) => FAMILY_DEFS[option(c, "family", FAMILIES)].params,134 validateConfig: (c) => optionError(c, "family", FAMILIES),135 compute: (p, _seed, c) => computeDistribution(p, c),136 View: DistributionView,137};138