exact-max-rectangle 0.2.0__cp39-cp39-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.
Files changed (30) hide show
  1. exact_max_rectangle/__init__.py +351 -0
  2. exact_max_rectangle/_core.cp39-win_amd64.pyd +0 -0
  3. exact_max_rectangle/_core.pyi +74 -0
  4. exact_max_rectangle/licenses/GPL-3.0.txt +674 -0
  5. exact_max_rectangle/licenses/LGPL-3.0.txt +165 -0
  6. exact_max_rectangle/licenses/LICENSE-OpenBLAS.txt +29 -0
  7. exact_max_rectangle/licenses/LICENSE-nanobind.txt +26 -0
  8. exact_max_rectangle/licenses/THIRD_PARTY_LICENSES.md +62 -0
  9. exact_max_rectangle/py.typed +0 -0
  10. exact_max_rectangle-0.2.0.dist-info/DELVEWHEEL +2 -0
  11. exact_max_rectangle-0.2.0.dist-info/METADATA +605 -0
  12. exact_max_rectangle-0.2.0.dist-info/RECORD +30 -0
  13. exact_max_rectangle-0.2.0.dist-info/WHEEL +5 -0
  14. exact_max_rectangle-0.2.0.dist-info/licenses/LICENSE +21 -0
  15. exact_max_rectangle-0.2.0.dist-info/licenses/python/exact_max_rectangle/licenses/GPL-3.0.txt +674 -0
  16. exact_max_rectangle-0.2.0.dist-info/licenses/python/exact_max_rectangle/licenses/LGPL-3.0.txt +165 -0
  17. exact_max_rectangle-0.2.0.dist-info/licenses/python/exact_max_rectangle/licenses/LICENSE-OpenBLAS.txt +29 -0
  18. exact_max_rectangle-0.2.0.dist-info/licenses/python/exact_max_rectangle/licenses/LICENSE-nanobind.txt +26 -0
  19. exact_max_rectangle-0.2.0.dist-info/licenses/python/exact_max_rectangle/licenses/THIRD_PARTY_LICENSES.md +62 -0
  20. exact_max_rectangle.libs/.load-order-exact_max_rectangle-0.2.0 +10 -0
  21. exact_max_rectangle.libs/libflint-24-802444a78e6649f9d434fc5ac919de8a.dll +0 -0
  22. exact_max_rectangle.libs/libgcc_s_seh-1-f2d91a389ed267bf2850f67e4a2ba348.dll +0 -0
  23. exact_max_rectangle.libs/libgfortran-5-5a454baa61df1304f57adc54dbeaa125.dll +0 -0
  24. exact_max_rectangle.libs/libgmp-10-c2567ccf3f410c3411ba7cd4b7ba14f3.dll +0 -0
  25. exact_max_rectangle.libs/libgomp-1-72d501ef2ed5f5806260cc1087ca6858.dll +0 -0
  26. exact_max_rectangle.libs/libmpfr-6-0862477d96e66861bce792441eb49bda.dll +0 -0
  27. exact_max_rectangle.libs/libopenblas-dc97cfbc99e1185046a9257d555f8490.dll +4 -0
  28. exact_max_rectangle.libs/libquadmath-0-702bbb638e333cd4bad0895d7357a825.dll +0 -0
  29. exact_max_rectangle.libs/libstdc++-6-87ee88041bba9266319e5b6133b716e4.dll +0 -0
  30. exact_max_rectangle.libs/libwinpthread-1-cba6809f1130894dc33f7b18e5952adb.dll +0 -0
@@ -0,0 +1,351 @@
1
+ """Exact maximum-area inscribed rectangle in a simple polygon.
2
+
3
+ Wraps the exact C++17 Choi, Lee, and Ahn solver (FLINT qqbar / GMP exact arithmetic).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+
9
+ # start delvewheel patch
10
+ def _delvewheel_patch_1_13_4():
11
+ import ctypes
12
+ import os
13
+ import platform
14
+ import sys
15
+ libs_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'exact_max_rectangle.libs'))
16
+ is_conda_cpython = platform.python_implementation() == 'CPython' and (hasattr(ctypes.pythonapi, 'Anaconda_GetVersion') or 'packaged by conda-forge' in sys.version)
17
+ if sys.version_info[:2] >= (3, 8) and not is_conda_cpython or sys.version_info[:2] >= (3, 10):
18
+ if os.path.isdir(libs_dir):
19
+ os.add_dll_directory(libs_dir)
20
+ else:
21
+ load_order_filepath = os.path.join(libs_dir, '.load-order-exact_max_rectangle-0.2.0')
22
+ if os.path.isfile(load_order_filepath):
23
+ import ctypes.wintypes
24
+ with open(os.path.join(libs_dir, '.load-order-exact_max_rectangle-0.2.0'), encoding='utf-8') as file:
25
+ load_order = file.read().split()
26
+ kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
27
+ kernel32.LoadLibraryExW.restype = ctypes.wintypes.HMODULE
28
+ kernel32.LoadLibraryExW.argtypes = ctypes.wintypes.LPCWSTR, ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD
29
+ for lib in load_order:
30
+ lib_path = os.path.join(os.path.join(libs_dir, lib))
31
+ if os.path.isfile(lib_path) and not kernel32.LoadLibraryExW(lib_path, None, 8):
32
+ raise OSError('Error loading {}; {}'.format(lib, ctypes.FormatError(ctypes.get_last_error())))
33
+
34
+
35
+ _delvewheel_patch_1_13_4()
36
+ del _delvewheel_patch_1_13_4
37
+ # end delvewheel patch
38
+
39
+ from collections.abc import Mapping
40
+ from decimal import Decimal
41
+ from fractions import Fraction
42
+ from importlib import metadata as _metadata
43
+ import math
44
+ import numbers
45
+ import operator
46
+ from typing import Any, Iterable, Sequence, Tuple, Union
47
+
48
+ from . import _core
49
+ from ._core import ExactNumber, ExactRectangle, Rectangle
50
+
51
+ try:
52
+ __version__ = _metadata.version("exact-max-rectangle")
53
+ except _metadata.PackageNotFoundError: # pragma: no cover - uninstalled source tree
54
+ __version__ = "0.0.0+unknown"
55
+
56
+ __all__ = [
57
+ "__version__",
58
+ "ExactNumber",
59
+ "ExactRectangle",
60
+ "Rectangle",
61
+ "largest_rectangle",
62
+ "largest_rectangles",
63
+ "largest_by_type",
64
+ ]
65
+
66
+ Coord = Union[numbers.Integral, numbers.Rational, numbers.Real, Decimal]
67
+ PointLike = Sequence[Coord]
68
+ PolygonInput = Union[Iterable[PointLike], Any]
69
+
70
+
71
+ def _int_to_hex(value: int) -> str:
72
+ """Format an int in base 16 (linear-time, exempt from sys.int_max_str_digits)."""
73
+ return format(value, "x")
74
+
75
+
76
+ class _NonFiniteValue(Exception):
77
+ def __init__(self, value: float) -> None:
78
+ self.value = value
79
+
80
+
81
+ def _exact_integer_ratio(value: object) -> Tuple[int, int] | None:
82
+ """Recover an exact (numerator, denominator) integer pair without rounding to binary64.
83
+
84
+ Supports Integral, Rational, Decimal, and float/Real types that expose ``as_integer_ratio()``.
85
+ Raises ``_NonFiniteValue`` for non-finite values of supported types, and returns ``None``
86
+ for unsupported types (including ``numbers.Real`` types without ``as_integer_ratio()``).
87
+ """
88
+ if isinstance(value, bool):
89
+ return None
90
+ if isinstance(value, numbers.Integral):
91
+ return (operator.index(value), 1)
92
+ if isinstance(value, numbers.Rational):
93
+ num = operator.index(value.numerator)
94
+ den = operator.index(value.denominator)
95
+ if den == 0:
96
+ raise ValueError("rational coordinate denominator must be nonzero")
97
+ return (num, den)
98
+ if isinstance(value, Decimal):
99
+ if value.is_nan():
100
+ raise _NonFiniteValue(math.nan)
101
+ if value.is_infinite():
102
+ raise _NonFiniteValue(math.inf if value > 0 else -math.inf)
103
+ return value.as_integer_ratio()
104
+ if isinstance(value, (float, numbers.Real)):
105
+ as_ratio = getattr(value, "as_integer_ratio", None)
106
+ if not callable(as_ratio):
107
+ return None
108
+ try:
109
+ ratio = as_ratio()
110
+ except ValueError as exc:
111
+ try:
112
+ is_nan = bool(value != value)
113
+ except TypeError:
114
+ is_nan = False
115
+ if is_nan:
116
+ raise _NonFiniteValue(math.nan) from exc
117
+ return None
118
+ except OverflowError as exc:
119
+ try:
120
+ is_pos = bool(value > 0)
121
+ except TypeError:
122
+ is_pos = False
123
+ raise _NonFiniteValue(math.inf if is_pos else -math.inf) from exc
124
+ try:
125
+ raw_num, raw_den = ratio
126
+ if isinstance(raw_num, bool) or isinstance(raw_den, bool):
127
+ return None
128
+ num = operator.index(raw_num)
129
+ den = operator.index(raw_den)
130
+ except (TypeError, ValueError):
131
+ return None
132
+ if den <= 0:
133
+ raise ValueError("as_integer_ratio() denominator must be positive")
134
+ return (num, den)
135
+ return None
136
+
137
+
138
+ def _coerce_operand(other: object) -> ExactNumber | float | None:
139
+ """Coerce a comparison operand to ExactNumber, non-finite float, or None (NotImplemented)."""
140
+ if isinstance(other, ExactNumber):
141
+ return other
142
+ try:
143
+ ratio = _exact_integer_ratio(other)
144
+ except _NonFiniteValue as exc:
145
+ return exc.value
146
+ if ratio is None:
147
+ return None
148
+ return ExactNumber._from_rational(_int_to_hex(ratio[0]), _int_to_hex(ratio[1]))
149
+
150
+
151
+ def _exact_eq(self: ExactNumber, other: object) -> bool:
152
+ rhs = _coerce_operand(other)
153
+ if isinstance(rhs, ExactNumber):
154
+ return ExactNumber._cmp(self, rhs) == 0
155
+ if isinstance(rhs, float):
156
+ return False
157
+ return NotImplemented
158
+
159
+
160
+ def _exact_lt(self: ExactNumber, other: object) -> bool:
161
+ rhs = _coerce_operand(other)
162
+ if isinstance(rhs, ExactNumber):
163
+ return ExactNumber._cmp(self, rhs) < 0
164
+ if isinstance(rhs, float):
165
+ return False if math.isnan(rhs) else rhs > 0
166
+ return NotImplemented
167
+
168
+
169
+ def _exact_le(self: ExactNumber, other: object) -> bool:
170
+ rhs = _coerce_operand(other)
171
+ if isinstance(rhs, ExactNumber):
172
+ return ExactNumber._cmp(self, rhs) <= 0
173
+ if isinstance(rhs, float):
174
+ return False if math.isnan(rhs) else rhs > 0
175
+ return NotImplemented
176
+
177
+
178
+ def _exact_gt(self: ExactNumber, other: object) -> bool:
179
+ rhs = _coerce_operand(other)
180
+ if isinstance(rhs, ExactNumber):
181
+ return ExactNumber._cmp(self, rhs) > 0
182
+ if isinstance(rhs, float):
183
+ return False if math.isnan(rhs) else rhs < 0
184
+ return NotImplemented
185
+
186
+
187
+ def _exact_ge(self: ExactNumber, other: object) -> bool:
188
+ rhs = _coerce_operand(other)
189
+ if isinstance(rhs, ExactNumber):
190
+ return ExactNumber._cmp(self, rhs) >= 0
191
+ if isinstance(rhs, float):
192
+ return False if math.isnan(rhs) else rhs < 0
193
+ return NotImplemented
194
+
195
+
196
+ def _exact_hash(self: ExactNumber) -> int:
197
+ # Rationals share Python's numeric hash contract with int, Fraction, and finite float;
198
+ # irrationals hash canonically by (minimal_polynomial, real_root_index) across solves.
199
+ if self.is_rational:
200
+ return hash(self.as_fraction())
201
+ return hash((self.minimal_polynomial, self._real_root_index()))
202
+
203
+
204
+ # Attach exact rich comparison and consistent hash operators.
205
+ ExactNumber.__eq__ = _exact_eq # type: ignore[method-assign]
206
+ ExactNumber.__lt__ = _exact_lt # type: ignore[method-assign]
207
+ ExactNumber.__le__ = _exact_le # type: ignore[method-assign]
208
+ ExactNumber.__gt__ = _exact_gt # type: ignore[method-assign]
209
+ ExactNumber.__ge__ = _exact_ge # type: ignore[method-assign]
210
+ ExactNumber.__hash__ = _exact_hash # type: ignore[method-assign]
211
+
212
+
213
+ def _rect_export_corners(rectangle: Rectangle) -> tuple[tuple[float, float], ...]:
214
+ corners = rectangle.corners
215
+ if any(not math.isfinite(coord) for corner in corners for coord in corner):
216
+ raise ValueError("rectangle coordinates are not finite in float64. Use r.exact for exact coordinates.")
217
+
218
+ # Test the rounded geometry exactly so that the turn calculation itself cannot
219
+ # overflow, underflow, or lose a small turn between large coordinates.
220
+ points = [(Fraction(x), Fraction(y)) for x, y in corners]
221
+ for i, (bx, by) in enumerate(points):
222
+ ax, ay = points[i - 1]
223
+ cx, cy = points[(i + 1) % len(points)]
224
+ if (bx - ax) * (cy - by) <= (by - ay) * (cx - bx):
225
+ raise ValueError("rectangle corners do not form a valid polygon in float64. Use r.exact for exact coordinates.")
226
+ return corners
227
+
228
+
229
+ def _rect_geo_interface(self: Rectangle) -> dict[str, Any]:
230
+ """Return a closed Polygon mapping in the input coordinate system.
231
+
232
+ Raises ValueError if the float64 corners are non-finite or fail to form a valid polygon.
233
+ """
234
+ ring = _rect_export_corners(self)
235
+ return {"type": "Polygon", "coordinates": ((*ring, ring[0]),)}
236
+
237
+
238
+ def _rect_to_shapely(self: Rectangle) -> Any:
239
+ """Return a ``shapely.Polygon`` of this rectangle's double-precision corners.
240
+
241
+ Requires the optional ``shapely`` package (``pip install exact-max-rectangle[examples]``).
242
+ Shapely stores float64 coordinates. Raises ValueError if those corners are non-finite
243
+ or fail to form a valid polygon. Use ``r.exact`` for exact algebraic coordinates and area.
244
+ """
245
+ try:
246
+ from shapely.geometry import Polygon
247
+ except ImportError as exc:
248
+ raise ImportError(
249
+ "Rectangle.to_shapely() requires shapely; install it with "
250
+ "'pip install shapely' or 'pip install exact-max-rectangle[examples]'"
251
+ ) from exc
252
+ return Polygon(_rect_export_corners(self))
253
+
254
+
255
+ Rectangle.__geo_interface__ = property(_rect_geo_interface) # type: ignore[attr-defined]
256
+ Rectangle.to_shapely = _rect_to_shapely # type: ignore[attr-defined]
257
+
258
+
259
+ def _coord_to_rational_strs(value: object) -> Tuple[str, str]:
260
+ if isinstance(value, bool):
261
+ raise TypeError("polygon coordinates must be real numbers (not bool)")
262
+ try:
263
+ ratio = _exact_integer_ratio(value)
264
+ except _NonFiniteValue as exc:
265
+ raise ValueError(f"polygon coordinate must be finite, got {value!r}") from exc
266
+ if ratio is None:
267
+ raise TypeError(
268
+ f"unsupported coordinate type {type(value).__name__!r}; "
269
+ "expected Integral, Rational, Decimal, or a Real exposing as_integer_ratio()"
270
+ )
271
+ return (_int_to_hex(ratio[0]), _int_to_hex(ratio[1]))
272
+
273
+
274
+ def _extract_geo_interface_ring(geo: Mapping[str, Any]) -> Sequence[PointLike]:
275
+ if geo.get("type") == "Feature":
276
+ geom = geo.get("geometry")
277
+ if not isinstance(geom, Mapping):
278
+ raise ValueError("__geo_interface__ Feature has no Polygon geometry")
279
+ geo = geom
280
+ gtype = geo.get("type")
281
+ if gtype != "Polygon":
282
+ hint = " (for MultiPolygon, iterate over .geoms)" if gtype == "MultiPolygon" else ""
283
+ raise ValueError(f"unsupported __geo_interface__ geometry type {gtype!r}; expected 'Polygon'{hint}")
284
+ coords = geo.get("coordinates")
285
+ if not isinstance(coords, Sequence) or isinstance(coords, (str, bytes)) or len(coords) == 0:
286
+ raise ValueError("__geo_interface__ Polygon must provide a non-empty exterior ring")
287
+ if len(coords) > 1:
288
+ raise ValueError("polygons with holes (interior rings) are not supported (issue #87)")
289
+ exterior = coords[0]
290
+ if not isinstance(exterior, Sequence) or isinstance(exterior, (str, bytes)):
291
+ raise ValueError("__geo_interface__ Polygon exterior ring must be a sequence of (x, y) pairs")
292
+ return exterior
293
+
294
+
295
+ def _convert_polygon(vertices: PolygonInput) -> list[Tuple[Tuple[str, str], Tuple[str, str]]]:
296
+ geo = getattr(vertices, "__geo_interface__", None)
297
+ from_geo = False
298
+ if geo is not None:
299
+ if not isinstance(geo, Mapping):
300
+ raise TypeError("__geo_interface__ must be a mapping")
301
+ vertices = _extract_geo_interface_ring(geo)
302
+ from_geo = True
303
+
304
+ raw: list[Tuple[Tuple[str, str], Tuple[str, str]]] = []
305
+ for pt in vertices:
306
+ try:
307
+ x, y = pt
308
+ except (TypeError, ValueError) as exc:
309
+ raise ValueError("each vertex must be a 2-element (x, y) pair") from exc
310
+ raw.append((_coord_to_rational_strs(x), _coord_to_rational_strs(y)))
311
+ if from_geo and len(raw) >= 2 and raw[0] == raw[-1]:
312
+ raw.pop()
313
+ if len(raw) < 3:
314
+ raise ValueError("polygon must have at least 3 vertices")
315
+ return raw
316
+
317
+
318
+ def largest_rectangle(vertices: PolygonInput, threads: int = 1) -> Rectangle | None:
319
+ """Return the exact largest-area rectangle inscribed in a simple polygon.
320
+
321
+ Parameters
322
+ ----------
323
+ vertices : iterable of (x, y) pairs or ``__geo_interface__`` Polygon
324
+ Simple polygon vertices in boundary order (counterclockwise; clockwise rings are
325
+ accepted and reversed), or any object exposing a GeoJSON Polygon ``__geo_interface__``
326
+ (such as a ``shapely.Polygon`` without holes; closing duplicate vertices are dropped).
327
+ Non-consecutive collinear vertices are accepted; non-simple polygons, polygons with
328
+ holes, zero-area polygons, consecutive collinear (straight-angle) vertices, and
329
+ non-finite coordinates raise ``ValueError``. Coordinates may be ``numbers.Integral``
330
+ (e.g. ``int``, ``numpy.int64``), ``numbers.Rational`` (e.g. ``fractions.Fraction``),
331
+ ``decimal.Decimal``, or ``float`` / ``numbers.Real`` exposing ``as_integer_ratio()``
332
+ (converted exactly; real types whose exact value cannot be recovered raise ``TypeError``).
333
+ threads : int, default 1
334
+ Number of solver threads (``0`` uses all hardware threads).
335
+
336
+ Returns
337
+ -------
338
+ Rectangle or None
339
+ The first globally largest rectangle in canonical order.
340
+ """
341
+ return _core._largest_rectangle(_convert_polygon(vertices), threads)
342
+
343
+
344
+ def largest_rectangles(vertices: PolygonInput, threads: int = 1) -> list[Rectangle]:
345
+ """Return every distinct globally largest rectangle in canonical order (exact ties)."""
346
+ return _core._largest_rectangles(_convert_polygon(vertices), threads)
347
+
348
+
349
+ def largest_by_type(vertices: PolygonInput) -> dict[str, Rectangle]:
350
+ """Return the largest rectangle of each paper type ('A', 'B1', ..., 'F') present in P."""
351
+ return _core._largest_by_type(_convert_polygon(vertices))
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ from fractions import Fraction
4
+ from typing import Any, Optional
5
+
6
+ class ExactNumber:
7
+ @property
8
+ def degree(self) -> int: ...
9
+ @property
10
+ def is_rational(self) -> bool: ...
11
+ @property
12
+ def approx(self) -> float: ...
13
+ @property
14
+ def minimal_polynomial(self) -> tuple[int, ...]: ...
15
+ def as_fraction(self) -> Fraction: ...
16
+ def isolating_interval(self, bits: int = 64) -> tuple[Fraction, Fraction]: ...
17
+ def decimal(self, digits: int = 50) -> str: ...
18
+ def _real_root_index(self) -> int: ...
19
+ def __float__(self) -> float: ...
20
+ def __hash__(self) -> int: ...
21
+ def __eq__(self, other: object) -> bool: ...
22
+ def __lt__(self, other: object) -> bool: ...
23
+ def __le__(self, other: object) -> bool: ...
24
+ def __gt__(self, other: object) -> bool: ...
25
+ def __ge__(self, other: object) -> bool: ...
26
+ @staticmethod
27
+ def _from_rational(num: str, den: str) -> ExactNumber: ...
28
+ @staticmethod
29
+ def _cmp(a: ExactNumber, b: ExactNumber) -> int: ...
30
+
31
+ class ExactRectangle:
32
+ @property
33
+ def area(self) -> ExactNumber: ...
34
+ @property
35
+ def corners(self) -> tuple[
36
+ tuple[ExactNumber, ExactNumber],
37
+ tuple[ExactNumber, ExactNumber],
38
+ tuple[ExactNumber, ExactNumber],
39
+ tuple[ExactNumber, ExactNumber],
40
+ ]: ...
41
+
42
+ class Rectangle:
43
+ @property
44
+ def type(self) -> str: ...
45
+ @property
46
+ def area(self) -> float: ...
47
+ @property
48
+ def corners(self) -> tuple[
49
+ tuple[float, float],
50
+ tuple[float, float],
51
+ tuple[float, float],
52
+ tuple[float, float],
53
+ ]: ...
54
+ @property
55
+ def angle(self) -> float: ...
56
+ @property
57
+ def exact(self) -> ExactRectangle: ...
58
+ @property
59
+ def __geo_interface__(self) -> dict[str, Any]: ...
60
+ def to_shapely(self) -> Any: ...
61
+
62
+ def _largest_rectangle(
63
+ vertices: list[tuple[tuple[str, str], tuple[str, str]]],
64
+ threads: int = 1,
65
+ ) -> Optional[Rectangle]: ...
66
+
67
+ def _largest_rectangles(
68
+ vertices: list[tuple[tuple[str, str], tuple[str, str]]],
69
+ threads: int = 1,
70
+ ) -> list[Rectangle]: ...
71
+
72
+ def _largest_by_type(
73
+ vertices: list[tuple[tuple[str, str], tuple[str, str]]],
74
+ ) -> dict[str, Rectangle]: ...