def test_reused_custom_gate_parameter(self):
        """Test reused custom gate with parameter."""
        parameter_a = Parameter("a")

        custom = QuantumCircuit(1)
        custom.rx(parameter_a, 0)

        circuit = QuantumCircuit(1)
        circuit.append(
            custom.bind_parameters({
                parameter_a: 0.5
            }).to_gate(), [0])
        circuit.append(custom.bind_parameters({parameter_a: 1}).to_gate(), [0])

        circuit_name_0 = circuit.data[0][0].definition.name
        circuit_name_1 = circuit.data[1][0].definition.name

        expected_qasm = "\n".join([
            "OPENQASM 3;",
            'include "stdgates.inc";',
            f"gate {circuit_name_0} q_0 {{",
            "  rx(0.5) q_0;",
            "}",
            f"gate {circuit_name_1} q_0 {{",
            "  rx(1) q_0;",
            "}",
            "qubit[1] _q;",
            "let q = _q[0];",
            f"{circuit_name_0} q[0];",
            f"{circuit_name_1} q[0];",
            "",
        ])
        self.assertEqual(Exporter().dumps(circuit), expected_qasm)
Beispiel #2
0
 def test_fix_variable(self):
     """Test setting a varaible to a constant value"""
     theta = Parameter('θ')
     qr = QuantumRegister(1)
     qc = QuantumCircuit(qr)
     qc.rx(theta, qr)
     qc.u3(0, theta, 0, qr)
     bqc = qc.bind_parameters({theta: 0.5})
     self.assertEqual(bqc.data[0][0].params[0], 0.5)
     self.assertEqual(bqc.data[1][0].params[1], 0.5)
     bqc = qc.bind_parameters({theta: 0.6})
     self.assertEqual(bqc.data[0][0].params[0], 0.6)
     self.assertEqual(bqc.data[1][0].params[1], 0.6)
    def test_unbound_parameters_in_rzx_template(self):
        """
        Test that rzx template ('zz2') functions correctly for a simple
        circuit with an unbound ParameterExpression. This uses the same
        Parameter (theta) as the template, so this also checks that template
        substitution handle this correctly.
        """

        theta = Parameter("ϴ")
        circuit_in = QuantumCircuit(2)
        circuit_in.cx(0, 1)
        circuit_in.p(2 * theta, 1)
        circuit_in.cx(0, 1)

        pass_ = TemplateOptimization(**rzx_templates(["zz2"]))
        circuit_out = PassManager(pass_).run(circuit_in)

        # these are NOT equal if template optimization works
        self.assertNotEqual(circuit_in, circuit_out)

        # however these are equivalent if the operators are the same
        theta_set = 0.42
        self.assertTrue(
            Operator(circuit_in.bind_parameters({theta: theta_set})).equiv(
                circuit_out.bind_parameters({theta: theta_set})))
Beispiel #4
0
 def PerformManySTsteps(self,STEPS=200,dt=1.7/200):
     '''
     Quantum circuit that performs time evolution from t=0 to t=simul_time
     using STEPS.
     '''
     ## Define parameter values for gates
     ## Values for theta parameters
     th1 = 2*self.ExchangeIntegrals[0]*dt
     th2 = 2*self.ExchangeIntegrals[1]*dt
     th3 = 2*self.ExchangeIntegrals[2]*dt
     ## Values for alpha parameters
     aH = 2*np.sqrt(sum(comps**2 for comps in self.ExternalField))*dt
     ## Define dictionary for parameter substitution
     params = {
         theta1:th1,
         theta2:th2,
         theta3:th3,
         alphaH:aH,
     }
     ## Create spin chain
     spinChain = QuantumRegister(self.num_spins,name='s')
     ## Create measurement register
     measureReg = ClassicalRegister(self.num_spins,name='b')
     ## Create quantum circuit
     qc_MST = QuantumCircuit(spinChain,measureReg)
     ## Append ST steps to circuit
     for _ in range(STEPS):
         qc_MST.append(self.SuzukiTrotter(spinChain),spinChain)
     ## Perform measurement for further simulation
     qc_MST.measure(spinChain,measureReg)
     ## Return circuit with binded parameters
     try:
         return qc_MST.bind_parameters(params)
     except exceptions.CircuitError:
         return qc_MST
    def test_from_qasm_str_custom_gate4(self):
        """Test load custom gates (parameterized)
        See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
        """
        qasm_string = """OPENQASM 2.0;
                         include "qelib1.inc";
                         gate my_gate(phi,lambda) q {u(1.5707963267948966,phi,lambda) q;}
                         qreg qr[1];
                         my_gate(pi, pi) qr[0];"""
        circuit = QuantumCircuit.from_qasm_str(qasm_string)

        my_gate_circuit = QuantumCircuit(1, name="my_gate")
        phi = Parameter("phi")
        lam = Parameter("lambda")
        my_gate_circuit.u(1.5707963267948966, phi, lam, 0)
        my_gate = my_gate_circuit.to_gate()

        qr = QuantumRegister(1, name="qr")
        expected = QuantumCircuit(qr, name="circuit")
        expected.append(my_gate, [qr[0]])
        expected = expected.bind_parameters({
            phi: 3.141592653589793,
            lam: 3.141592653589793
        })

        self.assertEqualUnroll("u", circuit, expected)
Beispiel #6
0
    def test_decompose_propagates_deeply_bound_parameters(self, target_type):
        """Verify bind-before-decompose preserves deeply bound values."""
        theta = Parameter('th')
        qc1 = QuantumCircuit(1)
        qc1.rx(theta, 0)

        if target_type == 'gate':
            inst = qc1.to_gate()
        elif target_type == 'instruction':
            inst = qc1.to_instruction()

        qc2 = QuantumCircuit(1)
        qc2.append(inst, [0])

        if target_type == 'gate':
            inst = qc2.to_gate()
        elif target_type == 'instruction':
            inst = qc2.to_instruction()

        qc3 = QuantumCircuit(1)
        qc3.append(inst, [0])

        bound_qc3 = qc3.bind_parameters({theta: 0.5})

        self.assertEqual(qc3.parameters, {theta})
        self.assertEqual(bound_qc3.parameters, set())

        decomposed_qc3 = bound_qc3.decompose()
        deep_decomposed_qc3 = decomposed_qc3.decompose()

        expected_qc3 = QuantumCircuit(1)
        expected_qc3.rx(0.5, 0)

        self.assertEqual(deep_decomposed_qc3.parameters, set())
        self.assertEqual(deep_decomposed_qc3, expected_qc3)
Beispiel #7
0
    def test_big_gates(self):
        """Test large gates with params"""
        qr = QuantumRegister(6, "q")
        circuit = QuantumCircuit(qr)
        circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])

        desired_vector = [
            1 / math.sqrt(16) * complex(0, 1),
            1 / math.sqrt(8) * complex(1, 0),
            1 / math.sqrt(16) * complex(1, 1),
            0,
            0,
            1 / math.sqrt(8) * complex(1, 2),
            1 / math.sqrt(16) * complex(1, 0),
            0,
        ]

        circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
        circuit.unitary([[1, 0], [0, 1]], [qr[0]])
        matrix = np.zeros((4, 4))
        theta = Parameter("theta")
        circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
        circuit = circuit.bind_parameters({theta: 1})
        circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])

        self.circuit_drawer(circuit, filename="big_gates.png")
    def test_custom_gate_with_bound_parameter(self):
        """Test custom gate with bound parameter."""
        parameter_a = Parameter("a")

        custom = QuantumCircuit(1)
        custom.rx(parameter_a, 0)
        custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate()
        custom_gate.name = "custom"

        circuit = QuantumCircuit(1)
        circuit.append(custom_gate, [0])

        expected_qasm = "\n".join(
            [
                "OPENQASM 3;",
                'include "stdgates.inc";',
                "gate custom q_0 {",
                "  rx(0.5) q_0;",
                "}",
                "qubit[1] _q;",
                "let q = _q[0];",
                "custom q[0];",
                "",
            ]
        )
        self.assertEqual(Exporter().dumps(circuit), expected_qasm)
Beispiel #9
0
    def test_from_qasm_str_custom_gate6(self):
        """ Test load custom gates (parameters used in expressions)
        See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-591668924
        """
        qasm_string = """OPENQASM 2.0;
                         include "qelib1.inc";
                         gate my_gate(phi,lambda) q
                           {u2(phi+pi,lambda/2) q;}  // parameters used in expressions
                         qreg qr[1];
                         my_gate(pi, pi) qr[0];"""
        circuit = QuantumCircuit.from_qasm_str(qasm_string)

        my_gate_circuit = QuantumCircuit(1, name='my_gate')
        phi = Parameter('phi')
        lam = Parameter('lambda')
        my_gate_circuit.u2(phi + 3.141592653589793, lam / 2, 0)
        my_gate = my_gate_circuit.to_gate()

        qr = QuantumRegister(1, name='qr')
        expected = QuantumCircuit(qr, name='circuit')
        expected.append(my_gate, [qr[0]])
        expected = expected.bind_parameters({
            phi: 3.141592653589793,
            lam: 3.141592653589793
        })

        self.assertEqualUnroll('u2', circuit, expected)
    def test_executing_parameterized_instruction_bound_early(self, target_type):
        """Verify bind-before-execute preserves bound values."""
        # ref: https://github.com/Qiskit/qiskit-terra/issues/2482

        theta = Parameter('theta')

        sub_qc = QuantumCircuit(2)
        sub_qc.h(0)
        sub_qc.cx(0, 1)
        sub_qc.rz(theta, [0, 1])
        sub_qc.cx(0, 1)
        sub_qc.h(0)

        if target_type == 'gate':
            sub_inst = sub_qc.to_gate()
        elif target_type == 'instruction':
            sub_inst = sub_qc.to_instruction()

        unbound_qc = QuantumCircuit(2, 1)
        unbound_qc.append(sub_inst, [0, 1], [])
        unbound_qc.measure(0, 0)

        bound_qc = unbound_qc.bind_parameters({theta: numpy.pi/2})

        shots = 1024
        job = execute(bound_qc, backend=BasicAer.get_backend('qasm_simulator'), shots=shots)
        self.assertDictAlmostEqual(job.result().get_counts(), {'1': shots}, 0.05 * shots)
Beispiel #11
0
    def test_from_qasm_str_custom_gate5(self):
        """ Test load custom gates (parametrized, with biop and constant)
        See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250
        """
        qasm_string = """OPENQASM 2.0;
                         include "qelib1.inc";
                         gate my_gate(phi,lambda) q {u3(pi/2,phi,lambda) q;} // biop with pi
                         qreg qr[1];
                         my_gate(pi, pi) qr[0];"""
        circuit = QuantumCircuit.from_qasm_str(qasm_string)

        my_gate_circuit = QuantumCircuit(1, name='my_gate')
        phi = Parameter('phi')
        lam = Parameter('lambda')
        my_gate_circuit.u3(1.5707963267948966, phi, lam, 0)
        my_gate = my_gate_circuit.to_gate()

        qr = QuantumRegister(1, name='qr')
        expected = QuantumCircuit(qr, name='circuit')
        expected.append(my_gate, [qr[0]])
        expected = expected.bind_parameters({
            phi: 3.141592653589793,
            lam: 3.141592653589793
        })

        self.assertEqualUnroll('u3', circuit, expected)
Beispiel #12
0
    def test_decompose_propagates_bound_parameters(self, target_type):
        """Verify bind-before-decompose preserves bound values."""
        # ref: https://github.com/Qiskit/qiskit-terra/issues/2482
        theta = Parameter('th')
        qc = QuantumCircuit(1)
        qc.rx(theta, 0)

        if target_type == 'gate':
            inst = qc.to_gate()
        elif target_type == 'instruction':
            inst = qc.to_instruction()

        qc2 = QuantumCircuit(1)
        qc2.append(inst, [0])

        bound_qc2 = qc2.bind_parameters({theta: 0.5})

        self.assertEqual(qc2.parameters, {theta})
        self.assertEqual(bound_qc2.parameters, set())

        decomposed_qc2 = bound_qc2.decompose()

        expected_qc2 = QuantumCircuit(1)
        expected_qc2.rx(0.5, 0)

        self.assertEqual(decomposed_qc2.parameters, set())
        self.assertEqual(decomposed_qc2, expected_qc2)
Beispiel #13
0
def _check_circuit_and_bind_parameters(quantum_circuit: QuantumCircuit,
                                       params: dict,
                                       diff_params: dict) -> QuantumCircuit:
    """Utility function for checking for a valid quantum circuit and then binding parameters.

    Args:
        quantum_circuit (QuantumCircuit): the quantum circuit to check and bind the parameters for
        params (dict): dictionary of the parameters in the circuit to their corresponding values
        diff_params (dict): dictionary mapping the differentiable parameters to PennyLane
            Variable instances

    Returns:
        QuantumCircuit: quantum circuit with bound parameters
    """
    if not isinstance(quantum_circuit, QuantumCircuit):
        raise ValueError(
            "The circuit {} is not a valid Qiskit QuantumCircuit.".format(
                quantum_circuit))

    if params is None:
        return quantum_circuit

    for k in diff_params:
        # Since we cannot bind Variables to Qiskit circuits,
        # we must remove them from the binding dictionary before binding.
        del params[k]

    return quantum_circuit.bind_parameters(params)
    def test_binding_across_broadcast_instruction(self):
        """Bind a parameter which was included via a broadcast instruction."""
        # ref: https://github.com/Qiskit/qiskit-terra/issues/3008

        from qiskit.extensions.standard import RZGate
        theta = Parameter('θ')
        n = 5

        qc = QuantumCircuit(n, 1)

        qc.h(0)
        for i in range(n-1):
            qc.cx(i, i+1)

        qc.barrier()
        qc.rz(theta, range(n))
        qc.barrier()

        for i in reversed(range(n-1)):
            qc.cx(i, i+1)
        qc.h(0)
        qc.measure(0, 0)

        theta_range = numpy.linspace(0, 2 * numpy.pi, 128)
        circuits = [qc.bind_parameters({theta: theta_val})
                    for theta_val in theta_range]

        self.assertEqual(len(circuits), len(theta_range))
        for theta_val, bound_circ in zip(theta_range, circuits):
            rz_gates = [inst for inst, qargs, cargs in bound_circ.data
                        if isinstance(inst, RZGate)]

            self.assertEqual(len(rz_gates), n)
            self.assertTrue(all(float(gate.params[0]) == theta_val
                                for gate in rz_gates))
Beispiel #15
0
def err(params: collections.abc.Collection, circ: qk.QuantumCircuit,
        u_params: collections.abc.Collection) -> float:
    tmp_circ_loc = circ.bind_parameters(
        {u_params[i]: params[i]
         for i in range(len(u_params))})
    res = swap_test(tmp_circ_loc)
    return (1 - res)**2
Beispiel #16
0
    def test_big_gates(self):
        """Test large gates with params"""
        filename = self._get_resource_path('test_latex_big_gates.tex')
        qr = QuantumRegister(6, 'q')
        circuit = QuantumCircuit(qr)
        circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])

        desired_vector = [
            1 / math.sqrt(16) * complex(0, 1),
            1 / math.sqrt(8) * complex(1, 0),
            1 / math.sqrt(16) * complex(1, 1),
            0,
            0,
            1 / math.sqrt(8) * complex(1, 2),
            1 / math.sqrt(16) * complex(1, 0),
            0]

        circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
        circuit.unitary([[1, 0], [0, 1]], [qr[0]])
        matrix = np.zeros((4, 4))
        theta = Parameter('theta')
        circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
        circuit = circuit.bind_parameters({theta: 1})
        circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])

        circuit_drawer(circuit, filename=filename, output='latex_source')

        self.assertEqualToReference(filename)
Beispiel #17
0
    def __init__(self):
        theta, phi = Parameter('theta'), Parameter('phi')

        theta_values = np.arange(start=0,
                                 stop=2 * np.pi,
                                 step=np.pi / accuracy).tolist()
        phi_values = np.arange(start=0, stop=np.pi,
                               step=np.pi / accuracy).tolist()

        controls = QuantumRegister(4)
        circuit3 = QuantumCircuit(controls)
        circuit3.x(1)
        circuit3.x(3)
        circuit3.ry(theta=-theta, qubit=2, label='PMNS_H')
        circuit3.ry(theta=-theta, qubit=3, label='PMNS_H')

        # circuit3.unitary(PMNS_H, [2], label='PMNS_H')
        # circuit3.unitary(PMNS_H, [3], label='PMNS_H')

        # circuit3.unitary(U_t, [0], label='U(t)')
        # circuit3.unitary(U_t, [1], label='U(t)')
        # circuit3.unitary(U_t, [2], label='U(t)')
        # circuit3.unitary(U_t, [3], label='U(t)')

        bound_circuit = circuit3.bind_parameters({theta: theta_values})

        circuit3.measure([0, 1, 2, 3], [0, 1, 2, 3])
        circuit3.draw(output="mpl")
    def test_bind_global_phase(self):
        """Test binding global phase."""
        x = Parameter("x")
        circuit = QuantumCircuit(1, global_phase=x)
        self.assertEqual(circuit.parameters, {x})

        bound = circuit.bind_parameters({x: 2})
        self.assertEqual(bound.global_phase, 2)
        self.assertEqual(bound.parameters, set())
Beispiel #19
0
 def test_decomposes_into_correct_unitary(self):
     """test 2 qubit hamiltonian """
     qc = QuantumCircuit(2)
     matrix = Operator.from_label('XY')
     theta = Parameter('theta')
     uni2q = HamiltonianGate(matrix, theta)
     qc.append(uni2q, [0, 1])
     qc = qc.bind_parameters({theta: -np.pi / 2}).decompose()
     decomposed_ham = qc.data[0][0]
     self.assertEqual(decomposed_ham,
                      UnitaryGate(Operator.from_label('XY')))
    def test_to_instruction_with_expression(self, target_type, order):
        """Test preservation of expressions via parameterized instructions.

                  ┌───────┐┌──────────┐┌───────────┐
        qr1_0: |0>┤ Rx(θ) ├┤ Rz(pi/2) ├┤ Ry(phi*θ) ├
                  └───────┘└──────────┘└───────────┘

                     ┌───────────┐
        qr2_0: |0>───┤ Ry(delta) ├───
                  ┌──┴───────────┴──┐
        qr2_1: |0>┤ Circuit0(phi,θ) ├
                  └─────────────────┘
        qr2_2: |0>───────────────────
        """

        theta = Parameter('θ')
        phi = Parameter('phi')
        qr1 = QuantumRegister(1, name='qr1')
        qc1 = QuantumCircuit(qr1)

        qc1.rx(theta, qr1)
        qc1.rz(numpy.pi/2, qr1)
        qc1.ry(theta * phi, qr1)

        if target_type == 'gate':
            gate = qc1.to_gate()
        elif target_type == 'instruction':
            gate = qc1.to_instruction()

        self.assertEqual(gate.params, [phi, theta])

        delta = Parameter('delta')
        qr2 = QuantumRegister(3, name='qr2')
        qc2 = QuantumCircuit(qr2)
        qc2.ry(delta, qr2[0])
        qc2.append(gate, qargs=[qr2[1]])

        self.assertEqual(qc2.parameters, {delta, theta, phi})

        binds = {delta: 1, theta: 2, phi: 3}
        expected_qc = QuantumCircuit(qr2)
        expected_qc.rx(2, 1)
        expected_qc.rz(numpy.pi/2, 1)
        expected_qc.ry(3 * 2, 1)
        expected_qc.r(1, numpy.pi/2, 0)

        if order == 'bind-decompose':
            decomp_bound_qc = qc2.bind_parameters(binds).decompose()
        elif order == 'decompose-bind':
            decomp_bound_qc = qc2.decompose().bind_parameters(binds)

        self.assertEqual(decomp_bound_qc.parameters, set())
        self.assertEqual(decomp_bound_qc, expected_qc)
 def test_gate_multiplicity_binding(self):
     """Test binding when circuit contains multiple references to same gate"""
     from qiskit.extensions.standard import RZGate
     qc = QuantumCircuit(1)
     theta = Parameter('theta')
     gate = RZGate(theta)
     qc.append(gate, [0], [])
     qc.append(gate, [0], [])
     qc2 = qc.bind_parameters({theta: 1.0})
     self.assertEqual(len(qc2._parameter_table), 0)
     for gate, _, _ in qc2.data:
         self.assertEqual(float(gate.params[0]), 1.0)
    def test_bind_parameter_in_phase_and_gate(self):
        """Test binding a parameter present in the global phase and the gates."""
        x = Parameter("x")
        circuit = QuantumCircuit(1, global_phase=x)
        circuit.rx(x, 0)
        self.assertEqual(circuit.parameters, {x})

        ref = QuantumCircuit(1, global_phase=2)
        ref.rx(2, 0)

        bound = circuit.bind_parameters({x: 2})
        self.assertEqual(bound, ref)
        self.assertEqual(bound.parameters, set())
    def test_decompose_propagates_deeply_bound_parameters(
            self, target_type, parameter_type):
        """Verify bind-before-decompose preserves deeply bound values."""
        theta = Parameter('th')
        qc1 = QuantumCircuit(1)
        qc1.rx(theta, 0)

        if target_type == 'gate':
            inst = qc1.to_gate()
        elif target_type == 'instruction':
            inst = qc1.to_instruction()

        qc2 = QuantumCircuit(1)
        qc2.append(inst, [0])

        if target_type == 'gate':
            inst = qc2.to_gate()
        elif target_type == 'instruction':
            inst = qc2.to_instruction()

        qc3 = QuantumCircuit(1)
        qc3.append(inst, [0])

        if parameter_type == 'numbers':
            bound_qc3 = qc3.bind_parameters({theta: 0.5})
            expected_parameters = set()
            expected_qc3 = QuantumCircuit(1)
            expected_qc3.rx(0.5, 0)
        else:
            phi = Parameter('ph')
            bound_qc3 = qc3.copy()
            bound_qc3._substitute_parameters({theta: phi})
            expected_parameters = {phi}
            expected_qc3 = QuantumCircuit(1)
            expected_qc3.rx(phi, 0)

        deep_decomposed_qc3 = bound_qc3.decompose().decompose()

        with self.subTest(msg='testing parameters of initial circuit'):
            self.assertEqual(qc3.parameters, {theta})

        with self.subTest(msg='testing parameters of bound circuit'):
            self.assertEqual(bound_qc3.parameters, expected_parameters)

        with self.subTest(
                msg='testing parameters of deep decomposed bound circuit'):
            self.assertEqual(deep_decomposed_qc3.parameters,
                             expected_parameters)

        with self.subTest(msg='testing deep decomposed circuit'):
            self.assertEqual(deep_decomposed_qc3, expected_qc3)
Beispiel #24
0
    def test_partial_binding(self):
        """Test that binding a subset of circuit parameters returns a new parameterized circuit."""
        theta = Parameter('θ')
        x = Parameter('x')
        qr = QuantumRegister(1)
        qc = QuantumCircuit(qr)
        qc.rx(theta, qr)
        qc.u3(0, theta, x, qr)

        pqc = qc.bind_parameters({theta: 2})

        self.assertEqual(pqc.parameters, {x})

        self.assertEqual(pqc.data[0][0].params[0], 2)
        self.assertEqual(pqc.data[1][0].params[1], 2)
    def test_to_instruction_expression_parameter_map(self, target_type, order):
        """Test preservation of expressions via instruction parameter_map."""

        theta = Parameter('θ')
        phi = Parameter('phi')
        qr1 = QuantumRegister(1, name='qr1')
        qc1 = QuantumCircuit(qr1)

        qc1.rx(theta, qr1)
        qc1.rz(numpy.pi / 2, qr1)
        qc1.ry(theta * phi, qr1)

        theta_p = Parameter('theta')
        phi_p = Parameter('phi')

        if target_type == 'gate':
            gate = qc1.to_gate(parameter_map={theta: theta_p, phi: phi_p})
        elif target_type == 'instruction':
            gate = qc1.to_instruction(parameter_map={
                theta: theta_p,
                phi: phi_p
            })

        self.assertEqual(gate.params, [phi_p, theta_p])

        delta = Parameter('delta')
        qr2 = QuantumRegister(3, name='qr2')
        qc2 = QuantumCircuit(qr2)
        qc2.ry(delta, qr2[0])
        qc2.append(gate, qargs=[qr2[1]])

        self.assertEqual(qc2.parameters, {delta, theta_p, phi_p})

        binds = {delta: 1, theta_p: 2, phi_p: 3}
        expected_qc = QuantumCircuit(qr2)
        expected_qc.rx(2, 1)
        expected_qc.rz(numpy.pi / 2, 1)
        expected_qc.ry(3 * 2, 1)
        expected_qc.r(1, numpy.pi / 2, 0)

        if order == 'bind-decompose':
            decomp_bound_qc = qc2.bind_parameters(binds).decompose()
        elif order == 'decompose-bind':
            decomp_bound_qc = qc2.decompose().bind_parameters(binds)

        self.assertEqual(decomp_bound_qc.parameters, set())
        self.assertEqual(decomp_bound_qc, expected_qc)
Beispiel #26
0
 def test_qobj_with_hamiltonian(self):
     """test qobj output with hamiltonian"""
     qr = QuantumRegister(4)
     qc = QuantumCircuit(qr)
     qc.rx(np.pi / 4, qr[0])
     matrix = Operator.from_label('XIZ')
     theta = Parameter('theta')
     uni = HamiltonianGate(matrix, theta, label='XIZ')
     qc.append(uni, [qr[0], qr[1], qr[3]])
     qc.cx(qr[3], qr[2])
     qc = qc.bind_parameters({theta: np.pi / 2})
     qobj = qiskit.compiler.assemble(qc)
     instr = qobj.experiments[0].instructions[1]
     self.assertEqual(instr.name, 'hamiltonian')
     # Also test label
     self.assertEqual(instr.label, 'XIZ')
     np.testing.assert_array_almost_equal(
         np.array(instr.params[0]).astype(np.complex64), matrix.data)
Beispiel #27
0
    def test_quantum_circuit_with_bound_parameters(self, recorder):
        """Tests loading a quantum circuit that already had bound parameters."""

        theta = Parameter("θ")

        qc = QuantumCircuit(3, 1)
        qc.rz(theta, [0])
        qc_1 = qc.bind_parameters({theta: 0.5})

        quantum_circuit = load(qc_1)

        with recorder:
            quantum_circuit()

        assert len(recorder.queue) == 1
        assert recorder.queue[0].name == "RZ"
        assert recorder.queue[0].parameters == [0.5]
        assert recorder.queue[0].wires == Wires([0])
    def test_decompose_propagates_bound_parameters(self, target_type,
                                                   parameter_type):
        """Verify bind-before-decompose preserves bound values."""
        # ref: https://github.com/Qiskit/qiskit-terra/issues/2482
        theta = Parameter('th')
        qc = QuantumCircuit(1)
        qc.rx(theta, 0)

        if target_type == 'gate':
            inst = qc.to_gate()
        elif target_type == 'instruction':
            inst = qc.to_instruction()

        qc2 = QuantumCircuit(1)
        qc2.append(inst, [0])

        if parameter_type == 'numbers':
            bound_qc2 = qc2.bind_parameters({theta: 0.5})
            expected_parameters = set()
            expected_qc2 = QuantumCircuit(1)
            expected_qc2.rx(0.5, 0)
        else:
            phi = Parameter('ph')
            bound_qc2 = qc2.copy()
            bound_qc2._substitute_parameters({theta: phi})
            expected_parameters = {phi}
            expected_qc2 = QuantumCircuit(1)
            expected_qc2.rx(phi, 0)

        decomposed_qc2 = bound_qc2.decompose()

        with self.subTest(msg='testing parameters of initial circuit'):
            self.assertEqual(qc2.parameters, {theta})

        with self.subTest(msg='testing parameters of bound circuit'):
            self.assertEqual(bound_qc2.parameters, expected_parameters)

        with self.subTest(
                msg='testing parameters of deep decomposed bound circuit'):
            self.assertEqual(decomposed_qc2.parameters, expected_parameters)

        with self.subTest(msg='testing deep decomposed circuit'):
            self.assertEqual(decomposed_qc2, expected_qc2)
 def test_bind_ryrz_vector(self):
     """Test binding a list of floats to a ParamterVector"""
     qc = QuantumCircuit(4)
     depth = 4
     theta = ParameterVector('θ', length=len(qc.qubits) * depth * 2)
     theta_iter = iter(theta)
     for _ in range(depth):
         for q in qc.qubits:
             qc.ry(next(theta_iter), q)
             qc.rz(next(theta_iter), q)
         for i, q in enumerate(qc.qubits[:-1]):
             qc.cx(qc.qubits[i], qc.qubits[i+1])
         qc.barrier()
     theta_vals = numpy.linspace(0, 1, len(theta)) * numpy.pi
     self.assertEqual(set(qc.parameters), set(theta.params))
     bqc = qc.bind_parameters({theta: theta_vals})
     for gate_tuple in bqc.data:
         if hasattr(gate_tuple[0], 'params') and gate_tuple[0].params:
             self.assertIn(gate_tuple[0].params[0], theta_vals)
Beispiel #30
0
    def test_1q_hamiltonian(self):
        """test 1 qubit hamiltonian"""
        qr = QuantumRegister(1, 'q0')
        cr = ClassicalRegister(1, 'c0')
        qc = QuantumCircuit(qr, cr)
        matrix = np.zeros((2, 2))
        qc.x(qr[0])
        theta = Parameter('theta')
        qc.append(HamiltonianGate(matrix, theta), [qr[0]])
        qc = qc.bind_parameters({theta: 1})

        # test of text drawer
        self.log.info(qc)
        dag = circuit_to_dag(qc)
        dag_nodes = dag.named_nodes('hamiltonian')
        self.assertTrue(len(dag_nodes) == 1)
        dnode = dag_nodes[0]
        self.assertIsInstance(dnode.op, HamiltonianGate)
        self.assertListEqual(dnode.qargs, qc.qubits)
        assert_allclose(dnode.op.to_matrix(), np.eye(2))