-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathgermselection.py
5015 lines (4052 loc) · 229 KB
/
germselection.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
"""
Functions for selecting a complete set of germs for a GST analysis.
"""
#***************************************************************************************************
# 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 warnings as _warnings
import numpy as _np
import numpy.linalg as _nla
import random as _random
import scipy.linalg as _sla
import itertools
from math import floor
from pygsti.algorithms import grasp as _grasp
from pygsti.algorithms import scoring as _scoring
from pygsti import circuits as _circuits
from pygsti import baseobjs as _baseobjs
from pygsti.tools import mpitools as _mpit
from pygsti.baseobjs.statespace import ExplicitStateSpace as _ExplicitStateSpace
from pygsti.baseobjs.statespace import QuditSpace as _QuditSpace
from pygsti.models import ExplicitOpModel as _ExplicitOpModel
FLOATSIZE = 8 # in bytes: TODO: a better way
def find_germs(target_model, randomize=True, randomization_strength=1e-2,
num_gs_copies=5, seed=None, candidate_germ_counts=None,
candidate_seed=None, force="singletons", algorithm='greedy',
algorithm_kwargs=None, mem_limit=None, comm=None,
profiler=None, verbosity=1, num_nongauge_params=None,
assume_real=False, float_type=_np.cdouble,
mode="all-Jac", toss_random_frac=None,
force_rank_increase=False, save_cevd_cache_filename= None,
load_cevd_cache_filename=None, file_compression=False):
"""
Generate a germ set for doing GST with a given target model.
This function provides a streamlined interface to a variety of germ
selection algorithms. It's goal is to provide a method that typical users
can run by simply providing a target model and leaving all other settings
at their default values, while providing flexibility for users desiring
more control to fine tune some of the general and algorithm-specific
details.
Currently, to break troublesome degeneracies and provide some confidence
that the chosen germ set is amplificationally complete (AC) for all
models in a neighborhood of the target model (rather than only the
target model), an ensemble of models with random unitary perturbations
to their gates must be provided or generated.
Parameters
----------
target_model : Model or list of Model
The model you are aiming to implement, or a list of models that are
copies of the model you are trying to implement (either with or
without random unitary perturbations applied to the models).
randomize : bool, optional
Whether or not to add random unitary perturbations to the model(s)
provided.
randomization_strength : float, optional
The size of the random unitary perturbations applied to gates in the
model. See :meth:`~pygsti.objects.Model.randomize_with_unitary`
for more details.
num_gs_copies : int, optional
The number of copies of the original model that should be used.
seed : int, optional
Seed for generating random unitary perturbations to models. Also
passed along to stochastic germ-selection algorithms and to the
rng for dropping random fraction of germs.
candidate_germ_counts : dict, optional
A dictionary of *germ_length* : *count* key-value pairs, specifying
the germ "candidate list" - a list of potential germs to draw from.
*count* is either an integer specifying the number of random germs
considered at the given *germ_length* or the special values `"all upto"`
that considers all of the of all non-equivalent germs of length up to
the corresponding *germ_length*. If None, all germs of up to length
6 are used, the equivalent of `{6: 'all upto'}`.
candidate_seed : int, optional
A seed value used when randomly selecting candidate germs. For each
germ length being randomly selected, the germ length is added to
the value of `candidate_seed` to get the actual seed used.
force : str or list, optional
A list of Circuits which *must* be included in the final germ set.
If set to the special string "singletons" then all length-1 strings will
be included. Seting to None is the same as an empty list.
algorithm : {'greedy', 'grasp', 'slack'}, optional
Specifies the algorithm to use to generate the germ set. Current
options are:
'greedy' : Add germs one-at-a-time until the set is AC, picking the germ that
improves the germ-set score by the largest amount at each step. See
:func:`find_germs_breadthfirst` for more details.
'grasp': Use GRASP to generate random greedy germ sets and then locally
optimize them. See :func:`find_germs_grasp` for more
details.
'slack': From a initial set of germs, add or remove a germ at each step in
an attempt to improve the germ-set score. Will allow moves that
degrade the score in an attempt to escape local optima as long as
the degredation is within some specified amount of "slack". See
:func:`find_germs_integer_slack` for more details.
algorithm_kwargs : dict
Dictionary of ``{'keyword': keyword_arg}`` pairs providing keyword
arguments for the specified `algorithm` function. See the documentation
for functions referred to in the `algorithm` keyword documentation for
what options are available for each algorithm.
mem_limit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
profiler : Profiler, optional
A profiler object used for to track timing and memory usage.
verbosity : int, optional
The verbosity level of the :class:`~pygsti.objects.VerbosityPrinter`
used to print log messages.
num_nongauge_params : int, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
float_type : numpy dtype object, optional
Numpy data type to use for floating point arrays.
toss_random_frac : float, optional
If specified this is a number between 0 and 1 that indicates the random fraction of candidate
germs to drop randomly following the deduping procedure.
mode : {'allJac', 'singleJac', 'compactEVD'}, optional (default 'allJac')
A flag to indicate the caching scheme used for storing the Jacobians for the candidate
germs. Default value of 'allJac' caches all of the Jacobians and requires the most memory.
'singleJac' doesn't cache anything and instead generates these Jacobians on the fly. The
final option, 'compactEVD', is currently only configured to work with the greedy search
algorithm. When selected the compact eigenvalue decomposition/compact SVD of each of
the Jacobians is constructed and is cached. This uses an intermediate amount of memory
between singleJac and allJac. When compactEVD mode is selected perform the greedy
search iterations using an alternative method based on low-rank updates to the
psuedoinverse. This alternative approach means that this mode also only works with the
score function option set to 'all'.
force_rank_increase : bool, optional (default False)
Optional flag that can be used in conjunction with the greedy search algorithm
in compactEVD mode. When set we require that each subsequant addition to the germ
set must increase the rank of the experiment design's composite Jacobian. Can potentially
speed up the search when set to True.
save_cevd_cache_filename : str, optional (default None)
When set and using the greedy search algorithm in 'compactEVD' mode this writes
the compact EVD cache to disk using the specified filename.
load_cevd_cache_filename : str, optional (default None)
A filename/path to load an existing compact EVD cache from. Useful for warmstarting
a germ set search with various cost function parameters, or for restarting a search
that failed/crashed/ran out of memory. Note that there are no safety checks to confirm
that the compact EVD cache indeed corresponds to that for of currently specified
candidate circuit list, so care must be take to confirm that the candidate
germ lists are consistent across runs.
file_compression : bool, optional (default False)
When True and a filename is given for the save_cevd_cache_filename the corresponding
numpy arrays are stored in a compressed format using numpy's savez_compressed.
Can significantly decrease the storage requirements on disk at the expense of
some additional computational cost writing and loading the files.
Returns
-------
list of Circuit
A list containing the germs making up the germ set.
"""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity, comm)
modelList = _setup_model_list(target_model, randomize,
randomization_strength, num_gs_copies, seed)
gates = list(target_model.operations.keys())
availableGermsList = []
if candidate_germ_counts is None: candidate_germ_counts = {6: 'all upto'}
for germLength, count in candidate_germ_counts.items():
if count == "all upto":
availableGermsList.extend(_circuits.list_all_circuits_without_powers_and_cycles(
gates, max_length=germLength))
else:
if (candidate_seed is None) and (seed is not None):
candidate_seed=seed
availableGermsList.extend(_circuits.list_random_circuits_onelen(
gates, germLength, count, seed=candidate_seed))
printer.log('Initial Length Available Germ List: '+ str(len(availableGermsList)), 1)
#Let's try deduping the available germ list too:
#build a ckt cache
ckt_cache= create_circuit_cache(target_model, availableGermsList)
#Then dedupe this cache:
#The second value returned is an updated ckt cache which we don't need right now
availableGermsList, _ = clean_germ_list(target_model, ckt_cache, eq_thresh= 1e-6)
printer.log('Length Available Germ List After Deduping: '+ str(len(availableGermsList)), 1)
#If specified, drop a random fraction of the remaining candidate germs.
if toss_random_frac is not None:
availableGermsList = drop_random_germs(availableGermsList, toss_random_frac, target_model, keep_bare=True, seed=seed)
printer.log('Length Available Germ List After Dropping Random Fraction: '+ str(len(availableGermsList)), 1)
#If we have specified a user specified germs to force inclusion of then there is a chance
#they got removed by the deduping and removal of random circuits above. The right way to fix this
#would be to add some logic to those subroutines that prevent this, but for now I am going to just
#manually add them back in (this will result almost suredly in a couple duplicate circuits, but oh well).
if force is not None:
#iterate through the list of forced germs to check for inclusion and
#if missing append to the list of available germs.
if isinstance(force, list):
for forced_germ in force:
if not forced_germ in availableGermsList:
availableGermsList.append(forced_germ)
printer.log('Length Available Germ List After Adding Back In Forced Germs: '+ str(len(availableGermsList)), 1)
#Add some checks related to the new option to switch up data types:
if not assume_real:
if not (float_type is _np.cdouble or float_type is _np.csingle):
printer.log('Selected numpy type: '+ str(float_type.dtype), 1)
raise ValueError('Unless working with (known) real-valued quantities only, please select an appropriate complex numpy dtype (either cdouble or csingle).')
else:
if not (float_type is _np.double or float_type is _np.single):
printer.log('Selected numpy type: '+ str(float_type.dtype), 1)
raise ValueError('When assuming real-valued quantities, please select a real-values numpy dtype (either double or single).')
#How many bytes per float?
FLOATSIZE= float_type(0).itemsize
dim = target_model.dim
#Np = model_list[0].num_params #wrong:? includes spam...
Np = target_model.num_params
if randomize==False:
num_gs_copies=1
memEstimatealljac = FLOATSIZE * num_gs_copies * len(availableGermsList) * Np**2
# for _compute_bulk_twirled_ddd
memEstimatealljac += FLOATSIZE * num_gs_copies * len(availableGermsList) * dim**2 * Np
# for _bulk_twirled_deriv sub-call
printer.log("Memory estimate of %.1f GB for all-Jac mode." %
(memEstimatealljac / 1024.0**3), 1)
memEstimatesinglejac = FLOATSIZE * 3 * len(modelList) * Np**2 + \
FLOATSIZE * 3 * len(modelList) * dim**2 * Np
#Factor of 3 accounts for currentDDDs, testDDDs, and bestDDDs
printer.log("Memory estimate of %.1f GB for single-Jac mode." %
(memEstimatesinglejac / 1024.0**3), 1)
if mem_limit is not None:
if memEstimatealljac > mem_limit:
printer.log("Not enough memory for all-Jac mode, mem_limit is %.1f GB." %
(mem_limit / 1024.0**3), 1)
if memEstimatesinglejac > mem_limit:
raise MemoryError("Too little memory, even for single-Jac mode!")
if algorithm_kwargs is None:
# Avoid danger of using empty dict for default value.
algorithm_kwargs = {}
if algorithm == 'greedy':
printer.log('Using greedy algorithm.', 1)
# Define defaults for parameters that currently have no default or
# whose default we want to change.
default_kwargs = {
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'verbosity': max(0, verbosity - 1),
'force': force,
'op_penalty': 0.0,
'score_func': 'all',
'comm': comm,
'mem_limit': mem_limit,
'profiler': profiler,
'num_nongauge_params': num_nongauge_params,
'float_type': float_type,
'mode' : mode,
'force_rank_increase': force_rank_increase,
'save_cevd_cache_filename': save_cevd_cache_filename,
'load_cevd_cache_filename': load_cevd_cache_filename,
'file_compression': file_compression,
'evd_tol': 1e-10,
'initial_germ_set_test': True
}
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_breadthfirst_greedy(model_list=modelList,
**algorithm_kwargs)
if germList is not None:
#TODO: We should already know the value of this from
#the final output of our optimization loop, so we ought
#to be able to avoid this function call and related overhead.
germsetScore = compute_germ_set_score(
germList, neighborhood=modelList,
score_func=algorithm_kwargs['score_func'],
op_penalty=algorithm_kwargs['op_penalty'],
num_nongauge_params=num_nongauge_params,
float_type=float_type)
printer.log('Constructed germ set:', 1)
printer.log(str([germ.str for germ in germList]), 1)
printer.log(germsetScore, 1)
elif algorithm == 'grasp':
printer.log('Using GRASP algorithm.', 1)
# Define defaults for parameters that currently have no default or
# whose default we want to change.
default_kwargs = {
'alpha': 0.1, # No real reason for setting this value of alpha.
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'l1_penalty': 0.0,
'op_penalty': 0.0,
'verbosity': max(0, verbosity - 1),
'force': force,
'return_all': False,
'score_func': 'all',
'num_nongauge_params': num_nongauge_params,
'float_type': float_type
}
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_grasp(model_list=modelList,
**algorithm_kwargs)
printer.log('Constructed germ set:', 1)
if algorithm_kwargs['return_all'] and germList[0] is not None:
germsetScore = compute_germ_set_score(
germList[0], neighborhood=modelList,
score_func=algorithm_kwargs['score_func'],
op_penalty=algorithm_kwargs['op_penalty'],
l1_penalty=algorithm_kwargs['l1_penalty'],
num_nongauge_params=num_nongauge_params,
float_type=float_type)
printer.log(str([germ.str for germ in germList[0]]), 1)
printer.log(germsetScore)
elif not algorithm_kwargs['return_all'] and germList is not None:
germsetScore = compute_germ_set_score(
germList, neighborhood=modelList,
score_func=algorithm_kwargs['score_func'],
op_penalty=algorithm_kwargs['op_penalty'],
l1_penalty=algorithm_kwargs['l1_penalty'],
num_nongauge_params=num_nongauge_params,
float_type=float_type)
printer.log(str([germ.str for germ in germList]), 1)
printer.log(germsetScore, 1)
elif algorithm == 'slack':
printer.log('Using slack algorithm.', 1)
# Define defaults for parameters that currently have no default or
# whose default we want to change.
default_kwargs = {
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'verbosity': max(0, verbosity - 1),
'l1_penalty': 0.0,
'op_penalty': 0.0,
'force': force,
'score_func': 'all',
'float_type': float_type
}
if ('slack_frac' not in algorithm_kwargs
and 'fixed_slack' not in algorithm_kwargs):
algorithm_kwargs['slack_frac'] = 0.1
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_integer_slack(modelList,
**algorithm_kwargs)
if germList is not None:
germsetScore = compute_germ_set_score(
germList, neighborhood=modelList,
score_func=algorithm_kwargs['score_func'],
op_penalty=algorithm_kwargs['op_penalty'],
l1_penalty=algorithm_kwargs['l1_penalty'],
num_nongauge_params=num_nongauge_params,
float_type=float_type)
printer.log('Constructed germ set:', 1)
printer.log(str([germ.str for germ in germList]), 1)
printer.log(germsetScore, 1)
else:
raise ValueError("'{}' is not a valid algorithm "
"identifier.".format(algorithm))
return germList
def compute_germ_set_score(germs, target_model=None, neighborhood=None,
neighborhood_size=5,
randomization_strength=1e-2, score_func='all',
op_penalty=0.0, l1_penalty=0.0, num_nongauge_params=None,
float_type=_np.cdouble):
"""
Calculate the score of a germ set with respect to a model.
More precisely, this function computes the maximum score (roughly equal
to the number of amplified parameters) for a cloud of models.
If `target_model` is given, it serves as the center of the cloud,
otherwise the cloud must be supplied directly via `neighborhood`.
Parameters
----------
germs : list
The germ set
target_model : Model, optional
The target model, used to generate a neighborhood of randomized models.
neighborhood : list of Models, optional
The "cloud" of models for which scores are computed. If not None, this
overrides `target_model`, `neighborhood_size`, and `randomization_strength`.
neighborhood_size : int, optional
Number of randomized models to construct around `target_model`.
randomization_strength : float, optional
Strength of unitary randomizations, as passed to :meth:`target_model.randomize_with_unitary`.
score_func : {'all', 'worst'}
Sets the objective function for scoring the eigenvalues. If 'all',
score is ``sum(1/input_array)``. If 'worst', score is ``1/min(input_array)``.
op_penalty : float, optional
Coefficient for a penalty linear in the sum of the germ lengths.
l1_penalty : float, optional
Coefficient for a penalty linear in the number of germs.
num_nongauge_params : int, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
float_type : numpy dtype object, optional
Numpy data type to use for floating point arrays.
Returns
-------
CompositeScore
The maximum score for `germs`, indicating how many parameters it amplifies.
"""
def score_fn(x): return _scoring.list_score(x, score_func=score_func)
if neighborhood is None:
neighborhood = [target_model.randomize_with_unitary(randomization_strength)
for n in range(neighborhood_size)]
scores = [compute_composite_germ_set_score(score_fn, model=model,
partial_germs_list=germs,
op_penalty=op_penalty,
l1_penalty=l1_penalty,
num_nongauge_params=num_nongauge_params,
float_type=float_type)
for model in neighborhood]
return max(scores)
def _get_model_params(model_list, printer=None):
"""
Get the number of gates and gauge parameters of the models in a list.
Also verifies all models have the same number of gates and gauge parameters.
Parameters
----------
model_list : list of Model
A list of models for which you want an AC germ set.
Returns
-------
reducedModelList : list of Model
The original list of models with SPAM removed
numGaugeParams : int
The number of non-SPAM gauge parameters for all models.
numNonGaugeParams : int
The number of non-SPAM non-gauge parameters for all models.
numOps : int
The number of gates for all models.
Raises
------
ValueError
If the number of gauge parameters or gates varies among the models.
"""
if printer is not None:
printer.log('Calculating number of gauge and non-gauge parameters', 1)
# We don't care about SPAM, since it can't be amplified.
reducedModelList = [_remove_spam_vectors(model)
for model in model_list]
# All the models should have the same number of parameters and gates, but
# let's be paranoid here for the time being and make sure.
numGaugeParamsList = [reducedModel.num_gauge_params
for reducedModel in reducedModelList]
numGaugeParams = numGaugeParamsList[0]
if not all([numGaugeParams == otherNumGaugeParams
for otherNumGaugeParams in numGaugeParamsList[1:]]):
raise ValueError("All models must have the same number of gauge "
"parameters!")
numNonGaugeParamsList = [reducedModel.num_nongauge_params
for reducedModel in reducedModelList]
numNonGaugeParams = numNonGaugeParamsList[0]
if not all([numNonGaugeParams == otherNumNonGaugeParams
for otherNumNonGaugeParams in numNonGaugeParamsList[1:]]):
raise ValueError("All models must have the same number of non-gauge "
"parameters!")
numOpsList = [len(reducedModel.operations)
for reducedModel in reducedModelList]
numOps = numOpsList[0]
if not all([numOps == otherNumOps
for otherNumOps in numOpsList[1:]]):
raise ValueError("All models must have the same number of gates!")
return reducedModelList, numGaugeParams, numNonGaugeParams, numOps
def _setup_model_list(model_list, randomize, randomization_strength,
num_copies, seed):
"""
Sets up a list of randomize models (helper function).
"""
if not isinstance(model_list, (list, tuple)):
model_list = [model_list]
if len(model_list) > 1 and num_copies is not None:
_warnings.warn("Ignoring num_copies={} since multiple models were "
"supplied.".format(num_copies))
if randomize:
model_list = randomize_model_list(model_list, randomization_strength,
num_copies, seed)
return model_list
def compute_composite_germ_set_score(score_fn, threshold_ac=1e6, init_n=1,
partial_deriv_dagger_deriv=None, model=None,
partial_germs_list=None, eps=None, germ_lengths=None,
op_penalty=0.0, l1_penalty=0.0, num_nongauge_params=None,
float_type=_np.cdouble):
"""
Compute the score for a germ set when it is not AC against a model.
Normally scores computed for germ sets against models for which they are
not AC will simply be astronomically large. This is fine if AC is all you
care about, but not so useful if you want to compare partial germ sets
against one another to see which is closer to being AC. This function
will see if the germ set is AC for the parameters corresponding to the
largest `N` eigenvalues for increasing `N` until it finds a value of `N`
for which the germ set is not AC or all the non gauge parameters are
accounted for and report the value of `N` as well as the score.
This allows partial germ set scores to be compared against one-another
sensibly, where a larger value of `N` always beats a smaller value of `N`,
and ties in the value of `N` are broken by the score for that value of `N`.
Parameters
----------
score_fn : callable
A function that takes as input a list of sorted eigenvalues and returns
a score for the partial germ set based on those eigenvalues, with lower
scores indicating better germ sets. Usually some flavor of
:func:`~pygsti.algorithms.scoring.list_score`.
threshold_ac : float, optional
Value which the score (before penalties are applied) must be lower than
for the germ set to be considered AC.
init_n : int
The number of largest eigenvalues to begin with checking.
partial_deriv_dagger_deriv : numpy.array, optional
Array with three axes, where the first axis indexes individual germs
within the partial germ set and the remaining axes index entries in the
positive square of the Jacobian of each individual germ's parameters
with respect to the model parameters.
If this array is not supplied it will need to be computed from
`germs_list` and `model`, which will take longer, so it is recommended
to precompute this array if this routine will be called multiple times.
model : Model, optional
The model against which the germ set is to be scored. Not needed if
`partial_deriv_dagger_deriv` is provided.
partial_germs_list : list of Circuit, optional
The list of germs in the partial germ set to be evaluated. Not needed
if `partial_deriv_dagger_deriv` (and `germ_lengths` when
``op_penalty > 0``) are provided.
eps : float, optional
Used when calculating `partial_deriv_dagger_deriv` to determine if two
eigenvalues are equal (see :func:`~pygsti.algorithms.germselection._bulk_twirled_deriv` for details). Not
used if `partial_deriv_dagger_deriv` is provided.
op_penalty : float, optional
Coefficient for a penalty linear in the sum of the germ lengths.
germ_lengths : numpy.array, optional
The length of each germ. Not needed if `op_penalty` is ``0.0`` or
`partial_germs_list` is provided.
l1_penalty : float, optional
Coefficient for a penalty linear in the number of germs.
num_nongauge_params : int, optional
Force the number of nongauge parameters rather than rely on automated gauge optimization.
Returns
-------
CompositeScore
The score for the germ set indicating how many parameters it amplifies
and its numerical score restricted to those parameters.
"""
if partial_deriv_dagger_deriv is None:
if model is None or partial_germs_list is None:
raise ValueError("Must provide either partial_deriv_dagger_deriv or "
"(model, partial_germs_list)!")
else:
Np= model.num_params
combinedDDD=_np.zeros((Np, Np), dtype=float_type)
pDDD_kwargs = {'float_type':float_type}
if eps is not None:
pDDD_kwargs['eps'] = eps
#use a more memory efficient calculation when generating
#twirled ddd from scratch again.
for germ in partial_germs_list:
combinedDDD += _compute_twirled_ddd(model, germ, **pDDD_kwargs)
if num_nongauge_params is None:
if model is None:
raise ValueError("Must provide either num_nongauge_params or model!")
else:
reduced_model = _remove_spam_vectors(model)
num_nongauge_params = reduced_model.num_params - reduced_model.num_gauge_params
# Calculate penalty scores
if partial_deriv_dagger_deriv is None:
numGerms= len(partial_germs_list)
else:
numGerms = partial_deriv_dagger_deriv.shape[0]
l1Score = l1_penalty * numGerms
opScore = 0.0
if op_penalty != 0.0:
if germ_lengths is None:
if partial_germs_list is None:
raise ValueError("Must provide either germ_lengths or "
"partial_germs_list when op_penalty != 0.0!")
else:
germ_lengths = _np.array([len(germ)
for germ in partial_germs_list])
opScore = op_penalty * _np.sum(germ_lengths)
if partial_deriv_dagger_deriv is not None:
combinedDDD = _np.sum(partial_deriv_dagger_deriv, axis=0)
sortedEigenvals = _np.sort(_np.real(_nla.eigvalsh(combinedDDD)))
observableEigenvals = sortedEigenvals[-num_nongauge_params:]
N_AC = 0
AC_score = _np.inf
for N in range(init_n, len(observableEigenvals) + 1):
scoredEigenvals = observableEigenvals[-N:]
candidate_AC_score = score_fn(scoredEigenvals)
if candidate_AC_score > threshold_ac:
break # We've found a set of parameters for which the germ set
# is not AC.
else:
AC_score = candidate_AC_score
N_AC = N
# OLD Apply penalties to the minor score; major part is just #amplified
#major_score = N_AC
#minor_score = AC_score + l1Score + opScore
# Apply penalties to the major score
major_score = -N_AC + opScore + l1Score
minor_score = AC_score
ret = _scoring.CompositeScore(major_score, minor_score, N_AC)
#DEBUG: ret.extra = {'opScore': opScore,
# 'sum(germ_lengths)': _np.sum(germ_lengths), 'l1': l1Score}
return ret
def _compute_bulk_twirled_ddd(model, germs_list, eps=1e-6, check=False,
germ_lengths=None, comm=None, float_type=_np.cdouble):
"""
Calculate the positive squares of the germ Jacobians.
twirledDerivDaggerDeriv == array J.H*J contributions from each germ
(J=Jacobian) indexed by (iGerm, iModelParam1, iModelParam2)
size (nGerms, vec_model_dim, vec_model_dim)
Parameters
----------
model : Model
The model defining the parameters to differentiate with respect to.
germs_list : list
The germ set
eps : float, optional
Tolerance used for testing whether two eigenvectors are degenerate
(i.e. abs(eval1 - eval2) < eps ? )
check : bool, optional
Whether to perform internal consistency checks, at the expense of
making the function slower.
germ_lengths : numpy.ndarray, optional
A pre-computed array of the length (depth) of each germ.
comm : mpi4py.MPI.Comm, optional
When not ``None``, an MPI communicator for distributing the computation
across multiple processors.
float_type : numpy dtype object, optional
Numpy data type to use in floating point arrays.
Returns
-------
twirledDerivDaggerDeriv : numpy.ndarray
A complex array of shape `(len(germs), model.num_params, model.num_params)`.
"""
if germ_lengths is None:
germ_lengths = _np.array([len(germ) for germ in germs_list])
twirledDeriv = _bulk_twirled_deriv(model, germs_list, eps, check, comm, float_type=float_type) / germ_lengths[:, None, None]
#OLD: slow, I think because conjugate *copies* a large tensor, causing a memory bottleneck
#twirledDerivDaggerDeriv = _np.einsum('ijk,ijl->ikl',
# _np.conjugate(twirledDeriv),
# twirledDeriv)
#NEW: faster, one-germ-at-a-time computation requires less memory.
nGerms, _, vec_model_dim = twirledDeriv.shape
twirledDerivDaggerDeriv = _np.empty((nGerms, vec_model_dim, vec_model_dim),
dtype=float_type)
for i in range(nGerms):
twirledDerivDaggerDeriv[i, :, :] = _np.dot(
twirledDeriv[i, :, :].conjugate().T, twirledDeriv[i, :, :])
return twirledDerivDaggerDeriv
def _compute_twirled_ddd(model, germ, eps=1e-6, float_type=_np.cdouble):
"""
Calculate the positive squares of the germ Jacobian.
twirledDerivDaggerDeriv == array J.H*J contributions from `germ`
(J=Jacobian) indexed by (iModelParam1, iModelParam2)
size (vec_model_dim, vec_model_dim)
Parameters
----------
model : Model
The model defining the parameters to differentiate with respect to.
germ : Circuit
The (single) germ circuit to consider. `J` above is the twirled
derivative of this circuit's action (process matrix).
eps : float, optional
Tolerance used for testing whether two eigenvectors are degenerate
(i.e. abs(eval1 - eval2) < eps ? )
Returns
-------
numpy.ndarray
"""
twirledDeriv = _twirled_deriv(model, germ, eps, float_type) / len(germ)
#twirledDerivDaggerDeriv = _np.einsum('jk,jl->kl',
# _np.conjugate(twirledDeriv),
# twirledDeriv)
twirledDerivDaggerDeriv = _np.tensordot(_np.conjugate(twirledDeriv),
twirledDeriv, (0, 0))
return twirledDerivDaggerDeriv
def _germ_set_score_slack(weights, model_num, score_func, deriv_dagger_deriv_list,
force_indices, force_score,
n_gauge_params, op_penalty, germ_lengths, l1_penalty=1e-2,
score_dict=None):
"""
Returns a germ set "score" in which smaller is better.
Also returns intentionally bad score (`force_score`) if `weights` is zero on any of
the "forced" germs (i.e. at any index in `forcedIndices`).
This function is included for use by :func:`find_germs_integer_slack`,
but is not convenient for just computing the score of a germ set. For that,
use :func:`compute_germ_set_score`.
Parameters
----------
weights : list
The per-germ "selection weight", indicating whether the germ
is present in the selected germ set or not.
model_num : int
index into `deriv_dagger_deriv_list` indicating which model (typically in
a neighborhood) we're computing scores for.
score_func : {'all', 'worst'}
Sets the objective function for scoring the eigenvalues. If 'all',
score is ``sum(1/input_array)``. If 'worst', score is ``1/min(input_array)``.
deriv_dagger_deriv_list : numpy.ndarray
Array of J.T * J contributions for each model.
force_indices : list of ints
Indices marking the germs that *must* be in the final set (or else `force_score`
will be returned).
force_score : float
The score that is returned when any of the germs indexed by `force_indices` are
not present (i.e. their weights are <= 0).
n_gauge_params : int
The number of gauge (not amplifiable) parameters in the model.
op_penalty : float
Coefficient for a penalty linear in the sum of the germ lengths.
germ_lengths : numpy.ndarray
A pre-computed array of the length (depth) of each germ.
l1_penalty : float
Coefficient for a penalty linear in the number of germs.
score_dict : dict, optional
A dictionary to cache the score valies for the given `model_num` and
`weights`, i.e. `score_dict[model_num, tuple(weights)]` is set to the
returned value.
Returns
-------
float
"""
if force_indices is not None and _np.any(weights[force_indices] <= 0):
score = force_score
else:
#combinedDDD = _np.einsum('i,ijk', weights,
# deriv_dagger_deriv_list[model_num])
combinedDDD = _np.squeeze(
_np.tensordot(_np.expand_dims(weights, 1),
deriv_dagger_deriv_list[model_num], (0, 0)))
assert len(combinedDDD.shape) == 2
sortedEigenvals = _np.sort(_np.real(_nla.eigvalsh(combinedDDD)))
observableEigenvals = sortedEigenvals[n_gauge_params:]
score = (_scoring.list_score(observableEigenvals, score_func)
+ l1_penalty * _np.sum(weights)
+ op_penalty * _np.dot(germ_lengths, weights))
if score_dict is not None:
# Side effect: calling _germ_set_score_slack caches result in score_dict
score_dict[model_num, tuple(weights)] = score
return score
def randomize_model_list(model_list, randomization_strength, num_copies,
seed=None):
"""
Applies random unitary perturbations to a model or list of models.
If `model_list` is a length-1 list, then `num_copies` determines how
many randomizations to create. If `model_list` containes multiple
models, then `num_copies` must be `None` and each model is
randomized once to create the corresponding returned model.
Parameters
----------
model_list : Model or list
A list of Model objects.
randomization_strength : float, optional
Strength of unitary randomizations, as passed to :meth:`Model.randomize_with_unitary`.
num_copies : int
The number of random perturbations of `model_list[0]` to generate when
`len(model_list) == 1`. A value of `None` will result in 1 copy. If
`len(model_list) > 1` then `num_copies` must be set to None.
seed : int, optional
Starting seed for randomization. Successive randomizations receive
successive seeds. `None` results in random seeds.
Returns
-------
list
A list of the randomized Models.
"""
if len(model_list) > 1 and num_copies is not None:
raise ValueError("Input multiple models XOR request multiple "
"copies only!")
newmodelList = []
if len(model_list) > 1:
for modelnum, model in enumerate(model_list):
newmodelList.append(model.randomize_with_unitary(
randomization_strength,
seed=None if seed is None else seed + modelnum))
else:
for modelnum in range(num_copies if num_copies is not None else 1):
newmodelList.append(model_list[0].randomize_with_unitary(
randomization_strength,
seed=None if seed is None else seed + modelnum))
return newmodelList
def test_germs_list_completeness(model_list, germs_list, score_func, threshold, float_type=_np.cdouble, comm=None, num_gauge_params = None):
"""
Check to see if the germs_list is amplificationally complete (AC).
Checks for AC with respect to all the Models in `model_list`, returning
the index of the first Model for which it is not AC or `-1` if it is AC
for all Models.
Parameters
----------
model_list : list
A list of models to test. Often this list is a neighborhood ("cloud") of
models around a model of interest.
germs_list : list
A list of the germ :class:`Circuit` objects (the "germ set") to test for completeness.
score_func : {'all', 'worst'}
Sets the objective function for scoring the eigenvalues. If 'all',
score is ``sum(1/eigval_array)``. If 'worst', score is ``1/min(eigval_array)``.
threshold : float, optional
An eigenvalue of `jacobian^T*jacobian` is considered zero and thus a
parameter un-amplified when its reciprocal is greater than threshold.
Also used for eigenvector degeneracy testing in twirling operation.
float_type : numpy dtype object, optional
Numpy data type to use for floating point arrays.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
num_gauge_params : int, optional (default None)
A optional kwarg for specifying the number of gauge
parameters. Specifying this if already precomputed can
save on computation.
Returns
-------
int
The index of the first model in `model_list` to fail the amplficational
completeness test. Returns -1 if germ set is AC for all tested models.
"""
for modelNum, model in enumerate(model_list):
initial_test = test_germ_set_infl(model, germs_list,
score_func=score_func,
threshold=threshold, float_type=float_type,
comm=comm)
if not initial_test:
return modelNum
# If the germs_list is complete for all models, return -1
return -1
def _remove_spam_vectors(model):
"""
Returns a copy of `model` with state preparations and effects removed.
Parameters
----------
model : Model
The model to act on.
Returns
-------
Model
"""
reducedModel = model.copy()
try:
for prepLabel in list(reducedModel.preps.keys()):