quantum-algorithms

git clone git://git.codymlewis.com/quantum-algorithms.git
Log | Files | Refs | README

fidelity (1488B)


      1 #!/usr/bin/env python3
      2 
      3 '''
      4 A simple quantum circuit that leads to calculating fidelity
      5 '''
      6 
      7 import argparse
      8 
      9 from qiskit import QuantumCircuit, execute
     10 from qiskit.providers.aer import Aer
     11 
     12 
     13 def add_hadamard(qcircuit, i):
     14     qcircuit.h(i)
     15 
     16 
     17 def to_statevector(a):
     18     '''Convert a binary string into its representative qubit statevector'''
     19     if a == "0":
     20         return [1, 0]
     21     return [0, 1]
     22 
     23 
     24 def create_circuit(in_states):
     25     '''Construct the circuit with the input states set'''
     26     n = len(in_states)
     27     qcircuit = QuantumCircuit(n + 1)
     28     for i in range(n):
     29         qcircuit.initialize(to_statevector(in_states[i]), i)
     30     qcircuit.initialize([1, 0], n)
     31     add_hadamard(qcircuit, n)
     32     qcircuit.cswap(n, 0, 1)
     33     add_hadamard(qcircuit, n)
     34     meas = QuantumCircuit(n + 1, n + 1)
     35     meas.barrier(range(n + 1))
     36     meas.measure(range(n + 1), range(n + 1))
     37     return qcircuit + meas
     38 
     39 
     40 if __name__ == '__main__':
     41     PARSER = argparse.ArgumentParser(
     42         description="A simple quantum circuit that leads to calculating fidelity"
     43     )
     44     PARSER.add_argument(
     45         'in_states', metavar='INPUT_STATES', type=str,
     46         help='Binary string representing the input states of the qubits'
     47     )
     48     ARGS = PARSER.parse_args()
     49     QCIRC = create_circuit(ARGS.in_states)
     50     print("Created circuit:")
     51     print(QCIRC.draw())
     52     BACKEND_SIM = Aer.get_backend('qasm_simulator')
     53     RESULT = execute(QCIRC, BACKEND_SIM).result()
     54     print(f"Result: {RESULT.get_counts()}")