Great! This is a classic differentiable optimization problem, and your max_nonoverlapping_radius function is perfect for it. Here’s a step-by-step plan and code to maximize the radius for packing N circles inside a unit circle using a neural net (or, more simply, a set of learnable parameters):
Approach
-
Parameterize the circle centers:
Use a neural net or, more simply, a set of learnable parameters for the 2D coordinates of the centers.
To ensure the centers stay inside the unit circle, parameterize them in polar coordinates (r, theta) with r constrained to [0, 1].
-
Optimization:
Use gradient ascent (or minimize the negative radius) to maximize the output of max_nonoverlapping_radius.
-
Implementation:
- Use PyTorch's autograd and optimizer.
- For N=15, optimize the 15 centers.
Implementation
import torch
import torch.nn as nn
import torch.optim as optim
import math
# Assume max_nonoverlapping_radius is already defined and imported
N = 15
device = 'cuda' if torch.cuda.is_available() else 'cpu'
class CirclePackingNet(nn.Module):
def __init__(self, N):
super().__init__()
# Parameterize in polar coordinates for easy constraint
# r: [0, 1], theta: [0, 2pi]
self.r = nn.Parameter(torch.rand(N, 1) * 0.8) # start inside unit circle
self.theta = nn.Parameter(torch.rand(N, 1) * 2 * math.pi)
def forward(self):
# Map r to [0, 1] using sigmoid
r = torch.sigmoid(self.r)
theta = self.theta
x = r * torch.cos(theta)
y = r * torch.sin(theta)
coords = torch.cat([x, y], dim=1)
return coords
# Instantiate model
model = CirclePackingNet(N).to(device)
optimizer = optim.Adam(model.parameters(), lr=0.05)
# Optimization loop
num_steps = 2000
best_radius = 0
best_coords = None
for step in range(num_steps):
optimizer.zero_grad()
coords = model()
radius = max_nonoverlapping_radius(coords, alpha=100.0)
loss = -radius # maximize radius
loss.backward()
optimizer.step()
# Track best
if radius.item() > best_radius:
best_radius = radius.item()
best_coords = coords.detach().cpu().numpy()
if step % 100 == 0 or step == num_steps - 1:
print(f"Step {step}: max radius = {radius.item():.4f}")
print(f"Best max radius found: {best_radius:.4f}")
# best_coords now contains the best found centers
Notes
- Parameterization:
Using polar coordinates and sigmoid ensures all centers stay inside the unit circle.
- Neural Net:
Here, the "neural net" is just a set of learnable parameters, but you could use a more complex net if you want to learn a mapping from some latent space.
- Visualization:
You can plot best_coords and the circles for visualization.
Let me know if you want a visualization snippet or want to try with a different N!