cl1norm 2.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cl1norm-2.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2026 Jan Zwiener
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ # sdist contents beyond what setuptools picks up by itself (the extension's
2
+ # .c sources, pyproject.toml, setup.py, the readme and the license)
3
+ include src/cl1norm.h src/cl1norm_impl.inc
4
+ recursive-include python/tests *.py
cl1norm-2.1.0/PKG-INFO ADDED
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: cl1norm
3
+ Version: 2.1.0
4
+ Summary: Fast constrained L1 (least absolute deviations) solver: Barrodale-Roberts simplex in C
5
+ Author: Jan Zwiener
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jnz/cl1norm
8
+ Project-URL: Source, https://github.com/jnz/cl1norm
9
+ Project-URL: Issues, https://github.com/jnz/cl1norm/issues
10
+ Keywords: l1,least-absolute-deviations,robust-regression,linear-programming,simplex,barrodale-roberts,outlier
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: C
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Operating System :: Microsoft :: Windows
19
+ Classifier: Operating System :: MacOS
20
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.23
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # cl1norm
30
+
31
+ Fast constrained L1 solver for Python: solves `A @ x = b` in the L1 sense
32
+ (least absolute deviations) instead of least squares, which makes it robust
33
+ against outliers in `b`, optionally subject to linear equality and
34
+ inequality constraints:
35
+
36
+ minimize sum(|b - A @ x|)
37
+ subject to C @ x = d, E @ x <= f
38
+
39
+ The solver is the Barrodale-Roberts simplex method (ACM Algorithm 552),
40
+ written in C, with a thin numpy layer on top. For small and medium problems
41
+ (up to a few thousand observations) it is much faster than a general LP
42
+ solver. Benchmarks, the C/C++/MATLAB interfaces and the embedded use are
43
+ described on [GitHub](https://github.com/jnz/cl1norm).
44
+
45
+ ## Install
46
+
47
+ ```sh
48
+ pip install cl1norm
49
+ ```
50
+
51
+ Pre-compiled wheels for CPython 3.11 and later on Linux x86_64 and aarch64,
52
+ Raspberry Pi OS 64-bit and 32-bit, Windows (64- and 32-bit) and macOS (Intel
53
+ and Apple silicon). numpy is the only dependency. Elsewhere (e.g. a Pi
54
+ Zero/1) pip builds from source, which needs a C compiler.
55
+
56
+ On a Raspberry Pi (Raspberry Pi OS 64-bit, or 32-bit on a Pi 2 and newer)
57
+ pip installs into a virtual environment. PyPI has no numpy for 32-bit ARM,
58
+ so take numpy from apt there (works on 64-bit too):
59
+
60
+ ```sh
61
+ sudo apt install python3-numpy
62
+ python3 -m venv --system-site-packages ~/venv
63
+ ~/venv/bin/pip install cl1norm
64
+ ```
65
+
66
+ ## Quick start
67
+
68
+ ```python
69
+ import numpy as np
70
+ import cl1norm
71
+
72
+ # fit y = x[0] + x[1]*t, the 5th measurement is an outlier
73
+ t = np.arange(8.0)
74
+ y = np.array([1.0, 1.5, 2.0, 2.5, 9.0, 3.5, 4.0, 4.5])
75
+ A = np.column_stack([np.ones_like(t), t])
76
+
77
+ x = cl1norm.solve(A, y) # array([1. , 0.5]): outlier ignored
78
+ x_ls = np.linalg.lstsq(A, y, rcond=None)[0] # array([1.5, 0.571]): pulled away
79
+
80
+ # offset fixed to 1.2 (C @ x = d), slope at most 0.4 (E @ x <= f)
81
+ r = cl1norm.solve(A, y, C=[1, 0], d=1.2, E=[0, 1], f=0.4, full_output=True)
82
+ r.x, r.residuals, r.error, r.iterations, r.status
83
+ ```
84
+
85
+ ## API
86
+
87
+ `cl1norm.solve(A, b, C=None, d=None, E=None, f=None, *, tol=None, maxiter=None, full_output=False)`
88
+
89
+ | argument | size | meaning |
90
+ |---------------|----------|------------------------------------------------|
91
+ | `A`, `b` | k x n, k | observations: minimize `sum(abs(b - A @ x))` |
92
+ | `C`, `d` | l x n, l | optional equality constraints `C @ x = d` |
93
+ | `E`, `f` | m x n, m | optional inequality constraints `E @ x <= f` |
94
+ | `tol` | | simplex tolerance, `None`: default |
95
+ | `maxiter` | | iteration limit, `None`: `10 * (k + l + m)` |
96
+ | `full_output` | | return a `Result` instead of only `x` |
97
+
98
+ * Returns `x` (n values) or, with `full_output=True`, a `Result` with `x`,
99
+ `residuals` (`[b - A@x, d - C@x, f - E@x]`), `error` (the minimum sum),
100
+ `iterations`, `status`, `success` and `message`.
101
+ * Raises `cl1norm.SolverError` if no optimal solution is found (infeasible
102
+ constraints, rounding errors, iteration limit); `err.result` holds the
103
+ attempt. Inconsistent shapes or NaN/Inf raise `ValueError`.
104
+ * float32 inputs (all of them) are solved in single precision, everything
105
+ else in double precision.
106
+ * The GIL is released while solving.
107
+
108
+ ## References
109
+
110
+ I. Barrodale and F. D. K. Roberts. 1980. Algorithm 552: Solution of the
111
+ Constrained L1 Linear Approximation Problem [F4]. ACM Trans. Math. Softw. 6,
112
+ 2 (June 1980), 231-235. https://doi.org/10.1145/355887.355896
113
+
114
+ ## License
115
+
116
+ MIT
@@ -0,0 +1,68 @@
1
+ # Packaging of the cl1norm Python package (pip install cl1norm).
2
+ #
3
+ # setup.py adds the C extension (python/cl1norm/_cl1norm.c + src/cl1norm.c),
4
+ # so building needs a C compiler:
5
+ # pip install . # build and install from the checkout
6
+ # python -m build # sdist + wheel into dist/
7
+ # The release wheels come from cibuildwheel in
8
+ # .github/workflows/release-pypi.yml. The extension uses the stable ABI, so
9
+ # there is one wheel per platform (cp311-abi3), not one per Python version.
10
+
11
+ [build-system]
12
+ requires = ["setuptools>=77"]
13
+ build-backend = "setuptools.build_meta"
14
+
15
+ [project]
16
+ name = "cl1norm"
17
+ dynamic = ["version"]
18
+ description = "Fast constrained L1 (least absolute deviations) solver: Barrodale-Roberts simplex in C"
19
+ readme = "python/PYPI.md"
20
+ requires-python = ">=3.11"
21
+ license = "MIT"
22
+ license-files = ["LICENSE"]
23
+ authors = [{ name = "Jan Zwiener" }]
24
+ dependencies = ["numpy>=1.23"]
25
+ keywords = ["l1", "least-absolute-deviations", "robust-regression",
26
+ "linear-programming", "simplex", "barrodale-roberts", "outlier"]
27
+ classifiers = [
28
+ "Development Status :: 5 - Production/Stable",
29
+ "Intended Audience :: Science/Research",
30
+ "Intended Audience :: Developers",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3 :: Only",
33
+ "Programming Language :: C",
34
+ "Operating System :: POSIX :: Linux",
35
+ "Operating System :: Microsoft :: Windows",
36
+ "Operating System :: MacOS",
37
+ "Topic :: Scientific/Engineering :: Mathematics",
38
+ ]
39
+
40
+ [project.optional-dependencies]
41
+ test = ["pytest"]
42
+
43
+ [project.urls]
44
+ Homepage = "https://github.com/jnz/cl1norm"
45
+ Source = "https://github.com/jnz/cl1norm"
46
+ Issues = "https://github.com/jnz/cl1norm/issues"
47
+
48
+ [tool.setuptools]
49
+ package-dir = { "" = "python" }
50
+ packages = ["cl1norm"]
51
+ include-package-data = false
52
+
53
+ # cl1norm.__version__ is the version of the release (tag v<version>, checked
54
+ # by .github/workflows/release-pypi.yml)
55
+ [tool.setuptools.dynamic]
56
+ version = { attr = "cl1norm.__version__" }
57
+
58
+ # abi3: one interpreter per platform is enough. The architectures per runner
59
+ # are set by the workflow matrix (CIBW_ARCHS).
60
+ [tool.cibuildwheel]
61
+ build = "cp311-*"
62
+ # 32-bit ARM only as manylinux (Raspberry Pi OS), Alpine there is rare
63
+ skip = "*-musllinux_armv7l"
64
+ test-requires = ["pytest"]
65
+ test-command = "pytest {project}/python/tests"
66
+ # PyPI has no numpy wheels for 32-bit ARM, so the armv7l wheel is tested in a
67
+ # Debian armhf container with apt's numpy instead (release-pypi.yml)
68
+ test-skip = "*-manylinux_armv7l"
@@ -0,0 +1,88 @@
1
+ # cl1norm
2
+
3
+ Fast constrained L1 solver for Python: solves `A @ x = b` in the L1 sense
4
+ (least absolute deviations) instead of least squares, which makes it robust
5
+ against outliers in `b`, optionally subject to linear equality and
6
+ inequality constraints:
7
+
8
+ minimize sum(|b - A @ x|)
9
+ subject to C @ x = d, E @ x <= f
10
+
11
+ The solver is the Barrodale-Roberts simplex method (ACM Algorithm 552),
12
+ written in C, with a thin numpy layer on top. For small and medium problems
13
+ (up to a few thousand observations) it is much faster than a general LP
14
+ solver. Benchmarks, the C/C++/MATLAB interfaces and the embedded use are
15
+ described on [GitHub](https://github.com/jnz/cl1norm).
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ pip install cl1norm
21
+ ```
22
+
23
+ Pre-compiled wheels for CPython 3.11 and later on Linux x86_64 and aarch64,
24
+ Raspberry Pi OS 64-bit and 32-bit, Windows (64- and 32-bit) and macOS (Intel
25
+ and Apple silicon). numpy is the only dependency. Elsewhere (e.g. a Pi
26
+ Zero/1) pip builds from source, which needs a C compiler.
27
+
28
+ On a Raspberry Pi (Raspberry Pi OS 64-bit, or 32-bit on a Pi 2 and newer)
29
+ pip installs into a virtual environment. PyPI has no numpy for 32-bit ARM,
30
+ so take numpy from apt there (works on 64-bit too):
31
+
32
+ ```sh
33
+ sudo apt install python3-numpy
34
+ python3 -m venv --system-site-packages ~/venv
35
+ ~/venv/bin/pip install cl1norm
36
+ ```
37
+
38
+ ## Quick start
39
+
40
+ ```python
41
+ import numpy as np
42
+ import cl1norm
43
+
44
+ # fit y = x[0] + x[1]*t, the 5th measurement is an outlier
45
+ t = np.arange(8.0)
46
+ y = np.array([1.0, 1.5, 2.0, 2.5, 9.0, 3.5, 4.0, 4.5])
47
+ A = np.column_stack([np.ones_like(t), t])
48
+
49
+ x = cl1norm.solve(A, y) # array([1. , 0.5]): outlier ignored
50
+ x_ls = np.linalg.lstsq(A, y, rcond=None)[0] # array([1.5, 0.571]): pulled away
51
+
52
+ # offset fixed to 1.2 (C @ x = d), slope at most 0.4 (E @ x <= f)
53
+ r = cl1norm.solve(A, y, C=[1, 0], d=1.2, E=[0, 1], f=0.4, full_output=True)
54
+ r.x, r.residuals, r.error, r.iterations, r.status
55
+ ```
56
+
57
+ ## API
58
+
59
+ `cl1norm.solve(A, b, C=None, d=None, E=None, f=None, *, tol=None, maxiter=None, full_output=False)`
60
+
61
+ | argument | size | meaning |
62
+ |---------------|----------|------------------------------------------------|
63
+ | `A`, `b` | k x n, k | observations: minimize `sum(abs(b - A @ x))` |
64
+ | `C`, `d` | l x n, l | optional equality constraints `C @ x = d` |
65
+ | `E`, `f` | m x n, m | optional inequality constraints `E @ x <= f` |
66
+ | `tol` | | simplex tolerance, `None`: default |
67
+ | `maxiter` | | iteration limit, `None`: `10 * (k + l + m)` |
68
+ | `full_output` | | return a `Result` instead of only `x` |
69
+
70
+ * Returns `x` (n values) or, with `full_output=True`, a `Result` with `x`,
71
+ `residuals` (`[b - A@x, d - C@x, f - E@x]`), `error` (the minimum sum),
72
+ `iterations`, `status`, `success` and `message`.
73
+ * Raises `cl1norm.SolverError` if no optimal solution is found (infeasible
74
+ constraints, rounding errors, iteration limit); `err.result` holds the
75
+ attempt. Inconsistent shapes or NaN/Inf raise `ValueError`.
76
+ * float32 inputs (all of them) are solved in single precision, everything
77
+ else in double precision.
78
+ * The GIL is released while solving.
79
+
80
+ ## References
81
+
82
+ I. Barrodale and F. D. K. Roberts. 1980. Algorithm 552: Solution of the
83
+ Constrained L1 Linear Approximation Problem [F4]. ACM Trans. Math. Softw. 6,
84
+ 2 (June 1980), 231-235. https://doi.org/10.1145/355887.355896
85
+
86
+ ## License
87
+
88
+ MIT
@@ -0,0 +1,184 @@
1
+ """cl1norm: constrained L1 (least absolute deviations) solver.
2
+
3
+ Solves ``A @ x = b`` in the L1 sense, i.e. finds the ``x`` that minimizes
4
+ ``sum(abs(b - A @ x))``, optionally subject to ``C @ x = d`` and
5
+ ``E @ x <= f``. Robust against outliers in ``b``.
6
+
7
+ The solver is the Barrodale-Roberts simplex method (ACM Algorithm 552) in C,
8
+ see https://github.com/jnz/cl1norm.
9
+
10
+ >>> import numpy as np, cl1norm
11
+ >>> t = np.arange(8.0)
12
+ >>> A = np.column_stack([np.ones(8), t])
13
+ >>> b = np.array([1.0, 1.5, 2.0, 2.5, 9.0, 3.5, 4.0, 4.5]) # 9.0: outlier
14
+ >>> cl1norm.solve(A, b)
15
+ array([1. , 0.5])
16
+ """
17
+
18
+ from typing import NamedTuple, Optional
19
+
20
+ import numpy as np
21
+
22
+ from . import _cl1norm
23
+
24
+ __version__ = "2.1.0"
25
+
26
+ __all__ = ["solve", "Result", "SolverError"]
27
+
28
+ # return codes of cl1_solve_double() / cl1_solve_float() that come from the
29
+ # solver itself; anything above is an argument error the wrapper prevents
30
+ _MESSAGES = {
31
+ 0: "optimal solution found",
32
+ 1: "no feasible solution to the constraints",
33
+ 2: "calculations terminated prematurely due to rounding errors",
34
+ 3: "maximum number of iterations reached",
35
+ }
36
+
37
+
38
+ class Result(NamedTuple):
39
+ """Full result of :func:`solve` (``full_output=True``).
40
+
41
+ Attributes:
42
+ x: the solution, ``n`` values.
43
+ residuals: ``[b - A@x, d - C@x, f - E@x]``, ``k + l + m`` values.
44
+ error: the minimum ``sum(abs(b - A@x))``.
45
+ iterations: number of simplex iterations.
46
+ status: 0 optimal, 1 infeasible constraints, 2 rounding errors,
47
+ 3 iteration limit reached.
48
+ """
49
+
50
+ x: np.ndarray
51
+ residuals: np.ndarray
52
+ error: float
53
+ iterations: int
54
+ status: int
55
+
56
+ @property
57
+ def success(self) -> bool:
58
+ """True if an optimal solution was found."""
59
+ return self.status == 0
60
+
61
+ @property
62
+ def message(self) -> str:
63
+ """The status as text."""
64
+ return _MESSAGES.get(self.status, "unknown status %d" % self.status)
65
+
66
+
67
+ class SolverError(RuntimeError):
68
+ """Raised by :func:`solve` if no optimal solution was found.
69
+
70
+ The ``result`` attribute holds the :class:`Result` of the attempt.
71
+ """
72
+
73
+ def __init__(self, result: Result):
74
+ super().__init__("cl1norm: %s (status %d)" % (result.message, result.status))
75
+ self.result = result
76
+
77
+
78
+ def _matrix(name, M, dtype, n):
79
+ M = np.asarray(M, dtype=dtype)
80
+ if M.ndim == 1: # a single constraint row, e.g. C=[1, 0]
81
+ M = M.reshape(1, -1)
82
+ if M.ndim != 2:
83
+ raise ValueError("%s must be a 2-D array, got shape %s" % (name, M.shape))
84
+ if n is not None and M.shape[1] != n:
85
+ raise ValueError("%s must have %d columns (like A), got shape %s"
86
+ % (name, n, M.shape))
87
+ return np.ascontiguousarray(M)
88
+
89
+
90
+ def _vector(name, v, dtype, rows, matrix_name):
91
+ v = np.asarray(v, dtype=dtype)
92
+ if v.ndim == 2 and v.shape[1] == 1: # column vector
93
+ v = v[:, 0]
94
+ elif v.ndim == 0: # scalar for a single constraint, e.g. d=1.2
95
+ v = v.reshape(1)
96
+ if v.ndim != 1 or v.shape[0] != rows:
97
+ raise ValueError("%s must have %d values (the rows of %s), got shape %s"
98
+ % (name, rows, matrix_name, v.shape))
99
+ return np.ascontiguousarray(v)
100
+
101
+
102
+ def solve(A, b, C=None, d=None, E=None, f=None, *,
103
+ tol: Optional[float] = None, maxiter: Optional[int] = None,
104
+ full_output: bool = False):
105
+ """Solve ``A @ x = b`` in the L1 sense, optionally with constraints.
106
+
107
+ Minimizes ``sum(abs(b - A @ x))`` subject to ``C @ x = d`` and
108
+ ``E @ x <= f``.
109
+
110
+ Args:
111
+ A: ``k x n`` matrix, one row per observation.
112
+ b: ``k`` observations.
113
+ C, d: optional equality constraints ``C @ x = d``, ``C`` is
114
+ ``l x n``. A single constraint can be given as a 1-D ``C`` and
115
+ a scalar ``d``.
116
+ E, f: optional inequality constraints ``E @ x <= f``, ``E`` is
117
+ ``m x n``.
118
+ tol: tolerance of the simplex method. ``None`` (or ``<= 0``) selects
119
+ the default, 2e-11 in double and 1e-5 in single precision.
120
+ maxiter: iteration limit. ``None`` (or ``<= 0``) selects
121
+ ``10 * (k + l + m)``.
122
+ full_output: return a :class:`Result` instead of only ``x``.
123
+
124
+ Precision: float32 inputs (all of them) are solved in single precision,
125
+ everything else in double precision.
126
+
127
+ Returns:
128
+ ``x`` (``n`` values), or a :class:`Result` if ``full_output`` is set.
129
+
130
+ Raises:
131
+ ValueError: inconsistent shapes, or non-finite values in the input.
132
+ SolverError: no optimal solution (infeasible constraints, rounding
133
+ errors or iteration limit); ``err.result`` holds the attempt.
134
+ """
135
+ if (C is None) != (d is None):
136
+ raise ValueError("C and d must be given together")
137
+ if (E is None) != (f is None):
138
+ raise ValueError("E and f must be given together")
139
+
140
+ A, b, C, d, E, f = (None if v is None else np.asarray(v)
141
+ for v in (A, b, C, d, E, f))
142
+ given = [v for v in (A, b, C, d, E, f) if v is not None]
143
+ if any(np.iscomplexobj(v) for v in given):
144
+ raise TypeError("cl1norm: complex input is not supported")
145
+ single = np.result_type(*given) == np.float32
146
+ dtype = np.float32 if single else np.float64
147
+
148
+ A = _matrix("A", A, dtype, None)
149
+ k, n = A.shape
150
+ if k < 1 or n < 1:
151
+ raise ValueError("A must have at least one row and one column")
152
+ b = _vector("b", b, dtype, k, "A")
153
+
154
+ if C is not None:
155
+ C = _matrix("C", C, dtype, n)
156
+ d = _vector("d", d, dtype, C.shape[0], "C")
157
+ l = 0 if C is None else C.shape[0]
158
+ if E is not None:
159
+ E = _matrix("E", E, dtype, n)
160
+ f = _vector("f", f, dtype, E.shape[0], "E")
161
+ m = 0 if E is None else E.shape[0]
162
+ if l == 0:
163
+ C = d = None
164
+ if m == 0:
165
+ E = f = None
166
+
167
+ for name, v in (("A", A), ("b", b), ("C", C), ("d", d), ("E", E), ("f", f)):
168
+ if v is not None and not np.isfinite(v).all():
169
+ raise ValueError("%s contains NaN or Inf" % name)
170
+
171
+ x = np.empty(n, dtype=dtype)
172
+ res = np.empty(k + l + m, dtype=dtype)
173
+ status, error, iterations = _cl1norm.solve(
174
+ k, l, m, n, A, b, C, d, E, f,
175
+ 0.0 if tol is None else float(tol),
176
+ 0 if maxiter is None else int(maxiter),
177
+ x, res, single)
178
+ if status not in _MESSAGES:
179
+ raise RuntimeError("cl1norm: internal error, return code %d" % status)
180
+
181
+ result = Result(x, res, error, iterations, status)
182
+ if status != 0:
183
+ raise SolverError(result)
184
+ return result if full_output else x
@@ -0,0 +1,208 @@
1
+ /*
2
+ * _cl1norm -- CPython extension module of the cl1norm Python package.
3
+ *
4
+ * Only a bridge to cl1_solve_double() / cl1_solve_float(): the package's
5
+ * __init__.py checks and converts the inputs with numpy and allocates x and
6
+ * res, this module allocates the workspace, releases the GIL and solves.
7
+ *
8
+ * Built against the stable ABI (Py_LIMITED_API, set by setup.py), so one
9
+ * wheel per platform serves every CPython from 3.11 on. The buffer protocol
10
+ * is the reason for 3.11: it joined the limited API there. No numpy headers
11
+ * are needed, numpy arrays are read and written through that protocol.
12
+ *
13
+ * Python signature (all arrays C-contiguous, float64 or float32 throughout):
14
+ *
15
+ * solve(k, l, m, n, A, b, C, d, E, f, tol, maxiter, x, res, single)
16
+ * -> (status, error, iterations)
17
+ *
18
+ * C, d may be None if l == 0, E, f may be None if m == 0.
19
+ */
20
+
21
+ #define PY_SSIZE_T_CLEAN
22
+ #include <Python.h>
23
+
24
+ #include <string.h> /* memset */
25
+
26
+ #include "cl1norm.h"
27
+
28
+ #define NBUF 8 /* A, b, C, d, E, f, x, res */
29
+
30
+ typedef struct
31
+ {
32
+ Py_buffer view[NBUF];
33
+ int held[NBUF];
34
+ } buffers_t;
35
+
36
+ static void release_all(buffers_t *bufs)
37
+ {
38
+ int i;
39
+ for (i = 0; i < NBUF; i++)
40
+ {
41
+ if (bufs->held[i])
42
+ {
43
+ PyBuffer_Release(&bufs->view[i]);
44
+ bufs->held[i] = 0;
45
+ }
46
+ }
47
+ }
48
+
49
+ /* Gets a C-contiguous buffer of exactly `count` items of `itemsize` bytes.
50
+ count == 0 accepts None (the optional C, d, E, f). */
51
+ static int get_buffer(buffers_t *bufs, int i, PyObject *obj, const char *name,
52
+ Py_ssize_t count, Py_ssize_t itemsize, int writable)
53
+ {
54
+ int flags = PyBUF_C_CONTIGUOUS;
55
+ if (writable)
56
+ {
57
+ flags |= PyBUF_WRITABLE;
58
+ }
59
+ if (obj == Py_None)
60
+ {
61
+ if (count == 0)
62
+ {
63
+ return 0;
64
+ }
65
+ PyErr_Format(PyExc_ValueError, "%s must not be None", name);
66
+ return -1;
67
+ }
68
+ if (PyObject_GetBuffer(obj, &bufs->view[i], flags) < 0)
69
+ {
70
+ return -1;
71
+ }
72
+ bufs->held[i] = 1;
73
+ if (bufs->view[i].itemsize != itemsize ||
74
+ bufs->view[i].len != count * itemsize)
75
+ {
76
+ PyErr_Format(PyExc_ValueError,
77
+ "%s: expected %zd items of %zd bytes, got %zd bytes",
78
+ name, count, itemsize, bufs->view[i].len);
79
+ return -1;
80
+ }
81
+ return 0;
82
+ }
83
+
84
+ static void *buf(const buffers_t *bufs, int i)
85
+ {
86
+ return bufs->held[i] ? bufs->view[i].buf : NULL;
87
+ }
88
+
89
+ static PyObject *cl1norm_solve(PyObject *self, PyObject *args)
90
+ {
91
+ int k, l, m, n, maxiter, single;
92
+ double tol;
93
+ PyObject *A, *b, *C, *d, *E, *f, *x, *res;
94
+ buffers_t bufs;
95
+ Py_ssize_t itemsize, klm;
96
+ size_t work_len, iwork_len;
97
+ void *work = NULL;
98
+ int *iwork = NULL;
99
+ cl1_result_t status;
100
+ double error = 0.0;
101
+ float error_f = 0.0f;
102
+ int iterations = 0;
103
+
104
+ (void)self;
105
+ memset(&bufs, 0, sizeof(bufs));
106
+
107
+ if (!PyArg_ParseTuple(args, "iiiiOOOOOOdiOOp:solve", &k, &l, &m, &n,
108
+ &A, &b, &C, &d, &E, &f, &tol, &maxiter, &x, &res,
109
+ &single))
110
+ {
111
+ return NULL;
112
+ }
113
+ if (k < 1 || n < 1 || l < 0 || m < 0)
114
+ {
115
+ PyErr_SetString(PyExc_ValueError,
116
+ "need k >= 1, n >= 1, l >= 0 and m >= 0");
117
+ return NULL;
118
+ }
119
+
120
+ itemsize = single ? (Py_ssize_t)sizeof(float) : (Py_ssize_t)sizeof(double);
121
+ klm = (Py_ssize_t)k + l + m;
122
+ if (get_buffer(&bufs, 0, A, "A", (Py_ssize_t)k * n, itemsize, 0) < 0 ||
123
+ get_buffer(&bufs, 1, b, "b", k, itemsize, 0) < 0 ||
124
+ get_buffer(&bufs, 2, C, "C", (Py_ssize_t)l * n, itemsize, 0) < 0 ||
125
+ get_buffer(&bufs, 3, d, "d", l, itemsize, 0) < 0 ||
126
+ get_buffer(&bufs, 4, E, "E", (Py_ssize_t)m * n, itemsize, 0) < 0 ||
127
+ get_buffer(&bufs, 5, f, "f", m, itemsize, 0) < 0 ||
128
+ get_buffer(&bufs, 6, x, "x", n, itemsize, 1) < 0 ||
129
+ get_buffer(&bufs, 7, res, "res", klm, itemsize, 1) < 0)
130
+ {
131
+ release_all(&bufs);
132
+ return NULL;
133
+ }
134
+
135
+ work_len = CL1_WORK_LEN(k, l, m, n);
136
+ iwork_len = CL1_IWORK_LEN(k, l, m, n);
137
+ work = PyMem_Malloc(work_len * (size_t)itemsize);
138
+ iwork = (int *)PyMem_Malloc(iwork_len * sizeof(int));
139
+ if (work == NULL || iwork == NULL)
140
+ {
141
+ PyMem_Free(work);
142
+ PyMem_Free(iwork);
143
+ release_all(&bufs);
144
+ return PyErr_NoMemory();
145
+ }
146
+
147
+ Py_BEGIN_ALLOW_THREADS
148
+ if (single)
149
+ {
150
+ status = cl1_solve_float(k, l, m, n,
151
+ (const float *)buf(&bufs, 0),
152
+ (const float *)buf(&bufs, 1),
153
+ (const float *)buf(&bufs, 2),
154
+ (const float *)buf(&bufs, 3),
155
+ (const float *)buf(&bufs, 4),
156
+ (const float *)buf(&bufs, 5),
157
+ CL1_ROW_MAJOR, (float)tol, maxiter,
158
+ (float *)buf(&bufs, 6),
159
+ (float *)buf(&bufs, 7),
160
+ &error_f, &iterations,
161
+ (float *)work, work_len, iwork, iwork_len);
162
+ error = (double)error_f;
163
+ }
164
+ else
165
+ {
166
+ status = cl1_solve_double(k, l, m, n,
167
+ (const double *)buf(&bufs, 0),
168
+ (const double *)buf(&bufs, 1),
169
+ (const double *)buf(&bufs, 2),
170
+ (const double *)buf(&bufs, 3),
171
+ (const double *)buf(&bufs, 4),
172
+ (const double *)buf(&bufs, 5),
173
+ CL1_ROW_MAJOR, tol, maxiter,
174
+ (double *)buf(&bufs, 6),
175
+ (double *)buf(&bufs, 7),
176
+ &error, &iterations,
177
+ (double *)work, work_len, iwork, iwork_len);
178
+ }
179
+ Py_END_ALLOW_THREADS
180
+
181
+ PyMem_Free(work);
182
+ PyMem_Free(iwork);
183
+ release_all(&bufs);
184
+
185
+ return Py_BuildValue("idi", (int)status, error, iterations);
186
+ }
187
+
188
+ static PyMethodDef cl1norm_methods[] = {
189
+ {"solve", cl1norm_solve, METH_VARARGS,
190
+ "solve(k, l, m, n, A, b, C, d, E, f, tol, maxiter, x, res, single)"
191
+ " -> (status, error, iterations)\n\n"
192
+ "Internal, use cl1norm.solve()."},
193
+ {NULL, NULL, 0, NULL}
194
+ };
195
+
196
+ static struct PyModuleDef cl1norm_module = {
197
+ PyModuleDef_HEAD_INIT,
198
+ "_cl1norm",
199
+ "C core of the cl1norm package (internal, use cl1norm.solve()).",
200
+ -1,
201
+ cl1norm_methods,
202
+ NULL, NULL, NULL, NULL
203
+ };
204
+
205
+ PyMODINIT_FUNC PyInit__cl1norm(void)
206
+ {
207
+ return PyModule_Create(&cl1norm_module);
208
+ }