text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modularity(matrix, clusters): """ Compute the modularity :param matrix: The adjacency matrix :param clusters: The clusters returned by get_clusters :returns: modularity value """
matrix = convert_to_adjacency_matrix(matrix) m = matrix.sum() if isspmatrix(matrix): matrix_2 = matrix.tocsr(copy=True) else : matrix_2 = matrix if is_undirected(matrix): expected = lambda i,j : (( matrix_2[i,:].sum() + matrix[:,i].sum() )* ( matrix[:,j].sum() + matrix_2[j,:].sum() )) else: expected = lambda i,j : ( matrix_2[i,:].sum()*matrix[:,j].sum() ) delta = delta_matrix(matrix, clusters) indices = np.array(delta.nonzero()) Q = sum( matrix[i, j] - expected(i, j)/m for i, j in indices.T )/m return Q
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sparse_allclose(a, b, rtol=1e-5, atol=1e-8): """ Version of np.allclose for use with sparse matrices """
c = np.abs(a - b) - rtol * np.abs(b) # noinspection PyUnresolvedReferences return c.max() <= atol
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _guess_concat(data): """ Guess concat function from given data """
return { type(u''): u''.join, type(b''): concat_bytes, }.get(type(data), list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_code_table(self, out=sys.stdout): """ Print code table overview """
out.write(u'bits code (value) symbol\n') for symbol, (bitsize, value) in sorted(self._table.items()): out.write(u'{b:4d} {c:10} ({v:5d}) {s!r}\n'.format( b=bitsize, v=value, s=symbol, c=bin(value)[2:].rjust(bitsize, '0') ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_streaming(self, data): """ Encode given data in streaming fashion. :param data: sequence of symbols (e.g. byte string, unicode string, list, iterator) :return: generator of bytes (single character strings in Python2, ints in Python 3) """
# Buffer value and size buffer = 0 size = 0 for s in data: b, v = self._table[s] # Shift new bits in the buffer buffer = (buffer << b) + v size += b while size >= 8: byte = buffer >> (size - 8) yield to_byte(byte) buffer = buffer - (byte << (size - 8)) size -= 8 # Handling of the final sub-byte chunk. # The end of the encoded bit stream does not align necessarily with byte boundaries, # so we need an "end of file" indicator symbol (_EOF) to guard against decoding # the non-data trailing bits of the last byte. # As an optimization however, while encoding _EOF, it is only necessary to encode up to # the end of the current byte and cut off there. # No new byte has to be started for the remainder, saving us one (or more) output bytes. if size > 0: b, v = self._table[_EOF] buffer = (buffer << b) + v size += b if size >= 8: byte = buffer >> (size - 8) else: byte = buffer << (8 - size) yield to_byte(byte)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, data, as_list=False): """ Decode given data. :param data: sequence of bytes (string, list or generator of bytes) :param as_list: whether to return as a list instead of :return: """
return self._concat(self.decode_streaming(data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_streaming(self, data): """ Decode given data in streaming fashion :param data: sequence of bytes (string, list or generator of bytes) :return: generator of symbols """
# Reverse lookup table: map (bitsize, value) to symbols lookup = dict(((b, v), s) for (s, (b, v)) in self._table.items()) buffer = 0 size = 0 for byte in data: for m in [128, 64, 32, 16, 8, 4, 2, 1]: buffer = (buffer << 1) + bool(from_byte(byte) & m) size += 1 if (size, buffer) in lookup: symbol = lookup[size, buffer] if symbol == _EOF: return yield symbol buffer = 0 size = 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_data(cls, data): """ Build Huffman code table from symbol sequence :param data: sequence of symbols (e.g. byte string, unicode string, list, iterator) :return: HuffmanCoder """
frequencies = collections.Counter(data) return cls.from_frequencies(frequencies, concat=_guess_concat(data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset_state(self): """Reset state about the previous query in preparation for running another query"""
self._uuid = None self._columns = None self._rownumber = 0 # Internal helper state self._state = self._STATE_NONE self._data = None self._columns = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetchone(self): """Fetch the next row of a query result set, returning a single sequence, or ``None`` when no more data is available. """
if self._state == self._STATE_NONE: raise Exception("No query yet") if not self._data: return None else: self._rownumber += 1 return self._data.pop(0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_response(self, response): """ Update the internal state with the data from the response """
assert self._state == self._STATE_RUNNING, "Should be running if processing response" cols = None data = [] for r in response: if not cols: cols = [(f, r._fields[f].db_type) for f in r._fields] data.append([getattr(r, f) for f in r._fields]) self._data = data self._columns = cols self._state = self._STATE_FINISHED
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _frequency_order_transform(sets): """Transform tokens to integers according to global frequency order. This step replaces all original tokens in the sets with integers, and helps to speed up subsequent prefix filtering and similarity computation. See Section 4.3.2 in the paper "A Primitive Operator for Similarity Joins in Data Cleaning" by Chaudhuri et al.. Args: sets (list): a list of sets, each entry is an iterable representing a set. Returns: sets (list): a list of sets, each entry is a sorted Numpy array with integer tokens replacing the tokens in the original set. order (dict): a dictionary that maps token to its integer representation in the frequency order. """
logging.debug("Applying frequency order transform on tokens...") counts = reversed(Counter(token for s in sets for token in s).most_common()) order = dict((token, i) for i, (token, _) in enumerate(counts)) sets = [np.sort([order[token] for token in s]) for s in sets] logging.debug("Done applying frequency order.") return sets, order
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_pairs(sets, similarity_func_name="jaccard", similarity_threshold=0.5): """Find all pairs of sets with similarity greater than a threshold. This is an implementation of the All-Pair-Binary algorithm in the paper "Scaling Up All Pairs Similarity Search" by Bayardo et al., with position filter enhancement. Args: sets (list): a list of sets, each entry is an iterable representing a set. similarity_func_name (str): the name of the similarity function used; this function currently supports `"jaccard"` and `"cosine"`. similarity_threshold (float): the threshold used, must be a float between 0 and 1.0. Returns: pairs (Iterator[tuple]): an iterator of tuples `(x, y, similarity)` where `x` and `y` are the indices of sets in the input list `sets`. """
if not isinstance(sets, list) or len(sets) == 0: raise ValueError("Input parameter sets must be a non-empty list.") if similarity_func_name not in _similarity_funcs: raise ValueError("Similarity function {} is not supported.".format( similarity_func_name)) if similarity_threshold < 0 or similarity_threshold > 1.0: raise ValueError("Similarity threshold must be in the range [0, 1].") if similarity_func_name not in _symmetric_similarity_funcs: raise ValueError("The similarity function must be symmetric " "({})".format(", ".join(_symmetric_similarity_funcs))) similarity_func = _similarity_funcs[similarity_func_name] overlap_threshold_func = _overlap_threshold_funcs[similarity_func_name] position_filter_func = _position_filter_funcs[similarity_func_name] sets, _ = _frequency_order_transform(sets) index = defaultdict(list) logging.debug("Find all pairs with similarities >= {}...".format( similarity_threshold)) count = 0 for x1 in np.argsort([len(s) for s in sets]): s1 = sets[x1] t = overlap_threshold_func(len(s1), similarity_threshold) prefix_size = len(s1) - t + 1 prefix = s1[:prefix_size] # Find candidates using tokens in the prefix. candidates = set([x2 for p1, token in enumerate(prefix) for x2, p2 in index[token] if position_filter_func(s1, sets[x2], p1, p2, similarity_threshold)]) for x2 in candidates: s2 = sets[x2] sim = similarity_func(s1, s2) if sim < similarity_threshold: continue # Output reverse-ordered set index pair (larger first). yield tuple(sorted([x1, x2], reverse=True) + [sim,]) count += 1 # Insert this prefix into index. for j, token in enumerate(prefix): index[token].append((x1, j)) logging.debug("{} pairs found.".format(count))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query(self, s): """Query the search index for sets similar to the query set. Args: s (Iterable): the query set. Returns (list): a list of tuples `(index, similarity)` where the index is the index of the matching sets in the original list of sets. """
s1 = np.sort([self.order[token] for token in s if token in self.order]) logging.debug("{} original tokens and {} tokens after applying " "frequency order.".format(len(s), len(s1))) prefix = self._get_prefix(s1) candidates = set([i for p1, token in enumerate(prefix) for i, p2 in self.index[token] if self.position_filter_func(s1, self.sets[i], p1, p2, self.similarity_threshold)]) logging.debug("{} candidates found.".format(len(candidates))) results = deque([]) for i in candidates: s2 = self.sets[i] sim = self.similarity_func(s1, s2) if sim < self.similarity_threshold: continue results.append((i, sim)) logging.debug("{} verified sets found.".format(len(results))) return list(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, bqm, num_reads=10): """Give random samples for a binary quadratic model. Variable assignments are chosen by coin flip. Args: bqm (:obj:`.BinaryQuadraticModel`): Binary quadratic model to be sampled from. num_reads (int, optional, default=10): Number of reads. Returns: :obj:`.SampleSet` """
values = tuple(bqm.vartype.value) def _itersample(): for __ in range(num_reads): sample = {v: choice(values) for v in bqm.linear} energy = bqm.energy(sample) yield sample, energy samples, energies = zip(*_itersample()) return SampleSet.from_samples(samples, bqm.vartype, energies)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combinations(n, k, strength=1, vartype=BINARY): r"""Generate a bqm that is minimized when k of n variables are selected. More fully, we wish to generate a binary quadratic model which is minimized for each of the k-combinations of its variables. The energy for the binary quadratic model is given by :math:`(\sum_{i} x_i - k)^2`. Args: n (int/list/set): If n is an integer, variables are labelled [0, n-1]. If n is list or set then the variables are labelled accordingly. k (int): The generated binary quadratic model will have 0 energy when any k of the variables are 1. strength (number, optional, default=1): The energy of the first excited state of the binary quadratic model. vartype (:class:`.Vartype`/str/set): Variable type for the binary quadratic model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` Returns: :obj:`.BinaryQuadraticModel` Examples: 0.0 1.0 0.0 1.0 0.0 3.0 """
if isinstance(n, abc.Sized) and isinstance(n, abc.Iterable): # what we actually want is abc.Collection but that doesn't exist in # python2 variables = n else: try: variables = range(n) except TypeError: raise TypeError('n should be a collection or an integer') if k > len(variables) or k < 0: raise ValueError("cannot select k={} from {} variables".format(k, len(variables))) # (\sum_i x_i - k)^2 # = \sum_i x_i \sum_j x_j - 2k\sum_i x_i + k^2 # = \sum_i,j x_ix_j + (1 - 2k)\sim_i x_i + k^2 lbias = float(strength*(1 - 2*k)) qbias = float(2*strength) bqm = BinaryQuadraticModel.empty(vartype) bqm.add_variables_from(((v, lbias) for v in variables), vartype=BINARY) bqm.add_interactions_from(((u, v, qbias) for u, v in itertools.combinations(variables, 2)), vartype=BINARY) bqm.add_offset(strength*(k**2)) return bqm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uniform(graph, vartype, low=0.0, high=1.0, cls=BinaryQuadraticModel, seed=None): """Generate a bqm with random biases and offset. Biases and offset are drawn from a uniform distribution range (low, high). Args: graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): The graph to build the bqm loops on. Either an integer n, interpreted as a complete graph of size n, or a nodes/edges pair, or a NetworkX graph. vartype (:class:`.Vartype`/str/set): Variable type for the binary quadratic model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` low (float, optional, default=0.0): The low end of the range for the random biases. high (float, optional, default=1.0): The high end of the range for the random biases. cls (:class:`.BinaryQuadraticModel`): Binary quadratic model class to build from. seed (int, optional, default=None): Random seed. Returns: :obj:`.BinaryQuadraticModel` """
if seed is None: seed = numpy.random.randint(2**32, dtype=np.uint32) r = numpy.random.RandomState(seed) variables, edges = graph index = {v: idx for idx, v in enumerate(variables)} if edges: irow, icol = zip(*((index[u], index[v]) for u, v in edges)) else: irow = icol = tuple() ldata = r.uniform(low, high, size=len(variables)) qdata = r.uniform(low, high, size=len(irow)) offset = r.uniform(low, high) return cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, vartype, variable_order=variables)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ran_r(r, graph, cls=BinaryQuadraticModel, seed=None): """Generate an Ising model for a RANr problem. In RANr problems all linear biases are zero and quadratic values are uniformly selected integers between -r to r, excluding zero. This class of problems is relevant for binary quadratic models (BQM) with spin variables (Ising models). This generator of RANr problems follows the definition in [Kin2015]_\ . Args: r (int): Order of the RANr problem. graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): The graph to build the BQM for. Either an integer n, interpreted as a complete graph of size n, or a nodes/edges pair, or a NetworkX graph. cls (:class:`.BinaryQuadraticModel`): Binary quadratic model class to build from. seed (int, optional, default=None): Random seed. Returns: :obj:`.BinaryQuadraticModel`. Examples: .. [Kin2015] James King, Sheir Yarkoni, Mayssam M. Nevisi, Jeremy P. Hilton, Catherine C. McGeoch. Benchmarking a quantum annealing processor with the time-to-target metric. https://arxiv.org/abs/1508.05087 """
if not isinstance(r, int): raise TypeError("r should be a positive integer") if r < 1: raise ValueError("r should be a positive integer") if seed is None: seed = numpy.random.randint(2**32, dtype=np.uint32) rnd = numpy.random.RandomState(seed) variables, edges = graph index = {v: idx for idx, v in enumerate(variables)} if edges: irow, icol = zip(*((index[u], index[v]) for u, v in edges)) else: irow = icol = tuple() ldata = np.zeros(len(variables)) rvals = np.empty(2*r) rvals[0:r] = range(-r, 0) rvals[r:] = range(1, r+1) qdata = rnd.choice(rvals, size=len(irow)) offset = 0 return cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, vartype='SPIN', variable_order=variables)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bqm_index_labels(f): """Decorator to convert a bqm to index-labels and relabel the sample set output. Designed to be applied to :meth:`.Sampler.sample`. Expects the wrapped function or method to accept a :obj:`.BinaryQuadraticModel` as the second input and to return a :obj:`.SampleSet`. """
@wraps(f) def _index_label(sampler, bqm, **kwargs): if not hasattr(bqm, 'linear'): raise TypeError('expected input to be a BinaryQuadraticModel') linear = bqm.linear # if already index-labelled, just continue if all(v in linear for v in range(len(bqm))): return f(sampler, bqm, **kwargs) try: inverse_mapping = dict(enumerate(sorted(linear))) except TypeError: # in python3 unlike types cannot be sorted inverse_mapping = dict(enumerate(linear)) mapping = {v: i for i, v in iteritems(inverse_mapping)} response = f(sampler, bqm.relabel_variables(mapping, inplace=False), **kwargs) # unapply the relabeling return response.relabel_variables(inverse_mapping, inplace=True) return _index_label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bqm_index_labelled_input(var_labels_arg_name, samples_arg_names): """Returns a decorator which ensures bqm variable labeling and all other specified sample-like inputs are index labeled and consistent. Args: var_labels_arg_name (str): The name of the argument that the user should use to pass in an index labeling for the bqm. samples_arg_names (list[str]): The names of the expected sample-like inputs which should be indexed according to the labels passed to the argument `var_labels_arg_name`. Returns: Function decorator. """
def index_label_decorator(f): @wraps(f) def _index_label(sampler, bqm, **kwargs): if not hasattr(bqm, 'linear'): raise TypeError('expected input to be a BinaryQuadraticModel') linear = bqm.linear var_labels = kwargs.get(var_labels_arg_name, None) has_samples_input = any(kwargs.get(arg_name, None) is not None for arg_name in samples_arg_names) if var_labels is None: # if already index-labelled, just continue if all(v in linear for v in range(len(bqm))): return f(sampler, bqm, **kwargs) if has_samples_input: err_str = ("Argument `{}` must be provided if any of the" " samples arguments {} are provided and the " "bqm is not already index-labelled".format( var_labels_arg_name, samples_arg_names)) raise ValueError(err_str) try: inverse_mapping = dict(enumerate(sorted(linear))) except TypeError: # in python3 unlike types cannot be sorted inverse_mapping = dict(enumerate(linear)) var_labels = {v: i for i, v in iteritems(inverse_mapping)} else: inverse_mapping = {i: v for v, i in iteritems(var_labels)} response = f(sampler, bqm.relabel_variables(var_labels, inplace=False), **kwargs) # unapply the relabeling return response.relabel_variables(inverse_mapping, inplace=True) return _index_label return index_label_decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bqm_structured(f): """Decorator to raise an error if the given bqm does not match the sampler's structure. Designed to be applied to :meth:`.Sampler.sample`. Expects the wrapped function or method to accept a :obj:`.BinaryQuadraticModel` as the second input and for the :class:`.Sampler` to also be :class:`.Structured`. """
@wraps(f) def new_f(sampler, bqm, **kwargs): try: structure = sampler.structure adjacency = structure.adjacency except AttributeError: if isinstance(sampler, Structured): raise RuntimeError("something is wrong with the structured sampler") else: raise TypeError("sampler does not have a structure property") if not all(v in adjacency for v in bqm.linear): # todo: better error message raise BinaryQuadraticModelStructureError("given bqm does not match the sampler's structure") if not all(u in adjacency[v] for u, v in bqm.quadratic): # todo: better error message raise BinaryQuadraticModelStructureError("given bqm does not match the sampler's structure") return f(sampler, bqm, **kwargs) return new_f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_argument(*arg_names, **options): """Decorator to coerce given graph arguments into a consistent form. The wrapped function will accept either an integer n, interpreted as a complete graph of size n, or a nodes/edges pair, or a NetworkX graph. The argument will then be converted into a nodes/edges 2-tuple. Args: *arg_names (optional, default='G'): The names of the arguments for input graphs. allow_None (bool, optional, default=False): Allow None as an input graph in which case it is passed through as None. """
# by default, constrain only one argument, the 'G` if not arg_names: arg_names = ['G'] # we only allow one option allow_None allow_None = options.pop("allow_None", False) if options: # to keep it consistent with python3 # behaviour like graph_argument(*arg_names, allow_None=False) key, _ = options.popitem() msg = "graph_argument() for an unexpected keyword argument '{}'".format(key) raise TypeError(msg) def _graph_arg(f): argspec = getargspec(f) def _enforce_single_arg(name, args, kwargs): try: G = kwargs[name] except KeyError: raise TypeError('Graph argument missing') if hasattr(G, 'edges') and hasattr(G, 'nodes'): # networkx or perhaps a named tuple kwargs[name] = (list(G.nodes), list(G.edges)) elif _is_integer(G): # an integer, cast to a complete graph kwargs[name] = (list(range(G)), list(itertools.combinations(range(G), 2))) elif isinstance(G, abc.Sequence) and len(G) == 2: # is a pair nodes/edges if isinstance(G[0], integer_types): # if nodes is an int kwargs[name] = (list(range(G[0])), G[1]) elif allow_None and G is None: # allow None to be passed through return G else: raise ValueError('Unexpected graph input form') return @wraps(f) def new_f(*args, **kwargs): # bound actual f arguments (including defaults) to f argument names # (note: if call arguments don't match actual function signature, # we'll fail here with the standard `TypeError`) bound_args = inspect.getcallargs(f, *args, **kwargs) # `getcallargs` doesn't merge additional positional/keyword arguments, # so do it manually final_args = list(bound_args.pop(argspec.varargs, ())) final_kwargs = bound_args.pop(argspec.keywords, {}) final_kwargs.update(bound_args) for name in arg_names: _enforce_single_arg(name, final_args, final_kwargs) return f(*final_args, **final_kwargs) return new_f return _graph_arg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array2bytes(arr, bytes_type=bytes): """Wraps NumPy's save function to return bytes. We use :func:`numpy.save` rather than :meth:`numpy.ndarray.tobytes` because it encodes endianness and order. Args: arr (:obj:`numpy.ndarray`): Array to be saved. bytes_type (class, optional, default=bytes): This class will be used to wrap the bytes objects in the serialization if `use_bytes` is true. Useful for when using Python 2 and using BSON encoding, which will not accept the raw `bytes` type, so `bson.Binary` can be used instead. Returns: bytes_type """
bio = io.BytesIO() np.save(bio, arr, allow_pickle=False) return bytes_type(bio.getvalue())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, bqm, **kwargs): """Sample from the problem provided by bqm and truncate output. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **kwargs: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet` """
tkw = self._truncate_kwargs if self._aggregate: return self.child.sample(bqm, **kwargs).aggregate().truncate(**tkw) else: return self.child.sample(bqm, **kwargs).truncate(**tkw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, bqm): """Sample from a binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. Returns: :obj:`~dimod.SampleSet` """
M = bqm.binary.to_numpy_matrix() off = bqm.binary.offset if M.shape == (0, 0): return SampleSet.from_samples([], bqm.vartype, energy=[]) sample = np.zeros((len(bqm),), dtype=bool) # 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 + off 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) + off samples, energies = zip(*iter_samples()) response = SampleSet.from_samples(np.array(samples, dtype='int8'), Vartype.BINARY, energies) # make sure the response matches the given vartype, in-place. response.change_vartype(bqm.vartype, inplace=True) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_vartype(vartype): """Cast various inputs to a valid vartype object. Args: vartype (:class:`.Vartype`/str/set): Variable type. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` Returns: :class:`.Vartype`: Either :class:`.Vartype.SPIN` or :class:`.Vartype.BINARY`. See also: :func:`~dimod.decorators.vartype_argument` """
if isinstance(vartype, Vartype): return vartype try: if isinstance(vartype, str): vartype = Vartype[vartype] elif isinstance(vartype, frozenset): vartype = Vartype(vartype) else: vartype = Vartype(frozenset(vartype)) except (ValueError, KeyError): raise TypeError(("expected input vartype to be one of: " "Vartype.SPIN, 'SPIN', {-1, 1}, " "Vartype.BINARY, 'BINARY', or {0, 1}.")) return vartype
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def energy(self, sample_like, dtype=np.float): """The energy of the given sample. Args: sample_like (samples_like): A raw sample. `sample_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. dtype (:class:`numpy.dtype`, optional): The data type of the returned energies. Defaults to float. Returns: The energy. """
energy, = self.energies(sample_like, dtype=dtype) return energy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def energies(self, samples_like, dtype=np.float): """The energies of the given samples. Args: samples_like (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. dtype (:class:`numpy.dtype`, optional): The data type of the returned energies. Defaults to float. Returns: :obj:`numpy.ndarray`: The energies. """
samples, labels = as_samples(samples_like) if labels: idx, label = zip(*enumerate(labels)) labeldict = dict(zip(label, idx)) else: labeldict = {} num_samples = samples.shape[0] energies = np.zeros(num_samples, dtype=dtype) for term, bias in self.items(): if len(term) == 0: energies += bias else: energies += np.prod([samples[:, labeldict[v]] for v in term], axis=0) * bias return energies
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relabel_variables(self, mapping, inplace=True): """Relabel variables of a binary polynomial as specified by mapping. Args: mapping (dict): Dict mapping current variable labels to new ones. If an incomplete mapping is provided, unmapped variables retain their current labels. inplace (bool, optional, default=True): If True, the binary polynomial is updated in-place; otherwise, a new binary polynomial is returned. Returns: :class:`.BinaryPolynomial`: A binary polynomial with the variables relabeled. If `inplace` is set to True, returns itself. """
if not inplace: return self.copy().relabel_variables(mapping, inplace=True) try: old_labels = set(mapping) new_labels = set(mapping.values()) except TypeError: raise ValueError("mapping targets must be hashable objects") variables = self.variables for v in new_labels: if v in variables and v not in old_labels: raise ValueError(('A variable cannot be relabeled "{}" without also relabeling ' "the existing variable of the same name").format(v)) shared = old_labels & new_labels if shared: old_to_intermediate, intermediate_to_new = resolve_label_conflict(mapping, old_labels, new_labels) self.relabel_variables(old_to_intermediate, inplace=True) self.relabel_variables(intermediate_to_new, inplace=True) return self for oldterm, bias in list(self.items()): newterm = frozenset((mapping.get(v, v) for v in oldterm)) if newterm != oldterm: self[newterm] = bias del self[oldterm] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scale(self, scalar, ignored_terms=None): """Multiply the polynomial by the given scalar. Args: scalar (number): Value to multiply the polynomial by. ignored_terms (iterable, optional): Biases associated with these terms are not scaled. """
if ignored_terms is None: ignored_terms = set() else: ignored_terms = {asfrozenset(term) for term in ignored_terms} for term in self: if term not in ignored_terms: self[term] *= scalar
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_hising(cls, h, J, offset=None): """Construct a binary polynomial from a higher-order Ising problem. Args: h (dict): The linear biases. J (dict): The higher-order biases. offset (optional, default=0.0): Constant offset applied to the model. Returns: :obj:`.BinaryPolynomial` Examples: """
poly = {(k,): v for k, v in h.items()} poly.update(J) if offset is not None: poly[frozenset([])] = offset return cls(poly, Vartype.SPIN)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_hising(self): """Construct a higher-order Ising problem from a binary polynomial. Returns: tuple: A 3-tuple of the form (`h`, `J`, `offset`) where `h` includes the linear biases, `J` has the higher-order biases and `offset` is the linear offset. Examples: {'a': -1} """
if self.vartype is Vartype.BINARY: return self.to_spin().to_hising() h = {} J = {} offset = 0 for term, bias in self.items(): if len(term) == 0: offset += bias elif len(term) == 1: v, = term h[v] = bias else: J[tuple(term)] = bias return h, J, offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def greedy_coloring(adj): """Determines a vertex coloring. Args: adj (dict): The edge structure of the graph to be colored. neighbors is a set. Returns: Note: This is a greedy heuristic: the resulting coloring is not necessarily minimal. """
# now let's start coloring coloring = {} colors = {} possible_colors = {n: set(range(len(adj))) for n in adj} while possible_colors: # get the n with the fewest possible colors n = min(possible_colors, key=lambda n: len(possible_colors[n])) # assign that node the lowest color it can still have color = min(possible_colors[n]) coloring[n] = color if color not in colors: colors[color] = {n} else: colors[color].add(n) # also remove color from the possible colors for n's neighbors for neighbor in adj[n]: if neighbor in possible_colors and color in possible_colors[neighbor]: possible_colors[neighbor].remove(color) # finally remove n from nodes del possible_colors[n] return coloring, colors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, bqm, beta_range=None, num_reads=10, num_sweeps=1000): """Sample from low-energy spin states using simulated annealing. Args: bqm (:obj:`.BinaryQuadraticModel`): Binary quadratic model to be sampled from. beta_range (tuple, optional): Beginning and end of the beta schedule (beta is the inverse temperature) as a 2-tuple. The schedule is applied linearly in beta. Default is chosen based on the total bias associated with each node. num_reads (int, optional, default=10): Number of reads. Each sample is the result of a single run of the simulated annealing algorithm. num_sweeps (int, optional, default=1000): Number of sweeps or steps. Returns: :obj:`.SampleSet` Note: This is a reference implementation, not optimized for speed and therefore not an appropriate sampler for benchmarking. """
# input checking # h, J are handled by the @ising decorator # beta_range, sweeps are handled by ising_simulated_annealing if not isinstance(num_reads, int): raise TypeError("'samples' should be a positive integer") if num_reads < 1: raise ValueError("'samples' should be a positive integer") h, J, offset = bqm.to_ising() # run the simulated annealing algorithm samples = [] energies = [] for __ in range(num_reads): sample, energy = ising_simulated_annealing(h, J, beta_range, num_sweeps) samples.append(sample) energies.append(energy) response = SampleSet.from_samples(samples, Vartype.SPIN, energies) response.change_vartype(bqm.vartype, offset, inplace=True) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scale_back_response(bqm, response, scalar, ignored_interactions, ignored_variables, ignore_offset): """Helper function to scale back the response of sample method"""
if len(ignored_interactions) + len( ignored_variables) + ignore_offset == 0: response.record.energy = np.divide(response.record.energy, scalar) else: response.record.energy = bqm.energies((response.record.sample, response.variables)) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_params(ignored_variables, ignored_interactions): """Helper for sample methods"""
if ignored_variables is None: ignored_variables = set() elif not isinstance(ignored_variables, abc.Container): ignored_variables = set(ignored_variables) if ignored_interactions is None: ignored_interactions = set() elif not isinstance(ignored_interactions, abc.Container): ignored_interactions = set(ignored_interactions) return ignored_variables, ignored_interactions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calc_norm_coeff(h, J, bias_range, quadratic_range, ignored_variables, ignored_interactions): """Helper function to calculate normalization coefficient"""
if ignored_variables is None or ignored_interactions is None: raise ValueError('ignored interactions or variables cannot be None') def parse_range(r): if isinstance(r, Number): return -abs(r), abs(r) return r def min_and_max(iterable): if not iterable: return 0, 0 return min(iterable), max(iterable) if quadratic_range is None: linear_range, quadratic_range = bias_range, bias_range else: linear_range = bias_range lin_range, quad_range = map(parse_range, (linear_range, quadratic_range)) lin_min, lin_max = min_and_max([v for k, v in h.items() if k not in ignored_variables]) quad_min, quad_max = min_and_max([v for k, v in J.items() if not check_isin(k, ignored_interactions)]) inv_scalar = max(lin_min / lin_range[0], lin_max / lin_range[1], quad_min / quad_range[0], quad_max / quad_range[1]) if inv_scalar != 0: return 1. / inv_scalar else: return 1.
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scaled_bqm(bqm, scalar, bias_range, quadratic_range, ignored_variables, ignored_interactions, ignore_offset): """Helper function of sample for scaling"""
bqm_copy = bqm.copy() if scalar is None: scalar = _calc_norm_coeff(bqm_copy.linear, bqm_copy.quadratic, bias_range, quadratic_range, ignored_variables, ignored_interactions) bqm_copy.scale(scalar, ignored_variables=ignored_variables, ignored_interactions=ignored_interactions, ignore_offset=ignore_offset) bqm_copy.info.update({'scalar': scalar}) return bqm_copy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, bqm, scalar=None, bias_range=1, quadratic_range=None, ignored_variables=None, ignored_interactions=None, ignore_offset=False, **parameters): """ Scale and sample from the provided binary quadratic model. if scalar is not given, problem is scaled based on bias and quadratic ranges. See :meth:`.BinaryQuadraticModel.scale` and :meth:`.BinaryQuadraticModel.normalize` Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. scalar (number): Value by which to scale the energy range of the binary quadratic model. bias_range (number/pair): Value/range by which to normalize the all the biases, or if `quadratic_range` is provided, just the linear biases. quadratic_range (number/pair): Value/range by which to normalize the quadratic biases. ignored_variables (iterable, optional): Biases associated with these variables are not scaled. ignored_interactions (iterable[tuple], optional): As an iterable of 2-tuples. Biases associated with these interactions are not scaled. ignore_offset (bool, default=False): If True, the offset is not scaled. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet` """
ignored_variables, ignored_interactions = _check_params( ignored_variables, ignored_interactions) child = self.child bqm_copy = _scaled_bqm(bqm, scalar, bias_range, quadratic_range, ignored_variables, ignored_interactions, ignore_offset) response = child.sample(bqm_copy, **parameters) return _scale_back_response(bqm, response, bqm_copy.info['scalar'], ignored_variables, ignored_interactions, ignore_offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_ising(self, h, J, offset=0, scalar=None, bias_range=1, quadratic_range=None, ignored_variables=None, ignored_interactions=None, ignore_offset=False, **parameters): """ Scale and sample from the problem provided by h, J, offset if scalar is not given, problem is scaled based on bias and quadratic ranges. Args: h (dict): linear biases J (dict): quadratic or higher order biases offset (float, optional): constant energy offset scalar (number): Value by which to scale the energy range of the binary quadratic model. bias_range (number/pair): Value/range by which to normalize the all the biases, or if `quadratic_range` is provided, just the linear biases. quadratic_range (number/pair): Value/range by which to normalize the quadratic biases. ignored_variables (iterable, optional): Biases associated with these variables are not scaled. ignored_interactions (iterable[tuple], optional): As an iterable of 2-tuples. Biases associated with these interactions are not scaled. ignore_offset (bool, default=False): If True, the offset is not scaled. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet` """
if any(len(inter) > 2 for inter in J): # handle HUBO import warnings msg = ("Support for higher order Ising models in ScaleComposite is " "deprecated and will be removed in dimod 0.9.0. Please use " "PolyScaleComposite.sample_hising instead.") warnings.warn(msg, DeprecationWarning) from dimod.reference.composites.higherordercomposites import PolyScaleComposite from dimod.higherorder.polynomial import BinaryPolynomial poly = BinaryPolynomial.from_hising(h, J, offset=offset) ignored_terms = set() if ignored_variables is not None: ignored_terms.update(frozenset(v) for v in ignored_variables) if ignored_interactions is not None: ignored_terms.update(frozenset(inter) for inter in ignored_interactions) if ignore_offset: ignored_terms.add(frozenset()) return PolyScaleComposite(self.child).sample_poly(poly, scalar=scalar, bias_range=bias_range, poly_range=quadratic_range, ignored_terms=ignored_terms, **parameters) bqm = BinaryQuadraticModel.from_ising(h, J, offset=offset) return self.sample(bqm, scalar=scalar, bias_range=bias_range, quadratic_range=quadratic_range, ignored_variables=ignored_variables, ignored_interactions=ignored_interactions, ignore_offset=ignore_offset, **parameters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chimera_anticluster(m, n=None, t=4, multiplier=3.0, cls=BinaryQuadraticModel, subgraph=None, seed=None): """Generate an anticluster problem on a Chimera lattice. An anticluster problem has weak interactions within a tile and strong interactions between tiles. Args: m (int): Number of rows in the Chimera lattice. n (int, optional, default=m): Number of columns in the Chimera lattice. t (int, optional, default=t): Size of the shore within each Chimera tile. multiplier (number, optional, default=3.0): Strength of the intertile edges. cls (class, optional, default=:class:`.BinaryQuadraticModel`): Binary quadratic model class to build from. subgraph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): A subgraph of a Chimera(m, n, t) graph to build the anticluster problem on. seed (int, optional, default=None): Random seed. Returns: :obj:`.BinaryQuadraticModel`: spin-valued binary quadratic model. """
if seed is None: seed = numpy.random.randint(2**32, dtype=np.uint32) r = numpy.random.RandomState(seed) m = int(m) if n is None: n = m else: n = int(n) t = int(t) ldata = np.zeros(m*n*t*2) # number of nodes if m and n and t: inrow, incol = zip(*_iter_chimera_tile_edges(m, n, t)) if m > 1 or n > 1: outrow, outcol = zip(*_iter_chimera_intertile_edges(m, n, t)) else: outrow = outcol = tuple() qdata = r.choice((-1., 1.), size=len(inrow)+len(outrow)) qdata[len(inrow):] *= multiplier irow = inrow + outrow icol = incol + outcol else: irow = icol = qdata = tuple() bqm = cls.from_numpy_vectors(ldata, (irow, icol, qdata), 0.0, SPIN) if subgraph is not None: nodes, edges = subgraph subbqm = cls.empty(SPIN) try: subbqm.add_variables_from((v, bqm.linear[v]) for v in nodes) except KeyError: msg = "given 'subgraph' contains nodes not in Chimera({}, {}, {})".format(m, n, t) raise ValueError(msg) try: subbqm.add_interactions_from((u, v, bqm.adj[u][v]) for u, v in edges) except KeyError: msg = "given 'subgraph' contains edges not in Chimera({}, {}, {})".format(m, n, t) raise ValueError(msg) bqm = subbqm return bqm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(bqm, fp, vartype_header=False): """Dump a binary quadratic model to a string in COOrdinate format."""
for triplet in _iter_triplets(bqm, vartype_header): fp.write('%s\n' % triplet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loads(s, cls=BinaryQuadraticModel, vartype=None): """Load a COOrdinate formatted binary quadratic model from a string."""
return load(s.split('\n'), cls=cls, vartype=vartype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(fp, cls=BinaryQuadraticModel, vartype=None): """Load a COOrdinate formatted binary quadratic model from a file."""
pattern = re.compile(_LINE_REGEX) vartype_pattern = re.compile(_VARTYPE_HEADER_REGEX) triplets = [] for line in fp: triplets.extend(pattern.findall(line)) vt = vartype_pattern.findall(line) if vt: if vartype is None: vartype = vt[0] else: if isinstance(vartype, str): vartype = Vartype[vartype] else: vartype = Vartype(vartype) if Vartype[vt[0]] != vartype: raise ValueError("vartypes from headers and/or inputs do not match") if vartype is None: raise ValueError("vartype must be provided either as a header or as an argument") bqm = cls.empty(vartype) for u, v, bias in triplets: if u == v: bqm.add_variable(int(u), float(bias)) else: bqm.add_interaction(int(u), int(v), float(bias)) return bqm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_variable(self, v): """Remove variable v and all its interactions from a binary quadratic model. Args: v (variable): The variable to be removed from the binary quadratic model. Notes: If the specified variable is not in the binary quadratic model, this function does nothing. Examples: This example creates an Ising model and then removes one variable. False True """
if v not in self: return adj = self.adj # first remove all the interactions associated with v while adj[v]: self.remove_interaction(v, next(iter(adj[v]))) # remove the variable del self.linear[v] try: # invalidates counterpart del self._counterpart if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'): del self._binary elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'): del self._spin except AttributeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_interaction(self, u, v): """Remove interaction of variables u, v from a binary quadratic model. Args: u (variable): One of the pair of variables in the binary quadratic model that has an interaction. v (variable): One of the pair of variables in the binary quadratic model that has an interaction. Notes: Any interaction not in the binary quadratic model is ignored. Examples: This example creates an Ising model with three variables that has interactions between two, and then removes an interaction. False 1 """
try: del self.quadratic[(u, v)] except KeyError: return # no interaction with that name try: # invalidates counterpart del self._counterpart if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'): del self._binary elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'): del self._spin except AttributeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_interactions_from(self, interactions): """Remove all specified interactions from the binary quadratic model. Args: interactions (iterable[[variable, variable]]): A collection of interactions. Each interaction should be a 2-tuple of variables in the binary quadratic model. Notes: Any interaction not in the binary quadratic model is ignored. Examples: This example creates an Ising model with three variables that has interactions between two, and then removes an interaction. 1 """
for u, v in interactions: self.remove_interaction(u, v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_offset(self, offset): """Add specified value to the offset of a binary quadratic model. Args: offset (number): Value to be added to the constant energy offset of the binary quadratic model. Examples: This example creates an Ising model with an offset of -0.5 and then adds to it. 0.5 """
self.offset += offset try: self._counterpart.add_offset(offset) except AttributeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scale(self, scalar, ignored_variables=None, ignored_interactions=None, ignore_offset=False): """Multiply by the specified scalar all the biases and offset of a binary quadratic model. Args: scalar (number): Value by which to scale the energy range of the binary quadratic model. ignored_variables (iterable, optional): Biases associated with these variables are not scaled. ignored_interactions (iterable[tuple], optional): As an iterable of 2-tuples. Biases associated with these interactions are not scaled. ignore_offset (bool, default=False): If True, the offset is not scaled. Examples: This example creates a binary quadratic model and then scales it to half the original energy range. -1.0 -0.5 0.5 """
if ignored_variables is None: ignored_variables = set() elif not isinstance(ignored_variables, abc.Container): ignored_variables = set(ignored_variables) if ignored_interactions is None: ignored_interactions = set() elif not isinstance(ignored_interactions, abc.Container): ignored_interactions = set(ignored_interactions) linear = self.linear for v in linear: if v in ignored_variables: continue linear[v] *= scalar quadratic = self.quadratic for u, v in quadratic: if (u, v) in ignored_interactions or (v, u) in ignored_interactions: continue quadratic[(u, v)] *= scalar if not ignore_offset: self.offset *= scalar try: self._counterpart.scale(scalar, ignored_variables=ignored_variables, ignored_interactions=ignored_interactions) except AttributeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_variable(self, v, value): """Fix the value of a variable and remove it from a binary quadratic model. Args: v (variable): Variable in the binary quadratic model to be fixed. value (int): Value assigned to the variable. Values must match the :class:`.Vartype` of the binary quadratic model. Examples: This example creates a binary quadratic model with one variable and fixes its value. 0.5 1.0 False """
adj = self.adj linear = self.linear if value not in self.vartype.value: raise ValueError("expected value to be in {}, received {} instead".format(self.vartype.value, value)) removed_interactions = [] for u in adj[v]: self.add_variable(u, value * adj[v][u]) removed_interactions.append((u, v)) self.remove_interactions_from(removed_interactions) self.add_offset(value * linear[v]) self.remove_variable(v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_variables(self, fixed): """Fix the value of the variables and remove it from a binary quadratic model. Args: fixed (dict): A dictionary of variable assignments. Examples: """
for v, val in fixed.items(): self.fix_variable(v, val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flip_variable(self, v): """Flip variable v in a binary quadratic model. Args: v (variable): Variable in the binary quadratic model. If v is not in the binary quadratic model, it is ignored. Examples: This example creates a binary quadratic model with two variables and inverts the value of one. (-1.0, 2, -0.5) """
adj = self.adj linear = self.linear quadratic = self.quadratic if v not in adj: return if self.vartype is Vartype.SPIN: # in this case we just multiply by -1 linear[v] *= -1. for u in adj[v]: adj[v][u] *= -1. adj[u][v] *= -1. if (u, v) in quadratic: quadratic[(u, v)] *= -1. elif (v, u) in quadratic: quadratic[(v, u)] *= -1. else: raise RuntimeError("quadratic is missing an interaction") elif self.vartype is Vartype.BINARY: self.offset += linear[v] linear[v] *= -1 for u in adj[v]: bias = adj[v][u] adj[v][u] *= -1. adj[u][v] *= -1. linear[u] += bias if (u, v) in quadratic: quadratic[(u, v)] *= -1. elif (v, u) in quadratic: quadratic[(v, u)] *= -1. else: raise RuntimeError("quadratic is missing an interaction") else: raise RuntimeError("Unexpected vartype") try: self._counterpart.flip_variable(v) except AttributeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, bqm, ignore_info=True): """Update one binary quadratic model from another. Args: bqm (:class:`.BinaryQuadraticModel`): The updating binary quadratic model. Any variables in the updating model are added to the updated model. Values of biases and the offset in the updating model are added to the corresponding values in the updated model. ignore_info (bool, optional, default=True): If True, info in the given binary quadratic model is ignored, otherwise :attr:`.BinaryQuadraticModel.info` is updated with the given binary quadratic model's info, potentially overwriting values. Examples: This example creates two binary quadratic models and updates the first from the second. 1.25 False True 2.0 """
self.add_variables_from(bqm.linear, vartype=bqm.vartype) self.add_interactions_from(bqm.quadratic, vartype=bqm.vartype) self.add_offset(bqm.offset) if not ignore_info: self.info.update(bqm.info)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contract_variables(self, u, v): """Enforce u, v being the same variable in a binary quadratic model. The resulting variable is labeled 'u'. Values of interactions between `v` and variables that `u` interacts with are added to the corresponding interactions of `u`. Args: u (variable): Variable in the binary quadratic model. v (variable): Variable in the binary quadratic model. Examples: This example creates a binary quadratic model representing the K4 complete graph and contracts node (variable) 3 into node 2. The interactions between 3 and its neighbors 1 and 4 are added to the corresponding interactions between 2 and those same neighbors. False 25 """
adj = self.adj if u not in adj: raise ValueError("{} is not a variable in the binary quadratic model".format(u)) if v not in adj: raise ValueError("{} is not a variable in the binary quadratic model".format(v)) # if there is an interaction between u, v it becomes linear for u if v in adj[u]: if self.vartype is Vartype.BINARY: self.add_variable(u, adj[u][v]) elif self.vartype is Vartype.SPIN: self.add_offset(adj[u][v]) else: raise RuntimeError("unexpected vartype") self.remove_interaction(u, v) # all of the interactions that v has become interactions for u neighbors = list(adj[v]) for w in neighbors: self.add_interaction(u, w, adj[v][w]) self.remove_interaction(v, w) # finally remove v self.remove_variable(v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relabel_variables(self, mapping, inplace=True): """Relabel variables of a binary quadratic model as specified by mapping. Args: mapping (dict): Dict mapping current variable labels to new ones. If an incomplete mapping is provided, unmapped variables retain their current labels. inplace (bool, optional, default=True): If True, the binary quadratic model is updated in-place; otherwise, a new binary quadratic model is returned. Returns: :class:`.BinaryQuadraticModel`: A binary quadratic model with the variables relabeled. If `inplace` is set to True, returns itself. Examples: This example creates a binary quadratic model with two variables and relables one. BinaryQuadraticModel({1: 1.0, 'a': 0.0}, {('a', 1): -1}, 0.0, Vartype.SPIN) This example creates a binary quadratic model with two variables and returns a new model with relabled variables. {('a', 'b'): -1} """
try: old_labels = set(mapping) new_labels = set(itervalues(mapping)) except TypeError: raise ValueError("mapping targets must be hashable objects") for v in new_labels: if v in self.linear and v not in old_labels: raise ValueError(('A variable cannot be relabeled "{}" without also relabeling ' "the existing variable of the same name").format(v)) if inplace: shared = old_labels & new_labels if shared: old_to_intermediate, intermediate_to_new = resolve_label_conflict(mapping, old_labels, new_labels) self.relabel_variables(old_to_intermediate, inplace=True) self.relabel_variables(intermediate_to_new, inplace=True) return self linear = self.linear quadratic = self.quadratic adj = self.adj # rebuild linear and adj with the new labels for old in list(linear): if old not in mapping: continue new = mapping[old] # get the new interactions that need to be added new_interactions = [(new, v, adj[old][v]) for v in adj[old]] self.add_variable(new, linear[old]) self.add_interactions_from(new_interactions) self.remove_variable(old) return self else: return BinaryQuadraticModel({mapping.get(v, v): bias for v, bias in iteritems(self.linear)}, {(mapping.get(u, u), mapping.get(v, v)): bias for (u, v), bias in iteritems(self.quadratic)}, self.offset, self.vartype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_vartype(self, vartype, inplace=True): """Create a binary quadratic model with the specified vartype. Args: vartype (:class:`.Vartype`/str/set, optional): Variable type for the changed model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` inplace (bool, optional, default=True): If True, the binary quadratic model is updated in-place; otherwise, a new binary quadratic model is returned. Returns: :class:`.BinaryQuadraticModel`. A new binary quadratic model with vartype matching input 'vartype'. Examples: This example creates an Ising model and then creates a QUBO from it. (0.5, <Vartype.SPIN: frozenset({1, -1})>) (-2.0, <Vartype.BINARY: frozenset({0, 1})>) """
if not inplace: # create a new model of the appropriate type, then add self's biases to it new_model = BinaryQuadraticModel({}, {}, 0.0, vartype) new_model.add_variables_from(self.linear, vartype=self.vartype) new_model.add_interactions_from(self.quadratic, vartype=self.vartype) new_model.add_offset(self.offset) return new_model # in this case we are doing things in-place, if the desired vartype matches self.vartype, # then we don't need to do anything if vartype is self.vartype: return self if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY: linear, quadratic, offset = self.spin_to_binary(self.linear, self.quadratic, self.offset) elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN: linear, quadratic, offset = self.binary_to_spin(self.linear, self.quadratic, self.offset) else: raise RuntimeError("something has gone wrong. unknown vartype conversion.") # drop everything for v in linear: self.remove_variable(v) self.add_offset(-self.offset) self.vartype = vartype self.add_variables_from(linear) self.add_interactions_from(quadratic) self.add_offset(offset) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spin_to_binary(linear, quadratic, offset): """convert linear, quadratic, and offset from spin to binary. Does no checking of vartype. Copies all of the values into new objects. """
# the linear biases are the easiest new_linear = {v: 2. * bias for v, bias in iteritems(linear)} # next the quadratic biases new_quadratic = {} for (u, v), bias in iteritems(quadratic): new_quadratic[(u, v)] = 4. * bias new_linear[u] -= 2. * bias new_linear[v] -= 2. * bias # finally calculate the offset offset += sum(itervalues(quadratic)) - sum(itervalues(linear)) return new_linear, new_quadratic, offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def binary_to_spin(linear, quadratic, offset): """convert linear, quadratic and offset from binary to spin. Does no checking of vartype. Copies all of the values into new objects. """
h = {} J = {} linear_offset = 0.0 quadratic_offset = 0.0 for u, bias in iteritems(linear): h[u] = .5 * bias linear_offset += bias for (u, v), bias in iteritems(quadratic): J[(u, v)] = .25 * bias h[u] += .25 * bias h[v] += .25 * bias quadratic_offset += bias offset += .5 * linear_offset + .25 * quadratic_offset return h, J, offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """Create a copy of a BinaryQuadraticModel. Returns: :class:`.BinaryQuadraticModel` Examples: """
# new objects are constructed for each, so we just need to pass them in return BinaryQuadraticModel(self.linear, self.quadratic, self.offset, self.vartype, **self.info)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def energy(self, sample): """Determine the energy of the specified sample of a binary quadratic model. Energy of a sample for a binary quadratic model is defined as a sum, offset by the constant energy offset associated with the binary quadratic model, of the sample multipled by the linear bias of the variable and all its interactions; that is, .. math:: E(\mathbf{s}) = \sum_v h_v s_v + \sum_{u,v} J_{u,v} s_u s_v + c where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}` the quadratic bias (interactions), and :math:`c` the energy offset. Code for the energy calculation might look like the following:: energy = model.offset # doctest: +SKIP for v in model: # doctest: +SKIP energy += model.linear[v] * sample[v] for u, v in model.quadratic: # doctest: +SKIP energy += model.quadratic[(u, v)] * sample[u] * sample[v] Args: sample (dict): Sample for which to calculate the energy, formatted as a dict where keys are variables and values are the value associated with each variable. Returns: float: Energy for the sample. Examples: This example creates a binary quadratic model and returns the energies for a couple of samples. -0.5 3.5 """
linear = self.linear quadratic = self.quadratic if isinstance(sample, SampleView): # because the SampleView object simply reads from an underlying matrix, each read # is relatively expensive. # However, sample.items() is ~10x faster than {sample[v] for v in sample}, therefore # it is much more efficient to dump sample into a dictionary for repeated reads sample = dict(sample) en = self.offset en += sum(linear[v] * sample[v] for v in linear) en += sum(sample[u] * sample[v] * quadratic[(u, v)] for u, v in quadratic) return en
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def energies(self, samples_like, dtype=np.float): """Determine the energies of the given samples. Args: samples_like (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. dtype (:class:`numpy.dtype`): The data type of the returned energies. Returns: :obj:`numpy.ndarray`: The energies. """
samples, labels = as_samples(samples_like) if all(v == idx for idx, v in enumerate(labels)): ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(dtype=dtype) else: ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(variable_order=labels, dtype=dtype) energies = samples.dot(ldata) + (samples[:, irow]*samples[:, icol]).dot(qdata) + offset return np.asarray(energies, dtype=dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_coo(self, fp=None, vartype_header=False): """Serialize the binary quadratic model to a COOrdinate_ format encoding. .. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO) Args: fp (file, optional): `.write()`-supporting `file object`_ to save the linear and quadratic biases of a binary quadratic model to. The model is stored as a list of 3-tuples, (i, j, bias), where :math:`i=j` for linear biases. If not provided, returns a string. vartype_header (bool, optional, default=False): If true, the binary quadratic model's variable type as prepended to the string or file as a header. .. _file object: https://docs.python.org/3/glossary.html#term-file-object .. note:: Variables must use index lables (numeric lables). Binary quadratic models saved to COOrdinate format encoding do not preserve offsets. Examples: This is an example of a binary quadratic model encoded in COOrdinate format. .. code-block:: none 0 0 0.50000 0 1 0.50000 1 1 -1.50000 The Coordinate format with a header .. code-block:: none # vartype=SPIN 0 0 0.50000 0 1 0.50000 1 1 -1.50000 This is an example of writing a binary quadratic model to a COOrdinate-format file. This is an example of writing a binary quadratic model to a COOrdinate-format string. 0 0 -1.000000 0 1 -1.000000 1 1 1.000000 """
import dimod.serialization.coo as coo if fp is None: return coo.dumps(self, vartype_header) else: coo.dump(self, fp, vartype_header)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_coo(cls, obj, vartype=None): """Deserialize a binary quadratic model from a COOrdinate_ format encoding. .. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO) Args: obj: (str/file): Either a string or a `.read()`-supporting `file object`_ that represents linear and quadratic biases for a binary quadratic model. This data is stored as a list of 3-tuples, (i, j, bias), where :math:`i=j` for linear biases. vartype (:class:`.Vartype`/str/set, optional): Variable type for the binary quadratic model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` If not provided, the vartype must be specified with a header in the file. .. _file object: https://docs.python.org/3/glossary.html#term-file-object .. note:: Variables must use index lables (numeric lables). Binary quadratic models created from COOrdinate format encoding have offsets set to zero. Examples: An example of a binary quadratic model encoded in COOrdinate format. .. code-block:: none 0 0 0.50000 0 1 0.50000 1 1 -1.50000 The Coordinate format with a header .. code-block:: none # vartype=SPIN 0 0 0.50000 0 1 0.50000 1 1 -1.50000 This example saves a binary quadratic model to a COOrdinate-format file and creates a new model by reading the saved file. True """
import dimod.serialization.coo as coo if isinstance(obj, str): return coo.loads(obj, cls=cls, vartype=vartype) return coo.load(obj, cls=cls, vartype=vartype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_serializable(self, use_bytes=False, bias_dtype=np.float32, bytes_type=bytes): """Convert the binary quadratic model to a serializable object. Args: use_bytes (bool, optional, default=False): If True, a compact representation representing the biases as bytes is used. bias_dtype (numpy.dtype, optional, default=numpy.float32): If `use_bytes` is True, this numpy dtype will be used to represent the bias values in the serialized format. bytes_type (class, optional, default=bytes): This class will be used to wrap the bytes objects in the serialization if `use_bytes` is true. Useful for when using Python 2 and using BSON encoding, which will not accept the raw `bytes` type, so `bson.Binary` can be used instead. Returns: dict: An object that can be serialized. Examples: Encode using JSON Encode using BSON_ in python 3.5+ Encode using BSON in python 2.7. Because :class:`bytes` is an alias for :class:`str`, we need to signal to the encoder that it should encode the biases and labels as binary data. See also: :meth:`~.BinaryQuadraticModel.from_serializable` :func:`json.dumps`, :func:`json.dump` JSON encoding functions :meth:`bson.BSON.encode` BSON encoding method .. _BSON: http://bsonspec.org/ """
from dimod.package_info import __version__ schema_version = "2.0.0" try: variables = sorted(self.variables) except TypeError: # sorting unlike types in py3 variables = list(self.variables) num_variables = len(variables) # when doing byte encoding we can use less space depending on the # total number of variables index_dtype = np.uint16 if num_variables <= 2**16 else np.uint32 ldata, (irow, icol, qdata), offset = self.to_numpy_vectors( dtype=bias_dtype, index_dtype=index_dtype, sort_indices=True, variable_order=variables) doc = {"basetype": "BinaryQuadraticModel", "type": type(self).__name__, "version": {"dimod": __version__, "bqm_schema": schema_version}, "variable_labels": variables, "variable_type": self.vartype.name, "info": self.info, "offset": float(offset), "use_bytes": bool(use_bytes) } if use_bytes: doc.update({'linear_biases': array2bytes(ldata, bytes_type=bytes_type), 'quadratic_biases': array2bytes(qdata, bytes_type=bytes_type), 'quadratic_head': array2bytes(irow, bytes_type=bytes_type), 'quadratic_tail': array2bytes(icol, bytes_type=bytes_type)}) else: doc.update({'linear_biases': ldata.tolist(), 'quadratic_biases': qdata.tolist(), 'quadratic_head': irow.tolist(), 'quadratic_tail': icol.tolist()}) return doc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_serializable(cls, obj): """Deserialize a binary quadratic model. Args: obj (dict): A binary quadratic model serialized by :meth:`~.BinaryQuadraticModel.to_serializable`. Returns: :obj:`.BinaryQuadraticModel` Examples: Encode and decode using JSON See also: :meth:`~.BinaryQuadraticModel.to_serializable` :func:`json.loads`, :func:`json.load` JSON deserialization functions """
if obj.get("version", {"bqm_schema": "1.0.0"})["bqm_schema"] != "2.0.0": return cls._from_serializable_v1(obj) variables = [tuple(v) if isinstance(v, list) else v for v in obj["variable_labels"]] if obj["use_bytes"]: ldata = bytes2array(obj["linear_biases"]) qdata = bytes2array(obj["quadratic_biases"]) irow = bytes2array(obj["quadratic_head"]) icol = bytes2array(obj["quadratic_tail"]) else: ldata = obj["linear_biases"] qdata = obj["quadratic_biases"] irow = obj["quadratic_head"] icol = obj["quadratic_tail"] offset = obj["offset"] vartype = obj["variable_type"] bqm = cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, str(vartype), # handle unicode for py2 variable_order=variables) bqm.info.update(obj["info"]) return bqm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_networkx_graph(self, node_attribute_name='bias', edge_attribute_name='bias'): """Convert a binary quadratic model to NetworkX graph format. Args: node_attribute_name (hashable, optional, default='bias'): Attribute name for linear biases. edge_attribute_name (hashable, optional, default='bias'): Attribute name for quadratic biases. Returns: :class:`networkx.Graph`: A NetworkX graph with biases stored as node/edge attributes. Examples: This example converts a binary quadratic model to a NetworkX graph, using first the default attribute name for quadratic biases then "weight". 0.5 1 0.5 """
import networkx as nx BQM = nx.Graph() # add the linear biases BQM.add_nodes_from(((v, {node_attribute_name: bias, 'vartype': self.vartype}) for v, bias in iteritems(self.linear))) # add the quadratic biases BQM.add_edges_from(((u, v, {edge_attribute_name: bias}) for (u, v), bias in iteritems(self.quadratic))) # set the offset and vartype properties for the graph BQM.offset = self.offset BQM.vartype = self.vartype return BQM
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_networkx_graph(cls, G, vartype=None, node_attribute_name='bias', edge_attribute_name='bias'): """Create a binary quadratic model from a NetworkX graph. Args: G (:obj:`networkx.Graph`): A NetworkX graph with biases stored as node/edge attributes. vartype (:class:`.Vartype`/str/set, optional): Variable type for the binary quadratic model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` If not provided, the `G` should have a vartype attribute. If `vartype` is provided and `G.vartype` exists then the argument overrides the property. node_attribute_name (hashable, optional, default='bias'): Attribute name for linear biases. If the node does not have a matching attribute then the bias defaults to 0. edge_attribute_name (hashable, optional, default='bias'): Attribute name for quadratic biases. If the edge does not have a matching attribute then the bias defaults to 0. Returns: :obj:`.BinaryQuadraticModel` Examples: -1 """
if vartype is None: if not hasattr(G, 'vartype'): msg = ("either 'vartype' argument must be provided or " "the given graph should have a vartype attribute.") raise ValueError(msg) vartype = G.vartype linear = G.nodes(data=node_attribute_name, default=0) quadratic = G.edges(data=edge_attribute_name, default=0) offset = getattr(G, 'offset', 0) return cls(linear, quadratic, offset, vartype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_ising(self): """Converts a binary quadratic model to Ising format. If the binary quadratic model's vartype is not :class:`.Vartype.SPIN`, values are converted. Returns: tuple: 3-tuple of form (`linear`, `quadratic`, `offset`), where `linear` is a dict of linear biases, `quadratic` is a dict of quadratic biases, and `offset` is a number that represents the constant offset of the binary quadratic model. Examples: This example converts a binary quadratic model to an Ising problem. ({0: 1, 1: -1, 2: 0.5}, {(0, 1): 0.5, (1, 2): 1.5}, 1.4) """
# cast to a dict return dict(self.spin.linear), dict(self.spin.quadratic), self.spin.offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_ising(cls, h, J, offset=0.0): """Create a binary quadratic model from an Ising problem. Args: h (dict/list): Linear biases of the Ising problem. If a dict, should be of the is its associated bias. If a list, it is treated as a list of biases where the indices are the variable labels. J (dict[(variable, variable), bias]): Quadratic biases of the Ising problem. offset (optional, default=0.0): Constant offset applied to the model. Returns: :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to :class:`.Vartype.SPIN`. Examples: This example creates a binary quadratic model from an Ising problem. BinaryQuadraticModel({1: 1, 2: 2, 3: 3, 4: 4}, {(1, 2): 12, (1, 3): 13, (1, 4): 14, (2, 3): 23, (3, 4): 34, (2, 4): 24}, 0.0, Vartype.SPIN) """
if isinstance(h, abc.Sequence): h = dict(enumerate(h)) return cls(h, J, offset, Vartype.SPIN)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_qubo(self): """Convert a binary quadratic model to QUBO format. If the binary quadratic model's vartype is not :class:`.Vartype.BINARY`, values are converted. Returns: tuple: 2-tuple of form (`biases`, `offset`), where `biases` is a dict in which keys are pairs of variables and values are the associated linear or quadratic bias and `offset` is a number that represents the constant offset of the binary quadratic model. Examples: This example converts a binary quadratic model with spin variables to QUBO format with binary variables. ({(0, 0): 1.0, (0, 1): 2.0, (1, 1): -6.0, (1, 2): 6.0, (2, 2): -2.0}, 2.9) """
qubo = dict(self.binary.quadratic) qubo.update(((v, v), bias) for v, bias in iteritems(self.binary.linear)) return qubo, self.binary.offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_qubo(cls, Q, offset=0.0): """Create a binary quadratic model from a QUBO model. Args: Q (dict): Coefficients of a quadratic unconstrained binary optimization where `u`, `v`, are binary-valued variables and `bias` is their associated coefficient. offset (optional, default=0.0): Constant offset applied to the model. Returns: :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to :class:`.Vartype.BINARY`. Examples: This example creates a binary quadratic model from a QUBO model. {0: -1, 1: -1} <Vartype.BINARY: frozenset({0, 1})> """
linear = {} quadratic = {} for (u, v), bias in iteritems(Q): if u == v: linear[u] = bias else: quadratic[(u, v)] = bias return cls(linear, quadratic, offset, Vartype.BINARY)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_numpy_matrix(self, variable_order=None): """Convert a binary quadratic model to NumPy 2D array. Args: variable_order (list, optional): If provided, indexes the rows/columns of the NumPy array. If `variable_order` includes any variables not in the binary quadratic model, these are added to the NumPy array. Returns: :class:`numpy.ndarray`: The binary quadratic model as a NumPy 2D array. Note that the binary quadratic model is converted to :class:`~.Vartype.BINARY` vartype. Notes: The matrix representation of a binary quadratic model only makes sense for binary models. For a binary sample x, the energy of the model is given by: .. math:: E(x) = x^T Q x The offset is dropped when converting to a NumPy array. Examples: This example converts a binary quadratic model to NumPy array format while ordering variables and adding one ('d'). array([[ 0. , 0. , 0. , 0. ], [ 0. , 0.5, 1.5, 0. ], [ 0. , 0. , -1. , 0.5], [ 0. , 0. , 0. , 1. ]]) """
import numpy as np if variable_order is None: # just use the existing variable labels, assuming that they are [0, N) num_variables = len(self) mat = np.zeros((num_variables, num_variables), dtype=float) try: for v, bias in iteritems(self.binary.linear): mat[v, v] = bias except IndexError: raise ValueError(("if 'variable_order' is not provided, binary quadratic model must be " "index labeled [0, ..., N-1]")) for (u, v), bias in iteritems(self.binary.quadratic): if u < v: mat[u, v] = bias else: mat[v, u] = bias else: num_variables = len(variable_order) idx = {v: i for i, v in enumerate(variable_order)} mat = np.zeros((num_variables, num_variables), dtype=float) try: for v, bias in iteritems(self.binary.linear): mat[idx[v], idx[v]] = bias except KeyError as e: raise ValueError(("variable {} is missing from variable_order".format(e))) for (u, v), bias in iteritems(self.binary.quadratic): iu, iv = idx[u], idx[v] if iu < iv: mat[iu, iv] = bias else: mat[iv, iu] = bias return mat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_numpy_matrix(cls, mat, variable_order=None, offset=0.0, interactions=None): """Create a binary quadratic model from a NumPy array. Args: mat (:class:`numpy.ndarray`): Coefficients of a quadratic unconstrained binary optimization (QUBO) model formatted as a square NumPy 2D array. variable_order (list, optional): If provided, labels the QUBO variables; otherwise, row/column indices are used. If `variable_order` is longer than the array, extra values are ignored. offset (optional, default=0.0): Constant offset for the binary quadratic model. interactions (iterable, optional, default=[]): Any additional 0.0-bias interactions to be added to the binary quadratic model. Returns: :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to :class:`.Vartype.BINARY`. Examples: This example creates a binary quadratic model from a QUBO in NumPy format while adding an interaction with a new variable ('f'), ignoring an extra variable ('g'), and setting an offset. {'a': 1.0, 'b': 2.0, 'c': 3.0, 'd': 4.0, 'e': 5.0, 'f': 0.0} 10.0 0.0 2.5 """
import numpy as np if mat.ndim != 2: raise ValueError("expected input mat to be a square 2D numpy array") num_row, num_col = mat.shape if num_col != num_row: raise ValueError("expected input mat to be a square 2D numpy array") if variable_order is None: variable_order = list(range(num_row)) if interactions is None: interactions = [] bqm = cls({}, {}, offset, Vartype.BINARY) for (row, col), bias in np.ndenumerate(mat): if row == col: bqm.add_variable(variable_order[row], bias) elif bias: bqm.add_interaction(variable_order[row], variable_order[col], bias) for u, v in interactions: bqm.add_interaction(u, v, 0.0) return bqm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_numpy_vectors(self, variable_order=None, dtype=np.float, index_dtype=np.int64, sort_indices=False): """Convert a binary quadratic model to numpy arrays. Args: variable_order (iterable, optional): If provided, labels the variables; otherwise, row/column indices are used. dtype (:class:`numpy.dtype`, optional): Data-type of the biases. By default, the data-type is inferred from the biases. index_dtype (:class:`numpy.dtype`, optional): Data-type of the indices. By default, the data-type is inferred from the labels. sort_indices (bool, optional, default=False): If True, the indices are sorted, first by row then by column. Otherwise they match :attr:`~.BinaryQuadraticModel.quadratic`. Returns: :obj:`~numpy.ndarray`: A numpy array of the linear biases. tuple: The quadratic biases in COOrdinate format. :obj:`~numpy.ndarray`: A numpy array of the row indices of the quadratic matrix entries :obj:`~numpy.ndarray`: A numpy array of the column indices of the quadratic matrix entries :obj:`~numpy.ndarray`: A numpy array of the values of the quadratic matrix entries The offset Examples: array([0., 0., 0., 0.]) array([0, 0, 2]) array([1, 3, 3]) array([ 0.5, 1.5, -1. ]) """
linear = self.linear quadratic = self.quadratic num_variables = len(linear) num_interactions = len(quadratic) irow = np.empty(num_interactions, dtype=index_dtype) icol = np.empty(num_interactions, dtype=index_dtype) qdata = np.empty(num_interactions, dtype=dtype) if variable_order is None: try: ldata = np.fromiter((linear[v] for v in range(num_variables)), count=num_variables, dtype=dtype) except KeyError: raise ValueError(("if 'variable_order' is not provided, binary quadratic model must be " "index labeled [0, ..., N-1]")) # we could speed this up a lot with cython for idx, ((u, v), bias) in enumerate(quadratic.items()): irow[idx] = u icol[idx] = v qdata[idx] = bias else: try: ldata = np.fromiter((linear[v] for v in variable_order), count=num_variables, dtype=dtype) except KeyError: raise ValueError("provided 'variable_order' does not match binary quadratic model") label_to_idx = {v: idx for idx, v in enumerate(variable_order)} # we could speed this up a lot with cython for idx, ((u, v), bias) in enumerate(quadratic.items()): irow[idx] = label_to_idx[u] icol[idx] = label_to_idx[v] qdata[idx] = bias if sort_indices: # row index should be less than col index, this handles upper-triangular vs lower-triangular swaps = irow > icol if swaps.any(): # in-place irow[swaps], icol[swaps] = icol[swaps], irow[swaps] # sort lexigraphically order = np.lexsort((irow, icol)) if not (order == range(len(order))).all(): # copy irow = irow[order] icol = icol[order] qdata = qdata[order] return ldata, (irow, icol, qdata), ldata.dtype.type(self.offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_numpy_vectors(cls, linear, quadratic, offset, vartype, variable_order=None): """Create a binary quadratic model from vectors. Args: linear (array_like): A 1D array-like iterable of linear biases. quadratic (tuple[array_like, array_like, array_like]): A 3-tuple of 1D array_like vectors of the form (row, col, bias). offset (numeric, optional): Constant offset for the binary quadratic model. vartype (:class:`.Vartype`/str/set): Variable type for the binary quadratic model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` variable_order (iterable, optional): If provided, labels the variables; otherwise, indices are used. Returns: :obj:`.BinaryQuadraticModel` Examples: {(0, 1): -1.0} """
try: heads, tails, values = quadratic except ValueError: raise ValueError("quadratic should be a 3-tuple") if not len(heads) == len(tails) == len(values): raise ValueError("row, col, and bias should be of equal length") if variable_order is None: variable_order = list(range(len(linear))) linear = {v: float(bias) for v, bias in zip(variable_order, linear)} quadratic = {(variable_order[u], variable_order[v]): float(bias) for u, v, bias in zip(heads, tails, values)} return cls(linear, quadratic, offset, vartype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pandas_dataframe(self): """Convert a binary quadratic model to pandas DataFrame format. Returns: :class:`pandas.DataFrame`: The binary quadratic model as a DataFrame. The DataFrame has binary vartype. The rows and columns are labeled by the variables in the binary quadratic model. Notes: The DataFrame representation of a binary quadratic model only makes sense for binary models. For a binary sample x, the energy of the model is given by: .. math:: E(x) = x^T Q x The offset is dropped when converting to a pandas DataFrame. Examples: This example converts a binary quadratic model to pandas DataFrame format. a b c a 1.1 0.5 0.0 b 0.0 -1.0 1.5 c 0.0 0.0 0.5 """
import pandas as pd try: variable_order = sorted(self.linear) except TypeError: variable_order = list(self.linear) return pd.DataFrame(self.to_numpy_matrix(variable_order=variable_order), index=variable_order, columns=variable_order)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_pandas_dataframe(cls, bqm_df, offset=0.0, interactions=None): """Create a binary quadratic model from a QUBO model formatted as a pandas DataFrame. Args: bqm_df (:class:`pandas.DataFrame`): Quadratic unconstrained binary optimization (QUBO) model formatted as a pandas DataFrame. Row and column indices label the QUBO variables; values are QUBO coefficients. offset (optional, default=0.0): Constant offset for the binary quadratic model. interactions (iterable, optional, default=[]): Any additional 0.0-bias interactions to be added to the binary quadratic model. Returns: :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to :class:`vartype.BINARY`. Examples: This example creates a binary quadratic model from a QUBO in pandas DataFrame format while adding an interaction and setting a constant offset. 0 1 0 -1 2 1 0 -1 {0: -1, 1: -1.0, 2: 0.0} {(0, 1): 2, (0, 2): 0.0, (1, 2): 0.0} 2.5 <Vartype.BINARY: frozenset({0, 1})> """
if interactions is None: interactions = [] bqm = cls({}, {}, offset, Vartype.BINARY) for u, row in bqm_df.iterrows(): for v, bias in row.iteritems(): if u == v: bqm.add_variable(u, bias) elif bias: bqm.add_interaction(u, v, bias) for u, v in interactions: bqm.add_interaction(u, v, 0.0) return bqm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ising_energy(sample, h, J, offset=0.0): """Calculate the energy for the specified sample of an Ising model. Energy of a sample for a binary quadratic model is defined as a sum, offset by the constant energy offset associated with the model, of the sample multipled by the linear bias of the variable and all its interactions. For an Ising model, .. math:: E(\mathbf{s}) = \sum_v h_v s_v + \sum_{u,v} J_{u,v} s_u s_v + c where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}` the quadratic bias (interactions), and :math:`c` the energy offset. Args: sample (dict[variable, spin]): where keys are variables of the model and values are spins (either -1 or 1). h (dict[variable, bias]): the model and values are biases. J (dict[(variable, variable), bias]): are 2-tuples of variables of the model and values are quadratic biases associated with the pair of variables (the interaction). offset (numeric, optional, default=0): Constant offset to be applied to the energy. Default 0. Returns: float: The induced energy. Notes: No input checking is performed. Examples: This example calculates the energy of a sample representing two down spins for an Ising model of two variables that have positive biases of value 1 and are positively coupled with an interaction of value 1. -0.5 References `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_ """
# add the contribution from the linear biases for v in h: offset += h[v] * sample[v] # add the contribution from the quadratic biases for v0, v1 in J: offset += J[(v0, v1)] * sample[v0] * sample[v1] return offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qubo_energy(sample, Q, offset=0.0): """Calculate the energy for the specified sample of a QUBO model. Energy of a sample for a binary quadratic model is defined as a sum, offset by the constant energy offset associated with the model, of the sample multipled by the linear bias of the variable and all its interactions. For a quadratic unconstrained binary optimization (QUBO) model, .. math:: E(\mathbf{x}) = \sum_{u,v} Q_{u,v} x_u x_v + c where :math:`x_v` is the sample, :math:`Q_{u,v}` a matrix of biases, and :math:`c` the energy offset. Args: sample (dict[variable, spin]): where keys are variables of the model and values are binary (either 0 or 1). Q (dict[(variable, variable), coefficient]): are 2-tuples of variables of the model and values are biases associated with the pair of variables. Tuples (u, v) represent interactions and (v, v) linear biases. offset (numeric, optional, default=0): Constant offset to be applied to the energy. Default 0. Returns: float: The induced energy. Notes: No input checking is performed. Examples: This example calculates the energy of a sample representing two zeros for a QUBO model of two variables that have positive biases of value 1 and are positively coupled with an interaction of value 1. 0.5 References `QUBO model on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_ """
for v0, v1 in Q: offset += sample[v0] * sample[v1] * Q[(v0, v1)] return offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ising_to_qubo(h, J, offset=0.0): """Convert an Ising problem to a QUBO problem. Map an Ising model defined on spins (variables with {-1, +1} values) to quadratic unconstrained binary optimization (QUBO) formulation :math:`x' Q x` defined over binary variables (0 or 1 values), where the linear term is contained along the diagonal of Q. Return matrix Q that defines the model as well as the offset in energy between the two problem formulations: .. math:: s' J s + h' s = offset + x' Q x See :meth:`~dimod.utilities.qubo_to_ising` for the inverse function. Args: h (dict[variable, bias]): the model and values are biases. J (dict[(variable, variable), bias]): are 2-tuples of variables of the model and values are quadratic biases associated with the pair of variables (the interaction). offset (numeric, optional, default=0): Constant offset to be applied to the energy. Default 0. Returns: (dict, float): A 2-tuple containing: dict: QUBO coefficients. float: New energy offset. Examples: This example converts an Ising problem of two variables that have positive biases of value 1 and are positively coupled with an interaction of value 1 to a QUBO problem. ({(1, 1): 0.0, (1, 2): 4.0, (2, 2): 0.0}, -0.5) """
# the linear biases are the easiest q = {(v, v): 2. * bias for v, bias in iteritems(h)} # next the quadratic biases for (u, v), bias in iteritems(J): if bias == 0.0: continue q[(u, v)] = 4. * bias q[(u, u)] -= 2. * bias q[(v, v)] -= 2. * bias # finally calculate the offset offset += sum(itervalues(J)) - sum(itervalues(h)) return q, offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qubo_to_ising(Q, offset=0.0): """Convert a QUBO problem to an Ising problem. Map a quadratic unconstrained binary optimization (QUBO) problem :math:`x' Q x` defined over binary variables (0 or 1 values), where the linear term is contained along the diagonal of Q, to an Ising model defined on spins (variables with {-1, +1} values). Return h and J that define the Ising model as well as the offset in energy between the two problem formulations: .. math:: x' Q x = offset + s' J s + h' s See :meth:`~dimod.utilities.ising_to_qubo` for the inverse function. Args: Q (dict[(variable, variable), coefficient]): are 2-tuples of variables of the model and values are biases associated with the pair of variables. Tuples (u, v) represent interactions and (v, v) linear biases. offset (numeric, optional, default=0): Constant offset to be applied to the energy. Default 0. Returns: (dict, dict, float): A 3-tuple containing: dict: Linear coefficients of the Ising problem. dict: Quadratic coefficients of the Ising problem. float: New energy offset. Examples: This example converts a QUBO problem of two variables that have positive biases of value 1 and are positively coupled with an interaction of value 1 to an Ising problem. ({1: 0.75, 2: 0.75}, {(1, 2): 0.25}, 1.75) """
h = {} J = {} linear_offset = 0.0 quadratic_offset = 0.0 for (u, v), bias in iteritems(Q): if u == v: if u in h: h[u] += .5 * bias else: h[u] = .5 * bias linear_offset += bias else: if bias != 0.0: J[(u, v)] = .25 * bias if u in h: h[u] += .25 * bias else: h[u] = .25 * bias if v in h: h[v] += .25 * bias else: h[v] = .25 * bias quadratic_offset += bias offset += .5 * linear_offset + .25 * quadratic_offset return h, J, offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_label_conflict(mapping, old_labels=None, new_labels=None): """Resolve a self-labeling conflict by creating an intermediate labeling. Args: mapping (dict): A dict mapping the current variable labels to new ones. old_labels (set, optional, default=None): The keys of mapping. Can be passed in for performance reasons. These are not checked. new_labels (set, optional, default=None): The values of mapping. Can be passed in for performance reasons. These are not checked. Returns: tuple: A 2-tuple containing: dict: A map from the keys of mapping to an intermediate labeling dict: A map from the intermediate labeling to the values of mapping. """
if old_labels is None: old_labels = set(mapping) if new_labels is None: new_labels = set(itervalues(mapping)) # counter will be used to generate the intermediate labels, as an easy optimization # we start the counter with a high number because often variables are labeled by # integers starting from 0 counter = itertools.count(2 * len(mapping)) old_to_intermediate = {} intermediate_to_new = {} for old, new in iteritems(mapping): if old == new: # we can remove self-labels continue if old in new_labels or new in old_labels: # try to get a new unique label lbl = next(counter) while lbl in new_labels or lbl in old_labels: lbl = next(counter) # add it to the mapping old_to_intermediate[old] = lbl intermediate_to_new[lbl] = new else: old_to_intermediate[old] = new # don't need to add it to intermediate_to_new because it is a self-label return old_to_intermediate, intermediate_to_new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_variables(bqm, sampling_mode=True): """Determine assignments for some variables of a binary quadratic model. Roof duality finds a lower bound for the minimum of a quadratic polynomial. It can also find minimizing assignments for some of the polynomial's variables; these fixed variables take the same values in all optimal solutions [BHT]_ [BH]_. A quadratic pseudo-Boolean function can be represented as a network to find the lower bound through network-flow computations. `fix_variables` uses maximum flow in the implication network to correctly fix variables. Consequently, you can find an assignment for the remaining variables that attains the optimal value. Args: bqm (:obj:`.BinaryQuadraticModel`) A binary quadratic model. sampling_mode (bool, optional, default=True): In sampling mode, only roof-duality is used. When `sampling_mode` is false, strongly connected components are used to fix more variables, but in some optimal solutions these variables may take different values. Returns: dict: Variable assignments for some variables of the specified binary quadratic model. Examples: This example creates a binary quadratic model with a single ground state and fixes the model's single variable to the minimizing assignment. {'a': -1} This example has two ground states, :math:`a=b=-1` and :math:`a=b=1`, with no variable having a single value for all ground states, so neither variable is fixed. {} This example turns sampling model off, so variables are fixed to an assignment that attains the ground state. {'a': 1, 'b': 1} .. [BHT] Boros, E., P.L. Hammer, G. Tavares. Preprocessing of Unconstraint Quadratic Binary Optimization. Rutcor Research Report 10-2006, April, 2006. .. [BH] Boros, E., P.L. Hammer. Pseudo-Boolean optimization. Discrete Applied Mathematics 123, (2002), pp. 155-225 """
try: from dimod.roof_duality._fix_variables import fix_variables_wrapper except ImportError: raise ImportError("c++ extension roof_duality is not built") if sampling_mode: method = 2 # roof-duality only else: method = 1 # roof-duality and strongly connected components linear = bqm.linear if all(v in linear for v in range(len(bqm))): # we can work with the binary form of the bqm directly fixed = fix_variables_wrapper(bqm.binary, method) else: try: inverse_mapping = dict(enumerate(sorted(linear))) except TypeError: # in python3 unlike types cannot be sorted inverse_mapping = dict(enumerate(linear)) mapping = {v: i for i, v in inverse_mapping.items()} fixed = fix_variables_wrapper(bqm.relabel_variables(mapping, inplace=False).binary, method) fixed = {inverse_mapping[v]: val for v, val in fixed.items()} if bqm.vartype is Vartype.SPIN: return {v: 2*val - 1 for v, val in fixed.items()} else: return fixed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dimod_object_hook(obj): """JSON-decoding for dimod objects. See Also: :class:`json.JSONDecoder` for using custom decoders. """
if _is_sampleset_v2(obj): # in the future we could handle subtypes but right now we just have the # one return SampleSet.from_serializable(obj) elif _is_bqm_v2(obj): # in the future we could handle subtypes but right now we just have the # one return BinaryQuadraticModel.from_serializable(obj) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode_label(label): """Convert a list label into a tuple. Works recursively on nested lists."""
if isinstance(label, list): return tuple(_decode_label(v) for v in label) return label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encode_label(label): """Convert a tuple label into a list. Works recursively on nested tuples."""
if isinstance(label, tuple): return [_encode_label(v) for v in label] return label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_quadratic(poly, strength, vartype=None, bqm=None): """Create a binary quadratic model from a higher order polynomial. Args: poly (dict): variables and `bias` the associated bias. strength (float): Strength of the reduction constraint. Insufficient strength can result in the binary quadratic model not having the same minimizations as the polynomial. vartype (:class:`.Vartype`, optional): Vartype of the polynomial. If `bqm` is provided, vartype is not required. bqm (:class:`.BinaryQuadraticModel`, optional): The terms of the reduced polynomial are added to this binary quadratic model. If not provided, a new binary quadratic model is created. Returns: :class:`.BinaryQuadraticModel` Examples: """
if bqm is None: if vartype is None: raise ValueError("one of vartype and bqm must be provided") bqm = BinaryQuadraticModel.empty(vartype) else: if not isinstance(bqm, BinaryQuadraticModel): raise TypeError('create_using must be a BinaryQuadraticModel') if vartype is not None and vartype is not bqm.vartype: raise ValueError("one of vartype and create_using must be provided") bqm.info['reduction'] = {} new_poly = {} for term, bias in iteritems(poly): if len(term) == 0: bqm.add_offset(bias) elif len(term) == 1: v, = term bqm.add_variable(v, bias) else: new_poly[term] = bias return _reduce_degree(bqm, new_poly, vartype, strength)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reduce_degree(bqm, poly, vartype, scale): """helper function for make_quadratic"""
if all(len(term) <= 2 for term in poly): # termination criteria, we are already quadratic bqm.add_interactions_from(poly) return bqm # determine which pair of variables appear most often paircounter = Counter() for term in poly: if len(term) > 2: for u, v in itertools.combinations(term, 2): pair = frozenset((u, v)) paircounter[pair] += 1 pair, __ = paircounter.most_common(1)[0] u, v = pair # make a new product variable and aux variable and add constraint that u*v == p p = '{}*{}'.format(u, v) while p in bqm.linear: p = '_' + p if vartype is Vartype.BINARY: constraint = _binary_product([u, v, p]) bqm.info['reduction'][(u, v)] = {'product': p} else: aux = 'aux{},{}'.format(u, v) while aux in bqm.linear: aux = '_' + aux constraint = _spin_product([u, v, p, aux]) bqm.info['reduction'][(u, v)] = {'product': p, 'auxiliary': aux} constraint.scale(scale) bqm.update(constraint) new_poly = {} for interaction, bias in poly.items(): if u in interaction and v in interaction: if len(interaction) == 2: # in this case we are reducing a quadratic bias, so it becomes linear and can # be removed assert len(interaction) >= 2 bqm.add_variable(p, bias) continue interaction = tuple(s for s in interaction if s not in pair) interaction += (p,) if interaction in new_poly: new_poly[interaction] += bias else: new_poly[interaction] = bias return _reduce_degree(bqm, new_poly, vartype, scale)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poly_energy(sample_like, poly): """Calculates energy of a sample from a higher order polynomial. Args: sample (samples_like): A raw sample. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. poly (dict): tuple of variables and `bias` the associated bias. Returns: float: The energy of the sample. """
msg = ("poly_energy is deprecated and will be removed in dimod 0.9.0." "In the future, use BinaryPolynomial.energy") warnings.warn(msg, DeprecationWarning) # dev note the vartype is not used in the energy calculation and this will # be deprecated in the future return BinaryPolynomial(poly, 'SPIN').energy(sample_like)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poly_energies(samples_like, poly): """Calculates energy of samples from a higher order polynomial. Args: sample (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. poly (dict): tuple of variables and `bias` the associated bias. Variable labeling/indexing of terms in poly dict must match that of the sample(s). Returns: list/:obj:`numpy.ndarray`: The energy of the sample(s). """
msg = ("poly_energies is deprecated and will be removed in dimod 0.9.0." "In the future, use BinaryPolynomial.energies") warnings.warn(msg, DeprecationWarning) # dev note the vartype is not used in the energy calculation and this will # be deprecated in the future return BinaryPolynomial(poly, 'SPIN').energies(samples_like)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frustrated_loop(graph, num_cycles, R=float('inf'), cycle_predicates=tuple(), max_failed_cycles=100, seed=None): """Generate a frustrated loop problem. A (generic) frustrated loop (FL) problem is a sum of Hamiltonians, each generated from a single "good" loop. 1. Generate a loop by random walking on the support graph. 2. If the cycle is "good" (according to provided predicates), continue, else go to 1. 3. Choose one edge of the loop to be anti-ferromagnetic; all other edges are ferromagnetic. 4. Add the loop's coupler values to the FL problem. If at any time the magnitude of a coupler in the FL problem exceeds a given precision `R`, remove that coupler from consideration in the loop generation procedure. This is a generic generator of FL problems that encompasses both the original FL problem definition from [#HJARTL]_ and the limited FL problem definition from [#KLH]_ Args: graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): The graph to build the frustrated loops on. Either an integer n, interpreted as a complete graph of size n, or a nodes/edges pair, or a NetworkX graph. num_cyles (int): Desired number of frustrated cycles. R (int, optional, default=inf): Maximum interaction weight. cycle_predicates (tuple[function], optional): An iterable of functions, which should accept a cycle and return a bool. max_failed_cycles (int, optional, default=100): Maximum number of failures to find a cycle before terminating. seed (int, optional, default=None): Random seed. .. [#HJARTL] Hen, I., J. Job, T. Albash, T.F. Rønnow, M. Troyer, D. Lidar. Probing for quantum speedup in spin glass problems with planted solutions. https://arxiv.org/abs/1502.01663v2 .. [#KLH] King, A.D., T. Lanting, R. Harris. Performance of a quantum annealer on range-limited constraint satisfaction problems. https://arxiv.org/abs/1502.02098 """
nodes, edges = graph if num_cycles <= 0: raise ValueError("num_cycles should be a positive integer") if R <= 0: raise ValueError("R should be a positive integer") if max_failed_cycles <= 0: raise ValueError("max_failed_cycles should be a positive integer") if seed is None: seed = numpy.random.randint(2**32, dtype=np.uint32) r = numpy.random.RandomState(seed) # G = nx.Graph(edges) # J = collections.defaultdict(int) adj = {v: set() for v in nodes} for u, v in edges: if u in adj: adj[u].add(v) else: adj[u] = {v} if v in adj: adj[v].add(u) else: adj[v] = {u} bqm = BinaryQuadraticModel({v: 0.0 for v in nodes}, {edge: 0.0 for edge in edges}, 0.0, SPIN) failed_cycles = 0 good_cycles = 0 while good_cycles < num_cycles and failed_cycles < max_failed_cycles: cycle = _random_cycle(adj, r) # if the cycle failed or it is otherwise invalid, mark as failed and continue if cycle is None or not all(pred(cycle) for pred in cycle_predicates): failed_cycles += 1 continue # If its a good cycle, modify J with it. good_cycles += 1 cycle_J = {(cycle[i - 1], cycle[i]): -1. for i in range(len(cycle))} # randomly select an edge and flip it idx = r.randint(len(cycle)) cycle_J[(cycle[idx - 1], cycle[idx])] *= -1. # update the bqm bqm.add_interactions_from(cycle_J) for u, v in cycle_J: if abs(bqm.adj[u][v]) >= R: adj[u].remove(v) adj[v].remove(u) if good_cycles < num_cycles: raise RuntimeError return bqm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _random_cycle(adj, random_state): """Find a cycle using a random graph walk."""
# step through idx values in adj to pick a random one, random.choice does not work on dicts n = random_state.randint(len(adj)) for idx, v in enumerate(adj): if idx == n: break start = v walk = [start] visited = {start: 0} while True: if len(walk) > 1: # as long as we don't step back one we won't have any repeated edges previous = walk[-2] neighbors = [u for u in adj[walk[-1]] if u != previous] else: neighbors = list(adj[walk[-1]]) if not neighbors: # we've walked into a dead end return None # get a random neighbor u = random_state.choice(neighbors) if u in visited: # if we've seen this neighbour, then we have a cycle starting from it return walk[visited[u]:] else: # add to walk and keep moving walk.append(u) visited[u] = len(visited)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, bqm, num_spin_reversal_transforms=2, spin_reversal_variables=None, **kwargs): """Sample from the binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. num_spin_reversal_transforms (integer, optional, default=2): Number of spin reversal transform runs. spin_reversal_variables (list/dict, optional): Deprecated and no longer functional. Returns: :obj:`.SampleSet` Examples: This example runs 100 spin reversals applied to one variable of a QUBO problem. 400 Sample(sample={'a': 0, 'b': 1}, energy=-1.0) """
if spin_reversal_variables is not None: # this kwarg does not actually make sense for multiple SRTs. To # get the same functionality a user should apply them by hand # to their BQM before submitting. import warnings warnings.warn("'spin_reversal_variables' kwarg is deprecated and no longer functions.", DeprecationWarning) # make a main response responses = [] flipped_bqm = bqm.copy() transform = {v: False for v in bqm.variables} for ii in range(num_spin_reversal_transforms): # flip each variable with a 50% chance for v in bqm: if random() > .5: transform[v] = not transform[v] flipped_bqm.flip_variable(v) flipped_response = self.child.sample(flipped_bqm, **kwargs) tf_idxs = [flipped_response.variables.index(v) for v, flip in transform.items() if flip] if bqm.vartype is Vartype.SPIN: flipped_response.record.sample[:, tf_idxs] = -1 * flipped_response.record.sample[:, tf_idxs] else: flipped_response.record.sample[:, tf_idxs] = 1 - flipped_response.record.sample[:, tf_idxs] responses.append(flipped_response) return concatenate(responses)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_index(self, num_rows): """Add an index column. Left justified, width is determined by the space needed to print the largest index. """
width = len(str(num_rows - 1)) def f(datum): return str(datum.idx).ljust(width) header = ' '*width self.append(header, f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_sample(self, v, vartype, _left=False): """Add a sample column"""
vstr = str(v).rjust(2) # the variable will be len 0, or 1 length = len(vstr) if vartype is dimod.SPIN: def f(datum): return _spinstr(datum.sample[v], rjust=length) else: def f(datum): return _binarystr(datum.sample[v], rjust=length) self.append(vstr, f, _left=_left)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_vector(self, name, vector, _left=False): """Add a data vectors column."""
if np.issubdtype(vector.dtype, np.integer): # determine the length we need largest = str(max(vector.max(), vector.min(), key=abs)) length = max(len(largest), min(7, len(name))) # how many spaces we need to represent if len(name) > length: header = name[:length-1] + '.' else: header = name.rjust(length) def f(datum): return str(getattr(datum, name)).rjust(length) elif np.issubdtype(vector.dtype, np.floating): largest = np.format_float_positional(max(vector.max(), vector.min(), key=abs), precision=6, trim='0') length = max(len(largest), min(7, len(name))) # how many spaces we need to represent if len(name) > length: header = name[:length-1] + '.' else: header = name.rjust(length) def f(datum): return np.format_float_positional(getattr(datum, name), precision=6, trim='0', ).rjust(length) else: length = 7 if len(name) > length: header = name[:length-1] + '.' else: header = name.rjust(length) def f(datum): r = repr(getattr(datum, name)) if len(r) > length: r = r[:length-3] + '...' return r.rjust(length) self.append(header, f, _left=_left)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(self, obj, **kwargs): """Return the formatted representation of the object as a string."""
sio = StringIO() self.fprint(obj, stream=sio, **kwargs) return sio.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fprint(self, obj, stream=None, **kwargs): """Prints the formatted representation of the object on stream"""
if stream is None: stream = sys.stdout options = self.options options.update(kwargs) if isinstance(obj, dimod.SampleSet): self._print_sampleset(obj, stream, **options) return raise TypeError("cannot format type {}".format(type(obj)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_samples(samples_like, dtype=None, copy=False, order='C'): """Convert a samples_like object to a NumPy array and list of labels. Args: samples_like (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like_ structure. See examples below. dtype (data-type, optional): dtype for the returned samples array. If not provided, it is either derived from `samples_like`, if that object has a dtype, or set to :class:`numpy.int8`. copy (bool, optional, default=False): If true, then samples_like is guaranteed to be copied, otherwise it is only copied if necessary. order ({'K', 'A', 'C', 'F'}, optional, default='C'): Specify the memory layout of the array. See :func:`numpy.array`. Returns: tuple: A 2-tuple containing: :obj:`numpy.ndarray`: Samples. list: Variable labels Examples: The following examples convert a variety of samples_like objects: NumPy arrays (array([[1, 1, 1, 1, 1]], dtype=int8), [0, 1, 2, 3, 4]) (array([[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], dtype=int8), [0, 1]) Lists (array([[-1, 1, -1]], dtype=int8), [0, 1, 2]) (array([[-1], [ 1], [-1]], dtype=int8), [0]) Dicts (array([[0, 1, 0]], dtype=int8), ['a', 'b', 'c']) (array([[-1, 1], [ 1, 1]], dtype=int8), ['a', 'b']) A 2-tuple containing an array_like object and a list of labels (array([[-1, 1, -1]], dtype=int8), ['a', 'b', 'c']) (array([[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], dtype=int8), ['in', 'out']) .. _array_like: https://docs.scipy.org/doc/numpy/user/basics.creation.html """
if isinstance(samples_like, SampleSet): # we implicitely support this by handling an iterable of mapping but # it is much faster to just do this here. return samples_like.record.sample, list(samples_like.variables) if isinstance(samples_like, tuple) and len(samples_like) == 2: samples_like, labels = samples_like if not isinstance(labels, list) and labels is not None: labels = list(labels) else: labels = None if isinstance(samples_like, abc.Iterator): # if we don't check this case we can get unexpected behaviour where an # iterator can be depleted raise TypeError('samples_like cannot be an iterator') if isinstance(samples_like, abc.Mapping): return as_samples(([samples_like], labels), dtype=dtype) if (isinstance(samples_like, list) and samples_like and isinstance(samples_like[0], numbers.Number)): # this is not actually necessary but it speeds up the # samples_like = [1, 0, 1,...] case significantly return as_samples(([samples_like], labels), dtype=dtype) if not isinstance(samples_like, np.ndarray): if any(isinstance(sample, abc.Mapping) for sample in samples_like): # go through samples-like, turning the dicts into lists samples_like, old = list(samples_like), samples_like if labels is None: first = samples_like[0] if isinstance(first, abc.Mapping): labels = list(first) else: labels = list(range(len(first))) for idx, sample in enumerate(old): if isinstance(sample, abc.Mapping): try: samples_like[idx] = [sample[v] for v in labels] except KeyError: raise ValueError("samples_like and labels do not match") if dtype is None and not hasattr(samples_like, 'dtype'): dtype = np.int8 # samples-like should now be array-like arr = np.array(samples_like, dtype=dtype, copy=copy, order=order) if arr.ndim > 2: raise ValueError("expected samples_like to be <= 2 dimensions") if arr.ndim < 2: if arr.size: arr = np.atleast_2d(arr) elif labels: # is not None and len > 0 arr = arr.reshape((0, len(labels))) else: arr = arr.reshape((0, 0)) # ok we're basically done, just need to check against the labels if labels is None: return arr, list(range(arr.shape[1])) elif len(labels) != arr.shape[1]: raise ValueError("samples_like and labels dimensions do not match") else: return arr, labels
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concatenate(samplesets, defaults=None): """Combine SampleSets. Args: samplesets (iterable[:obj:`.SampleSet`): An iterable of sample sets. defaults (dict, optional): Dictionary mapping data vector names to the corresponding default values. Returns: :obj:`.SampleSet`: A sample set with the same vartype and variable order as the first given in `samplesets`. Examples: array([[-1, 1], [ 1, -1]], dtype=int8) """
itertup = iter(samplesets) try: first = next(itertup) except StopIteration: raise ValueError("samplesets must contain at least one SampleSet") vartype = first.vartype variables = first.variables records = [first.record] records.extend(_iter_records(itertup, vartype, variables)) # dev note: I was able to get ~2x performance boost when trying to # implement the same functionality here by hand (I didn't know that # this function existed then). However I think it is better to use # numpy's function and rely on their testing etc. If however this becomes # a performance bottleneck in the future, it might be worth changing. record = recfunctions.stack_arrays(records, defaults=defaults, asrecarray=True, usemask=False) return SampleSet(record, variables, {}, vartype)