dimod icon indicating copy to clipboard operation
dimod copied to clipboard

Add ConstrainedQuadraticModel.add_linear_constraints() method

Open arcondello opened this issue 2 years ago • 1 comments

Speeds up adding linear constraints to the CQM. We get about a 10x speedup.

import time

import dimod
import numpy as np

num_variables = 1_000
num_constraints = 5_000
pnz = .25  # probability that a bias is non-zero

rng = np.random.default_rng(42)

A = rng.uniform(size=(num_constraints, num_variables))
A[A > pnz] = 0
b = rng.uniform(size=num_constraints)

####################

t = time.perf_counter()

cqm = dimod.ConstrainedQuadraticModel()
cqm.add_variables("BINARY", num_variables)

ci = 0
for rhs, lhs in zip(A, b):
    cqm.add_constraint(((v, bias) for v, bias in enumerate(rhs) if bias), '==', lhs, label=ci)
    ci += 1

print(f"old: {time.perf_counter() - t}")

old = cqm

###################

t = time.perf_counter()

cqm = dimod.ConstrainedQuadraticModel()
cqm.add_variables("BINARY", num_variables)
cqm.add_linear_constraints(A, '==', b, constraint_labels=range(num_constraints))

print(f"new: {time.perf_counter() - t}")

Gives

old: 0.6515062270009366
new: 0.07133342499946593

arcondello avatar Jan 27 '23 23:01 arcondello

Codecov Report

Merging #1307 (cc6e1e7) into main (8952fe8) will decrease coverage by 0.01%. The diff coverage is 84.61%.

:mega: This organization is not using Codecov’s GitHub App Integration. We recommend you install it so Codecov can continue to function properly for your repositories. Learn more

@@            Coverage Diff             @@
##             main    #1307      +/-   ##
==========================================
- Coverage   91.70%   91.69%   -0.01%     
==========================================
  Files          94       94              
  Lines       10135    10147      +12     
==========================================
+ Hits         9294     9304      +10     
- Misses        841      843       +2     
Impacted Files Coverage Δ
dimod/constrained/constrained.py 92.88% <84.61%> (-0.20%) :arrow_down:

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more

codecov-commenter avatar Jan 27 '23 23:01 codecov-commenter