/ concept-collection / fastandaccurate
Sign in
concept-collection / fastandaccurate
fastandaccurate / src / app / worker.ts
92 lines · 2.6 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 { matlabBase, solverSource } from "./matlabSources";
12export interface SweepRequest {
13 type: "sweep";
14 id: number;
15 instanceId: string;
16 solverId: string;
17 repeats: number;
20export interface SolutionRequest {
21 type: "solution";
22 id: number;
23 instanceId: string;
24 solverId: string;
25 n: number;
28export type WorkerRequest = SweepRequest | SolutionRequest;
30export type WorkerResponse =
31 | { type: "point"; id: number; point: ResultPoint; index: number; total: number }
32 | { type: "sweepDone"; id: number; points: ResultPoint[] }
33 | {
34 type: "solutionDone";
35 id: number;
36 point: ResultPoint;
37 uGrid: Float64Array;
38 }
39 | { type: "error"; id: number; message: string };
41self.onmessage = (e: MessageEvent<WorkerRequest>) => {
42 const msg = e.data;
43 try {
44 if (msg.type === "sweep") {
45 const points = runSweep({
46 instance: getInstance(msg.instanceId),
47 solver: getSolver(msg.solverId),
48 sources: { ...matlabBase(), solver: solverSource(msg.solverId) },
49 repeats: msg.repeats,
50 onPoint: (p, index, total) => {
51 const resp: WorkerResponse = {
52 type: "point",
53 id: msg.id,
54 point: toResultPoint(p),
55 index,
56 total,
57 };
58 postMessage(resp);
59 },
60 });
61 const resp: WorkerResponse = {
62 type: "sweepDone",
63 id: msg.id,
64 points: points.map(toResultPoint),
65 };
66 postMessage(resp);
67 } else if (msg.type === "solution") {
68 const p = runPoint({
69 instance: getInstance(msg.instanceId),
70 n: msg.n,
71 repeats: 1,
72 wantGrid: true,
73 sources: { ...matlabBase(), solver: solverSource(msg.solverId) },
74 });
75 if (!p.uGrid) throw new Error("solver returned no grid values");
76 const resp: WorkerResponse = {
77 type: "solutionDone",
78 id: msg.id,
79 point: toResultPoint(p),
80 uGrid: p.uGrid,
81 };
82 postMessage(resp, { transfer: [p.uGrid.buffer] });
83 }
84 } catch (err) {
85 const resp: WorkerResponse = {
86 type: "error",
87 id: msg.id,
88 message: err instanceof Error ? err.message : String(err),
89 };
90 postMessage(resp);
91 }
92};
moveopenescclose