pycapacity-cpp 0.1.0__cp313-cp313-win_amd64.whl

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.
@@ -0,0 +1,262 @@
1
+ """
2
+ Compiled polytope algorithms for pycapacity.
3
+
4
+ The functions below have the same signatures and return values as their
5
+ counterparts in :mod:`pycapacity.algorithms`, which calls them automatically
6
+ when this package is installed (set the environment variable
7
+ ``PYCAPACITY_BACKEND=python`` to disable that).
8
+
9
+ * :func:`hyper_plane_shift_method`
10
+ * :func:`vertex_enumeration_vepoli2`
11
+ * :func:`iterative_convex_hull_method`
12
+ * :func:`halfspace_intersection` (used by :func:`pycapacity.algorithms.hspace_to_vertex` in 2D and 3D)
13
+
14
+ and a general polytope projection, :func:`project_polytope`.
15
+ """
16
+
17
+
18
+ # start delvewheel patch
19
+ def _delvewheel_patch_1_13_2():
20
+ import os
21
+ if os.path.isdir(libs_dir := os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'pycapacity_cpp.libs'))):
22
+ os.add_dll_directory(libs_dir)
23
+
24
+
25
+ _delvewheel_patch_1_13_2()
26
+ del _delvewheel_patch_1_13_2
27
+ # end delvewheel patch
28
+
29
+ import numpy as np
30
+
31
+ from . import _core
32
+
33
+ __all__ = ["hyper_plane_shift_method", "vertex_enumeration_vepoli2",
34
+ "iterative_convex_hull_method", "project_polytope", "convex_hull",
35
+ "halfspace_intersection"]
36
+
37
+
38
+ def _vec(v, n=None):
39
+ if v is None:
40
+ return np.zeros(0)
41
+ v = np.asarray(v, dtype=float).reshape(-1)
42
+ if n is not None and v.size != n:
43
+ raise ValueError("expected {} entries, got {}".format(n, v.size))
44
+ return v
45
+
46
+
47
+ def _mat(M):
48
+ if M is None:
49
+ return np.zeros((0, 0))
50
+ return np.atleast_2d(np.asarray(M, dtype=float))
51
+
52
+
53
+ def hyper_plane_shift_method(A, x_min, x_max, tol=1e-12):
54
+ """Same as :func:`pycapacity.algorithms.hyper_plane_shift_method`.
55
+
56
+ Returns ``H, d`` with ``H x <= d``.
57
+ """
58
+ A = _mat(A)
59
+ H, d = _core.hyper_plane_shift_method(A, _vec(x_min, A.shape[1]),
60
+ _vec(x_max, A.shape[1]), tol)
61
+ return H, d
62
+
63
+
64
+ def vertex_enumeration_vepoli2(A, b_max, b_min, b_bias=None):
65
+ """Same as :func:`pycapacity.algorithms.vertex_enumeration_vepoli2`.
66
+
67
+ Vertices of ``{x | A x = b - b_bias, b_min <= b <= b_max}``; returns
68
+ ``x_vertex, b_vertex`` (``b_vertex = A x_vertex``).
69
+ """
70
+ A = _mat(A)
71
+ n = A.shape[0]
72
+ return _core.vertex_enumeration_vepoli2(A, _vec(b_min, n), _vec(b_max, n),
73
+ _vec(b_bias, n) if b_bias is not None
74
+ else np.zeros(0))
75
+
76
+
77
+ def iterative_convex_hull_method(A, B, y_min, y_max, tol, P=None, bias=None,
78
+ G_in=None, h_in=None, G_eq=None, h_eq=None,
79
+ max_iter=1000, verbose=False,
80
+ return_info=False, lp_solver="auto"):
81
+ """Same as :func:`pycapacity.algorithms.iterative_convex_hull_method`.
82
+
83
+ Returns ``x_vert, H, d, faces, y_vert, z_vert``; with ``return_info=True``
84
+ also a dict with the number of LPs solved, the final maximal error and
85
+ whether the tolerance was reached.
86
+
87
+ ``lp_solver``: ``"auto"`` (a small dense simplex warm-started from the
88
+ previous basis, HiGHS as fallback), ``"simplex"`` or ``"highs"``.
89
+
90
+ The vertices returned are the vertices of the final hull (the Python
91
+ implementation returns every point found, which can include points that
92
+ are not extreme).
93
+ """
94
+ A, B = _mat(A), _mat(B)
95
+ L = B.shape[1]
96
+ b = _vec(bias, A.shape[0]) if bias is not None else np.zeros(0)
97
+ r = _core.iterative_convex_hull_method(
98
+ A, B, _vec(y_min, L), _vec(y_max, L), float(tol), _mat(P), b,
99
+ _mat(G_in), _vec(h_in), _mat(G_eq), _vec(h_eq), int(max_iter),
100
+ {"auto": 0, "simplex": 1, "highs": 2}[lp_solver])
101
+ if verbose and not r.converged:
102
+ print("ICHM: stopped with max error {} > tol {} after {} LPs"
103
+ .format(r.max_delta, tol, r.n_lp))
104
+ z_vert = B @ r.y_vert + (b.reshape(-1, 1) if b.size else 0)
105
+ out = (r.x_vert, r.H, r.d, r.faces, r.y_vert, z_vert)
106
+ if return_info:
107
+ return out + ({"n_lp": r.n_lp, "max_delta": r.max_delta,
108
+ "converged": r.converged, "t_lp_ms": r.t_lp_ms,
109
+ "n_lp_fallback": r.n_lp_fallback,
110
+ "t_hull_ms": r.t_hull_ms},)
111
+ return out
112
+
113
+
114
+ def _split_bounds(A, b):
115
+ """Rows of A x <= b with a single nonzero are variable bounds: return
116
+ (lo, hi) from them and the remaining rows."""
117
+ n = A.shape[1]
118
+ lo, hi = np.full(n, -np.inf), np.full(n, np.inf)
119
+ nnz = np.count_nonzero(A, axis=1)
120
+ keep = nnz != 1
121
+ for i in np.where(nnz == 1)[0]:
122
+ j = np.flatnonzero(A[i])[0]
123
+ v = b[i] / A[i, j]
124
+ if A[i, j] > 0:
125
+ hi[j] = min(hi[j], v)
126
+ else:
127
+ lo[j] = max(lo[j], v)
128
+ if np.all(nnz == 0) and A.shape[0]:
129
+ keep[:] = True
130
+ return lo, hi, A[keep], b[keep]
131
+
132
+
133
+ def _bound_variables(lo, hi, A, b, C, d):
134
+ """Finite bounds for the variables still unbounded, by linear programs
135
+ over {A x <= b, C x = d, lo <= x <= hi}."""
136
+ n = lo.size
137
+ # fast path: warm-started dense simplex in C++, inside a large box
138
+ if A.shape[0] + (0 if C is None else C.shape[0]) <= 200:
139
+ scale = max(1.0, float(np.max(np.abs(b))) if b.size else 1.0,
140
+ float(np.max(np.abs(d))) if d is not None and d.size else 1.0,
141
+ float(np.max(np.abs(lo[np.isfinite(lo)]), initial=0)),
142
+ float(np.max(np.abs(hi[np.isfinite(hi)]), initial=0)))
143
+ rn = np.linalg.norm(A, axis=1) if A.shape[0] else np.ones(1)
144
+ big = 1e4 * scale / max(float(np.min(rn[rn > 0], initial=1.0)), 1e-12)
145
+ ok, l, h = _core.bound_variables(
146
+ A, b, _mat(C) if C is not None else np.zeros((0, n)),
147
+ d if d is not None else np.zeros(0), lo, hi, big)
148
+ if ok:
149
+ return l, h
150
+ # robust path (also detects unbounded/empty sets): scipy's HiGHS
151
+ from scipy.optimize import linprog
152
+ bounds = [(None if np.isinf(l) else l, None if np.isinf(h) else h)
153
+ for l, h in zip(lo, hi)]
154
+ kw = dict(A_ub=A if A.shape[0] else None, b_ub=b if A.shape[0] else None,
155
+ A_eq=C if C is not None and C.shape[0] else None,
156
+ b_eq=d if C is not None and C.shape[0] else None,
157
+ bounds=bounds, method="highs")
158
+ lo, hi = lo.copy(), hi.copy()
159
+ for j in range(n):
160
+ for sign in (1.0, -1.0):
161
+ if (sign > 0 and np.isfinite(lo[j])) or (sign < 0 and np.isfinite(hi[j])):
162
+ continue
163
+ c = np.zeros(n)
164
+ c[j] = sign
165
+ r = linprog(c, **kw)
166
+ if r.status == 3:
167
+ raise ValueError("the polytope is unbounded (variable {})"
168
+ .format(j))
169
+ if r.status != 0:
170
+ raise ValueError("the polytope is empty or the LP failed: "
171
+ + r.message)
172
+ if sign > 0:
173
+ lo[j] = r.fun
174
+ else:
175
+ hi[j] = -r.fun
176
+ return lo, hi
177
+
178
+
179
+ def project_polytope(proj, ineq, eq=None, tol=None, max_iter=100000,
180
+ return_info=False):
181
+ """Projection ``{E x + f | A x <= b, C x = d}`` of a polytope, in any
182
+ output dimension, with the iterative convex hull method.
183
+
184
+ Same arguments as :func:`pypoman.project_polytope` (``proj = (E, f)``,
185
+ ``ineq = (A, b)``, ``eq = (C, d)``) and the same result: the list of the
186
+ vertices of the projection.
187
+
188
+ Args:
189
+ tol: largest distance between the facets of the result and the exact
190
+ projection, in output units (the result is an inner
191
+ approximation; below ``1e-8`` times the size of the projection,
192
+ the precision of the LP solutions, it is raised to that).
193
+ Default: ``1e-7`` times the size of the projection.
194
+ return_info: also return ``H, d`` of the result (``H y <= d``) and a
195
+ dict with the number of LPs, the variable bounds and the
196
+ achieved error
197
+
198
+ Inequality rows with a single nonzero are used as variable bounds; the
199
+ other variables get a large artificial box (the polytope must be
200
+ bounded: a vertex on the artificial box raises ``ValueError``). The LPs of the ICHM are fast when the remaining
201
+ constraints have few rows (up to 40); with more rows they are solved by
202
+ HiGHS.
203
+ """
204
+ E, f = np.atleast_2d(np.asarray(proj[0], float)), np.asarray(proj[1], float).reshape(-1)
205
+ A, b = np.atleast_2d(np.asarray(ineq[0], float)), np.asarray(ineq[1], float).reshape(-1)
206
+ n = A.shape[1]
207
+ C = dvec = None
208
+ if eq is not None:
209
+ C = np.atleast_2d(np.asarray(eq[0], float))
210
+ dvec = np.asarray(eq[1], float).reshape(-1)
211
+ lo, hi, A_r, b_r = _split_bounds(A, b)
212
+ if np.any(lo > hi):
213
+ raise ValueError("the polytope is empty")
214
+ k = E.shape[0]
215
+ big = None
216
+ if not (np.all(np.isfinite(lo)) and np.all(np.isfinite(hi))):
217
+ n_rows = A_r.shape[0] + (0 if C is None else C.shape[0])
218
+ if n_rows <= 200:
219
+ # no bounding LPs: an artificial box much larger than the
220
+ # polytope, checked at the end (a vertex on it = unbounded)
221
+ fin = np.concatenate((np.abs(b_r), np.abs(lo[np.isfinite(lo)]),
222
+ np.abs(hi[np.isfinite(hi)]),
223
+ np.abs(dvec) if dvec is not None else []))
224
+ rn = np.linalg.norm(A_r, axis=1) if A_r.shape[0] else np.ones(1)
225
+ big = 1e4 * max(1.0, float(np.max(fin, initial=1.0))) / \
226
+ max(float(np.min(rn[rn > 0], initial=1.0)), 1e-12)
227
+ lo, hi = np.maximum(lo, -big), np.minimum(hi, big)
228
+ else:
229
+ lo, hi = _bound_variables(lo, hi, A_r, b_r, C, dvec)
230
+ size = float(np.max(np.abs(E) @ np.maximum(np.abs(lo), np.abs(hi))))
231
+ if tol is None:
232
+ tol = 1e-7 * max(1.0, size)
233
+ out = iterative_convex_hull_method(
234
+ np.eye(k), E, lo, hi, tol, bias=-f,
235
+ G_in=A_r if A_r.shape[0] else None, h_in=b_r if A_r.shape[0] else None,
236
+ G_eq=C, h_eq=dvec, max_iter=max_iter, return_info=True)
237
+ X, H, d, info = out[0], out[1], out[2], out[-1]
238
+ if big is not None:
239
+ Y = out[4]
240
+ if Y.size and np.max(np.abs(Y)) >= 0.5 * big:
241
+ raise ValueError("the polytope is unbounded")
242
+ vertices = [X[:, i].copy() for i in range(X.shape[1])]
243
+ if return_info:
244
+ info = dict(info, lo=lo, hi=hi, tol=tol)
245
+ return vertices, H, d, info
246
+ return vertices
247
+
248
+
249
+ def convex_hull(X, options="Qt"):
250
+ """Convex hull of the columns of X with Qhull: ``ok, normals, offsets,
251
+ simplices``."""
252
+ return _core.convex_hull(_mat(X), options)
253
+
254
+
255
+ def halfspace_intersection(H, d, c):
256
+ """Vertices of ``{x | H x <= d}`` (dimension >= 2) given a point ``c``
257
+ strictly inside, with Qhull (convex hull of the dual points): ``ok, V,
258
+ faces`` with each vertex once (columns of ``V``) and the triangulated
259
+ faces (edges in 2D) as indices into ``V``. ``ok`` is False if ``c`` is not
260
+ strictly inside or the set is unbounded."""
261
+ H = _mat(H)
262
+ return _core.halfspace_intersection(H, _vec(d, H.shape[0]), _vec(c, H.shape[1]))
Binary file
@@ -0,0 +1,2 @@
1
+ Version: 1.13.2
2
+ Arguments: ['C:\\Users\\runneradmin\\AppData\\Local\\Temp\\cibw-run-r6crm_lj\\cp313-win_amd64\\build\\venv\\Scripts\\delvewheel', 'repair', '-w', 'C:\\Users\\runneradmin\\AppData\\Local\\Temp\\cibw-run-r6crm_lj\\cp313-win_amd64\\repaired_wheel', '-v', 'C:\\Users\\runneradmin\\AppData\\Local\\Temp\\cibw-run-r6crm_lj\\cp313-win_amd64\\built_wheel\\pycapacity_cpp-0.1.0-cp313-cp313-win_amd64.whl']
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.2
2
+ Name: pycapacity-cpp
3
+ Version: 0.1.0
4
+ Summary: Compiled (C++) polytope algorithms for pycapacity: HPSM, VEPOLI2 and ICHM
5
+ Author: Antun Skuric
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/auctus-team/pycapacity
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: numpy
10
+ Description-Content-Type: text/markdown
11
+
12
+ # pycapacity-cpp
13
+
14
+ Compiled (C++) implementations of the polytope algorithms of
15
+ [pycapacity](https://github.com/auctus-team/pycapacity):
16
+
17
+ | algorithm | used for | speed-up over the Python code |
18
+ |---|---|---|
19
+ | `hyper_plane_shift_method` (HPSM) | velocity / acceleration / human force polytopes (H-rep) | 20-170x |
20
+ | `vertex_enumeration_vepoli2` | robot force polytopes (V-rep) | 15-50x |
21
+ | `iterative_convex_hull_method` (ICHM) | human polytopes, any problem of the unified form | 10-90x |
22
+ | `halfspace_intersection` (H -> V in 2D/3D) | `pycapacity.algorithms.hspace_to_vertex` | 2-4x |
23
+
24
+ It also provides `project_polytope(proj, ineq, eq=None, tol=None)`, a
25
+ general polytope projection `{E x + f | A x <= b, C x = d}` in any output
26
+ dimension with the same arguments and result as `pypoman.project_polytope`
27
+ (see below).
28
+
29
+ (Measured with `primer/benchmarks/bench_cpp.py`; the ranges depend on the
30
+ problem size, see the benchmark output.) On whole `pycapacity` calls: Franka
31
+ Panda velocity/acceleration/force polytopes 0.2/0.34/0.034 ms (Python 1.5-2
32
+ ms), 50-muscle human force polytope 1.3 ms at 10 N (Python 39 ms); see
33
+ `docs/source/backend.rst`.
34
+
35
+ When `pycapacity-cpp` is installed, `pycapacity` uses it automatically: the
36
+ functions of `pycapacity.algorithms`, and so every `robot.*` and `human.*`
37
+ polytope function, keep their inputs and outputs and run in C++. To select
38
+ the implementation:
39
+
40
+ ```python
41
+ import pycapacity.algorithms as algos
42
+ algos.get_backend() # 'cpp' or 'python'
43
+ algos.set_backend("python") # or "cpp", "auto" (default)
44
+ ```
45
+
46
+ or set the environment variable `PYCAPACITY_BACKEND=python` before importing.
47
+
48
+ ## Installation
49
+
50
+ ### conda (recommended)
51
+
52
+ From the `pycapacity` folder:
53
+
54
+ ```bash
55
+ conda env create -f cpp/environment.yml
56
+ conda activate pycapacity
57
+ ```
58
+
59
+ This creates an environment with pycapacity, the compiled backend and their
60
+ dependencies (all from conda-forge). In an existing conda environment:
61
+
62
+ ```bash
63
+ conda install -c conda-forge cxx-compiler cmake ninja eigen qhull highs pybind11 scikit-build-core
64
+ pip install ./cpp
65
+ ```
66
+
67
+ ### pip
68
+
69
+ Once released on PyPI, prebuilt wheels (Linux x86_64/aarch64, macOS
70
+ arm64/x86_64, Windows x64, Python 3.10-3.15) need no compiler:
71
+
72
+ ```bash
73
+ pip install pycapacity[fast] # or: pip install pycapacity-cpp
74
+ ```
75
+
76
+ From the sources, a C++17 compiler is needed (CMake comes from pip). Eigen,
77
+ Qhull and HiGHS are downloaded and built during the build if they are not
78
+ found:
79
+
80
+ ```bash
81
+ pip install ./cpp
82
+ ```
83
+
84
+ ### Releasing
85
+
86
+ The wheels are built and tested by `.github/workflows/cpp-wheels.yml`
87
+ (cibuildwheel; every wheel runs `cpp/tests` against the Python
88
+ implementation). Pull requests touching `cpp/` build them; a tag
89
+ `cpp-vX.Y.Z` matching the version in `cpp/pyproject.toml` also publishes
90
+ them to PyPI (trusted publishing, environment `pypi`).
91
+
92
+ ## How the ICHM is made fast
93
+
94
+ Almost all the time of the ICHM goes into the linear programs, one per facet,
95
+ each solved for a new cost on the same constraints
96
+ `y_min <= y <= y_max, E y = e, G y <= g`, with very few rows. A general LP
97
+ solver spends ~150 us per call in setup even for 3 pivots (HiGHS, GLPK), so
98
+ `pycapacity_cpp` uses a small dense bounded-variable primal simplex that keeps
99
+ its basis between calls (the previous optimum stays feasible when only the
100
+ cost changes), flips all wrong-bound variables at once when possible, and
101
+ solves the facets in an order where consecutive normals are close. A typical
102
+ LP then takes 2-20 us. Every solution is checked and HiGHS solves it instead
103
+ if the check fails (`info["n_lp_fallback"]` counts these; it is 0 in all the
104
+ benchmarks and tests). `lp_solver="highs"` forces HiGHS for comparison.
105
+
106
+ ## General projection: `project_polytope`
107
+
108
+ ```python
109
+ import pycapacity_cpp as pc
110
+ vertices = pc.project_polytope((E, f), (A, b), (C, d), tol=1e-6)
111
+ ```
112
+
113
+ Inequality rows with a single nonzero become variable bounds (the box of
114
+ the ICHM); the others are general constraint rows. With up to 200 constraint
115
+ rows the LPs use the dense simplex; beyond that they go to HiGHS. The
116
+ polytope must be bounded (a `ValueError` is raised otherwise). The result is
117
+ an inner approximation within `tol` (default `1e-7` of the size; never
118
+ below `1e-8` of the size, the precision of the LP solutions).
119
+
120
+ ## Tests
121
+
122
+ ```bash
123
+ python -m pytest cpp/tests # C++ against Python, same polytopes
124
+ PYCAPACITY_BACKEND=cpp python -m pytest tests
125
+ ```
126
+
127
+ ## Using the library from C++
128
+
129
+ `include/pycapacity_cpp/polycap.hpp` declares the functions (Eigen inputs and
130
+ outputs); the CMake target `polycap` is a static library.
@@ -0,0 +1,7 @@
1
+ pycapacity_cpp/_core.cp313-win_amd64.pyd,sha256=2uo7iURrk9QbWqX7yLjz8GgUKbv81xu0UuaAVRDrpL0,3698176
2
+ pycapacity_cpp/__init__.py,sha256=n2MTPEptHr5ArP5jqVVUCJ0t3avOwTpffA8UrsHcrS4,11294
3
+ pycapacity_cpp-0.1.0.dist-info/DELVEWHEEL,sha256=iH3Fkey1SKMVpZ2YvHZ7VqEWcvkVM4CaeUWdbbT8WPA,413
4
+ pycapacity_cpp-0.1.0.dist-info/METADATA,sha256=lkMD-MByTZesXWoMjiwNbqMaXc1xCtcG38jk4fXL-E8,4875
5
+ pycapacity_cpp-0.1.0.dist-info/RECORD,,
6
+ pycapacity_cpp-0.1.0.dist-info/WHEEL,sha256=bzccfTXe5NE7eB86OiS4hIwvwnRsRQgKw2c3BU4To6A,105
7
+ pycapacity_cpp.libs/msvcp140-a4c2229bdc2a2a630acdc095b4d86008.dll,sha256=pMIim9wqKmMKzcCVtNhgCOXD47x3cxdDVPPaT1vrnN4,575056
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: scikit-build-core 1.1.2
3
+ Root-Is-Purelib: false
4
+ Tag: cp313-cp313-win_amd64
5
+