From e1a583e9aa516b0218fa2b1bd928ae93ffd5d6d9 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Thu, 19 Nov 2026 08:56:24 +0100 Subject: [PATCH 1/2] Reduce the import time of optimagic from 2 to 0.6 seconds. Everything that minimize and maximize always need is still imported with optimagic. The time is saved as follows: - Packages that are only needed for some features are imported inside the functions that use them: numba (benchmark problems), scipy.stats and scipy.ndimage (multistart sampling, Richardson extrapolation), scipy.linalg, sqlalchemy (logging), plotly.express, joblib and pathos. - scipy.optimize is imported when a scipy optimizer runs and not when the optimizer modules are imported. - The pydantic validator of an algorithm class is built when the class is instantiated for the first time. validated_dataclass no longer re-creates the class as a pydantic dataclass but replaces its __init__. - The generated algorithm selection classes are plain classes and not dataclasses. A test fails if `import optimagic` imports one of the slow packages again. Co-Authored-By: Claude Fable 5.2 --- .tools/create_algo_selection_code.py | 58 +++++-- CHANGES.md | 6 + docs/source/development/styleguide.md | 9 + .../how_to/how_to_document_optimizers.md | 7 +- src/optimagic/algorithms.py | 162 +++--------------- src/optimagic/batch_evaluators.py | 19 +- .../benchmarking/get_benchmark_problems.py | 10 +- src/optimagic/config.py | 17 +- .../richardson_extrapolation.py | 16 +- src/optimagic/logging/logger.py | 14 +- src/optimagic/logging/sqlalchemy.py | 36 ++-- src/optimagic/mark.py | 6 +- src/optimagic/optimization/multistart.py | 4 +- src/optimagic/optimization/optimize.py | 6 +- .../optimizers/bayesian_optimizer.py | 2 +- src/optimagic/optimizers/ipopt.py | 9 +- src/optimagic/optimizers/pounders.py | 37 ++-- src/optimagic/optimizers/scipy_optimizers.py | 55 +++++- src/optimagic/parameters/bounds.py | 19 +- src/optimagic/typing.py | 66 +++++-- src/optimagic/utilities.py | 4 +- src/optimagic/visualization/deviation_plot.py | 4 +- src/optimagic/visualization/slice_plot_3d.py | 4 +- tests/optimagic/parameters/test_bounds.py | 11 ++ tests/optimagic/test_algo_selection.py | 28 +++ tests/optimagic/test_batch_evaluators.py | 13 +- tests/optimagic/test_import.py | 35 ++++ tests/optimagic/test_typing.py | 61 +++++++ 28 files changed, 466 insertions(+), 252 deletions(-) create mode 100644 tests/optimagic/test_import.py diff --git a/.tools/create_algo_selection_code.py b/.tools/create_algo_selection_code.py index 1000ca64f..0a110f13b 100644 --- a/.tools/create_algo_selection_code.py +++ b/.tools/create_algo_selection_code.py @@ -14,7 +14,7 @@ def main() -> None: """Create the source code for algorithms.py. - The main part of the generated code are nested dataclasses that enable filtered + The main part of the generated code are nested classes that enable filtered autocomplete for algorithm selection. Creating them entails the following steps: - Discover all modules that contain optimizer classes @@ -22,10 +22,14 @@ def main() -> None: - Create a mapping from a tuple of categories (e.g. Global, Bounded, ...) to the optimizer classes that belong to them. To find out which optimizers need to be included we use the attributes stored in optimizer_class.__algo_info__. - - Create the dataclasses that enable autocomplete for algorithm selection + - Create the classes that enable autocomplete for algorithm selection In addition we need to create the code for import statements, a AlgoSelection base - class and some code to instantiate the dataclasses. + class and some code to instantiate the classes. + + The generated classes are plain classes and not dataclasses, because creating more + than 100 dataclasses with about 2000 fields in total takes about 70 milliseconds + every time optimagic is imported. """ # create some basic inputs @@ -42,15 +46,15 @@ class and some code to instantiate the dataclasses. # create the code for the ABC AlgoSelection class parent_class_snippet = _get_base_class_code() - # create the code for the dataclasses - dataclass_snippets = [] + # create the code for the selection classes + class_snippets = [] for active_categories in selection_info: - new_snippet = create_dataclass_code( + new_snippet = create_selection_class_code( active_categories=active_categories, all_categories=all_categories, selection_info=selection_info, ) - dataclass_snippets.append(new_snippet) + class_snippets.append(new_snippet) # create the code for the instantiation instantiation_snippet = _get_instantiation_code() @@ -62,7 +66,7 @@ class and some code to instantiate the dataclasses. + "\n\n" + parent_class_snippet + "\n" - + "\n\n".join(dataclass_snippets) + + "\n\n".join(class_snippets) + "\n\n" + instantiation_snippet ) @@ -248,16 +252,16 @@ def _apply_filters( # ====================================================================================== -# Functions to create code for the dataclasses +# Functions to create code for the selection classes # ====================================================================================== -def create_dataclass_code( +def create_selection_class_code( active_categories: tuple[str, ...], all_categories: list[str], selection_info: dict[tuple[str, ...], dict[str, Type[Algorithm]]], ) -> str: - """Create the source code for a dataclass representing a selection of algorithms. + """Create the source code for a class representing a selection of algorithms. Args: active_categories: A tuple of active category names. @@ -266,7 +270,7 @@ def create_dataclass_code( of algorithm names and their corresponding classes. Returns: - A string containing the source code for the dataclass. + A string containing the source code for the class. """ # get the children of the active categories @@ -275,7 +279,7 @@ def create_dataclass_code( # get the name of the class to be generated class_name = _get_class_name(active_categories) - # get code for the dataclass fields + # get code for the class attributes that hold the algorithms field_template = " {name}: Type[{class_name}] = {class_name}" field_strings = [] for name, algo_class in selection_info[active_categories].items(): @@ -302,8 +306,7 @@ def {new_category}(self) -> {class_name}: children_code = "\n".join(child_strings) # assemble the class - out = "@dataclass(frozen=True)\n" - out += f"class {class_name}(AlgoSelection):\n" + out = f"class {class_name}(AlgoSelection):\n" out += fields + "\n" if children: out += children_code @@ -354,7 +357,7 @@ def _get_imports(modules: list[ModuleType]) -> str: """Create source code to import all algorithms.""" snippets = [ "from typing import Type", - "from dataclasses import dataclass", + "from dataclasses import FrozenInstanceError", "from optimagic.optimization.algorithm import Algorithm", "from typing import cast", ] @@ -374,11 +377,30 @@ def _get_imports(modules: list[ModuleType]) -> str: def _get_base_class_code() -> str: """Get the source code for the AlgoSelection class.""" out = textwrap.dedent(""" - @dataclass(frozen=True) class AlgoSelection: + \"\"\"Base class for selections of algorithms. + + The algorithms of a selection are its annotated class attributes. + + \"\"\" + + def __setattr__(self, name: str, value: object) -> None: + raise FrozenInstanceError(f"cannot assign to field {name!r}") + + def __delattr__(self, name: str) -> None: + raise FrozenInstanceError(f"cannot delete field {name!r}") + + def __eq__(self, other: object) -> bool: + return type(self) is type(other) + + def __hash__(self) -> int: + return hash(type(self)) + + def __repr__(self) -> str: + return f"{type(self).__name__}({', '.join(self.AllNames)})" def _all(self) -> list[Type[Algorithm]]: - raw = [field.default for field in self.__dataclass_fields__.values()] + raw = [getattr(self, name) for name in type(self).__annotations__] return cast(list[Type[Algorithm]], raw) diff --git a/CHANGES.md b/CHANGES.md index 83738e88b..f533e7468 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,12 @@ releases are available on [Anaconda.org](https://anaconda.org/optimagic-dev/opti This release adds experimental support for **SciPy-style callbacks**, replaces pybaum by **optree** for pytree handling and uses **pydantic** to validate algorithm options. +- {gh}`747` Reduces the time it takes to import optimagic from about 2 seconds to about + 0.6 seconds. Dependencies that are only needed for some features (scipy, numba, + sqlalchemy, plotly.express and joblib) are imported when they are used, the + validators of algorithm options are built when an algorithm is instantiated for the + first time and the classes behind `om.algos` are no longer dataclasses + ({ghuser}`janosg`). - {gh}`739` Fixes `tao_pounders` ignoring `convergence_gtol_abs`, `convergence_gtol_rel` and `convergence_gtol_scaled`. Reaching `stopping_maxiter` is now reported as unsuccessful with the message "maxits reached" instead of as diff --git a/docs/source/development/styleguide.md b/docs/source/development/styleguide.md index a15a3ad67..5931d3535 100644 --- a/docs/source/development/styleguide.md +++ b/docs/source/development/styleguide.md @@ -77,6 +77,15 @@ Your contribution should fulfill the criteria provided below. modules. Of course it is also not a solution to copy paste the function! If you would like to import a function that starts with an underscore, rename it. +- Keep `import optimagic` fast : Packages that are slow to import and only needed for + some features are imported inside the functions that use them and not at the top of a + module. Examples are `scipy`, `sqlalchemy`, `plotly.express`, `joblib`, `numba` and + the optimizer libraries. Everything that `minimize` and `maximize` always need is + imported at the top, so that the first optimization is not slowed down instead. + `tests/optimagic/test_import.py` fails if `import optimagic` imports one of the slow + packages. Run `python -X importtime -c "import optimagic"` to see how long each module + takes to import. + - All functions have a [Google style](https://tinyurl.com/mxams9k) docstring : The docstring describes all arguments and outputs. For arrays, please document how many dimensions and what shape they have. Look around in the code to find examples if you diff --git a/docs/source/how_to/how_to_document_optimizers.md b/docs/source/how_to/how_to_document_optimizers.md index c741f737e..22295e66c 100644 --- a/docs/source/how_to/how_to_document_optimizers.md +++ b/docs/source/how_to/how_to_document_optimizers.md @@ -245,10 +245,9 @@ Add the following to `docs/source/algorithms.md` in an `eval-rst` block: finite `bounds` if the algorithm needs them, and mark least-squares or likelihood functions with `om.mark.least_squares` or `om.mark.likelihood` - **Auto-generated documentation** via the `autoclass` directive that pulls in your - docstrings. The `:inherited-members: Algorithm, object` option is required: - `mark.minimizer` re-creates the algorithm class as a pydantic dataclass that inherits - from your class, so without it autodoc treats your documented fields as inherited and - does not show them + docstrings. The `:inherited-members: Algorithm, object` option also shows fields that + your class inherits from a base class of its own, without listing the members of + `Algorithm` ## Working with Existing Documentation diff --git a/src/optimagic/algorithms.py b/src/optimagic/algorithms.py index 9f5efb13a..9380fc125 100644 --- a/src/optimagic/algorithms.py +++ b/src/optimagic/algorithms.py @@ -8,7 +8,7 @@ """ -from dataclasses import dataclass +from dataclasses import FrozenInstanceError from typing import Type, cast from optimagic.optimization.algorithm import Algorithm @@ -116,10 +116,30 @@ from optimagic.optimizers.tranquilo import Tranquilo, TranquiloLS -@dataclass(frozen=True) class AlgoSelection: + """Base class for selections of algorithms. + + The algorithms of a selection are its annotated class attributes. + + """ + + def __setattr__(self, name: str, value: object) -> None: + raise FrozenInstanceError(f"cannot assign to field {name!r}") + + def __delattr__(self, name: str) -> None: + raise FrozenInstanceError(f"cannot delete field {name!r}") + + def __eq__(self, other: object) -> bool: + return type(self) is type(other) + + def __hash__(self) -> int: + return hash(type(self)) + + def __repr__(self) -> str: + return f"{type(self).__name__}({', '.join(self.AllNames)})" + def _all(self) -> list[Type[Algorithm]]: - raw = [field.default for field in self.__dataclass_fields__.values()] + raw = [getattr(self, name) for name in type(self).__annotations__] return cast(list[Type[Algorithm]], raw) def _available(self) -> list[Type[Algorithm]]: @@ -151,7 +171,6 @@ def _available_algorithms_dict(self) -> dict[str, Type[Algorithm]]: return {str(a.name): a for a in self._available()} -@dataclass(frozen=True) class BoundedGlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms( AlgoSelection ): @@ -160,12 +179,10 @@ class BoundedGlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms( ) -@dataclass(frozen=True) class BoundedGlobalGradientBasedNonlinearConstrainedScalarAlgorithms(AlgoSelection): scipy_shgo: Type[ScipySHGO] = ScipySHGO -@dataclass(frozen=True) class BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_mma: Type[NloptMMA] = NloptMMA @@ -174,7 +191,6 @@ class BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorithms(AlgoSelectio scipy_trust_constr: Type[ScipyTrustConstr] = ScipyTrustConstr -@dataclass(frozen=True) class BoundedGlobalGradientFreeNonlinearConstrainedScalarAlgorithms(AlgoSelection): nlopt_isres: Type[NloptISRES] = NloptISRES scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( @@ -188,7 +204,6 @@ def Parallel( return BoundedGlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientFreeNonlinearConstrainedParallelAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -201,7 +216,6 @@ def Scalar( return BoundedGlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientFreeParallelScalarAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -234,7 +248,6 @@ def NonlinearConstrained( return BoundedGlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -247,23 +260,19 @@ def Bounded( return BoundedGlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeLocalNonlinearConstrainedScalarAlgorithms(AlgoSelection): nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA -@dataclass(frozen=True) class BoundedGradientFreeLocalParallelScalarAlgorithms(AlgoSelection): tranquilo: Type[Tranquilo] = Tranquilo -@dataclass(frozen=True) class BoundedGradientFreeLeastSquaresLocalParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo_ls: Type[TranquiloLS] = TranquiloLS -@dataclass(frozen=True) class BoundedGradientFreeNonlinearConstrainedParallelScalarAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -276,7 +285,6 @@ def Global( return BoundedGlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalNonlinearConstrainedParallelScalarAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -289,7 +297,6 @@ def GradientFree( return BoundedGlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientBasedNonlinearConstrainedAlgorithms(AlgoSelection): scipy_shgo: Type[ScipySHGO] = ScipySHGO @@ -298,7 +305,6 @@ def Scalar(self) -> BoundedGlobalGradientBasedNonlinearConstrainedScalarAlgorith return BoundedGlobalGradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientBasedScalarAlgorithms(AlgoSelection): scipy_basinhopping: Type[ScipyBasinhopping] = ScipyBasinhopping scipy_dual_annealing: Type[ScipyDualAnnealing] = ScipyDualAnnealing @@ -311,7 +317,6 @@ def NonlinearConstrained( return BoundedGlobalGradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientBasedNonlinearConstrainedScalarAlgorithms(AlgoSelection): scipy_shgo: Type[ScipySHGO] = ScipySHGO @@ -320,7 +325,6 @@ def Bounded(self) -> BoundedGlobalGradientBasedNonlinearConstrainedScalarAlgorit return BoundedGlobalGradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientBasedLocalNonlinearConstrainedAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_mma: Type[NloptMMA] = NloptMMA @@ -333,7 +337,6 @@ def Scalar(self) -> BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorithm return BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientBasedLocalScalarAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -356,13 +359,11 @@ def NonlinearConstrained( return BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientBasedLeastSquaresLocalAlgorithms(AlgoSelection): scipy_ls_dogbox: Type[ScipyLSDogbox] = ScipyLSDogbox scipy_ls_trf: Type[ScipyLSTRF] = ScipyLSTRF -@dataclass(frozen=True) class GradientBasedLocalNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_mma: Type[NloptMMA] = NloptMMA @@ -375,7 +376,6 @@ def Bounded(self) -> BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorith return BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientBasedNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_mma: Type[NloptMMA] = NloptMMA @@ -393,7 +393,6 @@ def Local(self) -> BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorithms return BoundedGradientBasedLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientFreeNonlinearConstrainedAlgorithms(AlgoSelection): nlopt_isres: Type[NloptISRES] = NloptISRES scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( @@ -411,7 +410,6 @@ def Scalar(self) -> BoundedGlobalGradientFreeNonlinearConstrainedScalarAlgorithm return BoundedGlobalGradientFreeNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientFreeScalarAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -484,7 +482,6 @@ def Parallel(self) -> BoundedGlobalGradientFreeParallelScalarAlgorithms: return BoundedGlobalGradientFreeParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientFreeParallelAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -521,7 +518,6 @@ def Scalar(self) -> BoundedGlobalGradientFreeParallelScalarAlgorithms: return BoundedGlobalGradientFreeParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientFreeNonlinearConstrainedScalarAlgorithms(AlgoSelection): nlopt_isres: Type[NloptISRES] = NloptISRES scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( @@ -539,7 +535,6 @@ def Parallel( return GlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientFreeNonlinearConstrainedParallelAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -556,7 +551,6 @@ def Scalar(self) -> GlobalGradientFreeNonlinearConstrainedParallelScalarAlgorith return GlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientFreeParallelScalarAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -593,7 +587,6 @@ def NonlinearConstrained( return GlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeLocalNonlinearConstrainedAlgorithms(AlgoSelection): nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -602,7 +595,6 @@ def Scalar(self) -> BoundedGradientFreeLocalNonlinearConstrainedScalarAlgorithms return BoundedGradientFreeLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeLocalScalarAlgorithms(AlgoSelection): nag_pybobyqa: Type[NagPyBOBYQA] = NagPyBOBYQA nlopt_bobyqa: Type[NloptBOBYQA] = NloptBOBYQA @@ -626,7 +618,6 @@ def Parallel(self) -> BoundedGradientFreeLocalParallelScalarAlgorithms: return BoundedGradientFreeLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeLeastSquaresLocalAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS pounders: Type[Pounders] = Pounders @@ -638,7 +629,6 @@ def Parallel(self) -> BoundedGradientFreeLeastSquaresLocalParallelAlgorithms: return BoundedGradientFreeLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeLocalParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo: Type[Tranquilo] = Tranquilo @@ -653,7 +643,6 @@ def Scalar(self) -> BoundedGradientFreeLocalParallelScalarAlgorithms: return BoundedGradientFreeLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLocalNonlinearConstrainedScalarAlgorithms(AlgoSelection): nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA scipy_cobyla: Type[ScipyCOBYLA] = ScipyCOBYLA @@ -663,7 +652,6 @@ def Bounded(self) -> BoundedGradientFreeLocalNonlinearConstrainedScalarAlgorithm return BoundedGradientFreeLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLocalParallelScalarAlgorithms(AlgoSelection): neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel tranquilo: Type[Tranquilo] = Tranquilo @@ -673,7 +661,6 @@ def Bounded(self) -> BoundedGradientFreeLocalParallelScalarAlgorithms: return BoundedGradientFreeLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLeastSquaresLocalParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo_ls: Type[TranquiloLS] = TranquiloLS @@ -683,7 +670,6 @@ def Bounded(self) -> BoundedGradientFreeLeastSquaresLocalParallelAlgorithms: return BoundedGradientFreeLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeNonlinearConstrainedScalarAlgorithms(AlgoSelection): nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA nlopt_isres: Type[NloptISRES] = NloptISRES @@ -706,7 +692,6 @@ def Parallel( return BoundedGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeNonlinearConstrainedParallelAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -721,7 +706,6 @@ def Scalar(self) -> BoundedGradientFreeNonlinearConstrainedParallelScalarAlgorit return BoundedGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeParallelScalarAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -763,7 +747,6 @@ def NonlinearConstrained( return BoundedGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeLeastSquaresParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo_ls: Type[TranquiloLS] = TranquiloLS @@ -773,7 +756,6 @@ def Local(self) -> BoundedGradientFreeLeastSquaresLocalParallelAlgorithms: return BoundedGradientFreeLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class GradientFreeNonlinearConstrainedParallelScalarAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -790,7 +772,6 @@ def Global(self) -> GlobalGradientFreeNonlinearConstrainedParallelScalarAlgorith return GlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalNonlinearConstrainedScalarAlgorithms(AlgoSelection): nlopt_isres: Type[NloptISRES] = NloptISRES scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( @@ -815,7 +796,6 @@ def Parallel(self) -> BoundedGlobalNonlinearConstrainedParallelScalarAlgorithms: return BoundedGlobalNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalNonlinearConstrainedParallelAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -832,7 +812,6 @@ def Scalar(self) -> BoundedGlobalNonlinearConstrainedParallelScalarAlgorithms: return BoundedGlobalNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalParallelScalarAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -869,7 +848,6 @@ def NonlinearConstrained( return BoundedGlobalNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalNonlinearConstrainedParallelScalarAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -886,7 +864,6 @@ def GradientFree( return GlobalGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedLocalNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -908,7 +885,6 @@ def GradientFree( return BoundedGradientFreeLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedLocalParallelScalarAlgorithms(AlgoSelection): tranquilo: Type[Tranquilo] = Tranquilo @@ -917,7 +893,6 @@ def GradientFree(self) -> BoundedGradientFreeLocalParallelScalarAlgorithms: return BoundedGradientFreeLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedLeastSquaresLocalParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo_ls: Type[TranquiloLS] = TranquiloLS @@ -927,7 +902,6 @@ def GradientFree(self) -> BoundedGradientFreeLeastSquaresLocalParallelAlgorithms return BoundedGradientFreeLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class BoundedNonlinearConstrainedParallelScalarAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -944,7 +918,6 @@ def GradientFree( return BoundedGradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientBasedAlgorithms(AlgoSelection): scipy_basinhopping: Type[ScipyBasinhopping] = ScipyBasinhopping scipy_dual_annealing: Type[ScipyDualAnnealing] = ScipyDualAnnealing @@ -961,7 +934,6 @@ def Scalar(self) -> BoundedGlobalGradientBasedScalarAlgorithms: return BoundedGlobalGradientBasedScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientBasedNonlinearConstrainedAlgorithms(AlgoSelection): scipy_shgo: Type[ScipySHGO] = ScipySHGO @@ -974,7 +946,6 @@ def Scalar(self) -> GlobalGradientBasedNonlinearConstrainedScalarAlgorithms: return GlobalGradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientBasedScalarAlgorithms(AlgoSelection): scipy_basinhopping: Type[ScipyBasinhopping] = ScipyBasinhopping scipy_dual_annealing: Type[ScipyDualAnnealing] = ScipyDualAnnealing @@ -991,7 +962,6 @@ def NonlinearConstrained( return GlobalGradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientBasedLocalAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -1024,7 +994,6 @@ def Scalar(self) -> BoundedGradientBasedLocalScalarAlgorithms: return BoundedGradientBasedLocalScalarAlgorithms() -@dataclass(frozen=True) class GradientBasedLocalNonlinearConstrainedAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_mma: Type[NloptMMA] = NloptMMA @@ -1041,7 +1010,6 @@ def Scalar(self) -> GradientBasedLocalNonlinearConstrainedScalarAlgorithms: return GradientBasedLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GradientBasedLocalScalarAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -1071,7 +1039,6 @@ def NonlinearConstrained( return GradientBasedLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GradientBasedLeastSquaresLocalAlgorithms(AlgoSelection): scipy_ls_dogbox: Type[ScipyLSDogbox] = ScipyLSDogbox scipy_ls_lm: Type[ScipyLSLM] = ScipyLSLM @@ -1082,12 +1049,10 @@ def Bounded(self) -> BoundedGradientBasedLeastSquaresLocalAlgorithms: return BoundedGradientBasedLeastSquaresLocalAlgorithms() -@dataclass(frozen=True) class GradientBasedLikelihoodLocalAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH -@dataclass(frozen=True) class BoundedGradientBasedNonlinearConstrainedAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_mma: Type[NloptMMA] = NloptMMA @@ -1109,7 +1074,6 @@ def Scalar(self) -> BoundedGradientBasedNonlinearConstrainedScalarAlgorithms: return BoundedGradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientBasedScalarAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -1143,7 +1107,6 @@ def NonlinearConstrained( return BoundedGradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientBasedLeastSquaresAlgorithms(AlgoSelection): scipy_ls_dogbox: Type[ScipyLSDogbox] = ScipyLSDogbox scipy_ls_trf: Type[ScipyLSTRF] = ScipyLSTRF @@ -1153,7 +1116,6 @@ def Local(self) -> BoundedGradientBasedLeastSquaresLocalAlgorithms: return BoundedGradientBasedLeastSquaresLocalAlgorithms() -@dataclass(frozen=True) class GradientBasedNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_mma: Type[NloptMMA] = NloptMMA @@ -1175,7 +1137,6 @@ def Local(self) -> GradientBasedLocalNonlinearConstrainedScalarAlgorithms: return GradientBasedLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalGradientFreeAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -1252,7 +1213,6 @@ def Scalar(self) -> BoundedGlobalGradientFreeScalarAlgorithms: return BoundedGlobalGradientFreeScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientFreeNonlinearConstrainedAlgorithms(AlgoSelection): nlopt_isres: Type[NloptISRES] = NloptISRES scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( @@ -1272,7 +1232,6 @@ def Scalar(self) -> GlobalGradientFreeNonlinearConstrainedScalarAlgorithms: return GlobalGradientFreeNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientFreeScalarAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -1349,7 +1308,6 @@ def Parallel(self) -> GlobalGradientFreeParallelScalarAlgorithms: return GlobalGradientFreeParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientFreeParallelAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -1390,7 +1348,6 @@ def Scalar(self) -> GlobalGradientFreeParallelScalarAlgorithms: return GlobalGradientFreeParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeLocalAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS nag_pybobyqa: Type[NagPyBOBYQA] = NagPyBOBYQA @@ -1426,7 +1383,6 @@ def Scalar(self) -> BoundedGradientFreeLocalScalarAlgorithms: return BoundedGradientFreeLocalScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLocalNonlinearConstrainedAlgorithms(AlgoSelection): nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA scipy_cobyla: Type[ScipyCOBYLA] = ScipyCOBYLA @@ -1440,7 +1396,6 @@ def Scalar(self) -> GradientFreeLocalNonlinearConstrainedScalarAlgorithms: return GradientFreeLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLocalScalarAlgorithms(AlgoSelection): nag_pybobyqa: Type[NagPyBOBYQA] = NagPyBOBYQA neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel @@ -1470,7 +1425,6 @@ def Parallel(self) -> GradientFreeLocalParallelScalarAlgorithms: return GradientFreeLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLeastSquaresLocalAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS pounders: Type[Pounders] = Pounders @@ -1486,7 +1440,6 @@ def Parallel(self) -> GradientFreeLeastSquaresLocalParallelAlgorithms: return GradientFreeLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class GradientFreeLocalParallelAlgorithms(AlgoSelection): neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel pounders: Type[Pounders] = Pounders @@ -1506,7 +1459,6 @@ def Scalar(self) -> GradientFreeLocalParallelScalarAlgorithms: return GradientFreeLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeNonlinearConstrainedAlgorithms(AlgoSelection): nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA nlopt_isres: Type[NloptISRES] = NloptISRES @@ -1531,7 +1483,6 @@ def Scalar(self) -> BoundedGradientFreeNonlinearConstrainedScalarAlgorithms: return BoundedGradientFreeNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeScalarAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -1622,7 +1573,6 @@ def Parallel(self) -> BoundedGradientFreeParallelScalarAlgorithms: return BoundedGradientFreeParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeLeastSquaresAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS pounders: Type[Pounders] = Pounders @@ -1638,7 +1588,6 @@ def Parallel(self) -> BoundedGradientFreeLeastSquaresParallelAlgorithms: return BoundedGradientFreeLeastSquaresParallelAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeParallelAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -1690,7 +1639,6 @@ def Scalar(self) -> BoundedGradientFreeParallelScalarAlgorithms: return BoundedGradientFreeParallelScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeNonlinearConstrainedScalarAlgorithms(AlgoSelection): nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA nlopt_isres: Type[NloptISRES] = NloptISRES @@ -1716,7 +1664,6 @@ def Parallel(self) -> GradientFreeNonlinearConstrainedParallelScalarAlgorithms: return GradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeNonlinearConstrainedParallelAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -1735,7 +1682,6 @@ def Scalar(self) -> GradientFreeNonlinearConstrainedParallelScalarAlgorithms: return GradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeParallelScalarAlgorithms(AlgoSelection): neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim @@ -1782,7 +1728,6 @@ def NonlinearConstrained( return GradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLeastSquaresParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo_ls: Type[TranquiloLS] = TranquiloLS @@ -1796,7 +1741,6 @@ def Local(self) -> GradientFreeLeastSquaresLocalParallelAlgorithms: return GradientFreeLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class BoundedGlobalNonlinearConstrainedAlgorithms(AlgoSelection): nlopt_isres: Type[NloptISRES] = NloptISRES scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( @@ -1821,7 +1765,6 @@ def Scalar(self) -> BoundedGlobalNonlinearConstrainedScalarAlgorithms: return BoundedGlobalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalScalarAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -1903,7 +1846,6 @@ def Parallel(self) -> BoundedGlobalParallelScalarAlgorithms: return BoundedGlobalParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalParallelAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -1944,7 +1886,6 @@ def Scalar(self) -> BoundedGlobalParallelScalarAlgorithms: return BoundedGlobalParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalNonlinearConstrainedScalarAlgorithms(AlgoSelection): nlopt_isres: Type[NloptISRES] = NloptISRES scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( @@ -1969,7 +1910,6 @@ def Parallel(self) -> GlobalNonlinearConstrainedParallelScalarAlgorithms: return GlobalNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalNonlinearConstrainedParallelAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -1988,7 +1928,6 @@ def Scalar(self) -> GlobalNonlinearConstrainedParallelScalarAlgorithms: return GlobalNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalParallelScalarAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -2029,7 +1968,6 @@ def NonlinearConstrained( return GlobalNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedLocalNonlinearConstrainedAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -2051,7 +1989,6 @@ def Scalar(self) -> BoundedLocalNonlinearConstrainedScalarAlgorithms: return BoundedLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedLocalScalarAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -2094,7 +2031,6 @@ def Parallel(self) -> BoundedLocalParallelScalarAlgorithms: return BoundedLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedLeastSquaresLocalAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS pounders: Type[Pounders] = Pounders @@ -2116,7 +2052,6 @@ def Parallel(self) -> BoundedLeastSquaresLocalParallelAlgorithms: return BoundedLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class BoundedLocalParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo: Type[Tranquilo] = Tranquilo @@ -2135,7 +2070,6 @@ def Scalar(self) -> BoundedLocalParallelScalarAlgorithms: return BoundedLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class LocalNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -2158,7 +2092,6 @@ def GradientFree(self) -> GradientFreeLocalNonlinearConstrainedScalarAlgorithms: return GradientFreeLocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class LocalParallelScalarAlgorithms(AlgoSelection): neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel tranquilo: Type[Tranquilo] = Tranquilo @@ -2172,7 +2105,6 @@ def GradientFree(self) -> GradientFreeLocalParallelScalarAlgorithms: return GradientFreeLocalParallelScalarAlgorithms() -@dataclass(frozen=True) class LeastSquaresLocalParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo_ls: Type[TranquiloLS] = TranquiloLS @@ -2186,7 +2118,6 @@ def GradientFree(self) -> GradientFreeLeastSquaresLocalParallelAlgorithms: return GradientFreeLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class BoundedNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -2221,7 +2152,6 @@ def Parallel(self) -> BoundedNonlinearConstrainedParallelScalarAlgorithms: return BoundedNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedNonlinearConstrainedParallelAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -2240,7 +2170,6 @@ def Scalar(self) -> BoundedNonlinearConstrainedParallelScalarAlgorithms: return BoundedNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedParallelScalarAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -2286,7 +2215,6 @@ def NonlinearConstrained( return BoundedNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedLeastSquaresParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo_ls: Type[TranquiloLS] = TranquiloLS @@ -2300,7 +2228,6 @@ def Local(self) -> BoundedLeastSquaresLocalParallelAlgorithms: return BoundedLeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class NonlinearConstrainedParallelScalarAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -2319,7 +2246,6 @@ def GradientFree(self) -> GradientFreeNonlinearConstrainedParallelScalarAlgorith return GradientFreeNonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalGradientBasedAlgorithms(AlgoSelection): scipy_basinhopping: Type[ScipyBasinhopping] = ScipyBasinhopping scipy_dual_annealing: Type[ScipyDualAnnealing] = ScipyDualAnnealing @@ -2338,7 +2264,6 @@ def Scalar(self) -> GlobalGradientBasedScalarAlgorithms: return GlobalGradientBasedScalarAlgorithms() -@dataclass(frozen=True) class GradientBasedLocalAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH fides: Type[Fides] = Fides @@ -2382,7 +2307,6 @@ def Scalar(self) -> GradientBasedLocalScalarAlgorithms: return GradientBasedLocalScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientBasedAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -2426,7 +2350,6 @@ def Scalar(self) -> BoundedGradientBasedScalarAlgorithms: return BoundedGradientBasedScalarAlgorithms() -@dataclass(frozen=True) class GradientBasedNonlinearConstrainedAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_mma: Type[NloptMMA] = NloptMMA @@ -2452,7 +2375,6 @@ def Scalar(self) -> GradientBasedNonlinearConstrainedScalarAlgorithms: return GradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GradientBasedScalarAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -2491,7 +2413,6 @@ def NonlinearConstrained(self) -> GradientBasedNonlinearConstrainedScalarAlgorit return GradientBasedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GradientBasedLeastSquaresAlgorithms(AlgoSelection): scipy_ls_dogbox: Type[ScipyLSDogbox] = ScipyLSDogbox scipy_ls_lm: Type[ScipyLSLM] = ScipyLSLM @@ -2506,7 +2427,6 @@ def Local(self) -> GradientBasedLeastSquaresLocalAlgorithms: return GradientBasedLeastSquaresLocalAlgorithms() -@dataclass(frozen=True) class GradientBasedLikelihoodAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH @@ -2515,7 +2435,6 @@ def Local(self) -> GradientBasedLikelihoodLocalAlgorithms: return GradientBasedLikelihoodLocalAlgorithms() -@dataclass(frozen=True) class GlobalGradientFreeAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -2594,7 +2513,6 @@ def Scalar(self) -> GlobalGradientFreeScalarAlgorithms: return GlobalGradientFreeScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLocalAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS nag_pybobyqa: Type[NagPyBOBYQA] = NagPyBOBYQA @@ -2634,7 +2552,6 @@ def Scalar(self) -> GradientFreeLocalScalarAlgorithms: return GradientFreeLocalScalarAlgorithms() -@dataclass(frozen=True) class BoundedGradientFreeAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -2735,7 +2652,6 @@ def Scalar(self) -> BoundedGradientFreeScalarAlgorithms: return BoundedGradientFreeScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeNonlinearConstrainedAlgorithms(AlgoSelection): nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA nlopt_isres: Type[NloptISRES] = NloptISRES @@ -2765,7 +2681,6 @@ def Scalar(self) -> GradientFreeNonlinearConstrainedScalarAlgorithms: return GradientFreeNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeScalarAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -2860,7 +2775,6 @@ def Parallel(self) -> GradientFreeParallelScalarAlgorithms: return GradientFreeParallelScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeLeastSquaresAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS pounders: Type[Pounders] = Pounders @@ -2880,7 +2794,6 @@ def Parallel(self) -> GradientFreeLeastSquaresParallelAlgorithms: return GradientFreeLeastSquaresParallelAlgorithms() -@dataclass(frozen=True) class GradientFreeParallelAlgorithms(AlgoSelection): neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim @@ -2937,7 +2850,6 @@ def Scalar(self) -> GradientFreeParallelScalarAlgorithms: return GradientFreeParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedGlobalAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -3023,7 +2935,6 @@ def Scalar(self) -> BoundedGlobalScalarAlgorithms: return BoundedGlobalScalarAlgorithms() -@dataclass(frozen=True) class GlobalNonlinearConstrainedAlgorithms(AlgoSelection): nlopt_isres: Type[NloptISRES] = NloptISRES scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( @@ -3052,7 +2963,6 @@ def Scalar(self) -> GlobalNonlinearConstrainedScalarAlgorithms: return GlobalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class GlobalScalarAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -3138,7 +3048,6 @@ def Parallel(self) -> GlobalParallelScalarAlgorithms: return GlobalParallelScalarAlgorithms() -@dataclass(frozen=True) class GlobalParallelAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -3181,7 +3090,6 @@ def Scalar(self) -> GlobalParallelScalarAlgorithms: return GlobalParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedLocalAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -3238,7 +3146,6 @@ def Scalar(self) -> BoundedLocalScalarAlgorithms: return BoundedLocalScalarAlgorithms() -@dataclass(frozen=True) class LocalNonlinearConstrainedAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -3265,7 +3172,6 @@ def Scalar(self) -> LocalNonlinearConstrainedScalarAlgorithms: return LocalNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class LocalScalarAlgorithms(AlgoSelection): fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad @@ -3317,7 +3223,6 @@ def Parallel(self) -> LocalParallelScalarAlgorithms: return LocalParallelScalarAlgorithms() -@dataclass(frozen=True) class LeastSquaresLocalAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS pounders: Type[Pounders] = Pounders @@ -3344,7 +3249,6 @@ def Parallel(self) -> LeastSquaresLocalParallelAlgorithms: return LeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class LikelihoodLocalAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH @@ -3353,7 +3257,6 @@ def GradientBased(self) -> GradientBasedLikelihoodLocalAlgorithms: return GradientBasedLikelihoodLocalAlgorithms() -@dataclass(frozen=True) class LocalParallelAlgorithms(AlgoSelection): neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel pounders: Type[Pounders] = Pounders @@ -3377,7 +3280,6 @@ def Scalar(self) -> LocalParallelScalarAlgorithms: return LocalParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedNonlinearConstrainedAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -3416,7 +3318,6 @@ def Scalar(self) -> BoundedNonlinearConstrainedScalarAlgorithms: return BoundedNonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class BoundedScalarAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt fides: Type[Fides] = Fides @@ -3529,7 +3430,6 @@ def Parallel(self) -> BoundedParallelScalarAlgorithms: return BoundedParallelScalarAlgorithms() -@dataclass(frozen=True) class BoundedLeastSquaresAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS pounders: Type[Pounders] = Pounders @@ -3555,7 +3455,6 @@ def Parallel(self) -> BoundedLeastSquaresParallelAlgorithms: return BoundedLeastSquaresParallelAlgorithms() -@dataclass(frozen=True) class BoundedParallelAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim nevergrad_cga: Type[NevergradCGA] = NevergradCGA @@ -3609,7 +3508,6 @@ def Scalar(self) -> BoundedParallelScalarAlgorithms: return BoundedParallelScalarAlgorithms() -@dataclass(frozen=True) class NonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -3649,7 +3547,6 @@ def Parallel(self) -> NonlinearConstrainedParallelScalarAlgorithms: return NonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class NonlinearConstrainedParallelAlgorithms(AlgoSelection): scipy_differential_evolution: Type[ScipyDifferentialEvolution] = ( ScipyDifferentialEvolution @@ -3672,7 +3569,6 @@ def Scalar(self) -> NonlinearConstrainedParallelScalarAlgorithms: return NonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class ParallelScalarAlgorithms(AlgoSelection): neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim @@ -3721,7 +3617,6 @@ def NonlinearConstrained(self) -> NonlinearConstrainedParallelScalarAlgorithms: return NonlinearConstrainedParallelScalarAlgorithms() -@dataclass(frozen=True) class LeastSquaresParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders tranquilo_ls: Type[TranquiloLS] = TranquiloLS @@ -3739,7 +3634,6 @@ def Local(self) -> LeastSquaresLocalParallelAlgorithms: return LeastSquaresLocalParallelAlgorithms() -@dataclass(frozen=True) class GradientBasedAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH fides: Type[Fides] = Fides @@ -3794,7 +3688,6 @@ def Scalar(self) -> GradientBasedScalarAlgorithms: return GradientBasedScalarAlgorithms() -@dataclass(frozen=True) class GradientFreeAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -3901,7 +3794,6 @@ def Scalar(self) -> GradientFreeScalarAlgorithms: return GradientFreeScalarAlgorithms() -@dataclass(frozen=True) class GlobalAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt gfo_differential_evolution: Type[GFODifferentialEvolution] = ( @@ -3991,7 +3883,6 @@ def Scalar(self) -> GlobalScalarAlgorithms: return GlobalScalarAlgorithms() -@dataclass(frozen=True) class LocalAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH fides: Type[Fides] = Fides @@ -4063,7 +3954,6 @@ def Scalar(self) -> LocalScalarAlgorithms: return LocalScalarAlgorithms() -@dataclass(frozen=True) class BoundedAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt fides: Type[Fides] = Fides @@ -4190,7 +4080,6 @@ def Scalar(self) -> BoundedScalarAlgorithms: return BoundedScalarAlgorithms() -@dataclass(frozen=True) class NonlinearConstrainedAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA @@ -4234,7 +4123,6 @@ def Scalar(self) -> NonlinearConstrainedScalarAlgorithms: return NonlinearConstrainedScalarAlgorithms() -@dataclass(frozen=True) class ScalarAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt fides: Type[Fides] = Fides @@ -4356,7 +4244,6 @@ def Parallel(self) -> ParallelScalarAlgorithms: return ParallelScalarAlgorithms() -@dataclass(frozen=True) class LeastSquaresAlgorithms(AlgoSelection): nag_dfols: Type[NagDFOLS] = NagDFOLS pounders: Type[Pounders] = Pounders @@ -4387,7 +4274,6 @@ def Parallel(self) -> LeastSquaresParallelAlgorithms: return LeastSquaresParallelAlgorithms() -@dataclass(frozen=True) class LikelihoodAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH @@ -4400,7 +4286,6 @@ def Local(self) -> LikelihoodLocalAlgorithms: return LikelihoodLocalAlgorithms() -@dataclass(frozen=True) class ParallelAlgorithms(AlgoSelection): neldermead_parallel: Type[NelderMeadParallel] = NelderMeadParallel nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim @@ -4459,7 +4344,6 @@ def Scalar(self) -> ParallelScalarAlgorithms: return ParallelScalarAlgorithms() -@dataclass(frozen=True) class Algorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt bhhh: Type[BHHH] = BHHH diff --git a/src/optimagic/batch_evaluators.py b/src/optimagic/batch_evaluators.py index 778562fe8..0f58c50bb 100644 --- a/src/optimagic/batch_evaluators.py +++ b/src/optimagic/batch_evaluators.py @@ -5,15 +5,6 @@ """ -from joblib import Parallel, delayed - -try: - from pathos.pools import ProcessPool - - pathos_is_available = True -except ImportError: - pathos_is_available = False - import threading from typing import Any, Callable, Literal, TypeVar, cast @@ -61,11 +52,14 @@ def pathos_mp_batch_evaluator( list: The function evaluations. """ - if not pathos_is_available: + # imported here to keep `import optimagic` fast + try: + from pathos.pools import ProcessPool + except ImportError as e: raise NotImplementedError( "To use the pathos_mp_batch_evaluator, install pathos with " "conda install -c conda-forge pathos." - ) + ) from e _check_inputs(func, arguments, n_cores, error_handling, unpack_symbol) n_cores = int(n_cores) @@ -144,6 +138,9 @@ def internal_func(*args: Any, **kwargs: Any) -> T: if n_cores == 1: res = [internal_func(arg) for arg in arguments] else: + # imported here to keep `import optimagic` fast + from joblib import Parallel, delayed + res = Parallel(n_jobs=n_cores)(delayed(internal_func)(arg) for arg in arguments) return res diff --git a/src/optimagic/benchmarking/get_benchmark_problems.py b/src/optimagic/benchmarking/get_benchmark_problems.py index 2986891ed..ad51da106 100644 --- a/src/optimagic/benchmarking/get_benchmark_problems.py +++ b/src/optimagic/benchmarking/get_benchmark_problems.py @@ -4,8 +4,6 @@ import numpy as np from optimagic import mark -from optimagic.benchmarking.cartis_roberts import CARTIS_ROBERTS_PROBLEMS -from optimagic.benchmarking.more_wild import MORE_WILD_PROBLEMS from optimagic.benchmarking.noise_distributions import NOISE_DISTRIBUTIONS from optimagic.shared.process_user_function import infer_aggregation_level from optimagic.typing import AggregationLevel @@ -133,9 +131,15 @@ def get_benchmark_problems( def _get_raw_problems(name): + # The problem sets are imported here to keep `import optimagic` fast. Importing + # the Cartis-Roberts problems imports numba, which takes about 0.2 seconds. + from optimagic.benchmarking.more_wild import MORE_WILD_PROBLEMS + if name == "more_wild": raw_problems = MORE_WILD_PROBLEMS elif name == "cartis_roberts": + from optimagic.benchmarking.cartis_roberts import CARTIS_ROBERTS_PROBLEMS + raw_problems = CARTIS_ROBERTS_PROBLEMS elif name == "example": subset = { @@ -190,6 +194,8 @@ def _get_raw_problems(name): "cube_5", "chebyquad_10", } + from optimagic.benchmarking.cartis_roberts import CARTIS_ROBERTS_PROBLEMS + raw_problems = {} for k, v in MORE_WILD_PROBLEMS.items(): if k in subset_mw: diff --git a/src/optimagic/config.py b/src/optimagic/config.py index 4eced1e4b..4d828348c 100644 --- a/src/optimagic/config.py +++ b/src/optimagic/config.py @@ -2,13 +2,24 @@ import importlib.util from pathlib import Path -import plotly.express as px - DOCS_DIR = Path(__file__).parent.parent / "docs" OPTIMAGIC_ROOT = Path(__file__).parent PLOTLY_TEMPLATE = "simple_white" -PLOTLY_PALETTE = px.colors.qualitative.Set2 + +# The rgb strings are the Plotly Set2 qualitative palette, i.e. +# plotly.express.colors.qualitative.Set2. Hardcoded because importing plotly.express +# is slow. +PLOTLY_PALETTE = [ + "rgb(102,194,165)", + "rgb(252,141,98)", + "rgb(141,160,203)", + "rgb(231,138,195)", + "rgb(166,216,84)", + "rgb(255,217,47)", + "rgb(229,196,148)", + "rgb(179,179,179)", +] # The hex strings are obtained from the Plotly D3 qualitative palette. DEFAULT_PALETTE = [ diff --git a/src/optimagic/differentiation/richardson_extrapolation.py b/src/optimagic/differentiation/richardson_extrapolation.py index a22319cb9..caa75370e 100644 --- a/src/optimagic/differentiation/richardson_extrapolation.py +++ b/src/optimagic/differentiation/richardson_extrapolation.py @@ -1,7 +1,8 @@ import numpy as np -from scipy import stats -from scipy.linalg import pinv -from scipy.ndimage import convolve1d + +# The 0.975 quantile of the t-distribution with one degree of freedom, i.e. +# scipy.stats.t(df=1).ppf(0.975). Hardcoded because importing scipy.stats is slow. +T_QUANTILE = 12.706204736174694 def richardson_extrapolation(sequence, steps, method="central", num_terms=None): @@ -70,6 +71,9 @@ def richardson_extrapolation(sequence, steps, method="central", num_terms=None): order, ) + # imported here to keep `import optimagic` fast + from scipy.ndimage import convolve1d + new_sequence = convolve1d( input=sequence, weights=richardson_coef[::-1], axis=0, origin=num_terms // 2 ) @@ -136,6 +140,9 @@ def _richardson_coefficients(num_terms, step_ratio, exponentiation_step, order): rows @ (exponentiation_step * cols + order) ) + # imported here to keep `import optimagic` fast + from scipy.linalg import pinv + coef = pinv(coef_mat)[0] return coef @@ -161,11 +168,10 @@ def _estimate_error(new_seq, old_seq, richardson_coef): """ eps = np.finfo(float).eps - t_quantile = stats.t(df=1).ppf(0.975) # 12.7062047361747 in numdifftools new_seq_len = new_seq.shape[0] unnormalized_covariance = np.sum(richardson_coef**2) - fact = np.maximum(t_quantile * np.sqrt(unnormalized_covariance), eps * 10.0) + fact = np.maximum(T_QUANTILE * np.sqrt(unnormalized_covariance), eps * 10.0) if new_seq_len <= 1: delta = np.diff(old_seq, axis=0) diff --git a/src/optimagic/logging/logger.py b/src/optimagic/logging/logger.py index 3ea9787b8..f0a197160 100644 --- a/src/optimagic/logging/logger.py +++ b/src/optimagic/logging/logger.py @@ -3,13 +3,10 @@ import os from abc import ABC, abstractmethod from pathlib import Path -from typing import Any, Generic, Type, TypeVar, cast +from typing import TYPE_CHECKING, Any, Generic, Type, TypeVar, cast import numpy as np import pandas as pd -import sqlalchemy as sql -import sqlalchemy.event -from sqlalchemy.engine import Engine from optimagic.logging.base import ( NonUpdatableKeyValueStore, @@ -40,6 +37,11 @@ PyTree, ) +# sqlalchemy takes about 0.15 seconds to import. To keep `import optimagic` fast, it +# is only imported inside the functions that use it. +if TYPE_CHECKING: + from sqlalchemy.engine import Engine + class LogOptions: """Base class for defining different log options. @@ -417,6 +419,8 @@ def path(self) -> str | Path: return self._path def create_engine(self) -> Engine: + import sqlalchemy as sql + engine = sql.create_engine(self.url) self._configure_engine(engine) return engine @@ -435,6 +439,8 @@ def _configure_engine(self, engine: Engine) -> None: it also uses unsafe optimizations. """ + import sqlalchemy as sql + import sqlalchemy.event @sql.event.listens_for(engine, "connect") def do_connect(dbapi_connection: Any, connection_record: Any) -> None: # noqa: ARG001 diff --git a/src/optimagic/logging/sqlalchemy.py b/src/optimagic/logging/sqlalchemy.py index c7b21ee65..73fd92fcc 100644 --- a/src/optimagic/logging/sqlalchemy.py +++ b/src/optimagic/logging/sqlalchemy.py @@ -4,14 +4,7 @@ import warnings from dataclasses import asdict, dataclass from functools import cached_property -from typing import Any, Sequence, Type, cast - -import sqlalchemy as sql -import sqlalchemy.event -from sqlalchemy import Column, Integer, PickleType, Row, String -from sqlalchemy.engine.base import Engine -from sqlalchemy.sql.base import Executable -from sqlalchemy.sql.schema import MetaData +from typing import TYPE_CHECKING, Any, Sequence, Type, cast from optimagic.logging.base import ( InputType, @@ -29,6 +22,15 @@ StepResultWithId, ) +# sqlalchemy takes about 0.15 seconds to import. To keep `import optimagic` fast, it +# is only imported inside the functions that use it. +if TYPE_CHECKING: + import sqlalchemy as sql + from sqlalchemy import Column, Row + from sqlalchemy.engine.base import Engine + from sqlalchemy.sql.base import Executable + from sqlalchemy.sql.schema import MetaData + class SQLAlchemyConfig: """Configuration class for setting up an SQLAlchemy engine and metadata. @@ -55,6 +57,8 @@ def metadata(self) -> MetaData: The SQLAlchemy MetaData object reflecting the database schema. """ + from sqlalchemy.sql.schema import MetaData + engine = self.create_engine() metadata = MetaData() self._configure_reflect() @@ -69,6 +73,8 @@ def create_engine(self) -> Engine: An SQLAlchemy Engine object. """ + import sqlalchemy as sql + return sql.create_engine(self.url) @staticmethod @@ -78,6 +84,8 @@ def _configure_reflect() -> None: Code ist taken from the documentation: https://tinyurl.com/y7q287jr """ + import sqlalchemy as sql + import sqlalchemy.event @sql.event.listens_for(sql.Table, "column_reflect") def _setup_pickletype( @@ -120,6 +128,8 @@ def create_table(self, metadata: MetaData, engine: Engine) -> sql.Table: The SQLAlchemy Table object representing the created or reflected table. """ + import sqlalchemy as sql + metadata.reflect(engine) table = sql.Table( self.table_name, metadata, *self.columns, extend_existing=True @@ -234,6 +244,8 @@ def __init__( input_type: Type[InputType], output_type: Type[OutputType], ): + import sqlalchemy as sql + super().__init__(input_type, output_type, primary_key) columns = [ sql.Column(primary_key, sql.Integer, primary_key=True, autoincrement=True), @@ -423,6 +435,8 @@ def __init__( self, db_config: SQLAlchemyConfig, ): + from sqlalchemy import Column, Integer, String + columns = [ Column(self._PRIMARY_KEY, Integer, primary_key=True, autoincrement=True), Column("type", String), # e.g. optimization @@ -433,7 +447,7 @@ def __init__( table_config = TableConfig( self._TABLE_NAME, - cast(list[Column[Any]], columns), + cast("list[Column[Any]]", columns), self._PRIMARY_KEY, ) @@ -464,6 +478,8 @@ def __init__( self, db_config: SQLAlchemyConfig, ): + from sqlalchemy import Column, Integer, PickleType, String + columns = [ Column(self._PRIMARY_KEY, Integer, primary_key=True, autoincrement=True), Column("direction", String), @@ -472,7 +488,7 @@ def __init__( table_config = TableConfig( self._TABLE_NAME, - cast(list[Column[Any]], columns), + cast("list[Column[Any]]", columns), self._PRIMARY_KEY, ) diff --git a/src/optimagic/mark.py b/src/optimagic/mark.py index f6d7b7ec4..6c43e91a1 100644 --- a/src/optimagic/mark.py +++ b/src/optimagic/mark.py @@ -77,9 +77,9 @@ def minimizer( ) -> Callable[[AlgorithmSubclass], AlgorithmSubclass]: """Mark an algorithm as a optimagic minimizer and add AlgoInfo. - The decorated class is re-created as a pydantic dataclass, so algorithm options - are validated and converted according to their type annotations whenever an - instance is created. + The decorated class gets an ``__init__`` that uses pydantic to validate and convert + the algorithm options according to their type annotations whenever an instance is + created. Args: name: The name of the algorithm as a string. Used in error messages, warnings diff --git a/src/optimagic/optimization/multistart.py b/src/optimagic/optimization/multistart.py index 47ec38c2a..b6182f66a 100644 --- a/src/optimagic/optimization/multistart.py +++ b/src/optimagic/optimization/multistart.py @@ -17,7 +17,6 @@ import numpy as np from numpy.typing import NDArray -from scipy.stats import qmc, triang from optimagic.logging.logger import LogStore from optimagic.logging.types import StepStatus @@ -244,6 +243,9 @@ def _draw_exploration_sample( values. """ + # imported here to keep `import optimagic` fast + from scipy.stats import qmc, triang + if lower is None or upper is None: raise ValueError("lower and upper bounds must be provided for multistart.") diff --git a/src/optimagic/optimization/optimize.py b/src/optimagic/optimization/optimize.py index 1e82b6fe6..476b90682 100644 --- a/src/optimagic/optimization/optimize.py +++ b/src/optimagic/optimization/optimize.py @@ -15,12 +15,11 @@ from __future__ import annotations from pathlib import Path -from typing import Any, Callable, Literal, Sequence, Type, cast +from typing import TYPE_CHECKING, Any, Callable, Literal, Sequence, Type, cast import numpy as np import pandas as pd from numpy.typing import NDArray -from scipy.optimize import Bounds as ScipyBounds from optimagic.batch_evaluators import process_batch_evaluator from optimagic.constraints import Constraint, NonlinearConstraint @@ -75,6 +74,9 @@ PyTreeNamespace, ) +if TYPE_CHECKING: + from scipy.optimize import Bounds as ScipyBounds + FunType = Callable[..., float | PyTree | FunctionValue] AlgorithmType = str | Algorithm | Type[Algorithm] ConstraintsType = Constraint | dict[str, Any] | Sequence[Constraint | dict[str, Any]] diff --git a/src/optimagic/optimizers/bayesian_optimizer.py b/src/optimagic/optimizers/bayesian_optimizer.py index d33096ff3..66578f974 100644 --- a/src/optimagic/optimizers/bayesian_optimizer.py +++ b/src/optimagic/optimizers/bayesian_optimizer.py @@ -7,7 +7,6 @@ import numpy as np from numpy.typing import NDArray -from scipy.optimize import NonlinearConstraint from optimagic import mark from optimagic.config import IS_BAYESOPT_INSTALLED_AND_VERSION_NEWER_THAN_2 @@ -30,6 +29,7 @@ if TYPE_CHECKING: from bayes_opt import BayesianOptimization from bayes_opt.acquisition import AcquisitionFunction + from scipy.optimize import NonlinearConstraint else: # AcquisitionFunction is used in field annotations, which pydantic resolves at # runtime, so it needs a fallback that works without bayes_opt and avoids diff --git a/src/optimagic/optimizers/ipopt.py b/src/optimagic/optimizers/ipopt.py index 4b0cade7d..826cc5f20 100644 --- a/src/optimagic/optimizers/ipopt.py +++ b/src/optimagic/optimizers/ipopt.py @@ -3,11 +3,10 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Any, Literal +from typing import TYPE_CHECKING, Any, Literal import numpy as np from numpy.typing import NDArray -from scipy.optimize import Bounds as ScipyBounds from optimagic import mark from optimagic.config import IS_CYIPOPT_INSTALLED @@ -32,6 +31,9 @@ YesNoBool, ) +if TYPE_CHECKING: + from scipy.optimize import Bounds as ScipyBounds + @mark.minimizer( name="ipopt", @@ -2171,6 +2173,9 @@ def _solve_internal_problem( def _get_scipy_bounds(bounds: InternalBounds) -> ScipyBounds: + # imported here to keep `import optimagic` fast + from scipy.optimize import Bounds as ScipyBounds + return ScipyBounds(lb=bounds.lower, ub=bounds.upper) diff --git a/src/optimagic/optimizers/pounders.py b/src/optimagic/optimizers/pounders.py index c295b0d40..972cb4500 100644 --- a/src/optimagic/optimizers/pounders.py +++ b/src/optimagic/optimizers/pounders.py @@ -15,23 +15,6 @@ from optimagic.optimization.internal_optimization_problem import ( InternalOptimizationProblem, ) -from optimagic.optimizers._pounders.pounders_auxiliary import ( - add_accepted_point_to_residual_model, - add_geomtery_points_to_make_main_model_fully_linear, - create_initial_residual_model, - create_main_from_residual_model, - evaluate_residual_model, - find_affine_points, - fit_residual_model, - get_feature_matrices_residual_model, - get_last_model_indices_and_check_for_repeated_model, - solve_subproblem, - update_main_model_with_new_accepted_x, - update_residual_model, - update_residual_model_with_new_accepted_x, - update_trustregion_radius, -) -from optimagic.optimizers._pounders.pounders_history import LeastSquaresHistory from optimagic.typing import ( AggregationLevel, NonNegativeFloat, @@ -461,6 +444,26 @@ def internal_solve_pounders( before reaching maxiter. """ + # The helpers import scipy.linalg and scipy.optimize, which are slow to import. + # They are imported here to keep `import optimagic` fast. + from optimagic.optimizers._pounders.pounders_auxiliary import ( + add_accepted_point_to_residual_model, + add_geomtery_points_to_make_main_model_fully_linear, + create_initial_residual_model, + create_main_from_residual_model, + evaluate_residual_model, + find_affine_points, + fit_residual_model, + get_feature_matrices_residual_model, + get_last_model_indices_and_check_for_repeated_model, + solve_subproblem, + update_main_model_with_new_accepted_x, + update_residual_model, + update_residual_model_with_new_accepted_x, + update_trustregion_radius, + ) + from optimagic.optimizers._pounders.pounders_history import LeastSquaresHistory + history = LeastSquaresHistory() n = len(x0) diff --git a/src/optimagic/optimizers/scipy_optimizers.py b/src/optimagic/optimizers/scipy_optimizers.py index 8967db1b0..590029dfa 100644 --- a/src/optimagic/optimizers/scipy_optimizers.py +++ b/src/optimagic/optimizers/scipy_optimizers.py @@ -37,15 +37,10 @@ import functools from dataclasses import dataclass -from typing import Any, Callable, List, Literal, SupportsInt, Tuple +from typing import TYPE_CHECKING, Any, Callable, List, Literal, SupportsInt, Tuple import numpy as np -import scipy -import scipy.optimize from numpy.typing import NDArray -from scipy.optimize import Bounds as ScipyBounds -from scipy.optimize import NonlinearConstraint -from scipy.optimize import OptimizeResult as ScipyOptimizeResult from optimagic import mark from optimagic.batch_evaluators import process_batch_evaluator @@ -85,6 +80,12 @@ ) from optimagic.utilities import calculate_trustregion_initial_radius +# scipy.optimize takes about 0.3 seconds to import. To keep `import optimagic` fast, it +# is only imported inside the functions that use it. +if TYPE_CHECKING: + from scipy.optimize import Bounds as ScipyBounds + from scipy.optimize import OptimizeResult as ScipyOptimizeResult + @mark.minimizer( name="scipy_lbfgsb", @@ -181,6 +182,8 @@ def _solve_internal_problem( "maxiter": self.stopping_maxiter, "maxls": self.max_line_search_steps, } + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun_and_jac, x0=x0, @@ -253,6 +256,8 @@ def _solve_internal_problem( "ftol": self.convergence_ftol_abs, "disp": self.display, } + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun_and_jac, x0=x0, @@ -359,6 +364,8 @@ def _solve_internal_problem( "adaptive": self.adaptive, "disp": self.display, } + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun, x0=x0, @@ -464,6 +471,8 @@ def _solve_internal_problem( "maxiter": self.stopping_maxiter, "disp": self.display, } + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun, x0=x0, @@ -594,6 +603,8 @@ def _solve_internal_problem( "c1": self.armijo_condition, "c2": self.curvature_condition, } + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun_and_jac, x0=x0, method="BFGS", jac=True, options=options ) @@ -677,6 +688,8 @@ def _solve_internal_problem( "norm": self.norm, "disp": self.display, } + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun_and_jac, x0=x0, method="CG", jac=True, options=options ) @@ -764,6 +777,8 @@ def _solve_internal_problem( "maxiter": self.stopping_maxiter, "disp": self.display, } + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun_and_jac, x0=x0, @@ -873,6 +888,8 @@ def _solve_internal_problem( problem.nonlinear_constraints ) + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun, x0=x0, @@ -992,6 +1009,8 @@ def _solve_internal_problem( lower_bounds = -np.inf if problem.bounds.lower is None else problem.bounds.lower upper_bounds = np.inf if problem.bounds.upper is None else problem.bounds.upper + import scipy.optimize + raw_res = scipy.optimize.least_squares( fun=problem.fun, x0=x0, @@ -1114,6 +1133,8 @@ def _solve_internal_problem( lower_bounds = -np.inf if problem.bounds.lower is None else problem.bounds.lower upper_bounds = np.inf if problem.bounds.upper is None else problem.bounds.upper + import scipy.optimize + raw_res = scipy.optimize.least_squares( fun=problem.fun, x0=x0, @@ -1200,6 +1221,8 @@ class ScipyLSLM(Algorithm): def _solve_internal_problem( self, problem: InternalOptimizationProblem, x0: NDArray[np.float64] ) -> InternalOptimizeResult: + import scipy.optimize + raw_res = scipy.optimize.least_squares( fun=problem.fun, x0=x0, @@ -1374,6 +1397,8 @@ def _solve_internal_problem( "disp": self.display, } + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun_and_jac, x0=x0, @@ -1506,6 +1531,8 @@ def _solve_internal_problem( problem.nonlinear_constraints ) + import scipy.optimize + raw_res = scipy.optimize.minimize( fun=problem.fun_and_jac, jac=True, @@ -1564,6 +1591,8 @@ def _internal_to_scipy_constraint(c): lower, upper = -c["tol"], c["tol"] else: lower, upper = 0.0, np.inf + from scipy.optimize import NonlinearConstraint + new_constr = NonlinearConstraint( fun=c["fun"], lb=np.full(c["n_constr"], lower), @@ -1747,6 +1776,8 @@ def _solve_internal_problem( } minimizer_kwargs = {**minimizer_kwargs, **local_algo_options} + import scipy.optimize + res = scipy.optimize.basinhopping( func=problem.fun, x0=x0, @@ -1846,6 +1877,8 @@ def _solve_internal_problem( """Global algorithms like scipy_brute need finite bounds for all parameters""" ) + import scipy.optimize + raw_res = scipy.optimize.brute( func=problem.fun, ranges=tuple(zip(problem.bounds.lower, problem.bounds.upper, strict=True)), @@ -2045,6 +2078,8 @@ def _solve_internal_problem( self, problem: InternalOptimizationProblem, x0: NDArray[np.float64] ) -> InternalOptimizeResult: workers = _get_workers(self.n_cores, self.batch_evaluator) + import scipy.optimize + res = scipy.optimize.differential_evolution( func=problem.fun, bounds=_get_scipy_bounds(problem.bounds), @@ -2296,6 +2331,8 @@ def _solve_internal_problem( else: options_used = options + import scipy.optimize + res = scipy.optimize.shgo( func=problem.fun, bounds=_get_scipy_bounds(problem.bounds), @@ -2466,6 +2503,8 @@ def _solve_internal_problem( minimizer_kwargs = {**default_minimizer_kwargs, **local_algo_options} + import scipy.optimize + res = scipy.optimize.dual_annealing( func=problem.fun, bounds=_get_scipy_bounds(problem.bounds), @@ -2603,6 +2642,8 @@ class ScipyDirect(Algorithm): def _solve_internal_problem( self, problem: InternalOptimizationProblem, x0: NDArray[np.float64] ) -> InternalOptimizeResult: + import scipy.optimize + res = scipy.optimize.direct( func=problem.fun, bounds=_get_scipy_bounds(problem.bounds), @@ -2633,6 +2674,8 @@ def _get_scipy_bounds(bounds: InternalBounds) -> ScipyBounds | None: if bounds.lower is None and bounds.upper is None: return None + from scipy.optimize import Bounds as ScipyBounds + lower = bounds.lower if bounds.lower is not None else -np.inf upper = bounds.upper if bounds.upper is not None else np.inf return ScipyBounds(lb=lower, ub=upper) diff --git a/src/optimagic/parameters/bounds.py b/src/optimagic/parameters/bounds.py index a4075cb75..b17781384 100644 --- a/src/optimagic/parameters/bounds.py +++ b/src/optimagic/parameters/bounds.py @@ -1,11 +1,11 @@ from __future__ import annotations +import sys from dataclasses import dataclass -from typing import Any, Sequence +from typing import TYPE_CHECKING, Any, Sequence import numpy as np from numpy.typing import NDArray -from scipy.optimize import Bounds as ScipyBounds from optimagic.exceptions import InvalidBoundsError from optimagic.pytree import ( @@ -16,6 +16,9 @@ from optimagic.typing import PyTree, PyTreeNamespace from optimagic.utilities import fast_numpy_full +if TYPE_CHECKING: + from scipy.optimize import Bounds as ScipyBounds + @dataclass(frozen=True) class Bounds: @@ -44,9 +47,15 @@ def pre_process_bounds( the correct type. """ - if isinstance(bounds, ScipyBounds): - bounds = Bounds(lower=bounds.lb, upper=bounds.ub) - elif isinstance(bounds, Bounds) or bounds is None: + # Bounds can only be scipy bounds if scipy.optimize has already been imported. + # Checking this first avoids the slow import of scipy.optimize. + if "scipy.optimize" in sys.modules: + from scipy.optimize import Bounds as ScipyBounds + + if isinstance(bounds, ScipyBounds): + return Bounds(lower=bounds.lb, upper=bounds.ub) + + if isinstance(bounds, Bounds) or bounds is None: pass else: try: diff --git a/src/optimagic/typing.py b/src/optimagic/typing.py index 48a50fdc2..d90184b90 100644 --- a/src/optimagic/typing.py +++ b/src/optimagic/typing.py @@ -1,8 +1,8 @@ import functools -import typing from dataclasses import dataclass, fields from enum import Enum, StrEnum from typing import ( + TYPE_CHECKING, Annotated, Any, Callable, @@ -20,6 +20,10 @@ import pydantic from annotated_types import Ge, Gt, Le, Lt from numpy._typing import NDArray +from pydantic_core import ArgsKwargs, SchemaValidator + +if TYPE_CHECKING: + from pydantic.plugin._schema_validator import PluggableSchemaValidator PyTree = Any Scalar = Any @@ -171,21 +175,28 @@ def validated_dataclass( ) -> Callable[[type[DataclassT]], type[DataclassT]]: """Create a class decorator that adds pydantic validation to a frozen dataclass. - The decorated class is re-created as a pydantic dataclass, so field values are - validated and converted according to their type annotations on every + The ``__init__`` of the decorated class is replaced by one that validates and + converts the field values according to their type annotations on every instantiation (including via ``dataclasses.replace``). Annotations are resolved at runtime, so this also works in modules using ``from __future__ import annotations``. + The pydantic validator of a class is only built when the class is instantiated + for the first time. Building it takes about one millisecond per class, which + would add up to a noticeable share of the import time of optimagic if it was + done for all algorithm classes when they are defined. + This is deliberately a layer on top of existing dataclasses rather than a replacement for ``pydantic.dataclasses.dataclass`` at the definition site, for - two reasons. First, it keeps the classes themselves plain frozen dataclasses, + three reasons. First, it keeps the classes themselves plain frozen dataclasses, which made adopting pydantic non-breaking: algorithm classes — including ones defined outside optimagic — are still written as regular dataclasses and gain validation through ``mark.minimizer`` without any change to their definition. Second, it raises domain-specific exceptions (built by ``make_error``) instead of ``pydantic.ValidationError``, which preserves optimagic's exception contracts; pydantic itself has no hook to customize the raised exception type. + Third, pydantic dataclasses collect their fields when the class is defined, + which is slow even if building the validator is deferred. Args: config: The pydantic config that controls validation behavior. @@ -198,26 +209,51 @@ def validated_dataclass( """ def decorator(cls: type[DataclassT]) -> type[DataclassT]: - out = pydantic.dataclasses.dataclass(frozen=True, config=config)(cls) - # pydantic re-creates the class, which loses attributes that tooling and - # introspection rely on. - out.__doc__ = cls.__doc__ - out.__annotations__ = dict(cls.__annotations__) - original_init = out.__init__ - - @functools.wraps(original_init) + # pydantic reads the config of a standard dataclass from this attribute. + cls.__pydantic_config__ = config # ty:ignore[unresolved-attribute] + lazy_validator = _LazyValidator(cls) + + @functools.wraps(cls.__init__) def __init__(self: Any, *args: Any, **kwargs: Any) -> None: try: - original_init(self, *args, **kwargs) + # With self_instance, the validated field values are set on self + # instead of on a new instance. This is how the __init__ of a + # pydantic dataclass works. + lazy_validator.validator.validate_python( + ArgsKwargs(args, kwargs), self_instance=self + ) except pydantic.ValidationError as e: raise make_error(e) from e - out.__init__ = __init__ - return typing.cast("type[DataclassT]", out) + cls.__init__ = __init__ # ty:ignore[invalid-assignment] + return cls return decorator +class _LazyValidator: + """Build the pydantic validator of a dataclass when it is first needed.""" + + def __init__(self, cls: type) -> None: + self._cls = cls + + @functools.cached_property + def validator(self) -> "SchemaValidator | PluggableSchemaValidator": + """The pydantic validator of the dataclass.""" + return pydantic.TypeAdapter(self._cls).validator + + def __getstate__(self) -> dict[str, Any]: + """Build the validator before pickling. + + cloudpickle pickles classes that are defined in a script or notebook by value + and does not preserve the identity of ``dataclasses.MISSING``. pydantic cannot + build a validator from the fields of such an unpickled dataclass, so the + validator has to be part of the pickled state. + + """ + return {"_cls": self._cls, "validator": self.validator} + + @dataclass(frozen=True) class IterationHistory(DictLikeAccess): """History of iterations in a process.""" diff --git a/src/optimagic/utilities.py b/src/optimagic/utilities.py index c86f560e6..879eac8b8 100644 --- a/src/optimagic/utilities.py +++ b/src/optimagic/utilities.py @@ -6,7 +6,6 @@ import numpy as np import pandas as pd from numpy.typing import NDArray -from scipy.linalg import ldl, qr with warnings.catch_warnings(): warnings.simplefilter("ignore", category=UserWarning) @@ -235,6 +234,9 @@ def _internal_robust_cholesky(matrix, threshold): *threshold*. """ + # imported here to keep `import optimagic` fast + from scipy.linalg import ldl, qr + lu, d, _ = ldl(matrix) diags = np.diagonal(d).copy() diff --git a/src/optimagic/visualization/deviation_plot.py b/src/optimagic/visualization/deviation_plot.py index 2f8ee9130..bb820e3de 100644 --- a/src/optimagic/visualization/deviation_plot.py +++ b/src/optimagic/visualization/deviation_plot.py @@ -1,5 +1,4 @@ import pandas as pd -import plotly.express as px from optimagic.benchmarking.process_benchmark_results import ( process_benchmark_results, @@ -76,6 +75,9 @@ def deviation_plot( .mean(numeric_only=True)[outcome] .reset_index() ) + # imported here because importing plotly.express is slow + import plotly.express as px + fig = px.line(average_deviations, x=runtime_measure, y=outcome, color="algorithm") y_labels = { diff --git a/src/optimagic/visualization/slice_plot_3d.py b/src/optimagic/visualization/slice_plot_3d.py index f83439619..bcac6a944 100644 --- a/src/optimagic/visualization/slice_plot_3d.py +++ b/src/optimagic/visualization/slice_plot_3d.py @@ -4,7 +4,6 @@ from functools import partial import numpy as np -import plotly.express as px import plotly.graph_objects as go from numpy.typing import NDArray from plotly.subplots import make_subplots @@ -499,6 +498,9 @@ def plot_line( go.Figure: A Plotly figure object containing the line plot. """ + # imported here because importing plotly.express is slow + import plotly.express as px + fig = px.line(x=x, y=y, **plot_kwargs["line_plot"]) if plot_kwargs["scatter_plot"] is not None: fig.add_trace( diff --git a/tests/optimagic/parameters/test_bounds.py b/tests/optimagic/parameters/test_bounds.py index ac71de549..164b7fbcc 100644 --- a/tests/optimagic/parameters/test_bounds.py +++ b/tests/optimagic/parameters/test_bounds.py @@ -39,6 +39,17 @@ def test_pre_process_bounds_none_case(): assert pre_process_bounds(None) is None +def test_pre_process_bounds_scipy_bounds(): + from scipy.optimize import Bounds as ScipyBounds + + got = pre_process_bounds(ScipyBounds(lb=np.array([0, 1]), ub=np.array([2, 3]))) + assert isinstance(got, Bounds) + assert_array_equal(got.lower, np.array([0, 1])) + assert_array_equal(got.upper, np.array([2, 3])) + assert got.soft_lower is None + assert got.soft_upper is None + + def test_pre_process_bounds_sequence(): got = pre_process_bounds([(0, 1), (None, 1)]) expected = Bounds(lower=[0, -np.inf], upper=[1, 1]) diff --git a/tests/optimagic/test_algo_selection.py b/tests/optimagic/test_algo_selection.py index 31906c7c5..e76367fc2 100644 --- a/tests/optimagic/test_algo_selection.py +++ b/tests/optimagic/test_algo_selection.py @@ -1,4 +1,9 @@ +from dataclasses import FrozenInstanceError + +import pytest + from optimagic import algos +from optimagic.optimizers.scipy_optimizers import ScipyDifferentialEvolution def test_dfols_is_present(): @@ -30,3 +35,26 @@ def test_algorithm_lists(): assert len(algos.All) >= len(algos.Available) assert len(algos.AllNames) == len(algos.All) assert len(algos.AvailableNames) == len(algos.Available) + + +def test_selection_cannot_be_modified(): + with pytest.raises(FrozenInstanceError): + algos.scipy_lbfgsb = None # ty:ignore[invalid-assignment] + with pytest.raises(FrozenInstanceError): + del algos.scipy_lbfgsb + + +def test_selections_of_the_same_categories_are_equal(): + assert algos.Bounded.Local == algos.Local.Bounded + assert algos.Bounded != algos.Local + assert len({algos.Bounded.Local, algos.Local.Bounded, algos.Local}) == 2 + + +def test_selection_repr_lists_the_algorithms(): + selection = algos.Bounded.Global.NonlinearConstrained.Parallel.Scalar + assert selection.All == [ScipyDifferentialEvolution] + expected = ( + "BoundedGlobalNonlinearConstrainedParallelScalarAlgorithms(" + "scipy_differential_evolution)" + ) + assert repr(selection) == expected diff --git a/tests/optimagic/test_batch_evaluators.py b/tests/optimagic/test_batch_evaluators.py index d71791ede..ccbf9b334 100644 --- a/tests/optimagic/test_batch_evaluators.py +++ b/tests/optimagic/test_batch_evaluators.py @@ -1,9 +1,13 @@ import itertools +import sys import warnings import pytest -from optimagic.batch_evaluators import process_batch_evaluator +from optimagic.batch_evaluators import ( + pathos_mp_batch_evaluator, + process_batch_evaluator, +) batch_evaluators = ["joblib", "threading"] @@ -99,6 +103,13 @@ def test_batch_evaluator_with_dict_unpacking(batch_evaluator, n_cores): assert calculated == expected +def test_pathos_batch_evaluator_raises_if_pathos_is_not_installed(monkeypatch): + # A None entry in sys.modules makes the import fail, as if pathos was missing. + monkeypatch.setitem(sys.modules, "pathos.pools", None) + with pytest.raises(NotImplementedError, match="install pathos"): + pathos_mp_batch_evaluator(double, arguments=[1, 2], n_cores=1) + + def test_get_batch_evaluator_invalid_value(): with pytest.raises(ValueError): process_batch_evaluator("bla") # ty:ignore[invalid-argument-type] diff --git a/tests/optimagic/test_import.py b/tests/optimagic/test_import.py new file mode 100644 index 000000000..118bb9353 --- /dev/null +++ b/tests/optimagic/test_import.py @@ -0,0 +1,35 @@ +"""Test that importing optimagic stays fast. + +Importing optimagic must not import packages that are slow to import and only needed +for some features. Those are imported inside the functions that use them. + +""" + +import subprocess +import sys + +SLOW_MODULES = [ + "altair", + "bokeh", + "joblib", + "matplotlib", + "numba", + "plotly.express", + "scipy", + "sqlalchemy", +] + + +def test_import_does_not_import_slow_modules(): + code = "import optimagic, sys; print('\\n'.join(sys.modules))" + out = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=True + ) + imported = set(out.stdout.split()) + + unexpected = { + name + for name in imported + if any(name == slow or name.startswith(f"{slow}.") for slow in SLOW_MODULES) + } + assert not unexpected, f"`import optimagic` imported slow modules: {unexpected}" diff --git a/tests/optimagic/test_typing.py b/tests/optimagic/test_typing.py index cac1512b4..0195ca35f 100644 --- a/tests/optimagic/test_typing.py +++ b/tests/optimagic/test_typing.py @@ -5,8 +5,12 @@ """ +import pickle +import subprocess +import sys from dataclasses import FrozenInstanceError, dataclass, replace +import cloudpickle import pydantic import pytest @@ -14,6 +18,7 @@ DEFAULT_PYDANTIC_CONFIG, STRICT_PYDANTIC_CONFIG, PositiveInt, + _LazyValidator, validated_dataclass, ) @@ -136,3 +141,59 @@ def test_strict_config_rejects_values_that_need_conversion(): StrictOptions(n_points="2") # ty:ignore[invalid-argument-type] with pytest.raises(CustomError): StrictOptions(label=3) # ty:ignore[invalid-argument-type] + + +def test_decorated_class_is_not_replaced(): + @dataclass(frozen=True) + class Plain: + n_points: PositiveInt = 1 + + decorator = validated_dataclass( + config=DEFAULT_PYDANTIC_CONFIG, make_error=_make_error + ) + assert decorator(Plain) is Plain + + +def test_validator_is_only_built_when_it_is_needed(): + lazy_validator = _LazyValidator(Options) + assert "validator" not in vars(lazy_validator) + lazy_validator.validator # noqa: B018 + assert "validator" in vars(lazy_validator) + + +def test_pickled_lazy_validator_contains_the_validator(): + restored = pickle.loads(pickle.dumps(_LazyValidator(Options))) + assert "validator" in vars(restored) + + +@pytest.mark.parametrize("instantiate_before_pickling", [True, False]) +def test_class_that_is_pickled_by_value_validates_in_other_process( + instantiate_before_pickling, +): + # cloudpickle pickles classes that are defined inside of functions by value, as + # it does for classes that are defined in a script or notebook. This is what + # happens to user defined algorithms in parallel optimizations. + @validated_dataclass(config=DEFAULT_PYDANTIC_CONFIG, make_error=ValueError) + @dataclass(frozen=True) + class Local: + n_points: PositiveInt = 1 + + if instantiate_before_pickling: + Local() + + code = """ +import pickle, sys +cls = pickle.loads(sys.stdin.buffer.read()) +assert cls(n_points="2").n_points == 2 +try: + cls(n_points=0) +except ValueError: + print("validated") +""" + out = subprocess.run( + [sys.executable, "-c", code], + input=cloudpickle.dumps(Local), + capture_output=True, + check=True, + ) + assert out.stdout.decode().strip() == "validated" From 12650d64ea4a16adc204ca9451089389a35fea0c Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Mon, 23 Nov 2026 10:48:49 +0100 Subject: [PATCH 2/2] Import benchmark sets lazily and raise the minimum pydantic version to 2.10. - Each benchmark set has its own getter in the module that defines its problems, and get_benchmark_problems imports only the getters of the requested set. - Raise the minimum supported pydantic version to 2.10. Older versions do not validate the numpy array fields of InternalOptimizeResult and cannot pickle the validators with the standard pickle module. - Test that subclasses of algorithms can be decorated with mark.minimizer. Co-Authored-By: Claude Opus 5.5 --- CHANGES.md | 4 +- pixi.lock | 2 +- pyproject.toml | 4 +- src/optimagic/benchmarking/cartis_roberts.py | 12 ++ .../benchmarking/get_benchmark_problems.py | 162 ++++++++++-------- src/optimagic/benchmarking/more_wild.py | 12 ++ .../test_algo_option_validation.py | 34 ++++ ...test_algo_option_validation_stringified.py | 34 ++++ 8 files changed, 186 insertions(+), 78 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f533e7468..bae96df47 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -14,8 +14,8 @@ This release adds experimental support for **SciPy-style callbacks**, replaces p 0.6 seconds. Dependencies that are only needed for some features (scipy, numba, sqlalchemy, plotly.express and joblib) are imported when they are used, the validators of algorithm options are built when an algorithm is instantiated for the - first time and the classes behind `om.algos` are no longer dataclasses - ({ghuser}`janosg`). + first time and the classes behind `om.algos` are no longer dataclasses. The minimum + supported version of pydantic is now 2.10 ({ghuser}`janosg`). - {gh}`739` Fixes `tao_pounders` ignoring `convergence_gtol_abs`, `convergence_gtol_rel` and `convergence_gtol_scaled`. Reaching `stopping_maxiter` is now reported as unsuccessful with the message "maxits reached" instead of as diff --git a/pixi.lock b/pixi.lock index b01f56ed4..b51172f67 100644 --- a/pixi.lock +++ b/pixi.lock @@ -25152,7 +25152,7 @@ packages: - optree>=0.19 - pandas>=2.1 - plotly>=5.14 - - pydantic>=2.6 + - pydantic>=2.10 - scipy>=1.11 - sqlalchemy>=2.0 - typing-extensions>=4.5 diff --git a/pyproject.toml b/pyproject.toml index 4d754a497..ad927ca33 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ "scipy>=1.11", "sqlalchemy>=2.0", "annotated-types>=0.4", - "pydantic>=2.6", + "pydantic>=2.10", "typing-extensions>=4.5", "optree>=0.19", ] @@ -404,7 +404,7 @@ bokeh = ">=3.2" altair = ">=5.1" seaborn = ">=0.13" pyyaml = ">=6.0.1" -pydantic = ">=2.6" +pydantic = ">=2.10" jinja2 = ">=3.1" tranquilo = ">=0.1.1" iminuit = ">=2.25" diff --git a/src/optimagic/benchmarking/cartis_roberts.py b/src/optimagic/benchmarking/cartis_roberts.py index e5371d43c..29e481556 100644 --- a/src/optimagic/benchmarking/cartis_roberts.py +++ b/src/optimagic/benchmarking/cartis_roberts.py @@ -16,6 +16,7 @@ """ from functools import partial +from typing import Any import numpy as np @@ -5368,3 +5369,14 @@ def get_start_points_methanl8(): "solution_criterion": 0, }, } + + +def get_raw_problems_cartis_roberts() -> dict[str, dict[str, Any]]: + """Get the specifications of the Cartis-Roberts benchmark problems. + + Returns: + A dictionary that maps the name of each problem to its specification, which + contains the criterion function, the start values and the solution. + + """ + return CARTIS_ROBERTS_PROBLEMS diff --git a/src/optimagic/benchmarking/get_benchmark_problems.py b/src/optimagic/benchmarking/get_benchmark_problems.py index ad51da106..e1f878408 100644 --- a/src/optimagic/benchmarking/get_benchmark_problems.py +++ b/src/optimagic/benchmarking/get_benchmark_problems.py @@ -131,88 +131,104 @@ def get_benchmark_problems( def _get_raw_problems(name): - # The problem sets are imported here to keep `import optimagic` fast. Importing - # the Cartis-Roberts problems imports numba, which takes about 0.2 seconds. - from optimagic.benchmarking.more_wild import MORE_WILD_PROBLEMS - + # The benchmark sets are imported only when they are requested, to keep + # `import optimagic` fast. Importing the Cartis-Roberts problems imports numba, + # which takes about 0.2 seconds. if name == "more_wild": - raw_problems = MORE_WILD_PROBLEMS + from optimagic.benchmarking.more_wild import get_raw_problems_more_wild + + raw_problems = get_raw_problems_more_wild() elif name == "cartis_roberts": - from optimagic.benchmarking.cartis_roberts import CARTIS_ROBERTS_PROBLEMS + from optimagic.benchmarking.cartis_roberts import ( + get_raw_problems_cartis_roberts, + ) - raw_problems = CARTIS_ROBERTS_PROBLEMS + raw_problems = get_raw_problems_cartis_roberts() elif name == "example": - subset = { - "rosenbrock_good_start", - "helical_valley_good_start", - "powell_singular_good_start", - "freudenstein_roth_good_start", - "bard_good_start", - "box_3d", - "brown_dennis_good_start", - "chebyquad_6", - "bdqrtic_8", - "mancino_5_good_start", - } - raw_problems = {k: v for k, v in MORE_WILD_PROBLEMS.items() if k in subset} + raw_problems = _get_raw_problems_example() elif name == "estimagic": - subset_mw = { - "cube_8", - "chebyquad_6", - "bdqrtic_8", - "linear_full_rank_bad_start", - "chebyquad_7", - "osborne_two_bad_start", - "bdqrtic_10", - "bdqrtic_11", - "heart_eight_bad_start", - "mancino_5_bad_start", - "chebyquad_8", - "cube_6", - "cube_5", - "bdqrtic_12", - "chebyquad_10", - "chebyquad_9", - "chebyquad_11", - "mancino_8", - "mancino_10", - "mancino_12_bad_start", - } - subset_cr = { - "hatfldg", - "bratu_3d", - "cbratu_2d", - "chnrsbne", - "bratu_2d", - "vardimne", - "penalty_1", - "arglale", - "arglble", - } - subset_add_steps = { - "rosenbrock_good_start", - "cube_5", - "chebyquad_10", - } - from optimagic.benchmarking.cartis_roberts import CARTIS_ROBERTS_PROBLEMS + raw_problems = _get_raw_problems_estimagic() + else: + raise NotImplementedError() + return raw_problems - raw_problems = {} - for k, v in MORE_WILD_PROBLEMS.items(): - if k in subset_mw: - raw_problems[k] = v - if k in subset_add_steps: - problem = v.copy() - raw_func = problem["fun"] - problem["fun"] = wraps(raw_func)(partial(_step_func, raw_func=raw_func)) # ty:ignore[invalid-argument-type, invalid-assignment] - raw_problems[f"{k}_with_steps"] = problem +def _get_raw_problems_example(): + from optimagic.benchmarking.more_wild import get_raw_problems_more_wild + + subset = { + "rosenbrock_good_start", + "helical_valley_good_start", + "powell_singular_good_start", + "freudenstein_roth_good_start", + "bard_good_start", + "box_3d", + "brown_dennis_good_start", + "chebyquad_6", + "bdqrtic_8", + "mancino_5_good_start", + } + return {k: v for k, v in get_raw_problems_more_wild().items() if k in subset} + + +def _get_raw_problems_estimagic(): + from optimagic.benchmarking.cartis_roberts import get_raw_problems_cartis_roberts + from optimagic.benchmarking.more_wild import get_raw_problems_more_wild + + subset_mw = { + "cube_8", + "chebyquad_6", + "bdqrtic_8", + "linear_full_rank_bad_start", + "chebyquad_7", + "osborne_two_bad_start", + "bdqrtic_10", + "bdqrtic_11", + "heart_eight_bad_start", + "mancino_5_bad_start", + "chebyquad_8", + "cube_6", + "cube_5", + "bdqrtic_12", + "chebyquad_10", + "chebyquad_9", + "chebyquad_11", + "mancino_8", + "mancino_10", + "mancino_12_bad_start", + } + subset_cr = { + "hatfldg", + "bratu_3d", + "cbratu_2d", + "chnrsbne", + "bratu_2d", + "vardimne", + "penalty_1", + "arglale", + "arglble", + } + subset_add_steps = { + "rosenbrock_good_start", + "cube_5", + "chebyquad_10", + } - for k, v in CARTIS_ROBERTS_PROBLEMS.items(): - if k in subset_cr: - raw_problems[k] = v + raw_problems = {} + for k, v in get_raw_problems_more_wild().items(): + if k in subset_mw: + raw_problems[k] = v + if k in subset_add_steps: + problem = v.copy() + raw_func = problem["fun"] + + problem["fun"] = wraps(raw_func)(partial(_step_func, raw_func=raw_func)) + raw_problems[f"{k}_with_steps"] = problem + + for k, v in get_raw_problems_cartis_roberts().items(): + if k in subset_cr: + raw_problems[k] = v - else: - raise NotImplementedError() return raw_problems diff --git a/src/optimagic/benchmarking/more_wild.py b/src/optimagic/benchmarking/more_wild.py index 684e99947..235c64d49 100644 --- a/src/optimagic/benchmarking/more_wild.py +++ b/src/optimagic/benchmarking/more_wild.py @@ -22,6 +22,7 @@ """ from functools import partial +from typing import Any import numpy as np @@ -1187,3 +1188,14 @@ def get_start_points_mancino(n, a=1): "solution_criterion": 0, }, } + + +def get_raw_problems_more_wild() -> dict[str, dict[str, Any]]: + """Get the specifications of the More-Wild benchmark problems. + + Returns: + A dictionary that maps the name of each problem to its specification, which + contains the criterion function, the start values and the solution. + + """ + return MORE_WILD_PROBLEMS diff --git a/tests/optimagic/optimization/test_algo_option_validation.py b/tests/optimagic/optimization/test_algo_option_validation.py index 7ef9442a8..4fab2345f 100644 --- a/tests/optimagic/optimization/test_algo_option_validation.py +++ b/tests/optimagic/optimization/test_algo_option_validation.py @@ -40,6 +40,26 @@ def _solve_internal_problem(self, problem, x0): return InternalOptimizeResult(x=x0, fun=0.0, success=True) +@mark.minimizer( + name="dummy_subclass_algorithm", + solver_type=AggregationLevel.SCALAR, + is_available=True, + is_global=False, + needs_jac=False, + needs_hess=False, + needs_bounds=False, + supports_parallelism=False, + supports_bounds=False, + supports_infinite_bounds=False, + supports_linear_constraints=False, + supports_nonlinear_constraints=False, + disable_history=False, +) +@dataclass(frozen=True) +class DummySubclassAlgorithm(DummyAlgorithm): + n_restarts: PositiveInt = 1 + + def test_field_types_are_type_objects(): # Guard: if this fails, the module no longer covers the code path for regular # annotations and the mirrored test setup must be adapted. @@ -85,3 +105,17 @@ def test_conversion_works_in_with_option(): def test_validation_works_in_with_option(): with pytest.raises(InvalidAlgoOptionError): DummyAlgorithm().with_option(stopping_maxiter=-1) + + +def test_subclass_converts_inherited_and_new_options(): + algo = DummySubclassAlgorithm(stopping_maxiter=500.0, n_restarts="2") # ty:ignore[invalid-argument-type] + assert isinstance(algo.stopping_maxiter, int) + assert algo.stopping_maxiter == 500 + assert isinstance(algo.n_restarts, int) + assert algo.n_restarts == 2 + + +@pytest.mark.parametrize("option", ["stopping_maxiter", "n_restarts"]) +def test_subclass_validates_inherited_and_new_options(option): + with pytest.raises(InvalidAlgoOptionError): + DummySubclassAlgorithm(**{option: -1}) diff --git a/tests/optimagic/optimization/test_algo_option_validation_stringified.py b/tests/optimagic/optimization/test_algo_option_validation_stringified.py index 32ecdabcd..ece0adb4a 100644 --- a/tests/optimagic/optimization/test_algo_option_validation_stringified.py +++ b/tests/optimagic/optimization/test_algo_option_validation_stringified.py @@ -47,6 +47,26 @@ def _solve_internal_problem(self, problem, x0): return InternalOptimizeResult(x=x0, fun=0.0, success=True) +@mark.minimizer( + name="dummy_stringified_subclass_algorithm", + solver_type=AggregationLevel.SCALAR, + is_available=True, + is_global=False, + needs_jac=False, + needs_hess=False, + needs_bounds=False, + supports_parallelism=False, + supports_bounds=False, + supports_infinite_bounds=False, + supports_linear_constraints=False, + supports_nonlinear_constraints=False, + disable_history=False, +) +@dataclass(frozen=True) +class DummySubclassAlgorithm(DummyAlgorithm): + n_restarts: PositiveInt = 1 + + def test_field_types_are_annotation_strings(): # Guard: if this fails, the module no longer covers the code path for # stringified annotations and the mirrored test setup must be adapted. @@ -92,3 +112,17 @@ def test_conversion_works_in_with_option(): def test_validation_works_in_with_option(): with pytest.raises(InvalidAlgoOptionError): DummyAlgorithm().with_option(stopping_maxiter=-1) + + +def test_subclass_converts_inherited_and_new_options(): + algo = DummySubclassAlgorithm(stopping_maxiter=500.0, n_restarts="2") # ty:ignore[invalid-argument-type] + assert isinstance(algo.stopping_maxiter, int) + assert algo.stopping_maxiter == 500 + assert isinstance(algo.n_restarts, int) + assert algo.n_restarts == 2 + + +@pytest.mark.parametrize("option", ["stopping_maxiter", "n_restarts"]) +def test_subclass_validates_inherited_and_new_options(option): + with pytest.raises(InvalidAlgoOptionError): + DummySubclassAlgorithm(**{option: -1})