Repository navigation
Merge unstable into main: solver config interface and test coverage #377
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
13 commits
Select commit
Hold shift + click to select a range
d638b61
Remove stale mypy type-ignore for pint UnitRegistry
jdecarolis fc10702
chore: bump pint to 0.26.1 to match unit_checking type fix
jdecarolis f4310e6
Added solver configuration interface
yamilbknsu 6869621
Redact sensitive information from the configuration options that get …
yamilbknsu ac5fe15
code rabbit comments
yamilbknsu 1df3264
Add test coverage for CLI, myopic, stochastic, and extensions framework
idelder 2d83cc2
Stop refreshing databases for test collection
idelder 1002c32
Specify exact expected exit codes in test_cli
idelder ff96e56
Merge pull request #373 from yamilbknsu/dev/solver-spec
jdecarolis b8ab2ac
Merge pull request #374 from idelder/test/increase-coverage
jdecarolis 17e925b
Merge unstable into main: solver configuration interface and expanded…
jdecarolis a676abd
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2c72c76
Remove accidentally-included local scratch files from merge commit
jdecarolis 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
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') | ||
|
|
||
|
|
||
| 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 {})} | ||
Oops, something went wrong.
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.
🩺 Stability & Availability | 🔵 Trivial | 💤 Low value
Redaction does not cover nested or non-string option keys.
redact_solver_optionscallsoption.lower()on every key. If a solver option key is not a string, the call raisesAttributeError. A TOML file cannot produce that key. A programmaticSolverSpec(name, {1: ...})can produce it, andTemoaConfig.__repr__would then crash. The marker list also matcheskeyas a substring. That match masks benign options that contain "key", which is acceptable. Usestr(option).lower()to make the helper total.Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents