Skip to main content

BQM Usage Examples

Learn how to create and manipulate Binary Quadratic Models for quantum computing.

Creating BQMs

From Scratch

import dimod

# Method 1: Direct construction
bqm = dimod.BinaryQuadraticModel(
    linear={0: 1.0, 1: -1.0, 2: 0.5},
    quadratic={(0, 1): 0.5, (1, 2): -0.3},
    offset=0.0,
    vartype='BINARY'
)

From QUBO Matrix

import numpy as np

# Create QUBO matrix
Q = np.array([
    [1.0, 0.5, 0.0],
    [0.0, -1.0, -0.3],
    [0.0, 0.0, 0.5]
])

# Convert to BQM
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)

BQM Operations

Scaling for QPU

import dynex

# Scale BQM coefficients for QPU compatibility
scaled_bqm, scale_factor = dynex.scale_bqm_to_range(bqm, max_abs_coeff=9.0)

print(f"Original max coefficient: {max(abs(c) for c in bqm.linear.values())}")
print(f"Scaled max coefficient: {max(abs(c) for c in scaled_bqm.linear.values())}")
print(f"Scale factor: {scale_factor}")

BQM Analysis

# Analyze BQM properties
print(f"Number of variables: {len(bqm.variables)}")
print(f"Number of interactions: {len(bqm.quadratic)}")
print(f"Variable types: {bqm.vartype}")
print(f"Energy range: [{bqm.lower_bound}, {bqm.upper_bound}]")

Sampling Different BQM Types

SPIN vs BINARY

# BINARY variables (0, 1)
binary_bqm = dimod.BinaryQuadraticModel(
    {0: 1, 1: -1}, {(0, 1): 2}, 0.0, 'BINARY'
)

# SPIN variables (-1, +1)  
spin_bqm = dimod.BinaryQuadraticModel(
    {0: 1, 1: -1}, {(0, 1): 2}, 0.0, 'SPIN'
)

# Sample both
for name, bqm in [("BINARY", binary_bqm), ("SPIN", spin_bqm)]:
    model = dynex.BQM(bqm)
    sampler = dynex.DynexSampler(model)
    sampleset = sampler.sample(num_reads=10)
    
    print(f"{name} result: {sampleset.first.sample}")

Real-World Example: Max-Cut Problem

import networkx as nx

# Create a graph
G = nx.Graph()
G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)])

# Formulate as QUBO
Q = {}
for u, v in G.edges():
    Q[(u, u)] = Q.get((u, u), 0) + 1
    Q[(v, v)] = Q.get((v, v), 0) + 1  
    Q[(u, v)] = Q.get((u, v), 0) - 2

# Convert to BQM and solve
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
model = dynex.BQM(bqm)
sampler = dynex.DynexSampler(model)
sampleset = sampler.sample(num_reads=100)

# Interpret results
solution = sampleset.first.sample
partition_0 = [node for node, val in solution.items() if val == 0]
partition_1 = [node for node, val in solution.items() if val == 1]

print(f"Partition 0: {partition_0}")
print(f"Partition 1: {partition_1}")
print(f"Cut size: {-sampleset.first.energy}")

Next Steps