예제 #1
0
 def run(self, circuit: Circuit, data: dict[str, Any]) -> None:
     """Perform the pass's operation, see BasePass for more info."""
     _logger.debug('Converting PauliGates to U3Gates.')
     for cycle, op in circuit.operations_with_cycles():
         if isinstance(op.gate, PauliGate) and len(op.location, ) == 1:
             # Convert to SU(2)
             unitary = op.get_unitary().get_numpy()
             mag = np.linalg.det(unitary)**(-1 / 2)
             special_unitary = mag * unitary
             a = np.angle(special_unitary[1, 1])
             b = np.angle(special_unitary[1, 0])
             # Get angles
             theta = float(
                 np.arctan2(
                     np.abs(special_unitary[1, 0]),
                     np.abs(special_unitary[0, 0]),
                 ), ) * 2
             phi = (a + b)
             lamb = (a - b)
             # Replace
             point = CircuitPoint(cycle, op.location[0])
             circuit.replace_gate(
                 point,
                 U3Gate(),
                 op.location,
                 [theta, phi, lamb],
             )
예제 #2
0
def check_gradient(circ: Circuit, num_params: int) -> None:
    totaldiff = [0] * num_params
    eps = 1e-5
    repeats = 100
    for _ in range(repeats):
        v = np.random.rand(num_params) * 2 * np.pi
        M, Js = circ.get_unitary_and_grad(v)
        for i in range(num_params):
            v2 = np.copy(v)
            v2[i] = v[i] + eps
            U1 = circ.get_unitary(v2)
            if isinstance(U1, UnitaryMatrix):
                utry1 = U1.get_numpy()
            else:
                utry1 = U1
            v2[i] = v[i] - eps
            U2 = circ.get_unitary(v2)
            if isinstance(U2, UnitaryMatrix):
                utry2 = U2.get_numpy()
            else:
                utry2 = U2

            FD = (utry1 - utry2) / (2 * eps)

            diffs = np.sum(np.abs(FD - Js[i]))
            totaldiff[i] += diffs
    for i in range(num_params):
        assert totaldiff[i] < eps
예제 #3
0
 def test_type_invalid(self, circuit: Circuit, op: Operation) -> None:
     try:
         circuit.check_valid_operation(op)
     except TypeError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'
예제 #4
0
    def gen_initial_layer(
        self,
        target: UnitaryMatrix | StateVector,
        data: dict[str, Any],
    ) -> Circuit:
        """
        Generate the initial layer, see LayerGenerator for more.

        Raises:
            ValueError: If `target` has a radix mismatch with
                `self.initial_layer_gate`.
        """

        if not isinstance(target, (UnitaryMatrix, StateVector)):
            raise TypeError(
                'Expected unitary or state, got %s.' % type(target), )

        for radix in target.get_radixes():
            if radix != self.initial_layer_gate.get_radixes()[0]:
                raise ValueError(
                    'Radix mismatch between target and initial_layer_gate.', )

        init_circuit = Circuit(target.get_size(), target.get_radixes())
        for i in range(init_circuit.get_size()):
            init_circuit.append_gate(self.initial_layer_gate, [i])
        return init_circuit
예제 #5
0
class TestIsDifferentiable:
    """This tests `circuit.is_differentiable`."""
    def test_type(self, r6_qudit_circuit: Circuit) -> None:
        assert isinstance(r6_qudit_circuit.is_differentiable(), bool)

    def test_value(self, gate: Gate) -> None:
        circuit = Circuit(gate.get_size(), gate.get_radixes())
        assert circuit.is_differentiable()

        circuit.append_gate(gate, list(range(gate.get_size())))
        if isinstance(gate, DifferentiableUnitary):
            assert circuit.is_differentiable()
        else:
            assert not circuit.is_differentiable()

    @pytest.mark.parametrize(
        'circuit',
        [
            Circuit(1),
            Circuit(4),
            Circuit(4, [2, 3, 4, 5]),
        ],
    )
    def test_empty(self, circuit: Circuit) -> None:
        assert circuit.is_differentiable()
예제 #6
0
 def test_return_type(self, an_int: int) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     assert isinstance(
         circuit.is_point_in_range(
             (an_int, an_int),
         ), (bool, np.bool_),
     )
예제 #7
0
 def test_value(self, r6_qudit_circuit: Circuit) -> None:
     assert (r6_qudit_circuit.is_parameterized() !=
             r6_qudit_circuit.is_constant())
     if all(g.is_constant() for g in r6_qudit_circuit.get_gate_set()):
         assert r6_qudit_circuit.is_constant()
     else:
         assert not r6_qudit_circuit.is_constant()
예제 #8
0
def test_hilbert_schmidt_residuals(r3_qubit_circuit: Circuit) -> None:
    x0 = np.random.random((r3_qubit_circuit.get_num_params(), ))
    cost = HilbertSchmidtResidualsGenerator().gen_cost(
        r3_qubit_circuit,
        r3_qubit_circuit.get_unitary(x0),
    )
    assert cost.get_cost(x0) < 1e-10
예제 #9
0
 def test_type_valid_2(self) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.extend([Operation(HGate(), [0])])
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #10
0
 def test_type_valid_2(self) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.append_gate(HGate(), [2])
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #11
0
 def test_type_valid_1(self) -> None:
     circuit = Circuit(1)
     try:
         circuit.append(Operation(HGate(), [0]))
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #12
0
 def test_type_valid_1(self) -> None:
     circuit = Circuit(1)
     try:
         circuit.point(HGate())
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #13
0
 def test_type_valid_2(self, an_int: int, location: Sequence[int]) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.is_cycle_unoccupied(an_int, location)
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #14
0
 def test_value_invalid3(self) -> None:
     circuit = Circuit(1)
     try:
         circuit.append_qudit(1)
     except ValueError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'
예제 #15
0
 def test_type_invalid_1(self, not_an_int: Any) -> None:
     circuit = Circuit(1)
     try:
         circuit.pop_qudit(not_an_int)
     except TypeError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'
예제 #16
0
 def test_type_invalid_4(self, not_an_int: Any) -> None:
     circuit = Circuit(1)
     try:
         circuit.is_point_in_range((0, not_an_int))
     except TypeError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'
예제 #17
0
 def test_type_valid_3(self, an_int: int) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.is_point_in_range((an_int, an_int))
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #18
0
 def test_type_invalid_2(self, not_an_location: Sequence[int]) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.find_available_cycle(not_an_location)
     except TypeError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'
예제 #19
0
 def test_type_valid_1(self, location: Sequence[int]) -> None:
     circuit = Circuit(1)
     try:
         circuit.find_available_cycle(location)
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #20
0
 def test_type_valid_2(self, a_seq_int: Sequence[int]) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.extend_qudits(a_seq_int)
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #21
0
 def test_value_invalid6(self) -> None:
     circuit = Circuit(1)
     try:
         circuit.extend_qudits([2, 2, 3, 1])
     except ValueError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'
예제 #22
0
 def test_type_valid_2(self, an_int: int) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.is_qudit_idle(an_int)
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #23
0
 def test_index_invalid3(self) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.pop_qudit(5)
     except IndexError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'
예제 #24
0
파일: conftest.py 프로젝트: BQSKit/bqskit
def simple_circuit() -> Circuit:
    """Provides a simple circuit fixture."""
    circuit = Circuit(2)
    circuit.append_gate(XGate(), [0])
    circuit.append_gate(CNOTGate(), [0, 1])
    circuit.append_gate(XGate(), [1])
    circuit.append_gate(CNOTGate(), [1, 0])
    return circuit
예제 #25
0
 def test_type_valid_1(self, an_int: int) -> None:
     circuit = Circuit(1)
     try:
         circuit.is_qudit_in_range(an_int)
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #26
0
 def test_type_valid(self, points: Sequence[CircuitPointLike]) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.fold(circuit.get_region(points))
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #27
0
 def test_type_invalid_2(self, not_an_int: Any) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.is_qudit_idle(not_an_int)
     except TypeError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'
예제 #28
0
 def test_type_valid_4(self, an_int: int) -> None:
     circuit = Circuit(4, [2, 2, 3, 3])
     try:
         circuit.get_operation(CircuitPoint(an_int, an_int))
     except TypeError:
         assert False, 'Unexpected TypeError.'
     except BaseException:
         return
예제 #29
0
파일: visitor.py 프로젝트: BQSKit/bqskit
 def get_circuit(self) -> Circuit:
     """Retrieve the circuit generated after walking a parse tree."""
     num_qubits = sum(qubit_reg.size for qubit_reg in self.qubit_regs)
     if num_qubits == 0:
         raise LangException('No qubit registers defined.')
     circuit = Circuit(num_qubits)
     circuit.extend(self.op_list)
     return circuit
예제 #30
0
 def test_type_invalid_3(self, not_an_int: Any) -> None:
     circuit = Circuit(1)
     try:
         circuit.get_operation((not_an_int, not_an_int))
     except TypeError:
         return
     except BaseException:
         assert False, 'Unexpected Exception.'