-
Notifications
You must be signed in to change notification settings - Fork 75
Added solver configuration interface #373
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
Open
yamilbknsu
wants to merge
3
commits into
TemoaProject:unstable
Choose a base branch
from
yamilbknsu:dev/solver-spec
base: unstable
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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,107 @@ | ||
| """ | ||
| Solver selection and option resolution. | ||
|
|
||
| The config accepts ``solver`` as either a plain solver name or a table with a ``name`` and a | ||
| passthrough ``options`` table. Options that reach the solver are layered as: | ||
|
|
||
| DEFAULT_SOLVER_OPTIONS < [solver.options] < extension-specific options (MGA, MC, ...) | ||
|
|
||
| Any solver name known to pyomo's SolverFactory is accepted. Solvers without an entry in | ||
| DEFAULT_SOLVER_OPTIONS simply get no Temoa defaults. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Mapping | ||
| from dataclasses import dataclass, field | ||
| from typing import Any | ||
|
|
||
| # Note: these parameter values match mip-dev / PyPSA | ||
| # (see: https://pypsa-eur.readthedocs.io/en/latest/configuration.html) | ||
| DEFAULT_SOLVER_OPTIONS: dict[str, dict[str, Any]] = { | ||
| 'cplex': { | ||
| 'lpmethod': 4, # barrier | ||
| 'solutiontype': 2, # non basic solution, ie no crossover | ||
| 'barrier convergetol': 1.0e-3, | ||
| 'feasopt tolerance': 1.0e-4, | ||
| }, | ||
| 'gurobi': { | ||
| 'Method': 2, # barrier | ||
| 'Crossover': 0, # non basic solution, ie no crossover | ||
| 'BarConvTol': 1.0e-3, | ||
| 'FeasibilityTol': 1.0e-4, | ||
| 'BarOrder': -1, # auto ordering; 2-4x faster than AMD on large models | ||
| }, | ||
| } | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class SolverSpec: | ||
| """A solver name plus the user-supplied options from the config (defaults excluded).""" | ||
|
|
||
| name: str | ||
| options: Mapping[str, Any] = field(default_factory=dict) | ||
|
|
||
| @classmethod | ||
| def parse(cls, raw: str | Mapping[str, Any] | SolverSpec) -> SolverSpec: | ||
| """ | ||
| Build a SolverSpec from a solver name, a {'name': ..., 'options': {...}} mapping, or an | ||
| existing SolverSpec | ||
| """ | ||
| if isinstance(raw, SolverSpec): | ||
| return raw | ||
| if isinstance(raw, str): | ||
| if not raw: | ||
| raise ValueError('Solver name must not be empty') | ||
| return cls(raw) | ||
| if isinstance(raw, Mapping): | ||
| unknown = set(raw) - {'name', 'options'} | ||
| if unknown: | ||
| raise ValueError( | ||
| f'Unrecognized key(s) in solver table: {sorted(unknown)}. Expected "name" ' | ||
| 'and (optionally) "options". Solver parameters belong under [solver.options]' | ||
| ) | ||
| name = raw.get('name') | ||
| if not isinstance(name, str) or not name: | ||
| raise ValueError('The solver table requires a non-empty "name" entry') | ||
| options = raw.get('options', {}) | ||
| if not isinstance(options, Mapping): | ||
| raise ValueError('The "options" entry of the solver table must be a table/dict') | ||
| return cls(name, dict(options)) | ||
| raise TypeError(f'solver must be a str or a table/dict, got: {type(raw).__name__}') | ||
|
|
||
|
|
||
| # substrings (lowercase) of option names whose values are credentials, e.g. gurobi's WLSSecret, | ||
| # CloudSecretKey, CSAPIAccessID, ServerPassword, LicenseID | ||
| _SENSITIVE_OPTION_MARKERS = ('secret', 'password', 'accessid', 'licenseid', 'key', 'token') | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
|
|
||
| def redact_solver_options(options: Mapping[str, Any]) -> dict[str, Any]: | ||
| """ | ||
| Return a copy of the options that is safe to log or print, with credential values masked | ||
| """ | ||
| return { | ||
| option: '***' | ||
| if any(marker in option.lower() for marker in _SENSITIVE_OPTION_MARKERS) | ||
| else option_value | ||
| for option, option_value in options.items() | ||
| } | ||
|
|
||
|
|
||
| def resolve_solver_options( | ||
| spec: SolverSpec, | ||
| extension_options: Mapping[str, Any] | None = None, | ||
| *, | ||
| include_defaults: bool = True, | ||
| ) -> dict[str, Any]: | ||
| """ | ||
| Merge the option layers that are passed to the solver | ||
| :param spec: the solver spec from the config | ||
| :param extension_options: options from an extension's own source (MGA/MC/Morris toml, | ||
| stochastic config), which take precedence over everything else | ||
| :param include_defaults: include DEFAULT_SOLVER_OPTIONS as the bottom layer. Solve paths that | ||
| historically ran without Temoa defaults (MGA base solve, stochastic) turn this off. | ||
| :return: a new dict of solver options | ||
| """ | ||
| defaults = DEFAULT_SOLVER_OPTIONS.get(spec.name, {}) if include_defaults else {} | ||
| return {**defaults, **spec.options, **(extension_options or {})} | ||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just highlighting that here are the default options, which are the same as the current code