How to use the dimod.BinaryQuadraticModel.from_coo 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 / tests / test_binary_quadratic_model.py View on Github external
def test_coo_functional_string_BINARY(self):

        bqm = dimod.BinaryQuadraticModel({0: 1.}, {(0, 1): 2, (2, 3): .4}, 0.0, dimod.BINARY)

        s = bqm.to_coo()
        new_bqm = dimod.BinaryQuadraticModel.from_coo(s, dimod.BINARY)

        self.assertEqual(bqm, new_bqm)
github dwavesystems / dimod / tests / test_binary_quadratic_model.py View on Github external
def test_from_coo_file(self):
        filepath = path.join(path.dirname(path.abspath(__file__)), 'data', 'coo_qubo.qubo')

        with open(filepath, 'r') as fp:
            bqm = dimod.BinaryQuadraticModel.from_coo(fp, dimod.BINARY)

        self.assertEqual(bqm, dimod.BinaryQuadraticModel.from_qubo({(0, 0): -1, (1, 1): -1, (2, 2): -1, (3, 3): -1}))
github dwavesystems / dwave-cloud-client / dwave / cloud / cli.py View on Github external
click.echo(("Preparing to upload a problem from {!r} "
                "in {!r} format.").format(input_file.name, format))

    if format == 'coo':
        click.echo("Transcoding 'coo' to 'bq-zlib'.")

        try:
            import dimod
        except ImportError: # pragma: no cover
            raise RuntimeError("Can't decode 'coo' format without dimod. "
                               "Re-install the library with 'bqm' support.")

        # note: `BQM.from_coo` doesn't support files opened in binary (yet);
        # fallback to reopen for now
        with open(input_file.name, 'rt') as fp:
            bqm = dimod.BinaryQuadraticModel.from_coo(fp)
            problem = encode_problem_as_bq(bqm, compress=True)['data']

    elif format == 'bq-zlib':
        problem = input_file

    click.echo("Uploading...")

    try:
        future = client.upload_problem_encoded(
            problem=problem, problem_id=problem_id)
        remote_problem_id = future.result()
    except Exception as e:
        click.echo(e)
        return 2

    click.echo("Upload done. Problem ID: {!r}".format(remote_problem_id))
github dwavesystems / dwave-hybrid / examples / parallel-tempering-qpu.py View on Github external
import random

import numpy as np

import neal
import dimod
import hybrid

from hybrid.reference.pt import FixedTemperatureSampler
from hybrid.reference.pt import SwapReplicasDownsweep


# load a problem
problem = sys.argv[1]
with open(problem) as fp:
    bqm = dimod.BinaryQuadraticModel.from_coo(fp)

print("BQM: {} nodes, {} edges, {:.2f} density".format(
    len(bqm), len(bqm.quadratic), hybrid.bqm_density(bqm)))


# PT workflow: temperature/beta is a property of a branch

n_sweeps = 10000
n_replicas = 10
n_iterations = 10

# replicas are initialized with random samples
state = hybrid.State.from_problem(bqm)
replicas = hybrid.States(*[state.updated() for _ in range(n_replicas)])

# get a reasonable beta range
github dwavesystems / dwave-hybrid / examples / hybrid-sampler.py View on Github external
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

import dimod
import hybrid


# load a problem
problem = sys.argv[1]
with open(problem) as fp:
    bqm = dimod.BinaryQuadraticModel.from_coo(fp)


# define the workflow
workflow = hybrid.Loop(
    hybrid.Race(
        hybrid.InterruptableTabuSampler(),
        hybrid.EnergyImpactDecomposer(size=50, rolling=True, traversal='bfs')
        | hybrid.QPUSubproblemAutoEmbeddingSampler()
        | hybrid.SplatComposer()) | hybrid.ArgMin(), convergence=3)


# create a dimod sampler that runs the workflow and sample
result = hybrid.HybridSampler(workflow).sample(bqm)

# show results
print("Solution: sample={.first}".format(result))
github dwavesystems / dwave-hybrid / perf / perf.py View on Github external
with hybrid.tictoc() as timer:
            samples = sampler(bqm)

        return samples, timer

    # reuse the cloud client
    qpu = DWaveSampler()

    for path in problems:
        problem = os.path.splitext(os.path.basename(path))[0]

        target_energy = targets.get(problem)
        results[problem] = OrderedDict()

        with open(path) as fp:
            bqm = dimod.BinaryQuadraticModel.from_coo(fp)

        for runner, solvers in [(workflow_runner, workflows),
                                (sampler_runner, samplers)]:
            for solver_name, factory in solvers:
                run_results = []

                for run in range(n_runs):
                    case = '{!r} with {!r}, run={!r}, target={!r}'.format(
                        problem, solver_name, run, target_energy)

                    try:
                        samples, timer = runner(bqm, factory, qpu=qpu,
                                                energy_threshold=target_energy)

                    except Exception as exc:
                        print("FAILED {case}: {exc!r}".format(**locals()))
github dwavesystems / dwave-hybrid / examples / qbsolv-like-alt.py View on Github external
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

import dimod
import hybrid


# load a problem
problem = sys.argv[1]
with open(problem) as fp:
    bqm = dimod.BinaryQuadraticModel.from_coo(fp)


# define a qbsolv-like workflow
def merge_substates(_, substates):
    a, b = substates
    return a.updated(subsamples=hybrid.hstack_samplesets(a.subsamples, b.subsamples))

subproblems = hybrid.Unwind(
    hybrid.EnergyImpactDecomposer(size=50, rolling_history=0.15)
)

qpu = hybrid.Map(
    hybrid.QPUSubproblemAutoEmbeddingSampler()
) | hybrid.Reduce(
    hybrid.Lambda(merge_substates)
) | hybrid.SplatComposer()
github dwavesystems / dwave-hybrid / perf-kerberos.py View on Github external
def sampler_runner(bqm, sampler, energy_threshold=None, **kwargs):
        with tictoc() as timer:
            samples = sampler.sample(bqm, init_sample=lambda: min_sample(bqm),
                                     energy_threshold=energy_threshold)

        return samples, timer

    for problem in problems:
        results[problem] = OrderedDict()

        problem_nice_name = os.path.splitext(os.path.basename(problem))[0]
        target_energy = targets.get(problem_nice_name)

        with open(problem) as fp:
            bqm = dimod.BinaryQuadraticModel.from_coo(fp)

        for runner, solvers in [(workflow_runner, workflows), (sampler_runner, samplers)]:
            for name, factory in solvers:
                run_results = []

                for run in range(n_runs):
                    case = '{!r} with {!r}, run={!r}, target={!r}'.format(
                        problem, name, run, target_energy)

                    try:
                        samples, timer = runner(bqm, factory(),
                                                energy_threshold=target_energy)

                    except Exception as exc:
                        print("FAILED {case}: {exc!r}".format(**locals()))
                        run_results.append(dict(error=repr(exc)))