Ejemplo n.º 1
0
 def __init__(self,
              num_reads=None,
              initial_states_generator='random',
              **runopts):
     super(SteepestDescentSubproblemSampler, self).__init__(**runopts)
     self.num_reads = num_reads
     self.initial_states_generator = initial_states_generator
     self.sampler = SteepestDescentSolver()
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
class SteepestDescentProblemSampler(traits.ProblemSampler, traits.SISO, Runnable):
    """A steepest descent solver for a complete problem.

    Args:
        num_reads (int, optional, default=len(state.samples) or 1):
            Number of states (output solutions) to read from the sampler.

        initial_states_generator (str, 'none'/'tile'/'random', optional, default='random'):
            Defines the expansion of input state samples into `initial_states`
            for the steepest descent, if fewer than `num_reads` samples are
            present. See :meth:`greedy.sampler.SteepestDescentSolver.sample`.

    """

    def __init__(self, num_reads=None, initial_states_generator='random', **runopts):
        super(SteepestDescentProblemSampler, self).__init__(**runopts)
        self.num_reads = num_reads
        self.initial_states_generator = initial_states_generator
        self.sampler = SteepestDescentSolver()

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                       "initial_states_generator={self.initial_states_generator!r})").format(self=self)

    def next(self, state, **runopts):
        samples = self.sampler.sample(
            state.problem, num_reads=self.num_reads,
            initial_states=state.samples,
            initial_states_generator=self.initial_states_generator)
        return state.updated(samples=samples)
Ejemplo n.º 4
0
    def get_sampler(self, profile, solver):
        "Return a dimod.Sampler object and associated solver information."
        # Handle built-in software samplers as special cases.
        info = {}
        if solver != None:
            info["solver_name"] = solver
        if solver == "exact":
            return ExactSolver(), info, {}
        elif solver == "neal":
            return SimulatedAnnealingSampler(), info, {}
        elif solver == "tabu":
            return TabuSampler(), info, {}
        elif solver == "greedy":
            return SteepestDescentSolver(), info, {}
        elif solver == "kerberos" or (solver != None and solver[:9] == "kerberos,"):
            base_sampler = KerberosSampler()
            try:
                sub_sampler_name = solver.split(",")[1]
            except IndexError:
                sub_sampler_name = None
            sub_sampler, sub_info, params = self.get_sampler_from_config(profile, sub_sampler_name, "qpu")
            info.update(self._recursive_properties(sub_sampler))
            info["solver_name"] = "kerberos + %s" % sub_info["solver_name"]
            params["qpu_sampler"] = sub_sampler
            return base_sampler, info, params
        elif solver == "qbsolv" or (solver != None and solver[:7] == "qbsolv,"):
            base_sampler = QBSolv()
            try:
                sub_sampler_name = solver.split(",")[1]
            except IndexError:
                sub_sampler_name = None
            sub_sampler, sub_info, params = self.get_sampler(profile, sub_sampler_name)
            if getattr(sub_sampler, "structure", None) != None:
                sub_sampler = EmbeddingComposite(sub_sampler)
            info.update(self._recursive_properties(sub_sampler))
            info["solver_name"] = "QBSolv + %s" % sub_info["solver_name"]
            params["solver"] = sub_sampler
            return base_sampler, info, params

        # In the common case, read the configuration file, either the
        # default or the one named by the DWAVE_CONFIG_FILE environment
        # variable.
        return self.get_sampler_from_config(profile, solver)
Ejemplo n.º 5
0
def main(bits, T, chainstrength, numruns, control, greedy, inspect, repeat):
    """

    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:
        
    """
    x = symbols(' '.join((f'x{i}' for i in range(1, bits+1))))
    if bits == 3:
        ancillas = (symbols(' '.join((f'xa{i}' for i in range(1, 2)))), )
        f = functions.f_3(*x)
        r = functions.r_3()
    elif bits == 8:
        ancillas = symbols(' '.join((f'xa{i}' for i in range(1, 23))))
        f = functions.f_8(*x)
        r = functions.r_8()
    else:
        raise ValueError('Only instances for 3 and 8 bits are supported.\n')
        
    sym = x+ancillas
    symbol_num = {}
    for i in range(len(sym)):
        symbol_num[sym[i]] = i
    print(f'Solving a {bits} bit instance of a nonlinear function using Adiabatic Evolution.\n')
    print('Creating problem Hamiltonian.\n')
    h = functions.to_hamiltonian(f, r, sym)
    terms = functions.check_interactions(h)
    print('Number of terms for each k-body interactions.\n')
    print(terms, '\n')
    print('Reducing the k-body interactions using ancillas.\n')
    if control:
        h2, anc = functions.to_gadget_ruge2(h, sym, ancillas, bits)
    else:
        h2, anc = functions.to_gadget_ruge1(h, sym, ancillas, bits)
        
        
    terms = functions.check_interactions(h2, high=False)
    print(f'Total number of qubits needed for the 2-local hamiltonian encoding {bits} bits: {anc+bits}.\n')
    print('Number of terms for each k-body interactions after gadget aplication.\n')
    print(terms, '\n')
    
    
    functions.check_two_body(h2)
    Q, constant = functions.symbolic_to_dwave(h2, symbol_num)

    model = dimod.BinaryQuadraticModel.from_qubo(Q, offset = 0.0)
    if not chainstrength:
        chainstrength = 0
        for i in Q.values():
            chainstrength += abs(i)
        chainstrength *= 3/len(Q)
        #chainstrength = dwave.embedding.chain_strength.uniform_torque_compensation(model)
        print(f'Automatic chain strength: {chainstrength}\n')
    else:
        print(f'Chosen chain strength: {chainstrength}\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')
    
    record = response.record
    order = np.argsort(record['energy'])
    best_sample = record.sample[order[0]]
    best_energy = record.energy[order[0]]
    print(f'Best result found:\n')
    print(f'Relevant bits: {best_sample[:bits]}\n')
    print(f'Ancillas: {best_sample[bits:]}\n')
    print(f'With energy: {best_energy+constant}\n')
    print(f'The best {min(len(record.sample), bits)} samples found in the evolution are:\n')
    for i in range(min(len(record.sample), bits)):
        print(f'Bits: {record.sample[order[i]][:bits]}    Ancillas: {record.sample[order[i]][bits:]}    with energy: {record.energy[order[i]]+constant}\n')

    if inspect:
        dwave.inspector.show(response)

    fix = []
    out = []
    if repeat:
        for i in range(3):
            c = 0
            for j in range(len(sym)):
                if j in fix:
                    continue
                else:
                    a = True
                    b = record.sample[order[0]][c]
                    for k in range(min(len(record.sample), bits)):
                        if b != record.sample[order[k]][c]:
                            a = False
                    if a:
                        fix.append(j)
                        out.append(b)
                    c += 1
            print(f'The same value was found in positions {fix} \n')
            print(f'with values {out}.\n')
            for j in range(len(fix)):
                h2 = h2.subs(sym[fix[j]], out[j])
            terms = functions.check_interactions(h2, high=False)
            print(f'Total number of qubits needed for the next step: {bits+anc-len(fix)}.\n')
            print('Number of terms for each k-body interactions after gadget aplication.\n')
            print(terms, '\n')
            Q, constant = functions.symbolic_to_dwave(h2, symbol_num)

            model = dimod.BinaryQuadraticModel.from_qubo(Q, offset = 0.0)
            if not chainstrength:
                chainstrength = 0
                for i in Q.values():
                    chainstrength += abs(i)
                chainstrength *= 3/len(Q)
                #chainstrength = dwave.embedding.chain_strength.uniform_torque_compensation(model)
                print(f'Automatic chain strength: {chainstrength}\n')
            else:
                print(f'Chosen chain strength: {chainstrength}\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')
            record = response.record
            order = np.argsort(record['energy'])
            best_sample = record.sample[order[0]]
            best_energy = record.energy[order[0]]
            print(f'Best result found: {best_sample}\n')
            print(f'With energy: {best_energy+constant}\n')
            print(f'The best {min(len(record.sample), bits)} samples found in the evolution are:\n')
            for i in range(min(len(record.sample), bits)):
                print(f'Result: {record.sample[order[i]]}    with energy: {record.energy[order[i]]+constant}\n')
    print('Reconstructing state...\n')
    c = 0
    result = []
    for i in range(len(sym)):
        if i in fix:
            result.append(out[fix.index(i)])
        else:
            result.append(best_sample[c])
            c += 1
    print(f'Reconstructed result:\n')
    print(f'Relevant bits: {result[:bits]}\n')
    print(f'Ancillas: {result[bits:]}\n')
    for i in range(bits):
        h = h.subs(sym[i], result[i])
    print(f'With total energy: {h}\n')