Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add constraint/objective construction from NumPy arrays #1308

Open
arcondello opened this issue Feb 1, 2023 · 3 comments
Open

Add constraint/objective construction from NumPy arrays #1308

arcondello opened this issue Feb 1, 2023 · 3 comments
Labels
enhancement New feature or request

Comments

@arcondello
Copy link
Member

Requested by @mhramani #1307 (review).

Something like

indices = [0, 1, 5]
biases = [1, 2, 3]
cqm.add_constraint((indices, biases), "==", 5)

which would be interpreted as a linear constraint $x_0 + 2x_1 + 3x_5 = 5$.

@arcondello arcondello added the enhancement New feature or request label Feb 1, 2023
@ACE07-Sev
Copy link

Like so?

from dimod import ConstrainedQuadraticModel, Binary, quicksum

cqm_test = ConstrainedQuadraticModel()
vars = [Binary(f"X{i}") for i in range(7)]

def add_constraint(cqm, vars, indices, biases, sense, rhs):
    if len(indices) != len(biases):
        raise ValueError('The indices and biases do not have same size.')
    constraint = quicksum(biases[i] * vars[indices[i]] for i in range(len(indices)))
    cqm.add_constraint(constraint, sense=sense, rhs=rhs, label='c')

add_constraint(cqm_test, vars, [0, 2, 5], [1, 2, 3], "==", 5)

print(cqm_test.constraints['c'].to_polystring())
>> X0 + 2*X2 + 3*X5 == 5.0

@arcondello
Copy link
Member Author

Yes, something like that. Though the performance benefits of such a thing would come from implementing it at the Cython level, likely as a sibling method to cyConstrainedQuadraticModel.add_constraint_from_iterable() and cyConstrainedQuadraticModel.add_constraint_from_model().

@ACE07-Sev
Copy link

Understood, I'll try to make a PR on this soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants