diff --git a/.gitignore b/.gitignore index e4fbfcd..21e8fea 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ build/ dist/ *.egg-info/ *.so +.deb-out/ +obj-*/ # Python caches __pycache__/ diff --git a/.gitmodules b/.gitmodules index 1982aaf..b9e8d39 100644 --- a/.gitmodules +++ b/.gitmodules @@ -5,3 +5,6 @@ path = pybind11 url = https://github.com/pybind/pybind11.git branch = v3.0 +[submodule "qdldl"] + path = qdldl + url = https://github.com/osqp/qdldl.git diff --git a/AGENTS.md b/AGENTS.md index 7cc06f5..ee7abfa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,16 +10,28 @@ first-order ADMM solver for quadratic programs. marinholab/solvers/osqp/ __init__.py Public API re-exports (Solver, Configuration, Info, enums) solver.py numpy-friendly Solver wrapper (accepts None constraints, warm-starts) + _options.py Pure-Python IntEnum types (LinsysSolverType, + PreconditionerType, Status) that mirror the OSQP + enums accepted by Configuration.set() example.py runnable example (console script: osqp_example) example_kinematics.py OPTIONAL example (needs dqrobotics + dqrobotics-pyplot) _core.pyi type stub for the compiled _core extension (ships in the wheel) py.typed PEP 561 marker so stubs are picked up by type checkers -include/marinholab/solvers/osqp.h C++ header (Solver + Configuration + Info): `marinholab::solvers::osqp::Solver` + `Configuration` (doxygen-documented) -src/core.cpp pybind11 module (_core): binds `Solver` + `Configuration` + `Info` + enums -src/core_function.cpp C++ implementation (wraps OSQP's OSQPSolver); compiled into the `marinholab_osqp` static library -CMakeLists.txt CMake build: `marinholab_osqp` static lib, `_core` pybind11 module, optional C++ example (`-DBUILD_EXAMPLES=ON`) +include/marinholab/solvers/osqp.h C++ header (Solver + Configuration + Info) — OSQP-free (pimpl Solver; Configuration keyed by name with typed `OptionValue`s) +src/core.cpp pybind11 module (_core): binds `Solver` + `Configuration` (set/get/has/keys/defaults/reset) + `Info` with native Python values +src/core_function.cpp C++ implementation (wraps OSQP's OSQPSolver via pimpl); option name->kind map; compiled into the `marinholab_osqp` library (shared by default, `-DBUILD_SHARED_LIBS=OFF` for static) +CMakeLists.txt CMake build: `marinholab_osqp` lib (shared by default), `_core` pybind11 module (`-DBUILD_PYTHON=ON`), optional C++ example (`-DBUILD_EXAMPLES=ON`). The vendored OSQP is always built **static** (its linear-solver, qdldl, embedded via the `qdldl` submodule) and linked **PRIVATE** into `marinholab_osqp`; consumers only link `marinholab::solvers::osqp`. example/example.cpp standalone C++ usage example (target: `example_osqp`) +tests/test_solver.py pytest tests for `Solver` + `Configuration` (see "Tests") +cmake/GetVersion.cmake rolling version (YY.MM.NN) computed at configure time +cmake/marinholab_solver_osqp-config.cmake.in CMake package config (find_package consumers) +debian/ Debian packaging for the C++ part (libmarinholab-solver-osqp) +tools/version.sh compute the rolling version (YY.MM.NN) +tools/bump-changelog.sh bring debian/changelog in line with the rolling version +docker/build-deb.sh build the .deb (optionally + test it) in an Ubuntu noble container +docker/deb.Dockerfile Dockerfile for the .deb build osqp/ OSQP (git submodule) +qdldl/ qdldl linear-solver (git submodule, used by OSQP's built-in algebra) pybind11/ pybind11 (git submodule) setup.py PEP 517 build (CMake + pybind11) pyrightconfig.json Pyright configuration (python 3.9, mode basic) @@ -63,9 +75,27 @@ built only when `BUILD_EXAMPLES=ON`; it is *not* built by `pip install .`: ```console cmake -B build -GNinja -DCMAKE_BUILD_TYPE=Release -DBUILD_EXAMPLES=ON cmake --build build --target example_osqp -./build/example/example_osqp # prints x ≈ [0.2, 1.0] and the residuals +./build/example_osqp # prints x ≈ [0.2, 1.0] and the residuals ``` +## Tests + +```console +pip install pytest +cd tests && python -m pytest +``` + +Run pytest from inside `tests/`, not from the repository root. From the root, +the source `marinholab/` directory (which has no compiled `_core`) shadows the +installed package. CI runs the tests in the Docker job (`docker/compose.yml`) +before `osqp_example`. + +`tests/test_solver.py` checks that one `Solver` instance gives the same +answers as a fresh one when the number of variables or constraints changes +between calls (with `use_hotstart` on and off), that the name-keyed +`Configuration` converts values to each option's kind (and rejects the wrong +kind), and that `Configuration.defaults()` matches OSQP's own defaults. + ## Type checking (Pyright) ```console @@ -90,23 +120,38 @@ Configuration lives in `pyrightconfig.json` (`pythonVersion` 3.9, - **Defaults match OSQP.** `Configuration` defaults mirror OSQP's own `osqp_set_default_settings()` for a standard double-precision, direct-solver - build (see the defaults tables in `README.md`), with one documented - exception: `verbose` defaults to `0` (quiet) instead of OSQP's own - `OSQP_VERBOSE = 1`. Do not silently override them here; if a particular - problem needs a non-default option, set it on the `Configuration` in the - *caller* (e.g. `example.py` tightens `eps_abs`/`eps_rel` and raises + build (see `detail::default_values` in `src/core_function.cpp`), with one + documented exception: `verbose` defaults to `false` (quiet) instead of + OSQP's own `OSQP_VERBOSE = 1`. Do not silently override them here; if a + particular problem needs a non-default option, set it on the `Configuration` + in the *caller* (e.g. `example.py` tightens `eps_abs`/`eps_rel` and raises `max_iter`). Re-validate the `example.py` and `example_kinematics.py` solves after any change to a default. +- **Option values are typed, never round-tripped through text.** + `Configuration` stores `OptionValue = std::variant`, converted to the option's kind in `set()` + (`detail::normalize`). Defaults come straight from OSQP's `OSQPSettings` + (`detail::default_values`), and `settings_from()` starts from OSQP's + `osqp_set_default_settings()`, applies the quieter `verbose`, then only the + options that were set. Enum options hold the enum value name (e.g. + `OSQP_DIRECT_SOLVER`, `OSQP_DIAGONAL_PRECONDITIONER`). +- **`Configuration` keyed by name.** Options are set by name + (`set(key, value)`); the C++ public header exposes no OSQP types (OSQP is + reached only through the pimpl in `src/core_function.cpp`), so enumeration + values are held by name. The OSQP option keys keep the library's native + snake_case spelling (e.g. `eps_abs`, `max_iter`, `warm_starting`); the + wrapper-specific key that has no OSQP counterpart is also snake_case + (`use_hotstart`). Enum options take the enum value name or, in Python, an + enum member; `set()` also converts strings for the other kinds (`"1e-9"`, + `"false"`). The option name->kind map (`detail::option_kinds`) and the + pure-Python enums in `_options.py` must stay in sync with the + `Configuration` options. - **`Solver` API.** `Solver.solve_quadratic_program()` accepts `None` for `A`/`b`/`Aeq`/`beq` (in the Python wrapper, which substitutes a single trivially-satisfied zero row; the C++ `Solver` always takes all six matrices) and optional `x0`/`y0` warm-starts. `Solver.get_info()` returns `obj_val`, `dual_obj_val`, `prim_res`, `dual_res`, and the `dual_solution`. - **Style.** Match the existing style: docstrings on the public API. - `Configuration` fields that map to OSQP `OSQPSettings` fields keep the - library's native snake_case spelling (e.g. `eps_abs`, `max_iter`, - `warm_starting`); the wrapper-specific field that has no OSQP counterpart is - also snake_case (`use_hotstart`). - **Doxygen.** C++ types and members are documented with Doxygen (`/** ... @brief ... @param ... @return ... @see ... */` blocks). Keep that when adding fields or methods. @@ -121,10 +166,45 @@ Configuration lives in `pyrightconfig.json` (`pythonVersion` 3.9, `ubuntu-24.04-arm` for Python 3.12 and 3.13 and publishes to PyPI. Local builds here mirror that (aarch64, Python 3.13). +## Debian build (libmarinholab-solver-osqp) + +The `.deb` is **not** built by this repo's CI — it is built by the +SmartArmStack `build_ros2.sh` (SmartArmStack/smart_arm_stack_ROS2), which +clones `main` with submodules, runs `bash tools/bump-changelog.sh` and +`dpkg-buildpackage -us -uc -b` on this `debian/` directory, then `dpkg -i` +installs it. `build_ros2.sh`'s matrix is `ubuntu-24.04` (amd64) + +`ubuntu-24.04-arm` (arm64); the `debian/` packaging is shared, so it must +build on **both** architectures. + +```console +bash docker/build-deb.sh # build the .deb -> ./.deb-out/ +bash docker/build-deb.sh --test # + install it and build/run a + # find_package consumer inside the container +``` + +Only the C++ part is packaged (the `marinholab::solvers::osqp` library). The +vendored OSQP (with its linear-solver, qdldl, embedded) is built **static** +and bundled into the same package, so the `.deb` depends only on the C++ +runtime (`libc6`, `libgcc-s1`, `libstdc++6`). `debian/rules` appends `-fno-lto` +after the `dpkg-buildflags` defaults: Ubuntu noble enables `-flto=auto`, and +LTO is disabled for reproducibility. + +The `.deb` carries `libmarinholab_solver_osqp.so`, the bundled +`libosqpstatic.a`, the OSQP-free public header, the CMake package config +(`find_package(marinholab_solver_osqp)`) and the vendored OSQP/qdldl headers +(which are only needed to build the archive; they are not a consumer-facing +API). The pybind11 Python extension is intentionally NOT part of this +package; it is produced by `pip install .` from the same source tree. + ## Version -The version is dynamic (`dynamic = ["version"]` in `pyproject.toml`) via -`setuptools-git-versioning`, computed from the git tag/commit. `setup.py` +The Python wheel version is dynamic (`dynamic = ["version"]` in `pyproject.toml`) +via `setuptools-git-versioning`, computed from the git tag/commit. `setup.py` computes a date+commit-derived fallback when the git tag isn't available, which is why locally-built wheels may show a different distribution version — this is pre-existing and unrelated to code changes. + +The C++/Debian version is a rolling `YY.MM.NN` computed at configure time by +`cmake/GetVersion.cmake` (from `tools/version.sh`; it falls back to a +hardcoded version when `tools/` isn't present). `tools/bump-changelog.sh` +keeps `debian/changelog` in line with it before `dpkg-buildpackage`. diff --git a/CMakeLists.txt b/CMakeLists.txt index 97ed281..ef8e53d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,59 +5,133 @@ if(WIN32) set(CMAKE_TOOLCHAIN_FILE C:/vcpkg/scripts/buildsystems/vcpkg.cmake) endif() -project(marinholab_solver_osqp LANGUAGES CXX) +include(cmake/GetVersion.cmake) +project(marinholab_solver_osqp VERSION ${SOLVER_OSQP_VERSION} LANGUAGES CXX) set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) option(BUILD_EXAMPLES "Build the standalone C++ example (example/)." OFF) +# The pybind11 Python extension is built via `pip install .` / setup.py, +# which passes -DBUILD_PYTHON=ON; the C++-only build (Debian package, +# find_package consumers) leaves it OFF. +option(BUILD_PYTHON "Build the pybind11 Python extension module (_core)." OFF) +# Shared library by default; build a static library with -DBUILD_SHARED_LIBS=OFF. +# The option() establishes the default while still honouring a value that a +# parent project (or the command line) provides. +option(BUILD_SHARED_LIBS "Build the marinholab_osqp shared library" ON) find_package(Eigen3 REQUIRED) # https://stackoverflow.com/questions/38296756/what-is-the-idiomatic-way-in-cmake-to-add-the-fpic-compiler-option set(CMAKE_POSITION_INDEPENDENT_CODE ON) -# CMAKE was not passing BUILD_SHARED_LIBS nicely to the add_subdirectory. -# https://thatonegamedev.com/cpp/cmake/how-to-manage-dependencies-with-cmake/ -set(BUILD_SHARED_LIBS FALSE CACHE BOOL "x" FORCE) - -# We only need the static library, and none of OSQP's own demos/tests. +# OSQP is always built as a *static* library: its archive is bundled (installed) +# with our package rather than shipped as a separate shared object. The Python +# build additionally links it into the pybind11 module, so our own library must +# be static there as well; the C++-only build lets marinholab_osqp follow +# BUILD_SHARED_LIBS (shared by default). +if(BUILD_PYTHON) + set(BUILD_SHARED_LIBS FALSE CACHE BOOL "x" FORCE) +endif() +# We only need the static library, and none of OSQP's own demos/tests. The +# built-in algebra embeds its own linear-solver (qdldl), so the static archive +# is self-contained (only the C++ runtime and Eigen headers are needed at +# runtime), which is what lets the Debian package bundle it with no extra +# shared-library dependencies. set(OSQP_BUILD_SHARED_LIB FALSE CACHE BOOL "x" FORCE) set(OSQP_BUILD_STATIC_LIB TRUE CACHE BOOL "x" FORCE) set(OSQP_BUILD_DEMO_EXE FALSE CACHE BOOL "x" FORCE) set(OSQP_BUILD_UNITTESTS FALSE CACHE BOOL "x" FORCE) +# OSQP ships a code-generation tool; we only use its solver, so turn codegen +# off to keep the built and installed tree small. +set(OSQP_CODEGEN FALSE CACHE BOOL "x" FORCE) +# OSQP's built-in algebra pulls in its linear-solver (qdldl) via +# FetchContent. Point that at the vendored submodule so no network access is +# needed at configure time (reproducible, offline-friendly builds). +set(FETCHCONTENT_SOURCE_DIR_QDLDL "${CMAKE_CURRENT_SOURCE_DIR}/qdldl" CACHE STRING "x") add_subdirectory(osqp) -# Static library with the Solver/Configuration implementation. Both the -# pybind11 module and any standalone C++ consumer link against it, so the C++ -# code is compiled exactly once. -add_library(marinholab_osqp STATIC +# The Solver/Configuration implementation. Both the pybind11 module and the +# standalone example link against it, so the C++ code is compiled exactly once. +# Shared by default; static with -DBUILD_SHARED_LIBS=OFF. +add_library(marinholab_osqp src/core_function.cpp ) +add_library(marinholab::solvers::osqp ALIAS marinholab_osqp) + +set_target_properties(marinholab_osqp PROPERTIES + OUTPUT_NAME marinholab_solver_osqp + POSITION_INDEPENDENT_CODE ON + VERSION ${PROJECT_VERSION} + SOVERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}") target_include_directories(marinholab_osqp PUBLIC ${PROJECT_SOURCE_DIR}/include - osqp/include/public ) -target_link_libraries(marinholab_osqp PUBLIC Eigen3::Eigen osqpstatic) +# The vendored OSQP is a private implementation detail: its static archive is +# linked into this package, so consumers only ever link the +# marinholab::solvers::osqp target. The public header is OSQP-free, so its +# headers are not even exposed to consumers. +target_link_libraries(marinholab_osqp + PUBLIC Eigen3::Eigen + PRIVATE osqpstatic) # Build the standalone C++ example (see example/example.cpp). if (BUILD_EXAMPLES) add_executable(example_osqp example/example.cpp) target_link_libraries(example_osqp PRIVATE marinholab_osqp) - set_target_properties(example_osqp PROPERTIES - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/example) endif () -# Python extension. -set(PYBIND11_FINDPYTHON ON) -add_subdirectory(pybind11) -pybind11_add_module(_core MODULE - src/core.cpp - ) +# Python extension (built only for `pip install .` / setup.py). +if(BUILD_PYTHON) + set(PYBIND11_FINDPYTHON ON) + add_subdirectory(pybind11) + pybind11_add_module(_core MODULE + src/core.cpp + ) + target_link_libraries(_core PRIVATE marinholab_osqp) + # Version is dynamically obtained. See pyproject.toml + # Activating this causes issues with Windows compilation. + # target_compile_definitions(_core PRIVATE VERSION_INFO=${PROJECT_VERSION}) +endif() + +# ---- Install / CMake package (C++ part only) ---- +# Runs only under `cmake --install` (e.g. from the Debian package build); the +# `pip install .` path uses build_ext and never invokes the install rules. +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) + +# Values passed to the package config as @PACKAGE_@ (see PATH_VARS below). +# Using the actual install dirs keeps the config correct on multiarch Debian +# (libdir = lib/, includedir = include). +set(INCLUDE_INSTALL_DIR ${CMAKE_INSTALL_INCLUDEDIR}) +set(LIB_INSTALL_DIR ${CMAKE_INSTALL_LIBDIR}) + +install(TARGETS marinholab_osqp + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) + +install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + +if(BUILD_EXAMPLES) + install(TARGETS example_osqp RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +endif () + +configure_package_config_file( + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/marinholab_solver_osqp-config.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/marinholab_solver_osqp-config.cmake + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/marinholab_solver_osqp + PATH_VARS INCLUDE_INSTALL_DIR LIB_INSTALL_DIR) + +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/marinholab_solver_osqp-config-version.cmake + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion) -target_link_libraries(_core PRIVATE marinholab_osqp) -# Version is dynamically obtained. See pyproject.toml -# Activating this causes issues with Windows compilation. -# target_compile_definitions(_core PRIVATE VERSION_INFO=${PROJECT_VERSION}) +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/marinholab_solver_osqp-config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/marinholab_solver_osqp-config-version.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/marinholab_solver_osqp) diff --git a/README.md b/README.md index e4d6625..aefb32a 100644 --- a/README.md +++ b/README.md @@ -98,8 +98,8 @@ pybind11 layer over it). It is built with namespace osqp = marinholab::solvers::osqp; osqp::Configuration config; -config.eps_abs = 1.0e-9; // the rest keeps its defaults -config.polishing = 1; +config.set("eps_abs", 1.0e-9); // the rest keeps its defaults +config.set("polishing", true); osqp::Solver solver(config); @@ -151,18 +151,24 @@ the pybind11 surface in `src/core.cpp`. ## Configuration All of OSQP's `OSQPSettings` fields are exposed, plus one wrapper-specific -setting. Create a `Configuration`, tweak the fields you need, and pass it to -the solver: +setting. Options are set by name. Create a `Configuration`, set the options +you need, and pass it to the solver: ```python config = osqp.Configuration() -config.eps_abs = 1.0e-9 # tighter absolute tolerance -config.eps_rel = 1.0e-9 # tighter relative tolerance -config.max_iter = 20000 # more ADMM iterations -config.polishing = 1 # polish the ADMM solution +config.set("eps_abs", 1.0e-9) # tighter absolute tolerance +config.set("eps_rel", 1.0e-9) # tighter relative tolerance +config.set("max_iter", 20000) # more ADMM iterations +config.set("polishing", True) # polish the ADMM solution solver = osqp.Solver(config) ``` +Values may be given as bool, int, float, or str (enum options take the enum +value name, e.g. `"OSQP_DIRECT_SOLVER"`, or a `LinsysSolverType` member; +`set()` also converts strings such as `"1e-9"` or `"false"`). Unset options +keep OSQP's own defaults. `config.keys()` and `config.defaults()` list the +full option names and their defaults. + The enum types are re-exported for convenience: `osqp.LinsysSolverType`, `osqp.PreconditionerType`, and `osqp.Status`. diff --git a/cmake/GetVersion.cmake b/cmake/GetVersion.cmake new file mode 100644 index 0000000..f20ca43 --- /dev/null +++ b/cmake/GetVersion.cmake @@ -0,0 +1,27 @@ +# Compute the rolling version (YY.MM.NN) at configure time. +# Falls back to a hardcoded version when tools/version.sh is unavailable +# (e.g. when building from a release tarball without the tools/ directory). +# +# Named SOLVER_OSQP_VERSION (not OSQP_VERSION) on purpose: OSQP's own CMake +# also defines an internal `OSQP_VERSION` variable for its private +# version.h. Keeping the names distinct avoids clobbering OSQP's when we +# `add_subdirectory(osqp)`. +set(SOLVER_OSQP_FALLBACK_VERSION "26.09.00") + +if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/../tools/version.sh") + execute_process( + COMMAND bash "${CMAKE_CURRENT_LIST_DIR}/../tools/version.sh" + OUTPUT_VARIABLE _solver_osqp_version + RESULT_VARIABLE _solver_osqp_version_result + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + if(NOT _solver_osqp_version_result EQUAL 0 OR NOT _solver_osqp_version MATCHES "^[0-9]+\\.[0-9]+\\.[0-9]+$") + set(_solver_osqp_version "${SOLVER_OSQP_FALLBACK_VERSION}") + endif() +else() + set(_solver_osqp_version "${SOLVER_OSQP_FALLBACK_VERSION}") +endif() + +set(SOLVER_OSQP_VERSION "${_solver_osqp_version}") +message(STATUS "marinholab_solver_osqp version: ${SOLVER_OSQP_VERSION}") diff --git a/cmake/marinholab_solver_osqp-config.cmake.in b/cmake/marinholab_solver_osqp-config.cmake.in new file mode 100644 index 0000000..361399d --- /dev/null +++ b/cmake/marinholab_solver_osqp-config.cmake.in @@ -0,0 +1,28 @@ +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) +# The public header uses Eigen types in its method signatures. +find_dependency(Eigen3) +# OSQP is a private implementation detail, not a consumer-facing dependency: +# its static archive (with its linear-solver embedded) is linked into +# marinholab_solver_osqp, and the public header marinholab/solvers/osqp.h is +# OSQP-free, so consumers neither find_package() nor link OSQP directly. + +find_library(marinholab_solver_osqp_LIBRARY NAMES marinholab_solver_osqp + PATHS "@PACKAGE_LIB_INSTALL_DIR@" NO_DEFAULT_PATH) +find_path(marinholab_solver_osqp_INCLUDE_DIR NAMES marinholab/solvers/osqp.h + PATHS "@PACKAGE_INCLUDE_INSTALL_DIR@" NO_DEFAULT_PATH) + +if(marinholab_solver_osqp_LIBRARY AND marinholab_solver_osqp_INCLUDE_DIR) + add_library(marinholab::solvers::osqp SHARED IMPORTED) + set_target_properties(marinholab::solvers::osqp PROPERTIES + IMPORTED_LOCATION "${marinholab_solver_osqp_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${marinholab_solver_osqp_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES "Eigen3::Eigen") +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(marinholab_solver_osqp + REQUIRED_VARS + marinholab_solver_osqp_LIBRARY + marinholab_solver_osqp_INCLUDE_DIR) diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..194357a --- /dev/null +++ b/debian/changelog @@ -0,0 +1,9 @@ +libmarinholab-solver-osqp (26.09.00) noble; urgency=medium + + * Initial Debian package of the C++ part of the solver-osqp project: + the marinholab::solvers::osqp library (Solver + Configuration) and its + OSQP dependency, built with CMake and -O3. + The pybind11 Python extension is not packaged; it is built by + `pip install .`. + + -- Murilo M Marinho Wed, 16 Sep 2026 00:00:00 +0100 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..9239fe6 --- /dev/null +++ b/debian/control @@ -0,0 +1,28 @@ +Source: libmarinholab-solver-osqp +Section: libs +Priority: optional +Maintainer: Murilo M Marinho +Build-Depends: debhelper-compat (= 13), + make, + cmake, + g++, + libeigen3-dev +Standards-Version: 4.6.2 +Homepage: https://github.com/MarinhoLab/solver-osqp + +Package: libmarinholab-solver-osqp +Architecture: any +Multi-Arch: same +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: C++ OSQP ADMM solver wrapper (marinholab) + The marinholab-solvers-osqp C++ package provides the ROS-independent + C++ part of the solver-osqp project: the marinholab::solvers::osqp + namespace with the Solver (a first-order ADMM quadratic-program solver + wrapping OSQP's OSQPSolver) and its Configuration option holder. + . + It is built with CMake (with -O3) and exposes the CMake target + marinholab::solvers::osqp. The OSQP dependency (osqp/osqp) is vendored as a + git submodule, built as a static archive (its linear-solver, qdldl, is + embedded), and bundled into the same package. The pybind11 Python extension + is intentionally NOT part of this package; it is produced by `pip install .` + from the same source tree. diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..f750f86 --- /dev/null +++ b/debian/copyright @@ -0,0 +1,40 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: marinholab-solvers-osqp +Upstream-Contact: Murilo M Marinho +Source: https://github.com/MarinhoLab/solver-osqp + +Files: * +Copyright: 2026 Murilo Marques Marinho +License: LGPL-2.1+ + +Files: osqp/* +Copyright: 2017-2023 OSQP Team (https://osqp.org/) +License: Apache-2.0 + +License: LGPL-2.1+ + This package is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation; either version 2.1 of the + License, or (at your option) any later version. + . + This package is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + . + You should have received a copy of the GNU Lesser General Public + License along with this program. If not, see + . + +License: Apache-2.0 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. diff --git a/debian/rules b/debian/rules new file mode 100644 index 0000000..1a3aa15 --- /dev/null +++ b/debian/rules @@ -0,0 +1,20 @@ +#!/usr/bin/make -f + +# LTO is disabled (-fno-lto, appended after the distro flags so it wins): +# Ubuntu noble enables -flto=auto by default, and linking the vendored static +# OSQP archive into this wrapper can trip a GCC 13 linker internal compiler +# error on x86-64. It also buys no real benefit for a wrapper this small. +export CFLAGS := $(shell dpkg-buildflags --get CFLAGS) -fno-lto +export CXXFLAGS := $(shell dpkg-buildflags --get CXXFLAGS) -fno-lto +export CPPFLAGS := $(shell dpkg-buildflags --get CPPFLAGS) +export LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS) -fno-lto + +%: + dh $@ --buildsystem=cmake + +override_dh_auto_configure: + dh_auto_configure -- \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG" \ + -DCMAKE_INSTALL_PREFIX=/usr \ + -DBUILD_EXAMPLES=OFF diff --git a/debian/source/format b/debian/source/format new file mode 100644 index 0000000..89ae9db --- /dev/null +++ b/debian/source/format @@ -0,0 +1 @@ +3.0 (native) diff --git a/docker/Dockerfile b/docker/Dockerfile index 874e25a..70d80f9 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -5,5 +5,5 @@ ENV BASH_ENV="/etc/bash_env" RUN apt-get update RUN apt-get install -y python3 python3-pip cmake libeigen3-dev git -RUN pip install setuptools-git-versioning numpy --break-system-packages +RUN pip install setuptools-git-versioning numpy pytest --break-system-packages COPY . /root/solver-osqp diff --git a/docker/build-deb.sh b/docker/build-deb.sh new file mode 100644 index 0000000..c121b3f --- /dev/null +++ b/docker/build-deb.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Build the C++ Debian package (.deb) in an Ubuntu noble container. +# +# Produces only the C++ part of the project (the marinholab::solvers::osqp +# library + the vendored OSQP), with -O3. The pybind11 Python extension is +# intentionally not part of the .deb (it is built by `pip install .`). +# +# Usage: +# bash docker/build-deb.sh # build the .deb -> ./.deb-out/ +# bash docker/build-deb.sh --test # also install it and build/run a +# # find_package consumer inside the container +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TEST=0 +[ "${1:-}" = "--test" ] && TEST=1 + +IMAGE="marinholab-solver-osqp-deb" +TAG="$(date +%Y%m%d%H%M)" + +echo "=== Building ${IMAGE}:${TAG} ===" +docker build -f "${ROOT}/docker/deb.Dockerfile" -t "${IMAGE}:${TAG}" "${ROOT}" + +OUT="${ROOT}/.deb-out" +mkdir -p "${OUT}" + +WORKDIR="/opt/solver-osqp" +if [ "${TEST}" -eq 1 ]; then + # Build the package, install it, then build/run a find_package consumer. + docker run --rm -v "${OUT}:/deb-out" "${IMAGE}:${TAG}" bash -c " + set -euxo pipefail + cd ${WORKDIR} + bash tools/bump-changelog.sh + dpkg-buildpackage -us -uc -b + DEB=\$(ls /opt/*.deb | head -n1) + dpkg -i \"\${DEB}\" + mkdir -p /tmp/consumer && cd /tmp/consumer + cat > main.cpp <<'EOF' +#include +#include +namespace osqp = marinholab::solvers::osqp; +int main() +{ + osqp::Configuration config; + config.set(\"eps_abs\", 1.0e-9); + osqp::Solver solver(config); + Eigen::MatrixXd H = Eigen::MatrixXd::Identity(2, 2); + Eigen::VectorXd f(2); f << -1.0, -1.0; + Eigen::MatrixXd A(1, 2); A << 1.0, 0.0; + Eigen::VectorXd b(1); b << 0.2; + Eigen::MatrixXd Aeq = Eigen::MatrixXd::Zero(1, 2); + Eigen::VectorXd beq = Eigen::VectorXd::Zero(1); + Eigen::VectorXd x = solver.solve_quadratic_program(H, f, A, b, Aeq, beq); + std::cout << \"consumer x = \" << x.transpose() << std::endl; + return 0; +} +EOF + cat > CMakeLists.txt <<'EOF' +cmake_minimum_required(VERSION 3.16) +project(consumer CXX) +find_package(marinholab_solver_osqp REQUIRED) +add_executable(consumer main.cpp) +target_link_libraries(consumer PRIVATE marinholab::solvers::osqp) +EOF + cmake -B b -DCMAKE_BUILD_TYPE=Release . && cmake --build b && ./b/consumer + cp \"\${DEB}\" /deb-out/ + " +else + docker run --rm -v "${OUT}:/deb-out" "${IMAGE}:${TAG}" bash -c " + set -euxo pipefail + cd ${WORKDIR} + bash tools/bump-changelog.sh + dpkg-buildpackage -us -uc -b + cp /opt/*.deb /deb-out/ + " +fi + +echo "=== .deb written to ${OUT} ===" +ls -la "${OUT}" diff --git a/docker/compose.yml b/docker/compose.yml index 0492217..0854889 100644 --- a/docker/compose.yml +++ b/docker/compose.yml @@ -8,4 +8,5 @@ services: command: /bin/bash -c " cd /root/solver-osqp && pip install . --break-system-packages + && (cd tests && python3 -m pytest -q) && osqp_example" diff --git a/docker/deb.Dockerfile b/docker/deb.Dockerfile new file mode 100644 index 0000000..7eb4f1b --- /dev/null +++ b/docker/deb.Dockerfile @@ -0,0 +1,18 @@ +FROM ubuntu:noble +LABEL authors="murilomarinho" +SHELL ["/bin/bash", "-c"] +ENV DEBIAN_FRONTEND=noninteractive + +# Toolchain, C++ dependency and Debian packaging tools. OSQP and its +# linear-solver (qdldl) are vendored as git submodules, so only Eigen needs +# to come from the archive. +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential g++ cmake make pkg-config git \ + libeigen3-dev \ + dpkg-dev debhelper devscripts \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /opt/solver-osqp +COPY . /opt/solver-osqp + +CMD ["bash", "/opt/solver-osqp/docker/build-deb.sh"] diff --git a/evaluation/compare_qpoases_osqp.py b/evaluation/compare_qpoases_osqp.py index 5d039fe..84e131b 100644 --- a/evaluation/compare_qpoases_osqp.py +++ b/evaluation/compare_qpoases_osqp.py @@ -119,10 +119,10 @@ def main(): osqp_config = osqp.Configuration() # Tighten OSQP's tolerances/enable polishing so that its ADMM solution is # directly comparable to qpOASES' active-set solution. - osqp_config.eps_abs = 1e-7 - osqp_config.eps_rel = 1e-7 - osqp_config.max_iter = 20000 - osqp_config.polishing = 1 + osqp_config.set("eps_abs", 1e-7) + osqp_config.set("eps_rel", 1e-7) + osqp_config.set("max_iter", 20000) + osqp_config.set("polishing", True) all_passed = True diff --git a/example/example.cpp b/example/example.cpp index 37de075..abab02d 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -20,12 +20,13 @@ namespace osqp = marinholab::solvers::osqp; int main() { - // 1. Configure the solver. Only a couple of fields are set here; the rest - // keep their defaults (which mirror OSQP's own defaults for a standard - // double-precision, direct-solver build; see osqp_set_default_settings()). + // 1. Configure the solver. Only a couple of options are set here; the + // rest keep their defaults (which mirror OSQP's own defaults for a + // standard double-precision, direct-solver build; see + // osqp_set_default_settings()). osqp::Configuration config; - config.eps_abs = 1.0e-9; // tighter absolute tolerance - config.eps_rel = 1.0e-9; // tighter relative tolerance + config.set("eps_abs", 1.0e-9); // tighter absolute tolerance + config.set("eps_rel", 1.0e-9); // tighter relative tolerance osqp::Solver solver(config); diff --git a/include/marinholab/solvers/osqp.h b/include/marinholab/solvers/osqp.h index 14d735f..2864d2f 100644 --- a/include/marinholab/solvers/osqp.h +++ b/include/marinholab/solvers/osqp.h @@ -1,9 +1,12 @@ #pragma once +#include +#include +#include +#include #include -#include -#include +#include namespace marinholab { @@ -13,268 +16,127 @@ namespace solvers namespace osqp { -// Keep the using-directive scoped to this namespace rather than global -// scope: a global `using namespace Eigen;` would also be active while -// is parsed, which is unnecessary and can surprise code that -// includes this header. -using namespace Eigen; /** - * @brief Holds all user-configurable solver options. + * @brief The value of an option: a boolean, an integer, a real, or the + * name of an enumeration value (e.g. "OSQP_DIRECT_SOLVER"). + * + * Enumeration values are held by name so that this header stays free of + * OSQP types. + */ +using OptionValue = std::variant; + +/** + * @brief Holds all user-configurable solver options, keyed by name. + * + * Every OSQP `OSQPSettings` field plus the wrapper-specific settings is + * exposed under its name. Each option has a kind, and values are stored as + * that kind: + * + * - booleans: `bool` + * - integers: `long long` + * - reals: `double` + * - enumerations: `std::string` holding the enum value name, e.g. + * "OSQP_DIRECT_SOLVER", "OSQP_DIAGONAL_PRECONDITIONER" * - * Every `OSQPSettings` field is exposed here. Defaults match OSQP's own - * defaults for a standard double-precision, direct-solver build (see - * `osqp_set_default_settings()`), except `verbose`, which defaults to off so - * the solver is quiet by default. + * `set()` also accepts strings for the other kinds ("true"/"false", an + * integer or floating-point literal) and an integer for a real, and + * converts them. * - * @note OSQP validates its settings at setup/update time and will reject a - * build with settings outside their allowed range (e.g. non-positive - * tolerances). + * Unset options use OSQP's own defaults for a double-precision, + * direct-solver build (see `osqp_set_default_settings()`), taken directly + * from OSQP, except `verbose`, which defaults to the least verbose value + * (`false`) so the solver is quiet by default (OSQP's own default is `true`). + * + * @see Solver */ -struct Configuration +class Configuration { - // ------------------------------------------------------------------ - // Wrapper-specific option (not part of OSQP's `OSQPSettings`). - // ------------------------------------------------------------------ - +public: /** - * @brief Whether subsequent solves reuse the existing OSQP solver and - * update its data in place (`osqp_update_data_vec` / - * `osqp_update_data_mat`) instead of calling `osqp_setup()` again. + * @brief Default constructor. * - * This is analogous to qpOASES' `use_hotstart`. It only applies when the - * problem dimensions and sparsity pattern are unchanged since the last - * call; a change in shape always triggers a fresh `osqp_setup()`. + * Starts with an empty option map: every option holds its default. */ - bool use_hotstart = true; + Configuration(); - // ------------------------------------------------------------------ - // OSQP `OSQPSettings` fields (1:1 mapping, native snake_case names). - // ------------------------------------------------------------------ + /** @brief Copy constructor. */ + Configuration(const Configuration& other); - // Linear algebra settings + /** @brief Copy assignment. */ + Configuration& operator=(const Configuration& other); - /** - * @brief Device identifier; currently used for CUDA devices. - * @see `OSQPSettings::device` - */ - OSQPInt device = 0; + /** @brief Destructor. */ + ~Configuration(); /** - * @brief Linear system solver to use. - * @see `OSQPSettings::linsys_solver` - */ - ::osqp_linsys_solver_type linsys_solver = ::OSQP_DIRECT_SOLVER; - - // Control settings - - /** - * @brief Whether the solution is allocated in the solver during - * `osqp_setup()`. - * @see `OSQPSettings::allocate_solution` - */ - OSQPInt allocate_solution = 1; - - /** - * @brief Whether solver progress is written out. + * @brief Sets the option `key` to `value`. * - * Defaults to off so the solver is quiet by default; note this - * intentionally differs from OSQP's own default (`OSQP_VERBOSE = 1`). - * @see `OSQPSettings::verbose` - */ - OSQPInt verbose = 0; - - /** - * @brief Level of detail for profiler annotations. - * @see `OSQPSettings::profiler_level` - */ - OSQPInt profiler_level = 0; - - /** - * @brief Whether OSQP warm-starts from the previous solution between - * consecutive `osqp_solve()` calls. - * @see `OSQPSettings::warm_starting` - */ - OSQPInt warm_starting = OSQP_WARM_STARTING; - - /** - * @brief Number of heuristic data-scaling iterations; `0` disables - * scaling. - * @see `OSQPSettings::scaling` - */ - OSQPInt scaling = OSQP_SCALING; - - /** - * @brief Whether the ADMM solution is polished to improve accuracy. - * @see `OSQPSettings::polishing` - */ - OSQPInt polishing = OSQP_POLISHING; - - // ADMM parameters - - /** - * @brief ADMM penalty parameter (scalar). - * @see `OSQPSettings::rho` - */ - OSQPFloat rho = OSQP_RHO; - - /** - * @brief Whether `rho` is a scalar or a vector. - * @see `OSQPSettings::rho_is_vec` - */ - OSQPInt rho_is_vec = OSQP_RHO_IS_VEC; - - /** - * @brief ADMM regularization parameter (improves conditioning). - * @see `OSQPSettings::sigma` - */ - OSQPFloat sigma = OSQP_SIGMA; - - /** - * @brief ADMM relaxation parameter. - * @see `OSQPSettings::alpha` - */ - OSQPFloat alpha = OSQP_ALPHA; - - // CG settings - - /** - * @brief Maximum number of CG iterations per solve. - * @see `OSQPSettings::cg_max_iter` - */ - OSQPInt cg_max_iter = OSQP_CG_MAX_ITER; - - /** - * @brief Number of consecutive zero CG iterations before the tolerance - * is halved. - * @see `OSQPSettings::cg_tol_reduction` - */ - OSQPInt cg_tol_reduction = OSQP_CG_TOL_REDUCTION; - - /** - * @brief CG tolerance, as a fraction of the ADMM residuals. - * @see `OSQPSettings::cg_tol_fraction` - */ - OSQPFloat cg_tol_fraction = OSQP_CG_TOL_FRACTION; - - /** - * @brief Preconditioner used by the CG method. - * @see `OSQPSettings::cg_precond` - */ - ::osqp_precond_type cg_precond = ::OSQP_DIAGONAL_PRECONDITIONER; - - // Adaptive rho logic - - /** - * @brief ADMM `rho` stepsize adaptation method. - * @see `OSQPSettings::adaptive_rho` - */ - OSQPInt adaptive_rho = OSQP_ADAPTIVE_RHO_UPDATE_DEFAULT; - - /** - * @brief Interval between `rho` adaptations (used when - * `adaptive_rho == OSQP_ADAPTIVE_RHO_UPDATE_ITERATIONS`). - * @see `OSQPSettings::adaptive_rho_interval` - */ - OSQPInt adaptive_rho_interval = OSQP_ADAPTIVE_RHO_INTERVAL; - - /** - * @brief Adaptation parameter controlling when non-fixed `rho` - * adaptations occur (fraction of setup time, or of the previous - * KKT error, depending on `adaptive_rho`). - * @see `OSQPSettings::adaptive_rho_fraction` - */ - OSQPFloat adaptive_rho_fraction = OSQP_ADAPTIVE_RHO_FRACTION; - - /** - * @brief Tolerance applied when adapting `rho`: the new `rho` must be - * this many times larger or smaller than the current one. - * @see `OSQPSettings::adaptive_rho_tolerance` - */ - OSQPFloat adaptive_rho_tolerance = OSQP_ADAPTIVE_RHO_TOLERANCE; - - // Termination parameters - - /** - * @brief Maximum number of ADMM iterations. - * @see `OSQPSettings::max_iter` - */ - OSQPInt max_iter = OSQP_MAX_ITER; - - /** - * @brief Absolute solution tolerance. - * @see `OSQPSettings::eps_abs` - */ - OSQPFloat eps_abs = OSQP_EPS_ABS; - - /** - * @brief Relative solution tolerance. - * @see `OSQPSettings::eps_rel` + * The value is validated and converted to the option's kind + * immediately, so a misspelled key or a wrong type raises + * `std::invalid_argument` here rather than at solve time. + * + * @throws std::invalid_argument if the key is unknown or the value + * cannot be converted to that option's kind. */ - OSQPFloat eps_rel = OSQP_EPS_REL; + void set(const std::string& key, const OptionValue& value); /** - * @brief Primal infeasibility detection tolerance. - * @see `OSQPSettings::eps_prim_inf` + * @brief Sets the option `key` from a string literal (so that it is + * not converted to `bool`). + * + * @throws std::invalid_argument as `set(const std::string&, const OptionValue&)`. */ - OSQPFloat eps_prim_inf = OSQP_EPS_PRIM_INF; + void set(const std::string& key, const char* value); /** - * @brief Dual infeasibility detection tolerance. - * @see `OSQPSettings::eps_dual_inf` + * @brief Returns the value of the option `key`. + * + * @return The value, as the option's kind, or the option's default when + * it has not been set. + * @throws std::invalid_argument if the key is unknown. */ - OSQPFloat eps_dual_inf = OSQP_EPS_DUAL_INF; + OptionValue get(const std::string& key) const; /** - * @brief Whether the scaled termination criteria are used. - * @see `OSQPSettings::scaled_termination` + * @brief Whether the option `key` has been explicitly set. + * + * @return `true` when `set()` was called for `key`. + * @throws std::invalid_argument if the key is unknown. */ - OSQPInt scaled_termination = OSQP_SCALED_TERMINATION; + bool has(const std::string& key) const; /** - * @brief Interval at which termination is checked; `0` disables the - * periodic check. - * @see `OSQPSettings::check_termination` + * @brief The names of all settable options, sorted. + * + * @return A copy of the sorted option names. */ - OSQPInt check_termination = OSQP_CHECK_TERMINATION; + std::vector keys() const; /** - * @brief Whether the duality-gap termination criteria are used. - * @see `OSQPSettings::check_dualgap` + * @brief Removes `key` so the option reverts to its default. + * + * @throws std::invalid_argument if the key is unknown. */ - OSQPInt check_dualgap = OSQP_CHECK_DUALGAP; + void reset(const std::string& key); /** - * @brief Maximum time to solve the problem, in seconds. - * @see `OSQPSettings::time_limit` + * @brief Removes all options, reverting every one to its default. */ - OSQPFloat time_limit = OSQP_TIME_LIMIT; - - // Polishing parameters + void reset_all(); /** - * @brief Regularization parameter used by polishing. - * @see `OSQPSettings::delta` + * @brief The option names and their default values, sorted. + * + * @return A copy of the `{name: default_value}` map. */ - OSQPFloat delta = OSQP_DELTA; + std::map defaults() const; - /** - * @brief Number of iterative refinement steps performed during - * polishing. - * @see `OSQPSettings::polish_refine_iter` - */ - OSQPInt polish_refine_iter = OSQP_POLISH_REFINE_ITER; +private: + friend class Solver; - /** - * @brief Default constructor. - * - * Initialises every option to the defaults documented above. - * - * @note Declared here and defined out of line so that the in-class - * member initializers are used as expected. See - * https://stackoverflow.com/questions/53408962 - */ - Configuration(); + /** @brief Explicitly set option values, keyed by option name. */ + std::map options_; }; /** @@ -283,197 +145,141 @@ struct Configuration * * `Solver` exposes OSQP's first-order ADMM solver through a * MATLAB/`quadprog`-like, matrix-based interface. Internally it keeps an - * OSQP `OSQPSolver` object so that, once initialised, subsequent calls are - * warm-started (see `use_hotstart` and `warm_starting`). + * `OSQPSolver` so that, once set up, subsequent calls on the same instance + * reuse it and update its data in place by default (see the `use_hotstart` + * option); OSQP additionally warm-starts from the previous iterate between + * `osqp_solve()` calls. * - * The solver is configured through a `Configuration` structure whose members - * map directly onto OSQP's `OSQPSettings` struct. In addition to the standard - * OSQP settings, the configuration carries the wrapper-specific `use_hotstart` - * setting. + * The solver is configured through a `Configuration` keyed by option name. * - * @note The class is not thread-safe: a single instance owns one underlying - * OSQP solver and its state changes across calls. + * @note The class is not thread-safe: a single instance owns one + * underlying OSQP solver and its state changes across calls. + * @note The class is movable but not copyable (it owns the underlying + * solver state). */ class Solver { - protected: - /** @brief True until the first solve has set up the solver. */ - bool osqp_solve_first_time_; - /** @brief The underlying OSQP solver. */ - ::OSQPSolver* osqp_solver_; - /** @brief Active configuration, copied at construction. */ - Configuration configuration_; - - /** - * @brief Dimensions used in the last successful `osqp_setup()` call. - * Used to detect whether a new call is compatible with hotstarting or - * requires a fresh `osqp_setup()`. - */ - OSQPInt problem_size_; - OSQPInt constraint_size_; - - /** - * @brief Holds the CSC (compressed-sparse-column) arrays of a - * converted Eigen matrix. - * - * The vectors own the storage so that it outlives the temporary - * `OSQPCscMatrix` wrapper used when calling `osqp_setup()` / - * `osqp_update_data_mat()`. - */ - struct CSCMatrixData - { - std::vector x; - std::vector i; - std::vector p; - OSQPInt rows{0}; - OSQPInt cols{0}; - }; - - /** - * @brief Copies an Eigen vector into a std::vector. - * @param vectorxd Source vector. - * @return A copy of the vector's data. - * - * Copied from SmartArmStack's sas_conversions - * (https://github.com/SmartArmStack/sas_conversions/blob/master/src/eigen3_std_conversions.cpp). - */ - std::vector _vectorxd_to_std_vector_double(const VectorXd& vectorxd); - - /** - * @brief Maps a std::vector into an Eigen vector. - * @param std_vector_double Source vector. - * @return An Eigen vector wrapping the source data. - */ - VectorXd _std_vector_double_to_vectorxd(std::vector std_vector_double) const; - - /** - * @brief Converts a dense n x n matrix into the upper-triangular CSC - * representation required by OSQP for P. - * @param M Source matrix. - * @return The CSC arrays of the (upper triangle of the) matrix. - */ - static CSCMatrixData _dense_to_csc_upper_triangular(const MatrixXd& M); - - /** - * @brief Converts a dense m x n matrix into a structurally-dense CSC - * representation (i.e. every entry, including zeros, is stored - * explicitly). - * - * Keeping the sparsity pattern stable across calls is what allows - * `osqp_update_data_mat()` to be used when hotstarting. - * @param M Source matrix. - * @return The CSC arrays of the matrix. - */ - static CSCMatrixData _dense_to_csc(const MatrixXd& M); - - /** - * @brief Translates the user configuration into an `OSQPSettings` - * object. - * @return An `OSQPSettings` with all fields filled from - * `configuration_`. - */ - OSQPSettings _to_osqp_settings() const; - - /** - * @brief Releases the current `osqp_solver_` instance, if any. - */ - void _cleanup(); - - public: - /** - * @brief Named solution-quality values obtained from the last - * successful call to solve_quadratic_program(). - * - * See `OSQPInfo` in osqp_api_types.h for further details. - */ - struct Info - { - //Primal objective value. See OSQPInfo::obj_val. - OSQPFloat obj_val = 0.0; - //Dual objective value. See OSQPInfo::dual_obj_val. - OSQPFloat dual_obj_val = 0.0; - //Norm of the primal residual. See OSQPInfo::prim_res. - OSQPFloat prim_res = 0.0; - //Norm of the dual residual. See OSQPInfo::dual_res. - OSQPFloat dual_res = 0.0; - //Dual solution, i.e. the Lagrange multiplier associated with l <= Ax <= u. - //See OSQPSolution::y. - VectorXd dual_solution; - Info(); //https://stackoverflow.com/questions/53408962/try-to-understand-compiler-error-message-default-member-initializer-required-be - }; +public: + /** + * @brief Constructs a solver. + * @param configuration Options to use; defaults to the default + * configuration. + */ + explicit Solver(const Configuration& configuration = Configuration()); - /** - * @brief Constructs a solver. - * @param configuration Options to use; defaults to the default - * configuration. - */ - Solver(const Configuration& configuration = Configuration()); + /** + * @brief Move constructor. + * @param other The solver to move from. + */ + Solver(Solver&& other) noexcept; - /** @brief Destructor; releases the underlying OSQP solver. */ - ~Solver(); + /** + * @brief Move assignment. + * @param other The solver to move from. + */ + Solver& operator=(Solver&& other) noexcept; - //Not copyable, as this class owns a raw ::OSQPSolver* that is not reference counted. - Solver(const Solver&) = delete; - Solver& operator=(const Solver&) = delete; + /** @brief Solvers are not copyable (they own the solver state). */ + Solver(const Solver&) = delete; - /** - * @brief Solves the following quadratic program: - * - * min(x) 0.5*x'Hx + f'x - * s.t. Ax <= b - * Aeq*x = beq. - * - * Method signature is compatible with MATLAB's `quadprog`. - * - * @param H the n x n matrix of the quadratic coefficients of the - * decision variables. - * @param f the n x 1 vector of the linear coefficients of the - * decision variables. - * @param A the m x n matrix of inequality constraints. - * @param b the m x 1 value for the inequality constraints. - * @param Aeq the k x n matrix of equality constraints. - * @param beq the k x 1 value for the equality constraints. - * @param x0 optional n x 1 warm-start for the primal variable x, e.g. a - * known feasible solution. Passed to OSQP via - * `osqp_warm_start()`. Pass an empty vector (the default) to - * skip warm-starting. Must be compatible with H.rows() when - * provided. - * @param y0 optional warm-start for the dual variable y, e.g. a dual - * solution obtained from get_info().dual_solution in a previous - * call. Passed to OSQP via `osqp_warm_start()`. Pass an empty - * vector (the default) to skip dual warm-starting. Must have - * b.size()+beq.size() entries when provided. - * @return the optimal x. - * @throws std::runtime_error if any matrix is size-incompatible or - * OSQP fails to solve the problem. - */ - VectorXd solve_quadratic_program(const MatrixXd& H, const VectorXd& f, const MatrixXd& A, const VectorXd& b, const MatrixXd& Aeq, const VectorXd& beq, const VectorXd& x0 = VectorXd(), const VectorXd& y0 = VectorXd()); + /** @brief Solvers are not copyable (they own the solver state). */ + Solver& operator=(const Solver&) = delete; - /** - * @brief Returns named solution-quality values (obj_val, dual_obj_val, - * prim_res, dual_res) and the dual solution (dual_solution) from - * the last successful call to solve_quadratic_program(). - * @throws std::runtime_error if solve_quadratic_program() has not been - * called successfully yet. - * @return an Info instance with the values populated. - */ - Info get_info() const; + /** @brief Destructor; releases the underlying OSQP solver. */ + ~Solver(); + /** + * @brief Named solution-quality values obtained from the last + * successful call to solve_quadratic_program(). + * + * See `OSQPInfo` in `osqp_api_types.h` for further details. + */ + struct Info + { + /** @brief Primal objective value. See `OSQPInfo::obj_val`. */ + double obj_val = 0.0; + /** @brief Dual objective value. See `OSQPInfo::dual_obj_val`. */ + double dual_obj_val = 0.0; + /** @brief Norm of the primal residual. See `OSQPInfo::prim_res`. */ + double prim_res = 0.0; + /** @brief Norm of the dual residual. See `OSQPInfo::dual_res`. */ + double dual_res = 0.0; /** - * @brief Round-trips a vector to help evaluate the Eigen <-> std - * conversions used across the wrapper. - * @param v The vector to test. - * @return The same vector. + * @brief Dual solution, i.e. the Lagrange multiplier associated + * with `l <= A x <= u`. See `OSQPSolution::y`. */ - VectorXd test_vectorxd(const VectorXd& v); + Eigen::VectorXd dual_solution; + }; - /** - * @brief Round-trips a matrix to help evaluate the Eigen <-> std - * conversions used across the wrapper. - * @param m The matrix to test. - * @return The same matrix. - */ - MatrixXd test_matrixxd(const MatrixXd& m); + /** + * @brief Solves the following quadratic program: + * + * min(x) 0.5*x'Hx + f'x + * s.t. Ax <= b + * Aeq*x = beq. + * + * Method signature is compatible with MATLAB's `quadprog`. + * + * @param H the n x n matrix of the quadratic coefficients of the + * decision variables. + * @param f the n x 1 vector of the linear coefficients of the + * decision variables. + * @param A the m x n matrix of inequality constraints. + * @param b the m x 1 value for the inequality constraints. + * @param Aeq the k x n matrix of equality constraints. + * @param beq the k x 1 value for the equality constraints. + * @param x0 optional n x 1 warm-start for the primal variable x, e.g. a + * known feasible solution. Passed to OSQP via + * `osqp_warm_start()`. Pass an empty vector (the default) to + * skip warm-starting. Must be compatible with H.rows() when + * provided. + * @param y0 optional warm-start for the dual variable y, e.g. a dual + * solution obtained from get_info().dual_solution in a previous + * call. Passed to OSQP via `osqp_warm_start()`. Pass an empty + * vector (the default) to skip dual warm-starting. Must have + * b.size()+beq.size() entries when provided. + * @return the optimal x + * @throws std::runtime_error if any matrix is size-incompatible or + * OSQP fails to solve the problem. + */ + Eigen::VectorXd solve_quadratic_program(const Eigen::MatrixXd& H, const Eigen::VectorXd& f, const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const Eigen::MatrixXd& Aeq, const Eigen::VectorXd& beq, const Eigen::VectorXd& x0 = Eigen::VectorXd(), const Eigen::VectorXd& y0 = Eigen::VectorXd()); + + /** + * @brief Returns named solution-quality values (obj_val, dual_obj_val, + * prim_res, dual_res) and the dual solution (dual_solution) from + * the last successful call to solve_quadratic_program(). + * @throws std::runtime_error if solve_quadratic_program() has not been + * called successfully yet. + * @return an Info instance with the values populated. + */ + Info get_info() const; + + /** + * @brief Round-trips a vector to help evaluate the Eigen <-> std + * conversions used across the wrapper. + * @param v The vector to test. + * @return The same vector. + */ + Eigen::VectorXd test_vectorxd(const Eigen::VectorXd& v); + + /** + * @brief Round-trips a matrix to help evaluate the Eigen <-> std + * conversions used across the wrapper. + * @param m The matrix to test. + * @return The same matrix. + */ + Eigen::MatrixXd test_matrixxd(const Eigen::MatrixXd& m); + +private: + /** + * @brief Implementation (pimpl): owns the underlying OSQP solver and + * the conversion helpers. + * + * Declared here and defined in the implementation so that OSQP types + * never appear in this public header. + */ + struct Impl; + std::unique_ptr impl_; }; } // namespace osqp diff --git a/marinholab/solvers/osqp/__init__.py b/marinholab/solvers/osqp/__init__.py index 5f0fe34..1ffbf49 100644 --- a/marinholab/solvers/osqp/__init__.py +++ b/marinholab/solvers/osqp/__init__.py @@ -5,21 +5,28 @@ Public API of the `marinholab.solvers.osqp` package. `Solver` is a thin, numpy-friendly Python wrapper around the compiled OSQP -solver (`OSQP_Solver`). The configuration and enum types are re-exported for -convenience. +solver (`OSQP_Solver`). The `Configuration` (keyed by option name) and the +enum types are re-exported for convenience. + +The enum types are pure Python (see `_options.py`) so the compiled +extension's C++ header stays free of OSQP types. """ from .solver import Solver # TODO change this mess into inheritance via trampoline class # Interface won't change, so this will do for now from marinholab.solvers.osqp._core import OSQP_Solver -# Re-exported for convenience so users can write e.g. `osqp.Configuration` -# and `osqp.OSQP_Solver.Status.OSQP_SOLVED`. +# The configuration and info, backed by the compiled extension. Configuration = OSQP_Solver.Configuration Info = OSQP_Solver.Info -LinsysSolverType = OSQP_Solver.LinsysSolverType -PreconditionerType = OSQP_Solver.PreconditionerType -Status = OSQP_Solver.Status +# The enum types, provided in pure Python so users can still write e.g. +# `osqp.LinsysSolverType.OSQP_DIRECT_SOLVER` (`Configuration.set` also accepts +# these members directly). +from marinholab.solvers.osqp._options import ( + LinsysSolverType, + PreconditionerType, + Status, +) __all__ = [ "Solver", diff --git a/marinholab/solvers/osqp/_core.pyi b/marinholab/solvers/osqp/_core.pyi index f4b0d4a..478d596 100644 --- a/marinholab/solvers/osqp/_core.pyi +++ b/marinholab/solvers/osqp/_core.pyi @@ -3,137 +3,72 @@ The real module is built from ``src/core.cpp``; this file only exists so that type checkers (e.g. Pyright) can understand the public surface of the extension without having to parse C++. -""" - -from enum import IntEnum - -import numpy as np +The enum types (``LinsysSolverType``, ``PreconditionerType``, ``Status``) are +provided by the pure-Python module ``_options.py`` and re-exported by the +package ``__init__.py``; they are not part of the compiled extension. +""" -class LinsysSolverType(IntEnum): - """OSQP linear system solvers.""" +from typing import Union - OSQP_UNKNOWN_SOLVER: LinsysSolverType - OSQP_DIRECT_SOLVER: LinsysSolverType - OSQP_INDIRECT_SOLVER: LinsysSolverType +from collections.abc import Mapping +from enum import Enum +import numpy as np -class PreconditionerType(IntEnum): - """Preconditioners for the conjugate-gradient method.""" +OptionValue = Union[bool, int, float, str] +"""An option value: bool, int, float, or an enum value name.""" - OSQP_NO_PRECONDITIONER: PreconditionerType - OSQP_DIAGONAL_PRECONDITIONER: PreconditionerType +class OSQP_Solver: + """High-level, reusable solver for quadratic programs (QPs) based on OSQP.""" -class Status(IntEnum): - """OSQP solver status codes returned for the last solve.""" + class Configuration: + """Holder of all user-configurable solver options, keyed by name. + + Every OSQP ``OSQPSettings`` field plus the wrapper-specific + ``use_hotstart`` is exposed under its name via ``set()``/``get()``. + Values are bool, int, float, or str: enum options take the enum value + name (e.g. ``"OSQP_DIRECT_SOLVER"``, + ``"OSQP_DIAGONAL_PRECONDITIONER"``) or an enum member. ``set()`` also + converts strings such as ``"1e-9"`` or ``"false"``. Unset options use + OSQP's own defaults for a double-precision, direct-solver build + except ``verbose`` (``False``). See ``keys()`` and ``defaults()`` for + the full list. + """ - OSQP_SOLVED: Status - OSQP_SOLVED_INACCURATE: Status - OSQP_PRIMAL_INFEASIBLE: Status - OSQP_PRIMAL_INFEASIBLE_INACCURATE: Status - OSQP_DUAL_INFEASIBLE: Status - OSQP_DUAL_INFEASIBLE_INACCURATE: Status - OSQP_MAX_ITER_REACHED: Status - OSQP_TIME_LIMIT_REACHED: Status - OSQP_NON_CVX: Status - OSQP_SIGINT: Status - OSQP_UNSOLVED: Status + def __init__(self) -> None: ... + def set(self, key: str, value: Union[OptionValue, Enum]) -> None: + """Sets the option ``key`` to ``value`` (bool, int, float, str, or an + enum member such as ``LinsysSolverType.OSQP_DIRECT_SOLVER``), + converted to the option's kind. Raises ValueError for an unknown + key or a value that does not convert to that kind.""" + ... -class OSQP_Solver: - """High-level, reusable solver for quadratic programs (QPs) based on OSQP. + def get(self, key: str) -> OptionValue: + """Returns the value of ``key``, or its default if not set.""" + ... - Solves ``min(x) 0.5*x'Hx + f'x`` subject to ``Ax <= b`` and - ``Aeq*x = beq`` (MATLAB `quadprog`-like signature). Once the problem has - been solved once, subsequent solves are warm-started by default (see - ``Configuration.use_hotstart``). - """ + def has(self, key: str) -> bool: + """True if ``key`` has been explicitly set.""" + ... - # Nested aliases so the enums are also reachable as - # ``OSQP_Solver.LinsysSolverType`` etc. (matching the runtime layout, where - # ``export_values()`` binds them onto the class). - LinsysSolverType: type[LinsysSolverType] = LinsysSolverType - PreconditionerType: type[PreconditionerType] = PreconditionerType - Status: type[Status] = Status + def keys(self) -> list[str]: + """Sorted list of all settable option names.""" + ... - class Configuration: - """All user-configurable solver options. - - Members are a 1:1 mapping of OSQP's ``OSQPSettings`` fields (plus the - wrapper-specific ``use_hotstart``). Defaults match OSQP's own defaults - for a standard double-precision, direct-solver build (see - ``osqp_set_default_settings()``); see the C++ header - (``include/marinholab/solvers/osqp.h``) and the OSQP documentation - (https://osqp.org/docs/) for the meaning of each option. - """ + def defaults(self) -> Mapping[str, OptionValue]: + """Mapping of option name -> default value.""" + ... - #: Reuse the existing OSQP solver and update its data in place instead of re-running osqp_setup() when the problem shape is unchanged. - use_hotstart: bool - #: Device identifier; currently used for CUDA devices. - device: int - #: Linear system solver to use. - linsys_solver: LinsysSolverType - #: Whether the solution is allocated during osqp_setup(). - allocate_solution: int - #: Whether solver progress is written out (0 = quiet, the default). - verbose: int - #: Level of detail for profiler annotations. - profiler_level: int - #: Whether OSQP warm-starts from the previous solution between consecutive osqp_solve() calls. - warm_starting: int - #: Number of heuristic data-scaling iterations; 0 disables scaling. - scaling: int - #: Whether the ADMM solution is polished to improve accuracy. - polishing: int - #: ADMM penalty parameter (scalar). - rho: float - #: Whether rho is a scalar or a vector. - rho_is_vec: int - #: ADMM regularization parameter (improves conditioning). - sigma: float - #: ADMM relaxation parameter. - alpha: float - #: Maximum number of CG iterations per solve. - cg_max_iter: int - #: Number of consecutive zero CG iterations before the tolerance is halved. - cg_tol_reduction: int - #: CG tolerance, as a fraction of the ADMM residuals. - cg_tol_fraction: float - #: Preconditioner used by the CG method. - cg_precond: PreconditionerType - #: ADMM rho stepsize adaptation method. - adaptive_rho: int - #: Interval between rho adaptations (used with the iterations-based method). - adaptive_rho_interval: int - #: Adaptation parameter controlling when non-fixed rho adaptations occur. - adaptive_rho_fraction: float - #: Tolerance applied when adapting rho (min ratio between new and current rho). - adaptive_rho_tolerance: float - #: Maximum number of ADMM iterations. - max_iter: int - #: Absolute solution tolerance. - eps_abs: float - #: Relative solution tolerance. - eps_rel: float - #: Primal infeasibility detection tolerance. - eps_prim_inf: float - #: Dual infeasibility detection tolerance. - eps_dual_inf: float - #: Whether the scaled termination criteria are used. - scaled_termination: int - #: Interval at which termination is checked; 0 disables the periodic check. - check_termination: int - #: Whether the duality-gap termination criteria are used. - check_dualgap: int - #: Maximum time to solve the problem, in seconds. - time_limit: float - #: Regularization parameter used by polishing. - delta: float - #: Number of iterative refinement steps performed during polishing. - polish_refine_iter: int + def reset(self, key: str) -> None: + """Reverts ``key`` to its default.""" + ... - def __init__(self) -> None: ... + def reset_all(self) -> None: + """Reverts every option to its default.""" + ... class Info: """Solution-quality values obtained from the last successful call to ``solve_quadratic_program()``.""" diff --git a/marinholab/solvers/osqp/_options.py b/marinholab/solvers/osqp/_options.py new file mode 100644 index 0000000..eff2ba6 --- /dev/null +++ b/marinholab/solvers/osqp/_options.py @@ -0,0 +1,47 @@ +""" +Copyright (C) 2025 Murilo Marques Marinho (www.murilomarinho.info) +LGPLv2.1 License + +Pure-Python enum types that mirror the OSQP enumerations accepted by +`Configuration.set()`. + +These live in Python (not in the compiled extension) so the C++ public +header stays free of OSQP types. Each member's *name* is the value that +`Configuration` stores for the option (e.g. `LinsysSolverType.OSQP_DIRECT_SOLVER.name` +-> `"OSQP_DIRECT_SOLVER"`), and its *value* matches the underlying OSQP +integer. `Configuration.set()` accepts the member itself or its name. +""" +from __future__ import annotations + +from enum import IntEnum + + +class LinsysSolverType(IntEnum): + """OSQP linear system solvers (the ``linsys_solver`` option).""" + + OSQP_UNKNOWN_SOLVER = 0 + OSQP_DIRECT_SOLVER = 1 + OSQP_INDIRECT_SOLVER = 2 + + +class PreconditionerType(IntEnum): + """Preconditioners for the conjugate-gradient method (the ``cg_precond`` option).""" + + OSQP_NO_PRECONDITIONER = 0 + OSQP_DIAGONAL_PRECONDITIONER = 1 + + +class Status(IntEnum): + """OSQP solver status codes for the last solve.""" + + OSQP_SOLVED = 1 + OSQP_SOLVED_INACCURATE = 2 + OSQP_PRIMAL_INFEASIBLE = 3 + OSQP_PRIMAL_INFEASIBLE_INACCURATE = 4 + OSQP_DUAL_INFEASIBLE = 5 + OSQP_DUAL_INFEASIBLE_INACCURATE = 6 + OSQP_MAX_ITER_REACHED = 7 + OSQP_TIME_LIMIT_REACHED = 8 + OSQP_NON_CVX = 9 + OSQP_SIGINT = 10 + OSQP_UNSOLVED = 11 diff --git a/marinholab/solvers/osqp/example.py b/marinholab/solvers/osqp/example.py index b0af051..f43ad92 100644 --- a/marinholab/solvers/osqp/example.py +++ b/marinholab/solvers/osqp/example.py @@ -62,10 +62,10 @@ def positivedefinite(): def configuration_example(): config = osqp.Configuration() - config.eps_abs = 1e-5 - config.eps_rel = 1e-5 - config.max_iter = 10000 - config.verbose = 0 + config.set("eps_abs", 1e-5) + config.set("eps_rel", 1e-5) + config.set("max_iter", 10000) + config.set("verbose", False) solver = osqp.Solver(config) x = np.array([1.0, 0.0, 0.0, 0.0]) @@ -212,9 +212,9 @@ def hierarchical_example(): # value (Aeq = J1, beq = J1@u1) is enforced much more precisely, i.e. # J1@u2 ends up much closer to J1@u1 than with the default tolerances. config = osqp.Configuration() - config.eps_abs = 1e-9 - config.eps_rel = 1e-9 - config.max_iter = 20000 + config.set("eps_abs", 1e-9) + config.set("eps_rel", 1e-9) + config.set("max_iter", 20000) solver_1 = osqp.Solver(config) solver_2 = osqp.Solver(config) diff --git a/marinholab/solvers/osqp/example_kinematics.py b/marinholab/solvers/osqp/example_kinematics.py index f534776..097b6cd 100644 --- a/marinholab/solvers/osqp/example_kinematics.py +++ b/marinholab/solvers/osqp/example_kinematics.py @@ -62,9 +62,9 @@ def main(): # that the level-2 equality constraint that reproduces the level-1 task # (Aeq = Jt, beq = Jt @ u1) is enforced much more precisely. config = osqp.Configuration() - config.eps_abs = 1e-9 - config.eps_rel = 1e-9 - config.max_iter = 20000 + config.set("eps_abs", 1e-9) + config.set("eps_rel", 1e-9) + config.set("max_iter", 20000) solver_1 = osqp.Solver(config) # Level 1: end-effector position control solver_2 = osqp.Solver(config) # Level 2: redundancy resolution diff --git a/qdldl b/qdldl new file mode 160000 index 0000000..138fdac --- /dev/null +++ b/qdldl @@ -0,0 +1 @@ +Subproject commit 138fdac58b9cd1c4137ff1b99152c8108a6cff5b diff --git a/setup.py b/setup.py index 36c688e..aaec1b3 100644 --- a/setup.py +++ b/setup.py @@ -50,6 +50,9 @@ def build_extension(self, ext: CMakeExtension) -> None: f"-DPYTHON_EXECUTABLE={sys.executable}", f"-DCMAKE_BUILD_TYPE={cfg}" # not used on MSVC, but no harm ] + # The CMake default is BUILD_PYTHON=OFF (a C++-only build). The Python + # extension must be enabled explicitly for the wheel build. + cmake_args += ["-DBUILD_PYTHON=ON"] build_args = [] # Adding CMake arguments set as environment variable # (needed e.g. to build for ARM OSx on conda-forge) diff --git a/src/core.cpp b/src/core.cpp index 1ea1e24..c2c795f 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -2,13 +2,20 @@ (C) Copyright 2025-26 Murilo Marinho (murilomarinho@ieee.org) pybind11 bindings for marinholab::solvers::osqp::Solver. + +The `Configuration` is exposed with accessors keyed by option name (`set`, +`get`, `has`, `keys`, `defaults`, `reset`). Values are native Python bool, +int, float, or str (enumeration values by name), so the Python surface is +free of OSQP enum types. `set()` also accepts Python enum members (e.g. a +`LinsysSolverType`), which are passed by name. */ -#include +#include #include #include #include +#include #include @@ -18,6 +25,49 @@ pybind11 bindings for marinholab::solvers::osqp::Solver. namespace py = pybind11; using namespace marinholab::solvers::osqp; +namespace +{ + +/** + * @brief Converts a Python value into an `OptionValue` for + * `Configuration::set()`, which then converts it to the option's kind. + * + * Accepts: + * - `bool` -> bool (checked before int, since bool is an int) + * - an enum member -> its `.name` (e.g. `LinsysSolverType.OSQP_DIRECT_SOLVER` -> + * `"OSQP_DIRECT_SOLVER"`; checked before int, since an + * `IntEnum` is an int) + * - `int`, or anything with `__index__` (e.g. numpy integers) -> long long + * - `float`, or anything with `__float__` (e.g. numpy floats) -> double + * - `str` -> str + */ +OptionValue to_option_value(py::handle value) +{ + if(py::isinstance(value)) + return value.cast(); + + // Leaked on purpose: a static py::object would be destroyed after the + // interpreter has shut down. + static const py::object* enum_type = new py::object(py::module_::import("enum").attr("Enum")); + if(py::isinstance(value, *enum_type)) + return py::str(value.attr("name")).cast(); + + if(py::isinstance(value)) + return value.cast(); + + if(py::isinstance(value) || py::hasattr(value, "__index__")) + return py::int_(py::reinterpret_borrow(value)).cast(); + + if(py::isinstance(value) || py::hasattr(value, "__float__")) + return py::float_(py::reinterpret_borrow(value)).cast(); + + throw py::type_error( + "Option value must be a bool, an int, a float, a string, or an enum member; " + "got " + py::str(value.get_type()).cast()); +} + +} // namespace + PYBIND11_MODULE(_core, m) { m.doc() = "Python bindings for an OSQP-based quadratic program solver."; @@ -30,86 +80,50 @@ PYBIND11_MODULE(_core, m) { " Aeq*x = beq\n\n" "Method signature is compatible with MATLAB's `quadprog`. Once the\n" "problem has been solved once, subsequent solves are warm-started by\n" - "default (see `Configuration.use_hotstart`)."); - - py::enum_<::osqp_linsys_solver_type>(osqp_solver, "LinsysSolverType", - "OSQP linear system solvers.") - .value("OSQP_UNKNOWN_SOLVER", ::OSQP_UNKNOWN_SOLVER) - .value("OSQP_DIRECT_SOLVER", ::OSQP_DIRECT_SOLVER) - .value("OSQP_INDIRECT_SOLVER", ::OSQP_INDIRECT_SOLVER) - .export_values(); - - py::enum_<::osqp_precond_type>(osqp_solver, "PreconditionerType", - "Preconditioners for the conjugate-gradient method.") - .value("OSQP_NO_PRECONDITIONER", ::OSQP_NO_PRECONDITIONER) - .value("OSQP_DIAGONAL_PRECONDITIONER", ::OSQP_DIAGONAL_PRECONDITIONER) - .export_values(); - - py::enum_<::osqp_status_type>(osqp_solver, "Status", - "OSQP solver status codes returned for the last solve.") - .value("OSQP_SOLVED", ::OSQP_SOLVED) - .value("OSQP_SOLVED_INACCURATE", ::OSQP_SOLVED_INACCURATE) - .value("OSQP_PRIMAL_INFEASIBLE", ::OSQP_PRIMAL_INFEASIBLE) - .value("OSQP_PRIMAL_INFEASIBLE_INACCURATE", ::OSQP_PRIMAL_INFEASIBLE_INACCURATE) - .value("OSQP_DUAL_INFEASIBLE", ::OSQP_DUAL_INFEASIBLE) - .value("OSQP_DUAL_INFEASIBLE_INACCURATE", ::OSQP_DUAL_INFEASIBLE_INACCURATE) - .value("OSQP_MAX_ITER_REACHED", ::OSQP_MAX_ITER_REACHED) - .value("OSQP_TIME_LIMIT_REACHED", ::OSQP_TIME_LIMIT_REACHED) - .value("OSQP_NON_CVX", ::OSQP_NON_CVX) - .value("OSQP_SIGINT", ::OSQP_SIGINT) - .value("OSQP_UNSOLVED", ::OSQP_UNSOLVED) - .export_values(); - - py::class_ osqp_configuration(osqp_solver, "Configuration", - "All user-configurable solver options.\n\n" - "Members are a 1:1 mapping of OSQP's `OSQPSettings` fields (plus the\n" - "wrapper-specific `use_hotstart`). See the OSQP documentation for a\n" - "full description of each option: https://osqp.org/docs/"); - - osqp_configuration.def(py::init<>()); - - // Wrapper-specific option - osqp_configuration.def_readwrite("use_hotstart", &Configuration::use_hotstart, - "Reuse the existing OSQP solver and update its data in place instead of re-running osqp_setup() when the problem shape is unchanged."); - - // Linear algebra settings - osqp_configuration.def_readwrite("device", &Configuration::device, "Device identifier; currently used for CUDA devices."); - osqp_configuration.def_readwrite("linsys_solver", &Configuration::linsys_solver, "Linear system solver to use."); - // Control settings - osqp_configuration.def_readwrite("allocate_solution", &Configuration::allocate_solution, "Whether the solution is allocated during osqp_setup()."); - osqp_configuration.def_readwrite("verbose", &Configuration::verbose, "Whether solver progress is written out (0 = quiet, the default)."); - osqp_configuration.def_readwrite("profiler_level", &Configuration::profiler_level, "Level of detail for profiler annotations."); - osqp_configuration.def_readwrite("warm_starting", &Configuration::warm_starting, "Whether OSQP warm-starts from the previous solution between consecutive osqp_solve() calls."); - osqp_configuration.def_readwrite("scaling", &Configuration::scaling, "Number of heuristic data-scaling iterations; 0 disables scaling."); - osqp_configuration.def_readwrite("polishing", &Configuration::polishing, "Whether the ADMM solution is polished to improve accuracy."); - // ADMM parameters - osqp_configuration.def_readwrite("rho", &Configuration::rho, "ADMM penalty parameter (scalar)."); - osqp_configuration.def_readwrite("rho_is_vec", &Configuration::rho_is_vec, "Whether rho is a scalar or a vector."); - osqp_configuration.def_readwrite("sigma", &Configuration::sigma, "ADMM regularization parameter (improves conditioning)."); - osqp_configuration.def_readwrite("alpha", &Configuration::alpha, "ADMM relaxation parameter."); - // CG settings - osqp_configuration.def_readwrite("cg_max_iter", &Configuration::cg_max_iter, "Maximum number of CG iterations per solve."); - osqp_configuration.def_readwrite("cg_tol_reduction", &Configuration::cg_tol_reduction, "Number of consecutive zero CG iterations before the tolerance is halved."); - osqp_configuration.def_readwrite("cg_tol_fraction", &Configuration::cg_tol_fraction, "CG tolerance, as a fraction of the ADMM residuals."); - osqp_configuration.def_readwrite("cg_precond", &Configuration::cg_precond, "Preconditioner used by the CG method."); - // Adaptive rho logic - osqp_configuration.def_readwrite("adaptive_rho", &Configuration::adaptive_rho, "ADMM rho stepsize adaptation method."); - osqp_configuration.def_readwrite("adaptive_rho_interval", &Configuration::adaptive_rho_interval, "Interval between rho adaptations (used with the iterations-based method)."); - osqp_configuration.def_readwrite("adaptive_rho_fraction", &Configuration::adaptive_rho_fraction, "Adaptation parameter controlling when non-fixed rho adaptations occur."); - osqp_configuration.def_readwrite("adaptive_rho_tolerance", &Configuration::adaptive_rho_tolerance, "Tolerance applied when adapting rho (min ratio between new and current rho)."); - // Termination parameters - osqp_configuration.def_readwrite("max_iter", &Configuration::max_iter, "Maximum number of ADMM iterations."); - osqp_configuration.def_readwrite("eps_abs", &Configuration::eps_abs, "Absolute solution tolerance."); - osqp_configuration.def_readwrite("eps_rel", &Configuration::eps_rel, "Relative solution tolerance."); - osqp_configuration.def_readwrite("eps_prim_inf", &Configuration::eps_prim_inf, "Primal infeasibility detection tolerance."); - osqp_configuration.def_readwrite("eps_dual_inf", &Configuration::eps_dual_inf, "Dual infeasibility detection tolerance."); - osqp_configuration.def_readwrite("scaled_termination", &Configuration::scaled_termination, "Whether the scaled termination criteria are used."); - osqp_configuration.def_readwrite("check_termination", &Configuration::check_termination, "Interval at which termination is checked; 0 disables the periodic check."); - osqp_configuration.def_readwrite("check_dualgap", &Configuration::check_dualgap, "Whether the duality-gap termination criteria are used."); - osqp_configuration.def_readwrite("time_limit", &Configuration::time_limit, "Maximum time to solve the problem, in seconds."); - // Polishing parameters - osqp_configuration.def_readwrite("delta", &Configuration::delta, "Regularization parameter used by polishing."); - osqp_configuration.def_readwrite("polish_refine_iter", &Configuration::polish_refine_iter, "Number of iterative refinement steps performed during polishing."); + "default (see the `use_hotstart` option on the Configuration)."); + + py::class_ configuration(osqp_solver, "Configuration", + "Holder of all user-configurable solver options, keyed by name.\n\n" + "Every OSQP `OSQPSettings` field plus the wrapper-specific `use_hotstart`\n" + "is exposed under its name via `set()`/`get()`. Values are bool, int,\n" + "float, or str: enum options take the enum value name (e.g.\n" + "\"OSQP_DIRECT_SOLVER\", \"OSQP_DIAGONAL_PRECONDITIONER\") or an enum\n" + "member. `set()` also converts strings such as \"1e-9\" or \"false\".\n" + "Unset options use OSQP's own defaults for a double-precision,\n" + "direct-solver build except `verbose`, which defaults to 0. See\n" + "`keys()` and `defaults()` for the full list."); + + configuration.def(py::init<>()); + configuration.def("set", + [](Configuration& self, const std::string& key, py::handle value) { + self.set(key, to_option_value(value)); + }, + py::arg("key"), py::arg("value"), + "Sets the option `key` to `value` (bool, int, float, str, or an enum " + "member), converted to the option's kind. Raises ValueError for an " + "unknown key or a value that does not convert to that kind."); + configuration.def("get", + &Configuration::get, + py::arg("key"), + "Returns the value of `key` (bool, int, float, or str), or its default " + "if not set."); + configuration.def("has", + &Configuration::has, + py::arg("key"), + "True if `key` has been explicitly set."); + configuration.def("keys", + &Configuration::keys, + "Sorted list of all settable option names."); + configuration.def("defaults", + &Configuration::defaults, + "Mapping of option name -> default value."); + configuration.def("reset", + &Configuration::reset, + py::arg("key"), + "Reverts `key` to its default."); + configuration.def("reset_all", + &Configuration::reset_all, + "Reverts every option to its default."); py::class_ osqp_info(osqp_solver, "Info", "Solution-quality values obtained from the last successful call to " @@ -128,7 +142,7 @@ PYBIND11_MODULE(_core, m) { osqp_solver.def("solve_quadratic_program", &Solver::solve_quadratic_program, py::arg("H"), py::arg("f"), py::arg("A"), py::arg("b"), py::arg("Aeq"), py::arg("beq"), - py::arg("x0") = VectorXd(), py::arg("y0") = VectorXd(), + py::arg("x0") = Eigen::VectorXd(), py::arg("y0") = Eigen::VectorXd(), "Solves min(x) 0.5*x'Hx + f'x s.t. Ax <= b and Aeq*x = beq (MATLAB `quadprog`-like signature).\n\n" "Returns the optimal x. x0 and y0 are optional warm-starts for the primal and dual variables."); osqp_solver.def("get_info", diff --git a/src/core_function.cpp b/src/core_function.cpp index dcc5dbc..d7e06bf 100644 --- a/src/core_function.cpp +++ b/src/core_function.cpp @@ -2,10 +2,15 @@ Based on the marinholab::solvers::qpoases::Solver wrapper in solver-qpoases, adapted to use the OSQP solver. */ +#include +#include +#include +#include +#include + #include -#include -#include +#include namespace marinholab { @@ -16,172 +21,628 @@ namespace solvers namespace osqp { -// https://stackoverflow.com/questions/53408962/try-to-understand-compiler-error-message-default-member-initializer-required-be -Configuration::Configuration() = default; +// --------------------------------------------------------------------------- +// Option metadata +// --------------------------------------------------------------------------- + +enum class OptionKind +{ + Boolean, + Integer, + Real, + LinsysSolverType, + PreconditionerType, +}; + +namespace detail +{ + +inline const std::map& option_kinds() +{ + static const std::map kinds = { + // Wrapper-specific options. + {"use_hotstart", OptionKind::Boolean}, + // OSQP `OSQPSettings` fields (1:1 mapping). + // Linear algebra settings + {"device", OptionKind::Integer}, + {"linsys_solver", OptionKind::LinsysSolverType}, + // Control settings + {"allocate_solution", OptionKind::Boolean}, + {"verbose", OptionKind::Boolean}, + {"profiler_level", OptionKind::Integer}, + {"warm_starting", OptionKind::Boolean}, + {"scaling", OptionKind::Integer}, + {"polishing", OptionKind::Boolean}, + // ADMM parameters + {"rho", OptionKind::Real}, + {"rho_is_vec", OptionKind::Boolean}, + {"sigma", OptionKind::Real}, + {"alpha", OptionKind::Real}, + // CG settings + {"cg_max_iter", OptionKind::Integer}, + {"cg_tol_reduction", OptionKind::Integer}, + {"cg_tol_fraction", OptionKind::Real}, + {"cg_precond", OptionKind::PreconditionerType}, + // Adaptive rho logic + {"adaptive_rho", OptionKind::Integer}, + {"adaptive_rho_interval", OptionKind::Integer}, + {"adaptive_rho_fraction", OptionKind::Real}, + {"adaptive_rho_tolerance", OptionKind::Real}, + // Termination parameters + {"max_iter", OptionKind::Integer}, + {"eps_abs", OptionKind::Real}, + {"eps_rel", OptionKind::Real}, + {"eps_prim_inf", OptionKind::Real}, + {"eps_dual_inf", OptionKind::Real}, + {"scaled_termination", OptionKind::Boolean}, + {"check_termination", OptionKind::Integer}, + {"check_dualgap", OptionKind::Boolean}, + {"time_limit", OptionKind::Real}, + // Polishing parameters + {"delta", OptionKind::Real}, + {"polish_refine_iter", OptionKind::Integer}, + }; + return kinds; +} + +inline bool is_known_option(const std::string& key) +{ + return option_kinds().find(key) != option_kinds().end(); +} -// https://stackoverflow.com/questions/53408962/try-to-understand-compiler-error-message-default-member-initializer-required-be -Solver::Info::Info() = default; +inline std::string to_lower(const std::string& s) +{ + std::string out(s); + std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return out; +} /** - * \brief Builds an `OSQPSettings` object from the user configuration. + * @brief Parses a boolean string, returning true when the value is true. + */ +inline bool parse_bool(const std::string& value) +{ + const std::string v = to_lower(value); + if(v == "true" || v == "1" || v == "on") + return true; + if(v == "false" || v == "0" || v == "off") + return false; + throw std::invalid_argument("Invalid boolean value '" + value + "' (expected true/false)."); +} + +/** + * @brief Parses an integer string. + */ +inline long long parse_int(const std::string& value) +{ + const char* begin = value.c_str(); + char* end = nullptr; + const long long parsed = std::strtoll(begin, &end, 10); + if(begin == end || *end != '\0') + throw std::invalid_argument("Invalid integer value '" + value + "'."); + return parsed; +} + +/** + * @brief Parses a floating-point string. + */ +inline double parse_real(const std::string& value) +{ + const char* begin = value.c_str(); + char* end = nullptr; + const double parsed = std::strtod(begin, &end); + if(begin == end || *end != '\0') + throw std::invalid_argument("Invalid number value '" + value + "'."); + return parsed; +} + +/** + * @brief Parses an enumeration value by name, e.g. "OSQP_DIRECT_SOLVER". + */ +template +inline T parse_enum(const std::string& key, const std::string& value, + const std::map& allowed) +{ + const auto it = allowed.find(value); + if(it == allowed.end()) + { + std::string options; + for(const auto& pair : allowed) + options += (options.empty() ? "" : ", ") + pair.first; + throw std::invalid_argument("Invalid value '" + value + "' for option '" + key + "'. Allowed values: " + options + "."); + } + return it->second; +} + +/** @brief Names of the OSQP `osqp_linsys_solver_type` values. */ +inline const std::map& linsys_solver_types() +{ + static const std::map values = { + {"OSQP_UNKNOWN_SOLVER", ::OSQP_UNKNOWN_SOLVER}, + {"OSQP_DIRECT_SOLVER", ::OSQP_DIRECT_SOLVER}, + {"OSQP_INDIRECT_SOLVER", ::OSQP_INDIRECT_SOLVER}, + }; + return values; +} + +/** @brief Names of the OSQP `osqp_precond_type` values. */ +inline const std::map& preconditioner_types() +{ + static const std::map values = { + {"OSQP_NO_PRECONDITIONER", ::OSQP_NO_PRECONDITIONER}, + {"OSQP_DIAGONAL_PRECONDITIONER", ::OSQP_DIAGONAL_PRECONDITIONER}, + }; + return values; +} + +/** + * @brief The name of an enumeration value, from one of the tables above. + */ +template +inline std::string name_of(const std::map& names, T value) +{ + for(const auto& pair : names) + if(pair.second == value) + return pair.first; + throw std::logic_error("Enumeration value without a name."); +} + +/** + * @brief Converts `value` to the kind of option `key`. * - * Maps every `OSQPSettings` field onto the corresponding `Configuration` - * member. + * Booleans accept `bool` or "true"/"false"; integers accept `long long` or + * an integer literal; reals accept `double`, `long long` or a + * floating-point literal; enumerations accept a value name. */ -OSQPSettings Solver::_to_osqp_settings() const +inline OptionValue normalize(const std::string& key, const OptionValue& value) { - OSQPSettings settings; + const auto wrong_type = [&key](const std::string& expected) { + return std::invalid_argument("Invalid value for option '" + key + "': expected " + expected + "."); + }; + const auto* text = std::get_if(&value); + switch(option_kinds().at(key)) { + case OptionKind::Boolean: + if(const auto* b = std::get_if(&value)) + return *b; + if(text) + return parse_bool(*text); + throw wrong_type("a bool"); + case OptionKind::Integer: + if(const auto* i = std::get_if(&value)) + return *i; + if(text) + return parse_int(*text); + throw wrong_type("an integer"); + case OptionKind::Real: + if(const auto* d = std::get_if(&value)) + return *d; + if(const auto* i = std::get_if(&value)) + return static_cast(*i); + if(text) + return parse_real(*text); + throw wrong_type("a real number"); + case OptionKind::LinsysSolverType: + if(text) + return name_of(linsys_solver_types(), parse_enum(key, *text, linsys_solver_types())); + throw wrong_type("a linsys_solver name, e.g. \"OSQP_DIRECT_SOLVER\""); + case OptionKind::PreconditionerType: + if(text) + return name_of(preconditioner_types(), parse_enum(key, *text, preconditioner_types())); + throw wrong_type("a preconditioner name, e.g. \"OSQP_DIAGONAL_PRECONDITIONER\""); + } + throw std::logic_error("Unhandled option kind."); +} - // Linear algebra settings - settings.device = configuration_.device; - settings.linsys_solver = configuration_.linsys_solver; - - // Control settings - settings.allocate_solution = configuration_.allocate_solution; - settings.verbose = configuration_.verbose; - settings.profiler_level = configuration_.profiler_level; - settings.warm_starting = configuration_.warm_starting; - settings.scaling = configuration_.scaling; - settings.polishing = configuration_.polishing; - - // ADMM parameters - settings.rho = configuration_.rho; - settings.rho_is_vec = configuration_.rho_is_vec; - settings.sigma = configuration_.sigma; - settings.alpha = configuration_.alpha; - - // CG settings - settings.cg_max_iter = configuration_.cg_max_iter; - settings.cg_tol_reduction = configuration_.cg_tol_reduction; - settings.cg_tol_fraction = configuration_.cg_tol_fraction; - settings.cg_precond = configuration_.cg_precond; - - // Adaptive rho logic - settings.adaptive_rho = configuration_.adaptive_rho; - settings.adaptive_rho_interval = configuration_.adaptive_rho_interval; - settings.adaptive_rho_fraction = configuration_.adaptive_rho_fraction; - settings.adaptive_rho_tolerance = configuration_.adaptive_rho_tolerance; - - // Termination parameters - settings.max_iter = configuration_.max_iter; - settings.eps_abs = configuration_.eps_abs; - settings.eps_rel = configuration_.eps_rel; - settings.eps_prim_inf = configuration_.eps_prim_inf; - settings.eps_dual_inf = configuration_.eps_dual_inf; - settings.scaled_termination = configuration_.scaled_termination; - settings.check_termination = configuration_.check_termination; - settings.check_dualgap = configuration_.check_dualgap; - settings.time_limit = configuration_.time_limit; - - // Polishing parameters - settings.delta = configuration_.delta; - settings.polish_refine_iter = configuration_.polish_refine_iter; +/** + * @brief Every option's default value, taken directly from OSQP's + * `osqp_set_default_settings()` for a double-precision, + * direct-solver build. + */ +inline const std::map& default_values() +{ + static const std::map defaults = [] { + OSQPSettings settings; + osqp_set_default_settings(&settings); + const auto integer = [](OSQPInt value) { return static_cast(value); }; + const auto real = [](OSQPFloat value) { return static_cast(value); }; + std::map d; + d["use_hotstart"] = true; + // Linear algebra settings + d["device"] = integer(settings.device); + d["linsys_solver"] = name_of(linsys_solver_types(), settings.linsys_solver); + // Control settings + d["allocate_solution"] = integer(settings.allocate_solution) != 0; + d["verbose"] = false; // quiet by default (see Configuration) + d["profiler_level"] = integer(settings.profiler_level); + d["warm_starting"] = integer(settings.warm_starting) != 0; + d["scaling"] = integer(settings.scaling); + d["polishing"] = integer(settings.polishing) != 0; + // ADMM parameters + d["rho"] = real(settings.rho); + d["rho_is_vec"] = integer(settings.rho_is_vec) != 0; + d["sigma"] = real(settings.sigma); + d["alpha"] = real(settings.alpha); + // CG settings + d["cg_max_iter"] = integer(settings.cg_max_iter); + d["cg_tol_reduction"] = integer(settings.cg_tol_reduction); + d["cg_tol_fraction"] = real(settings.cg_tol_fraction); + d["cg_precond"] = name_of(preconditioner_types(), settings.cg_precond); + // Adaptive rho logic + d["adaptive_rho"] = integer(settings.adaptive_rho); + d["adaptive_rho_interval"] = integer(settings.adaptive_rho_interval); + d["adaptive_rho_fraction"] = real(settings.adaptive_rho_fraction); + d["adaptive_rho_tolerance"] = real(settings.adaptive_rho_tolerance); + // Termination parameters + d["max_iter"] = integer(settings.max_iter); + d["eps_abs"] = real(settings.eps_abs); + d["eps_rel"] = real(settings.eps_rel); + d["eps_prim_inf"] = real(settings.eps_prim_inf); + d["eps_dual_inf"] = real(settings.eps_dual_inf); + d["scaled_termination"] = integer(settings.scaled_termination) != 0; + d["check_termination"] = integer(settings.check_termination); + d["check_dualgap"] = integer(settings.check_dualgap) != 0; + d["time_limit"] = real(settings.time_limit); + // Polishing parameters + d["delta"] = real(settings.delta); + d["polish_refine_iter"] = integer(settings.polish_refine_iter); + return d; + }(); + return defaults; +} - return settings; +inline int64_t integer_from(const Configuration& configuration, const std::string& key) +{ + return std::get(configuration.get(key)); } -Solver::Solver(const Configuration& configuration): - osqp_solve_first_time_(true), - osqp_solver_(nullptr), - configuration_(configuration), - problem_size_(0), - constraint_size_(0) +inline double real_from(const Configuration& configuration, const std::string& key) { + return std::get(configuration.get(key)); +} +inline bool boolean_from(const Configuration& configuration, const std::string& key) +{ + return std::get(configuration.get(key)); } -Solver::~Solver() +/** + * @brief Translates the user configuration into an `OSQPSettings` object. + * + * Starts from OSQP's own defaults, overrides `verbose` with the (quieter) + * wrapper default, then applies every option that was explicitly set. + */ +inline OSQPSettings settings_from(const Configuration& configuration) { - _cleanup(); + OSQPSettings settings; + osqp_set_default_settings(&settings); + + settings.verbose = 0; // quiet by default (see Configuration) + + // Apply only the explicitly set options. + { + auto has_set = [&configuration](const std::string& key) { + return configuration.has(key); + }; + if(has_set("device")) + settings.device = static_cast(integer_from(configuration, "device")); + if(has_set("linsys_solver")) + settings.linsys_solver = parse_enum("linsys_solver", std::get(configuration.get("linsys_solver")), linsys_solver_types()); + if(has_set("allocate_solution")) + settings.allocate_solution = static_cast(boolean_from(configuration, "allocate_solution")); + if(has_set("verbose")) + settings.verbose = static_cast(boolean_from(configuration, "verbose")); + if(has_set("profiler_level")) + settings.profiler_level = static_cast(integer_from(configuration, "profiler_level")); + if(has_set("warm_starting")) + settings.warm_starting = static_cast(boolean_from(configuration, "warm_starting")); + if(has_set("scaling")) + settings.scaling = static_cast(integer_from(configuration, "scaling")); + if(has_set("polishing")) + settings.polishing = static_cast(boolean_from(configuration, "polishing")); + if(has_set("rho")) + settings.rho = real_from(configuration, "rho"); + if(has_set("rho_is_vec")) + settings.rho_is_vec = static_cast(boolean_from(configuration, "rho_is_vec")); + if(has_set("sigma")) + settings.sigma = real_from(configuration, "sigma"); + if(has_set("alpha")) + settings.alpha = real_from(configuration, "alpha"); + if(has_set("cg_max_iter")) + settings.cg_max_iter = static_cast(integer_from(configuration, "cg_max_iter")); + if(has_set("cg_tol_reduction")) + settings.cg_tol_reduction = static_cast(integer_from(configuration, "cg_tol_reduction")); + if(has_set("cg_tol_fraction")) + settings.cg_tol_fraction = real_from(configuration, "cg_tol_fraction"); + if(has_set("cg_precond")) + settings.cg_precond = parse_enum("cg_precond", std::get(configuration.get("cg_precond")), preconditioner_types()); + if(has_set("adaptive_rho")) + settings.adaptive_rho = static_cast(integer_from(configuration, "adaptive_rho")); + if(has_set("adaptive_rho_interval")) + settings.adaptive_rho_interval = static_cast(integer_from(configuration, "adaptive_rho_interval")); + if(has_set("adaptive_rho_fraction")) + settings.adaptive_rho_fraction = real_from(configuration, "adaptive_rho_fraction"); + if(has_set("adaptive_rho_tolerance")) + settings.adaptive_rho_tolerance = real_from(configuration, "adaptive_rho_tolerance"); + if(has_set("max_iter")) + settings.max_iter = static_cast(integer_from(configuration, "max_iter")); + if(has_set("eps_abs")) + settings.eps_abs = real_from(configuration, "eps_abs"); + if(has_set("eps_rel")) + settings.eps_rel = real_from(configuration, "eps_rel"); + if(has_set("eps_prim_inf")) + settings.eps_prim_inf = real_from(configuration, "eps_prim_inf"); + if(has_set("eps_dual_inf")) + settings.eps_dual_inf = real_from(configuration, "eps_dual_inf"); + if(has_set("scaled_termination")) + settings.scaled_termination = static_cast(boolean_from(configuration, "scaled_termination")); + if(has_set("check_termination")) + settings.check_termination = static_cast(integer_from(configuration, "check_termination")); + if(has_set("check_dualgap")) + settings.check_dualgap = static_cast(boolean_from(configuration, "check_dualgap")); + if(has_set("time_limit")) + settings.time_limit = real_from(configuration, "time_limit"); + if(has_set("delta")) + settings.delta = real_from(configuration, "delta"); + if(has_set("polish_refine_iter")) + settings.polish_refine_iter = static_cast(integer_from(configuration, "polish_refine_iter")); + } + return settings; } -void Solver::_cleanup() +inline void evaluate_osqp_exitflag(OSQPInt exitflag, const std::string& context) { - if(osqp_solver_ != nullptr) + if(exitflag != 0) { - osqp_cleanup(osqp_solver_); - osqp_solver_ = nullptr; + throw std::runtime_error("Solver::solve_quadratic_program(): "+context+" failed. OSQP returned error code "+std::to_string(exitflag)+": "+std::string(osqp_error_message(exitflag))); } } -std::vector Solver::_vectorxd_to_std_vector_double(const VectorXd& vectorxd) +} // namespace detail + +// --------------------------------------------------------------------------- +// Configuration +// --------------------------------------------------------------------------- + +Configuration::Configuration() = default; +Configuration::Configuration(const Configuration& other) = default; +Configuration& Configuration::operator=(const Configuration& other) = default; +Configuration::~Configuration() = default; + +void Configuration::set(const std::string& key, const OptionValue& value) { - std::vector vec(vectorxd.data(), vectorxd.data() + vectorxd.rows() * vectorxd.cols()); - return vec; + if(!detail::is_known_option(key)) + throw std::invalid_argument("Unknown option '" + key + "'. Use keys() for the valid option names."); + // Validate and convert up-front so type errors surface at set-time. + options_[key] = detail::normalize(key, value); } -VectorXd Solver::_std_vector_double_to_vectorxd(std::vector std_vector_double) const +void Configuration::set(const std::string& key, const char* value) { - double* ptr = &std_vector_double[0]; - Eigen::Map vec(ptr,std_vector_double.size()); - return vec; + set(key, OptionValue(std::string(value))); } -Solver::CSCMatrixData Solver::_dense_to_csc_upper_triangular(const MatrixXd& M) +OptionValue Configuration::get(const std::string& key) const { - if(M.rows()!=M.cols()) - throw std::runtime_error("Solver::_dense_to_csc_upper_triangular(): M must be square. M.rows()="+std::to_string(M.rows())+" but M.cols()="+std::to_string(M.cols())+"."); + if(!detail::is_known_option(key)) + throw std::invalid_argument("Unknown option '" + key + "'."); + const auto it = options_.find(key); + if(it != options_.end()) + return it->second; + return detail::default_values().at(key); +} - const OSQPInt n = static_cast(M.rows()); +bool Configuration::has(const std::string& key) const +{ + if(!detail::is_known_option(key)) + throw std::invalid_argument("Unknown option '" + key + "'. Use keys() for the valid option names."); + return options_.find(key) != options_.end(); +} - CSCMatrixData csc; - csc.rows = n; - csc.cols = n; - csc.p.resize(n + 1); +std::vector Configuration::keys() const +{ + const auto& kinds = detail::option_kinds(); + std::vector out; + out.reserve(kinds.size()); + for(const auto& pair : kinds) + out.push_back(pair.first); + return out; +} + +void Configuration::reset(const std::string& key) +{ + if(!detail::is_known_option(key)) + throw std::invalid_argument("Unknown option '" + key + "'. Use keys() for the valid option names."); + options_.erase(key); +} + +void Configuration::reset_all() +{ + options_.clear(); +} - OSQPInt nnz = 0; - for(OSQPInt col = 0; col < n; ++col) +std::map Configuration::defaults() const +{ + return detail::default_values(); +} + +// --------------------------------------------------------------------------- +// Solver +// --------------------------------------------------------------------------- + +struct Solver::Impl +{ + /** @brief True until the first solve has set up the solver. */ + bool osqp_solve_first_time_; + /** @brief The underlying OSQP solver. */ + ::OSQPSolver* osqp_solver_; + /** @brief Active configuration, copied at construction. */ + Configuration configuration_; + /** + * @brief Dimensions used in the last successful `osqp_setup()` call. + * Used to detect whether a new call is compatible with hotstarting or + * requires a fresh `osqp_setup()`. + */ + OSQPInt problem_size_; + OSQPInt constraint_size_; + + /** + * @brief Holds the CSC (compressed-sparse-column) arrays of a + * converted Eigen matrix. + * + * The vectors own the storage so that it outlives the temporary + * `OSQPCscMatrix` wrapper used when calling `osqp_setup()` / + * `osqp_update_data_mat()`. + */ + struct CSCMatrixData + { + std::vector x; + std::vector i; + std::vector p; + OSQPInt rows{0}; + OSQPInt cols{0}; + }; + + Impl(const Configuration& configuration) + : osqp_solve_first_time_(true) + , osqp_solver_(nullptr) + , configuration_(configuration) + , problem_size_(0) + , constraint_size_(0) { - csc.p[col] = nnz; - for(OSQPInt row = 0; row <= col; ++row) + } + + ~Impl() + { + cleanup(); + } + + /** + * @brief Copies an Eigen vector into a std::vector. + * @param vectorxd Source vector. + * @return A copy of the vector's data. + */ + std::vector vectorxd_to_std_vector_double(const Eigen::VectorXd& vectorxd) const + { + std::vector vec(vectorxd.data(), vectorxd.data() + vectorxd.rows() * vectorxd.cols()); + return vec; + } + + /** + * @brief Maps a std::vector into an Eigen vector. + * @param std_vector_double Source vector. + * @return An Eigen vector wrapping the source data. + */ + Eigen::VectorXd std_vector_double_to_vectorxd(std::vector std_vector_double) const + { + double* ptr = &std_vector_double[0]; + Eigen::Map vec(ptr, std_vector_double.size()); + return vec; + } + + /** + * @brief Converts a dense n x n matrix into the upper-triangular CSC + * representation required by OSQP for P. + * @param M Source matrix. + * @return The CSC arrays of the (upper triangle of the) matrix. + */ + static CSCMatrixData dense_to_csc_upper_triangular(const Eigen::MatrixXd& M) + { + if(M.rows() != M.cols()) + throw std::runtime_error("Solver::solve_quadratic_program(): H must be square. H.rows()="+std::to_string(M.rows())+" but H.cols()="+std::to_string(M.cols())+"."); + + const OSQPInt n = static_cast(M.rows()); + + CSCMatrixData csc; + csc.rows = n; + csc.cols = n; + csc.p.resize(n + 1); + + OSQPInt nnz = 0; + for(OSQPInt col = 0; col < n; ++col) { - csc.x.push_back(M(row, col)); - csc.i.push_back(row); - ++nnz; + csc.p[col] = nnz; + for(OSQPInt row = 0; row <= col; ++row) + { + csc.x.push_back(M(row, col)); + csc.i.push_back(row); + ++nnz; + } } - } - csc.p[n] = nnz; + csc.p[n] = nnz; - return csc; -} + return csc; + } -Solver::CSCMatrixData Solver::_dense_to_csc(const MatrixXd& M) -{ - const OSQPInt rows = static_cast(M.rows()); - const OSQPInt cols = static_cast(M.cols()); + /** + * @brief Converts a dense m x n matrix into a structurally-dense CSC + * representation (i.e. every entry, including zeros, is stored + * explicitly). + * + * Keeping the sparsity pattern stable across calls is what allows + * `osqp_update_data_mat()` to be used when hotstarting. + * @param M Source matrix. + * @return The CSC arrays of the matrix. + */ + static CSCMatrixData dense_to_csc(const Eigen::MatrixXd& M) + { + const OSQPInt rows = static_cast(M.rows()); + const OSQPInt cols = static_cast(M.cols()); + + CSCMatrixData csc; + csc.rows = rows; + csc.cols = cols; + csc.p.resize(cols + 1); + csc.x.resize(static_cast(rows) * static_cast(cols)); + csc.i.resize(static_cast(rows) * static_cast(cols)); + + OSQPInt nnz = 0; + for(OSQPInt col = 0; col < cols; ++col) + { + csc.p[col] = nnz; + for(OSQPInt row = 0; row < rows; ++row) + { + csc.x[nnz] = M(row, col); + csc.i[nnz] = row; + ++nnz; + } + } + csc.p[cols] = nnz; - CSCMatrixData csc; - csc.rows = rows; - csc.cols = cols; - csc.p.resize(cols + 1); - csc.x.resize(static_cast(rows) * static_cast(cols)); - csc.i.resize(static_cast(rows) * static_cast(cols)); + return csc; + } - OSQPInt nnz = 0; - for(OSQPInt col = 0; col < cols; ++col) + /** + * @brief Releases the current `osqp_solver_` instance, if any. + */ + void cleanup() { - csc.p[col] = nnz; - for(OSQPInt row = 0; row < rows; ++row) + if(osqp_solver_ != nullptr) { - csc.x[nnz] = M(row, col); - csc.i[nnz] = row; - ++nnz; + osqp_cleanup(osqp_solver_); + osqp_solver_ = nullptr; } } - csc.p[cols] = nnz; +}; - return csc; +Solver::Solver(const Configuration& configuration) + : impl_(std::make_unique(configuration)) +{ } -void evaluate_osqp_exitflag(OSQPInt exitflag, const std::string& context) +Solver::Solver(Solver&& other) noexcept = default; + +Solver& Solver::operator=(Solver&& other) noexcept { - if(exitflag != 0) - { - throw std::runtime_error("Solver::solve_quadratic_program(): "+context+" failed. OSQP returned error code "+std::to_string(exitflag)+": "+std::string(osqp_error_message(exitflag))); - } + if(this != &other) + impl_ = std::move(other.impl_); + return *this; } -VectorXd Solver::solve_quadratic_program(const MatrixXd& H, const VectorXd& f, const MatrixXd& A, const VectorXd& b, const MatrixXd& Aeq, const VectorXd& beq, const VectorXd& x0, const VectorXd& y0) +Solver::~Solver() = default; + +Eigen::VectorXd Solver::solve_quadratic_program(const Eigen::MatrixXd& H, const Eigen::VectorXd& f, const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const Eigen::MatrixXd& Aeq, const Eigen::VectorXd& beq, const Eigen::VectorXd& x0, const Eigen::VectorXd& y0) { const OSQPInt PROBLEM_SIZE = static_cast(H.rows()); const OSQPInt INEQUALITY_CONSTRAINT_SIZE = static_cast(b.size()); @@ -190,42 +651,42 @@ VectorXd Solver::solve_quadratic_program(const MatrixXd& H, const VectorXd& f, c ///Check sizes //Objective function - if(H.rows()!=H.cols()) + if(H.rows() != H.cols()) throw std::runtime_error("Solver::solve_quadratic_program(): H must be symmetric. H.rows()="+std::to_string(H.rows())+" but H.cols()="+std::to_string(H.cols())+"."); - if(f.size()!=H.rows()) + if(f.size() != H.rows()) throw std::runtime_error("Solver::solve_quadratic_program(): f must be compatible with H. H.rows()=H.cols()="+std::to_string(H.rows())+" but f.size()="+std::to_string(f.size())+"."); //Optional warm-start (e.g. a known feasible solution) for the primal variable x. - if(x0.size()!=0 && x0.size()!=PROBLEM_SIZE) + if(x0.size() != 0 && x0.size() != PROBLEM_SIZE) throw std::runtime_error("Solver::solve_quadratic_program(): x0 must be compatible with H. H.rows()=H.cols()="+std::to_string(H.rows())+" but x0.size()="+std::to_string(x0.size())+"."); //Optional warm-start (e.g. a dual solution obtained from get_info().dual_solution in a //previous call) for the dual variable y. - if(y0.size()!=0 && y0.size()!=TOTAL_CONSTRAINT_SIZE) + if(y0.size() != 0 && y0.size() != TOTAL_CONSTRAINT_SIZE) throw std::runtime_error("Solver::solve_quadratic_program(): y0 must be compatible with the total number of constraints. b.size()+beq.size()="+std::to_string(TOTAL_CONSTRAINT_SIZE)+" but y0.size()="+std::to_string(y0.size())+"."); //Inequality constraints - if(b.size()!=A.rows()) + if(b.size() != A.rows()) throw std::runtime_error("Solver::solve_quadratic_program(): size of b="+std::to_string(b.size())+" should be compatible with rows of A="+std::to_string(A.rows())+"."); - if(INEQUALITY_CONSTRAINT_SIZE!=0 && A.cols()!=PROBLEM_SIZE) + if(INEQUALITY_CONSTRAINT_SIZE != 0 && A.cols() != PROBLEM_SIZE) throw std::runtime_error("Solver::solve_quadratic_program(): A.cols()="+std::to_string(A.cols())+" should be compatible with H.rows()="+std::to_string(PROBLEM_SIZE)+"."); //Equality constraints - if(beq.size()!=Aeq.rows()) + if(beq.size() != Aeq.rows()) throw std::runtime_error("Solver::solve_quadratic_program(): size of beq="+std::to_string(beq.size())+" should be compatible with rows of Aeq="+std::to_string(Aeq.rows())+"."); - if(EQUALITY_CONSTRAINT_SIZE!=0 && Aeq.cols()!=PROBLEM_SIZE) + if(EQUALITY_CONSTRAINT_SIZE != 0 && Aeq.cols() != PROBLEM_SIZE) throw std::runtime_error("Solver::solve_quadratic_program(): Aeq.cols()="+std::to_string(Aeq.cols())+" should be compatible with H.rows()="+std::to_string(PROBLEM_SIZE)+"."); //Stack the inequality and equality constraints into OSQP's single l <= Ax <= u form. //Equality rows get l==u==beq. Inequality rows get l=-infinity, u=b. - MatrixXd A_extended(TOTAL_CONSTRAINT_SIZE, PROBLEM_SIZE); - VectorXd l_extended(TOTAL_CONSTRAINT_SIZE); - VectorXd u_extended(TOTAL_CONSTRAINT_SIZE); + Eigen::MatrixXd A_extended(TOTAL_CONSTRAINT_SIZE, PROBLEM_SIZE); + Eigen::VectorXd l_extended(TOTAL_CONSTRAINT_SIZE); + Eigen::VectorXd u_extended(TOTAL_CONSTRAINT_SIZE); if(INEQUALITY_CONSTRAINT_SIZE > 0) { A_extended.topRows(INEQUALITY_CONSTRAINT_SIZE) = A; - l_extended.head(INEQUALITY_CONSTRAINT_SIZE) = VectorXd::Constant(INEQUALITY_CONSTRAINT_SIZE, -OSQP_INFTY); + l_extended.head(INEQUALITY_CONSTRAINT_SIZE) = Eigen::VectorXd::Constant(INEQUALITY_CONSTRAINT_SIZE, -OSQP_INFTY); u_extended.head(INEQUALITY_CONSTRAINT_SIZE) = b; } if(EQUALITY_CONSTRAINT_SIZE > 0) @@ -235,58 +696,60 @@ VectorXd Solver::solve_quadratic_program(const MatrixXd& H, const VectorXd& f, c u_extended.tail(EQUALITY_CONSTRAINT_SIZE) = beq; } + auto& impl = *impl_; + //Convert the dense Eigen data into the CSC format required by OSQP. Every entry (including //zeros) is stored explicitly so that the sparsity pattern is stable across calls, which is //what allows osqp_update_data_mat() to be used below when hotstarting. - CSCMatrixData P_csc = _dense_to_csc_upper_triangular(H); - CSCMatrixData A_csc = _dense_to_csc(A_extended); - auto q_vec = _vectorxd_to_std_vector_double(f); - auto l_vec = _vectorxd_to_std_vector_double(l_extended); - auto u_vec = _vectorxd_to_std_vector_double(u_extended); + Solver::Impl::CSCMatrixData P_csc = Solver::Impl::dense_to_csc_upper_triangular(H); + Solver::Impl::CSCMatrixData A_csc = Solver::Impl::dense_to_csc(A_extended); + auto q_vec = impl.vectorxd_to_std_vector_double(f); + auto l_vec = impl.vectorxd_to_std_vector_double(l_extended); + auto u_vec = impl.vectorxd_to_std_vector_double(u_extended); - const bool problem_shape_changed = (PROBLEM_SIZE != problem_size_) || (TOTAL_CONSTRAINT_SIZE != constraint_size_); + const bool problem_shape_changed = (PROBLEM_SIZE != impl.problem_size_) || (TOTAL_CONSTRAINT_SIZE != impl.constraint_size_); - if(osqp_solve_first_time_ || problem_shape_changed || !configuration_.use_hotstart) + if(impl.osqp_solve_first_time_ || problem_shape_changed || !detail::boolean_from(impl.configuration_, "use_hotstart")) { //(Re)create the solver from scratch. This is required the first time, whenever the //problem dimensions change, or whenever hotstarting is disabled in the configuration. - _cleanup(); + impl.cleanup(); OSQPSettings* settings = OSQPSettings_new(); if(settings == nullptr) throw std::runtime_error("Solver::solve_quadratic_program(): unable to allocate OSQPSettings."); //Overwrite OSQP's defaults with the user's configuration. - const OSQPSettings user_settings = _to_osqp_settings(); + const OSQPSettings user_settings = detail::settings_from(impl.configuration_); *settings = user_settings; OSQPCscMatrix* P = OSQPCscMatrix_new(PROBLEM_SIZE, PROBLEM_SIZE, static_cast(P_csc.x.size()), P_csc.x.data(), P_csc.i.data(), P_csc.p.data()); OSQPCscMatrix* A_mat = OSQPCscMatrix_new(TOTAL_CONSTRAINT_SIZE, PROBLEM_SIZE, static_cast(A_csc.x.size()), A_csc.x.data(), A_csc.i.data(), A_csc.p.data()); - const OSQPInt exitflag = osqp_setup(&osqp_solver_, P, q_vec.data(), A_mat, l_vec.data(), u_vec.data(), TOTAL_CONSTRAINT_SIZE, PROBLEM_SIZE, settings); + const OSQPInt exitflag = osqp_setup(&impl.osqp_solver_, P, q_vec.data(), A_mat, l_vec.data(), u_vec.data(), TOTAL_CONSTRAINT_SIZE, PROBLEM_SIZE, settings); - //osqp_setup() copies whatever it needs out of P, A_mat and settings, so these can be freed - //right away (the underlying std::vector storage in P_csc/A_csc/q_vec/l_vec/u_vec is only - //required to stay alive up to this point). + //osqp_setup() copies whatever it needs out of P, A_mat and settings, so these can be + //freed right away (the underlying std::vector storage in P_csc/A_csc/q_vec/l_vec/u_vec + //is only required to stay alive up to this point). OSQPCscMatrix_free(P); OSQPCscMatrix_free(A_mat); OSQPSettings_free(settings); - evaluate_osqp_exitflag(exitflag, "osqp_setup()"); + detail::evaluate_osqp_exitflag(exitflag, "osqp_setup()"); - problem_size_ = PROBLEM_SIZE; - constraint_size_ = TOTAL_CONSTRAINT_SIZE; - osqp_solve_first_time_ = false; + impl.problem_size_ = PROBLEM_SIZE; + impl.constraint_size_ = TOTAL_CONSTRAINT_SIZE; + impl.osqp_solve_first_time_ = false; } else { //Same problem shape as before: update the existing solver's data in place instead of //rebuilding it, analogous to qpOASES_Solver's hotstart() call. - evaluate_osqp_exitflag(osqp_update_data_vec(osqp_solver_, q_vec.data(), l_vec.data(), u_vec.data()), "osqp_update_data_vec()"); - evaluate_osqp_exitflag(osqp_update_data_mat(osqp_solver_, - P_csc.x.data(), nullptr, static_cast(P_csc.x.size()), - A_csc.x.data(), nullptr, static_cast(A_csc.x.size())), - "osqp_update_data_mat()"); + detail::evaluate_osqp_exitflag(osqp_update_data_vec(impl.osqp_solver_, q_vec.data(), l_vec.data(), u_vec.data()), "osqp_update_data_vec()"); + detail::evaluate_osqp_exitflag(osqp_update_data_mat(impl.osqp_solver_, + P_csc.x.data(), nullptr, static_cast(P_csc.x.size()), + A_csc.x.data(), nullptr, static_cast(A_csc.x.size())), + "osqp_update_data_mat()"); } //If the user provided a warm-start for x and/or y, forward it to OSQP. Either can be @@ -300,59 +763,60 @@ VectorXd Solver::solve_quadratic_program(const MatrixXd& H, const VectorXd& f, c if(x0.size() != 0) { - x0_vec = _vectorxd_to_std_vector_double(x0); + x0_vec = impl.vectorxd_to_std_vector_double(x0); x0_ptr = x0_vec.data(); } if(y0.size() != 0) { - y0_vec = _vectorxd_to_std_vector_double(y0); + y0_vec = impl.vectorxd_to_std_vector_double(y0); y0_ptr = y0_vec.data(); } - evaluate_osqp_exitflag(osqp_warm_start(osqp_solver_, x0_ptr, y0_ptr), "osqp_warm_start()"); + detail::evaluate_osqp_exitflag(osqp_warm_start(impl.osqp_solver_, x0_ptr, y0_ptr), "osqp_warm_start()"); } - evaluate_osqp_exitflag(osqp_solve(osqp_solver_), "osqp_solve()"); + detail::evaluate_osqp_exitflag(osqp_solve(impl.osqp_solver_), "osqp_solve()"); - const OSQPInt status = osqp_solver_->info->status_val; + const OSQPInt status = impl.osqp_solver_->info->status_val; if(status != OSQP_SOLVED && status != OSQP_SOLVED_INACCURATE) - throw std::runtime_error("Solver::solve_quadratic_program(): unable to solve quadratic program. OSQP status: "+std::string(osqp_solver_->info->status)); + throw std::runtime_error("Solver::solve_quadratic_program(): unable to solve quadratic program. OSQP status: "+std::string(impl.osqp_solver_->info->status)); - std::vector return_value_std(osqp_solver_->solution->x, osqp_solver_->solution->x + PROBLEM_SIZE); + std::vector return_value_std(impl.osqp_solver_->solution->x, impl.osqp_solver_->solution->x + PROBLEM_SIZE); - return _std_vector_double_to_vectorxd(return_value_std); + return impl.std_vector_double_to_vectorxd(return_value_std); } Solver::Info Solver::get_info() const { - if(osqp_solver_ == nullptr || osqp_solver_->info == nullptr) + const auto& impl = *impl_; + if(impl.osqp_solver_ == nullptr || impl.osqp_solver_->info == nullptr) throw std::runtime_error("Solver::get_info(): no solution information available. solve_quadratic_program() must be called successfully first."); Info info; - info.obj_val = osqp_solver_->info->obj_val; - info.dual_obj_val = osqp_solver_->info->dual_obj_val; - info.prim_res = osqp_solver_->info->prim_res; - info.dual_res = osqp_solver_->info->dual_res; + info.obj_val = impl.osqp_solver_->info->obj_val; + info.dual_obj_val = impl.osqp_solver_->info->dual_obj_val; + info.prim_res = impl.osqp_solver_->info->prim_res; + info.dual_res = impl.osqp_solver_->info->dual_res; //The dual solution y (Lagrange multiplier associated with l <= Ax <= u) has //constraint_size_ entries, i.e. the total number of inequality/equality rows used //in the last successful solve_quadratic_program() call. - if(constraint_size_ > 0 && osqp_solver_->solution != nullptr && osqp_solver_->solution->y != nullptr) + if(impl.constraint_size_ > 0 && impl.osqp_solver_->solution != nullptr && impl.osqp_solver_->solution->y != nullptr) { - std::vector y_std(osqp_solver_->solution->y, osqp_solver_->solution->y + constraint_size_); - info.dual_solution = _std_vector_double_to_vectorxd(y_std); + std::vector y_std(impl.osqp_solver_->solution->y, impl.osqp_solver_->solution->y + impl.constraint_size_); + info.dual_solution = impl.std_vector_double_to_vectorxd(y_std); } return info; } // Helper functions to help evaluate the wrapper when needed. -VectorXd Solver::test_vectorxd(const VectorXd& v) +Eigen::VectorXd Solver::test_vectorxd(const Eigen::VectorXd& v) { return v; } -MatrixXd Solver::test_matrixxd(const MatrixXd& m) +Eigen::MatrixXd Solver::test_matrixxd(const Eigen::MatrixXd& m) { return m; } diff --git a/tests/test_solver.py b/tests/test_solver.py new file mode 100644 index 0000000..7eb776c --- /dev/null +++ b/tests/test_solver.py @@ -0,0 +1,200 @@ +""" +Copyright (C) 2025 Murilo Marques Marinho (www.murilomarinho.info) +LGPLv2.1 License + +Tests for `Solver` (in particular reusing one instance for problems whose +number of variables or constraints changes between calls) and for the +name-keyed `Configuration` (`set`/`get`/`has`/`keys`/`defaults`/`reset`). +""" +from __future__ import annotations + +import numpy as np +import pytest + +from marinholab.solvers import osqp + +H2 = np.eye(2) +F2 = np.array([-1.0, -1.0]) +A_THREE_ROWS = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]) +B_THREE_ROWS = np.array([0.2, 0.3, 10.0]) +A_ONE_ROW = np.array([[1.0, 0.0]]) +B_ONE_ROW = np.array([0.2]) + + +def _configuration(use_hotstart: bool = True, eps_abs: float = 1.0e-10, eps_rel: float = 1.0e-10, max_iter: int = 20000, polishing: bool = True) -> osqp.Configuration: + configuration = osqp.Configuration() + configuration.set("use_hotstart", use_hotstart) + configuration.set("eps_abs", eps_abs) + configuration.set("eps_rel", eps_rel) + configuration.set("max_iter", max_iter) + configuration.set("polishing", polishing) + return configuration + + +def _random_problem(rng: np.random.Generator, n: int, m: int): + """A strictly convex QP for which x = 0 is feasible.""" + M = rng.standard_normal((n, n)) + H = M @ M.T + np.eye(n) + f = rng.standard_normal(n) + A = rng.standard_normal((m, n)) + b = rng.uniform(0.1, 1.0, m) + return H, f, A, b + + +def test_single_solve(): + x = osqp.Solver(_configuration()).solve_quadratic_program(H2, F2, A_ONE_ROW, B_ONE_ROW, None, None) + assert np.allclose(x, [0.2, 1.0], atol=1e-6) + + +@pytest.mark.parametrize("use_hotstart", [True, False]) +def test_fewer_constraints_after_first_solve(use_hotstart: bool): + solver = osqp.Solver(_configuration(use_hotstart)) + x = solver.solve_quadratic_program(H2, F2, A_THREE_ROWS, B_THREE_ROWS, None, None) + assert np.allclose(x, [0.2, 0.3], atol=1e-6) + x = solver.solve_quadratic_program(H2, F2, A_ONE_ROW, B_ONE_ROW, None, None) + assert np.allclose(x, [0.2, 1.0], atol=1e-6) + + +@pytest.mark.parametrize("use_hotstart", [True, False]) +def test_more_constraints_after_first_solve(use_hotstart: bool): + solver = osqp.Solver(_configuration(use_hotstart)) + x = solver.solve_quadratic_program(H2, F2, A_ONE_ROW, B_ONE_ROW, None, None) + assert np.allclose(x, [0.2, 1.0], atol=1e-6) + x = solver.solve_quadratic_program(H2, F2, A_THREE_ROWS, B_THREE_ROWS, None, None) + assert np.allclose(x, [0.2, 0.3], atol=1e-6) + + +@pytest.mark.parametrize("use_hotstart", [True, False]) +def test_different_number_of_variables(use_hotstart: bool): + solver = osqp.Solver(_configuration(use_hotstart)) + x = solver.solve_quadratic_program(H2, F2, A_ONE_ROW, B_ONE_ROW, None, None) + assert np.allclose(x, [0.2, 1.0], atol=1e-6) + H3 = np.eye(3) + f3 = np.array([-1.0, -1.0, -1.0]) + x = solver.solve_quadratic_program(H3, f3, np.array([[0.0, 0.0, 1.0]]), np.array([0.5]), None, None) + assert np.allclose(x, [1.0, 1.0, 0.5], atol=1e-6) + + +def test_same_size_warm_start(): + """Consecutive problems of the same size, as in a control loop.""" + rng = np.random.default_rng(1) + solver = osqp.Solver(_configuration()) + H, f, A, b = _random_problem(rng, 5, 8) + for _ in range(50): + f = f + 0.05 * rng.standard_normal(5) + b = np.clip(b + 0.05 * rng.standard_normal(8), 0.1, None) + x_reused = solver.solve_quadratic_program(H, f, A, b, None, None) + x_fresh = osqp.Solver(_configuration()).solve_quadratic_program(H, f, A, b, None, None) + assert np.allclose(x_reused, x_fresh, atol=1e-6) + + +@pytest.mark.parametrize("use_hotstart", [True, False]) +def test_reused_solver_matches_fresh_solver_when_sizes_change(use_hotstart: bool): + rng = np.random.default_rng(0) + solver = osqp.Solver(_configuration(use_hotstart)) + for _ in range(200): + n = int(rng.integers(2, 8)) + m = int(rng.integers(1, 12)) + H, f, A, b = _random_problem(rng, n, m) + x_fresh = osqp.Solver(_configuration()).solve_quadratic_program(H, f, A, b, None, None) + x_reused = solver.solve_quadratic_program(H, f, A, b, None, None) + assert np.allclose(x_reused, x_fresh, atol=1e-6) + + +# OSQP's own defaults for its tolerances/parameters (double precision, +# direct-solver build), from osqp_set_default_settings(). +_OSQP_TOLERANCE_DEFAULTS = { + "eps_abs": 1.0e-3, + "eps_rel": 1.0e-3, + "eps_prim_inf": 1.0e-4, + "eps_dual_inf": 1.0e-4, + "sigma": 1.0e-6, + "delta": 1.0e-6, + "rho": 0.1, + "alpha": 1.6, + "cg_tol_fraction": 0.15, + "adaptive_rho_tolerance": 5.0, + "adaptive_rho_fraction": 0.4, + "time_limit": 1.0e10, +} + + +@pytest.mark.parametrize("key,expected", sorted(_OSQP_TOLERANCE_DEFAULTS.items())) +def test_defaults_match_osqp(key: str, expected: float): + value = osqp.Configuration().get(key) + assert isinstance(value, float) + assert value == pytest.approx(expected, rel=1e-12, abs=0.0) + + +def test_defaults_ints_and_booleans(): + configuration = osqp.Configuration() + assert configuration.get("max_iter") == 4000 + assert type(configuration.get("max_iter")) is int + assert configuration.get("use_hotstart") is True + # `verbose` defaults to quiet (off) instead of OSQP's own default (on). + assert configuration.get("verbose") is False + assert configuration.get("linsys_solver") == "OSQP_DIRECT_SOLVER" + assert configuration.get("cg_precond") == "OSQP_DIAGONAL_PRECONDITIONER" + + +def test_values_are_typed(): + configuration = osqp.Configuration() + assert type(configuration.get("use_hotstart")) is bool + assert type(configuration.get("max_iter")) is int + assert type(configuration.get("eps_abs")) is float + assert configuration.get("linsys_solver") == "OSQP_DIRECT_SOLVER" + defaults = configuration.defaults() + assert sorted(defaults) == configuration.keys() + assert {type(v) for v in defaults.values()} == {bool, int, float, str} + + +@pytest.mark.parametrize("key,value,expected", [ + ("eps_abs", 1.0e-9, 1.0e-9), + ("eps_abs", "1.0e-9", 1.0e-9), + ("eps_abs", 2, 2.0), + ("eps_abs", np.float64(3.0e-9), 3.0e-9), + ("max_iter", 3, 3), + ("max_iter", "3", 3), + ("max_iter", np.int64(4), 4), + ("verbose", False, False), + ("verbose", "false", False), + ("linsys_solver", osqp.LinsysSolverType.OSQP_DIRECT_SOLVER, "OSQP_DIRECT_SOLVER"), + ("linsys_solver", "OSQP_DIRECT_SOLVER", "OSQP_DIRECT_SOLVER"), + ("cg_precond", osqp.PreconditionerType.OSQP_NO_PRECONDITIONER, "OSQP_NO_PRECONDITIONER"), +]) +def test_set_converts_to_the_option_kind(key: str, value, expected): + configuration = osqp.Configuration() + configuration.set(key, value) + assert configuration.has(key) + got = configuration.get(key) + assert got == expected and type(got) is type(expected) + + +@pytest.mark.parametrize("key,value", [ + ("max_iter", 1.5), + ("max_iter", "1.5"), + ("verbose", 1.0), + ("verbose", "maybe"), + ("eps_abs", True), + ("eps_abs", "small"), + ("linsys_solver", 4), + ("linsys_solver", "OSQP_NOPE"), + ("no_such_option", 1), +]) +def test_set_rejects_values_of_the_wrong_kind(key: str, value): + configuration = osqp.Configuration() + with pytest.raises(ValueError): + configuration.set(key, value) + if key != "no_such_option": + assert not configuration.has(key) + + +def test_string_and_number_give_the_same_solution(): + rng = np.random.default_rng(2) + H, f, A, b = _random_problem(rng, 5, 8) + solutions = [] + for value in (1.0e-9, "1.0e-9"): + configuration = osqp.Configuration() + configuration.set("eps_abs", value) + solutions.append(osqp.Solver(configuration).solve_quadratic_program(H, f, A, b, None, None)) + assert np.array_equal(solutions[0], solutions[1]) diff --git a/tools/bump-changelog.sh b/tools/bump-changelog.sh new file mode 100755 index 0000000..61a8b26 --- /dev/null +++ b/tools/bump-changelog.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Bring debian/changelog in line with the rolling version (YY.MM.NN). +# Idempotent: a no-op when the changelog already carries that version. +# Run this before `dpkg-buildpackage` so the produced .deb is stamped with +# the version computed at build time. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +VERSION="$(bash "${ROOT}/tools/version.sh")" +CURRENT="$(head -n1 "${ROOT}/debian/changelog" | sed -nE 's/^[A-Za-z0-9._+-]+ \(([^)]*)\).*$/\1/p')" + +if [ "${VERSION}" = "${CURRENT}" ]; then + echo "Changelog already at ${VERSION}." +else + # dch identity: prefer the package maintainer (single source of truth in + # debian/control). Setting DEBFULLNAME/DEBEMAIL keeps dch non-interactive + # (it takes the name from DEBFULLNAME, not DEBNAME) -- without them dch + # prints warnings and waits for a keypress, which would hang unattended + # builds. + MAINTAINER="$(sed -nE 's/^Maintainer:[[:space:]]*(.*)$/\1/p' "${ROOT}/debian/control" | head -n1)" + EMAIL_RE='<([^>]+)>' + if [[ "${MAINTAINER}" =~ ${EMAIL_RE} ]]; then + NAME="${MAINTAINER%%" <"*}" + EMAIL="${BASH_REMATCH[1]}" + else + NAME="$(git -C "${ROOT}" config user.name || echo maintainer)" + EMAIL="$(git -C "${ROOT}" config user.email || echo maintainer@example.com)" + fi + DEBFULLNAME="${NAME}" DEBEMAIL="${EMAIL}" \ + dch --distribution noble -v "${VERSION}" \ + "Bumped to rolling version ${VERSION}." +fi diff --git a/tools/version.sh b/tools/version.sh new file mode 100755 index 0000000..30bc825 --- /dev/null +++ b/tools/version.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Compute the rolling project version: YY.MM.NN +# YY.MM : year.month of the current date (e.g. 26.09) +# NN : number of commits since the monthly version tag (e.g. 26.09). +# 00 when no such tag exists yet. +# The monthly tag is looked up without a "v" prefix; a "v"-prefixed +# tag is accepted as a fallback. +# Output: 26.09.05 +set -euo pipefail + +YYMM="$(date +%y.%m)" + +# Echo the first existing monthly tag (bare YY.MM, then v-prefixed). +find_version_tag() { + local t + for t in "${YYMM}" "v${YYMM}"; do + if git rev-parse --verify "refs/tags/${t}" >/dev/null 2>&1; then + printf '%s\n' "${t}" + return 0 + fi + done + return 1 +} + +NN=0 +if command -v git >/dev/null 2>&1 && git rev-parse --git-dir >/dev/null 2>&1; then + if TAG="$(find_version_tag)"; then + NN="$(git rev-list "${TAG}..HEAD" --count 2>/dev/null || echo 0)" + fi +fi + +printf '%s.%02d\n' "${YYMM}" "${NN:-0}"