forked from kanavsetia/pgs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweighted_pauli_operator.py
1303 lines (1099 loc) · 49.9 KB
/
weighted_pauli_operator.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
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Weighted Pauli Operator """
from copy import deepcopy
import itertools
import logging
import json
from operator import add as op_add, sub as op_sub
import sys
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Pauli
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import AquaError, aqua_globals
from .base_operator import BaseOperator
from .common import (measure_pauli_z, covariance, pauli_measurement,
kernel_F2, suzuki_expansion_slice_pauli_list,
check_commutativity, evolution_instruction)
logger = logging.getLogger(__name__)
class WeightedPauliOperator(BaseOperator):
""" Weighted Pauli Operator """
def __init__(self, paulis, basis=None, z2_symmetries=None, atol=1e-12, name=None):
"""
Args:
paulis (list[[complex, Pauli]]): the list of weighted Paulis, where a weighted pauli is
composed of
a length-2 list and the first item is the weight and
the second item is the Pauli object.
basis (list[tuple(object, [int])], optional): the grouping basis, each element is a
tuple composed of the basis
and the indices to paulis which are
belonged to that group.
e.g., if tpb basis is used, the object
will be a pauli.
by default, the group is equal to
non-grouping, each pauli is its own basis.
z2_symmetries (Z2Symmetires): recording the z2 symmetries info
atol (float, optional): the threshold used in truncating paulis
name (str, optional): the name of operator.
"""
super().__init__(basis, z2_symmetries, name)
# plain store the paulis, the group information is store in the basis
self._paulis_table = None
self._paulis = paulis
self._basis = \
[(pauli[1], [i]) for i, pauli in enumerate(paulis)] if basis is None else basis
# combine the paulis and remove those with zero weight
self.simplify()
self._aer_paulis = None
self._atol = atol
@classmethod
def from_list(cls, paulis, weights=None, name=None):
"""
Create a WeightedPauliOperator via a pair of list.
Args:
paulis (list[Pauli]): the list of Paulis
weights (list[complex], optional): the list of weights,
if it is None, all weights are 1.
name (str, optional): name of the operator.
Returns:
WeightedPauliOperator: operator
Raises:
ValueError: The length of weights and paulis must be the same
"""
if weights is not None and len(weights) != len(paulis):
raise ValueError("The length of weights and paulis must be the same.")
if weights is None:
weights = [1.0] * len(paulis)
return cls(paulis=[[w, p] for w, p in zip(weights, paulis)], name=name)
@property
def paulis(self):
""" get paulis """
return self._paulis
@property
def atol(self):
""" get atol """
return self._atol
@atol.setter
def atol(self, new_value):
""" set atol """
self._atol = new_value
@property
def num_qubits(self):
"""
number of qubits required for the operator.
Returns:
int: number of qubits
"""
if not self.is_empty():
return self._paulis[0][1].numberofqubits
else:
logger.warning("Operator is empty, Return 0.")
return 0
@property
def aer_paulis(self):
"""
Returns: the weighted paulis formatted for the aer simulator.
"""
if getattr(self, '_aer_paulis', None) is None:
aer_paulis = []
for weight, pauli in self._paulis:
new_weight = [weight.real, weight.imag]
new_pauli = pauli.to_label()
aer_paulis.append([new_weight, new_pauli])
self._aer_paulis = aer_paulis
return self._aer_paulis
def __eq__(self, other):
"""Overload == operation"""
# need to clean up the zeros
self.simplify()
other.simplify()
if len(self._paulis) != len(other.paulis):
return False
for weight, pauli in self._paulis:
found_pauli = False
other_weight = 0.0
for weight2, pauli2 in other.paulis:
if pauli == pauli2:
found_pauli = True
other_weight = weight2
break
if not found_pauli and other_weight != 0.0: # since we might have 0 weights of paulis.
return False
if weight != other_weight:
return False
return True
def _add_or_sub(self, other, operation, copy=True):
"""
Add two operators either extend (in-place) or combine (copy) them.
The addition performs optimized combination of two operators.
If `other` has identical basis, the coefficient are combined rather than
appended.
Args:
other (WeightedPauliOperator): to-be-combined operator
operation (callable or str): add or sub callable from operator
copy (bool): working on a copy or self
Returns:
WeightedPauliOperator: operator
Raises:
AquaError: two operators have different number of qubits.
"""
if not self.is_empty() and not other.is_empty():
if self.num_qubits != other.num_qubits:
raise AquaError("Can not add/sub two operators with different number of qubits.")
ret_op = self.copy() if copy else self
for pauli in other.paulis:
pauli_label = pauli[1].to_label()
idx = ret_op._paulis_table.get(pauli_label, None)
if idx is not None:
ret_op._paulis[idx][0] = operation(ret_op._paulis[idx][0], pauli[0])
else:
new_pauli = deepcopy(pauli)
ret_op._paulis_table[pauli_label] = len(ret_op._paulis)
ret_op._basis.append((new_pauli[1], [len(ret_op._paulis)]))
new_pauli[0] = operation(0.0, pauli[0])
ret_op._paulis.append(new_pauli)
return ret_op
def add(self, other, copy=False):
"""Perform self + other.
Args:
other (WeightedPauliOperator): to-be-combined operator
copy (bool): working on a copy or self, if False, the results are written back to self.
Returns:
WeightedPauliOperator: operator
"""
return self._add_or_sub(other, op_add, copy=copy)
def sub(self, other, copy=False):
"""Perform self - other.
Args:
other (WeightedPauliOperator): to-be-combined operator
copy (bool): working on a copy or self, if False, the results are written back to self.
Returns:
WeightedPauliOperator: operator
"""
return self._add_or_sub(other, op_sub, copy=copy)
def __add__(self, other):
"""Overload + operator."""
return self.add(other, copy=True)
def __iadd__(self, other):
"""Overload += operator."""
return self.add(other, copy=False)
def __sub__(self, other):
"""Overload - operator."""
return self.sub(other, copy=True)
def __isub__(self, other):
"""Overload -= operator."""
return self.sub(other, copy=False)
def _scaling_weight(self, scaling_factor, copy=False):
"""
Constantly scaling all weights of paulis.
Args:
scaling_factor (complex): the scaling factor
copy (bool): return a copy or modify in-place
Returns:
WeightedPauliOperator: a copy of the scaled one.
Raises:
ValueError: the scaling factor is not a valid type.
"""
if not isinstance(scaling_factor, (int, float, complex, np.int, np.float, np.complex)):
raise ValueError(
"Type of scaling factor is a valid type. {} if given.".format(
scaling_factor.__class__))
ret = self.copy() if copy else self
for idx in range(len(ret._paulis)):
ret._paulis[idx] = [ret._paulis[idx][0] * scaling_factor, ret._paulis[idx][1]]
return ret
def multiply(self, other):
"""
Perform self * other, and the phases are tracked.
Args:
other (WeightedPauliOperator): an operator
Returns:
WeightedPauliOperator: the multiplied operator
"""
ret_op = WeightedPauliOperator(paulis=[])
for existed_weight, existed_pauli in self.paulis:
for weight, pauli in other.paulis:
new_pauli, sign = Pauli.sgn_prod(existed_pauli, pauli)
new_weight = existed_weight * weight * sign
pauli_term = [new_weight, new_pauli]
ret_op += WeightedPauliOperator(paulis=[pauli_term])
return ret_op
def __rmul__(self, other):
"""Overload other * self."""
if isinstance(other, (int, float, complex, np.int, np.float, np.complex)):
return self._scaling_weight(other, copy=True)
else:
return other.multiply(self)
def __mul__(self, other):
"""Overload self * other."""
if isinstance(other, (int, float, complex, np.int, np.float, np.complex)):
return self._scaling_weight(other, copy=True)
else:
return self.multiply(other)
def __neg__(self):
"""Overload unary -."""
return self._scaling_weight(-1.0, copy=True)
def __str__(self):
"""Overload str()."""
curr_repr = 'paulis'
length = len(self._paulis)
name = "" if self._name == '' else "{}: ".format(self._name)
ret = "{}Representation: {}, qubits: {}, size: {}".format(name,
curr_repr,
self.num_qubits, length)
return ret
def print_details(self):
"""
Print out the operator in details.
Returns:
str: a formatted string describes the operator.
"""
if self.is_empty():
return "Operator is empty."
ret = ""
for weight, pauli in self._paulis:
ret = ''.join([ret, "{}\t{}\n".format(pauli.to_label(), weight)])
return ret
def copy(self):
"""Get a copy of self."""
return deepcopy(self)
def simplify(self, copy=False):
"""
Merge the paulis whose bases are identical and the pauli with zero coefficient
would be removed.
Notes:
This behavior of this method is slightly changed,
it will remove the paulis whose weights are zero.
Args:
copy (bool): simplify on a copy or self
Returns:
WeightedPauliOperator: the simplified operator
"""
op = self.copy() if copy else self
new_paulis = []
new_paulis_table = {}
old_to_new_indices = {}
curr_idx = 0
for curr_weight, curr_pauli in op.paulis:
pauli_label = curr_pauli.to_label()
new_idx = new_paulis_table.get(pauli_label, None)
if new_idx is not None:
new_paulis[new_idx][0] += curr_weight
old_to_new_indices[curr_idx] = new_idx
else:
new_paulis_table[pauli_label] = len(new_paulis)
old_to_new_indices[curr_idx] = len(new_paulis)
new_paulis.append([curr_weight, curr_pauli])
curr_idx += 1
op._paulis = new_paulis
op._paulis_table = new_paulis_table
# update the grouping info, since this method only reduce the number
# of paulis, we can handle it here for both
# pauli and tpb grouped pauli
# should have a better way to rebuild the basis here.
new_basis = []
for basis, indices in op.basis:
new_indices = []
found = False
if new_basis:
for b, ind in new_basis:
if b == basis:
new_indices = ind
found = True
break
for idx in indices:
new_idx = old_to_new_indices[idx]
if new_idx is not None:
new_indices.append(new_idx)
new_indices = list(set(new_indices))
if new_indices and not found:
new_basis.append((basis, new_indices))
op._basis = new_basis
op.chop(0.0)
return op
def rounding(self, decimals, copy=False):
"""Rounding the weight.
Args:
decimals (int): rounding the weight to the decimals.
copy (bool): chop on a copy or self
Returns:
WeightedPauliOperator: operator
"""
op = self.copy() if copy else self
op._paulis = [[np.around(weight, decimals=decimals), pauli] for weight, pauli in op.paulis]
return op
def chop(self, threshold=None, copy=False):
"""
Eliminate the real and imagine part of weight in each pauli by `threshold`.
If pauli's weight is less then `threshold` in both real and imagine parts,
the pauli is removed.
Note:
If weight is real-only, the imag part is skipped.
Args:
threshold (float): the threshold is used to remove the paulis
copy (bool): chop on a copy or self
Returns:
WeightedPauliOperator: if copy is True, the original operator is unchanged; otherwise,
the operator is mutated.
"""
threshold = self._atol if threshold is None else threshold
def chop_real_imag(weight):
temp_real = weight.real if np.absolute(weight.real) >= threshold else 0.0
temp_imag = weight.imag if np.absolute(weight.imag) >= threshold else 0.0
if temp_real == 0.0 and temp_imag == 0.0:
return 0.0
else:
new_weight = temp_real + 1j * temp_imag
return new_weight
op = self.copy() if copy else self
if op.is_empty():
return op
paulis = []
old_to_new_indices = {}
curr_idx = 0
for idx, weighted_pauli in enumerate(op.paulis):
weight, pauli = weighted_pauli
new_weight = chop_real_imag(weight)
if new_weight != 0.0:
old_to_new_indices[idx] = curr_idx
curr_idx += 1
paulis.append([new_weight, pauli])
op._paulis = paulis
op._paulis_table = \
{weighted_pauli[1].to_label(): i for i, weighted_pauli in enumerate(paulis)}
# update the grouping info, since this method only remove pauli,
# we can handle it here for both
# pauli and tpb grouped pauli
new_basis = []
for basis, indices in op.basis:
new_indices = []
for idx in indices:
new_idx = old_to_new_indices.get(idx, None)
if new_idx is not None:
new_indices.append(new_idx)
if new_indices:
new_basis.append((basis, new_indices))
op._basis = new_basis
return op
def commute_with(self, other):
""" commute with """
return check_commutativity(self, other)
def anticommute_with(self, other):
""" anti commute with """
return check_commutativity(self, other, anti=True)
def is_empty(self):
"""
Check Operator is empty or not.
Returns:
bool: is empty?
"""
if not self._paulis:
return True
elif not self._paulis[0]:
return True
else:
return False
@classmethod
def from_file(cls, file_name, before_04=False):
"""
Load paulis in a file to construct an Operator.
Args:
file_name (str): path to the file, which contains a list of Paulis and coefficients.
before_04 (bool): support the format before Aqua 0.4.
Returns:
WeightedPauliOperator: the loaded operator.
"""
with open(file_name, 'r') as file:
return cls.from_dict(json.load(file), before_04=before_04)
def to_file(self, file_name):
"""
Save operator to a file in pauli representation.
Args:
file_name (str): path to the file
"""
with open(file_name, 'w') as file:
json.dump(self.to_dict(), file)
@classmethod
def from_dict(cls, dictionary, before_04=False):
"""
Load paulis in a dict to construct an Operator, \
the dict must be represented as follows: label and coeff (real and imag). \
E.g.: \
{'paulis': \
[ \
{'label': 'IIII', \
'coeff': {'real': -0.33562957575267038, 'imag': 0.0}}, \
{'label': 'ZIII', \
'coeff': {'real': 0.28220597164664896, 'imag': 0.0}}, \
... \
] \
} \
Args:
dictionary (dict): dictionary, which contains a list of Paulis and coefficients.
before_04 (bool): support the format before Aqua 0.4.
Returns:
WeightedPauliOperator: the loaded operator.
Raises:
AquaError: Invalid dictionary
"""
if 'paulis' not in dictionary:
raise AquaError('Dictionary missing "paulis" key')
paulis = []
for op in dictionary['paulis']:
if 'label' not in op:
raise AquaError('Dictionary missing "label" key')
pauli_label = op['label']
if 'coeff' not in op:
raise AquaError('Dictionary missing "coeff" key')
pauli_coeff = op['coeff']
if 'real' not in pauli_coeff:
raise AquaError('Dictionary missing "real" key')
coeff = pauli_coeff['real']
if 'imag' in pauli_coeff:
coeff = complex(pauli_coeff['real'], pauli_coeff['imag'])
pauli_label = pauli_label[::-1] if before_04 else pauli_label
paulis.append([coeff, Pauli.from_label(pauli_label)])
return cls(paulis=paulis)
def to_dict(self):
"""
Save operator to a dict in pauli representation.
Returns:
dict: a dictionary contains an operator with pauli representation.
"""
ret_dict = {"paulis": []}
for coeff, pauli in self._paulis:
op = {"label": pauli.to_label()}
if isinstance(coeff, complex):
op["coeff"] = {"real": np.real(coeff),
"imag": np.imag(coeff)
}
else:
op["coeff"] = {"real": coeff}
ret_dict["paulis"].append(op)
return ret_dict
def evaluate_with_statevector(self, quantum_state):
"""
Args:
quantum_state (numpy.ndarray): a quantum state.
Returns:
float: the mean value
float: the standard deviation
Raises:
AquaError: if Operator is empty
"""
if self.is_empty():
raise AquaError("Operator is empty, check the operator.")
# convert to matrix first?
from .op_converter import to_matrix_operator
mat_op = to_matrix_operator(self)
avg = np.vdot(quantum_state, mat_op._matrix.dot(quantum_state))
return avg, 0.0
# pylint: disable=arguments-differ
def construct_evaluation_circuit(self, wave_function, statevector_mode,
qr=None, cr=None, use_simulator_operator_mode=False,
circuit_name_prefix=''):
"""
Construct the circuits for evaluation, which calculating the expectation <psi|H|psi>.
At statevector mode: to simplify the computation, we do not build the whole
circuit for <psi|H|psi>, instead of
that we construct an individual circuit <psi|, and a bundle circuit for H|psi>
Args:
wave_function (QuantumCircuit): the quantum circuit.
statevector_mode (bool): indicate which type of simulator are going to use.
qr (QuantumRegister, optional): the quantum register associated with the input_circuit
cr (ClassicalRegister, optional): the classical register associated
with the input_circuit
use_simulator_operator_mode (bool, optional): if aer_provider is used, we can do faster
evaluation for pauli mode on statevector simulation
circuit_name_prefix (str, optional): a prefix of circuit name
Returns:
list[QuantumCircuit]: a list of quantum circuits and each circuit with a unique name:
circuit_name_prefix + Pauli string
Raises:
AquaError: if Operator is empty
AquaError: Can not find quantum register with `q` as the name and do not provide
quantum register explicitly
AquaError: The provided qr is not in the wave_function
"""
if self.is_empty():
raise AquaError("Operator is empty, check the operator.")
from qiskit.aqua.utils.run_circuits import find_regs_by_name
if qr is None:
qr = find_regs_by_name(wave_function, 'q')
if qr is None:
raise AquaError("Either providing the quantum register (qr) explicitly"
"or used `q` as the name in the input circuit.")
else:
if not wave_function.has_register(qr):
raise AquaError("The provided QuantumRegister (qr) is not in the circuit.")
n_qubits = self.num_qubits
instructions = self.evaluation_instruction(statevector_mode, use_simulator_operator_mode)
circuits = []
if statevector_mode:
if use_simulator_operator_mode:
circuits.append(wave_function.copy(name=circuit_name_prefix + 'aer_mode'))
else:
circuits.append(wave_function.copy(name=circuit_name_prefix + 'psi'))
for _, pauli in self._paulis:
inst = instructions.get(pauli.to_label(), None)
if inst is not None:
circuit = wave_function.copy(name=circuit_name_prefix + pauli.to_label())
circuit.append(inst, qr)
# TODO: this decompose is used because of cache
circuits.append(circuit.decompose())
else:
base_circuit = wave_function.copy()
if cr is not None:
if not base_circuit.has_register(cr):
base_circuit.add_register(cr)
else:
cr = find_regs_by_name(base_circuit, 'c', qreg=False)
if cr is None:
cr = ClassicalRegister(n_qubits, name='c')
base_circuit.add_register(cr)
for basis, _ in self._basis:
circuit = base_circuit.copy(name=circuit_name_prefix + basis.to_label())
circuit.append(instructions[basis.to_label()], qargs=qr, cargs=cr)
# TODO: this decompose is used because of cache
circuits.append(circuit.decompose())
return circuits
def evaluation_instruction(self, statevector_mode, use_simulator_operator_mode=False):
"""
Args:
statevector_mode (bool): will it be run on statevector simulator or not
use_simulator_operator_mode (bool): will it use qiskit aer simulator operator mode
Returns:
dict: Pauli-instruction pair.
Raises:
AquaError: if Operator is empty
"""
if self.is_empty():
raise AquaError("Operator is empty, check the operator.")
instructions = {}
qr = QuantumRegister(self.num_qubits)
qc = QuantumCircuit(qr)
if statevector_mode and not use_simulator_operator_mode:
for _, pauli in self._paulis:
tmp_qc = qc.copy(name="Pauli " + pauli.to_label())
if np.all(np.logical_not(pauli.z)) and np.all(np.logical_not(pauli.x)): # all I
continue
# This explicit barrier is needed for statevector simulator since Qiskit-terra
# will remove global phase at default compilation level but the results here
# rely on global phase.
tmp_qc.barrier([x for x in range(self.num_qubits)])
tmp_qc.append(pauli, [x for x in range(self.num_qubits)])
instructions[pauli.to_label()] = tmp_qc.to_instruction()
else:
cr = ClassicalRegister(self.num_qubits)
qc.add_register(cr)
for basis, _ in self._basis:
tmp_qc = qc.copy(name="Pauli " + basis.to_label())
tmp_qc = pauli_measurement(tmp_qc, basis, qr, cr, barrier=True)
instructions[basis.to_label()] = tmp_qc.to_instruction()
return instructions
# pylint: disable=arguments-differ
def evaluate_with_result(self, result, statevector_mode, use_simulator_operator_mode=False,
circuit_name_prefix=''):
"""
This method can be only used with the circuits generated by the
`construct_evaluation_circuit` method with the same `circuit_name_prefix`
since the circuit names are tied to some meanings.
Calculate the evaluated value with the measurement results.
Args:
result (qiskit.Result): the result from the backend.
statevector_mode (bool): indicate which type of simulator are used.
use_simulator_operator_mode (bool): if aer_provider is used, we can do faster
evaluation for pauli mode on statevector simulation
circuit_name_prefix (str): a prefix of circuit name
Returns:
float: the mean value
float: the standard deviation
Raises:
AquaError: if Operator is empty
"""
if self.is_empty():
raise AquaError("Operator is empty, check the operator.")
avg, std_dev, variance = 0.0, 0.0, 0.0
if statevector_mode:
if use_simulator_operator_mode:
temp = \
result.data(
circuit_name_prefix + 'aer_mode')[
'snapshots']['expectation_value']['test'][0]['value']
avg = temp[0] + 1j * temp[1]
else:
quantum_state = np.asarray(result.get_statevector(circuit_name_prefix + 'psi'))
for weight, pauli in self._paulis:
# all I
if np.all(np.logical_not(pauli.z)) and np.all(np.logical_not(pauli.x)):
avg += weight
else:
quantum_state_i = \
result.get_statevector(circuit_name_prefix + pauli.to_label())
avg += (weight * (np.vdot(quantum_state, quantum_state_i)))
else:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Computing the expectation from measurement results:")
TextProgressBar(sys.stderr)
# pick the first result to get the total number of shots
num_shots = sum(list(result.get_counts(0).values()))
results = parallel_map(WeightedPauliOperator._routine_compute_mean_and_var,
[([self._paulis[idx] for idx in indices],
result.get_counts(circuit_name_prefix + basis.to_label()))
for basis, indices in self._basis],
num_processes=aqua_globals.num_processes)
for res in results:
avg += res[0]
variance += res[1]
std_dev = np.sqrt(variance / num_shots)
return avg, std_dev
@staticmethod
def _routine_compute_mean_and_var(args):
paulis, measured_results = args
avg_paulis = []
avg = 0.0
variance = 0.0
for weight, pauli in paulis:
observable = measure_pauli_z(measured_results, pauli)
avg += weight * observable
avg_paulis.append(observable)
for idx_1, weighted_pauli_1 in enumerate(paulis):
weight_1, pauli_1 = weighted_pauli_1
for idx_2, weighted_pauli_2 in enumerate(paulis):
weight_2, pauli_2 = weighted_pauli_2
variance += weight_1 * weight_2 * covariance(measured_results, pauli_1, pauli_2,
avg_paulis[idx_1], avg_paulis[idx_2])
return avg, variance
def reorder_paulis(self):
"""
Reorder the paulis based on the basis and return the reordered paulis.
Returns:
list[list[complex, paulis]]: the ordered paulis based on the basis.
"""
# if each pauli belongs to its group, no reordering it needed.
if len(self._basis) == len(self._paulis):
return self._paulis
paulis = []
new_basis = []
curr_count = 0
for basis, indices in self._basis:
sub_paulis = []
for idx in indices:
sub_paulis.append(self._paulis[idx])
new_basis.append((basis, range(curr_count, curr_count + len(sub_paulis))))
paulis.extend(sub_paulis)
curr_count += len(sub_paulis)
self._paulis = paulis
self._basis = new_basis
return self._paulis
# pylint: disable=arguments-differ
def evolve(self, state_in=None, evo_time=0, num_time_slices=1, quantum_registers=None,
expansion_mode='trotter', expansion_order=1):
"""
Carry out the eoh evolution for the operator under supplied specifications.
Args:
state_in (QuantumCircuit): a circuit describes the input state
evo_time (int): The evolution time
num_time_slices (int): The number of time slices for the expansion
quantum_registers (QuantumRegister): The QuantumRegister to build
the QuantumCircuit off of
expansion_mode (str): The mode under which the expansion is to be done.
Currently support 'trotter', which follows the expansion as discussed in
http://science.sciencemag.org/content/273/5278/1073,
and 'suzuki', which corresponds to the discussion in
https://arxiv.org/pdf/quant-ph/0508139.pdf
expansion_order (int): The order for suzuki expansion
Returns:
QuantumCircuit: The constructed circuit.
Raises:
AquaError: quantum_registers must be in the provided state_in circuit
AquaError: if operator is empty
"""
if self.is_empty():
raise AquaError("Operator is empty, can not evolve.")
if state_in is not None and quantum_registers is not None:
if not state_in.has_register(quantum_registers):
raise AquaError("quantum_registers must be in the provided state_in circuit.")
elif state_in is None and quantum_registers is None:
quantum_registers = QuantumRegister(self.num_qubits)
qc = QuantumCircuit(quantum_registers)
elif state_in is not None and quantum_registers is None:
# assuming the first register is for evolve
quantum_registers = state_in.qregs[0]
qc = QuantumCircuit() + state_in
else:
qc = QuantumCircuit(quantum_registers)
instruction = self.evolve_instruction(evo_time, num_time_slices,
expansion_mode, expansion_order)
qc.append(instruction, quantum_registers)
# TODO: this decompose is used because of cache
return qc.decompose()
def evolve_instruction(self, evo_time=0, num_time_slices=1,
expansion_mode='trotter', expansion_order=1):
"""
Carry out the eoh evolution for the operator under supplied specifications.
Args:
evo_time (int): The evolution time
num_time_slices (int): The number of time slices for the expansion
expansion_mode (str): The mode under which the expansion is to be done.
Currently support 'trotter', which follows the expansion as discussed in
http://science.sciencemag.org/content/273/5278/1073,
and 'suzuki', which corresponds to the discussion in
https://arxiv.org/pdf/quant-ph/0508139.pdf
expansion_order (int): The order for suzuki expansion
Returns:
QuantumCircuit: The constructed QuantumCircuit.
Raises:
ValueError: Number of time slices should be a non-negative integer
NotImplementedError: expansion mode not supported
AquaError: if operator is empty
"""
if self.is_empty():
raise AquaError("Operator is empty, can not build evolve instruction.")
# pylint: disable=no-member
if num_time_slices <= 0 or not isinstance(num_time_slices, int):
raise ValueError('Number of time slices should be a non-negative integer.')
if expansion_mode not in ['trotter', 'suzuki']:
raise NotImplementedError('Expansion mode {} not supported.'.format(expansion_mode))
pauli_list = self.reorder_paulis()
if len(pauli_list) == 1:
slice_pauli_list = pauli_list
else:
if expansion_mode == 'trotter':
slice_pauli_list = pauli_list
# suzuki expansion
else:
slice_pauli_list = suzuki_expansion_slice_pauli_list(
pauli_list,
1,
expansion_order
)
instruction = evolution_instruction(slice_pauli_list, evo_time, num_time_slices)
return instruction
class Z2Symmetries:
""" Z2 Symmetries """
def __init__(self, symmetries, sq_paulis, sq_list, tapering_values=None):
"""
Constructor.
Args:
symmetries (list[Pauli]): the list of Pauli objects representing the Z_2 symmetries
sq_paulis (list[Pauli]): the list of single - qubit Pauli objects to construct the
Clifford operators
sq_list (list[int]): the list of support of the single-qubit Pauli objects used to build
the clifford operators
tapering_values (list[int], optional): values determines the sector.
Raises:
AquaError: Invalid paulis
"""
if len(symmetries) != len(sq_paulis):
raise AquaError("Number of Z2 symmetries has to be the same as number "
"of single-qubit pauli x.")
if len(sq_paulis) != len(sq_list):
raise AquaError("Number of single-qubit pauli x has to be the same "
"as length of single-qubit list.")
if tapering_values is not None:
if len(sq_list) != len(tapering_values):
raise AquaError("The length of single-qubit list has "
"to be the same as length of tapering values.")
self._symmetries = symmetries
self._sq_paulis = sq_paulis
self._sq_list = sq_list
self._tapering_values = tapering_values
@property
def symmetries(self):
""" return symmetries """
return self._symmetries
@property
def sq_paulis(self):
""" returns sq paulis """
return self._sq_paulis
@property
def cliffords(self):
"""
Get clifford operators, build based on symmetries and single-qubit X.
Returns:
list[WeightedPauliOperator]: a list of unitaries used to diagonalize the Hamiltonian.
"""
cliffords = [WeightedPauliOperator(paulis=[[1 / np.sqrt(2), pauli_symm],
[1 / np.sqrt(2), sq_pauli]])
for pauli_symm, sq_pauli in zip(self._symmetries, self._sq_paulis)]
return cliffords
@property
def sq_list(self):
""" returns sq list """
return self._sq_list
@property
def tapering_values(self):
""" returns tapering values """
return self._tapering_values
@tapering_values.setter
def tapering_values(self, new_value):
""" set tapering values """
self._tapering_values = new_value
def __str__(self):