/
idtcore.py
1424 lines (1172 loc) · 62.2 KB
/
idtcore.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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
""" Core Idle Tomography routines """
import collections as _collections
import itertools as _itertools
import time as _time
import warnings as _warnings
import numpy as _np
from . import idttools as _idttools
from . import pauliobjs as _pobjs
from .idtresults import IdleTomographyResults as _IdleTomographyResults
from ... import baseobjs as _baseobjs
from ... import models as _models
from ... import tools as _tools
from ...models import modelconstruction as _modelconstruction
from ...modelmembers import states as _state
from ...modelmembers import operations as _op
from ...baseobjs.verbosityprinter import VerbosityPrinter as _VerbosityPrinter
from ...circuits.circuit import Circuit as _Circuit
# This module implements idle tomography, which deals only with
# many-qubit idle gates (on some number of qubits) and single-
# qubit gates (or tensor products of them) used to fiducials.
# As such, it is conventient to represent operations as native
# Python strings, where there is one I,X,Y, or Z letter per
# qubit.
def hamiltonian_jac_element(prep, error, observable):
"""
Computes the Jacobian matrix element for a Hamiltonian error: how the
expectation value of `observable` in state `prep` changes due to
Hamiltonian `error`.
Parameters
----------
prep : NQPauliState
The state that is prepared.
error : NQPauliOp
The type (as a pauli operator) of Hamiltonian error.
observable : NQPauliOp
The observable whose expectation value is measured.
Note: giving a NQPauliState will be treated as an
N-qubit Pauli operator whose sign is the product of
the signs of the NQPauliState's per-qubit basis signs.
Returns
-------
float
"""
# dp/deps where p = eps * i * Tr(Obs (Err*rho - rho*Err)) = eps * i * ( Tr(Obs Err rho) - Tr(Obs rho Err))
# = eps * i * Tr([Obs,Err] * rho) so dp/deps just drops eps factor
com = error.icommutator_over_2(observable)
return 0 if (com is None) else com.statedot(prep)
def stochastic_outcome(prep, error, meas):
"""
Computes the "expected" outcome when the stochastic error `error`
occurs between preparing in `prep` and measuring in basis `meas`.
Note: currently, the preparation and measurement bases must be the
same (up to signs) or an AssertionError is raised. (If they're not,
there isn't a single expected outcome).
Parameters
----------
prep : NQPauliState
The state that is prepared.
error : NQPauliOp
The type (as a pauli operator) of Stochastic error.
meas : NQPauliState
The basis which is measured. The 'signs' of the basis
Paulis determine which state is measured as a '0' vs. a '1'.
(essentially the POVM.)
Returns
-------
NQOutcome
"""
# We can consider each qubit separately, since Tr(A x B) = Tr(A)Tr(B).
# If for the i-th qubit the prep basis is s1*P and the meas basis is s2*P
# (s1 and s2 are the signs -- either +1 or -1 -- and P is the common
# Pauli whose eigenstates 1. form the measurement basis and 2. contain the
# state prep), then we're trying to sell which of:
# Tr( (I+s2*P) Err (I+s1*P) ) ['+' or '0' outcome] OR
# Tr( (I-s2*P) Err (I+s1*P) ) ['-' or '1' outcome] is nonzero.
# Combining these two via use of '+-' and expanding gives:
# Tr( Err + s1* Err P +- s2* P Err +- s1*s2* P Err P )
# assuming Err != I so Tr(Err) = 0 and Tr(P Err P) = 0 (b/c P either
# commutes or anticommutes w/Err and P^2 == I) =>
# Tr( s1* Err P +- s2* P Err )
# if [Err,P] = 0, then the '+'/'0' branch is nonzero when s1==s2
# and the '-'/'1' branch is nonzero when s1!=s2
# if {Err,P} = 0, then the opposite is true: '+'/'0' branch is nonzero
# when s1!=s2, etc.
# Takeaway: if basis (P) commutes with Err then outcome is '0' if s1==s2, "1" otherwise ...
outcome_str = ""
for s1, P1, s2, P2, Err in zip(prep.signs, prep.rep, meas.signs, meas.rep, error.rep):
assert(P1 == P2), "Stochastic outcomes must prep & measure along same bases!"
P = P1 # ( = P2)
if _pobjs._commute_parity(P, Err) == 1: # commutes: [P,Err] == 0
outcome_str += "0" if (s1 == s2) else "1"
else: # anticommutes: {P,Err} == 0
outcome_str += "1" if (s1 == s2) else "0"
return _pobjs.NQOutcome(outcome_str)
# Now we can define the functions that do the real work for stochastic tomography.
# StochasticMatrixElement() computes the derivative of the probability of "Outcome" with respect
# to the rate of "Error" if the N-qubit Pauli basis defined by "PrepMeas" is prepped and measured.
def stochastic_jac_element(prep, error, meas, outcome):
"""
Computes the Jacobian matrix element for a Stochastic error: how the
probability of `outcome` changes with respect to the rate of `error`
when preparing state `prep` and measuring in basis `meas`.
Parameters
----------
prep : NQPauliState
The state that is prepared.
error : NQPauliOp
The type (as a pauli operator) of Stochastic error.
meas : NQPauliState
The basis that is measured (essentially the POVM).
outcome : NQOutcome
The measurement outcome that is considered.
Returns
-------
float
"""
return 1 if (stochastic_outcome(prep, error, meas) == outcome) else 0
def affine_jac_element(prep, error, meas, outcome):
"""
Computes the Jacobian matrix element for a Affine error: how the
probability of `outcome` changes with respect to the rate of `error`
when preparing state `prep` and measuring in basis `meas`.
Note: Affine error maps leave qubits corresponging to I's in
`error` alone. An affine error is defined as replacing
portions of the density matrix corresponding to *non-trivial*
Pauli operators with those operators.
Parameters
----------
prep : NQPauliState
The state that is prepared.
error : NQPauliOp
The type (as a pauli operator) of Affine error.
meas : NQPauliState
The basis that is measured (essentially the POVM).
outcome : NQOutcome
The measurement outcome that is considered.
Returns
-------
float
"""
# Note an error of 'ZI' does *not* mean the "ZI affine error":
# rho -> (Id[rho] + eps*AffZI[rho]) = rho + eps*ZI
# where ZI = diag(1,1,-1,-1), so this adds prob to 00 and 01 and removes from 10 and 11.
# Instead it means the map AffZ x Id where AffZ : rho -> rho + eps Z and Id : rho -> rho.
def _affhelper(prep_sign, prep_basis, error_pauli, meas_sign, meas_basis, outcome_bit):
"""
Answers this question:
If a qubit is prepped in state (prep_sign,prep_basis) & measured
using POVM (meas_sign,meas_basis), and experiences an affine error given
(at this qubit) by Pauli "error_pauli", then at what rate does that change probability of outcome "bit"?
This is going to get multiplied over all qubits. A zero indicates that the affine error is orthogonal
to the measurement basis, which means the probability of *all* outcomes including this bit are unaffected.
Returns 0, +1, or -1.
"""
# Specifically, this computes Tr( (I+/-P) AffErr[ (I+/-P) ] ) where the two
# P's represent the prep & measure bases (and can be different). Here AffErr
# outputs ErrP if ErrP != 'I', otherwise it's just the identity map (see above).
#
# Thus, when ErrP != 'I', we have Tr( (I+/-P) ErrP ) which equals 0 whenever
# ErrP != P and +/-1 if ErrP == P. The sign equals meas_sign when outcome_bit == "0",
# and is reversed when it == "1".
# When ErrP == 'I', we have Tr( (I+/-P) (I+/-P) ) = Tr( I + sign*I)
# = 1 where sign = prep_sign*meas_sign when outcome == "0" and -1 times
# this when == "1".
# = 0 otherwise
assert(prep_basis in ("X", "Y", "Z")) # 'I', for instance, is invalid
assert(meas_basis in ("X", "Y", "Z")) # 'I', for instance, is invalid
assert(prep_basis == meas_basis) # always true
outsign = 1 if (outcome_bit == "0") else -1 # b/c we often just flip a sign when == "1"
# i.e. the sign used in I+/-P for measuring is meas_sign * outsign
if error_pauli == 'I': # special case: no affine action on this space
if prep_basis == meas_basis:
return 1 if (prep_sign * meas_sign * outsign == 1) else 0
else: return 1 # bases don't match
if meas_basis != error_pauli: # then they don't commute (b/c neither can be 'I')
return 0 # so there's no change along this axis (see docstring)
else: # meas_basis == error_pauli != 'I'
if outcome_bit == "0": return meas_sign
else: return meas_sign * -1
return _np.prod([_affhelper(s1, P1, Err, s2, P2, o) for s1, P1, s2, P2, Err, o
in zip(prep.signs, prep.rep, meas.signs, meas.rep,
error.rep, outcome.rep)])
def affine_jac_obs_element(prep, error, observable):
"""
Computes the Jacobian matrix element for a Affine error: how the
expectation value of `observable` changes with respect to the rate of
`error` when preparing state `prep`.
Note: Affine error maps leave qubits corresponging to I's in
`error` alone. An affine error is defined as replacing
portions of the density matrix corresponding to *non-trivial*
Pauli operators with those operators.
Parameters
----------
prep : NQPauliState
The state that is prepared.
error : NQPauliOp
The type (as a pauli operator) of Affine error.
observable : NQPauliOp
The observable whose expectation value is measured.
Returns
-------
float
"""
# Computes the Jacobian element of Tr(observable * error * prep) with basis
# convention given by `meas` (dictates sign of outcome).
# (observable should be equal to meas when it's not equal to 'I', up to sign)
# Note: as in affine_jac_element, 'I's in error mean that this affine error
# doesn't act (acts as the identity) on that qubit.
def _affhelper(prep_sign, prep_basis, error_pauli, obs_pauli):
assert(prep_basis in ("X", "Y", "Z")) # 'I', for instance, is invalid
# want Tr(obs_pauli * AffErr[ I+/-P ] ). There are several cases:
# 1) if obs_pauli == 'I':
# - if error_pauli == 'I' (so AffErr = Id), Tr(I +/- P) == 1 always
# - if error_pauli != 'I', Tr(ErrP) == 0 since ErrP != 'I'
# 2) if obs_pauli != 'I' (so Tr(obs_pauli) == 0)
# - if error_pauli == 'I', Tr(obs_pauli * (I +/- P)) = prep_sign if (obs_pauli == prep_basis) else 0
# - if error_pauli != 'I', Tr(obs_pauli * error_pauli) = 1 if (obs_pauli == error_pauli) else 0
# (and actually this counts at 2 instead of 1 b/c obs isn't normalized (I think?))
if obs_pauli == 'I':
return 1 if (error_pauli == 'I') else 0
elif error_pauli == 'I':
return prep_sign if (prep_basis == obs_pauli) else 0
else:
return 2 if (obs_pauli == error_pauli) else 0
return _np.prod([_affhelper(s1, P1, Err, o) for s1, P1, Err, o
in zip(prep.signs, prep.rep, error.rep, observable.rep)])
# -----------------------------------------------------------------------------
# Experiment generation:
# -----------------------------------------------------------------------------
def idle_tomography_fidpairs(nqubits, maxweight=2, include_hamiltonian=True,
include_stochastic=True, include_affine=True,
ham_tmpl="auto",
preferred_prep_basis_signs=("+", "+", "+"),
preferred_meas_basis_signs=("+", "+", "+")):
"""
Construct a list of Pauli-basis fiducial pairs for idle tomography.
This function constructs the "standard" set of fiducial pairs used
to generate idle tomography sequences which probe Hamiltonian,
Stochastic, and/or Affine errors in an idle gate.
Parameters
----------
nqubits : int
The number of qubits.
maxweight : int, optional
The maximum weight of errors to consider.
include_hamiltonian, include_stochastic, include_affine : bool, optional
Whether to include fiducial pairs for finding Hamiltonian-, Stochastic-,
and Affine-type errors.
ham_tmpl : tuple, optional
A tuple of length-`maxweight` Pauli strings (i.e. string w/letters "X",
"Y", or "Z"), describing how to construct the fiducial pairs used to
detect Hamiltonian errors. The special (and default) value "auto"
uses `("X","Y","Z")` and `("ZY","ZX","XZ","YZ","YX","XY")` for
`maxweight` equal to 1 and 2, repectively, and will generate an error
if `maxweight > 2`.
preferred_prep_basis_signs, preferred_meas_basis_signs: tuple, optional
A 3-tuple of "+" or "-" strings indicating which sign for preparing
or measuring in the X, Y, and Z bases is preferable. Usually one
orientation if preferred because it's easier to achieve using the
native model.
Returns
-------
list
a list of (prep,meas) 2-tuples of NQPauliState objects, each of
length `nqubits`, representing the fiducial pairs.
"""
fidpairs = [] # list of 2-tuples of NQPauliState objects to return
#convert +'s and -'s to dictionaries of +/-1 used later:
def conv(x): return 1 if x == "+" else -1
base_prep_signs = {l: conv(s) for l, s in zip(('X', 'Y', 'Z'), preferred_prep_basis_signs)}
base_meas_signs = {l: conv(s) for l, s in zip(('X', 'Y', 'Z'), preferred_meas_basis_signs)}
#these dicts give the preferred sign for prepping or measuring along each 1Q axis.
if include_stochastic:
if include_affine:
# in general there are 2^maxweight different permutations of +/- signs
# in maxweight==1 case, need 2 of 2 permutations
# in maxweight==2 case, need 3 of 4 permutations
# higher maxweight?
if maxweight == 1:
flips = [(1,), (-1,)] # consider both cases of not-flipping & flipping the preferred basis signs
elif maxweight == 2:
flips = [(1, 1), # don't flip anything
(1, -1), (-1, 1)] # flip 2nd or 1st pauli basis (weight = 2)
else:
raise NotImplementedError("No implementation for affine errors and maxweight > 2!")
#need to do more work to figure out how to generalize this to maxweight > 2
else:
flips = [(1,) * maxweight] # don't flip anything
#Build up "template" of 2-tuples of NQPauliState objects acting on
# maxweight qubits that should be tiled to full fiducial pairs.
sto_tmpl_pairs = []
for fliptup in flips: # elements of flips must have length=maxweight
# Create a set of "template" fiducial pairs using the current flips
for basisLets in _itertools.product(('X', 'Y', 'Z'), repeat=maxweight):
# flip base (preferred) basis signs as instructed by fliptup
prep_signs = [f * base_prep_signs[l] for f, l in zip(fliptup, basisLets)]
meas_signs = [f * base_meas_signs[l] for f, l in zip(fliptup, basisLets)]
sto_tmpl_pairs.append((_pobjs.NQPauliState(''.join(basisLets), prep_signs),
_pobjs.NQPauliState(''.join(basisLets), meas_signs)))
fidpairs.extend(_idttools.tile_pauli_fidpairs(sto_tmpl_pairs, nqubits, maxweight))
elif include_affine:
raise ValueError("Cannot include affine sequences without also including stochastic ones!")
if include_hamiltonian:
nextPauli = {"X": "Y", "Y": "Z", "Z": "X"}
prevPauli = {"X": "Z", "Y": "X", "Z": "Y"}
def prev(expt): return ''.join([prevPauli[p] for p in expt])
def next(expt): return ''.join([nextPauli[p] for p in expt])
if ham_tmpl == "auto":
if maxweight == 1: ham_tmpl = ("X", "Y", "Z")
elif maxweight == 2: ham_tmpl = ("ZY", "ZX", "XZ", "YZ", "YX", "XY")
else: raise ValueError("Must supply `ham_tmpl` when `maxweight > 2`!")
ham_tmpl_pairs = []
for tmplLets in ham_tmpl: # "Lets" = "letters", i.e. 'X', 'Y', or 'Z'
assert(len(tmplLets) == maxweight), \
"Hamiltonian 'template' strings must have length == maxweight: len(%s) != %d!" % (tmplLets, maxweight)
prepLets, measLets = prev(tmplLets), next(tmplLets)
# basis sign doesn't matter for hamiltonian terms,
# so just use preferred signs
prep_signs = [base_prep_signs[l] for l in prepLets]
meas_signs = [base_meas_signs[l] for l in measLets]
ham_tmpl_pairs.append((_pobjs.NQPauliState(prepLets, prep_signs),
_pobjs.NQPauliState(measLets, meas_signs)))
fidpairs.extend(_idttools.tile_pauli_fidpairs(ham_tmpl_pairs, nqubits, maxweight))
return fidpairs
def preferred_signs_from_paulidict(pauli_basis_dict):
"""
Infers what the preferred basis signs are based on the length of gate-name
strings in `pauli_basis_dict` (shorter strings are preferred).
Parameters
----------
pauli_basis_dict : dict
A dictionary w/keys like `"+X"` or `"-Y"` and values that
are tuples of gate *names* (not labels, which include qubit or
other state-space designations), e.g. `("Gx","Gx")`.
Returns
-------
tuple
A 3-tuple of elements in {"+", "-"}, exactly the format expected
by `preferred_*_basis_signs` arguments of
:function:`idle_tomography_fidpairs`.
"""
preferred_signs = ()
for let in ('X', 'Y', 'Z'):
if "+" + let in pauli_basis_dict: plusKey = "+" + let
elif let in pauli_basis_dict: plusKey = let
else: plusKey = None
if "-" + let in pauli_basis_dict: minusKey = '-' + let
else: minusKey = None
if minusKey and plusKey:
if len(pauli_basis_dict[plusKey]) <= len(pauli_basis_dict[minusKey]):
preferred_sign = '+'
else:
preferred_sign = '-'
elif plusKey:
preferred_sign = '+'
elif minusKey:
preferred_sign = '-'
else:
raise ValueError("No entry for %s-basis!" % let)
preferred_signs += (preferred_sign,)
return preferred_signs
def fidpairs_to_pauli_fidpairs(fidpairs_list, pauli_basis_dicts, nqubits):
"""
Translate :class:`GatesString`-type fiducial pairs to
:class:`NQPauliState`-type "Pauli fiducial pairs" using `pauli_basis_dicts`.
Parameters
----------
fidpairs_list : list
A list whose elements are 2-tuples of :class:`Circuit` objects.
pauli_basis_dicts : tuple
A `(prepPauliBasisDict,measPauliBasisDict)` tuple of dictionaries
specifying the way to prepare and measure in Pauli bases. See
:function:`preferred_signs_from_paulidict` for details on each
dictionary's format.
nqubits : int
The number of qubits. Needed because :class:`Circuit`
objects don't contain this information.
Returns
-------
list
A list of 2-tuples of :class:`NQPauliState` objects.
"""
#Example dicts:
#prepDict = { 'X': ('Gy',), 'Y': ('Gx',)*3, 'Z': (),
# '-X': ('Gy',)*3, '-Y': ('Gx',), '-Z': ('Gx','Gx')}
#measDict = { 'X': ('Gy',)*3, 'Y': ('Gx',), 'Z': (),
# '-X': ('Gy',), '-Y': ('Gx',)*3, '-Z': ('Gx','Gx')}
prepDict, measDict = pauli_basis_dicts
for k, v in prepDict.items():
assert(k[-1] in ('X', 'Y', 'Z') and isinstance(v, tuple)), \
"Invalid prep pauli dict format!"
for k, v in measDict.items():
assert(k[-1] in ('X', 'Y', 'Z') and isinstance(v, tuple)), \
"Invalid measuse pauli dict format!"
rev_prepDict = {v: k for k, v in prepDict.items()}
rev_measDict = {v: k for k, v in measDict.items()}
def convert(opstr, rev_pauli_dict):
#Get gatenames_per_qubit (keys = sslbls, vals = lists of gatenames)
#print("DB: Converting ",opstr)
gatenames_per_qubit = _collections.defaultdict(list)
for glbl in opstr:
for c in glbl.components: # in case of parallel labels
assert(len(c.sslbls) == 1)
assert(isinstance(c.sslbls[0], int))
gatenames_per_qubit[c.sslbls[0]].append(c.name)
#print("DB: gatenames_per_qubit = ",gatenames_per_qubit)
#print("DB: rev keys = ",list(rev_pauli_dict.keys()))
#Check if list of gatenames equals a known basis prep/meas:
letters = ""; signs = []
for i in range(nqubits):
basis = rev_pauli_dict.get(tuple(gatenames_per_qubit[i]), None)
#print("DB: Q%d: %s -> %s" % (i,str(gatenames_per_qubit[i]), str(basis)))
assert(basis is not None) # to indicate convert failed
letters += basis[-1] # last letter of basis should be 'X' 'Y' or 'Z'
signs.append(-1 if (basis[0] == '-') else 1)
#print("DB: SUCCESS: --> ",letters,signs)
return _pobjs.NQPauliState(letters, signs)
ret = []
for prepStr, measStr in fidpairs_list:
try:
prepPauli = convert(prepStr, rev_prepDict)
measPauli = convert(measStr, rev_measDict)
except AssertionError:
continue # skip strings we can't convert
ret.append((prepPauli, measPauli))
return ret
def determine_paulidicts(model):
"""
Intelligently determine preparation and measurement Pauli basis
dictionaries from a :class:`Model`.
The returned dictionaries are required for various parts of idle tomography,
as they bridge the native model's gates to the "Pauli basis language"
used in idle tomography.
Parameters
----------
model : Model
The model which defines the available preparation, measurement, and
operations. It is assumed that `model`'s operation are expressed
in a Pauli-product basis.
Returns
-------
pauli_basis_dicts or None
If successful, a `(prepDict,measureDict)` 2-tuple of Pauli basis
dictionaries. If unsuccessful, None.
"""
#TODO: check that basis == "pp" or something similar?
#Note: this routine just punts if model's operation labels are just strings.
model._clean_paramvec() # to ensure calls to obj.to_vector work below (setup model paramvec)
#First, check that spam is prep/meas in Z basis (just check prep for now):
try:
prepLbls = list(model.preps.keys())
prep = model.preps[prepLbls[0]] # just take the first one (usually there's only one anyway)
except AttributeError: # HACK to work w/Implicit models
prepLbls = list(model.prep_blks['layers'].keys())
prep = model.prep_blks['layers'][prepLbls[0]]
if isinstance(prep, _state.ComputationalBasisState):
if any([b != 0 for b in prep._zvals]): return None
elif isinstance(prep, _state.ComposedState):
if isinstance(prep.state_vec, _state.ComputationalBasisState):
if any([b != 0 for b in prep.state_vec._zvals]): return None
if any([abs(v) > 1e-6 for v in prep.to_vector()]): return None
else:
nqubits = int(round(_np.log2(model.dim) / 2))
cmp = _state.ComputationalBasisState([0] * nqubits, 'pp', model._evotype).to_dense()
if _np.linalg.norm(prep.to_dense() - cmp) > 1e-6: return None
def extract_action(g, cur_sslbls, ql):
""" Note: assumes cur_sslbs is just a list of labels (of first "sector"
of a real StateSpaceLabels struct) """
if isinstance(g, _op.ComposedOp):
action = _np.identity(4, 'd')
for fg in g.factorops:
action = _np.dot(extract_action(fg, cur_sslbls, ql), action)
return action
if isinstance(g, _op.EmbeddedOp):
#Note: an embedded gate need not use the *same* state space labels as the model
g_sslbls = g.state_space.tensor_product_block_labels(0)
lbls = [cur_sslbls[g_sslbls.index(locLbl)] for locLbl in g.target_labels]
# TODO: add to StateSpaceLabels functionality to make sure two are compatible, and to translate between
# them, & make sub-labels?
return extract_action(g.embedded_op, lbls, ql)
# StaticArbitraryOp, LindbladDenseOp, other gates...
if len(cur_sslbls) == 1 and cur_sslbls[0] == ql:
mx = g.to_dense()
assert(mx.shape == (4, 4))
return mx
else:
mx = g.to_dense()
if _np.linalg.norm(mx - _np.identity(g.dim, 'd')) < 1e-6:
# acts as identity on some other space - this is ok
return _np.identity(4, 'd')
else:
raise ValueError("LinearOperator acts nontrivially on a space other than that in its label!")
#Get several standard 1-qubit pi/2 rotations in Pauli basis:
pp = _baseobjs.BuiltinBasis('pp', 4)
Gx = _modelconstruction.create_operation("X(pi/2,Q0)", [('Q0',)], basis=pp,
parameterization="static").to_dense()
Gy = _modelconstruction.create_operation("Y(pi/2,Q0)", [('Q0',)], basis=pp,
parameterization="static").to_dense()
#try to find 1-qubit pi/2 rotations
found = {}
for gl in model.primitive_op_labels:
if isinstance(model, _models.ExplicitOpModel):
gate = model.operations[gl]
else:
gate = model.operation_blks['layers'][gl]
if gl.sslbls is None or len(gl.sslbls) != 1:
continue # skip gates that don't have 1Q-like labels
qubit_label = gl.sslbls[0] # the qubit this gate is supposed to act on
try:
assert(model.state_space.num_tensor_product_blocks == 1), "Assumes a single state space sector"
action_on_qubit = extract_action(gate,
model.state_space.tensor_product_block_labels(0),
qubit_label)
except ValueError:
continue # skip gates that we can't extract action from
#See if we recognize this action
# FUTURE: add more options for using other existing gates?
if _np.linalg.norm(action_on_qubit - Gx) < 1e-6:
found['Gx'] = gl.name
elif _np.linalg.norm(action_on_qubit - Gy) < 1e-6:
found['Gy'] = gl.name
if 'Gx' in found and 'Gy' in found:
Gxl = found['Gx']; Gyl = found['Gy']
prepDict = {'X': (Gyl,), 'Y': (Gxl,) * 3, 'Z': (),
'-X': (Gyl,) * 3, '-Y': (Gxl,), '-Z': (Gxl, Gxl)}
measDict = {'X': (Gyl,) * 3, 'Y': (Gxl,), 'Z': (),
'-X': (Gyl,), '-Y': (Gxl,) * 3, '-Z': (Gxl, Gxl)}
return prepDict, measDict
return None
def make_idle_tomography_list(nqubits, max_lengths, pauli_basis_dicts, maxweight=2,
idle_string=((),), include_hamiltonian=True,
include_stochastic=True, include_affine=True,
ham_tmpl="auto", preferred_prep_basis_signs="auto",
preferred_meas_basis_signs="auto"):
"""
Construct the list of experiments needed to perform idle tomography.
Parameters
----------
nqubits : int
The number of qubits.
max_lengths : list
A list of maximum germ-power lengths. Each specifies a number many times
to repeat the idle gate, and typically this is a list of the powers of
2 preceded by zero, e.g. `[0,1,2,4,16]`. The largest value in this
list should be chosen to be the maximum number of idle gates you want to
perform in a row (typically limited by performance or time constraints).
pauli_basis_dicts : tuple
A `(prepPauliBasisDict,measPauliBasisDict)` tuple of dictionaries
specifying the way to prepare and measure in Pauli bases. See
:function:`preferred_signs_from_paulidict` for details on each
dictionary's format.
maxweight : int, optional
The maximum weight of errors to consider.
idle_string : Circuit-like, optional
A Circuit or tuple of operation labels that represents the idle
gate being characterized by idle tomography.
include_hamiltonian, include_stochastic, include_affine : bool, optional
Whether to include fiducial pairs for finding Hamiltonian-, Stochastic-,
and Affine-type errors.
ham_tmpl : tuple, optional
A tuple of length-`maxweight` Pauli strings (i.e. string w/letters "X",
"Y", or "Z"), describing how to construct the fiducial pairs used to
detect Hamiltonian errors. The special (and default) value "auto"
uses `("X","Y","Z")` and `("ZY","ZX","XZ","YZ","YX","XY")` for
`maxweight` equal to 1 and 2, repectively, and will generate an error
if `maxweight > 2`.
preferred_prep_basis_signs, preferred_meas_basis_signs: tuple, optional
A 3-tuple of "+" or "-" strings indicating which sign for preparing
or measuring in the X, Y, and Z bases is preferable. Usually one
orientation if preferred because it's easier to achieve using the
native model. Additionally, the special (and default) value "auto"
may be used, in which case :function:`preferred_signs_from_paulidict`
is used to choose preferred signs based on `pauli_basis_dicts`.
Returns
-------
list
A list of :class:`Circuit` objects.
"""
prepDict, measDict = pauli_basis_dicts
if preferred_prep_basis_signs == "auto":
preferred_prep_basis_signs = preferred_signs_from_paulidict(prepDict)
if preferred_meas_basis_signs == "auto":
preferred_meas_basis_signs = preferred_signs_from_paulidict(measDict)
GiStr = _Circuit(idle_string, num_lines=nqubits)
pauli_fidpairs = idle_tomography_fidpairs(
nqubits, maxweight, include_hamiltonian, include_stochastic,
include_affine, ham_tmpl, preferred_prep_basis_signs,
preferred_meas_basis_signs)
fidpairs = [(x.to_circuit(prepDict), y.to_circuit(measDict))
for x, y in pauli_fidpairs] # e.g. convert ("XY","ZX") to tuple of Circuits
listOfExperiments = []
for prepFid, measFid in fidpairs: # list of fidpairs / configs (a prep/meas that gets I^L placed btwn it)
for L in max_lengths:
listOfExperiments.append(prepFid + GiStr * L + measFid)
return listOfExperiments
def make_idle_tomography_lists(nqubits, max_lengths, pauli_basis_dicts, maxweight=2,
idle_string=((),), include_hamiltonian=True,
include_stochastic=True, include_affine=True,
ham_tmpl="auto", preferred_prep_basis_signs="auto",
preferred_meas_basis_signs="auto"):
"""
Construct lists of experiments, one for each maximum-length value, needed
to perform idle tomography. This is potentiall useful for running GST on
idle tomography data.
Parameters
----------
nqubits : int
The number of qubits.
max_lengths : list
A list of maximum germ-power lengths. Each specifies a number many times
to repeat the idle gate, and typically this is a list of the powers of
2 preceded by zero, e.g. `[0,1,2,4,16]`. The largest value in this
list should be chosen to be the maximum number of idle gates you want to
perform in a row (typically limited by performance or time constraints).
pauli_basis_dicts : tuple
A `(prepPauliBasisDict,measPauliBasisDict)` tuple of dictionaries
specifying the way to prepare and measure in Pauli bases. See
:function:`preferred_signs_from_paulidict` for details on each
dictionary's format.
maxweight : int, optional
The maximum weight of errors to consider.
idle_string : Circuit-like, optional
A Circuit or tuple of operation labels that represents the idle
gate being characterized by idle tomography.
include_hamiltonian, include_stochastic, include_affine : bool, optional
Whether to include fiducial pairs for finding Hamiltonian-, Stochastic-,
and Affine-type errors.
ham_tmpl : tuple, optional
A tuple of length-`maxweight` Pauli strings (i.e. string w/letters "X",
"Y", or "Z"), describing how to construct the fiducial pairs used to
detect Hamiltonian errors. The special (and default) value "auto"
uses `("X","Y","Z")` and `("ZY","ZX","XZ","YZ","YX","XY")` for
`maxweight` equal to 1 and 2, repectively, and will generate an error
if `maxweight > 2`.
preferred_prep_basis_signs, preferred_meas_basis_signs: tuple, optional
A 3-tuple of "+" or "-" strings indicating which sign for preparing
or measuring in the X, Y, and Z bases is preferable. Usually one
orientation if preferred because it's easier to achieve using the
native model. Additionally, the special (and default) value "auto"
may be used, in which case :function:`preferred_signs_from_paulidict`
is used to choose preferred signs based on `pauli_basis_dicts`.
Returns
-------
list
A list of lists of :class:`Circuit` objects, one list per max-L value.
"""
prepDict, measDict = pauli_basis_dicts
if preferred_prep_basis_signs == "auto":
preferred_prep_basis_signs = preferred_signs_from_paulidict(prepDict)
if preferred_meas_basis_signs == "auto":
preferred_meas_basis_signs = preferred_signs_from_paulidict(measDict)
GiStr = _Circuit(idle_string, num_lines=nqubits)
pauli_fidpairs = idle_tomography_fidpairs(
nqubits, maxweight, include_hamiltonian, include_stochastic,
include_affine, ham_tmpl, preferred_prep_basis_signs,
preferred_meas_basis_signs)
fidpairs = [(x.to_circuit(prepDict), y.to_circuit(measDict))
for x, y in pauli_fidpairs] # e.g. convert ("XY","ZX") to tuple of Circuits
listOfListsOfExperiments = []
for L in max_lengths:
expsForThisL = []
for prepFid, measFid in fidpairs: # list of fidpairs / configs (a prep/meas that gets I^L placed btwn it)
expsForThisL.append(prepFid + GiStr * L + measFid)
listOfListsOfExperiments.append(expsForThisL)
return listOfListsOfExperiments
# -----------------------------------------------------------------------------
# Running idle tomography
# -----------------------------------------------------------------------------
def compute_observed_samebasis_err_rate(dataset, pauli_fidpair, pauli_basis_dicts, idle_string,
outcome, max_lengths, fit_order=1):
"""
Extract the observed error rate from a series of experiments which prepares
and measures in the *same* Pauli basis and tracks a particular `outcome`.
Parameters
----------
dataset : DataSet
The set of data counts (observations) to use.
pauli_fidpair : tuple
A `(prep,measure)` 2-tuple of :class:`NQPauliState` objects specifying
the prepation state and measurement basis.
pauli_basis_dicts : tuple
A `(prepPauliBasisDict,measPauliBasisDict)` tuple of dictionaries
specifying the way to prepare and measure in Pauli bases. See
:function:`preferred_signs_from_paulidict` for details on each
dictionary's format.
idle_string : Circuit
The Circuit representing the idle operation being characterized.
outcome : NQOutcome
The outcome being tracked.
max_lengths : list
A list of maximum germ-power lengths. The seriese of sequences
considered is `prepFiducial + idle_string^L + measFiducial`, where
`L` ranges over the values in `max_lengths`.
fit_order : int, optional
The polynomial order used to fit the observed data probabilities.
Returns
-------
dict
A dictionary of information about the fit, including the observed
error rate and the data points that were fit.
"""
# fit number of given outcome counts to a line
pauli_prep, pauli_meas = pauli_fidpair
prepDict, measDict = pauli_basis_dicts
prepFid = pauli_prep.to_circuit(prepDict)
measFid = pauli_meas.to_circuit(measDict)
#Note on weights:
# data point with frequency f and N samples should be weighted w/ sqrt(N)/sqrt(f*(1-f))
# but in case f is 0 or 1 we use proxy f' by adding a dummy 0 and 1 count.
def freq_and_weight(circuit, outcome):
"""Get the frequency, weight, and errobar for a ptic circuit"""
cnts = dataset[circuit].counts # a normal dict
total = sum(cnts.values())
f = cnts.get((outcome.rep,), 0) / total # (py3 division) NOTE: outcomes are actually 1-tuples
fp = (cnts.get((outcome.rep,), 0) + 1) / (total + 2) # Note: can't == 1
wt = _np.sqrt(total / abs(fp * (1.0 - fp))) # abs to deal with non-CP data (simulated using termorder:1)
err = _np.sqrt(abs(f * (1.0 - f)) / total) # no need to use fp
return f, wt, err
#Get data to fit and weights to use in fitting
data_to_fit = []; wts = []; errbars = []
for L in max_lengths:
opstr = prepFid + idle_string * L + measFid
f, wt, err = freq_and_weight(opstr, outcome)
data_to_fit.append(f)
wts.append(wt)
errbars.append(err)
#curvefit -> slope
coeffs = _np.polyfit(max_lengths, data_to_fit, fit_order, w=wts) # when fit_order = 1 = line
if fit_order == 1:
slope = coeffs[0]
elif fit_order == 2:
#OLD: slope = coeffs[1] # c2*x2 + c1*x + c0 ->deriv@x=0-> c1
det = coeffs[1]**2 - 4 * coeffs[2] * coeffs[0]
slope = -_np.sign(coeffs[0]) * _np.sqrt(det) if det >= 0 else coeffs[1]
else: raise NotImplementedError("Only fit_order <= 2 are supported!")
return {'rate': slope,
'fit_order': fit_order,
'fitCoeffs': coeffs,
'data': data_to_fit,
'errbars': errbars,
'weights': wts}
def compute_observed_diffbasis_err_rate(dataset, pauli_fidpair, pauli_basis_dicts,
idle_string, observable, max_lengths, fit_order=1):
"""
Extract the observed error rate from a series of experiments which prepares
and measures in *different* Pauli basis and tracks the expectation value of
a particular `observable`.
Parameters
----------
dataset : DataSet
The set of data counts (observations) to use.
pauli_fidpair : tuple
A `(prep,measure)` 2-tuple of :class:`NQPauliState` objects specifying
the prepation state and measurement basis.
pauli_basis_dicts : tuple
A `(prepPauliBasisDict,measPauliBasisDict)` tuple of dictionaries
specifying the way to prepare and measure in Pauli bases. See
:function:`preferred_signs_from_paulidict` for details on each
dictionary's format.
idle_string : Circuit
The Circuit representing the idle operation being characterized.
observable : NQPauliOp
The observable whose expectation value is being tracked.
max_lengths : list
A list of maximum germ-power lengths. The seriese of sequences
considered is `prepFiducial + idle_string^L + measFiducial`, where
`L` ranges over the values in `max_lengths`.
fit_order : int, optional
The polynomial order used to fit the observed data probabilities.
Returns
-------
dict
A dictionary of information about the fit, including the observed
error rate and the data points that were fit.
"""
# fit expectation value of `observable` (trace over all I elements of it) to a line
pauli_prep, pauli_meas = pauli_fidpair
prepDict, measDict = pauli_basis_dicts
prepFid = pauli_prep.to_circuit(prepDict)
measFid = pauli_meas.to_circuit(measDict)
#observable is always equal to pauli_meas (up to signs) with all but 1 or 2
# (maxErrWt in general) of it's elements replaced with 'I', essentially just
# telling us which 1 or 2 qubits to take the <Z> or <ZZ> expectation value of
# (since the meas fiducial gets us in the right basis) -- i.e. the qubits to *not* trace over.
obs_indices = [i for i, letter in enumerate(observable.rep) if letter != 'I']
minus_sign = _np.prod([pauli_meas.signs[i] for i in obs_indices])
def unsigned_exptn_and_weight(circuit, observed_indices):
#compute expectation value of observable
drow = dataset[circuit] # dataset row
total = drow.total
# <Z> = 0 count - 1 count (if measFid sign is +1, otherwise reversed via minus_sign)
if len(observed_indices) == 1:
i = observed_indices[0] # the qubit we care about
cnt0 = cnt1 = 0
for outcome, cnt in drow.counts.items():
if outcome[0][i] == '0': cnt0 += cnt # [0] b/c outcomes are actually 1-tuples
else: cnt1 += cnt
exptn = float(cnt0 - cnt1) / total
fp = 0.5 + 0.5 * float(cnt0 - cnt1 + 1) / (total + 2)
# <ZZ> = 00 count - 01 count - 10 count + 11 count (* minus_sign)
elif len(observed_indices) == 2:
i, j = observed_indices # the qubits we care about
cnt_even = cnt_odd = 0
for outcome, cnt in drow.counts.items():
if outcome[0][i] == outcome[0][j]: cnt_even += cnt
else: cnt_odd += cnt
exptn = float(cnt_even - cnt_odd) / total
fp = 0.5 + 0.5 * float(cnt_even - cnt_odd + 1) / (total + 2)