/ concept-collection / fastandaccurate
Sign in
concept-collection / fastandaccurate
fastandaccurate / src / app / worker.ts
93 lines · 2.7 KBBlameHistoryRaw
1/// <reference lib="webworker" />
2// The compute worker: runs numbl solves off the main thread. One request
3// at a time; requests queue in the message queue while a sweep runs.
5import { getInstance } from "../problems/laplace2d/spec";
6import { getSolver } from "../solvers";
7import { runSweep } from "../harness/sweep";
8import { runPoint } from "../harness/runner";
9import { toResultPoint, type ResultPoint } from "../harness/resultSchema";
10import { DEFAULT_TIMING, type TimingPolicy } from "../harness/timing";
11import { matlabBase, solverSource } from "./matlabSources";
13export interface SweepRequest {
14 type: "sweep";
15 id: number;
16 instanceId: string;
17 solverId: string;
18 timing: TimingPolicy;
21export interface SolutionRequest {
22 type: "solution";
23 id: number;
24 instanceId: string;
25 solverId: string;
26 n: number;
29export type WorkerRequest = SweepRequest | SolutionRequest;
31export type WorkerResponse =
32 | { type: "point"; id: number; point: ResultPoint; index: number; total: number }
33 | { type: "sweepDone"; id: number; points: ResultPoint[] }
34 | {
35 type: "solutionDone";
36 id: number;
37 point: ResultPoint;
38 uGrid: Float64Array;
39 }
40 | { type: "error"; id: number; message: string };
42self.onmessage = (e: MessageEvent<WorkerRequest>) => {
43 const msg = e.data;
44 try {
45 if (msg.type === "sweep") {
46 const points = runSweep({
47 instance: getInstance(msg.instanceId),
48 solver: getSolver(msg.solverId),
49 sources: { ...matlabBase(), solver: solverSource(msg.solverId) },
50 timing: msg.timing,
51 onPoint: (p, index, total) => {
52 const resp: WorkerResponse = {
53 type: "point",
54 id: msg.id,
55 point: toResultPoint(p),
56 index,
57 total,
58 };
59 postMessage(resp);
60 },
61 });
62 const resp: WorkerResponse = {
63 type: "sweepDone",
64 id: msg.id,
65 points: points.map(toResultPoint),
66 };
67 postMessage(resp);
68 } else if (msg.type === "solution") {
69 const p = runPoint({
70 instance: getInstance(msg.instanceId),
71 n: msg.n,
72 timing: { ...DEFAULT_TIMING, minTimedRuns: 1, timeBudgetSeconds: 0 },
73 wantGrid: true,
74 sources: { ...matlabBase(), solver: solverSource(msg.solverId) },
75 });
76 if (!p.uGrid) throw new Error("solver returned no grid values");
77 const resp: WorkerResponse = {
78 type: "solutionDone",
79 id: msg.id,
80 point: toResultPoint(p),
81 uGrid: p.uGrid,
82 };
83 postMessage(resp, { transfer: [p.uGrid.buffer] });
84 }
85 } catch (err) {
86 const resp: WorkerResponse = {
87 type: "error",
88 id: msg.id,
89 message: err instanceof Error ? err.message : String(err),
90 };
91 postMessage(resp);
92 }
93};
moveopenescclose