class TabuProblemSampler(Runnable, traits.ProblemSampler):
    """A tabu sampler for a binary quadratic problem.

    Args:
        num_reads (int, optional, default=1):
            Number of states (output solutions) to read from the sampler.
        tenure (int, optional):
            Tabu tenure, which is the length of the tabu list, or number of recently
            explored solutions kept in memory. Default is a quarter of the number
            of problem variables up to a maximum value of 20.
        timeout (int, optional, default=20):
            Total running time in milliseconds.

    Examples:
        See examples on https://docs.ocean.dwavesys.com/projects/hybrid/en/latest/reference/samplers.html#examples.
    """
    def __init__(self, num_reads=1, tenure=None, timeout=20):
        super(TabuProblemSampler, self).__init__()
        self.num_reads = num_reads
        self.tenure = tenure
        self.timeout = timeout
        self.sampler = TabuSampler()

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

    def next(self, state):
        sampleset = self.sampler.sample(state.problem,
                                        init_solution=state.samples,
                                        tenure=self.tenure,
                                        timeout=self.timeout,
                                        num_reads=self.num_reads)
        return state.updated(samples=sampleset)
示例#2
0
    def tabu_sampler(self):
        print("\nTabu Sampler....")
        from tabu import TabuSampler
        qpu = TabuSampler()
        self.title = "Tabu Sampler"

        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)
示例#3
0
class TabuProblemSampler(traits.ProblemSampler, traits.SISO, Runnable):
    """A tabu sampler for a binary quadratic problem.

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

        tenure (int, optional):
            Tabu tenure, which is the length of the tabu list, or number of
            recently explored solutions kept in memory. Default is a quarter of
            the number of problem variables up to a maximum value of 20.

        timeout (int, optional, default=100):
            Total running time in milliseconds.

        initial_states_generator (str, 'none'/'tile'/'random', optional, default='random'):
            Defines the expansion of input state samples into `initial_states`
            for the Tabu search, if fewer than `num_reads` samples are
            present. See :meth:`~tabu.TabuSampler.sample`.

    See :ref:`samplers-examples`.
    """
    def __init__(self,
                 num_reads=None,
                 tenure=None,
                 timeout=100,
                 initial_states_generator='random',
                 **runopts):
        super(TabuProblemSampler, self).__init__(**runopts)
        self.num_reads = num_reads
        self.tenure = tenure
        self.timeout = timeout
        self.initial_states_generator = initial_states_generator
        self.sampler = TabuSampler()

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

    def next(self, state, **runopts):
        sampleset = self.sampler.sample(
            state.problem,
            initial_states=state.samples,
            initial_states_generator=self.initial_states_generator,
            tenure=self.tenure,
            timeout=self.timeout,
            num_reads=self.num_reads)
        return state.updated(samples=sampleset)
示例#4
0
print(G.number_of_nodes(),
      G.number_of_edges(),
      bqm.num_variables,
      len(f1),
      len(f2),
      len(f0),
      end=' ')

# Choose one of the solvers below.
#sampler = SimulatedAnnealingSampler()
sampler = TabuSampler()
#sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True, 'postprocess': 'sampling'}))
#sampler = LeapHybridSampler()

# Conduct optimization
sampleset = sampler.sample(bqm)

print(sampleset.first.energy, end=' ')

# Summarize the results on the graph
GS = sample_graph(G, b, f0, sampleset.first.sample)

# Report violations
rep = report_graph(GS, G)

print(' '.join(str(x) for x in rep), end=' ')

# Report cycles
print(len(list(nx.simple_cycles(GS))))

# output