"""Reinsert several points by clipping away the forbidden strips.""" from itertools import combinations import numpy as np from search import N, TRIPLES, neighbor, signed_area SQUARE = ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)) TRIPLE_INDICES = np.array(TRIPLES) CANDIDATE_MASKS = [ np.array([sum(1 << node for node in members) for members in combinations(range(N), size)]) for size in range(3, N + 1) ] def minimum_cover(triples, rng): """Choose a smallest set of at least three points meeting every triple.""" edges = np.bitwise_or.reduce(1 << triples, axis=1) for masks in CANDIDATE_MASKS: valid = masks[np.all((masks[:, None] & edges) != 0, axis=1)] if len(valid): mask = int(rng.choice(valid)) return rng.permutation([i for i in range(N) if mask & (1 << i)]) raise ValueError("no cover of the tight triangles") def pair_lines(points): lines = [] for (ax, ay), (bx, by) in combinations(points, 2): nx, ny = (ay - by) / 2, (bx - ax) / 2 lines.append((nx, ny, nx * ax + ny * ay)) return sorted(lines, key=lambda line: line[0] ** 2 + line[1] ** 2) def clip_half_plane(vertices, distances): """Clip a convex polygon using signed distances to the clipping line.""" output = [] previous = vertices[-1] old_distance = distances[-1] for point, distance in zip(vertices, distances): if (old_distance >= 0) != (distance >= 0): scale = old_distance / (old_distance - distance) output.append(tuple(a + scale * (b - a) for a, b in zip(previous, point))) if distance >= 0: output.append(point) previous, old_distance = point, distance return output def feasible_cells(lines, target): """Return cells of the square where every fixed-pair area is at least target.""" cells = [SQUARE] for nx, ny, offset in lines: kept = [] for vertices in cells: values = [nx * x + ny * y - offset for x, y in vertices] high, low = max(values), min(values) if low >= target or high <= -target: kept.append(vertices) continue if high > target: kept.append(clip_half_plane(vertices, [value - target for value in values])) if low < -target: kept.append(clip_half_plane(vertices, [-value - target for value in values])) if not kept: return [] cells = kept return cells def insertion(fixed, previous, quality, rng, ratios): lines = pair_lines(fixed.tolist()) nx, ny, offsets = np.array(lines).T for ratio in ratios: target = max(0.003, ratio * quality) cells = feasible_cells(lines, target) centers = np.array([np.mean(cell, axis=0) for cell in cells]) if not len(centers): continue distances = np.linalg.norm(centers[:, None, :] - previous, axis=2).min(axis=1) far_enough = distances > 0.035 if far_enough.any(): centers = centers[far_enough] elif ratio != ratios[-1]: continue areas = np.abs(centers[:, 0, None] * nx + centers[:, 1, None] * ny - offsets) best = np.argsort(areas.min(axis=1))[-5:] return centers[rng.choice(best)] return None def strip_neighbor(points, rng, step): # Interleave the cheap single-point and Gaussian moves as a control. if step % 3 == 0 and step % 13 != 0: return neighbor(points, rng, step) areas = np.abs(signed_area(points)) quality = areas.min() tight = TRIPLE_INDICES[areas <= quality + 0.0008] weights = 1 + np.bincount(tight.ravel(), minlength=N) probabilities = weights / weights.sum() if step % 2 else None cover_move = step % 13 == 0 if cover_move: removed = minimum_cover(TRIPLE_INDICES[areas <= quality + 1e-8], rng) else: count = 3 if step % 5 == 0 else 2 removed = rng.choice(N, size=count, replace=False, p=probabilities) fixed = np.delete(points, removed, axis=0) new = points.copy() ratios = (0.93, 0.78, 0.62, 0.48, 0.33) if cover_move else (0.93, 0.78, 0.62) for index in removed: candidate = insertion(fixed, points[removed], quality, rng, ratios) if candidate is None: return neighbor(points, rng, step) new[index] = candidate fixed = np.vstack((fixed, candidate)) return np.clip(new, 0, 1)