diskpack 0.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.
- diskpack-0.1.0/LICENSE +21 -0
- diskpack-0.1.0/PKG-INFO +222 -0
- diskpack-0.1.0/README.md +212 -0
- diskpack-0.1.0/pyproject.toml +17 -0
- diskpack-0.1.0/setup.cfg +4 -0
- diskpack-0.1.0/src/diskpack/__init__.py +3 -0
- diskpack-0.1.0/src/diskpack/packer.py +208 -0
- diskpack-0.1.0/src/diskpack.egg-info/PKG-INFO +222 -0
- diskpack-0.1.0/src/diskpack.egg-info/SOURCES.txt +11 -0
- diskpack-0.1.0/src/diskpack.egg-info/dependency_links.txt +1 -0
- diskpack-0.1.0/src/diskpack.egg-info/requires.txt +1 -0
- diskpack-0.1.0/src/diskpack.egg-info/top_level.txt +1 -0
- diskpack-0.1.0/tests/tests.py +75 -0
diskpack-0.1.0/LICENSE
ADDED
|
@@ -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.
|
diskpack-0.1.0/PKG-INFO
ADDED
|
@@ -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
|
+

|
|
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
|
diskpack-0.1.0/README.md
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# diskpack
|
|
2
|
+
|
|
3
|
+
A Python library for packing circles within arbitrary polygon boundaries.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install git+https://github.com/semajyllek/diskpack.git
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or clone and install locally:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
git clone https://github.com/semajyllek/diskpack.git
|
|
17
|
+
cd diskpack
|
|
18
|
+
pip install -e .
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import numpy as np
|
|
25
|
+
from diskpack import CirclePacker, PackingConfig
|
|
26
|
+
|
|
27
|
+
# Define a polygon (list of [x, y] vertices)
|
|
28
|
+
square = np.array([
|
|
29
|
+
[0, 0],
|
|
30
|
+
[100, 0],
|
|
31
|
+
[100, 100],
|
|
32
|
+
[0, 100]
|
|
33
|
+
])
|
|
34
|
+
|
|
35
|
+
# Pack circles
|
|
36
|
+
packer = CirclePacker([square])
|
|
37
|
+
circles = packer.pack()
|
|
38
|
+
|
|
39
|
+
# Each circle is (x, y, radius)
|
|
40
|
+
for x, y, r in circles[:5]:
|
|
41
|
+
print(f"Circle at ({x:.1f}, {y:.1f}) with radius {r:.1f}")
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## How It Works
|
|
45
|
+
|
|
46
|
+
The algorithm uses a **greedy random sampling** approach:
|
|
47
|
+
|
|
48
|
+
1. **Sample** random points within the polygon's bounding box
|
|
49
|
+
2. **Filter** to keep only points inside the polygon (using the even-odd rule)
|
|
50
|
+
3. **Compute** the maximum radius at each point without overlapping boundaries or existing circles
|
|
51
|
+
4. **Place** the largest valid circle from each batch
|
|
52
|
+
5. **Repeat** until no more circles can be placed
|
|
53
|
+
|
|
54
|
+
### Key Techniques
|
|
55
|
+
|
|
56
|
+
**Even-Odd Rule for Point-in-Polygon**
|
|
57
|
+
|
|
58
|
+
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.
|
|
59
|
+
|
|
60
|
+
**Spatial Indexing**
|
|
61
|
+
|
|
62
|
+
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).
|
|
63
|
+
|
|
64
|
+
Large circles that span multiple grid cells are stored separately as "mega circles" and always checked—this prevents missed collisions at cell boundaries.
|
|
65
|
+
|
|
66
|
+
**Distance Calculations**
|
|
67
|
+
|
|
68
|
+
The maximum radius at any point is the minimum of:
|
|
69
|
+
- Distance to the nearest polygon edge
|
|
70
|
+
- Distance to the nearest existing circle's boundary
|
|
71
|
+
|
|
72
|
+
We subtract a configurable padding to prevent circles from touching.
|
|
73
|
+
|
|
74
|
+
## Configuration
|
|
75
|
+
|
|
76
|
+
Customize the packing behavior with `PackingConfig`:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from diskpack import PackingConfig
|
|
80
|
+
|
|
81
|
+
config = PackingConfig(
|
|
82
|
+
padding=1.5, # Gap between circles and boundaries
|
|
83
|
+
min_radius=1.0, # Smallest circle to place
|
|
84
|
+
max_failed_attempts=200, # Stop after this many failed attempts
|
|
85
|
+
sample_batch_size=50, # Points sampled per iteration
|
|
86
|
+
grid_resolution_divisor=25, # Controls spatial index cell size
|
|
87
|
+
mega_circle_threshold=0.5, # Radius/cell_size ratio for "mega" circles
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
packer = CirclePacker([polygon], config)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
| Parameter | Default | Description |
|
|
94
|
+
|-----------|---------|-------------|
|
|
95
|
+
| `padding` | 1.5 | Minimum gap between circles and between circles and edges |
|
|
96
|
+
| `min_radius` | 1.0 | Circles smaller than this won't be placed |
|
|
97
|
+
| `max_failed_attempts` | 200 | Algorithm stops after this many consecutive failed placements |
|
|
98
|
+
| `sample_batch_size` | 50 | Number of random points tested per iteration |
|
|
99
|
+
| `grid_resolution_divisor` | 25 | Higher = smaller grid cells = more memory, faster lookups |
|
|
100
|
+
| `mega_circle_threshold` | 0.5 | Circles with radius > cell_size × this value are tracked globally |
|
|
101
|
+
|
|
102
|
+
## Progress Tracking
|
|
103
|
+
|
|
104
|
+
Monitor the packing process with `verbose=True`:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
packer = CirclePacker([polygon], config)
|
|
108
|
+
circles = packer.pack(verbose=True)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Output:
|
|
112
|
+
```
|
|
113
|
+
Placed: 25 | Failed attempts: 0/200 (0%)
|
|
114
|
+
Placed: 50 | Failed attempts: 0/200 (0%)
|
|
115
|
+
Placed: 75 | Failed attempts: 0/200 (0%)
|
|
116
|
+
Placed: 75 | Failed attempts: 50/200 (25%)
|
|
117
|
+
...
|
|
118
|
+
Done! Placed: 82 | Failed attempts: 200/200 (100%)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
You can also check progress after packing:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
print(packer.progress)
|
|
125
|
+
# Placed: 82 | Failed attempts: 200/200 (100%)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Fixed-Radius Mode
|
|
129
|
+
|
|
130
|
+
Pack circles of uniform size:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
circles = packer.pack(fixed_radius=5.0)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Complex Polygons
|
|
137
|
+
|
|
138
|
+
The library handles concave polygons and multiple polygon boundaries:
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
# Star shape
|
|
142
|
+
angles = np.linspace(0, 2 * np.pi, 11)[:-1]
|
|
143
|
+
star = []
|
|
144
|
+
for i, a in enumerate(angles):
|
|
145
|
+
r = 100 if i % 2 == 0 else 40
|
|
146
|
+
star.append([r * np.cos(a), r * np.sin(a)])
|
|
147
|
+
|
|
148
|
+
packer = CirclePacker([np.array(star)])
|
|
149
|
+
circles = packer.pack()
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
# Multiple boundaries (e.g., polygon with a hole)
|
|
154
|
+
outer = np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
|
|
155
|
+
inner = np.array([[40, 40], [60, 40], [60, 60], [40, 60]]) # hole
|
|
156
|
+
|
|
157
|
+
packer = CirclePacker([outer, inner])
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Visualization
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
import matplotlib.pyplot as plt
|
|
164
|
+
|
|
165
|
+
def visualize(polygons, circles):
|
|
166
|
+
fig, ax = plt.subplots(figsize=(10, 10))
|
|
167
|
+
|
|
168
|
+
# Draw polygon boundaries
|
|
169
|
+
for poly in polygons:
|
|
170
|
+
closed = np.vstack([poly, poly[0]])
|
|
171
|
+
ax.plot(closed[:, 0], closed[:, 1], 'k-', linewidth=2)
|
|
172
|
+
|
|
173
|
+
# Draw circles
|
|
174
|
+
for x, y, r in circles:
|
|
175
|
+
ax.add_patch(plt.Circle((x, y), r, fill=True, alpha=0.7))
|
|
176
|
+
|
|
177
|
+
ax.set_aspect('equal')
|
|
178
|
+
ax.autoscale_view()
|
|
179
|
+
plt.show()
|
|
180
|
+
|
|
181
|
+
visualize([square], circles)
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## Generator Mode
|
|
185
|
+
|
|
186
|
+
For large packings or progress tracking, use the generator:
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
packer = CirclePacker([polygon])
|
|
190
|
+
|
|
191
|
+
for i, (x, y, r) in enumerate(packer.generate()):
|
|
192
|
+
print(f"Placed circle {i}: radius {r:.2f}")
|
|
193
|
+
|
|
194
|
+
if i >= 100: # Stop early
|
|
195
|
+
break
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## Performance Tips
|
|
199
|
+
|
|
200
|
+
- **Increase `sample_batch_size`** for denser packings (more candidates per iteration)
|
|
201
|
+
- **Decrease `max_failed_attempts`** if you're okay with slightly less dense results
|
|
202
|
+
- **Increase `grid_resolution_divisor`** for polygons with many small circles
|
|
203
|
+
- **Use `fixed_radius`** when you know the circle size—avoids max-radius computation
|
|
204
|
+
|
|
205
|
+
## Requirements
|
|
206
|
+
|
|
207
|
+
- Python 3.8+
|
|
208
|
+
- NumPy ≥ 1.20
|
|
209
|
+
|
|
210
|
+
## License
|
|
211
|
+
|
|
212
|
+
MIT
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "diskpack"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [{ name="James Kelly", email="mrkellyjam@gmail.com" }]
|
|
9
|
+
description = "A high-performance vectorized circle packer with spatial hashing."
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.8"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"numpy>=1.20",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.packages.find]
|
|
17
|
+
where = ["src"]
|
diskpack-0.1.0/setup.cfg
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,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
|
+

|
|
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,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/diskpack/__init__.py
|
|
5
|
+
src/diskpack/packer.py
|
|
6
|
+
src/diskpack.egg-info/PKG-INFO
|
|
7
|
+
src/diskpack.egg-info/SOURCES.txt
|
|
8
|
+
src/diskpack.egg-info/dependency_links.txt
|
|
9
|
+
src/diskpack.egg-info/requires.txt
|
|
10
|
+
src/diskpack.egg-info/top_level.txt
|
|
11
|
+
tests/tests.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
numpy>=1.20
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
diskpack
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
import numpy as np
|
|
3
|
+
from diskpack.packer import CirclePacker, PackingConfig, PolygonGeometry
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TestCirclePacker(unittest.TestCase):
|
|
8
|
+
def setUp(self):
|
|
9
|
+
"""Set up a simple 10x10 square for testing."""
|
|
10
|
+
self.square_verts = np.array([[0, 0], [10, 0], [10, 10], [0, 10]])
|
|
11
|
+
self.square = [self.square_verts]
|
|
12
|
+
# Use small padding/min_radius to allow for dense filling
|
|
13
|
+
self.config = PackingConfig(padding=0.1, min_radius=0.5, patience_before_stop=100)
|
|
14
|
+
|
|
15
|
+
def _calculate_poly_area(self, segments: list) -> float:
|
|
16
|
+
"""Calculates area of polygons (including holes) using the Shoelace Formula."""
|
|
17
|
+
total_area = 0
|
|
18
|
+
for poly in segments:
|
|
19
|
+
x = poly[:, 0]
|
|
20
|
+
y = poly[:, 1]
|
|
21
|
+
# Area = 0.5 * |sum(x_i * y_{i+1} - x_{i+1} * y_i)|
|
|
22
|
+
area = 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
|
|
23
|
+
# If it's a hole (clockwise), it naturally subtracts if we don't use abs here,
|
|
24
|
+
# but since our parser handles holes via Even-Odd, we treat all as positive
|
|
25
|
+
# and subtract holes manually if needed. For this test, we assume shells.
|
|
26
|
+
total_area += area
|
|
27
|
+
return total_area
|
|
28
|
+
|
|
29
|
+
def test_filling_density(self):
|
|
30
|
+
"""Verify that the packer fills a minimum percentage of the polygon area."""
|
|
31
|
+
packer = CirclePacker(self.square, self.config)
|
|
32
|
+
circles = list(packer.generate())
|
|
33
|
+
|
|
34
|
+
# Calculate areas
|
|
35
|
+
poly_area = self._calculate_poly_area(self.square)
|
|
36
|
+
circle_area = sum(np.pi * (r**2) for _, _, r in circles)
|
|
37
|
+
|
|
38
|
+
fill_percentage = (circle_area / poly_area) * 100
|
|
39
|
+
|
|
40
|
+
print(f"\nFill Analysis: {len(circles)} circles placed.")
|
|
41
|
+
print(f"Total Area: {poly_area:.2f} | Circle Area: {circle_area:.2f}")
|
|
42
|
+
print(f"Packing Density: {fill_percentage:.2f}%")
|
|
43
|
+
|
|
44
|
+
# Assert a minimum density threshold.
|
|
45
|
+
# For a random packer, 30-50% is a reasonable 'success' floor depending on radius.
|
|
46
|
+
self.assertGreater(fill_percentage, 25.0, f"Packing density too low: {fill_percentage:.2f}%")
|
|
47
|
+
|
|
48
|
+
def test_geometry_containment(self):
|
|
49
|
+
"""Verify the Even-Odd rule correctly identifies the interior."""
|
|
50
|
+
geo = PolygonGeometry(self.square)
|
|
51
|
+
test_pts = np.array([
|
|
52
|
+
[5, 5], # Center
|
|
53
|
+
[15, 5], # Far outside
|
|
54
|
+
[-1, -1] # Outside
|
|
55
|
+
])
|
|
56
|
+
results = geo.contains_points(test_pts)
|
|
57
|
+
self.assertTrue(results[0])
|
|
58
|
+
self.assertFalse(results[1])
|
|
59
|
+
self.assertFalse(results[2])
|
|
60
|
+
|
|
61
|
+
def test_no_overlap_integrity(self):
|
|
62
|
+
"""Mathematically verify no circles overlap including padding."""
|
|
63
|
+
packer = CirclePacker(self.square, self.config)
|
|
64
|
+
circles = list(packer.generate())
|
|
65
|
+
|
|
66
|
+
for i, (x1, y1, r1) in enumerate(circles):
|
|
67
|
+
for j, (x2, y2, r2) in enumerate(circles):
|
|
68
|
+
if i == j: continue
|
|
69
|
+
dist = np.sqrt((x1 - x2)**2 + (y1 - y2)**2)
|
|
70
|
+
# Distance must be >= sum of radii + padding
|
|
71
|
+
min_sep = r1 + r2 + self.config.padding
|
|
72
|
+
self.assertGreaterEqual(dist, min_sep - 1e-9)
|
|
73
|
+
|
|
74
|
+
if __name__ == '__main__':
|
|
75
|
+
unittest.main()
|