yang
This project has not described itself yet.
Brought by drakestapleton
yang / scripts / replica_shell_probe.py
| 1 | """Fixed-seed CPU probe of two exchange surfaces in periodic 4D SU(2) or compact U(1).""" |
| 2 | import argparse |
| 3 | from itertools import combinations, product |
| 4 | from math import sqrt |
| 5 | |
| 6 | import numpy as np |
| 7 | |
| 8 | |
| 9 | def mul(a, b): |
| 10 | scalar = a[..., :1] * b[..., :1] - (a[..., 1:] * b[..., 1:]).sum(axis=-1, keepdims=True) |
| 11 | vector = a[..., :1] * b[..., 1:] + b[..., :1] * a[..., 1:] + np.cross(a[..., 1:], b[..., 1:]) |
| 12 | return np.concatenate((scalar, vector), axis=-1) |
| 13 | |
| 14 | |
| 15 | def inv(a): |
| 16 | return a * np.array([1., -1., -1., -1.]) |
| 17 | |
| 18 | |
| 19 | class Lattice: |
| 20 | def __init__(self, side, group): |
| 21 | self.group = group |
| 22 | shape = (side,) * 4 |
| 23 | self.sites = np.arange(side**4) |
| 24 | coords = np.array(np.unravel_index(self.sites, shape)) |
| 25 | self.parity = coords.sum(axis=0) % 2 |
| 26 | self.plus = np.array([np.ravel_multi_index((coords + d[:, None]) % side, shape) for d in np.eye(4, dtype=int)]) |
| 27 | self.minus = np.argsort(self.plus, axis=1) |
| 28 | self.pairs = list(combinations(range(4), 2)) |
| 29 | self.faces = np.array([np.stack((i*side**4+self.sites, j*side**4+self.plus[i], |
| 30 | i*side**4+self.plus[j], j*side**4+self.sites), axis=-1) |
| 31 | for i, j in self.pairs]) |
| 32 | # Observed spatial plaquettes at (0,0,0,0) and (0,0,0,2). |
| 33 | self.separated = np.ravel_multi_index((0, 0, 0, 2), shape) |
| 34 | time = np.minimum(coords[3], side-coords[3]) |
| 35 | slab = np.broadcast_to(time, (4, len(time))) |
| 36 | ps = np.zeros((4, len(time)), dtype=bool) |
| 37 | ps.flat[self.faces[0, 0]] = True |
| 38 | expanded = ps.copy() |
| 39 | expanded.flat[self.faces[ps.ravel()[self.faces].any(axis=-1)].ravel()] = True |
| 40 | target = np.zeros_like(ps) |
| 41 | target.flat[self.faces[0, self.separated]] = True |
| 42 | self.masks = {'slab': [slab == 0, slab <= 1], 'local': [ps, expanded], |
| 43 | 'endpoints': [ps, target]} |
| 44 | for masks in self.masks.values(): |
| 45 | boundaries = [] |
| 46 | for mask in masks: |
| 47 | inside = mask.ravel()[self.faces] |
| 48 | boundaries.append(inside.any(axis=-1) & ~inside.all(axis=-1)) |
| 49 | at_source = mask.ravel()[self.faces[0, 0]] |
| 50 | at_target = mask.ravel()[self.faces[0, self.separated]] |
| 51 | assert (at_source.all() and not at_target.any()) or (at_target.all() and not at_source.any()) |
| 52 | assert not (boundaries[0] & boundaries[1]).any() |
| 53 | |
| 54 | # Breadth-first tree rooted at the observed plaquette. Store parent layers |
| 55 | # to propagate parallel transports in batches, including wrapped edges. |
| 56 | self.layers = [] |
| 57 | seen = {0} |
| 58 | level = [0] |
| 59 | while level: |
| 60 | layer = [] |
| 61 | for parent in level: |
| 62 | for direction in range(4): |
| 63 | for reverse, neighbor in [(False, self.plus), (True, self.minus)]: |
| 64 | child = int(neighbor[direction, parent]) |
| 65 | if child in seen: |
| 66 | continue |
| 67 | seen.add(child) |
| 68 | layer.append((parent, child, direction, reverse)) |
| 69 | if layer: |
| 70 | self.layers.append(np.array(layer, dtype=int).T) |
| 71 | level = [edge[1] for edge in layer] |
| 72 | |
| 73 | # Pin three sides of each observed square. The two components have |
| 74 | # separate roots, and no frame outside either square is adjusted. |
| 75 | roots = np.array([0, self.separated]) |
| 76 | x1 = self.plus[0, roots] |
| 77 | self.forest = [np.array([(x, self.plus[i, x], i, 0) for x in roots for i in (0, 1)]).T, |
| 78 | np.array([(x, self.plus[1, x], 1, 0) for x in x1]).T] |
| 79 | |
| 80 | def tree_frame(self, u, layers, verify): |
| 81 | frame = np.zeros((len(u), len(self.sites), 4)) |
| 82 | frame[..., 0] = 1 |
| 83 | for parent, child, direction, reverse in layers: |
| 84 | source = np.where(reverse, child, parent) |
| 85 | edge = u[:, direction, source] |
| 86 | oriented = np.where(reverse[None, :, None], inv(edge), edge) |
| 87 | frame[:, child] = mul(frame[:, parent], oriented) |
| 88 | fixed = np.stack([mul(mul(frame, u[:, i]), inv(frame[:, self.plus[i]])) for i in range(4)], axis=1) |
| 89 | if verify: |
| 90 | for parent, child, direction, reverse in layers: |
| 91 | source = np.where(reverse, child, parent) |
| 92 | assert np.max(np.abs(fixed[:, direction, source]-[1., 0., 0., 0.])) < 1e-10 |
| 93 | return fixed |
| 94 | |
| 95 | def traces(self, u): |
| 96 | return np.stack([mul(mul(u[:, i], u[:, j, self.plus[i]]), |
| 97 | inv(mul(u[:, j], u[:, i, self.plus[j]])))[..., 0] for i, j in self.pairs], axis=1) |
| 98 | |
| 99 | def staple(self, u, i): |
| 100 | total = np.zeros_like(u[:, i]) |
| 101 | for j in range(4): |
| 102 | if i == j: |
| 103 | continue |
| 104 | # Both paths go from x+i back to x. |
| 105 | total += mul(u[:, j, self.plus[i]], inv(mul(u[:, j], u[:, i, self.plus[j]]))) |
| 106 | back = self.minus[j] |
| 107 | total += mul(inv(mul(u[:, i, back], u[:, j, self.plus[i, back]])), u[:, j, back]) |
| 108 | return total |
| 109 | |
| 110 | def sweep(self, u, beta, rng): |
| 111 | for i in range(4): |
| 112 | for parity in (0, 1): |
| 113 | idx = self.sites[self.parity == parity] |
| 114 | staple = self.staple(u, i)[:, idx] |
| 115 | old = u[:, i, idx] |
| 116 | # Symmetric isotropic proposal on SU(2), with a beta-dependent step. |
| 117 | delta = rng.normal(size=old.shape) |
| 118 | if self.group == 'U1': |
| 119 | delta[..., 2:] = 0 |
| 120 | delta[..., 0] += 1.5 + beta |
| 121 | delta /= np.linalg.norm(delta, axis=-1, keepdims=True) |
| 122 | new = mul(old, delta) |
| 123 | new /= np.linalg.norm(new, axis=-1, keepdims=True) |
| 124 | change = beta*mul(new-old, staple)[..., 0] |
| 125 | accept = np.log(rng.random(change.shape)) <= change |
| 126 | u[:, i, idx] = np.where(accept[..., None], new, old) |
| 127 | |
| 128 | def observe(self, u, beta, verify, colors=False): |
| 129 | raw = self.traces(u) |
| 130 | delta = (raw[0, 0, 0]-raw[1, 0, 0])*(raw[0, 0, self.separated]-raw[1, 0, self.separated]) |
| 131 | result = [raw.mean(), delta/2] |
| 132 | slab_colors = [] |
| 133 | rotations = np.array([[1,1,1,1], [1,1,-1,-1], [1,-1,1,-1], [1,-1,-1,1]]) |
| 134 | if self.group == 'U1': |
| 135 | rotations = np.ones_like(rotations) |
| 136 | for fields_u, names in [(u, ('slab', 'local', 'endpoints')), |
| 137 | (self.tree_frame(u, self.layers, verify), ('slab', 'local', 'endpoints')), |
| 138 | (self.tree_frame(u, self.forest, verify), ('endpoints',))]: |
| 139 | traces = self.traces(fields_u) |
| 140 | if verify: |
| 141 | assert np.max(np.abs(raw-traces)) < 1e-10 |
| 142 | score = traces.sum() |
| 143 | for name in names: |
| 144 | masks = self.masks[name] |
| 145 | fields = [] |
| 146 | for mask in masks: |
| 147 | swapped = np.where(mask[None, ..., None], fields_u[::-1], fields_u) |
| 148 | fields.append(beta*(score-self.traces(swapped).sum())/2) |
| 149 | if names == ('endpoints',): |
| 150 | caps = [] |
| 151 | color_fields = [] |
| 152 | staples = self.staple(fields_u, 0) |
| 153 | for site, measured in zip((0, self.separated), fields): |
| 154 | free = self.plus[1, site] |
| 155 | link_diff = fields_u[0, 0, free]-fields_u[1, 0, free] |
| 156 | staple_diff = staples[0, free]-staples[1, free] |
| 157 | cap = abs(beta)*np.linalg.norm(link_diff)*np.linalg.norm(staple_diff)/2 |
| 158 | caps.append(cap) |
| 159 | if colors: |
| 160 | rotated_links = fields_u[1, 0, free]*rotations |
| 161 | rotated_staples = staples[1, free]*rotations |
| 162 | color_fields.append(beta*mul(fields_u[0, 0, free]-rotated_links, |
| 163 | staples[0, free]-rotated_staples)[:, 0]/2) |
| 164 | if verify: |
| 165 | assert abs(measured-beta*mul(link_diff, staple_diff)[0]/2) < 1e-9 |
| 166 | assert abs(measured) <= cap + 1e-9 |
| 167 | if colors and name == 'slab' and fields_u is not u: |
| 168 | # The outer slab has its boundary off the source slice. |
| 169 | # Rotate only the second framed replica, then exchange. |
| 170 | for rot in rotations: |
| 171 | colored = fields_u.copy() |
| 172 | colored[1] *= rot |
| 173 | swapped = np.where(masks[1][None, ..., None], colored[::-1], colored) |
| 174 | slab_colors.append(np.tanh(beta*(score-self.traces(swapped).sum())/2)) |
| 175 | if verify: |
| 176 | rotated = u.copy() |
| 177 | rotated[1] *= rot |
| 178 | assert np.max(np.abs(self.tree_frame(rotated, self.layers, verify)-colored)) < 1e-9 |
| 179 | attenuation = np.prod(np.tanh(fields)) |
| 180 | factors = np.abs(np.tanh(fields)) |
| 181 | # Stable loss avoids subtracting a rounded tanh from one. |
| 182 | tails = np.exp(-2*np.abs(fields)) |
| 183 | losses = 2*tails/(1+tails) |
| 184 | result.extend([abs(attenuation), delta*attenuation/2, abs(delta*attenuation)/2, |
| 185 | losses[0], factors[0]*losses[1], float(factors[0] <= 0.9), |
| 186 | factors[0]*float(factors[1] <= 0.9)]) |
| 187 | if names == ('endpoints',): |
| 188 | threshold = np.arctanh(0.9) |
| 189 | result.extend([float(caps[0] <= threshold), factors[0]*float(caps[1] <= threshold)]) |
| 190 | if colors: |
| 191 | color_products = np.tanh(color_fields).prod(axis=0) |
| 192 | mean_abs = np.abs(color_products).mean() |
| 193 | abs_mean = abs(color_products.mean()) |
| 194 | result.extend([mean_abs, abs_mean, mean_abs-abs_mean, abs(delta)*abs_mean/2]) |
| 195 | if verify: |
| 196 | assert abs(color_products[0]-attenuation) < 1e-9 |
| 197 | for rot in rotations: |
| 198 | rotated = u.copy() |
| 199 | rotated[1] *= rot |
| 200 | aligned = self.tree_frame(rotated, self.forest, verify) |
| 201 | assert np.max(np.abs(aligned[1]-fields_u[1]*rot)) < 1e-10 |
| 202 | assert np.max(np.abs(self.traces(rotated)-raw)) < 1e-10 |
| 203 | if verify: |
| 204 | orbit = [] |
| 205 | for bits in product((0, 1), repeat=2): |
| 206 | other = fields_u.copy() |
| 207 | for bit, mask in zip(bits, masks): |
| 208 | if bit: |
| 209 | other = np.where(mask[None, ..., None], other[::-1], other) |
| 210 | values = self.traces(other) |
| 211 | obs = (values[0, 0, 0]-values[1, 0, 0])*(values[0, 0, self.separated]-values[1, 0, self.separated]) |
| 212 | weight = beta*(values.sum()-score) |
| 213 | expected = -2*np.dot(bits, fields) |
| 214 | assert abs(weight-expected) < 1e-9 and abs(obs-delta*(-1)**sum(bits)) < 1e-12 |
| 215 | orbit.append((weight, obs)) |
| 216 | logw, obs = np.transpose(orbit) |
| 217 | w = np.exp(logw-logw.max()) |
| 218 | assert abs(np.dot(w, obs)/w.sum()-delta*attenuation) < 1e-10 |
| 219 | if colors: |
| 220 | mean_abs = np.abs(slab_colors).mean() |
| 221 | abs_mean = abs(np.mean(slab_colors)) |
| 222 | result.extend([mean_abs, abs_mean, mean_abs-abs_mean]) |
| 223 | return result |
| 224 | |
| 225 | |
| 226 | def run(): |
| 227 | arg = argparse.ArgumentParser(description=__doc__) |
| 228 | mode = arg.add_mutually_exclusive_group() |
| 229 | mode.add_argument('--colors', action='store_true', help='Average signed endpoint factors over four relative color orientations.') |
| 230 | mode.add_argument('--outer-spectrum', action='store_true', help='Emit one row per sample with the full rigid color-orbit extrema before tanh.') |
| 231 | mode.add_argument('--vertex-shell', action='store_true', help='Test shared vertex gauges on the unframed outer slab (side 4).') |
| 232 | mode.add_argument('--haar-shell', action='store_true', help='Measure product Haar weight on the outer vertex sheets (side 4).') |
| 233 | mode.add_argument('--middle-cut', action='store_true', help='Compare a minimum-face middle cut and a slab at separation three (side 6).') |
| 234 | mode.add_argument('--interior-shells', action='store_true', help='Measure two successive whole-slice separators at separation four (side 8).') |
| 235 | mode.add_argument('--local-neighborhoods', action='store_true', help='Compare two joint minimum-area exchanges at each of two local buffer sizes (side 8).') |
| 236 | arg.add_argument('--group', choices=('SU2', 'U1'), default='SU2') |
| 237 | arg.add_argument('--side', type=int, default=4) |
| 238 | arg.add_argument('--warmup', type=int, default=128) |
| 239 | arg.add_argument('--samples', type=int, default=128) |
| 240 | arg.add_argument('--stride', type=int, default=2) |
| 241 | arg.add_argument('--beta', type=float, nargs='+', default=[0, 0.1, 0.5, 2.3]) |
| 242 | opt = arg.parse_args() |
| 243 | if not np.isfinite(opt.beta).all() or opt.side < 4 or opt.side % 2 or opt.samples < 16 or opt.samples % 8 or opt.stride < 1 or opt.warmup < 0 or min(opt.beta) < 0: |
| 244 | arg.error('Use an even side >= 4, samples divisible by 8 and >= 16, positive stride and nonnegative beta and warmup.') |
| 245 | if (opt.vertex_shell or opt.haar_shell) and opt.side != 4: |
| 246 | arg.error('The dense shared-vertex diagnostic is limited to side 4.') |
| 247 | if opt.middle_cut and opt.side != 6: |
| 248 | arg.error('The three-exchange comparison uses side 6 and time separation 3.') |
| 249 | if opt.interior_shells and opt.side != 8: |
| 250 | arg.error('The two-interior-shell comparison uses side 8 and time separation 4.') |
| 251 | if opt.local_neighborhoods and opt.side != 8: |
| 252 | arg.error('The local-neighborhood comparison uses side 8 and time separation 4.') |
| 253 | lat = Lattice(opt.side, opt.group) |
| 254 | masks = ['slab', 'local', 'endpoints', 'tree_slab', 'tree_local', 'tree_endpoints', 'forest_endpoints'] |
| 255 | keys = ['trace', 'raw_cov'] + [mask+'_'+stat for mask in masks for stat in |
| 256 | ('abs_factor', 'signed_cov', 'abs_bound', 'first_loss', 'second_weighted_loss', |
| 257 | 'first_moderate', 'second_weighted_moderate')] |
| 258 | keys += ['forest_endpoints_first_moderate_cs', 'forest_endpoints_second_weighted_moderate_cs'] |
| 259 | if opt.colors: |
| 260 | keys += ['color_mean_abs', 'color_abs_mean', 'color_cancellation', 'color_abs_bound', 'color_outer_slab_mean_abs', |
| 261 | 'color_outer_slab_abs_mean', 'color_outer_slab_cancellation'] |
| 262 | measure = None |
| 263 | if opt.outer_spectrum: |
| 264 | from outer_slab_spectrum import COLUMNS, measure |
| 265 | elif opt.vertex_shell: |
| 266 | from vertex_shell_probe import COLUMNS, VertexProbe |
| 267 | measure = VertexProbe(lat).measure |
| 268 | elif opt.haar_shell: |
| 269 | from haar_shell_probe import COLUMNS, HaarProbe |
| 270 | measure = HaarProbe().measure |
| 271 | elif opt.middle_cut: |
| 272 | from middle_cut_probe import COLUMNS, MiddleCut |
| 273 | measure = MiddleCut(lat).measure |
| 274 | elif opt.interior_shells: |
| 275 | from middle_cut_probe import INTERIOR_COLUMNS as COLUMNS, MiddleCut |
| 276 | measure = MiddleCut(lat, geometry='interior').measure |
| 277 | elif opt.local_neighborhoods: |
| 278 | from middle_cut_probe import LOCAL_COLUMNS as COLUMNS, MiddleCut |
| 279 | measure = MiddleCut(lat, geometry='local').measure |
| 280 | if measure is not None: |
| 281 | columns = ('sample', *COLUMNS) |
| 282 | else: |
| 283 | columns = tuple(part for k in keys for part in (k, k+'_batch_se')) |
| 284 | print('group\tside\twarmup\tsamples\tstride\tbeta\tstart\tseed\t'+'\t'.join(columns), flush=True) |
| 285 | for ib, beta in enumerate(opt.beta): |
| 286 | for start in ('hot', 'cold'): |
| 287 | seed = 41123+2*ib+(start == 'cold') |
| 288 | rng = np.random.default_rng(seed) |
| 289 | u = rng.normal(size=(2, 4, len(lat.sites), 4)) |
| 290 | if opt.group == 'U1': |
| 291 | u[..., 2:] = 0 |
| 292 | u /= np.linalg.norm(u, axis=-1, keepdims=True) |
| 293 | if start == 'cold': |
| 294 | u[:] = 0 |
| 295 | u[..., 0] = 1 |
| 296 | # Check the local Metropolis increment against the complete Wilson action. |
| 297 | trial = u.copy() |
| 298 | proposal = np.array([0.5, 0.5, 0.5, 0.5]) |
| 299 | if opt.group == 'U1': |
| 300 | proposal = np.array([0., 1., 0., 0.]) |
| 301 | trial[0, 2, -1] = proposal |
| 302 | diff = mul(proposal-u[0, 2, -1], lat.staple(u, 2)[0, -1])[0] |
| 303 | assert abs(diff-(lat.traces(trial)-lat.traces(u)).sum()) < 1e-10 |
| 304 | for _ in range(opt.warmup): |
| 305 | lat.sweep(u, beta, rng) |
| 306 | samples = [] |
| 307 | prefix = f'{opt.group}\t{opt.side}\t{opt.warmup}\t{opt.samples}\t{opt.stride}\t{beta:g}\t{start}\t{seed}\t' |
| 308 | for j in range(opt.samples): |
| 309 | for _ in range(opt.stride): |
| 310 | lat.sweep(u, beta, rng) |
| 311 | if measure is not None: |
| 312 | row = measure(lat, u, beta, j % 32 == 0, mul, inv) |
| 313 | print(prefix+str(j)+'\t'+'\t'.join(f'{v:.12g}' for v in row)) |
| 314 | continue |
| 315 | samples.append(lat.observe(u, beta, verify=(j % 32 == 0), colors=opt.colors)) |
| 316 | if measure is not None: |
| 317 | continue |
| 318 | batch = np.array(samples).reshape(8, -1, len(keys)).mean(axis=1) |
| 319 | values = np.stack((batch.mean(axis=0), batch.std(axis=0, ddof=1)/sqrt(8)), axis=1).ravel() |
| 320 | print(prefix+'\t'.join(f'{v:.8g}' for v in values), flush=True) |
| 321 | |
| 322 | |
| 323 | if __name__ == '__main__': |
| 324 | run() |