def sample(self, bqm, *, components=None, **parameters): """Sample from the provided binary quadratic model. Args: bqm (:class:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. components (list(set)): A list of disjoint set of variables that fully partition the variables **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :class:`dimod.SampleSet` """ # make sure the BQM is shapeable bqm = as_bqm(bqm, cls=[AdjVectorBQM, AdjDictBQM]) # solve the problem on the child system child = self.child variables = bqm.variables if components is None: components = list(connected_components(bqm)) if isinstance(components, set): components = [components] sampleset = None fixed_value = min(bqm.vartype.value) for component in components: bqm_copy = bqm.copy() bqm_copy.fix_variables( {i: fixed_value for i in (variables - component)}) if sampleset is None: # here .truncate(1) is used to pick the best solution only. The other options # for future development is to combine all sample with all. # This way you'd get the same behaviour as the ExactSolver sampleset = child.sample(bqm_copy, **parameters).truncate(1) else: sampleset = append_variables( sampleset.truncate(1), child.sample(bqm_copy, **parameters).truncate(1)) if sampleset is None: return SampleSet.from_samples_bqm({}, bqm) else: return SampleSet.from_samples_bqm(sampleset, bqm)
def sample(self, bqm, **kwargs): """Sample from a binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. Returns: :obj:`~dimod.SampleSet` """ kwargs = self.remove_unknown_kwargs(**kwargs) n = len(bqm.variables) if n == 0: return SampleSet.from_samples([], bqm.vartype, energy=[]) samples = _graycode(bqm) if bqm.vartype is Vartype.SPIN: samples = 2 * samples - 1 response = SampleSet.from_samples_bqm((samples, list(bqm.variables)), bqm) return response
def sample(self, bqm, lower_bound=None, upper_bound=None, **parameters): """Clip and sample from the provided binary quadratic model. If lower_bound and upper_bound are given variables with value above or below are clipped. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. lower_bound (number): Value by which to clip the variables from below. upper_bound (number): Value by which to clip the variables from above. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet` """ child = self.child bqm_copy = _clip_bqm(bqm, lower_bound, upper_bound) response = child.sample(bqm_copy, **parameters) return SampleSet.from_samples_bqm(response, bqm, info=response.info)
def sample(self, bqm, **kwargs): """Return an empty sample set. Args: bqm (:obj:`.BinaryQuadraticModel`): The binary quadratic model determines the variables labels in the sample set. kwargs: As specified when constructing the null sampler. Returns: :obj:`.SampleSet`: The empty sample set. """ samples = np.empty((0, len(bqm))) labels = iter(bqm.variables) kwargs = self.remove_unknown_kwargs(**kwargs) return SampleSet.from_samples_bqm((samples, labels), bqm)
def sample(self, bqm, **kwargs): """Return an empty sample set. Args: bqm (:obj:`.BinaryQuadraticModel`): The binary quadratic model determines the variables labels in the sample set. kwargs: As specified when constructing the null sampler. Returns: :obj:`.SampleSet`: The empty sample set. """ samples = np.empty((0, len(bqm))) labels = iter(bqm.variables) for kw in kwargs: if kw not in self.parameters: raise ValueError("unknown parameter {!r}".format(kw)) return SampleSet.from_samples_bqm((samples, labels), bqm)
def parse_initial_states(self, bqm, initial_states=None, initial_states_generator='random', num_reads=None, seed=None): """Parses/generates initial states for an initialized sampler. Args: bqm (:class:`~dimod.BinaryQuadraticModel`): The binary quadratic model. num_reads (int, optional, default=len(initial_states) or 1): Number of reads. If `num_reads` is not explicitly given, it is selected to match the number of initial states given. If no initial states are given, it defaults to 1. initial_states (samples-like, optional, default=None): One or more samples, each defining an initial state for all the problem variables. Initial states are given one per read, but if fewer than `num_reads` initial states are defined, additional values are generated as specified by `initial_states_generator`. See func:`.as_samples` for a description of "samples-like". initial_states_generator ({'none', 'tile', 'random'}, optional, default='random'): Defines the expansion of `initial_states` if fewer than `num_reads` are specified: * "none": If the number of initial states specified is smaller than `num_reads`, raises ValueError. * "tile": Reuses the specified initial states if fewer than `num_reads` or truncates if greater. * "random": Expands the specified initial states with randomly generated states if fewer than `num_reads` or truncates if greater. seed (int (32-bit unsigned integer), optional): Seed to use for the PRNG. Specifying a particular seed with a constant set of parameters produces identical results. If not provided, a random seed is chosen. Returns: A named tuple with `['initial_states', 'initial_states_generator', 'num_reads', 'seed']` as generated by this function. """ num_variables = len(bqm) # validate/initialize initial_states if initial_states is None: initial_states_array = np.empty((0, num_variables), dtype=np.int8) initial_states_variables = list(bqm.variables) initial_states_vartype = bqm.vartype else: initial_states_array, initial_states_variables = \ as_samples(initial_states) # confirm that the vartype matches and/or make it match if isinstance(initial_states, SampleSet): initial_states_vartype = initial_states.vartype else: # check based on values, defaulting to match the current bqm initial_states_vartype = infer_vartype( initial_states_array) or bqm.vartype # confirm that the variables match if bqm.variables ^ initial_states_variables: raise ValueError("mismatch between variables in " "'initial_states' and 'bqm'") # match the vartype of the initial_states to the bqm if initial_states_vartype is Vartype.SPIN and bqm.vartype is Vartype.BINARY: initial_states_array += 1 initial_states_array //= 2 elif initial_states_vartype is Vartype.BINARY and bqm.vartype is Vartype.SPIN: initial_states_array *= 2 initial_states_array -= 1 # validate num_reads and/or infer them from initial_states if num_reads is None: num_reads = len(initial_states_array) or 1 if not isinstance(num_reads, Integral): raise TypeError("'num_reads' should be a positive integer") if num_reads < 1: raise ValueError("'num_reads' should be a positive integer") # fill/generate the initial states as needed if initial_states_generator not in self._generators: raise ValueError("unknown value for 'initial_states_generator'") extrapolate = self._generators[initial_states_generator] initial_states_array = extrapolate(initial_states=initial_states_array, num_reads=num_reads, num_variables=num_variables, seed=seed, vartype=bqm.vartype) initial_states_array = self._truncate_filter(initial_states_array, num_reads) sampleset = SampleSet.from_samples_bqm( (initial_states_array, initial_states_variables), bqm) return ParsedInputs(sampleset, initial_states_generator, num_reads, seed)