Example #1
0
    def __init__(self, num_reads=100, qpu_sampler=None):
        super(QPUSubproblemExternalEmbeddingSampler, self).__init__()

        self.num_reads = num_reads
        if qpu_sampler is None:
            qpu_sampler = DWaveSampler()
        self.sampler = qpu_sampler
Example #2
0
def main():
    """Entrypoint of this script.

    Synopsis is as follows:
      - construct qubo of some predefined size
      - solve it using QBSolv with patched sampler
      - show what is recorded
    """
    with open('dwave_credentials.txt') as token_file:
        token = token_file.read()

    qubo_dict = get_random_qubo(50)
    sampler = EmbeddingComposite(DWaveSampler(token=token, endpoint=ENDPOINT))

    with record_sampler_invocations(sampler) as records:
        response = QBSolv().sample_qubo(qubo_dict,
                                        solver_limit=30,
                                        solver=sampler)

    print('Sampler was invoked this many times: {}'.format(len(records)))

    # In this example we take only qubo calls - when I tested it it were the only
    # ones made
    qubo_timings = [
        record['timing'] for record in records if record['method'] == 'qubo'
    ]
    total_sampling_time = sum(record['qpu_sampling_time']
                              for record in qubo_timings)
    print('Average QPU sampling time [QUBO]: {}'.format(total_sampling_time /
                                                        len(qubo_timings)))
Example #3
0
    def test_typical(self):
        class MockScheduleSampler(DWaveSampler):
            parameters = {'anneal_schedule': ''}
            properties = {
                'max_anneal_schedule_points': 4,
                'annealing_time_range': [1, 2000]
            }

            def __init__(self):
                pass

        DWaveSampler.validate_anneal_schedule(
            MockScheduleSampler(),
            [[0.0, 0.0], [0.2, 0.2], [5.2, 0.2], [6.0, 1.0]])
        DWaveSampler.validate_anneal_schedule(MockScheduleSampler(),
                                              [(0, 1), (55.0, 0.45),
                                               (155.0, 0.45), (210.0, 1)])
Example #4
0
    def execute(self, buffer, program):
        from dwave.system.samplers import DWaveSampler
        from dwave.system.composites import EmbeddingComposite, FixedEmbeddingComposite
        from collections import Counter
        import dimod

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

        buffer.setSize(max(h.keys())+1)

        if buffer.hasExtraInfoKey('embedding'):
            sampler = FixedEmbeddingComposite(DWaveSampler(token=self.token, solver=self.backend), buffer['embedding'])
        else:
            sampler = EmbeddingComposite(DWaveSampler(token=self.token, solver=self.backend))

        if program.getTag() == "ising":
            response = sampler.sample_ising(h, J, num_reads=self.shots, return_embedding=True)
        else:
            response = sampler.sample_qubo(Q, chain_strength=self.chain_strength, num_reads=self.shots, return_embedding=True)

        if not buffer.hasExtraInfoKey('embedding'):
            # we used embeddingcomposite, get the computed
            # embedding
            emb = response.info['embedding_context']['embedding']
            buffer.addExtraInfo('embedding', emb)

        counts_list = []
        e_map = {}
        for r in response.record:
            sample, energy, nocc, _ = r
            bitstring = ''.join([str(s if s == 1 else 0) for s in sample])
            for i in range(nocc):
                counts_list.append(bitstring)
            e_map[bitstring] = energy

        counts = Counter(counts_list)
        buffer.setMeasurements(counts)
        buffer.addExtraInfo('energies', e_map)
Example #5
0
    def test_init_generic_behavior(self, MockClient):
        """Generic solver behavior (default prior to 0.10.0) can be forced."""

        sampler = DWaveSampler(client='base')

        MockClient.from_config.assert_called_once_with(
            client='base',
            defaults={'solver': {'order_by': '-num_active_qubits'}})
Example #6
0
    def test_init_default(self, MockClient):
        """QPU with the highest number of qubits chosen by default."""

        sampler = DWaveSampler()

        MockClient.from_config.assert_called_once_with(
            client='qpu',
            defaults={'solver': {'order_by': '-num_active_qubits'}})
Example #7
0
 def solve_tsp(self):
     response = EmbeddingComposite(
         DWaveSampler(token=self.sapi_token,
                      endpoint=self.url)).sample_qubo(
                          self.qubo_dict,
                          chain_strength=self.chainstrength,
                          num_reads=self.numruns)
     self.get_solutions(response)
     return self.solution, self.distribution
    def __init__(self,
                 objective_function=None,
                 dwave_sampler=None,
                 dwave_sampler_kwargs=None,
                 experiment_type=None,
                 population_size=1,
                 num_reads=1,
                 num_iters=None):
        super().__init__(objective_function=objective_function)

        self.n_obj = self.objective_function.n

        self.n_qubo = self.n_obj - 1
        self.dwave_solver = None
        self.sampler_kwargs = None
        self.qpu = False
        self.population_size = population_size
        self.num_reads = num_reads

        # Initialize dwave sampler:
        if dwave_sampler == 'QPU':
            self.dwave_solver = EmbeddingComposite(DWaveSampler())
            self.qpu = True
            if dwave_sampler_kwargs:
                self.sampler_kwargs = dwave_sampler_kwargs
            else:
                self.sampler_kwargs = dict()
        elif dwave_sampler == 'SA':
            self.dwave_solver = SimulatedAnnealingSampler()
            if num_reads:
                self.sampler_kwargs = {'num_reads': num_reads}
            else:
                self.sampler_kwargs = {'num_reads': 25}
        elif dwave_sampler == 'Tabu':
            self.dwave_solver = TabuSampler()
            if num_reads:
                self.sampler_kwargs = {'num_reads': num_reads}
            else:
                self.sampler_kwargs = {'num_reads': 250}

        self.stopwatch = 0

        if experiment_type == 'time_lim':
            self.n_iters = 1000
            self.time_limit = 30

        if experiment_type == 'iter_lim' and num_iters:
            self.n_iters = num_iters
            self.time_limit = False
        else:
            self.n_iters = 50
            self.time_limit = False

        self.form_qubo = NewLQUBO(objective_function=self.objective_function)

        self.solution = self.objective_function.min_v
Example #9
0
 def __init__(self, num_copies=1):
     self.endpoint = 'https://cloud.dwavesys.com/sapi'
     self.token = 'DEV-db4d47e5313cf3c52cac31dace7c5080a5ffc46d'
     self.solver = 'DW_2000Q_2_1'
     self.gamma = 1400
     self.chainstrength = 4700
     self.num_copies = num_copies
     self.child = DWaveSampler(endpoint=self.endpoint,
                               token=self.token,
                               solver=self.solver)
Example #10
0
    def test_solver_init(self, MockClient):
        """Deprecation warning is raised for `solver_features` use, but it still works."""

        # assertWarns not available in py2
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            DWaveSampler(solver_features={'qpu': True})
            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[-1].category, DeprecationWarning))

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            DWaveSampler(solver={'qpu': True})
            self.assertEqual(len(w), 0)

        MockClient.reset_mock()
        solver = {'qpu': True, 'num_qubits__gt': 1000}
        sampler = DWaveSampler(solver=solver)
        MockClient.from_config.assert_called_once_with(solver=solver)
Example #11
0
    def test_simple(self):
        sampler = DWaveSampler(solver={'qpu': True})

        embedding = minorminer.find_embedding([[0, 1], [1, 2], [0, 2]],
                                              sampler.edgelist)

        fbo1 = self.step1(sampler, embedding)
        fbo2 = self.step2(sampler, embedding)

        self.assertEqual(fbo1, fbo2)
Example #12
0
 def __init__(self, num_copies=1):
     self.endpoint = 'YOUR URL'
     self.token = 'YOUR TOKEN'
     self.solver = 'YOUR SOLVER'
     self.gamma = 1400
     self.chainstrength = 4700
     self.num_copies = num_copies
     self.child = DWaveSampler(endpoint=self.endpoint,
                               token=self.token,
                               solver=self.solver)
Example #13
0
File: 5.py Project: Ocete/TFG
def solve_qubo_dwave(Q, n_genome_reads, num_reads=100):
    # Create the solver (connecting to D-Wave) and the Sampler
    config_file = '../dwave_adv.conf'
    client = Client.from_config(config_file, profile='ocete')
    solver = client.get_solver('Advantage_system1.1')
    dwsampler = DWaveSampler(solver={
        'qpu': True,
        'topology__type': 'pegasus'
    },
                             token=token,
                             endpoint=endpoint)

    # We need to embed Q into a valid graph for the D-Wave architecture
    adjdict = edgelist_to_adjacency(solver.edges)
    embed = minorminer.find_embedding(Q, solver.edges)
    Q_embeded = embed_qubo(Q, embed, adjdict)

    # Obtain the response from the solver. This is the actual D-Wave execution!
    start = time.time()
    response_qpt = dwsampler.sample_qubo(
        Q_embeded,
        num_reads=num_reads,
        label='{} reads'.format(n_genome_reads))
    qpu_time = time.time() - start
    client.close()

    # Transform the response from the embeded graph to our original architecture
    bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)

    # Sort the solutions from lowest energy and format them to quboDict format
    unformated_solutions_list = sorted(unembedded.record, key=lambda x: +x[1])
    solutions_list = []
    for sol, energy, num_appereances in unformated_solutions_list:
        solutions_list.append([
            rebuild_quboDict_from_vector(sol, n_genome_reads), energy,
            num_appereances
        ])

    return solutions_list, qpu_time, get_max_chain_length(embed)
    def test_with_software_exact_solver(self):

        sampler = DWaveSampler(solver_features={'software': True})

        bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)

        # plant a solution

        for v in sampler.nodelist:
            bqm.add_variable(v, .001)

        for u, v in sampler.edgelist:
            bqm.add_interaction(u, v, -1)

        resp = sampler.sample(bqm, num_reads=100)

        # the ground solution should be all spin down
        ground = dict(next(iter(resp)))

        self.assertEqual(ground, {v: -1 for v in bqm})
Example #15
0
    def __init__(self, num_reads=100, qpu_sampler=None, anneal_schedule=None, **runopts):
        super(ReverseAnnealingAutoEmbeddingSampler, self).__init__(**runopts)

        self.num_reads = num_reads

        if anneal_schedule is None:
            anneal_schedule = [[0, 1], [0.5, 0.5], [1, 1]]
        self.anneal_schedule = anneal_schedule

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler(
                solver={'max_anneal_schedule_points__gte': len(self.anneal_schedule)})

        # validate schedule, raising `ValueError` on invalid schedule or
        # `RuntimeError` if anneal schedule not supported by QPU (this could
        # happen only if user provided the `qpu_sampler`)
        qpu_sampler.validate_anneal_schedule(anneal_schedule)

        # embed on fly and only if needed
        self.sampler = AutoEmbeddingComposite(qpu_sampler)
Example #16
0
    def test_init_solver(self, MockClient):
        """QPU can be explicitly selected (old default usage example)"""

        solver = {'qpu': True, 'num_qubits__gt': 1000}

        sampler = DWaveSampler(solver=solver)

        MockClient.from_config.assert_called_once_with(
            client='qpu',
            solver=solver,
            defaults={'solver': {'order_by': '-num_active_qubits'}})
Example #17
0
def get_solver(solver_type):
    solver = None
    if solver_type == 'standard':
        solver = EmbeddingComposite(DWaveSampler())
    if solver_type == 'hybrid':
        solver = hybrid_solver()
    if solver_type == 'kerberos':
        solver = KerberosSampler()
    if solver_type == 'qbsolv':
        solver = QBSolv()
    return solver
Example #18
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)
Example #19
0
    def __init__(self, num_reads=100, qpu_sampler=None, qpu_params=None, **runopts):
        super(QPUSubproblemExternalEmbeddingSampler, self).__init__(**runopts)

        self.num_reads = num_reads

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler()
        self.sampler = qpu_sampler

        if qpu_params is None:
            qpu_params = {}
        self.qpu_params = qpu_params
Example #20
0
    def anneal(self):
        ###########Perform this only the first time object is instanciated
        G = RectGridGraph(self.graph_size,
                          self.graph_size)  #create the graph only once
        net_start = [(0, 0)]
        net_end = [(0, 0)]
        Q = create_qubo(
            G, net_start,
            net_end)  #in order to produce the embedding we will run this once
        dwave_sampler = DWaveSampler(solver={'lower_noise': True, 'qpu': True})
        A = dwave_sampler.edgelist
        if self.embedding is None:
            self.embedding, _ = find_embedding_minorminer(
                Q, A)  #create the embedding only once
        #define global sampler here
        fixed_sampler = self.global_sampler()
        if self.costs is None:
            self.cost_function(G, fixed_sampler)
            best_sol = deepcopy(self.sol_)
            cost_old = self.cost_
            self.costs = [cost_old]
            self.sols = [best_sol]
        else:
            cost_old = deepcopy(self.costs[-1])
            best_sol = deepcopy(self.sols[-1])
###########
        while self.T > self.T_min:
            ## memory improvement
            #garbages = gc.collect()
            ##seems no longer tobe necessary
            print(self.T)
            ##
            i = 1
            while i <= self.max_iter:
                ## memory improvement
                #garbages = gc.collect()
                ######
                self.param_generator()
                self.cost_function(G, fixed_sampler)
                cost_new = self.cost_
                ap = self.accept_prob(cost_old, cost_new)
                if ap > random.random():
                    best_sol = deepcopy(self.sol_)
                    cost_old = cost_new
                    #print(best_sol)
                else:
                    self.cost_ = cost_old
                    self.sol_ = deepcopy(best_sol)
                i += 1
            self.costs.append(cost_old)
            self.sols.append(best_sol)
            self.T = self.T * self.alpha
    def test_typical_small(self):
        h = [0, 0, 0, 0, 0]
        J = {(0, 4): 1}
        bqm = dimod.BinaryQuadraticModel.from_ising(h, J)

        response = DWaveSampler(solver_features={'qpu': True}).sample(bqm)

        self.assertFalse(np.any(response.samples_matrix == 0))
        self.assertIs(response.vartype, dimod.SPIN)

        rows, cols = response.samples_matrix.shape

        self.assertEqual(cols, 5)
Example #22
0
    def __init__(self, num_reads=100, qpu_sampler=None):
        super(QPUSubproblemAutoEmbeddingSampler, self).__init__()

        self.num_reads = num_reads

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler()

        # convert the structured sampler to unstructured
        if isinstance(qpu_sampler, dimod.Structured):
            self.sampler = EmbeddingComposite(qpu_sampler)
        else:
            self.sampler = qpu_sampler
def quantumOptim(h,J):
    h,J=convertCompatible(h,J)
    sampler = EmbeddingComposite(DWaveSampler(endpoint='https://cloud.dwavesys.com/sapi', token='[EnterTokenHere]', solver='DW_2000Q_2_1'))
    response = sampler.sample_ising(h,J,num_reads=1000)

    Q_energy=[]
    Q_sigma=[]

    for datum in response.data(['sample', 'energy']):
        Q_energy.append(datum.energy)
        Q_sigma.append(list(datum.sample.values()))
      
    return Q_sigma[0],Q_energy[0]
 def dwave_solver(self, num_reads=100):
     """ Solves using Dwave solver
             :param num_reads:
             :return: tuple (energy, solution)
             """
     # TODO: add sapi_token, dwave_url checker
     from dwave.system.samplers import DWaveSampler
     from dwave.system.composites import EmbeddingComposite
     response = EmbeddingComposite(DWaveSampler()).sample(
         self.bqm, num_reads=num_reads)
     solution = np.array([int(i) for i in response.first[0].values()])
     self.current_solution = self.solution_energy(solution), solution
     return self.current_solution
Example #25
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)
Example #26
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)
Example #27
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)
Example #28
0
    def __init__(self, num_reads=100, qpu_sampler=None, qpu_params=None, **runopts):
        super(QPUSubproblemAutoEmbeddingSampler, self).__init__(**runopts)

        self.num_reads = num_reads

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler()

        # embed on fly and only if needed
        self.sampler = AutoEmbeddingComposite(qpu_sampler)

        if qpu_params is None:
            qpu_params = {}
        self.qpu_params = qpu_params
Example #29
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)
Example #30
0
 def sample(self, Q, num_reads=10):
     answer = None
     self.find_embedding(Q)
     while None == answer:
         try:
             self.create_sampler()
             # hier muss was gefixt werden
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             # bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
             # __, target_edgelist, target_adjacency = self.sampler.target_structure
             # bqm_embedded = embed_bqm(bqm, self.embedding, target_adjacency,
             #                  smear_vartype=dimod.SPIN)
             # # embed bqm gives a binary View object of the BQM which is not allowed in the TabuSampler
             # print(isinstance(bqm, dimod.BinaryQuadraticModel))
             # print(isinstance(bqm_embedded, dimod.BinaryQuadraticModel))
             if self.mode == self.op_mode_qbsolv:
                 answer = self.sampler.sample_qubo(Q,
                                                   num_repeats=num_reads -
                                                   1)
             else:
                 answer = self.sampler.sample_qubo(Q, num_reads=num_reads)
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
             #######################################################################################
         except SolverFailureError:
             self.sampler = None
             print("\n\n\n{} is now empty\n\n\n".format(self.api_tokens[0]))
             with open("./empty_api_tokens", mode='a',
                       encoding="utf-8") as file:
                 file.write("{}\n".format(self.api_tokens[0]))
             del self.api_tokens[0]
             self.base_sampler = DWaveSampler(solver={'qpu': True},
                                              token=self.api_tokens[0])
     ret = list(answer.data(['sample', 'num_occurrences']))
     return ret