Пример #1
0
def main(nqubits, instance, T, chainstrength, numruns, greedy, inspect):
    """

    Args:
        nqubits (int): number of qubits for the file that contains the
            information of an Exact Cover instance.
        instance (int): intance used for the desired number of qubits.
        T (float): 
        

    Returns:
        
    """
    control, solution, clauses = functions.read_file(nqubits, instance)
    nqubits = int(control[0])
    times = functions.times(nqubits, clauses)
    sh, smap = functions.h_problem(nqubits, clauses)
    Q, constant = functions.symbolic_to_dwave(sh, smap)
    

    model = dimod.BinaryQuadraticModel.from_qubo(Q, offset = 0.0)
    if not chainstrength:
        chainstrength = dwave.embedding.chain_strength.uniform_torque_compensation(model)
        print(f'Automatic chain strength: {chainstrength}\n')
    else:
        print(f'Chosen chain strength: {chainstrength}\n')

    if solution:
        print(f'Target solution that solves the problem: {" ".join(solution)}\n')

    sampler = EmbeddingComposite(DWaveSampler())
    if greedy:
        solver_greedy = SteepestDescentSolver()
        sampleset = sampler.sample(model, chain_strength=chainstrength, num_reads=numruns, annealing_time=T, answer_mode='raw')
        response = solver_greedy.sample(model, initial_states=sampleset)
    else:
        response = sampler.sample(model, chain_strength=chainstrength, num_reads=numruns, annealing_time=T, answer_mode='histogram')
    
    
    best_sample = response.record.sample[0]
    best_energy = response.record.energy[0]
    print(f'Best result found: {best_sample}\n')
    print(f'With energy: {best_energy+constant}\n')
    good_samples = response.record.sample[:min(len(response.record.sample), nqubits)]
    good_energies = response.record.energy[:min(len(response.record.energy), nqubits)]
    print(f'The best {len(good_samples)} samples found in the evolution are:\n')
    for i in range(len(good_samples)):
        print(f'Sample: {good_samples[i]}    with energy: {good_energies[i]+constant}\n')

    if inspect:
        dwave.inspector.show(response)
Пример #2
0
def main(nqubits, instance, T, dt, solver, plot, trotter, params, method,
         maxiter):
    """Adiabatic evoluition to find the solution of an exact cover instance.

    Args:
        nqubits (int): number of qubits for the file that contains the
            information of an Exact Cover instance.
        instance (int): intance used for the desired number of qubits.
        T (float): maximum schedule time. The larger T, better final results.
        dt (float): time interval for the evolution.
        solver (str): solver used for the adiabatic evolution.
        plot (bool): decides if plots of the energy and gap will be returned.
        trotter (bool): decides if a Trotter Hamiltonian will be used.
        params (list): list of polynomial coefficients for scheduling function.
            Default is linear scheduling.
        method (str): Method to use for scheduling optimization (optional).
        maxiter (bool): Maximum iterations for scheduling optimization (optional).

    Returns:
        Result of the most probable outcome after the adiabatic evolution.
        Plots of the ground and excited state energies and the underlying gap
        during the adiabatic evolution. The plots are created only if the
        ``--plot`` option is enabled.
    """
    # Read 3SAT clauses from file
    control, solution, clauses = functions.read_file(nqubits, instance)
    nqubits = int(control[0])
    # Define "easy" and "problem" Hamiltonians
    times = functions.times(nqubits, clauses)
    sh0, smap0 = functions.h_initial(nqubits, times)
    sh1, smap1 = functions.h_problem(nqubits, clauses)
    if trotter:
        print('Using Trotter decomposition for the Hamiltonian\n')
        gs = lambda: functions.ground_state(nqubits)
        H0 = hamiltonians.TrotterHamiltonian.from_symbolic(sh0,
                                                           smap0,
                                                           ground_state=gs)
        H1 = hamiltonians.TrotterHamiltonian.from_symbolic(sh1, smap1)
    else:
        print('Using the full Hamiltonian evolution\n')
        H0 = hamiltonians.Hamiltonian.from_symbolic(sh0, smap0)
        H1 = hamiltonians.Hamiltonian.from_symbolic(sh1, smap1)

    print('-' * 20 + '\n')
    if plot and nqubits >= 14:
        print('Currently not possible to calculate gap energy for {} qubits.'
              '\n Proceeding to adiabatic evolution without plotting data.\n'
              ''.format(nqubits))
        plot = False
    if plot and method is not None:
        print('Not possible to calculate gap energy during optimization.')
        plot = False

    # Define scheduling according to given params
    if params is None:
        # default is linear scheduling
        s = lambda t: t
    else:
        if method is None:
            s = lambda t: functions.spolynomial(t, params)
        else:
            s = functions.spolynomial

    # Define evolution model and (optionally) callbacks
    if plot:
        ground = callbacks.Gap(0)
        excited = callbacks.Gap(1)
        gap = callbacks.Gap()
        evolve = models.AdiabaticEvolution(H0,
                                           H1,
                                           s,
                                           dt,
                                           solver=solver,
                                           callbacks=[gap, ground, excited])
    else:
        evolve = models.AdiabaticEvolution(H0, H1, s, dt, solver=solver)

    if method is not None:
        print(f'Optimizing scheduling using {method}.\n')
        if params is None:
            params = [T]
        else:
            params.append(T)
        if method == "sgd":
            options = {"nepochs": maxiter}
        else:
            options = {"maxiter": maxiter, "disp": True}
        energy, params, _ = evolve.minimize(params,
                                            method=method,
                                            options=options)
        T = params[-1]

    # Perform evolution
    initial_state = np.ones(2**nqubits) / np.sqrt(2**nqubits)
    final_state = evolve(final_time=T, initial_state=initial_state)
    output_dec = (np.abs(final_state.numpy())**2).argmax()
    max_output = "{0:0{bits}b}".format(output_dec, bits=nqubits)
    max_prob = (np.abs(final_state.numpy())**2).max()
    print("Exact cover instance with {} qubits.\n".format(nqubits))
    if solution:
        print('Known solution: {}\n'.format(''.join(solution)))
    print('-' * 20 + '\n')
    print(f'Adiabatic evolution with total time {T}, evolution step {dt} and '
          f'solver {solver}.\n')
    print(f'Most common solution after adiabatic evolution: {max_output}.\n')
    print(f'Found with probability: {max_prob}.\n')
    if plot:
        print('-' * 20 + '\n')
        functions.plot(nqubits, ground[:], excited[:], gap[:], dt, T)
        print('Plots finished.\n')