def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit = qp.create_circuit('test_if', [qr], [cr])
        circuit.x(qr[0])
        circuit.x(qr[1])
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.x(qr[2]).c_if(cr, 0x3)
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.measure(qr[2], cr[2])
        circuit2 = qp.create_circuit('test_if_case_2', [qr], [cr])
        circuit2.x(qr[0])
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.x(qr[2]).c_if(cr, 0x3)
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_case_2')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit2 = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': ucircuit, 'config': config}
        result_if_true = QasmSimulator(job).run()
        job = {'compiled_circuit': ucircuit2, 'config': config}
        result_if_false = QasmSimulator(job).run()

        self.log.info('result_if_true circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_true={0}'.format(result_if_true))

        del circuit.data[1]
        self.log.info('result_if_false circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_false={0}'.format(result_if_false))
        self.assertTrue(result_if_true['data']['counts']['111'] == 100)
        self.assertTrue(result_if_false['data']['counts']['001'] == 100)
Example #2
0
    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit = qp.create_circuit('test_if', [qr], [cr])
        circuit.x(qr[0])
        circuit.x(qr[1])
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.x(qr[2]).c_if(cr, 0x3)
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.measure(qr[2], cr[2])
        circuit2 = qp.create_circuit('test_if_case_2', [qr], [cr])
        circuit2.x(qr[0])
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.x(qr[2]).c_if(cr, 0x3)
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_case_2')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit2 = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': ucircuit, 'config': config}
        result_if_true = QasmSimulator(job).run()
        job = {'compiled_circuit': ucircuit2, 'config': config}
        result_if_false = QasmSimulator(job).run()

        self.log.info('result_if_true circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_true={0}'.format(result_if_true))

        del circuit.data[1]
        self.log.info('result_if_false circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_false={0}'.format(result_if_false))
        self.assertTrue(result_if_true['data']['counts']['111'] == 100)
        self.assertTrue(result_if_false['data']['counts']['001'] == 100)
def use_sympy_backends():
    qprogram = QuantumProgram()
    current_dir = os.path.dirname(os.path.realpath(__file__))
    qasm_file = current_dir + "/../qasm/simple.qasm"
    qasm_circuit = qprogram.load_qasm_file(qasm_file)
    print("analyzing: " + qasm_file)
    print(qprogram.get_qasm(qasm_circuit))

    # sympy statevector simulator
    backend = 'local_sympy_qasm_simulator'
    result = qprogram.execute([qasm_circuit],
                              backend=backend,
                              shots=1,
                              timeout=300)
    print("final quantum amplitude vector: ")
    print(result.get_data(qasm_circuit)['quantum_state'])

    # sympy unitary simulator
    backend = 'local_sympy_unitary_simulator'
    result = qprogram.execute([qasm_circuit],
                              backend=backend,
                              shots=1,
                              timeout=300)
    print("\nunitary matrix of the circuit: ")
    print(result.get_data(qasm_circuit)['unitary'])
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)
    def test_get_qasm_all_gates(self):
        """Test the get_qasm for more gates.

        If all correct the qasm output should be of a certain lenght

        Previusly:
            Libraries:
                from qiskit import QuantumProgram
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)
        qc = QP_program.get_circuit("circuitName")
        qr = QP_program.get_quantum_register("qname")
        cr = QP_program.get_classical_register("cname")
        qc.u1(0.3, qr[0])
        qc.u2(0.2, 0.1, qr[1])
        qc.u3(0.3, 0.2, 0.1, qr[2])
        qc.s(qr[1])
        qc.s(qr[2]).inverse()
        qc.cx(qr[1], qr[2])
        qc.barrier()
        qc.cx(qr[0], qr[1])
        qc.h(qr[0])
        qc.x(qr[2]).c_if(cr, 0)
        qc.y(qr[2]).c_if(cr, 1)
        qc.z(qr[2]).c_if(cr, 2)
        qc.barrier(qr)
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        qc.measure(qr[2], cr[2])
        result = QP_program.get_qasm('circuitName')
        self.assertEqual(len(result), 535)
    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_get_qasm_all_gates(self):
        """Test the get_qasm for more gates.

        If all correct the qasm output should be of a certain lenght

        Previusly:
            Libraries:
                from qiskit import QuantumProgram
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)
        qc = QP_program.get_circuit("circuitName")
        qr = QP_program.get_quantum_register("qname")
        cr = QP_program.get_classical_register("cname")
        qc.u1(0.3, qr[0])
        qc.u2(0.2, 0.1, qr[1])
        qc.u3(0.3, 0.2, 0.1, qr[2])
        qc.s(qr[1])
        qc.s(qr[2]).inverse()
        qc.cx(qr[1], qr[2])
        qc.barrier()
        qc.cx(qr[0], qr[1])
        qc.h(qr[0])
        qc.x(qr[2]).c_if(cr, 0)
        qc.y(qr[2]).c_if(cr, 1)
        qc.z(qr[2]).c_if(cr, 2)
        qc.barrier(qr)
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        qc.measure(qr[2], cr[2])
        result = QP_program.get_qasm('circuitName')
        self.assertEqual(len(result), 535)
 def test_get_qasm_all_gates(self):
     """Test the get_qasm for more gates, using an specification without names.
     """
     q_program = QuantumProgram(specs=self.qps_specs_nonames)
     qc = q_program.get_circuit()
     qr = q_program.get_quantum_register()
     cr = q_program.get_classical_register()
     qc.u1(0.3, qr[0])
     qc.u2(0.2, 0.1, qr[1])
     qc.u3(0.3, 0.2, 0.1, qr[2])
     qc.s(qr[1])
     qc.s(qr[2]).inverse()
     qc.cx(qr[1], qr[2])
     qc.barrier()
     qc.cx(qr[0], qr[1])
     qc.h(qr[0])
     qc.x(qr[2]).c_if(cr, 0)
     qc.y(qr[2]).c_if(cr, 1)
     qc.z(qr[2]).c_if(cr, 2)
     qc.barrier(qr)
     qc.measure(qr[0], cr[0])
     qc.measure(qr[1], cr[1])
     qc.measure(qr[2], cr[2])
     result = q_program.get_qasm()
     self.assertEqual(len(result),
                      (len(qr.name) * 23 + len(cr.name) * 7 + 385))
 def test_get_qasm_all_gates(self):
     """Test the get_qasm for more gates, using an specification without names.
     """
     q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
     qc = q_program.get_circuit()
     qr = q_program.get_quantum_register()
     cr = q_program.get_classical_register()
     qc.u1(0.3, qr[0])
     qc.u2(0.2, 0.1, qr[1])
     qc.u3(0.3, 0.2, 0.1, qr[2])
     qc.s(qr[1])
     qc.s(qr[2]).inverse()
     qc.cx(qr[1], qr[2])
     qc.barrier()
     qc.cx(qr[0], qr[1])
     qc.h(qr[0])
     qc.x(qr[2]).c_if(cr, 0)
     qc.y(qr[2]).c_if(cr, 1)
     qc.z(qr[2]).c_if(cr, 2)
     qc.barrier(qr)
     qc.measure(qr[0], cr[0])
     qc.measure(qr[1], cr[1])
     qc.measure(qr[2], cr[2])
     result = q_program.get_qasm()
     self.assertEqual(len(result), (len(qr.name) * 23 +
                                    len(cr.name) * 7 +
                                    385))
    def test_json_output(self):
        qp = QuantumProgram()
        qp.load_qasm_file(self.QASM_FILE_PATH, name="example")

        basis_gates = []  # unroll to base gates, change to test
        unroller = unroll.Unroller(qasm.Qasm(data=qp.get_qasm("example")).parse(),
                                   unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.log.info('test_json_ouptut: %s', circuit)
Example #12
0
    def test_json_output(self):
        qprogram = QuantumProgram()
        qprogram.load_qasm_file(self.qasm_file_path, name="example")

        basis_gates = []  # unroll to base gates, change to test
        unroller = unroll.Unroller(qasm.Qasm(data=qprogram.get_qasm("example")).parse(),
                                   unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.log.info('test_json_ouptut: %s', circuit)
Example #13
0
File: test.py Project: NickyBar/QIP
    def test_print_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")

        qc.h(qr[1])
        result = QP_program.get_qasm("circuitName")
        self.assertEqual(len(result), 78)
    def test_load(self):
        """
        Load a Json Quantum Program
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)

        result = QP_program.load("./test/python/test_load.json")
        self.assertEqual(result['status'], 'Done')

        check_result = QP_program.get_qasm('circuitName')
        self.assertEqual(len(check_result), 1872)
    def test_load(self):
        """
        Load a Json Quantum Program
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)

        result = QP_program.load("./test/python/test_load.json")
        self.assertEqual(result['status'], 'Done')

        check_result = QP_program.get_qasm('circuitName')
        self.assertEqual(len(check_result), 1872)
Example #16
0
    def test_json_output(self):
        seed = 88
        qp = QuantumProgram()
        qp.load_qasm_file(self.QASM_FILE_PATH, name="example")

        basis_gates = []  # unroll to base gates, change to test
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        logging.info('test_json_ouptut: {0}'.format(circuit))
class LocalQasmSimulatorTest(QiskitTestCase):
    """Test local qasm simulator."""
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
        self.qp = QuantumProgram()
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        circuit_config = {
            'coupling_map': None,
            'basis_gates': 'u1,u2,u3,cx,id',
            'layout': None,
            'seed': self.seed
        }
        resources = {'max_credits': 3, 'wait': 5, 'timeout': 120}
        self.qobj = {
            'id':
            'test_sim_single_shot',
            'config': {
                'max_credits': resources['max_credits'],
                'shots': 1024,
                'backend': 'local_sympy_qasm_simulator',
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': None,
                'config': circuit_config
            }]
        }
        self.q_job = QuantumJob(self.qobj,
                                backend='local_sympy_qasm_simulator',
                                circuit_config=circuit_config,
                                seed=self.seed,
                                resources=resources,
                                preformatted=True)

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        result = SympyQasmSimulator().run(self.q_job)
        actual = result.get_data('test')['quantum_state']
        self.assertEqual(result.get_status(), 'COMPLETED')
        self.assertEqual(actual[0], sqrt(2) / 2)
        self.assertEqual(actual[1], 0)
        self.assertEqual(actual[2], 0)
        self.assertEqual(actual[3], sqrt(2) / 2)
Example #18
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)
class StatevectorSimulatorSympyTest(QiskitTestCase):
    """Test local statevector simulator."""

    def setUp(self):
        self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
        self.qp = QuantumProgram()
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        circuit_config = {'coupling_map': None,
                          'basis_gates': 'u1,u2,u3,cx,id',
                          'layout': None}
        resources = {'max_credits': 3}
        self.qobj = {'id': 'test_sim_single_shot',
                     'config': {
                         'max_credits': resources['max_credits'],
                         'shots': 1024,
                         'backend_name': 'local_statevector_simulator_sympy',
                     },
                     'circuits': [
                         {
                             'name': 'test',
                             'compiled_circuit': circuit,
                             'compiled_circuit_qasm': None,
                             'config': circuit_config
                         }
                     ]}
        self.q_job = QuantumJob(self.qobj,
                                backend=StatevectorSimulatorSympy(),
                                circuit_config=circuit_config,
                                resources=resources,
                                preformatted=True)

    def test_statevector_simulator_sympy(self):
        """Test data counts output for single circuit run against reference."""
        result = StatevectorSimulatorSympy().run(self.q_job).result()
        actual = result.get_data('test')['statevector']
        self.assertEqual(result.get_status(), 'COMPLETED')
        self.assertEqual(actual[0], sqrt(2)/2)
        self.assertEqual(actual[1], 0)
        self.assertEqual(actual[2], 0)
        self.assertEqual(actual[3], sqrt(2)/2)
def use_sympy_backends():
    qprogram = QuantumProgram()
    current_dir = os.path.dirname(os.path.realpath(__file__))
    qasm_file = current_dir + "/../qasm/simple.qasm"
    qasm_circuit = qprogram.load_qasm_file(qasm_file)
    print("analyzing: " + qasm_file)
    print(qprogram.get_qasm(qasm_circuit))
    
    # sympy statevector simulator
    backend = 'local_statevector_simulator_sympy'
    result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300)
    print("final quantum amplitude vector: ")
    print(result.get_data(qasm_circuit)['statevector'])

    # sympy unitary simulator
    backend = 'local_unitary_simulator_sympy'
    result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300)
    print("\nunitary matrix of the circuit: ")
    print(result.get_data(qasm_circuit)['unitary'])
Example #21
0
File: test.py Project: NickyBar/QIP
    def test_create_add_gates(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")

        qc.u3(0.3, 0.2, 0.1, qr[0])
        qc.h(qr[1])
        qc.cx(qr[1], qr[2])
        qc.barrier()
        qc.cx(qr[0], qr[1])
        qc.h(qr[0])
        qc.z(qr[2]).c_if(cr, 1)
        qc.x(qr[2]).c_if(cr, 1)
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])

        result = QP_program.get_qasm('circuitName')

        self.assertEqual(len(result), 348)
    def test_get_qasm(self):
        """Test the get_qasm.

        If all correct the qasm output should be of a certain lenght

        Previusly:
            Libraries:
                from qiskit import QuantumProgram
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)
        qc = QP_program.get_circuit("circuitName")
        qr = QP_program.get_quantum_register("qname")
        cr = QP_program.get_classical_register("cname")
        qc.h(qr[0])
        qc.cx(qr[0], qr[1])
        qc.cx(qr[1], qr[2])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        qc.measure(qr[2], cr[2])
        result = QP_program.get_qasm("circuitName")
        self.assertEqual(len(result), 212)
    def test_get_qasm(self):
        """Test the get_qasm.

        If all correct the qasm output should be of a certain lenght

        Previusly:
            Libraries:
                from qiskit import QuantumProgram
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)
        qc = QP_program.get_circuit("circuitName")
        qr = QP_program.get_quantum_register("qname")
        cr = QP_program.get_classical_register("cname")
        qc.h(qr[0])
        qc.cx(qr[0], qr[1])
        qc.cx(qr[1], qr[2])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        qc.measure(qr[2], cr[2])
        result = QP_program.get_qasm("circuitName")
        self.assertEqual(len(result), 212)
    def test_get_qasm_noname(self):
        """Test the get_qasm using an specification without names.
        """
        q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
        qc = q_program.get_circuit()

        qrn = list(q_program.get_quantum_register_names())
        self.assertEqual(len(qrn), 1)
        qr = q_program.get_quantum_register(qrn[0])

        crn = list(q_program.get_classical_register_names())
        self.assertEqual(len(crn), 1)
        cr = q_program.get_classical_register(crn[0])

        qc.h(qr[0])
        qc.cx(qr[0], qr[1])
        qc.cx(qr[1], qr[2])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        qc.measure(qr[2], cr[2])
        result = q_program.get_qasm()
        self.assertEqual(len(result), len(qrn[0]) * 9 + len(crn[0]) * 4 + 147)
Example #25
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))
Example #26
0
    def test_get_qasm_noname(self):
        """Test the get_qasm using an specification without names.
        """
        q_program = QuantumProgram(specs=self.qps_specs_nonames)
        qc = q_program.get_circuit()

        qrn = list(q_program.get_quantum_register_names())
        self.assertEqual(len(qrn), 1)
        qr = q_program.get_quantum_register(qrn[0])

        crn = list(q_program.get_classical_register_names())
        self.assertEqual(len(crn), 1)
        cr = q_program.get_classical_register(crn[0])

        qc.h(qr[0])
        qc.cx(qr[0], qr[1])
        qc.cx(qr[1], qr[2])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        qc.measure(qr[2], cr[2])
        result = q_program.get_qasm()
        self.assertEqual(len(result), len(qrn[0]) * 9 + len(crn[0]) * 4 + 147)
def main(M=16,
         numberOfCoins=8,
         indexOfFalseCoin=6,
         backend="local_qasm_simulator",
         shots=1):

    if numberOfCoins < 4 or numberOfCoins >= M:
        raise Exception("Please use numberOfCoins between 4 and ", M - 1)
    if indexOfFalseCoin < 0 or indexOfFalseCoin >= numberOfCoins:
        raise Exception("indexOfFalseCoin must be between 0 and ",
                        numberOfCoins - 1)

    # ------- Query the quantum beam balance
    Q_program = QuantumProgram()
    Q_program.set_api(Qconfig.APItoken,
                      Qconfig.config["url"])  # set the APIToken and API url

    # Create registers
    # numberOfCoins qubits for the binary query string and 1 qubit for
    # working and recording the result of quantum balance
    qr = Q_program.create_quantum_register("qr", numberOfCoins + 1)

    # for recording the measurement on qr
    cr = Q_program.create_classical_register("cr", numberOfCoins + 1)

    circuitName = "QueryStateCircuit"
    circuit = Q_program.create_circuit(circuitName, [qr], [cr])

    N = numberOfCoins

    #Create uniform superposition of all strings of length N
    for i in range(N):
        circuit.h(qr[i])

    #Perform XOR(x) by applying CNOT gates sequentially from qr[0] to qr[N-1] and storing the result to qr[N]
    for i in range(N):
        circuit.cx(qr[i], qr[N])

    #Measure qr[N] and store the result to cr[N]. We continue if cr[N] is zero, or repeat otherwise
    circuit.measure(qr[N], cr[N])

    # we proceed to query the quantum beam balance if the value of cr[0]...cr[N] is all zero
    # by preparing the Hadamard state of |1>, i.e., |0> - |1> at qr[N]
    circuit.x(qr[N]).c_if(cr, 0)
    circuit.h(qr[N]).c_if(cr, 0)

    # we rewind the computation when cr[N] is not zero
    for i in range(N):
        circuit.h(qr[i]).c_if(cr, 2**N)

    #----- Construct the quantum beam balance
    k = indexOfFalseCoin

    # Apply the quantum beam balance on the desired superposition state (marked by cr equal to zero)
    circuit.cx(qr[k], qr[N]).c_if(cr, 0)

    # --- Identify the false coin
    # Apply Hadamard transform on qr[0] ... qr[N-1]
    for i in range(N):
        circuit.h(qr[i]).c_if(cr, 0)

    # Measure qr[0] ... qr[N-1]
    for i in range(N):
        circuit.measure(qr[i], cr[i])

    print(Q_program.get_qasm(circuitName))

    results = Q_program.execute([circuitName], backend=backend, shots=shots)
    answer = results.get_counts(circuitName)

    print("Device " + backend + " counts " + str(answer))

    #plot_histogram(answer)

    for key in answer.keys():
        normalFlag, _ = Counter(
            key[1:]).most_common(1)[0]  #get most common label
        for i in range(2, len(key)):
            if key[i] != normalFlag:
                print("False coin index is: ", len(key) - i - 1)
Example #28
0
def Grover():
    if sys.version_info < (3, 5):
        raise Exception('Please use Python version 3.5 or greater.')

    #Create an object
    qp = QuantumProgram()
    backend = 'local_qasm_simulator'
    # backend = 'ibmqx4'
    max_credits = 15

    QX_TOKEN = "ee6100e19629678494bd4c9f4f0f3dc3038fe389b08eee456b8a8be280e08884f6b6228825afa60dda60bf7ee5995ce9e5ae6473f31137a0e94780669bce9707"
    QX_URL = "https://quantumexperience.ng.bluemix.net/api"

    # Set up the API and execute the program.

    # qp.set_api(QX_TOKEN, QX_URL)

    # quantum register for the circuit(3->5)
    q1 = qp.create_quantum_register('q1', 5)
    c1 = qp.create_classical_register('c1', 5)

    # making the circuit
    qc1 = qp.create_circuit('Grover', [q1], [c1])

    # line one
    qc1.x(q1[0])

    # line two
    qc1.h(q1[0])
    qc1.h(q1[1])
    qc1.h(q1[2])

    # line three
    qc1.x(q1[0])
    qc1.x(q1[1])

    # line four
    qc1.ccx(q1[2], q1[1], q1[0])

    qc1.x(q1[2])
    # qc1.x(q1[1])

    # line five
    qc1.h(q1[2])
    qc1.h(q1[1])

    # line six
    qc1.x(q1[2])
    qc1.x(q1[1])

    # line seven
    qc1.h(q1[1])

    # line eight
    qc1.cx(q1[2], q1[1])

    # line nine
    qc1.h(q1[1])

    # line ten
    qc1.x(q1[2])
    qc1.x(q1[1])

    # line eleven
    qc1.h(q1[0])
    qc1.h(q1[1])
    qc1.h(q1[2])

    # Measure
    for i in range(5):
        qc1.measure(q1[i], c1[i])

    # printing the circuits
    print(qp.get_qasm('Grover'))
    qobj = qp.compile('Grover', backend=backend, shots=1000, max_credits=15)
    qp.get_execution_list(qobj)
    qp.get_execution_list(qobj, verbose=True)
    qp.get_compiled_configuration(qobj, 'Grover')

    #new
    result = qp.execute('Grover', backend=backend, shots=1000, max_credits=15)

    #print result:
    print(qp.get_compiled_qasm(qobj, 'Grover'))

    #print info:
    #print(api.backend_status(backend))
    #print(api.backend_parameters(backend))

    #new
    # print(result)
    # print(result.get_data("Grover"))

    #Record information in text.txt(Create text.txt file in your repository)

    res = result.get_data("Grover")
    quasm = qp.get_qasm('Grover')
    b = ascii(res)
    c = ascii(quasm)
    with open('Fourth(111).txt', 'w') as ouf:
        ouf.write('\n' + b)
Example #29
0
class UnitarySimulatorSympyTest(QiskitTestCase):
    """Test local unitary simulator sympy."""
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
        self.qp = QuantumProgram()

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [
            op for op in circuit['operations'] if op['name'] != 'measure'
        ]
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id':
            'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_sympy_unitary_simulator'
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': self.qp.get_qasm('example'),
                'config': {
                    'coupling_map': None,
                    'basis_gates': None,
                    'layout': None,
                    'seed': None
                }
            }]
        }

        q_job = QuantumJob(qobj,
                           backend=UnitarySimulatorSympy(),
                           preformatted=True)

        result = UnitarySimulatorSympy().run(q_job).result()
        actual = result.get_data('test')['unitary']

        self.assertEqual(actual[0][0], sqrt(2) / 2)
        self.assertEqual(actual[0][1], sqrt(2) / 2)
        self.assertEqual(actual[0][2], 0)
        self.assertEqual(actual[0][3], 0)
        self.assertEqual(actual[1][0], 0)
        self.assertEqual(actual[1][1], 0)
        self.assertEqual(actual[1][2], sqrt(2) / 2)
        self.assertEqual(actual[1][3], -sqrt(2) / 2)
        self.assertEqual(actual[2][0], 0)
        self.assertEqual(actual[2][1], 0)
        self.assertEqual(actual[2][2], sqrt(2) / 2)
        self.assertEqual(actual[2][3], sqrt(2) / 2)
        self.assertEqual(actual[3][0], sqrt(2) / 2)
        self.assertEqual(actual[3][1], -sqrt(2) / 2)
        self.assertEqual(actual[3][2], 0)
        self.assertEqual(actual[3][3], 0)
qcircuit.x(qubit[0])
qcircuit.h(qubit[0])
qcircuit.ccx(qubit[0], qubit[1], qubit[6])
qcircuit.ccx(qubit[2], qubit[3], qubit[5])
qcircuit.ccx(qubit[5], qubit[6], qubit[4])
qcircuit.ccx(qubit[2], qubit[3], qubit[5])
qcircuit.ccx(qubit[0], qubit[1], qubit[6])
qcircuit.ccx(qubit[0], qubit[1], qubit[6])
qcircuit.ccx(qubit[6], qubit[2], qubit[3])
qcircuit.ccx(qubit[0], qubit[1], qubit[6])
qcircuit.ccx(qubit[0], qubit[1], qubit[2])
qcircuit.cx(qubit[0], qubit[1])
qcircuit.x(qubit[0])

qcircuit.measure(qubit[1], classic[0])
qcircuit.measure(qubit[2], classic[1])
qcircuit.measure(qubit[3], classic[2])
qcircuit.measure(qubit[4], classic[3])

#run the complete circuit and gather the result
result = quantum.execute(["quantumWalk"],
                         backend='local_qasm_simulator',
                         shots=1024)

#return the result to console: bits and bit states that were counted
print(quantum.get_qasm("quantumWalk"))
print(result)
print(result.get_data("quantumWalk"))

#plot the counts, determine probability of each state
plot_histogram(result.get_counts('quantumWalk'))
Example #31
0
class LocalQasmSimulatorTest(unittest.TestCase):
    """Test local qasm simulator."""
    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.pdf = PdfPages(cls.moduleName + '.pdf')
        cls.log = logging.getLogger(__name__)
        cls.log.setLevel(logging.INFO)
        logFileName = cls.moduleName + '.log'
        handler = logging.FileHandler(logFileName)
        handler.setLevel(logging.INFO)
        log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
                   ' %(message)s'.format(cls.__name__))
        formatter = logging.Formatter(log_fmt)
        handler.setFormatter(formatter)
        cls.log.addHandler(handler)

    @classmethod
    def tearDownClass(cls):
        cls.pdf.close()

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_qasm_simulator_single_shot(self):
        """Test single shot run."""
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': circuit, 'config': config}
        result = QasmSimulator(job).run()
        self.assertEqual(result['status'], 'DONE')

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': circuit, 'config': config}
        result = QasmSimulator(job).run()
        expected = {
            '100 100': 137,
            '011 011': 131,
            '101 101': 117,
            '111 111': 127,
            '000 000': 131,
            '010 010': 141,
            '110 110': 116,
            '001 001': 124
        }
        self.assertEqual(result['data']['counts'], expected)

    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit = qp.create_circuit('test_if', [qr], [cr])
        circuit.x(qr[0])
        circuit.x(qr[1])
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.x(qr[2]).c_if(cr, 0x3)
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.measure(qr[2], cr[2])
        circuit2 = qp.create_circuit('test_if_case_2', [qr], [cr])
        circuit2.x(qr[0])
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.x(qr[2]).c_if(cr, 0x3)
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_case_2')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit2 = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': ucircuit, 'config': config}
        result_if_true = QasmSimulator(job).run()
        job = {'compiled_circuit': ucircuit2, 'config': config}
        result_if_false = QasmSimulator(job).run()

        self.log.info('result_if_true circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_true={0}'.format(result_if_true))

        del circuit.data[1]
        self.log.info('result_if_false circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_false={0}'.format(result_if_false))
        self.assertTrue(result_if_true['data']['counts']['111'] == 100)
        self.assertTrue(result_if_false['data']['counts']['001'] == 100)

    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)

    def profile_qasm_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        seed = 88
        shots = 1024
        nCircuits = 100
        minDepth = 1
        maxDepth = 40
        minQubits = 1
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed,
                                             minQubits=minQubits,
                                             maxQubits=maxQubits,
                                             minDepth=minDepth,
                                             maxDepth=maxDepth)
        randomCircuits.add_circuits(nCircuits)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_qasm_simulator',
                        shots=shots)
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling QasmSimulator -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling QasmSimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

    def profile_nqubit_speed_grow_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is 10x the number of simulated
        qubits. Also creates a pdf file with this module name showing a
        plot of the results. Compilation is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubitRangeMax = 15
        nQubitList = range(1, qubitRangeMax + 1)
        nCircuits = 10
        shots = 1024
        seed = 88
        maxTime = 30  # seconds; timing stops when simulation time exceeds this number
        fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
        backendList = ['local_qasm_simulator', 'local_unitary_simulator']
        if shutil.which('qasm_simulator'):
            backendList.append('local_qasm_cpp_simulator')
        else:
            self.log.info(
                'profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping'
            )
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.25, 0.8, 0.6))
        for i, backend in enumerate(backendList):
            elapsedTime = np.zeros(len(nQubitList))
            if backend is 'local_unitary_simulator':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubitRangeMax and not timedOut:
                nQubits = nQubitList[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     minQubits=nQubits,
                                                     maxQubits=nQubits,
                                                     minDepth=nQubits * 10,
                                                     maxDepth=nQubits * 10)
                randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure)
                qp = randomCircuits.getProgram()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames,
                                  backend=backend,
                                  shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > maxTime:
                    timedOut = True
                self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j]))
                if backend is not 'local_unitary_simulator':
                    for name in cnames:
                        self.log.info(
                            fmtStr2.format(backend, name,
                                           len(qp.get_circuit(name)),
                                           results.get_data(name)))
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend is 'local_unitary_simulator':
                ax.plot(nQubitList[:j],
                        elapsedTime[:j],
                        label=backend,
                        marker='o')
            else:
                ax.plot(nQubitList[:j],
                        elapsedTime[:j] / shots,
                        label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_grow_depth')
            fig.text(
                0.1, 0.05,
                fmtStr3.format(minDepth='10*nQubits',
                               maxDepth='10*nQubits',
                               nCircuits=nCircuits,
                               shots=shots))
            ax.legend()
        self.pdf.savefig(fig)

    def profile_nqubit_speed_constant_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is fixed at 40. Also creates a pdf file
        with this module name showing a plot of the results. Compilation
        is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubitRangeMax = 15
        nQubitList = range(1, qubitRangeMax + 1)
        maxDepth = 40
        minDepth = 40
        nCircuits = 10
        shots = 1024
        seed = 88
        maxTime = 30  # seconds; timing stops when simulation time exceeds this number
        fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
        backendList = ['local_qasm_simulator', 'local_unitary_simulator']
        if shutil.which('qasm_simulator'):
            backendList.append('local_qasm_cpp_simulator')
        else:
            self.log.info(
                'profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping'
            )
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.2, 0.8, 0.6))
        for i, backend in enumerate(backendList):
            elapsedTime = np.zeros(len(nQubitList))
            if backend is 'local_unitary_simulator':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubitRangeMax and not timedOut:
                nQubits = nQubitList[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     minQubits=nQubits,
                                                     maxQubits=nQubits,
                                                     minDepth=minDepth,
                                                     maxDepth=maxDepth)
                randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure)
                qp = randomCircuits.getProgram()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames,
                                  backend=backend,
                                  shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > maxTime:
                    timedOut = True
                self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j]))
                if backend is not 'local_unitary_simulator':
                    for name in cnames:
                        self.log.info(
                            fmtStr2.format(backend, name,
                                           len(qp.get_circuit(name)),
                                           results.get_data(name)))
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend is 'local_unitary_simulator':
                ax.plot(nQubitList[:j],
                        elapsedTime[:j],
                        label=backend,
                        marker='o')
            else:
                ax.plot(nQubitList[:j],
                        elapsedTime[:j] / shots,
                        label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_constant_depth')
            fig.text(
                0.1, 0.05,
                fmtStr3.format(minDepth=minDepth,
                               maxDepth=maxDepth,
                               nCircuits=nCircuits,
                               shots=shots))
            ax.legend()
        self.pdf.savefig(fig)
class LocalSimulatorTest(unittest.TestCase):
    """
    Test interface to local simulators.
    """

    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.log = logging.getLogger(__name__)
        cls.log.setLevel(logging.INFO)
        logFileName = cls.moduleName + '.log'
        handler = logging.FileHandler(logFileName)
        handler.setLevel(logging.INFO)
        log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
                   ' %(message)s'.format(cls.__name__))
        formatter = logging.Formatter(log_fmt)
        handler.setFormatter(formatter)
        cls.log.addHandler(handler)

    @classmethod
    def tearDownClass(cls):
        #cls.pdf.close()
        pass

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
                      unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.job = {'compiled_circuit': circuit,
                    'config': {'shots': shots, 'seed': random.randint(0, 10)}
                   }

    def tearDown(self):
        pass

    def test_local_configuration_present(self):
        self.assertTrue(_localsimulator.local_configuration)

    def test_local_configurations(self):
        required_keys = ['name',
                         'url',
                         'simulator',
                         'description',
                         'coupling_map',
                         'basis_gates']
        for conf in _localsimulator.local_configuration:
            for key in required_keys:
                self.assertIn(key, conf.keys())

    def test_simulator_classes(self):
        cdict = _localsimulator._simulator_classes
        cdict = getattr(_localsimulator, '_simulator_classes')
        self.log.info('found local simulators: {0}'.format(repr(cdict)))
        self.assertTrue(cdict)

    def test_local_backends(self):
        backends = _localsimulator.local_backends()
        self.log.info('found local backends: {0}'.format(repr(backends)))
        self.assertTrue(backends)

    def test_instantiation(self):
        """
        Test instantiation of LocalSimulator
        """
        backend_list = _localsimulator.local_backends()
        for backend_name in backend_list:
            backend = _localsimulator.LocalSimulator(backend_name, self.job)
class LocalQasmSimulatorTest(unittest.TestCase):
    """Test local qasm simulator."""

    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.pdf = PdfPages(cls.moduleName + '.pdf')
        cls.log = logging.getLogger(__name__)
        cls.log.setLevel(logging.INFO)
        logFileName = cls.moduleName + '.log'
        handler = logging.FileHandler(logFileName)
        handler.setLevel(logging.INFO)
        log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
                   ' %(message)s'.format(cls.__name__))
        formatter = logging.Formatter(log_fmt)
        handler.setFormatter(formatter)
        cls.log.addHandler(handler)

    @classmethod
    def tearDownClass(cls):
        cls.pdf.close()

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_qasm_simulator_single_shot(self):
        """Test single shot run."""
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
                      unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': circuit, 'config': config}
        result = QasmSimulator(job).run()
        self.assertEqual(result['status'], 'DONE')

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
                      unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': circuit, 'config': config}
        result = QasmSimulator(job).run()
        expected = {'100 100': 137, '011 011': 131, '101 101': 117, '111 111': 127,
                    '000 000': 131, '010 010': 141, '110 110': 116, '001 001': 124}
        self.assertEqual(result['data']['counts'], expected)

    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit = qp.create_circuit('test_if', [qr], [cr])
        circuit.x(qr[0])
        circuit.x(qr[1])
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.x(qr[2]).c_if(cr, 0x3)
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.measure(qr[2], cr[2])
        circuit2 = qp.create_circuit('test_if_case_2', [qr], [cr])
        circuit2.x(qr[0])
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.x(qr[2]).c_if(cr, 0x3)
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_case_2')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit2 = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': ucircuit, 'config': config}
        result_if_true = QasmSimulator(job).run()
        job = {'compiled_circuit': ucircuit2, 'config': config}
        result_if_false = QasmSimulator(job).run()

        self.log.info('result_if_true circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_true={0}'.format(result_if_true))

        del circuit.data[1]
        self.log.info('result_if_false circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_false={0}'.format(result_if_false))
        self.assertTrue(result_if_true['data']['counts']['111'] == 100)
        self.assertTrue(result_if_false['data']['counts']['001'] == 100)

    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)

    def profile_qasm_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        seed = 88
        shots = 1024
        nCircuits = 100
        minDepth = 1
        maxDepth = 40
        minQubits = 1
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed,
                                             minQubits=minQubits,
                                             maxQubits=maxQubits,
                                             minDepth=minDepth,
                                             maxDepth=maxDepth)
        randomCircuits.add_circuits(nCircuits)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_qasm_simulator',
                        shots=shots)
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling QasmSimulator -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling QasmSimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

    def profile_nqubit_speed_grow_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is 10x the number of simulated
        qubits. Also creates a pdf file with this module name showing a
        plot of the results. Compilation is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubitRangeMax = 15
        nQubitList = range(1,qubitRangeMax + 1)
        nCircuits = 10
        shots = 1024
        seed = 88
        maxTime = 30 # seconds; timing stops when simulation time exceeds this number
        fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
        backendList = ['local_qasm_simulator', 'local_unitary_simulator']
        if shutil.which('qasm_simulator'):
            backendList.append('local_qasm_cpp_simulator')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.25, 0.8, 0.6))
        for i, backend in enumerate(backendList):
            elapsedTime = np.zeros(len(nQubitList))
            if backend is 'local_unitary_simulator':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubitRangeMax and not timedOut:
                nQubits = nQubitList[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     minQubits=nQubits,
                                                     maxQubits=nQubits,
                                                     minDepth=nQubits*10,
                                                     maxDepth=nQubits*10)
                randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure)
                qp = randomCircuits.getProgram()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames, backend=backend, shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > maxTime:
                    timedOut = True
                self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j]))
                if backend is not 'local_unitary_simulator':
                    for name in cnames:
                        self.log.info(fmtStr2.format(
                            backend, name, len(qp.get_circuit(name)),
                            results.get_data(name)))
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend is 'local_unitary_simulator':
                ax.plot(nQubitList[:j], elapsedTime[:j], label=backend, marker='o')
            else:
                ax.plot(nQubitList[:j], elapsedTime[:j]/shots, label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_grow_depth')
            fig.text(0.1, 0.05,
                     fmtStr3.format(minDepth='10*nQubits', maxDepth='10*nQubits',
                                    nCircuits=nCircuits, shots=shots))
            ax.legend()
        self.pdf.savefig(fig)

    def profile_nqubit_speed_constant_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is fixed at 40. Also creates a pdf file
        with this module name showing a plot of the results. Compilation
        is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubitRangeMax = 15
        nQubitList = range(1,qubitRangeMax + 1)
        maxDepth = 40
        minDepth = 40
        nCircuits = 10
        shots = 1024
        seed = 88
        maxTime = 30 # seconds; timing stops when simulation time exceeds this number
        fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
        backendList = ['local_qasm_simulator', 'local_unitary_simulator']
        if shutil.which('qasm_simulator'):
            backendList.append('local_qasm_cpp_simulator')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.2, 0.8, 0.6))
        for i, backend in enumerate(backendList):
            elapsedTime = np.zeros(len(nQubitList))
            if backend is 'local_unitary_simulator':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubitRangeMax and not timedOut:
                nQubits = nQubitList[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     minQubits=nQubits,
                                                     maxQubits=nQubits,
                                                     minDepth=minDepth,
                                                     maxDepth=maxDepth)
                randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure)
                qp = randomCircuits.getProgram()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames, backend=backend, shots=shots, seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > maxTime:
                    timedOut = True
                self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j]))
                if backend is not 'local_unitary_simulator':
                    for name in cnames:
                        self.log.info(fmtStr2.format(
                            backend, name, len(qp.get_circuit(name)),
                            results.get_data(name)))
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend is 'local_unitary_simulator':
                ax.plot(nQubitList[:j], elapsedTime[:j], label=backend, marker='o')
            else:
                ax.plot(nQubitList[:j], elapsedTime[:j]/shots, label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_constant_depth')
            fig.text(0.1, 0.05,
                     fmtStr3.format(minDepth=minDepth, maxDepth=maxDepth,
                                    nCircuits=nCircuits, shots=shots))
            ax.legend()
        self.pdf.savefig(fig)
class LocalSimulatorTest(unittest.TestCase):
    """
    Test interface to local simulators.
    """
    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.logFileName = cls.moduleName + '.log'
        log_fmt = 'LocalSimulatorTest:%(levelname)s:%(asctime)s: %(message)s'
        logging.basicConfig(filename=cls.logFileName,
                            level=logging.INFO,
                            format=log_fmt)

    @classmethod
    def tearDownClass(cls):
        #cls.pdf.close()
        pass

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.job = {
            'compiled_circuit': circuit,
            'config': {
                'shots': shots,
                'seed': random.randint(0, 10)
            }
        }

    def tearDown(self):
        pass

    def test_local_configuration_present(self):
        self.assertTrue(_localsimulator.local_configuration)

    def test_local_configurations(self):
        required_keys = [
            'name', 'url', 'simulator', 'description', 'coupling_map',
            'basis_gates'
        ]
        for conf in _localsimulator.local_configuration:
            for key in required_keys:
                self.assertIn(key, conf.keys())

    def test_simulator_classes(self):
        cdict = _localsimulator._simulator_classes
        cdict = getattr(_localsimulator, '_simulator_classes')
        logging.info('found local simulators: {0}'.format(repr(cdict)))
        self.assertTrue(cdict)

    def test_local_backends(self):
        backends = _localsimulator.local_backends()
        logging.info('found local backends: {0}'.format(repr(backends)))
        self.assertTrue(backends)

    def test_instantiation(self):
        """
        Test instantiation of LocalSimulator
        """
        backend_list = _localsimulator.local_backends()
        for backend_name in backend_list:
            backend = _localsimulator.LocalSimulator(backend_name, self.job)
class LocalUnitarySimulatorTest(unittest.TestCase):
    """Test local unitary simulator."""

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()
        self.moduleName = os.path.splitext(__file__)[0]
        self.modulePath = os.path.dirname(__file__)
        logFileName = self.moduleName + '.log'
        logging.basicConfig(filename=logFileName, level=logging.INFO)

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
                      unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
	# if we want to manipulate the circuit, we have to convert it to a dict
        circuit = json.loads(circuit.decode())
        #strip measurements from circuit to avoid warnings
        circuit['operations'] = [op for op in circuit['operations']
                                 if op['name'] != 'measure']
	# the simulator is expecting a JSON format, so we need to convert it back to JSON
        job = {'compiled_circuit': json.dumps(circuit).encode()}
        # numpy savetxt is currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, delimiter=',')
        expected = np.loadtxt(os.path.join(self.modulePath,
                                           'example_unitary_matrix.dat'),
                              dtype='complex', delimiter=',')
        result = UnitarySimulator(job).run()
        self.assertTrue(np.allclose(result['data']['unitary'], expected,
                                    rtol=1e-3))

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        nCircuits = 100
        maxDepth = 40
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed=self.seed,
                                             maxDepth=maxDepth,
                                             maxQubits=maxQubits)
        randomCircuits.add_circuits(nCircuits, doMeasure=False)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_unitary_simulator')
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        logging.info('------- start profiling UnitarySimulator -----------')
        ps.print_stats()
        logging.info(sout.getvalue())
        logging.info('------- stop profiling UnitarySimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
class TestLocalQasmSimulatorPy(QiskitTestCase):
    """Test local_qasm_simulator_py."""

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        if do_profiling:
            cls.pdf = PdfPages(cls.moduleName + '.pdf')

    @classmethod
    def tearDownClass(cls):
        if do_profiling:
            cls.pdf.close()

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        circuit_config = {'coupling_map': None,
                          'basis_gates': 'u1,u2,u3,cx,id',
                          'layout': None,
                          'seed': self.seed}
        resources = {'max_credits': 3}
        self.qobj = {'id': 'test_sim_single_shot',
                     'config': {
                         'max_credits': resources['max_credits'],
                         'shots': 1024,
                         'backend_name': 'local_qasm_simulator_py',
                     },
                     'circuits': [
                         {
                             'name': 'test',
                             'compiled_circuit': circuit,
                             'compiled_circuit_qasm': None,
                             'config': circuit_config
                         }
                     ]}
        self.q_job = QuantumJob(self.qobj,
                                backend=QasmSimulatorPy(),
                                circuit_config=circuit_config,
                                seed=self.seed,
                                resources=resources,
                                preformatted=True)

    def tearDown(self):
        pass

    def test_qasm_simulator_single_shot(self):
        """Test single shot run."""
        shots = 1
        self.qobj['config']['shots'] = shots
        result = QasmSimulatorPy().run(self.q_job).result()
        self.assertEqual(result.get_status(), 'COMPLETED')

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        result = QasmSimulatorPy().run(self.q_job).result()
        shots = 1024
        threshold = 0.04 * shots
        counts = result.get_counts('test')
        target = {'100 100': shots / 8, '011 011': shots / 8,
                  '101 101': shots / 8, '111 111': shots / 8,
                  '000 000': shots / 8, '010 010': shots / 8,
                  '110 110': shots / 8, '001 001': shots / 8}
        self.assertDictAlmostEqual(counts, target, threshold)

    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr])
        circuit_if_true.x(qr[0])
        circuit_if_true.x(qr[1])
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.x(qr[2]).c_if(cr, 0x3)
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.measure(qr[2], cr[2])
        circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr])
        circuit_if_false.x(qr[0])
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.x(qr[2]).c_if(cr, 0x3)
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_true = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_false')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_false = unroller.execute()
        qobj = {
            'id': 'test_if_qobj',
            'config': {
                'max_credits': 3,
                'shots': shots,
                'backend_name': 'local_qasm_simulator_py',
            },
            'circuits': [
                {
                    'name': 'test_if_true',
                    'compiled_circuit': ucircuit_true,
                    'compiled_circuit_qasm': None,
                    'config': {
                        'coupling_map': None,
                        'basis_gates': 'u1,u2,u3,cx,id',
                        'layout': None,
                        'seed': None
                    }
                },
                {
                    'name': 'test_if_false',
                    'compiled_circuit': ucircuit_false,
                    'compiled_circuit_qasm': None,
                    'config': {
                        'coupling_map': None,
                        'basis_gates': 'u1,u2,u3,cx,id',
                        'layout': None,
                        'seed': None
                    }
                }
            ]
        }
        q_job = QuantumJob(qobj, backend=QasmSimulatorPy(), preformatted=True)
        result = QasmSimulatorPy().run(q_job).result()
        result_if_true = result.get_data('test_if_true')
        self.log.info('result_if_true circuit:')
        self.log.info(circuit_if_true.qasm())
        self.log.info('result_if_true=%s', result_if_true)

        result_if_false = result.get_data('test_if_false')
        self.log.info('result_if_false circuit:')
        self.log.info(circuit_if_false.qasm())
        self.log.info('result_if_false=%s', result_if_false)
        self.assertTrue(result_if_true['counts']['111'] == 100)
        self.assertTrue(result_if_false['counts']['001'] == 100)

    @unittest.skipIf(version_info.minor == 5, "Due to gate ordering issues with Python 3.5 \
                                         we have to disable this test until fixed")
    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_py'
        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 %s', data)
        self.log.info('test_teleport: alice %s', alice)
        self.log.info('test_teleport: bob %s', 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 = %s', error)
        self.assertLess(error, 0.05)

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_qasm_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        seed = 88
        shots = 1024
        n_circuits = 100
        min_depth = 1
        max_depth = 40
        min_qubits = 1
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed,
                                              min_qubits=min_qubits,
                                              max_qubits=max_qubits,
                                              min_depth=min_depth,
                                              max_depth=max_depth)
        random_circuits.add_circuits(n_circuits)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_qasm_simulator_py',
                        shots=shots)
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling QasmSimulatorPy -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling QasmSimulatorPy -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_nqubit_speed_grow_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is 10x the number of simulated
        qubits. Also creates a pdf file with this module name showing a
        plot of the results. Compilation is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubit_range_max = 15
        n_qubit_list = range(1, qubit_range_max + 1)
        n_circuits = 10
        shots = 1024
        seed = 88
        max_time = 30  # seconds; timing stops when simulation time exceeds this number
        fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits},' \
                   'shots={shots}'
        backend_list = ['local_qasm_simulator_py', 'local_unitary_simulator_py']
        if shutil.which('qasm_simulator'):
            backend_list.append('local_qasm_simulator_cpp')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable'
                          'not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.25, 0.8, 0.6))
        for _, backend in enumerate(backend_list):
            elapsed_time = np.zeros(len(n_qubit_list))
            if backend == 'local_unitary_simulator_py':
                do_measure = False
            else:
                do_measure = True
            j, timed_out = 0, False
            while j < qubit_range_max and not timed_out:
                n_qubits = n_qubit_list[j]
                random_circuits = RandomQasmGenerator(seed,
                                                      min_qubits=n_qubits,
                                                      max_qubits=n_qubits,
                                                      min_depth=n_qubits * 10,
                                                      max_depth=n_qubits * 10)
                random_circuits.add_circuits(n_circuits, do_measure=do_measure)
                qp = random_circuits.get_program()
                c_names = qp.get_circuit_names()
                qobj = qp.compile(c_names, backend=backend, shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsed_time[j] = stop - start
                if elapsed_time[j] > max_time:
                    timed_out = True
                self.log.info(fmt_str1.format(n_qubits, backend, elapsed_time[j]))
                if backend != 'local_unitary_simulator_py':
                    for name in c_names:
                        log_str = fmt_str2.format(
                            backend, name, len(qp.get_circuit(name)),
                            results.get_data(name))
                        self.log.info(log_str)
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend == 'local_unitary_simulator_py':
                ax.plot(n_qubit_list[:j], elapsed_time[:j], label=backend, marker='o')
            else:
                ax.plot(n_qubit_list[:j], elapsed_time[:j]/shots, label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_grow_depth')
            fig.text(0.1, 0.05,
                     fmt_str3.format(minDepth='10*nQubits', maxDepth='10*nQubits',
                                     nCircuits=n_circuits, shots=shots))
            ax.legend()
        self.pdf.savefig(fig)

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_nqubit_speed_constant_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is fixed at 40. Also creates a pdf file
        with this module name showing a plot of the results. Compilation
        is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubit_range_max = 15
        n_qubit_list = range(1, qubit_range_max + 1)
        max_depth = 40
        min_depth = 40
        n_circuits = 10
        shots = 1024
        seed = 88
        max_time = 30  # seconds; timing stops when simulation time exceeds this number
        fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1},' \
                   'elapsed_time:{2:.2f}'
        fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth},' \
                   'num circuits={nCircuits}, shots={shots}'
        backend_list = ['local_qasm_simulator_py', 'local_unitary_simulator_py']
        if shutil.which('qasm_simulator'):
            backend_list.append('local_qasm_simulator_cpp')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable'
                          'not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.2, 0.8, 0.6))
        for _, backend in enumerate(backend_list):
            elapsedTime = np.zeros(len(n_qubit_list))
            if backend == 'local_unitary_simulator_py':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubit_range_max and not timedOut:
                nQubits = n_qubit_list[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     min_qubits=nQubits,
                                                     max_qubits=nQubits,
                                                     min_depth=min_depth,
                                                     max_depth=max_depth)
                randomCircuits.add_circuits(n_circuits, do_measure=doMeasure)
                qp = randomCircuits.get_program()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames, backend=backend, shots=shots, seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > max_time:
                    timedOut = True
                self.log.info(fmt_str1.format(nQubits, backend, elapsedTime[j]))
                if backend != 'local_unitary_simulator_py':
                    for name in cnames:
                        log_str = fmt_str2.format(
                            backend, name, len(qp.get_circuit(name)),
                            results.get_data(name))
                        self.log.info(log_str)
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend == 'local_unitary_simulator_py':
                ax.plot(n_qubit_list[:j], elapsedTime[:j], label=backend, marker='o')
            else:
                ax.plot(n_qubit_list[:j], elapsedTime[:j]/shots, label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_constant_depth')
            fig.text(0.1, 0.05,
                     fmt_str3.format(minDepth=min_depth, maxDepth=max_depth,
                                     nCircuits=n_circuits, shots=shots))
            ax.legend()
        self.pdf.savefig(fig)
class UnitarySimulatorSympyTest(QiskitTestCase):
    """Test local unitary simulator sympy."""

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
        self.qp = QuantumProgram()

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [op for op in circuit['operations']
                                 if op['name'] != 'measure']
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id': 'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_sympy_unitary_simulator'
            },
            'circuits': [
                {
                    'name': 'test',
                    'compiled_circuit': circuit,
                    'compiled_circuit_qasm': self.qp.get_qasm('example'),
                    'config': {
                        'coupling_map': None,
                        'basis_gates': None,
                        'layout': None,
                        'seed': None
                    }
                }
            ]
        }

        q_job = QuantumJob(qobj,
                           backend=UnitarySimulatorSympy(),
                           preformatted=True)

        result = UnitarySimulatorSympy().run(q_job).result()
        actual = result.get_data('test')['unitary']

        self.assertEqual(actual[0][0], sqrt(2)/2)
        self.assertEqual(actual[0][1], sqrt(2)/2)
        self.assertEqual(actual[0][2], 0)
        self.assertEqual(actual[0][3], 0)
        self.assertEqual(actual[1][0], 0)
        self.assertEqual(actual[1][1], 0)
        self.assertEqual(actual[1][2], sqrt(2)/2)
        self.assertEqual(actual[1][3], -sqrt(2)/2)
        self.assertEqual(actual[2][0], 0)
        self.assertEqual(actual[2][1], 0)
        self.assertEqual(actual[2][2], sqrt(2)/2)
        self.assertEqual(actual[2][3], sqrt(2)/2)
        self.assertEqual(actual[3][0], sqrt(2)/2)
        self.assertEqual(actual[3][1], -sqrt(2)/2)
        self.assertEqual(actual[3][2], 0)
        self.assertEqual(actual[3][3], 0)
                                 [quantum_r[x] for x in range(4)])
composite_gate_2._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_2)
circuit.cx(quantum_r[0], quantum_r[1])

circuit.h(quantum_r[0])

composite_gate_3 = CompositeGate("composite3", [],
                                 [quantum_r[x] for x in range(4)])
composite_gate_3._attach(CnotGate(quantum_r[0], quantum_r[1]))
composite_gate_3._attach(CnotGate(quantum_r[0], quantum_r[2]))
circuit._attach(composite_gate_3)

circuit.h(quantum_r[0])

composite_gate_4 = CompositeGate("composite4", [],
                                 [quantum_r[x] for x in range(4)])
composite_gate_4._attach(CnotGate(quantum_r[0], quantum_r[1]))
composite_gate_4._attach(RXGate(0, quantum_r[0]))
composite_gate_4._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_4)

print("Removed Zero Rotations: " + str(circuit.remove_zero_rotations()))

print("Removed Double CNOTs: " + str(circuit.remove_double_cnots_once()))

# QASM from a program

QASM_source = Q_program.get_qasm("Circuit")
print(QASM_source)
class LocalUnitarySimulatorTest(QiskitTestCase):
    """Test local unitary simulator."""

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [op for op in circuit['operations']
                                 if op['name'] != 'measure']
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id': 'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_unitary_simulator_py'
            },
            'circuits': [
                {
                    'name': 'test',
                    'compiled_circuit': circuit,
                    'compiled_circuit_qasm': self.qp.get_qasm('example'),
                    'config': {
                        'coupling_map': None,
                        'basis_gates': None,
                        'layout': None,
                        'seed': None
                    }
                }
            ]
        }
        # numpy.savetxt currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr,
        # delimiter=',')
        expected = np.loadtxt(self._get_resource_path('example_unitary_matrix.dat'),
                              dtype='complex', delimiter=',')
        q_job = QuantumJob(qobj,
                           backend=UnitarySimulatorPy(),
                           preformatted=True)

        result = UnitarySimulatorPy().run(q_job).result()
        self.assertTrue(np.allclose(result.get_unitary('test'),
                                    expected,
                                    rtol=1e-3))

    def test_two_unitary_simulator(self):
        """test running two circuits

        This test is similar to one in test_quantumprogram but doesn't use
        multiprocessing.
        """
        qr = QuantumRegister(2)
        cr = ClassicalRegister(1)
        qc1 = QuantumCircuit(qr, cr)
        qc2 = QuantumCircuit(qr, cr)
        qc1.h(qr)
        qc2.cx(qr[0], qr[1])
        backend = UnitarySimulatorPy()
        qobj = compile([qc1, qc2], backend=backend)
        job = backend.run(QuantumJob(qobj, backend=backend, preformatted=True))
        unitary1 = job.result().get_unitary(qc1)
        unitary2 = job.result().get_unitary(qc2)
        unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5],
                                 [0.5, 0.5, -0.5, -0.5],
                                 [0.5, -0.5, -0.5, 0.5]])
        unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1],
                                 [0., 0, 1, 0], [0, 1, 0, 0]])
        norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1))
        norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2))
        self.assertAlmostEqual(norm1, 4)
        self.assertAlmostEqual(norm2, 4)

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        n_circuits = 100
        max_depth = 40
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed=self.seed,
                                              max_depth=max_depth,
                                              max_qubits=max_qubits)
        random_circuits.add_circuits(n_circuits, do_measure=False)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend=UnitarySimulatorPy())
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling UnitarySimulatorPy -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling UnitarySimulatorPy -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
                                 [quantum_r[x] for x in range(4)])
composite_gate_2._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_2)
circuit.cx(quantum_r[0], quantum_r[1])

circuit.h(quantum_r[0])

composite_gate_3 = CompositeGate("composite3", [],
                                 [quantum_r[x] for x in range(4)])
composite_gate_3._attach(CnotGate(quantum_r[0], quantum_r[1]))
composite_gate_3._attach(CnotGate(quantum_r[0], quantum_r[2]))
circuit._attach(composite_gate_3)

circuit.h(quantum_r[0])

composite_gate_4 = CompositeGate("composite4", [],
                                 [quantum_r[x] for x in range(4)])
composite_gate_4._attach(CnotGate(quantum_r[0], quantum_r[1]))
composite_gate_4._attach(RXGate(0, quantum_r[0]))
composite_gate_4._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_4)

print("Removed Zero Rotations: " + str(circuit.remove_zero_rotations()))

print("Removed Double CNOTs: " + str(circuit.remove_double_cnots_once()))

# QASM from a program

QASM_source = Q_program.get_qasm("Circuit")
print(QASM_source)
Example #41
0
    qc.h(x0)
    qc.h(x1)
    qc.x(x0)
    qc.x(x1)
    qc.h(x1)
    qc.cx(x0, x1)
    qc.h(x1)
    qc.x(x0)
    qc.x(x1)
    qc.h(x0)
    qc.h(x1)
    qc.h(q)


testtiffoli(tiffoli)

b0 = qr[0]
b1 = qr[2]
b2 = qr[1]
qc.x(b2)  #put b2 in state |1>
qc.h(b0)  #put b0 in (|0>+|1>)/sqrt(2)
qc.h(b1)  #put b1 in (|0>+|1>)/sqrt(2)
qc.h(b2)  #put b2 in state (|0>-|1>)/sqrt(2)
for i in range(1):  #apply the oracle/grover operator in a loop
    grover(tiffoli2, qc, b0, b1, b2)
qc.measure(qr, cr)
result = Q.execute(["andgate"], backend="local_qasm_simulator", shots=1000)
print(result)
print(result.get_data("andgate"))
print(Q.get_qasm("andgate"))
    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr])
        circuit_if_true.x(qr[0])
        circuit_if_true.x(qr[1])
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.x(qr[2]).c_if(cr, 0x3)
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.measure(qr[2], cr[2])
        circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr])
        circuit_if_false.x(qr[0])
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.x(qr[2]).c_if(cr, 0x3)
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_true = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_false')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_false = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        qobj = {'id': 'test_if_qobj',
                'config': {
                    'max_credits': 3,
                    'shots': shots,
                    'backend': 'local_qasm_simulator',
                },
                'circuits': [
                    {
                        'name': 'test_if_true',
                        'compiled_circuit': ucircuit_true,
                        'compiled_circuit_qasm': None,
                        'config': {'coupling_map': None,
                                   'basis_gates': 'u1,u2,u3,cx,id',
                                   'layout': None,
                                   'seed': None
                                   }
                    },
                    {
                        'name': 'test_if_false',
                        'compiled_circuit': ucircuit_false,
                        'compiled_circuit_qasm': None,
                        'config': {'coupling_map': None,
                                   'basis_gates': 'u1,u2,u3,cx,id',
                                   'layout': None,
                                   'seed': None
                                   }
                    }
                ]
        }
        q_job = QuantumJob(qobj, preformatted=True)
        result = QasmSimulator().run(q_job)
        result_if_true = result.get_data('test_if_true')
        self.log.info('result_if_true circuit:')
        self.log.info(circuit_if_true.qasm())
        self.log.info('result_if_true={0}'.format(result_if_true))

        result_if_false = result.get_data('test_if_false')        
        self.log.info('result_if_false circuit:')
        self.log.info(circuit_if_false.qasm())
        self.log.info('result_if_false={0}'.format(result_if_false))
        self.assertTrue(result_if_true['counts']['111'] == 100)
        self.assertTrue(result_if_false['counts']['001'] == 100)
Example #43
0
# Create a Quantum Circuit
qc = qp.create_circuit('helloworld', [qbyte], [cbyte])

# Add a H gate on qubit 0, putting this qubit in superposition.
#qc.h(q[1])
#qc.h(q[2])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
#qc.cx(q[0], q[1])

# Measure
for i in range(0, 8):
    qc.measure(qbyte[i], cbyte[i])

print(qp.get_qasm('helloworld'))
"""
# See a list of available local simulators
print("Local backends: ", available_backends({'local': True}))

# Compile and run the Quantum circuit on a simulator backend
job_sim = execute(qc, "local_qasm_simulator")
sim_result = job_sim.result()

# Show the results
print("simulation: ", sim_result)
print(sim_result.get_counts(qc))

# Draw the circuit
#circuit_drawer(qc, filename='./test_circuit.png')
#diagram = circuit_drawer(qc)
Example #44
0
    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr])
        circuit_if_true.x(qr[0])
        circuit_if_true.x(qr[1])
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.x(qr[2]).c_if(cr, 0x3)
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.measure(qr[2], cr[2])
        circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr])
        circuit_if_false.x(qr[0])
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.x(qr[2]).c_if(cr, 0x3)
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_true = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_false')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_false = unroller.execute()
        qobj = {
            'id':
            'test_if_qobj',
            'config': {
                'max_credits': 3,
                'shots': shots,
                'backend_name': 'local_qasm_simulator_py',
            },
            'circuits': [{
                'name': 'test_if_true',
                'compiled_circuit': ucircuit_true,
                'compiled_circuit_qasm': None,
                'config': {
                    'coupling_map': None,
                    'basis_gates': 'u1,u2,u3,cx,id',
                    'layout': None,
                    'seed': None
                }
            }, {
                'name': 'test_if_false',
                'compiled_circuit': ucircuit_false,
                'compiled_circuit_qasm': None,
                'config': {
                    'coupling_map': None,
                    'basis_gates': 'u1,u2,u3,cx,id',
                    'layout': None,
                    'seed': None
                }
            }]
        }
        q_job = QuantumJob(qobj, backend=QasmSimulatorPy(), preformatted=True)
        result = QasmSimulatorPy().run(q_job).result()
        result_if_true = result.get_data('test_if_true')
        self.log.info('result_if_true circuit:')
        self.log.info(circuit_if_true.qasm())
        self.log.info('result_if_true=%s', result_if_true)

        result_if_false = result.get_data('test_if_false')
        self.log.info('result_if_false circuit:')
        self.log.info(circuit_if_false.qasm())
        self.log.info('result_if_false=%s', result_if_false)
        self.assertTrue(result_if_true['counts']['111'] == 100)
        self.assertTrue(result_if_false['counts']['001'] == 100)
Example #45
0
local_backends()

backend = 'local_qasm_simulator'
qp = QuantumProgram()
qp.set_api(Qconfig.APItoken, Qconfig.config['url'])
qr = qp.create_quantum_register('qr', 2)
cr = qp.create_classical_register('cr', 2)
qc = qp.create_circuit('Bell', [qr], [cr])

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())
Example #46
0
class TestLocalQasmSimulatorPy(QiskitTestCase):
    """Test local_qasm_simulator_py."""
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        if do_profiling:
            cls.pdf = PdfPages(cls.moduleName + '.pdf')

    @classmethod
    def tearDownClass(cls):
        if do_profiling:
            cls.pdf.close()

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        circuit_config = {
            'coupling_map': None,
            'basis_gates': 'u1,u2,u3,cx,id',
            'layout': None,
            'seed': self.seed
        }
        resources = {'max_credits': 3}
        self.qobj = {
            'id':
            'test_sim_single_shot',
            'config': {
                'max_credits': resources['max_credits'],
                'shots': 1024,
                'backend_name': 'local_qasm_simulator_py',
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': None,
                'config': circuit_config
            }]
        }
        self.q_job = QuantumJob(self.qobj,
                                backend=QasmSimulatorPy(),
                                circuit_config=circuit_config,
                                seed=self.seed,
                                resources=resources,
                                preformatted=True)

    def tearDown(self):
        pass

    def test_qasm_simulator_single_shot(self):
        """Test single shot run."""
        shots = 1
        self.qobj['config']['shots'] = shots
        result = QasmSimulatorPy().run(self.q_job).result()
        self.assertEqual(result.get_status(), 'COMPLETED')

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        result = QasmSimulatorPy().run(self.q_job).result()
        shots = 1024
        threshold = 0.04 * shots
        counts = result.get_counts('test')
        target = {
            '100 100': shots / 8,
            '011 011': shots / 8,
            '101 101': shots / 8,
            '111 111': shots / 8,
            '000 000': shots / 8,
            '010 010': shots / 8,
            '110 110': shots / 8,
            '001 001': shots / 8
        }
        self.assertDictAlmostEqual(counts, target, threshold)

    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr])
        circuit_if_true.x(qr[0])
        circuit_if_true.x(qr[1])
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.x(qr[2]).c_if(cr, 0x3)
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.measure(qr[2], cr[2])
        circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr])
        circuit_if_false.x(qr[0])
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.x(qr[2]).c_if(cr, 0x3)
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_true = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_false')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_false = unroller.execute()
        qobj = {
            'id':
            'test_if_qobj',
            'config': {
                'max_credits': 3,
                'shots': shots,
                'backend_name': 'local_qasm_simulator_py',
            },
            'circuits': [{
                'name': 'test_if_true',
                'compiled_circuit': ucircuit_true,
                'compiled_circuit_qasm': None,
                'config': {
                    'coupling_map': None,
                    'basis_gates': 'u1,u2,u3,cx,id',
                    'layout': None,
                    'seed': None
                }
            }, {
                'name': 'test_if_false',
                'compiled_circuit': ucircuit_false,
                'compiled_circuit_qasm': None,
                'config': {
                    'coupling_map': None,
                    'basis_gates': 'u1,u2,u3,cx,id',
                    'layout': None,
                    'seed': None
                }
            }]
        }
        q_job = QuantumJob(qobj, backend=QasmSimulatorPy(), preformatted=True)
        result = QasmSimulatorPy().run(q_job).result()
        result_if_true = result.get_data('test_if_true')
        self.log.info('result_if_true circuit:')
        self.log.info(circuit_if_true.qasm())
        self.log.info('result_if_true=%s', result_if_true)

        result_if_false = result.get_data('test_if_false')
        self.log.info('result_if_false circuit:')
        self.log.info(circuit_if_false.qasm())
        self.log.info('result_if_false=%s', result_if_false)
        self.assertTrue(result_if_true['counts']['111'] == 100)
        self.assertTrue(result_if_false['counts']['001'] == 100)

    @unittest.skipIf(version_info.minor == 5,
                     "Due to gate ordering issues with Python 3.5 \
                                         we have to disable this test until fixed"
                     )
    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_py'
        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 %s', data)
        self.log.info('test_teleport: alice %s', alice)
        self.log.info('test_teleport: bob %s', 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 = %s', error)
        self.assertLess(error, 0.05)

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_qasm_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        seed = 88
        shots = 1024
        n_circuits = 100
        min_depth = 1
        max_depth = 40
        min_qubits = 1
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed,
                                              min_qubits=min_qubits,
                                              max_qubits=max_qubits,
                                              min_depth=min_depth,
                                              max_depth=max_depth)
        random_circuits.add_circuits(n_circuits)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_qasm_simulator_py',
                        shots=shots)
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling QasmSimulatorPy -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling QasmSimulatorPy -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_nqubit_speed_grow_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is 10x the number of simulated
        qubits. Also creates a pdf file with this module name showing a
        plot of the results. Compilation is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubit_range_max = 15
        n_qubit_list = range(1, qubit_range_max + 1)
        n_circuits = 10
        shots = 1024
        seed = 88
        max_time = 30  # seconds; timing stops when simulation time exceeds this number
        fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits},' \
                   'shots={shots}'
        backend_list = [
            'local_qasm_simulator_py', 'local_unitary_simulator_py'
        ]
        if shutil.which('qasm_simulator'):
            backend_list.append('local_qasm_simulator_cpp')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable'
                          'not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.25, 0.8, 0.6))
        for _, backend in enumerate(backend_list):
            elapsed_time = np.zeros(len(n_qubit_list))
            if backend == 'local_unitary_simulator_py':
                do_measure = False
            else:
                do_measure = True
            j, timed_out = 0, False
            while j < qubit_range_max and not timed_out:
                n_qubits = n_qubit_list[j]
                random_circuits = RandomQasmGenerator(seed,
                                                      min_qubits=n_qubits,
                                                      max_qubits=n_qubits,
                                                      min_depth=n_qubits * 10,
                                                      max_depth=n_qubits * 10)
                random_circuits.add_circuits(n_circuits, do_measure=do_measure)
                qp = random_circuits.get_program()
                c_names = qp.get_circuit_names()
                qobj = qp.compile(c_names,
                                  backend=backend,
                                  shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsed_time[j] = stop - start
                if elapsed_time[j] > max_time:
                    timed_out = True
                self.log.info(
                    fmt_str1.format(n_qubits, backend, elapsed_time[j]))
                if backend != 'local_unitary_simulator_py':
                    for name in c_names:
                        log_str = fmt_str2.format(backend, name,
                                                  len(qp.get_circuit(name)),
                                                  results.get_data(name))
                        self.log.info(log_str)
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend == 'local_unitary_simulator_py':
                ax.plot(n_qubit_list[:j],
                        elapsed_time[:j],
                        label=backend,
                        marker='o')
            else:
                ax.plot(n_qubit_list[:j],
                        elapsed_time[:j] / shots,
                        label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_grow_depth')
            fig.text(
                0.1, 0.05,
                fmt_str3.format(minDepth='10*nQubits',
                                maxDepth='10*nQubits',
                                nCircuits=n_circuits,
                                shots=shots))
            ax.legend()
        self.pdf.savefig(fig)

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_nqubit_speed_constant_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is fixed at 40. Also creates a pdf file
        with this module name showing a plot of the results. Compilation
        is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubit_range_max = 15
        n_qubit_list = range(1, qubit_range_max + 1)
        max_depth = 40
        min_depth = 40
        n_circuits = 10
        shots = 1024
        seed = 88
        max_time = 30  # seconds; timing stops when simulation time exceeds this number
        fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1},' \
                   'elapsed_time:{2:.2f}'
        fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth},' \
                   'num circuits={nCircuits}, shots={shots}'
        backend_list = [
            'local_qasm_simulator_py', 'local_unitary_simulator_py'
        ]
        if shutil.which('qasm_simulator'):
            backend_list.append('local_qasm_simulator_cpp')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable'
                          'not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.2, 0.8, 0.6))
        for _, backend in enumerate(backend_list):
            elapsedTime = np.zeros(len(n_qubit_list))
            if backend == 'local_unitary_simulator_py':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubit_range_max and not timedOut:
                nQubits = n_qubit_list[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     min_qubits=nQubits,
                                                     max_qubits=nQubits,
                                                     min_depth=min_depth,
                                                     max_depth=max_depth)
                randomCircuits.add_circuits(n_circuits, do_measure=doMeasure)
                qp = randomCircuits.get_program()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames,
                                  backend=backend,
                                  shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > max_time:
                    timedOut = True
                self.log.info(fmt_str1.format(nQubits, backend,
                                              elapsedTime[j]))
                if backend != 'local_unitary_simulator_py':
                    for name in cnames:
                        log_str = fmt_str2.format(backend, name,
                                                  len(qp.get_circuit(name)),
                                                  results.get_data(name))
                        self.log.info(log_str)
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend == 'local_unitary_simulator_py':
                ax.plot(n_qubit_list[:j],
                        elapsedTime[:j],
                        label=backend,
                        marker='o')
            else:
                ax.plot(n_qubit_list[:j],
                        elapsedTime[:j] / shots,
                        label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_constant_depth')
            fig.text(
                0.1, 0.05,
                fmt_str3.format(minDepth=min_depth,
                                maxDepth=max_depth,
                                nCircuits=n_circuits,
                                shots=shots))
            ax.legend()
        self.pdf.savefig(fig)
class LocalUnitarySimulatorTest(unittest.TestCase):
    """Test local unitary simulator."""
    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.log = logging.getLogger(__name__)
        cls.log.setLevel(logging.INFO)
        logFileName = cls.moduleName + '.log'
        handler = logging.FileHandler(logFileName)
        handler.setLevel(logging.INFO)
        log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
                   ' %(message)s'.format(cls.__name__))
        formatter = logging.Formatter(log_fmt)
        handler.setFormatter(formatter)
        cls.log.addHandler(handler)

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.modulePath = os.path.dirname(__file__)
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # if we want to manipulate the circuit, we have to convert it to a dict
        circuit = json.loads(circuit.decode())
        #strip measurements from circuit to avoid warnings
        circuit['operations'] = [
            op for op in circuit['operations'] if op['name'] != 'measure'
        ]
        # the simulator is expecting a JSON format, so we need to convert it back to JSON
        job = {'compiled_circuit': json.dumps(circuit).encode()}
        # numpy savetxt is currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, delimiter=',')
        expected = np.loadtxt(os.path.join(self.modulePath,
                                           'example_unitary_matrix.dat'),
                              dtype='complex',
                              delimiter=',')
        result = UnitarySimulator(job).run()
        self.assertTrue(
            np.allclose(result['data']['unitary'], expected, rtol=1e-3))

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        nCircuits = 100
        maxDepth = 40
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed=self.seed,
                                             maxDepth=maxDepth,
                                             maxQubits=maxQubits)
        randomCircuits.add_circuits(nCircuits, doMeasure=False)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_unitary_simulator')
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling UnitarySimulator -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling UnitarySimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
Example #48
0
    1 / math.sqrt(8) * complex(0, 1),
    0,
    0,
    0,
    0,
    1 / math.sqrt(4) * complex(1, 0),
    1 / math.sqrt(8) * complex(1, 0)]

circuit.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]])

circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit.measure(qr[3], cr[3])

QASM_source = Q_program.get_qasm("initializer_circ")

print(QASM_source)
plot_circuit(circuit)

###############################################################
# Set the backend name and coupling map.
###############################################################
device = 'ibmqx2'
coupling_map = {0: [1, 2],
                1: [2],
                2: [],
                3: [2, 4],
                4: [2]}
circuits = ['initializer_circ']
shots = 1024
Example #49
0
class LocalUnitarySimulatorTest(QiskitTestCase):
    """Test local unitary simulator."""
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [
            op for op in circuit['operations'] if op['name'] != 'measure'
        ]
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id':
            'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_unitary_simulator_py'
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': self.qp.get_qasm('example'),
                'config': {
                    'coupling_map': None,
                    'basis_gates': None,
                    'layout': None,
                    'seed': None
                }
            }]
        }
        # numpy.savetxt currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr,
        # delimiter=',')
        expected = np.loadtxt(
            self._get_resource_path('example_unitary_matrix.dat'),
            dtype='complex',
            delimiter=',')
        q_job = QuantumJob(qobj,
                           backend=UnitarySimulatorPy(),
                           preformatted=True)

        result = UnitarySimulatorPy().run(q_job).result()
        self.assertTrue(
            np.allclose(result.get_unitary('test'), expected, rtol=1e-3))

    def test_two_unitary_simulator(self):
        """test running two circuits

        This test is similar to one in test_quantumprogram but doesn't use
        multiprocessing.
        """
        qr = QuantumRegister(2)
        cr = ClassicalRegister(1)
        qc1 = QuantumCircuit(qr, cr)
        qc2 = QuantumCircuit(qr, cr)
        qc1.h(qr)
        qc2.cx(qr[0], qr[1])
        backend = UnitarySimulatorPy()
        qobj = compile([qc1, qc2], backend=backend)
        job = backend.run(QuantumJob(qobj, backend=backend, preformatted=True))
        unitary1 = job.result().get_unitary(qc1)
        unitary2 = job.result().get_unitary(qc2)
        unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5],
                                 [0.5, 0.5, -0.5, -0.5],
                                 [0.5, -0.5, -0.5, 0.5]])
        unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0., 0, 1, 0],
                                 [0, 1, 0, 0]])
        norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1))
        norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2))
        self.assertAlmostEqual(norm1, 4)
        self.assertAlmostEqual(norm2, 4)

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        n_circuits = 100
        max_depth = 40
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed=self.seed,
                                              max_depth=max_depth,
                                              max_qubits=max_qubits)
        random_circuits.add_circuits(n_circuits, do_measure=False)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend=UnitarySimulatorPy())
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling UnitarySimulatorPy -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling UnitarySimulatorPy -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
desired_vector = [
    1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0,
    0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0),
    1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0,
    1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0)
]

circuit.initialize("QInit", desired_vector, [qr[0], qr[1], qr[2], qr[3]])

circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit.measure(qr[3], cr[3])

QASM_source = Q_program.get_qasm("initializer_circ")

print(QASM_source)

###############################################################
# Set the backend name and coupling map.
###############################################################
device = 'ibmqx2'
coupling_map = {0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4: [2]}
circuits = ['initializer_circ']
shots = 1024

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