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 ...
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,...
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 ...
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) ...
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(by...
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? ...
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 i...
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 = sel...
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.m...
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:]...
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 n...
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...
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 applyin...
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...
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_thre...
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 rep...
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) ...
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()) ...
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. ...
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 collecti...
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...
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 = ...
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 si...
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 ...
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 ...
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))): ...
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, ...
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_...
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"...
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: ...
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...
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...
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 (optio...
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 wi...
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. ...
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 # travers...
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 (bo...
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 (ValueErr...
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`...
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 ...
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) fo...
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 t...
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") variable...
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,...
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 N...
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...
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: ...
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 ...
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 = dimo...
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` ...
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)):...
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 lowe...
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, ...], ...} ...
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 ValueEr...
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...
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)...
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):...
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: ...
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_va...
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, ...
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`): ...
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_hi...
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 offs...
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(*_i...
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 Chim...
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] ...
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....
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:`...
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 ...
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:`varty...
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 ...
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,...
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 TypeErro...
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 ...
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: ...
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 a...
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...
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, ...
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 ...
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. ...
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'): ...
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...
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 inte...
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 t...
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(ignor...
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 va...
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: ...
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...
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 *...
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 ...
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) >>> b...
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] *= ...
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 inve...
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 ...
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 ...
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...
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 Va...
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, ...
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.quadra...
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`,...
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. * bia...
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 * bi...
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] f...
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 ...
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=dty...
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 t...
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 o...
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 ...
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...
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 >>> imp...
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, ...
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. ...
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.node...
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 inp...
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...
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 tr...
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...
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` ...
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 iterit...
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. ...
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...
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 p...
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, dt...
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-...
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...
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). offse...
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, ...
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: ...
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: ...
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; ...
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): ...
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...
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, ...
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 uncons...
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 # fina...
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. ...
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:...
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). R...
1.95767
2.14102
0.914363