Exemplo n.º 1
0
 def test_pqc_constraint(self):
     """Test attachment of constraint to layer."""
     my_constraint = tf.keras.constraints.NonNeg()
     (a, b, c) = sympy.symbols("a b c")
     qubit = cirq.GridQubit(0, 0)
     three_parameters = cirq.Circuit(
         [cirq.X(qubit)**a,
          cirq.Y(qubit)**b,
          cirq.Z(qubit)**c])
     mpqc = pqc.PQC(three_parameters,
                    cirq.Z(qubit),
                    constraint=my_constraint)
     self.assertEqual(my_constraint, mpqc.parameters.constraint)
Exemplo n.º 2
0
    def test_pqc_backend_error(self):
        """Test that invalid backends error properly."""
        symbol = sympy.Symbol('alpha')
        qubit = cirq.GridQubit(0, 0)
        learnable_flip = cirq.Circuit(cirq.X(qubit)**symbol)

        class MyExpectation(cirq.sim.simulator.SimulatesExpectationValues):
            """My expectation values simulator."""

            def simulate_expectation_values_sweep(self):
                """do nothing."""
                return

        class MySample(cirq.Sampler):
            """My state simulator."""

            def run_sweep(self):
                """do nothing."""
                return

        with self.assertRaisesRegex(
                TypeError,
                expected_regex="cirq.sim.simulator.SimulatesExpectation"):
            pqc.PQC(learnable_flip, cirq.Z(qubit), backend='junk')

        with self.assertRaisesRegex(TypeError, expected_regex="cirq.Sampler"):
            pqc.PQC(learnable_flip,
                    cirq.Z(qubit),
                    backend=MyExpectation,
                    repetitions=500)

        with self.assertRaisesRegex(
                TypeError,
                expected_regex="cirq.sim.simulator.SimulatesExpectationValues"):
            pqc.PQC(learnable_flip,
                    cirq.Z(qubit),
                    backend=MySample,
                    repetitions=None)
Exemplo n.º 3
0
    def test_keras_model_optimization(self):
        """Optimizate a PQC based keras model."""

        x = np.asarray([
            [0, 0],
            [0, 1],
            [1, 0],
            [1, 1],
        ], dtype=float)

        y = np.asarray([[-1], [1], [1], [-1]], dtype=np.float32)

        def convert_to_circuit(input_data):
            """Encode into quantum datapoint."""
            values = np.ndarray.flatten(input_data)
            qubits = cirq.GridQubit.rect(1, 2)
            circuit = cirq.Circuit()
            for i, value in enumerate(values):
                if value:
                    circuit.append(cirq.X(qubits[i]))
            return circuit

        x_circ = util.convert_to_tensor([convert_to_circuit(x) for x in x])

        # Create two qubits
        q0, q1 = cirq.GridQubit.rect(1, 2)

        # Create an anzatz on these qubits.
        a, b = sympy.symbols('a b')  # parameters for the circuit
        circuit = cirq.Circuit(
            cirq.rx(a).on(q0),
            cirq.ry(b).on(q1), cirq.CNOT(control=q0, target=q1))

        # Build the Keras model.
        model = tf.keras.Sequential([
            # The input is the data-circuit, encoded as a tf.string
            tf.keras.layers.Input(shape=(), dtype=tf.string),
            # The PQC layer returns the expected value of the
            # readout gate, range [-1,1].
            pqc.PQC(circuit, cirq.Z(q1)),
        ])

        # Initial guess of the parameter from random number
        result = rotosolve_minimizer.minimize(
            loss_function_with_model_parameters(model, tf.keras.losses.Hinge(),
                                                x_circ, y),
            tf.random.uniform(shape=[2]) * 2 * np.pi)

        self.assertAlmostEqual(result.objective_value, 0)
        self.assertTrue(result.converged)
Exemplo n.º 4
0
 def test_pqc_symbol_values(self):
     """Test that PQC symbol_values returns the correct key value pairs."""
     c, b, a, d = sympy.symbols('c b a d')
     bit = cirq.GridQubit(0, 0)
     test_circuit = cirq.Circuit(
         cirq.H(bit)**a,
         cirq.Z(bit)**b,
         cirq.X(bit)**d,
         cirq.Y(bit)**c)
     init_vals = [1, 2, 3, 4]
     layer = pqc.PQC(test_circuit,
                     cirq.Z(bit),
                     initializer=tf.constant_initializer(init_vals))
     expected_vals = dict(zip([a, b, c, d], init_vals))
     self.assertAllClose(layer.symbol_values(), expected_vals)