/ concept-collection / fastandaccurate
Sign in
concept-collection / fastandaccurate
fastandaccurate / src / harness / numblRun.ts
65 lines · 2.0 KBBlameHistoryRaw
1// Thin wrapper around numbl's synchronous executeCode for harness runs.
2// Works identically in a browser worker and in node: no file I/O adapters
3// are attached, so the MATLAB side must communicate through workspace
4// variables, which we read back from result.variableValues.
6import { executeCode } from "numbl";
8const PROJ = "/fastandaccurate";
10export interface NumblRunResult {
11 /** Console output of the run. */
12 output: string;
13 /** Named numeric results pulled from the final workspace. */
14 vars: Record<string, Float64Array>;
17/**
18 * Run mainSource as the main script with the given auxiliary .m files on
19 * the search path, and extract the requested workspace variables, which
20 * must be real numeric arrays (or scalars, returned as length-1 arrays).
21 * Throws on MATLAB errors and on missing/non-numeric variables.
22 */
23export function runNumblScript(
24 mainSource: string,
25 files: Record<string, string>,
26 wantVars: string[]
27): NumblRunResult {
28 const workspaceFiles = Object.entries(files).map(([name, source]) => ({
29 name: `${PROJ}/${name}`,
30 source,
31 }));
32 const outputs: string[] = [];
33 const result = executeCode(
34 mainSource,
35 {
36 onOutput: (text) => outputs.push(text),
37 displayResults: false,
38 optimization: "1",
39 implicitCwdPath: null,
40 },
41 workspaceFiles,
42 `${PROJ}/main.m`,
43 [PROJ]
44 );
45 const vars: Record<string, Float64Array> = {};
46 for (const name of wantVars) {
47 const v = result.variableValues[name];
48 if (typeof v === "number") {
49 vars[name] = new Float64Array([v]);
50 } else if (
51 v &&
52 typeof v === "object" &&
53 (v as { kind?: string }).kind === "tensor"
54 ) {
55 const tensor = v as { data: Float64Array; imag?: Float64Array };
56 if (tensor.imag) {
57 throw new Error(`variable ${name} is complex; expected real`);
58 }
59 vars[name] = tensor.data;
60 } else {
61 throw new Error(`variable ${name} missing or not numeric after run`);
62 }
63 }
64 return { output: outputs.join(""), vars };
moveopenescclose