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