Skip to content

Commit 2ceb0ac

Browse files
authored
Efficient unpacking of bitstring (#1276)
h/t @mhodson-rigetti Fix linting. Efficient unpacking of bitstring h/t @mhodson-rigetti
1 parent 918f84c commit 2ceb0ac

File tree

2 files changed

+5
-13
lines changed

2 files changed

+5
-13
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ Changelog
88

99
### Improvements and Changes
1010

11+
- Unpacking bitstrings is significantly faster (@mhodson-rigetti, @notmgsk, #1276).
12+
1113
### Bugfixes
1214

1315

pyquil/wavefunction.py

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
Module containing the Wavefunction object and methods for working with wavefunctions.
1818
"""
1919
import itertools
20-
import struct
2120
import warnings
2221
from typing import Dict, Iterator, List, Optional, Sequence, cast
2322

@@ -81,18 +80,9 @@ def from_bit_packed_string(coef_string: bytes) -> "Wavefunction":
8180
From a bit packed string, unpacks to get the wavefunction
8281
:param coef_string:
8382
"""
84-
num_octets = len(coef_string)
85-
86-
# Parse the wavefunction
87-
wf = np.zeros(num_octets // OCTETS_PER_COMPLEX_DOUBLE, dtype=np.cfloat)
88-
for i, p in enumerate(range(0, num_octets, OCTETS_PER_COMPLEX_DOUBLE)):
89-
re_be = coef_string[p : p + OCTETS_PER_DOUBLE_FLOAT]
90-
im_be = coef_string[p + OCTETS_PER_DOUBLE_FLOAT : p + OCTETS_PER_COMPLEX_DOUBLE]
91-
re = struct.unpack(">d", re_be)[0]
92-
im = struct.unpack(">d", im_be)[0]
93-
wf[i] = complex(re, im)
94-
95-
return Wavefunction(wf)
83+
num_cfloat = len(coef_string) // OCTETS_PER_COMPLEX_DOUBLE
84+
amplitude_vector = np.ndarray(shape=(num_cfloat,), buffer=coef_string, dtype=">c16")
85+
return Wavefunction(amplitude_vector)
9686

9787
def __len__(self) -> int:
9888
return len(self.amplitudes).bit_length() - 1

0 commit comments

Comments
 (0)