Commit eae27935 authored by Mccaskey, Alex's avatar Mccaskey, Alex
Browse files

add hadamard_test to standard lib

parent 6bae7628
Loading
Loading
Loading
Loading
+10 −30
Original line number Diff line number Diff line
#include <iomanip>
#include <qcor_hadamard_test>

__qpu__ void x_gate(qreg q) { X(q[1]); }
__qpu__ void h_gate(qreg q) { H(q[1]); }

__qpu__ void htest(qreg q) {
  // Create the superposition on the first qubit
  H(q[0]);

  // create the |1> on the second qubit
  x_gate(q);

  // create superposition on second qubit
  // h_gate(q);

  // apply ctrl-U
  x_gate::ctrl(q[0], q);

  // add the last hadamard
  H(q[0]);

  // measure
  Measure(q[0]);
}
__qpu__ void x_gate(qreg q) { X(q[0]); }
__qpu__ void h_gate(qreg q) { H(q[0]); }

int main() {
  auto q = qalloc(2);
  htest(q);
  q.print();
  auto count1 = q.counts().find("1")->second;
  auto count2 = q.counts().find("0")->second;
  std::cout << "<X> = " << std::setprecision(12)
            << std::fabs((count1 - count2) / (double)(count1 + count2)) << "\n";
  int n_state_qubits = 1;
  auto expectation = qcor::hadamard_test(x_gate, x_gate, n_state_qubits);
  print("<X> = ", expectation);
  
  expectation = qcor::hadamard_test(x_gate, h_gate, n_state_qubits);
  print("<H> = ", expectation);
  return 0;
}
 No newline at end of file
+41 −0
Original line number Diff line number Diff line
#pragma once

#include "qalloc.hpp"

using Unitary = KernelSignature<qreg>;
using StatePrep = KernelSignature<qreg>;

// <U> = <state_prep| U |state_prep>
__qpu__ void __quantum_hadamard_test(qreg q, StatePrep state_prep,
                                     Unitary unitary) {
  auto test_qubit = q.head();
  auto psi = q.extract_range({1, static_cast<std::size_t>(q.size())});

  // Prepare state |psi> on qreg of size n_qubits
  state_prep(psi);

  // Create the superposition on the first qubit
  H(test_qubit);

  // perform ctrl-U
  unitary.ctrl(test_qubit, psi);

  // add the last hadamard
  H(test_qubit);

  // measure
  Measure(test_qubit);
}

namespace qcor {
// Compute <U> = <state_prep | unitary | state_prep>
double hadamard_test(StatePrep state_prep, Unitary unitary,
                     int n_state_qubits) {
  auto q = qalloc(n_state_qubits + 1);
  __quantum_hadamard_test(q, state_prep, unitary);
  // Compute <psi|U|psi>
  double count1 = (double)q.counts().find("1")->second;
  double count2 = (double)q.counts().find("0")->second;
  return std::fabs((count1 - count2) / (count1 + count2));
}
}  // namespace qcor

lib/qcor_hadamard_test

0 → 100644
+2 −0
Original line number Diff line number Diff line
#pragma once
#include "impl/hadamard_test.hpp"