How to use the dimod.binary_quadratic_model.BinaryQuadraticModel function in dimod

To help you get started, we’ve selected a few dimod examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dwavesystems / dimod / dimod / serialization / coo.py View on Github external
def loads(s, cls=BinaryQuadraticModel, vartype=None):
    """Load a COOrdinate formatted binary quadratic model from a string."""
    return load(s.split('\n'), cls=cls, vartype=vartype)
github dwavesystems / dimod / dimod / serialization / bson.py View on Github external
def bqm_bson_decoder(doc, cls=BinaryQuadraticModel):
    lin = np.frombuffer(doc["linear"], dtype=np.float32)
    num_variables = len(lin)
    vals = np.frombuffer(doc["quadratic_vals"], dtype=np.float32)
    index_dtype = doc["index_dtype"]
    if doc["as_complete"]:
        i, j = zip(*itertools.combinations(range(num_variables), 2))
    else:
        i = np.frombuffer(doc["quadratic_head"], dtype=index_dtype)
        j = np.frombuffer(doc["quadratic_tail"], dtype=index_dtype)

    off = doc["offset"]

    return cls.from_numpy_vectors(lin, (i, j, vals), off,
                                  str(doc["variable_type"]),
                                  variable_order=doc["variable_order"])
github dwavesystems / dimod / dimod / higherorder / utils.py View on Github external
Examples:

        >>> poly = {(0,): -1, (1,): 1, (2,): 1.5, (0, 1): -1, (0, 1, 2): -2}
        >>> bqm = dimod.make_quadratic(poly, 5.0, dimod.SPIN)

    """
    if vartype is None:
        if bqm is None:
            raise ValueError("one of vartype or bqm must be provided")
        else:
            vartype = bqm.vartype
    else:
        vartype = as_vartype(vartype)  # handle other vartype inputs
        if bqm is None:
            bqm = BinaryQuadraticModel.empty(vartype)
        else:
            bqm = bqm.change_vartype(vartype, inplace=False)

    bqm.info['reduction'] = {}

    # we want to be able to mutate the polynomial so copy. We treat this as a
    # dict but by using BinaryPolynomial we also get automatic handling of
    # square terms
    poly = BinaryPolynomial(poly, vartype=bqm.vartype)
    variables = set().union(*poly)

    while any(len(term) > 2 for term in poly):
        # determine which pair of variables appear most often
        paircounter = Counter()
        for term in poly:
            if len(term) <= 2:
github dwavesystems / dimod / dimod / serialization / json.py View on Github external
def default(self, obj):
        if isinstance(obj, (SampleSet, BinaryQuadraticModel)):
            return obj.to_serializable()

        return json.JSONEncoder.default(self, obj)
github dwavesystems / dimod / dimod / binary_quadratic_model_convert.py View on Github external
import numpy as np

    if mat.ndim != 2:
        raise ValueError("expected input mat to be a square matrix")  # pragma: no cover

    num_row, num_col = mat.shape
    if num_col != num_row:
        raise ValueError("expected input mat to be a square matrix")  # pragma: no cover

    if variable_order is None:
        variable_order = list(range(num_row))

    if interactions is None:
        interactions = []

    bqm = BinaryQuadraticModel({}, {}, 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
github dwavesystems / dimod / dimod / serialization / coo.py View on Github external
def load(fp, cls=BinaryQuadraticModel, vartype=None):
    """Load a COOrdinate formatted binary quadratic model from a file."""
    pattern = re.compile(_LINE_REGEX)
    vartype_pattern = re.compile(_VARTYPE_HEADER_REGEX)

    triplets = []
    for line in fp:
        triplets.extend(pattern.findall(line))

        vt = vartype_pattern.findall(line)
        if vt:
            if vartype is None:
                vartype = vt[0]
            else:
                if isinstance(vartype, str):
                    vartype = Vartype[vartype]
                else:
github dwavesystems / dimod / dimod / higherorder / utils.py View on Github external
def _spin_product(variables):
    """A BQM with a gap of 1 that represents the product of two spin variables.

    Note that spin-product requires an auxiliary variable.

    Args:
        variables (list):
            multiplier, multiplicand, product, aux

    Returns:
        :obj:`.BinaryQuadraticModel`

    """
    multiplier, multiplicand, product, aux = variables

    return BinaryQuadraticModel({multiplier: -.5,
                                 multiplicand: -.5,
                                 product: -.5,
                                 aux: -1.},
                                {(multiplier, multiplicand): .5,
                                 (multiplier, product): .5,
                                 (multiplier, aux): 1.,
                                 (multiplicand, product): .5,
                                 (multiplicand, aux): 1.,
                                 (product, aux): 1.},
                                2.,
                                Vartype.SPIN)
github dwavesystems / dimod / dimod / binary_quadratic_model_convert.py View on Github external
offset (optional, default=0.0):
            The constant offset applied to the model.

    Returns:
        :class:`.BinaryQuadraticModel`

    """
    linear = {}
    quadratic = {}
    for (u, v), bias in iteritems(Q):
        if u == v:
            linear[u] = bias
        else:
            quadratic[(u, v)] = bias

    return BinaryQuadraticModel(linear, quadratic, offset, Vartype.BINARY)
github dwavesystems / dimod / dimod / generators / chimera.py View on Github external
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):
github dwavesystems / dimod / dimod / core / sampler.py View on Github external
biases where the indices are the variable labels.

            J (dict[(variable, variable), bias]):
                Quadratic biases of the Ising problem.

            **kwargs:
                See the implemented sampling for additional keyword definitions.

        Returns:
            :obj:`.SampleSet`

        See also:
            :meth:`.sample`, :meth:`.sample_qubo`

        """
        bqm = BinaryQuadraticModel.from_ising(h, J)
        return self.sample(bqm, **parameters)