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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Hierarchical Shape Generator - Two-Tier Gate Version
|
| 3 |
+
======================================================
|
| 4 |
+
Generates grids only. Patch analysis split into:
|
| 5 |
+
- Local properties: intrinsic to each patch's voxels (no cross-patch info)
|
| 6 |
+
- Structural properties: relational, require neighborhood context
|
| 7 |
+
|
| 8 |
+
Colab Cell 1 of 3 - runs first, populates shared namespace.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from typing import Dict, Optional
|
| 13 |
+
from itertools import combinations
|
| 14 |
+
|
| 15 |
+
# === Grid Constants ===========================================================
|
| 16 |
+
GZ, GY, GX = 8, 16, 16
|
| 17 |
+
GRID_SHAPE = (GZ, GY, GX)
|
| 18 |
+
GRID_VOLUME = GZ * GY * GX
|
| 19 |
+
|
| 20 |
+
PATCH_Z, PATCH_Y, PATCH_X = 2, 4, 4
|
| 21 |
+
PATCH_VOL = PATCH_Z * PATCH_Y * PATCH_X
|
| 22 |
+
MACRO_Z, MACRO_Y, MACRO_X = GZ // PATCH_Z, GY // PATCH_Y, GX // PATCH_X
|
| 23 |
+
MACRO_N = MACRO_Z * MACRO_Y * MACRO_X
|
| 24 |
+
|
| 25 |
+
# Worker budget (A100 Colab limit)
|
| 26 |
+
MAX_WORKERS = 10
|
| 27 |
+
|
| 28 |
+
_COORDS = np.mgrid[0:GZ, 0:GY, 0:GX].reshape(3, -1).T.astype(np.float64)
|
| 29 |
+
|
| 30 |
+
# === Classes ==================================================================
|
| 31 |
+
CLASS_NAMES = [
|
| 32 |
+
"point", "line", "corner", "cross", "arc", "helix", "circle",
|
| 33 |
+
"triangle", "quad", "plane", "disc",
|
| 34 |
+
"tetrahedron", "cube", "pyramid", "prism", "octahedron", "pentachoron", "wedge",
|
| 35 |
+
"sphere", "hemisphere", "torus", "bowl", "saddle", "capsule", "cylinder", "cone", "channel"
|
| 36 |
+
]
|
| 37 |
+
NUM_CLASSES = len(CLASS_NAMES)
|
| 38 |
+
CLASS_TO_IDX = {n: i for i, n in enumerate(CLASS_NAMES)}
|
| 39 |
+
|
| 40 |
+
# === Two-Tier Gate Constants ==================================================
|
| 41 |
+
|
| 42 |
+
# Local gates: intrinsic to each patch, no cross-patch info needed
|
| 43 |
+
# dims: 4 classes (0D point, 1D line, 2D surface, 3D volume)
|
| 44 |
+
# curvature: 3 classes (rigid, curved, combined)
|
| 45 |
+
# boundary: 1 binary (partial fill = surface patch)
|
| 46 |
+
# axis_active: 3 binary (which axes have extent > 1 voxel)
|
| 47 |
+
NUM_LOCAL_DIMS = 4
|
| 48 |
+
NUM_LOCAL_CURVS = 3
|
| 49 |
+
NUM_LOCAL_BOUNDARY = 1
|
| 50 |
+
NUM_LOCAL_AXES = 3
|
| 51 |
+
LOCAL_GATE_DIM = NUM_LOCAL_DIMS + NUM_LOCAL_CURVS + NUM_LOCAL_BOUNDARY + NUM_LOCAL_AXES # 11
|
| 52 |
+
|
| 53 |
+
# Structural gates: relational, require neighborhood context (post-attention)
|
| 54 |
+
# topology: 2 classes (open / closed based on neighbor count)
|
| 55 |
+
# neighbor_ct: 1 continuous (normalized 0-1, raw count / 6)
|
| 56 |
+
# surface_role: 3 classes (isolated 0-1 neighbors, boundary 2-4, interior 5-6)
|
| 57 |
+
NUM_STRUCT_TOPO = 2
|
| 58 |
+
NUM_STRUCT_NEIGHBOR = 1
|
| 59 |
+
NUM_STRUCT_ROLE = 3
|
| 60 |
+
STRUCTURAL_GATE_DIM = NUM_STRUCT_TOPO + NUM_STRUCT_NEIGHBOR + NUM_STRUCT_ROLE # 6
|
| 61 |
+
|
| 62 |
+
TOTAL_GATE_DIM = LOCAL_GATE_DIM + STRUCTURAL_GATE_DIM # 17
|
| 63 |
+
|
| 64 |
+
# Legacy compat
|
| 65 |
+
GATES = ["rigid", "curved", "combined", "open", "closed"]
|
| 66 |
+
NUM_GATES = len(GATES)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# === Rasterization ============================================================
|
| 70 |
+
def rasterize_line(p1, p2):
|
| 71 |
+
p1, p2 = np.array(p1, dtype=float), np.array(p2, dtype=float)
|
| 72 |
+
n = max(int(np.max(np.abs(p2 - p1))) + 1, 2)
|
| 73 |
+
t = np.linspace(0, 1, n)[:, None]
|
| 74 |
+
pts = np.round(p1 + t * (p2 - p1)).astype(int)
|
| 75 |
+
return np.clip(pts, [0, 0, 0], [GZ-1, GY-1, GX-1])
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def rasterize_edges(verts, edges):
|
| 79 |
+
pts = []
|
| 80 |
+
for i, j in edges:
|
| 81 |
+
pts.append(rasterize_line(verts[i], verts[j]))
|
| 82 |
+
return np.concatenate(pts)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def rasterize_faces(verts, faces, density=1.0):
|
| 86 |
+
pts = []
|
| 87 |
+
for f in faces:
|
| 88 |
+
v0, v1, v2 = [np.array(verts[i], dtype=float) for i in f[:3]]
|
| 89 |
+
e1, e2 = v1 - v0, v2 - v0
|
| 90 |
+
n = max(int(max(np.linalg.norm(e1), np.linalg.norm(e2)) * density) + 1, 3)
|
| 91 |
+
for u in np.linspace(0, 1, n):
|
| 92 |
+
for v in np.linspace(0, 1 - u, max(int(n * (1 - u)), 1)):
|
| 93 |
+
p = np.round(v0 + u * e1 + v * e2).astype(int)
|
| 94 |
+
pts.append(p)
|
| 95 |
+
return np.clip(np.array(pts), [0, 0, 0], [GZ-1, GY-1, GX-1])
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def rasterize_sphere(c, r, fill=True, half=False, zmin=None, zmax=None):
|
| 99 |
+
c = np.array(c, dtype=float)
|
| 100 |
+
pts = []
|
| 101 |
+
zr = range(max(0, int(c[0] - r)), min(GZ, int(c[0] + r) + 1))
|
| 102 |
+
for z in zr:
|
| 103 |
+
for y in range(max(0, int(c[1] - r)), min(GY, int(c[1] + r) + 1)):
|
| 104 |
+
for x in range(max(0, int(c[2] - r)), min(GX, int(c[2] + r) + 1)):
|
| 105 |
+
d = np.sqrt((z - c[0])**2 + (y - c[1])**2 + (x - c[2])**2)
|
| 106 |
+
if fill and d <= r:
|
| 107 |
+
if zmin is not None and z < zmin: continue
|
| 108 |
+
if zmax is not None and z > zmax: continue
|
| 109 |
+
pts.append([z, y, x])
|
| 110 |
+
elif not fill and abs(d - r) < 0.8:
|
| 111 |
+
if half and z < c[0]: continue
|
| 112 |
+
pts.append([z, y, x])
|
| 113 |
+
return np.array(pts) if pts else np.zeros((0, 3), dtype=int)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# === Shape Generators =========================================================
|
| 117 |
+
class HierarchicalShapeGenerator:
|
| 118 |
+
def __init__(self, seed=42):
|
| 119 |
+
self.rng = np.random.RandomState(seed)
|
| 120 |
+
|
| 121 |
+
def _random_center(self, margin=3):
|
| 122 |
+
return [self.rng.randint(max(1, margin//2), max(2, GZ - margin//2)),
|
| 123 |
+
self.rng.randint(margin, GY - margin),
|
| 124 |
+
self.rng.randint(margin, GX - margin)]
|
| 125 |
+
|
| 126 |
+
def _to_grid(self, pts):
|
| 127 |
+
if len(pts) == 0: return None, None
|
| 128 |
+
grid = np.zeros(GRID_SHAPE, dtype=np.float32)
|
| 129 |
+
pts = np.clip(np.array(pts).astype(int), [0, 0, 0], [GZ-1, GY-1, GX-1])
|
| 130 |
+
grid[pts[:, 0], pts[:, 1], pts[:, 2]] = 1.0
|
| 131 |
+
return grid, pts
|
| 132 |
+
|
| 133 |
+
def generate(self, name):
|
| 134 |
+
r = self.rng
|
| 135 |
+
c = self._random_center()
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
if name == "point":
|
| 139 |
+
pts = [c]
|
| 140 |
+
elif name == "line":
|
| 141 |
+
axis = r.randint(0, 3)
|
| 142 |
+
p1, p2 = list(c), list(c)
|
| 143 |
+
L = r.randint(4, [GZ, GY, GX][axis])
|
| 144 |
+
p1[axis] = max(0, c[axis] - L//2)
|
| 145 |
+
p2[axis] = min([GZ, GY, GX][axis] - 1, c[axis] + L//2)
|
| 146 |
+
pts = rasterize_line(p1, p2)
|
| 147 |
+
elif name == "corner":
|
| 148 |
+
L = r.randint(3, 7)
|
| 149 |
+
p1, p2 = list(c), list(c)
|
| 150 |
+
p1[1] = max(0, c[1] - L)
|
| 151 |
+
p2[2] = min(GX - 1, c[2] + L)
|
| 152 |
+
pts = np.concatenate([rasterize_line(c, p1), rasterize_line(c, p2)])
|
| 153 |
+
elif name == "cross":
|
| 154 |
+
L = r.randint(2, 5)
|
| 155 |
+
pts = []
|
| 156 |
+
for d in range(3):
|
| 157 |
+
p1, p2 = list(c), list(c)
|
| 158 |
+
p1[d] = max(0, c[d] - L)
|
| 159 |
+
p2[d] = min([GZ, GY, GX][d] - 1, c[d] + L)
|
| 160 |
+
pts.append(rasterize_line(p1, p2))
|
| 161 |
+
pts = np.concatenate(pts)
|
| 162 |
+
elif name == "arc":
|
| 163 |
+
R = r.uniform(2, 5)
|
| 164 |
+
t = np.linspace(0, np.pi * r.uniform(0.4, 0.9), 30)
|
| 165 |
+
pts = np.round(np.column_stack([c[0] + np.zeros_like(t), c[1] + R*np.cos(t), c[2] + R*np.sin(t)])).astype(int)
|
| 166 |
+
elif name == "helix":
|
| 167 |
+
R, H = r.uniform(2, 4), r.uniform(3, GZ - 2)
|
| 168 |
+
t = np.linspace(0, 4*np.pi, 60)
|
| 169 |
+
pts = np.round(np.column_stack([c[0] - H/2 + t/(4*np.pi)*H, c[1] + R*np.cos(t), c[2] + R*np.sin(t)])).astype(int)
|
| 170 |
+
elif name == "circle":
|
| 171 |
+
R = r.uniform(2, 5)
|
| 172 |
+
t = np.linspace(0, 2*np.pi, 40)
|
| 173 |
+
pts = np.round(np.column_stack([np.full_like(t, c[0]), c[1] + R*np.cos(t), c[2] + R*np.sin(t)])).astype(int)
|
| 174 |
+
elif name == "triangle":
|
| 175 |
+
s = r.uniform(3, 6)
|
| 176 |
+
v = [[c[0], c[1] - s, c[2]], [c[0], c[1] + s//2, c[2] - s], [c[0], c[1] + s//2, c[2] + s]]
|
| 177 |
+
pts = rasterize_edges(v, [(0,1),(1,2),(2,0)])
|
| 178 |
+
elif name == "quad":
|
| 179 |
+
s = r.randint(2, 5)
|
| 180 |
+
v = [[c[0], c[1]-s, c[2]-s], [c[0], c[1]-s, c[2]+s], [c[0], c[1]+s, c[2]+s], [c[0], c[1]+s, c[2]-s]]
|
| 181 |
+
pts = rasterize_edges(v, [(0,1),(1,2),(2,3),(3,0)])
|
| 182 |
+
elif name == "plane":
|
| 183 |
+
s = r.randint(2, 5)
|
| 184 |
+
pts = rasterize_faces([[c[0],c[1]-s,c[2]-s],[c[0],c[1]-s,c[2]+s],[c[0],c[1]+s,c[2]+s],[c[0],c[1]+s,c[2]-s]], [(0,1,2),(0,2,3)])
|
| 185 |
+
elif name == "disc":
|
| 186 |
+
R = r.uniform(2, 5)
|
| 187 |
+
pts = rasterize_sphere(c, R, fill=True)
|
| 188 |
+
pts = pts[pts[:, 0] == c[0]] if len(pts) > 0 else pts
|
| 189 |
+
elif name == "tetrahedron":
|
| 190 |
+
s = r.uniform(3, 5)
|
| 191 |
+
v = [[c[0]+s,c[1],c[2]], [c[0]-s//2,c[1]+s,c[2]], [c[0]-s//2,c[1]-s//2,c[2]+s], [c[0]-s//2,c[1]-s//2,c[2]-s]]
|
| 192 |
+
pts = rasterize_edges(v, [(0,1),(0,2),(0,3),(1,2),(1,3),(2,3)])
|
| 193 |
+
elif name == "cube":
|
| 194 |
+
s = r.randint(2, 4)
|
| 195 |
+
v = [[c[0]+d[0]*s, c[1]+d[1]*s, c[2]+d[2]*s] for d in [(-1,-1,-1),(-1,-1,1),(-1,1,1),(-1,1,-1),(1,-1,-1),(1,-1,1),(1,1,1),(1,1,-1)]]
|
| 196 |
+
pts = rasterize_edges(v, [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),(0,4),(1,5),(2,6),(3,7)])
|
| 197 |
+
elif name == "pyramid":
|
| 198 |
+
s = r.randint(2, 4)
|
| 199 |
+
base = [[c[0]-s,c[1]-s,c[2]-s],[c[0]-s,c[1]-s,c[2]+s],[c[0]-s,c[1]+s,c[2]+s],[c[0]-s,c[1]+s,c[2]-s]]
|
| 200 |
+
apex = [c[0]+s, c[1], c[2]]
|
| 201 |
+
v = base + [apex]
|
| 202 |
+
pts = rasterize_edges(v, [(0,1),(1,2),(2,3),(3,0),(0,4),(1,4),(2,4),(3,4)])
|
| 203 |
+
elif name == "prism":
|
| 204 |
+
s, h = r.randint(2, 4), r.randint(2, 4)
|
| 205 |
+
bottom = [[c[0]-h,c[1]-s,c[2]], [c[0]-h,c[1]+s//2,c[2]-s], [c[0]-h,c[1]+s//2,c[2]+s]]
|
| 206 |
+
top = [[b[0]+2*h, b[1], b[2]] for b in bottom]
|
| 207 |
+
v = bottom + top
|
| 208 |
+
pts = rasterize_edges(v, [(0,1),(1,2),(2,0),(3,4),(4,5),(5,3),(0,3),(1,4),(2,5)])
|
| 209 |
+
elif name == "octahedron":
|
| 210 |
+
s = r.uniform(2, 4)
|
| 211 |
+
v = [[c[0]+s,c[1],c[2]],[c[0]-s,c[1],c[2]],[c[0],c[1]+s,c[2]],[c[0],c[1]-s,c[2]],[c[0],c[1],c[2]+s],[c[0],c[1],c[2]-s]]
|
| 212 |
+
pts = rasterize_edges(v, [(0,2),(0,3),(0,4),(0,5),(1,2),(1,3),(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)])
|
| 213 |
+
elif name == "pentachoron":
|
| 214 |
+
s = r.uniform(2, 4)
|
| 215 |
+
v = [[c[0]+s,c[1],c[2]],[c[0]-s//2,c[1]+s,c[2]],[c[0]-s//2,c[1]-s//2,c[2]+s],[c[0]-s//2,c[1]-s//2,c[2]-s],[c[0],c[1],c[2]]]
|
| 216 |
+
pts = rasterize_edges(v, [(i,j) for i in range(5) for j in range(i+1,5)])
|
| 217 |
+
elif name == "wedge":
|
| 218 |
+
s = r.randint(2, 4)
|
| 219 |
+
v = [[c[0]-s,c[1]-s,c[2]-s],[c[0]-s,c[1]+s,c[2]-s],[c[0]-s,c[1],c[2]+s],[c[0]+s,c[1]-s,c[2]-s],[c[0]+s,c[1]+s,c[2]-s],[c[0]+s,c[1],c[2]+s]]
|
| 220 |
+
pts = rasterize_edges(v, [(0,1),(1,2),(2,0),(3,4),(4,5),(5,3),(0,3),(1,4),(2,5)])
|
| 221 |
+
elif name == "sphere":
|
| 222 |
+
R = r.uniform(2, min(3.5, GZ//2 - 1))
|
| 223 |
+
pts = rasterize_sphere(c, R, fill=False)
|
| 224 |
+
elif name == "hemisphere":
|
| 225 |
+
R = r.uniform(2, min(3.5, GZ//2 - 1))
|
| 226 |
+
pts = rasterize_sphere(c, R, fill=False, half=True)
|
| 227 |
+
elif name == "torus":
|
| 228 |
+
R, rr = r.uniform(3, 5), r.uniform(1, 2)
|
| 229 |
+
t = np.linspace(0, 2*np.pi, 40)
|
| 230 |
+
p = np.linspace(0, 2*np.pi, 20)
|
| 231 |
+
T, P = np.meshgrid(t, p)
|
| 232 |
+
pts = np.round(np.column_stack([c[0] + rr*np.sin(P.ravel()), c[1] + (R+rr*np.cos(P.ravel()))*np.cos(T.ravel()), c[2] + (R+rr*np.cos(P.ravel()))*np.sin(T.ravel())])).astype(int)
|
| 233 |
+
elif name == "bowl":
|
| 234 |
+
R = r.uniform(2, 4)
|
| 235 |
+
pts = rasterize_sphere(c, R, fill=False)
|
| 236 |
+
pts = pts[pts[:, 0] >= c[0]] if len(pts) > 0 else pts
|
| 237 |
+
elif name == "saddle":
|
| 238 |
+
s = r.uniform(2, 4)
|
| 239 |
+
Y, X = np.mgrid[-s:s:0.5, -s:s:0.5]
|
| 240 |
+
Z = (Y**2 - X**2) / (2*s)
|
| 241 |
+
pts = np.round(np.column_stack([c[0] + Z.ravel(), c[1] + Y.ravel(), c[2] + X.ravel()])).astype(int)
|
| 242 |
+
elif name == "capsule":
|
| 243 |
+
R, H = r.uniform(1.5, 3), r.uniform(2, 4)
|
| 244 |
+
shell = rasterize_sphere(c, R, fill=False)
|
| 245 |
+
body = []
|
| 246 |
+
for z in range(max(0, int(c[0]-H//2)), min(GZ, int(c[0]+H//2)+1)):
|
| 247 |
+
for y in range(GY):
|
| 248 |
+
for x in range(GX):
|
| 249 |
+
if abs(np.sqrt((y-c[1])**2 + (x-c[2])**2) - R) < 0.8:
|
| 250 |
+
body.append([z, y, x])
|
| 251 |
+
pts = np.concatenate([shell, np.array(body) if body else np.zeros((0,3), dtype=int)])
|
| 252 |
+
elif name == "cylinder":
|
| 253 |
+
R, H = r.uniform(2, 4), r.uniform(3, GZ - 2)
|
| 254 |
+
pts = []
|
| 255 |
+
for z in range(max(0, int(c[0]-H/2)), min(GZ, int(c[0]+H/2)+1)):
|
| 256 |
+
for y in range(GY):
|
| 257 |
+
for x in range(GX):
|
| 258 |
+
d = np.sqrt((y-c[1])**2 + (x-c[2])**2)
|
| 259 |
+
if abs(d - R) < 0.8:
|
| 260 |
+
pts.append([z, y, x])
|
| 261 |
+
pts = np.array(pts) if pts else np.zeros((0,3), dtype=int)
|
| 262 |
+
elif name == "cone":
|
| 263 |
+
R, H = r.uniform(2, 4), r.uniform(3, GZ - 2)
|
| 264 |
+
pts = []
|
| 265 |
+
for z in range(max(0, int(c[0]-H/2)), min(GZ, int(c[0]+H/2)+1)):
|
| 266 |
+
frac = 1 - (z - (c[0]-H/2)) / H
|
| 267 |
+
cr = R * frac
|
| 268 |
+
for y in range(GY):
|
| 269 |
+
for x in range(GX):
|
| 270 |
+
d = np.sqrt((y-c[1])**2 + (x-c[2])**2)
|
| 271 |
+
if abs(d - cr) < 0.8 and cr > 0.3:
|
| 272 |
+
pts.append([z, y, x])
|
| 273 |
+
pts = np.array(pts) if pts else np.zeros((0,3), dtype=int)
|
| 274 |
+
elif name == "channel":
|
| 275 |
+
R = r.uniform(2, 4)
|
| 276 |
+
L = r.randint(6, GX - 2)
|
| 277 |
+
pts = []
|
| 278 |
+
for z in range(GZ):
|
| 279 |
+
for x in range(max(0, c[2]-L//2), min(GX, c[2]+L//2)):
|
| 280 |
+
for y in range(GY):
|
| 281 |
+
d = np.sqrt((z - c[0])**2 + (y - c[1])**2)
|
| 282 |
+
if abs(d - R) < 0.8:
|
| 283 |
+
pts.append([z, y, x])
|
| 284 |
+
pts = np.array(pts) if pts else np.zeros((0,3), dtype=int)
|
| 285 |
+
else:
|
| 286 |
+
return None
|
| 287 |
+
except Exception:
|
| 288 |
+
return None
|
| 289 |
+
|
| 290 |
+
grid, pts = self._to_grid(pts)
|
| 291 |
+
if grid is not None and pts is not None and len(pts) > 0:
|
| 292 |
+
return {"grid": grid, "class_idx": CLASS_TO_IDX[name]}
|
| 293 |
+
return None
|
| 294 |
+
|
| 295 |
+
def generate_multi(self, n_shapes: int = None) -> Optional[Dict]:
|
| 296 |
+
if n_shapes is None:
|
| 297 |
+
n_shapes = self.rng.randint(2, 5)
|
| 298 |
+
names = list(self.rng.choice(CLASS_NAMES, size=n_shapes, replace=False))
|
| 299 |
+
shapes = [s for s in [self.generate(n) for n in names] if s is not None]
|
| 300 |
+
if len(shapes) < 2:
|
| 301 |
+
return None
|
| 302 |
+
grid = np.zeros(GRID_SHAPE, dtype=np.float32)
|
| 303 |
+
membership = np.zeros((MACRO_N, NUM_CLASSES), dtype=np.float32)
|
| 304 |
+
for s in shapes:
|
| 305 |
+
pts = np.argwhere(s["grid"] > 0.5)
|
| 306 |
+
grid[pts[:, 0], pts[:, 1], pts[:, 2]] = 1.0
|
| 307 |
+
patch_idx = (pts[:, 0]//PATCH_Z) * (MACRO_Y*MACRO_X) + (pts[:, 1]//PATCH_Y) * MACRO_X + (pts[:, 2]//PATCH_X)
|
| 308 |
+
np.add.at(membership[:, s["class_idx"]], patch_idx, 1.0)
|
| 309 |
+
return {"grid": grid, "membership": (membership > 0).astype(np.float32), "n_shapes": len(shapes)}
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def _worker(args):
|
| 313 |
+
seed, min_s, max_s = args
|
| 314 |
+
gen = HierarchicalShapeGenerator(seed)
|
| 315 |
+
return gen.generate_multi(gen.rng.randint(min_s, max_s + 1))
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def generate_dataset(n_samples: int, seed: int = 42, num_workers: int = MAX_WORKERS) -> Dict:
|
| 319 |
+
from multiprocessing import Pool
|
| 320 |
+
try:
|
| 321 |
+
from tqdm import tqdm
|
| 322 |
+
use_tqdm = True
|
| 323 |
+
except ImportError:
|
| 324 |
+
use_tqdm = False
|
| 325 |
+
|
| 326 |
+
tasks = [(seed * 10000 + i, 2, 4) for i in range(n_samples * 2)]
|
| 327 |
+
grids, memberships, n_shapes = [], [], []
|
| 328 |
+
|
| 329 |
+
with Pool(num_workers) as pool:
|
| 330 |
+
pbar = tqdm(total=n_samples, desc="Generating") if use_tqdm else None
|
| 331 |
+
for r in pool.imap_unordered(_worker, tasks):
|
| 332 |
+
if r is not None and len(grids) < n_samples:
|
| 333 |
+
grids.append(r["grid"])
|
| 334 |
+
memberships.append(r["membership"])
|
| 335 |
+
n_shapes.append(r["n_shapes"])
|
| 336 |
+
if pbar: pbar.update(1)
|
| 337 |
+
if len(grids) >= n_samples:
|
| 338 |
+
break
|
| 339 |
+
if pbar: pbar.close()
|
| 340 |
+
|
| 341 |
+
return {"grids": np.array(grids), "memberships": np.array(memberships), "n_shapes": np.array(n_shapes)}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
# === Patch Analysis: Two-Tier =================================================
|
| 345 |
+
|
| 346 |
+
def analyze_local_patches(grids):
|
| 347 |
+
"""
|
| 348 |
+
Local patch properties β intrinsic to each patch's voxels.
|
| 349 |
+
No cross-patch information. Computable from raw patch data.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
occupancy: (N, 64) float β mean voxel density
|
| 353 |
+
dims: (N, 64) long β 0-3 (axis extent counting)
|
| 354 |
+
curvature: (N, 64) long β 0=rigid, 1=curved, 2=combined
|
| 355 |
+
boundary: (N, 64) float β 1.0 if partial fill (surface patch)
|
| 356 |
+
axis_active: (N, 64, 3) float β which axes have extent > 1
|
| 357 |
+
fill_ratio: (N, 64) float β voxels / bounding_box_volume
|
| 358 |
+
"""
|
| 359 |
+
import torch
|
| 360 |
+
|
| 361 |
+
if isinstance(grids, np.ndarray):
|
| 362 |
+
grids = torch.from_numpy(grids).float()
|
| 363 |
+
|
| 364 |
+
device, N = grids.device, grids.shape[0]
|
| 365 |
+
patches = grids.view(N, MACRO_Z, PATCH_Z, MACRO_Y, PATCH_Y, MACRO_X, PATCH_X)
|
| 366 |
+
patches = patches.permute(0, 1, 3, 5, 2, 4, 6).contiguous().view(N, MACRO_N, PATCH_Z, PATCH_Y, PATCH_X)
|
| 367 |
+
|
| 368 |
+
occupancy = patches.sum(dim=(2, 3, 4)) / PATCH_VOL
|
| 369 |
+
occ_mask = occupancy > 0.01
|
| 370 |
+
occ = patches > 0.5
|
| 371 |
+
|
| 372 |
+
z_c = torch.arange(PATCH_Z, device=device).view(1, 1, PATCH_Z, 1, 1).float()
|
| 373 |
+
y_c = torch.arange(PATCH_Y, device=device).view(1, 1, 1, PATCH_Y, 1).float()
|
| 374 |
+
x_c = torch.arange(PATCH_X, device=device).view(1, 1, 1, 1, PATCH_X).float()
|
| 375 |
+
INF = 1000.0
|
| 376 |
+
|
| 377 |
+
z_ext = torch.where(occ, z_c.expand_as(patches), torch.full_like(patches, -INF)).amax(dim=(2,3,4)) - torch.where(occ, z_c.expand_as(patches), torch.full_like(patches, INF)).amin(dim=(2,3,4))
|
| 378 |
+
y_ext = torch.where(occ, y_c.expand_as(patches), torch.full_like(patches, -INF)).amax(dim=(2,3,4)) - torch.where(occ, y_c.expand_as(patches), torch.full_like(patches, INF)).amin(dim=(2,3,4))
|
| 379 |
+
x_ext = torch.where(occ, x_c.expand_as(patches), torch.full_like(patches, -INF)).amax(dim=(2,3,4)) - torch.where(occ, x_c.expand_as(patches), torch.full_like(patches, INF)).amin(dim=(2,3,4))
|
| 380 |
+
|
| 381 |
+
ext_sorted, _ = torch.stack([z_ext, y_ext, x_ext], dim=-1).clamp(min=0).sort(dim=-1, descending=True)
|
| 382 |
+
dims = torch.zeros(N, MACRO_N, dtype=torch.long, device=device)
|
| 383 |
+
dims = torch.where(ext_sorted[..., 0] >= 1, torch.tensor(1, device=device), dims)
|
| 384 |
+
dims = torch.where(ext_sorted[..., 1] >= 1, torch.tensor(2, device=device), dims)
|
| 385 |
+
dims = torch.where(ext_sorted[..., 2] >= 1, torch.tensor(3, device=device), dims)
|
| 386 |
+
dims = torch.where(~occ_mask, torch.tensor(-1, device=device), dims)
|
| 387 |
+
|
| 388 |
+
voxels = patches.sum(dim=(2, 3, 4))
|
| 389 |
+
bb_vol = ((z_ext + 1) * (y_ext + 1) * (x_ext + 1)).clamp(min=1)
|
| 390 |
+
fill_ratio = voxels / bb_vol
|
| 391 |
+
curvature = torch.where(fill_ratio > 0.6, 0, torch.where(fill_ratio < 0.3, 1, 2)).long()
|
| 392 |
+
|
| 393 |
+
boundary = ((occupancy > 0.01) & (occupancy < 0.9)).float()
|
| 394 |
+
|
| 395 |
+
axis_active = torch.stack([
|
| 396 |
+
(z_ext.clamp(min=0) >= 1).float(),
|
| 397 |
+
(y_ext.clamp(min=0) >= 1).float(),
|
| 398 |
+
(x_ext.clamp(min=0) >= 1).float(),
|
| 399 |
+
], dim=-1)
|
| 400 |
+
|
| 401 |
+
return {
|
| 402 |
+
"occupancy": occupancy,
|
| 403 |
+
"dims": dims,
|
| 404 |
+
"curvature": curvature,
|
| 405 |
+
"boundary": boundary,
|
| 406 |
+
"axis_active": axis_active,
|
| 407 |
+
"fill_ratio": fill_ratio,
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def analyze_structural_patches(grids, local_data):
|
| 412 |
+
"""
|
| 413 |
+
Structural patch properties β relational, require neighborhood context.
|
| 414 |
+
Ground truth targets for post-attention heads.
|
| 415 |
+
|
| 416 |
+
Returns:
|
| 417 |
+
topology: (N, 64) long β 0=open (<= 3 neighbors), 1=closed (> 3)
|
| 418 |
+
neighbor_count: (N, 64) float β normalized 0-1 (raw count / 6)
|
| 419 |
+
surface_role: (N, 64) long β 0=isolated (0-1), 1=boundary (2-4), 2=interior (5-6)
|
| 420 |
+
"""
|
| 421 |
+
import torch
|
| 422 |
+
import torch.nn.functional as F
|
| 423 |
+
|
| 424 |
+
if isinstance(grids, np.ndarray):
|
| 425 |
+
grids = torch.from_numpy(grids).float()
|
| 426 |
+
|
| 427 |
+
device, N = grids.device, grids.shape[0]
|
| 428 |
+
occ_mask = local_data["occupancy"] > 0.01
|
| 429 |
+
|
| 430 |
+
occ_3d = occ_mask.float().view(N, 1, MACRO_Z, MACRO_Y, MACRO_X)
|
| 431 |
+
kernel = torch.zeros(1, 1, 3, 3, 3, device=device)
|
| 432 |
+
kernel[0, 0, 1, 1, 0] = kernel[0, 0, 1, 1, 2] = 1
|
| 433 |
+
kernel[0, 0, 1, 0, 1] = kernel[0, 0, 1, 2, 1] = 1
|
| 434 |
+
kernel[0, 0, 0, 1, 1] = kernel[0, 0, 2, 1, 1] = 1
|
| 435 |
+
raw_count = F.conv3d(occ_3d, kernel, padding=1).view(N, MACRO_N)
|
| 436 |
+
|
| 437 |
+
topology = (raw_count > 3).long()
|
| 438 |
+
neighbor_count = raw_count / 6.0
|
| 439 |
+
|
| 440 |
+
surface_role = torch.zeros(N, MACRO_N, dtype=torch.long, device=device)
|
| 441 |
+
surface_role = torch.where(raw_count >= 2, torch.tensor(1, device=device), surface_role)
|
| 442 |
+
surface_role = torch.where(raw_count >= 5, torch.tensor(2, device=device), surface_role)
|
| 443 |
+
|
| 444 |
+
return {
|
| 445 |
+
"topology": topology,
|
| 446 |
+
"neighbor_count": neighbor_count,
|
| 447 |
+
"surface_role": surface_role,
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def analyze_patches_torch(grids):
|
| 452 |
+
"""Combined analysis β returns both local and structural properties."""
|
| 453 |
+
local_data = analyze_local_patches(grids)
|
| 454 |
+
struct_data = analyze_structural_patches(grids, local_data)
|
| 455 |
+
|
| 456 |
+
import torch
|
| 457 |
+
N = local_data["occupancy"].shape[0]
|
| 458 |
+
device = local_data["occupancy"].device
|
| 459 |
+
labels = torch.zeros(N, MACRO_N, NUM_GATES, device=device)
|
| 460 |
+
labels[..., 0] = (local_data["curvature"] == 0).float()
|
| 461 |
+
labels[..., 1] = (local_data["curvature"] == 1).float()
|
| 462 |
+
labels[..., 2] = (local_data["curvature"] == 2).float()
|
| 463 |
+
labels[..., 3] = (struct_data["topology"] == 0).float()
|
| 464 |
+
labels[..., 4] = (struct_data["topology"] == 1).float()
|
| 465 |
+
|
| 466 |
+
return {
|
| 467 |
+
# Local
|
| 468 |
+
"patch_occupancy": local_data["occupancy"],
|
| 469 |
+
"patch_dims": local_data["dims"],
|
| 470 |
+
"patch_curvature": local_data["curvature"],
|
| 471 |
+
"patch_boundary": local_data["boundary"],
|
| 472 |
+
"patch_axis_active": local_data["axis_active"],
|
| 473 |
+
"patch_fill_ratio": local_data["fill_ratio"],
|
| 474 |
+
# Structural
|
| 475 |
+
"patch_topology": struct_data["topology"],
|
| 476 |
+
"patch_neighbor_count": struct_data["neighbor_count"],
|
| 477 |
+
"patch_surface_role": struct_data["surface_role"],
|
| 478 |
+
# Legacy
|
| 479 |
+
"patch_labels": labels,
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
# === Dataset ==================================================================
|
| 484 |
+
import torch
|
| 485 |
+
from torch.utils.data import Dataset
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
class ShapeDataset(Dataset):
|
| 489 |
+
def __init__(self, grids, memberships, patch_data):
|
| 490 |
+
self.grids = grids
|
| 491 |
+
self.memberships = memberships
|
| 492 |
+
|
| 493 |
+
# Local
|
| 494 |
+
self.patch_occupancy = patch_data["patch_occupancy"]
|
| 495 |
+
self.patch_dims = patch_data["patch_dims"]
|
| 496 |
+
self.patch_curvature = patch_data["patch_curvature"]
|
| 497 |
+
self.patch_boundary = patch_data["patch_boundary"]
|
| 498 |
+
self.patch_axis_active = patch_data["patch_axis_active"]
|
| 499 |
+
self.patch_fill_ratio = patch_data["patch_fill_ratio"]
|
| 500 |
+
|
| 501 |
+
# Structural
|
| 502 |
+
self.patch_topology = patch_data["patch_topology"]
|
| 503 |
+
self.patch_neighbor_count = patch_data["patch_neighbor_count"]
|
| 504 |
+
self.patch_surface_role = patch_data["patch_surface_role"]
|
| 505 |
+
|
| 506 |
+
# Legacy
|
| 507 |
+
self.patch_labels = patch_data["patch_labels"]
|
| 508 |
+
|
| 509 |
+
# Derived global targets
|
| 510 |
+
self.patch_shape_count = (memberships > 0).sum(dim=-1).long()
|
| 511 |
+
self.global_shapes = (memberships.sum(dim=1) > 0).float()
|
| 512 |
+
occ_mask = self.patch_occupancy > 0.01
|
| 513 |
+
occ_count = occ_mask.sum(dim=1, keepdim=True).clamp(min=1)
|
| 514 |
+
self.global_gates = (self.patch_labels * occ_mask.unsqueeze(-1)).sum(dim=1) / occ_count
|
| 515 |
+
|
| 516 |
+
def __len__(self):
|
| 517 |
+
return len(self.grids)
|
| 518 |
+
|
| 519 |
+
def __getitem__(self, idx):
|
| 520 |
+
return {
|
| 521 |
+
"grid": self.grids[idx],
|
| 522 |
+
"patch_shape_membership": self.memberships[idx],
|
| 523 |
+
"patch_shape_count": self.patch_shape_count[idx],
|
| 524 |
+
# Local
|
| 525 |
+
"patch_occupancy": self.patch_occupancy[idx],
|
| 526 |
+
"patch_dims": self.patch_dims[idx],
|
| 527 |
+
"patch_curvature": self.patch_curvature[idx],
|
| 528 |
+
"patch_boundary": self.patch_boundary[idx],
|
| 529 |
+
"patch_axis_active": self.patch_axis_active[idx],
|
| 530 |
+
"patch_fill_ratio": self.patch_fill_ratio[idx],
|
| 531 |
+
# Structural
|
| 532 |
+
"patch_topology": self.patch_topology[idx],
|
| 533 |
+
"patch_neighbor_count": self.patch_neighbor_count[idx],
|
| 534 |
+
"patch_surface_role": self.patch_surface_role[idx],
|
| 535 |
+
# Legacy
|
| 536 |
+
"patch_labels": self.patch_labels[idx],
|
| 537 |
+
# Global
|
| 538 |
+
"global_shapes": self.global_shapes[idx],
|
| 539 |
+
"global_gates": self.global_gates[idx],
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def collate_fn(batch):
|
| 544 |
+
return {k: torch.stack([b[k] for b in batch]) for k in batch[0].keys()}
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
print(f"β Generator ready | Local: {LOCAL_GATE_DIM}d | Structural: {STRUCTURAL_GATE_DIM}d | Total: {TOTAL_GATE_DIM}d")
|