示例#1
0
文件: cgates.py 项目: NourO93/qibo
 def density_matrix_call(self, state):
     state = self.gate_op(state, self.qubits_tensor_dm, 2 * self.nqubits,
                          *self.target_qubits, get_threads())
     matrix = K.conj(matrices.Y)
     state = K.op.apply_gate(state, matrix, self.qubits_tensor,
                             2 * self.nqubits, *self.target_qubits_dm,
                             get_threads())
     return state
示例#2
0
文件: cgates.py 项目: NourO93/qibo
 def density_matrix_call(self, state):
     state = self.gate_op(
         state,
         self.matrix,
         self.qubits_tensor_dm,  # pylint: disable=E1121
         2 * self.nqubits,
         *self.target_qubits,
         get_threads())
     adjmatrix = K.conj(self.matrix)
     state = self.gate_op(state, adjmatrix, self.qubits_tensor,
                          2 * self.nqubits, *self.target_qubits_dm,
                          get_threads())
     return state
def test_unbalanced_probabilistic_measurement(backend, use_samples):
    original_backend = qibo.get_backend()
    original_threads = qibo.get_threads()
    qibo.set_backend(backend)
    # set single-thread to fix the random values generated from the frequency custom op
    qibo.set_threads(1)
    state = np.array([1, 1, 1, np.sqrt(3)]) / np.sqrt(6)
    c = models.Circuit(2)
    c.add(gates.Flatten(state))
    c.add(gates.M(0, 1))
    result = c(nshots=1000)

    K.set_seed(1234)
    if use_samples:
        # calculates sample tensor directly using `tf.random.categorical`
        # otherwise it uses the frequency-only calculation
        _ = result.samples()
    # update reference values based on backend and device
    if K.name == "tensorflow":
        if K.gpu_devices:  # pragma: no cover
            # CI does not use GPU
            decimal_frequencies = {0: 196, 1: 153, 2: 156, 3: 495}
        else:
            decimal_frequencies = {0: 168, 1: 188, 2: 154, 3: 490}
    elif K.name == "numpy":
        decimal_frequencies = {0: 171, 1: 148, 2: 161, 3: 520}
    assert sum(result.frequencies().values()) == 1000
    assert_result(result, decimal_frequencies=decimal_frequencies)
    qibo.set_backend(original_backend)
    qibo.set_threads(original_threads)
示例#4
0
文件: vqe.py 项目: qiboteam/qibo
def main(nqubits,
         nlayers,
         backend,
         varlayer=False,
         method="Powell",
         maxiter=None,
         filename=None):
    """Performs a VQE circuit minimization test."""
    qibo.set_backend(backend)
    logs = BenchmarkLogger(filename)
    logs.append({
        "nqubits": nqubits,
        "nlayers": nlayers,
        "varlayer": varlayer,
        "backend": qibo.get_backend(),
        "precision": qibo.get_precision(),
        "device": qibo.get_device(),
        "threads": qibo.get_threads(),
        "method": method,
        "maxiter": maxiter
    })
    print("Number of qubits:", nqubits)
    print("Number of layers:", nlayers)
    print("Backend:", logs[-1]["backend"])

    start_time = time.time()
    if varlayer:
        circuit = varlayer_circuit(nqubits, nlayers)
    else:
        circuit = standard_circuit(nqubits, nlayers)
    hamiltonian = hamiltonians.XXZ(nqubits=nqubits)
    vqe = models.VQE(circuit, hamiltonian)
    logs[-1]["creation_time"] = time.time() - start_time

    target = np.real(np.min(K.to_numpy(hamiltonian.eigenvalues())))
    print("\nTarget state =", target)

    np.random.seed(0)
    nparams = 2 * nqubits * nlayers + nqubits
    initial_parameters = np.random.uniform(0, 2 * np.pi, nparams)

    start_time = time.time()
    options = {'disp': False, 'maxiter': maxiter}
    best, params, _ = vqe.minimize(initial_parameters,
                                   method=method,
                                   options=options,
                                   compile=False)
    logs[-1]["minimization_time"] = time.time() - start_time
    epsilon = np.log10(1 / np.abs(best - target))
    print("Found state =", best)
    print("Final eps =", epsilon)

    logs[-1]["best_energy"] = float(best)
    logs[-1]["epsilon_energy"] = float(epsilon)

    print("\nCreation time =", logs[-1]["creation_time"])
    print("Minimization time =", logs[-1]["minimization_time"])
    print("Total time =",
          logs[-1]["minimization_time"] + logs[-1]["creation_time"])
    logs.dump()
示例#5
0
def test_parallel_circuit_evaluation(backend,
                                     skip_parallel):  # pragma: no cover
    """Evaluate circuit for multiple input states."""
    device = qibo.get_device()
    backend_name = qibo.get_backend()
    if skip_parallel:
        pytest.skip("Skipping parallel test.")
    if not is_parallel_supported(backend_name):
        pytest.skip("Skipping parallel test due to unsupported configuration.")
    original_threads = qibo.get_threads()
    qibo.set_threads(1)

    nqubits = 10
    np.random.seed(0)
    c = QFT(nqubits)

    states = [np.random.random(2**nqubits) for i in range(5)]

    r1 = []
    for state in states:
        r1.append(c(state))

    r2 = parallel_execution(c, states=states, processes=2)
    np.testing.assert_allclose(r1, r2)
    qibo.set_threads(original_threads)
def test_probabilistic_measurement(backend, accelerators, use_samples):
    original_backend = qibo.get_backend()
    original_threads = qibo.get_threads()
    qibo.set_backend(backend)
    # set single-thread to fix the random values generated from the frequency custom op
    qibo.set_threads(1)
    c = models.Circuit(4, accelerators)
    c.add(gates.H(0))
    c.add(gates.H(1))
    c.add(gates.M(0, 1))
    result = c(nshots=1000)

    K.set_seed(1234)
    if use_samples:
        # calculates sample tensor directly using `tf.random.categorical`
        # otherwise it uses the frequency-only calculation
        _ = result.samples()

    # update reference values based on backend and device
    if K.name == "tensorflow":
        if K.gpu_devices:  # pragma: no cover
            # CI does not use GPU
            decimal_frequencies = {0: 273, 1: 233, 2: 242, 3: 252}
        else:
            decimal_frequencies = {0: 271, 1: 239, 2: 242, 3: 248}
    elif K.name == "numpy":
        decimal_frequencies = {0: 249, 1: 231, 2: 253, 3: 267}
    assert sum(result.frequencies().values()) == 1000
    assert_result(result, decimal_frequencies=decimal_frequencies)
    qibo.set_backend(original_backend)
    qibo.set_threads(original_threads)
示例#7
0
def test_parallel_parametrized_circuit():
    """Evaluate circuit for multiple parameters."""
    if 'GPU' in get_device():  # pragma: no cover
        pytest.skip("unsupported configuration")
    original_threads = get_threads()
    set_threads(1)

    nqubits = 5
    nlayers = 10
    c = Circuit(nqubits)
    for l in range(nlayers):
        c.add((gates.RY(q, theta=0) for q in range(nqubits)))
        c.add((gates.CZ(q, q + 1) for q in range(0, nqubits - 1, 2)))
        c.add((gates.RY(q, theta=0) for q in range(nqubits)))
        c.add((gates.CZ(q, q + 1) for q in range(1, nqubits - 2, 2)))
        c.add(gates.CZ(0, nqubits - 1))
    c.add((gates.RY(q, theta=0) for q in range(nqubits)))

    size = len(c.get_parameters())
    np.random.seed(0)
    parameters = [np.random.uniform(0, 2 * np.pi, size) for i in range(10)]
    state = None

    r1 = []
    for params in parameters:
        c.set_parameters(params)
        r1.append(c(state))

    r2 = parallel_parametrized_execution(c,
                                         parameters=parameters,
                                         initial_state=state,
                                         processes=2)
    np.testing.assert_allclose(r1, r2)
    set_threads(original_threads)
示例#8
0
文件: cgates.py 项目: NourO93/qibo
 def state_vector_call(self, state):
     return self.gate_op(
         state,
         self.matrix,
         self.qubits_tensor,  # pylint: disable=E1121
         self.nqubits,
         *self.target_qubits,
         get_threads())
示例#9
0
文件: qaoa.py 项目: qiboteam/qibo
def main(nqubits,
         nangles,
         dense=True,
         solver="exp",
         method="Powell",
         maxiter=None,
         filename=None):
    """Performs a QAOA minimization test."""

    print("Number of qubits:", nqubits)
    print("Number of angles:", nangles)
    logs = BenchmarkLogger(filename)
    logs.append({
        "nqubits": nqubits,
        "nangles": nangles,
        "dense": dense,
        "solver": solver,
        "backend": qibo.get_backend(),
        "precision": qibo.get_precision(),
        "device": qibo.get_device(),
        "threads": qibo.get_threads(),
        "method": method,
        "maxiter": maxiter
    })

    hamiltonian = hamiltonians.XXZ(nqubits=nqubits, dense=dense)
    start_time = time.time()
    qaoa = models.QAOA(hamiltonian, solver=solver)
    logs[-1]["creation_time"] = time.time() - start_time

    target = np.real(np.min(K.to_numpy(hamiltonian.eigenvalues())))
    print("\nTarget state =", target)

    np.random.seed(0)
    initial_parameters = np.random.uniform(0, 0.1, nangles)

    start_time = time.time()
    options = {'disp': True, 'maxiter': maxiter}
    best, params, _ = qaoa.minimize(initial_parameters,
                                    method=method,
                                    options=options)
    logs[-1]["minimization_time"] = time.time() - start_time

    logs[-1]["best_energy"] = float(best)
    logs[-1]["target_energy"] = float(target)
    logs[-1]["epsilon"] = np.log10(1 / np.abs(best - target))
    print("Found state =", best)
    print("Final eps =", logs[-1]["epsilon"])

    print("\nCreation time =", logs[-1]["creation_time"])
    print("Minimization time =", logs[-1]["minimization_time"])
    print("Total time =",
          logs[-1]["creation_time"] + logs[-1]["minimization_time"])
    logs.dump()
示例#10
0
def test_aavqe(backend, method, options, compile, filename, skip_parallel):
    """Performs a AAVQE circuit minimization test."""
    original_threads = qibo.get_threads()

    if method == 'parallel_L-BFGS-B':  # pragma: no cover
        if skip_parallel:
            pytest.skip("Skipping parallel test.")
        from qibo.tests.test_parallel import is_parallel_supported
        backend_name = qibo.get_backend()
        if not is_parallel_supported(backend_name):
            pytest.skip(
                "Skipping parallel test due to unsupported configuration.")
        qibo.set_threads(1)
    nqubits = 6
    layers = 4
    circuit = models.Circuit(nqubits)

    for l in range(layers):
        for q in range(nqubits):
            circuit.add(gates.RY(q, theta=1.0))
        for q in range(0, nqubits - 1, 2):
            circuit.add(gates.CZ(q, q + 1))
        for q in range(nqubits):
            circuit.add(gates.RY(q, theta=1.0))
        for q in range(1, nqubits - 2, 2):
            circuit.add(gates.CZ(q, q + 1))
        circuit.add(gates.CZ(0, nqubits - 1))
    for q in range(nqubits):
        circuit.add(gates.RY(q, theta=1.0))

    easy_hamiltonian = hamiltonians.X(nqubits)
    problem_hamiltonian = hamiltonians.XXZ(nqubits)
    s = lambda t: t
    aavqe = models.AAVQE(circuit,
                         easy_hamiltonian,
                         problem_hamiltonian,
                         s,
                         nsteps=10,
                         t_max=1)
    np.random.seed(0)
    initial_parameters = np.random.uniform(0, 2 * np.pi,
                                           2 * nqubits * layers + nqubits)
    best, params = aavqe.minimize(params=initial_parameters,
                                  method=method,
                                  options=options,
                                  compile=compile)
    if method == "cma":
        # remove `outcmaes` folder
        import shutil
        shutil.rmtree("outcmaes")
    if filename is not None:
        assert_regression_fixture(params, filename, rtol=1e-2)
    qibo.set_threads(original_threads)
示例#11
0
def main(nqubits,
         dt,
         solver,
         backend,
         dense=False,
         accelerators=None,
         filename=None):
    """Performs adiabatic evolution with critical TFIM as the "hard" Hamiltonian."""
    qibo.set_backend(backend)
    if accelerators is not None:
        dense = False
        solver = "exp"

    logs = BenchmarkLogger(filename)
    logs.append({
        "nqubits": nqubits,
        "dt": dt,
        "solver": solver,
        "dense": dense,
        "backend": qibo.get_backend(),
        "precision": qibo.get_precision(),
        "device": qibo.get_device(),
        "threads": qibo.get_threads(),
        "accelerators": accelerators
    })
    print(f"Using {solver} solver and dt = {dt}.")
    print(f"Accelerators: {accelerators}")
    print("Backend:", logs[-1]["backend"])

    start_time = time.time()
    h0 = hamiltonians.X(nqubits, dense=dense)
    h1 = hamiltonians.TFIM(nqubits, h=1.0, dense=dense)
    logs[-1]["hamiltonian_creation_time"] = time.time() - start_time
    print(f"\nnqubits = {nqubits}, solver = {solver}")
    print(f"dense = {dense}, accelerators = {accelerators}")
    print("Hamiltonians created in:", logs[-1]["hamiltonian_creation_time"])

    start_time = time.time()
    evolution = models.AdiabaticEvolution(h0,
                                          h1,
                                          lambda t: t,
                                          dt=dt,
                                          solver=solver,
                                          accelerators=accelerators)
    logs[-1]["creation_time"] = time.time() - start_time
    print("Evolution model created in:", logs[-1]["creation_time"])

    start_time = time.time()
    final_psi = evolution(final_time=1.0)
    logs[-1]["simulation_time"] = time.time() - start_time
    print("Simulation time:", logs[-1]["simulation_time"])
    logs.dump()
示例#12
0
文件: parallel.py 项目: qiboteam/qibo
def _check_parallel_configuration(processes):  # pragma: no cover
    """Check if configuration is suitable for efficient parallel execution."""
    import sys, psutil
    from qibo import get_device, get_backend, get_threads
    from qibo.config import raise_error, log
    device = get_device()
    if sys.platform == "win32" or sys.platform == 'darwin':  # pragma: no cover
        raise_error(RuntimeError,
                    "Parallel evaluations supported only on linux.")
    if get_backend() == "tensorflow":  # pragma: no cover
        raise_error(
            RuntimeError,
            f"{get_backend()} backend does not support parallel evaluations.")
    if device is not None and "GPU" in device:  # pragma: no cover
        raise_error(RuntimeError,
                    "Parallel evaluations cannot be used with GPU.")
    if ((processes is not None
         and processes * get_threads() > psutil.cpu_count())
            or (processes is None and get_threads() != 1)):  # pragma: no cover
        log.warning(
            'Please consider using a lower number of threads per process,'
            ' or reduce the number of processes for better performance')
示例#13
0
def test_vqe(backend, method, options, compile, filename):
    """Performs a VQE circuit minimization test."""
    original_backend = qibo.get_backend()
    original_threads = qibo.get_threads()
    if (method == "sgd" or compile) and backend != "matmuleinsum":
        pytest.skip("Skipping SGD test for unsupported backend.")
    qibo.set_backend(backend)

    if method == 'parallel_L-BFGS-B':
        device = qibo.get_device()
        if device is not None and "GPU" in device:  # pragma: no cover
            pytest.skip("unsupported configuration")
        import os
        if os.name == 'nt':  # pragma: no cover
            pytest.skip("Parallel L-BFGS-B not supported on Windows.")
        qibo.set_threads(1)

    nqubits = 6
    layers = 4
    circuit = models.Circuit(nqubits)
    for l in range(layers):
        for q in range(nqubits):
            circuit.add(gates.RY(q, theta=1.0))
        for q in range(0, nqubits - 1, 2):
            circuit.add(gates.CZ(q, q + 1))
        for q in range(nqubits):
            circuit.add(gates.RY(q, theta=1.0))
        for q in range(1, nqubits - 2, 2):
            circuit.add(gates.CZ(q, q + 1))
        circuit.add(gates.CZ(0, nqubits - 1))
    for q in range(nqubits):
        circuit.add(gates.RY(q, theta=1.0))

    hamiltonian = hamiltonians.XXZ(nqubits=nqubits)
    np.random.seed(0)
    initial_parameters = np.random.uniform(0, 2 * np.pi,
                                           2 * nqubits * layers + nqubits)
    v = models.VQE(circuit, hamiltonian)
    best, params, _ = v.minimize(initial_parameters,
                                 method=method,
                                 options=options,
                                 compile=compile)
    if method == "cma":
        # remove `outcmaes` folder
        import shutil
        shutil.rmtree("outcmaes")
    if filename is not None:
        assert_regression_fixture(params, filename)
    qibo.set_backend(original_backend)
    qibo.set_threads(original_threads)
示例#14
0
def test_transpose_state(nqubits, ndevices):
    for _ in range(10):
        # Generate global qubits randomly
        all_qubits = np.arange(nqubits)
        np.random.shuffle(all_qubits)
        qubit_order = list(all_qubits)
        state = random_complex((2**nqubits, ))

        state_tensor = state.numpy().reshape(nqubits * (2, ))
        target_state = np.transpose(state_tensor, qubit_order).ravel()

        new_state = K.zeros_like(state)
        shape = (ndevices, int(state.shape[0]) // ndevices)
        state = K.reshape(state, shape)
        pieces = [state[i] for i in range(ndevices)]
        if K.gpu_devices:  # pragma: no cover
            # case not tested by GitHub workflows because it requires GPU
            check_unimplemented_error(K.op.transpose_state, pieces, new_state,
                                      nqubits, qubit_order, get_threads())
        else:
            new_state = K.op.transpose_state(pieces, new_state, nqubits,
                                             qubit_order, get_threads())
            np.testing.assert_allclose(target_state, new_state.numpy())
示例#15
0
def test_swap_pieces(nqubits):
    state = random_complex((2**nqubits, ))
    target_state = K.cast(np.copy(state.numpy()), dtype=state.dtype)
    shape = (2, int(state.shape[0]) // 2)

    for _ in range(10):
        global_qubit = np.random.randint(0, nqubits)
        local_qubit = np.random.randint(0, nqubits)
        while local_qubit == global_qubit:
            local_qubit = np.random.randint(0, nqubits)

        transpose_order = ([global_qubit] + list(range(global_qubit)) +
                           list(range(global_qubit + 1, nqubits)))

        qubits_t = qubits_tensor(nqubits, [global_qubit, local_qubit])
        target_state = K.op.apply_swap(target_state, qubits_t,
                                       nqubits, global_qubit, local_qubit,
                                       get_threads())
        target_state = K.reshape(target_state, nqubits * (2, ))
        target_state = K.transpose(target_state, transpose_order)
        target_state = K.reshape(target_state, shape)

        state = K.reshape(state, nqubits * (2, ))
        state = K.transpose(state, transpose_order)
        state = K.reshape(state, shape)
        piece0, piece1 = state[0], state[1]
        if K.gpu_devices:  # pragma: no cover
            # case not tested by GitHub workflows because it requires GPU
            check_unimplemented_error(K.op.swap_pieces, piece0, piece1,
                                      local_qubit - 1, nqubits - 1,
                                      get_threads())
        else:
            K.op.swap_pieces(piece0, piece1,
                             local_qubit - int(global_qubit < local_qubit),
                             nqubits - 1, get_threads())
            np.testing.assert_allclose(target_state[0], piece0.numpy())
            np.testing.assert_allclose(target_state[1], piece1.numpy())
示例#16
0
def test_swap_pieces_zero_global(nqubits):
    state = random_complex((2**nqubits, ))
    target_state = K.cast(np.copy(state.numpy()))
    shape = (2, int(state.shape[0]) // 2)
    state = K.reshape(state, shape)

    for _ in range(10):
        local = np.random.randint(1, nqubits)

        qubits_t = qubits_tensor(nqubits, [0, local])
        target_state = K.op.apply_swap(target_state, qubits_t, nqubits, 0,
                                       local, get_threads())
        target_state = K.reshape(target_state, shape)

        piece0, piece1 = state[0], state[1]
        if K.gpu_devices:  # pragma: no cover
            # case not tested by GitHub workflows because it requires GPU
            check_unimplemented_error(K.op.swap_pieces, piece0, piece1,
                                      local - 1, nqubits - 1, get_threads())
        else:
            K.op.swap_pieces(piece0, piece1, local - 1, nqubits - 1,
                             get_threads())
            np.testing.assert_allclose(target_state[0], piece0.numpy())
            np.testing.assert_allclose(target_state[1], piece1.numpy())
示例#17
0
def test_vqe(backend, method, options, compile, filename, skip_parallel):
    """Performs a VQE circuit minimization test."""
    original_threads = qibo.get_threads()
    if (method == "sgd" or compile) and qibo.get_backend() != "tensorflow":
        pytest.skip("Skipping SGD test for unsupported backend.")

    if method == 'parallel_L-BFGS-B':  # pragma: no cover
        if skip_parallel:
            pytest.skip("Skipping parallel test.")
        from qibo.tests.test_parallel import is_parallel_supported
        backend_name = qibo.get_backend()
        if not is_parallel_supported(backend_name):
            pytest.skip(
                "Skipping parallel test due to unsupported configuration.")
        qibo.set_threads(1)

    nqubits = 6
    layers = 4
    circuit = models.Circuit(nqubits)
    for l in range(layers):
        for q in range(nqubits):
            circuit.add(gates.RY(q, theta=1.0))
        for q in range(0, nqubits - 1, 2):
            circuit.add(gates.CZ(q, q + 1))
        for q in range(nqubits):
            circuit.add(gates.RY(q, theta=1.0))
        for q in range(1, nqubits - 2, 2):
            circuit.add(gates.CZ(q, q + 1))
        circuit.add(gates.CZ(0, nqubits - 1))
    for q in range(nqubits):
        circuit.add(gates.RY(q, theta=1.0))

    hamiltonian = hamiltonians.XXZ(nqubits=nqubits)
    np.random.seed(0)
    initial_parameters = np.random.uniform(0, 2 * np.pi,
                                           2 * nqubits * layers + nqubits)
    v = models.VQE(circuit, hamiltonian)
    best, params, _ = v.minimize(initial_parameters,
                                 method=method,
                                 options=options,
                                 compile=compile)
    if method == "cma":
        # remove `outcmaes` folder
        import shutil
        shutil.rmtree("outcmaes")
    if filename is not None:
        assert_regression_fixture(params, filename)
    qibo.set_threads(original_threads)
示例#18
0
def test_parallel_circuit_evaluation():
    """Evaluate circuit for multiple input states."""
    if 'GPU' in get_device():  # pragma: no cover
        pytest.skip("unsupported configuration")
    original_threads = get_threads()
    set_threads(1)

    nqubits = 10
    np.random.seed(0)
    c = QFT(nqubits)

    states = [np.random.random(2**nqubits) for i in range(5)]

    r1 = []
    for state in states:
        r1.append(c(state))

    r2 = parallel_execution(c, states=states, processes=2)
    np.testing.assert_allclose(r1, r2)
    set_threads(original_threads)
def test_unbalanced_probabilistic_measurement(backend, use_samples):
    original_threads = qibo.get_threads()
    # set single-thread to fix the random values generated from the frequency custom op
    qibo.set_threads(1)
    state = np.array([1, 1, 1, np.sqrt(3)]) / np.sqrt(6)
    c = models.Circuit(2)
    c.add(gates.Flatten(state))
    c.add(gates.M(0, 1))
    result = c(nshots=1000)

    K.set_seed(1234)
    if use_samples:
        # calculates sample tensor directly using `tf.random.categorical`
        # otherwise it uses the frequency-only calculation
        _ = result.samples()
    # update reference values based on backend and device
    decimal_frequencies = K.test_regressions(
        "test_unbalanced_probabilistic_measurement")
    assert sum(result.frequencies().values()) == 1000
    assert_result(result, decimal_frequencies=decimal_frequencies)
    qibo.set_threads(original_threads)
示例#20
0
def test_parallel_circuit_evaluation(backend):
    """Evaluate circuit for multiple input states."""
    device = qibo.get_device()
    backend = qibo.get_backend()
    if 'GPU' in qibo.get_device(
    ) or sys.platform == "win32" or sys.platform == "darwin" or backend == "tensorflow" or backend == "qibojit":  # pragma: no cover
        pytest.skip("unsupported configuration")
    original_threads = qibo.get_threads()
    qibo.set_threads(1)

    nqubits = 10
    np.random.seed(0)
    c = QFT(nqubits)

    states = [np.random.random(2**nqubits) for i in range(5)]

    r1 = []
    for state in states:
        r1.append(c(state))

    r2 = parallel_execution(c, states=states, processes=2)
    np.testing.assert_allclose(r1, r2)
    qibo.set_threads(original_threads)
示例#21
0
def test_apply_pauli_gate(nqubits, target, gate, compile):
    """Check ``apply_x``, ``apply_y`` and ``apply_z`` kernels."""
    matrices = {
        "x": np.array([[0, 1], [1, 0]], dtype=np.complex128),
        "y": np.array([[0, -1j], [1j, 0]], dtype=np.complex128),
        "z": np.array([[1, 0], [0, -1]], dtype=np.complex128)
    }
    state = random_complex((2**nqubits, ))
    target_state = K.cast(state, dtype=state.dtype)
    qubits = qubits_tensor(nqubits, [target])
    target_state = K.op.apply_gate(state, matrices[gate], qubits, nqubits,
                                   target, get_threads())

    def apply_operator(state):
        qubits = qubits_tensor(nqubits, [target])
        return getattr(K.op, "apply_{}".format(gate))(state, qubits, nqubits,
                                                      target, get_threads())

    if compile:
        apply_operator = K.compile(apply_operator)
    state = apply_operator(state)

    np.testing.assert_allclose(target_state.numpy(), state.numpy())
示例#22
0
def test_custom_op_toy_callback(gate, compile):
    """Check calculating ``callbacks`` using intermediate state values."""
    import functools
    state = random_complex((2**2, ))
    mask = random_complex((2**2, ))

    matrices = {
        "h": np.array([[1, 1], [1, -1]]) / np.sqrt(2),
        "x": np.array([[0, 1], [1, 0]]),
        "z": np.array([[1, 0], [0, -1]])
    }
    for k, v in matrices.items():
        matrices[k] = np.kron(v, np.eye(2))
    matrices["swap"] = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0],
                                 [0, 0, 0, 1]])

    target_state = state.numpy()
    target_c1 = mask.numpy().dot(target_state)
    target_state = matrices[gate].dot(target_state)
    target_c2 = mask.numpy().dot(target_state)
    assert target_c1 != target_c2
    target_callback = [target_c1, target_c2]

    htf = K.cast(np.array([[1, 1], [1, -1]]) / np.sqrt(2), dtype=state.dtype)
    qubits_t1 = qubits_tensor(2, [0])
    qubits_t2 = qubits_tensor(2, [0, 1])
    apply_gate = {
        "h":
        functools.partial(K.op.apply_gate,
                          gate=htf,
                          qubits=qubits_t1,
                          nqubits=2,
                          target=0,
                          omp_num_threads=get_threads()),
        "x":
        functools.partial(K.op.apply_x,
                          qubits=qubits_t1,
                          nqubits=2,
                          target=0,
                          omp_num_threads=get_threads()),
        "z":
        functools.partial(K.op.apply_z,
                          qubits=qubits_t1,
                          nqubits=2,
                          target=0,
                          omp_num_threads=get_threads()),
        "swap":
        functools.partial(K.op.apply_swap,
                          qubits=qubits_t2,
                          nqubits=2,
                          target1=0,
                          target2=1,
                          omp_num_threads=get_threads())
    }

    def apply_operator(state):
        c1 = K.sum(mask * state)
        state0 = apply_gate[gate](state)
        c2 = K.sum(mask * state0)
        return state0, K.stack([c1, c2])

    if compile:  # pragma: no cover
        # case not tested because it fails
        apply_operator = K.compile(apply_operator)
    state, callback = apply_operator(state)

    np.testing.assert_allclose(target_state, state.numpy())
    np.testing.assert_allclose(target_callback, callback.numpy())
示例#23
0
 def apply_operator(state):
     qubits = qubits_tensor(nqubits, targets, controls)
     return K.op.apply_swap(state, qubits, nqubits, *targets, get_threads())
示例#24
0
文件: cgates.py 项目: NourO93/qibo
 def state_vector_call(self, state):
     return self.gate_op(state, self.qubits_tensor, self.result_tensor,
                         self.nqubits, self.normalize, get_threads())
示例#25
0
 def apply_operator(state):
     qubits = qubits_tensor(nqubits, [nqubits - 1], controls)
     return K.op.apply_gate(state, xgate, qubits, nqubits, nqubits - 1,
                            get_threads())
示例#26
0
 def apply_operator(state, gate):
     qubits = qubits_tensor(nqubits, [target])
     return K.op.apply_gate(state, gate, qubits, nqubits, target,
                            get_threads())
示例#27
0
文件: cgates.py 项目: NourO93/qibo
 def state_vector_call(self, state):
     return self.gate_op(state, self.qubits_tensor, self.nqubits,
                         *self.target_qubits, get_threads())
示例#28
0
文件: cgates.py 项目: NourO93/qibo
 def density_matrix_call(self, state):
     state = self.gate_op(state, self.qubits_tensor_dm, 2 * self.nqubits,
                          *self.target_qubits, get_threads())
     state = self.gate_op(state, self.qubits_tensor, 2 * self.nqubits,
                          *self.target_qubits_dm, get_threads())
     return state
示例#29
0
文件: cgates.py 项目: NourO93/qibo
 def density_matrix_call(self, state):
     state = self.gate_op(state, self.qubits_tensor_dm, self.result_tensor,
                          2 * self.nqubits, False, get_threads())
     state = self.gate_op(state, self.qubits_tensor, self.result_tensor,
                          2 * self.nqubits, False, get_threads())
     return state / K.trace(state)
示例#30
0
 def apply_operator(dtype):
     """Apply the initial_state operator"""
     return K.op.initial_state(nqubits=4,
                               dtype=dtype,
                               is_matrix=False,
                               omp_num_threads=get_threads())