-
Notifications
You must be signed in to change notification settings - Fork 15
Use example scripts as tests. #277
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
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
3e60373
Initialize the example module.
paquiteau 5db5d3b
do not export the assert statements.
paquiteau c36efcb
add matplotlib as requirement.
paquiteau 04f9d1f
add support for sphinx-gallery
paquiteau d772cd1
Update modopt/examples/README.rst
paquiteau 482ba33
Update modopt/examples/__init__.py
paquiteau 8e76b65
Update modopt/examples/conftest.py
paquiteau 1866080
Update modopt/examples/example_lasso_forward_backward.py
paquiteau 5ce9243
Update modopt/examples/example_lasso_forward_backward.py
paquiteau c3f884f
ignore auto_example folder
paquiteau 22e782e
doc formatting.
paquiteau 93dbb09
add pogm and basic comparison.
paquiteau 63fee5c
Merge remote-tracking branch 'github_paquiteau/example2test' into exa…
paquiteau 8ffcf9d
Merge remote-tracking branch 'github_CEA-COSMIC/develop' into example…
paquiteau a7d5a8e
fix: add matplotlib for the plotting in examples scripts.
paquiteau bb4d0bc
fix: add matplotlib for basic ci too.
paquiteau c3b35f8
ci: run pytest with xdist for faster testing
paquiteau File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,3 +6,4 @@ numpydoc==1.1.0 | |
| sphinx==4.3.1 | ||
| sphinxcontrib-bibtex==2.4.1 | ||
| sphinxawesome-theme==3.2.1 | ||
| sphinx-gallery==0.11.1 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,6 +25,7 @@ | |
|
|
||
| plugin_example | ||
| notebooks | ||
| auto_examples/index | ||
|
|
||
| .. toctree:: | ||
| :hidden: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| ======== | ||
| Examples | ||
| ======== | ||
|
|
||
| This is a collection of Python scripts demonstrating the use of ModOpt. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| """EXAMPLES. | ||
|
|
||
| This module contains documented examples that demonstrate the usage of various | ||
| ModOpt tools. | ||
|
|
||
| These examples also serve as integration tests for various methods. | ||
|
|
||
| :Author: Pierre-Antoine Comby | ||
|
|
||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| """TEST CONFIGURATION. | ||
|
|
||
| This module contains methods for configuring the testing of the example | ||
| scripts. | ||
|
|
||
| :Author: Pierre-Antoine Comby | ||
|
|
||
| Notes | ||
| ----- | ||
| Based on: | ||
| https://stackoverflow.com/questions/56807698/how-to-run-script-as-pytest-test | ||
|
|
||
| """ | ||
| from pathlib import Path | ||
| import runpy | ||
| import pytest | ||
|
|
||
| def pytest_collect_file(path, parent): | ||
| """Pytest hook. | ||
|
|
||
| Create a collector for the given path, or None if not relevant. | ||
| The new node needs to have the specified parent as parent. | ||
| """ | ||
| p = Path(path) | ||
| if p.suffix == '.py' and 'example' in p.name: | ||
| return Script.from_parent(parent, path=p, name=p.name) | ||
|
|
||
|
|
||
| class Script(pytest.File): | ||
| """Script files collected by pytest.""" | ||
|
|
||
| def collect(self): | ||
| """Collect the script as its own item.""" | ||
| yield ScriptItem.from_parent(self, name=self.name) | ||
|
|
||
| class ScriptItem(pytest.Item): | ||
| """Item script collected by pytest.""" | ||
|
|
||
| def runtest(self): | ||
| """Run the script as a test.""" | ||
| runpy.run_path(str(self.path)) | ||
|
|
||
| def repr_failure(self, excinfo): | ||
| """Return only the error traceback of the script.""" | ||
| excinfo.traceback = excinfo.traceback.cut(path=self.path) | ||
| return super().repr_failure(excinfo) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| # noqa: D205 | ||
| """ | ||
| Solving the LASSO Problem with the Forward Backward Algorithm. | ||
| ============================================================== | ||
|
|
||
| This an example to show how to solve an example LASSO Problem | ||
| using the Forward-Backward Algorithm. | ||
|
|
||
| In this example we are going to use: | ||
| - Modopt Operators (Linear, Gradient, Proximal) | ||
| - Modopt implementation of solvers | ||
| - Modopt Metric API. | ||
| TODO: add reference to LASSO paper. | ||
| """ | ||
|
|
||
| import numpy as np | ||
| import matplotlib.pyplot as plt | ||
|
|
||
| from modopt.opt.algorithms import ForwardBackward, POGM | ||
| from modopt.opt.cost import costObj | ||
| from modopt.opt.linear import LinearParent, Identity | ||
| from modopt.opt.gradient import GradBasic | ||
| from modopt.opt.proximity import SparseThreshold | ||
| from modopt.math.matrix import PowerMethod | ||
| from modopt.math.stats import mse | ||
|
|
||
| # %% | ||
| # Here we create a instance of the LASSO Problem | ||
|
|
||
| BETA_TRUE = np.array( | ||
| [3.0, 1.5, 0, 0, 2, 0, 0, 0] | ||
| ) # 8 original values from lLASSO Paper | ||
| DIM = len(BETA_TRUE) | ||
|
|
||
|
|
||
| rng = np.random.default_rng() | ||
| sigma_noise = 1 | ||
| obs = 20 | ||
| # create a measurement matrix with decaying covariance matrix. | ||
| cov = 0.4 ** abs((np.arange(DIM) * np.ones((DIM, DIM))).T - np.arange(DIM)) | ||
| x = rng.multivariate_normal(np.zeros(DIM), cov, obs) | ||
|
|
||
| y = x @ BETA_TRUE | ||
| y_noise = y + (sigma_noise * np.random.standard_normal(obs)) | ||
|
|
||
|
|
||
| # %% | ||
| # Next we create Operators for solving the problem. | ||
|
|
||
| # MatrixOperator could also work here. | ||
| lin_op = LinearParent(lambda b: x @ b, lambda bb: x.T @ bb) | ||
| grad_op = GradBasic(y_noise, op=lin_op.op, trans_op=lin_op.adj_op) | ||
|
|
||
| prox_op = SparseThreshold(Identity(), 1, thresh_type="soft") | ||
|
|
||
| # %% | ||
| # In order to get the best convergence rate, we first determine the Lipschitz constant of the gradient Operator | ||
| # | ||
|
|
||
| calc_lips = PowerMethod(grad_op.trans_op_op, 8, data_type="float32", auto_run=True) | ||
| lip = calc_lips.spec_rad | ||
| print("lipschitz constant:", lip) | ||
|
|
||
| # %% | ||
| # Solving using FISTA algorithm | ||
| # ----------------------------- | ||
| # | ||
| # TODO: Add description/Reference of FISTA. | ||
|
|
||
| cost_op_fista = costObj([grad_op, prox_op], verbose=False) | ||
|
|
||
| fb_fista = ForwardBackward( | ||
| np.zeros(8), | ||
| beta_param=1 / lip, | ||
| grad=grad_op, | ||
| prox=prox_op, | ||
| cost=cost_op_fista, | ||
| metric_call_period=1, | ||
| auto_iterate=False, # Just to give us the pleasure of doing things by ourself. | ||
| ) | ||
|
|
||
| fb_fista.iterate() | ||
|
|
||
| # %% | ||
| # After the run we can have a look at the results | ||
|
|
||
| print(fb_fista.x_final) | ||
| mse_fista = mse(fb_fista.x_final, BETA_TRUE) | ||
| plt.stem(fb_fista.x_final, label="estimation", linefmt="C0-") | ||
| plt.stem(BETA_TRUE, label="reference", linefmt="C1-") | ||
| plt.legend() | ||
| plt.title(f"FISTA Estimation MSE={mse_fista:.4f}") | ||
|
|
||
| # sphinx_gallery_start_ignore | ||
| assert mse(fb_fista.x_final, BETA_TRUE) < 1 | ||
| # sphinx_gallery_end_ignore | ||
|
|
||
|
|
||
| # %% | ||
| # Solving Using the POGM Algorithm | ||
| # -------------------------------- | ||
| # | ||
| # TODO: Add description/Reference to POGM. | ||
|
|
||
|
|
||
| cost_op_pogm = costObj([grad_op, prox_op], verbose=False) | ||
|
|
||
| fb_pogm = POGM( | ||
| np.zeros(8), | ||
| np.zeros(8), | ||
| np.zeros(8), | ||
| np.zeros(8), | ||
| beta_param=1 / lip, | ||
| grad=grad_op, | ||
| prox=prox_op, | ||
| cost=cost_op_pogm, | ||
| metric_call_period=1, | ||
| auto_iterate=False, # Just to give us the pleasure of doing things by ourself. | ||
| ) | ||
|
|
||
| fb_pogm.iterate() | ||
|
|
||
| # %% | ||
| # After the run we can have a look at the results | ||
|
|
||
| print(fb_pogm.x_final) | ||
| mse_pogm = mse(fb_pogm.x_final, BETA_TRUE) | ||
|
|
||
| plt.stem(fb_pogm.x_final, label="estimation", linefmt="C0-") | ||
| plt.stem(BETA_TRUE, label="reference", linefmt="C1-") | ||
| plt.legend() | ||
| plt.title(f"FISTA Estimation MSE={mse_pogm:.4f}") | ||
| # | ||
| # sphinx_gallery_start_ignore | ||
| assert mse(fb_pogm.x_final, BETA_TRUE) < 1 | ||
|
|
||
| # %% | ||
| # Comparing the Two algorithms | ||
| # ---------------------------- | ||
|
|
||
| plt.figure() | ||
| plt.semilogy(cost_op_fista._cost_list, label="FISTA convergence") | ||
| plt.semilogy(cost_op_pogm._cost_list, label="POGM convergence") | ||
| plt.xlabel("iterations") | ||
| plt.ylabel("Cost Function") | ||
| plt.legend() | ||
| plt.show() | ||
|
|
||
|
|
||
| # %% | ||
| # We can see that the two algorithm converges quickly, and POGM requires less iterations. | ||
| # However the POGM iterations are more costly, so a proper benchmark with time measurement is needed. | ||
| # Check the benchopt benchmark for more details. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.