diff --git a/CMakeLists.txt b/CMakeLists.txt index ee8491733..ac34a7851 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,6 +11,7 @@ option(PACKINGSOLVER_USE_KNITRO "Use Knitro" OFF) option(PACKINGSOLVER_BUILD_MAIN "Build main" ON) option(PACKINGSOLVER_BUILD_TEST "Build unit tests" ON) option(PACKINGSOLVER_BUILD_PYTHON "Build Python bindings" OFF) +option(PACKINGSOLVER_BUILD_WASM "Build the WebAssembly module (with Emscripten)" OFF) # Avoid FetchContent warning. cmake_policy(SET CMP0135 NEW) @@ -32,6 +33,28 @@ if(PACKINGSOLVER_BUILD_PYTHON) endif() endif() +# The WebAssembly module is built with Emscripten, with thread support (each +# thread runs in a Web Worker), so that every optimization mode works. CLP +# isn't available there: the module uses HiGHS. C++ exceptions are enabled +# (they are disabled by default with Emscripten), since the library reports +# invalid inputs with exceptions. +if(PACKINGSOLVER_BUILD_WASM) + if(NOT EMSCRIPTEN) + message(FATAL_ERROR "PACKINGSOLVER_BUILD_WASM requires the Emscripten toolchain (use emcmake)") + endif() + if(PACKINGSOLVER_USE_CLP) + message(STATUS "PACKINGSOLVER_BUILD_WASM: disabling CLP") + set(PACKINGSOLVER_USE_CLP OFF) + endif() + if(NOT PACKINGSOLVER_USE_HIGHS) + message(FATAL_ERROR "PACKINGSOLVER_BUILD_WASM requires PACKINGSOLVER_USE_HIGHS") + endif() + set(PACKINGSOLVER_BUILD_MAIN OFF) + set(PACKINGSOLVER_BUILD_TEST OFF) + add_compile_options(-fwasm-exceptions -pthread) + add_link_options(-fwasm-exceptions -pthread) +endif() + # Enable output of compile commands during generation. set(CMAKE_EXPORT_COMPILE_COMMANDS ON) @@ -47,3 +70,6 @@ endif() if(PACKINGSOLVER_BUILD_PYTHON) add_subdirectory(python) endif() +if(PACKINGSOLVER_BUILD_WASM) + add_subdirectory(wasm) +endif() diff --git a/wasm/CMakeLists.txt b/wasm/CMakeLists.txt new file mode 100644 index 000000000..b3058f2fe --- /dev/null +++ b/wasm/CMakeLists.txt @@ -0,0 +1,28 @@ +add_executable(PackingSolver_wasm) +target_sources(PackingSolver_wasm PRIVATE + src/packingsolver_wasm.cpp) +target_link_libraries(PackingSolver_wasm PRIVATE + PackingSolver_rectangle) +target_link_options(PackingSolver_wasm PRIVATE + -lembind + # Load with 'await PackingSolver()', in the browser, a web worker or Node. + -sMODULARIZE=1 + -sEXPORT_NAME=PackingSolver + -sENVIRONMENT=web,worker,node + -sALLOW_MEMORY_GROWTH=1 + -sMAXIMUM_MEMORY=4GB + # The workers of the threads are started when the module is loaded: + # 'solve' blocks the calling thread, which then can't start new ones. If + # the algorithms need more threads than the pool has, the thread creation + # fails ('solve' returns an error) instead of blocking forever. + -sPTHREAD_POOL_SIZE=16 + -sPTHREAD_POOL_SIZE_STRICT=2 + # The default allocator (dlmalloc) has a single lock: with several + # threads, the algorithms were up to 7 times slower than natively. + -sMALLOC=mimalloc) +# embind requires C++17: only the bindings are compiled with it, the +# libraries stay C++14. +set_target_properties(PackingSolver_wasm PROPERTIES + CXX_STANDARD 17 + OUTPUT_NAME "packingsolver" + SUFFIX ".js") diff --git a/wasm/src/packingsolver_wasm.cpp b/wasm/src/packingsolver_wasm.cpp new file mode 100644 index 000000000..611a643a3 --- /dev/null +++ b/wasm/src/packingsolver_wasm.cpp @@ -0,0 +1,123 @@ +/** + * WebAssembly module: JavaScript API of PackingSolver. + * + * 'solve(problemType, instanceJson, parametersJson)' reads an instance in the + * JSON format of PackingSolver, solves it and returns a JSON string: + * + * { + * "output": ..., // 'Output::to_json()' + * "certificate": ... // the solution, in the CSV certificate format + * } + * + * 'solve' blocks the calling thread: in a browser, call it from a Web Worker + * (the main thread can't block). The threads of the algorithms run in a pool + * of Web Workers started when the module is loaded. + * + * Parameters (all optional): + * - "optimization_mode": "anytime" (default), "not-anytime", + * "not-anytime-deterministic" or "not-anytime-sequential" (single-threaded); + * in "anytime" mode, the algorithms run until the time limit, unless the + * solution is proven optimal; + * - "time_limit": time limit in seconds; + * - "verbosity_level": verbosity level, printed on the console. + */ + +#include "packingsolver/rectangle/instance_builder.hpp" +#include "packingsolver/rectangle/optimize.hpp" + +#include + +#include + +using namespace packingsolver; + +namespace +{ + +template +OptimizeParameters read_parameters(const std::string& parameters_json) +{ + OptimizeParameters parameters; + parameters.verbosity_level = 0; + // Only HiGHS is available in the module. + parameters.linear_programming_solver_name = columngenerationsolver::SolverName::Highs; + + if (parameters_json.empty()) + return parameters; + nlohmann::json json = nlohmann::json::parse(parameters_json); + if (json.contains("optimization_mode")) { + std::stringstream ss(json["optimization_mode"].get()); + ss >> parameters.optimization_mode; + if (ss.fail()) { + throw std::invalid_argument( + "solve: invalid optimization mode: " + + json["optimization_mode"].dump() + "."); + } + } + if (json.contains("time_limit")) + parameters.timer.set_time_limit(json["time_limit"].get()); + if (json.contains("verbosity_level")) + parameters.verbosity_level = json["verbosity_level"].get(); + return parameters; +} + +template +std::string to_result(const Output& output) +{ + std::stringstream certificate; + output.solution_pool.best().write(certificate); + nlohmann::json result; + result["output"] = output.to_json(); + result["certificate"] = certificate.str(); + return result.dump(); +} + +std::string solve_rectangle( + const std::string& instance_json, + const std::string& parameters_json) +{ + rectangle::InstanceBuilder instance_builder; + std::istringstream instance_stream(instance_json); + instance_builder.read(instance_stream); + const rectangle::Instance instance = instance_builder.build(); + const rectangle::OptimizeParameters parameters + = read_parameters(parameters_json); + const rectangle::Output output = rectangle::optimize(instance, parameters); + return to_result(output); +} + +std::string solve( + const std::string& problem_type, + const std::string& instance_json, + const std::string& parameters_json) +{ + if (problem_type == "rectangle") + return solve_rectangle(instance_json, parameters_json); + throw std::invalid_argument( + "solve: unsupported problem type: \"" + problem_type + "\"."); +} + +/** + * Wrapper returning errors as a JSON string: C++ exceptions only reach + * JavaScript as opaque pointers. + */ +std::string solve_or_error( + const std::string& problem_type, + const std::string& instance_json, + const std::string& parameters_json) +{ + try { + return solve(problem_type, instance_json, parameters_json); + } catch (const std::exception& e) { + nlohmann::json result; + result["error"] = e.what(); + return result.dump(); + } +} + +} + +EMSCRIPTEN_BINDINGS(packingsolver) +{ + emscripten::function("solve", &solve_or_error); +} diff --git a/wasm/tests/rectangle.test.js b/wasm/tests/rectangle.test.js new file mode 100644 index 000000000..8da2bbbc8 --- /dev/null +++ b/wasm/tests/rectangle.test.js @@ -0,0 +1,85 @@ +// Run with: node --test wasm/tests/ +// The module path can be set with PACKINGSOLVER_WASM (default: +// build_wasm/wasm/packingsolver.js). + +const assert = require("node:assert"); +const path = require("node:path"); +const test = require("node:test"); + +const MODULE_PATH = process.env.PACKINGSOLVER_WASM + || path.join(__dirname, "..", "..", "build_wasm", "wasm", "packingsolver.js"); + +let modulePromise = null; +function loadModule() { + if (modulePromise === null) + modulePromise = require(MODULE_PATH)(); + return modulePromise; +} + +// The 'rectangle' example of the README. +const README_INSTANCE = { + objective: "bin-packing-with-leftovers", + bin_types: [{x: 1000, y: 500, copies: 10}], + item_types: [ + {x: 300, y: 200, copies: 10}, + {x: 250, y: 150, copies: 10}, + ], +}; + +// Four 5x5 squares fill a 10x10 bin: the bound proves the solution optimal, +// so the anytime mode stops without a time limit. +const PROVEN_OPTIMAL_INSTANCE = { + objective: "bin-packing", + bin_types: [{x: 10, y: 10, copies: 4}], + item_types: [{x: 5, y: 5, copies: 4}], +}; + +function solve(module, instance, parameters) { + const result = JSON.parse(module.solve( + "rectangle", JSON.stringify(instance), JSON.stringify(parameters))); + assert.strictEqual(result.error, undefined); + return result; +} + +test("rectangle: anytime mode (default)", async () => { + const module = await loadModule(); + const result = solve(module, PROVEN_OPTIMAL_INSTANCE, {}); + assert.strictEqual(result.output.Solution.NumberOfBins, 1); + assert.strictEqual(result.output.BinPackingBound, 1); +}); + +for (const optimizationMode of [ + "not-anytime", "not-anytime-deterministic", "not-anytime-sequential"]) { + test(`rectangle: README example, ${optimizationMode}`, async () => { + const module = await loadModule(); + const result = solve(module, README_INSTANCE, { + optimization_mode: optimizationMode}); + assert.strictEqual(result.output.Solution.NumberOfItems, 20); + assert.ok(result.output.Solution.NumberOfBins >= 1); + // The certificate lists every bin and item. + const lines = result.certificate.trim().split("\n"); + assert.strictEqual(lines[0], "TYPE,ID,COPIES,BIN,X,Y,LX,LY,GROUP_ID"); + assert.strictEqual( + lines.filter((line) => line.startsWith("ITEM,")).length, 20); + }); +} + +test("rectangle: invalid optimization mode", async () => { + const module = await loadModule(); + const result = JSON.parse(module.solve( + "rectangle", JSON.stringify(README_INSTANCE), + JSON.stringify({optimization_mode: "fast"}))); + assert.match(result.error, /optimization mode/); +}); + +test("rectangle: invalid instance", async () => { + const module = await loadModule(); + const result = JSON.parse(module.solve("rectangle", "{}", "{}")); + assert.match(result.error, /objective/); +}); + +test("unsupported problem type", async () => { + const module = await loadModule(); + const result = JSON.parse(module.solve("unknown", "{}", "{}")); + assert.match(result.error, /unsupported problem type/); +});