Exemplo n.º 1
0
    def test_neal(self):
        import neal

        h = {'a': -1, 'b': +1}
        J = {('a', 'b'): -1}

        resp = neal.SimulatedAnnealingSampler().sample_ising(h, J)
    def test_close_to_pois(self):
        """Check that 1 new / 0 old chargers scenario is close to centroid of POIs"""

        w, h = (15, 15)
        num_poi, num_cs, num_new_cs = (3, 0, 1)

        _, pois, charging_stations, potential_new_cs_nodes = demo.set_up_scenario(
            w, h, num_poi, num_cs)

        pois = [(0, 0), (6, 14), (14, 0)]
        centroid = np.array(pois).mean(axis=0).round().tolist()

        bqm = demo.build_bqm(potential_new_cs_nodes, num_poi, pois, num_cs,
                             charging_stations, num_new_cs)

        # random.seed(1)
        sampler = neal.SimulatedAnnealingSampler()
        new_charging_nodes = demo.run_bqm_and_collect_solutions(
            bqm, sampler, potential_new_cs_nodes, seed=42)

        new_cs_x = new_charging_nodes[0][0]
        new_cs_y = new_charging_nodes[0][1]

        self.assertLess(new_cs_x - centroid[0], 5)
        self.assertLess(new_cs_y - centroid[1], 5)
def simulatedNeal(h, J, i, j):
    h, J = convertCompatible(h, J)
    #    print(h)
    #    print(J)
    sampler = neal.SimulatedAnnealingSampler()
    sampler.parameters['sweeps'] = i
    sampler.parameters['num_reads'] = j

    response = sampler.sample_ising(h, J, sweeps=i, num_reads=j)
    #    k=np.array(response.record)
    energies = response.record['energy']
    sigmas = response.record['sample']
    #    k=np.min(energies)
    ############################
    #####    minIdx=list(energies).index(np.min(energies))
    ##########################
    #####    minSigma=sigmas[minIdx]
    #####    minSigma=minSigma.astype('float32')
    #    p=[k[i][0] for i in range(len(k))]
    #    print(response.record)
    #    for datum in response.data(['sample', 'energy']):
    #        energy0.append(datum.energy)
    #        sigma=list(datum.sample.values())

    #    print(response.record,min(energy0))
    #    return sigma,min(energy0)

    #####    minSigma=nn.Parameter(torch.from_numpy(minSigma))
    return sigmas, energies
Exemplo n.º 4
0
def get_solver(solver_type: str, solver_name: str, token):
    filters = {}
    if solver_type.endswith("QPU") and solver_name in QPU_SOLVER_NAME_LIST:
        filters[
            "topology__type"] = "pegasus" if solver_name == "ADVANTAGE" else "chimera"
        filters[
            "name__contains"] = "Advantage_system" if solver_name == "ADVANTAGE" else "DW_2000Q"
    if solver_type.endswith(
            "HYBRID") and solver_name in HYBRID_SOLVER_NAME_LIST:
        filters[
            "name__contains"] = "version2" if solver_name == "HYBRID_V2" else "v1"

    if solver_type == "SA":
        solver = neal.SimulatedAnnealingSampler()
    elif solver_type == "QPU":
        solver = DWaveSampler(client="qpu", solver=filters, token=token)
        solver = EmbeddingComposite(solver)
    elif solver_type == "HYBRID":
        solver = LeapHybridSampler(solver=filters, token=token)
    elif solver_type == "FIXED_QPU":
        solver = DWaveSampler(client="qpu", solver=filters, token=token)
        solver = LazyFixedEmbeddingComposite(solver)
    elif solver_type == "CLIQUE_FIXED_QPU":
        solver = DWaveCliqueSampler(client="qpu", solver=filters, token=token)
    else:
        raise NotImplementedError(
            "Solver {} is not implemented".format(solver_type))
    return solver
Exemplo n.º 5
0
def solve_ising(linear, quad, num_reads=10, sweeps=1000, beta_range=(1.0, 50.0)):
    """Solve Ising model with Simulated Annealing (SA) provided by neal.

    Args:
        linear (dict[label, float]): The linear parameter of the Ising model.
        
        quad (dict[(label, label), float]): The quadratic parameter of the Ising model.

        num_reads (int, default=10): Number of run repetitions of SA.

        sweeps (int, default=1000): Number of iterations in each run of SA.

        beta_range (tuple(float, float), default=(1.0, 50.0)): Tuple of start beta and end beta.

    Returns:
         dict[label, bit]: The solution of SA.
    
    >>> from pyqubo import Spin, solve_ising
    >>> s1, s2, s3 = Spin("s1"), Spin("s2"), Spin("s3")
    >>> H = (2*s1 + 4*s2 + 6*s3)**2
    >>> model = H.compile()
    >>> linear, quad, offset = model.to_ising()
    >>> solution = solve_ising(linear, quad)
    """
    max_abs_value = float(max(abs(v) for v in (list(quad.values()) + list(linear.values()))))
    scale_linear = {k: float(v) / max_abs_value for k, v in linear.items()}
    scale_quad = {k: float(v) / max_abs_value for k, v in quad.items()}
    sa = neal.SimulatedAnnealingSampler()
    sa_computation = sa.sample_ising(scale_linear, scale_quad, num_reads=num_reads,
                                     sweeps=sweeps, beta_range=beta_range)
    best = np.argmin(sa_computation.record.energy)
    best_solution = list(sa_computation.record.sample[best])
    return dict(zip(sa_computation.variables, best_solution))
Exemplo n.º 6
0
Arquivo: 5.py Projeto: Ocete/TFG
def solve_qubo_simulated(Q, all=False, num_reads=10000):
    #solver = dimod.SimulatedAnnealingSampler()
    solver = neal.SimulatedAnnealingSampler()

    start = time.time()
    response = solver.sample_qubo(Q, num_reads=num_reads)
    qpu_time = time.time() - start

    # Count the number of ocurrences
    ocurrences = defaultdict(int)
    for sample, energy in response.data(['sample', 'energy']):
        frozen_sample = frozenset(sample.items())
        ocurrences[frozen_sample] += 1

    # Format the solutions
    solutions_list = []
    printed_sols = defaultdict(bool)
    for sample, energy in response.data(['sample', 'energy']):
        frozen_sample = frozenset(sample.items())
        if not printed_sols[frozen_sample]:
            printed_sols[frozen_sample] = True
            solutions_list.append([sample, energy, ocurrences[frozen_sample]])

    # Sort the solutions by increasing energy
    sorted_sols = sorted(solutions_list, key=lambda x: +x[1])

    return sorted_sols, qpu_time
Exemplo n.º 7
0
def QUBOSolve_SA(coo_qubo, offset, N, num_reads=100, num_sweeps=1000):
    qubo_dict = dict(
        zip([('X[%d]' % (i), 'X[%d]' % (j))
             for (i, j) in zip(coo_qubo.row, coo_qubo.col)], coo_qubo.data))

    sampler = neal.SimulatedAnnealingSampler()
    start = time.time()
    response = sampler.sample_qubo(qubo_dict,
                                   num_reads=num_reads,
                                   num_sweeps=num_sweeps)
    end = time.time()

    # create a solution lil matrix, since most of entries would be zero
    # and lil is friendly to change data
    # and fill it
    lil_sol = lil_matrix((N, N), dtype=np.uint8)
    for (key, value) in response.first.sample.items():
        if int(value) != 0:
            idx = int(re.findall(r'\d+', key)[0])
            row, col = int(idx / N), int(idx % N)
            lil_sol[row, col] = 1

    print('Elapsed %.2f seconds' % (end - start))
    print('Energy: %.2f' % (response.first.energy + offset))
    return lil_sol.tocsr()
Exemplo n.º 8
0
    def simulated_annealing(self):
        print("\nSimulated Annealing....")
        import neal
        qpu = neal.SimulatedAnnealingSampler()
        self.title = "Simmulated Annealer"

        selected_features = np.zeros((len(self.features), len(self.features)))
        for k in range(1, len(self.features) + 1):
            flag = False
            print("Submitting for k={}".format(k))
            kbqm = dimod.generators.combinations(self.features, k, strength=25)
            kbqm.update(self.bqm)
            kbqm.normalize()

            while not flag:
                result = qpu.sample(kbqm, num_reads=10)
                # result = qpu.sample_ising(kbqm.to_ising()[0], kbqm.to_ising()[1], num_reads=10)
                best = result.first.sample

                if list(result.first.sample.values()).count(1) == k:
                    flag = True

            for fi, f in enumerate(self.features):
                selected_features[k - 1, fi] = best[f]
        if self.is_notebook:
            from helpers.draw import plot_feature_selection
            from helpers.plots import plot_solutions
            plot_feature_selection(self.features, selected_features,
                                   self.title)
Exemplo n.º 9
0
    def next(self, state, **runopts):
        new_samples = neal.SimulatedAnnealingSampler().sample(
            state.problem, initial_states=state.samples,
            beta_range=(self.beta, self.beta), beta_schedule_type='linear',
            num_sweeps=self.num_sweeps).aggregate()

        return state.updated(samples=new_samples)
Exemplo n.º 10
0
    def execute(self, buffer, program):

        import neal
        from collections import Counter

        counter = 0
        h = {}
        J = {}
        for inst in program.getInstructions():
            if inst.bits()[0] == inst.bits()[1]:
                h[counter] = inst.getParameter(0)
                counter += 1
            else:
                J[(inst.bits()[0], inst.bits()[1])] = inst.getParameter(0)

        sampler = neal.SimulatedAnnealingSampler()
        response = sampler.sample_ising(h, J, num_reads=self.shots)
        energies = [d.energy for d in response.data(['energy'])]
        counts_list = []
        unique_config_to_energy = {}
        for i, sample in enumerate(response):
            l = list(sample.values())
            st = ''
            for li in l:
                st += '1' if li == 1 else '0'
            counts_list.append(st)
            if not st in unique_config_to_energy:
                unique_config_to_energy[st] = energies[i]

        counts = Counter(counts_list)
        buffer.setMeasurements(counts)
        buffer.addExtraInfo('unique-configurations', unique_config_to_energy)
Exemplo n.º 11
0
 def solve_q(self):
     '''
     ######################################################
     Ekq -> E2q -> E2s ->SOL(si)-> SOL(qi)            
     ######################################################
     '''
     print('Problem with a type-q (boolean 0/1) variable')
     varOrg, varStd, Ekq = eq_standardized(self.Ekx, 'q')
     self.Ekq = Ekq
     #
     self.var_original = varOrg
     self.var_standard = varStd
     ##
     if self.verbose:
         print('Problem in symbolic standard format: ', Ekq)
     # simplifying qi**2 <- 1
     #Hkq=simplify_squares(expand(Ekq))
     Hkq = expand(simplify_sq_squares(expand(Ekq), 'q'))
     self.Hkq = Hkq
     if self.verbose:
         print('Simplified Hkq=', Hkq)
     # Ekq-> E2q
     H2q = boole_reduce(Hkq, self.delta)
     self.H2q = H2q
     if self.verbose:
         print('H2q=', H2q)
     # ALT-1: H2q->H2s, then solve using ising SA
     # ALT-2: solve H2q using q-doman SA solver
     # ----------------------
     # choose ALT-1: H2s
     # ----------------------
     H2s = Hkq2Hks(H2q)
     self.H2s = H2s
     if self.verbose:
         print('H2s=', H2s)
     #
     self.extract_ising_coeffs()
     '''
     -----------------------------------------------------------------------------
     4. SOLVE THE PROBLEM
     -----------------------------------------------------------------------------
     select a solver
     > dimod: ExaxtSolver
     > neal:  SimulatedAnnealingSampler
     '''
     #
     print('Solving the problem using neal  ...')
     solver = neal.SimulatedAnnealingSampler()
     response = solver.sample_ising(self.ising_h, self.ising_J, \
                                    sweeps=self.NSWEEPS, \
                                    num_reads=self.NREADS)
     vE = response.data_vectors['energy']
     aSol = response.samples_matrix
     idxMinE = np.argmin(vE)
     tSol = aSol[idxMinE]
     # copy solution to global class variables
     self.min_configuration = vs2q(tSol[0])
     self.min_energy = vE[idxMinE]
     self.energies = vE
     self.configurations = vs2q(aSol)
Exemplo n.º 12
0
    def solve(self):

        if (self.useQPU):
            sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
            sampleset = sampler.sample_qubo(self.Q,
                                            num_reads=self.n_reads,
                                            chain_strength=self.chain)
        elif (self.useNeal):
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = neal.SimulatedAnnealingSampler()
            sampleset = sampler.sample(bqm,
                                       num_reads=self.n_reads,
                                       chain_strength=self.chain)
        elif (self.useHyb):
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = LeapHybridSampler()
            sampleset = sampler.sample(bqm, num_reads=self.n_reads)
        else:
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = TabuSampler()
            sampleset = sampler.sample(bqm,
                                       num_reads=self.n_reads,
                                       chain_strength=self.chain)

        self.sampleset = sampleset
Exemplo n.º 13
0
    def test_solution_quality(self):
        """Run demo.py with no POIs or existing chargers to locate two new chargers"""

        w, h = (15, 15)
        num_poi, num_cs, num_new_cs = (0, 0, 2)

        _, pois, charging_stations, potential_new_cs_nodes = demo.set_up_scenario(
            w, h, num_poi, num_cs)

        bqm = demo.build_bqm(potential_new_cs_nodes, num_poi, pois, num_cs,
                             charging_stations, num_new_cs)

        # random.seed(1)
        sampler = neal.SimulatedAnnealingSampler()
        new_charging_nodes = demo.run_bqm_and_collect_solutions(
            bqm, sampler, potential_new_cs_nodes, seed=1)

        new_cs_dist = 0
        for i in range(num_new_cs):
            for j in range(i + 1, num_new_cs):
                new_cs_dist += abs(new_charging_nodes[i][0] -
                                   new_charging_nodes[j][0]) + abs(
                                       new_charging_nodes[i][1] -
                                       new_charging_nodes[j][1])

        self.assertGreater(new_cs_dist, 10)
def simulatedNeal(h,J):
    h,J=convertCompatible(h,J)
    sampler=neal.SimulatedAnnealingSampler()
    response = sampler.sample_ising(h, J)
    
    for datum in response.data(['sample', 'energy']):
        energy=datum.energy
        sigma=list(datum.sample.values())
    return sigma,energy,response
Exemplo n.º 15
0
    def __init__(self, exact=False):
        super().__init__()
        self._exact = exact

        if self._exact:
            # dimod's brute force solver
            self._solver = dimod.ExactSolver()
        else:
            # Simulated annealing (SA)
            self._solver = neal.SimulatedAnnealingSampler()
Exemplo n.º 16
0
def simulated_annealing(QUBO):
    bqm = dimod.BQM.from_qubo(QUBO)
    sampler = neal.SimulatedAnnealingSampler()


    #response = sim_sample(sampler, bqm)
    response = real_sample(sampler, bqm)


    return response
Exemplo n.º 17
0
def sample_on_dwave(Q, Quantum=False):
    bqm = dimod.BinaryQuadraticModel.from_numpy_matrix(Q)

    if Quantum:
        # Real
        sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
        return sampler.sample(bqm, chain_strength=chstr)

    # Simulated
    sampler = neal.SimulatedAnnealingSampler()
    return sampler.sample(bqm=bqm, num_reads=numr)
Exemplo n.º 18
0
    def test_response_converter(self):
        try:
            from dimod.sampleset import SampleSet
            import neal
        except ImportError:
            print(' skip')
            return

        neal_sampler = neal.SimulatedAnnealingSampler()
        Q = {(1, 2): -1, (2, 3): -1}
        response = neal_sampler.sample_qubo(Q)
        oj_res = oj.convert_response(response)
Exemplo n.º 19
0
def num_of_errors_in_chain_strengths(qpu=False):
    jobs = {
        "1": [(0, 2), (1, 1), (2, 1)],
        "2": [(1, 1), (0, 1), (3, 2)],
        "3": [(2, 1), (3, 1), (1, 1)]
    }

    strengths = (0.5, 1, 1.5, 1.8, 2.0, 2.1, 2.3, 2.5, 3.0, 3.5, 4.0)
    errors = defaultdict(list)
    for strength in strengths:
        for i in range(12):
            print("tick " + str(strength) + " " + str(i))
            try:
                bqm = get_jss_bqm(jobs,
                                  8,
                                  stitch_kwargs={'min_classical_gap': 2.0})
                if qpu:
                    sampler = EmbeddingComposite(
                        DWaveSampler(solver={'qpu': True}))
                    sampleset = sampler.sample(bqm,
                                               chain_strength=strength,
                                               num_reads=1000)
                else:
                    sampler = neal.SimulatedAnnealingSampler()
                    sampleset = sampler.sample(bqm, num_reads=1000)
                sol_dict = printResults(sampleset, jobs)
                errors[strength].append(sol_dict['error'])
            except Exception as e:
                print(f"error: {strength}")
                print(e)
                continue
    medians = []
    margins = []
    for key, values in errors.items():
        values.sort()
        values = values[1:-1]
        medians.append(median(values))
        margins.append([
            abs(values[0] - median(values)),
            abs(values[-1] - median(values))
        ])
    plt.errorbar(errors.keys(),
                 medians,
                 yerr=np.array(margins).T,
                 fmt='o-',
                 color='blue')
    plt.xlabel('chain strength')
    plt.ylabel('number of error solutions provided (out of 1000)')
    # plt.show()
    plt.savefig('chain_strength.png')
    print(errors)
Exemplo n.º 20
0
    def solve_s(self):
        '''
        solve problem with variable 's'
        '''
        print('Problem with a type-s (spin -1,+1) variable')
        varOrg, varStd, Eks = eq_standardized(self.Ekx, 's')
        #
        self.var_original = varOrg
        self.var_standard = varStd
        print('problem in symbolic standard format', Eks)
        # remove squared variables
        #Hks=simplify_squares(expand(Eks))
        Hks = expand(simplify_sq_squares(expand(Eks), 's'))
        self.Hks = Hks
        if self.verbose:
            print('Hks->', Hks)
        # k-body to 2-body conversion, assume that k-max is 4
        Hkq = Hks2Hkq(Hks)
        self.Hkq = Hkq
        H2q = boole_reduce(Hkq, self.delta)
        self.H2q = H2q
        H2s = Hkq2Hks(H2q)
        self.H2s = H2s
        #
        self.extract_ising_coeffs()
        '''
        -----------------------------------------------------------------------------
        4. SOLVE THE PROBLEM
        -----------------------------------------------------------------------------
        select a solver
        > dimod: ExaxtSolver
        > neal:  SimulatedAnnealingSampler
        '''
        #
        print('Solving the problem using neal  ...')
        solver = neal.SimulatedAnnealingSampler()
        response = solver.sample_ising(self.ising_h, self.ising_J, sweeps=self.NSWEEPS, \
                                       num_reads=self.NREADS)
        #
        vE = response.data_vectors['energy']
        aSol = response.samples_matrix

        #
        idxMinE = np.argmin(vE)
        tSol = aSol[idxMinE]
        # copy solution to class global variables
        self.min_configuration = tSol[0]
        self.min_energy = vE[idxMinE]
        self.energies = vE
        self.configurations = aSol
Exemplo n.º 21
0
def sa_solver(bqm, previous_solution, num_reads=100):
    sampler = neal.SimulatedAnnealingSampler()
    response = sampler.sample(bqm, num_reads=num_reads)
    current_solution = previous_solution
    for sample, energy in response.data(['sample', 'energy']):
        if sum(sample.values()) > 0:
            current_solution = sample
            size = len(previous_solution)
            solution = []
            for i in range(size):
                key = 'x[{}]'.format(i)
                solution.append(current_solution[key])
            current_solution = np.array(solution)
    return current_solution
Exemplo n.º 22
0
def num_of_errors_in_min_gap(qpu=False, start=1.0):
    jobs = {"1": [(0, 2), (1, 1), (2, 1)],
            "2": [(1, 1), (2, 2), (0, 1)],
            "3": [(2, 2), (0, 1), (1, 2)]}

    # best_solution = { "1": [0,2,4],
    #                   "2": [0,2,4],
    #                   "3": [0,2,3]}
    #  result: 5

    import csv
    # wyniki.csv structure:
    # min_classical_gap, not found, incorrect, num_of_reads, 5, 6, 7, 8, 9, more

    with open("wyniki_min_gap.csv", mode='a') as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)

        # strengths = (25, 30, 35, 40, 45)
        # strengths = list(range(20, 25))
        from numpy import arange
        gaps = list(arange(start, start+.5, 0.1))
        num_reads = 1000
        for gap in gaps:
            for _ in range(10):
                try:
                    bqm = get_jss_bqm(jobs, 8, stitch_kwargs={
                        'min_classical_gap': gap})
                    if qpu:
                        sampler = EmbeddingComposite(
                            DWaveSampler(solver={'qpu': True}))
                        sampleset = sampler.sample(
                            bqm, chain_strength=10.0, num_reads=num_reads)
                    else:
                        sampler = neal.SimulatedAnnealingSampler()
                        sampleset = sampler.sample(bqm, num_reads=num_reads)
                    sol_dict = printResults(sampleset, jobs)
                except Exception as e:
                    print(f"error: {gap}")
                    print(e)
                    from time import sleep
                    sleep(60)
                    continue
                result_row = [gap, sol_dict['error'], sol_dict['incorrect'],
                               num_reads] + [sol_dict[i] for i in range(5, 10)]
                filewriter.writerow(result_row)
                print('zapisane', gap)

        from time import sleep
        sleep(30)
Exemplo n.º 23
0
def num_of_errors_in_times(qpu=False):
    jobs = {
        "1": [(0, 2), (1, 1), (0, 1)],
        "2": [(1, 1), (0, 1), (2, 2)],
        "3": [(2, 1), (2, 1), (1, 1)]
    }

    times = range(4, 12)
    errors = defaultdict(list)
    for time in times:
        for i in range(12):
            try:
                bqm = get_jss_bqm(jobs,
                                  time,
                                  stitch_kwargs={'min_classical_gap': 2.0})
                if qpu:
                    sampler = EmbeddingComposite(
                        DWaveSampler(solver={'qpu': True}))
                    sampleset = sampler.sample(bqm,
                                               chain_strength=2,
                                               num_reads=1000)
                else:
                    sampler = neal.SimulatedAnnealingSampler()
                    sampleset = sampler.sample(bqm, num_reads=1000)
                sol_dict = printResults(sampleset, jobs)
                errors[time].append(sol_dict['error'])
            except:
                print(f"error: {time}")
                continue
    medians = []
    margins = []
    for key, values in errors.items():
        values.sort()
        values = values[1:-1]
        medians.append(median(values))
        margins.append([
            abs(values[0] - median(values)),
            abs(values[-1] - median(values))
        ])
    plt.errorbar(errors.keys(),
                 medians,
                 yerr=np.array(margins).T,
                 fmt='o',
                 color='blue')
    plt.xlabel('max_time value')
    plt.ylabel('number of error solutions provided (out of 1000)')
    # plt.show()
    plt.savefig('times.png')
    print(errors)
Exemplo n.º 24
0
Arquivo: tc.py Projeto: chunyulin/sumo
def qubo(Coeff):
    #print("      Coeff: {}".format(Coeff) )
    lamda1 = -1
    lamda4 = 100
    Q1 = sum(x * Coeff)
    H = lamda1 * Q1 + lamda4 * Q_mode_constrain
    model = H.compile()
    bqm = model.to_bqm()
    sa = neal.SimulatedAnnealingSampler()
    sampleset = sa.sample(bqm, num_reads=20)
    decoded_samples = model.decode_sampleset(sampleset)
    best_sample = min(decoded_samples, key=lambda x: x.energy)
    opt = best_sample.sample
    #print("SA-Opt:{}  Energy:{}".format(best_sample.sample, best_sample.energy) )
    return opt
Exemplo n.º 25
0
def solve_ising(linear,
                quad,
                num_reads=10,
                sweeps=1000,
                beta_range=(1.0, 50.0)):
    """[deprecated] Solve Ising model with Simulated Annealing (SA) provided by neal.

    Args:
        linear (dict[label, float]): The linear parameter of the Ising model.
        
        quad (dict[(label, label), float]): The quadratic parameter of the Ising model.

        num_reads (int, default=10): Number of run repetitions of SA.

        sweeps (int, default=1000): Number of iterations in each run of SA.

        beta_range (tuple(float, float), default=(1.0, 50.0)): Tuple of start beta and end beta.

    Note:

        :func:`solve_ising` is deprecated. Use `dwave-neal` package instead like below.

        >>> from pyqubo import Spin
        >>> import neal
        >>> s1, s2, s3 = Spin("s1"), Spin("s2"), Spin("s3")
        >>> H = (2*s1 + 4*s2 + 6*s3)**2
        >>> model = H.compile()
        >>> bqm = model.to_bqm()
        >>> sa = neal.SimulatedAnnealingSampler()
        >>> sampleset = sa.sample(bqm, num_reads=10)
        >>> samples = model.decode_sampleset(sampleset)
        >>> best_sample = min(samples, key=lambda s: s.energy)
        >>> pprint(best_sample.sample) # doctest: +SKIP
        {'s1': 0, 's2': 0, 's3': 1}
    """
    max_abs_value = float(
        max(abs(v) for v in (list(quad.values()) + list(linear.values()))))
    scale_linear = {k: float(v) / max_abs_value for k, v in linear.items()}
    scale_quad = {k: float(v) / max_abs_value for k, v in quad.items()}
    sa = neal.SimulatedAnnealingSampler()
    sa_computation = sa.sample_ising(scale_linear,
                                     scale_quad,
                                     num_reads=num_reads,
                                     num_sweeps=sweeps,
                                     beta_range=beta_range)
    best = np.argmin(sa_computation.record.energy)
    best_solution = list(sa_computation.record.sample[best])
    return dict(zip(sa_computation.variables, best_solution))
    def __init__(self, B, K, C, gamma, xi, N, sampler_type) -> None:
        self.gamma = gamma
        self.B = B
        self.K = K
        self.C = C
        self.xi = xi
        self.N = N
        self.sampler_type = sampler_type

        if (sampler_type == 'HQPU'):
            self.sampler = LeapHybridSampler()
        if (sampler_type == 'SA'):
            self.sampler = neal.SimulatedAnnealingSampler()
        if (sampler_type == 'QPU'):
            self.sampler = EmbeddingComposite(DWaveSampler())

        pass
Exemplo n.º 27
0
def qubo(Coeff):
    print("      Coeff: {}".format(Coeff) )
    lamda1 = -1; lamda4 = 100;
    Q1 = sum(x*Coeff)
    H = lamda1*Q1 + lamda4*Q_mode_constrain
    model = H.compile()
    bqm = model.to_bqm()
    sa = neal.SimulatedAnnealingSampler()
    sampleset = sa.sample(bqm, num_reads=20)
    decoded_samples = model.decode_sampleset(sampleset)
    best_sample = min(decoded_samples, key=lambda x: x.energy)
    opt = best_sample.sample
    #print("SA-Opt:{}  Energy:{}".format(best_sample.sample, best_sample.energy) )
    ## Q: Is it possiable to have more than one activate mode in a junction if lambda4 is too small ? 
    ## Do we have to check that ?
    
    return opt
Exemplo n.º 28
0
def generate_stars(N: int, nstars: int, annealer="neal", num_reads=100):
    """
    Generate valid star positions on grid.
    Return a list of positions and an np.array.
    
    Annealer may be:
        1. 'neal' (simulated);
        2. 'leap' (real)."""

    g = 1
    Q = constraint_two_dont_touch(N)
    regions = [*row_regions(N), *column_regions(N)]
    for region in regions:
        Q = Q + g * region_constraint(region, nstars)
    
    if annealer == 'neal':
        sampler = neal.SimulatedAnnealingSampler()
        sampleset = sampler.sample_qubo(Q, num_reads=num_reads)
        
    elif annealer == 'leap':  # Go to DWave
        sampler = LeapHybridSampler()
        sampleset = sampler.sample_qubo(Q)
        
    else:
        raise Exception(f"Annealer {annealer} not recognized.")

        
    minimum_theo = -2 * N * nstars**2 * g
    
    valid_samples = []
    
    sorted_records = sorted(sampleset.record, key=lambda r: r.energy)
    variables = sampleset.variables
    
    for record in sorted_records:
        sample = {x_ij: value for x_ij, value in zip(variables, record.sample)}
        energy = record.energy

        cond_1 = confirm_solution_stars(sample, regions, nstars)
        cond_2 = abs(energy - minimum_theo) < 1e-6

        if not cond_1 | cond_2:
            break
            
        # Return a list of positions and an np.array.
        yield star_solutions(N, sample)
Exemplo n.º 29
0
def solve_qubo_simulated(Q,
                         all=False,
                         print_it=False,
                         save_it=False,
                         num_reads=10000):
    #solver = dimod.SimulatedAnnealingSampler()
    sampler = neal.SimulatedAnnealingSampler()

    start = time.time()
    response = sampler.sample_qubo(Q, num_reads=num_reads)
    qpu_time = time.time() - start

    # Count the number of ocurrences
    ocurrences = defaultdict(int)
    for sample, energy in response.data(['sample', 'energy']):
        frozen_sample = frozenset(sample.items())
        ocurrences[frozen_sample] += 1

    # Print the results
    if print_it:
        printed = defaultdict(bool)
        for sample, energy in response.data(['sample', 'energy']):
            frozen_sample = frozenset(sample.items())
            if not printed[frozen_sample]:
                printed[frozen_sample] = True
                print('({}, {}) --> {:.4f}'.format(sample,
                                                   ocurrences[frozen_sample],
                                                   energy))

    if save_it:
        target = open('results.txt', 'w')
        target.write('{\n')
        printed_2 = defaultdict(bool)

        for sample, energy in response.data(['sample', 'energy']):
            frozen_sample = frozenset(sample.items())
            if not printed_2[frozen_sample]:
                printed_2[frozen_sample] = True
                target.write('{}: ({}, {:.4f}),\n'.format(
                    frozen_sample, ocurrences[frozen_sample], energy))

        target.write('}')

    return qpu_time
Exemplo n.º 30
0
    def next(self, state, **runopts):
        beta = state.get('beta', self.beta)
        seed = runopts.pop('seed', self.seed)
        aggregate = runopts.pop('aggregate', self.aggregate)

        new_samples = neal.SimulatedAnnealingSampler().sample(
            state.problem,
            initial_states=state.samples,
            beta_range=(beta, beta),
            beta_schedule_type='linear',
            num_reads=self.num_reads,
            initial_states_generator='tile',
            num_sweeps=self.num_sweeps,
            seed=seed)

        if aggregate:
            new_samples = new_samples.aggregate()

        return state.updated(samples=new_samples)