Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/__pycache__/main.cpython-313.pycAdded
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/edit.diffAdded+510
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/llm_trajectories/shinka__native-gemini-3-pro-preview-g155-n1-r1-p1-1772468668.526-0c525125.jsonAdded
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/main.pyAdded+465
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/original.pyAdded+424
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/results/auxiliary_metrics_snapshot.pyAdded+163
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/results/correct.jsonAdded+4
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/results/metrics.jsonAdded+52
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/rewrite.txtAdded+456
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_0/main.pyAdded+94
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_1/edit.diffAdded+280
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_1/main.pyAdded+210
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_1/original.pyAdded+94
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_1/rewrite.txtAdded+201
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/__pycache__/main.cpython-313.pycAdded
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/edit.diffAdded+424
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/llm_trajectories/shinka__native-gemini-3-pro-preview-g10-n1-r1-p1-1772442494.013-168057e8.jsonAdded+69
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/main.pyAdded+323
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/original.pyAdded+305
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/results/auxiliary_metrics_snapshot.pyAdded+73
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/results/correct.jsonAdded+4
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/results/metrics.jsonAdded+40
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/rewrite.txtAdded+314
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_100/edit.diffAdded+473
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_100/main.pyAdded+440
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_100/original.pyAdded+398
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_100/rewrite.txtAdded+431
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_101/edit.diffAdded+572
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_101/main.pyAdded+380
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_101/original.pyAdded+469
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_101/search_replace.txtAdded+812
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/__pycache__/main.cpython-313.pycAdded
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/edit.diffAdded+738
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/llm_trajectories/shinka__native-gemini-3-pro-preview-g102-n1-r1-p1-1772458212.719-d820934f.jsonAdded
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/main.pyAdded+390
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/original.pyAdded+469
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/results/auxiliary_metrics_snapshot.pyAdded+182
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/results/correct.jsonAdded+4
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/results/metrics.jsonAdded+52
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/rewrite.txtAdded+381
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_103/edit.diffAdded+365
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_103/main.pyAdded+292
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_103/original.pyAdded+94
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_103/rewrite.txtAdded+283
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/edit.diffAdded+451
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/llm_trajectories/shinka__native-gemini-3-pro-preview-g104-n1-r1-p1-1772458635.700-5d5a0a79.jsonAdded
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/main.pyAdded+434
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/original.pyAdded+407
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/results/auxiliary_metrics_snapshot.pyAdded+182
- tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/search_replace.txtAdded+100
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510--- a/original.py+++ b/original.py@@ -1,424 +1,465 @@ # EVOLVE-BLOCK-START import numpy as np from scipy.optimize import minimize, linprog from scipy.spatial import Voronoi -class VoronoiPopHybrid:+class VoronoiPopHybridSupreme: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42) def get_initial_configs(self): """Generates diverse initial configurations.""" configs = [] # 1. Explicit Lattice Patterns (Rows)- # Targeted topologies for N=26 patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded- [3, 4, 5, 6, 5, 3] # Rounded small corners+ [3, 4, 5, 6, 5, 3] # Hex-like rounded ] dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers) # Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c scale = 0.85 / np.max(span) if np.max(span) > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it shift = 0.5 - np.mean(centers, axis=0) centers += shift # Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(centers) # 2. Spiral Packing indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) scale = 0.44 c_spiral[:, 0] = 0.5 + scale * r * np.cos(theta) c_spiral[:, 1] = 0.5 + scale * r * np.sin(theta) configs.append(c_spiral) - # 3. Boundary + Random Internal+ # 3. Generic Hex (Imported from Fused)+ configs.append(self.generate_generic_hex())++ # 4. Boundary + Random Internal boundary = [] n_side = 6 x = np.linspace(0.1, 0.9, n_side) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) combined = np.vstack([boundary, internal]) configs.append(combined) elif needed < 0: configs.append(boundary[:self.n]) else: configs.append(boundary) - # 4. Pure Random Relaxed+ # 5. Pure Random Relaxed rand_pts = 0.1 + 0.8 * self.rng.rand(self.n, 2) configs.append(rand_pts) return configs++ def generate_generic_hex(self):+ """Generates a generic hexagonal lattice patch."""+ v1 = np.array([1.0, 0.0])+ v2 = np.array([0.5, np.sqrt(3)/2])+ points = []+ for i in range(-5, 6):+ for j in range(-5, 6):+ points.append(i * v1 + j * v2)+ points = np.array(points)+ points -= np.mean(points, axis=0)+ dists = np.sum(points**2, axis=1)+ points = points[np.argsort(dists)[:self.n]]+ + min_xy = np.min(points, axis=0)+ max_xy = np.max(points, axis=0)+ scale = 0.8 / np.max(max_xy - min_xy)+ return (points - min_xy) * scale + 0.1 def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c = -np.ones(n) # Maximize sum(r) # Wall bounds bounds_list = [] for i in range(n): x, y = centers[i] # Ensure strictly inside 0..1 b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b))) # Pairwise constraints # r_i + r_j <= dist_ij diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq) A_ub = [] b_ub = [] for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j]) # Try Highs solver first (faster/robust) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass # Fallback to interior-point res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x # Last resort: just wall bounds return np.array([b[1] for b in bounds_list]) def find_largest_void(self, centers): """Finds the largest void using Voronoi diagram with boundary reflection.""" # Reflect points across walls to create 'ghost' neighbors for correct boundary cells points_aug = [centers] # Reflect across x=0, x=1, y=0, y=1 points_aug.append(np.column_stack([-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([2-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], -centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], 2-centers[:,1]])) all_pts = np.vstack(points_aug) candidates = [] try: vor = Voronoi(all_pts) for v in vor.vertices: if 0 <= v[0] <= 1 and 0 <= v[1] <= 1: candidates.append(v) except: pass if not candidates:- return np.array([0.5, 0.5])+ return np.array([0.5, 0.5]), 0.01 cand = np.array(candidates) # Distance to centers diff = cand[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c = np.min(np.sqrt(np.sum(diff**2, axis=2)), axis=1) # Distance to walls d_w = np.min(np.column_stack([cand[:,0], 1-cand[:,0], cand[:,1], 1-cand[:,1]]), axis=1) # Maximize min clearance clearance = np.minimum(d_c, d_w) best_idx = np.argmax(clearance)- return cand[best_idx]+ return cand[best_idx], clearance[best_idx] def run_physics_relaxation(self, centers, steps=60): """ Momentum-based relaxation with dynamic radii (fluffing).+ Adapted from Fused implementation. """ c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005-+ for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq)-+ r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists-+ forces = np.zeros_like(c)-+ mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis]- f_mag = overlaps * 40.0+ f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push-+ k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall-- velocities = velocities * 0.5 + forces * dt+ + velocities = velocities * 0.4 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0)-+ pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures-+ dr = np.where(total_p > 1e-4, -total_p * 0.5, 0.002) r += dr * dt- r = np.maximum(r, 0.01)-+ r = np.maximum(r, 0.01) + return c, r def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:] # Objective: Maximize sum(r) obj = -np.sum(r) if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2) # Penalties # 1. Wall Penetration w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2) # 2. Pairwise Overlap diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq) r_matrix = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_matrix - dists)[mask]**2) return obj + mu * (w_pen + ov_pen) def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)+ start_phase = 0+ else:+ # Warm start+ start_phase = 1 x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n current_x = x0 # Phases- phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0]+ all_phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0]+ phases = all_phases[start_phase:] phases = [p * stiffness_scale for p in phases] reg = 5.0 if equal_bias else 0.0 for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0-+ + # Reduce iters for very stiff phases iter_limit = 250 if mu > 5000 else 180 res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x return current_x[:2*n].reshape((n, 2)), current_x[2*n:] def optimize(self): configs = self.get_initial_configs() best_global_res = (None, None, -1.0) # 1. Seed Screening for c in configs: # Phase 1: Equalize radii to find structure c_opt, r_soft = self.local_optimization(c, equal_bias=True) # Phase 2: Relax sizes c_opt, _ = self.local_optimization(c_opt, radii_init=r_soft, equal_bias=False) r_lp = self.solve_lp_radii(c_opt) score = np.sum(r_lp) if score > best_global_res[2]: best_global_res = (c_opt, r_lp, score) # 2. Basin Hopping with Hybrid Moves curr_c = best_global_res[0] curr_r = best_global_res[1] curr_score = best_global_res[2] best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score n_iter = 40 temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() - # Decision: Pop vs Relaxed Jitter- is_pop = (self.rng.rand() < 0.4) # 40% chance to pop+ # Decision: Pop vs Weighted Jitter+ # 45% Pop, 55% Jitter+ is_pop = (self.rng.rand() < 0.45) if is_pop:- # Pop heuristic: Move smallest circle to largest void- min_r_idx = np.argmin(curr_r)+ # Stochastic Pop: Select from the bottom 5 smallest circles+ # This helps remove bottlenecks+ sorted_indices = np.argsort(curr_r)+ candidates = sorted_indices[:5]+ min_r_idx = self.rng.choice(candidates)+ other_indices = [idx for idx in range(self.n) if idx != min_r_idx] others = curr_c[other_indices] - target_pos = self.find_largest_void(others)+ # Move to largest void+ target_pos, target_rad = self.find_largest_void(others) trial_c[min_r_idx] = target_pos- # Small jitter to break symmetries- trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5)+ # Reduced Jitter+ trial_c += 0.003 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init = curr_r.copy()- trial_r_init[min_r_idx] = 0.05+ # Initialize with void radius estimate (conservative)+ trial_r_init[min_r_idx] = max(0.01, target_rad * 0.9) else:- # Relaxed Jitter: Noise + Physics Smoothing- mag = 0.03 * np.exp(-i/(n_iter*0.8))- perturb = mag * self.rng.randn(self.n, 2)+ # Weighted Physics Jitter+ # Weight perturbation by inverse radius (move small circles more)+ weights = 1.0 / (curr_r + 1e-6)+ weights /= np.mean(weights)+ weights = np.clip(weights, 0.5, 3.5)++ mag = 0.035 * np.exp(-i/(n_iter*0.8))+ perturb = mag * self.rng.randn(self.n, 2) * weights[:, np.newaxis]+ trial_c = np.clip(trial_c + perturb, 0.0, 1.0) - # Apply physics relaxation to resolve severe overlaps cheaply- trial_c, r_hint = self.run_physics_relaxation(trial_c, steps=60)-- trial_r_init = r_hint * 0.95 # Slightly shrink to allow rearrangement+ # Apply physics relaxation (Fluffing)+ # This finds a nearby jammed state for the perturbed config+ trial_c, r_hint = self.run_physics_relaxation(trial_c, steps=50)++ trial_r_init = r_hint * 0.95 # Run Local Optimization (High Stiffness)- c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.8)+ c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0) # Exact Evaluation via LP r_lp_new = self.solve_lp_radii(c_new) score_new = np.sum(r_lp_new) # Metropolis Acceptance delta = score_new - curr_score accept = False if delta > 0: accept = True elif self.rng.rand() < np.exp(delta / temperature): accept = True if accept: curr_c = c_new curr_r = r_lp_new curr_score = score_new if score_new > best_score: best_score = score_new best_c = c_new.copy() best_r = r_lp_new.copy()- temperature *= 0.95 # Cool down+ temperature *= 0.92 # 3. Final High-Precision Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n res = minimize( self._loss, x0,- args=(self.n, 100000.0, 0.0), # High penalty+ args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds,- options={'maxiter': 800, 'ftol': 1e-10}+ options={'maxiter': 1000, 'ftol': 1e-10} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c) return final_c, final_r def construct_packing():- opt = VoronoiPopHybrid(n=26)+ opt = VoronoiPopHybridSupreme(n=26) return opt.optimize() def compute_max_radii(centers):- opt = VoronoiPopHybrid(n=len(centers))+ opt = VoronoiPopHybridSupreme(n=len(centers)) return opt.solve_lp_radii(centers) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii # EVOLVE-BLOCK-END # This part remains fixed (not evolved) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465# EVOLVE-BLOCK-STARTimport numpy as npfrom scipy.optimize import minimize, linprogfrom scipy.spatial import Voronoi
class VoronoiPopHybridSupreme: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
def get_initial_configs(self): """Generates diverse initial configurations.""" configs = []
# 1. Explicit Lattice Patterns (Rows) patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Hex-like rounded ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
# Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c scale = 0.85 / np.max(span) if np.max(span) > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it shift = 0.5 - np.mean(centers, axis=0) centers += shift
# Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(centers)
# 2. Spiral Packing indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) scale = 0.44 c_spiral[:, 0] = 0.5 + scale * r * np.cos(theta) c_spiral[:, 1] = 0.5 + scale * r * np.sin(theta) configs.append(c_spiral)
# 3. Generic Hex (Imported from Fused) configs.append(self.generate_generic_hex())
# 4. Boundary + Random Internal boundary = [] n_side = 6 x = np.linspace(0.1, 0.9, n_side) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) combined = np.vstack([boundary, internal]) configs.append(combined) elif needed < 0: configs.append(boundary[:self.n]) else: configs.append(boundary)
# 5. Pure Random Relaxed rand_pts = 0.1 + 0.8 * self.rng.rand(self.n, 2) configs.append(rand_pts)
return configs
def generate_generic_hex(self): """Generates a generic hexagonal lattice patch.""" v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-5, 6): for j in range(-5, 6): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]] min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c = -np.ones(n) # Maximize sum(r)
# Wall bounds bounds_list = [] for i in range(n): x, y = centers[i] # Ensure strictly inside 0..1 b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
# Pairwise constraints # r_i + r_j <= dist_ij diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq)
A_ub = [] b_ub = []
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
# Try Highs solver first (faster/robust) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
# Fallback to interior-point res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
# Last resort: just wall bounds return np.array([b[1] for b in bounds_list])
def find_largest_void(self, centers): """Finds the largest void using Voronoi diagram with boundary reflection.""" # Reflect points across walls to create 'ghost' neighbors for correct boundary cells points_aug = [centers] # Reflect across x=0, x=1, y=0, y=1 points_aug.append(np.column_stack([-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([2-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], -centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], 2-centers[:,1]]))
all_pts = np.vstack(points_aug)
candidates = [] try: vor = Voronoi(all_pts) for v in vor.vertices: if 0 <= v[0] <= 1 and 0 <= v[1] <= 1: candidates.append(v) except: pass
if not candidates: return np.array([0.5, 0.5]), 0.01
cand = np.array(candidates)
# Distance to centers diff = cand[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c = np.min(np.sqrt(np.sum(diff**2, axis=2)), axis=1)
# Distance to walls d_w = np.min(np.column_stack([cand[:,0], 1-cand[:,0], cand[:,1], 1-cand[:,1]]), axis=1)
# Maximize min clearance clearance = np.minimum(d_c, d_w) best_idx = np.argmax(clearance) return cand[best_idx], clearance[best_idx]
def run_physics_relaxation(self, centers, steps=60): """ Momentum-based relaxation with dynamic radii (fluffing). Adapted from Fused implementation. """ c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005 for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists forces = np.zeros_like(c) mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall velocities = velocities * 0.4 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0) pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures dr = np.where(total_p > 1e-4, -total_p * 0.5, 0.002) r += dr * dt r = np.maximum(r, 0.01) return c, r
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
# Objective: Maximize sum(r) obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
# Penalties # 1. Wall Penetration w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
# 2. Pairwise Overlap diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_matrix = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_matrix - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n) start_phase = 0 else: # Warm start start_phase = 1
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0
# Phases all_phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = all_phases[start_phase:] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 # Reduce iters for very stiff phases iter_limit = 250 if mu > 5000 else 180
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs()
best_global_res = (None, None, -1.0)
# 1. Seed Screening for c in configs: # Phase 1: Equalize radii to find structure c_opt, r_soft = self.local_optimization(c, equal_bias=True) # Phase 2: Relax sizes c_opt, _ = self.local_optimization(c_opt, radii_init=r_soft, equal_bias=False)
r_lp = self.solve_lp_radii(c_opt) score = np.sum(r_lp)
if score > best_global_res[2]: best_global_res = (c_opt, r_lp, score)
# 2. Basin Hopping with Hybrid Moves curr_c = best_global_res[0] curr_r = best_global_res[1] curr_score = best_global_res[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 40 temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy()
# Decision: Pop vs Weighted Jitter # 45% Pop, 55% Jitter is_pop = (self.rng.rand() < 0.45)
if is_pop: # Stochastic Pop: Select from the bottom 5 smallest circles # This helps remove bottlenecks sorted_indices = np.argsort(curr_r) candidates = sorted_indices[:5] min_r_idx = self.rng.choice(candidates)
other_indices = [idx for idx in range(self.n) if idx != min_r_idx] others = curr_c[other_indices]
# Move to largest void target_pos, target_rad = self.find_largest_void(others)
trial_c[min_r_idx] = target_pos # Reduced Jitter trial_c += 0.003 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
trial_r_init = curr_r.copy() # Initialize with void radius estimate (conservative) trial_r_init[min_r_idx] = max(0.01, target_rad * 0.9) else: # Weighted Physics Jitter # Weight perturbation by inverse radius (move small circles more) weights = 1.0 / (curr_r + 1e-6) weights /= np.mean(weights) weights = np.clip(weights, 0.5, 3.5)
mag = 0.035 * np.exp(-i/(n_iter*0.8)) perturb = mag * self.rng.randn(self.n, 2) * weights[:, np.newaxis]
trial_c = np.clip(trial_c + perturb, 0.0, 1.0)
# Apply physics relaxation (Fluffing) # This finds a nearby jammed state for the perturbed config trial_c, r_hint = self.run_physics_relaxation(trial_c, steps=50)
trial_r_init = r_hint * 0.95
# Run Local Optimization (High Stiffness) c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)
# Exact Evaluation via LP r_lp_new = self.solve_lp_radii(c_new) score_new = np.sum(r_lp_new)
# Metropolis Acceptance delta = score_new - curr_score accept = False if delta > 0: accept = True elif self.rng.rand() < np.exp(delta / temperature): accept = True
if accept: curr_c = c_new curr_r = r_lp_new curr_score = score_new
if score_new > best_score: best_score = score_new best_c = c_new.copy() best_r = r_lp_new.copy() temperature *= 0.92
# 3. Final High-Precision Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 1000, 'ftol': 1e-10} )
final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = VoronoiPopHybridSupreme(n=26) return opt.optimize()
def compute_max_radii(centers): opt = VoronoiPopHybridSupreme(n=len(centers)) return opt.solve_lp_radii(centers)
def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424# EVOLVE-BLOCK-STARTimport numpy as npfrom scipy.optimize import minimize, linprogfrom scipy.spatial import Voronoi
class VoronoiPopHybrid: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
def get_initial_configs(self): """Generates diverse initial configurations.""" configs = []
# 1. Explicit Lattice Patterns (Rows) # Targeted topologies for N=26 patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Rounded small corners ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
# Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c scale = 0.85 / np.max(span) if np.max(span) > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it shift = 0.5 - np.mean(centers, axis=0) centers += shift
# Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(centers)
# 2. Spiral Packing indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) scale = 0.44 c_spiral[:, 0] = 0.5 + scale * r * np.cos(theta) c_spiral[:, 1] = 0.5 + scale * r * np.sin(theta) configs.append(c_spiral)
# 3. Boundary + Random Internal boundary = [] n_side = 6 x = np.linspace(0.1, 0.9, n_side) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) combined = np.vstack([boundary, internal]) configs.append(combined) elif needed < 0: configs.append(boundary[:self.n]) else: configs.append(boundary)
# 4. Pure Random Relaxed rand_pts = 0.1 + 0.8 * self.rng.rand(self.n, 2) configs.append(rand_pts)
return configs
def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c = -np.ones(n) # Maximize sum(r)
# Wall bounds bounds_list = [] for i in range(n): x, y = centers[i] # Ensure strictly inside 0..1 b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
# Pairwise constraints # r_i + r_j <= dist_ij diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq)
A_ub = [] b_ub = []
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
# Try Highs solver first (faster/robust) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
# Fallback to interior-point res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
# Last resort: just wall bounds return np.array([b[1] for b in bounds_list])
def find_largest_void(self, centers): """Finds the largest void using Voronoi diagram with boundary reflection.""" # Reflect points across walls to create 'ghost' neighbors for correct boundary cells points_aug = [centers] # Reflect across x=0, x=1, y=0, y=1 points_aug.append(np.column_stack([-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([2-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], -centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], 2-centers[:,1]]))
all_pts = np.vstack(points_aug)
candidates = [] try: vor = Voronoi(all_pts) for v in vor.vertices: if 0 <= v[0] <= 1 and 0 <= v[1] <= 1: candidates.append(v) except: pass
if not candidates: return np.array([0.5, 0.5])
cand = np.array(candidates)
# Distance to centers diff = cand[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c = np.min(np.sqrt(np.sum(diff**2, axis=2)), axis=1)
# Distance to walls d_w = np.min(np.column_stack([cand[:,0], 1-cand[:,0], cand[:,1], 1-cand[:,1]]), axis=1)
# Maximize min clearance clearance = np.minimum(d_c, d_w) best_idx = np.argmax(clearance) return cand[best_idx]
def run_physics_relaxation(self, centers, steps=60): """ Momentum-based relaxation with dynamic radii (fluffing). """ c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005
for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq)
r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists
forces = np.zeros_like(c)
mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push
k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall
velocities = velocities * 0.5 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0)
pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures
dr = np.where(total_p > 1e-4, -total_p * 0.5, 0.002) r += dr * dt r = np.maximum(r, 0.01)
return c, r
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
# Objective: Maximize sum(r) obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
# Penalties # 1. Wall Penetration w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
# 2. Pairwise Overlap diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_matrix = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_matrix - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0
# Phases phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0
iter_limit = 250 if mu > 5000 else 180
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs()
best_global_res = (None, None, -1.0)
# 1. Seed Screening for c in configs: # Phase 1: Equalize radii to find structure c_opt, r_soft = self.local_optimization(c, equal_bias=True) # Phase 2: Relax sizes c_opt, _ = self.local_optimization(c_opt, radii_init=r_soft, equal_bias=False)
r_lp = self.solve_lp_radii(c_opt) score = np.sum(r_lp)
if score > best_global_res[2]: best_global_res = (c_opt, r_lp, score)
# 2. Basin Hopping with Hybrid Moves curr_c = best_global_res[0] curr_r = best_global_res[1] curr_score = best_global_res[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 40 temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy()
# Decision: Pop vs Relaxed Jitter is_pop = (self.rng.rand() < 0.4) # 40% chance to pop
if is_pop: # Pop heuristic: Move smallest circle to largest void min_r_idx = np.argmin(curr_r) other_indices = [idx for idx in range(self.n) if idx != min_r_idx] others = curr_c[other_indices]
target_pos = self.find_largest_void(others)
trial_c[min_r_idx] = target_pos # Small jitter to break symmetries trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
trial_r_init = curr_r.copy() trial_r_init[min_r_idx] = 0.05 else: # Relaxed Jitter: Noise + Physics Smoothing mag = 0.03 * np.exp(-i/(n_iter*0.8)) perturb = mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c + perturb, 0.0, 1.0)
# Apply physics relaxation to resolve severe overlaps cheaply trial_c, r_hint = self.run_physics_relaxation(trial_c, steps=60)
trial_r_init = r_hint * 0.95 # Slightly shrink to allow rearrangement
# Run Local Optimization (High Stiffness) c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.8)
# Exact Evaluation via LP r_lp_new = self.solve_lp_radii(c_new) score_new = np.sum(r_lp_new)
# Metropolis Acceptance delta = score_new - curr_score accept = False if delta > 0: accept = True elif self.rng.rand() < np.exp(delta / temperature): accept = True
if accept: curr_c = c_new curr_r = r_lp_new curr_score = score_new
if score_new > best_score: best_score = score_new best_c = c_new.copy() best_r = r_lp_new.copy() temperature *= 0.95 # Cool down
# 3. Final High-Precision Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), # High penalty method='L-BFGS-B', bounds=bounds, options={'maxiter': 800, 'ftol': 1e-10} )
final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = VoronoiPopHybrid(n=26) return opt.optimize()
def compute_max_radii(centers): opt = VoronoiPopHybrid(n=len(centers)) return opt.solve_lp_radii(centers)
def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163import osimport jsonimport numpy as npfrom typing import Dict, Any, List, Tuple
def evaluate_aux(results_dir: str, primary_result: Dict[str, Any] | None = None) -> Dict[str, Any]: """ Evaluates auxiliary metrics for the circle packing problem. Focuses on robustness of data extraction and providing signals even on invalid states. """ metrics = { "aux_data_load_success": 0.0, "aux_primary_eval_successful": 0.0,
# Constraint Tension "aux_total_overlap_violation_distance": 0.0, "aux_total_wall_penetration_distance": 0.0, "aux_min_clearance_to_wall": 0.0, # Negative if penetrating "aux_min_pairwise_clearance": 0.0, # Negative if overlapping
# Structural Sensitivity "aux_radius_variance": 0.0, "aux_average_radius_valid_circles": 0.0, # New metric # Component Contribution "aux_zero_radius_count": 0.0,
# Structural Sensitivity "aux_neighbor_distance_variance": 0.0, }
L_x, L_y = 1.0, 1.0 # Unit square dimensions epsilon_contact = 1e-4 # Tolerance for "contact" or near-zero values epsilon_violation = 1e-6 # Tolerance for numerical stability in constraint checks
centers: np.ndarray | None = None radii: np.ndarray | None = None num_circles: int = 0
# --- Extract data from primary_result for high-level metrics --- if primary_result: if primary_result.get('correct', False): metrics["aux_primary_eval_successful"] = 1.0
# --- Attempt to load centers and radii from extra.npz first --- extra_file = os.path.join(results_dir, "extra.npz") if os.path.exists(extra_file): try: with np.load(extra_file) as data: centers = data['centers'] radii = data['radii'] metrics["aux_data_load_success"] = 1.0 if centers is not None and radii is not None and centers.shape[0] == radii.shape[0]: num_circles = centers.shape[0] else: print(f"Warning: Data in {extra_file} is malformed (centers/radii mismatch or None). Setting data_load_success to 0.0.") metrics["aux_data_load_success"] = 0.0 centers, radii, num_circles = None, None, 0 # Reset to ensure no partial data is used except Exception as e: print(f"Error loading extra.npz from {extra_file}: {e}. Setting data_load_success to 0.0.") metrics["aux_data_load_success"] = 0.0 else: print(f"extra.npz not found at {extra_file}. Geometric metrics will remain 0.0.") # If extra.npz is not found, we cannot proceed with geometric calculations based on centers and radii. # The aux_data_load_success will remain 0.0 as initialized. return metrics # Exit early if no data to process
# Ensure radii are positive for calculations, avoiding log/sqrt of negative numbers radii_positive = np.maximum(radii, epsilon_contact)
# --- Calculate Geometric Metrics ---
# aux_neighbor_distance_variance (Structural Sensitivity) neighbor_distances = [] if num_circles > 1: for i in range(num_circles): min_dist = float('inf') for j in range(num_circles): if i != j: dist = np.linalg.norm(centers[i] - centers[j]) if dist < min_dist: min_dist = dist if min_dist != float('inf'): # Only add if a neighbor was found neighbor_distances.append(min_dist) if len(neighbor_distances) > 0: metrics["aux_neighbor_distance_variance"] = float(np.var(neighbor_distances))
# aux_average_radius_valid_circles valid_radii = radii_positive[radii_positive > epsilon_contact] if len(valid_radii) > 0: metrics["aux_average_radius_valid_circles"] = float(np.mean(valid_radii))
# aux_radius_variance (Structural Sensitivity) metrics["aux_radius_variance"] = float(np.var(radii_positive))
# aux_zero_radius_count (Component Contribution) metrics["aux_zero_radius_count"] = float(np.sum(radii < epsilon_contact))
# --- Overlap and Wall Penetration Metrics (Constraint Tension) --- metrics["aux_total_overlap_violation_distance"] = 0.0 metrics["aux_min_pairwise_clearance"] = float('inf') # Initialize with positive infinity
for i in range(num_circles): for j in range(i + 1, num_circles): dist = np.linalg.norm(centers[i] - centers[j]) min_dist_for_contact = radii_positive[i] + radii_positive[j] clearance = dist - min_dist_for_contact # Positive for no overlap, negative for overlap
if clearance < -epsilon_violation: # Significant overlap metrics["aux_total_overlap_violation_distance"] += abs(clearance) if clearance < metrics["aux_min_pairwise_clearance"]: metrics["aux_min_pairwise_clearance"] = float(clearance)
# If no pairs, ensure min_pairwise_clearance is not inf (e.g., if num_circles < 2) if metrics["aux_min_pairwise_clearance"] == float('inf'): metrics["aux_min_pairwise_clearance"] = 0.0 # Or some reasonable default
metrics["aux_total_wall_penetration_distance"] = 0.0 metrics["aux_min_clearance_to_wall"] = float('inf') # Initialize with positive infinity
for i in range(num_circles): # Calculate penetration for each wall penetrations = [] clearances = []
# Left wall (x=0) clearance_left = centers[i][0] - radii_positive[i] penetrations.append(max(0.0, -clearance_left)) # Positive if penetrating clearances.append(clearance_left)
# Right wall (x=L_x) clearance_right = (L_x - centers[i][0]) - radii_positive[i] penetrations.append(max(0.0, -clearance_right)) clearances.append(clearance_right)
# Bottom wall (y=0) clearance_bottom = centers[i][1] - radii_positive[i] penetrations.append(max(0.0, -clearance_bottom)) clearances.append(clearance_bottom)
# Top wall (y=L_y) clearance_top = (L_y - centers[i][1]) - radii_positive[i] penetrations.append(max(0.0, -clearance_top)) clearances.append(clearance_top)
total_penetration_for_circle = sum(penetrations) if total_penetration_for_circle > epsilon_violation: metrics["aux_total_wall_penetration_distance"] += total_penetration_for_circle
min_clearance_for_circle = min(clearances) if min_clearance_for_circle < metrics["aux_min_clearance_to_wall"]: metrics["aux_min_clearance_to_wall"] = float(min_clearance_for_circle) # If no circles or no walls, ensure min_clearance_to_wall is not inf if metrics["aux_min_clearance_to_wall"] == float('inf'): metrics["aux_min_clearance_to_wall"] = 0.0 # Or some reasonable default
return metrics1234{ "correct": true, "error": null}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{ "combined_score": 2.6358783713813057, "correct": true, "primary": { "combined_score": 2.6358783713813057, "public": { "centers_str": " centers[0] = (0.1115, 0.1115)\n centers[1] = (0.3153, 0.0931)\n centers[2] = (0.5030, 0.0946)\n centers[3] = (0.6908, 0.0931)\n centers[4] = (0.8917, 0.1083)\n centers[5] = (0.0963, 0.3191)\n centers[6] = (0.2413, 0.2381)\n centers[7] = (0.4062, 0.2596)\n centers[8] = (0.5998, 0.2601)\n centers[9] = (0.7676, 0.2393)\n centers[10] = (0.9070, 0.3276)\n centers[11] = (0.1034, 0.5187)\n centers[12] = (0.2734, 0.4056)\n centers[13] = (0.5019, 0.4732)\n centers[14] = (0.7309, 0.4079)\n centers[15] = (0.8980, 0.5224)\n centers[16] = (0.1049, 0.7270)\n centers[17] = (0.2967, 0.6199)\n centers[18] = (0.5011, 0.7267)\n centers[19] = (0.7056, 0.6213)\n centers[20] = (0.8959, 0.7286)\n centers[21] = (0.0846, 0.9154)\n centers[22] = (0.2964, 0.8674)\n centers[23] = (0.5008, 0.9212)\n centers[24] = (0.7049, 0.8678)\n centers[25] = (0.9158, 0.9158)", "num_circles": 26 }, "private": { "reported_sum_of_radii": 2.6358783713813057 }, "execution_time_mean": 102.67474452685565, "execution_time_std": 0.0, "num_valid_runs": 1, "num_invalid_runs": 0, "all_validation_errors": [], "correct": true, "validation_error": null }, "auxiliary": { "aux_data_load_success": 1.0, "aux_primary_eval_successful": 1.0, "aux_total_overlap_violation_distance": 0.0, "aux_total_wall_penetration_distance": 0.0, "aux_min_clearance_to_wall": 0.0, "aux_min_pairwise_clearance": -3.700255996053059e-08, "aux_radius_variance": 0.00027805351965177284, "aux_average_radius_valid_circles": 0.10137993736081945, "aux_zero_radius_count": 0.0, "aux_neighbor_distance_variance": 0.00037197202837559927, "aux_metric_eval_success": 1.0, "aux_metric_error_code": 0.0, "aux_metric_error_message_length": 0.0, "aux_metric_error_detail_length": 0.0, "aux_metric_non_numeric_dropped_count": 0.0 }, "auxiliary_descriptions": { "aux_data_load_success": "Binary indicator (1.0 for success, 0.0 for failure) if circle data (centers/radii) was successfully loaded from `extra.npz`. (Feasibility)", "aux_primary_eval_successful": "Binary indicator (1.0 for success, 0.0 for failure) if the primary evaluation itself reported success. (Feasibility)", "aux_total_overlap_violation_distance": "Sum of pairwise overlap distances for all overlapping circles. Lower values are better, indicating less constraint violation. (Constraint Tension)", "aux_total_wall_penetration_distance": "Sum of individual wall penetration distances. Lower values are better, indicating less constraint violation. (Constraint Tension)", "aux_min_clearance_to_wall": "Minimum distance from any circle's edge to any wall. Negative values indicate wall penetration. Higher values (closer to zero or positive) are better. (Constraint Tension)", "aux_min_pairwise_clearance": "Minimum distance between any two circle edges. Negative values indicate overlap. Higher values (closer to zero or positive) are better. (Constraint Tension)", "aux_radius_variance": "Variance of the radii of all circles. Lower values (closer to zero) indicate more uniform radii. (Structural Sensitivity)", "aux_average_radius_valid_circles": "Average radius of circles with non-zero radii. Provides a signal on the typical size of circles that are actively contributing. (Structural Sensitivity / Feasibility)", "aux_zero_radius_count": "Count of circles with effectively zero radius. A higher value indicates more collapsed circles, suggesting issues with the optimization. (Component Contribution / Feasibility)", "aux_neighbor_distance_variance": "Variance of the distances to the nearest neighbor for all circles. Lower values indicate more uniform local environments, suggesting a more ordered packing structure. (Structural Sensitivity)" }, "timestamp": 1772468781.700546, "generation": 155}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456# EVOLVE-BLOCK-STARTimport numpy as npfrom scipy.optimize import minimize, linprogfrom scipy.spatial import Voronoi
class VoronoiPopHybridSupreme: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
def get_initial_configs(self): """Generates diverse initial configurations.""" configs = []
# 1. Explicit Lattice Patterns (Rows) patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Hex-like rounded ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
# Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c scale = 0.85 / np.max(span) if np.max(span) > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it shift = 0.5 - np.mean(centers, axis=0) centers += shift
# Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(centers)
# 2. Spiral Packing indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) scale = 0.44 c_spiral[:, 0] = 0.5 + scale * r * np.cos(theta) c_spiral[:, 1] = 0.5 + scale * r * np.sin(theta) configs.append(c_spiral)
# 3. Generic Hex (Imported from Fused) configs.append(self.generate_generic_hex())
# 4. Boundary + Random Internal boundary = [] n_side = 6 x = np.linspace(0.1, 0.9, n_side) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) combined = np.vstack([boundary, internal]) configs.append(combined) elif needed < 0: configs.append(boundary[:self.n]) else: configs.append(boundary)
# 5. Pure Random Relaxed rand_pts = 0.1 + 0.8 * self.rng.rand(self.n, 2) configs.append(rand_pts)
return configs
def generate_generic_hex(self): """Generates a generic hexagonal lattice patch.""" v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-5, 6): for j in range(-5, 6): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]] min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c = -np.ones(n) # Maximize sum(r)
# Wall bounds bounds_list = [] for i in range(n): x, y = centers[i] # Ensure strictly inside 0..1 b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
# Pairwise constraints # r_i + r_j <= dist_ij diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq)
A_ub = [] b_ub = []
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
# Try Highs solver first (faster/robust) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
# Fallback to interior-point res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
# Last resort: just wall bounds return np.array([b[1] for b in bounds_list])
def find_largest_void(self, centers): """Finds the largest void using Voronoi diagram with boundary reflection.""" # Reflect points across walls to create 'ghost' neighbors for correct boundary cells points_aug = [centers] # Reflect across x=0, x=1, y=0, y=1 points_aug.append(np.column_stack([-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([2-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], -centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], 2-centers[:,1]]))
all_pts = np.vstack(points_aug)
candidates = [] try: vor = Voronoi(all_pts) for v in vor.vertices: if 0 <= v[0] <= 1 and 0 <= v[1] <= 1: candidates.append(v) except: pass
if not candidates: return np.array([0.5, 0.5]), 0.01
cand = np.array(candidates)
# Distance to centers diff = cand[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c = np.min(np.sqrt(np.sum(diff**2, axis=2)), axis=1)
# Distance to walls d_w = np.min(np.column_stack([cand[:,0], 1-cand[:,0], cand[:,1], 1-cand[:,1]]), axis=1)
# Maximize min clearance clearance = np.minimum(d_c, d_w) best_idx = np.argmax(clearance) return cand[best_idx], clearance[best_idx]
def run_physics_relaxation(self, centers, steps=60): """ Momentum-based relaxation with dynamic radii (fluffing). Adapted from Fused implementation. """ c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005 for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists forces = np.zeros_like(c) mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall velocities = velocities * 0.4 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0) pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures dr = np.where(total_p > 1e-4, -total_p * 0.5, 0.002) r += dr * dt r = np.maximum(r, 0.01) return c, r
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
# Objective: Maximize sum(r) obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
# Penalties # 1. Wall Penetration w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
# 2. Pairwise Overlap diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_matrix = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_matrix - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n) start_phase = 0 else: # Warm start start_phase = 1
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0
# Phases all_phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = all_phases[start_phase:] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 # Reduce iters for very stiff phases iter_limit = 250 if mu > 5000 else 180
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs()
best_global_res = (None, None, -1.0)
# 1. Seed Screening for c in configs: # Phase 1: Equalize radii to find structure c_opt, r_soft = self.local_optimization(c, equal_bias=True) # Phase 2: Relax sizes c_opt, _ = self.local_optimization(c_opt, radii_init=r_soft, equal_bias=False)
r_lp = self.solve_lp_radii(c_opt) score = np.sum(r_lp)
if score > best_global_res[2]: best_global_res = (c_opt, r_lp, score)
# 2. Basin Hopping with Hybrid Moves curr_c = best_global_res[0] curr_r = best_global_res[1] curr_score = best_global_res[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 40 temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy()
# Decision: Pop vs Weighted Jitter # 45% Pop, 55% Jitter is_pop = (self.rng.rand() < 0.45)
if is_pop: # Stochastic Pop: Select from the bottom 5 smallest circles # This helps remove bottlenecks sorted_indices = np.argsort(curr_r) candidates = sorted_indices[:5] min_r_idx = self.rng.choice(candidates)
other_indices = [idx for idx in range(self.n) if idx != min_r_idx] others = curr_c[other_indices]
# Move to largest void target_pos, target_rad = self.find_largest_void(others)
trial_c[min_r_idx] = target_pos # Reduced Jitter trial_c += 0.003 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
trial_r_init = curr_r.copy() # Initialize with void radius estimate (conservative) trial_r_init[min_r_idx] = max(0.01, target_rad * 0.9) else: # Weighted Physics Jitter # Weight perturbation by inverse radius (move small circles more) weights = 1.0 / (curr_r + 1e-6) weights /= np.mean(weights) weights = np.clip(weights, 0.5, 3.5)
mag = 0.035 * np.exp(-i/(n_iter*0.8)) perturb = mag * self.rng.randn(self.n, 2) * weights[:, np.newaxis]
trial_c = np.clip(trial_c + perturb, 0.0, 1.0)
# Apply physics relaxation (Fluffing) # This finds a nearby jammed state for the perturbed config trial_c, r_hint = self.run_physics_relaxation(trial_c, steps=50)
trial_r_init = r_hint * 0.95
# Run Local Optimization (High Stiffness) c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)
# Exact Evaluation via LP r_lp_new = self.solve_lp_radii(c_new) score_new = np.sum(r_lp_new)
# Metropolis Acceptance delta = score_new - curr_score accept = False if delta > 0: accept = True elif self.rng.rand() < np.exp(delta / temperature): accept = True
if accept: curr_c = c_new curr_r = r_lp_new curr_score = score_new
if score_new > best_score: best_score = score_new best_c = c_new.copy() best_r = r_lp_new.copy() temperature *= 0.92
# 3. Final High-Precision Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 1000, 'ftol': 1e-10} )
final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = VoronoiPopHybridSupreme(n=26) return opt.optimize()
def compute_max_radii(centers): opt = VoronoiPopHybridSupreme(n=len(centers)) return opt.solve_lp_radii(centers)
def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii# EVOLVE-BLOCK-END12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# EVOLVE-BLOCK-START"""Constructor-based circle packing for n=26 circles"""
import numpy as np
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii.
Returns: Tuple of (centers, radii, sum_of_radii) centers: np.array of shape (26, 2) with (x, y) coordinates radii: np.array of shape (26) with radius of each circle sum_of_radii: Sum of all radii """ # Initialize arrays for 26 circles n = 26 centers = np.zeros((n, 2))
# Place circles in a structured pattern # This is a simple pattern - evolution will improve this
# First, place a large circle in the center centers[0] = [0.5, 0.5]
# Place 8 circles around it in a ring for i in range(8): angle = 2 * np.pi * i / 8 centers[i + 1] = [0.5 + 0.3 * np.cos(angle), 0.5 + 0.3 * np.sin(angle)]
# Place 16 more circles in an outer ring for i in range(16): angle = 2 * np.pi * i / 16 centers[i + 9] = [0.5 + 0.7 * np.cos(angle), 0.5 + 0.7 * np.sin(angle)]
# Additional positioning adjustment to make sure all circles # are inside the square and don't overlap # Clip to ensure everything is inside the unit square centers = np.clip(centers, 0.01, 0.99)
# Compute maximum valid radii for this configuration radii = compute_max_radii(centers) return centers, radii
def compute_max_radii(centers): """ Compute the maximum possible radii for each circle position such that they don't overlap and stay within the unit square.
Args: centers: np.array of shape (n, 2) with (x, y) coordinates
Returns: np.array of shape (n) with radius of each circle """ n = centers.shape[0] radii = np.ones(n)
# First, limit by distance to square borders for i in range(n): x, y = centers[i] # Distance to borders radii[i] = min(x, y, 1 - x, 1 - y)
# Then, limit by distance to other circles # Each pair of circles with centers at distance d can have # sum of radii at most d to avoid overlap for i in range(n): for j in range(i + 1, n): dist = np.sqrt(np.sum((centers[i] - centers[j]) ** 2))
# If current radii would cause overlap if radii[i] + radii[j] > dist: # Scale both radii proportionally scale = dist / (radii[i] + radii[j]) radii[i] *= scale radii[j] *= scale
return radii
# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280--- a/original.py+++ b/original.py@@ -1,94 +1,210 @@ # EVOLVE-BLOCK-START """Constructor-based circle packing for n=26 circles""" import numpy as np - def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square- that attempts to maximize the sum of their radii.+ that attempts to maximize the sum of their radii using a + physics-based relaxation algorithm with restarts. Returns:- Tuple of (centers, radii, sum_of_radii)- centers: np.array of shape (26, 2) with (x, y) coordinates- radii: np.array of shape (26) with radius of each circle- sum_of_radii: Sum of all radii- """- # Initialize arrays for 26 circles+ Tuple of (centers, radii)+ centers: np.array of shape (26, 2)+ radii: np.array of shape (26)+ """ n = 26- centers = np.zeros((n, 2))-- # Place circles in a structured pattern- # This is a simple pattern - evolution will improve this-- # First, place a large circle in the center- centers[0] = [0.5, 0.5]-- # Place 8 circles around it in a ring- for i in range(8):- angle = 2 * np.pi * i / 8- centers[i + 1] = [0.5 + 0.3 * np.cos(angle), 0.5 + 0.3 * np.sin(angle)]-- # Place 16 more circles in an outer ring- for i in range(16):- angle = 2 * np.pi * i / 16- centers[i + 9] = [0.5 + 0.7 * np.cos(angle), 0.5 + 0.7 * np.sin(angle)]-- # Additional positioning adjustment to make sure all circles- # are inside the square and don't overlap- # Clip to ensure everything is inside the unit square- centers = np.clip(centers, 0.01, 0.99)-- # Compute maximum valid radii for this configuration- radii = compute_max_radii(centers)+ best_centers = None+ best_radii = None+ best_score = -1.0++ # Run multiple restarts to find global optima+ # 26 circles have many local optima, so random restarts are crucial+ num_restarts = 8+ + for _ in range(num_restarts):+ centers, radii = run_physics_simulation(n)+ + # Enforce strict constraints based on the simulation result+ radii = compute_max_radii(centers, initial_radii=radii)+ + score = np.sum(radii)+ if score > best_score:+ best_score = score+ best_centers = centers.copy()+ best_radii = radii.copy()++ return best_centers, best_radii++def run_physics_simulation(n):+ """+ Simulates circles as soft bodies that repel each other and grow.+ """+ # Initialize random positions+ centers = np.random.rand(n, 2)+ # Start with small random radii to avoid huge initial explosions+ radii = np.random.rand(n) * 0.05 + 0.01+ + # Physics parameters+ iterations = 800+ dt = 0.01+ damping = 0.9+ growth_rate = 0.0002+ + velocities = np.zeros_like(centers)+ + for _ in range(iterations):+ # Calculate pair distances+ # dist_matrix: (n, n)+ delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]+ dist_sq = np.sum(delta**2, axis=2)+ + # Avoid division by zero+ np.fill_diagonal(dist_sq, 1.0)+ dists = np.sqrt(dist_sq)+ + # Calculate overlaps: (r_i + r_j) - dist+ # Positive value means overlap+ radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :]+ overlaps = radii_sum - dists+ np.fill_diagonal(overlaps, -1.0) # No self-overlap+ + # Forces+ forces = np.zeros_like(centers)+ + # 1. Circle-Circle Repulsion+ # Mask for interacting pairs+ # Interaction horizon: include slight non-overlapping neighbors to maintain spacing+ + # Normalize delta+ # If dist is very small, use random direction (or zero, but normalized needs care)+ small_dist = dists < 1e-6+ dists_safe = np.where(small_dist, 1.0, dists)+ delta_norm = delta / dists_safe[:, :, np.newaxis]+ + # Force magnitude+ # Stronger repulsion if overlapping+ f_mag = np.maximum(overlaps, 0) * 50.0 + + # Sum forces+ forces += np.sum(delta_norm * f_mag[:, :, np.newaxis], axis=1)+ + # 2. Wall Repulsion+ # Walls are at 0 and 1+ # Left (x=0)+ l_overlap = np.maximum(radii - centers[:, 0], 0)+ forces[:, 0] += l_overlap * 100.0+ + # Right (x=1)+ r_overlap = np.maximum(radii - (1.0 - centers[:, 0]), 0)+ forces[:, 0] -= r_overlap * 100.0+ + # Bottom (y=0)+ b_overlap = np.maximum(radii - centers[:, 1], 0)+ forces[:, 1] += b_overlap * 100.0+ + # Top (y=1)+ t_overlap = np.maximum(radii - (1.0 - centers[:, 1]), 0)+ forces[:, 1] -= t_overlap * 100.0+ + # 3. Update Velocities and Positions+ velocities = velocities * damping + forces * dt+ centers += velocities * dt+ + # Hard constraint on centers to keep them in [0,1]+ centers = np.clip(centers, 0.0, 1.0)+ + # 4. Radius Dynamics+ # If circle is under pressure (overlap > 0), shrink+ # If circle is free, grow+ + # Max overlap for each circle (sum of all overlaps)+ circle_pressure = np.sum(np.maximum(overlaps, 0), axis=1)+ + # Add wall pressure+ wall_pressure = l_overlap + r_overlap + b_overlap + t_overlap+ total_pressure = circle_pressure + wall_pressure+ + # Dynamics+ # If pressure > 0, shrink fast to resolve+ # If pressure == 0, grow slowly to fill space+ + dr = np.zeros(n)+ shrink_mask = total_pressure > 0+ dr[shrink_mask] = -total_pressure[shrink_mask] * 0.5 # Shrink rate+ dr[~shrink_mask] = growth_rate+ + radii += dr * dt+ radii = np.maximum(radii, 0.001) # Min radius+ return centers, radii --def compute_max_radii(centers):- """- Compute the maximum possible radii for each circle position- such that they don't overlap and stay within the unit square.-- Args:- centers: np.array of shape (n, 2) with (x, y) coordinates-- Returns:- np.array of shape (n) with radius of each circle+def compute_max_radii(centers, initial_radii=None):+ """+ Refine radii for fixed centers to ensure no overlaps.+ Starting from initial_radii if provided helps preserve the+ relative sizes found during simulation. """ n = centers.shape[0]- radii = np.ones(n)-- # First, limit by distance to square borders- for i in range(n):- x, y = centers[i]- # Distance to borders- radii[i] = min(x, y, 1 - x, 1 - y)-- # Then, limit by distance to other circles- # Each pair of circles with centers at distance d can have- # sum of radii at most d to avoid overlap- for i in range(n):- for j in range(i + 1, n):- dist = np.sqrt(np.sum((centers[i] - centers[j]) ** 2))-- # If current radii would cause overlap- if radii[i] + radii[j] > dist:- # Scale both radii proportionally- scale = dist / (radii[i] + radii[j])- radii[i] *= scale- radii[j] *= scale-+ + # Calculate max possible radius for each circle based on walls+ # Distance to closest wall+ max_wall_radii = np.minimum(centers[:, 0], 1 - centers[:, 0])+ max_wall_radii = np.minimum(max_wall_radii, centers[:, 1])+ max_wall_radii = np.minimum(max_wall_radii, 1 - centers[:, 1])+ + if initial_radii is not None:+ # Start from simulation proposal, but clipped to walls+ radii = np.minimum(initial_radii, max_wall_radii)+ else:+ # Default fallback+ radii = max_wall_radii.copy()+ + # Iteratively resolve overlaps+ # We want to keep the ratios of radii similar to input if possible, + # but strictly satisfy constraints.+ + # 100 iterations of relaxation+ for _ in range(100):+ valid = True+ for i in range(n):+ for j in range(i + 1, n):+ dist = np.sqrt(np.sum((centers[i] - centers[j])**2))+ sum_r = radii[i] + radii[j]+ + if sum_r > dist - 1e-10:+ valid = False+ # Overlap+ overlap = sum_r - dist+ + if sum_r > 1e-9:+ # Shrink proportional to current size (maintains relative scale)+ fraction_i = radii[i] / sum_r+ fraction_j = radii[j] / sum_r+ + # Apply correction with tiny safety buffer+ radii[i] -= overlap * fraction_i * 1.0001+ radii[j] -= overlap * fraction_j * 1.0001+ else:+ radii[i] -= overlap * 0.5+ radii[j] -= overlap * 0.5+ + # Clamp to walls again to be safe+ radii = np.minimum(radii, max_wall_radii)+ + if valid:+ break+ return radii- # EVOLVE-BLOCK-END # This part remains fixed (not evolved) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210# EVOLVE-BLOCK-START"""Constructor-based circle packing for n=26 circles"""
import numpy as np
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii using a physics-based relaxation algorithm with restarts.
Returns: Tuple of (centers, radii) centers: np.array of shape (26, 2) radii: np.array of shape (26) """ n = 26 best_centers = None best_radii = None best_score = -1.0
# Run multiple restarts to find global optima # 26 circles have many local optima, so random restarts are crucial num_restarts = 8 for _ in range(num_restarts): centers, radii = run_physics_simulation(n) # Enforce strict constraints based on the simulation result radii = compute_max_radii(centers, initial_radii=radii) score = np.sum(radii) if score > best_score: best_score = score best_centers = centers.copy() best_radii = radii.copy()
return best_centers, best_radii
def run_physics_simulation(n): """ Simulates circles as soft bodies that repel each other and grow. """ # Initialize random positions centers = np.random.rand(n, 2) # Start with small random radii to avoid huge initial explosions radii = np.random.rand(n) * 0.05 + 0.01 # Physics parameters iterations = 800 dt = 0.01 damping = 0.9 growth_rate = 0.0002 velocities = np.zeros_like(centers) for _ in range(iterations): # Calculate pair distances # dist_matrix: (n, n) delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(delta**2, axis=2) # Avoid division by zero np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # Calculate overlaps: (r_i + r_j) - dist # Positive value means overlap radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :] overlaps = radii_sum - dists np.fill_diagonal(overlaps, -1.0) # No self-overlap # Forces forces = np.zeros_like(centers) # 1. Circle-Circle Repulsion # Mask for interacting pairs # Interaction horizon: include slight non-overlapping neighbors to maintain spacing # Normalize delta # If dist is very small, use random direction (or zero, but normalized needs care) small_dist = dists < 1e-6 dists_safe = np.where(small_dist, 1.0, dists) delta_norm = delta / dists_safe[:, :, np.newaxis] # Force magnitude # Stronger repulsion if overlapping f_mag = np.maximum(overlaps, 0) * 50.0 # Sum forces forces += np.sum(delta_norm * f_mag[:, :, np.newaxis], axis=1) # 2. Wall Repulsion # Walls are at 0 and 1 # Left (x=0) l_overlap = np.maximum(radii - centers[:, 0], 0) forces[:, 0] += l_overlap * 100.0 # Right (x=1) r_overlap = np.maximum(radii - (1.0 - centers[:, 0]), 0) forces[:, 0] -= r_overlap * 100.0 # Bottom (y=0) b_overlap = np.maximum(radii - centers[:, 1], 0) forces[:, 1] += b_overlap * 100.0 # Top (y=1) t_overlap = np.maximum(radii - (1.0 - centers[:, 1]), 0) forces[:, 1] -= t_overlap * 100.0 # 3. Update Velocities and Positions velocities = velocities * damping + forces * dt centers += velocities * dt # Hard constraint on centers to keep them in [0,1] centers = np.clip(centers, 0.0, 1.0) # 4. Radius Dynamics # If circle is under pressure (overlap > 0), shrink # If circle is free, grow # Max overlap for each circle (sum of all overlaps) circle_pressure = np.sum(np.maximum(overlaps, 0), axis=1) # Add wall pressure wall_pressure = l_overlap + r_overlap + b_overlap + t_overlap total_pressure = circle_pressure + wall_pressure # Dynamics # If pressure > 0, shrink fast to resolve # If pressure == 0, grow slowly to fill space dr = np.zeros(n) shrink_mask = total_pressure > 0 dr[shrink_mask] = -total_pressure[shrink_mask] * 0.5 # Shrink rate dr[~shrink_mask] = growth_rate radii += dr * dt radii = np.maximum(radii, 0.001) # Min radius return centers, radii
def compute_max_radii(centers, initial_radii=None): """ Refine radii for fixed centers to ensure no overlaps. Starting from initial_radii if provided helps preserve the relative sizes found during simulation. """ n = centers.shape[0] # Calculate max possible radius for each circle based on walls # Distance to closest wall max_wall_radii = np.minimum(centers[:, 0], 1 - centers[:, 0]) max_wall_radii = np.minimum(max_wall_radii, centers[:, 1]) max_wall_radii = np.minimum(max_wall_radii, 1 - centers[:, 1]) if initial_radii is not None: # Start from simulation proposal, but clipped to walls radii = np.minimum(initial_radii, max_wall_radii) else: # Default fallback radii = max_wall_radii.copy() # Iteratively resolve overlaps # We want to keep the ratios of radii similar to input if possible, # but strictly satisfy constraints. # 100 iterations of relaxation for _ in range(100): valid = True for i in range(n): for j in range(i + 1, n): dist = np.sqrt(np.sum((centers[i] - centers[j])**2)) sum_r = radii[i] + radii[j] if sum_r > dist - 1e-10: valid = False # Overlap overlap = sum_r - dist if sum_r > 1e-9: # Shrink proportional to current size (maintains relative scale) fraction_i = radii[i] / sum_r fraction_j = radii[j] / sum_r # Apply correction with tiny safety buffer radii[i] -= overlap * fraction_i * 1.0001 radii[j] -= overlap * fraction_j * 1.0001 else: radii[i] -= overlap * 0.5 radii[j] -= overlap * 0.5 # Clamp to walls again to be safe radii = np.minimum(radii, max_wall_radii) if valid: break return radii
# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# EVOLVE-BLOCK-START"""Constructor-based circle packing for n=26 circles"""
import numpy as np
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii.
Returns: Tuple of (centers, radii, sum_of_radii) centers: np.array of shape (26, 2) with (x, y) coordinates radii: np.array of shape (26) with radius of each circle sum_of_radii: Sum of all radii """ # Initialize arrays for 26 circles n = 26 centers = np.zeros((n, 2))
# Place circles in a structured pattern # This is a simple pattern - evolution will improve this
# First, place a large circle in the center centers[0] = [0.5, 0.5]
# Place 8 circles around it in a ring for i in range(8): angle = 2 * np.pi * i / 8 centers[i + 1] = [0.5 + 0.3 * np.cos(angle), 0.5 + 0.3 * np.sin(angle)]
# Place 16 more circles in an outer ring for i in range(16): angle = 2 * np.pi * i / 16 centers[i + 9] = [0.5 + 0.7 * np.cos(angle), 0.5 + 0.7 * np.sin(angle)]
# Additional positioning adjustment to make sure all circles # are inside the square and don't overlap # Clip to ensure everything is inside the unit square centers = np.clip(centers, 0.01, 0.99)
# Compute maximum valid radii for this configuration radii = compute_max_radii(centers) return centers, radii
def compute_max_radii(centers): """ Compute the maximum possible radii for each circle position such that they don't overlap and stay within the unit square.
Args: centers: np.array of shape (n, 2) with (x, y) coordinates
Returns: np.array of shape (n) with radius of each circle """ n = centers.shape[0] radii = np.ones(n)
# First, limit by distance to square borders for i in range(n): x, y = centers[i] # Distance to borders radii[i] = min(x, y, 1 - x, 1 - y)
# Then, limit by distance to other circles # Each pair of circles with centers at distance d can have # sum of radii at most d to avoid overlap for i in range(n): for j in range(i + 1, n): dist = np.sqrt(np.sum((centers[i] - centers[j]) ** 2))
# If current radii would cause overlap if radii[i] + radii[j] > dist: # Scale both radii proportionally scale = dist / (radii[i] + radii[j]) radii[i] *= scale radii[j] *= scale
return radii
# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201# EVOLVE-BLOCK-START"""Constructor-based circle packing for n=26 circles"""
import numpy as np
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii using a physics-based relaxation algorithm with restarts.
Returns: Tuple of (centers, radii) centers: np.array of shape (26, 2) radii: np.array of shape (26) """ n = 26 best_centers = None best_radii = None best_score = -1.0
# Run multiple restarts to find global optima # 26 circles have many local optima, so random restarts are crucial num_restarts = 8 for _ in range(num_restarts): centers, radii = run_physics_simulation(n) # Enforce strict constraints based on the simulation result radii = compute_max_radii(centers, initial_radii=radii) score = np.sum(radii) if score > best_score: best_score = score best_centers = centers.copy() best_radii = radii.copy()
return best_centers, best_radii
def run_physics_simulation(n): """ Simulates circles as soft bodies that repel each other and grow. """ # Initialize random positions centers = np.random.rand(n, 2) # Start with small random radii to avoid huge initial explosions radii = np.random.rand(n) * 0.05 + 0.01 # Physics parameters iterations = 800 dt = 0.01 damping = 0.9 growth_rate = 0.0002 velocities = np.zeros_like(centers) for _ in range(iterations): # Calculate pair distances # dist_matrix: (n, n) delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(delta**2, axis=2) # Avoid division by zero np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # Calculate overlaps: (r_i + r_j) - dist # Positive value means overlap radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :] overlaps = radii_sum - dists np.fill_diagonal(overlaps, -1.0) # No self-overlap # Forces forces = np.zeros_like(centers) # 1. Circle-Circle Repulsion # Mask for interacting pairs # Interaction horizon: include slight non-overlapping neighbors to maintain spacing # Normalize delta # If dist is very small, use random direction (or zero, but normalized needs care) small_dist = dists < 1e-6 dists_safe = np.where(small_dist, 1.0, dists) delta_norm = delta / dists_safe[:, :, np.newaxis] # Force magnitude # Stronger repulsion if overlapping f_mag = np.maximum(overlaps, 0) * 50.0 # Sum forces forces += np.sum(delta_norm * f_mag[:, :, np.newaxis], axis=1) # 2. Wall Repulsion # Walls are at 0 and 1 # Left (x=0) l_overlap = np.maximum(radii - centers[:, 0], 0) forces[:, 0] += l_overlap * 100.0 # Right (x=1) r_overlap = np.maximum(radii - (1.0 - centers[:, 0]), 0) forces[:, 0] -= r_overlap * 100.0 # Bottom (y=0) b_overlap = np.maximum(radii - centers[:, 1], 0) forces[:, 1] += b_overlap * 100.0 # Top (y=1) t_overlap = np.maximum(radii - (1.0 - centers[:, 1]), 0) forces[:, 1] -= t_overlap * 100.0 # 3. Update Velocities and Positions velocities = velocities * damping + forces * dt centers += velocities * dt # Hard constraint on centers to keep them in [0,1] centers = np.clip(centers, 0.0, 1.0) # 4. Radius Dynamics # If circle is under pressure (overlap > 0), shrink # If circle is free, grow # Max overlap for each circle (sum of all overlaps) circle_pressure = np.sum(np.maximum(overlaps, 0), axis=1) # Add wall pressure wall_pressure = l_overlap + r_overlap + b_overlap + t_overlap total_pressure = circle_pressure + wall_pressure # Dynamics # If pressure > 0, shrink fast to resolve # If pressure == 0, grow slowly to fill space dr = np.zeros(n) shrink_mask = total_pressure > 0 dr[shrink_mask] = -total_pressure[shrink_mask] * 0.5 # Shrink rate dr[~shrink_mask] = growth_rate radii += dr * dt radii = np.maximum(radii, 0.001) # Min radius return centers, radii
def compute_max_radii(centers, initial_radii=None): """ Refine radii for fixed centers to ensure no overlaps. Starting from initial_radii if provided helps preserve the relative sizes found during simulation. """ n = centers.shape[0] # Calculate max possible radius for each circle based on walls # Distance to closest wall max_wall_radii = np.minimum(centers[:, 0], 1 - centers[:, 0]) max_wall_radii = np.minimum(max_wall_radii, centers[:, 1]) max_wall_radii = np.minimum(max_wall_radii, 1 - centers[:, 1]) if initial_radii is not None: # Start from simulation proposal, but clipped to walls radii = np.minimum(initial_radii, max_wall_radii) else: # Default fallback radii = max_wall_radii.copy() # Iteratively resolve overlaps # We want to keep the ratios of radii similar to input if possible, # but strictly satisfy constraints. # 100 iterations of relaxation for _ in range(100): valid = True for i in range(n): for j in range(i + 1, n): dist = np.sqrt(np.sum((centers[i] - centers[j])**2)) sum_r = radii[i] + radii[j] if sum_r > dist - 1e-10: valid = False # Overlap overlap = sum_r - dist if sum_r > 1e-9: # Shrink proportional to current size (maintains relative scale) fraction_i = radii[i] / sum_r fraction_j = radii[j] / sum_r # Apply correction with tiny safety buffer radii[i] -= overlap * fraction_i * 1.0001 radii[j] -= overlap * fraction_j * 1.0001 else: radii[i] -= overlap * 0.5 radii[j] -= overlap * 0.5 # Clamp to walls again to be safe radii = np.minimum(radii, max_wall_radii) if valid: break return radii
# EVOLVE-BLOCK-END123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424--- a/original.py+++ b/original.py@@ -1,305 +1,323 @@ # EVOLVE-BLOCK-START """Constructor-based circle packing for n=26 circles""" import numpy as np def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii. - Uses a hybrid approach:- 1. Diverse Initialization (Grid, Hex, Rings, Random) to find different basins.- 2. Physics-based relaxation to optimize packing density.- 3. Greedy expansion/shrinking to strictly enforce constraints while maximizing size.-- Returns:- Tuple of (centers, radii)- centers: np.array of shape (26, 2)- radii: np.array of shape (26)+ Combines:+ 1. Structured Lattice Seeds (from crossover)+ 2. Heuristic Patterns (Grid, Ring)+ 3. Physics-based relaxation+ 4. Greedy Expansion """ n = 26 best_centers = None best_radii = None best_score = -1.0 - # Strategy list defines initialization patterns- # We try structured patterns that are close to optimal packing densities- # plus random restarts to catch other variations.- strategies = [- 'hex', # Hexagonal lattice chunk- 'grid', # 5x5 grid + 1- 'ring', # Concentric rings (from inspiration)- 'random', # Pure random- 'random',- 'random',- 'random',- 'random'- ]-- for strat in strategies:- # 1. Initialization- if strat == 'grid':- centers = init_grid_plus_one(n)- elif strat == 'hex':- centers = init_hex_approx(n)- elif strat == 'ring':- centers = init_ring_pattern(n)- else:- centers = np.random.rand(n, 2)- - # Add small noise to break perfect symmetries and allow physics to slide- centers += (np.random.rand(n, 2) - 0.5) * 0.02- centers = np.clip(centers, 0.01, 0.99)- - # 2. Physics Simulation- # Run dynamics to settle circles into a packed state- centers, radii = run_physics_simulation(n, centers)- - # 3. Refinement (Maximize Radii)+ # Generate a diverse set of initial configurations+ seeds = get_all_seeds(n)+ + for centers in seeds:+ # 1. Physics Simulation+ # Run dynamics to settle circles+ # Add slight noise to break perfect symmetries if it's too regular+ centers_noisy = centers + (np.random.rand(n, 2) - 0.5) * 0.002+ centers_noisy = np.clip(centers_noisy, 0.01, 0.99)+ + sim_centers, sim_radii = run_physics_simulation(n, centers_noisy)+ + # 2. Refinement (Maximize Radii) # Strictly enforce constraints and expand to fill gaps- radii = maximize_radii_for_centers(centers, initial_radii=radii)- - score = np.sum(radii)+ final_radii = maximize_radii_for_centers(sim_centers, initial_radii=sim_radii)+ + score = np.sum(final_radii) if score > best_score: best_score = score- best_centers = centers.copy()- best_radii = radii.copy()+ best_centers = sim_centers.copy()+ best_radii = final_radii.copy() return best_centers, best_radii++def get_all_seeds(n):+ """Generates a list of initial center positions (n, 2)."""+ seeds = []+ + # 1. Lattice Patterns (from crossover source)+ # These are specific row-based hex-like packings known to yield good results+ patterns = [+ [5, 5, 6, 5, 5], # 26: Symmetric hex approx+ [6, 5, 6, 5, 4], # 26: Staggered+ [5, 6, 5, 5, 5], # 26+ [5, 5, 5, 5, 6], # 26+ [5, 5, 5, 5, 5, 1], # 26: Quasi-square with outlier+ [6, 6, 6, 6, 2], # 26+ [4, 5, 6, 6, 5] # 26+ ]+ for p in patterns:+ seeds.append(generate_lattice_from_rows(p, n))+ + # 2. Grid Plus One (heuristic)+ seeds.append(init_grid_plus_one(n))+ + # 3. Ring Pattern (heuristic)+ seeds.append(init_ring_pattern(n))+ + # 4. Hex Approx (procedural)+ seeds.append(init_hex_approx(n))+ + # 5. Random restarts+ for _ in range(4):+ seeds.append(np.random.rand(n, 2))+ + return seeds++def generate_lattice_from_rows(rows, n_target):+ """Generates centers based on row counts, centered and scaled."""+ centers = []+ dy = np.sqrt(3) / 2+ + for i, count in enumerate(rows):+ y = i * dy+ # Offset odd rows+ offset = 0.5 if i % 2 == 1 else 0.0+ for j in range(count):+ x = offset + j+ centers.append([x, y])+ + centers = np.array(centers)+ + # Normalize to [0.1, 0.9] to stay safely inside box+ if len(centers) > 0:+ min_c = np.min(centers, axis=0)+ max_c = np.max(centers, axis=0)+ range_c = max_c - min_c+ + scale_denom = np.max(range_c)+ if scale_denom < 1e-9: scale_denom = 1.0+ + # Scale to fit in 0.8 box centered at 0.5 (leaving 0.1 margin)+ scale = 0.8 / scale_denom+ centers = (centers - min_c) * scale + 0.1+ + # Adjust count to match n+ if len(centers) > n_target:+ centers = centers[:n_target]+ elif len(centers) < n_target:+ # Add random points if pattern produced too few+ extra = n_target - len(centers)+ centers = np.vstack([centers, np.random.rand(extra, 2) * 0.8 + 0.1])+ + return centers def init_grid_plus_one(n): """5x5 grid plus one extra circle.""" x = np.linspace(0.1, 0.9, 5) y = np.linspace(0.1, 0.9, 5) xv, yv = np.meshgrid(x, y) centers = np.column_stack((xv.flatten(), yv.flatten()))- # Add 26th circle near center but offset- extra = np.array([[0.52, 0.52]])+ extra = np.array([[0.52, 0.52]]) # Slightly off center if len(centers) < n: centers = np.vstack((centers, extra)) return centers[:n] def init_ring_pattern(n): """Concentric rings pattern.""" centers = np.zeros((n, 2)) centers[0] = [0.5, 0.5]- # Inner ring of 8+ # Inner ring for i in range(8): angle = 2 * np.pi * i / 8 centers[i + 1] = [0.5 + 0.25 * np.cos(angle), 0.5 + 0.25 * np.sin(angle)] # Outer ring remaining = n - 9- for i in range(remaining):- angle = 2 * np.pi * i / remaining- centers[i + 9] = [0.5 + 0.45 * np.cos(angle), 0.5 + 0.45 * np.sin(angle)]+ if remaining > 0:+ for i in range(remaining):+ angle = 2 * np.pi * i / remaining+ centers[i + 9] = [0.5 + 0.45 * np.cos(angle), 0.5 + 0.45 * np.sin(angle)] return centers def init_hex_approx(n):- """Triangular/Hexagonal lattice filling."""+ """Procedural hexagonal fill.""" centers = []- # Approx spacing for dense packing delta = 0.18 y = 0.1 row = 0 while len(centers) < n and y < 0.95: if row % 2 == 0: x_start = 0.1 else: x_start = 0.1 + delta * 0.5- x = x_start while len(centers) < n and x < 0.95: centers.append([x, y]) x += delta- y += delta * 0.866 # sqrt(3)/2+ y += delta * 0.866 row += 1- centers = np.array(centers) if len(centers) < n:- # Fill remaining with random if grid didn't fit enough fill = np.random.rand(n - len(centers), 2) centers = np.vstack((centers, fill)) return centers[:n] def run_physics_simulation(n, initial_centers): """ Simulate soft-body circles to find a good packing arrangement. """ centers = initial_centers.copy()- radii = np.ones(n) * 0.05 # Start small- - # Simulation params- iterations = 1000+ radii = np.ones(n) * 0.05 + + # Parameters+ iterations = 1200 dt = 0.01 damping = 0.8 growth_rate = 0.0005 velocities = np.zeros_like(centers) for _ in range(iterations): # 1. Distances delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(delta**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # 2. Overlaps- # overlap = (ri + rj) - dist radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :] overlaps = radii_sum - dists np.fill_diagonal(overlaps, -1.0) # 3. Forces forces = np.zeros_like(centers) - # Circle-Circle+ # Circle-Circle Repulsion mask = overlaps > 0 if np.any(mask):- # Safe normalization safe_dists = np.where(dists < 1e-6, 1.0, dists) dirs = delta / safe_dists[:, :, np.newaxis] - # Force magnitude proportional to overlap f_mag = overlaps * 50.0- f_mag = np.maximum(f_mag, 0) # Apply mask implicitly+ f_mag = np.maximum(f_mag, 0) forces += np.sum(dirs * f_mag[:, :, np.newaxis], axis=1) # Wall Repulsion- # Left l_ov = np.maximum(radii - centers[:, 0], 0) forces[:, 0] += l_ov * 100.0- # Right r_ov = np.maximum(radii - (1 - centers[:, 0]), 0) forces[:, 0] -= r_ov * 100.0- # Bottom b_ov = np.maximum(radii - centers[:, 1], 0) forces[:, 1] += b_ov * 100.0- # Top t_ov = np.maximum(radii - (1 - centers[:, 1]), 0) forces[:, 1] -= t_ov * 100.0 # 4. Integrate velocities = velocities * damping + forces * dt centers += velocities * dt centers = np.clip(centers, 0.0, 1.0) # 5. Radius Dynamics- # Pressure based on overlaps total_overlap = np.sum(np.maximum(overlaps, 0), axis=1) wall_overlap = l_ov + r_ov + b_ov + t_ov pressure = total_overlap + wall_overlap dr = np.zeros(n)- # Shrink if under pressure dr[pressure > 0] = -pressure[pressure > 0]- # Grow if free dr[pressure == 0] = growth_rate radii += dr * dt radii = np.maximum(radii, 0.001) return centers, radii def maximize_radii_for_centers(centers, initial_radii=None): """ Given fixed centers, compute the maximum possible radii that satisfy all constraints.- It resolves overlaps and then expands circles to fill gaps. """ n = centers.shape[0] # Distance to walls- # r <= x, r <= 1-x, etc. d_walls_x = np.minimum(centers[:, 0], 1 - centers[:, 0]) d_walls_y = np.minimum(centers[:, 1], 1 - centers[:, 1]) max_wall_radii = np.minimum(d_walls_x, d_walls_y) if initial_radii is not None: radii = initial_radii.copy() else: radii = max_wall_radii.copy() - # Ensure starting valid against walls radii = np.minimum(radii, max_wall_radii) - # Phase 1: Shrink to resolve circle-circle overlaps- # Iterative relaxation+ # Phase 1: Shrink to resolve overlaps for _ in range(200): changed = False for i in range(n): for j in range(i + 1, n): delta = centers[i] - centers[j] dist = np.sqrt(np.sum(delta**2)) sum_r = radii[i] + radii[j] if sum_r > dist:- # Overlap overlap = sum_r - dist- # Shrink both roughly equally to fix- # but check for small radii to avoid issues if sum_r > 1e-9:- # Proportional shrink fi = radii[i] / sum_r fj = radii[j] / sum_r- radii[i] -= overlap * fi * 1.0001 # Small bias to ensure separation+ # Shrink with small bias+ radii[i] -= overlap * fi * 1.0001 radii[j] -= overlap * fj * 1.0001 else: radii[i] -= overlap * 0.5 * 1.0001 radii[j] -= overlap * 0.5 * 1.0001 changed = True if not changed: break # Phase 2: Expand to fill gaps- # Iterate to maximize radii- # r_i = min(wall_i, min_j(dist_ij - r_j))- - # Pre-calculate distances dists_mat = np.zeros((n, n)) for i in range(n): for j in range(i + 1, n): d = np.sqrt(np.sum((centers[i] - centers[j])**2)) dists_mat[i, j] = d dists_mat[j, i] = d- np.fill_diagonal(dists_mat, np.inf) # Ignore self- - for _ in range(100):+ np.fill_diagonal(dists_mat, np.inf)+ + for _ in range(200): changed = False for i in range(n): # Max allowed by walls limit = max_wall_radii[i] # Max allowed by neighbors: r_i <= dist_ij - r_j- # So r_i <= min(dist_ij - r_j) constraints = dists_mat[i] - radii min_constraint = np.min(constraints) new_r = min(limit, min_constraint)- # Ensure non-negative (should be if centers disjoint) new_r = max(new_r, 0.0) - # Update if we can grow (or must shrink due to some other update)- # We add a tiny epsilon safety margin+ # Set target with tiny epsilon buffer for numerical stability target = new_r - 1e-10 - if abs(radii[i] - target) > 1e-7:+ if abs(radii[i] - target) > 1e-8: radii[i] = target changed = True if not changed: break return radii # EVOLVE-BLOCK-END # This part remains fixed (not evolved) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869{ "context_window": null, "messages": [ { "role": "system", "content": "You are an expert mathematician specializing in circle packing\nproblems and computational geometry. The best known result for the sum of radii\nwhen packing 26 circles in a unit square is around 2.635.\n\nYour objective:\n- Maximize sum of radii for 26 non-overlapping circles in [0,1] x [0,1].\n\nHard constraints:\n- All circles must be disjoint.\n- All circles must lie fully inside the unit square.\n- Return valid output in the evaluator contract.\n\nUseful directions:\n1. Hybrid arrangements with variable radii.\n2. Better edge/corner utilization.\n3. Careful placement + robust radius assignment.\n4. Iterative local improvements and perturbation heuristics.\n5. Stable numeric checks to avoid invalid overlap/out-of-bound states.\n\nBe creative but prioritize correctness and stable improvements.\n\nYou are given multiple code scripts implementing the same algorithm.\nYou are tasked with generating a new code snippet that combines these code scripts in a way that is more efficient. \nI.e. perform crossover between the code scripts.\nProvide the complete new program code.\nYou MUST repond using a short summary name, description and the full code:\n\n<NAME>\nA shortened name summarizing the code you are proposing. Lowercase, no spaces, underscores allowed.\n</NAME>\n\n<DESCRIPTION>\nA description and argumentation process of the code you are proposing.\n</DESCRIPTION>\n\n<CODE>\n```{language}\n# The new rewritten program here.\n```\n</CODE>\n\n* Keep the markers \"EVOLVE-BLOCK-START\" and \"EVOLVE-BLOCK-END\" in the code. Do not change the code outside of these markers.\n* Make sure your rewritten program maintains the same inputs and outputs as the original program, but with improved internal implementation.\n* Make sure the file still runs after your changes.\n* Use the <NAME>, <DESCRIPTION>, and <CODE> delimiters to structure your response. It will be parsed afterwards." }, { "role": "user", "content": "Here are the performance metrics of a set of prioviously implemented programs:\n\n# Prior programs\n\n```python\n# EVOLVE-BLOCK-START\n\"\"\"Constructor-based circle packing for n=26 circles\"\"\"\n\nimport numpy as np\n\ndef construct_packing():\n \"\"\"\n Construct a specific arrangement of 26 circles in a unit square\n that attempts to maximize the sum of their radii using a \n physics-based relaxation algorithm with restarts.\n\n Returns:\n Tuple of (centers, radii)\n centers: np.array of shape (26, 2)\n radii: np.array of shape (26)\n \"\"\"\n n = 26\n best_centers = None\n best_radii = None\n best_score = -1.0\n\n # Run multiple restarts to find global optima\n # 26 circles have many local optima, so random restarts are crucial\n num_restarts = 8\n \n for _ in range(num_restarts):\n centers, radii = run_physics_simulation(n)\n \n # Enforce strict constraints based on the simulation result\n radii = compute_max_radii(centers, initial_radii=radii)\n \n score = np.sum(radii)\n if score > best_score:\n best_score = score\n best_centers = centers.copy()\n best_radii = radii.copy()\n\n return best_centers, best_radii\n\ndef run_physics_simulation(n):\n \"\"\"\n Simulates circles as soft bodies that repel each other and grow.\n \"\"\"\n # Initialize random positions\n centers = np.random.rand(n, 2)\n # Start with small random radii to avoid huge initial explosions\n radii = np.random.rand(n) * 0.05 + 0.01\n \n # Physics parameters\n iterations = 800\n dt = 0.01\n damping = 0.9\n growth_rate = 0.0002\n \n velocities = np.zeros_like(centers)\n \n for _ in range(iterations):\n # Calculate pair distances\n # dist_matrix: (n, n)\n delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]\n dist_sq = np.sum(delta**2, axis=2)\n \n # Avoid division by zero\n np.fill_diagonal(dist_sq, 1.0)\n dists = np.sqrt(dist_sq)\n \n # Calculate overlaps: (r_i + r_j) - dist\n # Positive value means overlap\n radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :]\n overlaps = radii_sum - dists\n np.fill_diagonal(overlaps, -1.0) # No self-overlap\n \n # Forces\n forces = np.zeros_like(centers)\n \n # 1. Circle-Circle Repulsion\n # Mask for interacting pairs\n # Interaction horizon: include slight non-overlapping neighbors to maintain spacing\n \n # Normalize delta\n # If dist is very small, use random direction (or zero, but normalized needs care)\n small_dist = dists < 1e-6\n dists_safe = np.where(small_dist, 1.0, dists)\n delta_norm = delta / dists_safe[:, :, np.newaxis]\n \n # Force magnitude\n # Stronger repulsion if overlapping\n f_mag = np.maximum(overlaps, 0) * 50.0 \n \n # Sum forces\n forces += np.sum(delta_norm * f_mag[:, :, np.newaxis], axis=1)\n \n # 2. Wall Repulsion\n # Walls are at 0 and 1\n # Left (x=0)\n l_overlap = np.maximum(radii - centers[:, 0], 0)\n forces[:, 0] += l_overlap * 100.0\n \n # Right (x=1)\n r_overlap = np.maximum(radii - (1.0 - centers[:, 0]), 0)\n forces[:, 0] -= r_overlap * 100.0\n \n # Bottom (y=0)\n b_overlap = np.maximum(radii - centers[:, 1], 0)\n forces[:, 1] += b_overlap * 100.0\n \n # Top (y=1)\n t_overlap = np.maximum(radii - (1.0 - centers[:, 1]), 0)\n forces[:, 1] -= t_overlap * 100.0\n \n # 3. Update Velocities and Positions\n velocities = velocities * damping + forces * dt\n centers += velocities * dt\n \n # Hard constraint on centers to keep them in [0,1]\n centers = np.clip(centers, 0.0, 1.0)\n \n # 4. Radius Dynamics\n # If circle is under pressure (overlap > 0), shrink\n # If circle is free, grow\n \n # Max overlap for each circle (sum of all overlaps)\n circle_pressure = np.sum(np.maximum(overlaps, 0), axis=1)\n \n # Add wall pressure\n wall_pressure = l_overlap + r_overlap + b_overlap + t_overlap\n total_pressure = circle_pressure + wall_pressure\n \n # Dynamics\n # If pressure > 0, shrink fast to resolve\n # If pressure == 0, grow slowly to fill space\n \n dr = np.zeros(n)\n shrink_mask = total_pressure > 0\n dr[shrink_mask] = -total_pressure[shrink_mask] * 0.5 # Shrink rate\n dr[~shrink_mask] = growth_rate\n \n radii += dr * dt\n radii = np.maximum(radii, 0.001) # Min radius\n \n return centers, radii\n\ndef compute_max_radii(centers, initial_radii=None):\n \"\"\"\n Refine radii for fixed centers to ensure no overlaps.\n Starting from initial_radii if provided helps preserve the\n relative sizes found during simulation.\n \"\"\"\n n = centers.shape[0]\n \n # Calculate max possible radius for each circle based on walls\n # Distance to closest wall\n max_wall_radii = np.minimum(centers[:, 0], 1 - centers[:, 0])\n max_wall_radii = np.minimum(max_wall_radii, centers[:, 1])\n max_wall_radii = np.minimum(max_wall_radii, 1 - centers[:, 1])\n \n if initial_radii is not None:\n # Start from simulation proposal, but clipped to walls\n radii = np.minimum(initial_radii, max_wall_radii)\n else:\n # Default fallback\n radii = max_wall_radii.copy()\n \n # Iteratively resolve overlaps\n # We want to keep the ratios of radii similar to input if possible, \n # but strictly satisfy constraints.\n \n # 100 iterations of relaxation\n for _ in range(100):\n valid = True\n for i in range(n):\n for j in range(i + 1, n):\n dist = np.sqrt(np.sum((centers[i] - centers[j])**2))\n sum_r = radii[i] + radii[j]\n \n if sum_r > dist - 1e-10:\n valid = False\n # Overlap\n overlap = sum_r - dist\n \n if sum_r > 1e-9:\n # Shrink proportional to current size (maintains relative scale)\n fraction_i = radii[i] / sum_r\n fraction_j = radii[j] / sum_r\n \n # Apply correction with tiny safety buffer\n radii[i] -= overlap * fraction_i * 1.0001\n radii[j] -= overlap * fraction_j * 1.0001\n else:\n radii[i] -= overlap * 0.5\n radii[j] -= overlap * 0.5\n \n # Clamp to walls again to be safe\n radii = np.minimum(radii, max_wall_radii)\n \n if valid:\n break\n \n return radii\n\n# EVOLVE-BLOCK-END\n\n\n# This part remains fixed (not evolved)\ndef run_packing():\n \"\"\"Run the circle packing constructor for n=26\"\"\"\n centers, radii = construct_packing()\n # Calculate the sum of radii\n sum_radii = np.sum(radii)\n return centers, radii, sum_radii\n\n```\n\nPerformance metrics:\nCombined score to maximize: 1.0181431\ncenters_str: centers[0] = (0.6080, 0.0552)\n centers[1] = (0.0527, 0.2557)\n centers[2] = (0.8339, 0.3579)\n centers[3] = (0.2220, 0.5293)\n centers[4] = (0.7050, 0.4991)\n centers[5] = (0.7348, 0.9502)\n centers[6] = (0.7240, 0.8565)\n centers[7] = (0.5412, 0.1217)\n centers[8] = (0.0340, 0.8879)\n centers[9] = (0.2432, 0.1811)\n centers[10] = (0.2035, 0.6649)\n centers[11] = (0.1365, 0.6114)\n centers[12] = (0.4386, 0.9736)\n centers[13] = (0.9232, 0.6684)\n centers[14] = (0.1083, 0.9439)\n centers[15] = (0.7871, 0.1171)\n centers[16] = (0.4845, 0.0562)\n centers[17] = (0.1379, 0.5172)\n centers[18] = (0.5347, 0.9028)\n centers[19] = (0.5067, 0.2066)\n centers[20] = (0.6188, 0.6419)\n centers[21] = (0.7622, 0.4333)\n centers[22] = (0.9297, 0.1174)\n centers[23] = (0.1669, 0.7696)\n centers[24] = (0.4029, 0.1816)\n centers[25] = (0.3993, 0.3301); num_circles: 26; aux_aux_metric_eval_success: 1.0000000; aux_aux_metric_error_code: 0.0000000; aux_aux_metric_error_message_length: 0.0000000; aux_aux_metric_error_detail_length: 0.0000000; aux_aux_metric_non_numeric_dropped_count: 0.0000000\n\n```python\n# EVOLVE-BLOCK-START\n\"\"\"Constructor-based circle packing for n=26 circles\"\"\"\n\nimport numpy as np\n\ndef construct_packing():\n \"\"\"\n Construct a specific arrangement of 26 circles in a unit square\n that attempts to maximize the sum of their radii using a\n physics-based relaxation algorithm with varied initial lattice patterns.\n\n Returns:\n Tuple of (centers, radii)\n centers: np.array of shape (26, 2)\n radii: np.array of shape (26)\n \"\"\"\n n = 26\n best_centers = None\n best_radii = None\n best_score = -1.0\n\n # Define lattice patterns to seed the physics simulation\n # These hexagonal-like arrangements are more likely to lead to dense packings\n patterns = [\n [5, 5, 6, 5, 5], # 26: Symmetric hex\n [6, 5, 6, 5, 4], # 26: Staggered\n [5, 6, 5, 5, 5], # 26\n [5, 5, 5, 5, 6], # 26\n [5, 5, 5, 5, 5, 1], # 26: Quasi-square with outlier\n [6, 6, 6, 6, 2], # 26\n [4, 5, 6, 6, 5] # 26\n ]\n\n seeds = []\n for p in patterns:\n seeds.append(generate_lattice(p))\n\n # Also add some random restarts\n for _ in range(3):\n seeds.append(None)\n\n for seed in seeds:\n centers, radii = run_physics_simulation(n, initial_centers=seed)\n\n # Enforce strict constraints based on the simulation result\n radii = compute_max_radii(centers, initial_radii=radii)\n\n score = np.sum(radii)\n if score > best_score:\n best_score = score\n best_centers = centers.copy()\n best_radii = radii.copy()\n\n return best_centers, best_radii\n\ndef generate_lattice(rows):\n \"\"\"Generates a hexagonal-like lattice based on row counts.\"\"\"\n centers = []\n dy = np.sqrt(3) / 2\n\n for i, count in enumerate(rows):\n y = i * dy\n # Offset odd rows\n offset = 0.5 if i % 2 == 1 else 0.0\n for j in range(count):\n x = offset + j\n centers.append([x, y])\n\n centers = np.array(centers)\n\n # Normalize to [0.1, 0.9] to stay inside and allow growth\n if len(centers) > 0:\n min_c = np.min(centers, axis=0)\n max_c = np.max(centers, axis=0)\n range_c = max_c - min_c\n\n # Avoid division by zero if single row/column\n scale_denom = np.max(range_c)\n if scale_denom < 1e-9: scale_denom = 1.0\n\n scale = 0.8 / scale_denom\n centers = (centers - min_c) * scale + 0.1\n\n # Handle mismatches in count\n if len(centers) > 26:\n centers = centers[:26]\n elif len(centers) < 26:\n extra = 26 - len(centers)\n if len(centers) > 0:\n # Add random points near center\n centers = np.vstack([centers, np.random.rand(extra, 2) * 0.5 + 0.25])\n else:\n centers = np.random.rand(26, 2)\n\n return centers\n\ndef run_physics_simulation(n, initial_centers=None):\n \"\"\"\n Simulates circles as soft bodies that repel each other and grow.\n Accepts initial_centers to seed the simulation.\n \"\"\"\n if initial_centers is not None:\n centers = initial_centers.copy()\n # Uniform small radii for lattice seeds to preserve symmetry\n radii = np.ones(n) * 0.01\n else:\n # Initialize random positions\n centers = np.random.rand(n, 2)\n # Random small radii\n radii = np.random.rand(n) * 0.05 + 0.01\n\n # Physics parameters\n # More iterations and smaller timestep for higher quality convergence\n iterations = 2000\n dt = 0.005\n damping = 0.9\n growth_rate = 0.0005\n\n velocities = np.zeros_like(centers)\n\n for _ in range(iterations):\n # Calculate pair distances\n delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]\n dist_sq = np.sum(delta**2, axis=2)\n\n # Avoid division by zero\n np.fill_diagonal(dist_sq, 1.0)\n dists = np.sqrt(dist_sq)\n\n # Calculate overlaps: (r_i + r_j) - dist\n radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :]\n overlaps = radii_sum - dists\n np.fill_diagonal(overlaps, -1.0) # No self-overlap\n\n # Forces\n forces = np.zeros_like(centers)\n\n # 1. Circle-Circle Repulsion\n small_dist = dists < 1e-6\n dists_safe = np.where(small_dist, 1.0, dists)\n delta_norm = delta / dists_safe[:, :, np.newaxis]\n\n # Force magnitude\n f_mag = np.maximum(overlaps, 0) * 50.0\n\n # Sum forces\n forces += np.sum(delta_norm * f_mag[:, :, np.newaxis], axis=1)\n\n # 2. Wall Repulsion\n l_overlap = np.maximum(radii - centers[:, 0], 0)\n forces[:, 0] += l_overlap * 100.0\n\n r_overlap = np.maximum(radii - (1.0 - centers[:, 0]), 0)\n forces[:, 0] -= r_overlap * 100.0\n\n b_overlap = np.maximum(radii - centers[:, 1], 0)\n forces[:, 1] += b_overlap * 100.0\n\n t_overlap = np.maximum(radii - (1.0 - centers[:, 1]), 0)\n forces[:, 1] -= t_overlap * 100.0\n\n # 3. Update Velocities and Positions\n velocities = velocities * damping + forces * dt\n centers += velocities * dt\n\n # Hard constraint on centers to keep them in [0,1]\n centers = np.clip(centers, 0.0, 1.0)\n\n # 4. Radius Dynamics\n circle_pressure = np.sum(np.maximum(overlaps, 0), axis=1)\n wall_pressure = l_overlap + r_overlap + b_overlap + t_overlap\n total_pressure = circle_pressure + wall_pressure\n\n dr = np.zeros(n)\n shrink_mask = total_pressure > 0\n dr[shrink_mask] = -total_pressure[shrink_mask] * 0.5\n dr[~shrink_mask] = growth_rate\n\n radii += dr * dt\n radii = np.maximum(radii, 0.001)\n\n return centers, radii\n\ndef compute_max_radii(centers, initial_radii=None):\n \"\"\"\n Refine radii for fixed centers to ensure no overlaps.\n Starting from initial_radii if provided helps preserve the\n relative sizes found during simulation.\n \"\"\"\n n = centers.shape[0]\n\n # Calculate max possible radius for each circle based on walls\n # Distance to closest wall\n max_wall_radii = np.minimum(centers[:, 0], 1 - centers[:, 0])\n max_wall_radii = np.minimum(max_wall_radii, centers[:, 1])\n max_wall_radii = np.minimum(max_wall_radii, 1 - centers[:, 1])\n\n if initial_radii is not None:\n # Start from simulation proposal, but clipped to walls\n radii = np.minimum(initial_radii, max_wall_radii)\n else:\n # Default fallback\n radii = max_wall_radii.copy()\n\n # Iteratively resolve overlaps\n # We want to keep the ratios of radii similar to input if possible,\n # but strictly satisfy constraints.\n\n # 100 iterations of relaxation\n for _ in range(100):\n valid = True\n for i in range(n):\n for j in range(i + 1, n):\n dist = np.sqrt(np.sum((centers[i] - centers[j])**2))\n sum_r = radii[i] + radii[j]\n\n if sum_r > dist - 1e-10:\n valid = False\n # Overlap\n overlap = sum_r - dist\n\n if sum_r > 1e-9:\n # Shrink proportional to current size (maintains relative scale)\n fraction_i = radii[i] / sum_r\n fraction_j = radii[j] / sum_r\n\n # Apply correction with tiny safety buffer\n radii[i] -= overlap * fraction_i * 1.0001\n radii[j] -= overlap * fraction_j * 1.0001\n else:\n radii[i] -= overlap * 0.5\n radii[j] -= overlap * 0.5\n\n # Clamp to walls again to be safe\n radii = np.minimum(radii, max_wall_radii)\n\n if valid:\n break\n\n return radii\n\n# EVOLVE-BLOCK-END\n\n\n# This part remains fixed (not evolved)\ndef run_packing():\n \"\"\"Run the circle packing constructor for n=26\"\"\"\n centers, radii = construct_packing()\n # Calculate the sum of radii\n sum_radii = np.sum(radii)\n return centers, radii, sum_radii\n```\n\nPerformance metrics:\nCombined score to maximize: 1.0019459\ncenters_str: centers[0] = (0.7373, 0.7048)\n centers[1] = (0.4800, 0.2119)\n centers[2] = (0.3808, 0.2986)\n centers[3] = (0.5326, 0.5287)\n centers[4] = (0.0213, 0.0160)\n centers[5] = (0.9012, 0.3341)\n centers[6] = (0.6311, 0.2137)\n centers[7] = (0.1332, 0.6037)\n centers[8] = (0.5017, 0.3199)\n centers[9] = (0.1780, 0.1574)\n centers[10] = (0.3485, 0.8765)\n centers[11] = (0.1829, 0.6818)\n centers[12] = (0.3086, 0.2948)\n centers[13] = (0.4051, 0.3874)\n centers[14] = (0.8599, 0.5527)\n centers[15] = (0.1606, 0.0435)\n centers[16] = (0.6345, 0.2772)\n centers[17] = (0.6261, 0.9468)\n centers[18] = (0.2566, 0.2205)\n centers[19] = (0.3655, 0.1126)\n centers[20] = (0.9521, 0.1037)\n centers[21] = (0.6512, 0.7410)\n centers[22] = (0.4609, 0.4966)\n centers[23] = (0.0428, 0.4337)\n centers[24] = (0.1574, 0.9154)\n centers[25] = (0.2564, 0.0521); num_circles: 26; aux_aux_metric_eval_success: 1.0000000; aux_aux_metric_error_code: 0.0000000; aux_aux_metric_error_message_length: 0.0000000; aux_aux_metric_error_detail_length: 0.0000000; aux_aux_metric_non_numeric_dropped_count: 0.0000000\n\n\n# Current program\n\nHere is the current program we are trying to improve (you will need to propose a new program with the same inputs and outputs as the original program, but with improved internal implementation):\n\n```python\n# EVOLVE-BLOCK-START\n\"\"\"Constructor-based circle packing for n=26 circles\"\"\"\n\nimport numpy as np\n\ndef construct_packing():\n \"\"\"\n Construct a specific arrangement of 26 circles in a unit square\n that attempts to maximize the sum of their radii.\n \n Uses a hybrid approach:\n 1. Diverse Initialization (Grid, Hex, Rings, Random) to find different basins.\n 2. Physics-based relaxation to optimize packing density.\n 3. Greedy expansion/shrinking to strictly enforce constraints while maximizing size.\n\n Returns:\n Tuple of (centers, radii)\n centers: np.array of shape (26, 2)\n radii: np.array of shape (26)\n \"\"\"\n n = 26\n best_centers = None\n best_radii = None\n best_score = -1.0\n \n # Strategy list defines initialization patterns\n # We try structured patterns that are close to optimal packing densities\n # plus random restarts to catch other variations.\n strategies = [\n 'hex', # Hexagonal lattice chunk\n 'grid', # 5x5 grid + 1\n 'ring', # Concentric rings (from inspiration)\n 'random', # Pure random\n 'random',\n 'random',\n 'random',\n 'random'\n ]\n\n for strat in strategies:\n # 1. Initialization\n if strat == 'grid':\n centers = init_grid_plus_one(n)\n elif strat == 'hex':\n centers = init_hex_approx(n)\n elif strat == 'ring':\n centers = init_ring_pattern(n)\n else:\n centers = np.random.rand(n, 2)\n \n # Add small noise to break perfect symmetries and allow physics to slide\n centers += (np.random.rand(n, 2) - 0.5) * 0.02\n centers = np.clip(centers, 0.01, 0.99)\n \n # 2. Physics Simulation\n # Run dynamics to settle circles into a packed state\n centers, radii = run_physics_simulation(n, centers)\n \n # 3. Refinement (Maximize Radii)\n # Strictly enforce constraints and expand to fill gaps\n radii = maximize_radii_for_centers(centers, initial_radii=radii)\n \n score = np.sum(radii)\n if score > best_score:\n best_score = score\n best_centers = centers.copy()\n best_radii = radii.copy()\n\n return best_centers, best_radii\n\ndef init_grid_plus_one(n):\n \"\"\"5x5 grid plus one extra circle.\"\"\"\n x = np.linspace(0.1, 0.9, 5)\n y = np.linspace(0.1, 0.9, 5)\n xv, yv = np.meshgrid(x, y)\n centers = np.column_stack((xv.flatten(), yv.flatten()))\n # Add 26th circle near center but offset\n extra = np.array([[0.52, 0.52]])\n if len(centers) < n:\n centers = np.vstack((centers, extra))\n return centers[:n]\n\ndef init_ring_pattern(n):\n \"\"\"Concentric rings pattern.\"\"\"\n centers = np.zeros((n, 2))\n centers[0] = [0.5, 0.5]\n # Inner ring of 8\n for i in range(8):\n angle = 2 * np.pi * i / 8\n centers[i + 1] = [0.5 + 0.25 * np.cos(angle), 0.5 + 0.25 * np.sin(angle)]\n # Outer ring\n remaining = n - 9\n for i in range(remaining):\n angle = 2 * np.pi * i / remaining\n centers[i + 9] = [0.5 + 0.45 * np.cos(angle), 0.5 + 0.45 * np.sin(angle)]\n return centers\n\ndef init_hex_approx(n):\n \"\"\"Triangular/Hexagonal lattice filling.\"\"\"\n centers = []\n # Approx spacing for dense packing\n delta = 0.18\n y = 0.1\n row = 0\n while len(centers) < n and y < 0.95:\n if row % 2 == 0:\n x_start = 0.1\n else:\n x_start = 0.1 + delta * 0.5\n \n x = x_start\n while len(centers) < n and x < 0.95:\n centers.append([x, y])\n x += delta\n y += delta * 0.866 # sqrt(3)/2\n row += 1\n \n centers = np.array(centers)\n if len(centers) < n:\n # Fill remaining with random if grid didn't fit enough\n fill = np.random.rand(n - len(centers), 2)\n centers = np.vstack((centers, fill))\n return centers[:n]\n\ndef run_physics_simulation(n, initial_centers):\n \"\"\"\n Simulate soft-body circles to find a good packing arrangement.\n \"\"\"\n centers = initial_centers.copy()\n radii = np.ones(n) * 0.05 # Start small\n \n # Simulation params\n iterations = 1000\n dt = 0.01\n damping = 0.8\n growth_rate = 0.0005\n \n velocities = np.zeros_like(centers)\n \n for _ in range(iterations):\n # 1. Distances\n delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]\n dist_sq = np.sum(delta**2, axis=2)\n np.fill_diagonal(dist_sq, 1.0)\n dists = np.sqrt(dist_sq)\n \n # 2. Overlaps\n # overlap = (ri + rj) - dist\n radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :]\n overlaps = radii_sum - dists\n np.fill_diagonal(overlaps, -1.0)\n \n # 3. Forces\n forces = np.zeros_like(centers)\n \n # Circle-Circle\n mask = overlaps > 0\n if np.any(mask):\n # Safe normalization\n safe_dists = np.where(dists < 1e-6, 1.0, dists)\n dirs = delta / safe_dists[:, :, np.newaxis]\n \n # Force magnitude proportional to overlap\n f_mag = overlaps * 50.0\n f_mag = np.maximum(f_mag, 0) # Apply mask implicitly\n \n forces += np.sum(dirs * f_mag[:, :, np.newaxis], axis=1)\n \n # Wall Repulsion\n # Left\n l_ov = np.maximum(radii - centers[:, 0], 0)\n forces[:, 0] += l_ov * 100.0\n # Right\n r_ov = np.maximum(radii - (1 - centers[:, 0]), 0)\n forces[:, 0] -= r_ov * 100.0\n # Bottom\n b_ov = np.maximum(radii - centers[:, 1], 0)\n forces[:, 1] += b_ov * 100.0\n # Top\n t_ov = np.maximum(radii - (1 - centers[:, 1]), 0)\n forces[:, 1] -= t_ov * 100.0\n \n # 4. Integrate\n velocities = velocities * damping + forces * dt\n centers += velocities * dt\n centers = np.clip(centers, 0.0, 1.0)\n \n # 5. Radius Dynamics\n # Pressure based on overlaps\n total_overlap = np.sum(np.maximum(overlaps, 0), axis=1)\n wall_overlap = l_ov + r_ov + b_ov + t_ov\n pressure = total_overlap + wall_overlap\n \n dr = np.zeros(n)\n # Shrink if under pressure\n dr[pressure > 0] = -pressure[pressure > 0]\n # Grow if free\n dr[pressure == 0] = growth_rate\n \n radii += dr * dt\n radii = np.maximum(radii, 0.001)\n \n return centers, radii\n\ndef maximize_radii_for_centers(centers, initial_radii=None):\n \"\"\"\n Given fixed centers, compute the maximum possible radii \n that satisfy all constraints.\n It resolves overlaps and then expands circles to fill gaps.\n \"\"\"\n n = centers.shape[0]\n \n # Distance to walls\n # r <= x, r <= 1-x, etc.\n d_walls_x = np.minimum(centers[:, 0], 1 - centers[:, 0])\n d_walls_y = np.minimum(centers[:, 1], 1 - centers[:, 1])\n max_wall_radii = np.minimum(d_walls_x, d_walls_y)\n \n if initial_radii is not None:\n radii = initial_radii.copy()\n else:\n radii = max_wall_radii.copy()\n \n # Ensure starting valid against walls\n radii = np.minimum(radii, max_wall_radii)\n \n # Phase 1: Shrink to resolve circle-circle overlaps\n # Iterative relaxation\n for _ in range(200):\n changed = False\n for i in range(n):\n for j in range(i + 1, n):\n delta = centers[i] - centers[j]\n dist = np.sqrt(np.sum(delta**2))\n sum_r = radii[i] + radii[j]\n \n if sum_r > dist:\n # Overlap\n overlap = sum_r - dist\n # Shrink both roughly equally to fix\n # but check for small radii to avoid issues\n if sum_r > 1e-9:\n # Proportional shrink\n fi = radii[i] / sum_r\n fj = radii[j] / sum_r\n radii[i] -= overlap * fi * 1.0001 # Small bias to ensure separation\n radii[j] -= overlap * fj * 1.0001\n else:\n radii[i] -= overlap * 0.5 * 1.0001\n radii[j] -= overlap * 0.5 * 1.0001\n changed = True\n if not changed:\n break\n \n # Phase 2: Expand to fill gaps\n # Iterate to maximize radii\n # r_i = min(wall_i, min_j(dist_ij - r_j))\n \n # Pre-calculate distances\n dists_mat = np.zeros((n, n))\n for i in range(n):\n for j in range(i + 1, n):\n d = np.sqrt(np.sum((centers[i] - centers[j])**2))\n dists_mat[i, j] = d\n dists_mat[j, i] = d\n np.fill_diagonal(dists_mat, np.inf) # Ignore self\n \n for _ in range(100):\n changed = False\n for i in range(n):\n # Max allowed by walls\n limit = max_wall_radii[i]\n \n # Max allowed by neighbors: r_i <= dist_ij - r_j\n # So r_i <= min(dist_ij - r_j)\n constraints = dists_mat[i] - radii\n min_constraint = np.min(constraints)\n \n new_r = min(limit, min_constraint)\n # Ensure non-negative (should be if centers disjoint)\n new_r = max(new_r, 0.0)\n \n # Update if we can grow (or must shrink due to some other update)\n # We add a tiny epsilon safety margin\n target = new_r - 1e-10\n \n if abs(radii[i] - target) > 1e-7:\n radii[i] = target\n changed = True\n \n if not changed:\n break\n \n return radii\n\n# EVOLVE-BLOCK-END\n\n\n# This part remains fixed (not evolved)\ndef run_packing():\n \"\"\"Run the circle packing constructor for n=26\"\"\"\n centers, radii = construct_packing()\n # Calculate the sum of radii\n sum_radii = np.sum(radii)\n return centers, radii, sum_radii\n\n```\n\nHere are the performance metrics of the program:\n\nCombined score to maximize: 2.3731927\ncenters_str: centers[0] = (0.1097, 0.1047)\n centers[1] = (0.2946, 0.0922)\n centers[2] = (0.4984, 0.1047)\n centers[3] = (0.7060, 0.0932)\n centers[4] = (0.8902, 0.1090)\n centers[5] = (0.0941, 0.2974)\n centers[6] = (0.2973, 0.3081)\n centers[7] = (0.4963, 0.2937)\n centers[8] = (0.7034, 0.3005)\n centers[9] = (0.9072, 0.3097)\n centers[10] = (0.0907, 0.4908)\n centers[11] = (0.3024, 0.5005)\n centers[12] = (0.4846, 0.4778)\n centers[13] = (0.6935, 0.5082)\n centers[14] = (0.8994, 0.5061)\n centers[15] = (0.1020, 0.6984)\n centers[16] = (0.3098, 0.6973)\n centers[17] = (0.4923, 0.6973)\n centers[18] = (0.6967, 0.7031)\n centers[19] = (0.9042, 0.6998)\n centers[20] = (0.1047, 0.8974)\n centers[21] = (0.3000, 0.9097)\n centers[22] = (0.5089, 0.8919)\n centers[23] = (0.7023, 0.9012)\n centers[24] = (0.8961, 0.8952)\n centers[25] = (0.5340, 0.5425); num_circles: 26; aux_aux_metric_eval_success: 1.0000000; aux_aux_metric_error_code: 0.0000000; aux_aux_metric_error_message_length: 0.0000000; aux_aux_metric_error_detail_length: 0.0000000; aux_aux_metric_non_numeric_dropped_count: 0.0000000\n\n\n# Task\n\nPerform a cross-over between the code script above and the one below. Aim to combine the best parts of both code implementations that improves the score.\nAlways prioritize `combined_score`. Use `aux_*` metrics as supporting diagnostics to identify bottlenecks and guide edits toward better `combined_score` gains.\nProvide the complete new program code.\n\nIMPORTANT: Make sure your rewritten program maintains the same inputs and outputs as the original program, but with improved internal implementation.\n\n\n# Crossover Inspiration Programs\n```python\n# EVOLVE-BLOCK-START\n\"\"\"Constructor-based circle packing for n=26 circles\"\"\"\n\nimport numpy as np\n\ndef construct_packing():\n \"\"\"\n Construct a specific arrangement of 26 circles in a unit square\n that attempts to maximize the sum of their radii using a\n physics-based relaxation algorithm with varied initial lattice patterns.\n\n Returns:\n Tuple of (centers, radii)\n centers: np.array of shape (26, 2)\n radii: np.array of shape (26)\n \"\"\"\n n = 26\n best_centers = None\n best_radii = None\n best_score = -1.0\n\n # Define lattice patterns to seed the physics simulation\n # These hexagonal-like arrangements are more likely to lead to dense packings\n patterns = [\n [5, 5, 6, 5, 5], # 26: Symmetric hex\n [6, 5, 6, 5, 4], # 26: Staggered\n [5, 6, 5, 5, 5], # 26\n [5, 5, 5, 5, 6], # 26\n [5, 5, 5, 5, 5, 1], # 26: Quasi-square with outlier\n [6, 6, 6, 6, 2], # 26\n [4, 5, 6, 6, 5] # 26\n ]\n\n seeds = []\n for p in patterns:\n seeds.append(generate_lattice(p))\n\n # Also add some random restarts\n for _ in range(3):\n seeds.append(None)\n\n for seed in seeds:\n centers, radii = run_physics_simulation(n, initial_centers=seed)\n\n # Enforce strict constraints based on the simulation result\n radii = compute_max_radii(centers, initial_radii=radii)\n\n score = np.sum(radii)\n if score > best_score:\n best_score = score\n best_centers = centers.copy()\n best_radii = radii.copy()\n\n return best_centers, best_radii\n\ndef generate_lattice(rows):\n \"\"\"Generates a hexagonal-like lattice based on row counts.\"\"\"\n centers = []\n dy = np.sqrt(3) / 2\n\n for i, count in enumerate(rows):\n y = i * dy\n # Offset odd rows\n offset = 0.5 if i % 2 == 1 else 0.0\n for j in range(count):\n x = offset + j\n centers.append([x, y])\n\n centers = np.array(centers)\n\n # Normalize to [0.1, 0.9] to stay inside and allow growth\n if len(centers) > 0:\n min_c = np.min(centers, axis=0)\n max_c = np.max(centers, axis=0)\n range_c = max_c - min_c\n\n # Avoid division by zero if single row/column\n scale_denom = np.max(range_c)\n if scale_denom < 1e-9: scale_denom = 1.0\n\n scale = 0.8 / scale_denom\n centers = (centers - min_c) * scale + 0.1\n\n # Handle mismatches in count\n if len(centers) > 26:\n centers = centers[:26]\n elif len(centers) < 26:\n extra = 26 - len(centers)\n if len(centers) > 0:\n # Add random points near center\n centers = np.vstack([centers, np.random.rand(extra, 2) * 0.5 + 0.25])\n else:\n centers = np.random.rand(26, 2)\n\n return centers\n\ndef run_physics_simulation(n, initial_centers=None):\n \"\"\"\n Simulates circles as soft bodies that repel each other and grow.\n Accepts initial_centers to seed the simulation.\n \"\"\"\n if initial_centers is not None:\n centers = initial_centers.copy()\n # Uniform small radii for lattice seeds to preserve symmetry\n radii = np.ones(n) * 0.01\n else:\n # Initialize random positions\n centers = np.random.rand(n, 2)\n # Random small radii\n radii = np.random.rand(n) * 0.05 + 0.01\n\n # Physics parameters\n # More iterations and smaller timestep for higher quality convergence\n iterations = 2000\n dt = 0.005\n damping = 0.9\n growth_rate = 0.0005\n\n velocities = np.zeros_like(centers)\n\n for _ in range(iterations):\n # Calculate pair distances\n delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]\n dist_sq = np.sum(delta**2, axis=2)\n\n # Avoid division by zero\n np.fill_diagonal(dist_sq, 1.0)\n dists = np.sqrt(dist_sq)\n\n # Calculate overlaps: (r_i + r_j) - dist\n radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :]\n overlaps = radii_sum - dists\n np.fill_diagonal(overlaps, -1.0) # No self-overlap\n\n # Forces\n forces = np.zeros_like(centers)\n\n # 1. Circle-Circle Repulsion\n small_dist = dists < 1e-6\n dists_safe = np.where(small_dist, 1.0, dists)\n delta_norm = delta / dists_safe[:, :, np.newaxis]\n\n # Force magnitude\n f_mag = np.maximum(overlaps, 0) * 50.0\n\n # Sum forces\n forces += np.sum(delta_norm * f_mag[:, :, np.newaxis], axis=1)\n\n # 2. Wall Repulsion\n l_overlap = np.maximum(radii - centers[:, 0], 0)\n forces[:, 0] += l_overlap * 100.0\n\n r_overlap = np.maximum(radii - (1.0 - centers[:, 0]), 0)\n forces[:, 0] -= r_overlap * 100.0\n\n b_overlap = np.maximum(radii - centers[:, 1], 0)\n forces[:, 1] += b_overlap * 100.0\n\n t_overlap = np.maximum(radii - (1.0 - centers[:, 1]), 0)\n forces[:, 1] -= t_overlap * 100.0\n\n # 3. Update Velocities and Positions\n velocities = velocities * damping + forces * dt\n centers += velocities * dt\n\n # Hard constraint on centers to keep them in [0,1]\n centers = np.clip(centers, 0.0, 1.0)\n\n # 4. Radius Dynamics\n circle_pressure = np.sum(np.maximum(overlaps, 0), axis=1)\n wall_pressure = l_overlap + r_overlap + b_overlap + t_overlap\n total_pressure = circle_pressure + wall_pressure\n\n dr = np.zeros(n)\n shrink_mask = total_pressure > 0\n dr[shrink_mask] = -total_pressure[shrink_mask] * 0.5\n dr[~shrink_mask] = growth_rate\n\n radii += dr * dt\n radii = np.maximum(radii, 0.001)\n\n return centers, radii\n\ndef compute_max_radii(centers, initial_radii=None):\n \"\"\"\n Refine radii for fixed centers to ensure no overlaps.\n Starting from initial_radii if provided helps preserve the\n relative sizes found during simulation.\n \"\"\"\n n = centers.shape[0]\n\n # Calculate max possible radius for each circle based on walls\n # Distance to closest wall\n max_wall_radii = np.minimum(centers[:, 0], 1 - centers[:, 0])\n max_wall_radii = np.minimum(max_wall_radii, centers[:, 1])\n max_wall_radii = np.minimum(max_wall_radii, 1 - centers[:, 1])\n\n if initial_radii is not None:\n # Start from simulation proposal, but clipped to walls\n radii = np.minimum(initial_radii, max_wall_radii)\n else:\n # Default fallback\n radii = max_wall_radii.copy()\n\n # Iteratively resolve overlaps\n # We want to keep the ratios of radii similar to input if possible,\n # but strictly satisfy constraints.\n\n # 100 iterations of relaxation\n for _ in range(100):\n valid = True\n for i in range(n):\n for j in range(i + 1, n):\n dist = np.sqrt(np.sum((centers[i] - centers[j])**2))\n sum_r = radii[i] + radii[j]\n\n if sum_r > dist - 1e-10:\n valid = False\n # Overlap\n overlap = sum_r - dist\n\n if sum_r > 1e-9:\n # Shrink proportional to current size (maintains relative scale)\n fraction_i = radii[i] / sum_r\n fraction_j = radii[j] / sum_r\n\n # Apply correction with tiny safety buffer\n radii[i] -= overlap * fraction_i * 1.0001\n radii[j] -= overlap * fraction_j * 1.0001\n else:\n radii[i] -= overlap * 0.5\n radii[j] -= overlap * 0.5\n\n # Clamp to walls again to be safe\n radii = np.minimum(radii, max_wall_radii)\n\n if valid:\n break\n\n return radii\n\n# EVOLVE-BLOCK-END\n\n\n# This part remains fixed (not evolved)\ndef run_packing():\n \"\"\"Run the circle packing constructor for n=26\"\"\"\n centers, radii = construct_packing()\n # Calculate the sum of radii\n sum_radii = np.sum(radii)\n return centers, radii, sum_radii\n```\n\nPerformance metrics: Combined score to maximize: 1.0019459\ncenters_str: centers[0] = (0.7373, 0.7048)\n centers[1] = (0.4800, 0.2119)\n centers[2] = (0.3808, 0.2986)\n centers[3] = (0.5326, 0.5287)\n centers[4] = (0.0213, 0.0160)\n centers[5] = (0.9012, 0.3341)\n centers[6] = (0.6311, 0.2137)\n centers[7] = (0.1332, 0.6037)\n centers[8] = (0.5017, 0.3199)\n centers[9] = (0.1780, 0.1574)\n centers[10] = (0.3485, 0.8765)\n centers[11] = (0.1829, 0.6818)\n centers[12] = (0.3086, 0.2948)\n centers[13] = (0.4051, 0.3874)\n centers[14] = (0.8599, 0.5527)\n centers[15] = (0.1606, 0.0435)\n centers[16] = (0.6345, 0.2772)\n centers[17] = (0.6261, 0.9468)\n centers[18] = (0.2566, 0.2205)\n centers[19] = (0.3655, 0.1126)\n centers[20] = (0.9521, 0.1037)\n centers[21] = (0.6512, 0.7410)\n centers[22] = (0.4609, 0.4966)\n centers[23] = (0.0428, 0.4337)\n centers[24] = (0.1574, 0.9154)\n centers[25] = (0.2564, 0.0521); num_circles: 26; aux_aux_metric_eval_success: 1.0000000; aux_aux_metric_error_code: 0.0000000; aux_aux_metric_error_message_length: 0.0000000; aux_aux_metric_error_detail_length: 0.0000000; aux_aux_metric_non_numeric_dropped_count: 0.0000000\n\n\n# Search Mode\nCurrent mode: `recombine`.\nIntent: `recombine_high_value_ideas`.\nRationale: Blend multiple useful fragments to widen the search distribution.\nActively merge useful ideas from different prior programs instead of only polishing one lineage.\n\n# Universal Memory\nActive search mode: `recombine`.\n\nRecent wins:\n- Gen 2: `recombine_high_value_ideas` via `recombine/full` => +1.6288, verdict=win.\n- Gen 4: `recombine_high_value_ideas` via `recombine/cross` => +0.0224, verdict=win.\n- Gen 5: `recombine_high_value_ideas` via `recombine/cross` => +1.3550, verdict=win.\n\nRecent failures to avoid repeating blindly:\n- Gen 6: `incremental_improvement` via `refine/diff` => failure_mode=none, verdict=loss.\n- Gen 7: `incremental_improvement` via `refine/diff` => failure_mode=none, verdict=loss.\n- Gen 8: `incremental_improvement` via `refine/diff` => failure_mode=none, verdict=loss.\n\nMode-specific history for `recombine`:\n- Gen 4: patch=`hybrid_multi_init_packing`, delta=+0.0224, failure_mode=none.\n- Gen 5: patch=`hybrid_init_expand_packing`, delta=+1.3550, failure_mode=none.\n\nUnderexplored strategy families:\n- `diverge` has limited evidence so far.\n- `restart` has limited evidence so far.\n- `theory` has limited evidence so far." }, { "role": "assistant", "content": "<NAME>\nlattice_seeded_hybrid_packing\n</NAME>\n\n<DESCRIPTION>\nMerges the specialized hexagonal lattice seed patterns from the crossover source into the robust hybrid optimization framework of the current best program.\n1. **Initialization**: Incorporates a diverse set of initial states:\n - 7 specific row-based lattice patterns (from crossover) designed for high-density packing, normalized to fit the container.\n - Heuristic patterns: Grid+1, Concentric Rings, and Hexagonal approximation.\n - Random restarts to capture other basins of attraction.\n2. **Physics Simulation**: Uses the proven soft-body dynamics from the current best program (1200 iterations) to settle circles into local minima.\n3. **Refinement**: Retains the superior \"shrink-then-expand\" maximization routine that strictly enforces non-overlap while greedily expanding radii to touch walls or neighbors, ensuring the final configuration is locally optimal for the found centers.\n</DESCRIPTION>\n\n<CODE>\n```python\n# EVOLVE-BLOCK-START\n\"\"\"Constructor-based circle packing for n=26 circles\"\"\"\n\nimport numpy as np\n\ndef construct_packing():\n \"\"\"\n Construct a specific arrangement of 26 circles in a unit square\n that attempts to maximize the sum of their radii.\n \n Combines:\n 1. Structured Lattice Seeds (from crossover)\n 2. Heuristic Patterns (Grid, Ring)\n 3. Physics-based relaxation\n 4. Greedy Expansion\n \"\"\"\n n = 26\n best_centers = None\n best_radii = None\n best_score = -1.0\n \n # Generate a diverse set of initial configurations\n seeds = get_all_seeds(n)\n \n for centers in seeds:\n # 1. Physics Simulation\n # Run dynamics to settle circles\n # Add slight noise to break perfect symmetries if it's too regular\n centers_noisy = centers + (np.random.rand(n, 2) - 0.5) * 0.002\n centers_noisy = np.clip(centers_noisy, 0.01, 0.99)\n \n sim_centers, sim_radii = run_physics_simulation(n, centers_noisy)\n \n # 2. Refinement (Maximize Radii)\n # Strictly enforce constraints and expand to fill gaps\n final_radii = maximize_radii_for_centers(sim_centers, initial_radii=sim_radii)\n \n score = np.sum(final_radii)\n if score > best_score:\n best_score = score\n best_centers = sim_centers.copy()\n best_radii = final_radii.copy()\n\n return best_centers, best_radii\n\ndef get_all_seeds(n):\n \"\"\"Generates a list of initial center positions (n, 2).\"\"\"\n seeds = []\n \n # 1. Lattice Patterns (from crossover source)\n # These are specific row-based hex-like packings known to yield good results\n patterns = [\n [5, 5, 6, 5, 5], # 26: Symmetric hex approx\n [6, 5, 6, 5, 4], # 26: Staggered\n [5, 6, 5, 5, 5], # 26\n [5, 5, 5, 5, 6], # 26\n [5, 5, 5, 5, 5, 1], # 26: Quasi-square with outlier\n [6, 6, 6, 6, 2], # 26\n [4, 5, 6, 6, 5] # 26\n ]\n for p in patterns:\n seeds.append(generate_lattice_from_rows(p, n))\n \n # 2. Grid Plus One (heuristic)\n seeds.append(init_grid_plus_one(n))\n \n # 3. Ring Pattern (heuristic)\n seeds.append(init_ring_pattern(n))\n \n # 4. Hex Approx (procedural)\n seeds.append(init_hex_approx(n))\n \n # 5. Random restarts\n for _ in range(4):\n seeds.append(np.random.rand(n, 2))\n \n return seeds\n\ndef generate_lattice_from_rows(rows, n_target):\n \"\"\"Generates centers based on row counts, centered and scaled.\"\"\"\n centers = []\n dy = np.sqrt(3) / 2\n \n for i, count in enumerate(rows):\n y = i * dy\n # Offset odd rows\n offset = 0.5 if i % 2 == 1 else 0.0\n for j in range(count):\n x = offset + j\n centers.append([x, y])\n \n centers = np.array(centers)\n \n # Normalize to [0.1, 0.9] to stay safely inside box\n if len(centers) > 0:\n min_c = np.min(centers, axis=0)\n max_c = np.max(centers, axis=0)\n range_c = max_c - min_c\n \n scale_denom = np.max(range_c)\n if scale_denom < 1e-9: scale_denom = 1.0\n \n # Scale to fit in 0.8 box centered at 0.5 (leaving 0.1 margin)\n scale = 0.8 / scale_denom\n centers = (centers - min_c) * scale + 0.1\n \n # Adjust count to match n\n if len(centers) > n_target:\n centers = centers[:n_target]\n elif len(centers) < n_target:\n # Add random points if pattern produced too few\n extra = n_target - len(centers)\n centers = np.vstack([centers, np.random.rand(extra, 2) * 0.8 + 0.1])\n \n return centers\n\ndef init_grid_plus_one(n):\n \"\"\"5x5 grid plus one extra circle.\"\"\"\n x = np.linspace(0.1, 0.9, 5)\n y = np.linspace(0.1, 0.9, 5)\n xv, yv = np.meshgrid(x, y)\n centers = np.column_stack((xv.flatten(), yv.flatten()))\n extra = np.array([[0.52, 0.52]]) # Slightly off center\n if len(centers) < n:\n centers = np.vstack((centers, extra))\n return centers[:n]\n\ndef init_ring_pattern(n):\n \"\"\"Concentric rings pattern.\"\"\"\n centers = np.zeros((n, 2))\n centers[0] = [0.5, 0.5]\n # Inner ring\n for i in range(8):\n angle = 2 * np.pi * i / 8\n centers[i + 1] = [0.5 + 0.25 * np.cos(angle), 0.5 + 0.25 * np.sin(angle)]\n # Outer ring\n remaining = n - 9\n if remaining > 0:\n for i in range(remaining):\n angle = 2 * np.pi * i / remaining\n centers[i + 9] = [0.5 + 0.45 * np.cos(angle), 0.5 + 0.45 * np.sin(angle)]\n return centers\n\ndef init_hex_approx(n):\n \"\"\"Procedural hexagonal fill.\"\"\"\n centers = []\n delta = 0.18\n y = 0.1\n row = 0\n while len(centers) < n and y < 0.95:\n if row % 2 == 0:\n x_start = 0.1\n else:\n x_start = 0.1 + delta * 0.5\n x = x_start\n while len(centers) < n and x < 0.95:\n centers.append([x, y])\n x += delta\n y += delta * 0.866\n row += 1\n centers = np.array(centers)\n if len(centers) < n:\n fill = np.random.rand(n - len(centers), 2)\n centers = np.vstack((centers, fill))\n return centers[:n]\n\ndef run_physics_simulation(n, initial_centers):\n \"\"\"\n Simulate soft-body circles to find a good packing arrangement.\n \"\"\"\n centers = initial_centers.copy()\n radii = np.ones(n) * 0.05 \n \n # Parameters\n iterations = 1200 \n dt = 0.01\n damping = 0.8\n growth_rate = 0.0005\n \n velocities = np.zeros_like(centers)\n \n for _ in range(iterations):\n # 1. Distances\n delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]\n dist_sq = np.sum(delta**2, axis=2)\n np.fill_diagonal(dist_sq, 1.0)\n dists = np.sqrt(dist_sq)\n \n # 2. Overlaps\n radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :]\n overlaps = radii_sum - dists\n np.fill_diagonal(overlaps, -1.0)\n \n # 3. Forces\n forces = np.zeros_like(centers)\n \n # Circle-Circle Repulsion\n mask = overlaps > 0\n if np.any(mask):\n safe_dists = np.where(dists < 1e-6, 1.0, dists)\n dirs = delta / safe_dists[:, :, np.newaxis]\n \n f_mag = overlaps * 50.0\n f_mag = np.maximum(f_mag, 0)\n \n forces += np.sum(dirs * f_mag[:, :, np.newaxis], axis=1)\n \n # Wall Repulsion\n l_ov = np.maximum(radii - centers[:, 0], 0)\n forces[:, 0] += l_ov * 100.0\n r_ov = np.maximum(radii - (1 - centers[:, 0]), 0)\n forces[:, 0] -= r_ov * 100.0\n b_ov = np.maximum(radii - centers[:, 1], 0)\n forces[:, 1] += b_ov * 100.0\n t_ov = np.maximum(radii - (1 - centers[:, 1]), 0)\n forces[:, 1] -= t_ov * 100.0\n \n # 4. Integrate\n velocities = velocities * damping + forces * dt\n centers += velocities * dt\n centers = np.clip(centers, 0.0, 1.0)\n \n # 5. Radius Dynamics\n total_overlap = np.sum(np.maximum(overlaps, 0), axis=1)\n wall_overlap = l_ov + r_ov + b_ov + t_ov\n pressure = total_overlap + wall_overlap\n \n dr = np.zeros(n)\n dr[pressure > 0] = -pressure[pressure > 0]\n dr[pressure == 0] = growth_rate\n \n radii += dr * dt\n radii = np.maximum(radii, 0.001)\n \n return centers, radii\n\ndef maximize_radii_for_centers(centers, initial_radii=None):\n \"\"\"\n Given fixed centers, compute the maximum possible radii \n that satisfy all constraints.\n \"\"\"\n n = centers.shape[0]\n \n # Distance to walls\n d_walls_x = np.minimum(centers[:, 0], 1 - centers[:, 0])\n d_walls_y = np.minimum(centers[:, 1], 1 - centers[:, 1])\n max_wall_radii = np.minimum(d_walls_x, d_walls_y)\n \n if initial_radii is not None:\n radii = initial_radii.copy()\n else:\n radii = max_wall_radii.copy()\n \n radii = np.minimum(radii, max_wall_radii)\n \n # Phase 1: Shrink to resolve overlaps\n for _ in range(200):\n changed = False\n for i in range(n):\n for j in range(i + 1, n):\n delta = centers[i] - centers[j]\n dist = np.sqrt(np.sum(delta**2))\n sum_r = radii[i] + radii[j]\n \n if sum_r > dist:\n overlap = sum_r - dist\n if sum_r > 1e-9:\n fi = radii[i] / sum_r\n fj = radii[j] / sum_r\n # Shrink with small bias\n radii[i] -= overlap * fi * 1.0001 \n radii[j] -= overlap * fj * 1.0001\n else:\n radii[i] -= overlap * 0.5 * 1.0001\n radii[j] -= overlap * 0.5 * 1.0001\n changed = True\n if not changed:\n break\n \n # Phase 2: Expand to fill gaps\n dists_mat = np.zeros((n, n))\n for i in range(n):\n for j in range(i + 1, n):\n d = np.sqrt(np.sum((centers[i] - centers[j])**2))\n dists_mat[i, j] = d\n dists_mat[j, i] = d\n np.fill_diagonal(dists_mat, np.inf)\n \n for _ in range(200):\n changed = False\n for i in range(n):\n # Max allowed by walls\n limit = max_wall_radii[i]\n \n # Max allowed by neighbors: r_i <= dist_ij - r_j\n constraints = dists_mat[i] - radii\n min_constraint = np.min(constraints)\n \n new_r = min(limit, min_constraint)\n new_r = max(new_r, 0.0)\n \n # Set target with tiny epsilon buffer for numerical stability\n target = new_r - 1e-10\n \n if abs(radii[i] - target) > 1e-8:\n radii[i] = target\n changed = True\n \n if not changed:\n break\n \n return radii\n\n# EVOLVE-BLOCK-END\n```\n</CODE>", "thinking_blocks": [ { "type": "thinking", "thinking": "**Merging and Optimizing**\n\nI'm now integrating the lattice seed patterns. I've successfully incorporated them into the seed generation, alongside the other heuristics, adding a more diverse set of starting configurations. I've ensured all initializations are scaled correctly, and the core physics and expansion steps remain untouched. I'm hopeful this refinement will improve the final packing scores." } ] } ], "tools": [], "kwargs": { "model_name": "native-gemini-3-pro-preview", "temperature": 1.0, "max_tokens": 65536, "extra_body": { "extra_body": { "google": { "thinking_config": { "thinking_level": "high", "include_thoughts": true } } } } }, "response": { "content": "<NAME>\nlattice_seeded_hybrid_packing\n</NAME>\n\n<DESCRIPTION>\nMerges the specialized hexagonal lattice seed patterns from the crossover source into the robust hybrid optimization framework of the current best program.\n1. **Initialization**: Incorporates a diverse set of initial states:\n - 7 specific row-based lattice patterns (from crossover) designed for high-density packing, normalized to fit the container.\n - Heuristic patterns: Grid+1, Concentric Rings, and Hexagonal approximation.\n - Random restarts to capture other basins of attraction.\n2. **Physics Simulation**: Uses the proven soft-body dynamics from the current best program (1200 iterations) to settle circles into local minima.\n3. **Refinement**: Retains the superior \"shrink-then-expand\" maximization routine that strictly enforces non-overlap while greedily expanding radii to touch walls or neighbors, ensuring the final configuration is locally optimal for the found centers.\n</DESCRIPTION>\n\n<CODE>\n```python\n# EVOLVE-BLOCK-START\n\"\"\"Constructor-based circle packing for n=26 circles\"\"\"\n\nimport numpy as np\n\ndef construct_packing():\n \"\"\"\n Construct a specific arrangement of 26 circles in a unit square\n that attempts to maximize the sum of their radii.\n \n Combines:\n 1. Structured Lattice Seeds (from crossover)\n 2. Heuristic Patterns (Grid, Ring)\n 3. Physics-based relaxation\n 4. Greedy Expansion\n \"\"\"\n n = 26\n best_centers = None\n best_radii = None\n best_score = -1.0\n \n # Generate a diverse set of initial configurations\n seeds = get_all_seeds(n)\n \n for centers in seeds:\n # 1. Physics Simulation\n # Run dynamics to settle circles\n # Add slight noise to break perfect symmetries if it's too regular\n centers_noisy = centers + (np.random.rand(n, 2) - 0.5) * 0.002\n centers_noisy = np.clip(centers_noisy, 0.01, 0.99)\n \n sim_centers, sim_radii = run_physics_simulation(n, centers_noisy)\n \n # 2. Refinement (Maximize Radii)\n # Strictly enforce constraints and expand to fill gaps\n final_radii = maximize_radii_for_centers(sim_centers, initial_radii=sim_radii)\n \n score = np.sum(final_radii)\n if score > best_score:\n best_score = score\n best_centers = sim_centers.copy()\n best_radii = final_radii.copy()\n\n return best_centers, best_radii\n\ndef get_all_seeds(n):\n \"\"\"Generates a list of initial center positions (n, 2).\"\"\"\n seeds = []\n \n # 1. Lattice Patterns (from crossover source)\n # These are specific row-based hex-like packings known to yield good results\n patterns = [\n [5, 5, 6, 5, 5], # 26: Symmetric hex approx\n [6, 5, 6, 5, 4], # 26: Staggered\n [5, 6, 5, 5, 5], # 26\n [5, 5, 5, 5, 6], # 26\n [5, 5, 5, 5, 5, 1], # 26: Quasi-square with outlier\n [6, 6, 6, 6, 2], # 26\n [4, 5, 6, 6, 5] # 26\n ]\n for p in patterns:\n seeds.append(generate_lattice_from_rows(p, n))\n \n # 2. Grid Plus One (heuristic)\n seeds.append(init_grid_plus_one(n))\n \n # 3. Ring Pattern (heuristic)\n seeds.append(init_ring_pattern(n))\n \n # 4. Hex Approx (procedural)\n seeds.append(init_hex_approx(n))\n \n # 5. Random restarts\n for _ in range(4):\n seeds.append(np.random.rand(n, 2))\n \n return seeds\n\ndef generate_lattice_from_rows(rows, n_target):\n \"\"\"Generates centers based on row counts, centered and scaled.\"\"\"\n centers = []\n dy = np.sqrt(3) / 2\n \n for i, count in enumerate(rows):\n y = i * dy\n # Offset odd rows\n offset = 0.5 if i % 2 == 1 else 0.0\n for j in range(count):\n x = offset + j\n centers.append([x, y])\n \n centers = np.array(centers)\n \n # Normalize to [0.1, 0.9] to stay safely inside box\n if len(centers) > 0:\n min_c = np.min(centers, axis=0)\n max_c = np.max(centers, axis=0)\n range_c = max_c - min_c\n \n scale_denom = np.max(range_c)\n if scale_denom < 1e-9: scale_denom = 1.0\n \n # Scale to fit in 0.8 box centered at 0.5 (leaving 0.1 margin)\n scale = 0.8 / scale_denom\n centers = (centers - min_c) * scale + 0.1\n \n # Adjust count to match n\n if len(centers) > n_target:\n centers = centers[:n_target]\n elif len(centers) < n_target:\n # Add random points if pattern produced too few\n extra = n_target - len(centers)\n centers = np.vstack([centers, np.random.rand(extra, 2) * 0.8 + 0.1])\n \n return centers\n\ndef init_grid_plus_one(n):\n \"\"\"5x5 grid plus one extra circle.\"\"\"\n x = np.linspace(0.1, 0.9, 5)\n y = np.linspace(0.1, 0.9, 5)\n xv, yv = np.meshgrid(x, y)\n centers = np.column_stack((xv.flatten(), yv.flatten()))\n extra = np.array([[0.52, 0.52]]) # Slightly off center\n if len(centers) < n:\n centers = np.vstack((centers, extra))\n return centers[:n]\n\ndef init_ring_pattern(n):\n \"\"\"Concentric rings pattern.\"\"\"\n centers = np.zeros((n, 2))\n centers[0] = [0.5, 0.5]\n # Inner ring\n for i in range(8):\n angle = 2 * np.pi * i / 8\n centers[i + 1] = [0.5 + 0.25 * np.cos(angle), 0.5 + 0.25 * np.sin(angle)]\n # Outer ring\n remaining = n - 9\n if remaining > 0:\n for i in range(remaining):\n angle = 2 * np.pi * i / remaining\n centers[i + 9] = [0.5 + 0.45 * np.cos(angle), 0.5 + 0.45 * np.sin(angle)]\n return centers\n\ndef init_hex_approx(n):\n \"\"\"Procedural hexagonal fill.\"\"\"\n centers = []\n delta = 0.18\n y = 0.1\n row = 0\n while len(centers) < n and y < 0.95:\n if row % 2 == 0:\n x_start = 0.1\n else:\n x_start = 0.1 + delta * 0.5\n x = x_start\n while len(centers) < n and x < 0.95:\n centers.append([x, y])\n x += delta\n y += delta * 0.866\n row += 1\n centers = np.array(centers)\n if len(centers) < n:\n fill = np.random.rand(n - len(centers), 2)\n centers = np.vstack((centers, fill))\n return centers[:n]\n\ndef run_physics_simulation(n, initial_centers):\n \"\"\"\n Simulate soft-body circles to find a good packing arrangement.\n \"\"\"\n centers = initial_centers.copy()\n radii = np.ones(n) * 0.05 \n \n # Parameters\n iterations = 1200 \n dt = 0.01\n damping = 0.8\n growth_rate = 0.0005\n \n velocities = np.zeros_like(centers)\n \n for _ in range(iterations):\n # 1. Distances\n delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]\n dist_sq = np.sum(delta**2, axis=2)\n np.fill_diagonal(dist_sq, 1.0)\n dists = np.sqrt(dist_sq)\n \n # 2. Overlaps\n radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :]\n overlaps = radii_sum - dists\n np.fill_diagonal(overlaps, -1.0)\n \n # 3. Forces\n forces = np.zeros_like(centers)\n \n # Circle-Circle Repulsion\n mask = overlaps > 0\n if np.any(mask):\n safe_dists = np.where(dists < 1e-6, 1.0, dists)\n dirs = delta / safe_dists[:, :, np.newaxis]\n \n f_mag = overlaps * 50.0\n f_mag = np.maximum(f_mag, 0)\n \n forces += np.sum(dirs * f_mag[:, :, np.newaxis], axis=1)\n \n # Wall Repulsion\n l_ov = np.maximum(radii - centers[:, 0], 0)\n forces[:, 0] += l_ov * 100.0\n r_ov = np.maximum(radii - (1 - centers[:, 0]), 0)\n forces[:, 0] -= r_ov * 100.0\n b_ov = np.maximum(radii - centers[:, 1], 0)\n forces[:, 1] += b_ov * 100.0\n t_ov = np.maximum(radii - (1 - centers[:, 1]), 0)\n forces[:, 1] -= t_ov * 100.0\n \n # 4. Integrate\n velocities = velocities * damping + forces * dt\n centers += velocities * dt\n centers = np.clip(centers, 0.0, 1.0)\n \n # 5. Radius Dynamics\n total_overlap = np.sum(np.maximum(overlaps, 0), axis=1)\n wall_overlap = l_ov + r_ov + b_ov + t_ov\n pressure = total_overlap + wall_overlap\n \n dr = np.zeros(n)\n dr[pressure > 0] = -pressure[pressure > 0]\n dr[pressure == 0] = growth_rate\n \n radii += dr * dt\n radii = np.maximum(radii, 0.001)\n \n return centers, radii\n\ndef maximize_radii_for_centers(centers, initial_radii=None):\n \"\"\"\n Given fixed centers, compute the maximum possible radii \n that satisfy all constraints.\n \"\"\"\n n = centers.shape[0]\n \n # Distance to walls\n d_walls_x = np.minimum(centers[:, 0], 1 - centers[:, 0])\n d_walls_y = np.minimum(centers[:, 1], 1 - centers[:, 1])\n max_wall_radii = np.minimum(d_walls_x, d_walls_y)\n \n if initial_radii is not None:\n radii = initial_radii.copy()\n else:\n radii = max_wall_radii.copy()\n \n radii = np.minimum(radii, max_wall_radii)\n \n # Phase 1: Shrink to resolve overlaps\n for _ in range(200):\n changed = False\n for i in range(n):\n for j in range(i + 1, n):\n delta = centers[i] - centers[j]\n dist = np.sqrt(np.sum(delta**2))\n sum_r = radii[i] + radii[j]\n \n if sum_r > dist:\n overlap = sum_r - dist\n if sum_r > 1e-9:\n fi = radii[i] / sum_r\n fj = radii[j] / sum_r\n # Shrink with small bias\n radii[i] -= overlap * fi * 1.0001 \n radii[j] -= overlap * fj * 1.0001\n else:\n radii[i] -= overlap * 0.5 * 1.0001\n radii[j] -= overlap * 0.5 * 1.0001\n changed = True\n if not changed:\n break\n \n # Phase 2: Expand to fill gaps\n dists_mat = np.zeros((n, n))\n for i in range(n):\n for j in range(i + 1, n):\n d = np.sqrt(np.sum((centers[i] - centers[j])**2))\n dists_mat[i, j] = d\n dists_mat[j, i] = d\n np.fill_diagonal(dists_mat, np.inf)\n \n for _ in range(200):\n changed = False\n for i in range(n):\n # Max allowed by walls\n limit = max_wall_radii[i]\n \n # Max allowed by neighbors: r_i <= dist_ij - r_j\n constraints = dists_mat[i] - radii\n min_constraint = np.min(constraints)\n \n new_r = min(limit, min_constraint)\n new_r = max(new_r, 0.0)\n \n # Set target with tiny epsilon buffer for numerical stability\n target = new_r - 1e-10\n \n if abs(radii[i] - target) > 1e-8:\n radii[i] = target\n changed = True\n \n if not changed:\n break\n \n return radii\n\n# EVOLVE-BLOCK-END\n```\n</CODE>", "thought": "**Merging and Optimizing**\n\nI'm now integrating the lattice seed patterns. I've successfully incorporated them into the seed generation, alongside the other heuristics, adding a more diverse set of starting configurations. I've ensured all initializations are scaled correctly, and the core physics and expansion steps remain untouched. I'm hopeful this refinement will improve the final packing scores.", "model_name": "gemini-3-pro-preview", "model_posteriors": { "native-gemini-3-pro-preview": 1.0 } }, "cost": 0, "timestamp": 1772442494.0127237, "latency_sec": 112.040776014328, "usage_summary": { "input_tokens": 14276, "output_tokens": 3619, "thoughts_tokens": 9858, "total_tokens": 27753 }, "metadata": { "generation": 10, "novelty_attempt": 1, "resample_attempt": 1, "patch_attempt": 1, "patch_type": "cross", "parent_id": "7b296290-5d77-4bdc-bb68-f7484654f336", "query_status": "ok", "apply_success": true, "num_applied": 1, "error_attempt": null, "output_path": "tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/main.py" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323# EVOLVE-BLOCK-START"""Constructor-based circle packing for n=26 circles"""
import numpy as np
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii. Combines: 1. Structured Lattice Seeds (from crossover) 2. Heuristic Patterns (Grid, Ring) 3. Physics-based relaxation 4. Greedy Expansion """ n = 26 best_centers = None best_radii = None best_score = -1.0 # Generate a diverse set of initial configurations seeds = get_all_seeds(n) for centers in seeds: # 1. Physics Simulation # Run dynamics to settle circles # Add slight noise to break perfect symmetries if it's too regular centers_noisy = centers + (np.random.rand(n, 2) - 0.5) * 0.002 centers_noisy = np.clip(centers_noisy, 0.01, 0.99) sim_centers, sim_radii = run_physics_simulation(n, centers_noisy) # 2. Refinement (Maximize Radii) # Strictly enforce constraints and expand to fill gaps final_radii = maximize_radii_for_centers(sim_centers, initial_radii=sim_radii) score = np.sum(final_radii) if score > best_score: best_score = score best_centers = sim_centers.copy() best_radii = final_radii.copy()
return best_centers, best_radii
def get_all_seeds(n): """Generates a list of initial center positions (n, 2).""" seeds = [] # 1. Lattice Patterns (from crossover source) # These are specific row-based hex-like packings known to yield good results patterns = [ [5, 5, 6, 5, 5], # 26: Symmetric hex approx [6, 5, 6, 5, 4], # 26: Staggered [5, 6, 5, 5, 5], # 26 [5, 5, 5, 5, 6], # 26 [5, 5, 5, 5, 5, 1], # 26: Quasi-square with outlier [6, 6, 6, 6, 2], # 26 [4, 5, 6, 6, 5] # 26 ] for p in patterns: seeds.append(generate_lattice_from_rows(p, n)) # 2. Grid Plus One (heuristic) seeds.append(init_grid_plus_one(n)) # 3. Ring Pattern (heuristic) seeds.append(init_ring_pattern(n)) # 4. Hex Approx (procedural) seeds.append(init_hex_approx(n)) # 5. Random restarts for _ in range(4): seeds.append(np.random.rand(n, 2)) return seeds
def generate_lattice_from_rows(rows, n_target): """Generates centers based on row counts, centered and scaled.""" centers = [] dy = np.sqrt(3) / 2 for i, count in enumerate(rows): y = i * dy # Offset odd rows offset = 0.5 if i % 2 == 1 else 0.0 for j in range(count): x = offset + j centers.append([x, y]) centers = np.array(centers) # Normalize to [0.1, 0.9] to stay safely inside box if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) range_c = max_c - min_c scale_denom = np.max(range_c) if scale_denom < 1e-9: scale_denom = 1.0 # Scale to fit in 0.8 box centered at 0.5 (leaving 0.1 margin) scale = 0.8 / scale_denom centers = (centers - min_c) * scale + 0.1 # Adjust count to match n if len(centers) > n_target: centers = centers[:n_target] elif len(centers) < n_target: # Add random points if pattern produced too few extra = n_target - len(centers) centers = np.vstack([centers, np.random.rand(extra, 2) * 0.8 + 0.1]) return centers
def init_grid_plus_one(n): """5x5 grid plus one extra circle.""" x = np.linspace(0.1, 0.9, 5) y = np.linspace(0.1, 0.9, 5) xv, yv = np.meshgrid(x, y) centers = np.column_stack((xv.flatten(), yv.flatten())) extra = np.array([[0.52, 0.52]]) # Slightly off center if len(centers) < n: centers = np.vstack((centers, extra)) return centers[:n]
def init_ring_pattern(n): """Concentric rings pattern.""" centers = np.zeros((n, 2)) centers[0] = [0.5, 0.5] # Inner ring for i in range(8): angle = 2 * np.pi * i / 8 centers[i + 1] = [0.5 + 0.25 * np.cos(angle), 0.5 + 0.25 * np.sin(angle)] # Outer ring remaining = n - 9 if remaining > 0: for i in range(remaining): angle = 2 * np.pi * i / remaining centers[i + 9] = [0.5 + 0.45 * np.cos(angle), 0.5 + 0.45 * np.sin(angle)] return centers
def init_hex_approx(n): """Procedural hexagonal fill.""" centers = [] delta = 0.18 y = 0.1 row = 0 while len(centers) < n and y < 0.95: if row % 2 == 0: x_start = 0.1 else: x_start = 0.1 + delta * 0.5 x = x_start while len(centers) < n and x < 0.95: centers.append([x, y]) x += delta y += delta * 0.866 row += 1 centers = np.array(centers) if len(centers) < n: fill = np.random.rand(n - len(centers), 2) centers = np.vstack((centers, fill)) return centers[:n]
def run_physics_simulation(n, initial_centers): """ Simulate soft-body circles to find a good packing arrangement. """ centers = initial_centers.copy() radii = np.ones(n) * 0.05 # Parameters iterations = 1200 dt = 0.01 damping = 0.8 growth_rate = 0.0005 velocities = np.zeros_like(centers) for _ in range(iterations): # 1. Distances delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(delta**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # 2. Overlaps radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :] overlaps = radii_sum - dists np.fill_diagonal(overlaps, -1.0) # 3. Forces forces = np.zeros_like(centers) # Circle-Circle Repulsion mask = overlaps > 0 if np.any(mask): safe_dists = np.where(dists < 1e-6, 1.0, dists) dirs = delta / safe_dists[:, :, np.newaxis] f_mag = overlaps * 50.0 f_mag = np.maximum(f_mag, 0) forces += np.sum(dirs * f_mag[:, :, np.newaxis], axis=1) # Wall Repulsion l_ov = np.maximum(radii - centers[:, 0], 0) forces[:, 0] += l_ov * 100.0 r_ov = np.maximum(radii - (1 - centers[:, 0]), 0) forces[:, 0] -= r_ov * 100.0 b_ov = np.maximum(radii - centers[:, 1], 0) forces[:, 1] += b_ov * 100.0 t_ov = np.maximum(radii - (1 - centers[:, 1]), 0) forces[:, 1] -= t_ov * 100.0 # 4. Integrate velocities = velocities * damping + forces * dt centers += velocities * dt centers = np.clip(centers, 0.0, 1.0) # 5. Radius Dynamics total_overlap = np.sum(np.maximum(overlaps, 0), axis=1) wall_overlap = l_ov + r_ov + b_ov + t_ov pressure = total_overlap + wall_overlap dr = np.zeros(n) dr[pressure > 0] = -pressure[pressure > 0] dr[pressure == 0] = growth_rate radii += dr * dt radii = np.maximum(radii, 0.001) return centers, radii
def maximize_radii_for_centers(centers, initial_radii=None): """ Given fixed centers, compute the maximum possible radii that satisfy all constraints. """ n = centers.shape[0] # Distance to walls d_walls_x = np.minimum(centers[:, 0], 1 - centers[:, 0]) d_walls_y = np.minimum(centers[:, 1], 1 - centers[:, 1]) max_wall_radii = np.minimum(d_walls_x, d_walls_y) if initial_radii is not None: radii = initial_radii.copy() else: radii = max_wall_radii.copy() radii = np.minimum(radii, max_wall_radii) # Phase 1: Shrink to resolve overlaps for _ in range(200): changed = False for i in range(n): for j in range(i + 1, n): delta = centers[i] - centers[j] dist = np.sqrt(np.sum(delta**2)) sum_r = radii[i] + radii[j] if sum_r > dist: overlap = sum_r - dist if sum_r > 1e-9: fi = radii[i] / sum_r fj = radii[j] / sum_r # Shrink with small bias radii[i] -= overlap * fi * 1.0001 radii[j] -= overlap * fj * 1.0001 else: radii[i] -= overlap * 0.5 * 1.0001 radii[j] -= overlap * 0.5 * 1.0001 changed = True if not changed: break # Phase 2: Expand to fill gaps dists_mat = np.zeros((n, n)) for i in range(n): for j in range(i + 1, n): d = np.sqrt(np.sum((centers[i] - centers[j])**2)) dists_mat[i, j] = d dists_mat[j, i] = d np.fill_diagonal(dists_mat, np.inf) for _ in range(200): changed = False for i in range(n): # Max allowed by walls limit = max_wall_radii[i] # Max allowed by neighbors: r_i <= dist_ij - r_j constraints = dists_mat[i] - radii min_constraint = np.min(constraints) new_r = min(limit, min_constraint) new_r = max(new_r, 0.0) # Set target with tiny epsilon buffer for numerical stability target = new_r - 1e-10 if abs(radii[i] - target) > 1e-8: radii[i] = target changed = True if not changed: break return radii
# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305# EVOLVE-BLOCK-START"""Constructor-based circle packing for n=26 circles"""
import numpy as np
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii. Uses a hybrid approach: 1. Diverse Initialization (Grid, Hex, Rings, Random) to find different basins. 2. Physics-based relaxation to optimize packing density. 3. Greedy expansion/shrinking to strictly enforce constraints while maximizing size.
Returns: Tuple of (centers, radii) centers: np.array of shape (26, 2) radii: np.array of shape (26) """ n = 26 best_centers = None best_radii = None best_score = -1.0 # Strategy list defines initialization patterns # We try structured patterns that are close to optimal packing densities # plus random restarts to catch other variations. strategies = [ 'hex', # Hexagonal lattice chunk 'grid', # 5x5 grid + 1 'ring', # Concentric rings (from inspiration) 'random', # Pure random 'random', 'random', 'random', 'random' ]
for strat in strategies: # 1. Initialization if strat == 'grid': centers = init_grid_plus_one(n) elif strat == 'hex': centers = init_hex_approx(n) elif strat == 'ring': centers = init_ring_pattern(n) else: centers = np.random.rand(n, 2) # Add small noise to break perfect symmetries and allow physics to slide centers += (np.random.rand(n, 2) - 0.5) * 0.02 centers = np.clip(centers, 0.01, 0.99) # 2. Physics Simulation # Run dynamics to settle circles into a packed state centers, radii = run_physics_simulation(n, centers) # 3. Refinement (Maximize Radii) # Strictly enforce constraints and expand to fill gaps radii = maximize_radii_for_centers(centers, initial_radii=radii) score = np.sum(radii) if score > best_score: best_score = score best_centers = centers.copy() best_radii = radii.copy()
return best_centers, best_radii
def init_grid_plus_one(n): """5x5 grid plus one extra circle.""" x = np.linspace(0.1, 0.9, 5) y = np.linspace(0.1, 0.9, 5) xv, yv = np.meshgrid(x, y) centers = np.column_stack((xv.flatten(), yv.flatten())) # Add 26th circle near center but offset extra = np.array([[0.52, 0.52]]) if len(centers) < n: centers = np.vstack((centers, extra)) return centers[:n]
def init_ring_pattern(n): """Concentric rings pattern.""" centers = np.zeros((n, 2)) centers[0] = [0.5, 0.5] # Inner ring of 8 for i in range(8): angle = 2 * np.pi * i / 8 centers[i + 1] = [0.5 + 0.25 * np.cos(angle), 0.5 + 0.25 * np.sin(angle)] # Outer ring remaining = n - 9 for i in range(remaining): angle = 2 * np.pi * i / remaining centers[i + 9] = [0.5 + 0.45 * np.cos(angle), 0.5 + 0.45 * np.sin(angle)] return centers
def init_hex_approx(n): """Triangular/Hexagonal lattice filling.""" centers = [] # Approx spacing for dense packing delta = 0.18 y = 0.1 row = 0 while len(centers) < n and y < 0.95: if row % 2 == 0: x_start = 0.1 else: x_start = 0.1 + delta * 0.5 x = x_start while len(centers) < n and x < 0.95: centers.append([x, y]) x += delta y += delta * 0.866 # sqrt(3)/2 row += 1 centers = np.array(centers) if len(centers) < n: # Fill remaining with random if grid didn't fit enough fill = np.random.rand(n - len(centers), 2) centers = np.vstack((centers, fill)) return centers[:n]
def run_physics_simulation(n, initial_centers): """ Simulate soft-body circles to find a good packing arrangement. """ centers = initial_centers.copy() radii = np.ones(n) * 0.05 # Start small # Simulation params iterations = 1000 dt = 0.01 damping = 0.8 growth_rate = 0.0005 velocities = np.zeros_like(centers) for _ in range(iterations): # 1. Distances delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(delta**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # 2. Overlaps # overlap = (ri + rj) - dist radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :] overlaps = radii_sum - dists np.fill_diagonal(overlaps, -1.0) # 3. Forces forces = np.zeros_like(centers) # Circle-Circle mask = overlaps > 0 if np.any(mask): # Safe normalization safe_dists = np.where(dists < 1e-6, 1.0, dists) dirs = delta / safe_dists[:, :, np.newaxis] # Force magnitude proportional to overlap f_mag = overlaps * 50.0 f_mag = np.maximum(f_mag, 0) # Apply mask implicitly forces += np.sum(dirs * f_mag[:, :, np.newaxis], axis=1) # Wall Repulsion # Left l_ov = np.maximum(radii - centers[:, 0], 0) forces[:, 0] += l_ov * 100.0 # Right r_ov = np.maximum(radii - (1 - centers[:, 0]), 0) forces[:, 0] -= r_ov * 100.0 # Bottom b_ov = np.maximum(radii - centers[:, 1], 0) forces[:, 1] += b_ov * 100.0 # Top t_ov = np.maximum(radii - (1 - centers[:, 1]), 0) forces[:, 1] -= t_ov * 100.0 # 4. Integrate velocities = velocities * damping + forces * dt centers += velocities * dt centers = np.clip(centers, 0.0, 1.0) # 5. Radius Dynamics # Pressure based on overlaps total_overlap = np.sum(np.maximum(overlaps, 0), axis=1) wall_overlap = l_ov + r_ov + b_ov + t_ov pressure = total_overlap + wall_overlap dr = np.zeros(n) # Shrink if under pressure dr[pressure > 0] = -pressure[pressure > 0] # Grow if free dr[pressure == 0] = growth_rate radii += dr * dt radii = np.maximum(radii, 0.001) return centers, radii
def maximize_radii_for_centers(centers, initial_radii=None): """ Given fixed centers, compute the maximum possible radii that satisfy all constraints. It resolves overlaps and then expands circles to fill gaps. """ n = centers.shape[0] # Distance to walls # r <= x, r <= 1-x, etc. d_walls_x = np.minimum(centers[:, 0], 1 - centers[:, 0]) d_walls_y = np.minimum(centers[:, 1], 1 - centers[:, 1]) max_wall_radii = np.minimum(d_walls_x, d_walls_y) if initial_radii is not None: radii = initial_radii.copy() else: radii = max_wall_radii.copy() # Ensure starting valid against walls radii = np.minimum(radii, max_wall_radii) # Phase 1: Shrink to resolve circle-circle overlaps # Iterative relaxation for _ in range(200): changed = False for i in range(n): for j in range(i + 1, n): delta = centers[i] - centers[j] dist = np.sqrt(np.sum(delta**2)) sum_r = radii[i] + radii[j] if sum_r > dist: # Overlap overlap = sum_r - dist # Shrink both roughly equally to fix # but check for small radii to avoid issues if sum_r > 1e-9: # Proportional shrink fi = radii[i] / sum_r fj = radii[j] / sum_r radii[i] -= overlap * fi * 1.0001 # Small bias to ensure separation radii[j] -= overlap * fj * 1.0001 else: radii[i] -= overlap * 0.5 * 1.0001 radii[j] -= overlap * 0.5 * 1.0001 changed = True if not changed: break # Phase 2: Expand to fill gaps # Iterate to maximize radii # r_i = min(wall_i, min_j(dist_ij - r_j)) # Pre-calculate distances dists_mat = np.zeros((n, n)) for i in range(n): for j in range(i + 1, n): d = np.sqrt(np.sum((centers[i] - centers[j])**2)) dists_mat[i, j] = d dists_mat[j, i] = d np.fill_diagonal(dists_mat, np.inf) # Ignore self for _ in range(100): changed = False for i in range(n): # Max allowed by walls limit = max_wall_radii[i] # Max allowed by neighbors: r_i <= dist_ij - r_j # So r_i <= min(dist_ij - r_j) constraints = dists_mat[i] - radii min_constraint = np.min(constraints) new_r = min(limit, min_constraint) # Ensure non-negative (should be if centers disjoint) new_r = max(new_r, 0.0) # Update if we can grow (or must shrink due to some other update) # We add a tiny epsilon safety margin target = new_r - 1e-10 if abs(radii[i] - target) > 1e-7: radii[i] = target changed = True if not changed: break return radii
# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import numpy as npimport osfrom typing import Dict, Any
def evaluate_aux(results_dir: str, primary_result: Dict[str, Any] | None = None) -> Dict[str, Any]: """ Evaluates auxiliary metrics for the circle packing problem. """ metrics = {}
try: # Load data from extra.npz extra_data_path = os.path.join(results_dir, "extra.npz") if not os.path.exists(extra_data_path): print(f"Warning: {extra_data_path} not found. Cannot calculate auxiliary metrics.") return { "aux_min_radius_final": 0.0, "aux_num_negative_radii": 0.0, "aux_max_overlap_circles_final": 0.0, "aux_max_wall_penetration_final": 0.0, } data = np.load(extra_data_path) centers = data["centers"] radii = data["radii"] n = len(centers)
# 1. aux_min_radius_final metrics["aux_min_radius_final"] = float(np.min(radii))
# 2. aux_num_negative_radii metrics["aux_num_negative_radii"] = int(np.sum(radii < 0))
# 3. aux_max_overlap_circles_final max_overlap = 0.0 for i in range(n): for j in range(i + 1, n): dist = np.linalg.norm(centers[i] - centers[j]) overlap = (radii[i] + radii[j]) - dist if overlap > max_overlap: max_overlap = overlap metrics["aux_max_overlap_circles_final"] = float(max_overlap)
# 4. aux_max_wall_penetration_final max_wall_penetration = 0.0 for i in range(n): x, y = centers[i] r = radii[i] # Check against x=0, x=1, y=0, y=1 walls penetration_x0 = r - x penetration_x1 = r - (1 - x) penetration_y0 = r - y penetration_y1 = r - (1 - y) current_max_penetration = max(penetration_x0, penetration_x1, penetration_y0, penetration_y1) if current_max_penetration > max_wall_penetration: max_wall_penetration = current_max_penetration metrics["aux_max_wall_penetration_final"] = float(max_wall_penetration)
except Exception as e: print(f"Error calculating auxiliary metrics: {e}") return { "aux_min_radius_final": 0.0, "aux_num_negative_radii": 0.0, "aux_max_overlap_circles_final": 0.0, "aux_max_wall_penetration_final": 0.0, "aux_metric_error": 1.0, "aux_metric_error_message": str(e) }
return metrics
1234{ "correct": true, "error": null}12345678910111213141516171819202122232425262728293031323334353637383940{ "combined_score": 2.4694198666624443, "correct": true, "primary": { "combined_score": 2.4694198666624443, "public": { "centers_str": " centers[0] = (0.0996, 0.0993)\n centers[1] = (0.3003, 0.1004)\n centers[2] = (0.4995, 0.1000)\n centers[3] = (0.6990, 0.0991)\n centers[4] = (0.9000, 0.1001)\n centers[5] = (0.1006, 0.3001)\n centers[6] = (0.2996, 0.3004)\n centers[7] = (0.5004, 0.3005)\n centers[8] = (0.7005, 0.3001)\n centers[9] = (0.9002, 0.2992)\n centers[10] = (0.0991, 0.4999)\n centers[11] = (0.2996, 0.5007)\n centers[12] = (0.4818, 0.4818)\n centers[13] = (0.7002, 0.4994)\n centers[14] = (0.9007, 0.5008)\n centers[15] = (0.0995, 0.6997)\n centers[16] = (0.3002, 0.7003)\n centers[17] = (0.5003, 0.7001)\n centers[18] = (0.6997, 0.7006)\n centers[19] = (0.8993, 0.6998)\n centers[20] = (0.0999, 0.9002)\n centers[21] = (0.2990, 0.9001)\n centers[22] = (0.5005, 0.9005)\n centers[23] = (0.7004, 0.8996)\n centers[24] = (0.8997, 0.8991)\n centers[25] = (0.5373, 0.5387)", "num_circles": 26 }, "private": { "reported_sum_of_radii": 2.4694198666624443 }, "execution_time_mean": 2.154142980463803, "execution_time_std": 0.0, "num_valid_runs": 1, "num_invalid_runs": 0, "all_validation_errors": [], "correct": true, "validation_error": null }, "auxiliary": { "aux_min_radius_final": 0.039759545471233684, "aux_num_negative_radii": 0.0, "aux_max_overlap_circles_final": 0.0, "aux_max_wall_penetration_final": 0.0, "aux_metric_eval_success": 1.0, "aux_metric_error_code": 0.0, "aux_metric_error_message_length": 0.0, "aux_metric_error_detail_length": 0.0, "aux_metric_non_numeric_dropped_count": 0.0 }, "auxiliary_descriptions": { "aux_min_radius_final": "Minimum radius found among all circles after final radius computation. Negative values indicate invalid solutions.", "aux_num_negative_radii": "Count of circles with negative radii after final radius computation. Non-zero values indicate invalid solutions.", "aux_max_overlap_circles_final": "Maximum overlap value between any two circles after final radius computation. Non-zero values indicate invalid solutions.", "aux_max_wall_penetration_final": "Maximum penetration depth of any circle into a wall after final radius computation. Non-zero values indicate invalid solutions." }, "timestamp": 1772442505.8386474, "generation": 10}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314# EVOLVE-BLOCK-START"""Constructor-based circle packing for n=26 circles"""
import numpy as np
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii. Combines: 1. Structured Lattice Seeds (from crossover) 2. Heuristic Patterns (Grid, Ring) 3. Physics-based relaxation 4. Greedy Expansion """ n = 26 best_centers = None best_radii = None best_score = -1.0 # Generate a diverse set of initial configurations seeds = get_all_seeds(n) for centers in seeds: # 1. Physics Simulation # Run dynamics to settle circles # Add slight noise to break perfect symmetries if it's too regular centers_noisy = centers + (np.random.rand(n, 2) - 0.5) * 0.002 centers_noisy = np.clip(centers_noisy, 0.01, 0.99) sim_centers, sim_radii = run_physics_simulation(n, centers_noisy) # 2. Refinement (Maximize Radii) # Strictly enforce constraints and expand to fill gaps final_radii = maximize_radii_for_centers(sim_centers, initial_radii=sim_radii) score = np.sum(final_radii) if score > best_score: best_score = score best_centers = sim_centers.copy() best_radii = final_radii.copy()
return best_centers, best_radii
def get_all_seeds(n): """Generates a list of initial center positions (n, 2).""" seeds = [] # 1. Lattice Patterns (from crossover source) # These are specific row-based hex-like packings known to yield good results patterns = [ [5, 5, 6, 5, 5], # 26: Symmetric hex approx [6, 5, 6, 5, 4], # 26: Staggered [5, 6, 5, 5, 5], # 26 [5, 5, 5, 5, 6], # 26 [5, 5, 5, 5, 5, 1], # 26: Quasi-square with outlier [6, 6, 6, 6, 2], # 26 [4, 5, 6, 6, 5] # 26 ] for p in patterns: seeds.append(generate_lattice_from_rows(p, n)) # 2. Grid Plus One (heuristic) seeds.append(init_grid_plus_one(n)) # 3. Ring Pattern (heuristic) seeds.append(init_ring_pattern(n)) # 4. Hex Approx (procedural) seeds.append(init_hex_approx(n)) # 5. Random restarts for _ in range(4): seeds.append(np.random.rand(n, 2)) return seeds
def generate_lattice_from_rows(rows, n_target): """Generates centers based on row counts, centered and scaled.""" centers = [] dy = np.sqrt(3) / 2 for i, count in enumerate(rows): y = i * dy # Offset odd rows offset = 0.5 if i % 2 == 1 else 0.0 for j in range(count): x = offset + j centers.append([x, y]) centers = np.array(centers) # Normalize to [0.1, 0.9] to stay safely inside box if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) range_c = max_c - min_c scale_denom = np.max(range_c) if scale_denom < 1e-9: scale_denom = 1.0 # Scale to fit in 0.8 box centered at 0.5 (leaving 0.1 margin) scale = 0.8 / scale_denom centers = (centers - min_c) * scale + 0.1 # Adjust count to match n if len(centers) > n_target: centers = centers[:n_target] elif len(centers) < n_target: # Add random points if pattern produced too few extra = n_target - len(centers) centers = np.vstack([centers, np.random.rand(extra, 2) * 0.8 + 0.1]) return centers
def init_grid_plus_one(n): """5x5 grid plus one extra circle.""" x = np.linspace(0.1, 0.9, 5) y = np.linspace(0.1, 0.9, 5) xv, yv = np.meshgrid(x, y) centers = np.column_stack((xv.flatten(), yv.flatten())) extra = np.array([[0.52, 0.52]]) # Slightly off center if len(centers) < n: centers = np.vstack((centers, extra)) return centers[:n]
def init_ring_pattern(n): """Concentric rings pattern.""" centers = np.zeros((n, 2)) centers[0] = [0.5, 0.5] # Inner ring for i in range(8): angle = 2 * np.pi * i / 8 centers[i + 1] = [0.5 + 0.25 * np.cos(angle), 0.5 + 0.25 * np.sin(angle)] # Outer ring remaining = n - 9 if remaining > 0: for i in range(remaining): angle = 2 * np.pi * i / remaining centers[i + 9] = [0.5 + 0.45 * np.cos(angle), 0.5 + 0.45 * np.sin(angle)] return centers
def init_hex_approx(n): """Procedural hexagonal fill.""" centers = [] delta = 0.18 y = 0.1 row = 0 while len(centers) < n and y < 0.95: if row % 2 == 0: x_start = 0.1 else: x_start = 0.1 + delta * 0.5 x = x_start while len(centers) < n and x < 0.95: centers.append([x, y]) x += delta y += delta * 0.866 row += 1 centers = np.array(centers) if len(centers) < n: fill = np.random.rand(n - len(centers), 2) centers = np.vstack((centers, fill)) return centers[:n]
def run_physics_simulation(n, initial_centers): """ Simulate soft-body circles to find a good packing arrangement. """ centers = initial_centers.copy() radii = np.ones(n) * 0.05 # Parameters iterations = 1200 dt = 0.01 damping = 0.8 growth_rate = 0.0005 velocities = np.zeros_like(centers) for _ in range(iterations): # 1. Distances delta = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(delta**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # 2. Overlaps radii_sum = radii[:, np.newaxis] + radii[np.newaxis, :] overlaps = radii_sum - dists np.fill_diagonal(overlaps, -1.0) # 3. Forces forces = np.zeros_like(centers) # Circle-Circle Repulsion mask = overlaps > 0 if np.any(mask): safe_dists = np.where(dists < 1e-6, 1.0, dists) dirs = delta / safe_dists[:, :, np.newaxis] f_mag = overlaps * 50.0 f_mag = np.maximum(f_mag, 0) forces += np.sum(dirs * f_mag[:, :, np.newaxis], axis=1) # Wall Repulsion l_ov = np.maximum(radii - centers[:, 0], 0) forces[:, 0] += l_ov * 100.0 r_ov = np.maximum(radii - (1 - centers[:, 0]), 0) forces[:, 0] -= r_ov * 100.0 b_ov = np.maximum(radii - centers[:, 1], 0) forces[:, 1] += b_ov * 100.0 t_ov = np.maximum(radii - (1 - centers[:, 1]), 0) forces[:, 1] -= t_ov * 100.0 # 4. Integrate velocities = velocities * damping + forces * dt centers += velocities * dt centers = np.clip(centers, 0.0, 1.0) # 5. Radius Dynamics total_overlap = np.sum(np.maximum(overlaps, 0), axis=1) wall_overlap = l_ov + r_ov + b_ov + t_ov pressure = total_overlap + wall_overlap dr = np.zeros(n) dr[pressure > 0] = -pressure[pressure > 0] dr[pressure == 0] = growth_rate radii += dr * dt radii = np.maximum(radii, 0.001) return centers, radii
def maximize_radii_for_centers(centers, initial_radii=None): """ Given fixed centers, compute the maximum possible radii that satisfy all constraints. """ n = centers.shape[0] # Distance to walls d_walls_x = np.minimum(centers[:, 0], 1 - centers[:, 0]) d_walls_y = np.minimum(centers[:, 1], 1 - centers[:, 1]) max_wall_radii = np.minimum(d_walls_x, d_walls_y) if initial_radii is not None: radii = initial_radii.copy() else: radii = max_wall_radii.copy() radii = np.minimum(radii, max_wall_radii) # Phase 1: Shrink to resolve overlaps for _ in range(200): changed = False for i in range(n): for j in range(i + 1, n): delta = centers[i] - centers[j] dist = np.sqrt(np.sum(delta**2)) sum_r = radii[i] + radii[j] if sum_r > dist: overlap = sum_r - dist if sum_r > 1e-9: fi = radii[i] / sum_r fj = radii[j] / sum_r # Shrink with small bias radii[i] -= overlap * fi * 1.0001 radii[j] -= overlap * fj * 1.0001 else: radii[i] -= overlap * 0.5 * 1.0001 radii[j] -= overlap * 0.5 * 1.0001 changed = True if not changed: break # Phase 2: Expand to fill gaps dists_mat = np.zeros((n, n)) for i in range(n): for j in range(i + 1, n): d = np.sqrt(np.sum((centers[i] - centers[j])**2)) dists_mat[i, j] = d dists_mat[j, i] = d np.fill_diagonal(dists_mat, np.inf) for _ in range(200): changed = False for i in range(n): # Max allowed by walls limit = max_wall_radii[i] # Max allowed by neighbors: r_i <= dist_ij - r_j constraints = dists_mat[i] - radii min_constraint = np.min(constraints) new_r = min(limit, min_constraint) new_r = max(new_r, 0.0) # Set target with tiny epsilon buffer for numerical stability target = new_r - 1e-10 if abs(radii[i] - target) > 1e-8: radii[i] = target changed = True if not changed: break return radii
# EVOLVE-BLOCK-END123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473--- a/original.py+++ b/original.py@@ -1,398 +1,440 @@ # EVOLVE-BLOCK-START import numpy as np from scipy.optimize import minimize, linprog from scipy.spatial import Voronoi -class VoronoiPopHybridPlus:+class VoronoiPopHybridElite: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42) def get_initial_configs(self): """Generates diverse initial configurations.""" configs = [] # 1. Explicit Lattice Patterns (Rows) # Targeted topologies for N=26 patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like- [4, 6, 6, 6, 4] # Rounded+ [4, 6, 6, 6, 4], # Rounded+ [3, 4, 5, 6, 5, 3] # Rounded small corners ] dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers) # Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c scale = 0.85 / np.max(span) if np.max(span) > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it shift = 0.5 - np.mean(centers, axis=0) centers += shift # Adjust count if len(centers) > self.n: # Keep closest to center dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(centers) # 2. Spiral Packing indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) scale = 0.44 c_spiral[:, 0] = 0.5 + scale * r * np.cos(theta) c_spiral[:, 1] = 0.5 + scale * r * np.sin(theta) configs.append(c_spiral) # 3. Boundary + Random Internal boundary = [] n_side = 6 x = np.linspace(0.1, 0.9, n_side) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) combined = np.vstack([boundary, internal]) configs.append(combined) elif needed < 0: configs.append(boundary[:self.n]) else: configs.append(boundary) # 4. Pure Random Relaxed rand_pts = 0.1 + 0.8 * self.rng.rand(self.n, 2) configs.append(rand_pts) return configs def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c = -np.ones(n) # Maximize sum(r) # Wall bounds bounds_list = [] for i in range(n): x, y = centers[i] # Ensure strictly inside 0..1 b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b))) # Pairwise constraints # r_i + r_j <= dist_ij diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq) A_ub = [] b_ub = [] for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j]) # Try Highs solver first (faster/robust) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass # Fallback to interior-point res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x # Last resort: just wall bounds return np.array([b[1] for b in bounds_list]) def find_largest_void_voronoi(self, centers): """Finds the largest void using Voronoi diagram with boundary reflection.""" # Reflect points across walls to create 'ghost' neighbors for correct boundary cells points_aug = [centers] # Reflect across x=0, x=1, y=0, y=1 points_aug.append(np.column_stack([-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([2-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], -centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], 2-centers[:,1]])) all_pts = np.vstack(points_aug) candidates = [] try: vor = Voronoi(all_pts) for v in vor.vertices: if 0 <= v[0] <= 1 and 0 <= v[1] <= 1: candidates.append(v) except: pass if not candidates: return 0.1 + 0.8 * self.rng.rand(2) cand = np.array(candidates) # Distance to centers diff = cand[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c = np.min(np.sqrt(np.sum(diff**2, axis=2)), axis=1) # Distance to walls d_w = np.min(np.column_stack([cand[:,0], 1-cand[:,0], cand[:,1], 1-cand[:,1]]), axis=1) # Maximize min clearance clearance = np.minimum(d_c, d_w) best_idx = np.argmax(clearance) return cand[best_idx] - def relax_points(self, points, steps=20, dt=0.01):- """Soft repulsion smoothing."""- pts = points.copy()+ def run_physics_relaxation(self, centers, steps=60):+ """+ Momentum-based relaxation with dynamic radii (fluffing).+ Allows the system to find a jammed state with less overlap energy.+ """+ c = centers.copy()+ n = len(c)+ # Start with small radii to allow movement+ r = np.ones(n) * 0.05+ velocities = np.zeros_like(c)+ dt = 0.005+ for _ in range(steps):- diff = pts[:, np.newaxis, :] - pts[np.newaxis, :, :]+ diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) - # Repulsion radius approx 0.15 (avg diam is ~0.2, so rad ~0.1)- force = np.maximum(0, 0.15 - dists) * 10.0- - delta = diff * (force / (dists + 1e-9))[:, :, np.newaxis]- displacement = np.sum(delta, axis=1)- pts += displacement * dt- pts = np.clip(pts, 0.0, 1.0)- return pts+ # Forces based on current radii+ r_sum = r[:, np.newaxis] + r[np.newaxis, :]+ overlaps = r_sum - dists+ + forces = np.zeros_like(c)+ + mask = overlaps > 0+ if np.any(mask):+ safe_dists = np.maximum(dists, 1e-6)+ dirs = diff / safe_dists[:, :, np.newaxis]+ f_mag = overlaps * 40.0 # Spring stiffness+ push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1)+ forces += push+ + # Wall repulsion+ k_wall = 80.0+ forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall+ forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall+ forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall+ forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall+ + # Damping and integration+ velocities = velocities * 0.5 + forces * dt+ c += velocities * dt+ c = np.clip(c, 0.0, 1.0)+ + # Radii Breathing (Fluffing)+ # Calculate pressure+ pressures = np.sum(np.maximum(overlaps, 0), axis=1)+ w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) ++ np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0))+ total_p = pressures + w_pressures+ + # Dynamics: Shrink fast on pressure, grow slowly in free space+ dr = np.where(total_p > 1e-4, -total_p * 0.5, 0.002)+ r += dr * dt+ r = np.maximum(r, 0.01) # Min radius+ + return c, r def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:] # Objective: Maximize sum(r) obj = -np.sum(r) if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2) # Penalties # 1. Wall Penetration w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2) # 2. Pairwise Overlap diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq) r_matrix = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_matrix - dists)[mask]**2) return obj + mu * (w_pen + ov_pen) def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n) x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n current_x = x0 # 5 Phases for robustness and precision phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases] reg = 5.0 if equal_bias else 0.0 for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 - # Use fewer iterations for early low-stiffness phases, more for later+ # Adaptive iter limit iter_limit = 250 if mu > 5000 else 150 res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x return current_x[:2*n].reshape((n, 2)), current_x[2*n:] def optimize(self): configs = self.get_initial_configs() best_global_res = (None, None, -1.0) # 1. Seed Screening for c in configs: # Phase 1: Equalize radii to find structure c_opt, r_soft = self.local_optimization(c, equal_bias=True) # Phase 2: Relax sizes c_opt, _ = self.local_optimization(c_opt, radii_init=r_soft, equal_bias=False) r_lp = self.solve_lp_radii(c_opt) score = np.sum(r_lp) if score > best_global_res[2]: best_global_res = (c_opt, r_lp, score) # 2. Basin Hopping with Hybrid Moves curr_c = best_global_res[0] curr_r = best_global_res[1] curr_score = best_global_res[2] best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score n_iter = 30 temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() - # Decision: Pop vs Relaxed Jitter- is_pop = (self.rng.rand() < 0.4) # 40% chance to pop+ # Decision: Pop vs Physics Jitter+ is_pop = (self.rng.rand() < 0.4) if is_pop: # Stochastic Pop: Select from the bottom 3 smallest circles- # This prevents cycling the same circle if there are multiple bottlenecks sorted_indices = np.argsort(curr_r) candidates = sorted_indices[:3] target_idx = self.rng.choice(candidates) other_indices = [idx for idx in range(self.n) if idx != target_idx] others = curr_c[other_indices] # Move to largest Voronoi void target_pos = self.find_largest_void_voronoi(others) trial_c[target_idx] = target_pos - # Small jitter to break symmetries+ # Small jitter trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init = curr_r.copy() trial_r_init[target_idx] = 0.05 else:- # Relaxed Jitter: Noise + Physics Smoothing+ # Physics Jitter: Perturb + Dynamic Relaxation mag = 0.03 * np.exp(-i/(n_iter*0.8)) perturb = mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c + perturb, 0.0, 1.0) - # Apply physics relaxation to resolve severe overlaps cheaply- trial_c = self.relax_points(trial_c, steps=25)- - trial_r_init = curr_r * 0.95 -- # Run Local Optimization (High Stiffness)- c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.5)+ # Use physics relaxation (fluffing) to find a good local basin+ trial_c, r_hint = self.run_physics_relaxation(trial_c, steps=60)+ + # Use the hint radii from physics, but slightly smaller to allow optimizer room+ trial_r_init = r_hint * 0.95++ # Run Local Optimization+ # Use moderately high stiffness to ensure we respect constraints+ c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.8) # Exact Evaluation via LP r_lp_new = self.solve_lp_radii(c_new) score_new = np.sum(r_lp_new) # Metropolis Acceptance delta = score_new - curr_score accept = False if delta > 0: accept = True elif self.rng.rand() < np.exp(delta / temperature): accept = True if accept: curr_c = c_new curr_r = r_lp_new curr_score = score_new if score_new > best_score: best_score = score_new best_c = c_new.copy() best_r = r_lp_new.copy() temperature *= 0.9 # Cool down # 3. Final High-Precision Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), # High penalty method='L-BFGS-B', bounds=bounds,- options={'maxiter': 500, 'ftol': 1e-8}+ options={'maxiter': 600, 'ftol': 1e-8} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c) return final_c, final_r def construct_packing():- opt = VoronoiPopHybridPlus(n=26)+ opt = VoronoiPopHybridElite(n=26) return opt.optimize() def compute_max_radii(centers):- opt = VoronoiPopHybridPlus(n=len(centers))+ opt = VoronoiPopHybridElite(n=len(centers)) return opt.solve_lp_radii(centers) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii # EVOLVE-BLOCK-END # This part remains fixed (not evolved) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440# EVOLVE-BLOCK-STARTimport numpy as npfrom scipy.optimize import minimize, linprogfrom scipy.spatial import Voronoi
class VoronoiPopHybridElite: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
def get_initial_configs(self): """Generates diverse initial configurations.""" configs = []
# 1. Explicit Lattice Patterns (Rows) # Targeted topologies for N=26 patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Rounded small corners ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
# Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c scale = 0.85 / np.max(span) if np.max(span) > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it shift = 0.5 - np.mean(centers, axis=0) centers += shift
# Adjust count if len(centers) > self.n: # Keep closest to center dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(centers)
# 2. Spiral Packing indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) scale = 0.44 c_spiral[:, 0] = 0.5 + scale * r * np.cos(theta) c_spiral[:, 1] = 0.5 + scale * r * np.sin(theta) configs.append(c_spiral)
# 3. Boundary + Random Internal boundary = [] n_side = 6 x = np.linspace(0.1, 0.9, n_side) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) combined = np.vstack([boundary, internal]) configs.append(combined) elif needed < 0: configs.append(boundary[:self.n]) else: configs.append(boundary)
# 4. Pure Random Relaxed rand_pts = 0.1 + 0.8 * self.rng.rand(self.n, 2) configs.append(rand_pts)
return configs
def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c = -np.ones(n) # Maximize sum(r)
# Wall bounds bounds_list = [] for i in range(n): x, y = centers[i] # Ensure strictly inside 0..1 b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
# Pairwise constraints # r_i + r_j <= dist_ij diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq)
A_ub = [] b_ub = []
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
# Try Highs solver first (faster/robust) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
# Fallback to interior-point res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
# Last resort: just wall bounds return np.array([b[1] for b in bounds_list])
def find_largest_void_voronoi(self, centers): """Finds the largest void using Voronoi diagram with boundary reflection.""" # Reflect points across walls to create 'ghost' neighbors for correct boundary cells points_aug = [centers] # Reflect across x=0, x=1, y=0, y=1 points_aug.append(np.column_stack([-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([2-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], -centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], 2-centers[:,1]])) all_pts = np.vstack(points_aug) candidates = [] try: vor = Voronoi(all_pts) for v in vor.vertices: if 0 <= v[0] <= 1 and 0 <= v[1] <= 1: candidates.append(v) except: pass if not candidates: return 0.1 + 0.8 * self.rng.rand(2) cand = np.array(candidates) # Distance to centers diff = cand[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c = np.min(np.sqrt(np.sum(diff**2, axis=2)), axis=1) # Distance to walls d_w = np.min(np.column_stack([cand[:,0], 1-cand[:,0], cand[:,1], 1-cand[:,1]]), axis=1) # Maximize min clearance clearance = np.minimum(d_c, d_w) best_idx = np.argmax(clearance) return cand[best_idx]
def run_physics_relaxation(self, centers, steps=60): """ Momentum-based relaxation with dynamic radii (fluffing). Allows the system to find a jammed state with less overlap energy. """ c = centers.copy() n = len(c) # Start with small radii to allow movement r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005 for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # Forces based on current radii r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists forces = np.zeros_like(c) mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 # Spring stiffness push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push # Wall repulsion k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall # Damping and integration velocities = velocities * 0.5 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0) # Radii Breathing (Fluffing) # Calculate pressure pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures # Dynamics: Shrink fast on pressure, grow slowly in free space dr = np.where(total_p > 1e-4, -total_p * 0.5, 0.002) r += dr * dt r = np.maximum(r, 0.01) # Min radius return c, r
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
# Objective: Maximize sum(r) obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
# Penalties # 1. Wall Penetration w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
# 2. Pairwise Overlap diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_matrix = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_matrix - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0 # 5 Phases for robustness and precision phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 # Adaptive iter limit iter_limit = 250 if mu > 5000 else 150
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs()
best_global_res = (None, None, -1.0)
# 1. Seed Screening for c in configs: # Phase 1: Equalize radii to find structure c_opt, r_soft = self.local_optimization(c, equal_bias=True) # Phase 2: Relax sizes c_opt, _ = self.local_optimization(c_opt, radii_init=r_soft, equal_bias=False)
r_lp = self.solve_lp_radii(c_opt) score = np.sum(r_lp) if score > best_global_res[2]: best_global_res = (c_opt, r_lp, score)
# 2. Basin Hopping with Hybrid Moves curr_c = best_global_res[0] curr_r = best_global_res[1] curr_score = best_global_res[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 30 temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() # Decision: Pop vs Physics Jitter is_pop = (self.rng.rand() < 0.4)
if is_pop: # Stochastic Pop: Select from the bottom 3 smallest circles sorted_indices = np.argsort(curr_r) candidates = sorted_indices[:3] target_idx = self.rng.choice(candidates) other_indices = [idx for idx in range(self.n) if idx != target_idx] others = curr_c[other_indices] # Move to largest Voronoi void target_pos = self.find_largest_void_voronoi(others) trial_c[target_idx] = target_pos # Small jitter trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init = curr_r.copy() trial_r_init[target_idx] = 0.05 else: # Physics Jitter: Perturb + Dynamic Relaxation mag = 0.03 * np.exp(-i/(n_iter*0.8)) perturb = mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c + perturb, 0.0, 1.0) # Use physics relaxation (fluffing) to find a good local basin trial_c, r_hint = self.run_physics_relaxation(trial_c, steps=60) # Use the hint radii from physics, but slightly smaller to allow optimizer room trial_r_init = r_hint * 0.95
# Run Local Optimization # Use moderately high stiffness to ensure we respect constraints c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.8)
# Exact Evaluation via LP r_lp_new = self.solve_lp_radii(c_new) score_new = np.sum(r_lp_new)
# Metropolis Acceptance delta = score_new - curr_score accept = False if delta > 0: accept = True elif self.rng.rand() < np.exp(delta / temperature): accept = True
if accept: curr_c = c_new curr_r = r_lp_new curr_score = score_new
if score_new > best_score: best_score = score_new best_c = c_new.copy() best_r = r_lp_new.copy() temperature *= 0.9 # Cool down # 3. Final High-Precision Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), # High penalty method='L-BFGS-B', bounds=bounds, options={'maxiter': 600, 'ftol': 1e-8} )
final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = VoronoiPopHybridElite(n=26) return opt.optimize()
def compute_max_radii(centers): opt = VoronoiPopHybridElite(n=len(centers)) return opt.solve_lp_radii(centers)
def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398# EVOLVE-BLOCK-STARTimport numpy as npfrom scipy.optimize import minimize, linprogfrom scipy.spatial import Voronoi
class VoronoiPopHybridPlus: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
def get_initial_configs(self): """Generates diverse initial configurations.""" configs = []
# 1. Explicit Lattice Patterns (Rows) # Targeted topologies for N=26 patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4] # Rounded ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
# Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c scale = 0.85 / np.max(span) if np.max(span) > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it shift = 0.5 - np.mean(centers, axis=0) centers += shift
# Adjust count if len(centers) > self.n: # Keep closest to center dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(centers)
# 2. Spiral Packing indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) scale = 0.44 c_spiral[:, 0] = 0.5 + scale * r * np.cos(theta) c_spiral[:, 1] = 0.5 + scale * r * np.sin(theta) configs.append(c_spiral)
# 3. Boundary + Random Internal boundary = [] n_side = 6 x = np.linspace(0.1, 0.9, n_side) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) combined = np.vstack([boundary, internal]) configs.append(combined) elif needed < 0: configs.append(boundary[:self.n]) else: configs.append(boundary)
# 4. Pure Random Relaxed rand_pts = 0.1 + 0.8 * self.rng.rand(self.n, 2) configs.append(rand_pts)
return configs
def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c = -np.ones(n) # Maximize sum(r)
# Wall bounds bounds_list = [] for i in range(n): x, y = centers[i] # Ensure strictly inside 0..1 b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
# Pairwise constraints # r_i + r_j <= dist_ij diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq)
A_ub = [] b_ub = []
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
# Try Highs solver first (faster/robust) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
# Fallback to interior-point res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
# Last resort: just wall bounds return np.array([b[1] for b in bounds_list])
def find_largest_void_voronoi(self, centers): """Finds the largest void using Voronoi diagram with boundary reflection.""" # Reflect points across walls to create 'ghost' neighbors for correct boundary cells points_aug = [centers] # Reflect across x=0, x=1, y=0, y=1 points_aug.append(np.column_stack([-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([2-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], -centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], 2-centers[:,1]])) all_pts = np.vstack(points_aug) candidates = [] try: vor = Voronoi(all_pts) for v in vor.vertices: if 0 <= v[0] <= 1 and 0 <= v[1] <= 1: candidates.append(v) except: pass if not candidates: return 0.1 + 0.8 * self.rng.rand(2) cand = np.array(candidates) # Distance to centers diff = cand[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c = np.min(np.sqrt(np.sum(diff**2, axis=2)), axis=1) # Distance to walls d_w = np.min(np.column_stack([cand[:,0], 1-cand[:,0], cand[:,1], 1-cand[:,1]]), axis=1) # Maximize min clearance clearance = np.minimum(d_c, d_w) best_idx = np.argmax(clearance) return cand[best_idx]
def relax_points(self, points, steps=20, dt=0.01): """Soft repulsion smoothing.""" pts = points.copy() for _ in range(steps): diff = pts[:, np.newaxis, :] - pts[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # Repulsion radius approx 0.15 (avg diam is ~0.2, so rad ~0.1) force = np.maximum(0, 0.15 - dists) * 10.0 delta = diff * (force / (dists + 1e-9))[:, :, np.newaxis] displacement = np.sum(delta, axis=1) pts += displacement * dt pts = np.clip(pts, 0.0, 1.0) return pts
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
# Objective: Maximize sum(r) obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
# Penalties # 1. Wall Penetration w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
# 2. Pairwise Overlap diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_matrix = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_matrix - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0 # 5 Phases for robustness and precision phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 # Use fewer iterations for early low-stiffness phases, more for later iter_limit = 250 if mu > 5000 else 150
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs()
best_global_res = (None, None, -1.0)
# 1. Seed Screening for c in configs: # Phase 1: Equalize radii to find structure c_opt, r_soft = self.local_optimization(c, equal_bias=True) # Phase 2: Relax sizes c_opt, _ = self.local_optimization(c_opt, radii_init=r_soft, equal_bias=False)
r_lp = self.solve_lp_radii(c_opt) score = np.sum(r_lp) if score > best_global_res[2]: best_global_res = (c_opt, r_lp, score)
# 2. Basin Hopping with Hybrid Moves curr_c = best_global_res[0] curr_r = best_global_res[1] curr_score = best_global_res[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 30 temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() # Decision: Pop vs Relaxed Jitter is_pop = (self.rng.rand() < 0.4) # 40% chance to pop
if is_pop: # Stochastic Pop: Select from the bottom 3 smallest circles # This prevents cycling the same circle if there are multiple bottlenecks sorted_indices = np.argsort(curr_r) candidates = sorted_indices[:3] target_idx = self.rng.choice(candidates) other_indices = [idx for idx in range(self.n) if idx != target_idx] others = curr_c[other_indices] # Move to largest Voronoi void target_pos = self.find_largest_void_voronoi(others) trial_c[target_idx] = target_pos # Small jitter to break symmetries trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init = curr_r.copy() trial_r_init[target_idx] = 0.05 else: # Relaxed Jitter: Noise + Physics Smoothing mag = 0.03 * np.exp(-i/(n_iter*0.8)) perturb = mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c + perturb, 0.0, 1.0) # Apply physics relaxation to resolve severe overlaps cheaply trial_c = self.relax_points(trial_c, steps=25) trial_r_init = curr_r * 0.95
# Run Local Optimization (High Stiffness) c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.5)
# Exact Evaluation via LP r_lp_new = self.solve_lp_radii(c_new) score_new = np.sum(r_lp_new)
# Metropolis Acceptance delta = score_new - curr_score accept = False if delta > 0: accept = True elif self.rng.rand() < np.exp(delta / temperature): accept = True
if accept: curr_c = c_new curr_r = r_lp_new curr_score = score_new
if score_new > best_score: best_score = score_new best_c = c_new.copy() best_r = r_lp_new.copy() temperature *= 0.9 # Cool down # 3. Final High-Precision Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), # High penalty method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-8} )
final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = VoronoiPopHybridPlus(n=26) return opt.optimize()
def compute_max_radii(centers): opt = VoronoiPopHybridPlus(n=len(centers)) return opt.solve_lp_radii(centers)
def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431# EVOLVE-BLOCK-STARTimport numpy as npfrom scipy.optimize import minimize, linprogfrom scipy.spatial import Voronoi
class VoronoiPopHybridElite: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
def get_initial_configs(self): """Generates diverse initial configurations.""" configs = []
# 1. Explicit Lattice Patterns (Rows) # Targeted topologies for N=26 patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Rounded small corners ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
# Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c scale = 0.85 / np.max(span) if np.max(span) > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it shift = 0.5 - np.mean(centers, axis=0) centers += shift
# Adjust count if len(centers) > self.n: # Keep closest to center dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(centers)
# 2. Spiral Packing indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) scale = 0.44 c_spiral[:, 0] = 0.5 + scale * r * np.cos(theta) c_spiral[:, 1] = 0.5 + scale * r * np.sin(theta) configs.append(c_spiral)
# 3. Boundary + Random Internal boundary = [] n_side = 6 x = np.linspace(0.1, 0.9, n_side) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) combined = np.vstack([boundary, internal]) configs.append(combined) elif needed < 0: configs.append(boundary[:self.n]) else: configs.append(boundary)
# 4. Pure Random Relaxed rand_pts = 0.1 + 0.8 * self.rng.rand(self.n, 2) configs.append(rand_pts)
return configs
def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c = -np.ones(n) # Maximize sum(r)
# Wall bounds bounds_list = [] for i in range(n): x, y = centers[i] # Ensure strictly inside 0..1 b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
# Pairwise constraints # r_i + r_j <= dist_ij diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq)
A_ub = [] b_ub = []
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
# Try Highs solver first (faster/robust) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
# Fallback to interior-point res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
# Last resort: just wall bounds return np.array([b[1] for b in bounds_list])
def find_largest_void_voronoi(self, centers): """Finds the largest void using Voronoi diagram with boundary reflection.""" # Reflect points across walls to create 'ghost' neighbors for correct boundary cells points_aug = [centers] # Reflect across x=0, x=1, y=0, y=1 points_aug.append(np.column_stack([-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([2-centers[:,0], centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], -centers[:,1]])) points_aug.append(np.column_stack([centers[:,0], 2-centers[:,1]])) all_pts = np.vstack(points_aug) candidates = [] try: vor = Voronoi(all_pts) for v in vor.vertices: if 0 <= v[0] <= 1 and 0 <= v[1] <= 1: candidates.append(v) except: pass if not candidates: return 0.1 + 0.8 * self.rng.rand(2) cand = np.array(candidates) # Distance to centers diff = cand[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c = np.min(np.sqrt(np.sum(diff**2, axis=2)), axis=1) # Distance to walls d_w = np.min(np.column_stack([cand[:,0], 1-cand[:,0], cand[:,1], 1-cand[:,1]]), axis=1) # Maximize min clearance clearance = np.minimum(d_c, d_w) best_idx = np.argmax(clearance) return cand[best_idx]
def run_physics_relaxation(self, centers, steps=60): """ Momentum-based relaxation with dynamic radii (fluffing). Allows the system to find a jammed state with less overlap energy. """ c = centers.copy() n = len(c) # Start with small radii to allow movement r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005 for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) # Forces based on current radii r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists forces = np.zeros_like(c) mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 # Spring stiffness push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push # Wall repulsion k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall # Damping and integration velocities = velocities * 0.5 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0) # Radii Breathing (Fluffing) # Calculate pressure pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures # Dynamics: Shrink fast on pressure, grow slowly in free space dr = np.where(total_p > 1e-4, -total_p * 0.5, 0.002) r += dr * dt r = np.maximum(r, 0.01) # Min radius return c, r
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
# Objective: Maximize sum(r) obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
# Penalties # 1. Wall Penetration w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
# 2. Pairwise Overlap diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_matrix = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_matrix - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0 # 5 Phases for robustness and precision phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 # Adaptive iter limit iter_limit = 250 if mu > 5000 else 150
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs()
best_global_res = (None, None, -1.0)
# 1. Seed Screening for c in configs: # Phase 1: Equalize radii to find structure c_opt, r_soft = self.local_optimization(c, equal_bias=True) # Phase 2: Relax sizes c_opt, _ = self.local_optimization(c_opt, radii_init=r_soft, equal_bias=False)
r_lp = self.solve_lp_radii(c_opt) score = np.sum(r_lp) if score > best_global_res[2]: best_global_res = (c_opt, r_lp, score)
# 2. Basin Hopping with Hybrid Moves curr_c = best_global_res[0] curr_r = best_global_res[1] curr_score = best_global_res[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 30 temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() # Decision: Pop vs Physics Jitter is_pop = (self.rng.rand() < 0.4)
if is_pop: # Stochastic Pop: Select from the bottom 3 smallest circles sorted_indices = np.argsort(curr_r) candidates = sorted_indices[:3] target_idx = self.rng.choice(candidates) other_indices = [idx for idx in range(self.n) if idx != target_idx] others = curr_c[other_indices] # Move to largest Voronoi void target_pos = self.find_largest_void_voronoi(others) trial_c[target_idx] = target_pos # Small jitter trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init = curr_r.copy() trial_r_init[target_idx] = 0.05 else: # Physics Jitter: Perturb + Dynamic Relaxation mag = 0.03 * np.exp(-i/(n_iter*0.8)) perturb = mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c + perturb, 0.0, 1.0) # Use physics relaxation (fluffing) to find a good local basin trial_c, r_hint = self.run_physics_relaxation(trial_c, steps=60) # Use the hint radii from physics, but slightly smaller to allow optimizer room trial_r_init = r_hint * 0.95
# Run Local Optimization # Use moderately high stiffness to ensure we respect constraints c_new, r_soft_new = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.8)
# Exact Evaluation via LP r_lp_new = self.solve_lp_radii(c_new) score_new = np.sum(r_lp_new)
# Metropolis Acceptance delta = score_new - curr_score accept = False if delta > 0: accept = True elif self.rng.rand() < np.exp(delta / temperature): accept = True
if accept: curr_c = c_new curr_r = r_lp_new curr_score = score_new
if score_new > best_score: best_score = score_new best_c = c_new.copy() best_r = r_lp_new.copy() temperature *= 0.9 # Cool down # 3. Final High-Precision Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), # High penalty method='L-BFGS-B', bounds=bounds, options={'maxiter': 600, 'ftol': 1e-8} )
final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = VoronoiPopHybridElite(n=26) return opt.optimize()
def compute_max_radii(centers): opt = VoronoiPopHybridElite(n=len(centers)) return opt.solve_lp_radii(centers)
def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii# EVOLVE-BLOCK-END123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572--- a/original.py+++ b/original.py@@ -1,469 +1,380 @@ # EVOLVE-BLOCK-START """ Refined Hybrid Pop Optimizer: Merges 'HybridPopOptimizer' (Robust Optimization, Regularization, Physics Pre-conditioning) with 'Basin Hopping Refinement' (Precise Void Finding via Nelder-Mead). """ import numpy as np from scipy.optimize import minimize, linprog class RefinedHybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42) # Grid for void finding (coarse search)- self.grid_res = 60+ self.grid_res = 50 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy]) + def generate_lattice_patterns(self):+ """Dynamically generates hexagonal row compositions for N=26."""+ patterns = []+ def backtrack(current_rows):+ s = sum(current_rows)+ if s == self.n:+ patterns.append(current_rows)+ return+ if s > self.n:+ return++ last = current_rows[-1]+ candidates = [last-1, last, last+1]+ # Prune reasonable widths+ candidates = [c for c in candidates if 3 <= c <= 9]++ for c in candidates:+ backtrack(current_rows + [c])++ # Start with row lengths 4 to 8+ for start in range(4, 9):+ backtrack([start])++ # Filter for square-ish aspect ratio to prioritize likely candidates+ # Height ~= rows * 0.866, Width ~= max_row+ valid = []+ for p in patterns:+ h = len(p) * 0.866+ w = max(p)+ ratio = h / w+ if 0.7 <= ratio <= 1.45:+ valid.append(p)++ # Downsample if too many, favoring variety+ if len(valid) > 15:+ # Deterministic subset+ indices = np.linspace(0, len(valid)-1, 15, dtype=int)+ valid = [valid[i] for i in indices]++ return valid+ def get_initial_configs(self):- """Generates diverse initial configurations from multiple strategies."""+ """Generates diverse initial configurations.""" configs = [] - # 1. Explicit Lattice Patterns- patterns = [- [5, 5, 6, 5, 5], # Symmetric hex- [6, 5, 6, 5, 4], # Staggered- [5, 6, 5, 5, 5], # Center heavy- [6, 7, 6, 7], # Two-block- [5, 5, 5, 5, 6], # Bottom heavy- [4, 5, 6, 6, 5], # Asymmetric- [6, 6, 6, 6, 2], # Box-like- [4, 6, 6, 6, 4], # Rounded- [3, 4, 5, 6, 5, 3] # Rounded small corners- ]+ # 1. Automated Lattice Patterns+ patterns = self.generate_lattice_patterns()+ # Add a few known good ones manually just in case+ known = [[5, 5, 6, 5, 5], [6, 7, 6, 7], [6, 5, 6, 5, 4]]+ for k in known:+ if k not in patterns:+ patterns.append(k) dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers) if len(centers) > 0:- # Normalize and center min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09- curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center)-- # Fix count- if len(centers) > self.n:- dists = np.sum((centers - 0.5)**2, axis=1)- idx = np.argsort(dists)- centers = centers[idx[:self.n]]- elif len(centers) < self.n:- needed = self.n - len(centers)- fill = np.random.rand(needed, 2) * 0.8 + 0.1- centers = np.vstack([centers, fill])- configs.append(('lattice', centers)) - # 2. Spiral Packing+ # 2. Heuristics configs.append(('spiral', self.init_spiral()))-- # 3. Generic Hex configs.append(('hex_generic', self.generate_generic_hex()))-- # 4. Boundary + Random- configs.append(('boundary', self.init_boundary()))-- # 5. Grid Compact configs.append(('grid_5x5', self.init_grid_compact())) - # 6. Pure Random+ # 3. Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2))) return configs def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]]- min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1-- def init_boundary(self):- boundary = []- x = np.linspace(0.1, 0.9, 6)- for xi in x:- boundary.append([xi, 0.1])- boundary.append([xi, 0.9])- y = np.linspace(0.25, 0.75, 4)- for yi in y:- boundary.append([0.1, yi])- boundary.append([0.9, yi])- boundary = np.array(boundary)-- needed = self.n - len(boundary)- if needed > 0:- internal = 0.2 + 0.6 * self.rng.rand(needed, 2)- return np.vstack([boundary, internal])- elif needed < 0:- return boundary[:self.n]- return boundary def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c - def run_physics_relaxation(self, centers, steps=150):- """Momentum-based relaxation with dynamic radii to find jammed states."""+ def run_physics_relaxation(self, centers, steps=120): c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005- for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq)-- # Forces based on current radii r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists- forces = np.zeros_like(c)- mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push-- # Walls k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall-- # Integrate velocities = velocities * 0.7 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0)-- # Radii Dynamics pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures-- # Shrink fast on overlap, grow slowly otherwise dr = np.where(total_p > 0, -total_p * 0.1, 0.001) r += dr * dt r = np.maximum(r, 0.01)- return c, r def find_largest_void(self, centers):- """- Refined void finding.- 1. Coarse grid search maximizing min(dist_to_centers, dist_to_walls).- 2. Local refinement using Nelder-Mead.- """- # 1. Coarse Grid diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dist_centers = np.sqrt(np.min(dists_sq, axis=1))-- # Walls d_left = self.grid_pts[:, 0] d_right = 1.0 - self.grid_pts[:, 0] d_bottom = self.grid_pts[:, 1] d_top = 1.0 - self.grid_pts[:, 1] min_dist_walls = np.minimum(np.minimum(d_left, d_right), np.minimum(d_bottom, d_top))-- # Capacity capacity = np.minimum(min_dist_centers, min_dist_walls) best_idx = np.argmax(capacity) x0 = self.grid_pts[best_idx] - # 2. Local Refinement def neg_capacity(p):- if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1):- return 1.0+ if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0 d_c = np.min(np.linalg.norm(centers - p, axis=1)) d_w = min(p[0], 1.0 - p[0], p[1], 1.0 - p[1]) return -min(d_c, d_w) res = minimize( neg_capacity, x0, method='Nelder-Mead', bounds=[(0.0, 1.0), (0.0, 1.0)], options={'xatol': 1e-4, 'fatol': 1e-4, 'maxiter': 50} )-- # Check if valid return- if res.success or res.message:- return res.x- return x0+ return res.x if (res.success or res.message) else x0 def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n)- bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))- A_ub = [] b_ub = []- diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2))- for i in range(n): for j in range(i+1, n): row = np.zeros(n)- row[i] = 1.0- row[j] = 1.0- A_ub.append(row)- b_ub.append(dists[i, j])-+ row[i] = 1.0; row[j] = 1.0+ A_ub.append(row); b_ub.append(dists[i, j]) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass- res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point')- if res.success: return res.x-- return np.array([b[1] for b in bounds_list])+ return res.x if res.success else np.array([b[1] for b in bounds_list]) def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]- obj = -np.sum(r)- if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)-- w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 +- np.maximum(0, r - (1 - c[:, 0]))**2 +- np.maximum(0, r - c[:, 1])**2 +- np.maximum(0, r - (1 - c[:, 1]))**2)-+ w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 ++ np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2) diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)- r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2)- return obj + mu * (w_pen + ov_pen) - def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False):+ def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False, mode='normal'): n = self.n- if radii_init is None:- radii_init = 0.05 * np.ones(n)-+ if radii_init is None: radii_init = 0.05 * np.ones(n) x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n- current_x = x0 - phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0]+ if mode == 'fast':+ phases = [100.0, 10000.0]+ else:+ phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0]+ phases = [p * stiffness_scale for p in phases]- reg = 5.0 if equal_bias else 0.0 for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0- iter_limit = 250 if mu > 5000 else 150-- res = minimize(- self._loss,- current_x,- args=(n, mu, current_reg),- method='L-BFGS-B',- bounds=bounds,- options={'maxiter': iter_limit, 'ftol': 1e-5}- )+ iter_limit = 200 if mu > 5000 else 100+ res = minimize(self._loss, current_x, args=(n, mu, current_reg),+ method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5}) current_x = res.x- return current_x[:2*n].reshape((n, 2)), current_x[2*n:] def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0) - # 1. Global Search over Seeds+ # 1. Fast Screening for name, c_init in configs: c_relaxed, r_relaxed = self.run_physics_relaxation(c_init)-- # Phase 1: Regularized (Start with relaxed radii hint)- c_p1, r_p1 = self.local_optimization(c_relaxed, radii_init=r_relaxed, equal_bias=True)-- # Phase 2: Variable- c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False)-+ # Use 'fast' mode for screening+ c_p1, r_p1 = self.local_optimization(c_relaxed, radii_init=r_relaxed, equal_bias=True, mode='fast')+ c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False, mode='fast') r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp)- if score > best_global[2]: best_global = (c_p2, r_lp, score) - # 2. Basin Hopping with Pop and Swap+ # 2. Basin Hopping curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2]-- best_c = curr_c.copy()- best_r = curr_r.copy()- best_score = curr_score-- n_iter = 30+ best_c, best_r, best_score = curr_c.copy(), curr_r.copy(), curr_score++ n_iter = 40 # Increased iterations due to fast mode temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() trial_r_init = curr_r.copy()-- # Move selection rand_val = self.rng.rand() - if rand_val < 0.35:- # Pop Move: Relocate worst circle to largest void+ if rand_val < 0.4:+ # Pop Move with Void-Aware Radius min_idx = np.argmin(curr_r)- others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask]) + # Estimate clearance for radius init+ d_c = np.min(np.linalg.norm(curr_c[others_mask] - target, axis=1))+ d_w = min(target[0], 1.0-target[0], target[1], 1.0-target[1])+ new_r = max(0.01, min(d_c, d_w) - 0.005)+ trial_c[min_idx] = target- trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5)+ trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) # Micro jitter trial_c = np.clip(trial_c, 0.0, 1.0)-- trial_r_init[min_idx] = 0.05-- elif rand_val < 0.55:- # Swap Move: Exchange worst circle with a large one+ trial_r_init[min_idx] = new_r++ elif rand_val < 0.6:+ # Swap Move min_idx = np.argmin(curr_r)-- # Pick a large circle (top 50%)- sorted_indices = np.argsort(curr_r)- candidates = sorted_indices[self.n // 2:]+ candidates = np.argsort(curr_r)[self.n // 2:] target_idx = candidates[self.rng.randint(len(candidates))]-- # Swap positions pos_min = trial_c[min_idx].copy()- pos_target = trial_c[target_idx].copy()- trial_c[min_idx] = pos_target+ trial_c[min_idx] = trial_c[target_idx] trial_c[target_idx] = pos_min-- # Reset radii to allow re-fitting trial_r_init[min_idx] = 0.05 trial_r_init[target_idx] = 0.05-- # Slight jitter to break symmetry trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)- else: # Shake Move- mag = 0.02 * np.exp(-i/(n_iter*0.8))+ mag = 0.025 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0) - # Fast optimization- c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)-- # Evaluate+ # Fast optimization for exploration+ c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.5, mode='fast') r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new) - # Accept? delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy()- temperature *= 0.95-- # 3. Final Polish+ temperature *= 0.9++ # 3. Final Polish (Full precision) x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n- res = minimize(- self._loss,- x0,- args=(self.n, 100000.0, 0.0),- method='L-BFGS-B',- bounds=bounds,- options={'maxiter': 500, 'ftol': 1e-7}+ self._loss, x0, args=(self.n, 100000.0, 0.0),+ method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-8} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)- return final_c, final_r def construct_packing(): opt = RefinedHybridPopOptimizer(n=26) return opt.optimize() def compute_max_radii(centers): opt = RefinedHybridPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers) # EVOLVE-BLOCK-END # This part remains fixed (not evolved) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380# EVOLVE-BLOCK-START"""Refined Hybrid Pop Optimizer:Merges 'HybridPopOptimizer' (Robust Optimization, Regularization, Physics Pre-conditioning)with 'Basin Hopping Refinement' (Precise Void Finding via Nelder-Mead)."""
import numpy as npfrom scipy.optimize import minimize, linprog
class RefinedHybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
# Grid for void finding (coarse search) self.grid_res = 50 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def generate_lattice_patterns(self): """Dynamically generates hexagonal row compositions for N=26.""" patterns = [] def backtrack(current_rows): s = sum(current_rows) if s == self.n: patterns.append(current_rows) return if s > self.n: return
last = current_rows[-1] candidates = [last-1, last, last+1] # Prune reasonable widths candidates = [c for c in candidates if 3 <= c <= 9]
for c in candidates: backtrack(current_rows + [c])
# Start with row lengths 4 to 8 for start in range(4, 9): backtrack([start])
# Filter for square-ish aspect ratio to prioritize likely candidates # Height ~= rows * 0.866, Width ~= max_row valid = [] for p in patterns: h = len(p) * 0.866 w = max(p) ratio = h / w if 0.7 <= ratio <= 1.45: valid.append(p)
# Downsample if too many, favoring variety if len(valid) > 15: # Deterministic subset indices = np.linspace(0, len(valid)-1, 15, dtype=int) valid = [valid[i] for i in indices]
return valid
def get_initial_configs(self): """Generates diverse initial configurations.""" configs = []
# 1. Automated Lattice Patterns patterns = self.generate_lattice_patterns() # Add a few known good ones manually just in case known = [[5, 5, 6, 5, 5], [6, 7, 6, 7], [6, 5, 6, 5, 4]] for k in known: if k not in patterns: patterns.append(k)
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09 curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center) configs.append(('lattice', centers))
# 2. Heuristics configs.append(('spiral', self.init_spiral())) configs.append(('hex_generic', self.generate_generic_hex())) configs.append(('grid_5x5', self.init_grid_compact()))
# 3. Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2)))
return configs
def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c
def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]] min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c
def run_physics_relaxation(self, centers, steps=120): c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005 for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists forces = np.zeros_like(c) mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall velocities = velocities * 0.7 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0) pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures dr = np.where(total_p > 0, -total_p * 0.1, 0.001) r += dr * dt r = np.maximum(r, 0.01) return c, r
def find_largest_void(self, centers): diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dist_centers = np.sqrt(np.min(dists_sq, axis=1)) d_left = self.grid_pts[:, 0] d_right = 1.0 - self.grid_pts[:, 0] d_bottom = self.grid_pts[:, 1] d_top = 1.0 - self.grid_pts[:, 1] min_dist_walls = np.minimum(np.minimum(d_left, d_right), np.minimum(d_bottom, d_top)) capacity = np.minimum(min_dist_centers, min_dist_walls) best_idx = np.argmax(capacity) x0 = self.grid_pts[best_idx]
def neg_capacity(p): if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0 d_c = np.min(np.linalg.norm(centers - p, axis=1)) d_w = min(p[0], 1.0 - p[0], p[1], 1.0 - p[1]) return -min(d_c, d_w)
res = minimize( neg_capacity, x0, method='Nelder-Mead', bounds=[(0.0, 1.0), (0.0, 1.0)], options={'xatol': 1e-4, 'fatol': 1e-4, 'maxiter': 50} ) return res.x if (res.success or res.message) else x0
def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n) bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b))) A_ub = [] b_ub = [] diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2)) for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0; row[j] = 1.0 A_ub.append(row); b_ub.append(dists[i, j]) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') return res.x if res.success else np.array([b[1] for b in bounds_list])
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:] obj = -np.sum(r) if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2) w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2) diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2) return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False, mode='normal'): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n) x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n current_x = x0
if mode == 'fast': phases = [100.0, 10000.0] else: phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0]
phases = [p * stiffness_scale for p in phases] reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 iter_limit = 200 if mu > 5000 else 100 res = minimize(self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5}) current_x = res.x return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0)
# 1. Fast Screening for name, c_init in configs: c_relaxed, r_relaxed = self.run_physics_relaxation(c_init) # Use 'fast' mode for screening c_p1, r_p1 = self.local_optimization(c_relaxed, radii_init=r_relaxed, equal_bias=True, mode='fast') c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False, mode='fast') r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp) if score > best_global[2]: best_global = (c_p2, r_lp, score)
# 2. Basin Hopping curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2] best_c, best_r, best_score = curr_c.copy(), curr_r.copy(), curr_score
n_iter = 40 # Increased iterations due to fast mode temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy() trial_r_init = curr_r.copy() rand_val = self.rng.rand()
if rand_val < 0.4: # Pop Move with Void-Aware Radius min_idx = np.argmin(curr_r) others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask])
# Estimate clearance for radius init d_c = np.min(np.linalg.norm(curr_c[others_mask] - target, axis=1)) d_w = min(target[0], 1.0-target[0], target[1], 1.0-target[1]) new_r = max(0.01, min(d_c, d_w) - 0.005)
trial_c[min_idx] = target trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) # Micro jitter trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init[min_idx] = new_r
elif rand_val < 0.6: # Swap Move min_idx = np.argmin(curr_r) candidates = np.argsort(curr_r)[self.n // 2:] target_idx = candidates[self.rng.randint(len(candidates))] pos_min = trial_c[min_idx].copy() trial_c[min_idx] = trial_c[target_idx] trial_c[target_idx] = pos_min trial_r_init[min_idx] = 0.05 trial_r_init[target_idx] = 0.05 trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) else: # Shake Move mag = 0.025 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0)
# Fast optimization for exploration c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.5, mode='fast') r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new)
delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy() temperature *= 0.9
# 3. Final Polish (Full precision) x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-8} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c) return final_c, final_r
def construct_packing(): opt = RefinedHybridPopOptimizer(n=26) return opt.optimize()
def compute_max_radii(centers): opt = RefinedHybridPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers)# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469# EVOLVE-BLOCK-START"""Refined Hybrid Pop Optimizer:Merges 'HybridPopOptimizer' (Robust Optimization, Regularization, Physics Pre-conditioning)with 'Basin Hopping Refinement' (Precise Void Finding via Nelder-Mead)."""
import numpy as npfrom scipy.optimize import minimize, linprog
class RefinedHybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
# Grid for void finding (coarse search) self.grid_res = 60 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def get_initial_configs(self): """Generates diverse initial configurations from multiple strategies.""" configs = []
# 1. Explicit Lattice Patterns patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Rounded small corners ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
if len(centers) > 0: # Normalize and center min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09
curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center)
# Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill])
configs.append(('lattice', centers))
# 2. Spiral Packing configs.append(('spiral', self.init_spiral()))
# 3. Generic Hex configs.append(('hex_generic', self.generate_generic_hex()))
# 4. Boundary + Random configs.append(('boundary', self.init_boundary()))
# 5. Grid Compact configs.append(('grid_5x5', self.init_grid_compact()))
# 6. Pure Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2)))
return configs
def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c
def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]]
min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def init_boundary(self): boundary = [] x = np.linspace(0.1, 0.9, 6) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary)
needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) return np.vstack([boundary, internal]) elif needed < 0: return boundary[:self.n] return boundary
def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c
def run_physics_relaxation(self, centers, steps=150): """Momentum-based relaxation with dynamic radii to find jammed states.""" c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005
for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq)
# Forces based on current radii r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists
forces = np.zeros_like(c)
mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push
# Walls k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall
# Integrate velocities = velocities * 0.7 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0)
# Radii Dynamics pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures
# Shrink fast on overlap, grow slowly otherwise dr = np.where(total_p > 0, -total_p * 0.1, 0.001) r += dr * dt r = np.maximum(r, 0.01)
return c, r
def find_largest_void(self, centers): """ Refined void finding. 1. Coarse grid search maximizing min(dist_to_centers, dist_to_walls). 2. Local refinement using Nelder-Mead. """ # 1. Coarse Grid diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dist_centers = np.sqrt(np.min(dists_sq, axis=1))
# Walls d_left = self.grid_pts[:, 0] d_right = 1.0 - self.grid_pts[:, 0] d_bottom = self.grid_pts[:, 1] d_top = 1.0 - self.grid_pts[:, 1] min_dist_walls = np.minimum(np.minimum(d_left, d_right), np.minimum(d_bottom, d_top))
# Capacity capacity = np.minimum(min_dist_centers, min_dist_walls) best_idx = np.argmax(capacity) x0 = self.grid_pts[best_idx]
# 2. Local Refinement def neg_capacity(p): if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0 d_c = np.min(np.linalg.norm(centers - p, axis=1)) d_w = min(p[0], 1.0 - p[0], p[1], 1.0 - p[1]) return -min(d_c, d_w)
res = minimize( neg_capacity, x0, method='Nelder-Mead', bounds=[(0.0, 1.0), (0.0, 1.0)], options={'xatol': 1e-4, 'fatol': 1e-4, 'maxiter': 50} )
# Check if valid return if res.success or res.message: return res.x return x0
def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n)
bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
A_ub = [] b_ub = []
diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2))
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
return np.array([b[1] for b in bounds_list])
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0
phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 iter_limit = 250 if mu > 5000 else 150
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0)
# 1. Global Search over Seeds for name, c_init in configs: c_relaxed, r_relaxed = self.run_physics_relaxation(c_init)
# Phase 1: Regularized (Start with relaxed radii hint) c_p1, r_p1 = self.local_optimization(c_relaxed, radii_init=r_relaxed, equal_bias=True)
# Phase 2: Variable c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False)
r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp)
if score > best_global[2]: best_global = (c_p2, r_lp, score)
# 2. Basin Hopping with Pop and Swap curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 30 temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy() trial_r_init = curr_r.copy()
# Move selection rand_val = self.rng.rand()
if rand_val < 0.35: # Pop Move: Relocate worst circle to largest void min_idx = np.argmin(curr_r)
others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask])
trial_c[min_idx] = target trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
trial_r_init[min_idx] = 0.05
elif rand_val < 0.55: # Swap Move: Exchange worst circle with a large one min_idx = np.argmin(curr_r)
# Pick a large circle (top 50%) sorted_indices = np.argsort(curr_r) candidates = sorted_indices[self.n // 2:] target_idx = candidates[self.rng.randint(len(candidates))]
# Swap positions pos_min = trial_c[min_idx].copy() pos_target = trial_c[target_idx].copy() trial_c[min_idx] = pos_target trial_c[target_idx] = pos_min
# Reset radii to allow re-fitting trial_r_init[min_idx] = 0.05 trial_r_init[target_idx] = 0.05
# Slight jitter to break symmetry trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
else: # Shake Move mag = 0.02 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0)
# Fast optimization c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)
# Evaluate r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new)
# Accept? delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy() temperature *= 0.95
# 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-7} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = RefinedHybridPopOptimizer(n=26) return opt.optimize()
def compute_max_radii(centers): opt = RefinedHybridPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers)# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812<NAME>dynamic_lattice_gen_fast_bh</NAME>
<DESCRIPTION>1. **Automated Lattice Generation**: Replaces the hardcoded list of lattice patterns with a dynamic generator (`generate_lattice_patterns`) that produces all valid integer compositions of N=26 into rows (with adjacent row length difference <= 1). It filters these by aspect ratio (0.7 to 1.45) to ensure they fit well in a square, providing a richer set of topologically valid seeds.2. **Fast Optimization Mode**: Refactors `local_optimization` to accept a `mode` parameter. 'Fast' mode uses only 2 stiffness phases (100, 10000) instead of 5, drastically reducing computation time per call.3. **Optimization Loop Overhaul**: - **Screening**: Now uses 'fast' mode, allowing efficient scanning of the larger seed pool. - **Basin Hopping**: Now uses 'fast' mode for the inner loop, enabling an increase in iterations from 30 to 40 within the same compute budget. - **Final Polish**: Remains at full precision.4. **Smart Pop Radius**: When moving a circle to a void (Pop move), its radius is initialized to the estimated clearance distance rather than a hardcoded 0.05, giving the optimizer a better starting gradient.</DESCRIPTION>
<DIFF><<<<<<< SEARCHclass RefinedHybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
# Grid for void finding (coarse search) self.grid_res = 60 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def get_initial_configs(self): """Generates diverse initial configurations from multiple strategies.""" configs = []
# 1. Explicit Lattice Patterns patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Rounded small corners ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
if len(centers) > 0: # Normalize and center min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09
curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center)
# Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill])
configs.append(('lattice', centers))
# 2. Spiral Packing configs.append(('spiral', self.init_spiral()))
# 3. Generic Hex configs.append(('hex_generic', self.generate_generic_hex()))
# 4. Boundary + Random configs.append(('boundary', self.init_boundary()))
# 5. Grid Compact configs.append(('grid_5x5', self.init_grid_compact()))
# 6. Pure Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2)))
return configs
def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c
def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]]
min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def init_boundary(self): boundary = [] x = np.linspace(0.1, 0.9, 6) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary)
needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) return np.vstack([boundary, internal]) elif needed < 0: return boundary[:self.n] return boundary
def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c
def run_physics_relaxation(self, centers, steps=150): """Momentum-based relaxation with dynamic radii to find jammed states.""" c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005
for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq)
# Forces based on current radii r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists
forces = np.zeros_like(c)
mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push
# Walls k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall
# Integrate velocities = velocities * 0.7 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0)
# Radii Dynamics pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures
# Shrink fast on overlap, grow slowly otherwise dr = np.where(total_p > 0, -total_p * 0.1, 0.001) r += dr * dt r = np.maximum(r, 0.01)
return c, r
def find_largest_void(self, centers): """ Refined void finding. 1. Coarse grid search maximizing min(dist_to_centers, dist_to_walls). 2. Local refinement using Nelder-Mead. """ # 1. Coarse Grid diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dist_centers = np.sqrt(np.min(dists_sq, axis=1))
# Walls d_left = self.grid_pts[:, 0] d_right = 1.0 - self.grid_pts[:, 0] d_bottom = self.grid_pts[:, 1] d_top = 1.0 - self.grid_pts[:, 1] min_dist_walls = np.minimum(np.minimum(d_left, d_right), np.minimum(d_bottom, d_top))
# Capacity capacity = np.minimum(min_dist_centers, min_dist_walls) best_idx = np.argmax(capacity) x0 = self.grid_pts[best_idx]
# 2. Local Refinement def neg_capacity(p): if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0 d_c = np.min(np.linalg.norm(centers - p, axis=1)) d_w = min(p[0], 1.0 - p[0], p[1], 1.0 - p[1]) return -min(d_c, d_w)
res = minimize( neg_capacity, x0, method='Nelder-Mead', bounds=[(0.0, 1.0), (0.0, 1.0)], options={'xatol': 1e-4, 'fatol': 1e-4, 'maxiter': 50} )
# Check if valid return if res.success or res.message: return res.x return x0
def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n)
bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
A_ub = [] b_ub = []
diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2))
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
return np.array([b[1] for b in bounds_list])
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0
phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 iter_limit = 250 if mu > 5000 else 150
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0)
# 1. Global Search over Seeds for name, c_init in configs: c_relaxed, r_relaxed = self.run_physics_relaxation(c_init)
# Phase 1: Regularized (Start with relaxed radii hint) c_p1, r_p1 = self.local_optimization(c_relaxed, radii_init=r_relaxed, equal_bias=True)
# Phase 2: Variable c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False)
r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp)
if score > best_global[2]: best_global = (c_p2, r_lp, score)
# 2. Basin Hopping with Pop and Swap curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 30 temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy() trial_r_init = curr_r.copy()
# Move selection rand_val = self.rng.rand()
if rand_val < 0.35: # Pop Move: Relocate worst circle to largest void min_idx = np.argmin(curr_r)
others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask])
trial_c[min_idx] = target trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
trial_r_init[min_idx] = 0.05
elif rand_val < 0.55: # Swap Move: Exchange worst circle with a large one min_idx = np.argmin(curr_r)
# Pick a large circle (top 50%) sorted_indices = np.argsort(curr_r) candidates = sorted_indices[self.n // 2:] target_idx = candidates[self.rng.randint(len(candidates))]
# Swap positions pos_min = trial_c[min_idx].copy() pos_target = trial_c[target_idx].copy() trial_c[min_idx] = pos_target trial_c[target_idx] = pos_min
# Reset radii to allow re-fitting trial_r_init[min_idx] = 0.05 trial_r_init[target_idx] = 0.05
# Slight jitter to break symmetry trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
else: # Shake Move mag = 0.02 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0)
# Fast optimization c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)
# Evaluate r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new)
# Accept? delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy() temperature *= 0.95
# 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-7} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r=======class RefinedHybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
# Grid for void finding (coarse search) self.grid_res = 50 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def generate_lattice_patterns(self): """Dynamically generates hexagonal row compositions for N=26.""" patterns = [] def backtrack(current_rows): s = sum(current_rows) if s == self.n: patterns.append(current_rows) return if s > self.n: return
last = current_rows[-1] candidates = [last-1, last, last+1] # Prune reasonable widths candidates = [c for c in candidates if 3 <= c <= 9]
for c in candidates: backtrack(current_rows + [c])
# Start with row lengths 4 to 8 for start in range(4, 9): backtrack([start])
# Filter for square-ish aspect ratio to prioritize likely candidates # Height ~= rows * 0.866, Width ~= max_row valid = [] for p in patterns: h = len(p) * 0.866 w = max(p) ratio = h / w if 0.7 <= ratio <= 1.45: valid.append(p)
# Downsample if too many, favoring variety if len(valid) > 15: # Deterministic subset indices = np.linspace(0, len(valid)-1, 15, dtype=int) valid = [valid[i] for i in indices]
return valid
def get_initial_configs(self): """Generates diverse initial configurations.""" configs = []
# 1. Automated Lattice Patterns patterns = self.generate_lattice_patterns() # Add a few known good ones manually just in case known = [[5, 5, 6, 5, 5], [6, 7, 6, 7], [6, 5, 6, 5, 4]] for k in known: if k not in patterns: patterns.append(k)
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09 curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center) configs.append(('lattice', centers))
# 2. Heuristics configs.append(('spiral', self.init_spiral())) configs.append(('hex_generic', self.generate_generic_hex())) configs.append(('grid_5x5', self.init_grid_compact()))
# 3. Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2)))
return configs
def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c
def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]] min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c
def run_physics_relaxation(self, centers, steps=120): c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005 for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists forces = np.zeros_like(c) mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall velocities = velocities * 0.7 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0) pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures dr = np.where(total_p > 0, -total_p * 0.1, 0.001) r += dr * dt r = np.maximum(r, 0.01) return c, r
def find_largest_void(self, centers): diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dist_centers = np.sqrt(np.min(dists_sq, axis=1)) d_left = self.grid_pts[:, 0] d_right = 1.0 - self.grid_pts[:, 0] d_bottom = self.grid_pts[:, 1] d_top = 1.0 - self.grid_pts[:, 1] min_dist_walls = np.minimum(np.minimum(d_left, d_right), np.minimum(d_bottom, d_top)) capacity = np.minimum(min_dist_centers, min_dist_walls) best_idx = np.argmax(capacity) x0 = self.grid_pts[best_idx]
def neg_capacity(p): if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0 d_c = np.min(np.linalg.norm(centers - p, axis=1)) d_w = min(p[0], 1.0 - p[0], p[1], 1.0 - p[1]) return -min(d_c, d_w)
res = minimize( neg_capacity, x0, method='Nelder-Mead', bounds=[(0.0, 1.0), (0.0, 1.0)], options={'xatol': 1e-4, 'fatol': 1e-4, 'maxiter': 50} ) return res.x if (res.success or res.message) else x0
def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n) bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b))) A_ub = [] b_ub = [] diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2)) for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0; row[j] = 1.0 A_ub.append(row); b_ub.append(dists[i, j]) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') return res.x if res.success else np.array([b[1] for b in bounds_list])
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:] obj = -np.sum(r) if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2) w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2) diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2) return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False, mode='normal'): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n) x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n current_x = x0
if mode == 'fast': phases = [100.0, 10000.0] else: phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0]
phases = [p * stiffness_scale for p in phases] reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 iter_limit = 200 if mu > 5000 else 100 res = minimize(self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5}) current_x = res.x return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0)
# 1. Fast Screening for name, c_init in configs: c_relaxed, r_relaxed = self.run_physics_relaxation(c_init) # Use 'fast' mode for screening c_p1, r_p1 = self.local_optimization(c_relaxed, radii_init=r_relaxed, equal_bias=True, mode='fast') c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False, mode='fast') r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp) if score > best_global[2]: best_global = (c_p2, r_lp, score)
# 2. Basin Hopping curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2] best_c, best_r, best_score = curr_c.copy(), curr_r.copy(), curr_score
n_iter = 40 # Increased iterations due to fast mode temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy() trial_r_init = curr_r.copy() rand_val = self.rng.rand()
if rand_val < 0.4: # Pop Move with Void-Aware Radius min_idx = np.argmin(curr_r) others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask])
# Estimate clearance for radius init d_c = np.min(np.linalg.norm(curr_c[others_mask] - target, axis=1)) d_w = min(target[0], 1.0-target[0], target[1], 1.0-target[1]) new_r = max(0.01, min(d_c, d_w) - 0.005)
trial_c[min_idx] = target trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) # Micro jitter trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init[min_idx] = new_r
elif rand_val < 0.6: # Swap Move min_idx = np.argmin(curr_r) candidates = np.argsort(curr_r)[self.n // 2:] target_idx = candidates[self.rng.randint(len(candidates))] pos_min = trial_c[min_idx].copy() trial_c[min_idx] = trial_c[target_idx] trial_c[target_idx] = pos_min trial_r_init[min_idx] = 0.05 trial_r_init[target_idx] = 0.05 trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) else: # Shake Move mag = 0.025 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0)
# Fast optimization for exploration c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=1.5, mode='fast') r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new)
delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy() temperature *= 0.9
# 3. Final Polish (Full precision) x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-8} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c) return final_c, final_r>>>>>>> REPLACE</DIFF>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738--- a/original.py+++ b/original.py@@ -1,469 +1,390 @@ # EVOLVE-BLOCK-START-"""-Refined Hybrid Pop Optimizer:-Merges 'HybridPopOptimizer' (Robust Optimization, Regularization, Physics Pre-conditioning)-with 'Basin Hopping Refinement' (Precise Void Finding via Nelder-Mead).-"""- import numpy as np from scipy.optimize import minimize, linprog -class RefinedHybridPopOptimizer:+class LatticeGenPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)-- # Grid for void finding (coarse search)- self.grid_res = 60+ # Grid for void finding (resolution 50x50)+ self.grid_res = 50 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy]) + def get_lattice_patterns(self):+ """Generates all valid hexagonal lattice row compositions for N=26."""+ results = []+ + def backtrack(current_rows, current_sum):+ if current_sum == self.n:+ results.append(list(current_rows))+ return+ if current_sum > self.n:+ return+ + # Next row constraints:+ # 1. Difference from prev row <= 1 (hex packing property)+ # 2. Length within reasonable bounds (e.g., 2 to 9 for N=26)+ + if not current_rows:+ # First row: N=26 usually fits in rows of length 3-8+ options = range(3, 9)+ else:+ last = current_rows[-1]+ # Hexagonal lattice constraint: adjacent rows differ by at most 1+ options = [last-1, last, last+1]+ options = [x for x in options if 2 <= x <= 9]+ + for count in options:+ # Heuristic pruning: avoid extremely tall/narrow configurations+ # Approximate rows needed for remaining circles assuming similar width+ remaining = self.n - (current_sum + count)+ if remaining > 0:+ est_remaining_rows = remaining / max(1, count)+ if len(current_rows) + 1 + est_remaining_rows > 10:+ continue+ + backtrack(current_rows + [count], current_sum + count)++ backtrack([], 0)+ + # Sort by "squareness" likelihood+ # Optimal packing in a square usually has Height approx Width+ # Height ~ rows * sqrt(3)/2, Width ~ max_row_len+ def aspect_diff(rows):+ h = len(rows) * 0.866+ w = max(rows)+ return abs(h/w - 1.0)+ + results.sort(key=aspect_diff)+ + # Select the top candidates plus diversity+ top_k = results[:15]+ + # Ensure some known good patterns are present+ known_good = [+ [5, 5, 6, 5, 5],+ [6, 7, 6, 7],+ [6, 5, 6, 5, 4],+ [5, 6, 5, 5, 5]+ ]+ for k in known_good:+ if k not in top_k:+ top_k.append(k)+ + return top_k++ def generate_centers_from_rows(self, rows):+ centers = []+ dy = np.sqrt(3) / 2+ for i, count in enumerate(rows):+ y = i * dy+ for j in range(count):+ x = j - (count - 1) / 2.0+ centers.append([x, y])+ centers = np.array(centers)+ + # Normalize to unit square+ if len(centers) > 0:+ min_c = np.min(centers, axis=0)+ max_c = np.max(centers, axis=0)+ span = max_c - min_c+ max_span = np.max(span)+ scale = 0.85 / max_span if max_span > 1e-9 else 1.0+ centers = (centers - min_c) * scale + 0.075+ + # Center it+ curr_center = np.mean(centers, axis=0)+ centers += (0.5 - curr_center)+ + return centers+ def get_initial_configs(self):- """Generates diverse initial configurations from multiple strategies.""" configs = []-- # 1. Explicit Lattice Patterns- patterns = [- [5, 5, 6, 5, 5], # Symmetric hex- [6, 5, 6, 5, 4], # Staggered- [5, 6, 5, 5, 5], # Center heavy- [6, 7, 6, 7], # Two-block- [5, 5, 5, 5, 6], # Bottom heavy- [4, 5, 6, 6, 5], # Asymmetric- [6, 6, 6, 6, 2], # Box-like- [4, 6, 6, 6, 4], # Rounded- [3, 4, 5, 6, 5, 3] # Rounded small corners- ]-- dy = np.sqrt(3) / 2- for rows in patterns:- centers = []- for i, count in enumerate(rows):- y = i * dy- for j in range(count):- x = j - (count - 1) / 2.0- centers.append([x, y])- centers = np.array(centers)-- if len(centers) > 0:- # Normalize and center- min_c = np.min(centers, axis=0)- max_c = np.max(centers, axis=0)- span = np.max(max_c - min_c)- scale = 0.82 / span if span > 1e-9 else 1.0- centers = (centers - min_c) * scale + 0.09-- curr_center = np.mean(centers, axis=0)- centers += (0.5 - curr_center)-- # Fix count- if len(centers) > self.n:- dists = np.sum((centers - 0.5)**2, axis=1)- idx = np.argsort(dists)- centers = centers[idx[:self.n]]- elif len(centers) < self.n:- needed = self.n - len(centers)- fill = np.random.rand(needed, 2) * 0.8 + 0.1- centers = np.vstack([centers, fill])-- configs.append(('lattice', centers))-- # 2. Spiral Packing- configs.append(('spiral', self.init_spiral()))-- # 3. Generic Hex- configs.append(('hex_generic', self.generate_generic_hex()))-- # 4. Boundary + Random- configs.append(('boundary', self.init_boundary()))-- # 5. Grid Compact- configs.append(('grid_5x5', self.init_grid_compact()))-- # 6. Pure Random- configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2)))-+ + # 1. Lattice Patterns+ row_patterns = self.get_lattice_patterns()+ for rows in row_patterns:+ c = self.generate_centers_from_rows(rows)+ configs.append(c)+ + # 2. Geometric Fallbacks+ # Spiral+ indices = np.arange(self.n)+ theta = indices * np.pi * (3 - np.sqrt(5))+ r = np.sqrt(indices + 1) / np.sqrt(self.n)+ c_spiral = np.zeros((self.n, 2))+ c_spiral[:, 0] = 0.5 + 0.44 * r * np.cos(theta)+ c_spiral[:, 1] = 0.5 + 0.44 * r * np.sin(theta)+ configs.append(c_spiral)+ + # Pure Random+ configs.append(np.random.rand(self.n, 2))+ return configs - def init_spiral(self):- indices = np.arange(self.n)- golden_angle = np.pi * (3 - np.sqrt(5))- theta = indices * golden_angle- r = np.sqrt(indices + 1) / np.sqrt(self.n)- c = np.zeros((self.n, 2))- scale = 0.44- c[:, 0] = 0.5 + scale * r * np.cos(theta)- c[:, 1] = 0.5 + scale * r * np.sin(theta)- return c-- def generate_generic_hex(self):- v1 = np.array([1.0, 0.0])- v2 = np.array([0.5, np.sqrt(3)/2])- points = []- for i in range(-4, 5):- for j in range(-4, 5):- points.append(i * v1 + j * v2)- points = np.array(points)- points -= np.mean(points, axis=0)- dists = np.sum(points**2, axis=1)- points = points[np.argsort(dists)[:self.n]]-- min_xy = np.min(points, axis=0)- max_xy = np.max(points, axis=0)- scale = 0.8 / np.max(max_xy - min_xy)- return (points - min_xy) * scale + 0.1-- def init_boundary(self):- boundary = []- x = np.linspace(0.1, 0.9, 6)- for xi in x:- boundary.append([xi, 0.1])- boundary.append([xi, 0.9])- y = np.linspace(0.25, 0.75, 4)- for yi in y:- boundary.append([0.1, yi])- boundary.append([0.9, yi])- boundary = np.array(boundary)-- needed = self.n - len(boundary)- if needed > 0:- internal = 0.2 + 0.6 * self.rng.rand(needed, 2)- return np.vstack([boundary, internal])- elif needed < 0:- return boundary[:self.n]- return boundary-- def init_grid_compact(self):- x = np.linspace(0.15, 0.85, 5)- y = np.linspace(0.15, 0.85, 5)- xv, yv = np.meshgrid(x, y)- c = np.zeros((self.n, 2))- c[:25, 0] = xv.flatten()- c[:25, 1] = yv.flatten()- c[25] = np.array([0.5, 0.5])- c += 0.01 * (self.rng.rand(self.n, 2) - 0.5)- return c-- def run_physics_relaxation(self, centers, steps=150):- """Momentum-based relaxation with dynamic radii to find jammed states."""- c = centers.copy()- n = len(c)- r = np.ones(n) * 0.05- velocities = np.zeros_like(c)- dt = 0.005-- for _ in range(steps):- diff = c[:, np.newaxis, :] - c[np.newaxis, :, :]- dist_sq = np.sum(diff**2, axis=2)- np.fill_diagonal(dist_sq, 1.0)- dists = np.sqrt(dist_sq)-- # Forces based on current radii- r_sum = r[:, np.newaxis] + r[np.newaxis, :]- overlaps = r_sum - dists-- forces = np.zeros_like(c)-- mask = overlaps > 0- if np.any(mask):- safe_dists = np.maximum(dists, 1e-6)- dirs = diff / safe_dists[:, :, np.newaxis]- f_mag = overlaps * 40.0- push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1)- forces += push-- # Walls- k_wall = 80.0- forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall- forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall- forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall- forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall-- # Integrate- velocities = velocities * 0.7 + forces * dt- c += velocities * dt- c = np.clip(c, 0.0, 1.0)-- # Radii Dynamics- pressures = np.sum(np.maximum(overlaps, 0), axis=1)- w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) +- np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0))- total_p = pressures + w_pressures-- # Shrink fast on overlap, grow slowly otherwise- dr = np.where(total_p > 0, -total_p * 0.1, 0.001)- r += dr * dt- r = np.maximum(r, 0.01)-- return c, r-- def find_largest_void(self, centers):- """- Refined void finding.- 1. Coarse grid search maximizing min(dist_to_centers, dist_to_walls).- 2. Local refinement using Nelder-Mead.- """- # 1. Coarse Grid- diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :]- dists_sq = np.sum(diff**2, axis=2)- min_dist_centers = np.sqrt(np.min(dists_sq, axis=1))-- # Walls- d_left = self.grid_pts[:, 0]- d_right = 1.0 - self.grid_pts[:, 0]- d_bottom = self.grid_pts[:, 1]- d_top = 1.0 - self.grid_pts[:, 1]- min_dist_walls = np.minimum(np.minimum(d_left, d_right), np.minimum(d_bottom, d_top))-- # Capacity- capacity = np.minimum(min_dist_centers, min_dist_walls)- best_idx = np.argmax(capacity)- x0 = self.grid_pts[best_idx]-- # 2. Local Refinement- def neg_capacity(p):- if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1):- return 1.0- d_c = np.min(np.linalg.norm(centers - p, axis=1))- d_w = min(p[0], 1.0 - p[0], p[1], 1.0 - p[1])- return -min(d_c, d_w)-- res = minimize(- neg_capacity,- x0,- method='Nelder-Mead',- bounds=[(0.0, 1.0), (0.0, 1.0)],- options={'xatol': 1e-4, 'fatol': 1e-4, 'maxiter': 50}- )-- # Check if valid return- if res.success or res.message:- return res.x- return x0- def solve_lp_radii(self, centers):+ """Computes max radii for fixed centers using LP.""" n = len(centers)- c = -np.ones(n)-- bounds_list = []+ c_obj = -np.ones(n)++ bounds = [] for i in range(n): x, y = centers[i]+ # Clip to be safe inside [0,1]+ x = np.clip(x, 0, 1)+ y = np.clip(y, 0, 1) b = min(x, 1-x, y, 1-y)- bounds_list.append((0, max(1e-9, b)))+ bounds.append((0, max(0.0, b))) A_ub = [] b_ub = [] diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]- dists = np.sqrt(np.sum(diff**2, axis=2))+ dist_sq = np.sum(diff**2, axis=2)+ dists = np.sqrt(dist_sq) for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j]) + # Try Highs solver first try:- res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs')+ res = linprog(c_obj, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='highs') if res.success: return res.x except: pass-- res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point')+ + # Fallback to interior-point+ res = linprog(c_obj, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='interior-point') if res.success: return res.x-- return np.array([b[1] for b in bounds_list])+ + # Robust Fallback: Geometric approx+ r_fallback = np.zeros(n)+ for i in range(n):+ d_wall = bounds[i][1]+ # dist to nearest neighbor / 2+ d_neigh = np.min(dists[i, np.arange(n)!=i]) / 2.0+ r_fallback[i] = min(d_wall, d_neigh)+ return r_fallback++ def find_largest_void(self, centers):+ """Find point furthest from centers and walls."""+ # 1. Grid Search+ diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :]+ d_c_sq = np.min(np.sum(diff**2, axis=2), axis=1)+ d_c = np.sqrt(d_c_sq)+ + d_w = np.minimum(+ np.minimum(self.grid_pts[:, 0], 1 - self.grid_pts[:, 0]),+ np.minimum(self.grid_pts[:, 1], 1 - self.grid_pts[:, 1])+ )+ + min_clearance = np.minimum(d_c, d_w)+ best_idx = np.argmax(min_clearance)+ x0 = self.grid_pts[best_idx]+ + # 2. Nelder-Mead Polish+ def obj(p):+ # Penalize out of bounds+ if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0+ dc = np.min(np.linalg.norm(centers - p, axis=1))+ dw = min(p[0], 1-p[0], p[1], 1-p[1])+ return -min(dc, dw)+ + res = minimize(obj, x0, method='Nelder-Mead', bounds=[(0,1),(0,1)], options={'maxiter': 50, 'xatol': 1e-4})+ return res.x def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]-+ obj = -np.sum(r)-+ if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)-+ + # Wall Penalty w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)-+ + # Overlap Penalty diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2)- np.fill_diagonal(dist_sq, 10.0)+ np.fill_diagonal(dist_sq, 10.0) # Mask diagonal dists = np.sqrt(dist_sq)-+ r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2)-+ return obj + mu * (w_pen + ov_pen) - def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False):+ def local_optimization(self, centers, radii_init=None, equal_bias=False, fast=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)-+ x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n-+ + if fast:+ phases = [100.0, 5000.0]+ else:+ phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0]+ current_x = x0-- phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0]- phases = [p * stiffness_scale for p in phases]- reg = 5.0 if equal_bias else 0.0-+ for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0- iter_limit = 250 if mu > 5000 else 150-+ + # Iteration limit based on phase stiffness+ iter_lim = 100 if fast else (300 if mu > 5000 else 150)+ res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds,- options={'maxiter': iter_limit, 'ftol': 1e-5}+ options={'maxiter': iter_lim, 'ftol': 1e-5} ) current_x = res.x-+ return current_x[:2*n].reshape((n, 2)), current_x[2*n:] def optimize(self): configs = self.get_initial_configs()- best_global = (None, None, -1.0)-- # 1. Global Search over Seeds- for name, c_init in configs:- c_relaxed, r_relaxed = self.run_physics_relaxation(c_init)-- # Phase 1: Regularized (Start with relaxed radii hint)- c_p1, r_p1 = self.local_optimization(c_relaxed, radii_init=r_relaxed, equal_bias=True)-- # Phase 2: Variable- c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False)-- r_lp = self.solve_lp_radii(c_p2)+ + best_res = (None, None, -1.0)+ + # 1. Seed Screening+ for c_init in configs:+ # Phase 1: Equalize radii (Regularization High)+ c_eq, r_eq = self.local_optimization(c_init, equal_bias=True, fast=False)+ # Phase 2: Relax radii (Regularization Low)+ c_var, _ = self.local_optimization(c_eq, radii_init=r_eq, equal_bias=False, fast=False)+ + r_lp = self.solve_lp_radii(c_var) score = np.sum(r_lp)-- if score > best_global[2]:- best_global = (c_p2, r_lp, score)-- # 2. Basin Hopping with Pop and Swap- curr_c = best_global[0]- curr_r = best_global[1]- curr_score = best_global[2]-- best_c = curr_c.copy()- best_r = curr_r.copy()- best_score = curr_score-- n_iter = 30+ + if score > best_res[2]:+ best_res = (c_var, r_lp, score)++ # 2. Basin Hopping Refinement+ if best_res[0] is None:+ return np.random.rand(self.n, 2), np.ones(self.n)*0.01++ curr_c, curr_r, curr_score = best_res+ best_c, best_r, best_score = best_res+ + n_iter = 25 temperature = 0.003-+ for i in range(n_iter): trial_c = curr_c.copy()- trial_r_init = curr_r.copy()-- # Move selection- rand_val = self.rng.rand()-- if rand_val < 0.35:- # Pop Move: Relocate worst circle to largest void+ trial_r = curr_r.copy()+ + # Decision+ u = self.rng.rand()+ + if u < 0.4:+ # Pop Move: Move worst circle to void min_idx = np.argmin(curr_r)-- others_mask = np.ones(self.n, dtype=bool)- others_mask[min_idx] = False- target = self.find_largest_void(curr_c[others_mask])-+ mask = np.ones(self.n, dtype=bool)+ mask[min_idx] = False+ + target = self.find_largest_void(trial_c[mask]) trial_c[min_idx] = target- trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5)+ + # Jitter others to break static friction+ trial_c[mask] += 0.005 * (self.rng.rand(self.n-1, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)-- trial_r_init[min_idx] = 0.05-- elif rand_val < 0.55:- # Swap Move: Exchange worst circle with a large one+ trial_r[min_idx] = 0.05+ + elif u < 0.6:+ # Swap Move: Swap worst circle with a larger one min_idx = np.argmin(curr_r)-- # Pick a large circle (top 50%)- sorted_indices = np.argsort(curr_r)- candidates = sorted_indices[self.n // 2:]- target_idx = candidates[self.rng.randint(len(candidates))]-- # Swap positions- pos_min = trial_c[min_idx].copy()- pos_target = trial_c[target_idx].copy()- trial_c[min_idx] = pos_target- trial_c[target_idx] = pos_min-- # Reset radii to allow re-fitting- trial_r_init[min_idx] = 0.05- trial_r_init[target_idx] = 0.05-- # Slight jitter to break symmetry- trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5)- trial_c = np.clip(trial_c, 0.0, 1.0)-+ # Candidates larger than median+ large_candidates = np.where(curr_r > np.median(curr_r))[0]+ if len(large_candidates) > 0:+ swap_idx = self.rng.choice(large_candidates)+ # Swap+ trial_c[min_idx], trial_c[swap_idx] = trial_c[swap_idx].copy(), trial_c[min_idx].copy()+ trial_r[min_idx] = 0.05+ trial_r[swap_idx] = 0.05 else: # Shake Move- mag = 0.02 * np.exp(-i/(n_iter*0.8))- trial_c += mag * self.rng.randn(self.n, 2)- trial_c = np.clip(trial_c, 0.0, 1.0)-- # Fast optimization- c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)-- # Evaluate- r_new = self.solve_lp_radii(c_new)- s_new = np.sum(r_new)-- # Accept?+ mag = 0.02 * np.exp(-i / n_iter)+ perturb = mag * self.rng.randn(self.n, 2)+ trial_c = np.clip(trial_c + perturb, 0.0, 1.0)+ trial_r = trial_r * 0.95+ + # Fast Local Optimization+ c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r, fast=True)+ + # Exact LP Evaluation+ r_lp = self.solve_lp_radii(c_new)+ s_new = np.sum(r_lp)+ + # Metropolis Acceptance delta = s_new - curr_score- if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)):- curr_c, curr_r, curr_score = c_new, r_new, s_new+ if delta > 0 or (self.rng.rand() < np.exp(delta / temperature)):+ curr_c, curr_r, curr_score = c_new, r_lp, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy()- best_r = r_new.copy()+ best_r = r_lp.copy() temperature *= 0.95-+ # 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n-+ res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds,- options={'maxiter': 500, 'ftol': 1e-7}+ options={'maxiter': 500, 'ftol': 1e-8} )+ final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)-+ return final_c, final_r def construct_packing():- opt = RefinedHybridPopOptimizer(n=26)+ opt = LatticeGenPopOptimizer(n=26) return opt.optimize() def compute_max_radii(centers):- opt = RefinedHybridPopOptimizer(n=len(centers))+ opt = LatticeGenPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers)++def run_packing():+ """Run the circle packing constructor for n=26"""+ centers, radii = construct_packing()+ # Calculate the sum of radii+ sum_radii = np.sum(radii)+ return centers, radii, sum_radii # EVOLVE-BLOCK-END # This part remains fixed (not evolved) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390# EVOLVE-BLOCK-STARTimport numpy as npfrom scipy.optimize import minimize, linprog
class LatticeGenPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42) # Grid for void finding (resolution 50x50) self.grid_res = 50 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def get_lattice_patterns(self): """Generates all valid hexagonal lattice row compositions for N=26.""" results = [] def backtrack(current_rows, current_sum): if current_sum == self.n: results.append(list(current_rows)) return if current_sum > self.n: return # Next row constraints: # 1. Difference from prev row <= 1 (hex packing property) # 2. Length within reasonable bounds (e.g., 2 to 9 for N=26) if not current_rows: # First row: N=26 usually fits in rows of length 3-8 options = range(3, 9) else: last = current_rows[-1] # Hexagonal lattice constraint: adjacent rows differ by at most 1 options = [last-1, last, last+1] options = [x for x in options if 2 <= x <= 9] for count in options: # Heuristic pruning: avoid extremely tall/narrow configurations # Approximate rows needed for remaining circles assuming similar width remaining = self.n - (current_sum + count) if remaining > 0: est_remaining_rows = remaining / max(1, count) if len(current_rows) + 1 + est_remaining_rows > 10: continue backtrack(current_rows + [count], current_sum + count)
backtrack([], 0) # Sort by "squareness" likelihood # Optimal packing in a square usually has Height approx Width # Height ~ rows * sqrt(3)/2, Width ~ max_row_len def aspect_diff(rows): h = len(rows) * 0.866 w = max(rows) return abs(h/w - 1.0) results.sort(key=aspect_diff) # Select the top candidates plus diversity top_k = results[:15] # Ensure some known good patterns are present known_good = [ [5, 5, 6, 5, 5], [6, 7, 6, 7], [6, 5, 6, 5, 4], [5, 6, 5, 5, 5] ] for k in known_good: if k not in top_k: top_k.append(k) return top_k
def generate_centers_from_rows(self, rows): centers = [] dy = np.sqrt(3) / 2 for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers) # Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c max_span = np.max(span) scale = 0.85 / max_span if max_span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center) return centers
def get_initial_configs(self): configs = [] # 1. Lattice Patterns row_patterns = self.get_lattice_patterns() for rows in row_patterns: c = self.generate_centers_from_rows(rows) configs.append(c) # 2. Geometric Fallbacks # Spiral indices = np.arange(self.n) theta = indices * np.pi * (3 - np.sqrt(5)) r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) c_spiral[:, 0] = 0.5 + 0.44 * r * np.cos(theta) c_spiral[:, 1] = 0.5 + 0.44 * r * np.sin(theta) configs.append(c_spiral) # Pure Random configs.append(np.random.rand(self.n, 2)) return configs
def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c_obj = -np.ones(n)
bounds = [] for i in range(n): x, y = centers[i] # Clip to be safe inside [0,1] x = np.clip(x, 0, 1) y = np.clip(y, 0, 1) b = min(x, 1-x, y, 1-y) bounds.append((0, max(0.0, b)))
A_ub = [] b_ub = []
diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq)
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
# Try Highs solver first try: res = linprog(c_obj, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='highs') if res.success: return res.x except: pass # Fallback to interior-point res = linprog(c_obj, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='interior-point') if res.success: return res.x # Robust Fallback: Geometric approx r_fallback = np.zeros(n) for i in range(n): d_wall = bounds[i][1] # dist to nearest neighbor / 2 d_neigh = np.min(dists[i, np.arange(n)!=i]) / 2.0 r_fallback[i] = min(d_wall, d_neigh) return r_fallback
def find_largest_void(self, centers): """Find point furthest from centers and walls.""" # 1. Grid Search diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c_sq = np.min(np.sum(diff**2, axis=2), axis=1) d_c = np.sqrt(d_c_sq) d_w = np.minimum( np.minimum(self.grid_pts[:, 0], 1 - self.grid_pts[:, 0]), np.minimum(self.grid_pts[:, 1], 1 - self.grid_pts[:, 1]) ) min_clearance = np.minimum(d_c, d_w) best_idx = np.argmax(min_clearance) x0 = self.grid_pts[best_idx] # 2. Nelder-Mead Polish def obj(p): # Penalize out of bounds if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0 dc = np.min(np.linalg.norm(centers - p, axis=1)) dw = min(p[0], 1-p[0], p[1], 1-p[1]) return -min(dc, dw) res = minimize(obj, x0, method='Nelder-Mead', bounds=[(0,1),(0,1)], options={'maxiter': 50, 'xatol': 1e-4}) return res.x
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:] obj = -np.sum(r) if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2) # Wall Penalty w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2) # Overlap Penalty diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) # Mask diagonal dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2) return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, equal_bias=False, fast=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n) x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n if fast: phases = [100.0, 5000.0] else: phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] current_x = x0 reg = 5.0 if equal_bias else 0.0 for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 # Iteration limit based on phase stiffness iter_lim = 100 if fast else (300 if mu > 5000 else 150) res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_lim, 'ftol': 1e-5} ) current_x = res.x return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_res = (None, None, -1.0) # 1. Seed Screening for c_init in configs: # Phase 1: Equalize radii (Regularization High) c_eq, r_eq = self.local_optimization(c_init, equal_bias=True, fast=False) # Phase 2: Relax radii (Regularization Low) c_var, _ = self.local_optimization(c_eq, radii_init=r_eq, equal_bias=False, fast=False) r_lp = self.solve_lp_radii(c_var) score = np.sum(r_lp) if score > best_res[2]: best_res = (c_var, r_lp, score)
# 2. Basin Hopping Refinement if best_res[0] is None: return np.random.rand(self.n, 2), np.ones(self.n)*0.01
curr_c, curr_r, curr_score = best_res best_c, best_r, best_score = best_res n_iter = 25 temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() trial_r = curr_r.copy() # Decision u = self.rng.rand() if u < 0.4: # Pop Move: Move worst circle to void min_idx = np.argmin(curr_r) mask = np.ones(self.n, dtype=bool) mask[min_idx] = False target = self.find_largest_void(trial_c[mask]) trial_c[min_idx] = target # Jitter others to break static friction trial_c[mask] += 0.005 * (self.rng.rand(self.n-1, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r[min_idx] = 0.05 elif u < 0.6: # Swap Move: Swap worst circle with a larger one min_idx = np.argmin(curr_r) # Candidates larger than median large_candidates = np.where(curr_r > np.median(curr_r))[0] if len(large_candidates) > 0: swap_idx = self.rng.choice(large_candidates) # Swap trial_c[min_idx], trial_c[swap_idx] = trial_c[swap_idx].copy(), trial_c[min_idx].copy() trial_r[min_idx] = 0.05 trial_r[swap_idx] = 0.05 else: # Shake Move mag = 0.02 * np.exp(-i / n_iter) perturb = mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c + perturb, 0.0, 1.0) trial_r = trial_r * 0.95 # Fast Local Optimization c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r, fast=True) # Exact LP Evaluation r_lp = self.solve_lp_radii(c_new) s_new = np.sum(r_lp) # Metropolis Acceptance delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta / temperature)): curr_c, curr_r, curr_score = c_new, r_lp, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_lp.copy() temperature *= 0.95 # 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-8} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c) return final_c, final_r
def construct_packing(): opt = LatticeGenPopOptimizer(n=26) return opt.optimize()
def compute_max_radii(centers): opt = LatticeGenPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers)
def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469# EVOLVE-BLOCK-START"""Refined Hybrid Pop Optimizer:Merges 'HybridPopOptimizer' (Robust Optimization, Regularization, Physics Pre-conditioning)with 'Basin Hopping Refinement' (Precise Void Finding via Nelder-Mead)."""
import numpy as npfrom scipy.optimize import minimize, linprog
class RefinedHybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
# Grid for void finding (coarse search) self.grid_res = 60 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def get_initial_configs(self): """Generates diverse initial configurations from multiple strategies.""" configs = []
# 1. Explicit Lattice Patterns patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Rounded small corners ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
if len(centers) > 0: # Normalize and center min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09
curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center)
# Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill])
configs.append(('lattice', centers))
# 2. Spiral Packing configs.append(('spiral', self.init_spiral()))
# 3. Generic Hex configs.append(('hex_generic', self.generate_generic_hex()))
# 4. Boundary + Random configs.append(('boundary', self.init_boundary()))
# 5. Grid Compact configs.append(('grid_5x5', self.init_grid_compact()))
# 6. Pure Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2)))
return configs
def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c
def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]]
min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def init_boundary(self): boundary = [] x = np.linspace(0.1, 0.9, 6) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary)
needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) return np.vstack([boundary, internal]) elif needed < 0: return boundary[:self.n] return boundary
def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c
def run_physics_relaxation(self, centers, steps=150): """Momentum-based relaxation with dynamic radii to find jammed states.""" c = centers.copy() n = len(c) r = np.ones(n) * 0.05 velocities = np.zeros_like(c) dt = 0.005
for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq)
# Forces based on current radii r_sum = r[:, np.newaxis] + r[np.newaxis, :] overlaps = r_sum - dists
forces = np.zeros_like(c)
mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push
# Walls k_wall = 80.0 forces[:, 0] += np.maximum(r - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r - (1 - c[:, 1]), 0) * k_wall
# Integrate velocities = velocities * 0.7 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0)
# Radii Dynamics pressures = np.sum(np.maximum(overlaps, 0), axis=1) w_pressures = (np.maximum(r - c[:, 0], 0) + np.maximum(r - (1 - c[:, 0]), 0) + np.maximum(r - c[:, 1], 0) + np.maximum(r - (1 - c[:, 1]), 0)) total_p = pressures + w_pressures
# Shrink fast on overlap, grow slowly otherwise dr = np.where(total_p > 0, -total_p * 0.1, 0.001) r += dr * dt r = np.maximum(r, 0.01)
return c, r
def find_largest_void(self, centers): """ Refined void finding. 1. Coarse grid search maximizing min(dist_to_centers, dist_to_walls). 2. Local refinement using Nelder-Mead. """ # 1. Coarse Grid diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dist_centers = np.sqrt(np.min(dists_sq, axis=1))
# Walls d_left = self.grid_pts[:, 0] d_right = 1.0 - self.grid_pts[:, 0] d_bottom = self.grid_pts[:, 1] d_top = 1.0 - self.grid_pts[:, 1] min_dist_walls = np.minimum(np.minimum(d_left, d_right), np.minimum(d_bottom, d_top))
# Capacity capacity = np.minimum(min_dist_centers, min_dist_walls) best_idx = np.argmax(capacity) x0 = self.grid_pts[best_idx]
# 2. Local Refinement def neg_capacity(p): if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0 d_c = np.min(np.linalg.norm(centers - p, axis=1)) d_w = min(p[0], 1.0 - p[0], p[1], 1.0 - p[1]) return -min(d_c, d_w)
res = minimize( neg_capacity, x0, method='Nelder-Mead', bounds=[(0.0, 1.0), (0.0, 1.0)], options={'xatol': 1e-4, 'fatol': 1e-4, 'maxiter': 50} )
# Check if valid return if res.success or res.message: return res.x return x0
def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n)
bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
A_ub = [] b_ub = []
diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2))
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
return np.array([b[1] for b in bounds_list])
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0
phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 iter_limit = 250 if mu > 5000 else 150
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0)
# 1. Global Search over Seeds for name, c_init in configs: c_relaxed, r_relaxed = self.run_physics_relaxation(c_init)
# Phase 1: Regularized (Start with relaxed radii hint) c_p1, r_p1 = self.local_optimization(c_relaxed, radii_init=r_relaxed, equal_bias=True)
# Phase 2: Variable c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False)
r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp)
if score > best_global[2]: best_global = (c_p2, r_lp, score)
# 2. Basin Hopping with Pop and Swap curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
n_iter = 30 temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy() trial_r_init = curr_r.copy()
# Move selection rand_val = self.rng.rand()
if rand_val < 0.35: # Pop Move: Relocate worst circle to largest void min_idx = np.argmin(curr_r)
others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask])
trial_c[min_idx] = target trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
trial_r_init[min_idx] = 0.05
elif rand_val < 0.55: # Swap Move: Exchange worst circle with a large one min_idx = np.argmin(curr_r)
# Pick a large circle (top 50%) sorted_indices = np.argsort(curr_r) candidates = sorted_indices[self.n // 2:] target_idx = candidates[self.rng.randint(len(candidates))]
# Swap positions pos_min = trial_c[min_idx].copy() pos_target = trial_c[target_idx].copy() trial_c[min_idx] = pos_target trial_c[target_idx] = pos_min
# Reset radii to allow re-fitting trial_r_init[min_idx] = 0.05 trial_r_init[target_idx] = 0.05
# Slight jitter to break symmetry trial_c += 0.005 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
else: # Shake Move mag = 0.02 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0)
# Fast optimization c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)
# Evaluate r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new)
# Accept? delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy() temperature *= 0.95
# 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-7} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = RefinedHybridPopOptimizer(n=26) return opt.optimize()
def compute_max_radii(centers): opt = RefinedHybridPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers)# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182import numpy as npimport osimport jsonfrom typing import Dict, Anyimport glob
def evaluate_aux(results_dir: str, primary_result: Dict[str, Any] | None = None) -> Dict[str, Any]: """ Evaluates auxiliary metrics for the circle packing problem. """ metrics = { "aux_normalized_min_radius": 0.0, "aux_radius_variance_from_mean": 0.0, "aux_num_contact_points": 0.0, "aux_bottleneck_circle_ratio": 0.0, "aux_total_overlap_distance": 0.0, "aux_min_wall_distance": 0.0, "aux_num_timeout_generations_recent": 0.0, "aux_avg_execution_time_successful": 0.0, "aux_num_valid_runs_in_primary_result": 0.0, "aux_center_of_mass_deviation": 0.0, }
# --- Calculate aux_num_timeout_generations_recent and aux_avg_execution_time_successful --- try: timeout_count = 0 successful_execution_times = [] num_generations_to_check = 10
current_gen_path_segment = os.path.basename(os.path.dirname(results_dir)) current_gen_num = int(current_gen_path_segment.split('_')[-1]) if current_gen_path_segment.startswith('gen_') else 0
parent_results_base_dir = os.path.dirname(os.path.dirname(os.path.dirname(results_dir)))
for i in range(max(0, current_gen_num - num_generations_to_check), current_gen_num + 1): gen_path = os.path.join(parent_results_base_dir, f"gen_{i}", "results", "metrics.json") if os.path.exists(gen_path): try: with open(gen_path, 'r') as f: gen_metrics = json.load(f) if gen_metrics.get('combined_score', 0.0) == 0.0 and \ 'timeout' in gen_metrics.get('primary', {}).get('validation_error', '').lower(): timeout_count += 1 elif gen_metrics.get('primary', {}).get('num_valid_runs', 0) > 0: exec_time = gen_metrics.get('primary', {}).get('execution_time_mean') if exec_time is not None and exec_time > 0: successful_execution_times.append(exec_time) except (FileNotFoundError, json.JSONDecodeError): pass
metrics["aux_num_timeout_generations_recent"] = float(timeout_count) if successful_execution_times: metrics["aux_avg_execution_time_successful"] = float(np.mean(successful_execution_times)) else: metrics["aux_avg_execution_time_successful"] = 0.0 except Exception as e: print(f"Error calculating historical metrics: {e}")
# --- aux_num_valid_runs_in_primary_result --- try: if primary_result and primary_result.get('primary', {}).get('num_valid_runs') is not None: metrics["aux_num_valid_runs_in_primary_result"] = float(primary_result['primary']['num_valid_runs']) except Exception as e: print(f"Error calculating aux_num_valid_runs_in_primary_result: {e}")
# Process geometric metrics from extra.npz extra_data_path = os.path.join(results_dir, "extra.npz") centers = None radii = None valid_radii = None valid_centers = None num_valid_circles = 0
try: if os.path.exists(extra_data_path): data = np.load(extra_data_path) centers = data["centers"] radii = data["radii"]
valid_radii_mask = radii >= 1e-7 valid_radii = radii[valid_radii_mask] valid_centers = centers[valid_radii_mask] num_valid_circles = len(valid_radii) else: print(f"Warning: {extra_data_path} not found. Geometric metrics will be 0.0.") except Exception as e: print(f"Error loading or processing extra.npz: {e}")
if num_valid_circles > 0: # aux_center_of_mass_deviation (Structural Sensitivity) try: com = np.mean(centers, axis=0) deviation = np.linalg.norm(com - np.array([0.5, 0.5])) metrics["aux_center_of_mass_deviation"] = deviation except Exception as e: print(f"Error calculating aux_center_of_mass_deviation: {e}")
# aux_normalized_min_radius (Component Contribution) try: min_radius = np.min(valid_radii) avg_radius = np.mean(valid_radii) if avg_radius > 1e-7: metrics["aux_normalized_min_radius"] = min_radius / avg_radius else: metrics["aux_normalized_min_radius"] = 0.0 except Exception as e: print(f"Error calculating aux_normalized_min_radius: {e}")
# aux_radius_variance_from_mean (Structural Sensitivity) try: metrics["aux_radius_variance_from_mean"] = float(np.var(valid_radii)) except Exception as e: print(f"Error calculating aux_radius_variance_from_mean: {e}")
# aux_bottleneck_circle_ratio (Component Contribution / Structural Sensitivity) try: if num_valid_circles > 1: min_r = np.min(valid_radii) max_r = np.max(valid_radii) if max_r > 1e-7: metrics["aux_bottleneck_circle_ratio"] = min_r / max_r else: metrics["aux_bottleneck_circle_ratio"] = 0.0 elif num_valid_circles == 1: metrics["aux_bottleneck_circle_ratio"] = 1.0 else: metrics["aux_bottleneck_circle_ratio"] = 0.0 except Exception as e: print(f"Error calculating aux_bottleneck_circle_ratio: {e}")
# aux_total_overlap_distance (Constraint Tension) try: total_overlap_distance = 0.0 for i in range(num_valid_circles): for j in range(i + 1, num_valid_circles): dist_centers = np.linalg.norm(valid_centers[i] - valid_centers[j]) sum_radii = valid_radii[i] + valid_radii[j] if dist_centers < sum_radii: total_overlap_distance += (sum_radii - dist_centers) metrics["aux_total_overlap_distance"] = total_overlap_distance except Exception as e: print(f"Error calculating aux_total_overlap_distance: {e}")
# aux_min_wall_distance (Constraint Tension) try: min_wall_dist = float('inf') for i in range(num_valid_circles): x, y = valid_centers[i] r = valid_radii[i] min_wall_dist = min(min_wall_dist, x - r) min_wall_dist = min(min_wall_dist, 1.0 - x - r) min_wall_dist = min(min_wall_dist, y - r) min_wall_dist = min(min_wall_dist, 1.0 - y - r) metrics["aux_min_wall_distance"] = min_wall_dist except Exception as e: print(f"Error calculating aux_min_wall_distance: {e}") metrics["aux_min_wall_distance"] = 0.0
# aux_num_contact_points (Constraint Tension) try: contact_epsilon = 1e-6 num_contacts = 0
for i in range(num_valid_circles): x, y = valid_centers[i] r = valid_radii[i] if abs(x - r) < contact_epsilon: num_contacts += 1 if abs(1.0 - x - r) < contact_epsilon: num_contacts += 1 if abs(y - r) < contact_epsilon: num_contacts += 1 if abs(1.0 - y - r) < contact_epsilon: num_contacts += 1
for i in range(num_valid_circles): for j in range(i + 1, num_valid_circles): dist_centers = np.linalg.norm(valid_centers[i] - valid_centers[j]) sum_radii = valid_radii[i] + valid_radii[j] if abs(dist_centers - sum_radii) < contact_epsilon: num_contacts += 1 metrics["aux_num_contact_points"] = float(num_contacts) except Exception as e: print(f"Error calculating aux_num_contact_points: {e}")
return metrics1234{ "correct": true, "error": null}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{ "combined_score": 2.63555267307244, "correct": true, "primary": { "combined_score": 2.63555267307244, "public": { "centers_str": " centers[0] = (0.1106, 0.1106)\n centers[1] = (0.3130, 0.0927)\n centers[2] = (0.5001, 0.0943)\n centers[3] = (0.6870, 0.0926)\n centers[4] = (0.8894, 0.1106)\n centers[5] = (0.0954, 0.3197)\n centers[6] = (0.2390, 0.2376)\n centers[7] = (0.4038, 0.2587)\n centers[8] = (0.5961, 0.2588)\n centers[9] = (0.7609, 0.2375)\n centers[10] = (0.9045, 0.3196)\n centers[11] = (0.1030, 0.5190)\n centers[12] = (0.2720, 0.4051)\n centers[13] = (0.5000, 0.4721)\n centers[14] = (0.7279, 0.4051)\n centers[15] = (0.8970, 0.5189)\n centers[16] = (0.1049, 0.7269)\n centers[17] = (0.2961, 0.6191)\n centers[18] = (0.4999, 0.7265)\n centers[19] = (0.7038, 0.6192)\n centers[20] = (0.8951, 0.7269)\n centers[21] = (0.0846, 0.9154)\n centers[22] = (0.2959, 0.8672)\n centers[23] = (0.4999, 0.9211)\n centers[24] = (0.7040, 0.8672)\n centers[25] = (0.9154, 0.9154)", "num_circles": 26 }, "private": { "reported_sum_of_radii": 2.63555267307244 }, "execution_time_mean": 96.79738395940512, "execution_time_std": 0.0, "num_valid_runs": 1, "num_invalid_runs": 0, "all_validation_errors": [], "correct": true, "validation_error": null }, "auxiliary": { "aux_normalized_min_radius": 0.6907041519435574, "aux_radius_variance_from_mean": 0.0002791739773516252, "aux_num_contact_points": 35.0, "aux_bottleneck_circle_ratio": 0.5119789491208242, "aux_total_overlap_distance": 0.0, "aux_min_wall_distance": 0.0, "aux_num_timeout_generations_recent": 0.0, "aux_avg_execution_time_successful": 0.0, "aux_num_valid_runs_in_primary_result": 0.0, "aux_center_of_mass_deviation": 0.024698487612143605, "aux_metric_eval_success": 1.0, "aux_metric_error_code": 0.0, "aux_metric_error_message_length": 0.0, "aux_metric_error_detail_length": 0.0, "aux_metric_non_numeric_dropped_count": 0.0 }, "auxiliary_descriptions": { "aux_normalized_min_radius": "Minimum radius normalized by average radius. Higher values are better, indicating more uniform radii. (Component Contribution)", "aux_radius_variance_from_mean": "Variance of circle radii from the mean. Lower values are better, indicating more uniform radii, aligned with \"Hard-Sphere\" recommendation. (Structural Sensitivity)", "aux_num_contact_points": "Count of circle-circle and circle-wall contacts (distance within epsilon). A higher value indicates a tighter and more rigid packing. (Constraint Tension / Structural Sensitivity)", "aux_bottleneck_circle_ratio": "Ratio of the smallest radius to the largest radius. Closer to 1.0 indicates more uniform radii, useful for identifying bottleneck circles for \"Swap\" mutation. (Component Contribution / Structural Sensitivity)", "aux_total_overlap_distance": "Sum of pairwise overlap distances for all overlapping circles. Lower values are better, indicating less constraint violation. (Constraint Tension)", "aux_min_wall_distance": "Minimum distance from any circle's edge to any wall. Negative values indicate wall penetration. Higher values (closer to zero or positive) are better. (Constraint Tension)", "aux_num_timeout_generations_recent": "Count of generations (out of the last 10) that resulted in a timeout. Higher values indicate instability. (Search Velocity / Feasibility)", "aux_avg_execution_time_successful": "Average execution time (in seconds) of successful (non-timeout, non-zero primary score) generations from the last 10. Higher values indicate increasing computational cost. (Search Velocity)", "aux_num_valid_runs_in_primary_result": "Number of valid runs reported by the primary evaluator for the current generation. Higher values indicate more successful sub-evaluations. (Feasibility)", "aux_center_of_mass_deviation": "Euclidean distance of the packing's center of mass from the center of the unit square (0.5, 0.5). Higher values indicate less symmetric or more unbalanced packings, which might be harder to optimize. (Structural Sensitivity)" }, "timestamp": 1772458318.7084413, "generation": 102}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381# EVOLVE-BLOCK-STARTimport numpy as npfrom scipy.optimize import minimize, linprog
class LatticeGenPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42) # Grid for void finding (resolution 50x50) self.grid_res = 50 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def get_lattice_patterns(self): """Generates all valid hexagonal lattice row compositions for N=26.""" results = [] def backtrack(current_rows, current_sum): if current_sum == self.n: results.append(list(current_rows)) return if current_sum > self.n: return # Next row constraints: # 1. Difference from prev row <= 1 (hex packing property) # 2. Length within reasonable bounds (e.g., 2 to 9 for N=26) if not current_rows: # First row: N=26 usually fits in rows of length 3-8 options = range(3, 9) else: last = current_rows[-1] # Hexagonal lattice constraint: adjacent rows differ by at most 1 options = [last-1, last, last+1] options = [x for x in options if 2 <= x <= 9] for count in options: # Heuristic pruning: avoid extremely tall/narrow configurations # Approximate rows needed for remaining circles assuming similar width remaining = self.n - (current_sum + count) if remaining > 0: est_remaining_rows = remaining / max(1, count) if len(current_rows) + 1 + est_remaining_rows > 10: continue backtrack(current_rows + [count], current_sum + count)
backtrack([], 0) # Sort by "squareness" likelihood # Optimal packing in a square usually has Height approx Width # Height ~ rows * sqrt(3)/2, Width ~ max_row_len def aspect_diff(rows): h = len(rows) * 0.866 w = max(rows) return abs(h/w - 1.0) results.sort(key=aspect_diff) # Select the top candidates plus diversity top_k = results[:15] # Ensure some known good patterns are present known_good = [ [5, 5, 6, 5, 5], [6, 7, 6, 7], [6, 5, 6, 5, 4], [5, 6, 5, 5, 5] ] for k in known_good: if k not in top_k: top_k.append(k) return top_k
def generate_centers_from_rows(self, rows): centers = [] dy = np.sqrt(3) / 2 for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers) # Normalize to unit square if len(centers) > 0: min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = max_c - min_c max_span = np.max(span) scale = 0.85 / max_span if max_span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.075 # Center it curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center) return centers
def get_initial_configs(self): configs = [] # 1. Lattice Patterns row_patterns = self.get_lattice_patterns() for rows in row_patterns: c = self.generate_centers_from_rows(rows) configs.append(c) # 2. Geometric Fallbacks # Spiral indices = np.arange(self.n) theta = indices * np.pi * (3 - np.sqrt(5)) r = np.sqrt(indices + 1) / np.sqrt(self.n) c_spiral = np.zeros((self.n, 2)) c_spiral[:, 0] = 0.5 + 0.44 * r * np.cos(theta) c_spiral[:, 1] = 0.5 + 0.44 * r * np.sin(theta) configs.append(c_spiral) # Pure Random configs.append(np.random.rand(self.n, 2)) return configs
def solve_lp_radii(self, centers): """Computes max radii for fixed centers using LP.""" n = len(centers) c_obj = -np.ones(n)
bounds = [] for i in range(n): x, y = centers[i] # Clip to be safe inside [0,1] x = np.clip(x, 0, 1) y = np.clip(y, 0, 1) b = min(x, 1-x, y, 1-y) bounds.append((0, max(0.0, b)))
A_ub = [] b_ub = []
diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) dists = np.sqrt(dist_sq)
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
# Try Highs solver first try: res = linprog(c_obj, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='highs') if res.success: return res.x except: pass # Fallback to interior-point res = linprog(c_obj, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='interior-point') if res.success: return res.x # Robust Fallback: Geometric approx r_fallback = np.zeros(n) for i in range(n): d_wall = bounds[i][1] # dist to nearest neighbor / 2 d_neigh = np.min(dists[i, np.arange(n)!=i]) / 2.0 r_fallback[i] = min(d_wall, d_neigh) return r_fallback
def find_largest_void(self, centers): """Find point furthest from centers and walls.""" # 1. Grid Search diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] d_c_sq = np.min(np.sum(diff**2, axis=2), axis=1) d_c = np.sqrt(d_c_sq) d_w = np.minimum( np.minimum(self.grid_pts[:, 0], 1 - self.grid_pts[:, 0]), np.minimum(self.grid_pts[:, 1], 1 - self.grid_pts[:, 1]) ) min_clearance = np.minimum(d_c, d_w) best_idx = np.argmax(min_clearance) x0 = self.grid_pts[best_idx] # 2. Nelder-Mead Polish def obj(p): # Penalize out of bounds if not (0 <= p[0] <= 1 and 0 <= p[1] <= 1): return 1.0 dc = np.min(np.linalg.norm(centers - p, axis=1)) dw = min(p[0], 1-p[0], p[1], 1-p[1]) return -min(dc, dw) res = minimize(obj, x0, method='Nelder-Mead', bounds=[(0,1),(0,1)], options={'maxiter': 50, 'xatol': 1e-4}) return res.x
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:] obj = -np.sum(r) if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2) # Wall Penalty w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2) # Overlap Penalty diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) # Mask diagonal dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2) return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, equal_bias=False, fast=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n) x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n if fast: phases = [100.0, 5000.0] else: phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] current_x = x0 reg = 5.0 if equal_bias else 0.0 for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 # Iteration limit based on phase stiffness iter_lim = 100 if fast else (300 if mu > 5000 else 150) res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_lim, 'ftol': 1e-5} ) current_x = res.x return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_res = (None, None, -1.0) # 1. Seed Screening for c_init in configs: # Phase 1: Equalize radii (Regularization High) c_eq, r_eq = self.local_optimization(c_init, equal_bias=True, fast=False) # Phase 2: Relax radii (Regularization Low) c_var, _ = self.local_optimization(c_eq, radii_init=r_eq, equal_bias=False, fast=False) r_lp = self.solve_lp_radii(c_var) score = np.sum(r_lp) if score > best_res[2]: best_res = (c_var, r_lp, score)
# 2. Basin Hopping Refinement if best_res[0] is None: return np.random.rand(self.n, 2), np.ones(self.n)*0.01
curr_c, curr_r, curr_score = best_res best_c, best_r, best_score = best_res n_iter = 25 temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() trial_r = curr_r.copy() # Decision u = self.rng.rand() if u < 0.4: # Pop Move: Move worst circle to void min_idx = np.argmin(curr_r) mask = np.ones(self.n, dtype=bool) mask[min_idx] = False target = self.find_largest_void(trial_c[mask]) trial_c[min_idx] = target # Jitter others to break static friction trial_c[mask] += 0.005 * (self.rng.rand(self.n-1, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r[min_idx] = 0.05 elif u < 0.6: # Swap Move: Swap worst circle with a larger one min_idx = np.argmin(curr_r) # Candidates larger than median large_candidates = np.where(curr_r > np.median(curr_r))[0] if len(large_candidates) > 0: swap_idx = self.rng.choice(large_candidates) # Swap trial_c[min_idx], trial_c[swap_idx] = trial_c[swap_idx].copy(), trial_c[min_idx].copy() trial_r[min_idx] = 0.05 trial_r[swap_idx] = 0.05 else: # Shake Move mag = 0.02 * np.exp(-i / n_iter) perturb = mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c + perturb, 0.0, 1.0) trial_r = trial_r * 0.95 # Fast Local Optimization c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r, fast=True) # Exact LP Evaluation r_lp = self.solve_lp_radii(c_new) s_new = np.sum(r_lp) # Metropolis Acceptance delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta / temperature)): curr_c, curr_r, curr_score = c_new, r_lp, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_lp.copy() temperature *= 0.95 # 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-8} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c) return final_c, final_r
def construct_packing(): opt = LatticeGenPopOptimizer(n=26) return opt.optimize()
def compute_max_radii(centers): opt = LatticeGenPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers)
def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii# EVOLVE-BLOCK-END123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365--- a/original.py+++ b/original.py@@ -1,94 +1,292 @@ # EVOLVE-BLOCK-START-"""Constructor-based circle packing for n=26 circles"""+"""+Optimization-based circle packing for n=26 circles.+Uses scipy.optimize to maximize sum of radii with penalty method.+""" import numpy as np-+from scipy.optimize import minimize def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii.-- Returns:- Tuple of (centers, radii, sum_of_radii)- centers: np.array of shape (26, 2) with (x, y) coordinates- radii: np.array of shape (26) with radius of each circle- sum_of_radii: Sum of all radii- """- # Initialize arrays for 26 circles+ """ n = 26- centers = np.zeros((n, 2))-- # Place circles in a structured pattern- # This is a simple pattern - evolution will improve this-- # First, place a large circle in the center- centers[0] = [0.5, 0.5]-- # Place 8 circles around it in a ring- for i in range(8):- angle = 2 * np.pi * i / 8- centers[i + 1] = [0.5 + 0.3 * np.cos(angle), 0.5 + 0.3 * np.sin(angle)]-- # Place 16 more circles in an outer ring- for i in range(16):- angle = 2 * np.pi * i / 16- centers[i + 9] = [0.5 + 0.7 * np.cos(angle), 0.5 + 0.7 * np.sin(angle)]-- # Additional positioning adjustment to make sure all circles- # are inside the square and don't overlap- # Clip to ensure everything is inside the unit square- centers = np.clip(centers, 0.01, 0.99)-- # Compute maximum valid radii for this configuration- radii = compute_max_radii(centers)- return centers, radii---def compute_max_radii(centers):- """- Compute the maximum possible radii for each circle position- such that they don't overlap and stay within the unit square.-- Args:- centers: np.array of shape (n, 2) with (x, y) coordinates-- Returns:- np.array of shape (n) with radius of each circle- """- n = centers.shape[0]- radii = np.ones(n)-- # First, limit by distance to square borders+ + # 1. Generate Seeds+ seeds = generate_seeds(n)+ + # 2. Coarse Optimization (Screening)+ candidates = []+ # Reduced maxiter for screening+ coarse_opts = {'maxiter': 50, 'ftol': 1e-4}+ + for centers, radii in seeds:+ # Flatten parameters+ x0 = np.concatenate([centers.flatten(), radii])+ + # Bounds: centers in [0,1], radii in [0, 0.5]+ bounds = [(0, 1)] * (2 * n) + [(1e-4, 0.5)] * n+ + # Run minimization with moderate penalty+ try:+ res = minimize(+ objective_function, + x0, + args=(n, 100.0), # Moderate penalty+ method='L-BFGS-B', + bounds=bounds,+ options=coarse_opts+ )+ # Score is sum of radii (negative of objective without penalty approx)+ # We use the raw sum of radii from the result+ r_opt = res.x[2*n:]+ score = np.sum(r_opt)+ candidates.append((score, res.x))+ except Exception:+ continue+ + # 3. Select Best and Refine+ # Sort by score descending+ candidates.sort(key=lambda x: x[0], reverse=True)+ + # Take top candidate (or top 2 if budget allows, here top 1 for speed)+ best_params = candidates[0][1] if candidates else seeds[0][0].flatten().tolist() + seeds[0][1].tolist()+ + # Fine optimization with ramping penalty+ # Ramp 1: Stiffer penalty to resolve overlaps+ bounds = [(0, 1)] * (2 * n) + [(1e-4, 0.5)] * n+ res = minimize(+ objective_function,+ best_params,+ args=(n, 1000.0),+ method='L-BFGS-B',+ bounds=bounds,+ options={'maxiter': 200, 'ftol': 1e-6}+ )+ + # Ramp 2: Very stiff penalty for final polish+ res = minimize(+ objective_function,+ res.x,+ args=(n, 1e6),+ method='L-BFGS-B',+ bounds=bounds,+ options={'maxiter': 500, 'ftol': 1e-8}+ )+ + # 4. Extract and Validate+ final_x = res.x+ centers = final_x[:2*n].reshape((n, 2))+ radii = final_x[2*n:]+ + # Ensure strict validity by global scaling+ centers, radii = enforce_strict_validity(centers, radii)+ + return centers, radii, np.sum(radii)++def generate_seeds(n):+ """Generate a list of initial (centers, radii) tuples."""+ seeds = []+ + # Lattice patterns (row compositions summing to 26)+ # Designed to mimic hexagonal close packing in a square+ patterns = [+ [5, 5, 5, 5, 6],+ [6, 5, 5, 5, 5],+ [5, 6, 5, 5, 5],+ [5, 5, 6, 5, 5],+ [5, 5, 5, 6, 5],+ [6, 7, 7, 6], # Very dense hex+ [5, 5, 5, 5, 5, 1], # 5x5 + 1+ [4, 5, 5, 5, 5, 2],+ [4, 5, 6, 5, 4, 2],+ [7, 6, 7, 6] # 26 exactly+ ]+ + for pattern in patterns:+ centers = []+ # Construct lattice coordinates+ # Assume roughly unit distance 1, scale later+ y_cursor = 0.0+ row_height = np.sqrt(3) / 2.0+ + for i, count in enumerate(pattern):+ # Center the row: length is count-1.+ # x coords: 0, 1, 2... then shifted to center around 0+ row_width = max(0, count - 1)+ x_start = -row_width / 2.0+ + # Stagger: Shift every other row? + # In optimal hex packing, rows shift by 0.5 relative to neighbors.+ # Centering already handles implicit staggering if row lengths differ by 1.+ # If row lengths are same, we manually stagger.+ if i > 0 and len(pattern) > 1 and pattern[i] == pattern[i-1]:+ x_start += 0.5+ + for j in range(count):+ centers.append([x_start + j, y_cursor])+ + y_cursor += row_height+ + pts = np.array(centers)+ + # Verify count (patterns might be approximate)+ if len(pts) > n:+ pts = pts[:n]+ elif len(pts) < n:+ # Pad with random+ needed = n - len(pts)+ extra = np.random.uniform(-2, 2, (needed, 2))+ pts = np.vstack([pts, extra])+ + # Normalize to unit square [0.1, 0.9]+ min_vals = pts.min(axis=0)+ max_vals = pts.max(axis=0)+ dims = max_vals - min_vals+ scale = 0.8 / np.max(np.maximum(dims, 1e-6))+ + pts = (pts - min_vals) * scale + 0.1+ + # Initial radii guess+ radii = np.ones(n) * (0.5 / np.sqrt(n)) # rough heuristic+ seeds.append((pts, radii))+ + # Add random seeds+ for _ in range(3):+ c = np.random.uniform(0.1, 0.9, (n, 2))+ r = np.random.uniform(0.01, 0.05, n)+ seeds.append((c, r))+ + return seeds++def objective_function(params, n, penalty_weight):+ """+ Objective: minimize -sum(radii) + penalty * violations+ params: [x1, y1, ... xn, yn, r1, ... rn]+ """+ centers = params[:2*n].reshape((n, 2))+ radii = params[2*n:]+ + # Primary Objective: Maximize sum of radii+ obj = -np.sum(radii)+ + # 1. Wall Violations+ # x - r >= 0 -> violation: max(0, r - x)+ # x + r <= 1 -> violation: max(0, x + r - 1)+ # y same...+ + v_left = np.maximum(0, radii - centers[:, 0])+ v_right = np.maximum(0, centers[:, 0] + radii - 1.0)+ v_bottom = np.maximum(0, radii - centers[:, 1])+ v_top = np.maximum(0, centers[:, 1] + radii - 1.0)+ + wall_penalty = np.sum(v_left**2 + v_right**2 + v_bottom**2 + v_top**2)+ + # 2. Overlap Violations+ # dist(i,j) >= r_i + r_j+ # violation: max(0, r_i + r_j - dist)+ + # Vectorized distance calculation+ # (N, 1, 2) - (1, N, 2) -> (N, N, 2)+ diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]+ dist_sq = np.sum(diff**2, axis=2)+ + # Avoid sqrt(0) on diagonal+ safe_dist_sq = dist_sq.copy()+ np.fill_diagonal(safe_dist_sq, 1.0) # dummy value+ dist = np.sqrt(safe_dist_sq)+ + # Radii sum matrix+ r_sum = radii[:, np.newaxis] + radii[np.newaxis, :]+ + # Overlap amount+ overlap = np.maximum(0, r_sum - dist)+ np.fill_diagonal(overlap, 0) # clear self-overlap+ + # Since we sum over whole matrix, each pair is counted twice+ overlap_penalty = 0.5 * np.sum(overlap**2)+ + return obj + penalty_weight * (wall_penalty + overlap_penalty)++def enforce_strict_validity(centers, radii):+ """+ Scale radii to ensure all circles are strictly inside the square+ and disjoint. Uses a global scaling factor to preserve relative sizes.+ """+ n = len(radii)+ + # 1. Constraint: Walls+ # For each circle i: r_i * scale <= x_i, etc.+ # scale <= x_i / r_i+ + max_scale = 1.0+ for i in range(n): x, y = centers[i]- # Distance to borders- radii[i] = min(x, y, 1 - x, 1 - y)-- # Then, limit by distance to other circles- # Each pair of circles with centers at distance d can have- # sum of radii at most d to avoid overlap+ r = radii[i]+ if r < 1e-9: continue+ + # Distance to walls+ d_walls = min(x, y, 1.0 - x, 1.0 - y)+ if d_walls < r:+ max_scale = min(max_scale, d_walls / r)+ + # 2. Constraint: Overlaps+ # For pair i, j: scale * (r_i + r_j) <= dist_ij+ # scale <= dist_ij / (r_i + r_j)+ + # Vectorized check+ diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :]+ dist_sq = np.sum(diff**2, axis=2)+ + # We only care about off-diagonal+ # Add infinity to diagonal to ignore it in min()+ np.fill_diagonal(dist_sq, np.inf)+ dist = np.sqrt(dist_sq)+ + r_sum = radii[:, np.newaxis] + radii[np.newaxis, :]+ + # Ratios+ # We want min(dist / r_sum)+ # Avoid divide by zero+ r_sum[r_sum < 1e-9] = 1e-9+ + ratios = dist / r_sum+ min_overlap_scale = np.min(ratios)+ + max_scale = min(max_scale, min_overlap_scale)+ + # Apply scale (with tiny epsilon safety margin)+ final_scale = max_scale * (1.0 - 1e-7)+ + # If final_scale is effectively 1 (within tolerance), we keep it+ # If it's much smaller, we shrink.+ + return centers, radii * final_scale++def compute_max_radii(centers):+ """+ Legacy helper maintained for interface compatibility if needed,+ re-implemented to essentially perform the same validity check logic.+ """+ n = len(centers)+ radii = np.zeros(n)+ # Initialize with distance to wall for i in range(n):- for j in range(i + 1, n):- dist = np.sqrt(np.sum((centers[i] - centers[j]) ** 2))-- # If current radii would cause overlap- if radii[i] + radii[j] > dist:- # Scale both radii proportionally- scale = dist / (radii[i] + radii[j])- radii[i] *= scale- radii[j] *= scale-+ radii[i] = min(centers[i,0], centers[i,1], 1-centers[i,0], 1-centers[i,1])+ # Run the strict validity scaler on these max radii+ _, radii = enforce_strict_validity(centers, radii) return radii- # EVOLVE-BLOCK-END # This part remains fixed (not evolved) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292# EVOLVE-BLOCK-START"""Optimization-based circle packing for n=26 circles.Uses scipy.optimize to maximize sum of radii with penalty method."""
import numpy as npfrom scipy.optimize import minimize
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii. """ n = 26 # 1. Generate Seeds seeds = generate_seeds(n) # 2. Coarse Optimization (Screening) candidates = [] # Reduced maxiter for screening coarse_opts = {'maxiter': 50, 'ftol': 1e-4} for centers, radii in seeds: # Flatten parameters x0 = np.concatenate([centers.flatten(), radii]) # Bounds: centers in [0,1], radii in [0, 0.5] bounds = [(0, 1)] * (2 * n) + [(1e-4, 0.5)] * n # Run minimization with moderate penalty try: res = minimize( objective_function, x0, args=(n, 100.0), # Moderate penalty method='L-BFGS-B', bounds=bounds, options=coarse_opts ) # Score is sum of radii (negative of objective without penalty approx) # We use the raw sum of radii from the result r_opt = res.x[2*n:] score = np.sum(r_opt) candidates.append((score, res.x)) except Exception: continue # 3. Select Best and Refine # Sort by score descending candidates.sort(key=lambda x: x[0], reverse=True) # Take top candidate (or top 2 if budget allows, here top 1 for speed) best_params = candidates[0][1] if candidates else seeds[0][0].flatten().tolist() + seeds[0][1].tolist() # Fine optimization with ramping penalty # Ramp 1: Stiffer penalty to resolve overlaps bounds = [(0, 1)] * (2 * n) + [(1e-4, 0.5)] * n res = minimize( objective_function, best_params, args=(n, 1000.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 200, 'ftol': 1e-6} ) # Ramp 2: Very stiff penalty for final polish res = minimize( objective_function, res.x, args=(n, 1e6), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-8} ) # 4. Extract and Validate final_x = res.x centers = final_x[:2*n].reshape((n, 2)) radii = final_x[2*n:] # Ensure strict validity by global scaling centers, radii = enforce_strict_validity(centers, radii) return centers, radii, np.sum(radii)
def generate_seeds(n): """Generate a list of initial (centers, radii) tuples.""" seeds = [] # Lattice patterns (row compositions summing to 26) # Designed to mimic hexagonal close packing in a square patterns = [ [5, 5, 5, 5, 6], [6, 5, 5, 5, 5], [5, 6, 5, 5, 5], [5, 5, 6, 5, 5], [5, 5, 5, 6, 5], [6, 7, 7, 6], # Very dense hex [5, 5, 5, 5, 5, 1], # 5x5 + 1 [4, 5, 5, 5, 5, 2], [4, 5, 6, 5, 4, 2], [7, 6, 7, 6] # 26 exactly ] for pattern in patterns: centers = [] # Construct lattice coordinates # Assume roughly unit distance 1, scale later y_cursor = 0.0 row_height = np.sqrt(3) / 2.0 for i, count in enumerate(pattern): # Center the row: length is count-1. # x coords: 0, 1, 2... then shifted to center around 0 row_width = max(0, count - 1) x_start = -row_width / 2.0 # Stagger: Shift every other row? # In optimal hex packing, rows shift by 0.5 relative to neighbors. # Centering already handles implicit staggering if row lengths differ by 1. # If row lengths are same, we manually stagger. if i > 0 and len(pattern) > 1 and pattern[i] == pattern[i-1]: x_start += 0.5 for j in range(count): centers.append([x_start + j, y_cursor]) y_cursor += row_height pts = np.array(centers) # Verify count (patterns might be approximate) if len(pts) > n: pts = pts[:n] elif len(pts) < n: # Pad with random needed = n - len(pts) extra = np.random.uniform(-2, 2, (needed, 2)) pts = np.vstack([pts, extra]) # Normalize to unit square [0.1, 0.9] min_vals = pts.min(axis=0) max_vals = pts.max(axis=0) dims = max_vals - min_vals scale = 0.8 / np.max(np.maximum(dims, 1e-6)) pts = (pts - min_vals) * scale + 0.1 # Initial radii guess radii = np.ones(n) * (0.5 / np.sqrt(n)) # rough heuristic seeds.append((pts, radii)) # Add random seeds for _ in range(3): c = np.random.uniform(0.1, 0.9, (n, 2)) r = np.random.uniform(0.01, 0.05, n) seeds.append((c, r)) return seeds
def objective_function(params, n, penalty_weight): """ Objective: minimize -sum(radii) + penalty * violations params: [x1, y1, ... xn, yn, r1, ... rn] """ centers = params[:2*n].reshape((n, 2)) radii = params[2*n:] # Primary Objective: Maximize sum of radii obj = -np.sum(radii) # 1. Wall Violations # x - r >= 0 -> violation: max(0, r - x) # x + r <= 1 -> violation: max(0, x + r - 1) # y same... v_left = np.maximum(0, radii - centers[:, 0]) v_right = np.maximum(0, centers[:, 0] + radii - 1.0) v_bottom = np.maximum(0, radii - centers[:, 1]) v_top = np.maximum(0, centers[:, 1] + radii - 1.0) wall_penalty = np.sum(v_left**2 + v_right**2 + v_bottom**2 + v_top**2) # 2. Overlap Violations # dist(i,j) >= r_i + r_j # violation: max(0, r_i + r_j - dist) # Vectorized distance calculation # (N, 1, 2) - (1, N, 2) -> (N, N, 2) diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) # Avoid sqrt(0) on diagonal safe_dist_sq = dist_sq.copy() np.fill_diagonal(safe_dist_sq, 1.0) # dummy value dist = np.sqrt(safe_dist_sq) # Radii sum matrix r_sum = radii[:, np.newaxis] + radii[np.newaxis, :] # Overlap amount overlap = np.maximum(0, r_sum - dist) np.fill_diagonal(overlap, 0) # clear self-overlap # Since we sum over whole matrix, each pair is counted twice overlap_penalty = 0.5 * np.sum(overlap**2) return obj + penalty_weight * (wall_penalty + overlap_penalty)
def enforce_strict_validity(centers, radii): """ Scale radii to ensure all circles are strictly inside the square and disjoint. Uses a global scaling factor to preserve relative sizes. """ n = len(radii) # 1. Constraint: Walls # For each circle i: r_i * scale <= x_i, etc. # scale <= x_i / r_i max_scale = 1.0 for i in range(n): x, y = centers[i] r = radii[i] if r < 1e-9: continue # Distance to walls d_walls = min(x, y, 1.0 - x, 1.0 - y) if d_walls < r: max_scale = min(max_scale, d_walls / r) # 2. Constraint: Overlaps # For pair i, j: scale * (r_i + r_j) <= dist_ij # scale <= dist_ij / (r_i + r_j) # Vectorized check diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) # We only care about off-diagonal # Add infinity to diagonal to ignore it in min() np.fill_diagonal(dist_sq, np.inf) dist = np.sqrt(dist_sq) r_sum = radii[:, np.newaxis] + radii[np.newaxis, :] # Ratios # We want min(dist / r_sum) # Avoid divide by zero r_sum[r_sum < 1e-9] = 1e-9 ratios = dist / r_sum min_overlap_scale = np.min(ratios) max_scale = min(max_scale, min_overlap_scale) # Apply scale (with tiny epsilon safety margin) final_scale = max_scale * (1.0 - 1e-7) # If final_scale is effectively 1 (within tolerance), we keep it # If it's much smaller, we shrink. return centers, radii * final_scale
def compute_max_radii(centers): """ Legacy helper maintained for interface compatibility if needed, re-implemented to essentially perform the same validity check logic. """ n = len(centers) radii = np.zeros(n) # Initialize with distance to wall for i in range(n): radii[i] = min(centers[i,0], centers[i,1], 1-centers[i,0], 1-centers[i,1]) # Run the strict validity scaler on these max radii _, radii = enforce_strict_validity(centers, radii) return radii
# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# EVOLVE-BLOCK-START"""Constructor-based circle packing for n=26 circles"""
import numpy as np
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii.
Returns: Tuple of (centers, radii, sum_of_radii) centers: np.array of shape (26, 2) with (x, y) coordinates radii: np.array of shape (26) with radius of each circle sum_of_radii: Sum of all radii """ # Initialize arrays for 26 circles n = 26 centers = np.zeros((n, 2))
# Place circles in a structured pattern # This is a simple pattern - evolution will improve this
# First, place a large circle in the center centers[0] = [0.5, 0.5]
# Place 8 circles around it in a ring for i in range(8): angle = 2 * np.pi * i / 8 centers[i + 1] = [0.5 + 0.3 * np.cos(angle), 0.5 + 0.3 * np.sin(angle)]
# Place 16 more circles in an outer ring for i in range(16): angle = 2 * np.pi * i / 16 centers[i + 9] = [0.5 + 0.7 * np.cos(angle), 0.5 + 0.7 * np.sin(angle)]
# Additional positioning adjustment to make sure all circles # are inside the square and don't overlap # Clip to ensure everything is inside the unit square centers = np.clip(centers, 0.01, 0.99)
# Compute maximum valid radii for this configuration radii = compute_max_radii(centers) return centers, radii
def compute_max_radii(centers): """ Compute the maximum possible radii for each circle position such that they don't overlap and stay within the unit square.
Args: centers: np.array of shape (n, 2) with (x, y) coordinates
Returns: np.array of shape (n) with radius of each circle """ n = centers.shape[0] radii = np.ones(n)
# First, limit by distance to square borders for i in range(n): x, y = centers[i] # Distance to borders radii[i] = min(x, y, 1 - x, 1 - y)
# Then, limit by distance to other circles # Each pair of circles with centers at distance d can have # sum of radii at most d to avoid overlap for i in range(n): for j in range(i + 1, n): dist = np.sqrt(np.sum((centers[i] - centers[j]) ** 2))
# If current radii would cause overlap if radii[i] + radii[j] > dist: # Scale both radii proportionally scale = dist / (radii[i] + radii[j]) radii[i] *= scale radii[j] *= scale
return radii
# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283# EVOLVE-BLOCK-START"""Optimization-based circle packing for n=26 circles.Uses scipy.optimize to maximize sum of radii with penalty method."""
import numpy as npfrom scipy.optimize import minimize
def construct_packing(): """ Construct a specific arrangement of 26 circles in a unit square that attempts to maximize the sum of their radii. """ n = 26 # 1. Generate Seeds seeds = generate_seeds(n) # 2. Coarse Optimization (Screening) candidates = [] # Reduced maxiter for screening coarse_opts = {'maxiter': 50, 'ftol': 1e-4} for centers, radii in seeds: # Flatten parameters x0 = np.concatenate([centers.flatten(), radii]) # Bounds: centers in [0,1], radii in [0, 0.5] bounds = [(0, 1)] * (2 * n) + [(1e-4, 0.5)] * n # Run minimization with moderate penalty try: res = minimize( objective_function, x0, args=(n, 100.0), # Moderate penalty method='L-BFGS-B', bounds=bounds, options=coarse_opts ) # Score is sum of radii (negative of objective without penalty approx) # We use the raw sum of radii from the result r_opt = res.x[2*n:] score = np.sum(r_opt) candidates.append((score, res.x)) except Exception: continue # 3. Select Best and Refine # Sort by score descending candidates.sort(key=lambda x: x[0], reverse=True) # Take top candidate (or top 2 if budget allows, here top 1 for speed) best_params = candidates[0][1] if candidates else seeds[0][0].flatten().tolist() + seeds[0][1].tolist() # Fine optimization with ramping penalty # Ramp 1: Stiffer penalty to resolve overlaps bounds = [(0, 1)] * (2 * n) + [(1e-4, 0.5)] * n res = minimize( objective_function, best_params, args=(n, 1000.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 200, 'ftol': 1e-6} ) # Ramp 2: Very stiff penalty for final polish res = minimize( objective_function, res.x, args=(n, 1e6), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-8} ) # 4. Extract and Validate final_x = res.x centers = final_x[:2*n].reshape((n, 2)) radii = final_x[2*n:] # Ensure strict validity by global scaling centers, radii = enforce_strict_validity(centers, radii) return centers, radii, np.sum(radii)
def generate_seeds(n): """Generate a list of initial (centers, radii) tuples.""" seeds = [] # Lattice patterns (row compositions summing to 26) # Designed to mimic hexagonal close packing in a square patterns = [ [5, 5, 5, 5, 6], [6, 5, 5, 5, 5], [5, 6, 5, 5, 5], [5, 5, 6, 5, 5], [5, 5, 5, 6, 5], [6, 7, 7, 6], # Very dense hex [5, 5, 5, 5, 5, 1], # 5x5 + 1 [4, 5, 5, 5, 5, 2], [4, 5, 6, 5, 4, 2], [7, 6, 7, 6] # 26 exactly ] for pattern in patterns: centers = [] # Construct lattice coordinates # Assume roughly unit distance 1, scale later y_cursor = 0.0 row_height = np.sqrt(3) / 2.0 for i, count in enumerate(pattern): # Center the row: length is count-1. # x coords: 0, 1, 2... then shifted to center around 0 row_width = max(0, count - 1) x_start = -row_width / 2.0 # Stagger: Shift every other row? # In optimal hex packing, rows shift by 0.5 relative to neighbors. # Centering already handles implicit staggering if row lengths differ by 1. # If row lengths are same, we manually stagger. if i > 0 and len(pattern) > 1 and pattern[i] == pattern[i-1]: x_start += 0.5 for j in range(count): centers.append([x_start + j, y_cursor]) y_cursor += row_height pts = np.array(centers) # Verify count (patterns might be approximate) if len(pts) > n: pts = pts[:n] elif len(pts) < n: # Pad with random needed = n - len(pts) extra = np.random.uniform(-2, 2, (needed, 2)) pts = np.vstack([pts, extra]) # Normalize to unit square [0.1, 0.9] min_vals = pts.min(axis=0) max_vals = pts.max(axis=0) dims = max_vals - min_vals scale = 0.8 / np.max(np.maximum(dims, 1e-6)) pts = (pts - min_vals) * scale + 0.1 # Initial radii guess radii = np.ones(n) * (0.5 / np.sqrt(n)) # rough heuristic seeds.append((pts, radii)) # Add random seeds for _ in range(3): c = np.random.uniform(0.1, 0.9, (n, 2)) r = np.random.uniform(0.01, 0.05, n) seeds.append((c, r)) return seeds
def objective_function(params, n, penalty_weight): """ Objective: minimize -sum(radii) + penalty * violations params: [x1, y1, ... xn, yn, r1, ... rn] """ centers = params[:2*n].reshape((n, 2)) radii = params[2*n:] # Primary Objective: Maximize sum of radii obj = -np.sum(radii) # 1. Wall Violations # x - r >= 0 -> violation: max(0, r - x) # x + r <= 1 -> violation: max(0, x + r - 1) # y same... v_left = np.maximum(0, radii - centers[:, 0]) v_right = np.maximum(0, centers[:, 0] + radii - 1.0) v_bottom = np.maximum(0, radii - centers[:, 1]) v_top = np.maximum(0, centers[:, 1] + radii - 1.0) wall_penalty = np.sum(v_left**2 + v_right**2 + v_bottom**2 + v_top**2) # 2. Overlap Violations # dist(i,j) >= r_i + r_j # violation: max(0, r_i + r_j - dist) # Vectorized distance calculation # (N, 1, 2) - (1, N, 2) -> (N, N, 2) diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) # Avoid sqrt(0) on diagonal safe_dist_sq = dist_sq.copy() np.fill_diagonal(safe_dist_sq, 1.0) # dummy value dist = np.sqrt(safe_dist_sq) # Radii sum matrix r_sum = radii[:, np.newaxis] + radii[np.newaxis, :] # Overlap amount overlap = np.maximum(0, r_sum - dist) np.fill_diagonal(overlap, 0) # clear self-overlap # Since we sum over whole matrix, each pair is counted twice overlap_penalty = 0.5 * np.sum(overlap**2) return obj + penalty_weight * (wall_penalty + overlap_penalty)
def enforce_strict_validity(centers, radii): """ Scale radii to ensure all circles are strictly inside the square and disjoint. Uses a global scaling factor to preserve relative sizes. """ n = len(radii) # 1. Constraint: Walls # For each circle i: r_i * scale <= x_i, etc. # scale <= x_i / r_i max_scale = 1.0 for i in range(n): x, y = centers[i] r = radii[i] if r < 1e-9: continue # Distance to walls d_walls = min(x, y, 1.0 - x, 1.0 - y) if d_walls < r: max_scale = min(max_scale, d_walls / r) # 2. Constraint: Overlaps # For pair i, j: scale * (r_i + r_j) <= dist_ij # scale <= dist_ij / (r_i + r_j) # Vectorized check diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) # We only care about off-diagonal # Add infinity to diagonal to ignore it in min() np.fill_diagonal(dist_sq, np.inf) dist = np.sqrt(dist_sq) r_sum = radii[:, np.newaxis] + radii[np.newaxis, :] # Ratios # We want min(dist / r_sum) # Avoid divide by zero r_sum[r_sum < 1e-9] = 1e-9 ratios = dist / r_sum min_overlap_scale = np.min(ratios) max_scale = min(max_scale, min_overlap_scale) # Apply scale (with tiny epsilon safety margin) final_scale = max_scale * (1.0 - 1e-7) # If final_scale is effectively 1 (within tolerance), we keep it # If it's much smaller, we shrink. return centers, radii * final_scale
def compute_max_radii(centers): """ Legacy helper maintained for interface compatibility if needed, re-implemented to essentially perform the same validity check logic. """ n = len(centers) radii = np.zeros(n) # Initialize with distance to wall for i in range(n): radii[i] = min(centers[i,0], centers[i,1], 1-centers[i,0], 1-centers[i,1]) # Run the strict validity scaler on these max radii _, radii = enforce_strict_validity(centers, radii) return radii
# EVOLVE-BLOCK-END123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451--- a/original.py+++ b/original.py@@ -1,407 +1,434 @@ # EVOLVE-BLOCK-START """ hybrid_pop_optimizer Hybrid Pop Optimizer: Merges 'BottleneckPopOptimizer' (Pop-and-Reinsert Basin Hopping, Two-phase Optimization) with 'Hybrid Basin Hopping' (Diverse Initialization, Momentum-based Physics Pre-conditioning). Key innovation: Uses momentum-based physics to untangle complex initial topologies before feeding them into the rigorous Pop-Packing optimizer. """ import numpy as np from scipy.optimize import minimize, linprog class HybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42) # Grid for void finding self.grid_res = 60 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy]) + def _generate_staggered_patterns(self):+ """Generates all valid compositions of N into rows with |diff|<=1."""+ results = []+ def backtrack(current_rows, current_sum):+ if current_sum == self.n:+ results.append(list(current_rows))+ return++ if not current_rows:+ candidates = range(3, 10)+ else:+ last = current_rows[-1]+ candidates = [last-1, last, last+1]+ candidates = [c for c in candidates if 3 <= c <= 9]++ for c in candidates:+ if len(current_rows) < 8 and current_sum + c <= self.n:+ backtrack(current_rows + [c], current_sum + c)++ backtrack([], 0)+ # Add a few manual ones that might be skipped by strict rules (e.g. 2s)+ results.append([6, 6, 6, 6, 2])+ # Sort for consistency+ results.sort(key=lambda x: (len(x), tuple(x)))+ return results+ def get_initial_configs(self): """Generates diverse initial configurations from multiple strategies.""" configs = [] - # 1. Explicit Lattice Patterns (Merged List)- patterns = [- [5, 5, 6, 5, 5], # Symmetric hex- [6, 5, 6, 5, 4], # Staggered- [5, 6, 5, 5, 5], # Center heavy- [6, 7, 6, 7], # Two-block- [5, 5, 5, 5, 6], # Bottom heavy- [4, 5, 6, 6, 5], # Asymmetric- [6, 6, 6, 6, 2], # Box-like- [4, 6, 6, 6, 4], # Rounded- [3, 4, 5, 6, 5, 3] # Rounded small corners- ]+ # 1. Automated Staggered Lattice Patterns+ patterns = self._generate_staggered_patterns() dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers) if len(centers) > 0: # Normalize and center min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09 curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center) # Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill]) configs.append(('lattice', centers)) # 2. Spiral Packing configs.append(('spiral', self.init_spiral())) # 3. Generic Hex (from Hybrid) configs.append(('hex_generic', self.generate_generic_hex())) # 4. Boundary + Random (from Bottleneck) configs.append(('boundary', self.init_boundary())) # 5. Grid Compact (from Hybrid) configs.append(('grid_5x5', self.init_grid_compact())) # 6. Pure Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2))) return configs def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]] min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1 def init_boundary(self): boundary = [] x = np.linspace(0.1, 0.9, 6) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary) needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) return np.vstack([boundary, internal]) elif needed < 0: return boundary[:self.n] return boundary def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) # Center fill # Slight jitter c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c def run_physics_relaxation(self, centers, steps=100): """Momentum-based relaxation to separate circles.""" c = centers.copy() r_val = 0.05 velocities = np.zeros_like(c) dt = 0.01 for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq) target_dist = 2 * r_val overlaps = target_dist - dists forces = np.zeros_like(c) # Repulsion mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push # Walls k_wall = 80.0 forces[:, 0] += np.maximum(r_val - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r_val - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r_val - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r_val - (1 - c[:, 1]), 0) * k_wall # Integrate velocities = velocities * 0.6 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0) return c def find_largest_void(self, centers): """Grid search for point furthest from any center.""" diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dists_sq = np.min(dists_sq, axis=1) best_idx = np.argmax(min_dists_sq) return self.grid_pts[best_idx] def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n) bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b))) A_ub = [] b_ub = [] diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2)) for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j]) try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x return np.array([b[1] for b in bounds_list]) def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:] obj = -np.sum(r) if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2) w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2) diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq) r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2) return obj + mu * (w_pen + ov_pen) def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n) x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n current_x = x0 phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases] reg = 5.0 if equal_bias else 0.0 for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 iter_limit = 250 if mu > 5000 else 150 res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x return current_x[:2*n].reshape((n, 2)), current_x[2*n:] def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0) # 1. Global Search over Seeds for name, c_init in configs: # Physics Relaxation (Hybrid feature) c_relaxed = self.run_physics_relaxation(c_init) # Phase 1: Regularized (Bottleneck feature) c_p1, r_p1 = self.local_optimization(c_relaxed, equal_bias=True) # Phase 2: Variable (Bottleneck feature) c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False) r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp) if score > best_global[2]: best_global = (c_p2, r_lp, score) # 2. Basin Hopping with Pop (Bottleneck feature) curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2] best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score # Iterations n_iter = 25 temperature = 0.003 for i in range(n_iter): trial_c = curr_c.copy() # Pop vs Perturb is_pop = (self.rng.rand() < 0.35) if is_pop: # Find worst circle min_idx = np.argmin(curr_r) # Find hole relative to others others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask]) trial_c[min_idx] = target # Jitter trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0) - # Reset radius of moved circle so it can grow fresh+ # Smart Radius Reset+ others = trial_c[others_mask]+ dists = np.sqrt(np.sum((others - trial_c[min_idx])**2, axis=1))+ gaps = dists - curr_r[others_mask]++ p = trial_c[min_idx]+ wall_dist = min(p[0], 1-p[0], p[1], 1-p[1])++ # Initialize with safe estimate of available space+ new_r = min(np.min(gaps), wall_dist) * 0.95+ new_r = max(new_r, 0.02)+ trial_r_init = curr_r.copy()- trial_r_init[min_idx] = 0.05+ trial_r_init[min_idx] = new_r else: # Standard Shake mag = 0.03 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init = curr_r # Fast optimization c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0) # Evaluate r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new) # Accept? delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy() temperature *= 0.95 # 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-7} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c) return final_c, final_r def construct_packing(): opt = HybridPopOptimizer(n=26) return opt.optimize() def compute_max_radii(centers): opt = HybridPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers) # EVOLVE-BLOCK-END # This part remains fixed (not evolved) def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434# EVOLVE-BLOCK-START"""hybrid_pop_optimizerHybrid Pop Optimizer:Merges 'BottleneckPopOptimizer' (Pop-and-Reinsert Basin Hopping, Two-phase Optimization)with 'Hybrid Basin Hopping' (Diverse Initialization, Momentum-based Physics Pre-conditioning).Key innovation: Uses momentum-based physics to untangle complex initial topologies beforefeeding them into the rigorous Pop-Packing optimizer."""
import numpy as npfrom scipy.optimize import minimize, linprog
class HybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
# Grid for void finding self.grid_res = 60 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def _generate_staggered_patterns(self): """Generates all valid compositions of N into rows with |diff|<=1.""" results = [] def backtrack(current_rows, current_sum): if current_sum == self.n: results.append(list(current_rows)) return
if not current_rows: candidates = range(3, 10) else: last = current_rows[-1] candidates = [last-1, last, last+1] candidates = [c for c in candidates if 3 <= c <= 9]
for c in candidates: if len(current_rows) < 8 and current_sum + c <= self.n: backtrack(current_rows + [c], current_sum + c)
backtrack([], 0) # Add a few manual ones that might be skipped by strict rules (e.g. 2s) results.append([6, 6, 6, 6, 2]) # Sort for consistency results.sort(key=lambda x: (len(x), tuple(x))) return results
def get_initial_configs(self): """Generates diverse initial configurations from multiple strategies.""" configs = []
# 1. Automated Staggered Lattice Patterns patterns = self._generate_staggered_patterns()
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
if len(centers) > 0: # Normalize and center min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09
curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center)
# Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill])
configs.append(('lattice', centers))
# 2. Spiral Packing configs.append(('spiral', self.init_spiral()))
# 3. Generic Hex (from Hybrid) configs.append(('hex_generic', self.generate_generic_hex()))
# 4. Boundary + Random (from Bottleneck) configs.append(('boundary', self.init_boundary()))
# 5. Grid Compact (from Hybrid) configs.append(('grid_5x5', self.init_grid_compact()))
# 6. Pure Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2)))
return configs
def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c
def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]]
min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def init_boundary(self): boundary = [] x = np.linspace(0.1, 0.9, 6) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary)
needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) return np.vstack([boundary, internal]) elif needed < 0: return boundary[:self.n] return boundary
def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) # Center fill # Slight jitter c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c
def run_physics_relaxation(self, centers, steps=100): """Momentum-based relaxation to separate circles.""" c = centers.copy() r_val = 0.05 velocities = np.zeros_like(c) dt = 0.01
for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq)
target_dist = 2 * r_val overlaps = target_dist - dists
forces = np.zeros_like(c)
# Repulsion mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push
# Walls k_wall = 80.0 forces[:, 0] += np.maximum(r_val - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r_val - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r_val - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r_val - (1 - c[:, 1]), 0) * k_wall
# Integrate velocities = velocities * 0.6 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0)
return c
def find_largest_void(self, centers): """Grid search for point furthest from any center.""" diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dists_sq = np.min(dists_sq, axis=1) best_idx = np.argmax(min_dists_sq) return self.grid_pts[best_idx]
def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n)
bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
A_ub = [] b_ub = []
diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2))
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
return np.array([b[1] for b in bounds_list])
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0
phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 iter_limit = 250 if mu > 5000 else 150
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0)
# 1. Global Search over Seeds for name, c_init in configs: # Physics Relaxation (Hybrid feature) c_relaxed = self.run_physics_relaxation(c_init)
# Phase 1: Regularized (Bottleneck feature) c_p1, r_p1 = self.local_optimization(c_relaxed, equal_bias=True)
# Phase 2: Variable (Bottleneck feature) c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False)
r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp)
if score > best_global[2]: best_global = (c_p2, r_lp, score)
# 2. Basin Hopping with Pop (Bottleneck feature) curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
# Iterations n_iter = 25 temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy()
# Pop vs Perturb is_pop = (self.rng.rand() < 0.35)
if is_pop: # Find worst circle min_idx = np.argmin(curr_r) # Find hole relative to others others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask])
trial_c[min_idx] = target
# Jitter trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
# Smart Radius Reset others = trial_c[others_mask] dists = np.sqrt(np.sum((others - trial_c[min_idx])**2, axis=1)) gaps = dists - curr_r[others_mask]
p = trial_c[min_idx] wall_dist = min(p[0], 1-p[0], p[1], 1-p[1])
# Initialize with safe estimate of available space new_r = min(np.min(gaps), wall_dist) * 0.95 new_r = max(new_r, 0.02)
trial_r_init = curr_r.copy() trial_r_init[min_idx] = new_r else: # Standard Shake mag = 0.03 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init = curr_r
# Fast optimization c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)
# Evaluate r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new)
# Accept? delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy() temperature *= 0.95
# 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-7} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = HybridPopOptimizer(n=26) return opt.optimize()
def compute_max_radii(centers): opt = HybridPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers)# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407# EVOLVE-BLOCK-START"""hybrid_pop_optimizerHybrid Pop Optimizer:Merges 'BottleneckPopOptimizer' (Pop-and-Reinsert Basin Hopping, Two-phase Optimization)with 'Hybrid Basin Hopping' (Diverse Initialization, Momentum-based Physics Pre-conditioning).Key innovation: Uses momentum-based physics to untangle complex initial topologies beforefeeding them into the rigorous Pop-Packing optimizer."""
import numpy as npfrom scipy.optimize import minimize, linprog
class HybridPopOptimizer: def __init__(self, n=26): self.n = n self.rng = np.random.RandomState(42)
# Grid for void finding self.grid_res = 60 gx = np.linspace(0.01, 0.99, self.grid_res) gy = np.linspace(0.01, 0.99, self.grid_res) self.grid_pts = np.array([[x, y] for x in gx for y in gy])
def get_initial_configs(self): """Generates diverse initial configurations from multiple strategies.""" configs = []
# 1. Explicit Lattice Patterns (Merged List) patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Rounded small corners ]
dy = np.sqrt(3) / 2 for rows in patterns: centers = [] for i, count in enumerate(rows): y = i * dy for j in range(count): x = j - (count - 1) / 2.0 centers.append([x, y]) centers = np.array(centers)
if len(centers) > 0: # Normalize and center min_c = np.min(centers, axis=0) max_c = np.max(centers, axis=0) span = np.max(max_c - min_c) scale = 0.82 / span if span > 1e-9 else 1.0 centers = (centers - min_c) * scale + 0.09
curr_center = np.mean(centers, axis=0) centers += (0.5 - curr_center)
# Fix count if len(centers) > self.n: dists = np.sum((centers - 0.5)**2, axis=1) idx = np.argsort(dists) centers = centers[idx[:self.n]] elif len(centers) < self.n: needed = self.n - len(centers) fill = np.random.rand(needed, 2) * 0.8 + 0.1 centers = np.vstack([centers, fill])
configs.append(('lattice', centers))
# 2. Spiral Packing configs.append(('spiral', self.init_spiral()))
# 3. Generic Hex (from Hybrid) configs.append(('hex_generic', self.generate_generic_hex()))
# 4. Boundary + Random (from Bottleneck) configs.append(('boundary', self.init_boundary()))
# 5. Grid Compact (from Hybrid) configs.append(('grid_5x5', self.init_grid_compact()))
# 6. Pure Random configs.append(('random', 0.1 + 0.8 * self.rng.rand(self.n, 2)))
return configs
def init_spiral(self): indices = np.arange(self.n) golden_angle = np.pi * (3 - np.sqrt(5)) theta = indices * golden_angle r = np.sqrt(indices + 1) / np.sqrt(self.n) c = np.zeros((self.n, 2)) scale = 0.44 c[:, 0] = 0.5 + scale * r * np.cos(theta) c[:, 1] = 0.5 + scale * r * np.sin(theta) return c
def generate_generic_hex(self): v1 = np.array([1.0, 0.0]) v2 = np.array([0.5, np.sqrt(3)/2]) points = [] for i in range(-4, 5): for j in range(-4, 5): points.append(i * v1 + j * v2) points = np.array(points) points -= np.mean(points, axis=0) dists = np.sum(points**2, axis=1) points = points[np.argsort(dists)[:self.n]]
min_xy = np.min(points, axis=0) max_xy = np.max(points, axis=0) scale = 0.8 / np.max(max_xy - min_xy) return (points - min_xy) * scale + 0.1
def init_boundary(self): boundary = [] x = np.linspace(0.1, 0.9, 6) for xi in x: boundary.append([xi, 0.1]) boundary.append([xi, 0.9]) y = np.linspace(0.25, 0.75, 4) for yi in y: boundary.append([0.1, yi]) boundary.append([0.9, yi]) boundary = np.array(boundary)
needed = self.n - len(boundary) if needed > 0: internal = 0.2 + 0.6 * self.rng.rand(needed, 2) return np.vstack([boundary, internal]) elif needed < 0: return boundary[:self.n] return boundary
def init_grid_compact(self): x = np.linspace(0.15, 0.85, 5) y = np.linspace(0.15, 0.85, 5) xv, yv = np.meshgrid(x, y) c = np.zeros((self.n, 2)) c[:25, 0] = xv.flatten() c[:25, 1] = yv.flatten() c[25] = np.array([0.5, 0.5]) # Center fill # Slight jitter c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) return c
def run_physics_relaxation(self, centers, steps=100): """Momentum-based relaxation to separate circles.""" c = centers.copy() r_val = 0.05 velocities = np.zeros_like(c) dt = 0.01
for _ in range(steps): diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 1.0) dists = np.sqrt(dist_sq)
target_dist = 2 * r_val overlaps = target_dist - dists
forces = np.zeros_like(c)
# Repulsion mask = overlaps > 0 if np.any(mask): safe_dists = np.maximum(dists, 1e-6) dirs = diff / safe_dists[:, :, np.newaxis] f_mag = overlaps * 40.0 push = np.sum(dirs * np.maximum(f_mag, 0)[:, :, np.newaxis], axis=1) forces += push
# Walls k_wall = 80.0 forces[:, 0] += np.maximum(r_val - c[:, 0], 0) * k_wall forces[:, 0] -= np.maximum(r_val - (1 - c[:, 0]), 0) * k_wall forces[:, 1] += np.maximum(r_val - c[:, 1], 0) * k_wall forces[:, 1] -= np.maximum(r_val - (1 - c[:, 1]), 0) * k_wall
# Integrate velocities = velocities * 0.6 + forces * dt c += velocities * dt c = np.clip(c, 0.0, 1.0)
return c
def find_largest_void(self, centers): """Grid search for point furthest from any center.""" diff = self.grid_pts[:, np.newaxis, :] - centers[np.newaxis, :, :] dists_sq = np.sum(diff**2, axis=2) min_dists_sq = np.min(dists_sq, axis=1) best_idx = np.argmax(min_dists_sq) return self.grid_pts[best_idx]
def solve_lp_radii(self, centers): n = len(centers) c = -np.ones(n)
bounds_list = [] for i in range(n): x, y = centers[i] b = min(x, 1-x, y, 1-y) bounds_list.append((0, max(1e-9, b)))
A_ub = [] b_ub = []
diff = centers[:, np.newaxis, :] - centers[np.newaxis, :, :] dists = np.sqrt(np.sum(diff**2, axis=2))
for i in range(n): for j in range(i+1, n): row = np.zeros(n) row[i] = 1.0 row[j] = 1.0 A_ub.append(row) b_ub.append(dists[i, j])
try: res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='highs') if res.success: return res.x except: pass
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds_list, method='interior-point') if res.success: return res.x
return np.array([b[1] for b in bounds_list])
def _loss(self, params, n, mu, regularization=0.0): c = params[:2*n].reshape((n, 2)) r = params[2*n:]
obj = -np.sum(r)
if regularization > 0: mean_r = np.mean(r) obj += regularization * np.sum((r - mean_r)**2)
w_pen = np.sum(np.maximum(0, r - c[:, 0])**2 + np.maximum(0, r - (1 - c[:, 0]))**2 + np.maximum(0, r - c[:, 1])**2 + np.maximum(0, r - (1 - c[:, 1]))**2)
diff = c[:, np.newaxis, :] - c[np.newaxis, :, :] dist_sq = np.sum(diff**2, axis=2) np.fill_diagonal(dist_sq, 10.0) dists = np.sqrt(dist_sq)
r_sum = r[:, np.newaxis] + r[np.newaxis, :] mask = np.triu(np.ones((n, n), dtype=bool), k=1) ov_pen = np.sum(np.maximum(0, r_sum - dists)[mask]**2)
return obj + mu * (w_pen + ov_pen)
def local_optimization(self, centers, radii_init=None, stiffness_scale=1.0, equal_bias=False): n = self.n if radii_init is None: radii_init = 0.05 * np.ones(n)
x0 = np.concatenate([centers.flatten(), radii_init]) bounds = [(0.0, 1.0)] * (2*n) + [(1e-6, 0.6)] * n
current_x = x0
phases = [10.0, 100.0, 1000.0, 10000.0, 100000.0] phases = [p * stiffness_scale for p in phases]
reg = 5.0 if equal_bias else 0.0
for i, mu in enumerate(phases): current_reg = reg / (5**i) if equal_bias else 0.0 iter_limit = 250 if mu > 5000 else 150
res = minimize( self._loss, current_x, args=(n, mu, current_reg), method='L-BFGS-B', bounds=bounds, options={'maxiter': iter_limit, 'ftol': 1e-5} ) current_x = res.x
return current_x[:2*n].reshape((n, 2)), current_x[2*n:]
def optimize(self): configs = self.get_initial_configs() best_global = (None, None, -1.0)
# 1. Global Search over Seeds for name, c_init in configs: # Physics Relaxation (Hybrid feature) c_relaxed = self.run_physics_relaxation(c_init)
# Phase 1: Regularized (Bottleneck feature) c_p1, r_p1 = self.local_optimization(c_relaxed, equal_bias=True)
# Phase 2: Variable (Bottleneck feature) c_p2, _ = self.local_optimization(c_p1, radii_init=r_p1, equal_bias=False)
r_lp = self.solve_lp_radii(c_p2) score = np.sum(r_lp)
if score > best_global[2]: best_global = (c_p2, r_lp, score)
# 2. Basin Hopping with Pop (Bottleneck feature) curr_c = best_global[0] curr_r = best_global[1] curr_score = best_global[2]
best_c = curr_c.copy() best_r = curr_r.copy() best_score = curr_score
# Iterations n_iter = 25 temperature = 0.003
for i in range(n_iter): trial_c = curr_c.copy()
# Pop vs Perturb is_pop = (self.rng.rand() < 0.35)
if is_pop: # Find worst circle min_idx = np.argmin(curr_r) # Find hole relative to others others_mask = np.ones(self.n, dtype=bool) others_mask[min_idx] = False target = self.find_largest_void(curr_c[others_mask])
trial_c[min_idx] = target
# Jitter trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
# Reset radius of moved circle so it can grow fresh trial_r_init = curr_r.copy() trial_r_init[min_idx] = 0.05 else: # Standard Shake mag = 0.03 * np.exp(-i/(n_iter*0.8)) trial_c += mag * self.rng.randn(self.n, 2) trial_c = np.clip(trial_c, 0.0, 1.0) trial_r_init = curr_r
# Fast optimization c_new, r_soft = self.local_optimization(trial_c, radii_init=trial_r_init, stiffness_scale=2.0)
# Evaluate r_new = self.solve_lp_radii(c_new) s_new = np.sum(r_new)
# Accept? delta = s_new - curr_score if delta > 0 or (self.rng.rand() < np.exp(delta/temperature)): curr_c, curr_r, curr_score = c_new, r_new, s_new if s_new > best_score: best_score = s_new best_c = c_new.copy() best_r = r_new.copy() temperature *= 0.95
# 3. Final Polish x0 = np.concatenate([best_c.flatten(), best_r]) bounds = [(0.0, 1.0)] * (2*self.n) + [(1e-6, 0.6)] * self.n
res = minimize( self._loss, x0, args=(self.n, 100000.0, 0.0), method='L-BFGS-B', bounds=bounds, options={'maxiter': 500, 'ftol': 1e-7} ) final_c = res.x[:2*self.n].reshape((self.n, 2)) final_r = self.solve_lp_radii(final_c)
return final_c, final_r
def construct_packing(): opt = HybridPopOptimizer(n=26) return opt.optimize()
def compute_max_radii(centers): opt = HybridPopOptimizer(n=len(centers)) return opt.solve_lp_radii(centers)# EVOLVE-BLOCK-END
# This part remains fixed (not evolved)def run_packing(): """Run the circle packing constructor for n=26""" centers, radii = construct_packing() # Calculate the sum of radii sum_radii = np.sum(radii) return centers, radii, sum_radii123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182import numpy as npimport osimport jsonfrom typing import Dict, Anyimport glob
def evaluate_aux(results_dir: str, primary_result: Dict[str, Any] | None = None) -> Dict[str, Any]: """ Evaluates auxiliary metrics for the circle packing problem. """ metrics = { "aux_normalized_min_radius": 0.0, "aux_radius_variance_from_mean": 0.0, "aux_num_contact_points": 0.0, "aux_bottleneck_circle_ratio": 0.0, "aux_total_overlap_distance": 0.0, "aux_min_wall_distance": 0.0, "aux_num_timeout_generations_recent": 0.0, "aux_avg_execution_time_successful": 0.0, "aux_num_valid_runs_in_primary_result": 0.0, "aux_center_of_mass_deviation": 0.0, }
# --- Calculate aux_num_timeout_generations_recent and aux_avg_execution_time_successful --- try: timeout_count = 0 successful_execution_times = [] num_generations_to_check = 10
current_gen_path_segment = os.path.basename(os.path.dirname(results_dir)) current_gen_num = int(current_gen_path_segment.split('_')[-1]) if current_gen_path_segment.startswith('gen_') else 0
parent_results_base_dir = os.path.dirname(os.path.dirname(os.path.dirname(results_dir)))
for i in range(max(0, current_gen_num - num_generations_to_check), current_gen_num + 1): gen_path = os.path.join(parent_results_base_dir, f"gen_{i}", "results", "metrics.json") if os.path.exists(gen_path): try: with open(gen_path, 'r') as f: gen_metrics = json.load(f) if gen_metrics.get('combined_score', 0.0) == 0.0 and \ 'timeout' in gen_metrics.get('primary', {}).get('validation_error', '').lower(): timeout_count += 1 elif gen_metrics.get('primary', {}).get('num_valid_runs', 0) > 0: exec_time = gen_metrics.get('primary', {}).get('execution_time_mean') if exec_time is not None and exec_time > 0: successful_execution_times.append(exec_time) except (FileNotFoundError, json.JSONDecodeError): pass
metrics["aux_num_timeout_generations_recent"] = float(timeout_count) if successful_execution_times: metrics["aux_avg_execution_time_successful"] = float(np.mean(successful_execution_times)) else: metrics["aux_avg_execution_time_successful"] = 0.0 except Exception as e: print(f"Error calculating historical metrics: {e}")
# --- aux_num_valid_runs_in_primary_result --- try: if primary_result and primary_result.get('primary', {}).get('num_valid_runs') is not None: metrics["aux_num_valid_runs_in_primary_result"] = float(primary_result['primary']['num_valid_runs']) except Exception as e: print(f"Error calculating aux_num_valid_runs_in_primary_result: {e}")
# Process geometric metrics from extra.npz extra_data_path = os.path.join(results_dir, "extra.npz") centers = None radii = None valid_radii = None valid_centers = None num_valid_circles = 0
try: if os.path.exists(extra_data_path): data = np.load(extra_data_path) centers = data["centers"] radii = data["radii"]
valid_radii_mask = radii >= 1e-7 valid_radii = radii[valid_radii_mask] valid_centers = centers[valid_radii_mask] num_valid_circles = len(valid_radii) else: print(f"Warning: {extra_data_path} not found. Geometric metrics will be 0.0.") except Exception as e: print(f"Error loading or processing extra.npz: {e}")
if num_valid_circles > 0: # aux_center_of_mass_deviation (Structural Sensitivity) try: com = np.mean(centers, axis=0) deviation = np.linalg.norm(com - np.array([0.5, 0.5])) metrics["aux_center_of_mass_deviation"] = deviation except Exception as e: print(f"Error calculating aux_center_of_mass_deviation: {e}")
# aux_normalized_min_radius (Component Contribution) try: min_radius = np.min(valid_radii) avg_radius = np.mean(valid_radii) if avg_radius > 1e-7: metrics["aux_normalized_min_radius"] = min_radius / avg_radius else: metrics["aux_normalized_min_radius"] = 0.0 except Exception as e: print(f"Error calculating aux_normalized_min_radius: {e}")
# aux_radius_variance_from_mean (Structural Sensitivity) try: metrics["aux_radius_variance_from_mean"] = float(np.var(valid_radii)) except Exception as e: print(f"Error calculating aux_radius_variance_from_mean: {e}")
# aux_bottleneck_circle_ratio (Component Contribution / Structural Sensitivity) try: if num_valid_circles > 1: min_r = np.min(valid_radii) max_r = np.max(valid_radii) if max_r > 1e-7: metrics["aux_bottleneck_circle_ratio"] = min_r / max_r else: metrics["aux_bottleneck_circle_ratio"] = 0.0 elif num_valid_circles == 1: metrics["aux_bottleneck_circle_ratio"] = 1.0 else: metrics["aux_bottleneck_circle_ratio"] = 0.0 except Exception as e: print(f"Error calculating aux_bottleneck_circle_ratio: {e}")
# aux_total_overlap_distance (Constraint Tension) try: total_overlap_distance = 0.0 for i in range(num_valid_circles): for j in range(i + 1, num_valid_circles): dist_centers = np.linalg.norm(valid_centers[i] - valid_centers[j]) sum_radii = valid_radii[i] + valid_radii[j] if dist_centers < sum_radii: total_overlap_distance += (sum_radii - dist_centers) metrics["aux_total_overlap_distance"] = total_overlap_distance except Exception as e: print(f"Error calculating aux_total_overlap_distance: {e}")
# aux_min_wall_distance (Constraint Tension) try: min_wall_dist = float('inf') for i in range(num_valid_circles): x, y = valid_centers[i] r = valid_radii[i] min_wall_dist = min(min_wall_dist, x - r) min_wall_dist = min(min_wall_dist, 1.0 - x - r) min_wall_dist = min(min_wall_dist, y - r) min_wall_dist = min(min_wall_dist, 1.0 - y - r) metrics["aux_min_wall_distance"] = min_wall_dist except Exception as e: print(f"Error calculating aux_min_wall_distance: {e}") metrics["aux_min_wall_distance"] = 0.0
# aux_num_contact_points (Constraint Tension) try: contact_epsilon = 1e-6 num_contacts = 0
for i in range(num_valid_circles): x, y = valid_centers[i] r = valid_radii[i] if abs(x - r) < contact_epsilon: num_contacts += 1 if abs(1.0 - x - r) < contact_epsilon: num_contacts += 1 if abs(y - r) < contact_epsilon: num_contacts += 1 if abs(1.0 - y - r) < contact_epsilon: num_contacts += 1
for i in range(num_valid_circles): for j in range(i + 1, num_valid_circles): dist_centers = np.linalg.norm(valid_centers[i] - valid_centers[j]) sum_radii = valid_radii[i] + valid_radii[j] if abs(dist_centers - sum_radii) < contact_epsilon: num_contacts += 1 metrics["aux_num_contact_points"] = float(num_contacts) except Exception as e: print(f"Error calculating aux_num_contact_points: {e}")
return metrics123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100<NAME>automated_lattice_and_smart_pop</NAME>
<DESCRIPTION>1. Replaces the hardcoded list of lattice patterns with an automated generator `_generate_staggered_patterns` that produces all valid compositions of N=26 into rows with dense packing constraints (adjacent row length difference <= 1). This ensures the global optimum's topology is not missed.2. Enhances the "Pop" heuristic in the Basin Hopping phase by initializing the relocated circle's radius based on the actual available space (distance to neighbors and walls) rather than a fixed value. This gives the local optimizer a better starting point (Newton-like step) for the variable-radius phase.</DESCRIPTION>
<DIFF><<<<<<< SEARCH def get_initial_configs(self): """Generates diverse initial configurations from multiple strategies.""" configs = []
# 1. Explicit Lattice Patterns (Merged List) patterns = [ [5, 5, 6, 5, 5], # Symmetric hex [6, 5, 6, 5, 4], # Staggered [5, 6, 5, 5, 5], # Center heavy [6, 7, 6, 7], # Two-block [5, 5, 5, 5, 6], # Bottom heavy [4, 5, 6, 6, 5], # Asymmetric [6, 6, 6, 6, 2], # Box-like [4, 6, 6, 6, 4], # Rounded [3, 4, 5, 6, 5, 3] # Rounded small corners ]
dy = np.sqrt(3) / 2 for rows in patterns:======= def _generate_staggered_patterns(self): """Generates all valid compositions of N into rows with |diff|<=1.""" results = [] def backtrack(current_rows, current_sum): if current_sum == self.n: results.append(list(current_rows)) return
if not current_rows: candidates = range(3, 10) else: last = current_rows[-1] candidates = [last-1, last, last+1] candidates = [c for c in candidates if 3 <= c <= 9]
for c in candidates: if len(current_rows) < 8 and current_sum + c <= self.n: backtrack(current_rows + [c], current_sum + c)
backtrack([], 0) # Add a few manual ones that might be skipped by strict rules (e.g. 2s) results.append([6, 6, 6, 6, 2]) # Sort for consistency results.sort(key=lambda x: (len(x), tuple(x))) return results
def get_initial_configs(self): """Generates diverse initial configurations from multiple strategies.""" configs = []
# 1. Automated Staggered Lattice Patterns patterns = self._generate_staggered_patterns()
dy = np.sqrt(3) / 2 for rows in patterns:>>>>>>> REPLACE<<<<<<< SEARCH trial_c[min_idx] = target
# Jitter trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
# Reset radius of moved circle so it can grow fresh trial_r_init = curr_r.copy() trial_r_init[min_idx] = 0.05======= trial_c[min_idx] = target
# Jitter trial_c += 0.01 * (self.rng.rand(self.n, 2) - 0.5) trial_c = np.clip(trial_c, 0.0, 1.0)
# Smart Radius Reset others = trial_c[others_mask] dists = np.sqrt(np.sum((others - trial_c[min_idx])**2, axis=1)) gaps = dists - curr_r[others_mask]
p = trial_c[min_idx] wall_dist = min(p[0], 1-p[0], p[1], 1-p[1])
# Initialize with safe estimate of available space new_r = min(np.min(gaps), wall_dist) * 0.95 new_r = max(new_r, 0.02)
trial_r_init = curr_r.copy() trial_r_init[min_idx] = new_r>>>>>>> REPLACE</DIFF>tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/__pycache__/main.cpython-313.pycAdded
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/edit.diffAdded+510
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/llm_trajectories/shinka__native-gemini-3-pro-preview-g155-n1-r1-p1-1772468668.526-0c525125.jsonAdded
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/main.pyAdded+465
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/original.pyAdded+424
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/results/auxiliary_metrics_snapshot.pyAdded+163
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/results/correct.jsonAdded+4
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/results/metrics.jsonAdded+52
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/best/rewrite.txtAdded+456
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_0/main.pyAdded+94
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_1/edit.diffAdded+280
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_1/main.pyAdded+210
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_1/original.pyAdded+94
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_1/rewrite.txtAdded+201
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/__pycache__/main.cpython-313.pycAdded
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/edit.diffAdded+424
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/llm_trajectories/shinka__native-gemini-3-pro-preview-g10-n1-r1-p1-1772442494.013-168057e8.jsonAdded+69
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/main.pyAdded+323
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/original.pyAdded+305
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/results/auxiliary_metrics_snapshot.pyAdded+73
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/results/correct.jsonAdded+4
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/results/metrics.jsonAdded+40
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_10/rewrite.txtAdded+314
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_100/edit.diffAdded+473
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_100/main.pyAdded+440
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_100/original.pyAdded+398
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_100/rewrite.txtAdded+431
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_101/edit.diffAdded+572
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_101/main.pyAdded+380
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_101/original.pyAdded+469
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_101/search_replace.txtAdded+812
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/__pycache__/main.cpython-313.pycAdded
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/edit.diffAdded+738
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/llm_trajectories/shinka__native-gemini-3-pro-preview-g102-n1-r1-p1-1772458212.719-d820934f.jsonAdded
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/main.pyAdded+390
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/original.pyAdded+469
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/results/auxiliary_metrics_snapshot.pyAdded+182
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/results/correct.jsonAdded+4
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/results/metrics.jsonAdded+52
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_102/rewrite.txtAdded+381
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_103/edit.diffAdded+365
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_103/main.pyAdded+292
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_103/original.pyAdded+94
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_103/rewrite.txtAdded+283
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/edit.diffAdded+451
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/llm_trajectories/shinka__native-gemini-3-pro-preview-g104-n1-r1-p1-1772458635.700-5d5a0a79.jsonAdded
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/main.pyAdded+434
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/original.pyAdded+407
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/results/auxiliary_metrics_snapshot.pyAdded+182
tasks/circle_packing/results/results_circle_packing_v3_g200_periodic5_20260302_084441/gen_104/search_replace.txtAdded+100