Esempio n. 1
0
def test_state_shape_and_dtype(backend):
    state = states.VectorState.zero_state(3)
    assert state.shape == (8, )
    assert state.dtype == K.dtypes('DTYPECPX')
    state = states.MatrixState.zero_state(3)
    assert state.shape == (8, 8)
    assert state.dtype == K.dtypes('DTYPECPX')
Esempio n. 2
0
def test_state_shape_and_dtype(backend):
    original_backend = qibo.get_backend()
    qibo.set_backend(backend)
    state = states.VectorState.zero_state(3)
    assert state.shape == (8, )
    assert state.dtype == K.dtypes('DTYPECPX')
    state = states.MatrixState.zero_state(3)
    assert state.shape == (8, 8)
    assert state.dtype == K.dtypes('DTYPECPX')
    qibo.set_backend(original_backend)
Esempio n. 3
0
def test_variable_backpropagation(backend):
    if backend == "custom":
        pytest.skip("Custom gates do not support automatic differentiation.")
    original_backend = qibo.get_backend()
    qibo.set_backend(backend)
    if K.name != "tensorflow":
        qibo.set_backend(original_backend)
        pytest.skip("Backpropagation is not supported by {}.".format(K.name))

    theta = K.optimization.Variable(0.1234, dtype=K.dtypes('DTYPE'))
    # TODO: Fix parametrized gates so that `Circuit` can be defined outside
    # of the gradient tape
    with K.optimization.GradientTape() as tape:
        c = Circuit(1)
        c.add(gates.X(0))
        c.add(gates.RZ(0, theta))
        loss = K.real(c()[-1])
    grad = tape.gradient(loss, theta)

    target_loss = np.cos(theta / 2.0)
    np.testing.assert_allclose(loss, target_loss)

    target_grad = -np.sin(theta / 2.0) / 2.0
    np.testing.assert_allclose(grad, target_grad)
    qibo.set_backend(original_backend)
def test_two_variables_backpropagation(backend):
    if backend == "custom":
        pytest.skip("Custom gates do not support automatic differentiation.")
    original_backend = qibo.get_backend()
    qibo.set_backend(backend)
    if "numpy" in K.name:
        qibo.set_backend(original_backend)
        pytest.skip("Backpropagation is not supported by {}.".format(K.name))

    theta = K.optimization.Variable([0.1234, 0.4321], dtype=K.dtypes('DTYPE'))
    # TODO: Fix parametrized gates so that `Circuit` can be defined outside
    # of the gradient tape
    with K.optimization.GradientTape() as tape:
        c = Circuit(2)
        c.add(gates.RX(0, theta[0]))
        c.add(gates.RY(1, theta[1]))
        loss = K.real(c()[0])
    grad = tape.gradient(loss, theta)

    t = np.array([0.1234, 0.4321]) / 2.0
    target_loss = np.cos(t[0]) * np.cos(t[1])
    np.testing.assert_allclose(loss, target_loss)

    target_grad1 = -np.sin(t[0]) * np.cos(t[1])
    target_grad2 = -np.cos(t[0]) * np.sin(t[1])
    target_grad = np.array([target_grad1, target_grad2]) / 2.0
    np.testing.assert_allclose(grad, target_grad)
    qibo.set_backend(original_backend)
Esempio n. 5
0
def test_variable_theta(backend):
    """Check that parametrized gates accept `tf.Variable` parameters."""
    backend = qibo.get_backend()
    if backend != "tensorflow":
        pytest.skip("Numpy backends do not support variable parameters.")
    theta1 = K.optimization.Variable(0.1234, dtype=K.dtypes('DTYPE'))
    theta2 = K.optimization.Variable(0.4321, dtype=K.dtypes('DTYPE'))
    cvar = Circuit(2)
    cvar.add(gates.RX(0, theta1))
    cvar.add(gates.RY(1, theta2))
    final_state = cvar()

    c = Circuit(2)
    c.add(gates.RX(0, 0.1234))
    c.add(gates.RY(1, 0.4321))
    target_state = c()
    K.assert_allclose(final_state, target_state)
Esempio n. 6
0
 def plus_state(cls, circuit):
     """Creates ``|++...+>`` as a distributed state."""
     state = cls(circuit)
     with K.on_cpu():
         n = K.cast(2**state.nlocal, dtype=K.dtypes('DTYPEINT'))
         norm = K.cast(2**float(state.nqubits / 2.0))
         state.pieces = [
             K.cpu_tensor(K.ones(n) / norm) for _ in range(state.ndevices)
         ]
     return state
Esempio n. 7
0
def test_state_set_measurements(registers):
    from qibo import gates
    state = states.VectorState.zero_state(3)
    samples = K.cast(50 * [0] + 50 * [1], dtype=K.dtypes("DTYPEINT"))
    state.set_measurements([0, 2], samples, registers)
    target_samples = np.array(50 * [[0, 0]] + 50 * [[0, 1]])
    K.assert_allclose(state.samples(), target_samples)
    assert state.frequencies() == {"00": 50, "01": 50}
    if registers is not None:
        target_freqs = {"a": {"0": 100}, "b": {"0": 50, "1": 50}}
    else:
        target_freqs = {"00": 50, "01": 50}
    assert state.frequencies(registers=True) == target_freqs
def test_variable_theta(backend):
    """Check that parametrized gates accept `tf.Variable` parameters."""
    if "numpy" in backend:
        pytest.skip("Numpy backends do not support variable parameters.")

    from qibo import K
    original_backend = qibo.get_backend()
    qibo.set_backend(backend)
    theta1 = K.optimization.Variable(0.1234, dtype=K.dtypes('DTYPE'))
    theta2 = K.optimization.Variable(0.4321, dtype=K.dtypes('DTYPE'))

    cvar = Circuit(2)
    cvar.add(gates.RX(0, theta1))
    cvar.add(gates.RY(1, theta2))
    final_state = cvar()

    c = Circuit(2)
    c.add(gates.RX(0, 0.1234))
    c.add(gates.RY(1, 0.4321))
    target_state = c()
    np.testing.assert_allclose(final_state, target_state)
    qibo.set_backend(original_backend)
Esempio n. 9
0
def test_set_precision(backend, precision):
    original_precision = backends.get_precision()
    backends.set_precision(precision)
    if precision == "single":
        expected_dtype = K.backend.complex64
    else:
        expected_dtype = K.backend.complex128
    assert backends.get_precision() == precision
    assert K.dtypes('DTYPECPX') == expected_dtype
    # Test that circuits use proper precision
    circuit = models.Circuit(2)
    circuit.add([gates.H(0), gates.H(1)])
    final_state = circuit()
    assert final_state.dtype == expected_dtype
    backends.set_precision(original_precision)
Esempio n. 10
0
def test_hamiltonian_initialization():
    """Testing hamiltonian initialization errors."""
    import tensorflow as tf
    dtype = K.dtypes('DTYPECPX')
    with pytest.raises(TypeError):
        H = Hamiltonian(2, "test")
    H1 = Hamiltonian(2, np.eye(4))
    H1 = Hamiltonian(2, np.eye(4), numpy=True)
    H1 = Hamiltonian(2, tf.eye(4, dtype=dtype))
    H1 = Hamiltonian(2, tf.eye(4, dtype=dtype), numpy=True)
    with pytest.raises(ValueError):
        H1 = Hamiltonian(-2, np.eye(4))
    with pytest.raises(RuntimeError):
        H2 = Hamiltonian(np.eye(2), np.eye(4))
    with pytest.raises(ValueError):
        H3 = Hamiltonian(4, np.eye(10))
Esempio n. 11
0
 def tensor(self, x):
     if not isinstance(x, K.Tensor):
         if isinstance(x, K.qnp.tensor_types):
             x = K.cast(x)
         else:
             raise_error(
                 TypeError, "Initial state type {} is not recognized."
                 "".format(type(x)))
     if x.dtype != K.dtypes('DTYPECPX'):
         x = K.cast(x)
     shape = tuple(x.shape)
     if self._nqubits is None:
         self.nqubits = int(K.np.log2(shape[0]))
     if shape != self.shape:
         raise_error(
             ValueError, "Invalid tensor shape {} for state of {} "
             "qubits.".format(shape, self.nqubits))
     self._tensor = x
Esempio n. 12
0
def test_variable_backpropagation(backend):
    if not K.supports_gradients:
        pytest.skip("Backpropagation is not supported by {}.".format(K.name))

    theta = K.optimization.Variable(0.1234, dtype=K.dtypes('DTYPE'))
    # TODO: Fix parametrized gates so that `Circuit` can be defined outside
    # of the gradient tape
    with K.optimization.GradientTape() as tape:
        c = Circuit(1)
        c.add(gates.X(0))
        c.add(gates.RZ(0, theta))
        loss = K.real(c()[-1])
    grad = tape.gradient(loss, theta)

    target_loss = np.cos(theta / 2.0)
    K.assert_allclose(loss, target_loss)

    target_grad = -np.sin(theta / 2.0) / 2.0
    K.assert_allclose(grad, target_grad)
Esempio n. 13
0
def test_two_variables_backpropagation(backend):
    if not K.supports_gradients:
        pytest.skip("Backpropagation is not supported by {}.".format(K.name))

    theta = K.optimization.Variable([0.1234, 0.4321], dtype=K.dtypes('DTYPE'))
    # TODO: Fix parametrized gates so that `Circuit` can be defined outside
    # of the gradient tape
    with K.optimization.GradientTape() as tape:
        c = Circuit(2)
        c.add(gates.RX(0, theta[0]))
        c.add(gates.RY(1, theta[1]))
        loss = K.real(c()[0])
    grad = tape.gradient(loss, theta)

    t = np.array([0.1234, 0.4321]) / 2.0
    target_loss = np.cos(t[0]) * np.cos(t[1])
    K.assert_allclose(loss, target_loss)

    target_grad1 = -np.sin(t[0]) * np.cos(t[1])
    target_grad2 = -np.cos(t[0]) * np.sin(t[1])
    target_grad = np.array([target_grad1, target_grad2]) / 2.0
    K.assert_allclose(grad, target_grad)
Esempio n. 14
0
 def _convert_to_decimal(self):
     _range = K.range(self.nqubits - 1, -1, -1, dtype=K.dtypes('DTYPEINT'))
     _range = K.pow(2, _range)[:, K.newaxis]
     return K.matmul(self.binary, _range)[:, 0]
Esempio n. 15
0
 def _convert_to_binary(self):
     _range = K.range(self.nqubits - 1, -1, -1, dtype=K.dtypes('DTYPEINT'))
     return K.mod(K.right_shift(self.decimal[:, K.newaxis], _range), 2)