Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 40 additions & 18 deletions .tools/create_algo_selection_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,22 @@
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
- Collect all optimizer classes
- 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
Expand All @@ -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()
Expand All @@ -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
)
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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():
Expand All @@ -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
Expand Down Expand Up @@ -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",
]
Expand All @@ -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)


Expand Down
6 changes: 6 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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
Expand Down
9 changes: 9 additions & 0 deletions docs/source/development/styleguide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 3 additions & 4 deletions docs/source/how_to/how_to_document_optimizers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion pixi.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
Expand Down Expand Up @@ -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"
Expand Down
Loading
Loading