-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
inference.py
1687 lines (1436 loc) · 64 KB
/
inference.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 (C) 2020 Unitary Fund
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Classes corresponding to different zero-noise extrapolation methods."""
from abc import ABC, abstractmethod
from copy import deepcopy
from typing import (
Any,
Callable,
cast,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
)
import warnings
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
import numpy.typing as npt
from numpy.lib.polynomial import RankWarning
from scipy.optimize import curve_fit, OptimizeWarning
from cirq import Circuit
from mitiq._typing import QPROGRAM, QuantumResult
from mitiq.observable import Observable
from mitiq.executor import Executor
from mitiq.zne.scaling import fold_gates_at_random
from mitiq.interface import accept_any_qprogram_as_input
ExtrapolationResult = Union[
float, # The zero-noise value.
Tuple[
float, # The zero-noise value.
Optional[float], # The (estimated) error on the zero-noise value.
List[float], # Optimal parameters found during fitting.
Optional[np.ndarray], # Covariance of fitting parameters.
Callable[[float], float], # Function that was fit.
],
]
class ExtrapolationError(Exception):
"""Error raised by :class:`.Factory` objects when
the extrapolation fit fails.
"""
pass
_EXTR_ERR = (
"The extrapolation fit failed to converge."
" The problem may be solved by switching to a more stable"
" extrapolation model such as `LinearFactory`."
)
class ExtrapolationWarning(Warning):
"""Warning raised by :class:`.Factory` objects when
the extrapolation fit is ill-conditioned.
"""
pass
_EXTR_WARN = (
"The extrapolation fit may be ill-conditioned."
" Likely, more data points are necessary to fit the parameters"
" of the model."
)
DATA_MISSING_ERR = (
"Data is either ill-defined or not enough to evaluate the required"
" information. Please make sure that the 'run' and 'reduce' methods"
" have been called and that enough expectation values have been measured."
)
class ConvergenceWarning(Warning):
"""Warning raised by :class:`.Factory` objects when
their `run_classical` method fails to converge.
"""
pass
@accept_any_qprogram_as_input
def _check_circuit_length(circuit: Circuit) -> None:
"""Raises a warning if the circuit is too short."""
if len(list(circuit.all_operations())) < 5:
warnings.warn(
"The input circuit is very short. "
"This may reduce the accuracy of noise scaling."
)
def mitiq_curve_fit(
ansatz: Callable[..., float],
scale_factors: Sequence[float],
exp_values: Sequence[float],
init_params: Optional[List[float]] = None,
) -> Tuple[List[float], npt.NDArray[np.float64]]:
"""Fits the ansatz to the (scale factor, expectation value) data using
``scipy.optimize.curve_fit``, returning the optimal parameters and
covariance matrix of the parameters.
Args:
ansatz: The model function used for zero-noise extrapolation. The first
argument is the noise scale variable, the remaining arguments are
the parameters to fit.
scale_factors: The array of noise scale factors.
exp_values: The array of expectation values.
init_params: Initial guess for the parameters. If None, the initial
values are set to 1.
Returns:
The array of optimal parameters and the covariance matrix of the
parameters. If the fit is ill-conditioned, the covariance matrix may
contain np.inf elements.
Raises:
ExtrapolationError: If the extrapolation fit fails.
ExtrapolationWarning: If the extrapolation fit is ill-conditioned.
"""
try:
with warnings.catch_warnings(record=True) as warn_list:
opt_params, params_cov = curve_fit(
ansatz, scale_factors, exp_values, p0=init_params
)
for warn in warn_list:
# replace OptimizeWarning with ExtrapolationWarning
if warn.category is OptimizeWarning:
warn.category = ExtrapolationWarning
warn.message = _EXTR_WARN # type: ignore
# re-raise all warnings
warnings.warn_explicit(
warn.message, warn.category, warn.filename, warn.lineno
)
except RuntimeError:
raise ExtrapolationError(_EXTR_ERR) from None
return list(opt_params), params_cov
def mitiq_polyfit(
scale_factors: Sequence[float],
exp_values: Sequence[float],
deg: int,
weights: Optional[Sequence[float]] = None,
) -> Tuple[List[float], Optional[npt.NDArray[np.float64]]]:
"""Fits the ansatz to the (scale factor, expectation value) data using
``numpy.polyfit``, returning the optimal parameters and covariance matrix
of the parameters.
Args:
scale_factors: The array of noise scale factors.
exp_values: The array of expectation values.
deg: The degree of the polynomial fit.
weights: Optional array of weights for each sampled point.
This is used to make a weighted least squares fit.
Returns:
The optimal parameters and covariance matrix of the parameters.
If there is not enough data to estimate the covariance matrix, it is
returned as None.
Raises:
ExtrapolationWarning: If the extrapolation fit is ill-conditioned.
"""
with warnings.catch_warnings(record=True) as warn_list:
try:
opt_params, params_cov = np.polyfit(
scale_factors, exp_values, deg, w=weights, cov=True
)
except (ValueError, np.linalg.LinAlgError):
opt_params = np.polyfit(scale_factors, exp_values, deg, w=weights)
params_cov = None
for warn in warn_list:
# replace RankWarning with ExtrapolationWarning
if warn.category is RankWarning:
warn.category = ExtrapolationWarning
warn.message = _EXTR_WARN # type: ignore
# re-raise all warnings
warnings.warn_explicit(
warn.message, warn.category, warn.filename, warn.lineno
)
return list(opt_params), params_cov
class Factory(ABC):
"""Abstract base class which performs the classical parts of zero-noise
extrapolation. This minimally includes:
* scaling circuits,
* sending jobs to execute,
* collecting the results,
* fitting the collected data,
* Extrapolating to the zero-noise limit.
If all scale factors are set a priori, the jobs can be batched. This is
handled by a BatchedFactory.
If the next scale factor depends on the previous history of results,
jobs are run sequentially. This is handled by an AdaptiveFactory.
"""
def __init__(self) -> None:
self._instack: List[Dict[str, float]] = []
self._outstack: List[float] = []
self._opt_params: Optional[List[float]] = None
self._params_cov: Optional[npt.NDArray[np.float64]] = None
self._zne_limit: Optional[float] = None
self._zne_error: Optional[float] = None
self._zne_curve: Optional[Callable[[float], float]] = None
self._already_reduced = False
self._options: Dict[str, Optional[float]] = {}
def get_scale_factors(self) -> npt.NDArray[np.float64]:
"""Returns the scale factors at which the factory has computed
expectation values.
"""
return np.array(
[params.get("scale_factor") for params in self._instack]
)
def get_expectation_values(self) -> npt.NDArray[np.float64]:
"""Returns the expectation values computed by the factory."""
return np.array(self._outstack)
def get_optimal_parameters(self) -> npt.NDArray[np.float64]:
"""Returns the optimal model parameters produced by the extrapolation
fit.
"""
if self._opt_params is None:
raise ValueError(DATA_MISSING_ERR)
return np.array(self._opt_params)
def get_parameters_covariance(self) -> npt.NDArray[np.float64]:
"""Returns the covariance matrix of the model parameters produced by
the extrapolation fit.
"""
if self._params_cov is None:
raise ValueError(DATA_MISSING_ERR)
return np.array(self._params_cov)
def get_zero_noise_limit(self) -> float:
"""Returns the last evaluation of the zero-noise limit
computed by the factory. To re-evaluate
its value, the method 'reduce' should be called first.
"""
if self._zne_limit is None:
raise ValueError(DATA_MISSING_ERR)
return self._zne_limit
def get_zero_noise_limit_error(self) -> float:
"""Returns the extrapolation error representing the uncertainty
affecting the zero-noise limit. It is deduced by error propagation
from the covariance matrix associated to the fit parameters.
Note: this quantity is only related to the ability of the model
to fit the measured data. Therefore, it may underestimate the
actual error existing between the zero-noise limit and the
true ideal expectation value.
"""
if self._zne_error is None:
raise ValueError(DATA_MISSING_ERR)
return self._zne_error
def get_extrapolation_curve(self) -> Callable[[float], float]:
"""Returns the extrapolation curve, i.e., a function which
inputs a noise scale factor and outputs the associated expectation
value. This function is the solution of the regression problem
used to evaluate the zero-noise extrapolation.
"""
if self._zne_curve is None:
raise ValueError(DATA_MISSING_ERR)
return self._zne_curve
@abstractmethod
def run(
self,
qp: QPROGRAM,
executor: Union[Executor, Callable[..., QuantumResult]],
observable: Optional[Observable] = None,
scale_noise: Callable[
[QPROGRAM, float], QPROGRAM
] = fold_gates_at_random,
num_to_average: int = 1,
) -> "Factory":
"""Calls the executor function on noise-scaled quantum circuit and
stores the results.
Args:
qp: Quantum circuit to scale noise in.
executor: A ``mitiq.Executor`` or a function which inputs a (list
of) quantum circuits and outputs a (list of)
``mitiq.QuantumResult`` s.
observable: Observable to compute the expectation value of. If
None, the `executor` must return an expectation value.
Otherwise, the `QuantumResult` returned by `executor` is used
to compute the expectation of the observable.
scale_noise: Function which inputs a quantum circuit and outputs
a noise-scaled quantum circuit.
num_to_average: Number of times the executor function is called
on each noise-scaled quantum circuit.
"""
raise NotImplementedError
@abstractmethod
def run_classical(
self,
scale_factor_to_expectation_value: Callable[..., float],
) -> "Factory":
"""Calls the function scale_factor_to_expectation_value at each scale
factor of the factory, and stores the results.
Args:
scale_factor_to_expectation_value: A function which inputs a scale
factor and outputs an expectation value. This does not have to
involve a quantum processor making this a "classical analogue"
of the run method.
"""
raise NotImplementedError
@abstractmethod
def reduce(self) -> float:
raise NotImplementedError
def push(
self, instack_val: Dict[str, float], outstack_val: float
) -> "Factory":
"""Appends "instack_val" to "self._instack" and "outstack_val" to
"self._outstack". Each time a new expectation value is computed this
method should be used to update the internal state of the Factory.
"""
if self._already_reduced:
warnings.warn(
"You are pushing new data into a factory object despite its "
".reduce() method has already been called. Please make "
"sure your intention is to append new data to the stack of "
"previous data. Otherwise, the method .reset() can be used "
"to clean the internal state of the factory.",
ExtrapolationWarning,
)
self._instack.append(instack_val)
self._outstack.append(outstack_val)
return self
def plot_data(self) -> Figure:
"""Returns a figure which is a scatter plot of (x, y) data where x are
scale factors at which expectation values have been computed, and y are
the associated expectation values.
Returns:
fig: A 2D scatter plot described above.
"""
fig = plt.figure(figsize=(7, 5))
ax = plt.gca()
plt.plot(
self.get_scale_factors(),
self.get_expectation_values(),
"o",
markersize=10,
markeredgecolor="black",
alpha=0.8,
label="Data",
)
ax.grid(True)
plt.xlabel("Noise scale factor")
plt.ylabel("Expectation value")
return fig
def plot_fit(self) -> Figure:
"""Returns a figure which plots the experimental data as well as the
best fit curve.
Returns:
fig: A figure which plots the best fit curve as well as the data.
"""
fig = self.plot_data()
smooth_scale_factors = np.linspace(0, self.get_scale_factors()[-1], 20)
smooth_expectations = [
self.get_extrapolation_curve()(scale_factor)
for scale_factor in smooth_scale_factors
]
plt.xlim(left=0)
fig.axes[0].plot(
smooth_scale_factors,
smooth_expectations,
"--",
lw=2,
color="black",
label="Best fit",
)
return fig
def reset(self) -> "Factory":
"""Resets the internal state of the Factory."""
self._instack = []
self._outstack = []
self._opt_params = None
self._params_cov = None
self._zne_limit = None
self._zne_error = None
self._already_reduced = False
return self
class BatchedFactory(Factory, ABC):
"""Abstract class of a non-adaptive Factory initialized with a
pre-determined set of scale factors.
Specific (non-adaptive) extrapolation algorithms are derived from this
class by defining the `reduce` method.
"""
def __init__(
self,
scale_factors: Sequence[float],
shot_list: Optional[List[int]] = None,
) -> None:
"""Constructs a BatchedFactory.
Args:
scale_factors: Sequence of noise scale factors at which expectation
values should be measured.
shot_list: Optional sequence of integers corresponding to the
number of samples taken for each expectation value. If this
argument is explicitly passed to the factory, it must have the
same length of scale_factors and the executor function must
accept "shots" as a valid keyword argument.
Raises:
ValueError: If the number of scale factors is less than 2.
TypeError: If shot_list is provided and has any non-integer values.
"""
if len(scale_factors) < 2:
raise ValueError("At least 2 scale factors are necessary.")
if shot_list and (
not isinstance(shot_list, Sequence)
or not all([isinstance(shots, int) for shots in shot_list])
):
raise TypeError(
"The optional argument shot_list must be None "
"or a valid iterator of integers."
)
if shot_list and (len(scale_factors) != len(shot_list)):
raise IndexError(
"The arguments scale_factors and shot_list"
" must have the same length."
f" But len(scale_factors) is {len(scale_factors)}"
f" and len(shot_list) is {len(shot_list)}."
)
self._scale_factors = scale_factors
self._shot_list = shot_list
super(BatchedFactory, self).__init__()
@staticmethod
@abstractmethod
def extrapolate(*args: Any, **kwargs: Any) -> ExtrapolationResult:
"""Returns the extrapolation to the zero-noise limit."""
raise NotImplementedError
def reduce(self) -> float:
"""Evaluates the zero-noise limit found by fitting according to
the factory's extrapolation method.
Returns:
The zero-noise limit.
"""
(
self._zne_limit,
self._zne_error,
self._opt_params,
self._params_cov,
self._zne_curve,
) = self.extrapolate( # type: ignore
self.get_scale_factors(),
self.get_expectation_values(),
full_output=True,
**self._options,
)
self._already_reduced = True
return self._zne_limit
def run(
self,
qp: QPROGRAM,
executor: Union[Executor, Callable[..., QuantumResult]],
observable: Optional[Observable] = None,
scale_noise: Callable[
[QPROGRAM, float], QPROGRAM
] = fold_gates_at_random,
num_to_average: int = 1,
) -> "BatchedFactory":
"""Computes the expectation values at each scale factor and stores them
in the factory. If the executor returns a single expectation value, the
circuits are run sequentially. If the executor is batched and returns
a list of expectation values (one for each circuit), then the circuits
are sent to the backend as a single job. To detect if an executor is
batched, it must be annotated with a return type that is one of the
following:
* Iterable[float]
* List[float]
* Sequence[float]
* Tuple[float]
* numpy.ndarray
Args:
qp: Quantum circuit to run.
executor: A ``mitiq.Executor`` or a function which inputs a (list
of) quantum circuits and outputs a (list of)
``mitiq.QuantumResult`` s.
observable: Observable to compute the expectation value of. If
None, the `executor` must return an expectation value.
Otherwise, the `QuantumResult` returned by `executor` is used
to compute the expectation of the observable.
scale_noise: Noise scaling function.
num_to_average: The number of circuits executed for each noise
scale factor. This parameter can be used to increase the
precision of the "executor" or to average the effect of a
non-deterministic "scale_noise" function.
"""
self.reset()
self._batch_populate_instack()
_check_circuit_length(qp)
# Get all noise-scaled circuits to run.
to_run = self._generate_circuits(qp, scale_noise, num_to_average)
# Run all circuits.
if not isinstance(executor, Executor):
executor = Executor(executor)
# Get the list of keywords associated to each circuit in "to_run".
kwargs_list = self._get_keyword_args(num_to_average)
# If there are different keyword args, run each circuit individually.
# https://stackoverflow.com/questions/1151658/python-hashable-dicts.
class HashableDict(Dict[Any, Any]):
def __hash__(self) -> int: # type: ignore[override]
return hash(tuple(sorted(self.items())))
if len(set(HashableDict(kwargs) for kwargs in kwargs_list)) != 1:
res = []
for circuit, kwargs in zip(to_run, kwargs_list):
res.extend(
executor.evaluate(
circuit, observable, force_run_all=True, **kwargs
)
)
else:
# Else, run all circuits.
res = executor.evaluate(
to_run, observable, force_run_all=True, **kwargs_list[0]
)
# Reshape "res" to have "num_to_average" columns
reshaped = np.array(res).reshape((-1, num_to_average))
# Average the "num_to_average" columns
self._outstack = np.average(reshaped, axis=1)
return self
def run_classical(
self, scale_factor_to_expectation_value: Callable[..., float]
) -> "BatchedFactory":
"""Computes expectation values by calling the input function at each
scale factor.
Args:
scale_factor_to_expectation_value: Function mapping a noise scale
factor to an expectation value. If shot_list is not None,
"shots" must be an argument of this function.
"""
self.reset()
self._batch_populate_instack()
kwargs_list = self._get_keyword_args(num_to_average=1)
self._outstack = [
scale_factor_to_expectation_value(scale_factor, **kwargs)
for scale_factor, kwargs in zip(self._scale_factors, kwargs_list)
]
return self
def _generate_circuits(
self,
circuit: QPROGRAM,
scale_noise: Callable[[QPROGRAM, float], QPROGRAM],
num_to_average: int = 1,
) -> List[QPROGRAM]:
"""Returns all noise-scaled circuits to run.
Args:
circuit: Base circuit to scale noise in.
scale_noise: Noise scaling function.
num_to_average: Number of times to call scale_noise at each scale
factor.
"""
to_run = []
for scale_factor in self.get_scale_factors():
for _ in range(num_to_average):
to_run.append(scale_noise(circuit, scale_factor))
return to_run
def _batch_populate_instack(self) -> None:
"""Populates the instack with all computed values."""
if self._shot_list:
self._instack = [
{"scale_factor": scale, "shots": shots}
for scale, shots in zip(self._scale_factors, self._shot_list)
]
else:
self._instack = [
{"scale_factor": scale} for scale in self._scale_factors
]
def _get_keyword_args(self, num_to_average: int) -> List[Dict[str, Any]]:
"""Returns a list of keyword dictionaries to be used for
executing the circuits generated by the method "_generate_circuits".
Args:
num_to_average: The number of times the same keywords are used
for each scale factor. This should correspond to the number
of circuits executed for each scale factor.
Returns:
The output list of keyword dictionaries.
"""
params = deepcopy(self._instack)
for d in params:
_ = d.pop("scale_factor")
# Repeat each keyword num_to_average times
return [k for k in params for _ in range(num_to_average)]
class AdaptiveFactory(Factory, ABC):
"""Abstract class designed to adaptively produce a new noise scaling
parameter based on a historical stack of previous noise scale parameters
("self._instack") and previously estimated expectation values
("self._outstack").
Specific zero-noise extrapolation algorithms which are adaptive are derived
from this class.
"""
@abstractmethod
def next(self) -> Dict[str, float]:
"""Returns a dictionary of parameters to execute a circuit at."""
raise NotImplementedError
@abstractmethod
def is_converged(self) -> bool:
"""Returns True if all needed expectation values have been computed,
else False.
"""
raise NotImplementedError
@abstractmethod
def reduce(self) -> float:
"""Returns the extrapolation to the zero-noise limit."""
raise NotImplementedError
def run_classical(
self,
scale_factor_to_expectation_value: Callable[..., float],
max_iterations: int = 100,
) -> "AdaptiveFactory":
"""Evaluates a sequence of expectation values until enough
data is collected (or iterations reach "max_iterations").
Args:
scale_factor_to_expectation_value: Function mapping a noise scale
factor to an expectation value. If shot_list is not None,
"shots" must be an argument of this function.
max_iterations: Maximum number of iterations (optional).
Default: 100.
Raises:
ConvergenceWarning: If iteration loop stops before convergence.
"""
# Reset the instack, outstack, and optimal parameters
self.reset()
counter = 0
while not self.is_converged() and counter < max_iterations:
next_in_params = self.next()
next_exec_params = deepcopy(next_in_params)
# Get next scale factor and remove it from next_exec_params
scale_factor = next_exec_params.pop("scale_factor")
next_expval = scale_factor_to_expectation_value(
scale_factor, **next_exec_params
)
self.push(next_in_params, next_expval)
counter += 1
if counter == max_iterations:
warnings.warn(
"Factory iteration loop stopped before convergence. "
f"Maximum number of iterations ({max_iterations}) "
"was reached.",
ConvergenceWarning,
)
return self
def run(
self,
qp: QPROGRAM,
executor: Union[Executor, Callable[..., QuantumResult]],
observable: Optional[Observable] = None,
scale_noise: Callable[
[QPROGRAM, float], QPROGRAM
] = fold_gates_at_random,
num_to_average: int = 1,
max_iterations: int = 100,
) -> "AdaptiveFactory":
"""Evaluates a sequence of expectation values by executing quantum
circuits until enough data is collected (or iterations reach
"max_iterations").
Args:
qp: Circuit to mitigate.
executor: A ``mitiq.Executor`` or a function which inputs a (list
of) quantum circuits and outputs a (list of)
``mitiq.QuantumResult`` s.
observable: Observable to compute the expectation value of. If
None, the `executor` must return an expectation value.
Otherwise, the `QuantumResult` returned by `executor` is used
to compute the expectation of the observable.
scale_noise: Function that scales the noise level of a quantum
circuit.
num_to_average: Number of times expectation values are computed by
the executor after each call to scale_noise, then averaged.
max_iterations: Maximum number of iterations (optional).
"""
_check_circuit_length(qp)
if not isinstance(executor, Executor):
executor = Executor(executor)
def scale_factor_to_expectation_value(
scale_factor: float, **exec_params: Any
) -> float:
"""Evaluates the quantum expectation value for a given
scale_factor and other executor parameters."""
to_run = [
scale_noise(qp, scale_factor) for _ in range(num_to_average)
]
expectation_values = executor.evaluate( # type: ignore[union-attr]
to_run, observable, force_run_all=True, **exec_params
)
return cast(float, np.average(expectation_values))
return self.run_classical(
scale_factor_to_expectation_value, max_iterations
)
class PolyFactory(BatchedFactory):
"""Factory object implementing a zero-noise extrapolation algorithm based
on a polynomial fit.
Args:
scale_factors: Sequence of noise scale factors at which
expectation values should be measured.
order: Extrapolation order (degree of the polynomial fit).
It cannot exceed len(scale_factors) - 1.
shot_list: Optional sequence of integers corresponding to the number
of samples taken for each expectation value. If this
argument is explicitly passed to the factory, it must have
the same length of scale_factors and the executor function
must accept "shots" as a valid keyword argument.
Raises:
ValueError: If data is not consistent with the extrapolation model.
ExtrapolationWarning: If the extrapolation fit is ill-conditioned.
Note:
RichardsonFactory and LinearFactory are special cases of PolyFactory.
"""
def __init__(
self,
scale_factors: Sequence[float],
order: int,
shot_list: Optional[List[int]] = None,
) -> None:
"""Instantiates a new object of this Factory class."""
if order > len(scale_factors) - 1:
raise ValueError(
"The extrapolation order cannot exceed len(scale_factors) - 1."
)
super(PolyFactory, self).__init__(scale_factors, shot_list)
self._options = {"order": order}
@staticmethod
def extrapolate( # type: ignore
scale_factors: Sequence[float],
exp_values: Sequence[float],
order: int,
full_output: bool = False,
) -> ExtrapolationResult:
"""Static method which evaluates a polynomial extrapolation to the
zero-noise limit.
Args:
scale_factors: The array of noise scale factors.
exp_values: The array of expectation values.
order: The extrapolation order (degree of the polynomial fit).
full_output: If False (default), only the zero-noise limit is
returned. If True, additional information about the
extrapolated limit is returned too.
Returns:
The extrapolated zero-noise limit. If full_output is True, also
returns
* standard deviation of the extrapolated zero-noise limit,
* optimal parameters of the best-fit model,
* parameter covariance matrix of best-fit model,
* best-fit model as a Callable[[float], float] function.
Raises:
ExtrapolationWarning: If the extrapolation fit is ill-conditioned.
Note:
This static method computes the zero-noise limit from input
parameters. To compute the zero-noise limit from the Factory
parameters, use the ``reduce`` method.
"""
opt_params, params_cov = mitiq_polyfit(
scale_factors, exp_values, order
)
zne_limit = opt_params[-1]
if not full_output:
return zne_limit
zne_error = None
if params_cov is not None:
if params_cov.shape == (order + 1, order + 1):
zne_error = np.sqrt(params_cov[order, order])
def zne_curve(scale_factor: float) -> float:
return cast(float, np.polyval(opt_params, scale_factor))
return zne_limit, zne_error, opt_params, params_cov, zne_curve
class RichardsonFactory(BatchedFactory):
"""Factory object implementing Richardson extrapolation.
Args:
scale_factors: Sequence of noise scale factors at which
expectation values should be measured.
shot_list: Optional sequence of integers corresponding to the number
of samples taken for each expectation value. If this
argument is explicitly passed to the factory, it must have
the same length of scale_factors and the executor function
must accept "shots" as a valid keyword argument.
Raises:
ValueError: If data is not consistent with the extrapolation model.
ExtrapolationWarning: If the extrapolation fit is ill-conditioned.
"""
@staticmethod
def extrapolate( # type: ignore
scale_factors: Sequence[float],
exp_values: Sequence[float],
full_output: bool = False,
) -> ExtrapolationResult:
"""Static method which evaluates the Richardson extrapolation to the
zero-noise limit.
Args:
scale_factors: The array of noise scale factors.
exp_values: The array of expectation values.
full_output: If False (default), only the zero-noise limit is
returned. If True, additional results are returned too.
Returns:
The extrapolated zero-noise limit. If full_output is True, also
returns
* standard deviation of the extrapolated zero-noise limit,
* optimal parameters of the best-fit model,
* parameter covariance matrix of best-fit model,
* best-fit model as a Callable[[float], float] function.
Raises:
ExtrapolationWarning: If the extrapolation fit is ill-conditioned.
Note:
This static method computes the zero-noise limit from input
parameters. To compute the zero-noise limit from the Factory
parameters, use the ``reduce`` method.
"""
# Richardson extrapolation is a particular case of a polynomial fit
# with order equal to the number of data points minus 1.
order = len(scale_factors) - 1
return PolyFactory.extrapolate(
scale_factors, exp_values, order, full_output
)
class FakeNodesFactory(BatchedFactory):
"""Factory object implementing a modified version [De2020polynomial]_ of
Richardson extrapolation. In this version the original set of scale factors
is mapped to a new set of fake nodes, known as Chebyshev-Lobatto points.
This method may give a better interpolation for particular types of curves
and if the number of scale factors is large (> 10). One should be aware
that, in many other cases, the fake nodes extrapolation method is usually
not superior to standard Richardson extrapolation.
Args:
scale_factors: Sequence of noise scale factors at which
expectation values should be measured.
shot_list: Optional sequence of integers corresponding to the number
of samples taken for each expectation value. If this
argument is explicitly passed to the factory, it must have
the same length of scale_factors and the executor function
must accept "shots" as a valid keyword argument.
Raises:
ValueError: If data is not consistent with the extrapolation model.
ExtrapolationWarning: If the extrapolation fit is ill-conditioned.
.. [De2020polynomial] : S.De Marchia. F. Marchetti, E.Perracchionea
and D.Poggialia,
"Polynomial interpolation via mapped bases without resampling,"
*Journ of Comp. and App. Math.* **364**, 112347 (2020),
(https://www.sciencedirect.com/science/article/abs/pii/S0377042719303449).
"""
@staticmethod
def extrapolate( # type: ignore
scale_factors: Sequence[float],
exp_values: Sequence[float],
full_output: bool = False,
) -> ExtrapolationResult:
if not FakeNodesFactory._is_equally_spaced(scale_factors):
raise ValueError("The scale factors must be equally spaced.")
# Define interval [a, b] for which the scale_factors are mapped to
a = 0.0
b = min(scale_factors) + max(scale_factors)
# Mapping to the fake nodes
fake_nodes = FakeNodesFactory._map_to_fake_nodes(scale_factors, a, b)
if not full_output:
return RichardsonFactory.extrapolate(fake_nodes, exp_values)
(
zne_limit,
zne_error,
opt_params,
params_cov,
zne_curve,
) = RichardsonFactory.extrapolate( # type: ignore[misc]
fake_nodes, exp_values, True
)
# Convert zne_curve from the "fake node space" to the real space.
# Note: since a=0.0, this conversion is not necessary for zne_limit.