-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulation.py
More file actions
466 lines (384 loc) · 16 KB
/
Copy pathsimulation.py
File metadata and controls
466 lines (384 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# """
# simulation.py — Monte Carlo threshold simulation for D(S3).
# Supports two noise models:
# Code capacity: T=1 round, p_meas=0 (perfect syndromes).
# Phenomenological: T=L rounds, p_meas=p (noisy syndromes).
# Uses JIT decoder with commit/defer rule.
# Trial structure:
# 1. Prepare D(S3) ground state.
# 2. Record initial logical observables.
# 3. For T rounds: apply errors, take syndrome measurement, run JIT step.
# 4. Take final NOISELESS syndrome round, run JIT step.
# 5. Finalize: force-commit remaining clusters, decode eta globally.
# 6. Logical error = any change in homological invariants.
# L must not be divisible by 3 (Z3 logical wraps trivially).
# """
# import numpy as np
# import matplotlib
# matplotlib.use('Agg')
# import matplotlib.pyplot as plt
# import time
# from datetime import datetime
# import os
# from lattice import DS3Lattice
# from errors import DepolarizingError
# from decoder import JITDecoder
# def run_trial(L, T, error_model, rng):
# """
# Single Monte Carlo trial with JIT decoding.
# At each timestep: apply errors → measure (with noise) → JIT step.
# The JIT receives p_meas so D(Z3) measurements within ungauged
# patches also experience measurement noise.
# Returns True if logical error occurred.
# """
# lattice = DS3Lattice(L)
# init_obs = lattice.get_logical_observables()
# decoder = JITDecoder(lattice)
# p_meas = error_model.p_meas
# # T noisy rounds with JIT decoding at each step
# for step in range(T):
# error_model.apply(lattice, rng)
# det = lattice.step(p_meas=p_meas, rng=rng)
# decoder.process_timestep(det, det['t'], p_meas=p_meas, rng=rng)
# # Final noiseless round
# det = lattice.step(p_meas=0.0, rng=rng)
# decoder.process_timestep(det, det['t'], p_meas=0.0, rng=rng)
# # Finalize: complete patches, force-commit, decode eta
# decoder.finalize()
# return lattice.has_logical_error(init_obs)
# def run_sweep(L_values, p_values, n_trials=500, T=1, p_meas_factor=0.0,
# seed=42, verbose=True):
# """
# Sweep over (L, p).
# Parameters
# ----------
# T : int
# Number of noisy rounds per trial.
# T=1 for code capacity, T=L for phenomenological.
# p_meas_factor : float
# Measurement noise as multiple of p.
# 0.0 = perfect syndromes (code capacity).
# 1.0 = p_meas = p (phenomenological).
# Returns results[L][p] = (p_L, std_err).
# """
# rng = np.random.default_rng(seed)
# results = {L: {} for L in L_values}
# total = len(L_values) * len(p_values)
# done = 0
# t0 = time.time()
# for L in L_values:
# T_actual = T if T > 1 else 1 # allow T=L convention
# for p in p_values:
# p_meas = p * p_meas_factor
# em = DepolarizingError(p, p_meas)
# n_err = sum(run_trial(L, T_actual, em, rng) for _ in range(n_trials))
# pL = n_err / n_trials
# se = np.sqrt(pL * (1 - pL) / n_trials)
# results[L][p] = (pL, se)
# done += 1
# if verbose:
# elapsed = time.time() - t0
# print(f' L={L:2d} p={p:.3f} pL={pL:.4f}±{se:.4f} '
# f'[{done}/{total}] [{elapsed:.0f}s]', flush=True)
# return results
# def run_sweep_phenomenological(L_values, p_values, n_trials=500,
# seed=42, verbose=True):
# """
# Sweep with phenomenological noise: T=L rounds, p_meas=p.
# """
# rng = np.random.default_rng(seed)
# results = {L: {} for L in L_values}
# total = len(L_values) * len(p_values)
# done = 0
# t0 = time.time()
# for L in L_values:
# for p in p_values:
# em = DepolarizingError(p, p) # p_meas = p
# n_err = sum(run_trial(L, L, em, rng) for _ in range(n_trials))
# pL = n_err / n_trials
# se = np.sqrt(pL * (1 - pL) / n_trials)
# results[L][p] = (pL, se)
# done += 1
# if verbose:
# elapsed = time.time() - t0
# print(f' L={L:2d} T={L} p={p:.3f} pL={pL:.4f}±{se:.4f} '
# f'[{done}/{total}] [{elapsed:.0f}s]', flush=True)
# return results
# def plot_results(results, L_values, p_values, save_path, title=None):
# fig, ax = plt.subplots(figsize=(10, 7))
# cmap = plt.get_cmap('tab10')
# for i, L in enumerate(sorted(L_values)):
# ps = sorted(results[L].keys())
# pLs = [results[L][p][0] for p in ps]
# errs = [results[L][p][1] for p in ps]
# ax.errorbar(ps, pLs, yerr=errs, marker='o', capsize=3,
# linewidth=2, label=f'L = {L}', color=cmap(i))
# ax.axhline(0.5, color='grey', ls='--', alpha=0.5)
# ax.set_xlabel('Physical error rate $p$', fontsize=14)
# ax.set_ylabel('Logical error rate $p_L$', fontsize=14)
# ax.set_title(title or r'D(S$_3$) Threshold', fontsize=15)
# ax.legend(fontsize=12)
# ax.grid(True, alpha=0.3)
# ax.set_ylim(-0.02, 1.02)
# plt.tight_layout()
# plt.savefig(save_path, dpi=150, bbox_inches='tight')
# print(f'Saved: {save_path}')
# def main():
# print('=' * 60)
# print('D(S3) Threshold Simulation — JIT Decoder')
# print('=' * 60)
# # Code-capacity mode
# L_values = [4, 5, 7, 8]
# p_values = [0.02, 0.04, 0.06, 0.08, 0.10, 0.12, 0.14, 0.16, 0.18]
# n_trials = 300
# # T = 1
# # p_meas_factor = 0.0
# # Phenomenological mode
# T = L # convention: T=L rounds for phenomenological
# p_meas_factor = 0.02 # p_meas = p for phenomenological
# print(f'Mode: code capacity (T={T}, p_meas={p_meas_factor}*p)')
# print(f'L: {L_values}')
# print(f'p: {[f"{p:.2f}" for p in p_values]}')
# print(f'Trials: {n_trials}')
# print()
# t0 = time.time()
# results = run_sweep(L_values, p_values, n_trials=n_trials,
# T=T, p_meas_factor=p_meas_factor,
# seed=2024, verbose=True)
# print(f'\nTotal: {time.time()-t0:.0f}s')
# script_dir = os.path.dirname(os.path.abspath(__file__))
# plot_dir = os.path.join(script_dir, 'threshold_plots')
# os.makedirs(plot_dir, exist_ok=True)
# # plot_results(results, L_values, p_values,
# # os.path.join(plot_dir, 'threshold_plot.png'),
# # title=r'D(S$_3$) Code-Capacity Threshold (JIT Decoder)')
# now = datetime.now()
# formatted_time = now.strftime("%Y_%m_%d_%H_%M_%S")
# if T == 1 and p_meas_factor == 0.0:
# plot_title = r'D(S$_3$) Code-Capacity Threshold (JIT Decoder)'
# plot_name = f'code_capacity_threshold_{formatted_time}.png'
# else:
# plot_title = r'D(S$_3$) Phenomenological Threshold (JIT Decoder)'
# plot_name = f'phenomenological_threshold_{formatted_time}.png'
# plot_results(results, L_values, p_values,
# os.path.join(plot_dir, plot_name),
# title=plot_title)
# print('\nSummary:')
# hdr = f'{"p":>8}' + ''.join(f' L={L:2d} ' for L in sorted(L_values))
# print(hdr)
# for p in sorted(p_values):
# row = f'{p:8.3f}'
# for L in sorted(L_values):
# row += f' {results[L][p][0]:.4f} '
# print(row)
# if __name__ == '__main__':
# main()
"""
simulation.py — Monte Carlo threshold simulation for D(S3).
Supports two noise models:
Code capacity: T=1 round, p_meas=0 (perfect syndromes).
Phenomenological: T=L rounds, p_meas=p (noisy syndromes).
Uses JIT decoder with commit/defer rule.
Trial structure:
1. Prepare D(S3) ground state.
2. Record initial logical observables.
3. For T rounds: apply errors, take syndrome measurement, run JIT step.
4. Take final NOISELESS syndrome round, run JIT step.
5. Finalize: force-commit remaining clusters, decode eta globally.
6. Logical error = any change in homological invariants.
L must not be divisible by 3 (Z3 logical wraps trivially).
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import time
from datetime import datetime
import os
from lattice import DS3Lattice
from errors import DepolarizingError
from decoder import JITDecoder
def run_trial(L, T, error_model, rng):
"""
Single Monte Carlo trial with JIT decoding.
At each timestep: apply errors → measure (with noise) → JIT step.
The JIT receives p_meas so D(Z3) measurements within ungauged
patches also experience measurement noise.
Returns True if logical error occurred.
"""
lattice = DS3Lattice(L)
init_obs = lattice.get_logical_observables()
decoder = JITDecoder(lattice)
p_meas = error_model.p_meas
# T noisy rounds with JIT decoding at each step
for step in range(T):
error_model.apply(lattice, rng)
det = lattice.step(p_meas=p_meas, rng=rng)
decoder.process_timestep(det, det['t'], p_meas=p_meas, rng=rng)
# Final noiseless round
det = lattice.step(p_meas=0.0, rng=rng)
decoder.process_timestep(det, det['t'], p_meas=0.0, rng=rng)
# Finalize: complete patches, force-commit, decode eta
decoder.finalize()
return lattice.has_logical_error(init_obs)
def run_sweep(L_values, p_values, n_trials=500, T=1, p_meas_factor=0.0,
seed=42, verbose=True):
"""
Sweep over (L, p).
Parameters
----------
T : int
Number of noisy rounds per trial.
T=1 for code capacity, T=L for phenomenological.
p_meas_factor : float
Measurement noise as multiple of p.
0.0 = perfect syndromes (code capacity).
1.0 = p_meas = p (phenomenological).
Returns results[L][p] = (p_L, std_err).
"""
rng = np.random.default_rng(seed)
results = {L: {} for L in L_values}
total = len(L_values) * len(p_values)
done = 0
t0 = time.time()
for L in L_values:
T_actual = T if T > 1 else 1 # allow T='L' convention
for p in p_values:
p_meas = p * p_meas_factor
em = DepolarizingError(p, p_meas)
n_err = sum(run_trial(L, T_actual, em, rng) for _ in range(n_trials))
pL = n_err / n_trials
se = np.sqrt(pL * (1 - pL) / n_trials)
results[L][p] = (pL, se)
done += 1
if verbose:
elapsed = time.time() - t0
print(f' L={L:2d} p={p:.3f} pL={pL:.4f}±{se:.4f} '
f'[{done}/{total}] [{elapsed:.0f}s]', flush=True)
return results
def run_sweep_phenomenological(L_values, p_values, n_trials=500,
seed=42, verbose=True):
"""
Sweep with phenomenological noise: T=L rounds, p_meas=p.
"""
rng = np.random.default_rng(seed)
results = {L: {} for L in L_values}
total = len(L_values) * len(p_values)
done = 0
t0 = time.time()
for L in L_values:
for p in p_values:
em = DepolarizingError(p, p) # p_meas = p
n_err = sum(run_trial(L, L, em, rng) for _ in range(n_trials))
pL = n_err / n_trials
se = np.sqrt(pL * (1 - pL) / n_trials)
results[L][p] = (pL, se)
done += 1
if verbose:
elapsed = time.time() - t0
print(f' L={L:2d} T={L} p={p:.3f} pL={pL:.4f}±{se:.4f} '
f'[{done}/{total}] [{elapsed:.0f}s]', flush=True)
return results
def plot_results(results, L_values, p_values, save_path, title=None):
fig, ax = plt.subplots(figsize=(10, 7))
cmap = plt.get_cmap('tab10')
for i, L in enumerate(sorted(L_values)):
ps = sorted(results[L].keys())
pLs = [results[L][p][0] for p in ps]
errs = [results[L][p][1] for p in ps]
ax.errorbar(ps, pLs, yerr=errs, marker='o', capsize=3,
linewidth=2, label=f'L = {L}', color=cmap(i))
ax.axhline(0.5, color='grey', ls='--', alpha=0.5)
ax.set_xlabel('Physical error rate $p$', fontsize=14)
ax.set_ylabel('Logical error rate $p_L$', fontsize=14)
ax.set_title(title or r'D(S$_3$) Threshold', fontsize=15)
ax.legend(fontsize=12)
ax.grid(True, alpha=0.3)
ax.set_ylim(-0.02, 1.02)
plt.tight_layout()
plt.savefig(save_path, dpi=150, bbox_inches='tight')
print(f'Saved: {save_path}')
def main():
import argparse
parser = argparse.ArgumentParser(
description='D(S3) Threshold Simulation — JIT Decoder')
parser.add_argument('--mode', choices=['code_capacity', 'phenomenological', 'both'],
default='both', help='Which threshold to compute')
parser.add_argument('--trials', type=int, default=500,
help='Number of trials per (L, p) point')
parser.add_argument('--seed', type=int, default=2024)
args = parser.parse_args()
script_dir = os.path.dirname(os.path.abspath(__file__))
plot_dir = os.path.join(script_dir, 'threshold_plots')
os.makedirs(plot_dir, exist_ok=True)
now = datetime.now()
formatted_time = now.strftime("%Y_%m_%d_%H_%M_%S")
# ── Code capacity ──
if args.mode in ('code_capacity', 'both'):
print('=' * 60)
print('Code-Capacity Threshold (T=1, p_meas=0)')
print('=' * 60)
# L_values = [4, 7, 10, 13]
L_values = [4, 10, 17]
# p_values = [0.08, 0.10, 0.12, 0.14, 0.16, 0.18, 0.20, 0.22, 0.225, 0.23, 0.235, 0.24]
p_values = [0.20, 0.21, 0.22, 0.225, 0.23, 0.235, 0.24]
n_trials = args.trials
print(f'L: {L_values}')
print(f'p: {[f"{p:.2f}" for p in p_values]}')
print(f'Trials: {n_trials}')
print()
t0 = time.time()
results = run_sweep(L_values, p_values, n_trials=n_trials,
T=1, p_meas_factor=0.0,
seed=args.seed, verbose=True)
print(f'\nTotal: {time.time()-t0:.0f}s')
# plot_results(results, L_values, p_values,
# os.path.join(plot_dir, 'code_capacity.png'),
# title=r'D(S$_3$) Code-Capacity Threshold (HDRG)')
script_dir = os.path.dirname(os.path.abspath(__file__))
plot_dir = os.path.join(script_dir, 'threshold_plots')
os.makedirs(plot_dir, exist_ok=True)
plot_title = r'D(S$_3$) Code-Capacity Threshold (JIT Decoder)'
plot_name = f'code_capacity_threshold_{formatted_time}.png'
plot_results(results, L_values, p_values,
os.path.join(plot_dir, plot_name),
title=plot_title)
_print_table(results, L_values, p_values)
# ── Phenomenological ──
if args.mode in ('phenomenological', 'both'):
print('\n' + '=' * 60)
print('Phenomenological Threshold (T=L, p_meas=p)')
print('=' * 60)
L_values = [4, 7, 10, 13]
p_values = [0.001, 0.002, 0.003, 0.004, 0.005, 0.006,
0.007, 0.008, 0.010, 0.012, 0.015]
n_trials = args.trials
print(f'L: {L_values}')
print(f'p: {[f"{p:.3f}" for p in p_values]}')
print(f'Trials: {n_trials}')
print()
t0 = time.time()
results = run_sweep_phenomenological(L_values, p_values,
n_trials=n_trials,
seed=args.seed, verbose=True)
print(f'\nTotal: {time.time()-t0:.0f}s')
plot_title = r'D(S$_3$) Phenomenological Threshold (JIT Decoder)'
plot_name = f'phenomenological_threshold_{formatted_time}.png'
plot_results(results, L_values, p_values,
os.path.join(plot_dir, plot_name),
title=plot_title)
_print_table(results, L_values, p_values)
def _print_table(results, L_values, p_values):
"""Print a summary table of results."""
print('\nSummary:')
hdr = f'{"p":>8}' + ''.join(f' L={L:<3d} ' for L in sorted(L_values))
print(hdr)
print('-' * len(hdr))
for p in sorted(p_values):
row = f'{p:8.4f}'
for L in sorted(L_values):
pL, se = results[L][p]
row += f' {pL:.4f}±{se:.4f}'
print(row)
if __name__ == '__main__':
main()