-
Notifications
You must be signed in to change notification settings - Fork 55
/
nqnoiseconstruction.py
3400 lines (2871 loc) · 171 KB
/
nqnoiseconstruction.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
""" Defines classes which represent gates, as well as supporting functions """
from __future__ import division, print_function, absolute_import, unicode_literals
#***************************************************************************************************
# 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.
#***************************************************************************************************
import collections as _collections
import itertools as _itertools
import numpy as _np
import scipy as _scipy
import scipy.sparse as _sps
import warnings as _warnings
from .. import objects as _objs
from ..tools import basistools as _bt
from ..tools import matrixtools as _mt
from ..tools import optools as _gt
from ..tools import slicetools as _slct
from ..tools import listtools as _lt
from ..tools import internalgates as _itgs
from ..tools import mpitools as _mpit
from ..tools import compattools as _compat
from ..objects import model as _mdl
from ..objects import operation as _op
from ..objects import opfactory as _opfactory
from ..objects import spamvec as _sv
from ..objects import povm as _povm
from ..objects import qubitgraph as _qgraph
from ..objects import labeldicts as _ld
from ..objects.cloudnoisemodel import CloudNoiseModel as _CloudNoiseModel
from ..objects.labeldicts import StateSpaceLabels as _StateSpaceLabels
from ..baseobjs import VerbosityPrinter as _VerbosityPrinter
from ..baseobjs import Basis as _Basis
from ..baseobjs import BuiltinBasis as _BuiltinBasis
from ..baseobjs import Label as _Lbl
from ..baseobjs import CircuitParser as _CircuitParser
from . import circuitconstruction as _gsc
from .modelconstruction import basis_build_vector as _basis_build_vector
RANK_TOL = 1e-9
def nparams_XYCNOT_cloudnoise_model(nQubits, geometry="line", maxIdleWeight=1, maxhops=0,
extraWeight1Hops=0, extraGateWeight=0, requireConnected=False,
independent1Qgates=True, ZZonly=False, verbosity=0):
"""
Returns the number of parameters in the :class:`CloudNoiseModel` containing
X(pi/2), Y(pi/2) and CNOT gates using the specified arguments without
actually constructing the model (useful for considering parameter-count
scaling).
Parameters
----------
Subset of those of :function:`build_cloudnoise_model_from_hops_and_weights`.
Returns
-------
int
"""
# noise can be either a seed or a random array that is long enough to use
printer = _VerbosityPrinter.build_printer(verbosity)
printer.log("Computing parameters for a %d-qubit %s model" % (nQubits, geometry))
qubitGraph = _objs.QubitGraph.common_graph(nQubits, geometry)
#printer.log("Created qubit graph:\n"+str(qubitGraph))
def idle_count_nparams(maxWeight):
"""Parameter count of a `build_nqn_global_idle`-constructed gate"""
ret = 0
possible_err_qubit_inds = _np.arange(nQubits)
for wt in range(1, maxWeight + 1):
nErrTargetLocations = qubitGraph.connected_combos(possible_err_qubit_inds, wt)
if ZZonly and wt > 1: basisSizeWoutId = 1**wt # ( == 1)
else: basisSizeWoutId = 3**wt # (X,Y,Z)^wt
nErrParams = 2 * basisSizeWoutId # H+S terms
ret += nErrTargetLocations * nErrParams
return ret
def op_count_nparams(target_qubit_inds, weight_maxhops_tuples, debug=False):
"""Parameter count of a `build_nqn_composed_gate`-constructed gate"""
ret = 0
#Note: no contrib from idle noise (already parameterized)
for wt, maxHops in weight_maxhops_tuples:
possible_err_qubit_inds = _np.array(qubitGraph.radius(target_qubit_inds, maxHops), _np.int64)
if requireConnected:
nErrTargetLocations = qubitGraph.connected_combos(possible_err_qubit_inds, wt)
else:
nErrTargetLocations = _scipy.special.comb(len(possible_err_qubit_inds), wt)
if ZZonly and wt > 1: basisSizeWoutId = 1**wt # ( == 1)
else: basisSizeWoutId = 3**wt # (X,Y,Z)^wt
nErrParams = 2 * basisSizeWoutId # H+S terms
if debug:
print(" -- wt%d, hops%d: inds=%s locs = %d, eparams=%d, total contrib = %d" %
(wt, maxHops, str(possible_err_qubit_inds), nErrTargetLocations,
nErrParams, nErrTargetLocations * nErrParams))
ret += nErrTargetLocations * nErrParams
return ret
nParams = _collections.OrderedDict()
printer.log("Creating Idle:")
nParams[_Lbl('Gi')] = idle_count_nparams(maxIdleWeight)
#1Q gates: X(pi/2) & Y(pi/2) on each qubit
weight_maxhops_tuples_1Q = [(1, maxhops + extraWeight1Hops)] + \
[(1 + x, maxhops) for x in range(1, extraGateWeight + 1)]
if independent1Qgates:
for i in range(nQubits):
printer.log("Creating 1Q X(pi/2) and Y(pi/2) gates on qubit %d!!" % i)
nParams[_Lbl("Gx", i)] = op_count_nparams((i,), weight_maxhops_tuples_1Q)
nParams[_Lbl("Gy", i)] = op_count_nparams((i,), weight_maxhops_tuples_1Q)
else:
printer.log("Creating common 1Q X(pi/2) and Y(pi/2) gates")
rep = int(nQubits / 2)
nParams[_Lbl("Gxrep")] = op_count_nparams((rep,), weight_maxhops_tuples_1Q)
nParams[_Lbl("Gyrep")] = op_count_nparams((rep,), weight_maxhops_tuples_1Q)
#2Q gates: CNOT gates along each graph edge
weight_maxhops_tuples_2Q = [(1, maxhops + extraWeight1Hops), (2, maxhops)] + \
[(2 + x, maxhops) for x in range(1, extraGateWeight + 1)]
for i, j in qubitGraph.edges(): # note: all edges have i<j so "control" of CNOT is always lower index (arbitrary)
printer.log("Creating CNOT gate between qubits %d and %d!!" % (i, j))
nParams[_Lbl("Gcnot", (i, j))] = op_count_nparams((i, j), weight_maxhops_tuples_2Q)
#SPAM
nPOVM_1Q = 4 # params for a single 1Q POVM
nParams[_Lbl('rho0')] = 3 * nQubits # 3 b/c each component is TP
nParams[_Lbl('Mdefault')] = nPOVM_1Q * nQubits # nQubits 1Q-POVMs
return nParams, sum(nParams.values())
def build_cloudnoise_model_from_hops_and_weights(
nQubits, gate_names, nonstd_gate_unitaries=None, custom_gates=None,
availability=None, qubit_labels=None, geometry="line",
maxIdleWeight=1, maxSpamWeight=1, maxhops=0,
extraWeight1Hops=0, extraGateWeight=0, sparse=False,
roughNoise=None, sim_type="auto", parameterization="H+S",
spamtype="lindblad", addIdleNoiseToAllGates=True,
errcomp_type="gates", independent_clouds=True,
return_clouds=False, verbosity=0): # , debug=False):
"""
Create a "standard" n-qubit model using a low-weight and geometrically local
error model with a common "global idle" operation.
This type of model is referred to as a "cloud noise" model because
noise specific to a gate may act on a neighborhood or cloud around
the gate's target qubits. This type of model is generally useful
for performing GST on a multi-qubit system, whereas local-noise
models (:class:`LocalNoiseModel` objects, created by, e.g.,
:function:`create_standard localnoise_model`) are more useful for
representing static (non-parameterized) models.
The returned model is "standard", in that the following standard gate
names may be specified as elements to `gate_names` without the need to
supply their corresponding unitaries (as one must when calling
the constructor directly):
- 'Gi' : the 1Q idle operation
- 'Gx','Gy','Gz' : 1Q pi/2 rotations
- 'Gxpi','Gypi','Gzpi' : 1Q pi rotations
- 'Gh' : Hadamard
- 'Gp' : phase
- 'Gcphase','Gcnot','Gswap' : standard 2Q gates
Furthermore, if additional "non-standard" gates are needed,
they are specified by their *unitary* gate action, even if
the final model propagates density matrices (as opposed
to state vectors).
Parameters
----------
nQubits : int
The total number of qubits.
gate_names : list
A list of string-type gate names (e.g. `"Gx"`) either taken from
the list of builtin "standard" gate names given above or from the
keys of `nonstd_gate_unitaries`. These are the typically 1- and 2-qubit
gates that are repeatedly embedded (based on `availability`) to form
the resulting model.
nonstd_gate_unitaries : dict, optional
A dictionary of numpy arrays which specifies the unitary gate action
of the gate names given by the dictionary's keys. As an advanced
behavior, a unitary-matrix-returning function which takes a single
argument - a tuple of label arguments - may be given instead of a
single matrix to create an operation *factory* which allows
continuously-parameterized gates. This function must also return
an empty/dummy unitary when `None` is given as it's argument.
custom_gates : dict
A dictionary that associates with gate labels
:class:`LinearOperator`, :class:`OpFactory`, or `numpy.ndarray`
objects. These objects describe the full action of the gate or
primitive-layer they're labeled by (so if the model represents
states by density matrices these objects are superoperators, not
unitaries), and override any standard construction based on builtin
gate names or `nonstd_gate_unitaries`. Keys of this dictionary must
be string-type gate *names* -- they cannot include state space labels
-- and they must be *static* (have zero parameters) because they
represent only the ideal behavior of each gate -- the cloudnoise
operations represent the parameterized noise. To fine-tune how this
noise is parameterized, call the :class:`CloudNoiseModel` constructor
directly.
availability : dict, optional
A dictionary whose keys are the same gate names as in
`gatedict` and whose values are lists of qubit-label-tuples. Each
qubit-label-tuple must have length equal to the number of qubits
the corresponding gate acts upon, and causes that gate to be
embedded to act on the specified qubits. For example,
`{ 'Gx': [(0,),(1,),(2,)], 'Gcnot': [(0,1),(1,2)] }` would cause
the `1-qubit `'Gx'`-gate to be embedded three times, acting on qubits
0, 1, and 2, and the 2-qubit `'Gcnot'`-gate to be embedded twice,
acting on qubits 0 & 1 and 1 & 2. Instead of a list of tuples,
values of `availability` may take the special values:
- `"all-permutations"` and `"all-combinations"` equate to all possible
permutations and combinations of the appropriate number of qubit labels
(deterined by the gate's dimension).
- `"all-edges"` equates to all the vertices, for 1Q gates, and all the
edges, for 2Q gates of the graphy given by `geometry`.
- `"arbitrary"` or `"*"` means that the corresponding gate can be placed
on any target qubits via an :class:`EmbeddingOpFactory` (uses less
memory but slower than `"all-permutations"`.
If a gate name (a key of `gatedict`) is not present in `availability`,
the default is `"all-edges"`.
qubit_labels : tuple, optional
The circuit-line labels for each of the qubits, which can be integers
and/or strings. Must be of length `nQubits`. If None, then the
integers from 0 to `nQubits-1` are used.
geometry : {"line","ring","grid","torus"} or QubitGraph
The type of connectivity among the qubits, specifying a
graph used to define neighbor relationships. Alternatively,
a :class:`QubitGraph` object with node labels equal to
`qubit_labels` may be passed directly.
maxIdleWeight : int, optional
The maximum-weight for errors on the global idle gate.
maxSpamWeight : int, optional
The maximum-weight for SPAM errors when `spamtype == "linblad"`.
maxhops : int
The locality constraint: for a gate, errors (of weight up to the
maximum weight for the gate) are allowed to occur on the gate's
target qubits and those reachable by hopping at most `maxhops` times
from a target qubit along nearest-neighbor links (defined by the
`geometry`).
extraWeight1Hops : int, optional
Additional hops (adds to `maxhops`) for weight-1 errors. A value > 0
can be useful for allowing just weight-1 errors (of which there are
relatively few) to be dispersed farther from a gate's target qubits.
For example, a crosstalk-detecting model might use this.
extraGateWeight : int, optional
Addtional weight, beyond the number of target qubits (taken as a "base
weight" - i.e. weight 2 for a 2Q gate), allowed for gate errors. If
this equals 1, for instance, then 1-qubit gates can have up to weight-2
errors and 2-qubit gates can have up to weight-3 errors.
sparse : bool, optional
Whether the embedded Lindblad-parameterized gates within the constructed
`nQubits`-qubit gates are sparse or not. (This is determied by whether
they are constructed using sparse basis matrices.) When sparse, these
Lindblad gates take up less memory, but their action is slightly slower.
Usually it's fine to leave this as the default (False), except when
considering particularly high-weight terms (b/c then the Lindblad gates
are higher dimensional and sparsity has a significant impact).
roughNoise: tuple or numpy.ndarray, optional
If not None, noise to place on the gates, the state prep and the povm.
This can either be a `(seed,strength)` 2-tuple, or a long enough numpy
array (longer than what is needed is OK). These values specify random
`gate.from_vector` initialization for the model, and as such applies an
often unstructured and unmeaningful type of noise.
sim_type : {"auto","matrix","map","termorder:<N>"}
The type of forward simulation (probability computation) to use for the
returned :class:`Model`. That is, how should the model compute
operation sequence/circuit probabilities when requested. `"matrix"` is better
for small numbers of qubits, `"map"` is better for larger numbers. The
`"termorder"` option is designed for even larger numbers. Usually,
the default of `"auto"` is what you want.
parameterization : {"P", "P terms", "P clifford terms"}
Where *P* can be any Lindblad parameterization base type (e.g. CPTP,
H+S+A, H+S, S, D, etc.) This is the type of parameterizaton to use in
the constructed model. Types without any "terms" suffix perform
usual density-matrix evolution to compute circuit probabilities. The
other "terms" options compute probabilities using a path-integral
approach designed for larger numbers of qubits (experts only).
spamtype : { "static", "lindblad", "tensorproduct" }
Specifies how the SPAM elements of the returned `Model` are formed.
Static elements are ideal (perfect) operations with no parameters, i.e.
no possibility for noise. Lindblad SPAM operations are the "normal"
way to allow SPAM noise, in which case error terms up to weight
`maxSpamWeight` are included. Tensor-product operations require that
the state prep and POVM effects have a tensor-product structure; the
"tensorproduct" mode exists for historical reasons and is *deprecated*
in favor of `"lindblad"`; use it only if you know what you're doing.
addIdleNoiseToAllGates: bool, optional
Whether the global idle should be added as a factor following the
ideal action of each of the non-idle gates.
errcomp_type : {"gates","errorgens"}
How errors are composed when creating layer operations in the returned
model. `"gates"` means that the errors on multiple gates in a single
layer are composed as separate and subsequent processes. Specifically,
the layer operation has the form `Composed(target,idleErr,cloudErr)`
where `target` is a composition of all the ideal gate operations in the
layer, `idleErr` is idle error (`.operation_blks['layers']['globalIdle']`),
and `cloudErr` is the composition (ordered as layer-label) of cloud-
noise contributions, i.e. a map that acts as the product of exponentiated
error-generator matrices. `"errorgens"` means that layer operations
have the form `Composed(target, error)` where `target` is as above and
`error` results from composing the idle and cloud-noise error
*generators*, i.e. a map that acts as the exponentiated sum of error
generators (ordering is irrelevant in this case).
independent_clouds : bool, optional
Currently this must be set to True. In a future version, setting to
true will allow all the clouds of a given gate name to have a similar
cloud-noise process, mapped to the full qubit graph via a stencil.
return_clouds : bool, optional
Whether to return a dictionary of "cloud" objects, used for constructing
the operation sequences necessary for probing the returned Model's
parameters. Used primarily internally within pyGSTi.
verbosity : int, optional
An integer >= 0 dictating how must output to send to stdout.
Returns
-------
Model
"""
mdl = _CloudNoiseModel.build_from_hops_and_weights(
nQubits, gate_names, nonstd_gate_unitaries, custom_gates,
availability, qubit_labels, geometry,
maxIdleWeight, maxSpamWeight, maxhops,
extraWeight1Hops, extraGateWeight, sparse,
sim_type, parameterization, spamtype,
addIdleNoiseToAllGates, errcomp_type,
independent_clouds, verbosity)
#Insert noise on everything using roughNoise (really shouldn't be used!)
if roughNoise is not None:
vec = mdl.to_vector()
assert(spamtype == "lindblad"), "Can only apply rough noise when spamtype == lindblad"
assert(_np.linalg.norm(vec) / len(vec) < 1e-6) # make sure our base is zero
if isinstance(roughNoise, tuple): # use as (seed, strength)
seed, strength = roughNoise
rndm = _np.random.RandomState(seed)
vec += _np.abs(rndm.random_sample(len(vec)) * strength) # abs b/c some params need to be positive
else: # use as a vector
vec += roughNoise[0:len(vec)]
mdl.from_vector(vec)
if return_clouds:
#FUTURE - just return cloud *keys*? (operation label values are never used
# downstream, but may still be useful for debugging, so keep for now)
return mdl, mdl.get_clouds()
else:
return mdl
def build_cloud_crosstalk_model(nQubits, gate_names, error_rates, nonstd_gate_unitaries=None, custom_gates=None,
availability=None, qubit_labels=None, geometry="line", parameterization='auto',
evotype="auto", sim_type="auto", independent_gates=False, sparse=True,
errcomp_type="errorgens", addIdleNoiseToAllGates=True, verbosity=0):
"""
Create a n-qubit model that may contain crosstalk errors.
This function constructs a :class:`CloudNoiseModel` that may place noise on
a gate that affects arbitrary qubits, i.e. qubits in addition to the target
qubits of the gate. These errors are specified uing a dictionary of error
rates.
Parameters
----------
nQubits : int
The number of qubits
error_rates : dict
A dictionary whose keys are primitive-layer and gate labels (e.g.
`("Gx",0)` or `"Gx"`) and whose values are "error-dictionaries"
that determine the type and amount of error placed on each item.
Error-dictionary keys are `(termType, basisLabel)` tuples, where
`termType` can be `"H"` (Hamiltonian), `"S"` (Stochastic), or `"A"`
(Affine), and `basisLabel` is a string of I, X, Y, or Z to describe a
Pauli basis element appropriate for the gate (i.e. having the same
number of letters as there are qubits in the gate). For example, you
could specify a 0.01-radian Z-rotation error and 0.05 rate of Pauli-
stochastic X errors on a 1-qubit gate by using the error dictionary:
`{('H','Z'): 0.01, ('S','X'): 0.05}`. Furthermore, basis elements
may be directed at specific qubits using a color followed by a comma-
separated qubit-label-list. For example, `('S',"XX:0,1")` would
mean a weight-2 XX stochastic error on qubits 0 and 1, and this term
could be placed in the error dictionary for a gate that is only
supposed to target qubit 0, for instance. In addition to the primitive
label names, the special values `"prep"`, `"povm"`, and `"idle"` may be
used as keys of `error_rates` to specify the error on the state
preparation, measurement, and global idle, respectively.
nonstd_gate_unitaries : dict, optional
A dictionary of numpy arrays which specifies the unitary gate action
of the gate names given by the dictionary's keys. As an advanced
behavior, a unitary-matrix-returning function which takes a single
argument - a tuple of label arguments - may be given instead of a
single matrix to create an operation *factory* which allows
continuously-parameterized gates. This function must also return
an empty/dummy unitary when `None` is given as it's argument.
custom_gates : dict, optional
A dictionary that associates with gate labels
:class:`LinearOperator`, :class:`OpFactory`, or `numpy.ndarray`
objects. These objects override any other behavior for constructing
their designated operations (e.g. from `error_rates` or
`nonstd_gate_unitaries`). Note: currently these objects must
be *static*, and keys of this dictionary must by strings - there's
no way to specify the "cloudnoise" part of a gate via this dict
yet, only the "target" part.
availability : dict, optional
A dictionary whose keys are the same gate names as in
`gatedict` and whose values are lists of qubit-label-tuples. Each
qubit-label-tuple must have length equal to the number of qubits
the corresponding gate acts upon, and causes that gate to be
embedded to act on the specified qubits. For example,
`{ 'Gx': [(0,),(1,),(2,)], 'Gcnot': [(0,1),(1,2)] }` would cause
the `1-qubit `'Gx'`-gate to be embedded three times, acting on qubits
0, 1, and 2, and the 2-qubit `'Gcnot'`-gate to be embedded twice,
acting on qubits 0 & 1 and 1 & 2. Instead of a list of tuples,
values of `availability` may take the special values:
- `"all-permutations"` and `"all-combinations"` equate to all possible
permutations and combinations of the appropriate number of qubit labels
(deterined by the gate's dimension).
- `"all-edges"` equates to all the vertices, for 1Q gates, and all the
edges, for 2Q gates of the graphy given by `geometry`.
- `"arbitrary"` or `"*"` means that the corresponding gate can be placed
on any target qubits via an :class:`EmbeddingOpFactory` (uses less
memory but slower than `"all-permutations"`.
If a gate name (a key of `gatedict`) is not present in `availability`,
the default is `"all-edges"`.
qubit_labels : tuple, optional
The circuit-line labels for each of the qubits, which can be integers
and/or strings. Must be of length `nQubits`. If None, then the
integers from 0 to `nQubits-1` are used.
geometry : {"line","ring","grid","torus"} or QubitGraph
The type of connectivity among the qubits, specifying a
graph used to define neighbor relationships. Alternatively,
a :class:`QubitGraph` object with node labels equal to
`qubit_labels` may be passed directly.
parameterization : "auto"
This argument is for future expansion and currently must be set to `"auto"`.
evotype : {"auto","densitymx","statevec","stabilizer","svterm","cterm"}
The evolution type. If "auto" is specified, "densitymx" is used.
sim_type : {"auto","matrix","map","termorder:<N>"}
The type of forward simulation (probability computation) to use for the
returned :class:`Model`. That is, how should the model compute
operation sequence/circuit probabilities when requested. `"matrix"` is better
for small numbers of qubits, `"map"` is better for larger numbers. The
`"termorder"` option is designed for even larger numbers. Usually,
the default of `"auto"` is what you want.
independent_gates : bool, optional
Whether gates are allowed independent cloud noise or not. If False,
then all gates with the same name (e.g. "Gx") will have the *same*
noise. If True, then gates with the same name acting on different
qubits may have different noise.
sparse : bool, optional
Whether the embedded Lindblad-parameterized gates within the constructed
`nQubits`-qubit gates are sparse or not.
errcomp_type : {"gates","errorgens"}
How errors are composed when creating layer operations in the returned
model. `"gates"` means that the errors on multiple gates in a single
layer are composed as separate and subsequent processes. `"errorgens"`
means that layer operations have the form `Composed(target, error)`
where `target` is as above and `error` results from composing the idle
and cloud-noise error *generators*, i.e. a map that acts as the
exponentiated sum of error generators (ordering is irrelevant in
this case).
addIdleNoiseToAllGates: bool, optional
Whether the global idle should be added as a factor following the
ideal action of each of the non-idle gates when constructing layer
operations.
verbosity : int, optional
An integer >= 0 dictating how must output to send to stdout.
Returns
-------
CloudNoiseModel
"""
# E.g. error_rates could == {'Gx': {('H','X'): 0.1, ('S','Y'): 0.2} } # Lindblad, b/c val is dict
# or {'Gx': 0.1 } # Depolarization b/c val is a float
# or {'Gx': (0.1,0.2,0.2) } # Pauli-Stochastic b/c val is a tuple
# (same as those of a crosstalk-free model) PLUS additional ones which specify which
# qubits the error operates (not necessarily the target qubits of the gate in question)
# for example: { 'Gx:Q0': { ('H','X:Q1'): 0.01, ('S','XX:Q0,Q1'): 0.01} }
#NOTE: to have "independent_gates=False" and specify error rates for "Gx" vs "Gx:Q0", we
# need to have some ability to stencil a gate's cloud based on different target-qubits in
# the qubit graph.
printer = _VerbosityPrinter.build_printer(verbosity)
if parameterization != "auto":
raise NotImplementedError(("Future versions of pyGSTi may allow you to specify a non-automatic "
"parameterization - for instance building DepolarizeOp objects "
"instead of LindbladOps for depolarization errors."))
if evotype == "auto":
evotype = "densitymx" # FUTURE: do something more sophisticated?
if qubit_labels is None:
qubit_labels = tuple(range(nQubits))
qubit_dim = 2 if evotype in ('statevec', 'stabilizer') else 4
if not isinstance(qubit_labels, _ld.StateSpaceLabels): # allow user to specify a StateSpaceLabels object
all_sslbls = _ld.StateSpaceLabels(qubit_labels, (qubit_dim,) * len(qubit_labels), evotype=evotype)
else:
all_sslbls = qubit_labels
qubit_labels = [lbl for lbl in all_sslbls.labels[0] if all_sslbls.labeldims[lbl] == qubit_dim]
#Only extract qubit labels from the first tensor-product block...
if isinstance(geometry, _qgraph.QubitGraph):
qubitGraph = geometry
else:
qubitGraph = _qgraph.QubitGraph.common_graph(nQubits, geometry, directed=True,
qubit_labels=qubit_labels, all_directions=True)
printer.log("Created qubit graph:\n" + str(qubitGraph))
nQubit_dim = 2**nQubits if evotype in ('statevec', 'stabilizer') else 4**nQubits
orig_error_rates = error_rates.copy()
cparser = _CircuitParser()
cparser.lookup = None # lookup - functionality removed as it wasn't used
for k, v in orig_error_rates.items():
if _compat.isstr(k) and ":" in k: # then parse this to get a label, allowing, e.g. "Gx:0"
lbls, _ = cparser.parse(k)
assert(len(lbls) == 1), "Only single primitive-gate labels allowed as keys! (not %s)" % str(k)
assert(all([sslbl in qubitGraph.get_node_names() for sslbl in lbls[0].sslbls])), \
"One or more invalid qubit names in: %s" % k
del error_rates[k]
error_rates[lbls[0]] = v
elif isinstance(k, _Lbl):
if k.sslbls is not None:
assert(all([sslbl in qubitGraph.get_node_names() for sslbl in k.sslbls])), \
"One or more invalid qubit names in the label: %s" % str(k)
def _parameterization_from_errgendict(errs):
paramtypes = []
if any([nm[0] == 'H' for nm in errs]): paramtypes.append('H')
if any([nm[0] == 'S' for nm in errs]): paramtypes.append('S')
if any([nm[0] == 'A' for nm in errs]): paramtypes.append('A')
if any([nm[0] == 'S' and isinstance(nm, tuple) and len(nm) == 3 for nm in errs]):
# parameterization must be "CPTP" if there are any ('S',b1,b2) keys
parameterization = "CPTP"
else:
parameterization = '+'.join(paramtypes)
return parameterization
def _map_stencil_sslbls(stencil_sslbls, target_lbls): # deals with graph directions
ret = [qubitGraph.resolve_relative_nodelabel(s, target_lbls) for s in stencil_sslbls]
if any([x is None for x in ret]): return None # signals there is a non-present dirs, e.g. end of chain
return ret
def create_error(target_labels, errs=None, stencil=None, return_what="auto"): # err = an error rates dict
"""
Create an error generator or error superoperator based on the error dictionary
`errs`. This function is used to construct error for SPAM and gate layer operations.
Parameters
----------
target_labels : tuple
The target labels of the gate/primitive layer we're constructing an
error for. This is needed for knowing the size of the target op and
for using "@" syntax within stencils.
errs : dict
A error-dictionary specifying what types of errors we need to construct.
stencil : None or OrderedDict
Instead of specifying `errs`, one can specify `stencil` to tell us how
and *with what* to construct an error -- `stencil` will contain keys
that are tuples of "stencil labels" and values which are error generators,
specifying errors that occur on certain "real" qubits by mapping the
stencil qubits to real qubits using `target_labels` as an anchor.
return_what : {"auto", "stencil", "errmap", "errgen"}, optional
What type of object should be returned. "auto" causes either an
"errmap" (a superoperator) or "errgen" (an error generator) to
be selected based on the outside-scope value of `errcomp_type`.
Returns
-------
LinearOperator or OrderedDict
The former in the "errmap" and "errgen" cases, the latter in the
"stencil" case.
"""
target_nQubits = len(target_labels)
if return_what == "auto": # then just base return type on errcomp_type
return_what == "errgen" if errcomp_type == "errorgens" else "errmap"
assert(stencil is None or errs is None), "Cannot specify both `errs` and `stencil`!"
if errs is None:
if stencil is None:
if return_what == "stencil":
new_stencil = _collections.OrderedDict() # return an empty stencil
return new_stencil
errgen = _op.ComposedErrorgen([], nQubit_dim, evotype)
else:
# stencil is valid: apply it to create errgen
embedded_errgens = []
for stencil_sslbls, lind_errgen in stencil.items():
# Note: stencil_sslbls should contain directions like "up" or integer indices of target qubits.
error_sslbls = _map_stencil_sslbls(stencil_sslbls, target_labels) # deals with graph directions
if error_sslbls is None: continue # signals not all direction were present => skip this term
op_to_embed = lind_errgen.copy() if independent_gates else lind_errgen # copy for independent gates
#REMOVE print("DB: Applying stencil: ",all_sslbls, error_sslbls,op_to_embed.dim)
embedded_errgen = _op.EmbeddedErrorgen(all_sslbls, error_sslbls, op_to_embed)
embedded_errgens.append(embedded_errgen)
errgen = _op.ComposedErrorgen(embedded_errgens, nQubit_dim, evotype)
else:
#We need to build a stencil (which may contain QubitGraph directions) or an effective stencil
assert(stencil is None) # checked by above assert too
# distinct sets of qubits upon which a single (high-weight) error term acts:
distinct_errorqubits = _collections.OrderedDict()
if isinstance(errs, dict): # either for creating a stencil or an error
for nm, val in errs.items():
#REMOVE print("DB: Processing: ",nm, val)
if _compat.isstr(nm): nm = (nm[0], nm[1:]) # e.g. "HXX" => ('H','XX')
err_typ, basisEls = nm[0], nm[1:]
sslbls = None
local_nm = [err_typ]
for bel in basisEls: # e.g. bel could be "X:Q0" or "XX:Q0,Q1"
#REMOVE print("Basis el: ",bel)
# OR "X:<n>" where n indexes a target qubit or "X:<dir>" where dir indicates
# a graph *direction*, e.g. "up"
if ':' in bel:
bel_name, bel_sslbls = bel.split(':') # should have form <name>:<comma-separated-sslbls>
bel_sslbls = bel_sslbls.split(',') # e.g. ('Q0','Q1')
integerized_sslbls = []
for ssl in bel_sslbls:
try: integerized_sslbls.append(int(ssl))
except: integerized_sslbls.append(ssl)
bel_sslbls = tuple(integerized_sslbls)
else:
bel_name = bel
bel_sslbls = target_labels
#REMOVE print("DB: Nm + sslbls: ",bel_name,bel_sslbls)
if sslbls is None:
sslbls = bel_sslbls
else:
#Note: sslbls should always be the same if there are multiple basisEls,
# i.e for nm == ('S',bel1,bel2)
assert(sslbls == bel_sslbls), \
"All basis elements of the same error term must operate on the *same* state!"
local_nm.append(bel_name) # drop the state space labels, e.g. "XY:Q0,Q1" => "XY"
# keep track of errors by the qubits they act on, as only each such
# set will have it's own LindbladErrorgen
sslbls = tuple(sorted(sslbls))
local_nm = tuple(local_nm) # so it's hashable
if sslbls not in distinct_errorqubits:
distinct_errorqubits[sslbls] = _collections.OrderedDict()
if local_nm in distinct_errorqubits[sslbls]:
distinct_errorqubits[sslbls][local_nm] += val
else:
distinct_errorqubits[sslbls][local_nm] = val
elif isinstance(errs, float): # depolarization, action on only target qubits
sslbls = tuple(range(target_nQubits)) if return_what == "stencil" else target_labels
# Note: we use relative target indices in a stencil
basis = _BuiltinBasis('pp', 4**target_nQubits) # assume we always use Pauli basis?
distinct_errorqubits[sslbls] = _collections.OrderedDict()
perPauliRate = errs / len(basis.labels)
for bl in basis.labels:
distinct_errorqubits[sslbls][('S', bl)] = perPauliRate
else:
raise ValueError("Invalid `error_rates` value: %s (type %s)" % (str(errs), type(errs)))
new_stencil = _collections.OrderedDict()
for error_sslbls, local_errs_for_these_sslbls in distinct_errorqubits.items():
local_nQubits = len(error_sslbls) # weight of this group of errors which act on the same qubits
local_dim = 4**local_nQubits
basis = _BuiltinBasis('pp', local_dim) # assume we're always given basis els in a Pauli basis?
#Sanity check to catch user errors that would be hard to interpret if they get caught further down
for nm in local_errs_for_these_sslbls:
for bel in nm[1:]: # bel should be a *local* (bare) basis el name, e.g. "XX" but not "XX:Q0,Q1"
if bel not in basis.labels:
raise ValueError("In %s: invalid basis element label `%s` where one of {%s} was expected" %
(str(errs), str(bel), ', '.join(basis.labels)))
parameterization = _parameterization_from_errgendict(local_errs_for_these_sslbls)
#REMOVE print("DB: Param from ", local_errs_for_these_sslbls, " = ",parameterization)
_, _, nonham_mode, param_mode = _op.LindbladOp.decomp_paramtype(parameterization)
lind_errgen = _op.LindbladErrorgen(local_dim, local_errs_for_these_sslbls, basis, param_mode,
nonham_mode, truncate=False, mxBasis="pp", evotype=evotype)
#REMOVE print("DB: Adding to stencil: ",error_sslbls,lind_errgen.dim,local_dim)
new_stencil[error_sslbls] = lind_errgen
if return_what == "stencil": # then we just return the stencil, not the error map or generator
return new_stencil
#Use stencil to create error map or generator. Here `new_stencil` is not a "true" stencil
# in that it should contain only absolute labels (it wasn't created in stencil="create" mode)
embedded_errgens = []
for error_sslbls, lind_errgen in new_stencil.items():
#Then use the stencils for these steps later (if independent errgens is False especially?)
#REMOVE print("DB: Creating from stencil: ",all_sslbls, error_sslbls)
embedded_errgen = _op.EmbeddedErrorgen(all_sslbls, error_sslbls, lind_errgen)
embedded_errgens.append(embedded_errgen)
errgen = _op.ComposedErrorgen(embedded_errgens, nQubit_dim, evotype)
#If we get here, we've created errgen, which we either return or package into a map:
if return_what == "errmap":
return _op.LindbladOp(None, errgen, sparse_expm=sparse)
else:
return errgen
#Process "auto" sim_type
_, evotype = _gt.split_lindblad_paramtype(parameterization) # what about "auto" parameterization?
assert(evotype in ("densitymx", "svterm", "cterm")), "State-vector evolution types not allowed."
if sim_type == "auto":
if evotype in ("svterm", "cterm"): sim_type = "termorder:1"
else: sim_type = "map" if nQubits > 2 else "matrix"
assert(sim_type in ("matrix", "map") or sim_type.startswith("termorder"))
#Global Idle
if 'idle' in error_rates:
printer.log("Creating Idle:")
global_idle_layer = create_error(qubit_labels, error_rates['idle'], return_what="errmap")
else:
global_idle_layer = None
#SPAM
if 'prep' in error_rates:
prepPure = _sv.ComputationalSPAMVec([0] * nQubits, evotype)
prepNoiseMap = create_error(qubit_labels, error_rates['prep'], return_what="errmap")
prep_layers = [_sv.LindbladSPAMVec(prepPure, prepNoiseMap, "prep")]
else:
prep_layers = [_sv.ComputationalSPAMVec([0] * nQubits, evotype)]
if 'povm' in error_rates:
povmNoiseMap = create_error(qubit_labels, error_rates['povm'], return_what="errmap")
povm_layers = [_povm.LindbladPOVM(povmNoiseMap, None, "pp")]
else:
povm_layers = [_povm.ComputationalBasisPOVM(nQubits, evotype)]
stencils = _collections.OrderedDict()
def build_cloudnoise_fn(lbl):
# lbl will be for a particular gate and target qubits. If we have error rates for this specific gate
# and target qubits (i.e this primitive layer op) then we should build it directly (and independently,
# regardless of the value of `independent_gates`) using these rates. Otherwise, if we have a stencil
# for this gate, then we should use it to construct the output, using a copy when gates are independent
# and a reference to the *same* stencil operations when `independent_gates==False`.
if lbl in error_rates:
return create_error(lbl.sslbls, errs=error_rates[lbl]) # specific instructions for this primitive layer
elif lbl.name in stencils:
return create_error(lbl.sslbls, stencil=stencils[lbl.name]) # use existing stencil
elif lbl.name in error_rates:
stencils[lbl.name] = create_error(lbl.sslbls, error_rates[lbl.name],
return_what='stencil') # create stencil
return create_error(lbl.sslbls, stencil=stencils[lbl.name]) # and then use it
else:
return create_error(lbl, None)
def build_cloudkey_fn(lbl):
#FUTURE: Get a list of all the qubit labels `lbl`'s cloudnoise error touches and form this into a key
# For now, we just punt and return a key based on the target labels
cloud_key = tuple(lbl.sslbls)
return cloud_key
# gate_names => gatedict
if custom_gates is None: custom_gates = {}
if nonstd_gate_unitaries is None: nonstd_gate_unitaries = {}
std_unitaries = _itgs.get_standard_gatename_unitaries()
gatedict = _collections.OrderedDict()
for name in gate_names:
if name in custom_gates:
gatedict[name] = custom_gates[name]
else:
U = nonstd_gate_unitaries.get(name, std_unitaries.get(name, None))
if U is None: raise KeyError("'%s' gate unitary needs to be provided by `nonstd_gate_unitaries` arg" % name)
if callable(U): # then assume a function: args -> unitary
U0 = U(None) # U fns must return a sample unitary when passed None to get size.
gatedict[name] = _opfactory.UnitaryOpFactory(U, U0.shape[0], evotype=evotype)
else:
gatedict[name] = _bt.change_basis(_gt.unitary_to_process_mx(U), "std", "pp")
# assume evotype is a densitymx or term type
#Add anything from custom_gates directly if it wasn't added already
for lbl, gate in custom_gates.items():
if lbl not in gate_names: gatedict[lbl] = gate
return _CloudNoiseModel(nQubits, gatedict, availability, qubit_labels, geometry,
global_idle_layer, prep_layers, povm_layers,
build_cloudnoise_fn, build_cloudkey_fn,
sim_type, evotype, errcomp_type,
addIdleNoiseToAllGates, sparse, printer)
# -----------------------------------------------------------------------------------
# nqnoise gate sequence construction methods
# -----------------------------------------------------------------------------------
#Note: these methods assume a Model with:
# Gx and Gy gates on each qubit that are pi/2 rotations
# a prep labeled "rho0"
# a povm labeled "Mdefault" - so effects labeled "Mdefault_N" for N=0->2^nQubits-1
def _onqubit(s, iQubit):
""" Takes `s`, a tuple of gate *names* and creates a Circuit
where those names act on the `iQubit`-th qubit """
return _objs.Circuit([_Lbl(nm, iQubit) for nm in s])
def find_amped_polys_for_syntheticidle(qubit_filter, idleStr, model, singleQfiducials=None,
prepLbl=None, effectLbls=None, initJ=None, initJrank=None,
wrtParams=None, algorithm="greedy", require_all_amped=True,
idtPauliDicts=None, comm=None, verbosity=0):
"""
Find fiducial pairs which amplify the parameters of a synthetic idle gate.
This routine is primarily used internally within higher-level n-qubit
sequence selection routines.
Parameters
----------
qubit_filter : list
A list specifying which qubits fiducial pairs should be placed upon.
Typically this is a subset of all the qubits, as the synthetic idle
is composed of nontrivial gates acting on a localized set of qubits
and noise/errors are localized around these.
idleStr : Circuit
The operation sequence specifying the idle operation to consider. This may
just be a single idle gate, or it could be multiple non-idle gates
which together act as an idle.
model : Model
The model used to compute the polynomial expressions of probabilities
to first-order. Thus, this model should always have (simulation)
type "termorder:1".
singleQfiducials : list, optional
A list of gate-name tuples (e.g. `('Gx',)`) which specify a set of single-
qubit fiducials to use when trying to amplify gate parameters. Note that
no qubit "state-space" label is required here (i.e. *not* `(('Gx',1),)`);
the tuples just contain single-qubit gate *names*. If None, then
`[(), ('Gx',), ('Gy',)]` is used by default.
prepLbl : Label, optional
The state preparation label to use. If None, then the first (and
usually the only) state prep label of `model` is used, so it's
usually fine to leave this as None.
effectLbls : list, optional
The list of POVM effect labels to use, as a list of `Label` objects.
These are *simplified* POVM effect labels, so something like "Mdefault_0",
and if None the default is all the effect labels of the first POVM of
`model`, which is usually what you want.
initJ : numpy.ndarray, optional
An initial Jacobian giving the derivatives of some other polynomials
with respect to the same `wrtParams` that this function is called with.
This acts as a starting point, and essentially informs the fiducial-pair
selection algorithm that some parameters (or linear combos of them) are
*already* amplified (e.g. by some other germ that's already been
selected) and for which fiducial pairs are not needed.
initJrank : int, optional
The rank of `initJ`. The function could compute this from `initJ`
but in practice one usually has the rank of `initJ` lying around and
so this saves a call to `np.linalg.matrix_rank`.
wrtParams : slice, optional
The parameters to consider for amplification. (This function seeks
fiducial pairs that amplify these parameters.) If None, then pairs
which amplify all of `model`'s parameters are searched for.
algorithm : {"greedy","sequential"}
Which algorithm is used internally to find fiducial pairs. "greedy"
will give smaller sets of fiducial pairs (better) but takes longer.
Usually it's worth the wait and you should use the default ("greedy").
require_all_amped : bool, optional
If True and AssertionError is raised when fewer than all of the
requested parameters (in `wrtParams`) are amplifed by the final set of
fiducial pairs.
verbosity : int, optional
The level of detail printed to stdout. 0 means silent.
Returns
-------
J : numpy.ndarray
The final jacobian with rows equal to the number of chosen amplified
polynomials (note there is one row per fiducial pair *including* the
outcome - so there will be two different rows for two different
outcomes) and one column for each parameter specified by `wrtParams`.
Jrank : int
The rank of the jacobian `J`, equal to the number of amplified
parameters (at most the number requested).
fidpair_lists : list
The selected fiducial pairs, each in "gatename-fidpair-list" format.
Elements of `fidpair_lists` are themselves lists, all of length=#qubits.
Each element of these lists is a (prep1Qnames, meas1Qnames) 2-tuple
specifying the 1-qubit gates (by *name* only) on the corresponding qubit.
For example, the single fiducial pair prep=Gx:1Gy:2, meas=Gx:0Gy:0 in a
3-qubit system would have `fidpair_lists` equal to:
`[ [ [(),('Gx','Gy')], [('Gx',), () ], [('Gy',), () ] ] ]`
` < Q0 prep,meas >, < Q1 prep,meas >, < Q2 prep,meas >`
"""
#Note: "useful" fiducial pairs are identified by looking at the rank of a
# Jacobian matrix. Each row of this Jacobian is the derivative of the
# "amplified polynomial" - the L=1 polynomial for a fiducial pair (i.e.
# pr_poly(F1*(germ)*F2) ) minus the L=0 polynomial (i.e. pr_poly(F1*F2) ).
# When the model only gives probability polynomials to first order in
# the error rates this gives the L-dependent and hence amplified part
# of the polynomial expression for the probability of F1*(germ^L)*F2.
# This derivative of an amplified polynomial, taken with respect to
# all the parameters we care about (i.e. wrtParams) would ideally be
# kept as a polynomial and the "rank" of J would be the number of
# linearly independent polynomials within the rows of J (each poly
# would be a vector in the space of polynomials). We currently take
# a cheap/HACK way out and evaluate the derivative-polynomial at a
# random dummy value which should yield linearly dependent vectors
# in R^n whenever the polynomials are linearly indepdendent - then
# we can use the usual scipy/numpy routines for computing a matrix
# rank, etc.
# Assert that model uses termorder:1, as doing L1-L0 to extract the "amplified" part
# relies on only expanding to *first* order.
assert(model._sim_type == "termorder" and model._sim_args[0] == '1'), \
'`model` must use "termorder:1" simulation type!'
printer = _VerbosityPrinter.build_printer(verbosity, comm)
if prepLbl is None:
prepLbl = model._shlp.get_default_prep_lbl()
if effectLbls is None:
povmLbl = model._shlp.get_default_povm_lbl()
effectLbls = [_Lbl("%s_%s" % (povmLbl, l))
for l in model._shlp.get_effect_labels_for_povm(povmLbl)]
if singleQfiducials is None:
# TODO: assert model has Gx and Gy gates?
singleQfiducials = [(), ('Gx',), ('Gy',)] # ('Gx','Gx')
#dummy = 0.05*_np.ones(model.num_params(),'d') # for evaluating derivs...
#dummy = 0.05*_np.arange(1,model.num_params()+1) # for evaluating derivs...
#dummy = 0.05*_np.random.random(model.num_params())
dummy = 5.0 * _np.random.random(model.num_params()) + 0.5 * _np.ones(model.num_params(), 'd')
# expect terms to be either coeff*x or coeff*x^2 - (b/c of latter case don't eval at zero)
#amped_polys = []
selected_gatename_fidpair_lists = []
if wrtParams is None: wrtParams = slice(0, model.num_params())
Np = _slct.length(wrtParams)
if initJ is None: