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:...
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() )* ...
<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)...
# 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) y...
<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 retu...
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: generat...
# 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)...
<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) :...
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]) ...
<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 wit...
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 fr...
<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 imp...
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_threshol...
<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, s...
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) ...
<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:`.BinaryQ...
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()) retu...
<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 bi...
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...
<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...
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...
<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 quadrati...
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 ...
<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`. Expe...
@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))): ...
<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-l...
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...
<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`....
@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") ...
<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 intege...
# 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_Non...
<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` becau...
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...
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. Retur...
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 s...
<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: * :c...
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, ...
<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 ...
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...
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, ...
<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 curr...
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...
<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...
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 h...
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` inc...
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...
<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: T...
# 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 c...
<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:`.BinaryQ...
# 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("'sa...
<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 ...
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)) ...
<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): ...
<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: ...
<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_variab...
<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): """...
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, ...
<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, **...
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 ins...
<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 latt...
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_...
<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...
<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 t...
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 counterp...
<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 t...
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 sel...
<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, v...
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 ...
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...
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_inter...
<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 quadrat...
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][...
<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 assi...
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 binar...
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. ...
<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 quad...
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 interac...
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 becom...
<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...
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...
<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, optiona...
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, var...
<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 value...
# 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 ...
<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...
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 ...
<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...
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 ...
<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, 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) ...
<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.o...
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/S...
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_by...
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...
<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...
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...
<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_att...
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...
<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. ...
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=n...
<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 conve...
# 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 d...
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 conver...
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 optimi...
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, index...
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...
<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:`nu...
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...
<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. A...
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=dtyp...
<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):...
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: ...
<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 ...
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, ...
<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...
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: ...
<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 i...
# 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 defi...
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 quadr...
# 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 ...
<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` ...
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: ...
<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 (d...
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 # inte...
<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 min...
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...
<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 BinaryQuadra...
<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 ...
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') i...
<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 i...
<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` i...
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(po...
<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....
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...
<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 (gen...
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: ...
<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: ...
<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...
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_vari...
<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=leng...
<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...
<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 (sample...
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: ...
<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, op...
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, vari...