ControlledGateApplicator.cpp 22.3 KB
Newer Older
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
1
2
3
4
5
6
7
8
9
10
11
12
13
/*******************************************************************************
 * Copyright (c) 2019 UT-Battelle, LLC.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompanies this
 * distribution. The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
 *License is available at https://eclipse.org/org/documents/edl-v10.php
 *
 * Contributors:
 *   Thien Nguyen - initial API and implementation
 *******************************************************************************/
#include "ControlledGateApplicator.hpp"
14
#include "xacc_service.hpp"
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
15
16

namespace xacc {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
17
namespace circuits {
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
using QubitT = std::pair<std::string, std::size_t>;

std::vector<std::string> _generate_gray_code(int num_bits) {
  // if num_bits <= 0:
  //     raise ValueError("Cannot generate the gray code for less than 1 bit.")

  std::vector<int> result{0};
  for (int i = 0; i < num_bits; i++) {
    // reverse the vector
    std::vector<int> copy_result = result;
    std::reverse(copy_result.begin(), copy_result.end());

    for (int x : copy_result) {
      result.push_back(x + std::pow(2, i));
    }
  }

  // for (auto r : result) {
  //   std::cout << r << " ";
  // }
  // std::cout << "\n";

  auto int_to_str = [&](int n) -> std::string {
    const int size = sizeof(n) * 8;
    std::string res;
    bool s = 0;
    for (int a = 0; a < size; a++) {
      bool bit = n >> (size - 1);
      if (bit)
        s = 1;
      if (s)
        res.push_back(bit + '0');
      n <<= 1;
    }
    while (res.size() < num_bits) {
      res = '0' + res;
    }
    return res;
  };

  std::vector<std::string> ret;
  for (auto r : result) {
    ret.push_back(int_to_str(r));
    // std::cout << "HI: " << ret.back() << "\n";
  }

  return ret;
}

using QubitT = std::pair<std::string, size_t>;

void _apply_cu(std::shared_ptr<CompositeInstruction> circuit, double theta,
               double phi, double lam, const QubitT &control, QubitT &target) {
  auto provider = xacc::getIRProvider("quantum");

  circuit->addInstruction(provider->createInstruction(
      "U", {control},
      std::vector<xacc::InstructionParameter>{0.0, 0.0, (lam + phi) / 2.}));
  circuit->addInstruction(provider->createInstruction(
      "U", {target},
      std::vector<xacc::InstructionParameter>{0.0, 0.0, (lam - phi) / 2.}));
  circuit->addInstruction(
      provider->createInstruction("CNOT", {control, target}));

  circuit->addInstruction(
      provider->createInstruction("U", {target},
                                  std::vector<xacc::InstructionParameter>{
                                      -theta / 2, 0, -(lam + phi) / 2.}));

  circuit->addInstruction(
      provider->createInstruction("CNOT", {control, target}));
  circuit->addInstruction(provider->createInstruction(
      "U", {target},
      std::vector<xacc::InstructionParameter>{theta / 2., phi, 0.0}));
}

void _apply_mcu_graycode(std::shared_ptr<CompositeInstruction> circuit,
                         double theta, double phi, double lam,
                         const std::vector<QubitT> &ctrl_qubits, QubitT &tgt) {
  auto provider = xacc::getIRProvider("quantum");
  auto zip = [](std::vector<char> first, std::vector<char> second) {
    std::vector<std::pair<char, char>> zipped;
    std::transform(
        first.begin(), first.end(), second.begin(), std::back_inserter(zipped),
        [](const auto &aa, const auto &bb) { return std::make_pair(aa, bb); });
    return zipped;
  };

  auto n = ctrl_qubits.size();
  auto gray_code = _generate_gray_code(n);
  std::string last_pattern = "";

  for (auto pattern : gray_code) {
    if (pattern.find("1") == std::string::npos) {
      continue;
    }

    if (last_pattern.empty()) {
      last_pattern = pattern;
    }

    auto lm_pos = pattern.find_first_of("1");

    std::vector<char> pattern_z(pattern.begin(), pattern.end()),
        last_pattern_z(last_pattern.begin(), last_pattern.end());
    std::vector<bool> comp;
    for (auto [i, j] : zip(pattern_z, last_pattern_z)) {
      comp.push_back(i != j);
    }

    int pos = -1;
    auto true_itr = std::find(comp.begin(), comp.end(), true);
    if (true_itr != comp.end()) {
      pos = comp[std::distance(comp.begin(), true_itr)];
    }

    if (pos != -1) {
      if (pos != lm_pos) {
        circuit->addInstruction(provider->createInstruction(
            "CNOT", {ctrl_qubits[pos], ctrl_qubits[lm_pos]}));
      } else {
        std::vector<int> indices;
        for (int i = 0; i < pattern.size(); i++) {
          if (pattern[i] == '1') {
            indices.push_back(i);
          }
        }
        // start at 1 here bc indices[0] == lm_pos
        for (int idx = 1; idx < indices.size(); idx++) {
          circuit->addInstruction(provider->createInstruction(
              "CNOT", {ctrl_qubits[indices[idx]], ctrl_qubits[lm_pos]}));
        }
      }
    }

    int count = 0;
    for (int i = 0; i < pattern.length(); i++) {
      if (pattern[i] == '1')
        count++;
    }

    if (count % 2 == 0) {
      _apply_cu(circuit, -theta, -lam, -phi, ctrl_qubits[lm_pos], tgt);
    } else {
      _apply_cu(circuit, theta, phi, lam, ctrl_qubits[lm_pos], tgt);
    }
    last_pattern = pattern;
  }
}

std::shared_ptr<CompositeInstruction> __gray_code_mcu_gen(
    std::shared_ptr<CompositeInstruction> u,
    const std::vector<std::pair<std::string, size_t>> &ctrl_qubits) {
  auto inst = u->getInstruction(0);
  auto name = inst->name();
  QubitT target_qubit =
      std::make_pair(inst->getBufferNames()[0], inst->bits()[0]);
  auto n_c = ctrl_qubits.size();
  auto circuit = std::make_shared<Circuit>("__ctrl_circuit__");

  double theta = 0.0, phi = 0.0, lam = 0.0;
  if (name == "Rz" || name == "Z") {
    auto __lam = inst->isParameterized() ? inst->getParameter(0).as<double>()
                                         : constants::pi;
    lam = __lam * (1 / (std::pow(2, n_c - 1)));
  }

  _apply_mcu_graycode(circuit, theta, phi, lam, ctrl_qubits, target_qubit);

  return circuit;
}

template <typename GateType>
std::shared_ptr<GateType>
createGate(std::vector<QubitT> &&args,
           std::vector<InstructionParameter> params = {}) {
  std::vector<std::string> buffer_names;
  std::vector<std::size_t> idxs;

  for (const auto &qb : args) {
    buffer_names.emplace_back(qb.first);
    idxs.emplace_back(qb.second);
  }

  auto i = std::make_shared<GateType>(idxs, params);
  i->setBufferNames(buffer_names);
  return i;
}
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
206

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
207
208
209
210
bool ControlledU::expand(const xacc::HeterogeneousMap &runtimeOptions) {
  // Single control or multiple-controls (as vector of int or qubits)
  if (!runtimeOptions.keyExists<int>("control-idx") &&
      !runtimeOptions.keyExists<std::vector<int>>("control-idx") &&
211
      !runtimeOptions.keyExists<std::pair<std::string, size_t>>(
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
212
          "control-idx") &&
213
      !runtimeOptions.keyExists<std::vector<std::pair<std::string, size_t>>>(
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
214
215
216
217
          "control-idx")) {
    xacc::error("'control-idx' is required.");
    return false;
  }
218

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
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
  if (!runtimeOptions.pointerLikeExists<CompositeInstruction>("U")) {
    xacc::error("'U' composite is required.");
    return false;
  }

  // Original U
  auto uComposite = std::shared_ptr<CompositeInstruction>(
      runtimeOptions.getPointerLike<CompositeInstruction>("U"),
      xacc::empty_delete<CompositeInstruction>());

  const std::vector<std::pair<std::string, size_t>> ctrlIdxs =
      [&runtimeOptions,
       uComposite]() -> std::vector<std::pair<std::string, size_t>> {
    // Try to find the control buffer name:
    const std::string buffer_name = [&]() -> std::string {
      if (runtimeOptions.stringExists("control-buffer")) {
        return runtimeOptions.getString("control-buffer");
      }

      // Use the buffer name of the input Composite:
      if (!uComposite->getBufferNames().empty()) {
        return uComposite->getBufferName(0);
      }
      // No information, just use a generic name
      return "q";
    }();

    if (runtimeOptions.keyExists<int>("control-idx")) {
      return {std::make_pair(
          buffer_name,
          static_cast<size_t>(runtimeOptions.get<int>("control-idx")))};
250
    } else if (runtimeOptions.keyExists<std::vector<int>>("control-idx")) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
251
252
253
254
255
256
      std::vector<std::pair<std::string, size_t>> result;
      for (const auto &qId :
           runtimeOptions.get<std::vector<int>>("control-idx")) {
        result.emplace_back(buffer_name, static_cast<size_t>(qId));
      }
      return result;
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
257
    }
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274

    // Qubit input (as string + int pairs)
    if (runtimeOptions.keyExists<std::pair<std::string, size_t>>(
            "control-idx")) {
      auto qubit =
          runtimeOptions.get<std::pair<std::string, size_t>>("control-idx");
      return {qubit};
    }

    if (runtimeOptions.keyExists<std::vector<std::pair<std::string, size_t>>>(
            "control-idx")) {
      auto qubits =
          runtimeOptions.get<std::vector<std::pair<std::string, size_t>>>(
              "control-idx");
      return qubits;
    }
    return {};
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
275
  }();
276
277
278
279

  if (ctrlIdxs.empty()) {
    xacc::error("Failed to retrieve control bits.");
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
280
281
282
283
  // Check duplicate
  const std::set<std::pair<std::string, size_t>> s(ctrlIdxs.begin(),
                                                   ctrlIdxs.end());
  if (s.size() != ctrlIdxs.size()) {
284
285
286
287
288
    std::stringstream ss;
    for (auto c : ctrlIdxs) {
      ss << c.first << ", " << c.second << "\n";
    }
    xacc::error("Control bits must be unique:\n" + ss.str());
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
289
  }
290

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
291
  auto ctrlU = uComposite;
292

293
  auto should_run_gray_mcu_synth = [ctrlU, &ctrlIdxs]() {
294
295
296
    if (ctrlU->nInstructions() == 1) {
      std::vector<std::string> allowed{"Z"};
      auto inst = ctrlU->getInstruction(0);
297
298
      if (xacc::container::contains(allowed, inst->name()) &&
          ctrlIdxs.size() > 2) {
299
300
301
302
303
304
305
306
        return true;
      }
    }
    return false;
  };

  if (should_run_gray_mcu_synth()) {
    ctrlU = __gray_code_mcu_gen(ctrlU, ctrlIdxs);
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
    std::vector<int> zero_rotation_idxs;
    for (int i = 0; i < ctrlU->nInstructions(); i++) {
      auto inst = ctrlU->getInstruction(i);
      if (inst->name() == "U") {
        auto p0 = inst->getParameter(0);
        auto p1 = inst->getParameter(1);
        auto p2 = inst->getParameter(2);
        if (p0.isNumeric() && p1.isNumeric() && p2.isNumeric()) {
          if (std::fabs(xacc::InstructionParameterToDouble(p0)) < 1e-12 &&
              std::fabs(xacc::InstructionParameterToDouble(p1)) < 1e-12 &&
              std::fabs(xacc::InstructionParameterToDouble(p2)) < 1e-12) {
            // std::cout << "Removing " << inst->toString() << "\n";
            // inst->disable();
            zero_rotation_idxs.push_back(i);
          }
        }
      }
    }

    for (auto iter = zero_rotation_idxs.rbegin();
         iter != zero_rotation_idxs.rend(); ++iter) {
      ctrlU->removeInstruction(*iter);
    }

331
332
333
334
335
336
  } else {

    // Recursive application of control bits:
    for (const auto &ctrlIdx : ctrlIdxs) {
      ctrlU = applyControl(ctrlU, ctrlIdx);
    }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
337
338
339
340
341
342
343
  }

  for (int instId = 0; instId < ctrlU->nInstructions(); ++instId) {
    auto inst = ctrlU->getInstruction(instId)->clone();
    addInstruction(inst);
  }
  return true;
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
344
345
}

346
347
std::shared_ptr<xacc::CompositeInstruction> ControlledU::applyControl(
    const std::shared_ptr<xacc::CompositeInstruction> &in_program,
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
348
    const std::pair<std::string, size_t> &in_ctrlIdx) {
349
350
351
  std::string qcor_compute_section_key = "__qcor__compute__segment__";
  m_gateProvider = xacc::getService<xacc::IRProvider>("quantum");
  m_composite = m_gateProvider->createComposite(
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
352
353
354
      "CTRL_" + in_program->name() + "_" + in_ctrlIdx.first +
      std::to_string(in_ctrlIdx.second));
  // Set the current control qubit before visiting...
355
356
357
358
359
360
361
362
363
364
365
366
367
368
  m_ctrlIdx = in_ctrlIdx;
  InstructionIterator it(in_program);
  while (it.hasNext()) {
    auto nextInst = it.next();
    if (nextInst->isEnabled()) {
      auto metadata = nextInst->getMetadata();
      if (metadata.keyExists<bool>(qcor_compute_section_key) &&
          metadata.get<bool>(qcor_compute_section_key)) {
        // Just add the instructino
        m_composite->addInstruction(nextInst);
      } else {
        // Otherwise add the ctrl version of the gate
        nextInst->accept(this);
      }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
369
    }
370
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
371

372
  return m_composite;
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
373
374
}

375
void ControlledU::visit(Hadamard &h) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
376
377
  if (h.bits()[0] == m_ctrlIdx.second &&
      h.getBufferName(0) == m_ctrlIdx.first) {
378
379
    xacc::error("Control bit must be different from target qubit(s).");
  } else {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
380
    const auto targetIdx = std::make_pair(h.getBufferName(0), h.bits()[0]);
381
    // CH
382
    m_composite->addInstruction(createGate<CH>({m_ctrlIdx, targetIdx}));
383
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
384
385
}

386
void ControlledU::visit(X &x) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
387
388
  if (x.bits()[0] == m_ctrlIdx.second &&
      x.getBufferName(0) == m_ctrlIdx.first) {
389
390
    xacc::error("Control bit must be different from target qubit(s).");
  } else {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
391
    const auto targetIdx = std::make_pair(x.getBufferName(0), x.bits()[0]);
392
    // CNOT
393
    m_composite->addInstruction(createGate<CNOT>({m_ctrlIdx, targetIdx}));
394
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
395
396
}

397
void ControlledU::visit(Y &y) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
398
399
  if (y.bits()[0] == m_ctrlIdx.second &&
      y.getBufferName(0) == m_ctrlIdx.first) {
400
401
    xacc::error("Control bit must be different from target qubit(s).");
  } else {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
402
    const auto targetIdx = std::make_pair(y.getBufferName(0), y.bits()[0]);
403
    // CY
404
    m_composite->addInstruction(createGate<CY>({m_ctrlIdx, targetIdx}));
405
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
406
407
}

408
void ControlledU::visit(Z &z) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
409
410
  if (z.bits()[0] == m_ctrlIdx.second &&
      z.getBufferName(0) == m_ctrlIdx.first) {
411
412
    xacc::error("Control bit must be different from target qubit(s).");
  } else {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
413
    const auto targetIdx = std::make_pair(z.getBufferName(0), z.bits()[0]);
414
    // CZ
415
    m_composite->addInstruction(createGate<CZ>({m_ctrlIdx, targetIdx}));
416
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
417
418
}

419
420
421
void ControlledU::visit(CNOT &cnot) {
  // CCNOT gate:
  // We now have two control bits
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
422
  const auto ctrlIdx1 = std::make_pair(cnot.getBufferName(0), cnot.bits()[0]);
423
424
  const auto ctrlIdx2 = m_ctrlIdx;
  // Target qubit
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
425
  const auto targetIdx = std::make_pair(cnot.getBufferName(1), cnot.bits()[1]);
426
427
428
429
430
431
432

  // gate ccx a,b,c (see qelib1.inc)
  // Maps qubit indices:
  const auto a = m_ctrlIdx;
  const auto b = ctrlIdx1;
  const auto c = targetIdx;
  //     h c;
433
434
  m_composite->addInstruction(createGate<Hadamard>({c}));
  // m_composite->addInstruction(m_gateProvider->createInstruction("H", {c}));
435
436

  //     cx b,c; tdg c;
437
438
  m_composite->addInstruction(createGate<CNOT>({b, c}));
  m_composite->addInstruction(createGate<Tdg>({c}));
439
440

  //     cx a,c; t c;
441
442
  m_composite->addInstruction(createGate<CNOT>({a, c}));
  m_composite->addInstruction(createGate<T>({c}));
443
444

  //     cx b,c; tdg c;
445
446
  m_composite->addInstruction(createGate<CNOT>({b, c}));
  m_composite->addInstruction(createGate<Tdg>({c}));
447
448

  //     cx a,c; t b; t c; h c;
449
450
451
452
  m_composite->addInstruction(createGate<CNOT>({a, c}));
  m_composite->addInstruction(createGate<T>({b}));
  m_composite->addInstruction(createGate<T>({c}));
  m_composite->addInstruction(createGate<Hadamard>({c}));
453
454

  //     cx a,b; t a; tdg b;
455
456
457
  m_composite->addInstruction(createGate<CNOT>({a, b}));
  m_composite->addInstruction(createGate<T>({a}));
  m_composite->addInstruction(createGate<Tdg>({b}));
458
459

  //     cx a,b;
460
  m_composite->addInstruction(createGate<CNOT>({a, b}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
461
462
}

463
void ControlledU::visit(Rx &rx) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
464
465
  if (rx.bits()[0] == m_ctrlIdx.second &&
      rx.getBufferName(0) == m_ctrlIdx.first) {
466
467
    xacc::error("Control bit must be different from target qubit(s).");
  } else {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
468
469
    const auto targetIdx = std::make_pair(rx.getBufferName(0), rx.bits()[0]);
    ;
470
471
    const auto angle = InstructionParameterToDouble(rx.getParameter(0));
    // Rx(angle) = u3(angle,-pi/2,pi/2)
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
472
473
    auto rxAsU3 = U(targetIdx.second, angle, -M_PI_2, M_PI_2);
    rxAsU3.setBufferNames({targetIdx.first});
474
475
    visit(rxAsU3);
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
476
477
}

478
void ControlledU::visit(Ry &ry) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
479
480
  if (ry.bits()[0] == m_ctrlIdx.second &&
      ry.getBufferName(0) == m_ctrlIdx.first) {
481
482
    xacc::error("Control bit must be different from target qubit(s).");
  } else {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
483
    const auto targetIdx = std::make_pair(ry.getBufferName(0), ry.bits()[0]);
484
485
    const auto angle = InstructionParameterToDouble(ry.getParameter(0));
    //  Ry(theta)  ==  u3(theta,0,0)
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
486
487
    auto ryAsU3 = U(targetIdx.second, angle, 0.0, 0.0);
    ryAsU3.setBufferNames({targetIdx.first});
488
489
    visit(ryAsU3);
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
490
491
}

492
void ControlledU::visit(Rz &rz) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
493
494
  if (rz.bits()[0] == m_ctrlIdx.second &&
      rz.getBufferName(0) == m_ctrlIdx.first) {
495
496
    xacc::error("Control bit must be different from target qubit(s).");
  } else {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
497
    const auto targetIdx = std::make_pair(rz.getBufferName(0), rz.bits()[0]);
498
499
    const auto angle = InstructionParameterToDouble(rz.getParameter(0));
    // CRz
500
501
    m_composite->addInstruction(
        createGate<CRZ>({m_ctrlIdx, targetIdx}, {angle}));
502
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
503
504
}

505
506
void ControlledU::visit(S &s) {
  // Ctrl-S = CPhase(pi/2)
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
507
  const auto targetIdx = std::make_pair(s.getBufferName(0), s.bits()[0]);
508
509
  m_composite->addInstruction(
      createGate<CPhase>({m_ctrlIdx, targetIdx}, {M_PI_2}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
510
511
}

512
513
void ControlledU::visit(Sdg &sdg) {
  // Ctrl-Sdg = CPhase(-pi/2)
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
514
  const auto targetIdx = std::make_pair(sdg.getBufferName(0), sdg.bits()[0]);
515
516
  m_composite->addInstruction(
      createGate<CPhase>({m_ctrlIdx, targetIdx}, {-M_PI_2}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
517
518
}

519
520
void ControlledU::visit(T &t) {
  // Ctrl-T = CPhase(pi/4)
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
521
  const auto targetIdx = std::make_pair(t.getBufferName(0), t.bits()[0]);
522
523
  m_composite->addInstruction(
      createGate<CPhase>({m_ctrlIdx, targetIdx}, {M_PI_4}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
524
525
}

526
527
void ControlledU::visit(Tdg &tdg) {
  // Ctrl-Tdg = CPhase(-pi/4)
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
528
  const auto targetIdx = std::make_pair(tdg.getBufferName(0), tdg.bits()[0]);
529
530
  m_composite->addInstruction(
      createGate<CPhase>({m_ctrlIdx, targetIdx}, {-M_PI_4}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
531
532
}

533
534
535
536
void ControlledU::visit(Swap &s) {
  // Fredkin gate: controlled-swap
  // Decompose Swap gate into CNOT gates;
  // then re-visit those CNOT gates (becoming CCNOT).
537
538
539
540
  // CX(0, 1) CX (1, 0) CX(0, 1) is a compute-action pattern,
  // we only need to convert the middle CX to CCX:
  const auto qubit1 = std::make_pair(s.getBufferName(0), s.bits()[0]);
  const auto qubit2 = std::make_pair(s.getBufferName(1), s.bits()[1]);
541
  m_composite->addInstruction(createGate<CNOT>({qubit1, qubit2}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
542

543
  // Visit the middle CNOT ==> CCNOT
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
544
545
  CNOT c2(s.bits()[1], s.bits()[0]);
  c2.setBufferNames({s.getBufferName(1), s.getBufferName(0)});
546
  visit(c2);
547
548

  // Add the uncompute CNOT
549
  m_composite->addInstruction(createGate<CNOT>({qubit1, qubit2}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
550
551
}

552
553
554
555
556
557
558
559
560
void ControlledU::visit(U &u) {
  // controlled-U
  // gate cu3(theta, phi, lambda) c, t {
  //   u1((lambda - phi) / 2) t;
  //   cx c, t;
  //   u3(-theta / 2, 0, -(phi + lambda) / 2) t;
  //   cx c, t;
  //   u3(theta / 2, phi, 0) t;
  // }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
561
  const auto targetIdx = std::make_pair(u.getBufferName(0), u.bits()[0]);
562
563
564
565
566
  const double theta = InstructionParameterToDouble(u.getParameter(0));
  const double phi = InstructionParameterToDouble(u.getParameter(1));
  const double lambda = InstructionParameterToDouble(u.getParameter(2));
  m_composite->addInstruction(m_gateProvider->createInstruction(
      "Rz", {targetIdx}, {(lambda - phi) / 2}));
567
  m_composite->addInstruction(createGate<CNOT>({m_ctrlIdx, targetIdx}));
568
  m_composite->addInstruction(
569
570
      createGate<U>({targetIdx}, {-theta / 2, 0.0, -(phi + lambda) / 2}));
  m_composite->addInstruction(createGate<CNOT>({m_ctrlIdx, targetIdx}));
571
  m_composite->addInstruction(
572
      createGate<U>({targetIdx}, {theta / 2, phi, 0.0}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
573
574
}

575
576
void ControlledU::visit(U1 &u1) {
  // cU1 == CPhase
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
577
  const auto targetIdx = std::make_pair(u1.getBufferName(0), u1.bits()[0]);
578
  auto angle = u1.getParameter(0);
579
580
  m_composite->addInstruction(
      createGate<CPhase>({m_ctrlIdx, targetIdx}, {angle}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
581
582
}

583
584
585
void ControlledU::visit(CY &cy) {
  // controlled-Y = Sdg(target) - CX - S(target)
  CNOT c1(cy.bits());
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
586
587
  c1.setBufferNames({cy.getBufferName(0), cy.getBufferName(1)});

588
  Sdg sdg(cy.bits()[1]);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
589
590
  sdg.setBufferNames({cy.getBufferName(1)});

591
  S s(cy.bits()[1]);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
592
593
  s.setBufferNames({cy.getBufferName(1)});

594
595
596
597
  // Revisit these gates: CNOT->CCNOT; S -> CPhase
  visit(sdg);
  visit(c1);
  visit(s);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
598
599
}

600
601
602
void ControlledU::visit(CZ &cz) {
  // CZ = H(target) - CX - H(target)
  CNOT c1(cz.bits());
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
603
604
  c1.setBufferNames({cz.getBufferName(0), cz.getBufferName(1)});

605
  Hadamard h1(cz.bits()[1]);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
606
607
  h1.setBufferNames({cz.getBufferName(1)});

608
  Hadamard h2(cz.bits()[1]);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
609
  h2.setBufferNames({cz.getBufferName(1)});
610
611
612
613
614

  // Revisit these gates: CNOT->CCNOT; H -> CH
  visit(h1);
  visit(c1);
  visit(h2);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
615
616
}

617
618
619
620
void ControlledU::visit(CRZ &crz) {
  const auto theta = InstructionParameterToDouble(crz.getParameter(0));
  // Decompose
  Rz rz1(crz.bits()[1], theta / 2);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
621
622
  rz1.setBufferNames({crz.getBufferName(1)});

623
  CNOT c1(crz.bits());
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
624
625
  c1.setBufferNames({crz.getBufferName(0), crz.getBufferName(1)});

626
  Rz rz2(crz.bits()[1], -theta / 2);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
627
628
  rz2.setBufferNames({crz.getBufferName(1)});

629
  CNOT c2(crz.bits());
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
630
631
  c2.setBufferNames({crz.getBufferName(0), crz.getBufferName(1)});

632
633
634
635
636
  // Revisit:
  visit(rz1);
  visit(c1);
  visit(rz2);
  visit(c2);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
637
638
}

639
640
641
void ControlledU::visit(CH &ch) {
  // controlled-H = Ry(pi/4, target) - CX - Ry(-pi/4, target)
  CNOT c1(ch.bits());
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
642
643
  c1.setBufferNames({ch.getBufferName(0), ch.getBufferName(1)});

644
  Ry ry1(ch.bits()[1], M_PI_4);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
645
646
  ry1.setBufferNames({ch.getBufferName(1)});

647
  Ry ry2(ch.bits()[1], -M_PI_4);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
648
649
  ry2.setBufferNames({ch.getBufferName(1)});

650
651
652
  visit(ry1);
  visit(c1);
  visit(ry2);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
653
654
}

655
656
657
658
659
660
661
662
663
664
void ControlledU::visit(CPhase &cphase) {
  // This is effectively CRz but due to the global phase difference
  // in the matrix definitions of U1 and Rz,
  // CU1 (i.e. CPhase) and CRz are different gates with a relative phase
  // difference. Ref: ccu1(t, ctrl1, ctrl2, target) = cu1(t/2, ctrl1, ctrl2)
  // cx(ctrl2, target)
  // cu1(-t/2, ctrl1, target)
  // cx(ctrl2, target)
  // cu1(t/2, ctrl1, target)

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
665
666
  const auto ctrlIdx1 =
      std::make_pair(cphase.getBufferName(0), cphase.bits()[0]);
667
668
  const auto ctrlIdx2 = m_ctrlIdx;
  // Target qubit
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
669
670
  const auto targetIdx =
      std::make_pair(cphase.getBufferName(1), cphase.bits()[1]);
671
672
673
  // Angle
  const auto angle = InstructionParameterToDouble(cphase.getParameter(0));
  m_composite->addInstruction(
674
675
      createGate<CPhase>({ctrlIdx1, ctrlIdx2}, {angle / 2}));
  m_composite->addInstruction(createGate<CNOT>({ctrlIdx2, targetIdx}));
676
  m_composite->addInstruction(
677
678
679
680
      createGate<CPhase>({ctrlIdx1, targetIdx}, {-angle / 2}));
  m_composite->addInstruction(createGate<CNOT>({ctrlIdx2, targetIdx}));
  m_composite->addInstruction(
      createGate<CPhase>({ctrlIdx1, targetIdx}, {angle / 2}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
681
}
682
683
} // namespace circuits
} // namespace xacc