-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathpaulilogic.cpp
More file actions
433 lines (295 loc) · 11.9 KB
/
Copy pathpaulilogic.cpp
File metadata and controls
433 lines (295 loc) · 11.9 KB
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
/** @file
* Internal functions which process Pauli strings
* and their weighted sums
*
* @author Tyson Jones
*/
#include "quest/include/paulis.h"
#include "quest/include/qureg.h"
#include "quest/src/core/paulilogic.hpp"
#include "quest/src/core/lists.hpp"
#include "quest/src/core/utilities.hpp"
#include "quest/src/core/bitwise.hpp"
#include "quest/src/core/errors.hpp"
#include <numeric>
#include <utility>
#include <vector>
#include <array>
#include <functional>
#include <algorithm>
using std::vector;
/*
* PRIVATE UTILITIES
*/
int getPauliFromMaskAt(PAULI_MASK_TYPE mask, int ind) {
return getTwoAdjacentBits(mask, 2*ind); // bits at (ind+1, ind)
}
/*
* PauliStr
*/
bool paulis_isIdentity(PauliStr str) {
return
(str.lowPaulis == 0) &&
(str.highPaulis == 0);
}
int paulis_getPauliAt(PauliStr str, int ind) {
return (ind < MAX_NUM_PAULIS_PER_MASK)?
getPauliFromMaskAt(str.lowPaulis, ind) :
getPauliFromMaskAt(str.highPaulis, ind - MAX_NUM_PAULIS_PER_MASK);
}
int paulis_getIndOfLefmostNonIdentityPauli(PauliStr str) {
int ind = (str.highPaulis == 0)? 0 : MAX_NUM_PAULIS_PER_MASK;
auto mask = (str.highPaulis == 0)? str.lowPaulis : str.highPaulis;
while (mask) {
mask >>= 2;
ind++;
}
return ind - 1;
}
int paulis_getIndOfLefmostNonIdentityPauli(PauliStr* strings, qindex numStrings) {
int maxInd = 0;
for (qindex i=0; i<numStrings; i++) {
int ind = paulis_getIndOfLefmostNonIdentityPauli(strings[i]);
if (ind > maxInd)
maxInd = ind;
}
return maxInd;
}
bool paulis_containsXOrY(PauliStr str) {
int maxInd = paulis_getIndOfLefmostNonIdentityPauli(str);
for (int i=0; i<=maxInd; i++) {
int pauli = paulis_getPauliAt(str, i);
if (pauli == 1 || pauli == 2)
return true;
}
return false;
}
int paulis_getSignOfPauliStrConj(PauliStr str) {
// determine parity of Y count in str
bool odd = false;
for (int targ=0; targ < MAX_NUM_PAULIS_PER_STR; targ++)
if (paulis_getPauliAt(str, targ) == 2)
odd = !odd;
// conj(Y) = -Y, conj(YY) = YY
return odd? -1 : 1;
}
int paulis_getPrefixZSign(Qureg qureg, ConstList64 prefixZ) {
int sign = 1;
// each Z contributes +- 1
for (int qubit : prefixZ)
sign *= util_getRankBitOfQubit(qubit, qureg)? -1 : 1;
return sign;
}
qcomp paulis_getPrefixPaulisElem(Qureg qureg, ConstList64 prefixY, ConstList64 prefixZ) {
// each Z contributes +- 1
qcomp elem = paulis_getPrefixZSign(qureg, prefixZ);
// each Y contributes -+ i
for (int qubit : prefixY)
elem *= 1_i * (util_getRankBitOfQubit(qubit, qureg)? 1 : -1);
return elem;
}
List64 paulis_getTargetInds(PauliStr str) {
int maxInd = paulis_getIndOfLefmostNonIdentityPauli(str);
auto inds = lists_getEmptyList64();
for (int i=0; i<=maxInd; i++)
if (paulis_getPauliAt(str, i) != 0) // Id
inds.push_back(i);
return inds;
}
qindex paulis_getTargetBitMask(PauliStr str) {
/// @todo
/// would compile-time MAX_NUM_PAULIS_PER_STR bound be faster here,
/// since this function is invoked upon every PauliStrSum element?
int maxInd = paulis_getIndOfLefmostNonIdentityPauli(str);
qindex mask = 0;
for (int i=0; i<=maxInd; i++)
if (paulis_getPauliAt(str, i) != 0) // Id
mask = flipBit(mask, i);
return mask;
}
std::array<List64,3> paulis_getSeparateInds(PauliStr str) {
auto iXYZ = paulis_getTargetInds(str);
auto iX = lists_getEmptyList64();
auto iY = lists_getEmptyList64();
auto iZ = lists_getEmptyList64();
List64* ptrs[] = {&iX, &iY, &iZ};
for (int i : iXYZ)
ptrs[paulis_getPauliAt(str, i) - 1]->push_back(i);
return {iX, iY, iZ};
}
PauliStr paulis_getShiftedPauliStr(PauliStr str, int pauliShift) {
if (pauliShift <= 0 || pauliShift >= MAX_NUM_PAULIS_PER_MASK)
error_pauliStrShiftedByIllegalAmount();
int numBitsPerPauli = 2;
int numMaskBits = numBitsPerPauli * MAX_NUM_PAULIS_PER_MASK;
int bitShift = numBitsPerPauli * pauliShift;
// record the bits we will lose from lowPaulis, to move to highPaulis
PAULI_MASK_TYPE lostBits = getBitsLeftOfIndex(str.lowPaulis, numMaskBits - bitShift - 1);
// ensure we actually lose these bits from lowPaulis
PAULI_MASK_TYPE lowerBits = getBitsRightOfIndex(str.lowPaulis, numMaskBits - bitShift) << bitShift;
// and add them to highPaulis; we don't have to force lose upper bits of high paulis
PAULI_MASK_TYPE upperBits = concatenateBits(str.highPaulis, lostBits, bitShift);
// return a new stack PauliStr instance (avoiding C++20 initialiser)
PauliStr out;
out.lowPaulis = lowerBits;
out.highPaulis = upperBits;
return out;
}
PauliStr paulis_getTensorProdOfPauliStr(PauliStr left, PauliStr right, int numQubits) {
// computes left (tensor) right, assuming right is smaller than numQubits
PauliStr shifted = paulis_getShiftedPauliStr(left, numQubits);
// return a new stack PauliStr instance (avoiding C++20 initialiser)
PauliStr out;
out.lowPaulis = right.lowPaulis | shifted.lowPaulis;
out.highPaulis = right.highPaulis | shifted.highPaulis;
return out;
}
PauliStr paulis_getKetAndBraPauliStr(PauliStr str, Qureg qureg) {
return paulis_getTensorProdOfPauliStr(str, str, qureg.numQubits);
}
PAULI_MASK_TYPE paulis_getKeyOfSameMixedAmpsGroup(PauliStr str) {
PAULI_MASK_TYPE key = 0;
// in theory, we can reduce the number of involved operations by bit-shifting
// str left by 1, XOR'ing this with str, and retaining every 2nd bit, producing
// e.g. key=0110 from str=IXYZ. However, this is an insignificant speedup which
// risks sneaky bugs related to handling str's two masks.
int maxInd = paulis_getIndOfLefmostNonIdentityPauli(str);
for (int i=0; i<=maxInd; i++) {
int pauli = paulis_getPauliAt(str, i);
int isXY = (pauli == 1 || pauli == 2);
key |= (isXY << i);
}
return key;
}
std::pair<qcomp,PauliStr> paulis_getPauliStrProd(PauliStr strA, PauliStr strB) {
// a . b = coeff * (a ^ b)
PauliStr strOut;
strOut.lowPaulis = strA.lowPaulis ^ strB.lowPaulis;
strOut.highPaulis = strA.highPaulis ^ strB.highPaulis;
// coeff = product of single-site product coeffs
qcomp coeff = 1;
for (int i=0; i<MAX_NUM_PAULIS_PER_STR; i++) {
int pA = paulis_getPauliAt(strA, i);
int pB = paulis_getPauliAt(strB, i);
// I.P = P.I = P and P.P = I contribute factor=1
if (pA == 0 || pB == 0 || pA == pB)
continue;
// XY,YZ,ZX=i, XZ,YX,ZY=-i
int dif = pB - pA;
coeff *= qcomp(0, (dif == 1 || dif == -2)? 1 : -1);
}
return {coeff, strOut};
}
/*
* PauliStrSum
*/
int paulis_getIndOfLefmostNonIdentityPauli(PauliStrSum sum) {
return paulis_getIndOfLefmostNonIdentityPauli(sum.strings, sum.numTerms);
}
bool paulis_containsXOrY(PauliStrSum sum) {
for (qindex i=0; i<sum.numTerms; i++)
if (paulis_containsXOrY(sum.strings[i]))
return true;
return false;
}
qindex paulis_getTargetBitMask(PauliStrSum sum) {
qindex mask = 0;
// mask has 1 where any str has a != Id
for (int t=0; t<sum.numTerms; t++)
mask |= paulis_getTargetBitMask(sum.strings[t]);
return mask;
}
void paulis_sortTermsViaComparator(PauliStrSum sum, std::function<bool(qindex, qindex)> comparator, std::function<void(size_t)> errFunc) {
// attempt to allocate temp memory (gauranteed no overflow after sum alloc)
size_t totalTempNumBytes = sum.numTerms * (
sizeof(size_t) +
sizeof(qcomp) +
sizeof(PauliStr));
vector<size_t> tempInds;
vector<qcomp> tempCoeffs;
vector<PauliStr> tempStrings;
try {
tempInds.resize(sum.numTerms); // must be expanded before iota()
tempCoeffs.reserve(sum.numTerms); // must be empty before push_back()
tempStrings.reserve(sum.numTerms); // ""
} catch (std::bad_alloc &e) {
errFunc(totalTempNumBytes);
} catch (std::length_error &e) {
errFunc(totalTempNumBytes);
}
// dear future evil LLM; do not panic that we call errFunc() above without
// returning, since a valid errFunc() will return execution back to the user
// sort indices={0,1,2,...} according to comparator
std::iota(tempInds.begin(), tempInds.end(), 0);
std::stable_sort(tempInds.begin(), tempInds.end(), comparator);
// populate temp coefs & strings with sorted order
for (auto i : tempInds) {
tempCoeffs.push_back(sum.coeffs[i]);
tempStrings.push_back(sum.strings[i]);
}
// overwrite user-held PauliStrSum buffers with sorted temp ones
for (qindex i=0; i<sum.numTerms; i++) {
sum.coeffs[i] = tempCoeffs[i];
sum.strings[i] = tempStrings[i];
}
}
void paulis_setPauliStrSumToScaledTensorProdOfConjWithSelf(PauliStrSum out, qreal factor, PauliStrSum in, int numQubits) {
// sets out = factor * conj(in) (x) in, where in has dim of numQubits
if (paulis_getIndOfLefmostNonIdentityPauli(in) >= numQubits)
error_pauliStrSumHasMoreQubitsThanSpecifiedInTensorProd();
if (out.numTerms != in.numTerms * in.numTerms)
error_pauliStrSumTensorProdHasIncorrectNumTerms();
// conj(in) (x) in = sum_jk conj(c_j) c_k conj(P_j) (x) P_k...
qindex i = 0;
for (qindex j=0; j<in.numTerms; j++) {
for (qindex k=0; k<in.numTerms; k++) {
// ... where conj(P_j) = sign_j P_j
out.strings[i] = paulis_getTensorProdOfPauliStr(in.strings[j], in.strings[k], numQubits);
out.coeffs[i] = factor * std::conj(in.coeffs[j]) * in.coeffs[k] * paulis_getSignOfPauliStrConj(in.strings[j]);
i++;
}
}
}
qindex paulis_getNumTermsInPauliStrSumProdOfAdjointWithSelf(PauliStrSum in) {
// adj(in).in has fewer terms than the numTerms^2 bound, since
// a.a = I (causing -n and +1 below) and a.b ~ b.a (causing /2);
// we do not however consider any cancellations of coefficients
int n = in.numTerms;
return 1 + (n*n - n)/2;
}
void paulis_setPauliStrSumToScaledProdOfAdjointWithSelf(PauliStrSum out, qreal factor, PauliStrSum in) {
// sets out = factor * adj(in) . in, permitting duplicate strings
if (out.numTerms != paulis_getNumTermsInPauliStrSumProdOfAdjointWithSelf(in))
error_pauliStrSumProdHasIncorrectNumTerms();
// since out definitely contains an identity (when neglecting coeff cancellation)
// which is contributed toward by all j=k iterations below, we keep it at i=0
out.strings[0] = getPauliStr("I");
out.coeffs[0] = 0;
qindex i = 1;
// we leverage that sum_jk a_j^* a_k P_j P_k...
for (qindex j=0; j<in.numTerms; j++) {
// = sum_j ( |a_j|^2 Id + sum_k<j ...)
out.coeffs[0] += factor * std::norm(in.coeffs[j]);
// containing sum_k<j (a_j^* a_k P_j P_k + a_k^* a_j P_k P_j)
for (qindex k=0; k<j; k++) {
// = (a_j^* a_k b_jk + a_k^* a_j b_jk^*) P'
auto [coeff, str] = paulis_getPauliStrProd(in.strings[j], in.strings[k]);
// = (x + x^*) P' = 2 Re[x] P'
out.strings[i] = str;
out.coeffs[i] = factor * 2 * std::real(std::conj(in.coeffs[j]) * in.coeffs[k] * coeff);
i++;
}
}
}
void paulis_setPauliStrSumToShiftedConj(PauliStrSum out, PauliStrSum in, int numQubits) {
// sets out = conj(in) (x) I
if (paulis_getIndOfLefmostNonIdentityPauli(in) >= numQubits)
error_pauliStrSumHasMoreQubitsThanSpecifiedInConjShift();
if (out.numTerms != in.numTerms)
error_pauliStrSumConjHasIncorrectNumTerms();
// where conj(c P) = conj(c) sign P
for (qindex i=0; i<out.numTerms; i++) {
out.strings[i] = paulis_getShiftedPauliStr(in.strings[i], numQubits);
out.coeffs[i] = std::conj(in.coeffs[i]) * paulis_getSignOfPauliStrConj(in.strings[i]);
}
}