-
Notifications
You must be signed in to change notification settings - Fork 55
/
test_fogi_gst.py
380 lines (324 loc) · 18.9 KB
/
test_fogi_gst.py
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
import unittest
import numpy as np
import pygsti
from pygsti.modelpacks import smq1Q_XYI as std
from pygsti.baseobjs import Basis, CompleteElementaryErrorgenBasis
from pygsti.processors import QubitProcessorSpec
from pygsti.models import create_crosstalk_free_model
from pygsti.models import create_cloud_crosstalk_model_from_hops_and_weights
from ..testutils import BaseTestCase, compare_files, regenerate_references
#Perform a small gauge transformation and check FOGI error rates
def do_small_gauge_transform(base_model, target_model, model_type, gauge_basis, gauge_mag=0.01,
include_spam=True, reparam=True):
mdl2 = base_model.copy()
mdl2.set_all_parameterizations('full TP')
random_tp_op = np.identity(4) + np.concatenate((np.zeros((1,4)), 2 * gauge_mag * (np.random.random((3,4)) - 0.5)), axis=0)
random_gauge_el = pygsti.models.gaugegroup.TPDiagGaugeGroupElement(random_tp_op) # why not TPGaugeGroupElement
mdl2.transform_inplace(random_gauge_el)
mdl2.convert_members_inplace(model_type, ideal_model=target_model) #mdl2.set_all_parameterizations(model_type)
# categories_to_convert='ops',
#print(mdl2.strdiff(model)) #DEBUG
#DEBUG
#cmp_egs = base_model.errorgen_coefficients()
#for lbl, coeffs in mdl2.errorgen_coefficients().items():
# print(lbl)
# coeffs_cmp = cmp_egs[lbl]
# for eglbl, val in coeffs.items():
# if abs(coeffs_cmp[eglbl] - val) > 1e-8:
# print(eglbl, coeffs_cmp[eglbl], val)
# print("\n")
mdl2.setup_fogi(gauge_basis, None, None,
reparameterize=reparam, dependent_fogi_action='drop', include_spam=include_spam)
#labels2 = mdl2.fogi_errorgen_component_labels(include_fogv, typ='normal')
#raw_labels2 = mdl2.fogi_errorgen_component_labels(include_fogv, typ='raw')
#coeffs2 = mdl2.fogi_errorgen_components_array(include_fogv)
#print("\n".join(["%d: %s = << %s >> = %g" % (i,lbl,raw,coeff)
# for i,(lbl,raw,coeff) in enumerate(zip(labels2, raw_labels2, coeffs2))]))
return mdl2.fogi_errorgen_components_array(include_fogv=True, normalized_elem_gens=reparam)
def generate_small_gauge_transform_data(base_model, target_model, model_type, gauge_basis,
nFOGI, xvals, base_data, num_samples_per_gauge_mag=10,
include_spam=True, reparam=True):
ys_fogi = []; yerrs_fogi = []
ys_fogv = []; yerrs_fogv = []
for gaugemag in xvals:
print(" --- Gauge mag ", gaugemag, '---')
vals_fogi = []; vals_fogv = []
for k in range(num_samples_per_gauge_mag):
try:
ar_cmp = do_small_gauge_transform(base_model, target_model, model_type, gauge_basis, gaugemag,
include_spam, reparam)
ar_fogi_cmp = ar_cmp[0:nFOGI]
ar_fogv_cmp = ar_cmp[nFOGI:]
v_fogi = np.linalg.norm(base_data[0:nFOGI] - ar_fogi_cmp) / ar_fogi_cmp.size
v_fogv = np.linalg.norm(base_data[nFOGI:] - ar_fogv_cmp) / ar_fogv_cmp.size
print(" diffs: FOGI", v_fogi, ", FOGV", v_fogv)
vals_fogi.append(v_fogi)
vals_fogv.append(v_fogv)
except:
print(" FAIL")
print("")
ys_fogi.append(np.mean(vals_fogi))
yerrs_fogi.append(np.std(vals_fogi))
ys_fogv.append(np.mean(vals_fogv))
yerrs_fogv.append(np.std(vals_fogv))
return ys_fogi, yerrs_fogi, ys_fogv, yerrs_fogv
class FOGIisFOGITestCase(BaseTestCase):
def test_std_fogi_is_fogi(self):
model_type = "GLND"
errgen_types = ('H', 'S', 'C', 'A')
model = std.target_model(model_type)
target_model = std.target_model('static')
#basis = Basis.cast('pp', model.dim)
basis1q = Basis.cast('pp', 4)
gauge_basis = CompleteElementaryErrorgenBasis(
basis1q, model.state_space, elementary_errorgen_types=errgen_types)
reparam = False
include_spam = False # TODO - figure out why setting == True seems to lessen FOGI vs FOGV effect.
op_abbrevs = {(): 'I',
('Gxpi2', 0): 'Gx',
('Gypi2', 0): 'Gy',
('Gzpi2', 0): 'Gz'}
model.setup_fogi(gauge_basis, None, op_abbrevs if model.dim == 4 else None,
reparameterize=reparam, dependent_fogi_action='drop', include_spam=include_spam)
# Initialize random FOGI error rates
base_model_error_strength = 1e-4
np.random.seed(100)
ar = model.fogi_errorgen_components_array(include_fogv=False, normalized_elem_gens=reparam)
ar = base_model_error_strength * (np.random.rand(len(ar)) - 0.5)
model.set_fogi_errorgen_components_array(ar, include_fogv=False, normalized_elem_gens=reparam)
nFOGI = len(ar)
all_ar = model.fogi_errorgen_components_array(include_fogv=True, normalized_elem_gens=reparam)
#Print FOGI error rates
#labels = model.fogi_errorgen_component_labels(include_fogv=False, typ='normal')
#raw_labels = model.fogi_errorgen_component_labels(include_fogv=False, typ='raw')
#coeffs = model.fogi_errorgen_components_array(include_fogv=False)
#print("\n".join(["%d: %s = << %s >> = %g" % (i,lbl,raw,coeff)
# for i,(lbl,raw,coeff) in enumerate(zip(labels, raw_labels, coeffs))]))
gauge_mag=0.01
ar_cmp = do_small_gauge_transform(model, target_model, model_type, gauge_basis, gauge_mag,
include_spam=include_spam, reparam=reparam)
ar_fogi_cmp = ar_cmp[0:nFOGI]
ar_fogv_cmp = ar_cmp[nFOGI:]
fogi_diff = np.linalg.norm(all_ar[0:nFOGI] - ar_fogi_cmp)
fogv_diff = np.linalg.norm(all_ar[nFOGI:] - ar_fogv_cmp)
print("Gauge mag = ", gauge_mag)
print("FOGI diff = ", fogi_diff)
print("FOGV diff = ", fogv_diff)
self.assertLess(fogv_diff, 5 * gauge_mag)
self.assertGreater(fogv_diff, 0.2 * gauge_mag)
self.assertLess(fogi_diff, 5 * gauge_mag**2)
#xs = np.logspace(-4, -1, 10)
#ys, yerrs, _, _ = generate_small_gauge_transform_data(model, xs, ar, 10)
class FOGIGSTTestCase(object):
def test_fogi_gst(self):
#create_model
mdl = self.create_model()
mdl_no_fogi = mdl.copy()
print(mdl.num_params, 'parameters')
# Perform FOGI analysis
reparam = True
basis1q = Basis.cast('pp', 4)
gauge_basis = CompleteElementaryErrorgenBasis(
basis1q, mdl.state_space, elementary_errorgen_types='HS')
mdl.setup_fogi(gauge_basis, None, None, reparameterize=reparam, dependent_fogi_action='drop', include_spam=True)
#Create edesign
use_std_edesign = True
if use_std_edesign:
# create standard GST experiment design & data
edesign = std.create_gst_experiment_design(1)
else:
pspec = self.create_pspec()
circuits = pygsti.circuits.create_cloudnoise_circuits(
pspec, [1,], [(), ('Gxpi2',), ('Gypi2',), ('Gxpi2','Gxpi2')],
max_idle_weight=0, extra_gate_weight=1, maxhops=1)
print(len(circuits))
edesign = pygsti.protocols.GSTDesign(pspec, circuits)
#Generate data
mdl_datagen = mdl.copy()
ar = mdl_datagen.fogi_errorgen_components_array(include_fogv=False, normalized_elem_gens=True)
np.random.seed(1234)
ar = 0.001 * np.random.rand(len(ar))
mdl_datagen.set_fogi_errorgen_components_array(ar, include_fogv=False, normalized_elem_gens=True)
ds = pygsti.data.simulate_data(mdl_datagen, edesign, 1000, seed=2022) #, sample_error='none')
data = pygsti.protocols.ProtocolData(edesign, ds)
datagen_2dlogl = pygsti.tools.two_delta_logl(mdl_datagen, ds)
print("Datagen 2dlogl = ", datagen_2dlogl)
#Run GST without FOGI setup
sim_type = 'matrix'
gst_mdl = self.create_model()
print("Before FOGI reparam, Np = ", gst_mdl.num_params)
gst_mdl.sim = sim_type
proto = pygsti.protocols.GST(gst_mdl, gaugeopt_suite=None, optimizer={'maxiter': 100, 'tol': 1e-7}, verbosity=3)
results_before = proto.run(data)
#Run GST *with* FOGI setup
gst_mdl = self.create_model()
basis1q = pygsti.baseobjs.Basis.cast('pp', 4)
gauge_basis = pygsti.baseobjs.CompleteElementaryErrorgenBasis(
basis1q, gst_mdl.state_space, elementary_errorgen_types='HS')
gst_mdl.setup_fogi(gauge_basis, None, None, reparameterize=True,
dependent_fogi_action='drop', include_spam=True)
print("After FOGI reparam, Np = ", gst_mdl.num_params)
gst_mdl.sim = sim_type
proto = pygsti.protocols.GST(gst_mdl, gaugeopt_suite=None, optimizer={'maxiter': 100, 'tol': 1e-7}, verbosity=3)
results_after = proto.run(data)
#Compute hessian at MLE point for both estimates
gaugeopt_suite = "final iteration estimate"
#hessian_projection = 'none' # because we don't relly need it
#'intrinsic error' #'optimal gate CIs' # 'std'
results_before.estimates['GateSetTomography'].models[gaugeopt_suite].sim = sim_type
# pygsti.forwardsims.MatrixForwardSimulator(param_blk_sizes=(4,4))
results_after.estimates['GateSetTomography'].models[gaugeopt_suite].sim = sim_type
# pygsti.forwardsims.MatrixForwardSimulator(param_blk_sizes=(4,4))
crfact = results_before.estimates['GateSetTomography'].add_confidence_region_factory(gaugeopt_suite, 'final')
crfact.compute_hessian()
#crfact.project_hessian(hessian_projection)
crfact = results_after.estimates['GateSetTomography'].add_confidence_region_factory(gaugeopt_suite, 'final')
crfact.compute_hessian()
#crfact.project_hessian(hessian_projection)
def get_hessian_spectrum_and_gauge_param_count(estimate, model_key='stdgaugeopt'):
executed_circuits = estimate.parent.circuit_lists['final']
crf = estimate.confidence_region_factories[(model_key, 'final')]
hessian = crf.hessian
print(hessian.shape)
mdl = estimate.models[model_key]
hessian_eigs = np.linalg.eigvals(hessian)
return hessian_eigs, 0 #mdl.num_gauge_params
hessian_eigs_before, ngauge_before = get_hessian_spectrum_and_gauge_param_count(
results_before.estimates['GateSetTomography'], gaugeopt_suite)
hessian_eigs_after, ngauge_after = get_hessian_spectrum_and_gauge_param_count(
results_after.estimates['GateSetTomography'], gaugeopt_suite)
make_plot = False
if make_plot: # make a plot comparing the FOGI-parameterized vs non-FOGI-parameterized (normal) Hessian spectra
import matplotlib.pyplot as plt
#%matplotlib inline
#ngauge_before = 12 # HARCODE because pygsti gets this wrong
fig = plt.figure(figsize=(12,12))
plt.title("Hessian spectrum at MLE point (found by GST)")
plt.xlabel("Index into sorted eigenvalues, 0 == num_gauge_params ($N_g$)")
plt.ylabel("Absolute value of eigenvalue")
plt.yscale('log')
plt.plot(np.arange(len(hessian_eigs_before)) - ngauge_before, sorted(np.abs(hessian_eigs_before)),
label='GLND parameterization, $N_g = %d$' % (ngauge_before), marker='.')
plt.plot(np.arange(len(hessian_eigs_after)) - ngauge_after, sorted(np.abs(hessian_eigs_after)),
label='FOGI(GLND) parameterization, $N_g = %d$' % (ngauge_after), marker='.')
plt.axvline(x=0, color='k', linestyle=':')
#plt.axvline(x=12, color='k', linestyle=':')
#plt.axvline(x=29, color='k', linestyle=':')
#plt.axvline(x=20, color='g', linestyle=':')
#num_stochastic = 3 * 9
#plt.axvline(x=num_stochastic, color='r', linestyle=':')
#plt.axvline(x=8 - ngauge_CPTP, color='r', linestyle=':')
#num_spam_gauge = 17
#plt.axvline(x=num_spam_gauge - ngauge_CPTP, color='y', linestyle=':')
plt.legend()
plt.grid(color='gray', linestyle='-', linewidth=0.5)
class CrosstalkFreeFOGIGSTTester(FOGIGSTTestCase, BaseTestCase):
def create_pspec(self):
nQubits = 2
#pspec = pygsti.processors.QubitProcessorSpec(nQubits, ['Gxpi2', 'Gypi2', 'Gi'], geometry='line')
#availability={'Gcnot': [(0,1)]}, # to match smq2Q_XYCNOT
pspec = pygsti.processors.QubitProcessorSpec(nQubits, ['Gxpi2', 'Gypi2', 'Gcnot'],
availability={'Gcnot': [(0,1)]}, geometry='line')
return pspec
def create_model(self):
pspec = self.create_pspec()
return create_crosstalk_free_model(pspec, ideal_gate_type='H+s', independent_gates=True,
implicit_idle_mode='only_global')
#If we enable this, it causes above class to fail (???!) with an Arpack error. These should be independent,
# so something very strange is going on here. Don't have time to debug now, so just disabling this test.
#class CloudCrosstalkFOGIGSTTester(FOGIGSTTestCase, BaseTestCase):
# def create_pspec(self):
# nQubits = 1
# pspec = pygsti.processors.QubitProcessorSpec(nQubits, ['Gxpi2', 'Gypi2', 'Gi' ], # 'Gcnot'
# #availability={'Gcnot': [(0,1)]}, # to match smq2Q_XYCNOT
# geometry='line')
# return pspec
#
# def create_model(self):
# pspec = self.create_pspec()
# return pygsti.models.create_cloud_crosstalk_model_from_hops_and_weights(
# pspec, max_idle_weight=1, max_spam_weight=2, extra_gate_weight=1, maxhops=1,
# gate_type='H+s', spam_type='H+s', connected_highweight_errors=False,
# implicit_idle_mode='only_global')
def build_debug_plot1(model, nFOGI, reparam):
# ## TEST 1: FOGI errors
# Target is perturbed by FOGI errors and the effect of small gauge transforms on the noisy model is studied.
from matplotlib import pyplot as plt
np.random.seed(123456)
xs = np.logspace(-4, -1, 10)
basemdl = model.copy()
num_samples_per_gauge_mag = 10
ys_fogi_dict = {}; yerr_fogi_dict = {}
ys_fogv_dict = {}; yerr_fogv_dict = {}
for base_err_strength in [1e-4, 1e-3, 1e-2, 1e-1]:
print("******* Computing for base-model error strength %g *******" % base_err_strength)
#include_fogv = False # needed to just compare FOGI (and not gauge)
#ar = basemdl.fogi_errorgen_components_array(include_fogv=True, normalized_elem_gens=reparam)
ar_fogi = base_err_strength * (np.random.rand(nFOGI) - 0.5)
basemdl.set_fogi_errorgen_components_array(ar_fogi, include_fogv=False, normalized_elem_gens=reparam)
base_data = basemdl.fogi_errorgen_components_array(include_fogv=True, normalized_elem_gens=reparam)
ys_fogi, yerrs_fogi, ys_fogv, yerrs_fogv = generate_small_gauge_transform_data(basemdl, xs, base_data,
num_samples_per_gauge_mag)
ys_fogi_dict[base_err_strength] = ys_fogi
yerr_fogi_dict[base_err_strength] = yerrs_fogi
ys_fogv_dict[base_err_strength] = ys_fogv
yerr_fogv_dict[base_err_strength] = yerrs_fogv
plt.figure(figsize=(9, 9))
plt.plot(xs, [x**2 for x in xs], linestyle='--', color='k', label='x**2 (for reference)')
plt.plot(xs, xs, linestyle=':', color='k', label='x (for reference)')
plt.yscale('log')
plt.xscale('log')
plt.title('How much do gauge transformations affect FOGI quantities?\n(are they really FOGI?) samples-per-point = %d'
% num_samples_per_gauge_mag,
size=14)
plt.xlabel("Gauge transform strength (avg. mag. of element in T)", size=14)
plt.ylabel("Avg change in a FOGI error rate", size=14)
plt.xticks(size=13)
plt.yticks(size=13)
for base_err_strength in [1e-4, 1e-3, 1e-2, 1e-1]:
ebc = plt.errorbar(xs, ys_fogi_dict[base_err_strength], yerr=yerr_fogi_dict[base_err_strength], marker='o',
label='base err %g' % base_err_strength)
plt.errorbar(xs, ys_fogv_dict[base_err_strength], yerr=yerr_fogv_dict[base_err_strength],
color=ebc.lines[0].get_color(), marker='o', linestyle=':', label=None)
plt.legend(fontsize=13)
def build_debug_plot2(model, reparam):
# ## TEST 2: general errors
# Target is perturbed by generic errors, then the effect of small gauge transforms on the noisy model is studied.
from matplotlib import pyplot as plt
np.random.seed(123456)
xs = np.logspace(-4, -1, 10)
basemdl = model.copy()
num_samples_per_gauge_mag = 10
ys_fogi_dict = {}; yerr_fogi_dict = {}
ys_fogv_dict = {}; yerr_fogv_dict = {}
for base_err_strength in [1e-4, 1e-3, 1e-2, 1e-1]:
print("******* Computing for base-model error strength %g *******" % base_err_strength)
#include_fogv = False # needed to just compare FOGI (and not gauge)
ar = basemdl.fogi_errorgen_components_array(include_fogv=True, normalized_elem_gens=reparam)
ar_fogi = base_err_strength * (np.random.rand(len(ar)) - 0.5)
basemdl.set_fogi_errorgen_components_array(ar_fogi, include_fogv=True, normalized_elem_gens=reparam)
base_data = basemdl.fogi_errorgen_components_array(include_fogv=True, normalized_elem_gens=reparam)
ys_fogi, yerrs_fogi, ys_fogv, yerrs_fogv = generate_small_gauge_transform_data(basemdl, xs, base_data,
num_samples_per_gauge_mag)
ys_fogi_dict[base_err_strength] = ys_fogi
yerr_fogi_dict[base_err_strength] = yerrs_fogi
ys_fogv_dict[base_err_strength] = ys_fogv
yerr_fogv_dict[base_err_strength] = yerrs_fogv
plt.figure(figsize=(9, 9))
plt.plot(xs, [x**2 for x in xs], linestyle='--', color='k', label='x**2 (for reference)')
plt.plot(xs, xs, linestyle=':', color='k', label='x (for reference)')
plt.yscale('log')
plt.xscale('log')
plt.title('How much do gauge transformations affect FOGI quantities?\n(are they really FOGI?) samples-per-point = %d'
% num_samples_per_gauge_mag,
size=14)
plt.xlabel("Gauge transform strength (avg. mag. of element in T)", size=14)
plt.ylabel("Avg change in a FOGI error rate", size=14)
plt.xticks(size=13)
plt.yticks(size=13)
for base_err_strength in [1e-4, 1e-3, 1e-2, 1e-1]:
ebc = plt.errorbar(xs, ys_fogi_dict[base_err_strength], yerr=yerr_fogi_dict[base_err_strength], marker='o',
label='base err %g' % base_err_strength)
plt.errorbar(xs, ys_fogv_dict[base_err_strength], yerr=yerr_fogv_dict[base_err_strength],
color=ebc.lines[0].get_color(), marker='o', linestyle=':', label=None)
plt.legend(fontsize=13)