-
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathQuantumComputation.cpp
More file actions
1667 lines (1493 loc) · 59.9 KB
/
Copy pathQuantumComputation.cpp
File metadata and controls
1667 lines (1493 loc) · 59.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
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
/*
* Copyright (c) 2023 - 2025 Chair for Design Automation, TUM
* Copyright (c) 2025 Munich Quantum Software Company GmbH
* All rights reserved.
*
* SPDX-License-Identifier: MIT
*
* Licensed under the MIT License
*/
#include "ir/QuantumComputation.hpp"
#include "ir/Definitions.hpp"
#include "ir/Register.hpp"
#include "ir/operations/CompoundOperation.hpp"
#include "ir/operations/Control.hpp"
#include "ir/operations/Expression.hpp"
#include "ir/operations/IfElseOperation.hpp"
#include "ir/operations/NonUnitaryOperation.hpp"
#include "ir/operations/OpType.hpp"
#include "ir/operations/StandardOperation.hpp"
#include "ir/operations/SymbolicOperation.hpp"
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <ostream>
#include <random>
#include <ranges>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <variant>
#include <vector>
namespace qc {
namespace {
template <class RegisterType>
void printSortedRegisters(
const std::unordered_map<std::string, RegisterType>& registers,
const std::string& identifier, std::ostream& of, const bool openQASM3) {
// sort regs by start index
std::map<size_t, RegisterType> sortedRegs{};
for (const auto& [name, reg] : registers) {
sortedRegs.emplace(reg.getStartIndex(), reg);
}
for (const auto& r : sortedRegs) {
const auto& reg = r.second;
if (openQASM3) {
of << identifier << "[" << reg.getSize() << "] " << reg.getName()
<< ";\n";
} else {
of << identifier << " " << reg.getName() << "[" << reg.getSize()
<< "];\n";
}
}
}
void consolidateRegister(QuantumRegisterMap& regs) {
bool finished = regs.empty();
while (!finished) {
for (const auto& [name, qreg] : regs) {
finished = true;
// check if lower part of register
if (name.ends_with("_l")) {
auto lowidx = qreg.getStartIndex();
auto lownum = qreg.getSize();
// search for higher part of register
auto highname = name.substr(0, name.size() - 1) + 'h';
if (const auto it = regs.find(highname); it != regs.end()) {
auto& highReg = it->second;
auto highidx = highReg.getStartIndex();
auto highnum = highReg.getSize();
// fusion of registers possible
if (lowidx + lownum == highidx) {
finished = false;
auto targetname = name.substr(0, name.size() - 2);
auto targetidx = lowidx;
auto targetnum = lownum + highnum;
regs.erase(name);
regs.erase(highname);
regs.try_emplace(targetname, targetidx, targetnum, targetname);
}
}
break;
}
}
}
}
/**
* @brief Removes a certain qubit in a register from the register map
* @details If this was the last qubit in the register, the register is
* deleted. Removals at the beginning or the end of a register just modify the
* existing register. Removals in the middle of a register split the register
* into two new registers. The new registers are named by appending "_l" and
* "_h" to the original register name.
* @param regs A collection of all the registers
* @param reg The name of the register containing the qubit to be removed
* @param idx The index of the qubit in the register to be removed
*/
void removeQubitfromQubitRegister(QuantumRegisterMap& regs,
QuantumRegister& reg, const Qubit idx) {
if (idx == 0) {
// last remaining qubit of register
if (reg.getSize() == 1) {
// delete register
regs.erase(reg.getName());
}
// first qubit of register
else {
reg.getStartIndex()++;
reg.getSize()--;
}
// last index
} else if (idx == reg.getSize() - 1) {
// reduce count of register
reg.getSize()--;
} else {
const auto startIndex = reg.getStartIndex();
const auto count = reg.getSize();
const auto lowPart = reg.getName() + "_l";
const auto lowIndex = startIndex;
const auto lowCount = idx;
const auto highPart = reg.getName() + "_h";
const auto highIndex = startIndex + idx + 1;
const auto highCount = count - idx - 1;
regs.erase(reg.getName());
regs.try_emplace(lowPart, lowIndex, lowCount, lowPart);
regs.try_emplace(highPart, highIndex, highCount, highPart);
}
}
/**
* @brief Adds a qubit to a register in the register map
* @details If the register map is empty, a new register is created with the
* default name. If the qubit can be appended to the start or the end of an
* existing register, it is appended. Otherwise a new register is created with
* the default name and the qubit index appended.
* @param regs A collection of all the registers
* @param physicalQubitIndex The index of the qubit to be added
* @param defaultRegName The default name of the register to be created
*/
void addQubitToQubitRegister(QuantumRegisterMap& regs, Qubit physicalQubitIndex,
const std::string& defaultRegName) {
auto fusionPossible = false;
for (auto& [name, reg] : regs) {
auto& startIndex = reg.getStartIndex();
auto& count = reg.getSize();
// 1st case: can append to start of existing register
if (startIndex == physicalQubitIndex + 1) {
startIndex--;
count++;
fusionPossible = true;
break;
}
// 2nd case: can append to end of existing register
if (startIndex + count == physicalQubitIndex) {
count++;
fusionPossible = true;
break;
}
}
consolidateRegister(regs);
if (regs.empty()) {
regs.try_emplace(defaultRegName, physicalQubitIndex, 1, defaultRegName);
} else if (!fusionPossible) {
const auto newRegName =
defaultRegName + "_" + std::to_string(physicalQubitIndex);
regs.try_emplace(newRegName, physicalQubitIndex, 1, newRegName);
}
}
} // namespace
/***
* Public Methods
***/
std::size_t QuantumComputation::getNindividualOps() const {
std::size_t nops = 0;
for (const auto& op : ops) {
if (const auto* const comp =
dynamic_cast<const CompoundOperation*>(op.get());
comp != nullptr) {
nops += comp->size();
} else {
++nops;
}
}
return nops;
}
std::size_t QuantumComputation::getNsingleQubitOps() const {
std::size_t nops = 0;
for (const auto& op : ops) {
if (!op->isUnitary()) {
continue;
}
if (const auto* const comp =
dynamic_cast<const CompoundOperation*>(op.get());
comp != nullptr) {
for (const auto& subop : *comp) {
if (subop->isUnitary() && !subop->isControlled() &&
subop->getNtargets() == 1U) {
++nops;
}
}
} else {
if (!op->isControlled() && op->getNtargets() == 1U) {
++nops;
}
}
}
return nops;
}
std::size_t QuantumComputation::getDepth() const {
if (empty()) {
return 0U;
}
std::vector<std::size_t> depths(getNqubits(), 0U);
for (const auto& op : ops) {
op->addDepthContribution(depths);
}
return *std::ranges::max_element(depths);
}
void QuantumComputation::initializeIOMapping() {
// try gathering (additional) output permutation information from
// measurements, e.g., a measurement
// `measure q[i] -> c[j];`
// implies that the j-th (logical) output is obtained from measuring the i-th
// physical qubit.
const bool outputPermutationFound = !outputPermutation.empty();
// track whether the circuit contains measurements at the end of the circuit
// if it does, then all qubits that are not measured shall be considered
// garbage outputs
bool outputPermutationFromMeasurements = false;
std::set<Qubit> measuredQubits{};
for (const auto& opIt : ops) {
if (const auto* const op = dynamic_cast<NonUnitaryOperation*>(opIt.get());
op != nullptr && op->getType() == Measure) {
outputPermutationFromMeasurements = true;
assert(op->getTargets().size() == op->getClassics().size());
auto classicIt = op->getClassics().cbegin();
for (const auto& q : op->getTargets()) {
const auto qubitidx = q;
// only the first measurement of a qubit is used to determine the output
// permutation
if (measuredQubits.contains(qubitidx)) {
continue;
}
const auto bitidx = *classicIt;
if (outputPermutationFound) {
// output permutation was already set before -> permute existing
// values
if (const auto current = outputPermutation.at(qubitidx);
static_cast<std::size_t>(current) != bitidx) {
for (auto& p : outputPermutation) {
if (static_cast<std::size_t>(p.second) == bitidx) {
p.second = current;
break;
}
}
outputPermutation.at(qubitidx) = static_cast<Qubit>(bitidx);
}
} else {
// directly set permutation if none was set beforehand
outputPermutation[qubitidx] = static_cast<Qubit>(bitidx);
}
measuredQubits.emplace(qubitidx);
++classicIt;
}
}
}
// clear any qubits that were not measured from the output permutation
// these will be marked garbage further down below
if (outputPermutationFromMeasurements) {
auto it = outputPermutation.begin();
while (it != outputPermutation.end()) {
if (!measuredQubits.contains(it->first)) {
it = outputPermutation.erase(it);
} else {
++it;
}
}
}
garbage.assign(nqubits + nancillae, false);
for (const auto& [physicalIn, logicalIn] : initialLayout) {
// if the qubit is not an output, mark it as garbage
const bool isOutput = std::ranges::any_of(
outputPermutation,
[&logicIn = logicalIn](const auto& p) { return p.second == logicIn; });
if (!isOutput) {
setLogicalQubitGarbage(logicalIn);
}
// if the qubit is an ancillary and idle, mark it as garbage
if (const bool isIdle = isIdleQubit(physicalIn);
logicalQubitIsAncillary(logicalIn) && isIdle) {
setLogicalQubitGarbage(logicalIn);
}
}
}
const QuantumRegister&
QuantumComputation::addQubitRegister(std::size_t nq,
const std::string& regName) {
if (quantumRegisters.contains(regName)) {
throw std::runtime_error("[addQubitRegister] Register " + regName +
" already exists");
}
if (nq == 0) {
throw std::runtime_error(
"[addQubitRegister] New register size must be larger than 0");
}
if (nancillae != 0) {
throw std::runtime_error(
"[addQubitRegister] Cannot add qubit register after ancillary "
"qubits have been added");
}
quantumRegisters.try_emplace(regName, static_cast<Qubit>(nqubits), nq,
regName);
for (std::size_t i = 0; i < nq; ++i) {
auto j = static_cast<Qubit>(nqubits + i);
initialLayout.emplace(j, j);
outputPermutation.emplace(j, j);
}
nqubits += nq;
ancillary.resize(nqubits + nancillae);
garbage.resize(nqubits + nancillae);
return quantumRegisters.at(regName);
}
const ClassicalRegister&
QuantumComputation::addClassicalRegister(std::size_t nc,
const std::string& regName) {
if (classicalRegisters.contains(regName)) {
throw std::runtime_error("[addClassicalRegister] Register " + regName +
" already exists");
}
if (nc == 0) {
throw std::runtime_error(
"[addClassicalRegister] New register size must be larger than 0");
}
const auto [it, success] =
classicalRegisters.try_emplace(regName, nclassics, nc, regName);
assert(success);
nclassics += nc;
return it->second;
}
const QuantumRegister&
QuantumComputation::addAncillaryRegister(std::size_t nq,
const std::string& regName) {
if (ancillaRegisters.contains(regName)) {
throw std::runtime_error("[addAncillaryRegister] Register " + regName +
" already exists");
}
if (nq == 0) {
throw std::runtime_error(
"[addAncillaryRegister] New register size must be larger than 0");
}
const auto totalqubits = static_cast<Qubit>(nqubits + nancillae);
ancillaRegisters.try_emplace(regName, totalqubits, nq, regName);
ancillary.resize(totalqubits + nq);
garbage.resize(totalqubits + nq);
for (std::size_t i = 0; i < nq; ++i) {
auto j = static_cast<Qubit>(totalqubits + i);
initialLayout.emplace(j, j);
outputPermutation.emplace(j, j);
ancillary[j] = true;
}
nancillae += nq;
return ancillaRegisters.at(regName);
}
std::pair<Qubit, std::optional<Qubit>>
QuantumComputation::removeQubit(const Qubit logicalQubitIndex) {
// Find index of the physical qubit i is assigned to
const auto physicalQubitIndex = getPhysicalQubitIndex(logicalQubitIndex);
// get register and register-index of the corresponding qubit
auto& reg = getQubitRegister(physicalQubitIndex);
const auto& idx = reg.getLocalIndex(physicalQubitIndex);
if (physicalQubitIsAncillary(physicalQubitIndex)) {
removeQubitfromQubitRegister(ancillaRegisters, reg, idx);
// reduce ancilla count
nancillae--;
} else {
removeQubitfromQubitRegister(quantumRegisters, reg, idx);
// reduce qubit count
if (ancillary.at(logicalQubitIndex)) {
// if the qubit is ancillary, it is not counted as a qubit
nancillae--;
} else {
nqubits--;
}
}
// adjust initial layout permutation
initialLayout.erase(physicalQubitIndex);
// remove potential output permutation entry
std::optional<Qubit> outputQubitIndex{};
if (const auto it = outputPermutation.find(physicalQubitIndex);
it != outputPermutation.end()) {
outputQubitIndex = it->second;
// erasing entry
outputPermutation.erase(physicalQubitIndex);
}
// update ancillary and garbage tracking
const auto totalQubits = nqubits + nancillae;
for (std::size_t i = logicalQubitIndex; i < totalQubits; ++i) {
ancillary[i] = ancillary[i + 1];
garbage[i] = garbage[i + 1];
}
// unset last entry
ancillary[totalQubits] = false;
garbage[totalQubits] = false;
return {physicalQubitIndex, outputQubitIndex};
}
// adds j-th physical qubit as ancilla to the end of reg or creates the register
// if necessary
void QuantumComputation::addAncillaryQubit(
Qubit physicalQubitIndex, std::optional<Qubit> outputQubitIndex) {
if (initialLayout.count(physicalQubitIndex) > 0 ||
outputPermutation.count(physicalQubitIndex) > 0) {
throw std::runtime_error(
"[addAncillaryQubit] Attempting to insert physical "
"qubit that is already assigned");
}
addQubitToQubitRegister(ancillaRegisters, physicalQubitIndex, "anc");
// index of logical qubit
const auto logicalQubitIndex = nqubits + nancillae;
// resize ancillary and garbage tracking vectors
ancillary.resize(logicalQubitIndex + 1U);
garbage.resize(logicalQubitIndex + 1U);
// increase ancillae count and mark as ancillary
nancillae++;
ancillary[logicalQubitIndex] = true;
// adjust initial layout
initialLayout.emplace(physicalQubitIndex,
static_cast<Qubit>(logicalQubitIndex));
// adjust output permutation
if (outputQubitIndex.has_value()) {
outputPermutation.emplace(physicalQubitIndex, *outputQubitIndex);
} else {
// if a qubit is not relevant for the output, it is considered garbage
garbage[logicalQubitIndex] = true;
}
}
void QuantumComputation::addQubit(const Qubit logicalQubitIndex,
const Qubit physicalQubitIndex,
const std::optional<Qubit> outputQubitIndex) {
if (initialLayout.count(physicalQubitIndex) > 0 ||
outputPermutation.count(physicalQubitIndex) > 0) {
throw std::runtime_error(
"[addQubit] Attempting to insert physical qubit that is "
"already assigned");
}
if (logicalQubitIndex > nqubits) {
throw std::runtime_error(
"[addQubit] There are currently only " + std::to_string(nqubits) +
" qubits in the circuit. Adding " + std::to_string(logicalQubitIndex) +
" is therefore not possible at the moment.");
// TODO: this does not necessarily have to lead to an error. A new qubit
// register could be created and all ancillaries shifted
}
addQubitToQubitRegister(quantumRegisters, physicalQubitIndex, "q");
// increase qubit count
nqubits++;
// adjust initial layout
initialLayout.emplace(physicalQubitIndex, logicalQubitIndex);
if (outputQubitIndex.has_value()) {
// adjust output permutation
outputPermutation.emplace(physicalQubitIndex, *outputQubitIndex);
}
// update ancillary and garbage tracking
const auto totalQubits = nqubits + nancillae;
ancillary.resize(totalQubits);
garbage.resize(totalQubits);
for (auto i = totalQubits - 1; i > logicalQubitIndex; --i) {
ancillary[i] = ancillary[i - 1];
garbage[i] = garbage[i - 1];
}
// unset new entry
ancillary[logicalQubitIndex] = false;
garbage[logicalQubitIndex] = false;
}
QuantumComputation
QuantumComputation::instantiate(const VariableAssignment& assignment) const {
QuantumComputation result(*this);
result.instantiateInplace(assignment);
return result;
}
void QuantumComputation::invert() {
for (const auto& op : ops) {
op->invert();
}
std::ranges::reverse(ops);
if (initialLayout.size() == outputPermutation.size()) {
std::swap(initialLayout, outputPermutation);
} else {
std::cerr << "Warning: Inverting a circuit with different initial layout "
"and output permutation sizes. This is not supported yet.\n"
"The circuit will be inverted, but the initial layout and "
"output permutation will not be swapped.\n";
}
}
bool QuantumComputation::operator==(const QuantumComputation& rhs) const {
if (nqubits != rhs.nqubits || nancillae != rhs.nancillae ||
nclassics != rhs.nclassics || quantumRegisters != rhs.quantumRegisters ||
classicalRegisters != rhs.classicalRegisters ||
ancillaRegisters != rhs.ancillaRegisters ||
initialLayout != rhs.initialLayout ||
outputPermutation != rhs.outputPermutation ||
ancillary != rhs.ancillary || garbage != rhs.garbage ||
seed != rhs.seed || globalPhase != rhs.globalPhase ||
occurringVariables != rhs.occurringVariables) {
return false;
}
if (ops.size() != rhs.ops.size()) {
return false;
}
for (std::size_t i = 0; i < ops.size(); ++i) {
if (*ops[i] != *rhs.ops[i]) {
return false;
}
}
return true;
}
std::ostream& QuantumComputation::print(std::ostream& os) const {
os << name << "\n";
const auto width =
ops.empty() ? 1 : static_cast<int>(std::log10(ops.size()) + 1.);
os << std::setw(width + 1) << "i:";
for (const auto& [physical, logical] : initialLayout) {
if (ancillary[logical]) {
os << "\033[31m";
}
os << std::setw(4) << logical << "\033[0m";
}
os << "\n";
size_t i = 0U;
for (const auto& op : ops) {
os << std::setw(width) << ++i << ":";
op->print(os, initialLayout, static_cast<std::size_t>(width) + 1U,
getNqubits());
os << "\n";
}
os << std::setw(width + 1) << "o:";
for (const auto& physicalQubit : initialLayout) {
auto it = outputPermutation.find(physicalQubit.first);
if (it == outputPermutation.end()) {
os << "\033[31m" << std::setw(4) << "|" << "\033[0m";
} else {
os << std::setw(4) << it->second;
}
}
os << "\n";
return os;
}
std::ostream& QuantumComputation::printStatistics(std::ostream& os) const {
os << "QC Statistics:";
os << "\n\tn: " << static_cast<std::size_t>(nqubits);
os << "\n\tanc: " << static_cast<std::size_t>(nancillae);
os << "\n\tm: " << ops.size();
os << "\n--------------\n";
return os;
}
void QuantumComputation::dumpOpenQASM(std::ostream& of, bool openQASM3) const {
// dump initial layout and output permutation
// since it might happen that the physical qubit indices are not consecutive,
// due to qubit removals, we need to adjust them accordingly.
Permutation qubitToIndex{};
Permutation inverseInitialLayout{};
Qubit idx = 0;
for (const auto& [physical, logical] : initialLayout) {
inverseInitialLayout.emplace(logical, idx);
qubitToIndex[physical] = idx;
++idx;
}
of << "// i";
for (const auto& [logical, physical] : inverseInitialLayout) {
of << " " << static_cast<std::size_t>(physical);
}
of << "\n";
Permutation inverseOutputPermutation{};
for (const auto& [physical, logical] : outputPermutation) {
inverseOutputPermutation.emplace(logical, qubitToIndex[physical]);
}
of << "// o";
for (const auto& [logical, physical] : inverseOutputPermutation) {
of << " " << physical;
}
of << "\n";
if (openQASM3) {
of << "OPENQASM 3.0;\n";
of << "include \"stdgates.inc\";\n";
} else {
of << "OPENQASM 2.0;\n";
of << "include \"qelib1.inc\";\n";
}
// combine qregs and ancregs
auto combinedRegs = quantumRegisters;
for (const auto& reg : ancillaRegisters) {
combinedRegs.emplace(reg);
}
printSortedRegisters(combinedRegs, openQASM3 ? "qubit" : "qreg", of,
openQASM3);
printSortedRegisters(classicalRegisters, openQASM3 ? "bit" : "creg", of,
openQASM3);
// build qubit index -> register map
QubitIndexToRegisterMap qubitMap{};
for (const auto& [_, reg] : combinedRegs) {
const auto bound = reg.getStartIndex() + reg.getSize();
for (Qubit i = reg.getStartIndex(); i < bound; ++i) {
qubitMap.try_emplace(i, reg, reg.toString(i));
}
}
// build classical index -> register map
BitIndexToRegisterMap bitMap{};
for (const auto& [_, reg] : classicalRegisters) {
const auto bound = reg.getStartIndex() + reg.getSize();
for (Bit i = reg.getStartIndex(); i < bound; ++i) {
bitMap.try_emplace(i, reg, reg.toString(i));
}
}
for (const auto& op : ops) {
op->dumpOpenQASM(of, qubitMap, bitMap, 0, openQASM3);
}
}
std::string QuantumComputation::toQASM(const bool qasm3) const {
std::stringstream ss;
dumpOpenQASM(ss, qasm3);
return ss.str();
}
std::unique_ptr<Operation> QuantumComputation::asOperation() {
if (ops.empty()) {
return {};
}
if (ops.size() == 1) {
auto op = std::move(ops.front());
ops.clear();
return op;
}
return asCompoundOperation();
}
void QuantumComputation::reset() {
ops.clear();
nqubits = 0;
nclassics = 0;
nancillae = 0;
quantumRegisters.clear();
classicalRegisters.clear();
ancillaRegisters.clear();
initialLayout.clear();
outputPermutation.clear();
}
void QuantumComputation::dump(const std::string& filename,
const Format format) const {
auto of = std::ofstream(filename);
if (!of.good()) {
throw std::runtime_error("[dump] Error opening file: " + filename);
}
if (format == Format::OpenQASM3) {
dumpOpenQASM(of, true);
} else {
dumpOpenQASM(of, false);
}
}
bool QuantumComputation::isIdleQubit(const Qubit physicalQubit) const {
return std::ranges::none_of(ops, [&physicalQubit](const auto& op) {
return op->actsOn(physicalQubit);
});
}
void QuantumComputation::stripIdleQubits(bool force) {
auto layoutCopy = initialLayout;
for (auto& physicalQubitIt : std::ranges::reverse_view(layoutCopy)) {
if (const auto physicalQubitIndex = physicalQubitIt.first;
isIdleQubit(physicalQubitIndex)) {
if (auto it = outputPermutation.find(physicalQubitIndex);
it != outputPermutation.end() && !force) {
continue;
}
const auto logicalQubitIndex = initialLayout.at(physicalQubitIndex);
// check whether the logical qubit is used in the output permutation
auto usedInOutputPermutation = false;
for (const auto& [physical, logical] : outputPermutation) {
if (logical == logicalQubitIndex) {
usedInOutputPermutation = true;
break;
}
}
if (usedInOutputPermutation && !force) {
// cannot strip a logical qubit that is used in the output permutation
continue;
}
removeQubit(logicalQubitIndex);
if (logicalQubitIndex < nqubits + nancillae) {
for (auto& [physical, logical] : initialLayout) {
if (logical > logicalQubitIndex) {
--logical;
}
}
for (auto& [physical, logical] : outputPermutation) {
if (logical > logicalQubitIndex) {
--logical;
}
}
}
}
}
}
QuantumRegister&
QuantumComputation::getQubitRegister(const Qubit physicalQubitIndex) {
for (auto& [_, reg] : quantumRegisters) {
if (reg.contains(physicalQubitIndex)) {
return reg;
}
}
for (auto& [_, reg] : ancillaRegisters) {
if (reg.contains(physicalQubitIndex)) {
return reg;
}
}
throw std::runtime_error("[getQubitRegister] Qubit index " +
std::to_string(physicalQubitIndex) +
" not found in any register");
}
Qubit QuantumComputation::getPhysicalQubitIndex(
const Qubit logicalQubitIndex) const {
for (const auto& [physical, logical] : initialLayout) {
if (logical == logicalQubitIndex) {
return physical;
}
}
throw std::runtime_error("[getPhysicalQubitIndex] Logical qubit index " +
std::to_string(logicalQubitIndex) +
" not found in initial layout");
}
std::ostream&
QuantumComputation::printPermutation(const Permutation& permutation,
std::ostream& os) {
for (const auto& [physical, logical] : permutation) {
os << "\t" << physical << ": " << logical << "\n";
}
return os;
}
Qubit QuantumComputation::getHighestLogicalQubitIndex() const {
return initialLayout.maxValue();
}
Qubit QuantumComputation::getHighestPhysicalQubitIndex() const {
return initialLayout.maxKey();
}
bool QuantumComputation::physicalQubitIsAncillary(
const Qubit physicalQubitIndex) const {
return std::ranges::any_of(ancillaRegisters,
[&physicalQubitIndex](const auto& reg) {
return reg.second.contains(physicalQubitIndex);
});
}
void QuantumComputation::setLogicalQubitAncillary(
const Qubit logicalQubitIndex) {
if (logicalQubitIsAncillary(logicalQubitIndex)) {
return;
}
nqubits--;
nancillae++;
ancillary[logicalQubitIndex] = true;
}
void QuantumComputation::setLogicalQubitsAncillary(
const Qubit minLogicalQubitIndex, const Qubit maxLogicalQubitIndex) {
for (Qubit i = minLogicalQubitIndex; i <= maxLogicalQubitIndex; i++) {
setLogicalQubitAncillary(i);
}
}
void QuantumComputation::setLogicalQubitGarbage(const Qubit logicalQubitIndex) {
garbage[logicalQubitIndex] = true;
// setting a logical qubit garbage also means removing it from the output
// permutation if it was present before
for (auto it = outputPermutation.begin(); it != outputPermutation.end();
++it) {
if (it->second == logicalQubitIndex) {
outputPermutation.erase(it);
break;
}
}
}
void QuantumComputation::setLogicalQubitsGarbage(
const Qubit minLogicalQubitIndex, const Qubit maxLogicalQubitIndex) {
for (Qubit i = minLogicalQubitIndex; i <= maxLogicalQubitIndex; i++) {
setLogicalQubitGarbage(i);
}
}
[[nodiscard]] std::pair<bool, std::optional<Qubit>>
QuantumComputation::containsLogicalQubit(const Qubit logicalQubitIndex) const {
if (const auto it =
std::ranges::find_if(initialLayout,
[&logicalQubitIndex](const auto& mapping) {
return mapping.second == logicalQubitIndex;
});
it != initialLayout.cend()) {
return {true, it->first};
}
return {false, std::nullopt};
}
bool QuantumComputation::isLastOperationOnQubit(
const const_iterator& opIt, const const_iterator& end) const {
if (opIt == end) {
return true;
}
// determine which qubits the gate acts on
std::vector<bool> actson(nqubits + nancillae);
for (std::size_t i = 0; i < actson.size(); ++i) {
if ((*opIt)->actsOn(static_cast<Qubit>(i))) {
actson[i] = true;
}
}
// iterate over remaining gates and check if any act on qubits overlapping
// with the target gate
auto atEnd = opIt;
std::advance(atEnd, 1);
while (atEnd != end) {
for (std::size_t i = 0; i < actson.size(); ++i) {
if (actson[i] && (*atEnd)->actsOn(static_cast<Qubit>(i))) {
return false;
}
}
++atEnd;
}
return true;
}
const QuantumRegister&
QuantumComputation::unifyQuantumRegisters(const std::string& regName) {
ancillaRegisters.clear();
quantumRegisters.clear();
nqubits += nancillae;
nancillae = 0;
quantumRegisters.try_emplace(regName, 0, nqubits, regName);
return quantumRegisters.at(regName);
}
void QuantumComputation::appendMeasurementsAccordingToOutputPermutation(
const std::string& registerName) {
// ensure that the circuit contains enough classical registers
if (classicalRegisters.empty()) {
// in case there are no registers, create a new one
addClassicalRegister(outputPermutation.size(), registerName);
} else if (nclassics < outputPermutation.size()) {
if (classicalRegisters.contains(registerName)) {
throw std::runtime_error(
"[appendMeasurementsAccordingToOutputPermutation] Register " +
registerName + " already exists but is too small");
}
addClassicalRegister(outputPermutation.size() - nclassics, registerName);
}
barrier();
// append measurements according to output permutation
for (const auto& [qubit, clbit] : outputPermutation) {
measure(qubit, clbit);
}
}
void QuantumComputation::checkQubitRange(const Qubit qubit) const {
if (const auto it = initialLayout.find(qubit);
it == initialLayout.end() || it->second >= getNqubits()) {
throw std::out_of_range("Qubit index out of range: " +
std::to_string(qubit));
}
}
void QuantumComputation::checkQubitRange(const Qubit qubit,
const Controls& controls) const {
checkQubitRange(qubit);
for (const auto& [ctrl, _] : controls) {
checkQubitRange(ctrl);
}
}
void QuantumComputation::checkQubitRange(const Qubit qubit0, const Qubit qubit1,
const Controls& controls) const {
checkQubitRange(qubit0, controls);
checkQubitRange(qubit1);
}
void QuantumComputation::checkQubitRange(
const std::vector<Qubit>& qubits) const {
for (const auto& qubit : qubits) {
checkQubitRange(qubit);
}
}
void QuantumComputation::checkBitRange(const Bit bit) const {
if (bit >= nclassics) {
std::stringstream ss{};
ss << "Classical bit index " << bit << " not found in any register";
throw std::runtime_error(ss.str());
}
}
void QuantumComputation::checkBitRange(const std::vector<Bit>& bits) const {
for (const auto& bit : bits) {
checkBitRange(bit);