def test_run_program(self):
        """Test run.

        If all correct should the data.
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)
        qr = QP_program.get_quantum_register("qname")
        cr = QP_program.get_classical_register("cname")
        qc2 = QP_program.create_circuit("qc2", [qr], [cr])
        qc3 = QP_program.create_circuit("qc3", [qr], [cr])
        qc2.h(qr[0])
        qc2.cx(qr[0], qr[1])
        qc2.cx(qr[0], qr[2])
        qc3.h(qr)
        qc2.measure(qr, cr)
        qc3.measure(qr, cr)
        circuits = ['qc2', 'qc3']
        shots = 1024  # the number of shots in the experiment.
        backend = 'local_qasm_simulator'
        qobj = QP_program.compile(circuits, backend=backend, shots=shots,
                                  seed=88)
        out = QP_program.run(qobj)
        results2 = out.get_counts('qc2')
        results3 = out.get_counts('qc3')
        self.assertEqual(results2, {'000': 518, '111': 506})
        self.assertEqual(results3, {'001': 119, '111': 129, '110': 134,
                                    '100': 117, '000': 129, '101': 126,
                                    '010': 145, '011': 125})
Ejemplo n.º 2
0
def main():
    qp = QuantumProgram()
    #Create 1 qubit
    quantum_r = qp.create_quantum_register("qr",1)
    #Create 1 classical register
    classical_r = qp.create_classical_register("cr",1)
    #Create a circuit
    qp.create_circuit("Circuit", [quantum_r], [classical_r])
    #Get the circuit by name
    circuit = qp.get_circuit('Circuit')
    #enable logging
    qp.enable_logs(logging.DEBUG);
    #pauliX gate
    circuit.x(quantum_r[0])
    #measure gate from qubit 0 to classical bit 0
    circuit.measure(quantum_r[0], classical_r[0])

    #backend simulator
    backend = 'local_qasm_simulator'
    #circuits to execute
    circuits = ['Circuit']
    #Compile the program
    qobj = qp.compile(circuits, backend)
    #run simulator
    result = qp.run(qobj, timeout=240)
    #Show result counts
    print(str(result.get_counts('Circuit')))
Ejemplo n.º 3
0
    def test_run_program_map(self):
        """Test run_program_map.

        If all correct should return 10010.
        """
        QP_program = QuantumProgram()
        QP_program.set_api(API_TOKEN, URL)
        backend = 'local_qasm_simulator'  # the backend to run on
        shots = 100  # the number of shots in the experiment.
        max_credits = 3
        coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]}
        initial_layout = {
            ("q", 0): ("q", 0),
            ("q", 1): ("q", 1),
            ("q", 2): ("q", 2),
            ("q", 3): ("q", 3),
            ("q", 4): ("q", 4)
        }
        QP_program.load_qasm_file(QASM_FILE_PATH_2, name="circuit-dev")
        circuits = ["circuit-dev"]
        qobj = QP_program.compile(circuits,
                                  backend=backend,
                                  shots=shots,
                                  max_credits=max_credits,
                                  seed=65,
                                  coupling_map=coupling_map,
                                  initial_layout=initial_layout)
        result = QP_program.run(qobj)
        self.assertEqual(result.get_counts("circuit-dev"), {'10010': 100})
    def test_compile_coupling_map(self):
        """Test compile_coupling_map.

        If all correct should return data with the same stats. The circuit may
        be different.
        """
        QP_program = QuantumProgram()
        q = QP_program.create_quantum_register("q", 3, verbose=False)
        c = QP_program.create_classical_register("c", 3, verbose=False)
        qc = QP_program.create_circuit("circuitName", [q], [c])
        qc.h(q[0])
        qc.cx(q[0], q[1])
        qc.cx(q[0], q[2])
        qc.measure(q[0], c[0])
        qc.measure(q[1], c[1])
        qc.measure(q[2], c[2])
        backend = 'local_qasm_simulator'  # the backend to run on
        shots = 1024  # the number of shots in the experiment.
        coupling_map = {0: [1], 1: [2]}
        initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1),
                          ("q", 2): ("q", 2)}
        circuits = ["circuitName"]
        qobj = QP_program.compile(circuits, backend=backend, shots=shots,
                                  coupling_map=coupling_map,
                                  initial_layout=initial_layout, seed=88)
        result = QP_program.run(qobj)
        to_check = QP_program.get_qasm("circuitName")
        self.assertEqual(len(to_check), 160)
        self.assertEqual(result.get_counts("circuitName"),
                         {'000': 518, '111': 506})
    def test_compile_coupling_map(self):
        """Test compile_coupling_map.

        If all correct should return data with the same stats. The circuit may
        be different.
        """
        QP_program = QuantumProgram()
        q = QP_program.create_quantum_register("q", 3, verbose=False)
        c = QP_program.create_classical_register("c", 3, verbose=False)
        qc = QP_program.create_circuit("circuitName", [q], [c])
        qc.h(q[0])
        qc.cx(q[0], q[1])
        qc.cx(q[0], q[2])
        qc.measure(q[0], c[0])
        qc.measure(q[1], c[1])
        qc.measure(q[2], c[2])
        backend = 'local_qasm_simulator'  # the backend to run on
        shots = 1024  # the number of shots in the experiment.
        coupling_map = {0: [1], 1: [2]}
        initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1),
                          ("q", 2): ("q", 2)}
        circuits = ["circuitName"]
        qobj = QP_program.compile(circuits, backend=backend, shots=shots,
                                  coupling_map=coupling_map,
                                  initial_layout=initial_layout, seed=88)
        result = QP_program.run(qobj)
        to_check = QP_program.get_qasm("circuitName")
        self.assertEqual(len(to_check), 160)
        self.assertEqual(result.get_counts("circuitName"),
                         {'000': 518, '111': 506})
    def test_run_program(self):
        """Test run.

        If all correct should the data.
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)
        qr = QP_program.get_quantum_register("qname")
        cr = QP_program.get_classical_register("cname")
        qc2 = QP_program.create_circuit("qc2", [qr], [cr])
        qc3 = QP_program.create_circuit("qc3", [qr], [cr])
        qc2.h(qr[0])
        qc2.cx(qr[0], qr[1])
        qc2.cx(qr[0], qr[2])
        qc3.h(qr)
        qc2.measure(qr[0], cr[0])
        qc3.measure(qr[0], cr[0])
        qc2.measure(qr[1], cr[1])
        qc3.measure(qr[1], cr[1])
        qc2.measure(qr[2], cr[2])
        qc3.measure(qr[2], cr[2])
        circuits = ['qc2', 'qc3']
        shots = 1024  # the number of shots in the experiment.
        backend = 'local_qasm_simulator'
        qobj = QP_program.compile(circuits, backend=backend, shots=shots,
                                  seed=88)
        out = QP_program.run(qobj)
        results2 = out.get_counts('qc2')
        results3 = out.get_counts('qc3')
        self.assertEqual(results2, {'000': 518, '111': 506})
        self.assertEqual(results3, {'001': 119, '111': 129, '110': 134,
                                    '100': 117, '000': 129, '101': 126,
                                    '010': 145, '011': 125})
Ejemplo n.º 7
0
def twoBitsAdder():
    Circuit = 'twoBitsAdderCircuit'

    # Create the quantum program
    qp = QuantumProgram()

    # Creating registers
    n_qubits = 8
    qr = qp.create_quantum_register("qr", n_qubits)
    cr = qp.create_classical_register("cr", n_qubits)

    # Two-bits adder circuit, where:
    # qr[0|1] and qr[2|3] are adders
    # qr[4-5] are the result
    # qr[6] is the carry_out
    # qr[7] is the temp reg
    obc = qp.create_circuit(Circuit, [qr], [cr])

    # Prepare bits to add
    obc.h(qr[0])
    obc.h(qr[1])
    obc.h(qr[2])
    obc.h(qr[3])

    # The low-bit result in qr[4]
    obc.cx(qr[0], qr[4])
    obc.cx(qr[2], qr[4])
    # The carry in temp reg
    obc.ccx(qr[0], qr[2], qr[7])

    # The high-bit result in qr[5]
    obc.cx(qr[1], qr[5])
    obc.cx(qr[3], qr[5])
    obc.cx(qr[7], qr[5])

    # The carry_out in qr[6]
    obc.ccx(qr[1], qr[3], qr[6])
    obc.ccx(qr[1], qr[7], qr[6])
    obc.ccx(qr[3], qr[7], qr[6])

    # Measure
    for i in range(0, n_qubits):
        obc.measure(qr[i], cr[i])

    # Get qasm source
    source = qp.get_qasm(Circuit)
    print(source)

    # Compile and run
    backend = 'local_qasm_simulator'
    circuits = [Circuit]  # Group of circuits to execute

    qobj = qp.compile(circuits, backend)  # Compile your program

    result = qp.run(qobj, wait=2, timeout=240)
    print(result)

    results = result.get_counts(Circuit)
    print(results)
    validate(results)
Ejemplo n.º 8
0
Archivo: test.py Proyecto: NickyBar/QIP
    def test_run_program(self):
        QP_program = QuantumProgram(specs=QPS_SPECS)

        qc = QP_program.get_circuit("circuitName")
        qr = QP_program.get_quantum_registers("qname")
        cr = QP_program.get_classical_registers("cname")

        qc2 = QP_program.create_circuit("qc2", ["qname"], ["cname"])
        qc3 = QP_program.create_circuit("qc3", ["qname"], ["cname"])
        qc2.h(qr[0])
        qc3.h(qr[0])
        qc2.measure(qr[0], cr[0])
        qc3.measure(qr[0], cr[0])
        circuits = ['qc2', 'qc3']

        device = 'simulator'  # the device to run on
        shots = 1024  # the number of shots in the experiment.
        credits = 3
        coupling_map = None

        apiconnection = QP_program.set_api(API_TOKEN, URL)
        QP_program.compile(circuits, device, shots, credits, coupling_map)
        result = QP_program.run()
        # print(QP_program())
        print(result)
        # TODO: Revire result
        self.assertEqual(result['status'], 'COMPLETED')
Ejemplo n.º 9
0
    def q_add_one_mod_5(self, n):
        qasm = """
    OPENQASM 2.0;
    include "qelib1.inc";
    
    qreg q[5];
    creg c[3];
    
    // Inputs.
    {}x q[0];
    {}x q[1];
    {}x q[2];
    
    cx q[2],q[3];
    cx q[1],q[4];
    x q[2];
    ccx q[1],q[2],q[4];
    cx q[3],q[1];
    cx q[4],q[0];
    reset q[3];
    reset q[4];
    ccx q[0],q[1],q[3];
    cx q[3],q[1];
    cx q[3],q[0];
    ccx q[2],q[3],q[1];
    cx q[3],q[2];
    reset q[3];
    x q[0];
    x q[1];
    x q[2];
    ccx q[0],q[1],q[3];
    ccx q[2],q[3],q[4];
    x q[0];
    x q[1];
    x q[2];
    reset q[3];
    cx q[4],q[2];
    cx q[4],q[1];
    measure q[0] -> c[2];
    measure q[1] -> c[1];
    measure q[2] -> c[0];
    """
        binary = bin(n)[2:].zfill(3)
        comments = ['' if int(bi) else '//' for bi in binary]
        qasm = qasm.format(*comments)
        qp = QuantumProgram()
        qp.load_qasm_text(qasm, name='circuit')
        qobj = qp.compile(['circuit'])
        result = qp.run(qobj, wait=2, timeout=240)
        counted_result = Counter(result.get_counts('circuit'))
        # Turn binary back to decimal.
        output = int(counted_result.most_common()[0][0], 2)

        return output
Ejemplo n.º 10
0
def oneBitAdder():
    from qiskit import QuantumProgram
    Circuit = 'oneBitAdderCircuit'

    # Create the quantum program
    qp = QuantumProgram()

    # Creating registers
    n_qubits = 4
    qr = qp.create_quantum_register("qr", n_qubits)
    cr = qp.create_classical_register("cr", n_qubits)

    # One-bit adder circuit, where:
    # qr[2] = qr[0] + qr[1]
    # qr[3] = carry
    obc = qp.create_circuit(Circuit, [qr], [cr])

    # Prepare bits to add
    obc.h(qr[0])
    obc.h(qr[1])

    # qr[2] = 1 when qr0/1 has only one 1;
    #       = 0 when qr0/1 are both 0 or 1;
    obc.cx(qr[0], qr[2])
    obc.cx(qr[1], qr[2])

    # qr[3] = 1 when qr0/1 are both 1;
    #       = 0 otherwise;
    obc.ccx(qr[0], qr[1], qr[3])

    # Measure
    for i in range(0, n_qubits):
        obc.measure(qr[i], cr[i])

    # Get qasm source
    source = qp.get_qasm(Circuit)
    print(source)

    # Compile and run
    backend = 'local_qasm_simulator'
    circuits = [Circuit]  # Group of circuits to execute

    qobj = qp.compile(circuits, backend)  # Compile your program

    result = qp.run(qobj, wait=2, timeout=240)
    print(result)

    results = result.get_counts(Circuit)
    print(results)
    validate(results)
Ejemplo n.º 11
0
    def test_teleport(self):
        """test teleportation as in tutorials"""

        self.log.info('test_teleport')
        pi = np.pi
        shots = 1000
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', 3)
        cr0 = qp.create_classical_register('cr0', 1)
        cr1 = qp.create_classical_register('cr1', 1)
        cr2 = qp.create_classical_register('cr2', 1)
        circuit = qp.create_circuit('teleport', [qr], [cr0, cr1, cr2])
        circuit.h(qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.ry(pi / 4, qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.h(qr[0])
        circuit.barrier(qr)
        circuit.measure(qr[0], cr0[0])
        circuit.measure(qr[1], cr1[0])
        circuit.z(qr[2]).c_if(cr0, 1)
        circuit.x(qr[2]).c_if(cr1, 1)
        circuit.measure(qr[2], cr2[0])
        backend = 'local_qasm_simulator'
        qobj = qp.compile('teleport',
                          backend=backend,
                          shots=shots,
                          seed=self.seed)
        results = qp.run(qobj)
        data = results.get_counts('teleport')
        alice = {}
        bob = {}
        alice['00'] = data['0 0 0'] + data['1 0 0']
        alice['01'] = data['0 1 0'] + data['1 1 0']
        alice['10'] = data['0 0 1'] + data['1 0 1']
        alice['11'] = data['0 1 1'] + data['1 1 1']
        bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1']
        bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1']
        self.log.info('test_telport: circuit:')
        self.log.info(circuit.qasm())
        self.log.info('test_teleport: data {0}'.format(data))
        self.log.info('test_teleport: alice {0}'.format(alice))
        self.log.info('test_teleport: bob {0}'.format(bob))
        alice_ratio = 1 / np.tan(pi / 8)**2
        bob_ratio = bob['0'] / float(bob['1'])
        error = abs(alice_ratio - bob_ratio) / alice_ratio
        self.log.info('test_teleport: relative error = {0:.4f}'.format(error))
        self.assertLess(error, 0.05)
Ejemplo n.º 12
0
Archivo: test.py Proyecto: NickyBar/QIP
    def test_new_run(self):
        QP_program = QuantumProgram()

        device = 'local_qasm_simulator'  # the device to run on
        shots = 1  # the number of shots in the experiment.
        credits = 3
        coupling_map = None
        QP_program.load_qasm("circuit-dev", "test.qasm")
        circuits = ["circuit-dev"]

        result = QP_program.compile(circuits, device, shots, credits,
                                    coupling_map)

        result = QP_program.run()

        self.assertEqual(result['status'], 'COMPLETED')
    def test_teleport(self):
        """test teleportation as in tutorials"""

        self.log.info('test_teleport')
        pi = np.pi
        shots = 1000
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', 3)
        cr0 = qp.create_classical_register('cr0', 1)
        cr1 = qp.create_classical_register('cr1', 1)
        cr2 = qp.create_classical_register('cr2', 1)
        circuit = qp.create_circuit('teleport', [qr],
                                    [cr0, cr1, cr2])
        circuit.h(qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.ry(pi/4, qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.h(qr[0])
        circuit.barrier(qr)
        circuit.measure(qr[0], cr0[0])
        circuit.measure(qr[1], cr1[0])
        circuit.z(qr[2]).c_if(cr0, 1)
        circuit.x(qr[2]).c_if(cr1, 1)
        circuit.measure(qr[2], cr2[0])
        backend = 'local_qasm_simulator'
        qobj = qp.compile('teleport', backend=backend, shots=shots,
                   seed=self.seed)
        results = qp.run(qobj)
        data = results.get_counts('teleport')
        alice = {}
        bob = {}
        alice['00'] = data['0 0 0'] + data['1 0 0']
        alice['01'] = data['0 1 0'] + data['1 1 0']
        alice['10'] = data['0 0 1'] + data['1 0 1']
        alice['11'] = data['0 1 1'] + data['1 1 1']
        bob['0'] = data['0 0 0'] + data['0 1 0'] +  data['0 0 1'] + data['0 1 1']
        bob['1'] = data['1 0 0'] + data['1 1 0'] +  data['1 0 1'] + data['1 1 1']
        self.log.info('test_telport: circuit:')
        self.log.info( circuit.qasm() )
        self.log.info('test_teleport: data {0}'.format(data))
        self.log.info('test_teleport: alice {0}'.format(alice))
        self.log.info('test_teleport: bob {0}'.format(bob))
        alice_ratio = 1/np.tan(pi/8)**2
        bob_ratio = bob['0']/float(bob['1'])
        error = abs(alice_ratio - bob_ratio) / alice_ratio
        self.log.info('test_teleport: relative error = {0:.4f}'.format(error))
        self.assertLess(error, 0.05)
Ejemplo n.º 14
0
def QISKit_NOT_Gate(x):
    backend = 'local_qasm_simulator'
    Circuit = 'NOT_GATE'
    qProgram = QuantumProgram()
    qRegister = qProgram.create_quantum_register('q1', 1)
    cRegister = qProgram.create_classical_register('c1', 1)
    qCircuit = qProgram.create_circuit(Circuit, [qRegister], [cRegister])

    if (x == 1):
        qCircuit.x(qRegister[0])
    qCircuit.x(qRegister[0])
    qCircuit.measure(qRegister[0], cRegister[0])

    qobj = qProgram.compile([Circuit], backend=backend)
    result = qProgram.run(qobj, wait=2, timeout=240)
    dic_result = result.get_counts(Circuit)
    max_prob_key = max(dic_result, key=dic_result.get)
    return int(max_prob_key)
    def test_run_program_map(self):
        """Test run_program_map.

        If all correct should return 10010.
        """
        QP_program = QuantumProgram()
        QP_program.set_api(API_TOKEN, URL)
        backend = 'local_qasm_simulator'  # the backend to run on
        shots = 100  # the number of shots in the experiment.
        max_credits = 3
        coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]}
        initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1),
                          ("q", 2): ("q", 2), ("q", 3): ("q", 3),
                          ("q", 4): ("q", 4)}
        QP_program.load_qasm_file(QASM_FILE_PATH_2, name="circuit-dev")
        circuits = ["circuit-dev"]
        qobj = QP_program.compile(circuits, backend=backend, shots=shots,
                                  max_credits=max_credits, seed=65,
                                  coupling_map=coupling_map,
                                  initial_layout=initial_layout)
        result = QP_program.run(qobj)
        self.assertEqual(result.get_counts("circuit-dev"), {'10010': 100})
Ejemplo n.º 16
0
def execute(argv, verbose=False):
    from qiskit import QuantumProgram
    # Create the quantum program
    qp = QuantumProgram()

    # Load from filename
    circuit = qp.load_qasm_file(filename)

    # Get qasm source
    source = qp.get_qasm(circuit)
    if verbose:
        print(source)

    # Compile and run
    backend = 'local_qasm_simulator'
    qobj = qp.compile([circuit], backend)  # Compile your program
    result = qp.run(qobj, wait=2, timeout=240)

    if verbose:
        print(result)

    print(result.get_counts(circuit))
Ejemplo n.º 17
0
def main():	

	# create a  program
	qp = QuantumProgram()
	
	# create 1 qubit
	quantum_r = qp.create_quantum_register("qr", 1)
	
	# create 1 classical register
	classical_r = qp.create_classical_register("cr", 1)
	
	# create a circuit
	circuit = qp.create_circuit("Circuit", [quantum_r], [classical_r])

	# enable logging
	qp.enable_logs(logging.DEBUG);

	# Pauli X gate to qubit 1 in the Quantum Register "qr" 
	circuit.x(quantum_r[0])
	
	# measure gate from qubit 0 to classical bit 0
	circuit.measure(quantum_r[0], classical_r[0])

	# backend simulator
	backend = 'local_qasm_simulator' 

	# Group of circuits to execute
	circuits = ['Circuit']  

	# Compile your program: ASM print(qp.get_qasm('Circuit')), JSON: print(str(qobj))
	qobj = qp.compile(circuits, backend) 
	
	# run in the simulator wait=2,
	result = qp.run(qobj,  timeout=240)
	
	# Show result counts
	print (str(result.get_counts('Circuit')))
Ejemplo n.º 18
0
# Measure all of the qubits in the standard basis
for i in range(5):
    ghz.measure(q[i], c[i])

# Create a Bell state
bell.h(q[0])
bell.cx(q[0], q[1])
bell.barrier()
bell.measure(q[0], c[0])
bell.measure(q[1], c[1])

print(ghz.qasm())
print(bell.qasm())

###############################################################
# Set up the API and execute the program.
###############################################################
result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"])
if not result:
    print("Error setting API")
    sys.exit(1)

qp.compile(["bell"], device='local_qasm_simulator', shots=1024)
qp.compile(["ghz"], device='simulator', shots=1024, coupling_map=coupling_map)

qp.run()

print(qp.get_counts("bell"))  # returns error, don't do this
print(qp.get_counts("bell", device="local_qasm_simulator"))
print(qp.get_counts("ghz"))
Ejemplo n.º 19
0
circuit.ccx(q_register[0], q_register[1], q_register[2])

# XOR gate from Qbit 0 to the Qbit 3
circuit.cx(q_register[0], q_register[3])

# XOR gate from Qbit 1 to the Qbit 3
circuit.cx(q_register[1], q_register[3])

# measure gate from the Qbit 0 to Classical bit 3
circuit.measure(q_register[0], c_register[3])

# measure gate from the Qbit 1 to Classical bit 2
circuit.measure(q_register[1], c_register[2])

# measure gate from the Qbit 2 to Classical bit 1
circuit.measure(q_register[2], c_register[1])

# measure gate from the Qbit 3 to Classical bit 0
circuit.measure(q_register[3], c_register[0])

source = program.get_qasm('circuit')
print(source)

backend = 'local_qasm_simulator'
circuits = ['circuit']

object = program.compile(circuits, backend)

result = program.run(object, wait=2, timeout=240)
print(result)
print(result.get_counts('circuit'))
Ejemplo n.º 20
0
qc.x(a[0])  # Set input a = 0...0001
qc.x(b)   # Set input b = 1...1111
# Apply the adder
qc += adder_subcircuit
# Measure the output register in the computational basis
for j in range(n):
    qc.measure(b[j], ans[j])
qc.measure(cout[0], ans[n])

###############################################################
# Set up the API and execute the program.
###############################################################
qp.set_api(Qconfig.APItoken, Qconfig.config["url"])

# First version: not mapped
result = qp.execute(["rippleadd"], backend=backend,
                    coupling_map=None, shots=1024)
print(result)
print(result.get_counts("rippleadd"))

# Second version: mapped to 2x8 array coupling graph
obj = qp.compile(["rippleadd"], backend=backend,
                 coupling_map=coupling_map, shots=1024)
result = qp.run(obj)

print(result)
print(result.get_ran_qasm("rippleadd"))
print(result.get_counts("rippleadd"))

# Both versions should give the same distribution
Ejemplo n.º 21
0
# Measure the output register in the computational basis
for j in range(n):
    qc.measure(b[j], ans[j])
qc.measure(cout[0], ans[n])

###############################################################
# Set up the API and execute the program.
###############################################################
qp.set_api(Qconfig.APItoken, Qconfig.config["url"])

# First version: not mapped
result = qp.execute(["rippleadd"],
                    backend=backend,
                    coupling_map=None,
                    shots=1024)
print(result)
print(result.get_counts("rippleadd"))

# Second version: mapped to 2x8 array coupling graph
obj = qp.compile(["rippleadd"],
                 backend=backend,
                 coupling_map=coupling_map,
                 shots=1024)
result = qp.run(obj)

print(result)
print(result.get_ran_qasm("rippleadd"))
print(result.get_counts("rippleadd"))

# Both versions should give the same distribution
Ejemplo n.º 22
0
def shorTest():
    # N=15 and a=7
    # Let's find period of f(x) = a^x mod N
    Circuit = 'shorTest'

    # Create the quantum program
    qp = QuantumProgram()

    # Creating registers
    n_qubits = 8
    qr = qp.create_quantum_register("qr", n_qubits)
    cr = qp.create_classical_register("cr", n_qubits)

    # We are going to find Q=2^q, where N^2 <= Q < 2*N^2
    # So the max Q is 450, needing 9 bits?
    
    # Shor algorithm with 4 qbits, where:
    # qr[0-3] are the bits for Q
    # qr[4-7] are the bits for U-gates
    obc = qp.create_circuit(Circuit, [qr], [cr])

    # Prepare bits
    obc.h(qr[0])
    obc.h(qr[1])
    obc.h(qr[2])
    obc.h(qr[3])

    # U0
    # U-a^2^0: multi 7*1
    # Refer to https://github.com/QISKit/ibmqx-user-guides/blob/master/rst/full-user-guide/004-Quantum_Algorithms/110-Shor's_algorithm.rst
    obc.x(qr[4])
    shorU(obc, qr, cr, 0)
    
    # U1
    shorU(obc, qr, cr, 1)
    shorU(obc, qr, cr, 1)

    # U2
    shorU(obc, qr, cr, 2)
    shorU(obc, qr, cr, 2)
    shorU(obc, qr, cr, 2)
    shorU(obc, qr, cr, 2)

    # U3
    shorU(obc, qr, cr, 3)
    shorU(obc, qr, cr, 3)
    shorU(obc, qr, cr, 3)
    shorU(obc, qr, cr, 3)
    shorU(obc, qr, cr, 3)
    shorU(obc, qr, cr, 3)
    shorU(obc, qr, cr, 3)
    shorU(obc, qr, cr, 3)

    # These are here for reference
#    # U-a^2^1: multi 7*7
#    obc.cx(qr[1], qr[5])
#    obc.cx(qr[1], qr[6])
#    obc.cx(qr[1], qr[7])
#    shorU(obc, qr, cr, 1)
#
#    # U-a^2^2: multi 7*4
#    obc.cx(qr[2], qr[5])
#    shorU(obc, qr, cr, 2)
#
#    # U-a^2^3: multi 7*13
#    obc.cx(qr[3], qr[4])
#    obc.cx(qr[3], qr[5])
#    obc.cx(qr[3], qr[7])
#    shorU(obc, qr, cr, 3)

    # Measure all gates
    for i in range(0, 8):
        obc.measure(qr[i], cr[i])

    # Get qasm source
    source = qp.get_qasm(Circuit)
    print(source)

    # Compile and run
    backend = 'local_qasm_simulator'
    circuits = [Circuit]  # Group of circuits to execute

    qobj = qp.compile(circuits, backend, shots = 32)  # Compile your program

    result = qp.run(qobj, wait=2, timeout=240)
    print(result)

    results = result.get_counts(Circuit)
    print(results)
    validate(results)
    def test_example_multiple_compile(self):
        """Test a toy example compiling multiple circuits.

        Pass if the results are correct.
        """
        coupling_map = {0: [1, 2],
                        1: [2],
                        2: [],
                        3: [2, 4],
                        4: [2]}
        QPS_SPECS = {
            "circuits": [{
                "name": "ghz",
                "quantum_registers": [{
                    "name": "q",
                    "size": 5
                }],
                "classical_registers": [{
                    "name": "c",
                    "size": 5}
                ]}, {
                "name": "bell",
                "quantum_registers": [{
                    "name": "q",
                    "size": 5
                }],
                "classical_registers": [{
                    "name": "c",
                    "size": 5
                }]}
            ]
        }
        qp = QuantumProgram(specs=QPS_SPECS)
        ghz = qp.get_circuit("ghz")
        bell = qp.get_circuit("bell")
        q = qp.get_quantum_register("q")
        c = qp.get_classical_register("c")
        # Create a GHZ state
        ghz.h(q[0])
        for i in range(4):
            ghz.cx(q[i], q[i+1])
        # Insert a barrier before measurement
        ghz.barrier()
        # Measure all of the qubits in the standard basis
        for i in range(5):
            ghz.measure(q[i], c[i])
        # Create a Bell state
        bell.h(q[0])
        bell.cx(q[0], q[1])
        bell.barrier()
        bell.measure(q[0], c[0])
        bell.measure(q[1], c[1])
        qp.set_api(API_TOKEN, URL)
        bellobj = qp.compile(["bell"], backend='local_qasm_simulator',
                             shots=2048, seed=10)
        ghzobj = qp.compile(["ghz"], backend='local_qasm_simulator',
                            shots=2048, coupling_map=coupling_map,
                            seed=10)
        bellresult = qp.run(bellobj)
        ghzresult = qp.run(ghzobj)
        print(bellresult.get_counts("bell"))
        print(ghzresult.get_counts("ghz"))
        self.assertEqual(bellresult.get_counts("bell"),
                         {'00000': 1034, '00011': 1014})
        self.assertEqual(ghzresult.get_counts("ghz"),
                         {'00000': 1047, '11111': 1001})
    def test_example_multiple_compile(self):
        """Test a toy example compiling multiple circuits.

        Pass if the results are correct.
        """
        coupling_map = {0: [1, 2],
                        1: [2],
                        2: [],
                        3: [2, 4],
                        4: [2]}
        QPS_SPECS = {
            "circuits": [{
                "name": "ghz",
                "quantum_registers": [{
                    "name": "q",
                    "size": 5
                }],
                "classical_registers": [{
                    "name": "c",
                    "size": 5}
                ]}, {
                "name": "bell",
                "quantum_registers": [{
                    "name": "q",
                    "size": 5
                }],
                "classical_registers": [{
                    "name": "c",
                    "size": 5
                }]}
            ]
        }
        qp = QuantumProgram(specs=QPS_SPECS)
        ghz = qp.get_circuit("ghz")
        bell = qp.get_circuit("bell")
        q = qp.get_quantum_register("q")
        c = qp.get_classical_register("c")
        # Create a GHZ state
        ghz.h(q[0])
        for i in range(4):
            ghz.cx(q[i], q[i+1])
        # Insert a barrier before measurement
        ghz.barrier()
        # Measure all of the qubits in the standard basis
        for i in range(5):
            ghz.measure(q[i], c[i])
        # Create a Bell state
        bell.h(q[0])
        bell.cx(q[0], q[1])
        bell.barrier()
        bell.measure(q[0], c[0])
        bell.measure(q[1], c[1])
        qp.set_api(API_TOKEN, URL)
        bellobj = qp.compile(["bell"], backend='local_qasm_simulator',
                             shots=2048, seed=10)
        ghzobj = qp.compile(["ghz"], backend='local_qasm_simulator',
                            shots=2048, coupling_map=coupling_map,
                            seed=10)
        bellresult = qp.run(bellobj)
        ghzresult = qp.run(ghzobj)
        print(bellresult.get_counts("bell"))
        print(ghzresult.get_counts("ghz"))
        self.assertEqual(bellresult.get_counts("bell"),
                         {'00000': 1034, '00011': 1014})
        self.assertEqual(ghzresult.get_counts("ghz"),
                         {'00000': 1047, '11111': 1001})
Ejemplo n.º 25
0
def evaluate(compiler_function=None, test_circuits=None, verbose=False, backend='local_qiskit_simulator', seed=19):
    """
    Evaluates the given complier_function with the circuits in test_circuits
    and compares the output circuit and quantum state with the original and
    a reference obtained with the qiskit compiler.

    Args:
        compiler_function (function): reference to user compiler function
        test_circuits (dict): named dict of circuits for which the compiler performance is evaluated

            test_circuits: {
                "name": {
                    "qasm": 'qasm_str',
                    "coupling_map": 'target_coupling_map
                }
            }

        verbose (bool): specifies if performance of basic QISKit unroler and mapper circuit is shown for each circuit
        backend (string): backend to use. For Windows Systems you should specify 'local_qasm_simulator' until
                         'local_qiskit_simulator' is available.



    Returns:
        dict
        {
            "name": circuit name
            {
                "optimizer_time": time taken by user compiler,
                "reference_time": reference time taken by qiskit circuit mapper/unroler (if verbose),
                "cost_original":  original circuit cost function value (if verbose),
                "cost_reference": reference circuit cost function value (if verbose),
                "cost_optimized": optimized circuit cost function value,
                "coupling_correct_original": (bool) does original circuit
                                                    satisfy the coupling map (if verbose),
                "coupling_correct_reference": (bool) does circuit produced
                                                    by the qiskit mapper/unroler
                                                    satisfy the coupling map (if verbose),
                "coupling_correct_optimized": (bool) does optimized circuit
                                                    satisfy the coupling map,
                "state_correct_optimized": (bool) does optimized circuit
                                                  return correct state
            }
        }
    """

    # Initial Setup
    basis_gates = 'u1,u2,u3,cx,id'  # or use "U,CX?"
    gate_costs = {'id': 0, 'u1': 0, 'measure': 0, 'reset': 0, 'barrier': 0,
                  'u2': 1, 'u3': 1, 'U': 1,
                  'cx': 10, 'CX': 10,
                  'seed': seed}  # pass the seed through gate costs

    # Results data structure
    results = {}

    fileJSONExists = False
    # paler json
    if os.path.isfile("run_once_results.json"):
        with open("run_once_results.json", "r") as f:
            fileJSONExists = True
            results = json.load(f)
            print("Paler: Loaded JSON")
    # end paler json


    # Load QASM files and extract DAG circuits
    for name, circuit in test_circuits.items():
        print("....name " + name)

        qp = QuantumProgram()
        qp.load_qasm_text(
            circuit["qasm"], name, basis_gates=basis_gates)
        circuit["dag_original"] = qasm_to_dag_circuit(circuit["qasm"], basis_gates=basis_gates)
        test_circuits[name] = circuit

        if not fileJSONExists:
            results[name] = {}  # build empty result dict to be filled later

    # Only return results if a valid compiler function is provided
    if compiler_function is not None:
        # step through all the test circuits using multiprocessing
        compile_jobs = [[name, circuit, 0, compiler_function, gate_costs] for name, circuit in test_circuits.items()]
        with Pool(len(compile_jobs)) as job:
            res_values_opt = job.map(_compile_circuits, compile_jobs)
        # stash the results in the respective dicts
        print("..... [compiled optimised]")

        for job in range(len(compile_jobs)):
            name = res_values_opt[job].pop("name")
            test_circuits[name].update(
                res_values_opt[job].pop("circuit"))  # remove the circuit from the results and store it
            # results[name] = res_values_opt[job]
            results[name].update(res_values_opt[job])
        # do the same for the reference compiler in qiskit if verbose == True
        # paler json
        if verbose and (not fileJSONExists):
            compile_jobs = [[name, circuit, 1, _qiskit_compiler, gate_costs] for name, circuit in
                            test_circuits.items()]
            with Pool(len(compile_jobs)) as job:
                res_values = job.map(_compile_circuits, compile_jobs)
            # also stash this but use update so we don't overwrite anything
            print("..... [compiled reference]")
            for job in range(len(compile_jobs)):
                name = res_values[job].pop("name")
                test_circuits[name].update(
                    res_values[job].pop("circuit"))  # remove the circuit from the results and store it
                results[name].update(res_values[job])

        # determine the final permutation of the qubits
        # this is done by analyzing the measurements on the qubits
        compile_jobs = [[name, circuit, verbose] for name, circuit in test_circuits.items()]
        with Pool(len(compile_jobs)) as job:
            res_values = job.map(_prep_sim, compile_jobs)

        for job in range(len(compile_jobs)):
            name = res_values[job].pop("name")
            test_circuits[name].update(
                res_values[job].pop("circuit"))  # remove the circuit from the results and store it
            results[name].update(res_values[job])

        # Compose qobj for simulation
        config = {
            'data': ['quantum_state'],
        }

        # generate qobj for original circuit
        qobj_original = _compose_qobj("original", test_circuits,
                                      backend=backend,
                                      config=config,
                                      basis_gates=basis_gates,
                                      shots=1,
                                      seed=None)

        # Compute original cost and check original coupling map
        if verbose and (not fileJSONExists):
            for circuit in qobj_original["circuits"]:
                name = circuit["name"]
                coupling_map = test_circuits[name].get("coupling_map", None)
                coupling_map_passes = True
                cost = 0
                for op in circuit["compiled_circuit"]["operations"]:
                    cost += gate_costs.get(op["name"])  # compute cost
                    if op["name"] in ["cx", "CX"] \
                            and coupling_map is not None:  # check coupling map
                        coupling_map_passes &= (
                            op["qubits"][0] in coupling_map)
                        if op["qubits"][0] in coupling_map:
                            coupling_map_passes &= (
                                op["qubits"][1] in coupling_map[op["qubits"][0]]
                            )

                results[name]["cost_original"] = cost
                results[name]["coupling_correct_original"] = coupling_map_passes

        # Run simulation
        if not skipVerif:
            time_start = time.process_time()
            res_original = qp.run(qobj_original, timeout=GLOBAL_TIMEOUT)
            print("..... [executed original]")
            results[name]["sim_time_orig"] = time.process_time() - time_start

        # Generate qobj for optimized circuit
        qobj_optimized = _compose_qobj("optimized", test_circuits,
                                       backend=backend,
                                       config=config,
                                       basis_gates=basis_gates,
                                       shots=1,
                                       seed=None)

        # Compute compiled circuit cost and check coupling map
        for circuit in qobj_optimized["circuits"]:
            name = circuit["name"]
            coupling_map = test_circuits[name].get("coupling_map", None)
            coupling_map_passes = True
            cost = 0
            for op in circuit["compiled_circuit"]["operations"]:
                cost += gate_costs.get(op["name"])  # compute cost
                if op["name"] in ["cx", "CX"] \
                        and coupling_map is not None:  # check coupling map
                    coupling_map_passes &= (
                        op["qubits"][0] in coupling_map)
                    if op["qubits"][0] in coupling_map:
                        coupling_map_passes &= (
                            op["qubits"][1] in coupling_map[op["qubits"][0]]
                        )
            results[name]["cost_optimized"] = cost
            results[name]["coupling_correct_optimized"] = coupling_map_passes

        # Run simulation
        if not skipVerif:
            time_start = time.process_time()
            res_optimized = qp.run(qobj_optimized, timeout=GLOBAL_TIMEOUT)
            results[name]["sim_time_opti"] = time.process_time() - time_start
            print("..... [executed optimised]")

        # paler json
        if verbose and (not fileJSONExists):
            # Generate qobj for reference circuit optimized by qiskit compiler
            qobj_reference = _compose_qobj("reference", test_circuits,
                                           backend=backend,
                                           config=config,
                                           basis_gates=basis_gates,
                                           shots=1,
                                           seed=None)

            # Compute reference cost and check reference coupling map
            for circuit in qobj_reference["circuits"]:
                name = circuit["name"]
                coupling_map = test_circuits[name].get("coupling_map", None)
                coupling_map_passes = True
                cost = 0
                for op in circuit["compiled_circuit"]["operations"]:
                    cost += gate_costs.get(op["name"])  # compute cost
                    if op["name"] in ["cx", "CX"] \
                            and coupling_map is not None:  # check coupling map
                        coupling_map_passes &= (
                            op["qubits"][0] in coupling_map)
                        if op["qubits"][0] in coupling_map:
                            coupling_map_passes &= (
                                op["qubits"][1] in coupling_map[op["qubits"][0]]
                            )
                results[name]["cost_reference"] = cost
                results[name]["coupling_correct_reference"] = coupling_map_passes

                # Skip simulation of reference State to speed things up!
                # time_start = time.process_time()
                # res_reference = qp.run(qobj_reference, timeout=GLOBAL_TIMEOUT)
                # results[name]["sim_time_ref"] = time.process_time() - time_start

        # Check output quantum state of optimized circuit is correct in comparison to original
        for name in results.keys():
            # handle errors here

            if skipVerif:
                results[name]["state_correct_optimized"] = True
                continue

            data_original = res_original.get_data(name)
            if test_circuits[name]["dag_optimized"] is not None:
                data_optimized = res_optimized.get_data(name)
                correct = _compare_outputs(data_original, data_optimized, test_circuits[name]["perm_optimized"])
                # paler transform np.bool_ to bool
                results[name]["state_correct_optimized"] = bool(correct)

                print(name, bool(correct))

                # skip verification
                # results[name]["state_correct_optimized"] = True
            else:
                results[name]["state_correct_optimized"] = False
                # Skip verification of the reference State to speed things up!
                # if verbose:
                #     if test_circuits[name]["dag_reference"] is not None:
                #         data_reference = res_reference.get_data(name)
                #         correct = _compare_outputs(data_original, data_reference, test_circuits[name]["perm_reference"])
                #         results[name]["state_correct_reference"] = correct
                #     else:
                #         results[name]["state_correct_reference"] = False

    # paler json
    with open("run_once_results.json", "w") as f:
        json.dump(results, f)
        print("Paler: Wrote JSON")
    # end paler json

    return results
Ejemplo n.º 26
0
 def run(self, **kwargs):
     if self._qobj is None:
         self.compile()
     self._qresult = QuantumProgram.run(self, self._qobj, **kwargs)
     print(self._qresult)
     return self._qresult
Ejemplo n.º 27
0
if sys.argv[1] == "run":
    backend = "ibmqx5"
    tomo_circuits = tomo.create_tomography_circuits(qp, 'tomo', qr, cr,
                                                    tomo_set)
    qobj = qp.compile(tomo_circuits, backend=backend, shots=1024)

    qasms = split_qobj(qobj, M=1)
    run_splitted_qasms(qasms, qobj, backend)
    sys.exit(0)
elif sys.argv[1] == "simulate":
    tomo_circuits = tomo.create_tomography_circuits(qp, 'tomo', qr, cr,
                                                    tomo_set)
    qobj = qp.compile(tomo_circuits,
                      backend="local_qiskit_simulator",
                      shots=1024)

    res = qp.run(qobj)
else:
    res = recover(sys.argv[1])
    # pprint(res1._result)
    # pprint(res._result)
    # print(res.get_counts("tomo_meas_X(0)X(1)X(2)X(3)"))
tomo_data = tomo.tomography_data(res, "tomo", tomo_set)
rho_fit = tomo.fit_tomography_data(tomo_data)

np.save("state_tomography/rho.npy", rho_fit)
ev = eigvals(rho_fit)

plt.bar(range(len(ev)), ev.real)
plt.show()
Ejemplo n.º 28
0
qCircuit.z(qRegister[0])
qCircuit.cz(qRegister[1], qRegister[2])

# Now, we apply the H-gate to all the qubits again.
for i in range(n):
    qCircuit.h(qRegister[i])

# That's it for this algorithm! Measure the qubits into the classical registers.
# For a constant function, we expect a 100% chance of observing all 0s. (if simulated)
# For a balanced function, we expect anything else.
# This means that when we examine the probability of measuring all 0s, we get 1 for a constant
# function (due to constructive interference) and 0 for a balanced function (destructed interference).
# This is a deterministic algorithm.
# The math behind this algorithm is on IBM's QX Full user guide:
# https://quantumexperience.ng.bluemix.net/qx/tutorial?sectionId=8443c4f713521c10b1a56a533958286b&pageIndex=3
# The biggest resource that helped my understand constructive/destructive interference in the algorithm was this video:
# https://www.youtube.com/watch?v=mGqyzZ-fnnY
# This algorithm can evaluate the function in one call, which is exponentially faster than
# a classical computer's 2^(n-1) + 1.
qCircuit.measure(qRegister[0], cRegister[0])
qCircuit.measure(qRegister[1], cRegister[1])
qCircuit.measure(qRegister[2], cRegister[2])

device = 'ibmqx_qasm_simulator'  # Backend to execute your program, in this case it is the online simulator
circuits = ["qCircuit"]  # Group of circuits to execute
qProgram.compile(circuits, "local_qasm_simulator")  # Compile your program

# Run your program in the device and check the execution result every 2 seconds
result = qProgram.run(wait=2, timeout=240)

print(qProgram.get_counts("qCircuit"))
Ejemplo n.º 29
0
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])

source = qp.get_qasm('Bell')
print(source)

#result = qp.execute('Bell')


circuits = ['Bell']

qobj = qp.compile(circuits, backend)

result = qp.run(qobj, wait=2, timeout=240)


#print(result.get_counts('Bell'))

pprint(qp.available_backends())

#pprint(qp.get_backend_status('ibmqx2'))


pprint(qp.get_backend_configuration('ibmqx5'))




# quantum register for the first circuit
Ejemplo n.º 30
0
for j in range(n):
    qc.measure(b[j], ans[j])
qc.measure(cout[0], ans[n])

###############################################################
# Set up the API and execute the program.
###############################################################
result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"])
if not result:
    print("Error setting API")
    sys.exit(1)

# First version: not compiled
result = qp.execute(["rippleadd"],
                    device=device,
                    coupling_map=None,
                    shots=1024)
print(result)
print(qp.get_counts("rippleadd"))

# Second version: compiled to 2x8 array coupling graph
qp.compile(["rippleadd"], device=device, coupling_map=coupling_map, shots=1024)
# qp.print_execution_list(verbose=True)
result = qp.run()

print(result)
print(qp.get_compiled_qasm("rippleadd"))
print(qp.get_counts("rippleadd"))

# Both versions should give the same distribution
Ejemplo n.º 31
0
class QC():
    '''
    class QC
    '''
    # pylint: disable=too-many-instance-attributes
    def __init__(self, backend='local_qasm_simulator', remote=False, qubits=3):
        # private member
        # __qp
        self.__qp = None

        # calc phase
        self.phase = [
            ['0', 'initialized.']
            ]
        # config
        self.backend = backend
        self.remote = remote
        self.qubits = qubits
        # circuits variable
        self.shots = 2
        # async
        self.wait = False
        self.last = ['init', 'None']

        self.load()

    def load(self, api_info=True):
        '''
        load
        '''
        self.__qp = QuantumProgram()
        if self.remote:
            try:
                import Qconfig
                self.__qp.set_api(Qconfig.APItoken, Qconfig.config["url"],
                                  hub=Qconfig.config["hub"],
                                  group=Qconfig.config["group"],
                                  project=Qconfig.config["project"])

            except ImportError as ex:
                msg = 'Error in loading Qconfig.py!. Error = {}\n'.format(ex)
                sys.stdout.write(msg)
                sys.stdout.flush()
                return False

            if api_info is True:
                api = self.__qp.get_api()
                sys.stdout.write('<IBM Quantum Experience API information>\n')
                sys.stdout.flush()
                sys.stdout.write('Version: {0}\n'.format(api.api_version()))
                sys.stdout.write('User jobs (last 5):\n')
                jobs = api.get_jobs(limit=500)

                def format_date(job_item):
                    '''
                    format
                    '''
                    return datetime.strptime(job_item['creationDate'],
                                             '%Y-%m-%dT%H:%M:%S.%fZ')
                sortedjobs = sorted(jobs,
                                    key=format_date)
                sys.stdout.write('  {0:<32} {1:<24} {2:<9} {3}\n'
                                 .format('id',
                                         'creationDate',
                                         'status',
                                         'backend'))
                sys.stdout.write('{:-^94}\n'.format(""))
                for job in sortedjobs[-5:]:
                    sys.stdout.write('  {0:<32} {1:<24} {2:<9} {3}\n'
                                     .format(job['id'],
                                             job['creationDate'],
                                             job['status'],
                                             job['backend']['name']))
                sys.stdout.write('There are {0} jobs on the server\n'
                                 .format(len(jobs)))
                sys.stdout.write('Credits: {0}\n'
                                 .format(api.get_my_credits()))
                sys.stdout.flush()

        self.backends = self.__qp.available_backends()
        status = self.__qp.get_backend_status(self.backend)

        if 'available' in status:
            if status['available'] is False:
                return False
        return True

    def set_config(self, config=None):
        '''
        set config
        '''
        if config is None:
            config = {}

        if 'backend' in config:
            self.backend = str(config['backend'])
            if 'local_' in self.backend:
                self.remote = False
            else:
                self.remote = True

        if 'remote' in config:
            self.remote = config['remote']

        if 'qubits' in config:
            self.qubits = int(config['qubits'])

        return True

    def _progress(self, phasename, text):
        self.phase.append([str(phasename), str(text)])
        text = "Phase {0}: {1}".format(phasename, text)
        sys.stdout.write("{}\n".format(text))
        sys.stdout.flush()

    def _init_circuit(self):
        self._progress('1', 'Initialize quantum registers and circuit')
        qubits = self.qubits

        quantum_registers = [
            {"name": "cin", "size": 1},
            {"name": "qa", "size": qubits},
            {"name": "qb", "size": qubits},
            {"name": "cout", "size": 1}
            ]

        classical_registers = [
            {"name": "ans", "size": qubits + 1}
            ]

        if 'cin' in self.__qp.get_quantum_register_names():
            self.__qp.destroy_quantum_registers(quantum_registers)
            self.__qp.destroy_classical_registers(classical_registers)

        q_r = self.__qp.create_quantum_registers(quantum_registers)
        c_r = self.__qp.create_classical_registers(classical_registers)

        self.__qp.create_circuit("qcirc", q_r, c_r)

    def _create_circuit_qadd(self):
        # quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184
        def majority(circuit, q_a, q_b, q_c):
            '''
            majority
            '''
            circuit.cx(q_c, q_b)
            circuit.cx(q_c, q_a)
            circuit.ccx(q_a, q_b, q_c)

        def unmaj(circuit, q_a, q_b, q_c):
            '''
            unmajority
            '''
            circuit.ccx(q_a, q_b, q_c)
            circuit.cx(q_c, q_a)
            circuit.cx(q_a, q_b)

        def adder(circuit, c_in, q_a, q_b, c_out, qubits):
            '''
            adder
            '''
            # pylint: disable=too-many-arguments
            majority(circuit, c_in[0], q_b[0], q_a[0])
            for i in range(qubits - 1):
                majority(circuit, q_a[i], q_b[i + 1], q_a[i + 1])

            circuit.cx(q_a[qubits - 1], c_out[0])

            for i in range(qubits - 1)[::-1]:
                unmaj(circuit, q_a[i], q_b[i + 1], q_a[i + 1])
            unmaj(circuit, c_in[0], q_b[0], q_a[0])

        if 'add' not in self.__qp.get_circuit_names():
            [c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register,
                                          ["cin", "qa", "qb", "cout"])
            ans = self.__qp.get_classical_register('ans')
            qadder = self.__qp.create_circuit("qadd",
                                              [c_in, q_a, q_b, c_out],
                                              [ans])
            adder(qadder, c_in, q_a, q_b, c_out, self.qubits)

        return 'add' in self.__qp.get_circuit_names()

    def _create_circuit_qsub(self):
        circuit_names = self.__qp.get_circuit_names()
        if 'qsub' not in circuit_names:
            if 'qadd' not in circuit_names:
                self._create_circuit_qadd()

            # subtractor circuit
            self.__qp.add_circuit('qsub', self.__qp.get_circuit('qadd'))
            qsubtractor = self.__qp.get_circuit('qsub')
            qsubtractor.reverse()
        return 'qsub' in self.__qp.get_circuit_names()

    def _qadd(self, input_a, input_b=None, subtract=False, observe=False):
        # pylint: disable=too-many-locals

        def measure(circuit, q_b, c_out, ans):
            '''
            measure
            '''
            circuit.barrier()
            for i in range(self.qubits):
                circuit.measure(q_b[i], ans[i])
            circuit.measure(c_out[0], ans[self.qubits])

        def char2q(circuit, cbit, qbit):
            '''
            char2q
            '''
            if cbit == '1':
                circuit.x(qbit)
            elif cbit == 'H':
                circuit.h(qbit)
                self.shots = 5 * (2**self.qubits)

        def input_state(circuit, input_a, input_b=None):
            '''
            input state
            '''
            input_a = input_a[::-1]
            for i in range(self.qubits):
                char2q(circuit, input_a[i], q_a[i])

            if input_b is not None:
                input_b = input_b[::-1]
                for i in range(self.qubits):
                    char2q(circuit, input_b[i], q_b[i])

        def reset_input(circuit, c_in, q_a, c_out):
            '''
            reset input
            '''
            circuit.reset(c_in)
            circuit.reset(c_out)
            for i in range(self.qubits):
                circuit.reset(q_a[i])

        # get registers
        [c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register,
                                      ["cin", "qa", "qb", "cout"])
        ans = self.__qp.get_classical_register('ans')
        qcirc = self.__qp.get_circuit('qcirc')

        self._progress('2',
                       'Define input state ({})'
                       .format('QADD' if subtract is False else 'QSUB'))
        if input_b is not None:
            if subtract is True:
                # subtract
                input_state(qcirc, input_b, input_a)
            else:
                # add
                input_state(qcirc, input_a, input_b)
        else:
            reset_input(qcirc, c_in, q_a, c_out)
            input_state(qcirc, input_a)

        self._progress('3',
                       'Define quantum circuit ({})'
                       .format('QADD' if subtract is False else 'QSUB'))
        if subtract is True:
            self._create_circuit_qsub()
            qcirc.extend(self.__qp.get_circuit('qsub'))
        else:
            self._create_circuit_qadd()
            qcirc.extend(self.__qp.get_circuit('qadd'))

        if observe is True:
            measure(qcirc, q_b, c_out, ans)

    def _qsub(self, input_a, input_b=None, observe=False):
        self._qadd(input_a, input_b, subtract=True, observe=observe)

    def _qope(self, input_a, operator, input_b=None, observe=False):
        if operator == '+':
            return self._qadd(input_a, input_b, observe=observe)
        elif operator == '-':
            return self._qsub(input_a, input_b, observe=observe)
        return None

    def _compile(self, name, cross_backend=None, print_qasm=False):
        self._progress('4', 'Compile quantum circuit')

        coupling_map = None
        if cross_backend is not None:
            backend_conf = self.__qp.get_backend_configuration(cross_backend)
            coupling_map = backend_conf.get('coupling_map', None)
            if coupling_map is None:
                sys.stdout.write('backend: {} coupling_map not found'
                                 .format(cross_backend))

        qobj = self.__qp.compile([name],
                                 backend=self.backend,
                                 shots=self.shots,
                                 seed=1,
                                 coupling_map=coupling_map)

        if print_qasm is True:
            sys.stdout.write(self.__qp.get_compiled_qasm(qobj, 'qcirc'))
            sys.stdout.flush()
        return qobj

    def _run(self, qobj):
        self._progress('5', 'Run quantum circuit (wait for answer)')
        result = self.__qp.run(qobj, wait=5, timeout=100000)
        return result

    def _run_async(self, qobj):
        '''
        _run_async
        '''
        self._progress('5', 'Run quantum circuit')
        self.wait = True

        def async_result(result):
            '''
            async call back
            '''
            self.wait = False
            self.last = self.result_parse(result)

        self.__qp.run_async(qobj,
                            wait=5, timeout=100000, callback=async_result)

    def _is_regular_number(self, numstring, base):
        '''
        returns input binary format string or None.
        '''
        if base == 'bin':
            binstring = numstring
        elif base == 'dec':
            if numstring == 'H':
                binstring = 'H'*self.qubits
            else:
                binstring = format(int(numstring), "0{}b".format(self.qubits))

        if len(binstring) != self.qubits:
            return None

        return binstring

    def get_seq(self, text, base='dec'):
        '''
        convert seq and check it
        if text is invalid, return the list of length 0.
        '''
        operators = u'(\\+|\\-)'
        seq = re.split(operators, text)

        # length check
        if len(seq) % 2 == 0 or len(seq) == 1:
            return []

        # regex
        if base == 'bin':
            regex = re.compile(r'[01H]+')
        else:
            regex = re.compile(r'(^(?!.H)[0-9]+|H)')

        for i in range(0, len(seq), 2):
            match = regex.match(seq[i])
            if match is None:
                return []
            num = match.group(0)
            seq[i] = self._is_regular_number(num, base)

            if seq[i] is None:
                return []

        return seq

    def result_parse(self, result):
        '''
        result_parse
        '''
        data = result.get_data("qcirc")
        sys.stdout.write("job id: {0}\n".format(result.get_job_id()))
        sys.stdout.write("raw result: {0}\n".format(data))
        sys.stdout.write("{:=^40}\n".format("answer"))

        counts = data['counts']
        sortedcounts = sorted(counts.items(),
                              key=lambda x: -x[1])

        sortedans = []
        for count in sortedcounts:
            if count[0][0] == '1':
                ans = 'OR'
            else:
                ans = str(int(count[0][-self.qubits:], 2))
            sortedans.append(ans)
            sys.stdout.write('Dec: {0:>2} Bin: {1} Count: {2} \n'
                             .format(ans, str(count[0]), str(count[1])))

        sys.stdout.write('{0:d} answer{1}\n'
                         .format(len(sortedans),
                                 '' if len(sortedans) == 1 else 's'))
        sys.stdout.write("{:=^40}\n".format(""))
        if 'time' in data:
            sys.stdout.write("time: {0:<3} sec\n".format(data['time']))
        sys.stdout.write("All process done.\n")
        sys.stdout.flush()

        uniqanswer = sorted(set(sortedans), key=sortedans.index)

        ans = ",".join(uniqanswer)

        return [str(result), ans]

    def exec_calc(self, text, base='dec', wait_result=False):
        '''
        exec_calc
        '''
        seq = self.get_seq(text, base)
        print('QC seq:', seq)
        if seq == []:
            return ["Syntax error", None]

        # fail message
        fail_msg = None

        try:
            self._init_circuit()
            numbers = seq[0::2]     # slice even index
            i = 1
            observe = False
            for oper in seq[1::2]:  # slice odd index
                if i == len(numbers) - 1:
                    observe = True
                if i == 1:
                    self._qope(numbers[0], oper, numbers[1], observe=observe)
                else:
                    self._qope(numbers[i], oper, observe=observe)
                i = i + 1

            qobj = self._compile('qcirc')

            if wait_result is True:
                [status, ans] = self.result_parse(self._run(qobj))
            else:
                self._run_async(qobj)
                [status, ans] = [
                    'Wait. Calculating on {0}'.format(self.backend),
                    '...'
                    ]

        except QISKitError as ex:
            fail_msg = ('There was an error in the circuit!. Error = {}\n'
                        .format(ex))
        except RegisterSizeError as ex:
            fail_msg = ('Error in the number of registers!. Error = {}\n'
                        .format(ex))

        if fail_msg is not None:
            sys.stdout.write(fail_msg)
            sys.stdout.flush()
            return ["FAIL", None]

        return [status, ans]
Ejemplo n.º 32
0
from qiskit import QuantumProgram

#why?
if __name__ == '__main__':

    qp = QuantumProgram()
    qr = qp.create_quantum_register('qr', 1)
    cr = qp.create_classical_register('cr', 1)
    qc = qp.create_circuit('cir1', [qr], [cr])

    qc.x(qr[0])

    qc.measure(qr[0], cr[0])

    # print result count
    qobj = qp.compile(['cir1'], 'local_qasm_simulator')
    result = qp.run(qobj, wait=5, timeout=2400)
    print(result.get_counts('cir1'))