/ concept-collection / fastandaccurate
Sign in
concept-collection / fastandaccurate
fastandaccurate / src / app / components / SolutionSection.tsx
175 lines · 6.0 KBBlameHistoryRaw
1// The solution-and-error view: compute one solve in the browser at a
2// chosen resolution and show the field next to its pointwise error
3// against the exact solution.
5import { useMemo, useState } from "react";
6import type { Laplace2dInstance } from "../../problems/laplace2d/spec";
7import {
8 evalPoints,
9 exactU,
10 vizGrid,
11 VIZ_NGRID,
12} from "../../problems/laplace2d/exact";
13import { SOLVERS, getSolver, sweepNFor } from "../../solvers";
14import { solutionInBrowser } from "../workerClient";
15import type { ResultPoint } from "../../harness/resultSchema";
16import { FieldView, fieldAbsMax } from "./FieldView";
18function exactGridValues(inst: Laplace2dInstance): Float64Array {
19 const { xs } = vizGrid(inst);
20 const out = new Float64Array(VIZ_NGRID * VIZ_NGRID);
21 for (let ix = 0; ix < VIZ_NGRID; ix++) {
22 for (let iy = 0; iy < VIZ_NGRID; iy++) {
23 out[ix * VIZ_NGRID + iy] = exactU(inst, xs[ix], xs[iy]);
24 }
25 }
26 return out;
29interface Computed {
30 solverId: string;
31 n: number;
32 uGrid: Float64Array;
33 point: ResultPoint;
36// Only solvers that run in the browser can compute a field here.
37const BROWSER_SOLVERS = SOLVERS.filter((s) => s.runtime === "numbl");
39export function SolutionSection({ inst }: { inst: Laplace2dInstance }) {
40 const [solverId, setSolverId] = useState(BROWSER_SOLVERS[0].id);
41 const [n, setN] = useState<number>(
42 BROWSER_SOLVERS[0].sweepN[Math.floor(BROWSER_SOLVERS[0].sweepN.length * 0.7)]
43 );
44 const [busy, setBusy] = useState(false);
45 const [error, setError] = useState<string | null>(null);
46 const [computed, setComputed] = useState<Computed | null>(null);
47 const [showMarks, setShowMarks] = useState(false);
49 const exact = useMemo(() => exactGridValues(inst), [inst]);
51 const errField = useMemo(() => {
52 if (!computed) return null;
53 const out = new Float64Array(exact.length);
54 for (let i = 0; i < exact.length; i++) {
55 out[i] = Math.abs(computed.uGrid[i] - exact[i]);
56 }
57 return out;
58 }, [computed, exact]);
60 const solver = getSolver(solverId);
61 const showsComputed = computed !== null && computed.solverId === solverId;
63 // One color scale shared by the exact and computed solution fields, set
64 // by the dynamic range of the exact solution; a computed field that
65 // exceeds it clips.
66 const sharedRange = useMemo(() => {
67 const vabs = fieldAbsMax(inst, exact);
68 return { lo: -vabs, hi: vabs };
69 }, [inst, exact]);
71 const marks = useMemo(() => evalPoints(inst), [inst]);
73 // The resolutions offered depend on the instance as well as the solver,
74 // since a harder geometry sweeps a different range. If the instance
75 // changes under a selected n that its list does not contain, fall back
76 // to a resolution partway up the new list.
77 const ns = useMemo(() => sweepNFor(solver, inst.id), [solver, inst.id]);
78 const nSel = ns.includes(n) ? n : ns[Math.floor(ns.length * 0.7)];
80 async function compute() {
81 setBusy(true);
82 setError(null);
83 try {
84 const { point, uGrid } = await solutionInBrowser(inst.id, solverId, nSel);
85 setComputed({ solverId, n: nSel, uGrid, point });
86 } catch (err) {
87 setError(err instanceof Error ? err.message : String(err));
88 } finally {
89 setBusy(false);
90 }
91 }
93 return (
94 <div>
95 <div className="row" style={{ alignItems: "center", gap: 12, marginBottom: 12 }}>
96 <label>
97 solver{" "}
98 <select
99 value={solverId}
100 onChange={(e) => {
101 const id = e.target.value;
102 setSolverId(id);
103 const sw = sweepNFor(getSolver(id), inst.id);
104 setN(sw[Math.floor(sw.length * 0.7)]);
105 }}
106 >
107 {BROWSER_SOLVERS.map((s) => (
108 <option key={s.id} value={s.id}>
109 {s.name}
110 </option>
111 ))}
112 </select>
113 </label>
114 <label>
115 n{" "}
116 <select value={nSel} onChange={(e) => setN(parseInt(e.target.value, 10))}>
117 {ns.map((v) => (
118 <option key={v} value={v}>
119 {v}
120 </option>
121 ))}
122 </select>
123 </label>
124 <button className="primary" onClick={compute} disabled={busy}>
125 {busy ? "computing…" : "Compute in this browser"}
126 </button>
127 <label className="small">
128 <input
129 type="checkbox"
130 checked={showMarks}
131 onChange={(e) => setShowMarks(e.target.checked)}
132 />{" "}
133 show evaluation points on the error map
134 </label>
135 </div>
136 {error && <p className="small" style={{ color: "var(--series-2)" }}>{error}</p>}
137 <div className="row">
138 <FieldView
139 inst={inst}
140 values={exact}
141 mode="diverging"
142 range={sharedRange}
143 title="Exact solution"
144 caption="The exact solution on the visualization grid. The color scale is shared with the computed field."
145 />
146 {showsComputed && computed && (
147 <FieldView
148 inst={inst}
149 values={computed.uGrid}
150 mode="diverging"
151 range={sharedRange}
152 title={`${solver.name}, n = ${computed.n}`}
153 caption={`Computed in this browser: rel max error ${computed.point.relMax.toExponential(2)} at the evaluation points, solve ${(computed.point.solveSeconds * 1000).toPrecision(3)} ms. Same color scale as the exact solution.`}
154 />
155 )}
156 {showsComputed && errField && computed && (
157 <FieldView
158 inst={inst}
159 values={errField}
160 mode="logmag"
161 overlayPoints={showMarks ? marks : undefined}
162 title="Pointwise error (log scale)"
163 caption={
164 "Absolute difference from the exact solution; the color scale " +
165 "spans 8 decades below the maximum." +
166 (showMarks
167 ? ` Dots mark the ${marks.length} evaluation points where the reported errors are measured.`
168 : "")
169 }
170 />
171 )}
172 </div>
173 </div>
174 );
moveopenescclose