qiskit-addon-sqd 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ # This code is a Qiskit project.
2
+
3
+ # (C) Copyright IBM 2024.
4
+
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE.txt file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ # Any modifications or derivative works of this code must retain this
9
+ # copyright notice, and modified files need to carry a notice indicating
10
+ # that they have been altered from the originals.
11
+
12
+ """
13
+ Primary SQD functionality.
14
+
15
+ .. currentmodule:: qiskit_addon_sqd
16
+
17
+ .. autosummary::
18
+ :toctree: ../stubs/
19
+ :nosignatures:
20
+
21
+ Modules
22
+ =======
23
+ .. autosummary::
24
+ :toctree:
25
+
26
+ configuration_recovery
27
+ subsampling
28
+ counts
29
+ fermion
30
+ qubit
31
+ """
@@ -0,0 +1,298 @@
1
+ # This code is a Qiskit project.
2
+
3
+ # (C) Copyright IBM 2024.
4
+
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE.txt file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ # Any modifications or derivative works of this code must retain this
9
+ # copyright notice, and modified files need to carry a notice indicating
10
+ # that they have been altered from the originals.
11
+
12
+ """
13
+ Functions for performing self-consistent configuration recovery.
14
+
15
+ .. currentmodule:: qiskit_addon_sqd.configuration_recovery
16
+
17
+ .. autosummary::
18
+ :toctree: ../stubs/
19
+ :nosignatures:
20
+
21
+ post_select_by_hamming_weight
22
+ recover_configurations
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from collections.abc import Sequence
28
+
29
+ import numpy as np
30
+
31
+
32
+ def post_select_by_hamming_weight(
33
+ bitstring_matrix: np.ndarray, hamming_left: int, hamming_right: int
34
+ ) -> np.ndarray:
35
+ """
36
+ Post-select bitstrings based on the hamming weight of each half.
37
+
38
+ Args:
39
+ bitstring_matrix: A 2D array of ``bool`` representations of bit
40
+ values such that each row represents a single bitstring
41
+ hamming_left: The target hamming weight of the left half of bitstrings
42
+ hamming_right: The target hamming weight of the right half of bitstrings
43
+
44
+ Returns:
45
+ A mask signifying which samples were selected from the input matrix.
46
+ """
47
+ if hamming_left < 0 or hamming_right < 0:
48
+ raise ValueError("Hamming weights must be non-negative integers.")
49
+ num_bits = bitstring_matrix.shape[1]
50
+
51
+ # Find the bitstrings with correct hamming weight on both halves
52
+ up_keepers = np.sum(bitstring_matrix[:, : num_bits // 2], axis=1) == hamming_left
53
+ down_keepers = np.sum(bitstring_matrix[:, num_bits // 2 :], axis=1) == hamming_right
54
+ correct_bs_mask = np.array(np.logical_and(up_keepers, down_keepers))
55
+
56
+ return correct_bs_mask
57
+
58
+
59
+ def recover_configurations(
60
+ bitstring_matrix: np.ndarray,
61
+ probabilities: Sequence[float],
62
+ avg_occupancies: np.ndarray,
63
+ hamming_left: int,
64
+ hamming_right: int,
65
+ *,
66
+ rand_seed: int | None = None,
67
+ ) -> tuple[np.ndarray, np.ndarray]:
68
+ """
69
+ Refine bitstrings based on average orbital occupancy and a target hamming weight.
70
+
71
+ This function makes the assumption that bit ``i`` represents the same orbital as
72
+ bit ``i + # orbitals`` in all input bitstrings, s.t. ``i < # orbitals``.
73
+
74
+ Args:
75
+ bitstring_matrix: A 2D array of ``bool`` representations of bit
76
+ values such that each row represents a single bitstring
77
+ probabilities: A 1D array specifying a probability distribution over the bitstrings
78
+ avg_occupancies: A 1D array containing the mean occupancy of each orbital. It is assumed
79
+ that ``avg_occupancies[i]`` corresponds to the orbital represented by column
80
+ ``i`` in ``bitstring_matrix``.
81
+ hamming_left: The target hamming weight used for the left half of the bitstring
82
+ hamming_right: The target hamming weight used for the right half of the bitstring
83
+ rand_seed: A seed to control random behavior
84
+
85
+ Returns:
86
+ A corrected bitstring matrix and an updated probability array
87
+ """
88
+ if hamming_left < 0 or hamming_right < 0:
89
+ raise ValueError("Hamming weights must be non-negative integers.")
90
+
91
+ # First, we need to flip the orbitals such that
92
+
93
+ corrected_dict: dict[str, float] = {}
94
+ for bitstring, freq in zip(bitstring_matrix, probabilities):
95
+ bs_corrected = _bipartite_bitstring_correcting(
96
+ bitstring,
97
+ avg_occupancies,
98
+ hamming_left,
99
+ hamming_right,
100
+ rand_seed=rand_seed,
101
+ )
102
+ bs_str = np.array2string(bs_corrected.astype(int), separator="")[1:-1]
103
+ corrected_dict[bs_str] = corrected_dict.get(bs_str, 0.0) + freq
104
+ bs_mat_out = np.array([[bit == "1" for bit in bs] for bs in corrected_dict])
105
+ freqs_out = np.array([f for f in corrected_dict.values()])
106
+ freqs_out = np.abs(freqs_out) / np.sum(np.abs(freqs_out))
107
+
108
+ return bs_mat_out, freqs_out
109
+
110
+
111
+ def _p_flip_0_to_1(ratio_exp: float, occ: float, eps: float = 0.01) -> float:
112
+ """
113
+ Calculate the probability of flipping a bit from 0 to 1.
114
+
115
+ This function will more aggressively flip bits which are in disagreement
116
+ with the occupation information.
117
+
118
+ Args:
119
+ ratio_exp: The ratio of 1's expected in the set of bits
120
+ occ: The occupancy of a particular bit, based estimated ground
121
+ state found at the end of each configuration recovery iteration.
122
+ eps: A value for controlling how aggressively to flip bits
123
+
124
+ Returns:
125
+ The probability with which to flip the bit
126
+ """
127
+ # Occupancy is < than naive expectation.
128
+ # Flip 0s to 1 with small (~eps) probability in this case
129
+ if occ < ratio_exp:
130
+ return occ * eps / ratio_exp
131
+
132
+ # Occupancy is >= naive expectation.
133
+ # The probability to flip the bit increases linearly from ``eps`` to
134
+ # ``~1.0`` as the occupation deviates further from the expected ratio
135
+ slope = (1 - eps) / (1 - ratio_exp)
136
+ intercept = 1 - slope
137
+ return occ * slope + intercept
138
+
139
+
140
+ def _p_flip_1_to_0(ratio_exp: float, occ: float, eps: float = 0.01) -> float:
141
+ """
142
+ Calculate the probability of flipping a bit from 1 to 0.
143
+
144
+ This function will more aggressively flip bits which are in disagreement
145
+ with the occupation information.
146
+
147
+ Args:
148
+ ratio_exp: The ratio of 1's expected in the set of bits
149
+ occ: The occupancy of a particular bit, based estimated ground
150
+ state found at the end of each configuration recovery iteration.
151
+ eps: A value for controlling how aggressively to flip bits
152
+
153
+ Returns:
154
+ The probability with which to flip the bit
155
+ """
156
+ # Occupancy is < naive expectation.
157
+ # The probability to flip the bit increases linearly from ``eps`` to
158
+ # ``~1.0`` as the occupation deviates further from the expected ratio
159
+ if occ < 1.0 - ratio_exp:
160
+ slope = (1.0 - eps) / (1.0 - ratio_exp)
161
+ return 1.0 - occ * slope
162
+
163
+ # Occupancy is >= naive expectation.
164
+ # Flip 1s to 0 with small (~eps) probability in this case
165
+ slope = -eps / ratio_exp
166
+ intercept = eps / ratio_exp
167
+ return occ * slope + intercept
168
+
169
+
170
+ def _bipartite_bitstring_correcting(
171
+ bit_array: np.ndarray,
172
+ avg_occupancies: np.ndarray,
173
+ hamming_left: int,
174
+ hamming_right: int,
175
+ rand_seed: int | None = None,
176
+ ) -> np.ndarray:
177
+ """
178
+ Use occupancy information and target hamming weight to correct a bitstring.
179
+
180
+ Args:
181
+ bit_array: A 1D array of ``bool`` representations of bit values
182
+ avg_occupancies: A 1D array containing the mean occupancy of each orbital.
183
+ hamming_left: The target hamming weight used for the left half of the bitstring
184
+ hamming_right: The target hamming weight used for the right half of the bitstring
185
+ rand_seed: A seed to control random behavior
186
+
187
+ Returns:
188
+ A corrected bitstring
189
+ """
190
+ # This function must not mutate the input arrays.
191
+ bit_array = bit_array.copy()
192
+
193
+ np.random.seed(rand_seed)
194
+
195
+ # The number of bits should be even
196
+ num_bits = bit_array.shape[0]
197
+ partition_size = num_bits // 2
198
+
199
+ # Get the probability of flipping each bit, separated into LEFT and RIGHT subsystems,
200
+ # based on the avg occupancy of each bit and the target hamming weight
201
+ probs_left = np.zeros(partition_size)
202
+ probs_right = np.zeros(partition_size)
203
+ for i in range(partition_size):
204
+ if bit_array[i]:
205
+ probs_left[i] = _p_flip_1_to_0(
206
+ hamming_left / float(partition_size), avg_occupancies[i], 0.01
207
+ )
208
+ else:
209
+ probs_left[i] = _p_flip_0_to_1(
210
+ hamming_left / float(partition_size), avg_occupancies[i], 0.01
211
+ )
212
+
213
+ if bit_array[i + partition_size]:
214
+ probs_right[i] = _p_flip_1_to_0(
215
+ hamming_right / float(partition_size), avg_occupancies[i], 0.01
216
+ )
217
+ else:
218
+ probs_right[i] = _p_flip_0_to_1(
219
+ hamming_right / float(partition_size), avg_occupancies[i], 0.01
220
+ )
221
+
222
+ # Normalize
223
+ probs_left = np.absolute(probs_left)
224
+ probs_right = np.absolute(probs_right)
225
+ probs_left = probs_left / np.sum(probs_left)
226
+ probs_right = probs_right / np.sum(probs_right)
227
+
228
+ ######################## Handle LEFT bits ########################
229
+
230
+ # Get difference between # of 1s and expected # of 1s in LEFT bits
231
+ n_left = np.sum(bit_array[:partition_size])
232
+ n_diff = n_left - hamming_left
233
+
234
+ # Too many electrons in LEFT bits
235
+ if n_diff > 0:
236
+ indices_occupied = np.where(bit_array[:partition_size])[0]
237
+ # Get the probabilities that each 1 should be flipped to 0
238
+ p_choice = probs_left[bit_array[:partition_size]] / np.sum(
239
+ probs_left[bit_array[:partition_size]]
240
+ )
241
+ # Correct the hamming by probabilistically flipping some bits to flip to 0
242
+ indices_to_flip = np.random.choice(
243
+ indices_occupied, size=round(n_diff), replace=False, p=p_choice
244
+ )
245
+ bit_array[:partition_size][indices_to_flip] = False
246
+
247
+ # too few electrons in LEFT bits
248
+ if n_diff < 0:
249
+ indices_empty = np.where(np.logical_not(bit_array[:partition_size]))[0]
250
+ # Get the probabilities that each 0 should be flipped to 1
251
+ p_choice = probs_left[np.logical_not(bit_array[:partition_size])] / np.sum(
252
+ probs_left[np.logical_not(bit_array[:partition_size])]
253
+ )
254
+ # Correct the hamming by probabilistically flipping some bits to flip to 1
255
+ indices_to_flip = np.random.choice(
256
+ indices_empty, size=round(np.abs(n_diff)), replace=False, p=p_choice
257
+ )
258
+ bit_array[:partition_size][indices_to_flip] = np.logical_not(
259
+ bit_array[:partition_size][indices_to_flip]
260
+ )
261
+
262
+ ######################## Handle RIGHT bits ########################
263
+
264
+ # Get difference between # of 1s and expected # of 1s in RIGHT bits
265
+ n_right = np.sum(bit_array[partition_size:])
266
+ n_diff = n_right - hamming_right
267
+
268
+ # too many electrons in RIGHT bits
269
+ if n_diff > 0:
270
+ indices_occupied = np.where(bit_array[partition_size:])[0]
271
+ # Get the probabilities that each 1 should be flipped to 0
272
+ p_choice = probs_right[bit_array[partition_size:]] / np.sum(
273
+ probs_right[bit_array[partition_size:]]
274
+ )
275
+ # Correct the hamming by probabilistically flipping some bits to flip to 0
276
+ indices_to_flip = np.random.choice(
277
+ indices_occupied, size=round(n_diff), replace=False, p=p_choice
278
+ )
279
+ bit_array[partition_size:][indices_to_flip] = np.logical_not(
280
+ bit_array[partition_size:][indices_to_flip]
281
+ )
282
+
283
+ # too few electrons in RIGHT bits
284
+ if n_diff < 0:
285
+ indices_empty = np.where(np.logical_not(bit_array[partition_size:]))[0]
286
+ # Get the probabilities that each 1 should be flipped to 0
287
+ p_choice = probs_right[np.logical_not(bit_array[partition_size:])] / np.sum(
288
+ probs_right[np.logical_not(bit_array[partition_size:])]
289
+ )
290
+ # Correct the hamming by probabilistically flipping some bits to flip to 1
291
+ indices_to_flip = np.random.choice(
292
+ indices_empty, size=round(np.abs(n_diff)), replace=False, p=p_choice
293
+ )
294
+ bit_array[partition_size:][indices_to_flip] = np.logical_not(
295
+ bit_array[partition_size:][indices_to_flip]
296
+ )
297
+
298
+ return bit_array
@@ -0,0 +1,158 @@
1
+ # This code is a Qiskit project.
2
+
3
+ # (C) Copyright IBM 2024.
4
+
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE.txt file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ # Any modifications or derivative works of this code must retain this
9
+ # copyright notice, and modified files need to carry a notice indicating
10
+ # that they have been altered from the originals.
11
+
12
+ """
13
+ Functions for transforming counts dictionaries.
14
+
15
+ .. currentmodule:: qiskit_addon_sqd.counts
16
+
17
+ .. autosummary::
18
+ :toctree: ../stubs/
19
+ :nosignatures:
20
+
21
+ counts_to_arrays
22
+ generate_counts_uniform
23
+ generate_counts_bipartite_hamming
24
+ normalize_counts_dict
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import numpy as np
30
+
31
+
32
+ def counts_to_arrays(counts: dict[str, float | int]) -> tuple[np.ndarray, np.ndarray]:
33
+ """
34
+ Convert a counts dictionary into a bitstring matrix and a probability array.
35
+
36
+ Args:
37
+ counts: The counts dictionary to convert
38
+
39
+ Returns:
40
+ A tuple containing:
41
+ - A 2D array representing the sampled bitstrings. Each row represents a
42
+ bitstring, and each element is a ``bool`` representation of the
43
+ bit's value
44
+ - A 1D array containing the probability with which each bitstring was sampled
45
+ """
46
+ if counts == {}:
47
+ return np.array([]), np.array([])
48
+ prob_dict = normalize_counts_dict(counts)
49
+ bs_mat = np.array([[bit == "1" for bit in bitstring] for bitstring in prob_dict])
50
+ freq_arr = np.array(list(prob_dict.values()))
51
+
52
+ return bs_mat, freq_arr
53
+
54
+
55
+ def generate_counts_uniform(
56
+ num_samples: int, num_bits: int, rand_seed: None | int = None
57
+ ) -> dict[str, int]:
58
+ """
59
+ Generate a bitstring counts dictionary of samples drawn from the uniform distribution.
60
+
61
+ Args:
62
+ num_samples: The number of samples to draw
63
+ num_bits: The number of bits in the bitstrings
64
+ rand_seed: A seed for controlling randomness
65
+
66
+ Returns:
67
+ A dictionary mapping bitstrings of length ``num_bits`` to the
68
+ number of times they were sampled.
69
+
70
+ Raises:
71
+ ValueError: ``num_samples`` and ``num_bits`` must be positive integers.
72
+ """
73
+ if num_samples < 1:
74
+ raise ValueError("The number of samples must be specified with a positive integer.")
75
+ if num_bits < 1:
76
+ raise ValueError("The number of bits must be specified with a positive integer.")
77
+ np.random.seed(rand_seed)
78
+ sample_dict: dict[str, int] = {}
79
+ # Use numpy to generate a random matrix of bit values and
80
+ # convert it to a dictionary of bitstring samples
81
+ bts_matrix = np.random.choice([0, 1], size=(num_samples, num_bits))
82
+ for i in range(num_samples):
83
+ bts_arr = bts_matrix[i, :].astype("int")
84
+ bts = np.array2string(bts_arr, separator="")[1:-1]
85
+ sample_dict[bts] = sample_dict.get(bts, 0) + 1
86
+
87
+ return sample_dict
88
+
89
+
90
+ def generate_counts_bipartite_hamming(
91
+ num_samples: int,
92
+ num_bits: int,
93
+ hamming_left: int,
94
+ hamming_right: int,
95
+ rand_seed: None | int = None,
96
+ ) -> dict[str, int]:
97
+ """
98
+ Generate a bitstring counts dictionary with specified bipartite hamming weight.
99
+
100
+ Args:
101
+ num_samples: The number of samples to draw
102
+ num_bits: The number of bits in the bitstrings
103
+ hamming_left: The hamming weight on the left half of each bitstring
104
+ hamming_right: The hamming weight on the right half of each bitstring
105
+ rand_seed: A seed for controlling randomness
106
+
107
+ Returns:
108
+ A dictionary mapping bitstrings to the number of times they were sampled.
109
+ Each half of each bitstring in the output dictionary will have a hamming
110
+ weight as specified by the inputs.
111
+
112
+ Raises:
113
+ ValueError: ``num_bits`` and ``num_samples`` must be positive integers.
114
+ ValueError: Hamming weights must be specified as non-negative integers.
115
+ ValueError: ``num_bits`` must be even.
116
+ """
117
+ if num_bits % 2 != 0:
118
+ raise ValueError("The number of bits must be specified with an even integer.")
119
+ if num_samples < 1:
120
+ raise ValueError("The number of samples must be specified with a positive integer.")
121
+ if num_bits < 1:
122
+ raise ValueError("The number of bits must be specified with a positive integer.")
123
+ if hamming_left < 0 or hamming_right < 0:
124
+ raise ValueError("Hamming weights must be specified as non-negative integers.")
125
+
126
+ np.random.seed(rand_seed)
127
+
128
+ sample_dict: dict[str, int] = {}
129
+ for _ in range(num_samples):
130
+ # Pick random bits to flip such that the left and right hamming weights are correct
131
+ up_flips = np.random.choice(np.arange(num_bits // 2), hamming_left, replace=False).astype(
132
+ "int"
133
+ )
134
+ dn_flips = np.random.choice(np.arange(num_bits // 2), hamming_right, replace=False).astype(
135
+ "int"
136
+ )
137
+
138
+ # Create a bitstring with the chosen bits flipped
139
+ bts_arr = np.zeros(num_bits)
140
+ bts_arr[up_flips] = 1
141
+ bts_arr[dn_flips + num_bits // 2] = 1
142
+ bts_arr = bts_arr.astype("int")
143
+ bts = np.array2string(bts_arr, separator="")[1:-1]
144
+
145
+ # Add the bitstring to the sample dict
146
+ sample_dict[bts] = sample_dict.get(bts, 0) + 1
147
+
148
+ return sample_dict
149
+
150
+
151
+ def normalize_counts_dict(counts: dict[str, float | int]) -> dict[str, float]:
152
+ """Convert a counts dictionary into a probability dictionary."""
153
+ if counts == {}:
154
+ return counts
155
+
156
+ total_counts = float(sum(counts.values()))
157
+
158
+ return {bs: count / total_counts for bs, count in counts.items()}