From 3d9f83e1809a8a84aa4f619635c53dfb890ca7bd Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Fri, 23 Jan 2026 23:18:22 -0500 Subject: [PATCH 1/7] Remove Python packaging, add LICENSE - Remove pyproject.toml (Python packaging now handled by CVXPY) - Remove src/dnlp_diff_engine/ Python wrapper (no longer needed) - Add Apache 2.0 LICENSE file Co-Authored-By: Claude Opus 4.5 --- LICENSE | 201 +++++++++++++++++++++++++++++++ pyproject.toml | 44 ------- src/dnlp_diff_engine/__init__.py | 53 -------- 3 files changed, 201 insertions(+), 97 deletions(-) create mode 100644 LICENSE delete mode 100644 pyproject.toml delete mode 100644 src/dnlp_diff_engine/__init__.py diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b1a313f --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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/pyproject.toml b/pyproject.toml deleted file mode 100644 index 37c735f..0000000 --- a/pyproject.toml +++ /dev/null @@ -1,44 +0,0 @@ -[build-system] -requires = ["scikit-build-core>=0.5", "numpy"] -build-backend = "scikit_build_core.build" - -[project] -name = "dnlp-diff-engine" -version = "0.1.0" -description = "Low-level C autodiff engine for nonlinear optimization" -readme = "README.md" -requires-python = ">=3.10" -dependencies = [ - "numpy", -] - -[project.optional-dependencies] -test = [ - "pytest>=7.0", - "cvxpy", # For integration tests - "scipy", # Required by cvxpy integration -] -dev = [ - "pytest>=7.0", - "ruff", -] - -[tool.scikit-build] -cmake.source-dir = "." -wheel.packages = ["src/dnlp_diff_engine"] -build-dir = "build/{wheel_tag}" - -[tool.scikit-build.cmake.define] -CMAKE_BUILD_TYPE = "Debug" - -[tool.pytest.ini_options] -testpaths = ["python/tests"] -python_files = ["test_*.py"] -python_functions = ["test_*"] - -[tool.ruff] -line-length = 100 -target-version = "py310" - -[tool.ruff.lint] -select = ["E", "F", "W", "I"] diff --git a/src/dnlp_diff_engine/__init__.py b/src/dnlp_diff_engine/__init__.py deleted file mode 100644 index b1ab670..0000000 --- a/src/dnlp_diff_engine/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -DNLP Diff Engine - Low-level C bindings for automatic differentiation. - -This package provides the raw C extension for building expression trees -and computing derivatives. For CVXPY integration, use: - from cvxpy.reductions.solvers.nlp_solvers.diff_engine import C_problem -""" - -# Re-export all C functions directly from the _core extension -from ._core import * # noqa: F401, F403 - -__all__ = [ - # Atom constructors - "make_variable", - "make_constant", - "make_add", - "make_broadcast", - "make_neg", - "make_sum", - "make_promote", - "make_index", - "make_reshape", - "make_log", - "make_exp", - "make_power", - "make_entr", - "make_logistic", - "make_xexp", - "make_sin", - "make_cos", - "make_tan", - "make_sinh", - "make_tanh", - "make_asinh", - "make_atanh", - "make_multiply", - "make_const_scalar_mult", - "make_const_vector_mult", - "make_left_matmul", - "make_right_matmul", - "make_quad_form", - "make_quad_over_lin", - "make_rel_entr", - "make_prod", - # Problem interface - "make_problem", - "problem_init_derivatives", - "problem_objective_forward", - "problem_constraint_forward", - "problem_gradient", - "problem_jacobian", - "problem_hessian", -] From 35bf83bbc17124d7d867859f333799d22d0a30ef Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Fri, 23 Jan 2026 23:19:28 -0500 Subject: [PATCH 2/7] Rename Python module from _core to _diffengine Update module name to _diffengine for integration with CVXPY build system. Co-Authored-By: Claude Opus 4.5 --- python/bindings.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/bindings.c b/python/bindings.c index 71d702a..f7c5232 100644 --- a/python/bindings.c +++ b/python/bindings.c @@ -145,9 +145,9 @@ static PyMethodDef DNLPMethods[] = { {NULL, NULL, 0, NULL}}; static struct PyModuleDef dnlp_module = { - PyModuleDef_HEAD_INIT, "dnlp_diff_engine._core", NULL, -1, DNLPMethods}; + PyModuleDef_HEAD_INIT, "_diffengine", NULL, -1, DNLPMethods}; -PyMODINIT_FUNC PyInit__core(void) +PyMODINIT_FUNC PyInit__diffengine(void) { if (ensure_numpy() < 0) return NULL; return PyModule_Create(&dnlp_module); From e2a3c1a63b28919290e648415d43d2aec9fafdc7 Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Fri, 23 Jan 2026 23:23:41 -0500 Subject: [PATCH 3/7] Update CLAUDE.md for pure C library setup Document the new workflow where Python packaging is handled by CVXPY. Co-Authored-By: Claude Opus 4.5 --- CLAUDE.md | 63 +++++++++++++++++++------------------------------------ 1 file changed, 22 insertions(+), 41 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d97f995..e9a7f2a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,36 +4,13 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Overview -DNLP-diff-engine is a C library with Python bindings that provides automatic differentiation for nonlinear optimization problems. It builds expression trees (ASTs) from CVXPY problems and computes first and second derivatives (gradients, Jacobians, Hessians) needed by NLP solvers like IPOPT. +DNLP-diff-engine is a pure C library that provides automatic differentiation for nonlinear optimization problems. It builds expression trees (ASTs) from CVXPY problems and computes first and second derivatives (gradients, Jacobians, Hessians) needed by NLP solvers like IPOPT. -## Build Commands - -### Python Package (Recommended) - -```bash -# Install in development mode with uv (recommended) -uv pip install -e ".[test]" - -# Or with pip -pip install -e ".[test]" +**Note:** This library is designed to be used as a git submodule in CVXPY. Python packaging is handled by the CVXPY build system, not this repository. -# Run all Python tests (tests are in python/tests/) -pytest - -# Run specific test file -pytest python/tests/test_unconstrained.py - -# Run specific test -pytest python/tests/test_unconstrained.py::test_sum_log - -# Lint with ruff -ruff check src/ - -# Auto-fix lint issues -ruff check --fix src/ -``` +## Build Commands -### Standalone C Library +### Standalone C Library (for testing/development) ```bash # Build core C library and tests @@ -44,6 +21,17 @@ cmake --build build ./build/all_tests ``` +### Building with CVXPY + +This library is included as a git submodule in CVXPY. To build: + +```bash +# From the CVXPY repository root +pip install -e . # or: uv pip install -e . + +# The _diffengine Python extension is built automatically +``` + ## Architecture ### Expression Tree System @@ -81,18 +69,12 @@ Key oracle methods: ### Python Bindings -The Python package `dnlp_diff_engine` (in `src/dnlp_diff_engine/`) provides: - -**High-level API** (`__init__.py`): -- `C_problem` class wraps the C problem struct -- `convert_problem()` builds expression trees from CVXPY Problem objects -- Atoms are mapped via `ATOM_CONVERTERS` dictionary (maps CVXPY atom names → converter functions) -- Special converters handle: matrix multiplication (`_convert_matmul`), multiply with constants (`_convert_multiply`), indexing, reshape (Fortran order only) - -**Low-level C extension** (`_core` module, built from `python/bindings.c`): +The Python C extension (`_diffengine` module, built from `python/bindings.c`) provides: - Atom constructors: `make_variable`, `make_constant`, `make_log`, `make_exp`, `make_add`, etc. - Problem interface: `make_problem`, `problem_init_derivatives`, `problem_objective_forward`, `problem_gradient`, `problem_jacobian`, `problem_hessian` +The high-level Python API (converters, C_problem class) is in CVXPY at `cvxpy/reductions/solvers/nlp_solvers/diff_engine/`. + ### Derivative Computation Flow 1. **Initialization**: `problem_init_derivatives()` allocates storage and computes sparsity patterns for all Jacobians and Hessians. This is done once per problem. @@ -112,11 +94,10 @@ Hessian computes weighted sum: `obj_w * H_obj + sum(lambda_i * H_constraint_i)`, - `include/` - Header files defining public API (`expr.h`, `problem.h`, atom headers) - `src/` - C implementation files organized by atom category -- `src/dnlp_diff_engine/` - Python package with high-level API (`__init__.py` contains `C_problem` class and `ATOM_CONVERTERS`) - `python/` - Python bindings C code (`bindings.c`) - `python/atoms/` - Python binding headers for each atom type - `python/problem/` - Python binding headers for problem interface -- `python/tests/` - Python integration tests (run via pytest): `test_unconstrained.py`, `test_constrained.py`, `test_problem_native.py` +- `python/tests/` - Python integration tests (run via pytest from CVXPY) - `tests/` - C tests using minunit framework - `tests/forward_pass/` - Forward evaluation tests (C) - `tests/jacobian_tests/` - Jacobian correctness tests (C) @@ -129,9 +110,9 @@ Hessian computes weighted sum: `obj_w * H_obj + sum(lambda_i * H_constraint_i)`, 3. Implement: `forward`, `jacobian_init`, `eval_jacobian`, `eval_wsum_hess` (optional), `free_type_data` (if needed) 4. Add Python binding header in `python/atoms/` 5. Register in `python/bindings.c` (both include and method table) -6. Export in `src/dnlp_diff_engine/__init__.py` `__all__` list -7. Rebuild: `uv pip install -e .` -8. Add tests in `tests/` (C, register in `tests/all_tests.c`) and `python/tests/` (Python) +6. Add converter in CVXPY: `cvxpy/reductions/solvers/nlp_solvers/diff_engine/converters.py` +7. Rebuild CVXPY: `pip install -e .` +8. Add tests in `tests/` (C, register in `tests/all_tests.c`) and CVXPY `cvxpy/tests/nlp_tests/` ## Known Limitations From 81110c4d41712589afb0db0d97befc85774364d7 Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Wed, 21 Jan 2026 21:53:18 -0500 Subject: [PATCH 4/7] Add diag_vec atom for creating diagonal matrices from vectors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements diag_vec which converts a vector of size n into an n×n diagonal matrix. Includes forward pass, Jacobian, and Hessian computations. Co-Authored-By: Claude Opus 4.5 --- include/affine.h | 1 + python/atoms/diag_vec.h | 32 +++++++++ python/bindings.c | 2 + src/affine/diag_vec.c | 140 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 175 insertions(+) create mode 100644 python/atoms/diag_vec.h create mode 100644 src/affine/diag_vec.c diff --git a/include/affine.h b/include/affine.h index 88b1f7b..00286f0 100644 --- a/include/affine.h +++ b/include/affine.h @@ -22,5 +22,6 @@ expr *new_index(expr *child, int d1, int d2, const int *indices, int n_idxs); expr *new_reshape(expr *child, int d1, int d2); expr *new_broadcast(expr *child, int target_d1, int target_d2); expr *new_transpose(expr *child); +expr *new_diag_vec(expr *child); #endif /* AFFINE_H */ diff --git a/python/atoms/diag_vec.h b/python/atoms/diag_vec.h new file mode 100644 index 0000000..b1056d6 --- /dev/null +++ b/python/atoms/diag_vec.h @@ -0,0 +1,32 @@ +#ifndef ATOM_DIAG_VEC_H +#define ATOM_DIAG_VEC_H + +#include "common.h" + +static PyObject *py_make_diag_vec(PyObject *self, PyObject *args) +{ + PyObject *child_capsule; + + if (!PyArg_ParseTuple(args, "O", &child_capsule)) + { + return NULL; + } + + expr *child = (expr *) PyCapsule_GetPointer(child_capsule, EXPR_CAPSULE_NAME); + if (!child) + { + return NULL; + } + + expr *node = new_diag_vec(child); + if (!node) + { + PyErr_SetString(PyExc_RuntimeError, "failed to create diag_vec node"); + return NULL; + } + + expr_retain(node); + return PyCapsule_New(node, EXPR_CAPSULE_NAME, expr_capsule_destructor); +} + +#endif /* ATOM_DIAG_VEC_H */ diff --git a/python/bindings.c b/python/bindings.c index f7c5232..47c5fc8 100644 --- a/python/bindings.c +++ b/python/bindings.c @@ -11,6 +11,7 @@ #include "atoms/const_vector_mult.h" #include "atoms/constant.h" #include "atoms/cos.h" +#include "atoms/diag_vec.h" #include "atoms/entr.h" #include "atoms/exp.h" #include "atoms/getters.h" @@ -96,6 +97,7 @@ static PyMethodDef DNLPMethods[] = { "Create prod_axis_one node"}, {"make_sin", py_make_sin, METH_VARARGS, "Create sin node"}, {"make_cos", py_make_cos, METH_VARARGS, "Create cos node"}, + {"make_diag_vec", py_make_diag_vec, METH_VARARGS, "Create diag_vec node"}, {"make_tan", py_make_tan, METH_VARARGS, "Create tan node"}, {"make_sinh", py_make_sinh, METH_VARARGS, "Create sinh node"}, {"make_tanh", py_make_tanh, METH_VARARGS, "Create tanh node"}, diff --git a/src/affine/diag_vec.c b/src/affine/diag_vec.c new file mode 100644 index 0000000..6f6a9b2 --- /dev/null +++ b/src/affine/diag_vec.c @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "affine.h" +#include +#include +#include + +/* diag_vec: converts a vector of size n into an n×n diagonal matrix. + * In Fortran (column-major) order, element i of the input maps to + * position i*(n+1) in the flattened output (the diagonal positions). */ + +static void forward(expr *node, const double *u) +{ + expr *x = node->left; + int n = x->size; + + /* child's forward pass */ + x->forward(x, u); + + /* zero-initialize output */ + memset(node->value, 0, node->size * sizeof(double)); + + /* place input elements on the diagonal */ + for (int i = 0; i < n; i++) + { + node->value[i * (n + 1)] = x->value[i]; + } +} + +static void jacobian_init(expr *node) +{ + expr *x = node->left; + int n = x->size; + x->jacobian_init(x); + + CSR_Matrix *Jx = x->jacobian; + + /* Output Jacobian has n² rows, but only n rows (diagonal positions) are non-zero. + * We allocate space for the same nnz as child, but with n² rows. */ + CSR_Matrix *J = new_csr_matrix(node->size, node->n_vars, Jx->nnz); + + /* Build row pointers: rows at diagonal positions copy from child, + * all other rows are empty */ + J->p[0] = 0; + int child_row = 0; + for (int out_row = 0; out_row < node->size; out_row++) + { + if (out_row == child_row * (n + 1) && child_row < n) + { + /* This is a diagonal position - copy sparsity from child row */ + int len = Jx->p[child_row + 1] - Jx->p[child_row]; + memcpy(J->i + J->p[out_row], Jx->i + Jx->p[child_row], len * sizeof(int)); + J->p[out_row + 1] = J->p[out_row] + len; + child_row++; + } + else + { + /* Non-diagonal row - empty */ + J->p[out_row + 1] = J->p[out_row]; + } + } + + node->jacobian = J; +} + +static void eval_jacobian(expr *node) +{ + expr *x = node->left; + int n = x->size; + x->eval_jacobian(x); + + CSR_Matrix *J = node->jacobian; + CSR_Matrix *Jx = x->jacobian; + + /* Copy values from child Jacobian to diagonal positions */ + int child_row = 0; + for (int out_row = 0; out_row < node->size && child_row < n; out_row++) + { + if (out_row == child_row * (n + 1)) + { + int len = J->p[out_row + 1] - J->p[out_row]; + memcpy(J->x + J->p[out_row], Jx->x + Jx->p[child_row], len * sizeof(double)); + child_row++; + } + } +} + +static void wsum_hess_init(expr *node) +{ + expr *x = node->left; + + /* initialize child's wsum_hess */ + x->wsum_hess_init(x); + + /* workspace for extracting diagonal weights */ + node->dwork = (double *) calloc(x->size, sizeof(double)); + + /* Copy child's Hessian structure (diag_vec is linear, so its own Hessian is zero) */ + CSR_Matrix *Hx = x->wsum_hess; + node->wsum_hess = new_csr_matrix(Hx->m, Hx->n, Hx->nnz); + memcpy(node->wsum_hess->p, Hx->p, (Hx->m + 1) * sizeof(int)); + memcpy(node->wsum_hess->i, Hx->i, Hx->nnz * sizeof(int)); +} + +static void eval_wsum_hess(expr *node, const double *w) +{ + expr *x = node->left; + int n = x->size; + + /* Extract weights from diagonal positions of w (which has n² elements) */ + for (int i = 0; i < n; i++) + { + node->dwork[i] = w[i * (n + 1)]; + } + + /* Evaluate child's Hessian with extracted weights */ + x->eval_wsum_hess(x, node->dwork); + memcpy(node->wsum_hess->x, x->wsum_hess->x, x->wsum_hess->nnz * sizeof(double)); +} + +static bool is_affine(const expr *node) +{ + return node->left->is_affine(node->left); +} + +expr *new_diag_vec(expr *child) +{ + /* child must be a vector: either column (n, 1) or row (1, n) */ + assert(child->d1 == 1 || child->d2 == 1); + + /* n is the number of elements (works for both row and column vectors) */ + int n = child->size; + expr *node = (expr *) calloc(1, sizeof(expr)); + init_expr(node, n, n, child->n_vars, forward, jacobian_init, eval_jacobian, + is_affine, wsum_hess_init, eval_wsum_hess, NULL); + node->left = child; + expr_retain(child); + + return node; +} From f0df9c156fb95ab4ffd5d1b17776f4f026ce0d71 Mon Sep 17 00:00:00 2001 From: William Zijie Zhang Date: Wed, 21 Jan 2026 22:04:31 -0500 Subject: [PATCH 5/7] Clean up diag_vec jacobian_init and eval_jacobian - Use standard CSR building pattern (J->p[row] = nnz) - Use next_diag counter instead of checking row == child_row * (n+1) - Simplify eval_jacobian to O(n) loop computing out_row directly Co-Authored-By: Claude Opus 4.5 --- src/affine/diag_vec.c | 44 +++++++++++++++++-------------------------- 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/src/affine/diag_vec.c b/src/affine/diag_vec.c index 6f6a9b2..5d2a303 100644 --- a/src/affine/diag_vec.c +++ b/src/affine/diag_vec.c @@ -34,31 +34,25 @@ static void jacobian_init(expr *node) x->jacobian_init(x); CSR_Matrix *Jx = x->jacobian; - - /* Output Jacobian has n² rows, but only n rows (diagonal positions) are non-zero. - * We allocate space for the same nnz as child, but with n² rows. */ CSR_Matrix *J = new_csr_matrix(node->size, node->n_vars, Jx->nnz); - /* Build row pointers: rows at diagonal positions copy from child, - * all other rows are empty */ - J->p[0] = 0; - int child_row = 0; - for (int out_row = 0; out_row < node->size; out_row++) + /* Output has n² rows but only n diagonal positions are non-empty. + * Diagonal position i is at row i*(n+1) in Fortran order. */ + int nnz = 0; + int next_diag = 0; + for (int row = 0; row < node->size; row++) { - if (out_row == child_row * (n + 1) && child_row < n) + J->p[row] = nnz; + if (row == next_diag) { - /* This is a diagonal position - copy sparsity from child row */ + int child_row = row / (n + 1); int len = Jx->p[child_row + 1] - Jx->p[child_row]; - memcpy(J->i + J->p[out_row], Jx->i + Jx->p[child_row], len * sizeof(int)); - J->p[out_row + 1] = J->p[out_row] + len; - child_row++; - } - else - { - /* Non-diagonal row - empty */ - J->p[out_row + 1] = J->p[out_row]; + memcpy(J->i + nnz, Jx->i + Jx->p[child_row], len * sizeof(int)); + nnz += len; + next_diag += n + 1; } } + J->p[node->size] = nnz; node->jacobian = J; } @@ -72,16 +66,12 @@ static void eval_jacobian(expr *node) CSR_Matrix *J = node->jacobian; CSR_Matrix *Jx = x->jacobian; - /* Copy values from child Jacobian to diagonal positions */ - int child_row = 0; - for (int out_row = 0; out_row < node->size && child_row < n; out_row++) + /* Copy values from child row i to output diagonal row i*(n+1) */ + for (int i = 0; i < n; i++) { - if (out_row == child_row * (n + 1)) - { - int len = J->p[out_row + 1] - J->p[out_row]; - memcpy(J->x + J->p[out_row], Jx->x + Jx->p[child_row], len * sizeof(double)); - child_row++; - } + int out_row = i * (n + 1); + int len = J->p[out_row + 1] - J->p[out_row]; + memcpy(J->x + J->p[out_row], Jx->x + Jx->p[i], len * sizeof(double)); } } From 35f6f5202bd3a76136519df775ee4a41e025d8fd Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 30 Jan 2026 10:01:12 -0800 Subject: [PATCH 6/7] update readme --- README.md | 63 +++---------------------------------------- src/affine/diag_vec.c | 7 ++--- 2 files changed, 8 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 739ba9b..882899c 100644 --- a/README.md +++ b/README.md @@ -1,62 +1,7 @@ -# DNLP Diff Engine +# CVXPY DNLP Differentiation Engine -A C library with Python bindings for automatic differentiation of nonlinear optimization problems. Builds expression trees from CVXPY problems and computes gradients, Jacobians, and Hessians needed by NLP solvers like IPOPT. +This repository contains a **C implementation of the differentiation engine used by CVXPY** for its extension to [**Disciplined Nonlinear Programming (DNLP)**](https://github.com/cvxgrp/DNLP). -## Installation +The library provides low-level routines for computing derivatives required by nonlinear programming problems. +The library is intended as a **backend component** and is not meant to be used directly by end users. -### Using uv (recommended) - -```bash -uv venv .venv -source .venv/bin/activate -uv pip install -e ".[test]" -``` - -### Using pip - -```bash -python -m venv .venv -source .venv/bin/activate -pip install -e ".[test]" -``` - -## Running Tests - -```bash -# first go to python folder - -# Run all tests -pytest -``` - -## Usage - -```python -import cvxpy as cp -import numpy as np -from dnlp_diff_engine import C_problem - -# Define a CVXPY problem -x = cp.Variable(3) -problem = cp.Problem(cp.Minimize(cp.sum(cp.log(x)))) - -# Convert to C problem struct -prob = C_problem(problem) -prob.init_derivatives() - -# Evaluate at a point -u = np.array([1.0, 2.0, 3.0]) -obj_val = prob.objective_forward(u) -gradient = prob.gradient() - -print(f"Objective: {obj_val}") -print(f"Gradient: {gradient}") -``` - -## Building the C Library (standalone) - -```bash -cmake -B build -S . -cmake --build build -./build/all_tests -``` diff --git a/src/affine/diag_vec.c b/src/affine/diag_vec.c index 5d2a303..184ebd0 100644 --- a/src/affine/diag_vec.c +++ b/src/affine/diag_vec.c @@ -36,7 +36,7 @@ static void jacobian_init(expr *node) CSR_Matrix *Jx = x->jacobian; CSR_Matrix *J = new_csr_matrix(node->size, node->n_vars, Jx->nnz); - /* Output has n² rows but only n diagonal positions are non-empty. + /* Output has n^2 rows but only n diagonal positions are non-empty. * Diagonal position i is at row i*(n+1) in Fortran order. */ int nnz = 0; int next_diag = 0; @@ -85,7 +85,8 @@ static void wsum_hess_init(expr *node) /* workspace for extracting diagonal weights */ node->dwork = (double *) calloc(x->size, sizeof(double)); - /* Copy child's Hessian structure (diag_vec is linear, so its own Hessian is zero) */ + /* Copy child's Hessian structure (diag_vec is linear, so its own Hessian is + * zero) */ CSR_Matrix *Hx = x->wsum_hess; node->wsum_hess = new_csr_matrix(Hx->m, Hx->n, Hx->nnz); memcpy(node->wsum_hess->p, Hx->p, (Hx->m + 1) * sizeof(int)); @@ -97,7 +98,7 @@ static void eval_wsum_hess(expr *node, const double *w) expr *x = node->left; int n = x->size; - /* Extract weights from diagonal positions of w (which has n² elements) */ + /* Extract weights from diagonal positions of w (which has n^2 elements) */ for (int i = 0; i < n; i++) { node->dwork[i] = w[i * (n + 1)]; From c1a3e21d7386dcfd92c54e5bc08a8e573b8570a2 Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 30 Jan 2026 10:05:17 -0800 Subject: [PATCH 7/7] added our names to license --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index b1a313f..b55a190 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2025 Daniel Cederberg and William Zhang Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.