forked from cda-tum/mqt-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircuitOptimizer.cpp
1755 lines (1584 loc) · 58.9 KB
/
CircuitOptimizer.cpp
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 "CircuitOptimizer.hpp"
#include "operations/NonUnitaryOperation.hpp"
#include <algorithm>
#include <cassert>
#include <unordered_map>
#include <utility>
#include <vector>
namespace qc {
void CircuitOptimizer::removeIdentities(QuantumComputation& qc) {
// delete the identities from circuit
auto it = qc.ops.begin();
while (it != qc.ops.end()) {
if ((*it)->getType() == I) {
it = qc.ops.erase(it);
} else if ((*it)->isCompoundOperation()) {
auto* compOp = dynamic_cast<qc::CompoundOperation*>((*it).get());
auto cit = compOp->cbegin();
while (cit != compOp->cend()) {
const auto* cop = cit->get();
if (cop->getType() == qc::I) {
cit = compOp->erase(cit);
} else {
++cit;
}
}
if (compOp->empty()) {
it = qc.ops.erase(it);
} else {
if (compOp->size() == 1) {
// CompoundOperation has degraded to single Operation
(*it) = std::move(*(compOp->begin()));
}
++it;
}
} else {
++it;
}
}
}
void CircuitOptimizer::swapReconstruction(QuantumComputation& qc) {
Qubit highestPhysicalQubit = 0;
for (const auto& q : qc.initialLayout) {
highestPhysicalQubit = std::max(q.first, highestPhysicalQubit);
}
auto dag = DAG(highestPhysicalQubit + 1);
for (auto& it : qc.ops) {
if (!it->isStandardOperation()) {
addNonStandardOperationToDag(dag, &it);
continue;
}
// Operation is not a CNOT
if (it->getType() != X || it->getNcontrols() != 1 ||
it->getControls().begin()->type != Control::Type::Pos) {
addToDag(dag, &it);
continue;
}
const Qubit control = it->getControls().begin()->qubit;
const Qubit target = it->getTargets().at(0);
// first operation
if (dag.at(control).empty() || dag.at(target).empty()) {
addToDag(dag, &it);
continue;
}
auto* opC = dag.at(control).back();
auto* opT = dag.at(target).back();
// previous operation is not a CNOT
if ((*opC)->getType() != qc::X || (*opC)->getNcontrols() != 1 ||
(*opC)->getControls().begin()->type != Control::Type::Pos ||
(*opT)->getType() != qc::X || (*opT)->getNcontrols() != 1 ||
(*opT)->getControls().begin()->type != Control::Type::Pos) {
addToDag(dag, &it);
continue;
}
const auto opCcontrol = (*opC)->getControls().begin()->qubit;
const auto opCtarget = (*opC)->getTargets().at(0);
const auto opTcontrol = (*opT)->getControls().begin()->qubit;
const auto opTtarget = (*opT)->getTargets().at(0);
// operation at control and target qubit are not the same
if (opCcontrol != opTcontrol || opCtarget != opTtarget) {
addToDag(dag, &it);
continue;
}
if (control == opCcontrol && target == opCtarget) {
// elimination
dag.at(control).pop_back();
dag.at(target).pop_back();
(*opC)->setGate(I);
(*opC)->clearControls();
it->setGate(I);
it->clearControls();
} else if (control == opCtarget && target == opCcontrol) {
dag.at(control).pop_back();
dag.at(target).pop_back();
// replace with SWAP + CNOT
(*opC)->setGate(SWAP);
if (target > control) {
(*opC)->setTargets({control, target});
} else {
(*opC)->setTargets({target, control});
}
(*opC)->clearControls();
addToDag(dag, opC);
it->setTargets({control});
it->setControls({Control{target}});
addToDag(dag, &it);
} else {
addToDag(dag, &it);
}
}
removeIdentities(qc);
}
DAG CircuitOptimizer::constructDAG(QuantumComputation& qc) {
Qubit highestPhysicalQubit = 0;
for (const auto& q : qc.initialLayout) {
highestPhysicalQubit = std::max(q.first, highestPhysicalQubit);
}
auto dag = DAG(highestPhysicalQubit + 1);
for (auto& it : qc.ops) {
if (!it->isStandardOperation()) {
addNonStandardOperationToDag(dag, &it);
} else {
addToDag(dag, &it);
}
}
return dag;
}
void CircuitOptimizer::addToDag(DAG& dag, std::unique_ptr<Operation>* op) {
for (const auto& control : (*op)->getControls()) {
dag.at(control.qubit).push_back(op);
}
for (const auto& target : (*op)->getTargets()) {
dag.at(target).push_back(op);
}
}
void CircuitOptimizer::addNonStandardOperationToDag(
DAG& dag, std::unique_ptr<Operation>* op) {
const auto& gate = *op;
// compound operations are added "as-is"
if (gate->isCompoundOperation()) {
const auto usedQubits = gate->getUsedQubits();
for (const auto q : usedQubits) {
dag.at(q).push_back(op);
}
} else if (gate->isNonUnitaryOperation()) {
for (const auto& b : gate->getTargets()) {
dag.at(b).push_back(op);
}
} else if (gate->isClassicControlledOperation()) {
auto* cop =
dynamic_cast<ClassicControlledOperation*>(gate.get())->getOperation();
for (const auto& control : cop->getControls()) {
dag.at(control.qubit).push_back(op);
}
for (const auto& target : cop->getTargets()) {
dag.at(target).push_back(op);
}
} else {
throw QFRException("Unexpected operation encountered");
}
}
void CircuitOptimizer::singleQubitGateFusion(QuantumComputation& qc) {
static const std::map<qc::OpType, qc::OpType> INVERSE_MAP = {
{qc::I, qc::I}, {qc::X, qc::X}, {qc::Y, qc::Y},
{qc::Z, qc::Z}, {qc::H, qc::H}, {qc::S, qc::Sdg},
{qc::Sdg, qc::S}, {qc::T, qc::Tdg}, {qc::Tdg, qc::T},
{qc::SX, qc::SXdg}, {qc::SXdg, qc::SX}, {qc::Barrier, qc::Barrier}};
Qubit highestPhysicalQubit = 0;
for (const auto& q : qc.initialLayout) {
highestPhysicalQubit = std::max(q.first, highestPhysicalQubit);
}
auto dag = DAG(highestPhysicalQubit + 1);
for (auto& it : qc.ops) {
if (!it->isStandardOperation()) {
addNonStandardOperationToDag(dag, &it);
continue;
}
// not a single qubit operation TODO: multiple targets could also be
// considered here
if (!it->getControls().empty() || it->getTargets().size() > 1) {
addToDag(dag, &it);
continue;
}
const auto target = it->getTargets().at(0);
// first operation
if (dag.at(target).empty()) {
addToDag(dag, &it);
continue;
}
auto dagQubit = dag.at(target);
auto* op = dagQubit.back();
// no single qubit op to fuse with operation
if (!(*op)->isCompoundOperation() &&
(!(*op)->getControls().empty() || (*op)->getTargets().size() > 1)) {
addToDag(dag, &it);
continue;
}
// compound operation
if ((*op)->isCompoundOperation()) {
auto* compop = dynamic_cast<CompoundOperation*>(op->get());
// check if compound operation contains non-single-qubit gates
std::size_t involvedQubits = 0;
for (std::size_t q = 0; q < dag.size(); ++q) {
if (compop->actsOn(static_cast<Qubit>(q))) {
++involvedQubits;
}
}
if (involvedQubits > 1) {
addToDag(dag, &it);
continue;
}
// check if the compound operation is empty (e.g., -X-H-H-X-Z-)
if (compop->empty()) {
compop->emplace_back(it->clone());
it->setGate(I);
continue;
}
// check if inverse
auto lastop = (--(compop->end()));
auto inverseIt = INVERSE_MAP.find((*lastop)->getType());
// check if current operation is the inverse of the previous operation
if (inverseIt != INVERSE_MAP.end() &&
it->getType() == inverseIt->second) {
compop->pop_back();
it->setGate(qc::I);
} else {
compop->emplace_back<StandardOperation>(
it->getTargets().at(0), it->getType(), it->getParameter());
it->setGate(I);
}
continue;
}
// single qubit op
// check if current operation is the inverse of the previous operation
auto inverseIt = INVERSE_MAP.find((*op)->getType());
if (inverseIt != INVERSE_MAP.end() && it->getType() == inverseIt->second) {
(*op)->setGate(qc::I);
it->setGate(qc::I);
} else {
auto compop = std::make_unique<CompoundOperation>();
compop->emplace_back<StandardOperation>(
(*op)->getTargets().at(0), (*op)->getType(), (*op)->getParameter());
compop->emplace_back<StandardOperation>(
it->getTargets().at(0), it->getType(), it->getParameter());
it->setGate(I);
(*op) = std::move(compop);
dag.at(target).push_back(op);
}
}
removeIdentities(qc);
}
bool removeDiagonalGate(DAG& dag, DAGReverseIterators& dagIterators, Qubit idx,
DAGReverseIterator& it, qc::Operation* op);
void removeDiagonalGatesBeforeMeasureRecursive(
DAG& dag, DAGReverseIterators& dagIterators, Qubit idx,
const qc::Operation* until) {
// qubit is finished -> consider next qubit
if (dagIterators.at(idx) == dag.at(idx).rend()) {
if (idx < static_cast<Qubit>(dag.size() - 1)) {
removeDiagonalGatesBeforeMeasureRecursive(dag, dagIterators, idx + 1,
nullptr);
}
return;
}
// check if desired operation was reached
if (until != nullptr) {
if ((*dagIterators.at(idx))->get() == until) {
return;
}
}
auto& it = dagIterators.at(idx);
while (it != dag.at(idx).rend()) {
// check if desired operation was reached
if (until != nullptr) {
if ((*dagIterators.at(idx))->get() == until) {
break;
}
}
auto* op = (*it)->get();
if (op->isStandardOperation()) {
// try removing gate and upon success increase all corresponding iterators
auto onlyDiagonalGates =
removeDiagonalGate(dag, dagIterators, idx, it, op);
if (onlyDiagonalGates) {
for (const auto& control : op->getControls()) {
++(dagIterators.at(control.qubit));
}
for (const auto& target : op->getTargets()) {
++(dagIterators.at(target));
}
}
} else if (op->isCompoundOperation()) {
// iterate over all gates of compound operation and upon success increase
// all corresponding iterators
auto* compOp = dynamic_cast<qc::CompoundOperation*>(op);
bool onlyDiagonalGates = true;
auto cit = compOp->rbegin();
while (cit != compOp->rend()) {
auto* cop = (*cit).get();
onlyDiagonalGates = removeDiagonalGate(dag, dagIterators, idx, it, cop);
if (!onlyDiagonalGates) {
break;
}
++cit;
}
if (onlyDiagonalGates) {
for (size_t q = 0; q < dag.size(); ++q) {
if (compOp->actsOn(static_cast<Qubit>(q))) {
++(dagIterators.at(q));
}
}
}
} else if (op->isClassicControlledOperation()) {
// consider the operation that is classically controlled and proceed as
// above
auto* cop = dynamic_cast<ClassicControlledOperation*>(op)->getOperation();
const bool onlyDiagonalGates =
removeDiagonalGate(dag, dagIterators, idx, it, cop);
if (onlyDiagonalGates) {
for (const auto& control : cop->getControls()) {
++(dagIterators.at(control.qubit));
}
for (const auto& target : cop->getTargets()) {
++(dagIterators.at(target));
}
}
} else if (op->isNonUnitaryOperation()) {
// non-unitary operation is not diagonal
it = dag.at(idx).rend();
} else {
throw QFRException("Unexpected operation encountered");
}
}
// qubit is finished -> consider next qubit
if (dagIterators.at(idx) == dag.at(idx).rend() &&
idx < static_cast<Qubit>(dag.size() - 1)) {
removeDiagonalGatesBeforeMeasureRecursive(dag, dagIterators, idx + 1,
nullptr);
}
}
bool removeDiagonalGate(DAG& dag, DAGReverseIterators& dagIterators, Qubit idx,
DAGReverseIterator& it, qc::Operation* op) {
// not a diagonal gate
if (std::find(DIAGONAL_GATES.begin(), DIAGONAL_GATES.end(), op->getType()) ==
DIAGONAL_GATES.end()) {
it = dag.at(idx).rend();
return false;
}
if (op->getNcontrols() != 0) {
// need to check all controls and targets
bool onlyDiagonalGates = true;
for (const auto& control : op->getControls()) {
auto controlQubit = control.qubit;
if (controlQubit == idx) {
continue;
}
if (control.type == Control::Type::Neg) {
dagIterators.at(controlQubit) = dag.at(controlQubit).rend();
onlyDiagonalGates = false;
break;
}
if (dagIterators.at(controlQubit) == dag.at(controlQubit).rend()) {
onlyDiagonalGates = false;
break;
}
// recursive call at control with this operation as goal
removeDiagonalGatesBeforeMeasureRecursive(dag, dagIterators, controlQubit,
(*it)->get());
// check if iteration of control qubit was successful
if (*dagIterators.at(controlQubit) != *it) {
onlyDiagonalGates = false;
break;
}
}
for (const auto& target : op->getTargets()) {
if (target == idx) {
continue;
}
if (dagIterators.at(target) == dag.at(target).rend()) {
onlyDiagonalGates = false;
break;
}
// recursive call at target with this operation as goal
removeDiagonalGatesBeforeMeasureRecursive(dag, dagIterators, target,
(*it)->get());
// check if iteration of target qubit was successful
if (*dagIterators.at(target) != *it) {
onlyDiagonalGates = false;
break;
}
}
if (!onlyDiagonalGates) {
// end qubit
dagIterators.at(idx) = dag.at(idx).rend();
} else {
// set operation to identity so that it can be collected by the
// removeIdentities pass
op->setGate(qc::I);
}
return onlyDiagonalGates;
}
// set operation to identity so that it can be collected by the
// removeIdentities pass
op->setGate(qc::I);
return true;
}
void CircuitOptimizer::removeDiagonalGatesBeforeMeasure(
QuantumComputation& qc) {
auto dag = constructDAG(qc);
// initialize iterators
DAGReverseIterators dagIterators{dag.size()};
for (size_t q = 0; q < dag.size(); ++q) {
if (dag.at(q).empty() ||
dag.at(q).back()->get()->getType() != qc::Measure) {
// qubit is not measured and thus does not have to be considered
dagIterators.at(q) = dag.at(q).rend();
} else {
// point to operation before measurement
dagIterators.at(q) = ++(dag.at(q).rbegin());
}
}
// iterate over DAG in depth-first fashion
removeDiagonalGatesBeforeMeasureRecursive(dag, dagIterators, 0, nullptr);
// remove resulting identities from circuit
removeIdentities(qc);
}
bool removeFinalMeasurement(DAG& dag, DAGReverseIterators& dagIterators,
Qubit idx, DAGReverseIterator& it,
qc::Operation* op);
void removeFinalMeasurementsRecursive(DAG& dag,
DAGReverseIterators& dagIterators,
Qubit idx, const qc::Operation* until) {
if (dagIterators.at(idx) == dag.at(idx).rend()) { // we reached the end
if (idx < static_cast<Qubit>(dag.size() - 1)) {
removeFinalMeasurementsRecursive(dag, dagIterators, idx + 1, nullptr);
}
return;
}
// check if desired operation was reached
if (until != nullptr) {
if ((*dagIterators.at(idx))->get() == until) {
return;
}
}
auto& it = dagIterators.at(idx);
while (it != dag.at(idx).rend()) {
if (until != nullptr) {
if ((*dagIterators.at(idx))->get() == until) {
break;
}
}
auto* op = (*it)->get();
if (op->getType() == Measure || op->getType() == Barrier) {
const bool onlyMeasurement =
removeFinalMeasurement(dag, dagIterators, idx, it, op);
if (onlyMeasurement) {
for (const auto& target : op->getTargets()) {
if (dagIterators.at(target) == dag.at(target).rend()) {
break;
}
++(dagIterators.at(target));
}
}
} else if (op->isCompoundOperation() && op->isNonUnitaryOperation()) {
// iterate over all gates of compound operation and upon success increase
// all corresponding iterators
auto* compOp = dynamic_cast<qc::CompoundOperation*>(op);
bool onlyMeasurement = true;
auto cit = compOp->rbegin();
while (cit != compOp->rend()) {
auto* cop = (*cit).get();
if (cop->getNtargets() > 0 && cop->getTargets()[0] != idx) {
++cit;
continue;
}
onlyMeasurement =
removeFinalMeasurement(dag, dagIterators, idx, it, cop);
if (!onlyMeasurement) {
break;
}
++cit;
}
if (onlyMeasurement) {
++(dagIterators.at(idx));
}
} else {
// not a measurement, we are done
dagIterators.at(idx) = dag.at(idx).rend();
break;
}
}
if (dagIterators.at(idx) == dag.at(idx).rend() &&
idx < static_cast<Qubit>(dag.size() - 1)) {
removeFinalMeasurementsRecursive(dag, dagIterators, idx + 1, nullptr);
}
}
bool removeFinalMeasurement(DAG& dag, DAGReverseIterators& dagIterators,
Qubit idx, DAGReverseIterator& it,
qc::Operation* op) {
if (op->getNtargets() != 0) {
// need to check all targets
bool onlyMeasurements = true;
for (const auto& target : op->getTargets()) {
if (target == idx) {
continue;
}
if (dagIterators.at(target) == dag.at(target).rend()) {
onlyMeasurements = false;
break;
}
// recursive call at target with this operation as goal
removeFinalMeasurementsRecursive(dag, dagIterators, target, (*it)->get());
// check if iteration of target qubit was successful
if (dagIterators.at(target) == dag.at(target).rend() ||
*dagIterators.at(target) != *it) {
onlyMeasurements = false;
break;
}
}
if (!onlyMeasurements) {
// end qubit
dagIterators.at(idx) = dag.at(idx).rend();
} else {
// set operation to identity so that it can be collected by the
// removeIdentities pass
op->setGate(qc::I);
}
return onlyMeasurements;
}
return false;
}
void CircuitOptimizer::removeFinalMeasurements(QuantumComputation& qc) {
auto dag = constructDAG(qc);
DAGReverseIterators dagIterators{dag.size()};
for (size_t q = 0; q < dag.size(); ++q) {
dagIterators.at(q) = (dag.at(q).rbegin());
}
removeFinalMeasurementsRecursive(dag, dagIterators, 0, nullptr);
removeIdentities(qc);
}
void CircuitOptimizer::decomposeSWAP(QuantumComputation& qc,
bool isDirectedArchitecture) {
// decompose SWAPS in three cnot and optionally in four H
auto it = qc.ops.begin();
while (it != qc.ops.end()) {
if ((*it)->isStandardOperation()) {
if ((*it)->getType() == qc::SWAP) {
const auto targets = (*it)->getTargets();
it = qc.ops.erase(it);
it = qc.ops.insert(it, std::make_unique<StandardOperation>(
Control{targets[0]}, targets[1], qc::X));
if (isDirectedArchitecture) {
it = qc.ops.insert(
it, std::make_unique<StandardOperation>(targets[0], qc::H));
it = qc.ops.insert(
it, std::make_unique<StandardOperation>(targets[1], qc::H));
it = qc.ops.insert(it, std::make_unique<StandardOperation>(
Control{targets[0]}, targets[1], qc::X));
it = qc.ops.insert(
it, std::make_unique<StandardOperation>(targets[0], qc::H));
it = qc.ops.insert(
it, std::make_unique<StandardOperation>(targets[1], qc::H));
} else {
it = qc.ops.insert(it, std::make_unique<StandardOperation>(
Control{targets[1]}, targets[0], qc::X));
}
it = qc.ops.insert(it, std::make_unique<StandardOperation>(
Control{targets[0]}, targets[1], qc::X));
} else {
++it;
}
} else if ((*it)->isCompoundOperation()) {
auto* compOp = dynamic_cast<qc::CompoundOperation*>((*it).get());
auto cit = compOp->begin();
while (cit != compOp->end()) {
if ((*cit)->isStandardOperation() && (*cit)->getType() == qc::SWAP) {
const auto targets = (*cit)->getTargets();
cit = compOp->erase(cit);
cit = compOp->insert<StandardOperation>(cit, Control{targets[0]},
targets[1], qc::X);
if (isDirectedArchitecture) {
cit = compOp->insert<StandardOperation>(cit, targets[0], qc::H);
cit = compOp->insert<StandardOperation>(cit, targets[1], qc::H);
cit = compOp->insert<StandardOperation>(cit, Control{targets[0]},
targets[1], qc::X);
cit = compOp->insert<StandardOperation>(cit, targets[0], qc::H);
cit = compOp->insert<StandardOperation>(cit, targets[1], qc::H);
} else {
cit = compOp->insert<StandardOperation>(cit, Control{targets[1]},
targets[0], qc::X);
}
cit = compOp->insert<StandardOperation>(cit, Control{targets[0]},
targets[1], qc::X);
} else {
++cit;
}
}
++it;
} else {
++it;
}
}
}
void CircuitOptimizer::decomposeTeleport(
[[maybe_unused]] QuantumComputation& qc) {}
void changeTargets(Targets& targets,
const std::map<Qubit, Qubit>& replacementMap) {
for (auto& target : targets) {
auto newTargetIt = replacementMap.find(target);
if (newTargetIt != replacementMap.end()) {
target = newTargetIt->second;
}
}
}
void changeControls(Controls& controls,
const std::map<Qubit, Qubit>& replacementMap) {
if (controls.empty() || replacementMap.empty()) {
return;
}
// iterate over the replacement map and see if any control matches
for (const auto& [from, to] : replacementMap) {
auto controlIt = controls.find(from);
if (controlIt != controls.end()) {
const auto controlType = controlIt->type;
controls.erase(controlIt);
controls.insert(Control{to, controlType});
}
}
}
void CircuitOptimizer::eliminateResets(QuantumComputation& qc) {
// ┌───┐┌─┐ ┌───┐┌─┐ ┌───┐┌─┐ ░
// q_0: ┤ H ├┤M├─|0>─┤ H ├┤M├ q_0: ┤ H ├┤M├─░─────────
// └───┘└╥┘ └───┘└╥┘ --> └───┘└╥┘ ░ ┌───┐┌─┐
// c: 2/══════╩════════════╩═ q_1: ──────╫──░─┤ H ├┤M├
// 0 1 ║ ░ └───┘└╥┘
// c: 2/══════╩══════════╩═
// 0 1
auto replacementMap = std::map<Qubit, Qubit>();
auto it = qc.ops.begin();
while (it != qc.ops.end()) {
if ((*it)->getType() == qc::Reset) {
for (const auto& target : (*it)->getTargets()) {
auto indexAddQubit = static_cast<Qubit>(qc.getNqubits());
qc.addQubit(indexAddQubit, indexAddQubit, indexAddQubit);
auto oldReset = replacementMap.find(target);
if (oldReset != replacementMap.end()) {
oldReset->second = indexAddQubit;
} else {
replacementMap.try_emplace(target, indexAddQubit);
}
}
it = qc.erase(it);
} else if (!replacementMap.empty()) {
if ((*it)->isCompoundOperation()) {
auto* compOp = dynamic_cast<qc::CompoundOperation*>((*it).get());
auto compOpIt = compOp->begin();
while (compOpIt != compOp->end()) {
if ((*compOpIt)->getType() == qc::Reset) {
for (const auto& compTarget : (*compOpIt)->getTargets()) {
auto indexAddQubit = static_cast<Qubit>(qc.getNqubits());
qc.addQubit(indexAddQubit, indexAddQubit, indexAddQubit);
auto oldReset = replacementMap.find(compTarget);
if (oldReset != replacementMap.end()) {
oldReset->second = indexAddQubit;
} else {
replacementMap.try_emplace(compTarget, indexAddQubit);
}
}
compOpIt = compOp->erase(compOpIt);
} else {
if ((*compOpIt)->isStandardOperation() ||
(*compOpIt)->isClassicControlledOperation()) {
auto& targets = (*compOpIt)->getTargets();
auto& controls = (*compOpIt)->getControls();
changeTargets(targets, replacementMap);
changeControls(controls, replacementMap);
} else if ((*compOpIt)->isNonUnitaryOperation()) {
auto& targets = (*compOpIt)->getTargets();
changeTargets(targets, replacementMap);
}
compOpIt++;
}
}
}
if ((*it)->isStandardOperation() ||
(*it)->isClassicControlledOperation()) {
auto& targets = (*it)->getTargets();
auto& controls = (*it)->getControls();
changeTargets(targets, replacementMap);
changeControls(controls, replacementMap);
} else if ((*it)->isNonUnitaryOperation()) {
auto& targets = (*it)->getTargets();
changeTargets(targets, replacementMap);
}
it++;
} else {
it++;
}
}
}
void CircuitOptimizer::deferMeasurements(QuantumComputation& qc) {
// ┌───┐┌─┐ ┌───┐ ┌─┐
// q_0: ┤ H ├┤M├─────── q_0: ┤ H ├──■──┤M├
// └───┘└╥┘ ┌───┐ └───┘┌─┴─┐└╥┘
// q_1: ──────╫──┤ X ├─ --> q_1: ─────┤ X ├─╫─
// ║ └─╥─┘ └───┘ ║
// ║ ┌──╨──┐ c: 2/═══════════╩═
// c: 2/══════╩═╡ = 1 ╞ 0
// 0 └─────┘
std::unordered_map<Qubit, std::size_t> qubitsToAddMeasurements{};
auto it = qc.begin();
while (it != qc.end()) {
if (const auto* measurement =
dynamic_cast<qc::NonUnitaryOperation*>(it->get());
measurement != nullptr && measurement->getType() == qc::Measure) {
const auto targets = measurement->getTargets();
const auto classics = measurement->getClassics();
if (targets.size() != 1 && classics.size() != 1) {
throw QFRException(
"Deferring measurements with more than 1 target is not yet "
"supported. Try decomposing your measurements.");
}
// if this is the last operation, nothing has to be done
if (*it == qc.ops.back()) {
break;
}
const auto measurementQubit = targets[0];
const auto measurementBit = classics[0];
// remember q->c for adding measurements later
qubitsToAddMeasurements[measurementQubit] = measurementBit;
// remove the measurement from the vector of operations
it = qc.erase(it);
// starting from the next operation after the measurement (if there is
// any)
auto opIt = it;
auto currentInsertionPoint = it;
// iterate over all subsequent operations
while (opIt != qc.end()) {
const auto* operation = opIt->get();
if (operation->isUnitary()) {
// if an operation does not act on the measured qubit, the insert
// location for potential operations has to be updated
if (!operation->actsOn(measurementQubit)) {
++currentInsertionPoint;
}
++opIt;
continue;
}
if (operation->getType() == qc::Reset) {
throw QFRException(
"Reset encountered in deferMeasurements routine. Please use the "
"eliminateResets method before deferring measurements.");
}
if (const auto* measurement2 =
dynamic_cast<qc::NonUnitaryOperation*>((*opIt).get());
measurement2 != nullptr && operation->getType() == qc::Measure) {
const auto& targets2 = measurement2->getTargets();
const auto& classics2 = measurement2->getClassics();
// if this is the same measurement a breakpoint has been reached
if (targets == targets2 && classics == classics2) {
break;
}
++currentInsertionPoint;
++opIt;
continue;
}
if (const auto* classicOp =
dynamic_cast<qc::ClassicControlledOperation*>((*opIt).get());
classicOp != nullptr) {
const auto& controlRegister = classicOp->getControlRegister();
const auto& expectedValue = classicOp->getExpectedValue();
if (controlRegister.second != 1 && expectedValue <= 1) {
throw QFRException(
"Classic-controlled operations targeted at more than one bit "
"are currently not supported. Try decomposing the operation "
"into individual contributions.");
}
// if this is not the classical bit that is measured, continue
if (controlRegister.first == static_cast<Qubit>(measurementBit)) {
// get the underlying operation
const auto* standardOp =
dynamic_cast<qc::StandardOperation*>(classicOp->getOperation());
if (standardOp == nullptr) {
std::stringstream ss{};
ss << "Underlying operation of classic-controlled operation is "
"not a StandardOperation.\n";
classicOp->print(ss, qc.nqubits);
throw QFRException(ss.str());
}
// get all the necessary information for reconstructing the
// operation
const auto type = standardOp->getType();
const auto targs = standardOp->getTargets();
for (const auto& target : targs) {
if (target == measurementQubit) {
throw qc::QFRException(
"Implicit reset operation in circuit detected. Measuring a "
"qubit and then targeting the same qubit with a "
"classic-controlled operation is not allowed at the "
"moment.");
}
}
// determine the appropriate control to add
auto controls = standardOp->getControls();
const auto controlQubit = measurementQubit;
const auto controlType =
(expectedValue == 1) ? Control::Type::Pos : Control::Type::Neg;
controls.emplace(controlQubit, controlType);
const auto parameters = standardOp->getParameter();
// remove the classic-controlled operation
// carefully handle iterator invalidation.
// if the current insertion point is the same as the current
// iterator the insertion point has to be updated to the new
// operation as well.
auto itInvalidated = (it >= opIt);
const auto insertionPointInvalidated =
(currentInsertionPoint >= opIt);
opIt = qc.erase(opIt);
if (itInvalidated) {
it = opIt;
}
if (insertionPointInvalidated) {
currentInsertionPoint = opIt;
}
itInvalidated = (it >= currentInsertionPoint);
// insert the new operation (invalidated all pointer onwards)
currentInsertionPoint = qc.insert(
currentInsertionPoint, std::make_unique<qc::StandardOperation>(
controls, targs, type, parameters));
if (itInvalidated) {
it = currentInsertionPoint;
}
// advance just after the currently inserted operation
++currentInsertionPoint;
// the inner loop also has to restart from here due to the
// invalidation of the iterators
opIt = currentInsertionPoint;
} else {
if (!operation->actsOn(measurementQubit)) {
++currentInsertionPoint;
}
++opIt;
continue;
}
}
}
}
++it;
}
if (qubitsToAddMeasurements.empty()) {
return;
}
qc.outputPermutation.clear();
for (const auto& [qubit, clbit] : qubitsToAddMeasurements) {
qc.measure(qubit, clbit);
}
qc.initializeIOMapping();
}
bool CircuitOptimizer::isDynamicCircuit(QuantumComputation& qc) {
Qubit highestPhysicalQubit = 0;
for (const auto& q : qc.initialLayout) {
if (q.first > highestPhysicalQubit) {
highestPhysicalQubit = q.first;
}
}
auto dag = DAG(highestPhysicalQubit + 1);
bool hasMeasurements = false;
for (auto& it : qc.ops) {
if (!it->isStandardOperation()) {
if (it->isNonUnitaryOperation()) {
// whenever a reset operation is encountered the circuit has to be
// dynamic
if (it->getType() == Reset) {
return true;
}
// record whether the circuit contains measurements
if (it->getType() == Measure) {
hasMeasurements = true;
}
for (const auto& b : it->getTargets()) {
dag.at(b).push_back(&it);
}
} else if (it->isClassicControlledOperation()) {
// whenever a classic-controlled operation is encountered the circuit
// has to be dynamic
return true;
} else if (it->isCompoundOperation()) {
auto* compOp = dynamic_cast<CompoundOperation*>(it.get());
for (auto& op : *compOp) {
if (op->getType() == Reset || op->isClassicControlledOperation()) {
return true;
}
if (op->getType() == Measure) {
hasMeasurements = true;
}
if (op->isNonUnitaryOperation()) {
for (const auto& b : op->getTargets()) {
dag.at(b).push_back(&op);
}
} else {
addToDag(dag, &op);
}
}
}
} else {
addToDag(dag, &it);
}
}