Example #1
0
def main(nqubits, hfield, T, dt, solver, save):
    """Performs adiabatic evolution with critical TFIM as the "hard" Hamiltonian.

    Plots how the <H1> energy and the overlap with the actual ground state
    changes during the evolution.
    Linear scheduling is used.

    Args:
        nqubits (int): Number of qubits in the system.
        hfield (float): Transverse field Ising model h-field h value.
        T (float): Total time of the adiabatic evolution.
        dt (float): Time step used for integration.
        solver (str): Solver used for integration.
        save (bool): Whether to save the plots.
    """
    h0 = hamiltonians.X(nqubits)
    h1 = hamiltonians.TFIM(nqubits, h=hfield)

    # Calculate target values (H1 ground state)
    target_state = h1.ground_state()
    target_energy = h1.eigenvalues()[0].numpy().real

    # Check ground state
    state_energy = callbacks.Energy(h1)(target_state).numpy()
    np.testing.assert_allclose(state_energy.real, target_energy)

    energy = callbacks.Energy(h1)
    overlap = callbacks.Overlap(target_state)
    evolution = models.AdiabaticEvolution(h0,
                                          h1,
                                          lambda t: t,
                                          dt=dt,
                                          solver=solver,
                                          callbacks=[energy, overlap])
    final_psi = evolution(final_time=T)

    # Plots
    tt = np.linspace(0, T, int(T / dt) + 1)
    plt.figure(figsize=(12, 4))
    plt.subplot(121)
    plt.plot(tt, energy[:], linewidth=2.0, label="Evolved state")
    plt.axhline(y=target_energy,
                color="red",
                linewidth=2.0,
                label="Ground state")
    plt.xlabel("$t$")
    plt.ylabel("$H_1$")
    plt.legend()

    plt.subplot(122)
    plt.plot(tt, overlap[:], linewidth=2.0)
    plt.xlabel("$t$")
    plt.ylabel("Overlap")

    if save:
        plt.savefig(f"images/dynamics_n{nqubits}T{T}.png", bbox_inches="tight")
    else:
        plt.show()
def test_overlap():
    state0 = np.random.random(4) + 1j * np.random.random(4)
    overlap = callbacks.Overlap(state0)

    state1 = np.random.random(4) + 1j * np.random.random(4)
    target_overlap = np.abs((state0.conj() * state1).sum())
    np.testing.assert_allclose(overlap(state1), target_overlap)

    with pytest.raises(NotImplementedError):
        overlap(state1, is_density_matrix=True)
Example #3
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)
Example #4
0
def main(nqubits, hfield, params, dt, solver, method, maxiter, save):
    """Optimizes the scheduling of the adiabatic evolution.

    The ansatz for s(t) is a polynomial whose order is defined by the length of
    ``params`` given.

    Args:
        nqubits (int): Number of qubits in the system.
        hfield (float): Transverse field Ising model h-field h value.
        params (str): Initial guess for the free parameters.
        dt (float): Time step used for integration.
        solver (str): Solver used for integration.
        method (str): Which scipy optimizer to use.
        maxiter (int): Maximum iterations for scipy optimizer.
        save (str): Name to use for saving optimization history.
            If ``None`` history will not be saved.
    """
    h0 = hamiltonians.X(nqubits)
    h1 = hamiltonians.TFIM(nqubits, h=hfield)

    # Calculate target values (H1 ground state)
    target_state = h1.ground_state()
    target_energy = h1.eigenvalues()[0].numpy().real

    # Check ground state
    state_energy = callbacks.Energy(h1)(target_state).numpy()
    np.testing.assert_allclose(state_energy.real, target_energy)

    evolution = models.AdiabaticEvolution(h0,
                                          h1,
                                          spolynomial,
                                          dt=dt,
                                          solver=solver)
    options = {"maxiter": maxiter, "disp": True}
    energy, parameters, _ = evolution.minimize(params,
                                               method=method,
                                               options=options,
                                               messages=True)

    print("\nBest energy found:", energy)
    print("Final parameters:", parameters)

    final_state = evolution(parameters[-1])
    overlap = callbacks.Overlap(target_state)(final_state).numpy()
    print("Target energy:", target_energy)
    print("Overlap:", overlap)

    if save:
        evolution.opt_history["loss"].append(target_energy)
        np.save(f"optparams/{save}_n{nqubits}_loss.npy",
                evolution.opt_history["loss"])
        np.save(f"optparams/{save}_n{nqubits}_params.npy",
                evolution.opt_history["params"])
Example #5
0
def main(nqubits, hfield, T, save):
    """Compares exact with Trotterized state evolution.

    Plots the overlap between the exact final state and the state from the
    Trotterized evolution as a function of the number of time steps used for
    the discretization of time.
    The transverse field Ising model (TFIM) is used as a toy model for this
    experiment.

    Args:
        nqubits (int): Number of qubits in the system.
        hfield (float): Transverse field Ising model h-field h value.
        T (float): Total time of the adiabatic evolution.
        save (bool): Whether to save the plots.
    """
    dense_h = hamiltonians.TFIM(nqubits, h=hfield)
    trotter_h = hamiltonians.TFIM(nqubits, h=hfield, trotter=True)
    initial_state = np.ones(2 ** nqubits) / np.sqrt(2 ** nqubits)

    nsteps_list = np.arange(50, 550, 50)
    overlaps = []
    for nsteps in nsteps_list:
        exact_ev = models.StateEvolution(dense_h, dt=T/nsteps)
        trotter_ev = models.StateEvolution(trotter_h, dt=T/nsteps)
        exact_state = exact_ev(final_time=T, initial_state=np.copy(initial_state))
        trotter_state = trotter_ev(final_time=T, initial_state=np.copy(initial_state))
        overlaps.append(callbacks.Overlap(exact_state)(trotter_state).numpy())

    dt_list = T / nsteps_list
    overlaps = 1 - np.array(overlaps)

    exponent = int(linregress(np.log(dt_list), np.log(overlaps))[0])
    err = [overlaps[0] * (dt_list / dt_list[0])**(exponent - 1),
           overlaps[0] * (dt_list / dt_list[0])**exponent,
           overlaps[0] * (dt_list / dt_list[0])**(exponent + 1)]
    alphas = [1.0, 0.7, 0.4]
    labels = [r"$\delta t ^{}$".format(exponent - 1),
              r"$\delta t ^{}$".format(exponent),
              r"$\delta t ^{}$".format(exponent + 1)]

    plt.figure(figsize=(7, 4))
    plt.semilogy(nsteps_list, overlaps, marker="o", markersize=8, linewidth=2.0, label="Error")
    for e, a, l in zip(err, alphas, labels):
        plt.semilogy(nsteps_list, e, color="red", alpha=a, linestyle="--", linewidth=2.0, label=l)
    plt.xlabel("Number of steps")
    plt.ylabel("$1 -$ Overlap")
    plt.legend()

    if save:
        plt.savefig(f"images/trotter_error_n{nqubits}T{T}.png", bbox_inches="tight")
    else:
        plt.show()
Example #6
0
def test_overlap(backend, density_matrix):
    original_backend = qibo.get_backend()
    qibo.set_backend(backend)

    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())
        np.testing.assert_allclose(overlap(state1), target_overlap)
    qibo.set_backend(original_backend)