File size: 2,094 Bytes
373fbfb
60943f3
 
7b67454
 
60943f3
 
 
 
 
 
373fbfb
 
60943f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const PYODIDE_URL = "https://cdn.jsdelivr.net/pyodide/v0.26.1/full/pyodide.mjs";

// @ts-ignore
import managerCode from "../../../backend/src/optimization_manager.py?raw";
import logicCode from "../../../backend/src/optimization_logic.py?raw";
import type { WorkerMessage } from "./types";

let pyodide: any = null;
let manager: any = null;

async function init() {
  const { loadPyodide } = await import(/* @vite-ignore */ PYODIDE_URL);

  pyodide = await loadPyodide({
    indexURL: "https://cdn.jsdelivr.net/pyodide/v0.26.1/full/"
  });

  await pyodide.loadPackage(["numpy", "sympy"]);

  pyodide.FS.writeFile("optimization_logic.py", logicCode);
  pyodide.FS.writeFile("optimization_manager.py", managerCode);

  pyodide.runPython(`from optimization_manager import OptimizationManager; manager = OptimizationManager();`);

  manager = pyodide.globals.get("manager");

  if (!manager) {
    console.error("Failed to initialize optimization manager");
  }

  self.postMessage({ type: "READY" });
}

function handlePythonResult(result: any) {
  if (!result) {
    return null;
  }

  try {
    const data = result.toJs({ dict_converter: Object.fromEntries });

    if (result.destroy) {
      result.destroy();
    }

    self.postMessage({ type: "RESULT", data: data });
  } catch (error) {
    console.error("Error handling Python result:", error);
  }
}

self.onmessage = async (event) => {
  const message = event.data as WorkerMessage;

  if (!manager) {
    console.warn("Pyodide is not ready yet");
    return;
  }

  switch (message.type) {
    case "INIT":
      const pythonSettings = pyodide.toPy(message.settings);
      handlePythonResult(manager.handle_update_settings(pythonSettings));
      break;
    case "NEXT_STEP":
      handlePythonResult(manager.handle_next_step());
      break;
    case "PREV_STEP":
      handlePythonResult(manager.handle_prev_step());
      break;
    case "RESET":
      handlePythonResult(manager.handle_reset());
      break;
    default:
      console.error("Unknown message type:", message);
      break;

  }
}

// Start of execution
init();