diskpack 0.1.0__py3-none-any.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.
diskpack/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .packer import CirclePacker, PackingConfig, PackingProgress
2
+
3
+ __all__ = ["CirclePacker", "PackingConfig", "PackingProgress"]
diskpack/packer.py ADDED
@@ -0,0 +1,208 @@
1
+ import numpy as np
2
+ from dataclasses import dataclass, field
3
+ from typing import List, Optional, Iterator, Tuple, Dict
4
+
5
+ # Type aliases
6
+ Polygon = np.ndarray
7
+ Point = np.ndarray
8
+ GridKey = Tuple[int, int]
9
+ Circle = Tuple[float, float, float]
10
+
11
+
12
+ @dataclass
13
+ class PackingConfig:
14
+ """Configuration parameters for the circle packing algorithm."""
15
+ padding: float = 1.5
16
+ min_radius: float = 1.0
17
+ grid_resolution_divisor: float = 25
18
+ max_failed_attempts: int = 200
19
+ mega_circle_threshold: float = 0.5
20
+ ray_cast_epsilon: float = 1e-10
21
+ sample_batch_size: int = 50
22
+
23
+
24
+ @dataclass
25
+ class PackingProgress:
26
+ """Tracks the current state of the packing algorithm."""
27
+ circles_placed: int = 0
28
+ failed_attempts: int = 0
29
+ max_failed_attempts: int = 200
30
+
31
+ @property
32
+ def progress_ratio(self) -> float:
33
+ """How close we are to stopping (0.0 = just started, 1.0 = about to stop)."""
34
+ return self.failed_attempts / self.max_failed_attempts
35
+
36
+ def __str__(self) -> str:
37
+ return f"Placed: {self.circles_placed} | Failed attempts: {self.failed_attempts}/{self.max_failed_attempts} ({self.progress_ratio:.0%})"
38
+
39
+
40
+ class PolygonGeometry:
41
+ """Handles geometric calculations for polygon boundaries."""
42
+
43
+ def __init__(self, polygons: List[Polygon], epsilon: float = 1e-10):
44
+ self.polygons = [np.array(p, dtype=float) for p in polygons]
45
+ self.epsilon = epsilon
46
+ self._compute_bounds()
47
+
48
+ def _compute_bounds(self) -> None:
49
+ all_vertices = np.vstack(self.polygons)
50
+ self.min_coords = np.min(all_vertices, axis=0)
51
+ self.max_coords = np.max(all_vertices, axis=0)
52
+
53
+ def contains_points(self, points: np.ndarray) -> np.ndarray:
54
+ """Even-Odd Rule for interior detection, supports holes."""
55
+ x, y = points[:, 0], points[:, 1]
56
+ inside = np.zeros(len(points), dtype=bool)
57
+
58
+ for poly in self.polygons:
59
+ n = len(poly)
60
+ for i in range(n):
61
+ p1, p2 = poly[i], poly[(i + 1) % n]
62
+ crosses_edge = (p1[1] > y) != (p2[1] > y)
63
+ dy = p2[1] - p1[1] + self.epsilon
64
+ x_intercept = (p2[0] - p1[0]) * (y - p1[1]) / dy + p1[0]
65
+ inside ^= crosses_edge & (x < x_intercept)
66
+
67
+ return inside
68
+
69
+ def distance_to_boundary(self, point: Point) -> float:
70
+ min_distance = float('inf')
71
+ for poly in self.polygons:
72
+ for i in range(len(poly)):
73
+ p1, p2 = poly[i], poly[(i + 1) % len(poly)]
74
+ min_distance = min(min_distance, self._point_to_segment_distance(point, p1, p2))
75
+ return min_distance
76
+
77
+ @staticmethod
78
+ def _point_to_segment_distance(point: Point, seg_start: Point, seg_end: Point) -> float:
79
+ segment_vec = seg_end - seg_start
80
+ segment_length_sq = np.sum(segment_vec ** 2)
81
+ if segment_length_sq == 0:
82
+ return np.linalg.norm(point - seg_start)
83
+ t = np.clip(np.dot(point - seg_start, segment_vec) / segment_length_sq, 0, 1)
84
+ projection = seg_start + t * segment_vec
85
+ return np.linalg.norm(point - projection)
86
+
87
+
88
+ @dataclass
89
+ class SpatialIndex:
90
+ """Grid-based spatial index for efficient collision detection."""
91
+ cell_size: float
92
+ origin: np.ndarray
93
+ mega_threshold: float
94
+ grid: Dict[GridKey, List[int]] = field(default_factory=dict)
95
+ mega_circles: List[int] = field(default_factory=list)
96
+
97
+ def add_circle(self, index: int, center: Point, radius: float) -> None:
98
+ if radius > self.cell_size * self.mega_threshold:
99
+ self.mega_circles.append(index)
100
+ else:
101
+ key = self._get_cell_key(center)
102
+ self.grid.setdefault(key, []).append(index)
103
+
104
+ def get_nearby_indices(self, point: Point) -> Iterator[int]:
105
+ yield from self.mega_circles
106
+ center_key = self._get_cell_key(point)
107
+ for dx in range(-1, 2):
108
+ for dy in range(-1, 2):
109
+ neighbor_key = (center_key[0] + dx, center_key[1] + dy)
110
+ if neighbor_key in self.grid:
111
+ yield from self.grid[neighbor_key]
112
+
113
+ def _get_cell_key(self, point: Point) -> GridKey:
114
+ cell_coords = ((point - self.origin) // self.cell_size).astype(int)
115
+ return (int(cell_coords[0]), int(cell_coords[1]))
116
+
117
+
118
+ class CirclePacker:
119
+ """Packs circles within polygon boundaries using random sampling."""
120
+
121
+ def __init__(self, polygons: List[Polygon], config: Optional[PackingConfig] = None):
122
+ self.config = config or PackingConfig()
123
+ self.geometry = PolygonGeometry(polygons, self.config.ray_cast_epsilon)
124
+ self.centers: List[Point] = []
125
+ self.radii: List[float] = []
126
+ self.progress = PackingProgress(max_failed_attempts=self.config.max_failed_attempts)
127
+
128
+ extent = max(self.geometry.max_coords - self.geometry.min_coords)
129
+ cell_size = extent / self.config.grid_resolution_divisor
130
+ self.spatial_index = SpatialIndex(
131
+ cell_size=cell_size,
132
+ origin=self.geometry.min_coords,
133
+ mega_threshold=self.config.mega_circle_threshold
134
+ )
135
+
136
+ def _sample_candidate_points(self, count: int) -> np.ndarray:
137
+ points = np.random.uniform(
138
+ self.geometry.min_coords,
139
+ self.geometry.max_coords,
140
+ size=(count, 2)
141
+ )
142
+ return points[self.geometry.contains_points(points)]
143
+
144
+ def _compute_max_radius(self, point: Point) -> float:
145
+ max_radius = self.geometry.distance_to_boundary(point)
146
+ for idx in self.spatial_index.get_nearby_indices(point):
147
+ distance_to_circle = np.linalg.norm(self.centers[idx] - point) - self.radii[idx]
148
+ max_radius = min(max_radius, distance_to_circle)
149
+ return max_radius - self.config.padding
150
+
151
+ def _find_best_placement(self, candidates: np.ndarray, fixed_radius: Optional[float]) -> Optional[Tuple[Point, float]]:
152
+ best_point, best_radius = None, 0
153
+ for point in candidates:
154
+ radius = self._compute_max_radius(point)
155
+ if fixed_radius is not None:
156
+ radius = fixed_radius if radius >= fixed_radius else -1
157
+ if radius > best_radius:
158
+ best_point, best_radius = point, radius
159
+
160
+ if best_point is not None and best_radius >= self.config.min_radius:
161
+ return best_point, best_radius
162
+ return None
163
+
164
+ def _place_circle(self, center: Point, radius: float) -> None:
165
+ idx = len(self.centers)
166
+ self.centers.append(center)
167
+ self.radii.append(radius)
168
+ self.spatial_index.add_circle(idx, center, radius)
169
+
170
+ def generate(self, fixed_radius: Optional[float] = None, verbose: bool = False) -> Iterator[Circle]:
171
+ """
172
+ Generate circles until no more can be placed.
173
+
174
+ Args:
175
+ fixed_radius: If provided, all circles will have this exact radius.
176
+ verbose: If True, print progress updates periodically.
177
+
178
+ Yields:
179
+ Tuples of (x, y, radius) for each placed circle.
180
+ """
181
+ self.progress = PackingProgress(max_failed_attempts=self.config.max_failed_attempts)
182
+
183
+ while self.progress.failed_attempts < self.config.max_failed_attempts:
184
+ candidates = self._sample_candidate_points(self.config.sample_batch_size)
185
+ result = self._find_best_placement(candidates, fixed_radius)
186
+
187
+ if result is not None:
188
+ center, radius = result
189
+ self._place_circle(center, radius)
190
+ self.progress.circles_placed += 1
191
+ self.progress.failed_attempts = 0
192
+
193
+ if verbose and self.progress.circles_placed % 25 == 0:
194
+ print(self.progress)
195
+
196
+ yield (float(center[0]), float(center[1]), float(radius))
197
+ else:
198
+ self.progress.failed_attempts += 1
199
+
200
+ if verbose and self.progress.failed_attempts % 50 == 0:
201
+ print(self.progress)
202
+
203
+ if verbose:
204
+ print(f"Done! {self.progress}")
205
+
206
+ def pack(self, fixed_radius: Optional[float] = None, verbose: bool = False) -> List[Circle]:
207
+ """Pack circles and return them as a list."""
208
+ return list(self.generate(fixed_radius, verbose=verbose))
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 James Kelly
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,222 @@
1
+ Metadata-Version: 2.1
2
+ Name: diskpack
3
+ Version: 0.1.0
4
+ Summary: A high-performance vectorized circle packer with spatial hashing.
5
+ Author-email: James Kelly <mrkellyjam@gmail.com>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy >=1.20
10
+
11
+ # diskpack
12
+
13
+ A Python library for packing circles within arbitrary polygon boundaries.
14
+
15
+ ![Circle packing example](https://via.placeholder.com/600x400?text=Circle+Packing+Example)
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install git+https://github.com/semajyllek/diskpack.git
21
+ ```
22
+
23
+ Or clone and install locally:
24
+
25
+ ```bash
26
+ git clone https://github.com/semajyllek/diskpack.git
27
+ cd diskpack
28
+ pip install -e .
29
+ ```
30
+
31
+ ## Quick Start
32
+
33
+ ```python
34
+ import numpy as np
35
+ from diskpack import CirclePacker, PackingConfig
36
+
37
+ # Define a polygon (list of [x, y] vertices)
38
+ square = np.array([
39
+ [0, 0],
40
+ [100, 0],
41
+ [100, 100],
42
+ [0, 100]
43
+ ])
44
+
45
+ # Pack circles
46
+ packer = CirclePacker([square])
47
+ circles = packer.pack()
48
+
49
+ # Each circle is (x, y, radius)
50
+ for x, y, r in circles[:5]:
51
+ print(f"Circle at ({x:.1f}, {y:.1f}) with radius {r:.1f}")
52
+ ```
53
+
54
+ ## How It Works
55
+
56
+ The algorithm uses a **greedy random sampling** approach:
57
+
58
+ 1. **Sample** random points within the polygon's bounding box
59
+ 2. **Filter** to keep only points inside the polygon (using the even-odd rule)
60
+ 3. **Compute** the maximum radius at each point without overlapping boundaries or existing circles
61
+ 4. **Place** the largest valid circle from each batch
62
+ 5. **Repeat** until no more circles can be placed
63
+
64
+ ### Key Techniques
65
+
66
+ **Even-Odd Rule for Point-in-Polygon**
67
+
68
+ To determine if a point is inside a polygon (including polygons with holes), we cast a ray from the point and count edge crossings. An odd count means inside, even means outside.
69
+
70
+ **Spatial Indexing**
71
+
72
+ Checking every existing circle for collisions is O(n) per placement. We use a grid-based spatial index to only check nearby circles, bringing average-case down to O(1).
73
+
74
+ Large circles that span multiple grid cells are stored separately as "mega circles" and always checked—this prevents missed collisions at cell boundaries.
75
+
76
+ **Distance Calculations**
77
+
78
+ The maximum radius at any point is the minimum of:
79
+ - Distance to the nearest polygon edge
80
+ - Distance to the nearest existing circle's boundary
81
+
82
+ We subtract a configurable padding to prevent circles from touching.
83
+
84
+ ## Configuration
85
+
86
+ Customize the packing behavior with `PackingConfig`:
87
+
88
+ ```python
89
+ from diskpack import PackingConfig
90
+
91
+ config = PackingConfig(
92
+ padding=1.5, # Gap between circles and boundaries
93
+ min_radius=1.0, # Smallest circle to place
94
+ max_failed_attempts=200, # Stop after this many failed attempts
95
+ sample_batch_size=50, # Points sampled per iteration
96
+ grid_resolution_divisor=25, # Controls spatial index cell size
97
+ mega_circle_threshold=0.5, # Radius/cell_size ratio for "mega" circles
98
+ )
99
+
100
+ packer = CirclePacker([polygon], config)
101
+ ```
102
+
103
+ | Parameter | Default | Description |
104
+ |-----------|---------|-------------|
105
+ | `padding` | 1.5 | Minimum gap between circles and between circles and edges |
106
+ | `min_radius` | 1.0 | Circles smaller than this won't be placed |
107
+ | `max_failed_attempts` | 200 | Algorithm stops after this many consecutive failed placements |
108
+ | `sample_batch_size` | 50 | Number of random points tested per iteration |
109
+ | `grid_resolution_divisor` | 25 | Higher = smaller grid cells = more memory, faster lookups |
110
+ | `mega_circle_threshold` | 0.5 | Circles with radius > cell_size × this value are tracked globally |
111
+
112
+ ## Progress Tracking
113
+
114
+ Monitor the packing process with `verbose=True`:
115
+
116
+ ```python
117
+ packer = CirclePacker([polygon], config)
118
+ circles = packer.pack(verbose=True)
119
+ ```
120
+
121
+ Output:
122
+ ```
123
+ Placed: 25 | Failed attempts: 0/200 (0%)
124
+ Placed: 50 | Failed attempts: 0/200 (0%)
125
+ Placed: 75 | Failed attempts: 0/200 (0%)
126
+ Placed: 75 | Failed attempts: 50/200 (25%)
127
+ ...
128
+ Done! Placed: 82 | Failed attempts: 200/200 (100%)
129
+ ```
130
+
131
+ You can also check progress after packing:
132
+
133
+ ```python
134
+ print(packer.progress)
135
+ # Placed: 82 | Failed attempts: 200/200 (100%)
136
+ ```
137
+
138
+ ## Fixed-Radius Mode
139
+
140
+ Pack circles of uniform size:
141
+
142
+ ```python
143
+ circles = packer.pack(fixed_radius=5.0)
144
+ ```
145
+
146
+ ## Complex Polygons
147
+
148
+ The library handles concave polygons and multiple polygon boundaries:
149
+
150
+ ```python
151
+ # Star shape
152
+ angles = np.linspace(0, 2 * np.pi, 11)[:-1]
153
+ star = []
154
+ for i, a in enumerate(angles):
155
+ r = 100 if i % 2 == 0 else 40
156
+ star.append([r * np.cos(a), r * np.sin(a)])
157
+
158
+ packer = CirclePacker([np.array(star)])
159
+ circles = packer.pack()
160
+ ```
161
+
162
+ ```python
163
+ # Multiple boundaries (e.g., polygon with a hole)
164
+ outer = np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
165
+ inner = np.array([[40, 40], [60, 40], [60, 60], [40, 60]]) # hole
166
+
167
+ packer = CirclePacker([outer, inner])
168
+ ```
169
+
170
+ ## Visualization
171
+
172
+ ```python
173
+ import matplotlib.pyplot as plt
174
+
175
+ def visualize(polygons, circles):
176
+ fig, ax = plt.subplots(figsize=(10, 10))
177
+
178
+ # Draw polygon boundaries
179
+ for poly in polygons:
180
+ closed = np.vstack([poly, poly[0]])
181
+ ax.plot(closed[:, 0], closed[:, 1], 'k-', linewidth=2)
182
+
183
+ # Draw circles
184
+ for x, y, r in circles:
185
+ ax.add_patch(plt.Circle((x, y), r, fill=True, alpha=0.7))
186
+
187
+ ax.set_aspect('equal')
188
+ ax.autoscale_view()
189
+ plt.show()
190
+
191
+ visualize([square], circles)
192
+ ```
193
+
194
+ ## Generator Mode
195
+
196
+ For large packings or progress tracking, use the generator:
197
+
198
+ ```python
199
+ packer = CirclePacker([polygon])
200
+
201
+ for i, (x, y, r) in enumerate(packer.generate()):
202
+ print(f"Placed circle {i}: radius {r:.2f}")
203
+
204
+ if i >= 100: # Stop early
205
+ break
206
+ ```
207
+
208
+ ## Performance Tips
209
+
210
+ - **Increase `sample_batch_size`** for denser packings (more candidates per iteration)
211
+ - **Decrease `max_failed_attempts`** if you're okay with slightly less dense results
212
+ - **Increase `grid_resolution_divisor`** for polygons with many small circles
213
+ - **Use `fixed_radius`** when you know the circle size—avoids max-radius computation
214
+
215
+ ## Requirements
216
+
217
+ - Python 3.8+
218
+ - NumPy ≥ 1.20
219
+
220
+ ## License
221
+
222
+ MIT
@@ -0,0 +1,7 @@
1
+ diskpack/__init__.py,sha256=pIshCneWsJKLJfOjqgglhJKz5gHLSr_T4gC-Lukuae4,129
2
+ diskpack/packer.py,sha256=g4S8tKWiz_-SxGrQEodF286h66ph5lF1iEBa7ttJ7rQ,8313
3
+ diskpack-0.1.0.dist-info/LICENSE,sha256=LmBHYUBGMVV_Anw_LzP7XEbEBPux_wmdAcjhPr7hd8U,1068
4
+ diskpack-0.1.0.dist-info/METADATA,sha256=P1D9ErQNpK9WGZJD1zF6Bp74DknBt1K7w_laX-X5Nac,6011
5
+ diskpack-0.1.0.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
6
+ diskpack-0.1.0.dist-info/top_level.txt,sha256=We_sJIqEIiaQdtmCNrU-ohWkdbJSNaArss9AD2wbOiI,9
7
+ diskpack-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ diskpack