1
1
# This code is part of Qiskit.
2
2
#
3
- # (C) Copyright IBM 2017, 2020
3
+ # (C) Copyright IBM 2017, 2023
4
4
#
5
5
# This code is licensed under the Apache License, Version 2.0. You may
6
6
# obtain a copy of this license in the LICENSE.txt file in the root directory
26
26
from qiskit .quantum_info .operators .mixins import AdjointMixin , MultiplyMixin
27
27
28
28
29
+ # utility for _to_matrix
30
+ _PARITY = np .array ([- 1 if bin (i ).count ("1" ) % 2 else 1 for i in range (256 )], dtype = complex )
31
+
32
+
29
33
class BasePauli (BaseOperator , AdjointMixin , MultiplyMixin ):
30
34
r"""Symplectic representation of a list of N-qubit Paulis.
31
35
@@ -392,7 +396,7 @@ def _from_array(z, x, phase=0):
392
396
393
397
@staticmethod
394
398
def _to_matrix (z , x , phase = 0 , group_phase = False , sparse = False ):
395
- """Return the matrix matrix from symplectic representation.
399
+ """Return the matrix from symplectic representation.
396
400
397
401
The Pauli is defined as :math:`P = (-i)^{phase + z.x} * Z^z.x^x`
398
402
where ``array = [x, z]``.
@@ -430,7 +434,19 @@ def _to_matrix(z, x, phase=0, group_phase=False, sparse=False):
430
434
coeff = (- 1j ) ** phase
431
435
else :
432
436
coeff = 1
433
- data = np .array ([coeff * (- 1 ) ** (bin (i ).count ("1" ) % 2 ) for i in z_indices & indptr ])
437
+
438
+ # Compute parities of `z_indices & indptr`, i.e.,
439
+ # np.array([(-1) ** bin(i).count("1") for i in z_indices & indptr])
440
+ vec_u64 = z_indices & indptr
441
+ mat_u8 = np .zeros ((vec_u64 .size , 8 ), dtype = np .uint8 )
442
+ for i in range (8 ):
443
+ mat_u8 [:, i ] = vec_u64 & 255
444
+ vec_u64 >>= 8
445
+ if np .all (vec_u64 == 0 ):
446
+ break
447
+ parity = _PARITY [np .bitwise_xor .reduce (mat_u8 , axis = 1 )]
448
+
449
+ data = coeff * parity
434
450
if sparse :
435
451
# Return sparse matrix
436
452
from scipy .sparse import csr_matrix
@@ -439,8 +455,7 @@ def _to_matrix(z, x, phase=0, group_phase=False, sparse=False):
439
455
440
456
# Build dense matrix using csr format
441
457
mat = np .zeros ((dim , dim ), dtype = complex )
442
- for i in range (dim ):
443
- mat [i ][indices [indptr [i ] : indptr [i + 1 ]]] = data [indptr [i ] : indptr [i + 1 ]]
458
+ mat [range (dim ), indices [:dim ]] = data [:dim ]
444
459
return mat
445
460
446
461
@staticmethod
0 commit comments