-
Notifications
You must be signed in to change notification settings - Fork 273
Primal-dual evolution event handler recipe #916
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
14 commits
Select commit
Hold shift + click to select a range
5148fe7
Minor fixes
Joao-Dionisio 58ad6d1
Add primal_dual_evolution and test and plot
Joao-Dionisio 1e5a56f
Update CHANGELOG
Joao-Dionisio 53627d2
More robust testing
Joao-Dionisio 7c23a54
Update src/pyscipopt/recipes/primal_dual_evolution.py
Joao-Dionisio cca56ee
Update tests/helpers/utils.py
Joao-Dionisio a3cddcb
some comments
7c87182
remove is_optimized_mode
06b4e72
add docstring. remove useless util
3886f4a
Clean up code and example
Joao-Dionisio e011945
Add inits for ease of import later
Joao-Dionisio 9db8870
Restore optimized test
Joao-Dionisio 15f7e1b
finally working
Joao-Dionisio ea9ab18
Merge branch 'master' into plot-pd-evolution
Joao-Dionisio 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
Empty file.
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,54 @@ | ||
| """ | ||
| This example show how to retrieve the primal and dual solutions during the optimization process | ||
| and plot them as a function of time. The model is about gas transportation and can be found in | ||
| PySCIPOpt/tests/helpers/utils.py | ||
|
|
||
| It makes use of the attach_primal_dual_evolution_eventhdlr recipe. | ||
|
|
||
| Requires matplotlib, and may require PyQt6 to show the plot. | ||
| """ | ||
|
|
||
| from pyscipopt import Model | ||
|
|
||
| def plot_primal_dual_evolution(model: Model): | ||
| try: | ||
| from matplotlib import pyplot as plt | ||
| except ImportError: | ||
| raise ImportError("matplotlib is required to plot the solution. Try running `pip install matplotlib` in the command line.\ | ||
| You may also need to install PyQt6 to show the plot.") | ||
|
|
||
| assert model.data["primal_log"], "Could not find any feasible solutions" | ||
| time_primal, val_primal = map(list,zip(*model.data["primal_log"])) | ||
| time_dual, val_dual = map(list,zip(*model.data["dual_log"])) | ||
|
|
||
|
|
||
| if time_primal[-1] < time_dual[-1]: | ||
| time_primal.append(time_dual[-1]) | ||
| val_primal.append(val_primal[-1]) | ||
|
|
||
| if time_primal[-1] > time_dual[-1]: | ||
| time_dual.append(time_primal[-1]) | ||
| val_dual.append(val_dual[-1]) | ||
|
|
||
| plt.plot(time_primal, val_primal, label="Primal bound") | ||
| plt.plot(time_dual, val_dual, label="Dual bound") | ||
|
|
||
| plt.legend(loc="best") | ||
| plt.show() | ||
|
|
||
| if __name__=="__main__": | ||
| from pyscipopt.recipes.primal_dual_evolution import attach_primal_dual_evolution_eventhdlr | ||
| import os | ||
| import sys | ||
|
|
||
| # just a way to import files from different folders, not important | ||
| sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../tests/helpers'))) | ||
|
|
||
| from utils import gastrans_model | ||
|
|
||
| model = gastrans_model() | ||
| model.data = {} | ||
| attach_primal_dual_evolution_eventhdlr(model) | ||
|
|
||
| model.optimize() | ||
| plot_primal_dual_evolution(model) |
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 @@ | ||
| from pyscipopt import Model, Eventhdlr, SCIP_EVENTTYPE, Eventhdlr | ||
|
|
||
| def attach_primal_dual_evolution_eventhdlr(model: Model): | ||
| """ | ||
| Attaches an event handler to a given SCIP model that collects primal and dual solutions, | ||
| along with the solving time when they were found. | ||
| The data is saved in model.data["primal_log"] and model.data["dual_log"]. They consist of | ||
| a list of tuples, each tuple containing the solving time and the corresponding solution. | ||
|
|
||
| A usage example can be found in examples/finished/plot_primal_dual_evolution.py. The | ||
| example takes the information provided by this recipe and uses it to plot the evolution | ||
| of the dual and primal bounds over time. | ||
| """ | ||
| class GapEventhdlr(Eventhdlr): | ||
|
|
||
| def eventinit(self): # we want to collect best primal solutions and best dual solutions | ||
| self.model.catchEvent(SCIP_EVENTTYPE.BESTSOLFOUND, self) | ||
| self.model.catchEvent(SCIP_EVENTTYPE.LPSOLVED, self) | ||
| self.model.catchEvent(SCIP_EVENTTYPE.NODESOLVED, self) | ||
|
|
||
|
|
||
| def eventexec(self, event): | ||
| # if a new best primal solution was found, we save when it was found and also its objective | ||
| if event.getType() == SCIP_EVENTTYPE.BESTSOLFOUND: | ||
| self.model.data["primal_log"].append([self.model.getSolvingTime(), self.model.getPrimalbound()]) | ||
|
|
||
| if not self.model.data["dual_log"]: | ||
| self.model.data["dual_log"].append([self.model.getSolvingTime(), self.model.getDualbound()]) | ||
|
|
||
| if self.model.getObjectiveSense() == "minimize": | ||
| if self.model.isGT(self.model.getDualbound(), self.model.data["dual_log"][-1][1]): | ||
| self.model.data["dual_log"].append([self.model.getSolvingTime(), self.model.getDualbound()]) | ||
| else: | ||
| if self.model.isLT(self.model.getDualbound(), self.model.data["dual_log"][-1][1]): | ||
| self.model.data["dual_log"].append([self.model.getSolvingTime(), self.model.getDualbound()]) | ||
|
|
||
|
|
||
| if not hasattr(model, "data") or model.data==None: | ||
| model.data = {} | ||
|
|
||
| model.data["primal_log"] = [] | ||
| model.data["dual_log"] = [] | ||
| hdlr = GapEventhdlr() | ||
| model.includeEventhdlr(hdlr, "gapEventHandler", "Event handler which collects primal and dual solution evolution") | ||
|
|
||
| return model | ||
Large diffs are not rendered by default.
Oops, something went wrong.
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
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,28 @@ | ||
| from pyscipopt.recipes.primal_dual_evolution import attach_primal_dual_evolution_eventhdlr | ||
| from helpers.utils import bin_packing_model | ||
|
|
||
| def test_primal_dual_evolution(): | ||
| from random import randint | ||
|
|
||
| model = bin_packing_model(sizes=[randint(1,40) for _ in range(120)], capacity=50) | ||
| model.setParam("limits/time",5) | ||
|
|
||
| model.data = {"test": True} | ||
| model = attach_primal_dual_evolution_eventhdlr(model) | ||
|
|
||
| assert "test" in model.data | ||
| assert "primal_log" in model.data | ||
|
|
||
| model.optimize() | ||
|
|
||
| for i in range(1, len(model.data["primal_log"])): | ||
| if model.getObjectiveSense() == "minimize": | ||
| assert model.data["primal_log"][i][1] <= model.data["primal_log"][i-1][1] | ||
| else: | ||
| assert model.data["primal_log"][i][1] >= model.data["primal_log"][i-1][1] | ||
|
|
||
| for i in range(1, len(model.data["dual_log"])): | ||
| if model.getObjectiveSense() == "minimize": | ||
| assert model.data["dual_log"][i][1] >= model.data["dual_log"][i-1][1] | ||
| else: | ||
| assert model.data["dual_log"][i][1] <= model.data["dual_log"][i-1][1] |
Oops, something went wrong.
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.