예제 #1
0
def test_vector_state_to_density_matrix(backend):
    vector = np.random.random(32) + 1j * np.random.random(32)
    vector = vector / np.sqrt((np.abs(vector) ** 2).sum())
    state = states.VectorState.from_tensor(vector)
    mstate = state.to_density_matrix()
    target_matrix = np.outer(vector, vector.conj())
    K.assert_allclose(mstate.tensor, target_matrix)
    state = states.MatrixState.from_tensor(target_matrix)
    with pytest.raises(RuntimeError):
        state.to_density_matrix()
예제 #2
0
def test_cnot(backend, applyx):
    if applyx:
        gatelist = [gates.X(0)]
    else:
        gatelist = []
    gatelist.append(gates.CNOT(0, 1))
    final_state = apply_gates(gatelist, nqubits=2)
    target_state = np.zeros_like(final_state)
    target_state[3 * int(applyx)] = 1.0
    K.assert_allclose(final_state, target_state)
예제 #3
0
def test_measurementregistersresult_samples(backend):
    samples = np.random.randint(0, 2, (20, 4))
    result = measurements.MeasurementResult((0, 1, 2, 3))
    result.binary = K.cast(samples)
    qubits = {"a": (0, 2), "b": (1, 3)}
    result = measurements.MeasurementRegistersResult(qubits, result)
    register_samples = result.samples(registers=True)
    assert register_samples.keys() == qubits.keys()
    K.assert_allclose(register_samples["a"], samples[:, [0, 2]])
    K.assert_allclose(register_samples["b"], samples[:, [1, 3]])
예제 #4
0
def test_one_qubit_gates(backend, gatename, gatekwargs):
    """Check applying one qubit gates to one qubit density matrix."""
    initial_rho = random_density_matrix(1)
    gate = getattr(gates, gatename)(0, **gatekwargs)
    gate.density_matrix = True
    final_rho = gate(np.copy(initial_rho))

    matrix = K.to_numpy(gate.matrix)
    target_rho = np.einsum("ab,bc,cd->ad", matrix, initial_rho, matrix.conj().T)
    K.assert_allclose(final_rho, target_rho)
예제 #5
0
def assert_result(result, decimal_samples=None, binary_samples=None,
                  decimal_frequencies=None, binary_frequencies=None):
    if decimal_frequencies is not None:
        assert result.frequencies(False) == decimal_frequencies
    if binary_frequencies is not None:
        assert result.frequencies(True) == binary_frequencies
    if decimal_samples is not None:
        K.assert_allclose(result.samples(False), decimal_samples)
    if binary_samples is not None:
        K.assert_allclose(result.samples(True), binary_samples)
예제 #6
0
def test_hgate_density_matrix(backend):
    initial_rho = random_density_matrix(2)
    gate = gates.H(1)
    gate.density_matrix = True
    final_rho = gate(np.copy(initial_rho))

    matrix = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
    matrix = np.kron(np.eye(2), matrix)
    target_rho = matrix.dot(initial_rho).dot(matrix)
    K.assert_allclose(final_rho, target_rho)
예제 #7
0
def test_state_probabilities(backend, state_type, use_gate):
    state = getattr(states, state_type).plus_state(4)
    if use_gate:
        from qibo import gates
        mgate = gates.M(0, 1)
        probs = state.probabilities(measurement_gate=mgate)
    else:
        probs = state.probabilities(qubits=[0, 1])
    target_probs = np.ones((2, 2)) / 4
    K.assert_allclose(probs, target_probs)
예제 #8
0
def test_fuse_circuit_two_qubit_gates(backend):
    """Check circuit fusion in circuit with two-qubit gates only."""
    c = Circuit(2)
    c.add(gates.CNOT(0, 1))
    c.add(gates.RX(0, theta=0.1234).controlled_by(1))
    c.add(gates.SWAP(0, 1))
    c.add(gates.fSim(1, 0, theta=0.1234, phi=0.324))
    c.add(gates.RY(1, theta=0.1234).controlled_by(0))
    fused_c = c.fuse()
    K.assert_allclose(fused_c(), c())
예제 #9
0
def test_trotter_hamiltonian_scalar_mul(nqubits=3):
    """Test multiplication of Trotter Hamiltonian with scalar."""
    local_ham = hamiltonians.TFIM(nqubits, h=1.0, dense=False)
    target_ham = 2 * hamiltonians.TFIM(nqubits, h=1.0)
    local_dense = (2 * local_ham).dense
    K.assert_allclose(local_dense.matrix, target_ham.matrix)

    local_ham = hamiltonians.TFIM(nqubits, h=1.0, dense=False)
    local_dense = (local_ham * 2).dense
    K.assert_allclose(local_dense.matrix, target_ham.matrix)
예제 #10
0
def test_trotter_hamiltonian_scalar_add(nqubits=4):
    """Test addition of Trotter Hamiltonian with scalar."""
    local_ham = hamiltonians.TFIM(nqubits, h=1.0, dense=False)
    target_ham = 2 + hamiltonians.TFIM(nqubits, h=1.0)
    local_dense = (2 + local_ham).dense
    K.assert_allclose(local_dense.matrix, target_ham.matrix)

    local_ham = hamiltonians.TFIM(nqubits, h=1.0, dense=False)
    local_dense = (local_ham + 2).dense
    K.assert_allclose(local_dense.matrix, target_ham.matrix)
예제 #11
0
def test_controlled_x_vs_toffoli(backend):
    c1 = Circuit(3)
    c1.add(gates.X(0))
    c1.add(gates.X(2))
    c1.add(gates.X(1).controlled_by(0, 2))
    c2 = Circuit(3)
    c2.add(gates.X(0))
    c2.add(gates.X(2))
    c2.add(gates.TOFFOLI(0, 2, 1))
    K.assert_allclose(c1(), c2())
예제 #12
0
def test_variational_layer_dagger(backend, nqubits):
    theta = 2 * np.pi * np.random.random((2, nqubits))
    pairs = list((i, i + 1) for i in range(0, nqubits - 1, 2))
    gate = gates.VariationalLayer(range(nqubits), pairs, gates.RY, gates.CZ,
                                  theta[0], theta[1])
    c = Circuit(nqubits)
    c.add((gate, gate.dagger()))
    initial_state = random_state(nqubits)
    final_state = c(np.copy(initial_state))
    K.assert_allclose(final_state, initial_state)
예제 #13
0
def test_unitary_dagger(backend, nqubits):
    matrix = np.random.random((2**nqubits, 2**nqubits))
    gate = gates.Unitary(matrix, *range(nqubits))
    c = Circuit(nqubits)
    c.add((gate, gate.dagger()))
    initial_state = random_state(nqubits)
    final_state = c(np.copy(initial_state))
    target_state = np.dot(matrix, initial_state)
    target_state = np.dot(np.conj(matrix).T, target_state)
    K.assert_allclose(final_state, target_state)
예제 #14
0
def test_controlled_unitary_dagger(backend):
    from scipy.linalg import expm
    matrix = np.random.random((2, 2))
    matrix = expm(1j * (matrix + matrix.T))
    gate = gates.Unitary(matrix, 0).controlled_by(1, 2, 3, 4)
    c = Circuit(5)
    c.add((gate, gate.dagger()))
    initial_state = random_state(5)
    final_state = c(np.copy(initial_state))
    K.assert_allclose(final_state, initial_state)
예제 #15
0
def test_toffoli_gate(backend):
    """Check applying Toffoli to three qubit density matrix."""
    initial_rho = random_density_matrix(3)
    gate = gates.TOFFOLI(0, 1, 2)
    gate.density_matrix = True
    final_rho = gate(np.copy(initial_rho))

    matrix = K.to_numpy(gate.matrix)
    target_rho = np.einsum("ab,bc,cd->ad", matrix, initial_rho, matrix.conj().T)
    K.assert_allclose(final_rho, target_rho)
예제 #16
0
def test_distributed_circuit_execution_special_gate(backend, accelerators):
    dist_c = DistributedCircuit(6, accelerators)
    initial_state = random_state(dist_c.nqubits)
    dist_c.add(gates.Flatten(np.copy(initial_state)))
    dist_c.add((gates.H(i) for i in range(dist_c.nlocal)))
    dist_c.global_qubits = range(dist_c.nlocal, dist_c.nqubits)
    c = Circuit(6)
    c.add(gates.Flatten(np.copy(initial_state)))
    c.add((gates.H(i) for i in range(dist_c.nlocal)))
    K.assert_allclose(dist_c(), c())
예제 #17
0
def test_entropy_switch_partition(backend):
    """Check that partition is switched to the largest counterpart."""
    entropy = callbacks.EntanglementEntropy([0])
    # Prepare ghz state of 5 qubits
    state = np.zeros(2 ** 5)
    state[0], state[-1] = 1, 1
    state = state / np.sqrt(2)

    result = entropy(K.cast(state))
    K.assert_allclose(result, 1.0)
예제 #18
0
def test_trotter_hamiltonian_scalar_sub(nqubits=3):
    """Test subtraction of Trotter Hamiltonian with scalar."""
    local_ham = hamiltonians.TFIM(nqubits, h=1.0, dense=False)
    target_ham = 2 - hamiltonians.TFIM(nqubits, h=1.0)
    local_dense = (2 - local_ham).dense
    K.assert_allclose(local_dense.matrix, target_ham.matrix)

    target_ham = hamiltonians.TFIM(nqubits, h=1.0) - 2
    local_ham = hamiltonians.TFIM(nqubits, h=1.0, dense=False)
    local_dense = (local_ham - 2).dense
    K.assert_allclose(local_dense.matrix, target_ham.matrix)
예제 #19
0
def test_overlap(backend, density_matrix):
    state0 = np.random.random(4) + 1j * np.random.random(4)
    state1 = np.random.random(4) + 1j * np.random.random(4)
    overlap = callbacks.Overlap(state0)
    if density_matrix:
        overlap.density_matrix = True
        with pytest.raises(NotImplementedError):
            overlap(state1)
    else:
        target_overlap = np.abs((state0.conj() * state1).sum())
        K.assert_allclose(overlap(K.cast(state1)), target_overlap)
예제 #20
0
def test_norm(backend, density_matrix):
    norm = callbacks.Norm()
    if density_matrix:
        norm.density_matrix = True
        state = np.random.random((2, 2)) + 1j * np.random.random((2, 2))
        target_norm = np.trace(state)
    else:
        state = np.random.random(4) + 1j * np.random.random(4)
        target_norm = np.sqrt((np.abs(state) ** 2).sum())

    K.assert_allclose(norm(K.cast(state)), target_norm)
예제 #21
0
def test_controlled_by_gates_fusion(backend):
    """Check circuit fusion that contains ``controlled_by`` gates."""
    c = Circuit(4)
    c.add((gates.H(i) for i in range(4)))
    c.add(gates.RX(1, theta=0.1234).controlled_by(0))
    c.add(gates.RX(3, theta=0.4321).controlled_by(2))
    c.add((gates.RY(i, theta=0.5678) for i in range(4)))
    c.add(gates.RX(1, theta=0.1234).controlled_by(0))
    c.add(gates.RX(3, theta=0.4321).controlled_by(2))
    fused_c = c.fuse()
    K.assert_allclose(fused_c(), c())
예제 #22
0
def test_hamiltonian_ground_state(sparse_type, dense):
    """Test Hamiltonian ground state."""
    if sparse_type is None:
        H = hamiltonians.XXZ(nqubits=2, delta=0.5, dense=dense)
    else:
        from scipy import sparse
        H = hamiltonians.XXZ(nqubits=5, delta=0.5)
        m = getattr(sparse, f"{sparse_type}_matrix")(K.to_numpy(H.matrix))
        H = hamiltonians.Hamiltonian(5, m)
    V = K.to_numpy(H.eigenvectors())
    K.assert_allclose(H.ground_state(), V[:, 0])
예제 #23
0
def test_final_state_property(backend):
    """Check accessing final state using the circuit's property."""
    c = Circuit(2)
    c.add([gates.H(0), gates.H(1)])

    with pytest.raises(RuntimeError):
        final_state = c.final_state

    _ = c()
    target_state = np.ones(4) / 2
    K.assert_allclose(c.final_state, target_state)
예제 #24
0
def test_circuit_unitary(backend):
    from qibo import matrices
    c = Circuit(2)
    c.add(gates.H(0))
    c.add(gates.H(1))
    c.add(gates.CNOT(0, 1))
    c.add(gates.X(0))
    c.add(gates.Y(1))
    h = np.kron(matrices.H, matrices.H)
    target_matrix = np.kron(matrices.X, matrices.Y) @ matrices.CNOT @ h
    K.assert_allclose(c.unitary(), target_matrix)
예제 #25
0
def test_generalizedfsim_dagger(backend):
    from scipy.linalg import expm
    phi = 0.2
    matrix = np.random.random((2, 2))
    matrix = expm(1j * (matrix + matrix.T))
    gate = gates.GeneralizedfSim(0, 1, matrix, phi)
    c = Circuit(2)
    c.add((gate, gate.dagger()))
    initial_state = random_state(2)
    final_state = c(np.copy(initial_state))
    K.assert_allclose(final_state, initial_state)
예제 #26
0
def test_pauli_noise_channel(backend):
    initial_rho = random_density_matrix(2)
    gate = gates.PauliNoiseChannel(1, px=0.3)
    gate.density_matrix = True
    final_rho = gate(K.cast(np.copy(initial_rho)))
    gate = gates.X(1)
    gate.density_matrix = True
    initial_rho = K.cast(initial_rho)
    target_rho = 0.3 * gate(K.copy(initial_rho))
    target_rho += 0.7 * initial_rho
    K.assert_allclose(final_rho, target_rho)
예제 #27
0
def test_variational_layer(backend, nqubits):
    theta = 2 * np.pi * np.random.random(nqubits)
    gatelist = [gates.RY(i, t) for i, t in enumerate(theta)]
    gatelist.extend(gates.CZ(i, i + 1) for i in range(0, nqubits - 1, 2))
    target_state = apply_gates(gatelist, nqubits=nqubits)

    pairs = list((i, i + 1) for i in range(0, nqubits - 1, 2))
    gate = gates.VariationalLayer(range(nqubits), pairs, gates.RY, gates.CZ,
                                  theta)
    final_state = apply_gates([gate], nqubits=nqubits)
    K.assert_allclose(target_state, final_state)
예제 #28
0
def test_vector_state_expectation(backend, dense):
    from qibo.hamiltonians import XXZ
    ham = XXZ(nqubits=5, delta=0.5, dense=dense)
    matrix = K.to_numpy(ham.matrix)

    state = np.random.random(32) + 1j * np.random.random(32)
    norm = np.sum(np.abs(state)**2)
    target_ev = np.sum(state.conj() * matrix.dot(state)).real
    state = states.VectorState.from_tensor(state)

    K.assert_allclose(state.expectation(ham), target_ev)
    K.assert_allclose(state.expectation(ham, True), target_ev / norm)
예제 #29
0
def test_hamiltonian_term_merge(backend):
    """Test ``HamiltonianTerm.merge``."""
    matrix1 = np.random.random((2, 2))
    matrix2 = np.random.random((4, 4))
    term1 = terms.HamiltonianTerm(matrix1, 1)
    term2 = terms.HamiltonianTerm(matrix2, 0, 1)
    mterm = term2.merge(term1)
    target_matrix = np.kron(np.eye(2), matrix1) + matrix2
    assert mterm.target_qubits == (0, 1)
    K.assert_allclose(mterm.matrix, target_matrix)
    with pytest.raises(ValueError):
        term1.merge(term2)
예제 #30
0
def test_unitary_initialization(backend):
    matrix = np.random.random((4, 4))
    gate = gates.Unitary(matrix, 0, 1)
    K.assert_allclose(gate.parameters, matrix)
    matrix = np.random.random((8, 8))
    with pytest.raises(ValueError):
        gate = gates.Unitary(matrix, 0, 1)
    with pytest.raises(TypeError):
        gate = gates.Unitary("abc", 0, 1)
    if K.op is not None:
        with pytest.raises(NotImplementedError):
            gate = gates.Unitary(matrix, 0, 1, 2)