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], )
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
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.'
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
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()
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_), )
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()
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
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
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
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
def test_type_valid_1(self) -> None: circuit = Circuit(1) try: circuit.point(HGate()) except TypeError: assert False, 'Unexpected TypeError.' except BaseException: return
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
def test_value_invalid3(self) -> None: circuit = Circuit(1) try: circuit.append_qudit(1) except ValueError: return except BaseException: assert False, 'Unexpected Exception.'
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.'
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.'
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
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.'
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
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
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.'
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
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.'
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
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
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
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.'
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
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
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.'