def sample(self, bqm, num_reads=10): """Gives random samples. Args: todo Returns: :obj:`.Response`: The vartype will match the given binary quadratic model. Notes: For each variable in each sample, the value is chosen by a coin flip. """ values = np.asarray(list(bqm.vartype.value), dtype='int8') samples = np.random.choice(values, (num_reads, len(bqm))) df_samples = pd.DataFrame(samples, columns=bqm.linear) energies = [ bqm.energy(sample) for idx, sample in df_samples.iterrows() ] response = Response(bqm.vartype) response.add_samples_from(df_samples, energies) return response
def sample(self, bqm, num_spin_reversal_transforms=2, spin_reversal_variables=None, **kwargs): # make a main response response = Response(bqm.vartype) for __ in range(num_spin_reversal_transforms): if spin_reversal_variables is None: # apply spin transform to each variable with 50% chance transform = list(v for v in bqm.linear if random() > .5) else: transform = list(spin_reversal_variables) flipped_bqm = bqm.copy() for v in transform: flipped_bqm.flip_variable(v) flipped_response = self.child.sample(bqm, **kwargs) data_kwargs = flipped_response.df_data.to_dict('list') if 'spin_reversal_variables' in data_kwargs: data_kwargs['spin_reversal_variables_{}'.format( time.time())] = [transform] * len(flipped_response) else: data_kwargs['spin_reversal_variables'] = [ transform ] * len(flipped_response) if bqm.vartype is Vartype.SPIN: flipped_response.df_samples[ transform] = -1 * flipped_response.df_samples[transform] else: flipped_response.df_samples[ transform] = 1 - flipped_response.df_samples[transform] response.add_samples_from(flipped_response.df_samples, **data_kwargs) return response
def sample(self, bqm): M = to_numpy_matrix(bqm.binary) sample = np.zeros((len(bqm), ), dtype=bool) response = Response(Vartype.BINARY) # now we iterate, flipping one bit at a time until we have # traversed all samples. This is a Gray code. # https://en.wikipedia.org/wiki/Gray_code def iter_samples(): sample = np.zeros((len(bqm)), dtype=bool) energy = 0.0 yield sample.copy(), energy for i in range(1, 1 << len(bqm)): v = _ffs(i) # flip the bit in the sample sample[v] = not sample[v] # for now just calculate the energy, but there is a more clever way by calculating # the energy delta for the single bit flip, don't have time, pull requests # appreciated! energy = sample.dot(M).dot(sample.transpose()) yield sample.copy(), float(energy) + bqm.offset samples, energies = zip_(*iter_samples()) response.add_samples_from(np.asarray(samples), energies) # finally make sure the response matches the given vartype, in-place. response.change_vartype(bqm.vartype) return response