Skip to content

Commit

Permalink
fix: avoid flaky test behavior on macOS (#10) (#11)
Browse files Browse the repository at this point in the history
(cherry picked from commit 5a50591)

Co-authored-by: Max Rossmannek <oss@zurich.ibm.com>
  • Loading branch information
mergify[bot] and mrossinek authored Sep 13, 2024
1 parent 814481c commit e007dda
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions test/static/test_approximate.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"""Tests for the ``qiskit_addon_mpf.static.approximate`` module."""

import unittest
from typing import Any, ClassVar

import cvxpy as cp
import numpy as np
Expand All @@ -23,19 +24,25 @@
class TestApproximateCoeffs(unittest.TestCase):
"""Tests for the ``qiskit_addon_mpf.static.approximate`` module."""

CVXPY_SOLVER_SETTINGS: ClassVar[dict[str, Any]] = {
"warm_start": False,
"eps_abs": 1e-7,
"eps_rel": 1e-7,
}

def test_setup_approximate_model(self):
"""Tests the :meth:`.setup_approximate_model` method."""
trotter_steps = [1, 2, 4]
lse = setup_lse(trotter_steps, order=2, symmetric=True)
problem, coeffs = setup_approximate_model(lse)

with self.subTest("final cost"):
final_cost = problem.solve()
final_cost = problem.solve(**self.CVXPY_SOLVER_SETTINGS)
self.assertAlmostEqual(final_cost, 0)

with self.subTest("optimal coefficients"):
expected = np.array([0.02222225, -0.44444444, 1.42222216])
np.testing.assert_allclose(coeffs.value, expected, rtol=1e-5)
np.testing.assert_allclose(coeffs.value, expected, rtol=1e-4)

def test_setup_approximate_model_max_l1_norm(self):
"""Tests the :meth:`.setup_approximate_model` method with ``max_l1_norm``."""
Expand All @@ -44,12 +51,12 @@ def test_setup_approximate_model_max_l1_norm(self):
problem, coeffs = setup_approximate_model(lse, max_l1_norm=1.5)

with self.subTest("final cost"):
final_cost = problem.solve()
final_cost = problem.solve(**self.CVXPY_SOLVER_SETTINGS)
self.assertAlmostEqual(final_cost, 0.00035765)

with self.subTest("optimal coefficients"):
expected = np.array([-0.001143293, -0.2488567, 1.25])
np.testing.assert_allclose(coeffs.value, expected, rtol=1e-5)
np.testing.assert_allclose(coeffs.value, expected, rtol=1e-4)

def test_setup_approximate_model_params(self):
"""Tests the :meth:`.setup_approximate_model` method with parameters."""
Expand All @@ -60,12 +67,12 @@ def test_setup_approximate_model_params(self):
ks.value = [1, 2, 4]

with self.subTest("final cost"):
final_cost = problem.solve()
final_cost = problem.solve(**self.CVXPY_SOLVER_SETTINGS)
self.assertAlmostEqual(final_cost, 0)

with self.subTest("optimal coefficients"):
expected = np.array([0.02222225, -0.44444444, 1.42222216])
np.testing.assert_allclose(coeffs.value, expected, rtol=1e-5)
np.testing.assert_allclose(coeffs.value, expected, rtol=1e-4)


if __name__ == "__main__":
Expand Down

0 comments on commit e007dda

Please sign in to comment.