code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not isspmatrix(matrix): # cast to sparse so that we don't need to handle different # matrix types matrix = csc_matrix(matrix) # get the attractors - non-zero elements of the matrix diagonal attractors = matrix.diagonal().nonzero()[0] # somewhere to put the clusters clusters = set() # the nodes in the same row as each attractor form a cluster for attractor in attractors: cluster = tuple(matrix.getrow(attractor).nonzero()[1].tolist()) clusters.add(cluster) return sorted(list(clusters))
def get_clusters(matrix)
Retrieve the clusters from the matrix :param matrix: The matrix produced by the MCL algorithm :returns: A list of tuples where each tuple represents a cluster and contains the indices of the nodes belonging to the cluster
4.992376
5.290568
0.943637
assert expansion > 1, "Invalid expansion parameter" assert inflation > 1, "Invalid inflation parameter" assert loop_value >= 0, "Invalid loop_value" assert iterations > 0, "Invalid number of iterations" assert pruning_threshold >= 0, "Invalid pruning_threshold" assert pruning_frequency > 0, "Invalid pruning_frequency" assert convergence_check_frequency > 0, "Invalid convergence_check_frequency" printer = MessagePrinter(verbose) printer.print("-" * 50) printer.print("MCL Parameters") printer.print("Expansion: {}".format(expansion)) printer.print("Inflation: {}".format(inflation)) if pruning_threshold > 0: printer.print("Pruning threshold: {}, frequency: {} iteration{}".format( pruning_threshold, pruning_frequency, "s" if pruning_frequency > 1 else "")) else: printer.print("No pruning") printer.print("Convergence check: {} iteration{}".format( convergence_check_frequency, "s" if convergence_check_frequency > 1 else "")) printer.print("Maximum iterations: {}".format(iterations)) printer.print("{} matrix mode".format("Sparse" if isspmatrix(matrix) else "Dense")) printer.print("-" * 50) # Initialize self-loops if loop_value > 0: matrix = add_self_loops(matrix, loop_value) # Normalize matrix = normalize(matrix) # iterations for i in range(iterations): printer.print("Iteration {}".format(i + 1)) # store current matrix for convergence checking last_mat = matrix.copy() # perform MCL expansion and inflation matrix = iterate(matrix, expansion, inflation) # prune if pruning_threshold > 0 and i % pruning_frequency == pruning_frequency - 1: printer.print("Pruning") matrix = prune(matrix, pruning_threshold) # Check for convergence if i % convergence_check_frequency == convergence_check_frequency - 1: printer.print("Checking for convergence") if converged(matrix, last_mat): printer.print("Converged after {} iteration{}".format(i + 1, "s" if i > 0 else "")) break printer.print("-" * 50) return matrix
def run_mcl(matrix, expansion=2, inflation=2, loop_value=1, iterations=100, pruning_threshold=0.001, pruning_frequency=1, convergence_check_frequency=1, verbose=False)
Perform MCL on the given similarity matrix :param matrix: The similarity matrix to cluster :param expansion: The cluster expansion factor :param inflation: The cluster inflation factor :param loop_value: Initialization value for self-loops :param iterations: Maximum number of iterations (actual number of iterations will be less if convergence is reached) :param pruning_threshold: Threshold below which matrix elements will be set set to 0 :param pruning_frequency: Perform pruning every 'pruning_frequency' iterations. :param convergence_check_frequency: Perform the check for convergence every convergence_check_frequency iterations :param verbose: Print extra information to the console :returns: The final matrix
1.922698
1.903716
1.009971
return { type(u''): u''.join, type(b''): concat_bytes, }.get(type(data), list)
def _guess_concat(data)
Guess concat function from given data
7.919831
7.212847
1.098017
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') ))
def print_code_table(self, out=sys.stdout)
Print code table overview
4.230495
3.983809
1.061922
# 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)
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)
6.21517
6.279108
0.989817
return self._concat(self.decode_streaming(data))
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:
29.326363
54.265423
0.540424
# 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
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
3.671222
3.75753
0.977031
concat = concat or _guess_concat(next(iter(frequencies))) # Heap consists of tuples: (frequency, [list of tuples: (symbol, (bitsize, value))]) heap = [(f, [(s, (0, 0))]) for s, f in frequencies.items()] # Add EOF symbol. # TODO: argument to set frequency of EOF? heap.append((1, [(_EOF, (0, 0))])) # Use heapq approach to build the encodings of the huffman tree leaves. heapify(heap) while len(heap) > 1: # Pop the 2 smallest items from heap a = heappop(heap) b = heappop(heap) # Merge nodes (update codes for each symbol appropriately) merged = ( a[0] + b[0], [(s, (n + 1, v)) for (s, (n, v)) in a[1]] + [(s, (n + 1, (1 << n) + v)) for (s, (n, v)) in b[1]] ) heappush(heap, merged) # Code table is dictionary mapping symbol to (bitsize, value) table = dict(heappop(heap)[1]) return cls(table, concat=concat, check=False)
def from_frequencies(cls, frequencies, concat=None)
Build Huffman code table from given symbol frequencies :param frequencies: symbol to frequency mapping :param concat: function to concatenate symbols
4.455069
4.427739
1.006173
frequencies = collections.Counter(data) return cls.from_frequencies(frequencies, concat=_guess_concat(data))
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
14.885896
15.543967
0.957664
self._uuid = None self._columns = None self._rownumber = 0 # Internal helper state self._state = self._STATE_NONE self._data = None self._columns = None
def _reset_state(self)
Reset state about the previous query in preparation for running another query
8.318041
7.199523
1.15536
# Sleep until we're done or we got the columns if self._columns is None: return [] return [ # name, type_code, display_size, internal_size, precision, scale, null_ok (col[0], col[1], None, None, None, None, True) for col in self._columns ]
def description(self)
This read-only attribute is a sequence of 7-item sequences. Each of these sequences contains information describing one result column: - name - type_code - display_size (None in current implementation) - internal_size (None in current implementation) - precision (None in current implementation) - scale (None in current implementation) - null_ok (always True in current implementation) The ``type_code`` can be interpreted by comparing it to the Type Objects specified in the section below.
5.127356
4.229885
1.212174
if parameters is None or not parameters: sql = operation else: sql = operation % _escaper.escape_args(parameters) self._reset_state() self._state = self._STATE_RUNNING self._uuid = uuid.uuid1() if is_response: response = self._db.select(sql, settings={'query_id': self._uuid}) self._process_response(response) else: self._db.raw(sql)
def execute(self, operation, parameters=None, is_response=True)
Prepare and execute a database operation (query or command).
4.613877
4.431314
1.041199
values_list = [] RE_INSERT_VALUES = re.compile( r"\s*((?:INSERT|REPLACE)\s.+\sVALUES?\s*)" + r"(\(\s*(?:%s|%\(.+\)s)\s*(?:,\s*(?:%s|%\(.+\)s)\s*)*\))" + r"(\s*(?:ON DUPLICATE.*)?);?\s*\Z", re.IGNORECASE | re.DOTALL) m = RE_INSERT_VALUES.match(operation) if m: q_prefix = m.group(1) % () q_values = m.group(2).rstrip() for parameters in seq_of_parameters[:-1]: values_list.append(q_values % _escaper.escape_args(parameters)) query = '{} {};'.format(q_prefix, ','.join(values_list)) return self._db.raw(query) for parameters in seq_of_parameters[:-1]: self.execute(operation, parameters, is_response=False)
def executemany(self, operation, seq_of_parameters)
Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence ``seq_of_parameters``. Only the final result set is retained. Return values are not defined.
3.936556
4.193134
0.93881
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)
def fetchone(self)
Fetch the next row of a query result set, returning a single sequence, or ``None`` when no more data is available.
4.407143
4.410436
0.999253
if self._state == self._STATE_NONE: raise Exception("No query yet") if size is None: size = 1 if not self._data: return [] else: if len(self._data) > size: result, self._data = self._data[:size], self._data[size:] else: result, self._data = self._data, [] self._rownumber += len(result) return result
def fetchmany(self, size=None)
Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor's arraysize determines the number of rows to be fetched. The method should try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned.
2.68893
3.031264
0.887066
if self._state == self._STATE_NONE: raise Exception("No query yet") if not self._data: return [] else: result, self._data = self._data, [] self._rownumber += len(result) return result
def fetchall(self)
Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples).
4.629742
4.396096
1.053149
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
def _process_response(self, response)
Update the internal state with the data from the response
4.095018
3.754002
1.090841
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
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.
3.581961
3.080801
1.162672
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))
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`.
2.914356
2.922982
0.997049
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)
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.
4.277056
4.166536
1.026526
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)
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`
3.50657
3.968147
0.883679
r 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
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: >>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2) >>> bqm.energy({'a': 1, 'b': 0, 'c': 1}) 0.0 >>> bqm.energy({'a': 1, 'b': 1, 'c': 1}) 1.0 >>> bqm = dimod.generators.combinations(5, 1) >>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 0, 4: 0}) 0.0 >>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 1, 4: 0}) 1.0 >>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2, strength=3.0) >>> bqm.energy({'a': 1, 'b': 0, 'c': 1}) 0.0 >>> bqm.energy({'a': 1, 'b': 1, 'c': 1}) 3.0
3.972084
3.95309
1.004805
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)
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`
2.971577
2.929465
1.014375
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)
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: >>> import networkx as nx >>> K_7 = nx.complete_graph(7) >>> bqm = dimod.generators.random.ran_r(1, K_7) .. [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
3.026956
3.15199
0.960332
@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
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`.
3.60963
3.330365
1.083854
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
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.
2.915395
2.920727
0.998175
@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
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`.
2.969151
2.531555
1.172856
# by default, constrain only one argument, the 'vartype` if not arg_names: arg_names = ['vartype'] def _vartype_arg(f): argspec = getargspec(f) def _enforce_single_arg(name, args, kwargs): try: vartype = kwargs[name] except KeyError: raise TypeError('vartype argument missing') kwargs[name] = as_vartype(vartype) @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 _vartype_arg
def vartype_argument(*arg_names)
Ensures the wrapped function receives valid vartype argument(s). One or more argument names can be specified (as a list of string arguments). Args: *arg_names (list[str], argument names, optional, default='vartype'): The names of the constrained arguments in function decorated. Returns: Function decorator. Examples: >>> from dimod.decorators import vartype_argument >>> @vartype_argument() ... def f(x, vartype): ... print(vartype) ... >>> f(1, 'SPIN') Vartype.SPIN >>> f(1, vartype='SPIN') Vartype.SPIN >>> @vartype_argument('y') ... def f(x, y): ... print(y) ... >>> f(1, 'SPIN') Vartype.SPIN >>> f(1, y='SPIN') Vartype.SPIN >>> @vartype_argument('z') ... def f(x, **kwargs): ... print(kwargs['z']) ... >>> f(1, z='SPIN') Vartype.SPIN Note: The function decorated can explicitly list (name) vartype arguments constrained by :func:`vartype_argument`, or it can use a keyword arguments `dict`. See also: :func:`~dimod.as_vartype`
3.679456
3.795559
0.969411
# 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
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.
4.297855
3.944737
1.089516
bio = io.BytesIO() np.save(bio, arr, allow_pickle=False) return bytes_type(bio.getvalue())
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
2.552646
4.618453
0.552706
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)
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`
5.244122
5.639841
0.929835
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
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`
4.793343
4.752664
1.008559
# use roof-duality to decide which variables to fix parameters['fixed_variables'] = fix_variables(bqm, sampling_mode=sampling_mode) return super(RoofDualityComposite, self).sample(bqm, **parameters)
def sample(self, bqm, sampling_mode=True, **parameters)
Sample from the provided binary quadratic model. Uses the :func:`~dimod.roof_duality.fix_variables` function to determine which variables to fix. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. 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. **parameters: Parameters for the child sampler. Returns: :obj:`dimod.SampleSet`
7.366251
4.489199
1.640883
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
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`
2.656172
2.454417
1.082201
energy, = self.energies(sample_like, dtype=dtype) return energy
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.
6.090631
17.192669
0.354257
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
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.
3.354526
3.502929
0.957635
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
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.
3.262737
3.422833
0.953227
def parse_range(r): if isinstance(r, Number): return -abs(r), abs(r) return r if ignored_terms is None: ignored_terms = set() else: ignored_terms = {asfrozenset(term) for term in ignored_terms} if poly_range is None: linear_range, poly_range = bias_range, bias_range else: linear_range = bias_range lin_range, poly_range = map(parse_range, (linear_range, poly_range)) # determine the current ranges for linear, higherorder lmin = lmax = 0 pmin = pmax = 0 for term, bias in self.items(): if term in ignored_terms: # we don't use the ignored terms to calculate the scaling continue if len(term) == 1: lmin = min(bias, lmin) lmax = max(bias, lmax) elif len(term) > 1: pmin = min(bias, pmin) pmax = max(bias, pmax) inv_scalar = max(lmin / lin_range[0], lmax / lin_range[1], pmin / poly_range[0], pmax / poly_range[1]) if inv_scalar != 0: self.scale(1 / inv_scalar, ignored_terms=ignored_terms)
def normalize(self, bias_range=1, poly_range=None, ignored_terms=None)
Normalizes the biases of the binary polynomial such that they fall in the provided range(s). If `poly_range` is provided, then `bias_range` will be treated as the range for the linear biases and `poly_range` will be used for the range of the other biases. Args: bias_range (number/pair): Value/range by which to normalize the all the biases, or if `poly_range` is provided, just the linear biases. poly_range (number/pair, optional): Value/range by which to normalize the higher order biases. ignored_terms (iterable, optional): Biases associated with these terms are not scaled.
2.719776
2.546298
1.06813
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
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.
3.03316
3.113181
0.974296
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)
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 = dimod.BinaryPolynomial.from_hising({'a': 2}, {'ab': -1}, 0)
5.117118
6.866802
0.745197
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
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: >>> poly = dimod.BinaryPolynomial({'a': -1, 'ab': 1, 'abc': -1}, dimod.SPIN) >>> h, J, off = poly.to_hising() >>> h {'a': -1}
3.96428
2.905254
1.364521
poly = cls(H, Vartype.BINARY) if offset is not None: poly[()] = poly.get((), 0) + offset return poly
def from_hubo(cls, H, offset=None)
Construct a binary polynomial from a higher-order unconstrained binary optimization (HUBO) problem. Args: H (dict): Coefficients of a higher-order unconstrained binary optimization (HUBO) model. Returns: :obj:`.BinaryPolynomial` Examples: >>> poly = dimod.BinaryPolynomial.from_hubo({('a', 'b', 'c'): -1})
8.158825
14.866661
0.5488
if self.vartype is Vartype.SPIN: return self.to_binary().to_hubo() H = {tuple(term): bias for term, bias in self.items() if term} offset = self[tuple()] if tuple() in self else 0 return H, offset
def to_hubo(self)
Construct a higher-order unconstrained binary optimization (HUBO) problem from a binary polynomial. Returns: tuple: A 2-tuple of the form (`H`, `offset`) where `H` is the HUBO and `offset` is the linear offset.
6.665108
5.281325
1.262014
if self.vartype is Vartype.BINARY: if copy: return self.copy() else: return self new = BinaryPolynomial({}, Vartype.BINARY) # s = 2x - 1 for term, bias in self.items(): for t in map(frozenset, powerset(term)): newbias = bias * 2**len(t) * (-1)**(len(term) - len(t)) if t in new: new[t] += newbias else: new[t] = newbias return new
def to_binary(self, copy=False)
Return a binary polynomial over `{0, 1}` variables. Args: copy (optional, default=False): If True, the returned polynomial is always a copy. Otherwise, if the polynomial is binary-valued already it returns itself. Returns: :obj:`.BinaryPolynomial`
4.077989
4.220127
0.966319
# 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
def greedy_coloring(adj)
Determines a vertex coloring. Args: adj (dict): The edge structure of the graph to be colored. `adj` should be of the form {node: neighbors, ...} where neighbors is a set. Returns: dict: the coloring {node: color, ...} dict: the colors {color: [node, ...], ...} Note: This is a greedy heuristic: the resulting coloring is not necessarily minimal.
2.765174
2.780173
0.994605
# 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
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.
3.492303
3.627219
0.962804
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
def _scale_back_response(bqm, response, scalar, ignored_interactions, ignored_variables, ignore_offset)
Helper function to scale back the response of sample method
3.942761
3.666744
1.075276
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
def _check_params(ignored_variables, ignored_interactions)
Helper for sample methods
1.634309
1.577022
1.036326
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.
def _calc_norm_coeff(h, J, bias_range, quadratic_range, ignored_variables, ignored_interactions)
Helper function to calculate normalization coefficient
2.465653
2.383372
1.034523
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
def _scaled_bqm(bqm, scalar, bias_range, quadratic_range, ignored_variables, ignored_interactions, ignore_offset)
Helper function of sample for scaling
2.329872
2.23814
1.040986
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)
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`
3.026464
3.138264
0.964375
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)
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`
2.917559
2.88554
1.011096
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
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.
2.791713
2.668818
1.046049
for triplet in _iter_triplets(bqm, vartype_header): fp.write('%s\n' % triplet)
def dump(bqm, fp, vartype_header=False)
Dump a binary quadratic model to a string in COOrdinate format.
3.662037
3.651886
1.00278
return load(s.split('\n'), cls=cls, vartype=vartype)
def loads(s, cls=BinaryQuadraticModel, vartype=None)
Load a COOrdinate formatted binary quadratic model from a string.
3.907978
3.985777
0.980481
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
def load(fp, cls=BinaryQuadraticModel, vartype=None)
Load a COOrdinate formatted binary quadratic model from a file.
2.468081
2.437902
1.012379
# NB: The existence of the _spin property implies that it is up to date, methods that # invalidate it will erase the property try: spin = self._spin if spin is not None: return spin except AttributeError: pass if self.vartype is Vartype.SPIN: self._spin = spin = self else: self._counterpart = self._spin = spin = self.change_vartype(Vartype.SPIN, inplace=False) # we also want to go ahead and set spin.binary to refer back to self spin._binary = self return spin
def spin(self)
:class:`.BinaryQuadraticModel`: An instance of the Ising model subclass of the :class:`.BinaryQuadraticModel` superclass, corresponding to a binary quadratic model with spins as its variables. Enables access to biases for the spin-valued binary quadratic model regardless of the :class:`vartype` set when the model was created. If the model was created with the :attr:`.binary` vartype, the Ising model subclass is instantiated upon the first use of the :attr:`.spin` property and used in any subsequent reads. Examples: This example creates a QUBO model and uses the :attr:`.spin` property to instantiate the corresponding Ising model. >>> import dimod ... >>> bqm_qubo = dimod.BinaryQuadraticModel({0: -1, 1: -1}, {(0, 1): 2}, 0.0, dimod.BINARY) >>> bqm_spin = bqm_qubo.spin >>> bqm_spin # doctest: +SKIP BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, Vartype.SPIN) >>> bqm_spin.spin is bqm_spin True Note: Methods like :meth:`.add_variable`, :meth:`.add_variables_from`, :meth:`.add_interaction`, etc. should only be used on the base model.
6.740547
6.228312
1.082243
# NB: The existence of the _binary property implies that it is up to date, methods that # invalidate it will erase the property try: binary = self._binary if binary is not None: return binary except AttributeError: pass if self.vartype is Vartype.BINARY: self._binary = binary = self else: self._counterpart = self._binary = binary = self.change_vartype(Vartype.BINARY, inplace=False) # we also want to go ahead and set binary.spin to refer back to self binary._spin = self return binary
def binary(self)
:class:`.BinaryQuadraticModel`: An instance of the QUBO model subclass of the :class:`.BinaryQuadraticModel` superclass, corresponding to a binary quadratic model with binary variables. Enables access to biases for the binary-valued binary quadratic model regardless of the :class:`vartype` set when the model was created. If the model was created with the :attr:`.spin` vartype, the QUBO model subclass is instantiated upon the first use of the :attr:`.binary` property and used in any subsequent reads. Examples: This example creates an Ising model and uses the :attr:`.binary` property to instantiate the corresponding QUBO model. >>> import dimod ... >>> bqm_spin = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN) >>> bqm_qubo = bqm_spin.binary >>> bqm_qubo # doctest: +SKIP BinaryQuadraticModel({0: -1.0, 1: -1.0}, {(0, 1): 2.0}, 0.0, Vartype.BINARY) >>> bqm_qubo.binary is bqm_qubo True Note: Methods like :meth:`.add_variable`, :meth:`.add_variables_from`, :meth:`.add_interaction`, etc. should only be used on the base model.
7.414647
6.549386
1.132113
# handle the case that a different vartype is provided if vartype is not None and vartype is not self.vartype: if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY: # convert from binary to spin bias /= 2 self.offset += bias elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN: # convert from spin to binary self.offset -= bias bias *= 2 else: raise ValueError("unknown vartype") # we used to do this using self.linear but working directly with _adj # is much faster _adj = self._adj if v in _adj: if v in _adj[v]: _adj[v][v] += bias else: _adj[v][v] = bias else: _adj[v] = {v: bias} try: self._counterpart.add_variable(v, bias, vartype=self.vartype) except AttributeError: pass
def add_variable(self, v, bias, vartype=None)
Add variable v and/or its bias to a binary quadratic model. Args: v (variable): The variable to add to the model. Can be any python object that is a valid dict key. bias (bias): Linear bias associated with v. If v is already in the model, this value is added to its current linear bias. Many methods and functions expect `bias` to be a number but this is not explicitly checked. vartype (:class:`.Vartype`, optional, default=None): Vartype of the given bias. If None, the vartype of the binary quadratic model is used. Valid values are :class:`.Vartype.SPIN` or :class:`.Vartype.BINARY`. Examples: This example creates an Ising model with two variables, adds a third, and adds to the linear biases of the initial two. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN) >>> len(bqm.linear) 2 >>> bqm.add_variable(2, 2.0, vartype=dimod.SPIN) # Add a new variable >>> bqm.add_variable(1, 0.33, vartype=dimod.SPIN) >>> bqm.add_variable(0, 0.33, vartype=dimod.BINARY) # Binary value is converted to spin value >>> len(bqm.linear) 3 >>> bqm.linear[1] 1.33
2.826842
2.748036
1.028677
if isinstance(linear, abc.Mapping): for v, bias in iteritems(linear): self.add_variable(v, bias, vartype=vartype) else: try: for v, bias in linear: self.add_variable(v, bias, vartype=vartype) except TypeError: raise TypeError("expected 'linear' to be a dict or an iterable of 2-tuples.")
def add_variables_from(self, linear, vartype=None)
Add variables and/or linear biases to a binary quadratic model. Args: linear (dict[variable, bias]/iterable[(variable, bias)]): A collection of variables and their linear biases to add to the model. If a dict, keys are variables in the binary quadratic model and values are biases. Alternatively, an iterable of (variable, bias) pairs. Variables can be any python object that is a valid dict key. Many methods and functions expect the biases to be numbers but this is not explicitly checked. If any variable already exists in the model, its bias is added to the variable's current linear bias. vartype (:class:`.Vartype`, optional, default=None): Vartype of the given bias. If None, the vartype of the binary quadratic model is used. Valid values are :class:`.Vartype.SPIN` or :class:`.Vartype.BINARY`. Examples: This example creates creates an empty Ising model, adds two variables, and subsequently adds to the bias of the one while adding a new, third, variable. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({}, {}, 0.0, dimod.SPIN) >>> len(bqm.linear) 0 >>> bqm.add_variables_from({'a': .5, 'b': -1.}) >>> 'b' in bqm True >>> bqm.add_variables_from({'b': -1., 'c': 2.0}) >>> bqm.linear['b'] -2.0
2.557387
2.86397
0.892952
if u == v: raise ValueError("no self-loops allowed, therefore ({}, {}) is not an allowed interaction".format(u, v)) _adj = self._adj if vartype is not None and vartype is not self.vartype: if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY: # convert from binary to spin bias /= 4 self.add_offset(bias) self.add_variable(u, bias) self.add_variable(v, bias) elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN: # convert from spin to binary self.add_offset(bias) self.add_variable(u, -2 * bias) self.add_variable(v, -2 * bias) bias *= 4 else: raise ValueError("unknown vartype") else: # so that they exist. if u not in self: _adj[u] = {} if v not in self: _adj[v] = {} if u in _adj[v]: _adj[u][v] = _adj[v][u] = _adj[u][v] + bias else: _adj[u][v] = _adj[v][u] = bias try: self._counterpart.add_interaction(u, v, bias, vartype=self.vartype) except AttributeError: pass
def add_interaction(self, u, v, bias, vartype=None)
Add an interaction and/or quadratic bias to a binary quadratic model. Args: v (variable): One of the pair of variables to add to the model. Can be any python object that is a valid dict key. u (variable): One of the pair of variables to add to the model. Can be any python object that is a valid dict key. bias (bias): Quadratic bias associated with u, v. If u, v is already in the model, this value is added to the current quadratic bias. Many methods and functions expect `bias` to be a number but this is not explicitly checked. vartype (:class:`.Vartype`, optional, default=None): Vartype of the given bias. If None, the vartype of the binary quadratic model is used. Valid values are :class:`.Vartype.SPIN` or :class:`.Vartype.BINARY`. Examples: This example creates an Ising model with two variables, adds a third, adds to the bias of the initial interaction, and creates a new interaction. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN) >>> len(bqm.quadratic) 1 >>> bqm.add_interaction(0, 2, 2) # Add new variable 2 >>> bqm.add_interaction(0, 1, .25) >>> bqm.add_interaction(1, 2, .25, vartype=dimod.BINARY) # Binary value is converted to spin value >>> len(bqm.quadratic) 3 >>> bqm.quadratic[(0, 1)] 0.75
2.507573
2.64303
0.948749
if isinstance(quadratic, abc.Mapping): for (u, v), bias in iteritems(quadratic): self.add_interaction(u, v, bias, vartype=vartype) else: try: for u, v, bias in quadratic: self.add_interaction(u, v, bias, vartype=vartype) except TypeError: raise TypeError("expected 'quadratic' to be a dict or an iterable of 3-tuples.")
def add_interactions_from(self, quadratic, vartype=None)
Add interactions and/or quadratic biases to a binary quadratic model. Args: quadratic (dict[(variable, variable), bias]/iterable[(variable, variable, bias)]): A collection of variables that have an interaction and their quadratic bias to add to the model. If a dict, keys are 2-tuples of variables in the binary quadratic model and values are their corresponding bias. Alternatively, an iterable of 3-tuples. Each interaction in `quadratic` should be unique; that is, if `(u, v)` is a key, `(v, u)` should not be. Variables can be any python object that is a valid dict key. Many methods and functions expect the biases to be numbers but this is not explicitly checked. vartype (:class:`.Vartype`, optional, default=None): Vartype of the given bias. If None, the vartype of the binary quadratic model is used. Valid values are :class:`.Vartype.SPIN` or :class:`.Vartype.BINARY`. Examples: This example creates creates an empty Ising model, adds an interaction for two variables, adds to its bias while adding a new variable, then adds another interaction. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN) >>> bqm.add_interactions_from({('a', 'b'): -.5}) >>> bqm.quadratic[('a', 'b')] -0.5 >>> bqm.add_interactions_from({('a', 'b'): -.5, ('a', 'c'): 2}) >>> bqm.add_interactions_from({('b', 'c'): 2}, vartype=dimod.BINARY) # Binary value is converted to spin value >>> len(bqm.quadratic) 3 >>> bqm.quadratic[('a', 'b')] -1.0
2.231702
2.450882
0.910571
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
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. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({'a': 0.0, 'b': 1.0, 'c': 2.0}, ... {('a', 'b'): 0.25, ('a','c'): 0.5, ('b','c'): 0.75}, ... -0.5, dimod.SPIN) >>> bqm.remove_variable('a') >>> 'a' in bqm.linear False >>> ('b','c') in bqm.quadratic True
4.599473
4.222111
1.089378
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
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. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN) >>> bqm.remove_interaction('b', 'c') >>> ('b', 'c') in bqm.quadratic False >>> bqm.remove_interaction('a', 'c') # not an interaction, so ignored >>> len(bqm.quadratic) 1
5.123085
4.99189
1.026282
for u, v in interactions: self.remove_interaction(u, v)
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. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN) >>> bqm.remove_interactions_from([('b', 'c'), ('a', 'c')]) # ('a', 'c') is not an interaction, so ignored >>> len(bqm.quadratic) 1
4.761947
16.889858
0.281941
self.offset += offset try: self._counterpart.add_offset(offset) except AttributeError: pass
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. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN) >>> bqm.add_offset(1.0) >>> bqm.offset 0.5
6.97748
13.665574
0.510588
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
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. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 2.0}, {('a', 'b'): -1.0}, 1.0, dimod.SPIN) >>> bqm.scale(0.5) >>> bqm.linear['a'] -1.0 >>> bqm.quadratic[('a', 'b')] -0.5 >>> bqm.offset 0.5
1.783
1.821931
0.978632
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 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) 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 self.linear.items() if k not in ignored_variables]) quad_min, quad_max = min_and_max([v for (a, b), v in self.quadratic.items() if ((a, b) not in ignored_interactions and (b, a) not in 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: self.scale(1 / inv_scalar, ignored_variables=ignored_variables, ignored_interactions=ignored_interactions, ignore_offset=ignore_offset)
def normalize(self, bias_range=1, quadratic_range=None, ignored_variables=None, ignored_interactions=None, ignore_offset=False)
Normalizes the biases of the binary quadratic model such that they fall in the provided range(s), and adjusts the offset appropriately. If `quadratic_range` is provided, then `bias_range` will be treated as the range for the linear biases and `quadratic_range` will be used for the range of the quadratic biases. Args: 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. Examples: >>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 1.5}, ... {('a', 'b'): -1.0}, ... 1.0, dimod.SPIN) >>> max(abs(bias) for bias in bqm.linear.values()) 2.0 >>> max(abs(bias) for bias in bqm.quadratic.values()) 1.0 >>> bqm.normalize([-1.0, 1.0]) >>> max(abs(bias) for bias in bqm.linear.values()) 1.0 >>> max(abs(bias) for bias in bqm.quadratic.values()) 0.5
1.912195
1.848851
1.034261
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)
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. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0.}, {('a', 'b'): -1}, 0.0, dimod.SPIN) >>> bqm.fix_variable('a', -1) >>> bqm.offset 0.5 >>> bqm.linear['b'] 1.0 >>> 'a' in bqm False
3.92488
3.807022
1.030958
for v, val in fixed.items(): self.fix_variable(v, val)
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: >>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN) >>> bqm.fix_variables({'a': -1, 'b': +1})
4.956192
9.074707
0.546154
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
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. >>> import dimod ... >>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN) >>> bqm.flip_variable(1) >>> bqm.linear[1], bqm.linear[2], bqm.quadratic[(1, 2)] (-1.0, 2, -0.5)
2.168379
2.169607
0.999434
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)
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. >>> import dimod ... >>> linear1 = {1: 1, 2: 2} >>> quadratic1 = {(1, 2): 12} >>> bqm1 = dimod.BinaryQuadraticModel(linear1, quadratic1, 0.5, dimod.SPIN) >>> bqm1.info = {'BQM number 1'} >>> linear2 = {2: 0.25, 3: 0.35} >>> quadratic2 = {(2, 3): 23} >>> bqm2 = dimod.BinaryQuadraticModel(linear2, quadratic2, 0.75, dimod.SPIN) >>> bqm2.info = {'BQM number 2'} >>> bqm1.update(bqm2) >>> bqm1.offset 1.25 >>> 'BQM number 2' in bqm1.info False >>> bqm1.update(bqm2, ignore_info=False) >>> 'BQM number 2' in bqm1.info True >>> bqm1.offset 2.0
2.118931
2.615862
0.810031
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)
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. >>> import dimod ... >>> linear = {1: 1, 2: 2, 3: 3, 4: 4} >>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14, ... (2, 3): 23, (2, 4): 24, ... (3, 4): 34} >>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0.5, dimod.SPIN) >>> bqm.contract_variables(2, 3) >>> 3 in bqm.linear False >>> bqm.quadratic[(1, 2)] 25
3.129669
3.017884
1.037041
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)
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. >>> import dimod ... >>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN) >>> model.relabel_variables({0: 'a'}) # doctest: +SKIP 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. >>> import dimod ... >>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN) >>> new_model = model.relabel_variables({0: 'a', 1: 'b'}, inplace=False) # doctest: +SKIP >>> new_model.quadratic # doctest: +SKIP {('a', 'b'): -1}
3.305525
3.044308
1.085805
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
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. >>> import dimod ... >>> bqm_spin = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN) >>> bqm_qubo = bqm_spin.change_vartype('BINARY', inplace=False) >>> bqm_spin.offset, bqm_spin.vartype (0.5, <Vartype.SPIN: frozenset({1, -1})>) >>> bqm_qubo.offset, bqm_qubo.vartype (-2.0, <Vartype.BINARY: frozenset({0, 1})>)
2.612703
2.409536
1.084318
# 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
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.
3.016407
2.938989
1.026342
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
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.
2.625826
2.594205
1.012189
# 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)
def copy(self)
Create a copy of a BinaryQuadraticModel. Returns: :class:`.BinaryQuadraticModel` Examples: >>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN) >>> bqm2 = bqm.copy()
11.703104
11.526476
1.015324
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
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. >>> import dimod >>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 1}, {(1, 2): 1}, 0.5, dimod.SPIN) >>> bqm.energy({1: -1, 2: -1}) -0.5 >>> bqm.energy({1: 1, 2: 1}) 3.5
6.433684
5.705369
1.127654
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)
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.
4.677588
5.132651
0.91134
import dimod.serialization.coo as coo if fp is None: return coo.dumps(self, vartype_header) else: coo.dump(self, fp, vartype_header)
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. >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN) >>> with open('tmp.ising', 'w') as file: # doctest: +SKIP ... bqm.to_coo(file) This is an example of writing a binary quadratic model to a COOrdinate-format string. >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN) >>> bqm.to_coo() # doctest: +SKIP 0 0 -1.000000 0 1 -1.000000 1 1 1.000000
2.97892
3.594123
0.828831
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)
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. >>> import dimod >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.BINARY) >>> with open('tmp.qubo', 'w') as file: # doctest: +SKIP ... bqm.to_coo(file) >>> with open('tmp.qubo', 'r') as file: # doctest: +SKIP ... new_bqm = dimod.BinaryQuadraticModel.from_coo(file, dimod.BINARY) >>> any(new_bqm) # doctest: +SKIP True
3.031063
3.661472
0.827826
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
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 >>> import dimod >>> import json ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> s = json.dumps(bqm.to_serializable()) >>> new_bqm = dimod.BinaryQuadraticModel.from_serializable(json.loads(s)) See also: :meth:`~.BinaryQuadraticModel.to_serializable` :func:`json.loads`, :func:`json.load` JSON deserialization functions
3.216671
3.225291
0.997328
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
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". >>> import networkx as nx >>> bqm = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5}, ... {(0, 1): .5, (1, 2): 1.5}, ... 1.4, ... dimod.SPIN) >>> BQM = bqm.to_networkx_graph() >>> BQM[0][1]['bias'] 0.5 >>> BQM.node[0]['bias'] 1 >>> BQM_w = bqm.to_networkx_graph(edge_attribute_name='weight') >>> BQM_w[0][1]['weight'] 0.5
2.625476
2.406676
1.090914
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)
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: >>> import networkx as nx ... >>> G = nx.Graph() >>> G.add_node('a', bias=.5) >>> G.add_edge('a', 'b', bias=-1) >>> bqm = dimod.BinaryQuadraticModel.from_networkx_graph(G, 'SPIN') >>> bqm.adj['a']['b'] -1
2.607971
3.033738
0.859656
# cast to a dict return dict(self.spin.linear), dict(self.spin.quadratic), self.spin.offset
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. >>> import dimod >>> model = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5}, ... {(0, 1): .5, (1, 2): 1.5}, ... 1.4, ... dimod.SPIN) >>> model.to_ising() # doctest: +SKIP ({0: 1, 1: -1, 2: 0.5}, {(0, 1): 0.5, (1, 2): 1.5}, 1.4)
12.248668
13.767109
0.889705
if isinstance(h, abc.Sequence): h = dict(enumerate(h)) return cls(h, J, offset, Vartype.SPIN)
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 form `{v: bias, ...}` where v is a spin-valued variable and `bias` 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. >>> import dimod >>> h = {1: 1, 2: 2, 3: 3, 4: 4} >>> J = {(1, 2): 12, (1, 3): 13, (1, 4): 14, ... (2, 3): 23, (2, 4): 24, ... (3, 4): 34} >>> model = dimod.BinaryQuadraticModel.from_ising(h, J, offset = 0.0) >>> model # doctest: +SKIP 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)
5.25548
8.82514
0.595512
qubo = dict(self.binary.quadratic) qubo.update(((v, v), bias) for v, bias in iteritems(self.binary.linear)) return qubo, self.binary.offset
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. >>> import dimod >>> model = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5}, ... {(0, 1): .5, (1, 2): 1.5}, ... 1.4, ... dimod.SPIN) >>> model.to_qubo() # doctest: +SKIP ({(0, 0): 1.0, (0, 1): 2.0, (1, 1): -6.0, (1, 2): 6.0, (2, 2): -2.0}, 2.9)
5.054
5.22394
0.967469
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)
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 (QUBO) problem. Should be a dict of the form `{(u, v): bias, ...}` 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. >>> import dimod >>> Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} >>> model = dimod.BinaryQuadraticModel.from_qubo(Q, offset = 0.0) >>> model.linear # doctest: +SKIP {0: -1, 1: -1} >>> model.vartype <Vartype.BINARY: frozenset({0, 1})>
2.619609
3.798105
0.689715
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
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'). >>> import dimod >>> import numpy as np ... >>> model = dimod.BinaryQuadraticModel({'a': 1, 'b': -1, 'c': .5}, ... {('a', 'b'): .5, ('b', 'c'): 1.5}, ... 1.4, ... dimod.BINARY) >>> model.to_numpy_matrix(variable_order=['d', 'c', 'b', 'a']) array([[ 0. , 0. , 0. , 0. ], [ 0. , 0.5, 1.5, 0. ], [ 0. , 0. , -1. , 0.5], [ 0. , 0. , 0. , 1. ]])
2.447825
2.366129
1.034527
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
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. >>> import dimod >>> import numpy as np >>> Q = np.array([[1, 0, 0, 10, 11], ... [0, 2, 0, 12, 13], ... [0, 0, 3, 14, 15], ... [0, 0, 0, 4, 0], ... [0, 0, 0, 0, 5]]).astype(np.float32) >>> model = dimod.BinaryQuadraticModel.from_numpy_matrix(Q, ... variable_order = ['a', 'b', 'c', 'd', 'e', 'f', 'g'], ... offset = 2.5, ... interactions = {('a', 'f')}) >>> model.linear # doctest: +SKIP {'a': 1.0, 'b': 2.0, 'c': 3.0, 'd': 4.0, 'e': 5.0, 'f': 0.0} >>> model.quadratic[('a', 'd')] 10.0 >>> model.quadratic[('a', 'f')] 0.0 >>> model.offset 2.5
2.191611
2.210897
0.991277
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)
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: >>> bqm = dimod.BinaryQuadraticModel({}, {(0, 1): .5, (3, 2): -1, (0, 3): 1.5}, 0.0, dimod.SPIN) >>> lin, (i, j, vals), off = bqm.to_numpy_vectors(sort_indices=True) >>> lin array([0., 0., 0., 0.]) >>> i array([0, 0, 2]) >>> j array([1, 3, 3]) >>> vals array([ 0.5, 1.5, -1. ])
2.344794
2.304714
1.01739
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)
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: >>> import dimod >>> import numpy as np ... >>> linear_vector = np.asarray([-1, 1]) >>> quadratic_vectors = (np.asarray([0]), np.asarray([1]), np.asarray([-1.0])) >>> bqm = dimod.BinaryQuadraticModel.from_numpy_vectors(linear_vector, quadratic_vectors, 0.0, dimod.SPIN) >>> print(bqm.quadratic) {(0, 1): -1.0}
2.497309
2.497252
1.000023
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)
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. >>> import dimod >>> model = dimod.BinaryQuadraticModel({'a': 1.1, 'b': -1., 'c': .5}, ... {('a', 'b'): .5, ('b', 'c'): 1.5}, ... 1.4, ... dimod.BINARY) >>> model.to_pandas_dataframe() # doctest: +SKIP a b c a 1.1 0.5 0.0 b 0.0 -1.0 1.5 c 0.0 0.0 0.5
3.928429
4.013398
0.978829
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
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. >>> import dimod >>> import pandas as pd >>> pd_qubo = pd.DataFrame(data={0: [-1, 0], 1: [2, -1]}) >>> pd_qubo 0 1 0 -1 2 1 0 -1 >>> model = dimod.BinaryQuadraticModel.from_pandas_dataframe(pd_qubo, ... offset = 2.5, ... interactions = {(0,2), (1,2)}) >>> model.linear # doctest: +SKIP {0: -1, 1: -1.0, 2: 0.0} >>> model.quadratic # doctest: +SKIP {(0, 1): 2, (0, 2): 0.0, (1, 2): 0.0} >>> model.offset 2.5 >>> model.vartype <Vartype.BINARY: frozenset({0, 1})>
2.45648
3.386976
0.725273
# solve the problem on the child system child = self.child bqm_copy = bqm.copy() if fixed_variables is None: fixed_variables = {} bqm_copy.fix_variables(fixed_variables) sampleset = child.sample(bqm_copy, **parameters) if len(sampleset): return sampleset.append_variables(fixed_variables) elif fixed_variables: return type(sampleset).from_samples_bqm(fixed_variables, bqm=bqm) else: # no fixed variables and sampleset is empty return sampleset
def sample(self, bqm, fixed_variables=None, **parameters)
Sample from the provided binary quadratic model. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. fixed_variables (dict): A dictionary of variable assignments. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :obj:`dimod.SampleSet`
3.390697
3.515661
0.964455
# 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
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]): Sample for a binary quadratic model as a dict of form {v: spin, ...}, where keys are variables of the model and values are spins (either -1 or 1). h (dict[variable, bias]): Linear biases as a dict of the form {v: bias, ...}, where keys are variables of the model and values are biases. J (dict[(variable, variable), bias]): Quadratic biases as a dict of the form {(u, v): bias, ...}, where keys 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. >>> import dimod >>> sample = {1: -1, 2: -1} >>> h = {1: 1, 2: 1} >>> J = {(1, 2): 1} >>> dimod.ising_energy(sample, h, J, 0.5) -0.5 References ---------- `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_
2.899018
3.698531
0.78383
for v0, v1 in Q: offset += sample[v0] * sample[v1] * Q[(v0, v1)] return offset
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]): Sample for a binary quadratic model as a dict of form {v: bin, ...}, where keys are variables of the model and values are binary (either 0 or 1). Q (dict[(variable, variable), coefficient]): QUBO coefficients in a dict of form {(u, v): coefficient, ...}, where keys 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. >>> import dimod >>> sample = {1: 0, 2: 0} >>> Q = {(1, 1): 1, (2, 2): 1, (1, 2): 1} >>> dimod.qubo_energy(sample, Q, 0.5) 0.5 References ---------- `QUBO model on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_
3.600541
10.444696
0.344724
# 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
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]): Linear biases as a dict of the form {v: bias, ...}, where keys are variables of the model and values are biases. J (dict[(variable, variable), bias]): Quadratic biases as a dict of the form {(u, v): bias, ...}, where keys 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. >>> import dimod >>> h = {1: 1, 2: 1} >>> J = {(1, 2): 1} >>> dimod.ising_to_qubo(h, J, 0.5) # doctest: +SKIP ({(1, 1): 0.0, (1, 2): 4.0, (2, 2): 0.0}, -0.5)
3.235246
3.988032
0.811239
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
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]): QUBO coefficients in a dict of form {(u, v): coefficient, ...}, where keys 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. >>> import dimod >>> Q = {(1, 1): 1, (2, 2): 1, (1, 2): 1} >>> dimod.qubo_to_ising(Q, 0.5) # doctest: +SKIP ({1: 0.75, 2: 0.75}, {(1, 2): 0.25}, 1.75)
1.95767
2.14102
0.914363