-
Notifications
You must be signed in to change notification settings - Fork 558
/
_qubit_device.py
2068 lines (1650 loc) · 84.2 KB
/
_qubit_device.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 2018-2021 Xanadu Quantum Technologies Inc.
# 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
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module contains the :class:`QubitDevice` abstract base class.
"""
# For now, arguments may be different from the signatures provided in Device
# e.g. instead of expval(self, observable, wires, par) have expval(self, observable)
# pylint: disable=arguments-differ, abstract-method, no-value-for-parameter,too-many-instance-attributes,too-many-branches, no-member, bad-option-value, arguments-renamed
import abc
import contextlib
import itertools
import warnings
from collections import defaultdict
from typing import Union, List
import inspect
import logging
import numpy as np
import pennylane as qml
from pennylane import Device, DeviceError
from pennylane.interfaces import set_shots
from pennylane.math import multiply as qmlmul
from pennylane.math import sum as qmlsum
from pennylane.measurements import (
AllCounts,
ClassicalShadowMP,
Counts,
CountsMP,
Expectation,
ExpectationMP,
MeasurementProcess,
MeasurementTransform,
MutualInfo,
MutualInfoMP,
Probability,
ProbabilityMP,
Sample,
SampleMeasurement,
SampleMP,
Shadow,
ShadowExpval,
ShadowExpvalMP,
State,
StateMeasurement,
StateMP,
Variance,
VarianceMP,
VnEntropy,
VnEntropyMP,
Shots,
)
from pennylane.ops.qubit.observables import BasisStateProjector
from pennylane.resource import Resources
from pennylane.operation import operation_derivative, Operation
from pennylane.tape import QuantumScript, QuantumTape
from pennylane.wires import Wires
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
def _sample_to_str(sample):
"""Converts a bit-array to a string. For example, ``[0, 1]`` would become '01'."""
return "".join(map(str, sample))
class QubitDevice(Device):
"""Abstract base class for PennyLane qubit devices.
The following abstract method **must** be defined:
* :meth:`~.apply`: append circuit operations, compile the circuit (if applicable),
and perform the quantum computation.
Devices that generate their own samples (such as hardware) may optionally
overwrite :meth:`~.probability`. This method otherwise automatically
computes the probabilities from the generated samples, and **must**
overwrite the following method:
* :meth:`~.generate_samples`: Generate samples from the device from the
exact or approximate probability distribution.
Analytic devices **must** overwrite the following method:
* :meth:`~.analytic_probability`: returns the probability or marginal probability from the
device after circuit execution. :meth:`~.marginal_prob` may be used here.
This device contains common utility methods for qubit-based devices. These
do not need to be overwritten. Utility methods include:
* :meth:`~.expval`, :meth:`~.var`, :meth:`~.sample`: return expectation values,
variances, and samples of observables after the circuit has been rotated
into the observable eigenbasis.
Args:
wires (int, Iterable[Number, str]]): Number of subsystems represented by the device,
or iterable that contains unique labels for the subsystems as numbers (i.e., ``[-1, 0, 2]``)
or strings (``['ancilla', 'q1', 'q2']``). Default 1 if not specified.
shots (None, int, list[int]): Number of circuit evaluations/random samples used to estimate
expectation values of observables. If ``None``, the device calculates probability, expectation values,
and variances analytically. If an integer, it specifies the number of samples to estimate these quantities.
If a list of integers is passed, the circuit evaluations are batched over the list of shots.
r_dtype: Real floating point precision type.
c_dtype: Complex floating point precision type.
"""
# pylint: disable=too-many-public-methods
_asarray = staticmethod(np.asarray)
_dot = staticmethod(np.dot)
_abs = staticmethod(np.abs)
_reduce_sum = staticmethod(lambda array, axes: np.sum(array, axis=tuple(axes)))
_reshape = staticmethod(np.reshape)
_flatten = staticmethod(lambda array: array.flatten())
_gather = staticmethod(
lambda array, indices, axis=0: array[:, indices] if axis == 1 else array[indices]
) # Make sure to only use _gather with axis=0 or axis=1
_einsum = staticmethod(np.einsum)
_cast = staticmethod(np.asarray)
_transpose = staticmethod(np.transpose)
_tensordot = staticmethod(np.tensordot)
_conj = staticmethod(np.conj)
_imag = staticmethod(np.imag)
_roll = staticmethod(np.roll)
_stack = staticmethod(np.stack)
_outer = staticmethod(np.outer)
_diag = staticmethod(np.diag)
_real = staticmethod(np.real)
_size = staticmethod(np.size)
_ndim = staticmethod(np.ndim)
@staticmethod
def _scatter(indices, array, new_dimensions):
new_array = np.zeros(new_dimensions, dtype=array.dtype.type)
new_array[indices] = array
return new_array
@staticmethod
def _const_mul(constant, array):
"""Data type preserving multiply operation"""
return qmlmul(constant, array, dtype=array.dtype)
observables = {
"PauliX",
"PauliY",
"PauliZ",
"Hadamard",
"Hermitian",
"Identity",
"Projector",
"Sum",
"Sprod",
"Prod",
}
measurement_map = defaultdict(lambda: "") # e.g. {SampleMP: "sample"}
"""Mapping used to override the logic of measurement processes. The dictionary maps a
measurement class to a string containing the name of a device's method that overrides the
measurement process. The method defined by the device should have the following arguments:
* measurement (MeasurementProcess): measurement to override
* shot_range (tuple[int]): 2-tuple of integers specifying the range of samples
to use. If not specified, all samples are used.
* bin_size (int): Divides the shot range into bins of size ``bin_size``, and
returns the measurement statistic separately over each bin. If not
provided, the entire shot range is treated as a single bin.
.. note::
When overriding the logic of a :class:`~pennylane.measurements.MeasurementTransform`, the
method defined by the device should only have a single argument:
* tape: quantum tape to transform
**Example:**
Let's create device that inherits from :class:`~pennylane.devices.DefaultQubit` and overrides the
logic of the `qml.sample` measurement. To do so we will need to update the ``measurement_map``
dictionary:
.. code-block:: python
class NewDevice(DefaultQubit):
def __init__(self, wires, shots):
super().__init__(wires=wires, shots=shots)
self.measurement_map[SampleMP] = "sample_measurement"
def sample_measurement(self, measurement, shot_range=None, bin_size=None):
return 2
>>> dev = NewDevice(wires=2, shots=1000)
>>> @qml.qnode(dev)
... def circuit():
... return qml.sample()
>>> circuit()
tensor(2, requires_grad=True)
"""
def __init__(
self, wires=1, shots=None, *, r_dtype=np.float64, c_dtype=np.complex128, analytic=None
):
super().__init__(wires=wires, shots=shots, analytic=analytic)
if "float" not in str(r_dtype):
raise DeviceError("Real datatype must be a floating point type.")
if "complex" not in str(c_dtype):
raise DeviceError("Complex datatype must be a complex floating point type.")
self.C_DTYPE = c_dtype
self.R_DTYPE = r_dtype
self._samples = None
"""None or array[int]: stores the samples generated by the device
*after* rotation to diagonalize the observables."""
@classmethod
def capabilities(cls):
capabilities = super().capabilities().copy()
capabilities.update(
model="qubit",
supports_broadcasting=False,
supports_finite_shots=True,
supports_tensor_observables=True,
returns_probs=True,
)
return capabilities
def reset(self):
"""Reset the backend state.
After the reset, the backend should be as if it was just constructed.
Most importantly the quantum state is reset to its initial value.
"""
self._samples = None
def _collect_shotvector_results(self, circuit, counts_exist): # pragma: no cover
"""Obtain and process statistics when using a shot vector.
This routine is part of the ``execute()`` method."""
if self._ndim(self._samples) == 3:
raise NotImplementedError(
"Parameter broadcasting when using a shot vector is not supported yet."
)
results = []
s1 = 0
for shot_tuple in self._shot_vector:
s2 = s1 + np.prod(shot_tuple)
r = self._statistics_legacy(circuit, shot_range=[s1, s2], bin_size=shot_tuple.shots)
if qml.math.get_interface(*r) == "jax": # pylint: disable=protected-access
r = r[0]
elif not counts_exist:
# Measurement types except for Counts
r = qml.math.squeeze(r)
if counts_exist:
# This happens when at least one measurement type is Counts
for result_group in r:
if isinstance(result_group, list):
# List that contains one or more dictionaries
results.extend(result_group)
else:
# Other measurement results
results.append(result_group.T)
elif shot_tuple.copies > 1:
results.extend(r.T)
else:
results.append(r.T)
s1 = s2
multiple_sampled_jobs = circuit.is_sampled and self._has_partitioned_shots()
if not multiple_sampled_jobs and not counts_exist:
# Can only stack single element outputs
results = self._stack(results)
return results
def execute(self, circuit, **kwargs):
"""It executes a queue of quantum operations on the device and then measure the given observables.
For plugin developers: instead of overwriting this, consider
implementing a suitable subset of
* :meth:`apply`
* :meth:`~.generate_samples`
* :meth:`~.probability`
Additional keyword arguments may be passed to this method
that can be utilised by :meth:`apply`. An example would be passing
the ``QNode`` hash that can be used later for parametric compilation.
Args:
circuit (~.tape.QuantumTape): circuit to execute on the device
Raises:
QuantumFunctionError: if the value of :attr:`~.Observable.return_type` is not supported
Returns:
array[float]: measured value(s)
"""
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
"Entry with args=(circuit=%s, kwargs=%s) called by=%s",
circuit,
kwargs,
"::L".join(
str(i) for i in inspect.getouterframes(inspect.currentframe(), 2)[1][1:3]
),
)
if not qml.active_return():
return self._execute_legacy(circuit, **kwargs)
self.check_validity(circuit.operations, circuit.observables)
# apply all circuit operations
self.apply(circuit.operations, rotations=self._get_diagonalizing_gates(circuit), **kwargs)
# generate computational basis samples
if self.shots is not None or circuit.is_sampled:
self._samples = self.generate_samples()
# compute the required statistics
if self._shot_vector is not None:
results = self.shot_vec_statistics(circuit)
else:
results = self.statistics(circuit)
single_measurement = len(circuit.measurements) == 1
results = results[0] if single_measurement else tuple(results)
# increment counter for number of executions of qubit device
self._num_executions += 1
if self.tracker.active:
shots_from_dev = self._shots if not self.shot_vector else self._raw_shot_sequence
tape_resources = circuit.specs["resources"]
resources = Resources( # temporary until shots get updated on tape !
tape_resources.num_wires,
tape_resources.num_gates,
tape_resources.gate_types,
tape_resources.gate_sizes,
tape_resources.depth,
Shots(shots_from_dev),
)
self.tracker.update(
executions=1, shots=self._shots, results=results, resources=resources
)
self.tracker.record()
return results
def _execute_legacy(self, circuit: QuantumTape, **kwargs):
"""Execute a queue of quantum operations on the device and then
measure the given observables.
For plugin developers: instead of overwriting this, consider
implementing a suitable subset of
* :meth:`apply`
* :meth:`~.generate_samples`
* :meth:`~.probability`
Additional keyword arguments may be passed to the this method
that can be utilised by :meth:`apply`. An example would be passing
the ``QNode`` hash that can be used later for parametric compilation.
Args:
circuit (~.tape.QuantumTape): circuit to execute on the device
Raises:
QuantumFunctionError: if the value of :attr:`~.Observable.return_type` is not supported
Returns:
array[float]: measured value(s)
"""
self.check_validity(circuit.operations, circuit.observables)
# apply all circuit operations
self.apply(circuit.operations, rotations=self._get_diagonalizing_gates(circuit), **kwargs)
# generate computational basis samples
if self.shots is not None or circuit.is_sampled:
self._samples = self.generate_samples()
measurements = circuit.measurements
counts_exist = any(isinstance(m, CountsMP) for m in measurements)
# compute the required statistics
if not self.analytic and self._shot_vector is not None:
results = self._collect_shotvector_results(circuit, counts_exist)
else:
results = self._statistics_legacy(circuit=circuit)
if not circuit.is_sampled:
if len(measurements) == 1:
if isinstance(measurements[0], StateMP):
# State: assumed to only be allowed if it's the only measurement
results = self._asarray(results, dtype=self.C_DTYPE)
else:
# Measurements with expval, var or probs
with contextlib.suppress(TypeError):
# Feature for returning custom objects: if the type cannot be cast to float then we can still allow it as an output
results = self._asarray(results, dtype=self.R_DTYPE)
elif all(isinstance(m, (ExpectationMP, VarianceMP)) for m in measurements):
# Measurements with expval or var
results = self._asarray(results, dtype=self.R_DTYPE)
elif not counts_exist:
# all the other cases except any counts
results = self._asarray(results)
elif circuit.all_sampled and not self._has_partitioned_shots() and not counts_exist:
results = self._asarray(results)
else:
results = tuple(
r if isinstance(r, dict) else qml.math.squeeze(self._asarray(r)) for r in results
)
# increment counter for number of executions of qubit device
self._num_executions += 1
if self.tracker.active:
self.tracker.update(executions=1, shots=self._shots, results=results)
self.tracker.record()
return results
def shot_vec_statistics(self, circuit: QuantumTape):
"""Process measurement results from circuit execution using a device
with a shot vector and return statistics.
This is an auxiliary method of execute and uses statistics.
When using shot vectors, measurement results for each item of the shot
vector are contained in a tuple.
Args:
circuit (~.tape.QuantumTape): circuit to execute on the device
Raises:
QuantumFunctionError: if the value of :attr:`~.Observable.return_type` is not supported
Returns:
tuple: stastics for each shot item from the shot vector
"""
results = []
s1 = 0
measurements = circuit.measurements
counts_exist = any(isinstance(m, CountsMP) for m in measurements)
single_measurement = len(measurements) == 1
for shot_tuple in self._shot_vector:
s2 = s1 + np.prod(shot_tuple)
r = self.statistics(circuit, shot_range=[s1, s2], bin_size=shot_tuple.shots)
# This will likely be required:
# if qml.math.get_interface(*r) == "jax": # pylint: disable=protected-access
# r = r[0]
if single_measurement:
r = r[0]
elif shot_tuple.copies == 1:
r = tuple(r_[0] if isinstance(r_, list) else r_.T for r_ in r)
elif counts_exist:
r = self._multi_meas_with_counts_shot_vec(circuit, shot_tuple, r)
else:
# r is a nested sequence, contains the results for
# multiple measurements
#
# Each item of r has copies length, we need to extract
# each measurement result from the arrays
# 1. transpose: applied because measurements like probs
# for multiple copies output results with shape (N,
# copies) and we'd like to index straight to get rows
# which requires a shape of (copies, N)
# 2. asarray: done because indexing into a flat array produces a
# scalar instead of a scalar shaped array
r = [
tuple(self._asarray(r_.T[idx]) for r_ in r) for idx in range(shot_tuple.copies)
]
if isinstance(r, qml.numpy.ndarray):
if shot_tuple.copies > 1:
results.extend([self._asarray(r_) for r_ in qml.math.unstack(r.T)])
else:
results.append(r.T)
elif single_measurement and counts_exist:
# Results are nested in a sequence
results.extend(r)
elif not single_measurement and shot_tuple.copies > 1:
# Some samples may still be transposed, fix their shapes
# Leave dictionaries intact
r = [tuple(elem if isinstance(elem, dict) else elem.T for elem in r_) for r_ in r]
results.extend(r)
else:
results.append(r)
s1 = s2
return tuple(results)
def _multi_meas_with_counts_shot_vec(self, circuit: QuantumTape, shot_tuple, r):
"""Auxiliary function of the shot_vec_statistics and execute
functions for post-processing the results of multiple measurements at
least one of which was a counts measurement.
The measurements were executed on a device that defines a shot vector.
"""
# First: iterate over each group of measurement
# results that contain copies many outcomes for a
# single measurement
new_r = []
# Each item of r has copies length
for idx in range(shot_tuple.copies):
result_group = []
for idx2, r_ in enumerate(r):
measurement_proc = circuit.measurements[idx2]
if isinstance(measurement_proc, ProbabilityMP) or (
isinstance(measurement_proc, SampleMP) and measurement_proc.obs
):
# Here, the result has a shape of (num_basis_states, shot_tuple.copies)
# Extract a single row -> shape (num_basis_states,)
result = r_[:, idx]
else:
result = r_[idx]
if not isinstance(measurement_proc, CountsMP):
result = self._asarray(result.T)
result_group.append(result)
new_r.append(tuple(result_group))
return new_r
def _batch_execute_legacy(self, circuits):
"""Execute a batch of quantum circuits on the device.
The circuits are represented by tapes, and they are executed one-by-one using the
device's ``execute`` method. The results are collected in a list.
For plugin developers: This function should be overwritten if the device can efficiently run multiple
circuits on a backend, for example using parallel and/or asynchronous executions.
Args:
circuits (list[~.tape.QuantumTape]): circuits to execute on the device
Returns:
list[array[float]]: list of measured value(s)
"""
results = []
for circuit in circuits:
# we need to reset the device here, else it will
# not start the next computation in the zero state
self.reset()
res = self._execute_legacy(circuit)
results.append(res)
if self.tracker.active:
self.tracker.update(batches=1, batch_len=len(circuits))
self.tracker.record()
return results
def batch_execute(self, circuits):
"""Execute a batch of quantum circuits on the device.
The circuits are represented by tapes, and they are executed one-by-one using the
device's ``execute`` method. The results are collected in a list.
For plugin developers: This function should be overwritten if the device can efficiently run multiple
circuits on a backend, for example using parallel and/or asynchronous executions.
Args:
circuits (list[~.tape.QuantumTape]): circuits to execute on the device
Returns:
list[array[float]]: list of measured value(s)
"""
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
"""Entry with args=(circuits=%s) called by=%s""",
circuits,
"::L".join(
str(i) for i in inspect.getouterframes(inspect.currentframe(), 2)[1][1:3]
),
)
if not qml.active_return():
return self._batch_execute_legacy(circuits=circuits)
results = []
for circuit in circuits:
# we need to reset the device here, else it will
# not start the next computation in the zero state
self.reset()
res = self.execute(circuit)
results.append(res)
if self.tracker.active:
self.tracker.update(batches=1, batch_len=len(circuits))
self.tracker.record()
return results
@abc.abstractmethod
def apply(self, operations, **kwargs):
"""Apply quantum operations, rotate the circuit into the measurement
basis, and compile and execute the quantum circuit.
This method receives a list of quantum operations queued by the QNode,
and should be responsible for:
* Constructing the quantum program
* (Optional) Rotating the quantum circuit using the rotation
operations provided. This diagonalizes the circuit so that arbitrary
observables can be measured in the computational basis.
* Compile the circuit
* Execute the quantum circuit
Both arguments are provided as lists of PennyLane :class:`~.Operation`
instances. Useful properties include :attr:`~.Operation.name`,
:attr:`~.Operation.wires`, and :attr:`~.Operation.parameters`:
>>> op = qml.RX(0.2, wires=[0])
>>> op.name # returns the operation name
"RX"
>>> op.wires # returns a Wires object representing the wires that the operation acts on
<Wires = [0]>
>>> op.parameters # returns a list of parameters
[0.2]
Args:
operations (list[~.Operation]): operations to apply to the device
Keyword args:
rotations (list[~.Operation]): operations that rotate the circuit
pre-measurement into the eigenbasis of the observables.
hash (int): the hash value of the circuit constructed by `CircuitGraph.hash`
"""
@staticmethod
def active_wires(operators):
"""Returns the wires acted on by a set of operators.
Args:
operators (list[~.Operation]): operators for which
we are gathering the active wires
Returns:
Wires: wires activated by the specified operators
"""
list_of_wires = [op.wires for op in operators]
return Wires.all_wires(list_of_wires)
# pylint: disable=too-many-statements
def _statistics_legacy(
self, observables=None, shot_range=None, bin_size=None, circuit: QuantumTape = None
): # pragma: no cover
"""Process measurement results from circuit execution and return statistics.
This includes returning expectation values, variance, samples, probabilities, states, and
density matrices.
Args:
circuit (~.tape.QuantumTape): the quantum tape currently being executed
shot_range (tuple[int]): 2-tuple of integers specifying the range of samples
to use. If not specified, all samples are used.
bin_size (int): Divides the shot range into bins of size ``bin_size``, and
returns the measurement statistic separately over each bin. If not
provided, the entire shot range is treated as a single bin.
Raises:
QuantumFunctionError: if the value of :attr:`~.Observable.return_type` is not supported
Returns:
Union[float, List[float]]: the corresponding statistics
.. details::
:title: Usage Details
The ``shot_range`` and ``bin_size`` arguments allow for the statistics
to be performed on only a subset of device samples. This finer level
of control is accessible from the main UI by instantiating a device
with a batch of shots.
For example, consider the following device:
>>> dev = qml.device("my_device", shots=[5, (10, 3), 100])
This device will execute QNodes using 135 shots, however
measurement statistics will be **coarse grained** across these 135
shots:
* All measurement statistics will first be computed using the
first 5 shots --- that is, ``shots_range=[0, 5]``, ``bin_size=5``.
* Next, the tuple ``(10, 3)`` indicates 10 shots, repeated 3 times. We will want to use
``shot_range=[5, 35]``, performing the expectation value in bins of size 10
(``bin_size=10``).
* Finally, we repeat the measurement statistics for the final 100 shots,
``shot_range=[35, 135]``, ``bin_size=100``.
"""
if observables is not None:
if isinstance(observables, QuantumScript):
circuit = observables
measurements = circuit.measurements
else:
warnings.warn(
message="Using a list of observables in ``QubitDevice.statistics`` is deprecated. "
"Please use a ``QuantumTape`` instead. This should be passed to ``circuit``, "
"as the ``observables`` argument is also deprecated.",
category=UserWarning,
)
measurements = observables
elif circuit is not None:
measurements = circuit.measurements
else:
raise ValueError("Please provide a circuit into the statistics method.")
results = []
for m in measurements:
# TODO: Remove this when all overriden measurements support the `MeasurementProcess` class
if isinstance(m, MeasurementProcess) and m.obs is not None:
obs = m.obs
obs.return_type = m.return_type
else:
obs = m
# Check if there is an overriden version of the measurement process
if method := getattr(self, self.measurement_map[type(m)], False):
if isinstance(m, MeasurementTransform):
results.append(method(tape=circuit))
else:
results.append(method(m, shot_range=shot_range, bin_size=bin_size))
# TODO: Remove return_type when `observables` argument is removed from this method
# Pass instances directly
elif obs.return_type is Expectation:
# Appends a result of shape (num_bins,) if bin_size is not None, else a scalar
results.append(self.expval(obs, shot_range=shot_range, bin_size=bin_size))
elif obs.return_type is Variance:
# Appends a result of shape (num_bins,) if bin_size is not None, else a scalar
results.append(self.var(obs, shot_range=shot_range, bin_size=bin_size))
elif obs.return_type is Sample:
# Appends a result of shape (shots, num_bins,) if bin_size is not None else (shots,)
results.append(
self.sample(obs, shot_range=shot_range, bin_size=bin_size, counts=False)
)
elif obs.return_type in (Counts, AllCounts):
results.append(
self.sample(obs, shot_range=shot_range, bin_size=bin_size, counts=True)
)
elif obs.return_type is Probability:
# Appends a result of shape (2**len(obs.wires), num_bins,)
# if bin_size is not None else (2**len(obs.wires),)
results.append(
self.probability(wires=obs.wires, shot_range=shot_range, bin_size=bin_size)
)
elif obs.return_type is State:
if len(measurements) > 1:
raise qml.QuantumFunctionError(
"The state or density matrix cannot be returned in combination "
"with other return types"
)
if self.shots is not None:
warnings.warn(
"Requested state or density matrix with finite shots; the returned "
"state information is analytic and is unaffected by sampling. To silence "
"this warning, set shots=None on the device.",
UserWarning,
)
# Check if the state is accessible and decide to return the state or the density
# matrix.
results.append(self.access_state(wires=obs.wires))
elif obs.return_type is VnEntropy:
if self.wires.labels != tuple(range(self.num_wires)):
raise qml.QuantumFunctionError(
"Returning the Von Neumann entropy is not supported when using custom wire labels"
)
if self._shot_vector is not None:
raise NotImplementedError(
"Returning the Von Neumann entropy is not supported with shot vectors."
)
if self.shots is not None:
warnings.warn(
"Requested Von Neumann entropy with finite shots; the returned "
"result is analytic and is unaffected by sampling. To silence "
"this warning, set shots=None on the device.",
UserWarning,
)
results.append(self.vn_entropy(wires=obs.wires, log_base=obs.log_base))
elif obs.return_type is MutualInfo:
if self.wires.labels != tuple(range(self.num_wires)):
raise qml.QuantumFunctionError(
"Returning the mutual information is not supported when using custom wire labels"
)
if self._shot_vector is not None:
raise NotImplementedError(
"Returning the mutual information is not supported with shot vectors."
)
if self.shots is not None:
warnings.warn(
"Requested mutual information with finite shots; the returned "
"state information is analytic and is unaffected by sampling. To silence "
"this warning, set shots=None on the device.",
UserWarning,
)
wires0, wires1 = obs.raw_wires
results.append(
self.mutual_info(wires0=wires0, wires1=wires1, log_base=obs.log_base)
)
elif obs.return_type is Shadow:
if len(measurements) > 1:
raise qml.QuantumFunctionError(
"Classical shadows cannot be returned in combination "
"with other return types"
)
results.append(self.classical_shadow(obs, circuit))
elif obs.return_type is ShadowExpval:
if len(measurements) > 1:
raise qml.QuantumFunctionError(
"Classical shadows cannot be returned in combination "
"with other return types"
)
results.append(self.shadow_expval(obs, circuit=circuit))
elif isinstance(m, MeasurementTransform):
results.append(m.process(tape=circuit, device=self))
elif isinstance(m, (SampleMeasurement, StateMeasurement)):
results.append(self._measure(m, shot_range=shot_range, bin_size=bin_size))
elif obs.return_type is not None:
raise qml.QuantumFunctionError(
f"Unsupported return type specified for observable {obs.name}"
)
return results
def _measure(
self,
measurement: Union[SampleMeasurement, StateMeasurement],
shot_range=None,
bin_size=None,
):
"""Compute the corresponding measurement process depending on ``shots`` and the measurement
type.
Args:
measurement (Union[SampleMeasurement, StateMeasurement]): measurement process
shot_range (tuple[int]): 2-tuple of integers specifying the range of samples
to use. If not specified, all samples are used.
bin_size (int): Divides the shot range into bins of size ``bin_size``, and
returns the measurement statistic separately over each bin. If not
provided, the entire shot range is treated as a single bin.
Raises:
ValueError: if the measurement cannot be computed
Returns:
Union[float, dict, list[float]]: result of the measurement
"""
if self.shots is None:
if isinstance(measurement, StateMeasurement):
return measurement.process_state(state=self.state, wire_order=self.wires)
raise ValueError(
"Shots must be specified in the device to compute the measurement "
f"{measurement.__class__.__name__}"
)
if isinstance(measurement, StateMeasurement):
warnings.warn(
f"Requested measurement {measurement.__class__.__name__} with finite shots; the "
"returned state information is analytic and is unaffected by sampling. "
"To silence this warning, set shots=None on the device.",
UserWarning,
)
return measurement.process_state(state=self.state, wire_order=self.wires)
return measurement.process_samples(
samples=self._samples, wire_order=self.wires, shot_range=shot_range, bin_size=bin_size
)
def statistics(self, circuit: QuantumTape, shot_range=None, bin_size=None):
"""Process measurement results from circuit execution and return statistics.
This includes returning expectation values, variance, samples, probabilities, states, and
density matrices.
Args:
circuit (~.tape.QuantumTape): the quantum tape currently being executed
shot_range (tuple[int]): 2-tuple of integers specifying the range of samples
to use. If not specified, all samples are used.
bin_size (int): Divides the shot range into bins of size ``bin_size``, and
returns the measurement statistic separately over each bin. If not
provided, the entire shot range is treated as a single bin.
Raises:
QuantumFunctionError: if the value of :attr:`~.Observable.return_type` is not supported
Returns:
Union[float, List[float]]: the corresponding statistics
.. details::
:title: Usage Details
The ``shot_range`` and ``bin_size`` arguments allow for the statistics
to be performed on only a subset of device samples. This finer level
of control is accessible from the main UI by instantiating a device
with a batch of shots.
For example, consider the following device:
>>> dev = qml.device("my_device", shots=[5, (10, 3), 100])
This device will execute QNodes using 135 shots, however
measurement statistics will be **course grained** across these 135
shots:
* All measurement statistics will first be computed using the
first 5 shots --- that is, ``shots_range=[0, 5]``, ``bin_size=5``.
* Next, the tuple ``(10, 3)`` indicates 10 shots, repeated 3 times. We will want to use
``shot_range=[5, 35]``, performing the expectation value in bins of size 10
(``bin_size=10``).
* Finally, we repeat the measurement statistics for the final 100 shots,
``shot_range=[35, 135]``, ``bin_size=100``.
"""
measurements = circuit.measurements
results = []
for m in measurements:
# TODO: Remove this when all overriden measurements support the `MeasurementProcess` class
if m.obs is not None:
obs = m.obs
obs.return_type = m.return_type
else:
obs = m
# Check if there is an overriden version of the measurement process
if method := getattr(self, self.measurement_map[type(m)], False):
if isinstance(m, MeasurementTransform):
result = method(tape=circuit)
else:
result = method(m, shot_range=shot_range, bin_size=bin_size)
# 1. Based on the measurement type, compute statistics
# Pass instances directly
elif isinstance(m, ExpectationMP):
result = self.expval(obs, shot_range=shot_range, bin_size=bin_size)