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

Conversion performance improvement #594

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions qiskit_optimization/problems/quadratic_expression.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2019, 2023.
# (C) Copyright IBM 2019, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand All @@ -14,6 +14,7 @@

from typing import List, Union, Dict, Tuple, Any

import sys
import numpy as np
from numpy import ndarray
from scipy.sparse import spmatrix, dok_matrix, tril, triu
Expand Down Expand Up @@ -105,15 +106,31 @@ def _coeffs_to_dok_matrix(
if isinstance(coefficients, (list, ndarray, spmatrix)):
coefficients = dok_matrix(coefficients)
elif isinstance(coefficients, dict):

# Check if the python version is at least 3.9.
# See pull request #594 for more details why we do this check.
new_update_rule = sys.version_info >= (3, 9)

n = self.quadratic_program.get_num_vars()
coeffs = dok_matrix((n, n))
for (i, j), value in coefficients.items():
if isinstance(i, str):
i = self.quadratic_program.variables_index[i]
if isinstance(j, str):
j = self.quadratic_program.variables_index[j]
coeffs[i, j] = value
coefficients = coeffs

if new_update_rule:
if i > j:
coeffs[j, i] += value
else:
coeffs[i, j] += value
else:
coeffs[i, j] = value

if new_update_rule:
return coeffs
else:
coefficients = coeffs
else:
raise QiskitOptimizationError(f"Unsupported format for coefficients: {coefficients}")
return self._triangle_matrix(coefficients)
Expand Down
34 changes: 33 additions & 1 deletion test/problems/test_quadratic_expression.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2020, 2023.
# (C) Copyright IBM 2020, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand Down Expand Up @@ -273,6 +273,38 @@ def test_str_repr(self):
self.assertEqual(str(expr), expected)
self.assertEqual(repr(expr), f"<QuadraticExpression: {expected[:DEFAULT_TRUNCATE]}...>")

def test_coeffs_to_dok_matrix(self):
"""test that the conversion from coefficients to a dok_matrix is correct"""
num_vars = 4
quadratic_program = QuadraticProgram()
for _ in range(num_vars):
quadratic_program.binary_var()

coefficients = {
(1, 1): 1,
(1, 2): 2,
(2, 1): 3,
(1, 3): 3,
(3, 1): 3,
(2, 2): 4,
(2, 3): 12,
(3, 3): 9,
}

quadratic = QuadraticExpression(quadratic_program, coefficients)

res = quadratic._coeffs_to_dok_matrix(coefficients)

expected = dok_matrix((num_vars, num_vars))
expected[1, 1] = 1
expected[1, 2] = 5
expected[1, 3] = 6
expected[2, 2] = 4
expected[2, 3] = 12
expected[3, 3] = 9

self.assertTrue(np.allclose(expected.todense(), res.todense()))


if __name__ == "__main__":
unittest.main()