-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuantumComputation.cpp
More file actions
1069 lines (965 loc) · 32.5 KB
/
QuantumComputation.cpp
File metadata and controls
1069 lines (965 loc) · 32.5 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
#include "QuantumComputation.hpp"
#include <cassert>
namespace qc {
/***
* Public Methods
***/
std::size_t QuantumComputation::getNindividualOps() const {
std::size_t nops = 0;
for (const auto& op : ops) {
if (op->isCompoundOperation()) {
auto&& comp = dynamic_cast<CompoundOperation*>(op.get());
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 (op->isCompoundOperation()) {
const auto* const comp = dynamic_cast<const CompoundOperation*>(op.get());
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::max_element(depths.begin(), depths.end());
}
void QuantumComputation::import(const std::string& filename) {
const std::size_t dot = filename.find_last_of('.');
std::string extension = filename.substr(dot + 1);
std::transform(
extension.begin(), extension.end(), extension.begin(),
[](unsigned char ch) { return static_cast<char>(::tolower(ch)); });
if (extension == "real") {
import(filename, Format::Real);
} else if (extension == "qasm") {
import(filename, Format::OpenQASM);
} else if (extension == "txt") {
import(filename, Format::GRCS);
} else if (extension == "tfc") {
import(filename, Format::TFC);
} else if (extension == "qc") {
import(filename, Format::QC);
} else {
throw QFRException("[import] extension " + extension + " not recognized");
}
}
void QuantumComputation::import(const std::string& filename, Format format) {
const std::size_t slash = filename.find_last_of('/');
const std::size_t dot = filename.find_last_of('.');
name = filename.substr(slash + 1, dot - slash - 1);
auto ifs = std::ifstream(filename);
if (ifs.good()) {
import(ifs, format);
} else {
throw QFRException("[import] Error processing input stream: " + name);
}
}
void QuantumComputation::import(std::istream&& is, Format format) {
// reset circuit before importing
reset();
switch (format) {
case Format::Real:
importReal(is);
break;
case Format::OpenQASM:
updateMaxControls(2);
importOpenQASM(is);
break;
case Format::GRCS:
importGRCS(is);
break;
case Format::TFC:
importTFC(is);
break;
case Format::QC:
importQC(is);
break;
default:
throw QFRException("[import] format not recognized");
}
// initialize the initial layout and output permutation
initializeIOMapping();
}
void QuantumComputation::initializeIOMapping() {
// if no initial layout was found during parsing the identity mapping is
// assumed
if (initialLayout.empty()) {
for (Qubit i = 0; i < nqubits; ++i) {
initialLayout.emplace(i, i);
}
}
// 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 (opIt->getType() == qc::Measure) {
outputPermutationFromMeasurements = true;
auto* op = dynamic_cast<NonUnitaryOperation*>(opIt.get());
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.count(qubitidx) != 0) {
continue;
}
const auto bitidx = *classicIt;
if (outputPermutationFound) {
// output permutation was already set before -> permute existing
// values
const auto current = outputPermutation.at(qubitidx);
if (static_cast<std::size_t>(qubitidx) != bitidx &&
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.find(it->first) == measuredQubits.end()) {
it = outputPermutation.erase(it);
} else {
++it;
}
}
}
const bool buildOutputPermutation = outputPermutation.empty();
for (const auto& [physicalIn, logicalIn] : initialLayout) {
const bool isIdle = isIdleQubit(physicalIn);
// if no output permutation was found, build it from the initial layout
if (buildOutputPermutation && !isIdle) {
outputPermutation.insert({physicalIn, logicalIn});
}
// if the qubit is not an output, mark it as garbage
const bool isOutput =
std::any_of(outputPermutation.begin(), outputPermutation.end(),
[&logicalIn = logicalIn](const auto& p) {
return p.second == logicalIn;
});
if (!isOutput) {
setLogicalQubitGarbage(logicalIn);
}
// if the qubit is an ancillary and idle, mark it as garbage
if (logicalQubitIsAncillary(logicalIn) && isIdle) {
setLogicalQubitGarbage(logicalIn);
}
}
}
void QuantumComputation::addQubitRegister(std::size_t nq,
const std::string& regName) {
if (qregs.count(regName) != 0) {
auto& reg = qregs.at(regName);
if (reg.first + reg.second == nqubits + nancillae) {
reg.second += nq;
} else {
throw QFRException(
"[addQubitRegister] Augmenting existing qubit registers is only "
"supported for the last register in a circuit");
}
} else {
qregs.try_emplace(regName, static_cast<Qubit>(nqubits), nq);
}
assert(nancillae ==
0); // should only reach this point if no ancillae are present
for (std::size_t i = 0; i < nq; ++i) {
auto j = static_cast<Qubit>(nqubits + i);
initialLayout.insert({j, j});
outputPermutation.insert({j, j});
}
nqubits += nq;
for (auto& op : ops) {
op->setNqubits(nqubits + nancillae);
}
ancillary.resize(nqubits + nancillae);
garbage.resize(nqubits + nancillae);
}
void QuantumComputation::addClassicalRegister(std::size_t nc,
const std::string& regName) {
if (cregs.count(regName) != 0) {
throw QFRException("[addClassicalRegister] Augmenting existing classical "
"registers is currently not supported");
}
if (nc == 0) {
throw QFRException(
"[addClassicalRegister] New register size must be larger than 0");
}
cregs.try_emplace(regName, nclassics, nc);
nclassics += nc;
}
void QuantumComputation::addAncillaryRegister(std::size_t nq,
const std::string& regName) {
const auto totalqubits = nqubits + nancillae;
if (ancregs.count(regName) != 0) {
auto& reg = ancregs.at(regName);
if (reg.first + reg.second == totalqubits) {
reg.second += nq;
} else {
throw QFRException(
"[addAncillaryRegister] Augmenting existing ancillary registers is "
"only supported for the last register in a circuit");
}
} else {
ancregs.try_emplace(regName, static_cast<Qubit>(totalqubits), nq);
}
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.insert({j, j});
outputPermutation.insert({j, j});
ancillary[j] = true;
}
nancillae += nq;
for (auto& op : ops) {
op->setNqubits(nqubits + nancillae);
}
}
// removes the i-th logical qubit and returns the index j it was assigned to in
// the initial layout i.e., initialLayout[j] = i
std::pair<Qubit, std::optional<Qubit>>
QuantumComputation::removeQubit(const Qubit logicalQubitIndex) {
// Find index of the physical qubit i is assigned to
Qubit physicalQubitIndex = 0;
for (const auto& [physical, logical] : initialLayout) {
if (logical == logicalQubitIndex) {
physicalQubitIndex = physical;
}
}
// get register and register-index of the corresponding qubit
auto reg = getQubitRegisterAndIndex(physicalQubitIndex);
if (physicalQubitIsAncillary(physicalQubitIndex)) {
// first index
if (reg.second == 0) {
// last remaining qubit of register
if (ancregs[reg.first].second == 1) {
// delete register
ancregs.erase(reg.first);
}
// first qubit of register
else {
ancregs[reg.first].first++;
ancregs[reg.first].second--;
}
// last index
} else if (reg.second == ancregs[reg.first].second - 1) {
// reduce count of register
ancregs[reg.first].second--;
} else {
auto ancreg = ancregs.at(reg.first);
auto lowPart = reg.first + "_l";
auto lowIndex = ancreg.first;
auto lowCount = reg.second;
auto highPart = reg.first + "_h";
auto highIndex = ancreg.first + reg.second + 1;
auto highCount = ancreg.second - reg.second - 1;
ancregs.erase(reg.first);
ancregs.try_emplace(lowPart, lowIndex, lowCount);
ancregs.try_emplace(highPart, highIndex, highCount);
}
// reduce ancilla count
nancillae--;
} else {
if (reg.second == 0) {
// last remaining qubit of register
if (qregs[reg.first].second == 1) {
// delete register
qregs.erase(reg.first);
}
// first qubit of register
else {
qregs[reg.first].first++;
qregs[reg.first].second--;
}
// last index
} else if (reg.second == qregs[reg.first].second - 1) {
// reduce count of register
qregs[reg.first].second--;
} else {
auto qreg = qregs.at(reg.first);
auto lowPart = reg.first + "_l";
auto lowIndex = qreg.first;
auto lowCount = reg.second;
auto highPart = reg.first + "_h";
auto highIndex = qreg.first + reg.second + 1;
auto highCount = qreg.second - reg.second - 1;
qregs.erase(reg.first);
qregs.try_emplace(lowPart, lowIndex, lowCount);
qregs.try_emplace(highPart, highIndex, highCount);
}
// reduce qubit count
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 all operations
const auto totalQubits = nqubits + nancillae;
for (auto& op : ops) {
op->setNqubits(totalQubits);
}
// update ancillary and garbage tracking
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 QFRException("[addAncillaryQubit] Attempting to insert physical "
"qubit that is already assigned");
}
bool fusionPossible = false;
for (auto& ancreg : ancregs) {
auto& ancStartIndex = ancreg.second.first;
auto& ancCount = ancreg.second.second;
// 1st case: can append to start of existing register
if (ancStartIndex == physicalQubitIndex + 1) {
ancStartIndex--;
ancCount++;
fusionPossible = true;
break;
}
// 2nd case: can append to end of existing register
if (ancStartIndex + ancCount == physicalQubitIndex) {
ancCount++;
fusionPossible = true;
break;
}
}
if (ancregs.empty()) {
ancregs.try_emplace("anc", physicalQubitIndex, 1);
} else if (!fusionPossible) {
auto newRegName = "anc_" + std::to_string(physicalQubitIndex);
ancregs.try_emplace(newRegName, physicalQubitIndex, 1);
}
// 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.insert(
{physicalQubitIndex, static_cast<Qubit>(logicalQubitIndex)});
// adjust output permutation
if (outputQubitIndex.has_value()) {
outputPermutation.insert({physicalQubitIndex, *outputQubitIndex});
} else {
// if a qubit is not relevant for the output, it is considered garbage
garbage[logicalQubitIndex] = true;
}
// update all operations
for (auto& op : ops) {
op->setNqubits(nqubits + nancillae);
}
}
void QuantumComputation::addQubit(const Qubit logicalQubitIndex,
const Qubit physicalQubitIndex,
const std::optional<Qubit> outputQubitIndex) {
if (initialLayout.count(physicalQubitIndex) > 0 ||
outputPermutation.count(physicalQubitIndex) > 0) {
throw QFRException("[addQubit] Attempting to insert physical qubit that is "
"already assigned");
}
if (logicalQubitIndex > nqubits) {
throw QFRException(
"[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
}
// check if qubit fits in existing register
bool fusionPossible = false;
for (auto& qreg : qregs) {
auto& qStartIndex = qreg.second.first;
auto& qCount = qreg.second.second;
// 1st case: can append to start of existing register
if (qStartIndex == physicalQubitIndex + 1) {
qStartIndex--;
qCount++;
fusionPossible = true;
break;
}
// 2nd case: can append to end of existing register
if (qStartIndex + qCount == physicalQubitIndex) {
if (physicalQubitIndex == nqubits) {
// need to shift ancillaries
for (auto& ancreg : ancregs) {
ancreg.second.first++;
}
}
qCount++;
fusionPossible = true;
break;
}
}
consolidateRegister(qregs);
if (qregs.empty()) {
qregs.try_emplace("q", physicalQubitIndex, 1);
} else if (!fusionPossible) {
auto newRegName = "q_" + std::to_string(physicalQubitIndex);
qregs.try_emplace(newRegName, physicalQubitIndex, 1);
}
// increase qubit count
nqubits++;
// adjust initial layout
initialLayout.insert({physicalQubitIndex, logicalQubitIndex});
if (outputQubitIndex.has_value()) {
// adjust output permutation
outputPermutation.insert({physicalQubitIndex, *outputQubitIndex});
}
const auto totalQubits = nqubits + nancillae;
// update all operations
for (auto& op : ops) {
op->setNqubits(totalQubits);
}
// update ancillary and garbage tracking
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;
}
std::ostream& QuantumComputation::print(std::ostream& os) const {
const auto width =
ops.empty() ? 1 : static_cast<int>(std::log10(ops.size()) + 1.);
if (!ops.empty()) {
os << std::setw(width) << "i"
<< ": \t\t\t";
} else {
os << "i: \t\t\t";
}
for (const auto& [physical, logical] : initialLayout) {
if (ancillary[logical]) {
os << "\033[31m" << logical << "\t\033[0m";
} else {
os << logical << "\t";
}
}
os << std::endl;
size_t i = 0U;
for (const auto& op : ops) {
os << std::setw(width) << ++i << ": \t";
op->print(os, initialLayout);
os << std::endl;
}
if (!ops.empty()) {
os << std::setw(width) << "o"
<< ": \t\t\t";
} else {
os << "o: \t\t\t";
}
for (const auto& physicalQubit : initialLayout) {
auto it = outputPermutation.find(physicalQubit.first);
if (it == outputPermutation.end()) {
if (garbage[physicalQubit.second]) {
os << "\033[31m|\t\033[0m";
} else {
os << "|\t";
}
} else {
os << it->second << "\t";
}
}
os << std::endl;
return os;
}
void QuantumComputation::printBin(std::size_t n, std::stringstream& ss) {
if (n > 1) {
printBin(n / 2, ss);
}
ss << n % 2;
}
std::ostream& QuantumComputation::printStatistics(std::ostream& os) const {
os << "QC Statistics:\n";
os << "\tn: " << static_cast<std::size_t>(nqubits) << std::endl;
os << "\tanc: " << static_cast<std::size_t>(nancillae) << std::endl;
os << "\tm: " << ops.size() << std::endl;
os << "--------------" << std::endl;
return os;
}
void QuantumComputation::dump(const std::string& filename) {
const std::size_t dot = filename.find_last_of('.');
std::string extension = filename.substr(dot + 1);
std::transform(
extension.begin(), extension.end(), extension.begin(),
[](unsigned char c) { return static_cast<char>(::tolower(c)); });
if (extension == "real") {
dump(filename, Format::Real);
} else if (extension == "qasm") {
dump(filename, Format::OpenQASM);
} else if (extension == "qc") {
dump(filename, Format::QC);
} else if (extension == "tfc") {
dump(filename, Format::TFC);
} else if (extension == "tensor") {
dump(filename, Format::Tensor);
} else {
throw QFRException("[dump] Extension " + extension +
" not recognized/supported for dumping.");
}
}
void QuantumComputation::dumpOpenQASM(std::ostream& of) {
// Add missing physical qubits
if (!qregs.empty()) {
for (Qubit physicalQubit = 0; physicalQubit < initialLayout.rbegin()->first;
++physicalQubit) {
if (initialLayout.count(physicalQubit) == 0) {
const auto logicalQubit = getHighestLogicalQubitIndex() + 1;
addQubit(logicalQubit, physicalQubit, std::nullopt);
}
}
}
// dump initial layout and output permutation
Permutation inverseInitialLayout{};
for (const auto& q : initialLayout) {
inverseInitialLayout.insert({q.second, q.first});
}
of << "// i";
for (const auto& q : inverseInitialLayout) {
of << " " << static_cast<std::size_t>(q.second);
}
of << std::endl;
Permutation inverseOutputPermutation{};
for (const auto& q : outputPermutation) {
inverseOutputPermutation.insert({q.second, q.first});
}
of << "// o";
for (const auto& q : inverseOutputPermutation) {
of << " " << q.second;
}
of << std::endl;
of << "OPENQASM 2.0;" << std::endl;
of << "include \"qelib1.inc\";" << std::endl;
if (std::any_of(std::begin(ops), std::end(ops), [](const auto& op) {
return op->getType() == OpType::Teleportation;
})) {
of << "opaque teleport src, anc, tgt;" << std::endl;
}
if (!qregs.empty()) {
printSortedRegisters(qregs, "qreg", of);
} else if (nqubits > 0) {
of << "qreg q[" << nqubits << "];" << std::endl;
}
if (!cregs.empty()) {
printSortedRegisters(cregs, "creg", of);
} else if (nclassics > 0) {
of << "creg c[" << nclassics << "];" << std::endl;
}
if (!ancregs.empty()) {
printSortedRegisters(ancregs, "qreg", of);
} else if (nancillae > 0) {
of << "qreg anc[" << nancillae << "];" << std::endl;
}
RegisterNames qregnames{};
RegisterNames cregnames{};
RegisterNames ancregnames{};
createRegisterArray(qregs, qregnames, nqubits, "q");
createRegisterArray(cregs, cregnames, nclassics, "c");
createRegisterArray(ancregs, ancregnames, nancillae, "anc");
for (const auto& ancregname : ancregnames) {
qregnames.push_back(ancregname);
}
for (const auto& op : ops) {
op->dumpOpenQASM(of, qregnames, cregnames);
}
}
void QuantumComputation::dump(const std::string& filename, Format format) {
assert(std::count(filename.begin(), filename.end(), '.') == 1);
auto of = std::ofstream(filename);
if (!of.good()) {
throw QFRException("[dump] Error opening file: " + filename);
}
dump(of, format);
}
void QuantumComputation::dump(std::ostream&& of, Format format) {
switch (format) {
case Format::OpenQASM:
dumpOpenQASM(of);
break;
case Format::Real:
std::cerr << "Dumping in real format currently not supported\n";
break;
case Format::GRCS:
std::cerr << "Dumping in GRCS format currently not supported\n";
break;
case Format::TFC:
std::cerr << "Dumping in TFC format currently not supported\n";
break;
case Format::QC:
std::cerr << "Dumping in QC format currently not supported\n";
break;
default:
throw QFRException("[dump] Format not recognized/supported for dumping.");
}
}
bool QuantumComputation::isIdleQubit(const Qubit physicalQubit) const {
return !std::any_of(
ops.cbegin(), ops.cend(),
[&physicalQubit](const auto& op) { return op->actsOn(physicalQubit); });
}
void QuantumComputation::stripIdleQubits(bool force,
bool reduceIOpermutations) {
auto layoutCopy = initialLayout;
for (auto physicalQubitIt = layoutCopy.rbegin();
physicalQubitIt != layoutCopy.rend(); ++physicalQubitIt) {
auto physicalQubitIndex = physicalQubitIt->first;
if (isIdleQubit(physicalQubitIndex)) {
if (auto it = outputPermutation.find(physicalQubitIndex);
it != outputPermutation.end() && !force) {
continue;
}
auto logicalQubitIndex = initialLayout.at(physicalQubitIndex);
// check whether the logical qubit is used in the output permutation
bool 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 (reduceIOpermutations && (logicalQubitIndex < nqubits + nancillae)) {
for (auto& [physical, logical] : initialLayout) {
if (logical > logicalQubitIndex) {
--logical;
}
}
for (auto& [physical, logical] : outputPermutation) {
if (logical > logicalQubitIndex) {
--logical;
}
}
}
}
}
}
std::string
QuantumComputation::getQubitRegister(const Qubit physicalQubitIndex) const {
for (const auto& reg : qregs) {
auto startIdx = reg.second.first;
auto count = reg.second.second;
if (physicalQubitIndex < startIdx) {
continue;
}
if (physicalQubitIndex >= startIdx + count) {
continue;
}
return reg.first;
}
for (const auto& reg : ancregs) {
auto startIdx = reg.second.first;
auto count = reg.second.second;
if (physicalQubitIndex < startIdx) {
continue;
}
if (physicalQubitIndex >= startIdx + count) {
continue;
}
return reg.first;
}
throw QFRException("[getQubitRegister] Qubit index " +
std::to_string(physicalQubitIndex) +
" not found in any register");
}
std::pair<std::string, Qubit> QuantumComputation::getQubitRegisterAndIndex(
const Qubit physicalQubitIndex) const {
const std::string regName = getQubitRegister(physicalQubitIndex);
Qubit index = 0;
auto it = qregs.find(regName);
if (it != qregs.end()) {
index = physicalQubitIndex - it->second.first;
} else {
auto itAnc = ancregs.find(regName);
if (itAnc != ancregs.end()) {
index = physicalQubitIndex - itAnc->second.first;
}
// no else branch needed here, since error would have already shown in
// getQubitRegister(physicalQubitIndex)
}
return {regName, index};
}
std::string
QuantumComputation::getClassicalRegister(const Bit classicalIndex) const {
for (const auto& reg : cregs) {
auto startIdx = reg.second.first;
auto count = reg.second.second;
if (classicalIndex < startIdx) {
continue;
}
if (classicalIndex >= startIdx + count) {
continue;
}
return reg.first;
}
throw QFRException("[getClassicalRegister] Classical index " +
std::to_string(classicalIndex) +
" not found in any register");
}
std::pair<std::string, Bit> QuantumComputation::getClassicalRegisterAndIndex(
const Bit classicalIndex) const {
const std::string regName = getClassicalRegister(classicalIndex);
std::size_t index = 0;
auto it = cregs.find(regName);
if (it != cregs.end()) {
index = classicalIndex - it->second.first;
} // else branch not needed since getClassicalRegister already covers this
// case
return {regName, index};
}
Qubit QuantumComputation::getIndexFromQubitRegister(
const std::pair<std::string, Qubit>& qubit) const {
// no range check is performed here!
return qregs.at(qubit.first).first + qubit.second;
}
Bit QuantumComputation::getIndexFromClassicalRegister(
const std::pair<std::string, std::size_t>& clbit) const {
// no range check is performed here!
return cregs.at(clbit.first).first + clbit.second;
}
std::ostream&
QuantumComputation::printPermutation(const Permutation& permutation,
std::ostream& os) {
for (const auto& [physical, logical] : permutation) {
os << "\t" << physical << ": " << logical << std::endl;
}
return os;
}
std::ostream& QuantumComputation::printRegisters(std::ostream& os) const {
os << "qregs:";
for (const auto& qreg : qregs) {
os << " {" << qreg.first << ", {" << qreg.second.first << ", "
<< qreg.second.second << "}}";
}
os << std::endl;
if (!ancregs.empty()) {
os << "ancregs:";
for (const auto& ancreg : ancregs) {
os << " {" << ancreg.first << ", {" << ancreg.second.first << ", "
<< ancreg.second.second << "}}";
}
os << std::endl;
}
os << "cregs:";
for (const auto& creg : cregs) {
os << " {" << creg.first << ", {" << creg.second.first << ", "
<< creg.second.second << "}}";
}
os << std::endl;
return os;
}
Qubit QuantumComputation::getHighestLogicalQubitIndex(
const Permutation& permutation) {
Qubit maxIndex = 0;
for (const auto& [physical, logical] : permutation) {
maxIndex = std::max(maxIndex, logical);
}
return maxIndex;
}
bool QuantumComputation::physicalQubitIsAncillary(
const Qubit physicalQubitIndex) const {
return std::any_of(ancregs.cbegin(), ancregs.cend(),
[&physicalQubitIndex](const auto& ancreg) {
return ancreg.second.first <= physicalQubitIndex &&
physicalQubitIndex <
ancreg.second.first + ancreg.second.second;
});
}
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;
}
}
}
[[nodiscard]] std::pair<bool, std::optional<Qubit>>
QuantumComputation::containsLogicalQubit(const Qubit logicalQubitIndex) const {
if (const auto it = std::find_if(initialLayout.cbegin(), initialLayout.cend(),
[&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;
}
void QuantumComputation::unifyQuantumRegisters(const std::string& regName) {
ancregs.clear();
qregs.clear();
qregs[regName] = {0, getNqubits()};
nancillae = 0;
}
void QuantumComputation::appendMeasurementsAccordingToOutputPermutation(
const std::string& registerName) {
// ensure that the circuit contains enough classical registers