From a3f5f3febaa63f0eb6038d425c8968c26f6683e7 Mon Sep 17 00:00:00 2001 From: Dominic Hofer <6570912+dominichofer@users.noreply.github.com> Date: Thu, 20 Feb 2025 18:09:41 +0100 Subject: [PATCH 1/2] Fix projected_gradient_method --- src/deepcpp/algorithm.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/deepcpp/algorithm.cpp b/src/deepcpp/algorithm.cpp index 7051823..7e4722c 100644 --- a/src/deepcpp/algorithm.cpp +++ b/src/deepcpp/algorithm.cpp @@ -112,7 +112,7 @@ VectorXd projected_gradient_method( double tolerance) { double step_size = 1 / mat.norm(); - VectorXd x_old = projection(target); + VectorXd x_old = projection(initial_guess); for (int i = 0; i < max_iterations; ++i) { VectorXd x_new = projection(x_old - step_size * (mat * x_old - target)); From 0376868d809014a5873d3153313130812b45504f Mon Sep 17 00:00:00 2001 From: Dominic Hofer <6570912+dominichofer@users.noreply.github.com> Date: Thu, 6 Mar 2025 23:50:24 +0100 Subject: [PATCH 2/2] Fix projected_gradient_method testgit --- tests/deepc/test_math.py | 13 ++++++++++++- tests/deepcpp/test_algorithm.cpp | 4 ++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/tests/deepc/test_math.py b/tests/deepc/test_math.py index 460ace1..a42a4f9 100644 --- a/tests/deepc/test_math.py +++ b/tests/deepc/test_math.py @@ -1,6 +1,6 @@ import unittest import numpy as np -from deepc.math import left_pseudoinverse, right_pseudoinverse, hankel_matrix +from deepc.math import left_pseudoinverse, right_pseudoinverse, hankel_matrix, projected_gradient_method class TestLeftPseudoinverse(unittest.TestCase): @@ -76,6 +76,17 @@ def test_size_3_and_2_rows(self): def test_size_3_and_3_rows(self): np.testing.assert_array_equal(hankel_matrix(3, [(1, 2), (3, 4), (5, 6)]), [[1], [2], [3], [4], [5], [6]]) +class TestProjectedGradientMethod(unittest.TestCase): + def test_1x1(self): + mat = np.array([[1, 0], [0, 1]]) + x_ini = np.array([1, 1]) + target = np.array([0, 0]) + def constrain(x): + return x + + res = projected_gradient_method(mat, x_ini, target, constrain) + + np.testing.assert_array_almost_equal(res, np.array([0, 0]), decimal=5) if __name__ == "__main__": unittest.main() diff --git a/tests/deepcpp/test_algorithm.cpp b/tests/deepcpp/test_algorithm.cpp index 23f19ec..3800bc4 100644 --- a/tests/deepcpp/test_algorithm.cpp +++ b/tests/deepcpp/test_algorithm.cpp @@ -171,7 +171,7 @@ TEST(HankelMatrix_2D_data, Size_3_and_3_row) EXPECT_EQ(res, expected); } -TEST(Algorithm, ProjectedGradientMethod) +TEST(Algorithm, projected_gradient_method) { auto mat = Matrix({1, 0}, {0, 1}); auto initial_guess = Vector(1, 1); @@ -180,5 +180,5 @@ TEST(Algorithm, ProjectedGradientMethod) auto res = projected_gradient_method(mat, initial_guess, target, projection); - EXPECT_EQ(res, Vector(0, 0)); + EXPECT_LE(res.norm(), 1e-6); }