diff --git a/.claude/skills/wrap-optimizer/SKILL.md b/.claude/skills/wrap-optimizer/SKILL.md new file mode 100644 index 000000000..33522e953 --- /dev/null +++ b/.claude/skills/wrap-optimizer/SKILL.md @@ -0,0 +1,189 @@ +--- +name: wrap-optimizer +description: Add an optimizer wrapper to optimagic or bring an existing wrapper up to the wrapper standards. +disable-model-invocation: true +--- + +Wrap an optimizer for optimagic, or bring an existing wrapper up to standard. Both +branches run the same steps; a paragraph marked **New** or **Existing** applies to +one branch only. + +The rules are in two docs pages. Each step names the sections to read before you do +it: + +- `docs/source/how_to/how_to_add_optimizers.md`, part "Standards for wrappers" +- `docs/source/how_to/how_to_document_optimizers.md` + +Reference implementations: `src/optimagic/optimizers/fides.py` with +`tests/optimagic/optimizers/test_fides_wrappers.py` (flat options, objects from the +library, a changed default) and `nag_optimizers.py` with `test_nag_wrappers.py` (option +groups, converted deprecations). + +The spine of the work is the **option table**: one row per option of the library. +Every step after the audit is checked against its rows. + +## 1. Audit the library + +Work against the newest release. **New:** add the dependency as described in +"Integrate the wrapper into optimagic". **Existing:** raise the minimal version in +`pyproject.toml` to the newest release, run `pixi install`, and read the changelog +between the old and the new minimal version. + +Read the papers and the documentation, then establish every fact from the installed +source: documentation goes stale. For each option, follow it from the entry point to +the lines that use it and note its default, the range and type it accepts, and its +effect. Note also whether the library treats an absent option differently from one +passed as `None`, whether a default depends on the problem, and whether a flag makes +other options ineffective while it is off. Where the source leaves a doubt, run the +library directly on a small problem and look. + +List what the library returns and which fields of `InternalOptimizeResult` it can +fill, directly or with a counter in the wrapper. + +**Existing:** also list every defect of the current wrapper: options that are never +passed, passed under a wrong key, typed so that they cannot be used, results read +from the wrong field. Check whether `replace_and_warn_about_deprecated_algo_options` +in `src/optimagic/deprecations.py` renames an option of this wrapper before it +arrives. Search the open issues for the wrapper, its algorithms and the library (for +example `gh issue list --state open --search ""`, then once per algorithm +name), and add every problem they report to the list of defects. + +Done when every argument of the library's entry point, every key of its option +dictionaries and every attribute of its configuration objects has a row, for each +row you can name the function in the library's source where the option takes effect, +and every field of `InternalOptimizeResult` is marked as filled or as impossible to +fill with the reason. + +## 2. Draft the option table + +Read "The option table", "Which options to expose", "Keep the library's grouping", +"Names of options" and "Defaults". + +Fill every column of every row, and list the options that are not exposed with their +reasons. A flag together with the options it switches on becomes one row group for an +option of the form `bool | `. + +A default that deviates from the library needs **evidence**, and so does adopting a +library default that the current wrapper deviates from. See +[Evidence for defaults](#evidence-for-defaults). The harmonized stopping and +convergence options are the exception: they take the optimagic values, and the +evidence to collect is which criterion ends the runs. + +Done when every row has a name, a group, a default, the name it replaces and a planned +test, and every default that differs from the library's has a benchmark result or +"harmonized" next to it. + +## 3. Checkpoint: the option table + +Present to the user, in plain language with examples from this library: + +- the option table and the list of options that are not exposed, +- the fields of the result the wrapper will fill and those it cannot, +- the defaults that deviate or change, with the evidence, +- **Existing:** the defects found, the open issues and which of them this work + closes, and the deprecations the table implies, +- whether a tutorial is due (section "Tutorials"), +- every open question as a recommendation with its alternative. + +Stop here. Continue once the user has approved the table, with their corrections +applied to it. + +## 4. Implement + +Read "Keep the library's grouping", "The result" and "Changing an existing wrapper". + +Put the tables that tests and wrapper share into the wrapper module as public +constants: library name to optimagic name, options that are not exposed with reasons, +defaults that deviate with reasons. Build the call to the library from the first +table. + +**Existing:** declare every renamed, moved or converted option as a `DeprecatedOption` +and every changed default with `resolve_changed_default`. Announce removals and new +defaults for the minor release after the one that ships the change (see `CHANGES.md` +and the latest git tag for the current version). + +Done when every row of the approved table is in the code under its approved name and +default, every defect from the audit is fixed, the result has every field the audit +marked as filled, and +`pixi run tests tests/optimagic/optimization/test_many_algorithms.py -k ` +passes. + +## 5. Test + +Read "Tests". + +Probe before you assert: run the tiny problem with two values of the option and write +the assertion for the effect you observed. An option that shows no effect in the probe +is a finding. Go back to the library's source and find out when the option matters. +Put that into its docstring, or, if the option cannot have an effect inside +optimagic, move it to the options that are not exposed and tell the user. + +Let forwarding tests run the real solver with a tiny budget behind the spy. They then +also show that the library accepts the value. Let the contract test read the +library's defaults in every context they depend on (noisy or not, few or many +parameters): it then verifies each "depends on the problem" claim of the table. + +Done when + +- every row has the test planned for it, and every deprecated name and changed default + has a deprecation test, +- `pixi run tests tests/optimagic/optimizers/test__wrappers.py` passes in + under a minute, +- deleting one entry from the name table makes a contract test fail (try it, then + restore the entry), +- `pixi run -e tests- tests --library ` passes; it fails if a test + of the library is skipped. + +## 6. Document + +Read `how_to_document_optimizers.md`. + +Done when every option and every attribute of an option group has a docstring with the +three parts of the template, the class docstring lists the unsupported features with +reasons, `pixi run -e docs build-docs` passes, and you have read the rendered entry of +the algorithm from top to bottom. + +## 7. Tutorial + +Only if a tutorial is due. Read "Tutorials". + +Find each example by experiment first: a section stays only if running it shows the +effect it claims. Generate the numbers in the notebook instead of writing them into +the text. + +Done when the notebook runs from top to bottom without warnings in under a minute and +is linked from `docs/source/tutorials/index.md` and from the class docstring. + +## 8. Finish + +- Register the marker and the library as described in "Integrate the wrapper into + optimagic". Add the entry to `CHANGES.md`. +- Run `pixi run tests` if you changed code outside the wrapper module, otherwise + `pixi run tests-fast`; then `pixi run -e type-checking ty` and + `prek run --all-files`. +- Draft an issue for every unsupported feature that a reasonable extension of + optimagic could support. +- Draft the pull request description: what changed for users, the issues it closes, + the final option table, + the evidence for defaults, and the AI-use note the contributor guide asks for + (`docs/source/development/how_to_contribute.md`, "Using AI tools"). + +Done when all checks pass and the user has the drafts of the pull request and the +issues to review before anything is published. + +## Evidence for defaults + +Compare the candidate values on `om.get_benchmark_problems("more_wild")`, with bounds +added if the option only matters with bounds. Keep everything else at the planned +defaults. Report for each candidate: + +- the share of problems on which it comes within 1e-4 of the best value any candidate + found, relative to the improvement over the start value, +- the median number of function evaluations it needs to get there, +- the computation time per iteration, if the option changes the work inside the + optimizer, +- for convergence options: which criterion ends the runs and on how many problems a + run stops short of the best value. + +The library default stands unless the numbers show that another value is better. Put +the numbers into the checkpoint and later into the pull request description. diff --git a/.github/workflows/wrapper-tests.yml b/.github/workflows/wrapper-tests.yml new file mode 100644 index 000000000..407b96edf --- /dev/null +++ b/.github/workflows/wrapper-tests.yml @@ -0,0 +1,45 @@ +--- +# Tests of the wrapped optimizer libraries against their newest release, to detect +# upstream changes. They run once a month and can be started by hand. For every pull +# request, the main workflow runs the same tests with the library versions in the lock +# file. +permissions: + contents: read +name: wrapper-tests +on: + schedule: + - cron: 0 5 1 * * + workflow_dispatch: null +jobs: + run-wrapper-tests: + name: Run ${{ matrix.library }} tests with the newest release + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # Libraries that have wrapper tests, with their packages. Add a library when + # you add its wrapper tests. + include: + - library: fides + packages: fides + - library: nag + packages: dfo-ls py-bobyqa + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: prefix-dev/setup-pixi@9936258fee697aff89b3fed6ca1f80a382ef694e # v0.11.3 + with: + pixi-version: v0.71.2 + cache: true + cache-write: false + frozen: true + environments: tests-${{ matrix.library }} + - name: Update the wrapped library to its newest release + shell: bash -el {0} + run: pixi update -e tests-${{ matrix.library }} ${{ matrix.packages }} + - name: Run pytest + shell: bash -el {0} + run: >- + pixi run -e tests-${{ matrix.library }} tests + --library ${{ matrix.library }} diff --git a/AGENTS.md b/AGENTS.md index 099b16160..febdaf3b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,5 +22,8 @@ Consult the relevant sections of the documentation for your task: - Contribution workflow: [contributor guide](docs/source/development/how_to_contribute.md). - Code changes: [style guide](docs/source/development/styleguide.md). - Typing and public interfaces: [EP-02](docs/source/development/ep-02-typing.md). +- Optimizer wrappers (adding or changing one): + [how to add optimizers](docs/source/how_to/how_to_add_optimizers.md). The + user-invoked `wrap-optimizer` skill runs the full workflow. - GitHub activity: read the contributor guide's AI-use section and\ follow its guidance before publishing. diff --git a/CHANGES.md b/CHANGES.md index 664c74932..e32fdd204 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -29,6 +29,38 @@ This release adds experimental support for **SciPy-style callbacks**, replaces p 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}`746` Modernizes the `fides` wrapper, which now requires `fides>=0.8.2`. Options + are renamed to stay closer to fides (`hessian_update`, `subspace_solver`, + `stepback_strategy`, `max_stepback_fraction`, `stopping_maxtime`) and to follow a new + convention for trust-region options (`trustregion_shrinking_threshold`, + `trustregion_expansion_threshold`, `trustregion_shrinking_factor`, + `trustregion_expansion_factor`). The old names are deprecated and will be removed in + 0.7.0. `stepback_strategy="refine"` is new. For problems with bounds, the default of + `stepback_strategy` will change from `"truncate"` to `"reflect"` in 0.7.0. A new + tutorial shows how to use the advanced options of fides ({ghuser}`janosg`). +- {gh}`746` Modernizes `nag_dfols` and `nag_pybobyqa`, which now require + `DFO-LS>=1.6.5` and `Py-BOBYQA>=1.5.0`. Options that belong together are bundled in + option groups that mirror the solvers (`init_options`, `trustregion_options`, + `slow_progress_options`, `interpolation_options`, `regression_options`, + `growing_options`). Restarts are switched on with `restarts=True` or configured with + an instance of the restart options, noisy functions are declared with `noisy=True` + or with an instance of `NagNoiseOptions`, and all options of the solvers that + optimagic can serve are available. The old option names are deprecated and will be + removed in 0.7.0 ({ghuser}`janosg`). +- {gh}`746` Fixes several bugs in `nag_dfols` and `nag_pybobyqa`: `n_evals_per_point` + (formerly `noise_n_evals_per_point`) could not be used, `n_fun_evals` counted points + instead of evaluations or was missing, `stopping_maxfun` was ignored by + `nag_pybobyqa`, `n_iterations` was one too low and some options were never passed + to the solvers. Options the solvers reject now raise an `InvalidAlgoOptionError`. + `fides` now reports `status`, `n_fun_evals` and `n_jac_evals` ({ghuser}`janosg`). +- {gh}`746` Adds tools for the options of algorithm wrappers: the + `mark.deprecated_options` decorator keeps old option names working with a + `FutureWarning`, and related options can be bundled in validated option groups, + which are passed as instances of their class. Adds detailed wrapper tests, which + run in the CI jobs of the libraries for every pull request and once a month against + the newest releases of the wrapped libraries. The guides on adding and + documenting optimizers describe the new standards for wrappers, and a + `wrap-optimizer` skill guides coding agents through them ({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/algorithms.md b/docs/source/algorithms.md index bd6b2ac44..c953ac1b0 100644 --- a/docs/source/algorithms.md +++ b/docs/source/algorithms.md @@ -968,8 +968,18 @@ need to have [petsc4py](https://pypi.org/project/petsc4py/) installed. We wrap two algorithms from the numerical algorithms group. To use them, you need to install each of them separately: -- `pip install DFO-LS` -- `pip install Py-BOBYQA` +- `pip install "DFO-LS>=1.6.5"` +- `pip install "Py-BOBYQA>=1.5.0"` + +Both algorithms have a few options of their own and several option groups, for example +`trustregion_options`. An option group is passed as an instance of the class that is +documented below the algorithm. The classes are imported from +`optimagic.optimizers.nag_optimizers`. + +Two options are a switch and an option group in one: `noisy` and `restarts`. `True` +switches the feature on with default settings, for example `noisy=True` or +`restarts=True`. An instance of the option group switches it on with your settings, for +example `restarts=DfolsRestartOptions(max_unsuccessful_restarts=3)`. ```{eval-rst} .. dropdown:: nag_dfols @@ -980,6 +990,7 @@ install each of them separately: import numpy as np import optimagic as om + from optimagic.optimizers.nag_optimizers import DfolsRestartOptions @om.mark.least_squares @@ -990,7 +1001,11 @@ install each of them separately: om.minimize( fun=fun, params=np.array([1.0, 2.0, 3.0]), - algorithm=om.algos.nag_dfols(stopping_maxfun=10_000), + algorithm=om.algos.nag_dfols( + stopping_maxfun=10_000, + noisy=True, + restarts=DfolsRestartOptions(max_unsuccessful_restarts=3), + ), ) or using the string interface: @@ -999,6 +1014,7 @@ install each of them separately: import numpy as np import optimagic as om + from optimagic.optimizers.nag_optimizers import DfolsRestartOptions @om.mark.least_squares @@ -1010,7 +1026,11 @@ install each of them separately: fun=fun, params=np.array([1.0, 2.0, 3.0]), algorithm="nag_dfols", - algo_options={"stopping_maxfun": 10_000}, + algo_options={ + "stopping_maxfun": 10_000, + "noisy": True, + "restarts": DfolsRestartOptions(max_unsuccessful_restarts=3), + }, ) **Description and available options:** @@ -1018,6 +1038,40 @@ install each of them separately: .. autoclass:: optimagic.optimizers.nag_optimizers.NagDFOLS :members: :inherited-members: Algorithm, object + + **Option groups:** + + .. autoclass:: optimagic.optimizers.nag_optimizers.NagInitOptions + :members: + :inherited-members: object + + .. autoclass:: optimagic.optimizers.nag_optimizers.NagTrustregionOptions + :members: + :inherited-members: object + + .. autoclass:: optimagic.optimizers.nag_optimizers.NagSlowProgressOptions + :members: + :inherited-members: object + + .. autoclass:: optimagic.optimizers.nag_optimizers.NagNoiseOptions + :members: + :inherited-members: object + + .. autoclass:: optimagic.optimizers.nag_optimizers.DfolsInterpolationOptions + :members: + :inherited-members: object + + .. autoclass:: optimagic.optimizers.nag_optimizers.DfolsRegressionOptions + :members: + :inherited-members: object + + .. autoclass:: optimagic.optimizers.nag_optimizers.DfolsRestartOptions + :members: + :inherited-members: object + + .. autoclass:: optimagic.optimizers.nag_optimizers.DfolsGrowingOptions + :members: + :inherited-members: object ``` ```{eval-rst} @@ -1029,12 +1083,14 @@ install each of them separately: import numpy as np import optimagic as om + from optimagic.optimizers.nag_optimizers import NagTrustregionOptions om.minimize( fun=lambda x: x @ x, params=np.array([1.0, 2.0, 3.0]), algorithm=om.algos.nag_pybobyqa( - convergence_minimal_trustregion_radius_tolerance=1e-6, + convergence_min_trustregion_radius=1e-6, + trustregion_options=NagTrustregionOptions(expansion_factor=3.0), ), ) @@ -1044,12 +1100,16 @@ install each of them separately: import numpy as np import optimagic as om + from optimagic.optimizers.nag_optimizers import NagTrustregionOptions om.minimize( fun=lambda x: x @ x, params=np.array([1.0, 2.0, 3.0]), algorithm="nag_pybobyqa", - algo_options={"convergence_minimal_trustregion_radius_tolerance": 1e-6}, + algo_options={ + "convergence_min_trustregion_radius": 1e-6, + "trustregion_options": NagTrustregionOptions(expansion_factor=3.0), + }, ) **Description and available options:** @@ -1057,6 +1117,23 @@ install each of them separately: .. autoclass:: optimagic.optimizers.nag_optimizers.NagPyBOBYQA :members: :inherited-members: Algorithm, object + + **Option groups:** + + The groups of ``init_options``, ``trustregion_options``, + ``slow_progress_options`` and ``noisy`` are the same as for ``nag_dfols``: see + :class:`~optimagic.optimizers.nag_optimizers.NagInitOptions`, + :class:`~optimagic.optimizers.nag_optimizers.NagTrustregionOptions`, + :class:`~optimagic.optimizers.nag_optimizers.NagSlowProgressOptions` and + :class:`~optimagic.optimizers.nag_optimizers.NagNoiseOptions`. + + .. autoclass:: optimagic.optimizers.nag_optimizers.PybobyqaInterpolationOptions + :members: + :inherited-members: object + + .. autoclass:: optimagic.optimizers.nag_optimizers.PybobyqaRestartOptions + :members: + :inherited-members: object ``` (pygmo-algorithms)= @@ -1747,7 +1824,8 @@ To use ipopt, you need to have optimagic supports the [Fides Optimizer](https://fides-optimizer.readthedocs.io/en/latest). To use Fides, you need to have [the fides package](https://github.com/fides-dev/fides) installed -(`pip install fides>=0.7.4`). +(`pip install fides>=0.8.2`). The [fides tutorial](fides_tutorial) shows how to use its +advanced options. ```{eval-rst} .. dropdown:: fides @@ -1762,7 +1840,7 @@ need to have [the fides package](https://github.com/fides-dev/fides) installed om.minimize( fun=lambda x: x @ x, params=np.array([1.0, 2.0, 3.0]), - algorithm=om.algos.fides(hessian_update_strategy="bfgs"), + algorithm=om.algos.fides(hessian_update="sr1", subspace_solver="2D"), ) or using the string interface: @@ -1776,7 +1854,7 @@ need to have [the fides package](https://github.com/fides-dev/fides) installed fun=lambda x: x @ x, params=np.array([1.0, 2.0, 3.0]), algorithm="fides", - algo_options={"hessian_update_strategy": "bfgs"}, + algo_options={"hessian_update": "sr1", "subspace_solver": "2D"}, ) **Description and available options:** diff --git a/docs/source/explanation/internal_optimizers.md b/docs/source/explanation/internal_optimizers.md index 6ff5d17a1..d7a92c006 100644 --- a/docs/source/explanation/internal_optimizers.md +++ b/docs/source/explanation/internal_optimizers.md @@ -30,7 +30,7 @@ transformed problem. The functions and classes below are everything you need to know to add an optimizer to optimagic. To see them in action look at -[this guide](../how_to/how_to_add_optimizers.ipynb) +[this guide](../how_to/how_to_add_optimizers.md) ```{eval-rst} .. currentmodule:: optimagic.mark @@ -46,6 +46,16 @@ optimagic. To see them in action look at .. autofunction:: minimizer ``` +```{eval-rst} +.. dropdown:: mark.deprecated_options + + The `mark.deprecated_options` decorator keeps old names of algorithm options + working after they were renamed. See :ref:`wrapper-standards-deprecations` for + how to use it. + + .. autofunction:: deprecated_options +``` + ```{eval-rst} .. currentmodule:: optimagic.optimization.internal_optimization_problem ``` diff --git a/docs/source/how_to/how_to_add_optimizers.ipynb b/docs/source/how_to/how_to_add_optimizers.ipynb deleted file mode 100644 index 448b7493a..000000000 --- a/docs/source/how_to/how_to_add_optimizers.ipynb +++ /dev/null @@ -1,651 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "source": [ - "# How to add optimizers to optimagic\n", - "\n", - "This is a hands-on guide that shows you how to use custom optimizers with optimagic or\n", - "how to contribute an optimizer to the optimagic library.\n", - "\n", - "We have many [examples of optimizers](https://github.com/optimagic-dev/optimagic/tree/main/src/optimagic/optimizers) that are already part of optimagic and you can learn a lot from looking at \n", - "those. However, only looking at the final results might be a bit intimidating and does\n", - "not show the process of exploring a new optimizer library and gradually developing a \n", - "wrapper. \n", - "\n", - "This guide is there to fill the gap. It tells the story of how the `pygmo_gaco`\n", - "optimizer was added to optimagic by someone who was unfamiliar with pygmo or the \n", - "gaco algorithm. \n", - "\n", - "The steps of adding an algorithm are roughly as follows:\n", - "\n", - "1. **Understand how to use the algorithm**: Play around with the algorithm you want to \n", - "add in a notebook and solve some simple problems with it. Only move on to the next step \n", - "after you have a solid understanding. This is completely unrelated to optimagic and only\n", - "about he algorithm implementation you want to wrap. \n", - "2. **Understand how the algorithm works**: Read documentation,\n", - "research papers and other resources to find out why this algorithm was created and what \n", - "problems it is supposed to solve really well. \n", - "3. **Implement the minimal wrapper**: Learn about the `om.mark.minimizer` decorator as \n", - "well as the `om.InternalOptimizationProblem` and the `om.Algorithm` classes. Implement a \n", - "minimal version of your wrapper and test it.\n", - "4. **Complete and refactor the wrapper**: Make sure that all convergence criteria, \n", - "stopping criteria, and tuning parameters the algorithm supports can be passed to your \n", - "wrapper. Also check that the algorithm gets everything it needs to achieve maximum \n", - "performance (e.g. closed form derivatives and batch function evaluators). Now is also \n", - "the time to clean-up and refactor your code, especially if you wrap multiple optimizers \n", - "from a library.\n", - "5. **Align the wrapper with optimagic conventions**: Use harmonized names wherever \n", - "a convention exists. Think about good names everywhere else. Set stopping criteria \n", - "similar to other optimizers and try to adhere to our [design philosophy](style_guide) \n", - "when it comes to tuning parameters. \n", - "6. **Integrate your code into optimagic**: Learn how to add an optional dependency to \n", - "optimagic, where you need to put your code and how to add tests and documentation. \n", - "\n", - "\n", - "## Gen AI Policy \n", - "\n", - "It is ok to use GenAI and AI based coding assistants to speed up the process of adding \n", - "an optimizer to optimagic. They can be very useful for step 1 and 2. However, AI models \n", - "often fail completely when filling out the arguments of `om.mark.minimizer`, when you \n", - "ask them to come up with good names for tuning parameters or when you auto-generate the \n", - "documentation. \n", - "\n", - "Even for step 1 and 2 you should not use an AI Model naively, but upload a paper or \n", - "documentation page to provide context to the AI.\n", - "\n", - "Our policy is therefore:\n", - "1. Only use AI for drafts that you double-check; Never rely on AI producing correct results \n", - "2. Be transparent about your use of AI \n", - "\n", - "We will reject all Pull Requests that violate this policy. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 1. Understand how to use the algorithm\n", - "\n", - "Understanding how to use an algorithm means that you are at least able to solve a \n", - "simple optimization problem (like a sphere function or a rosenbrock function). \n", - "\n", - "The best starting point for this are usually tutorials or example notebooks from the \n", - "documentation. An AI model can also be a good idea. \n", - "\n", - "The things you need to find out for any new algorithm are:\n", - "\n", - "1. How to code up the objective function \n", - "2. How to run an optimization at default values\n", - "3. How to pass tuning parameters \n", - "4. How to pass bounds, constraints, derivatives, batch evaluators, etc. \n", - "5. How to get results back from the optimizer\n", - "\n", - "### Objective functions in pygmo\n", - "\n", - "To add pygmo_gaco, let's start by looking at the pygmo [tutorials](https://esa.github.io/pygmo2/tutorials/tutorials.html). Objective functions are coded up via the Problem class. We skip using [pre-defined problems](https://esa.github.io/pygmo2/tutorials/using_problem.html) because they will not help us and directly go to [user defined problems](https://esa.github.io/pygmo2/tutorials/coding_udp_simple.html).\n", - "\n", - "The following is copied from the documentation:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pygmo as pg\n", - "\n", - "\n", - "class sphere_function:\n", - " def fitness(self, x):\n", - " return [sum(x * x)]\n", - "\n", - " def get_bounds(self):\n", - " return ([-1, -1], [1, 1])\n", - "\n", - "\n", - "prob = pg.problem(sphere_function())" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This looks simple enough. No subclassing is required, `fitness` implements the objective\n", - "function, which returns the objective value as a list of a scalar and `get_bounds` returns \n", - "the bounds. We can immediately see how we would adjust this for any scalar objective \n", - "function. \n", - "\n", - "### How to run an optimization at default values\n", - "\n", - "After copy pasting from a few tutorials we find the following:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# The initial population\n", - "pop = pg.population(prob, size=20)\n", - "# The algorithm; ker needs to be at most the population size to avoid errors\n", - "algo = pg.algorithm(pg.gaco(ker=20))\n", - "# The actual optimization process\n", - "pop = algo.evolve(pop)\n", - "# Getting the best individual in the population\n", - "best_fitness = pop.get_f()[pop.best_idx()]\n", - "print(best_fitness)\n", - "best_x = pop.get_x()[pop.best_idx()]\n", - "print(np.round(best_x, 4))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It looks like the optimization worked, even though the precision is not great. The true optimal function value is 0 and the true optimal parameters are [0, 0]. But global algorithms like gaco are almost never precise, so this is good enough. \n", - "\n", - "We can also see that pygmo is really organized around concepts that are specific to genetic optimizers. Examples are `population` and `evolve`. The optimagic wrapper will hide the details (i.e. users don't have to create a population) but still allow full customization (the population size will be an algorithm specific option that can be set by the user).\n", - "\n", - "### How to pass tuning parameters\n", - "\n", - "We already saw in the previous step that tuning parameters like `ker` are passed when the \n", - "algorithm is created. \n", - "\n", - "All supported tuning parameters of gaco are listed and described \n", - "[here](https://esa.github.io/pygmo2/algorithms.html#pygmo.gaco). Unfortunately, the \n", - "description is not great so we'll have to look into the [paper](https://digital.csic.es/bitstream/10261/54957/3/Extended_ant_colony_2009.pdf) for details. \n", - "\n", - "\n", - "### How to pass bounds, constraints, derivatives, batch evaluators, etc. \n", - "\n", - "- We already saw how to pass bounds via the Problem class \n", - "- gaco does not support any other constraints, so we don't need to pass them \n", - "- gaco is derivative free, so we don't need to pass derivatives \n", - "- gaco can parallelize, so we need to find out how to pass a batch version of the \n", - "objective function\n", - "\n", - "After searching around in the pygmo documentation, we find out that our Problem needs to \n", - "be extended with a [`batch_fitness`](https://esa.github.io/pygmo2/problem.html#pygmo.problem.batch_fitness)\n", - "and our algorithm needs to know about [`pg.bfe()`](https://esa.github.io/pygmo2/bfe.html).\n", - "In our previous example it will look like this:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pygmo as pg\n", - "\n", - "\n", - "class sphere_function:\n", - " def fitness(self, x):\n", - " return [sum(x * x)]\n", - "\n", - " def get_bounds(self):\n", - " return ([-1, -1], [1, 1])\n", - "\n", - " # dvs represents a batch of parameter vectors at which the objective function is\n", - " # evaluated. However it is stored in an unintuitive format that needs to be reshaped\n", - " # to get at the actual parameter vectors.\n", - " def batch_fitness(self, dvs):\n", - " dim = len(self.get_bounds()[0])\n", - " x_list = list(dvs.reshape(-1, dim))\n", - " # we don't actually need to parallelize to find out how batch evaluators work\n", - " # and optimagic will make it really easy to parallelize this later on.\n", - " eval_list = [self.fitness(x)[0] for x in x_list]\n", - " evals = np.array(eval_list)\n", - " return evals\n", - "\n", - "\n", - "prob = pg.problem(sphere_function())\n", - "\n", - "pop = pg.population(prob, size=20)\n", - "\n", - "# creating the algorithm now requires 3 steps\n", - "pygmo_uda = pg.gaco(ker=20)\n", - "pygmo_uda.set_bfe(pg.bfe())\n", - "algo = pg.algorithm(pygmo_uda)\n", - "\n", - "pop = algo.evolve(pop)\n", - "best_fitness = pop.get_f()[pop.best_idx()]\n", - "print(best_fitness)\n", - "best_x = pop.get_x()[pop.best_idx()]\n", - "print(np.round(best_x, 4))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For this how-to guide we leave it at this basic exploration of the pygmo library. If you actually contributed an optimizer to optimagic, you would have to explore much more and document your exploration to convince us that you understand the library you wrap in detail. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### How to get results back \n", - "\n", - "The results are stored as part of the evolved population" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(\"Best function value: \", pop.get_f()[pop.best_idx()][0])\n", - "print(\"Best parameters: \", pop.get_x()[pop.best_idx()])\n", - "print(\"Number of function evaluations: \", pop.problem.get_fevals())" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 2. Understand how the algorithm works\n", - "\n", - "Here we want to find out as much as possible about the algorithm. Common questions \n", - "that should be answered are:\n", - "- For which kind of problems and situations was it designed?\n", - "- How does it work (intuitively)?\n", - "- Are there any papers, blogposts or other sources of information on the algorithm? \n", - "- Which tuning parameters does it have and what do they mean? \n", - "- Are there known limitations? \n", - "\n", - "### For which kind of problems and situations was it desigend \n", - "\n", - "gaco is a global optimizer that does not use derivative information. It should not be\n", - "used if you only need a local optimum or if you have derivatives. Other algorithms would \n", - "be more efficient and more precise there. \n", - "\n", - "Since gaco can evaluate the objective function in parallel it is designed for problems \n", - "with expensive objective functions. \n", - "\n", - "\n", - "### How does it work (intuitively)\n", - "\n", - "Ant colony optimization is a class of optimization algorithms modeled on the\n", - "actions of an ant colony. Artificial \"ants\" (e.g. simulation agents) locate\n", - "optimal solutions by moving through a parameter space representing all\n", - "possible solutions. Real ants lay down pheromones directing each other to\n", - "resources while exploring their environment. The simulated \"ants\" similarly\n", - "record their positions and the quality of their solutions, so that in later\n", - "simulation iterations more ants locate better solutions.\n", - "\n", - "The generalized ant colony algorithm generates future generations of ants by\n", - "using a multi-kernel gaussian distribution based on three parameters (i.e.,\n", - "pheromone values) which are computed depending on the quality of each\n", - "previous solution. The solutions are ranked through an oracle penalty\n", - "method.\n", - "\n", - "\n", - "### Are there any papers, blogposts or other sources of information on the algorithm? \n", - "\n", - "gaco was proposed in M. Schlueter, et al. (2009). Extended ant colony optimization for \n", - "non-convex mixed integer non-linear programming. Computers & Operations Research.\n", - "\n", - "See [here](https://digital.csic.es/bitstream/10261/54957/3/Extended_ant_colony_2009.pdf) for a free pdf. \n", - "\n", - "### Which tuning parameters does it have and what do they mean? \n", - "\n", - "The following is not just copied from the documentation but extended by reading the\n", - "paper. It is super important to provide as much information as possible for every \n", - "tunig parameter: \n", - "\n", - "- gen (int): number of generations.\n", - "- ker (int): number of solutions stored in the solution archive. Must be <= the population\n", - " size. \n", - "- q (float): convergence speed parameter. This parameter manages the convergence speed\n", - " towards the found minima (the smaller the faster). It must be positive and can be\n", - " larger than 1. The default is 1.0 until **threshold** is reached. Then it\n", - " is set to 0.01.\n", - "- oracle (float): oracle parameter used in the penalty method.\n", - "- acc (float): accuracy parameter for maintaining a minimum penalty\n", - " function's values distances.\n", - "- threshold (int): when the iteration counter reaches the threshold the\n", - " convergence speed is set to 0.01 automatically. To deactivate this effect\n", - " set the threshold to stopping.maxiter which is the largest allowed\n", - " value.\n", - "- n_gen_mark (int): parameter that determines the convergence speed of the standard \n", - " deviations. This must be an integer.\n", - "- impstop (int): if a positive integer is assigned here, the algorithm will count the \n", - " runs without improvements, if this number exceeds the given value, the algorithm \n", - " will be stopped.\n", - "- evalstop (int): maximum number of function evaluations.\n", - "- focus (float): this parameter makes the search for the optimum greedier\n", - " and more focused on local improvements (the higher the greedier). If the\n", - " value is very high, the search is more focused around the current best\n", - " solutions. Values larger than 1 are allowed.\n", - "- memory (bool): if True, memory is activated in the algorithm for multiple calls.\n", - "- seed (int): seed used by the internal random number generator (default is random).\n", - "\n", - "\n", - "### Are there known limitations \n", - "\n", - "No. \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 3. Implement the minimal wrapper\n", - "\n", - "\n", - "### Learn the relevant functions and classes\n", - "\n", - "Before you implement a minimal wrapper, you need to familiarize yourself with a few\n", - "important [classes and functions](functions_and_classes_for_internal_optimizers) \n", - "you will need. \n", - "\n", - "- The `mark.miminizer` decorator \n", - "- The `Algorithm` class \n", - "- The `InternalOptimizationProblem` class \n", - "- The `InternalOptimizeResult` class \n", - "\n", - "**Your task will be to subclass `Algorithm`. Your subclass must be decorated with\n", - "`mark.minizer` and override `Algorithm._solve_internal_problem`. `_solve_internal_problem`\n", - "takes an `InternalOptimizationProblem` and returns an `InternalOptimizeResult`**\n", - "\n", - "```{note}\n", - "Users of optimagic never create instances of `InternalOptimizationProblem` nor \n", - "do they call the `_solve_internal_problem` methods of algorithms. Instead they call \n", - "`minimize` or `maximize` which are much more convenient and flexible. \n", - "\n", - "`minimize` and `maximize` will then create an `InternalOptimizationProblem` from the \n", - "user's inputs, call the `_solve_internal_problem` method and postprocess it to create an \n", - "OptimizeResult. \n", - "\n", - "To summarize: The public `minimize` interface is optimized for user-friendliness. The \n", - "`InternalOptimizeProblem` is optimized for easy wrapping of external libraries. \n", - "```\n", - "\n", - "Below we define a heavily commented minimal version of a wrapper for pygmo's gaco \n", - "algorithm. We stay as close as possible to the pygmo examples we have worked with \n", - "before and ignore most tuning parameters for now. \n", - "\n", - "\n", - "### Write the minimal implementation" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from dataclasses import dataclass\n", - "\n", - "from numpy.typing import NDArray\n", - "\n", - "import optimagic as om\n", - "from optimagic.optimization.algorithm import Algorithm, InternalOptimizeResult\n", - "from optimagic.optimization.internal_optimization_problem import (\n", - " InternalOptimizationProblem,\n", - ")\n", - "from optimagic.typing import AggregationLevel, PositiveInt\n", - "\n", - "try:\n", - " import pygmo as pg\n", - "\n", - " IS_PYGMO_INSTALLED = True\n", - "except ImportError:\n", - " IS_PYGMO_INSTALLED = False\n", - "\n", - "\n", - "@om.mark.minimizer(\n", - " # you can pick the name; convention is lowercase with underscores\n", - " name=\"pygmo_gaco\",\n", - " # the type of problem this optimizer can solve -> scalar problems; Other optimizers\n", - " # solve likelihood or least_squares problems.\n", - " solver_type=AggregationLevel.SCALAR,\n", - " # is the optimizer available? -> only if pygmo is installed\n", - " is_available=IS_PYGMO_INSTALLED,\n", - " # is the optimizer a global optimizer? -> yes\n", - " is_global=True,\n", - " # does the optimizer need the jacobian? -> no, gaco is derivative free\n", - " needs_jac=False,\n", - " # does the optimizer need the hessian? -> no, gaco is derivative free\n", - " needs_hess=False,\n", - " # does the optimizer need bounds? -> yes, gaco needs finite bounds\n", - " needs_bounds=True,\n", - " # does the optimizer support parallelism? -> yes\n", - " supports_parallelism=True,\n", - " # does the optimizer support bounds? -> yes\n", - " supports_bounds=True,\n", - " # does the optimizer support infinite bounds? -> no, bounds must be finite\n", - " supports_infinite_bounds=False,\n", - " # does the optimizer support linear constraints? -> no\n", - " supports_linear_constraints=False,\n", - " # does the optimizer support nonlinear constraints? -> no\n", - " supports_nonlinear_constraints=False,\n", - " # should the history be disabled? -> no\n", - " disable_history=False,\n", - ")\n", - "# All algorithms need to be frozen dataclasses.\n", - "@dataclass(frozen=True)\n", - "class PygmoGaco(Algorithm):\n", - " # for now only set one parameter to get things running. The rest will come later.\n", - " stopping_maxiter: PositiveInt = 1000\n", - " n_cores: int = 1\n", - "\n", - " def _solve_internal_problem(\n", - " self, problem: InternalOptimizationProblem, x0: NDArray[np.float64]\n", - " ) -> InternalOptimizeResult:\n", - " # create a pygmo problem from the internal optimization problem\n", - " # This is just slightly more abstract than before and actually simpler because\n", - " # we have problem.batch_fun.\n", - "\n", - " n_cores = self.n_cores\n", - "\n", - " class PygmoProblem:\n", - " def fitness(self, x):\n", - " # problem.fun is not just the `fun` that was passed to `minimize` by\n", - " # the user. It is a wrapper around fun with added error handling,\n", - " # history collection, and reparametrization to enforce constraints.\n", - " # Moreover, it always works on flat numpy arrays as parameters and\n", - " # does not have additional arguments. The magic of optimagic is to\n", - " # create this internal `fun` from the user's `fun`, so you don't have\n", - " # to deal with constraints, weird parameter formats and similar when\n", - " # implementing the wrapper.\n", - " return [problem.fun(x)]\n", - "\n", - " def get_bounds(self):\n", - " # problem.bounds is not just the `bounds` that was passed to `minimize`\n", - " # by the user, which could have been a dictionary or some other non-flat\n", - " # format. `problem.bounds` always contains flat arrays with lower and\n", - " # upper bounds because this makes it easy to write wrappers.\n", - " return (problem.bounds.lower, problem.bounds.upper)\n", - "\n", - " def batch_fitness(self, dvs):\n", - " # The processing of dvs is pygmo specific.\n", - " dim = len(self.get_bounds()[0])\n", - " x_list = list(dvs.reshape(-1, dim))\n", - " # problem.batch_fun is a parallelized version of problem.fun.\n", - " eval_list = problem.batch_fun(x_list, n_cores)\n", - " evals = np.array(eval_list)\n", - " return evals\n", - "\n", - " prob = pg.problem(PygmoProblem())\n", - " pop = pg.population(prob, size=20)\n", - " pygmo_uda = pg.gaco(ker=20)\n", - " pygmo_uda.set_bfe(pg.bfe())\n", - " algo = pg.algorithm(pygmo_uda)\n", - " pop = algo.evolve(pop)\n", - " best_fun = pop.get_f()[pop.best_idx()][0]\n", - " best_x = pop.get_x()[pop.best_idx()]\n", - " n_fun_evals = pop.problem.get_fevals()\n", - " # For now we only use a few fields of the InternalOptimizeResult.\n", - " out = InternalOptimizeResult(\n", - " x=best_x,\n", - " fun=best_fun,\n", - " n_fun_evals=n_fun_evals,\n", - " )\n", - " return out" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Test the minimal wrapper directly\n", - "\n", - "So now that we have a wrapper, what do we do with it? And how can we be sure it works?\n", - "\n", - "We'll first try it out directly with the `SphereExampleInternalOptimizationProblem`. \n", - "This is only for debugging and testing purposes. A user would never create an \n", - "InternalOptimizationProblem and call an algorithm with it. It's called \"Internal\" for \n", - "a reason!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from optimagic.optimization.internal_optimization_problem import (\n", - " SphereExampleInternalOptimizationProblem,\n", - ")\n", - "\n", - "problem = SphereExampleInternalOptimizationProblem()\n", - "\n", - "gaco = PygmoGaco()\n", - "\n", - "result = gaco._solve_internal_problem(problem, x0=np.array([1.0, 1.0]))\n", - "\n", - "print(result.fun)\n", - "print(result.x)\n", - "print(result.n_fun_evals)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Use the minimal wrapper in minimize\n", - "\n", - "The internal testing gives us some confidence that the wrapper works correctly and would \n", - "have been good for debugging if it didn't. But now we want to test the wrapper in the\n", - "way it would be used later: via `minimize`\n", - "\n", - "With this we also get all the benefits of optimagic, from history collection and \n", - "criterion plots to flexible parameter formats. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "res = om.minimize(\n", - " fun=lambda x: x @ x,\n", - " params=np.arange(5),\n", - " algorithm=PygmoGaco,\n", - " bounds=om.Bounds(lower=-np.ones(5), upper=np.ones(5)),\n", - ")\n", - "\n", - "om.criterion_plot(res, monotone=True)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 4 Complete and refactor the wrapper\n", - "\n", - "To keep things simple, we left out almost all tuning parameters of the gaco algorithm \n", - "when we wrote the minimal wrapper. \n", - "\n", - "Now it's time to add them. You can add them one by one and make sure nothing breaks by \n", - "testing your wrapper after each change - both with the internal problem and via \n", - "minimize. \n", - "\n", - "Moreover, our code looks quite messy currently. Despite being a minimal wrapper, the \n", - "`_solve_internal_problem` method is quite long, unstructured and hard to read. \n", - "\n", - "The result of completing and refactoring the wrapper is too long to be repeated in the \n", - "notebook. Instead you can look at the actual [implementation in optimagic](\n", - "https://github.com/optimagic-dev/optimagic/blob/ba2678753587f91cea54de69ff76cb3dcb4257d4/src/optimagic/optimizers/pygmo_optimizers.py#L70)\n", - "\n", - "\n", - "The PygmoGaco class now contains all tuning parameters we identified in step 2 as\n", - "dataclass fields. They all have very useful type-hints that don't just show whether\n", - "a parameter is an int, str or float but also which values it can take (e.g. PositiveInt).\n", - "\n", - "`_solve_internal_problem` is now also much cleaner. It mainly maps our mor descriptive \n", - "names of tuning parameters to the old pygmo names and then calls a function called \n", - "`_minimize_pygmo` that does all the heavy lifting and can be re-used for other pygmo \n", - "optimizers. \n", - "\n", - "The arguments to `mark.minimizer` have not changed. They always need te be set correctly,\n", - "even for minimal working examples. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 5. Align the wrapper with optimagic conventions\n", - "\n", - "To make switching between different algorithm as simple as possible, we align the names \n", - "of commonly used convergence and stopping criteria. We also align the default values for \n", - "stopping and convergence criteria as much as possible. \n", - "\n", - "You can find the harmonized names and value {ref}`here `. \n", - "\n", - "To align the names of other tuning parameters as much as possible with what is already \n", - "there, simply have a look at the optimizers we already wrapped. For example, if you are \n", - "wrapping a bfgs or lbfgs algorithm from some library, try to look at all existing wrappers \n", - "of bfgs algorithms and use the same names for the same options. \n", - "\n", - "You can see what this means for the gaco algorithm [here](\n", - "https://github.com/optimagic-dev/optimagic/blob/ba2678753587f91cea54de69ff76cb3dcb4257d4/src/optimagic/optimizers/pygmo_optimizers.py#L70)\n", - "\n", - "In the future we will provide much more extensive guidelines for harmonization. \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": "## 6. Integrate your code into optimagic\n\nSo far you could have worked in a Jupyter Notebook. Integrating your code into\noptimagic only requires a few small changes:\n\n1. Add new dependencies to the `[tool.pixi.feature.test.dependencies]` section of\n`pyproject.toml` and run `pixi install` to update the lock file. Then re-create the\nenvironment to make sure that the environment is the same as we will use for continuous\nintegration. If your dependencies don't work on all platforms (e.g. linux only packages),\nskip this entire step and reach out to a core contributor for help.\n2. Save the code for your algorithm wrapper in a .py file in `optimagic.algorithms`.\nUse an existing file if you wrap another algorithm from a library we already had.\nOtherwise, create a new file.\n3. Run `pre-commit run --all-files`. This will trigger an automatic code generation\nthat fully integrates your wrapper into our algorithm selection tool.\n4. Run `pytest`. This will run at least a few tests for your new algorithm. Add more\ntests for algorithm specific things (e.g. tests that make sure tuning parameters have\nthe intended effects).\n5. Write documentation. The documentation should contain everything you figured out in\nstep 2. You can either write it into the docstring of your algorithm class (preferred,\nas this is what we will do for all algorithms in the long run) or in `algorithms.md`\nin the documentation.\n6. Create a pull request [in the optimagic repository](https://github.com/optimagic-dev/optimagic)\nand ask for a review." - } - ], - "metadata": { - "kernelspec": { - "display_name": "optimagic", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.15" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/docs/source/how_to/how_to_add_optimizers.md b/docs/source/how_to/how_to_add_optimizers.md new file mode 100644 index 000000000..9d53a3cf2 --- /dev/null +++ b/docs/source/how_to/how_to_add_optimizers.md @@ -0,0 +1,629 @@ +(how-to-add-optimizers)= + +# How to add optimizers to optimagic + +This guide shows you how to wrap an optimizer for optimagic and which standards a +wrapper has to meet. The same standards apply when you improve an existing wrapper. + +You can use a wrapper in your own project without contributing it. Then only the +[walkthrough](wrapper-walkthrough) is relevant for you. Wrappers that become part of +optimagic also have to follow the [standards](wrapper-standards). + +## The steps + +1. **Learn to use the optimizer.** Solve a few simple problems with the library you want + to wrap, without optimagic. Find out how to pass the objective function, options, + bounds, constraints and derivatives, and how to get the results. +1. **Learn how the optimizer works.** Read the documentation and the papers. Find out + which problems the optimizer was made for, what each option does and how to choose + its value. +1. **Write a minimal wrapper** and test it. +1. **Make the option table.** List every option of the library and decide whether it is + exposed, under which name, with which default and how it will be tested. For + contributions, discuss the table with a maintainer before you continue. The + [standards](wrapper-standards) tell you how to fill it. +1. **Complete the wrapper**: all options, tests, documentation and, for highly + configurable optimizers, a tutorial. +1. **Integrate the wrapper into optimagic.** + +If you use Claude Code, the `wrap-optimizer` skill (`.claude/skills/wrap-optimizer`) +guides an agent through these steps. It stops for your decision on the option table. + +## Using AI tools + +Follow the [AI policy of the contributor guide](../development/how_to_contribute.md). +For wrappers, two things are especially important: + +1. Only use AI for drafts that you double-check. Option names, defaults and + documentation are user-facing design decisions. Never rely on AI producing correct + results, and give it the papers and the documentation of the library as context. +1. Be transparent about your use of AI. + +(wrapper-walkthrough)= + +## Walkthrough: wrapping `pygmo_gaco` + +The walkthrough tells the story of how the `pygmo_gaco` optimizer was added by someone +who knew neither pygmo nor the gaco algorithm. + +### 1. Learn to use the optimizer + +The pygmo [tutorials](https://esa.github.io/pygmo2/tutorials/tutorials.html) show that +objective functions are passed as a problem class: + +```python +import numpy as np +import pygmo as pg + + +class sphere_function: + def fitness(self, x): + return [sum(x * x)] + + def get_bounds(self): + return ([-1, -1], [1, 1]) + + +prob = pg.problem(sphere_function()) +``` + +`fitness` returns the function value as a list with one entry and `get_bounds` returns +the bounds. An optimization at default values looks like this: + +```python +# The initial population +pop = pg.population(prob, size=20) +# The algorithm; ker needs to be at most the population size to avoid errors +algo = pg.algorithm(pg.gaco(ker=20)) +# The actual optimization process +pop = algo.evolve(pop) +# The best individual in the population +best_fitness = pop.get_f()[pop.best_idx()] +best_x = pop.get_x()[pop.best_idx()] +``` + +From this exploration we learn: + +- Options such as `ker` are passed when the algorithm is created. They are listed + [here](https://esa.github.io/pygmo2/algorithms.html#pygmo.gaco). +- Bounds are part of the problem class. gaco supports no other constraints and uses no + derivatives. +- gaco can evaluate the function in parallel. For this the problem class needs a + [`batch_fitness`](https://esa.github.io/pygmo2/problem.html#pygmo.problem.batch_fitness) + method and the algorithm needs `set_bfe(pg.bfe())`. +- The results are stored in the evolved population. The number of function evaluations + is `pop.problem.get_fevals()`. + +For a real contribution you have to explore much more, and document it, to convince us +that you understand the library in detail. + +### 2. Learn how the optimizer works + +Answer these questions before you write the wrapper: + +- For which problems and situations was the optimizer designed? +- How does it work, intuitively? +- Which papers and other sources describe it? +- What does each option do and how should a user choose its value? +- Which features of the library can optimagic not support, and why? +- Are there known limitations? + +For gaco the answers are: It is a global optimizer that uses no derivatives and can +evaluate the function in parallel, so it is meant for expensive functions with several +local optima. It should not be used if a local optimum is enough or if derivatives are +available. It simulates ants that explore the parameter space and leave more +"pheromones" at good solutions, so that later generations search there more often. It +was proposed by +[Schlueter et al. (2009)](https://digital.csic.es/bitstream/10261/54957/3/Extended_ant_colony_2009.pdf). + +The descriptions of the options in the pygmo documentation are short. Reading the paper +was necessary to understand them. For example, for `q` the documentation only says +"convergence speed parameter". The paper shows that smaller values make the search +concentrate faster on the best solutions found so far. + +### 3. Write a minimal wrapper + +A wrapper is a frozen dataclass that inherits from `Algorithm`, is decorated with +`mark.minimizer` and implements `_solve_internal_problem`. This method takes an +`InternalOptimizationProblem` and returns an `InternalOptimizeResult`. These +[classes and functions](functions_and_classes_for_internal_optimizers) are explained in +detail elsewhere. + +```{note} +Users never create an `InternalOptimizationProblem`. They call `minimize` or +`maximize`, which create it from their inputs. The public interface is made for +convenience, the internal problem is made for easy wrapping: its functions take a +flat numpy array and already handle constraints, scaling, errors and the history. +``` + +```python +from dataclasses import dataclass + +import numpy as np +from numpy.typing import NDArray + +import optimagic as om +from optimagic.optimization.algorithm import Algorithm, InternalOptimizeResult +from optimagic.optimization.internal_optimization_problem import ( + InternalOptimizationProblem, +) +from optimagic.typing import AggregationLevel, PositiveInt + +try: + import pygmo as pg + + IS_PYGMO_INSTALLED = True +except ImportError: + IS_PYGMO_INSTALLED = False + + +@om.mark.minimizer( + # lowercase with underscores, starting with the name of the library + name="pygmo_gaco", + # scalar, least-squares or likelihood problems + solver_type=AggregationLevel.SCALAR, + is_available=IS_PYGMO_INSTALLED, + is_global=True, + # gaco is derivative free + needs_jac=False, + needs_hess=False, + # gaco needs finite bounds + needs_bounds=True, + supports_parallelism=True, + supports_bounds=True, + supports_infinite_bounds=False, + supports_linear_constraints=False, + supports_nonlinear_constraints=False, + disable_history=False, +) +@dataclass(frozen=True) +class PygmoGaco(Algorithm): + # Only two options to get things running. The rest comes later. + stopping_maxiter: PositiveInt = 1000 + n_cores: int = 1 + + def _solve_internal_problem( + self, problem: InternalOptimizationProblem, x0: NDArray[np.float64] + ) -> InternalOptimizeResult: + n_cores = self.n_cores + + class PygmoProblem: + def fitness(self, x): + return [problem.fun(x)] + + def get_bounds(self): + return (problem.bounds.lower, problem.bounds.upper) + + def batch_fitness(self, dvs): + dim = len(self.get_bounds()[0]) + x_list = list(dvs.reshape(-1, dim)) + # problem.batch_fun is a parallelized version of problem.fun + return np.array(problem.batch_fun(x_list, n_cores)) + + prob = pg.problem(PygmoProblem()) + pop = pg.population(prob, size=20) + pygmo_uda = pg.gaco(ker=20, gen=self.stopping_maxiter) + pygmo_uda.set_bfe(pg.bfe()) + pop = pg.algorithm(pygmo_uda).evolve(pop) + + return InternalOptimizeResult( + x=pop.get_x()[pop.best_idx()], + fun=pop.get_f()[pop.best_idx()][0], + n_fun_evals=pop.problem.get_fevals(), + ) +``` + +Test the wrapper in the way it will be used: + +```python +res = om.minimize( + fun=lambda x: x @ x, + params=np.arange(5), + algorithm=PygmoGaco, + bounds=om.Bounds(lower=-np.ones(5), upper=np.ones(5)), +) +om.criterion_plot(res, monotone=True) +``` + +For debugging you can also call the wrapper directly with an example problem: + +```python +from optimagic.optimization.internal_optimization_problem import ( + SphereExampleInternalOptimizationProblem, +) + +problem = SphereExampleInternalOptimizationProblem() +result = PygmoGaco()._solve_internal_problem(problem, x0=np.array([1.0, 1.0])) +``` + +The arguments of `mark.minimizer` have to be correct even in a minimal wrapper. +optimagic uses them to decide which problems an algorithm can solve and what it passes +to the algorithm. + +### 4. to 6. Complete and integrate the wrapper + +The final version of the wrapper is in +[`pygmo_optimizers.py`](https://github.com/optimagic-dev/optimagic/blob/main/src/optimagic/optimizers/pygmo_optimizers.py). +The remaining steps are described by the standards below and by the +[integration checklist](wrapper-integration). + +(wrapper-standards)= + +## Standards for wrappers + +The wrappers of +[fides](https://github.com/optimagic-dev/optimagic/blob/main/src/optimagic/optimizers/fides.py) +and of the +[NAG optimizers](https://github.com/optimagic-dev/optimagic/blob/main/src/optimagic/optimizers/nag_optimizers.py) +follow these standards and serve as examples. + +(wrapper-standards-option-table)= + +### The option table + +Before you complete a wrapper, make a table with one row for every option of the +library. Options are the arguments of the function or class you call and everything that +can be set through option dictionaries or configuration objects. The columns are: + +| Column | Content | +| ------------------------ | ------------------------------------------------------------------------------------ | +| Library name and default | As in the newest release of the library. | +| optimagic name | Following the [naming rules](wrapper-standards-names), with the group it belongs to. | +| optimagic default | Following the [rules for defaults](wrapper-standards-defaults). | +| Replaces | The old optimagic name, if you improve an existing wrapper. | +| Test | Behavior or forwarding, see [tests](wrapper-standards-tests). | + +Options that are not exposed are listed below the table with the reason. The table is +the basis of the discussion with the maintainers and goes into the description of the +pull request. + +(wrapper-standards-coverage)= + +### Which options to expose + +Expose every option that optimagic can serve. An option is not exposed if + +- optimagic already handles it, for example logging, printing, the history, scaling or + additional arguments of the objective function. Point to the optimagic feature in the + docstring of the class. +- it does not do what it promises in the release you wrap. For example, a parallel mode + that still evaluates the function one point at a time. +- it cannot have an effect inside optimagic. For example, a check that catches errors of + the objective function which optimagic already handles before the library sees them. +- it needs information that optimagic cannot pass to an optimizer yet, for example exact + Hessians, projections onto constraint sets or proximal operators. + +List the features that are not supported in the docstring of the class and say why. Open +an issue if a feature could be supported with a reasonable extension of optimagic. + +(wrapper-standards-structure)= + +### Keep the library's grouping + +- Options the library takes directly are direct options of the algorithm. +- If the library bundles options into a group, the group becomes one option called + `_options`. Examples are the option dictionary of DFO-LS with keys such as + `tr_radius.gamma_dec`, which becomes `trustregion_options`, or a configuration object + that is passed to the optimizer. +- If a group belongs to a feature that can be switched on and off, the switch and the + group become one option (see [below](wrapper-standards-switch)). +- A group that is only a miscellaneous bucket is dissolved. DFO-LS has a group + `general.*` with three unrelated options. A `general_options` argument would tell + users nothing, so the three are direct options. +- Do not invent groups the library does not have and do not flatten groups it has. + +A group is a frozen dataclass with one attribute per option. Decorate it with +`option_group`, annotate the field of the algorithm with the class and use the class as +`default_factory`: + +```python +from optimagic.optimization.algo_option_tools import option_group + + +@option_group +@dataclass(frozen=True) +class TrustregionOptions: + """Options that control how the trust region changes its size.""" + + shrinking_factor: ProbabilityFloat = 0.5 + """Factor by which the radius shrinks after an unsuccessful step. ...""" + + expansion_factor: PositiveFloat = 2.0 + """...""" + + +@mark.minimizer(...) +@dataclass(frozen=True) +class MyAlgorithm(Algorithm): + trustregion_options: TrustregionOptions = field(default_factory=TrustregionOptions) + """Options that control how the trust region changes its size. + + An instance of :class:`TrustregionOptions`. + + """ +``` + +Users pass an instance of the class. The entries are validated when the instance is +created: + +```python +om.algos.my_algorithm(trustregion_options=TrustregionOptions(shrinking_factor=0.9)) +om.minimize( + ..., + algo_options={"trustregion_options": TrustregionOptions(shrinking_factor=0.9)}, +) +``` + +A dictionary with the same entries is rejected. This keeps one way of setting a group +that editors and type checkers understand. Write each group as its own class without +base classes: inherited attributes lose their type in the rendered documentation. + +(wrapper-standards-switch)= + +**Features that can be switched on and off:** Some libraries have a flag that switches a +feature on and options that configure it. DFO-LS has `restarts.use_restarts` and a dozen +more `restarts.*` options, which do nothing while the flag is off. Do not expose the +flag and the options separately, because options that are set without the flag would +silently do nothing. Combine them in one option that takes a boolean or the group. The +option is named after the feature and has no `_options` suffix, and the group has no +entry for the flag: + +```python +restarts: bool | RestartOptions = False +"""Whether the optimizer restarts when it stagnates, and how. ...""" +``` + +```python +om.algos.my_algorithm(restarts=True) # on, with all defaults, nothing to import +om.algos.my_algorithm(restarts=RestartOptions(max_restarts=5)) # on, configured +om.algos.my_algorithm(restarts=False) # off +``` + +Passing the group always switches the feature on. This is the same pattern as `scaling` +and `multistart` in `minimize`. Declaring the function as noisy works the same way if +the library has options that describe the noise: `noisy=True` or +`noisy=NoiseOptions(additive_noise_level=0.1)`. If the library switches the feature on +by itself in some situations, add `None` as the default and state the rule in the +docstring. + +If the library is configured with its own objects, for example a Hessian approximation +or an acquisition function, accept these objects without hiding them. In addition, offer +names for the common choices and a default, so that nobody has to import anything from +the library to get started. An example is `hessian_update` of `fides`, which accepts +`"bfgs"`, `"sr1"` or an instance of a class from `fides.hessian_approximation`. + +(wrapper-standards-names)= + +### Names of options + +Keep the name the library uses if it is readable. Replace only + +- symbols from the paper: `eta1`, `rho`, `gamma_dec`, +- cut-off words: `thresh` becomes `threshold`, `geom` becomes `geometry`, +- words for which optimagic has its own term (see the table below), +- names that describe the direction of the optimization. Every algorithm can also be + used with `maximize`, so `seek_global_minimum` becomes `seek_global_optimum`. + +Symbols that are used everywhere in the optimization literature are fine. For example, +counts start with `n_` as in `n_restarts`. + +Longer is not better. A name should be as short as it can be while still telling a user +who has not read the paper what the option is about. + +Options that occur in many algorithms have fixed names: + +| Meaning | Name | +| ----------------------------------------------------- | -------------------------------------------------------------- | +| The objective function | `fun` in all names, not `objfun` or `criterion` | +| Maximum number of function evaluations | `stopping_maxfun` | +| Maximum number of iterations | `stopping_maxiter` | +| Maximum runtime in seconds | `stopping_maxtime` | +| Tolerances on the function value | `convergence_ftol_abs`, `convergence_ftol_rel` | +| Tolerances on the gradient | `convergence_gtol_abs`, `convergence_gtol_rel` | +| Tolerances on the parameters | `convergence_xtol_abs`, `convergence_xtol_rel` | +| Stop when this function value is reached | `convergence_target_value` | +| Stop when the trust-region radius is this small | `convergence_min_trustregion_radius` | +| Radius of the trust region at the start | `trustregion_initial_radius` | +| Step quality below which the trust region shrinks | `trustregion_shrinking_threshold` | +| Step quality above which the trust region grows | `trustregion_expansion_threshold` | +| Factors for shrinking and growing the trust region | `trustregion_shrinking_factor`, `trustregion_expansion_factor` | +| Solver of the trust-region subproblem and its options | `trustregion_subsolver`, `trustregion_subsolver_options` | +| Whether the function is noisy, and how | `noisy` | +| Evaluations that are averaged at each point | `n_evals_per_point` | +| Number of cores and random seed | `n_cores`, `seed` | + +All other criteria that end an optimization start with `convergence_` if they indicate +success and with `stopping_` if they limit resources. Inside a group the prefix of the +group is dropped: the entry of `trustregion_options` is called `shrinking_factor`. The +default values of the harmonized options are listed {ref}`here `. + +If the same option exists in other wrappers of the same kind of algorithm, use the same +name. + +**Optimizers from scipy:** optimagic aims to be a drop-in replacement for +`scipy.optimize`. An option of a scipy optimizer gets a readable optimagic name like any +other option. The scipy name has to keep working in addition, as a permanent alias +without a warning. The mechanism for these aliases is tracked in +[issue 745](https://github.com/optimagic-dev/optimagic/issues/745). + +(wrapper-standards-defaults)= + +### Defaults + +- Every option has a default. Users can run the algorithm without setting anything and + without importing anything from the library. +- Use the default of the library, with two exceptions: the harmonized stopping and + convergence options, and cases where a benchmark shows that another value is better. + State every deviation and its reason in the docstring of the option. +- If the default of the library depends on the problem, for example on the number of + parameters or on whether the function is noisy, use `None`, do not pass the option to + the library and state the rule in the docstring. Leaving the option out is not the + same as passing `None`: some libraries only choose a default themselves if the option + is absent. +- Annotate each option with the range the library accepts, for example `PositiveInt` or + `ProbabilityFloat`. Invalid values then raise when the algorithm is created. + +**Convergence criteria:** At the defaults, an optimizer should stop because it has +reached an optimum, not because progress became slow. Criteria that measure closeness to +an optimum are the main criteria. These are the gradient norm or, for derivative-free +trust-region methods, the trust-region radius. Criteria that only measure progress, such +as the change in the function value or in the parameters or a count of slow iterations, +stay switched on as a safety net. Their defaults have to be strict enough that they do +not cost accuracy. Check this by running a benchmark set at the defaults and looking at +which criterion ends the runs and how close they get to the best known value. + +(wrapper-standards-result)= + +### The result + +A wrapper reports as many fields of `InternalOptimizeResult` as it can: the parameters +and the function value, `success`, `message` and `status`, the numbers of function +evaluations, derivative evaluations and iterations, and the derivatives at the solution +if the library provides them. Everything else the library reports goes into `info`. + +- If the library does not count something, count it in the wrapper where this is + possible, for example by counting the calls of the function. +- If collecting a value costs time, collect it anyway unless the cost is large compared + to a cheap function evaluation, and switch off the expensive parts that are not + needed. +- Say in the docstring of the class if a reported derivative is an approximation. +- A value that an existing wrapper reported is still reported after a change. + +(wrapper-standards-deprecations)= + +### Changing an existing wrapper + +Every change that users can notice needs a deprecation cycle. Old code keeps working for +one minor release and emits a `FutureWarning` that says what to use instead and in which +version the old behavior is removed. Changes are made in place; we do not add a second +wrapper for the same algorithm under a new name. + +**Renamed, moved or converted options** are declared next to the algorithm and passed to +the `mark.deprecated_options` decorator, which is placed above `mark.minimizer`: + +```python +from optimagic.optimization.algo_option_tools import DeprecatedOption + +DEPRECATED_OPTIONS = ( + # a new name + DeprecatedOption("stopping_max_seconds", "stopping_maxtime", "0.7.0"), + # moved into a group + DeprecatedOption("n_restarts", "restarts.max_restarts", "0.7.0"), + # a value that has to be converted, or an option that is split up + DeprecatedOption( + "reset_type", + lambda value, options: {"restarts.use_soft_restarts": value == "soft"}, + "0.7.0", + ), +) + + +@mark.deprecated_options(DEPRECATED_OPTIONS) +@mark.minimizer(...) +@dataclass(frozen=True) +class MyAlgorithm(Algorithm): ... +``` + +The old names then work wherever options can be set, i.e. when the algorithm is created, +in `with_option` and in `algo_options`. They do not appear in the signature or in the +documentation. Combining an old name with the option or the group that replaces it +raises an error. + +A function that converts a value is called with the old value and with all options that +were passed in the same call. Use the second argument if the old option only had an +effect together with another one. An old option that moves into an option of the form +`bool | ` switches the feature on. To switch it off, let the function return the +option itself, for example `{"restarts": False}`. + +**Changed defaults:** Give the option the default `None` for one release and resolve it +with `resolve_changed_default` when the optimization starts. Users who did not set the +option keep the old default and get a warning that announces the new one. Do not warn in +situations in which the option has no effect. + +The version in the warnings is the minor release after the one that ships the change. + +(wrapper-standards-tests)= + +### Tests + +Every wrapper has two sets of tests. + +**General tests.** All algorithms are tested on simple problems in +`test_many_algorithms.py`. + +**Wrapper tests** check every option. They are in +`tests/optimagic/optimizers/test__wrappers.py` and carry the marker of the +library, for example `pytestmark = pytest.mark.fides`. Like all tests with this marker, +they run whenever the library is installed, and in the CI job of the library for every +pull request. To run all tests of one library in its own environment: + +```console +$ pixi run -e tests-fides tests --library fides +``` + +In addition, the `wrapper-tests` workflow runs the tests of each library that has +wrapper tests once a month against the newest release of the library and can be started +by hand. The wrapper tests consist of: + +- **Contract tests** that detect changes in the library. They compare the options the + library offers (found by introspection) with tables in the wrapper module: one that + maps library names to optimagic names, one with the options that are not exposed and + one with the defaults that deviate on purpose. The wrapper uses the same tables to + build its call, so that tests and wrapper cannot diverge. Also compare signatures and + sets of valid choices. +- **Behavior tests** that run `om.minimize` on a tiny problem and show that an option + has its intended effect: a looser tolerance needs fewer iterations, the first step has + the length of the initial radius, a limit ends the run with the right message. +- **Forwarding tests** for options whose effect cannot be observed on a tiny problem. + They replace the library function by a spy and check that the value arrives under the + right name, and that options with the default `None` are not passed. +- **Deprecation tests** for every deprecated name and every changed default. + +Choose problems with a handful of parameters and fixed seeds. The wrapper tests of one +library should run in well under a minute. + +(wrapper-standards-docs)= + +### Documentation + +All documentation of an algorithm is in the docstrings of its class and its options, and +of its option groups. [How to document optimizers](how_to_document_optimizers.md) +explains what to write and how the docstrings are rendered. + +(wrapper-standards-tutorials)= + +### Tutorials + +A wrapper that accepts objects from the library needs a tutorial notebook in +`docs/source/tutorials`. For other highly configurable optimizers, for example those +with several option groups, a tutorial is recommended. + +A tutorial explains why and how to use the advanced options. Each section is either a +situation in which the defaults struggle and an option solves the problem, or an +illustration of what is possible and how it is done. Only keep examples in which you can +reproduce the effect. The [fides tutorial](fides_tutorial) is an example. + +(wrapper-integration)= + +## Integrate the wrapper into optimagic + +1. Add a pixi feature for the library to `pyproject.toml`, named after the pytest marker + of the library (for example `[tool.pixi.feature.fides.pypi-dependencies]`), and the + environment `tests-`. If the library can be installed together with the other + libraries, also add the feature to the environments `default`, `type-checking` and + `docs`. Run `pixi install` to update the lock file. Use the newest release as the + minimal version. If the library does not work on all platforms, reach out to a + maintainer. +1. Put the wrapper into a module in `src/optimagic/optimizers`. Use the existing module + if we already wrap other optimizers from the library. +1. Run `prek run --all-files`. This also generates the code that makes the algorithm + available as `om.algos.`. +1. Add the tests. For a new library, register its marker in `pyproject.toml`, map the + wrapper module to the marker in `OPTIMIZER_MODULE_TO_LIBRARY` in `tests/conftest.py` + and add the marker to the `library` matrix of `.github/workflows/main.yml`; + `tests/test_optimizer_library_markers.py` checks these three steps. Add the library + and its packages to the matrix of `.github/workflows/wrapper-tests.yml`. +1. Add the algorithm to `docs/source/algorithms.md` as described in + [how to document optimizers](how_to_document_optimizers.md). +1. Add an entry to `CHANGES.md` and create a pull request. Put the final option table + into its description. diff --git a/docs/source/how_to/how_to_document_optimizers.md b/docs/source/how_to/how_to_document_optimizers.md index 22295e66c..edb453ac5 100644 --- a/docs/source/how_to/how_to_document_optimizers.md +++ b/docs/source/how_to/how_to_document_optimizers.md @@ -1,174 +1,133 @@ -# How to document optimizers - -This guide shows you how to document algorithms in optimagic using our new documentation -system. We'll walk through the process step-by-step using the `ScipyLBFGSB` optimizer as -a complete example. - -## When to Use This Guide - -Use this guide when you need to: - -- Document a new algorithm you've added to optimagic -- Migrate existing algorithm documentation from the old split system (docstrings + - `algorithms.md`) to the new system -- Update or improve existing algorithm documentation +(how-to-document-optimizers)= -If you're adding a completely new optimizer to optimagic, start with the "How to Add -Optimizers guide" first, then use this guide to document your algorithm properly. - -## Why the New Documentation System? - -Previously, algorithm documentation was scattered across multiple places: - -- Basic descriptions in the algorithm class docstrings -- Detailed parameter descriptions in `algorithms.md` -- Usage examples separate from the algorithm definitions +# How to document optimizers -This made it hard to maintain consistency and keep documentation up-to-date. The new -system centralizes nearly all documentation in the algorithm code itself, making it: +This guide shows how to document an algorithm in optimagic. Use it when you add a new +algorithm or improve the documentation of an existing one. If you add a new optimizer, +start with [how to add optimizers](how_to_add_optimizers.md). -- Easier to maintain (documentation lives next to code) -- More consistent (unified format across all algorithms) -- Auto-generated (parameter lists appear automatically in docs) -- Type-safe (documentation matches actual parameter types) +The goal of the documentation is that users understand what an option does and how to +choose its value, without reading the paper. It should not be academic or low-level. -## The Documentation System Components +## Where the documentation lives -Our documentation system has three main parts: +All documentation of an algorithm is in the code: -1. **Algorithm Class Documentation**: A comprehensive docstring in the algorithm - dataclass that explains what the algorithm does, how it works, and when to use it -1. **Parameter Documentation**: Detailed docstrings for each parameter with mathematical - formulations when needed -1. **Usage Integration**: A section in `algorithms.md` that show how to use the - algorithm +1. The **docstring of the algorithm class** explains what the algorithm does and when to + use it. +1. The **docstring of each option** explains the effect of the option. Option groups are + documented in the same way: one docstring for the class and one per attribute. +1. An **entry in `algorithms.md`** shows how to select the algorithm and renders the + docstrings. -Let's walk through documenting an algorithm from start to finish. +## The docstring of the algorithm class -## Example: Documenting ScipyLBFGSB +The class docstring gives users what they need to decide whether to use the algorithm: -We'll use the `ScipyLBFGSB` optimizer to show you exactly how to document an algorithm. -This is a real example from the optimagic codebase, so you can follow along and see the -results. +- The first line says what the algorithm does. +- For which problems it is a good choice, and for which it is not. Compare it to related + algorithms. +- How it works, in a few intuitive sentences. +- Where the implementation comes from, how to install it and which papers to cite. +- Which features of the library are not supported and why. +- A link to the tutorial, if there is one. -### Step 1: Understand Your Algorithm +Here is an excerpt from the docstring of `Fides`: -Before writing documentation, make sure you understand: +```python +class Fides(Algorithm): + """Minimize a scalar function using the Fides trust-region optimizer. -- What the algorithm does mathematically -- What problems it's designed to solve -- How its parameters affect behavior -- Any performance characteristics or limitations + Fides is a gradient-based local optimizer for smooth scalar functions with or + without bounds. It is a good choice if evaluating the function and its gradient + is expensive, because it spends more effort than line-search methods such as + L-BFGS-B on choosing each step and typically needs fewer evaluations in return. + The price is a matrix factorization per iteration, so it is less suited for + problems with thousands of parameters. -For L-BFGS-B, this means understanding it's a quasi-Newton method for bound-constrained -optimization that approximates the Hessian using gradient history. + ... -```{eval-rst} + The following features of fides are not supported yet: -.. note:: - If you are simply migrating an existing algorithm, you can mostly rely on the - existing documentation in the algorithm class docstring and `algorithms.md`. + - Exact Hessians and the hybrid Hessian approximations that need them + (``HybridFixed``, ``HybridFraction``), because optimagic does not pass + user-provided Hessians to optimizers. + - ... + """ ``` -### Step 2: Write the Algorithm Class Documentation - -The algorithm class docstring is the most important part. It should give users -everything they need to decide whether to use this algorithm. +(option-docstring-template)= -Here's how we document `ScipyLBFGSB`: - -```python -# src/optimagic/optimizers/scipy_optimizers.py -class ScipyLBFGSB(Algorithm): - """Minimize a scalar differentiable function using the L-BFGS-B algorithm. +## The docstring of an option - The optimizer is taken from scipy, which uses the code written by the original - authors of the algorithm (L-BFGS-B v3.0). This code includes the corrections and - improvements that were introduced in a follow up paper. Since SciPy 1.15, SciPy - uses a C translation of the original Fortran code; older versions call the - Fortran code directly. +Every option docstring has three parts: - lbfgsb is a limited memory version of the original bfgs algorithm, that deals with - lower and upper bounds via an active set approach. +1. **One plain sentence that says what the option controls.** +1. **The effect of the values and when to change them.** For a number: what happens with + larger and with smaller values. For a choice: what each choice does. Say in which + situation a user should deviate from the default. +1. **A closing line with the name of the option in the library and the source of the + default.** If the default differs from the default of the library, say why. - The lbfgsb algorithm is well suited for differentiable scalar optimization problems - with up to several hundred parameters. +```python +trustregion_initial_radius: PositiveFloat = 1.0 +"""Radius of the trust region in the first iteration. - It is a quasi-newton line search algorithm. At each trial point it evaluates the - criterion function and its gradient to find a search direction. It then approximates - the hessian using the stored history of gradients and uses the hessian to calculate - a candidate step size. Then it uses a gradient based line search algorithm to - determine the actual step length. Since the algorithm always evaluates the gradient - and criterion function jointly, the user should provide a ``fun_and_jac`` function - that exploits the synergies in the calculation of criterion and gradient. +The radius limits the length of the first step, measured in the units of the +parameters. Decrease it if the first steps lead into regions where the function +is not defined or behaves very differently than at the start parameters. +Increase it if the start parameters are far from the optimum and the first +steps are too cautious. After the first iterations the radius adapts itself. - The lbfgsb algorithm is almost perfectly scale invariant. Thus, it is not necessary - to scale the parameters. +This is the ``delta_init`` option of fides and has the same default. - """ +""" ``` -**What makes this docstring effective:** +Rules for the wording: -- **Clear first line**: States exactly what the algorithm does -- **Implementation details**: Explains which implementation scipy uses -- **Algorithm classification**: Identifies it as a quasi-Newton method -- **Problem suitability**: Explains what problems it's good for -- **How it works**: Brief explanation of the algorithm's approach -- **Performance characteristics**: Mentions scale invariance -- **Usage advice**: Suggests using `fun_and_jac` for efficiency +- Describe effects, not formulas. Use a formula only where it is the definition of the + option, which is mostly the case for convergence criteria. +- Use the symbols of the paper only in the closing line. Write "the radius of the trust + region", not "delta". +- Explain technical terms in half a sentence when you first use them, for example "the + quality of a step, i.e. the actual improvement of the function divided by the + improvement the model predicted". +- Only describe effects you have verified in the code of the library or in an + experiment. Documentation of libraries is sometimes out of date. +- For convergence criteria, say whether the criterion measures closeness to an optimum + or only progress. +- If the default is `None` because the library chooses a value that depends on the + problem, state the rule the library uses. -### Step 3: Document Individual Parameters - -Each parameter needs clear documentation explaining what it controls and how it affects -the algorithm's behavior. +An option with a formula and a default that differs from the library looks like this: ```python -# Basic parameter documentation -stopping_maxiter: PositiveInt = STOPPING_MAXITER -"""Maximum number of iterations.""" - -# Parameter with mathematical formulation -convergence_ftol_rel: NonNegativeFloat = CONVERGENCE_FTOL_REL -r"""Converge if the relative change in the objective function is less than this -value. +convergence_gtol_rel: NonNegativeFloat = CONVERGENCE_GTOL_REL +r"""Stop when the norm of the gradient is at most this value times the absolute +function value. -More formally, this is expressed as +This makes the gradient criterion independent of the scale of the function, +i.e. fides stops when :math:`\|g_k\| \leq \text{gtol\_rel} \cdot |f_k|`. It has +no effect if the function value at the optimum is zero. -.. math:: - - \frac{f^k - f^{k+1}}{\max\{|f^k|, |f^{k+1}|, 1\}} \leq - \textsf{convergence\_ftol\_rel}. - -""" - -# Parameter with external library context -limited_memory_storage_length: PositiveInt = LIMITED_MEMORY_STORAGE_LENGTH -"""The maximum number of variable metric corrections used to define the limited -memory matrix. This is the 'maxcor' parameter in the SciPy documentation. - -The default value is taken from SciPy's L-BFGS-B implementation. Larger values use -more memory but may converge faster for some problems. +This is the ``grtol`` option of fides. The default of 1e-8 is harmonized across +optimagic; fides defaults to 0, which switches the criterion off. """ ``` -**Key principles for parameter documentation:** +## Type hints -- **Start with a clear description** of what the parameter controls -- **Add mathematical formulations** when they clarify the exact meaning (use `r"""` for - raw strings with LaTeX) -- **Include external library context** when relevant (e.g., "Default value is taken from - SciPy") -- **Explain performance implications** when they matter -- **Use proper type annotations** that match the parameter's constraints +Option values are validated against the type hints, so the type hints are part of the +documentation. Use the types from `optimagic.typing` that describe valid values, such as +`PositiveInt` or `NonNegativeFloat`, and `Literal` for choices. ```{eval-rst} .. warning:: - If your optimizer module uses type hints (e.g., ``PositiveInt``, - ``NonNegativeInt``), include the following at the top of your optimizer module: + Include the following at the top of your optimizer module: .. code-block:: python @@ -178,25 +137,22 @@ more memory but may converge faster for some problems. documentation (e.g., as ``Annotated[int, Gt(gt=0)]``). .. warning:: - Option values are validated against the field annotations with pydantic, which - resolves the annotations at runtime. Every name used in a field annotation must - therefore be importable at runtime -- a name that is only imported inside an - ``if TYPE_CHECKING:`` block will raise an error when the algorithm is - instantiated. If an optional dependency provides a type you want to use in an - annotation, add a runtime fallback next to the ``TYPE_CHECKING`` import, as is - done for ``HessianApproximation`` in ``optimagic/optimizers/fides.py``. + Option values are validated with pydantic, which resolves the annotations at + runtime. Every name used in a field annotation must therefore be importable at + runtime -- a name that is only imported inside an ``if TYPE_CHECKING:`` block + will raise an error when the algorithm is instantiated. If an optional + dependency provides a type you want to use in an annotation, add a runtime + fallback next to the ``TYPE_CHECKING`` import, as is done for + ``HessianApproximation`` in ``optimagic/optimizers/fides.py``. Since annotations are enforced, they must also be honest: document and annotate the values the optimizer actually accepts, rather than a narrower set. ``` -### Step 4: Integrate into `algorithms.md` +## The entry in `algorithms.md` -The final step is integrating your documented algorithm into the main documentation. -This creates a dropdown section that shows users how to use the algorithm. - -Add the following to `docs/source/algorithms.md` in an `eval-rst` block: +Add a dropdown to `docs/source/algorithms.md` in an `eval-rst` block: ```text .. dropdown:: scipy_lbfgsb @@ -235,64 +191,26 @@ Add the following to `docs/source/algorithms.md` in an `eval-rst` block: :inherited-members: Algorithm, object ``` -**What this section provides:** - -- **The dropdown button and title**: Makes it easy to find the algorithm -- **Concrete usage examples** showing both the object and string interfaces -- **Algorithm-specific parameter** in the usage example -- **Copy-pasteable code**: Each code block is self-contained and runs as is. Pass - `params` as a NumPy array so that `x @ x` works, don't use `...` placeholders, add - 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 also shows fields that - your class inherits from a base class of its own, without listing the members of - `Algorithm` - -## Working with Existing Documentation - -If you're migrating an algorithm that already has documentation: - -### Finding Existing Content - -Look for existing documentation in: - -- **Algorithm class docstrings**: Usually basic descriptions -- **`docs/source/algorithms.md`**: Detailed parameter descriptions and examples -- **Research papers**: For mathematical formulations and background -- **External library docs**: For default values and parameter meanings - -### Migration Strategy - -1. **Start with the algorithm class**: Move the best description from `algorithms.md` to - the class docstring -1. **Update and expand**: Add missing information about performance, usage, etc. -1. **Move parameter docs**: Transfer parameter descriptions from `algorithms.md` to - individual parameter docstrings -1. **Verify accuracy**: Check that all information is current and correct -1. **Create new integration**: Replace the old `algorithms.md` section with the new - dropdown format - -## Common Pitfalls to Avoid - -- **Don't copy-paste generic descriptions**: Each algorithm needs specific, detailed - documentation -- **Don't skip mathematical formulations**: When convergence criteria or parameters have - precise mathematical definitions, include them -- **Don't ignore external library context**: Always mention where default values come - from -- **Don't use vague parameter descriptions**: "Controls the algorithm behavior" is not - helpful -- **Don't forget performance implications**: Users need to understand trade-offs between - parameters - -## Getting Help - -If you're stuck or need clarification: - -- Look at existing well-documented algorithms like `ScipyLBFGSB` -- Check the {ref}`style_guide` for coding conventions -- Ask questions in GitHub issues or discussions - -The goal is to make optimagic's algorithm documentation the best resource for -understanding and using optimization algorithms effectively. +- Each code block is self-contained and runs as is. Pass `params` as a NumPy array so + that `x @ x` works, do not use `...` placeholders, add finite `bounds` if the + algorithm needs them, and mark least-squares or likelihood functions with + `om.mark.least_squares` or `om.mark.likelihood`. +- Set an option that is specific to the algorithm in the examples. +- 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`. +- If the algorithm has option groups, add an `autoclass` directive with `:members:` and + `:inherited-members: object` for each group class below the algorithm. See the entry + of `nag_dfols` for an example. + +## Check the result + +Build the documentation with `pixi run -e docs build-docs` and read the rendered page of +your algorithm. The build fails on warnings, for example on broken references. + +Common problems are: + +- Descriptions that only repeat the name of the option, such as "Controls the shrinking + of the radius". +- Descriptions that are copied from the paper and can only be understood with the paper. +- Missing information on where a default comes from. +- Missing advice on when to change an option. diff --git a/docs/source/tutorials/fides_tutorial.ipynb b/docs/source/tutorials/fides_tutorial.ipynb new file mode 100644 index 000000000..a501ea8ad --- /dev/null +++ b/docs/source/tutorials/fides_tutorial.ipynb @@ -0,0 +1,585 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0", + "metadata": {}, + "source": [ + "(fides_tutorial)=\n", + "\n", + "# Getting the most out of the fides optimizer\n", + "\n", + "[Fides](https://fides-optimizer.readthedocs.io) is a trust-region optimizer for smooth\n", + "functions with or without bounds. It needs gradients and typically needs few function\n", + "evaluations, which makes it a good choice for expensive functions.\n", + "\n", + "Fides works out of the box, but it is also one of the most configurable optimizers\n", + "in optimagic. In this tutorial you learn:\n", + "\n", + "- how to use fides with its defaults\n", + "- how to keep fides away from regions where your function is not defined\n", + "- how to choose and customize the Hessian approximation\n", + "- which options matter for bounds and for problems with many parameters\n", + "- how to control when fides stops\n", + "\n", + "To run the tutorial you need fides (`pip install \"fides>=0.8.2\"`)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1", + "metadata": {}, + "outputs": [], + "source": [ + "import time\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "\n", + "import optimagic as om" + ] + }, + { + "cell_type": "markdown", + "id": "2", + "metadata": {}, + "source": [ + "## Fides with default options\n", + "\n", + "We start with the Rosenbrock function, a standard test problem with a curved valley\n", + "that leads to the optimum at `[1, 1, ..., 1]`. Fides evaluates the function and its\n", + "gradient together in every iteration, so we provide both in one function via\n", + "`fun_and_jac`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3", + "metadata": {}, + "outputs": [], + "source": [ + "def rosenbrock(x):\n", + " return (100 * (x[1:] - x[:-1] ** 2) ** 2 + (1 - x[:-1]) ** 2).sum()\n", + "\n", + "\n", + "def rosenbrock_and_gradient(x):\n", + " grad = np.zeros_like(x)\n", + " grad[:-1] = -400 * x[:-1] * (x[1:] - x[:-1] ** 2) - 2 * (1 - x[:-1])\n", + " grad[1:] += 200 * (x[1:] - x[:-1] ** 2)\n", + " return rosenbrock(x), grad\n", + "\n", + "\n", + "res = om.minimize(\n", + " fun=rosenbrock,\n", + " fun_and_jac=rosenbrock_and_gradient,\n", + " params=np.full(5, -1.0),\n", + " algorithm=\"fides\",\n", + ")\n", + "res.params.round(5), res.n_iterations, res.message" + ] + }, + { + "cell_type": "markdown", + "id": "4", + "metadata": {}, + "source": [ + "The message tells you why fides stopped. Here the gradient is close enough to zero,\n", + "which means that the parameters are close to a local optimum.\n", + "\n", + "All options of fides can be set when you select the algorithm, either as\n", + "`om.algos.fides(...)` or via `algo_options`. The following sections show the options\n", + "that are most useful in practice. You find the complete list in the\n", + "[algorithm documentation](fides-algorithm)." + ] + }, + { + "cell_type": "markdown", + "id": "5", + "metadata": {}, + "source": [ + "## Staying inside the region where the function is defined\n", + "\n", + "Many functions are not defined for all parameter values, and often the region where\n", + "they are defined cannot be described by simple bounds. An optimizer that takes a long\n", + "first step can leave this region before it has learned anything about the function.\n", + "\n", + "As an example we fit a generalized Pareto distribution to data, as it is done for\n", + "insurance losses or flood heights. The distribution has a `scale` and a `shape`\n", + "parameter. Its likelihood is only defined if `1 + shape * y / scale > 0` for every\n", + "observation `y`. Whether parameters are valid therefore depends on the data." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6", + "metadata": {}, + "outputs": [], + "source": [ + "rng = np.random.default_rng(0)\n", + "uniform = rng.uniform(size=500)\n", + "data = 2.0 / 0.2 * ((1 - uniform) ** (-0.2) - 1) # scale = 2, shape = 0.2\n", + "\n", + "\n", + "def pareto_negative_loglike_and_gradient(params):\n", + " scale, shape = params\n", + " z = 1 + shape * data / scale\n", + " if scale <= 0 or (z <= 0).any():\n", + " raise ValueError(\"The likelihood is not defined at these parameters.\")\n", + " n_obs = len(data)\n", + " value = n_obs * np.log(scale) + (1 + 1 / shape) * np.log(z).sum()\n", + " grad_scale = n_obs / scale - (1 + 1 / shape) * (shape * data / scale**2 / z).sum()\n", + " grad_shape = (\n", + " -np.log(z).sum() / shape**2 + (1 + 1 / shape) * (data / scale / z).sum()\n", + " )\n", + " return value, np.array([grad_scale, grad_shape])\n", + "\n", + "\n", + "def pareto_negative_loglike(params):\n", + " return pareto_negative_loglike_and_gradient(params)[0]\n", + "\n", + "\n", + "def fit_pareto(algorithm):\n", + " return om.minimize(\n", + " fun=pareto_negative_loglike,\n", + " fun_and_jac=pareto_negative_loglike_and_gradient,\n", + " params=np.array([4.0, 0.1]),\n", + " algorithm=algorithm,\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "7", + "metadata": {}, + "source": [ + "With default options, fides fails. So does L-BFGS-B from scipy. Both step into the\n", + "undefined region right at the start:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8", + "metadata": {}, + "outputs": [], + "source": [ + "for algorithm in [om.algos.fides, om.algos.scipy_lbfgsb]:\n", + " try:\n", + " fit_pareto(algorithm)\n", + " except Exception as error:\n", + " print(f\"{algorithm.name} failed: {str(error).splitlines()[0]}\")" + ] + }, + { + "cell_type": "markdown", + "id": "9", + "metadata": {}, + "source": [ + "The reason is the length of the first step. Fides only trusts its model of the\n", + "function inside the trust region, and the first step can be as long as the initial\n", + "radius of this region. The default radius of 1 is too long here: The gradient at the\n", + "start parameters is large and points towards invalid parameters.\n", + "\n", + "`trustregion_initial_radius` makes the first step shorter. Afterwards fides adapts the\n", + "radius on its own: It grows when the model predicts the function well and shrinks\n", + "otherwise." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "10", + "metadata": {}, + "outputs": [], + "source": [ + "res = fit_pareto(om.algos.fides(trustregion_initial_radius=0.1))\n", + "res.params.round(3), res.n_iterations" + ] + }, + { + "cell_type": "markdown", + "id": "11", + "metadata": {}, + "source": [ + "Fides now converges in a few iterations. The estimates are close to the values that\n", + "generated the data (2 and 0.2).\n", + "\n", + "```{note}\n", + "Choose the initial radius in the units of your parameters: It is the largest distance\n", + "the parameters can move in the first iteration. If a short first step is not enough,\n", + "you can also let the radius grow more slowly with `trustregion_expansion_factor`.\n", + "A small radius does not guarantee that the function is never evaluated at invalid\n", + "parameters. For this case, optimagic can replace failed evaluations by a penalty; see\n", + "[how to handle errors](../how_to/how_to_errors_during_optimization.ipynb).\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "12", + "metadata": {}, + "source": [ + "## Choosing the Hessian approximation\n", + "\n", + "Fides builds a quadratic model of the function in every iteration. For this it needs\n", + "the Hessian, which it approximates from the gradients it has seen. The approximation\n", + "decides how good the steps are, so `hessian_update` is the option with the largest\n", + "effect on the number of iterations.\n", + "\n", + "The two most useful choices are `\"bfgs\"` (the default) and `\"sr1\"`. BFGS keeps the\n", + "model convex, which is robust. SR1 can also represent negative curvature. Which one is\n", + "better depends on the problem, and trying both is cheap. We compare them on the\n", + "Rosenbrock function and on the Mancino function from optimagic's benchmark problems." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13", + "metadata": {}, + "outputs": [], + "source": [ + "mancino = om.get_benchmark_problems(\"more_wild\")[\"mancino_5_good_start\"][\"inputs\"]\n", + "\n", + "comparison = {}\n", + "for hessian_update in [\"bfgs\", \"sr1\"]:\n", + " algorithm = om.algos.fides(hessian_update=hessian_update)\n", + " res_rosenbrock = om.minimize(\n", + " fun=rosenbrock,\n", + " fun_and_jac=rosenbrock_and_gradient,\n", + " params=np.full(5, -1.0),\n", + " algorithm=algorithm,\n", + " )\n", + " res_mancino = om.minimize(\n", + " fun=mancino[\"fun\"],\n", + " params=mancino[\"params\"],\n", + " algorithm=algorithm,\n", + " numdiff_options=om.NumdiffOptions(method=\"central\"),\n", + " )\n", + " comparison[hessian_update] = {\n", + " \"rosenbrock\": res_rosenbrock.n_iterations,\n", + " \"mancino\": res_mancino.n_iterations,\n", + " }\n", + "\n", + "pd.DataFrame(comparison).rename_axis(\"iterations until convergence\")" + ] + }, + { + "cell_type": "markdown", + "id": "14", + "metadata": {}, + "source": [ + "BFGS is clearly better on the Rosenbrock function, SR1 is clearly better on the\n", + "Mancino function. If your function is expensive, such a comparison on a small version\n", + "of your problem pays off quickly.\n", + "\n", + "### Customizing the approximation with objects from fides\n", + "\n", + "The names are shortcuts. For full control you can pass an object from\n", + "`fides.hessian_approximation` instead. Two examples:\n", + "\n", + "- `Broyden(phi=...)` mixes the BFGS update (`phi=0`) and the DFP update (`phi=1`).\n", + "- `BFGS(enforce_curv_cond=False)` also updates the approximation after steps where\n", + " the gradients indicate negative curvature. By default such updates are skipped." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "15", + "metadata": {}, + "outputs": [], + "source": [ + "from fides.hessian_approximation import BFGS, Broyden\n", + "\n", + "custom_updates = {\n", + " \"bfgs\": \"bfgs\",\n", + " \"Broyden(phi=0.5)\": Broyden(phi=0.5),\n", + " \"BFGS(enforce_curv_cond=False)\": BFGS(enforce_curv_cond=False),\n", + "}\n", + "\n", + "iterations = {}\n", + "for name, hessian_update in custom_updates.items():\n", + " res = om.minimize(\n", + " fun=mancino[\"fun\"],\n", + " params=mancino[\"params\"],\n", + " algorithm=om.algos.fides(hessian_update=hessian_update),\n", + " numdiff_options=om.NumdiffOptions(method=\"central\"),\n", + " )\n", + " iterations[name] = res.n_iterations\n", + "\n", + "pd.Series(iterations, name=\"iterations on the Mancino function\")" + ] + }, + { + "cell_type": "markdown", + "id": "16", + "metadata": {}, + "source": [ + "```{note}\n", + "Fides also has Hessian approximations that need exact Hessians (`HybridFixed`,\n", + "`HybridFraction`) or least-squares residuals (`FX`, `SSM`, `TSSM`, `GNSBFGS`). They\n", + "are not supported in optimagic yet.\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "17", + "metadata": {}, + "source": [ + "## Problems with bounds\n", + "\n", + "Fides keeps the parameters strictly inside the bounds. Two options control what\n", + "happens when a step would cross a bound:\n", + "\n", + "- `stepback_strategy` decides how the step is changed. With `\"reflect\"` the step\n", + " bounces off the bound, with `\"truncate\"` it stops there and the remaining\n", + " parameters are optimized again. `\"mixed\"` and `\"refine\"` invest more computation to\n", + " find a better step.\n", + "- `max_stepback_fraction` decides how close a single step may get to a bound.\n", + "\n", + "The differences are usually small, as in the following example where an upper bound\n", + "of 0.5 cuts off the optimum of the Rosenbrock function. Trying the strategies is\n", + "most promising if many parameters end up at a bound and fides needs many\n", + "iterations." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "18", + "metadata": {}, + "outputs": [], + "source": [ + "n_params = 50\n", + "bounds = om.Bounds(lower=np.full(n_params, -2.0), upper=np.full(n_params, 0.5))\n", + "\n", + "iterations = {}\n", + "for strategy in [\"reflect\", \"reflect_single\", \"truncate\", \"mixed\", \"refine\"]:\n", + " res = om.minimize(\n", + " fun=rosenbrock,\n", + " fun_and_jac=rosenbrock_and_gradient,\n", + " params=np.full(n_params, -1.0),\n", + " bounds=bounds,\n", + " algorithm=om.algos.fides(stepback_strategy=strategy),\n", + " )\n", + " iterations[strategy] = res.n_iterations\n", + "\n", + "pd.Series(iterations, name=\"iterations\")" + ] + }, + { + "cell_type": "markdown", + "id": "19", + "metadata": {}, + "source": [ + "```{note}\n", + "If you do not set `stepback_strategy` on a problem with bounds, optimagic currently\n", + "uses `\"truncate\"` and warns that the default will change to `\"reflect\"`, the default\n", + "of fides, in optimagic 0.7.0. Set the option explicitly to silence the warning.\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "20", + "metadata": {}, + "source": [ + "## Problems with many parameters\n", + "\n", + "In every iteration fides has to find the best step for its quadratic model. How this\n", + "is done is controlled by `subspace_solver`:\n", + "\n", + "- `\"full\"` finds the exact solution. This is the default in optimagic.\n", + "- `\"2D\"` only searches a two-dimensional plane. This is the default of fides.\n", + "- `\"scg\"` uses a conjugate gradient method that stops early.\n", + "\n", + "For expensive functions the number of iterations is what counts. For cheap functions\n", + "with many parameters, the time spent inside the optimizer becomes important. `\"scg\"`\n", + "needs more iterations, but each one is much cheaper:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "21", + "metadata": {}, + "outputs": [], + "source": [ + "rows = {}\n", + "for solver in [\"full\", \"2D\", \"scg\"]:\n", + " start = time.perf_counter()\n", + " res = om.minimize(\n", + " fun=rosenbrock,\n", + " fun_and_jac=rosenbrock_and_gradient,\n", + " params=np.full(100, -1.0),\n", + " algorithm=om.algos.fides(subspace_solver=solver),\n", + " )\n", + " rows[solver] = {\n", + " \"iterations\": res.n_iterations,\n", + " \"seconds\": round(time.perf_counter() - start, 2),\n", + " }\n", + "\n", + "pd.DataFrame.from_dict(rows, orient=\"index\")" + ] + }, + { + "cell_type": "markdown", + "id": "22", + "metadata": {}, + "source": [ + "With 100 parameters and a function that takes microseconds, `\"scg\"` is the fastest\n", + "although it needs about three times as many iterations. If one evaluation of your\n", + "function takes a second, the picture is reversed and `\"full\"` is the better choice." + ] + }, + { + "cell_type": "markdown", + "id": "23", + "metadata": {}, + "source": [ + "## Controlling when fides stops\n", + "\n", + "Fides has two kinds of convergence criteria:\n", + "\n", + "- The gradient criteria `convergence_gtol_abs` and `convergence_gtol_rel` measure\n", + " closeness to an optimum: At an optimum the gradient is zero. These are the main\n", + " criteria.\n", + "- `convergence_ftol_abs`, `convergence_ftol_rel` and `convergence_xtol_abs` measure\n", + " progress: Fides stops when the function value or the parameters hardly change\n", + " anymore. They are a safety net for problems where the gradient cannot become small\n", + " enough, for example because it is noisy.\n", + "\n", + "The defaults in optimagic are stricter than the defaults of fides, so that most runs\n", + "are ended by a gradient criterion. You see which criterion ended a run in\n", + "`res.message`.\n", + "\n", + "If you need a more precise solution, tighten the gradient tolerance. If function\n", + "evaluations are expensive and a rough solution is enough, loosen it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "24", + "metadata": {}, + "outputs": [], + "source": [ + "rows = {}\n", + "for gtol in [1e-2, 1e-5, 1e-8]:\n", + " res = om.minimize(\n", + " fun=rosenbrock,\n", + " fun_and_jac=rosenbrock_and_gradient,\n", + " params=np.full(5, -1.0),\n", + " algorithm=om.algos.fides(convergence_gtol_abs=gtol),\n", + " )\n", + " rows[gtol] = {\n", + " \"iterations\": res.n_iterations,\n", + " \"distance to optimum\": np.abs(res.params - 1).max(),\n", + " }\n", + "\n", + "pd.DataFrame.from_dict(rows, orient=\"index\").rename_axis(\"convergence_gtol_abs\")" + ] + }, + { + "cell_type": "markdown", + "id": "25", + "metadata": {}, + "source": [ + "You can also limit the resources of a run with `stopping_maxiter` and\n", + "`stopping_maxtime` (in seconds). A run that hits one of these limits is reported as\n", + "not successful:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "26", + "metadata": {}, + "outputs": [], + "source": [ + "res = om.minimize(\n", + " fun=rosenbrock,\n", + " fun_and_jac=rosenbrock_and_gradient,\n", + " params=np.full(5, -1.0),\n", + " algorithm=om.algos.fides(stopping_maxiter=10),\n", + ")\n", + "res.success, res.message" + ] + }, + { + "cell_type": "markdown", + "id": "27", + "metadata": {}, + "source": [ + "## Fine-tuning the trust region\n", + "\n", + "After every step fides compares the actual improvement of the function with the\n", + "improvement its model predicted. Four options control how the radius of the trust\n", + "region reacts:\n", + "\n", + "| Option | Default | Effect |\n", + "| --- | --- | --- |\n", + "| `trustregion_shrinking_threshold` | 0.25 | The radius shrinks if the step achieved at most this share of the predicted improvement. |\n", + "| `trustregion_shrinking_factor` | 0.25 | The radius is multiplied by this factor when it shrinks. |\n", + "| `trustregion_expansion_threshold` | 0.75 | The radius can grow if the step achieved at least this share of the predicted improvement. |\n", + "| `trustregion_expansion_factor` | 2.0 | The radius is multiplied by this factor when it grows. |\n", + "\n", + "The defaults work well for most problems. Changing them is worth a try in two\n", + "situations:\n", + "\n", + "- The function has regions where it is not defined or changes abruptly. A smaller\n", + " expansion factor makes fides more careful after a good step.\n", + "- The start parameters are far from the optimum and the function is well behaved. A\n", + " larger expansion factor gets fides up to speed in fewer iterations.\n", + "\n", + "The following configuration is a cautious one for the generalized Pareto example\n", + "from above:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "28", + "metadata": {}, + "outputs": [], + "source": [ + "cautious = om.algos.fides(\n", + " trustregion_initial_radius=0.1,\n", + " trustregion_expansion_factor=1.5,\n", + " trustregion_shrinking_factor=0.1,\n", + ")\n", + "res = fit_pareto(cautious)\n", + "res.params.round(3), res.n_iterations" + ] + }, + { + "cell_type": "markdown", + "id": "29", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "| Situation | Option to try |\n", + "| --- | --- |\n", + "| The first steps leave the region where the function is defined | `trustregion_initial_radius`, `trustregion_expansion_factor` |\n", + "| Fides needs many iterations | `hessian_update=\"sr1\"` or a customized object from fides |\n", + "| Many parameters are at a bound | `stepback_strategy` |\n", + "| Many parameters and a cheap function | `subspace_solver=\"scg\"` |\n", + "| The solution is not precise enough | `convergence_gtol_abs` |\n", + "| The gradient is noisy and fides does not stop | `convergence_ftol_rel` |" + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/source/tutorials/index.md b/docs/source/tutorials/index.md index e9a6b1e26..bb2251096 100644 --- a/docs/source/tutorials/index.md +++ b/docs/source/tutorials/index.md @@ -67,6 +67,25 @@ Tutorial on the bayes_opt optimizer in optimagic. ```` +````{grid-item-card} +:text-align: center +:img-top: ../_static/images/optimization.svg +:class-img-top: index-card-image +:shadow: md + +```{button-link} fides_tutorial.html +--- +click-parent: +ref-type: ref +class: stretched-link index-card-link sd-text-primary +--- +fides Optimizer +``` + +Learn when and how to use the advanced options of fides. + +```` + ````` ```{toctree} @@ -77,4 +96,5 @@ maxdepth: 1 optimization_overview numdiff_overview bayes_opt_tutorial +fides_tutorial ``` diff --git a/pixi.lock b/pixi.lock index 622f06e18..56c9879c0 100644 --- a/pixi.lock +++ b/pixi.lock @@ -349,16 +349,16 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/zipp-3.23.0-pyhcf101f3_1.conda - pypi: ./ - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/51/fe/53ac0cd932db5dcaf55961bc7cb7afdca8d80d8cc7406ed661f0c7dc111a/pdbp-1.8.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/80/54/95a2d47e8ae8ba5c871be6cd7bba6c77f6af74c6966d8fb711710f03851e/optree-0.20.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl @@ -640,15 +640,15 @@ environments: - conda: https://conda.anaconda.org/conda-forge/osx-arm64/zstd-1.5.7-hbf9d68e_6.conda - pypi: ./ - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/51/fe/53ac0cd932db5dcaf55961bc7cb7afdca8d80d8cc7406ed661f0c7dc111a/pdbp-1.8.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl @@ -924,16 +924,16 @@ environments: - conda: https://conda.anaconda.org/conda-forge/win-64/zstd-1.5.7-h534d264_6.conda - pypi: ./ - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/51/fe/53ac0cd932db5dcaf55961bc7cb7afdca8d80d8cc7406ed661f0c7dc111a/pdbp-1.8.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/5a/dc/491b7661614ab97483abf2056be1deee4dc2490ecbf7bff9ab5cdbac86e1/pyreadline3-3.5.4-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl @@ -1307,17 +1307,17 @@ environments: - pypi: ./ - pypi: https://files.pythonhosted.org/packages/03/46/25d64bcd7821c8d6f1080e1c43d5fcdfc442a18f759a230b5ccdc891093e/sphinxcontrib_mermaid-2.0.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/51/fe/53ac0cd932db5dcaf55961bc7cb7afdca8d80d8cc7406ed661f0c7dc111a/pdbp-1.8.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/80/54/95a2d47e8ae8ba5c871be6cd7bba6c77f6af74c6966d8fb711710f03851e/optree-0.20.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b8/c9/11ccfaacd8bbc0398a113d9f7ca3592b18ec15a37e77fe7f9496a6d9f5f0/intersphinx_registry-0.2602.2-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl @@ -1633,16 +1633,16 @@ environments: - pypi: ./ - pypi: https://files.pythonhosted.org/packages/03/46/25d64bcd7821c8d6f1080e1c43d5fcdfc442a18f759a230b5ccdc891093e/sphinxcontrib_mermaid-2.0.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/51/fe/53ac0cd932db5dcaf55961bc7cb7afdca8d80d8cc7406ed661f0c7dc111a/pdbp-1.8.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b8/c9/11ccfaacd8bbc0398a113d9f7ca3592b18ec15a37e77fe7f9496a6d9f5f0/intersphinx_registry-0.2602.2-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl @@ -1952,17 +1952,17 @@ environments: - pypi: ./ - pypi: https://files.pythonhosted.org/packages/03/46/25d64bcd7821c8d6f1080e1c43d5fcdfc442a18f759a230b5ccdc891093e/sphinxcontrib_mermaid-2.0.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/51/fe/53ac0cd932db5dcaf55961bc7cb7afdca8d80d8cc7406ed661f0c7dc111a/pdbp-1.8.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/5a/dc/491b7661614ab97483abf2056be1deee4dc2490ecbf7bff9ab5cdbac86e1/pyreadline3-3.5.4-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b8/c9/11ccfaacd8bbc0398a113d9f7ca3592b18ec15a37e77fe7f9496a6d9f5f0/intersphinx_registry-0.2602.2-py2.py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl @@ -3039,11 +3039,11 @@ environments: - pypi: https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/29/13/dbb9d0aef7de6518f0b8b2de7850d3acec5b29693267a8d7596a4b0ecdb1/sqlalchemy-2.1.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/7f/75/8fc9fe1c135ada492258fda71cc6c5c555bc26db461387cfb824768ff0a1/pdbp-1.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/80/54/95a2d47e8ae8ba5c871be6cd7bba6c77f6af74c6966d8fb711710f03851e/optree-0.20.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/9a/0b/33e6e63d23691c4561a8a60e14c458dffa350b72255350dfdd008d6d838a/kaleido-1.5.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/a4/42/3b121b42b114919ffc6195a81c1c7065a465f62f46477fbdb87a07699e51/cloudpickle-3.1.3-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/cb/fc/8c82be70b8f96d09943360f34cfb2ecdd3035294c51bce4131eeabe56645/tabcompleter-1.4.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e2/01/2e202a5dda101b0bdc3cdef4e76d635e602efef8293e80c9c9b6570b56a0/simplejson-4.3.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl @@ -3293,10 +3293,10 @@ environments: - pypi: https://files.pythonhosted.org/packages/12/24/96b041b800d1de465758106353bedc1e682c5671b3a18142e71e67613996/choreographer-1.4.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/7f/75/8fc9fe1c135ada492258fda71cc6c5c555bc26db461387cfb824768ff0a1/pdbp-1.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/9a/0b/33e6e63d23691c4561a8a60e14c458dffa350b72255350dfdd008d6d838a/kaleido-1.5.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/a4/42/3b121b42b114919ffc6195a81c1c7065a465f62f46477fbdb87a07699e51/cloudpickle-3.1.3-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/bd/35/1b5aa5ddbbb28c47a68e2d247a6eac9b0118deef6530085c0b48eb6f4c5f/simplejson-4.3.0-cp314-cp314-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/cb/fc/8c82be70b8f96d09943360f34cfb2ecdd3035294c51bce4131eeabe56645/tabcompleter-1.4.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl @@ -3546,11 +3546,11 @@ environments: - pypi: https://files.pythonhosted.org/packages/12/24/96b041b800d1de465758106353bedc1e682c5671b3a18142e71e67613996/choreographer-1.4.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/7f/75/8fc9fe1c135ada492258fda71cc6c5c555bc26db461387cfb824768ff0a1/pdbp-1.9.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/83/01/83ddf9f0187fa5648ad5b6fc9300a050f854b3c0f657e06b3b687a5fbf14/simplejson-4.3.0-cp314-cp314-win_amd64.whl - pypi: https://files.pythonhosted.org/packages/9a/0b/33e6e63d23691c4561a8a60e14c458dffa350b72255350dfdd008d6d838a/kaleido-1.5.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/a4/42/3b121b42b114919ffc6195a81c1c7065a465f62f46477fbdb87a07699e51/cloudpickle-3.1.3-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/cb/fc/8c82be70b8f96d09943360f34cfb2ecdd3035294c51bce4131eeabe56645/tabcompleter-1.4.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/f2/23/75d736f3ece18dd459b8d123743c47d0a2e021435af8a1801f3393d5cff4/sqlalchemy-2.1.9-cp314-cp314-win_amd64.whl @@ -14466,21 +14466,21 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/zipp-3.23.0-pyhcf101f3_1.conda - pypi: ./ - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/36/3c/d49cf3f4489a10e9ddefde18fd258f120754c5825d06d145d9a0aaac770b/types_openpyxl-3.1.5.20250919-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/3e/54/3489432b1d9bc713c9d8aa810296b8f5b0088403662959fb63a8acdbd4fc/types_setuptools-82.0.0.20260210-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/51/fe/53ac0cd932db5dcaf55961bc7cb7afdca8d80d8cc7406ed661f0c7dc111a/pdbp-1.8.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7c/2f/f91e4eee21585ff548e83358332d5632ee49f6b2dcd96cb5dca4e0468951/pandas_stubs-3.0.0.260204-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/80/54/95a2d47e8ae8ba5c871be6cd7bba6c77f6af74c6966d8fb711710f03851e/optree-0.20.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/b0/e79d84748f1d34304f13191424348a719c3febaa3493835370fe9528e1e6/types_Jinja2-2.11.9-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/d6/b8effb1c48539260a5eb4196afc55efac4ea1684a4991977555eb266b2ef/types_MarkupSafe-1.1.10-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c8/15/4564f173d031f64bf56964d192b6b705e679fc23c02704b84ccbcb809396/types_cffi-1.17.0.20260307-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl @@ -14760,20 +14760,20 @@ environments: - conda: https://conda.anaconda.org/conda-forge/osx-arm64/zstd-1.5.7-hbf9d68e_6.conda - pypi: ./ - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/36/3c/d49cf3f4489a10e9ddefde18fd258f120754c5825d06d145d9a0aaac770b/types_openpyxl-3.1.5.20250919-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/3e/54/3489432b1d9bc713c9d8aa810296b8f5b0088403662959fb63a8acdbd4fc/types_setuptools-82.0.0.20260210-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/51/fe/53ac0cd932db5dcaf55961bc7cb7afdca8d80d8cc7406ed661f0c7dc111a/pdbp-1.8.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7c/2f/f91e4eee21585ff548e83358332d5632ee49f6b2dcd96cb5dca4e0468951/pandas_stubs-3.0.0.260204-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/b0/e79d84748f1d34304f13191424348a719c3febaa3493835370fe9528e1e6/types_Jinja2-2.11.9-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/d6/b8effb1c48539260a5eb4196afc55efac4ea1684a4991977555eb266b2ef/types_MarkupSafe-1.1.10-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c8/15/4564f173d031f64bf56964d192b6b705e679fc23c02704b84ccbcb809396/types_cffi-1.17.0.20260307-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl @@ -15047,7 +15047,6 @@ environments: - conda: https://conda.anaconda.org/conda-forge/win-64/zstd-1.5.7-h534d264_6.conda - pypi: ./ - pypi: https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/36/3c/d49cf3f4489a10e9ddefde18fd258f120754c5825d06d145d9a0aaac770b/types_openpyxl-3.1.5.20250919-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/3e/54/3489432b1d9bc713c9d8aa810296b8f5b0088403662959fb63a8acdbd4fc/types_setuptools-82.0.0.20260210-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl @@ -15055,13 +15054,14 @@ environments: - pypi: https://files.pythonhosted.org/packages/52/d2/c6e44dba74f17c6216ce1b56044a9b93a929f1c2d5bdaff892512b260f5e/plotly-6.6.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/5a/dc/491b7661614ab97483abf2056be1deee4dc2490ecbf7bff9ab5cdbac86e1/pyreadline3-3.5.4-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7c/2f/f91e4eee21585ff548e83358332d5632ee49f6b2dcd96cb5dca4e0468951/pandas_stubs-3.0.0.260204-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/9f/d73dfb85d7a5b1a56a99adc50f2074029468168c970ff5daeade4ad819e4/choreographer-1.2.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/b7/b0/e79d84748f1d34304f13191424348a719c3febaa3493835370fe9528e1e6/types_Jinja2-2.11.9-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/bc/d6/b8effb1c48539260a5eb4196afc55efac4ea1684a4991977555eb266b2ef/types_MarkupSafe-1.1.10-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/a0/5ff05d1919ca249508012cad89f08fdc6cfbdaa15b41651c5fe6dffaf1d3/dfo_ls-1.6.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c8/15/4564f173d031f64bf56964d192b6b705e679fc23c02704b84ccbcb809396/types_cffi-1.17.0.20260307-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d1/fd/5c2baba82425b75baf7dbec5af57219cd252aa8a1ace4f5cd1d88e472276/pyswarms-1.3.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/2a/4a9d31c685157d9bb82e1beee51e811dddd10d83cad3368630a9c1fd9e1a/bayesian_optimization-3.2.0-py3-none-any.whl @@ -33261,20 +33261,6 @@ packages: - platformdirs>=4.3.6 - simplejson>=3.19.3 requires_python: '>=3.9' -- pypi: https://files.pythonhosted.org/packages/13/40/e412e277c43983693456d7f11f2bc72ca9209aa1342255bb446496d2fb48/dfo_ls-1.6.2-py3-none-any.whl - name: dfo-ls - version: 1.6.2 - sha256: 961d15e7194f3868e9e48da45010cb6d24d85491007fbee4e38a9f3ab8050cef - requires_dist: - - setuptools - - numpy - - scipy>=1.11 - - pandas - - pytest ; extra == 'dev' - - sphinx ; extra == 'dev' - - sphinx-rtd-theme ; extra == 'dev' - - trustregion>=1.1 ; extra == 'trustregion' - requires_python: '>=3.9' - pypi: https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl name: joblib version: 1.6.0 @@ -33634,6 +33620,17 @@ packages: - pytest ; extra == 'dev' - twine ; extra == 'dev' requires_python: '>=3.8' +- pypi: https://files.pythonhosted.org/packages/5d/89/eea7d5f82d65fab90ec75782e899eda1b681cdff92462902d7950b7856d2/fides-0.8.2.tar.gz + name: fides + version: 0.8.2 + sha256: 5ea5fa718a4425b114db9e82ad9d7e6de726e0ef7f1a2f9d01574b6165c3e6dd + requires_dist: + - numpy>=1.19.2 + - scipy>=1.5.2 + - h5py>=3.5.0 + - pytest>=5.4.2 ; extra == 'test' + - pytest-cov>=4.0.0 ; extra == 'test' + requires_python: '>=3.12' - pypi: https://files.pythonhosted.org/packages/65/44/bb509c3d2c0b5a87e7a5af1d5917a402a32ff026f777a6d7cb6990746cbb/tabcompleter-1.4.0-py3-none-any.whl name: tabcompleter version: 1.4.0 @@ -33832,15 +33829,6 @@ packages: - envwrap ; extra == 'telegram' - ipywidgets>=6 ; extra == 'notebook' requires_python: '>=3.8' -- pypi: https://files.pythonhosted.org/packages/ac/5c/f176b0a5af2a69bd2ffa04cbdd937268373cb639e02196121cfc2f691647/fides-0.7.4.tar.gz - name: fides - version: 0.7.4 - sha256: 12f02d4c8451d9e08377162dd419f5872587c3bec043ca33a08fb990103468bb - requires_dist: - - numpy>=1.19.2 - - scipy>=1.5.2 - - h5py>=3.5.0 - requires_python: '>=3.7' - pypi: https://files.pythonhosted.org/packages/af/d0/0c2aaa6173accca6507d25a82c266af8c01d94138058e99712153d4296a6/gradient_free_optimizers-1.10.1-py3-none-any.whl name: gradient-free-optimizers version: 1.10.1 diff --git a/pyproject.toml b/pyproject.toml index 329c52591..5c9819995 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -296,6 +296,7 @@ filterwarnings = [ "ignore:The following exception was caught when evaluating", "ignore:The following exception was caught when calculating", "ignore:Usage of the parameter log_options", + "ignore:The default of the option `stepback_strategy` of the algorithm fides", ] addopts = ["--doctest-modules", "--pdbcls=pdbp:Pdb"] markers = [ @@ -485,7 +486,7 @@ bayesian-optimization = ">=1.4" # PyPI has no h5py wheels for the newest Python version yet. h5py = "*" [tool.pixi.feature.fides.pypi-dependencies] -fides = "==0.7.4" +fides = ">=0.8.2" [tool.pixi.feature.gfo.pypi-dependencies] gradient-free-optimizers = ">=1.6.0" @@ -501,8 +502,8 @@ iminuit = ">=2.25" cyipopt = ">=1.4.0" [tool.pixi.feature.nag.pypi-dependencies] -dfo-ls = ">=1.5.3" -py-bobyqa = ">=1.3" +dfo-ls = ">=1.6.5" +py-bobyqa = ">=1.5.0" # nevergrad_bo needs bayes-optim, which needs torch and scikit-learn. The conda-forge # CPU build of torch keeps the PyPI resolver from installing the much larger CUDA build. diff --git a/src/optimagic/mark.py b/src/optimagic/mark.py index 6c43e91a1..58df22703 100644 --- a/src/optimagic/mark.py +++ b/src/optimagic/mark.py @@ -1,9 +1,13 @@ from functools import wraps -from typing import Any, Callable, ParamSpec, Protocol, TypeVar, cast +from typing import Any, Callable, ParamSpec, Protocol, Sequence, TypeVar, cast import pydantic from optimagic.exceptions import InvalidAlgoOptionError +from optimagic.optimization.algo_option_tools import ( + DeprecatedOption, + replace_deprecated_options, +) from optimagic.optimization.algorithm import AlgoInfo from optimagic.typing import ( DEFAULT_PYDANTIC_CONFIG, @@ -145,3 +149,49 @@ def decorator(cls: AlgorithmSubclass) -> AlgorithmSubclass: return cast("AlgorithmSubclass", out) return decorator + + +def deprecated_options( + deprecated: Sequence[DeprecatedOption], +) -> Callable[[AlgorithmSubclass], AlgorithmSubclass]: + """Keep old option names of an algorithm working for one deprecation cycle. + + The old names are replaced by their new spelling with a ``FutureWarning`` wherever + options are set: when the algorithm is created, in ``with_option`` and in + ``algo_options``. + + The decorator has to be placed above ``mark.minimizer``: + + .. code-block:: python + + @mark.deprecated_options(DEPRECATED_OPTIONS) + @mark.minimizer(...) + @dataclass(frozen=True) + class MyAlgorithm(Algorithm): ... + + Args: + deprecated: The old option names with their replacements. + + """ + + def decorator(cls: AlgorithmSubclass) -> AlgorithmSubclass: + out = cast("Any", cls) + if getattr(out, "__algo_info__", None) is None: + msg = ( + "The `mark.deprecated_options` decorator has to be placed above the " + "`mark.minimizer` decorator." + ) + raise TypeError(msg) + + out.__deprecated_options__ = tuple(deprecated) + validated_init = out.__init__ + + @wraps(validated_init) + def __init__(self: Any, *args: Any, **kwargs: Any) -> None: + kwargs = replace_deprecated_options(kwargs, out) + validated_init(self, *args, **kwargs) + + out.__init__ = __init__ + return cls + + return decorator diff --git a/src/optimagic/optimization/algo_option_tools.py b/src/optimagic/optimization/algo_option_tools.py new file mode 100644 index 000000000..94e934041 --- /dev/null +++ b/src/optimagic/optimization/algo_option_tools.py @@ -0,0 +1,281 @@ +"""Tools for defining the options of algorithm wrappers. + +The module contains what wrappers need beyond plain dataclass fields: + +- :func:`option_group` validates a dataclass that bundles related options. +- :class:`DeprecatedOption` and :func:`replace_deprecated_options` keep old option + names working for one deprecation cycle. +- :func:`resolve_changed_default` announces a default that is about to change. + +""" + +from __future__ import annotations + +import warnings +from dataclasses import MISSING, dataclass, is_dataclass, replace +from typing import Any, Callable, Mapping, TypeVar, cast, get_args, get_type_hints + +import pydantic +from pydantic_core import core_schema + +from optimagic.exceptions import InvalidAlgoOptionError +from optimagic.typing import DEFAULT_PYDANTIC_CONFIG, validated_dataclass + +OptionGroupT = TypeVar("OptionGroupT") + + +def option_group(cls: type[OptionGroupT]) -> type[OptionGroupT]: + """Add validation to a frozen dataclass that bundles related algorithm options. + + Invalid entries raise an ``InvalidAlgoOptionError`` when the group is created. An + algorithm field that is annotated with the decorated class only accepts instances + of the class. Dictionaries are rejected. + + If the group belongs to a feature that can be switched on and off, annotate the + field of the algorithm with ``bool | `` instead of adding a switch + to the group: ``True`` switches the feature on with default entries, and an + instance switches it on with the given entries. + + Args: + cls: A frozen dataclass with one attribute per option of the group. + + Returns: + The class with validation added. + + """ + + def make_error(e: pydantic.ValidationError) -> Exception: + msg = f"The following entries of {cls.__name__} are invalid:\n\n{e}" + return InvalidAlgoOptionError(msg) + + out = validated_dataclass(config=DEFAULT_PYDANTIC_CONFIG, make_error=make_error)( + cls + ) + + def get_schema( + source: Any, handler: pydantic.GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + # A strict dataclass schema only accepts instances of the group wherever the + # group is used as a field of an algorithm. Without it, pydantic would also + # accept a dictionary with the entries of the group. The validator of the + # group itself uses the same schema; it still converts the entries when the + # group is created, because pydantic validates the arguments of __init__ + # independently of the strict flag. + schema = handler(source) + dataclass_schema = handler.resolve_ref_schema(schema) + cast("core_schema.DataclassSchema", dataclass_schema)["strict"] = True + return schema + + setattr(out, "__get_pydantic_core_schema__", get_schema) # noqa: B010 + return out + + +@dataclass(frozen=True) +class DeprecatedOption: + """An old spelling of an algorithm option that still works but warns.""" + + name: str + """The deprecated name of the option.""" + + replacement: str | Callable[[Any, Mapping[str, Any]], dict[str, Any]] + """The new spelling of the option. + + Either the name of the option that takes over the value unchanged, or a function + that returns a dictionary of new option names and values. The function is called + with the deprecated value and with all options that were passed together with it, + for the case that the new spelling depends on another option. + + An entry of an option group is addressed as ``"."``, e.g. + ``"trustregion_options.shrinking_factor"``. If the option also accepts a boolean + (``bool | ``), setting an entry switches the feature on, and the + option itself can be set to ``True`` or ``False``. + + """ + + removed_in: str + """The optimagic version in which the deprecated name stops working.""" + + +def replace_deprecated_options(options: Mapping[str, Any], algo: Any) -> dict[str, Any]: + """Replace deprecated algorithm options by their new spelling. + + Every deprecated option that is found emits a ``FutureWarning`` that shows the new + spelling. + + Args: + options: The options as passed by the user. + algo: The algorithm class if the options are used to create an algorithm, or + the configured algorithm if the options are applied to it. With a + configured algorithm, entries of option groups that are not replaced keep + their current values instead of falling back to their defaults. + + Returns: + The options with all deprecated names replaced. + + Raises: + InvalidAlgoOptionError: If a deprecated option is combined with the option or + option group that replaces it, or if two deprecated options translate to + different values of the same new option. + + """ + out = dict(options) + present = [dep for dep in algo.__deprecated_options__ if dep.name in out] + if not present: + return out + + algo_name = algo.name + group_updates: dict[str, dict[str, Any]] = {} + + for dep in present: + value = out.pop(dep.name) + if isinstance(dep.replacement, str): + new = {dep.replacement: value} + else: + new = dep.replacement(value, options) + + warnings.warn(_deprecation_message(dep, new, algo), FutureWarning, stacklevel=3) + + for target, new_value in new.items(): + group, _, entry = target.partition(".") + if not entry: + if target in options: + raise _mixed_spelling_error(dep.name, target, algo_name) + is_contradiction = target in group_updates or ( + target in out and not _is_same(out[target], new_value) + ) + if is_contradiction: + raise _conflicting_values_error(dep.name, target, algo_name) + out[target] = new_value + else: + if group in options: + raise _mixed_spelling_error(dep.name, group, algo_name) + if group in out: + raise _conflicting_values_error(dep.name, group, algo_name) + updates = group_updates.setdefault(group, {}) + if entry in updates and not _is_same(updates[entry], new_value): + raise _conflicting_values_error(dep.name, target, algo_name) + updates[entry] = new_value + + for group, updates in group_updates.items(): + out[group] = replace(_get_option_group(algo, group), **updates) + + return out + + +def _get_option_group(algo: Any, group: str) -> Any: + """Get the option group that entries of deprecated options are merged into. + + This is the current value of the group for a configured algorithm and its default + for an algorithm class. If the value is not a group but a boolean or None, i.e. + the option is annotated as ``bool | ``, it is a group with default + entries. + + """ + if not isinstance(algo, type): + value = getattr(algo, group) + algo_cls = type(algo) + else: + field = algo.__dataclass_fields__[group] + has_factory = field.default_factory is not MISSING + value = field.default_factory() if has_factory else field.default + algo_cls = algo + + if is_dataclass(value): + return value + + annotation = get_type_hints(algo_cls)[group] + candidates = [annotation, *get_args(annotation)] + group_cls = next(c for c in candidates if isinstance(c, type) and is_dataclass(c)) + return group_cls() + + +def resolve_changed_default( + value: Any, + *, + option: str, + old_default: Any, + new_default: Any, + algo_name: str, + changed_in: str, +) -> Any: + """Get the value of an option whose default is about to change. + + During the deprecation cycle the option has the default ``None``, which stands + for "not set by the user". In this case the old default is used and a + ``FutureWarning`` announces the new one. + + Args: + value: The value of the option. ``None`` if the user did not set it. + option: The name of the option. + old_default: The default that is still used. + new_default: The default that will be used from ``changed_in`` on. + algo_name: The name of the algorithm. + changed_in: The optimagic version in which the default changes. + + Returns: + ``value`` if it is not ``None``, otherwise ``old_default``. + + """ + if value is not None: + return value + + msg = ( + f"The default of the option `{option}` of the algorithm {algo_name} will " + f"change from {old_default!r} to {new_default!r} in optimagic {changed_in}. " + f"Set `{option}` explicitly to choose one of them and to silence this warning." + ) + warnings.warn(msg, FutureWarning, stacklevel=2) + return old_default + + +def _deprecation_message( + dep: DeprecatedOption, new: Mapping[str, Any], algo: Any +) -> str: + msg = ( + f"The option `{dep.name}` of the algorithm {algo.name} is deprecated and will " + f"be removed in optimagic {dep.removed_in}. " + ) + if not new: + return msg + "The value you passed has no effect." + + flat: dict[str, Any] = {} + groups: dict[str, dict[str, Any]] = {} + for target, value in new.items(): + group, _, entry = target.partition(".") + if entry: + groups.setdefault(group, {})[entry] = value + else: + flat[target] = value + + parts = [f"{name}={value!r}" for name, value in flat.items()] + for group, entries in groups.items(): + group_cls = type(_get_option_group(algo, group)).__name__ + args = ", ".join(f"{name}={value!r}" for name, value in entries.items()) + parts.append(f"{group}={group_cls}({args})") + return msg + f"Use `{', '.join(parts)}` instead." + + +def _mixed_spelling_error(old: str, new: str, algo_name: str) -> InvalidAlgoOptionError: + msg = ( + f"The deprecated option `{old}` of the algorithm {algo_name} cannot be " + f"combined with `{new}`, which replaces it. Use only `{new}`." + ) + return InvalidAlgoOptionError(msg) + + +def _conflicting_values_error( + old: str, new: str, algo_name: str +) -> InvalidAlgoOptionError: + msg = ( + f"The deprecated option `{old}` of the algorithm {algo_name} translates to " + f"a value of `{new}` that contradicts another deprecated option you passed. " + f"Use `{new}` instead of the deprecated options." + ) + return InvalidAlgoOptionError(msg) + + +def _is_same(left: Any, right: Any) -> bool: + try: + return bool(left == right) + except Exception: + return left is right diff --git a/src/optimagic/optimization/algorithm.py b/src/optimagic/optimization/algorithm.py index c66e55808..77caa33c0 100644 --- a/src/optimagic/optimization/algorithm.py +++ b/src/optimagic/optimization/algorithm.py @@ -11,6 +11,10 @@ from optimagic.exceptions import InvalidAlgoInfoError, InvalidAlgoOptionError from optimagic.logging.types import StepStatus +from optimagic.optimization.algo_option_tools import ( + DeprecatedOption, + replace_deprecated_options, +) from optimagic.optimization.history import History from optimagic.optimization.internal_optimization_problem import ( InternalOptimizationProblem, @@ -139,6 +143,9 @@ class Algorithm(ABC, metaclass=AlgorithmMeta): __algo_info__: ClassVar[AlgoInfo | None] = None """Information about the algorithm; set by the `mark.minimizer` decorator.""" + __deprecated_options__: ClassVar[tuple[DeprecatedOption, ...]] = () + """Old option names that still work; set by `mark.deprecated_options`.""" + @abstractmethod def _solve_internal_problem( self, problem: InternalOptimizationProblem, x0: NDArray[np.float64] @@ -147,6 +154,7 @@ def _solve_internal_problem( def with_option(self, **kwargs: Any) -> Self: """Create a modified copy with the given options.""" + kwargs = replace_deprecated_options(kwargs, self) valid_keys = set(self.__dataclass_fields__) - {"__algo_info__"} invalid = set(kwargs) - valid_keys if invalid: @@ -211,6 +219,7 @@ def solve_internal_problem( def with_option_if_applicable(self, **kwargs: Any) -> Self: """Call with_option only with applicable keyword arguments.""" + kwargs = replace_deprecated_options(kwargs, self) valid_keys = set(self.__dataclass_fields__) - {"__algo_info__"} invalid = set(kwargs) - valid_keys if invalid: diff --git a/src/optimagic/optimizers/fides.py b/src/optimagic/optimizers/fides.py index 3f307f5db..ea660d866 100644 --- a/src/optimagic/optimizers/fides.py +++ b/src/optimagic/optimizers/fides.py @@ -4,14 +4,19 @@ import logging from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Callable, Literal, TypeAlias, cast +from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeAlias import numpy as np +from annotated_types import Ge, Gt, Lt from numpy.typing import NDArray from optimagic import mark from optimagic.config import IS_FIDES_INSTALLED from optimagic.exceptions import NotInstalledError +from optimagic.optimization.algo_option_tools import ( + DeprecatedOption, + resolve_changed_default, +) from optimagic.optimization.algo_options import ( CONVERGENCE_FTOL_ABS, CONVERGENCE_FTOL_REL, @@ -26,9 +31,11 @@ ) from optimagic.typing import ( AggregationLevel, + GtOneFloat, NonNegativeFloat, PositiveFloat, PositiveInt, + UnitIntervalFloat, ) if TYPE_CHECKING: @@ -39,13 +46,80 @@ # importing it at optimagic import time. HessianApproximation = Any -HessianUpdateStrategy: TypeAlias = ( - Literal["bfgs", "bb", "bg", "dfp", "sr1"] | str | HessianApproximation +HessianUpdate: TypeAlias = ( + Literal["bfgs", "sr1", "dfp", "bg", "bb"] | str | HessianApproximation ) -"""Hessian update strategies: a case-insensitive name or a HessianApproximation +"""Hessian approximations of fides: a case-insensitive name or a HessianApproximation instance from fides.""" +SubspaceSolver: TypeAlias = Literal["2D", "full", "scg"] +"""Solvers for the trust-region subproblem of fides.""" + +StepbackStrategy: TypeAlias = Literal[ + "reflect", "reflect_single", "truncate", "mixed", "refine" +] +"""Strategies of fides for steps that would cross a bound.""" + +FIDES_OPTION_NAMES = { + "maxiter": "stopping_maxiter", + "maxtime": "stopping_maxtime", + "fatol": "convergence_ftol_abs", + "frtol": "convergence_ftol_rel", + "xtol": "convergence_xtol_abs", + "gatol": "convergence_gtol_abs", + "grtol": "convergence_gtol_rel", + "subspace_solver": "subspace_solver", + "stepback_strategy": "stepback_strategy", + "theta_max": "max_stepback_fraction", + "delta_init": "trustregion_initial_radius", + "mu": "trustregion_shrinking_threshold", + "eta": "trustregion_expansion_threshold", + "gamma1": "trustregion_shrinking_factor", + "gamma2": "trustregion_expansion_factor", +} +"""The option names of ``fides.Optimizer`` and the optimagic options they are set by.""" + +FIDES_OPTIONS_NOT_EXPOSED = { + "history_file": "optimagic collects the history and can log it to a database.", +} +"""Options of ``fides.Optimizer`` that cannot be set, with the reason.""" + +FIDES_DEVIATING_DEFAULTS = { + "stopping_maxiter": "harmonized across optimagic", + "convergence_ftol_abs": "harmonized across optimagic", + "convergence_ftol_rel": "harmonized across optimagic", + "convergence_gtol_abs": "harmonized across optimagic", + "convergence_gtol_rel": "harmonized across optimagic", + "subspace_solver": "'full' has less overhead than '2D' at similar step quality", + "stepback_strategy": "changes to the fides default in optimagic 0.7.0", +} +"""Options whose default differs from the default of fides, with the reason.""" + +FIDES_DEPRECATED_OPTIONS = ( + DeprecatedOption("hessian_update_strategy", "hessian_update", "0.7.0"), + DeprecatedOption("stopping_max_seconds", "stopping_maxtime", "0.7.0"), + DeprecatedOption("trustregion_subspace_dimension", "subspace_solver", "0.7.0"), + DeprecatedOption("trustregion_stepback_strategy", "stepback_strategy", "0.7.0"), + DeprecatedOption( + "trustregion_max_stepback_fraction", "max_stepback_fraction", "0.7.0" + ), + DeprecatedOption( + "trustregion_decrease_threshold", "trustregion_shrinking_threshold", "0.7.0" + ), + DeprecatedOption( + "trustregion_increase_threshold", "trustregion_expansion_threshold", "0.7.0" + ), + DeprecatedOption( + "trustregion_decrease_factor", "trustregion_shrinking_factor", "0.7.0" + ), + DeprecatedOption( + "trustregion_increase_factor", "trustregion_expansion_factor", "0.7.0" + ), +) +"""Option names of the fides wrapper that are deprecated.""" + +@mark.deprecated_options(FIDES_DEPRECATED_OPTIONS) @mark.minimizer( name="fides", solver_type=AggregationLevel.SCALAR, @@ -65,417 +139,412 @@ class Fides(Algorithm): """Minimize a scalar function using the Fides trust-region optimizer. - Fides implements an Interior Trust-Region Reflective method for bound-constrained - optimization, following the approach of :cite:`Coleman1994` and - :cite:`Coleman1996`. Accordingly, Fides is named after the Roman goddess of trust - and reliability. The optimizer is taken from the ``fides`` package - (:cite:`Froehlich2022`), which must be installed separately - (``pip install "fides>=0.7.4"``). - - Fides is a gradient-based local optimizer for smooth, differentiable scalar - objective functions. It supports lower and upper bounds (including infinite - bounds) but no linear or nonlinear constraints. It requires first derivatives; the - Hessian is approximated internally using one of several quasi-Newton update - strategies, so no user-provided Hessian is needed. - - In contrast to many other trust-region methods, Fides can solve the full - trust-region subproblem exactly rather than approximately; this is the case for - the default ``trustregion_subspace_dimension="full"``. This can yield - higher-quality proposal steps at a higher per-iteration cost, which makes Fides - especially attractive when the objective function is expensive to evaluate and - the cost of solving the trust-region subproblem is negligible in comparison. - - .. note:: - General linear and nonlinear constraints are not supported by optimagic. + Fides is a gradient-based local optimizer for smooth scalar functions with or + without bounds. It is a good choice if evaluating the function and its gradient + is expensive, because it spends more effort than line-search methods such as + L-BFGS-B on choosing each step and typically needs fewer evaluations in return. + The price is a matrix factorization per iteration, so it is less suited for + problems with thousands of parameters. + + In each iteration, fides builds a quadratic model of the function from the + gradient and an approximation of the Hessian and minimizes it within a trust + region, i.e. the region around the current parameters in which the model is + trusted. The radius of the region grows when the model predicts the function + well and shrinks when it does not. Bounds are handled with the interior + trust-region reflective approach of :cite:`Coleman1994` and :cite:`Coleman1996`: + The parameters stay strictly inside the bounds and steps that would cross a + bound are reflected or truncated. Fides is named after the Roman goddess of + trust and reliability. + + Fides is highly configurable. You can choose how the Hessian is approximated + (``hessian_update``), how the model is minimized (``subspace_solver``), what + happens at bounds (``stepback_strategy``) and how the trust-region radius is + managed. The :ref:`fides tutorial ` shows when and how to use + these options. + + The optimizer is taken from the ``fides`` package (:cite:`Froehlich2022`), which + must be installed separately (``pip install "fides>=0.8.2"``). + + The following features of fides are not supported yet: + + - Exact Hessians and the hybrid Hessian approximations that need them + (``HybridFixed``, ``HybridFraction``), because optimagic does not pass + user-provided Hessians to optimizers. + - Least-squares problems (``resfun=True``) and the Hessian approximations that + need residuals (``FX``, ``SSM``, ``TSSM``, ``GNSBFGS``). + - A custom initial Hessian approximation (``hess0``). The approximation always + starts with the identity matrix. + - The history file of fides (``history_file``). Use optimagic's history and + logging instead. """ - hessian_update_strategy: HessianUpdateStrategy = "bfgs" - r"""Quasi-Newton strategy used to approximate the Hessian of the objective. - - Can be the (case-insensitive) name of a strategy or an instance of - ``fides.hessian_approximation.HessianApproximation``. The available names are: - - - ``"bfgs"``: the Broyden-Fletcher-Goldfarb-Shanno update, a rank-2 update that - preserves symmetry and positive definiteness. This is the default. - - ``"dfp"``: the Davidon-Fletcher-Powell update. - - ``"sr1"``: the Symmetric Rank 1 update, described in :cite:`Nocedal1999`, - Chapter 6.2. - - ``"bb"``: Broyden's "bad" method, introduced in :cite:`Broyden1965`. - - ``"bg"``: Broyden's "good" method, introduced in :cite:`Broyden1965`. - - The general Broyden class update is a convex combination of the BFGS and DFP - updates controlled by an interpolation parameter :math:`\phi` - (:cite:`Nocedal1999`, Chapter 6.3): :math:`\phi = 0` gives BFGS and - :math:`\phi = 1` gives DFP. For :math:`\phi \in [0, 1]` the update preserves - symmetry and positive semi-definiteness. It cannot be selected by name because - :math:`\phi` has no default; instead, create an instance of - ``fides.hessian_approximation.Broyden`` with the desired :math:`\phi` and pass - it here. - - The residual-based approximations ``FX``, ``SSM``, ``TSSM`` and ``GNSBFGS`` - provided by the ``fides`` package are not available, because optimagic does not - pass least-squares residuals to fides. + hessian_update: HessianUpdate = "bfgs" + r"""How the Hessian of the function is approximated from gradients. + + The approximation determines the quality of the quadratic model and therefore + of the steps. You can pass a (case-insensitive) name: + + - ``"bfgs"``: The standard choice. The approximation is always positive + definite, which is reliable for most problems but cannot represent negative + curvature. + - ``"sr1"``: Can represent negative curvature. Try it if the function is far + from convex, e.g. if ``"bfgs"`` makes slow progress around saddle points. + - ``"dfp"``, ``"bg"`` and ``"bb"``: Older update formulas that mostly serve as + comparison. They typically converge much more slowly than ``"bfgs"`` and + ``"sr1"``. + + For more control, pass an instance of a class from + ``fides.hessian_approximation``, for example ``BFGS(enforce_curv_cond=False)`` + to also update the approximation after steps that violate the curvature + condition, or ``Broyden(phi=0.5)`` for a mix of BFGS and DFP. The classes that + need exact Hessians or residuals are not supported. + + This is the ``hessian_update`` argument of ``fides.Optimizer``. Without it, fides + expects exact Hessians, which optimagic cannot provide, so optimagic defaults to + ``"bfgs"``. """ convergence_ftol_abs: NonNegativeFloat = CONVERGENCE_FTOL_ABS - r"""Stop when the absolute change in the objective becomes small. + r"""Stop when the function value changes by less than this between iterations. - Denoting the absolute criterion tolerance by :math:`\alpha` (this parameter) and - the relative criterion tolerance by :math:`\beta` - (``convergence_ftol_rel``), Fides stops successfully when + This criterion measures progress, not closeness to an optimum. It is a safety + net for problems where the gradient criteria cannot be met, e.g. because the + gradient is noisy. Increase it to stop earlier on such problems. Together with + ``convergence_ftol_rel``, fides stops when .. math:: - |f_k - f_{k-1}| < \alpha + \beta \, |f_{k-1}| + |f_k - f_{k-1}| < \text{ftol\_abs} + \text{ftol\_rel} \cdot |f_{k-1}| - in an iteration in which the trust-region radius was not increased. Here, - :math:`f_k` is the objective value at the proposed point and :math:`f_{k-1}` the - one at the current iterate. + after a successful step that was not limited by the trust region. - This parameter therefore governs convergence on its own only when - ``convergence_ftol_rel`` is set to 0. Note that optimagic defaults to 0, whereas - the ``fides`` package itself defaults to 1e-8. + This is the ``fatol`` option of fides. The default of 0 is harmonized across + optimagic and means that only the relative tolerance is used; fides defaults to + 1e-8. """ convergence_ftol_rel: NonNegativeFloat = CONVERGENCE_FTOL_REL - r"""Stop when the relative change in the objective becomes small. + r"""Stop when the relative change of the function value between iterations is + smaller than this. - This is the relative criterion tolerance :math:`\beta` in the joint convergence - condition documented under ``convergence_ftol_abs``. It governs convergence on its - own only when ``convergence_ftol_abs`` is set to 0 (as is the default). Note that - optimagic defaults to 2e-9, whereas the ``fides`` package itself defaults to - 1e-8. + This criterion measures progress, not closeness to an optimum; see + ``convergence_ftol_abs`` for the formula. Increase it to stop earlier if function + evaluations are expensive and a rough solution is enough. Set it to 0 to rely on + the gradient criteria alone. + + This is the ``frtol`` option of fides. The default of 2e-9 is harmonized across + optimagic and stricter than the fides default of 1e-8, so that most runs are + ended by a gradient criterion. """ convergence_xtol_abs: NonNegativeFloat = CONVERGENCE_XTOL_ABS - r"""Stop when the step size becomes small. + r"""Stop when a successful step is shorter than this. + + The length is the Euclidean norm of the step, :math:`\|x_k - x_{k-1}\|`, measured + in coordinates that are rescaled close to bounds. Like the function tolerances, + this criterion measures progress and not closeness to an optimum. - The optimization terminates successfully when the norm of the step - :math:`\|x_{k} - x_{k-1}\|` falls below this tolerance. + This is the ``xtol`` option of fides. The default of 0 switches the criterion + off, as in fides. """ convergence_gtol_abs: NonNegativeFloat = CONVERGENCE_GTOL_ABS - """Stop when the gradient norm is less than or equal to this tolerance. + r"""Stop when the norm of the gradient is at most this value. - Note that optimagic defaults to 1e-5, whereas the ``fides`` package itself - defaults to 1e-6. + A small gradient means that the parameters are close to a local optimum, so this + is the main convergence criterion. Decrease it for a more precise solution; + increase it if the gradient is too noisy to become this small. For parameters at + a bound, only the part of the gradient that points into the feasible region + counts. + + This is the ``gatol`` option of fides. The default of 1e-5 is harmonized across + optimagic; fides defaults to 1e-6. """ convergence_gtol_rel: NonNegativeFloat = CONVERGENCE_GTOL_REL - """Stop when the gradient norm divided by the absolute function value is less than - or equal to this tolerance. + r"""Stop when the norm of the gradient is at most this value times the absolute + function value. + + This makes the gradient criterion independent of the scale of the function, + i.e. fides stops when :math:`\|g_k\| \leq \text{gtol\_rel} \cdot |f_k|`. It has + no effect if the function value at the optimum is zero. - Note that optimagic defaults to 1e-8, whereas the ``fides`` package itself - defaults to 0, i.e. deactivates this criterion. + This is the ``grtol`` option of fides. The default of 1e-8 is harmonized across + optimagic; fides defaults to 0, which switches the criterion off. """ stopping_maxiter: PositiveInt = STOPPING_MAXITER """Maximum number of iterations. - Note that optimagic defaults to 1,000,000, whereas the ``fides`` package itself - defaults to 1,000. + Each iteration evaluates the function and its gradient once. If the limit is + reached, the optimization stops without success. + + This is the ``maxiter`` option of fides. The default of 1,000,000 is harmonized + across optimagic; fides defaults to 1,000. """ - stopping_max_seconds: float = np.inf - """Maximum number of wall-clock seconds. Deactivated (infinite) by default.""" + stopping_maxtime: PositiveFloat = np.inf + """Maximum runtime in seconds. - trustregion_initial_radius: PositiveFloat = 1.0 - """Initial trust-region radius.""" + Fides stops before an iteration if it expects that the iteration would exceed + the limit, based on the average duration of the previous iterations. - trustregion_stepback_strategy: Literal[ - "truncate", - "reflect", - "reflect_single", - "mixed", - ] = "truncate" - """Refinement strategy applied when a proposed step reaches a parameter bound. + This is the ``maxtime`` option of fides. As in fides, there is no limit by + default. - The available options are: + """ - - ``"truncate"``: truncate the step at the boundary and re-solve the restricted - subproblem. This is optimagic's default. - - ``"reflect"``: recursive reflections at the boundary. - - ``"reflect_single"``: a single reflection at the boundary. - - ``"mixed"``: mix reflections and truncations. + trustregion_initial_radius: PositiveFloat = 1.0 + """Radius of the trust region in the first iteration. - Note that optimagic defaults to ``"truncate"``, whereas the ``fides`` package - itself defaults to ``"reflect"``. + The radius limits the length of the first step, measured in the units of the + parameters. Decrease it if the first steps lead into regions where the function + is not defined or behaves very differently than at the start parameters. + Increase it if the start parameters are far from the optimum and the first + steps are too cautious. After the first iterations the radius adapts itself. + + This is the ``delta_init`` option of fides and has the same default. """ - trustregion_subspace_dimension: Literal[ - "full", - "2D", - "scg", - ] = "full" - """Dimension of the subspace in which the trust-region subproblem is solved. + stepback_strategy: StepbackStrategy | None = None + """What happens with a step that would cross a bound. + + The option only matters for problems with bounds, and mostly if several + parameters are at a bound at the optimum. + + - ``"reflect"``: The step is reflected at each bound it reaches, like a ball + bouncing off a wall. This is the default of fides. + - ``"reflect_single"``: Like ``"reflect"``, but with at most one reflection. + - ``"truncate"``: The step is cut off at the bound. Then the parameters at the + bound are fixed and the step is recomputed for the remaining ones. + - ``"mixed"``: Fides computes reflected and truncated steps and takes the one + that promises the larger improvement. + - ``"refine"``: The reflected step is improved by an additional optimization of + the model inside the bounds. This can save iterations if many bounds are + active. + + This is the ``stepback_strategy`` option of fides. The default None currently + means ``"truncate"`` and emits a warning if the problem has bounds; from + optimagic 0.7.0 on the default is ``"reflect"``, the default of fides. + + """ - The available options are: + subspace_solver: SubspaceSolver = "full" + """How the quadratic model is minimized inside the trust region. - - ``"full"``: use the full parameter dimensionality. This is optimagic's default. - - ``"2D"``: a two-dimensional Newton/gradient subspace. - - ``"scg"``: a conjugate-gradient subspace via Steihaug's method. + - ``"full"``: Minimize the model exactly over all parameters. This gives the + best step the model can offer. + - ``"2D"``: Only search the plane spanned by the gradient and the Newton + direction. The steps are usually almost as good as the exact ones. This is + the default of fides. + - ``"scg"``: Use a conjugate gradient method that stops early. With hundreds of + parameters, an iteration is much cheaper but more iterations are needed. Use + it if the function is cheap to evaluate and most of the runtime is spent + inside the optimizer. - Note that optimagic defaults to ``"full"``, whereas the ``fides`` package itself - defaults to ``"2D"``. + This is the ``subspace_solver`` option of fides. optimagic defaults to + ``"full"`` instead of ``"2D"`` because in benchmarks with fides 0.8.2 it needed + about the same number of function evaluations and less computation time per + iteration. """ - trustregion_max_stepback_fraction: float = 0.95 - """Controls how close steps are allowed to get to the boundary. + max_stepback_fraction: UnitIntervalFloat = 0.95 + """How close a single step may get to a bound. + + If a step would hit a bound, fides takes at most this fraction of the way to + the bound, so the parameters always stay strictly inside the bounds. Values + closer to 1 let the parameters approach a bound in fewer iterations. Smaller + values keep more distance to the bounds in every step. The fraction increases + automatically towards 1 as the optimizer converges. - It is the maximal fraction of a step to take if the full step would reach a - breakpoint (the bound). + This is the ``theta_max`` option of fides and has the same default. """ - trustregion_decrease_threshold: float = 0.25 - r"""Threshold for the trust-region ratio at or below which the radius is decreased. + trustregion_shrinking_threshold: Annotated[float, Ge(0), Lt(1)] = 0.25 + """The trust region shrinks after steps whose quality is at or below this value. + + The quality of a step is the actual improvement of the function divided by the + improvement the model predicted. Larger values shrink the region more often, + which is more cautious but can slow down progress. The threshold does not decide + whether a step is accepted: Every step that improves the function is accepted. - Note that this is not an acceptance threshold: fides accepts every step with a - positive trust-region ratio. This is the ``mu`` option of fides; its default is - the value used in algorithm 4.1 of :cite:`Nocedal2006`. + This is the ``mu`` option of fides and has the same default. """ - trustregion_increase_threshold: float = 0.75 - r"""Threshold for the trust-region ratio at or above which the radius may be - increased. + trustregion_expansion_threshold: Annotated[float, Ge(0), Lt(1)] = 0.75 + """The trust region can grow after steps whose quality is at or above this value. - The radius is only increased if, in addition, the norm of the proposed step is at - least 90% of the current radius. This is the ``eta`` option of fides; its default - is the value used in algorithm 4.1 of :cite:`Nocedal2006`. + The quality of a step is the actual improvement of the function divided by the + improvement the model predicted. Smaller values let the region grow more easily, + which leads to longer steps and is useful if the function is well approximated + by a quadratic model. The region only grows after steps that used at least 90 + percent of the current radius. + + This is the ``eta`` option of fides and has the same default. """ - trustregion_decrease_factor: float = 0.25 - r"""Factor by which the trust-region radius is multiplied when it is decreased. + trustregion_shrinking_factor: Annotated[float, Gt(0), Lt(1)] = 0.25 + """Factor by which the radius of the trust region is multiplied when it shrinks. + + Smaller values shrink the region faster. This helps if the optimizer needs + several unsuccessful steps in a row before it makes progress again, e.g. on + functions that are not defined everywhere. The new radius is never larger than + a quarter of the length of the unsuccessful step, so values above 0.25 rarely + make a difference. - More precisely, the decreased radius is :math:`\min(\gamma_1 \Delta, \|s\| / 4)`, - where :math:`\gamma_1` is this factor, :math:`\Delta` the current radius and - :math:`s` the proposed step. This is the ``gamma1`` option of fides; its default - is the value used in algorithm 4.1 of :cite:`Nocedal2006`. + This is the ``gamma1`` option of fides and has the same default. """ - trustregion_increase_factor: float = 2.0 - r"""Factor by which the trust-region radius is multiplied when it is increased. + trustregion_expansion_factor: GtOneFloat = 2.0 + """Factor by which the radius of the trust region is multiplied when it grows. + + Larger values lead to longer steps more quickly, which saves iterations if the + start parameters are far from the optimum, but makes unsuccessful steps more + likely. - This is the ``gamma2`` option of fides; its default is the value used in - algorithm 4.1 of :cite:`Nocedal2006`. + This is the ``gamma2`` option of fides and has the same default. """ def _solve_internal_problem( self, problem: InternalOptimizationProblem, x0: NDArray[np.float64] ) -> InternalOptimizeResult: - res = fides_internal( - fun_and_jac=cast( - Callable[[NDArray[np.float64]], NDArray[np.float64]], - problem.fun_and_jac, - ), - x=x0, - lower_bounds=problem.bounds.lower, - upper_bounds=problem.bounds.upper, - hessian_update_strategy=self.hessian_update_strategy, - convergence_ftol_abs=self.convergence_ftol_abs, - convergence_ftol_rel=self.convergence_ftol_rel, - convergence_xtol_abs=self.convergence_xtol_abs, - convergence_gtol_abs=self.convergence_gtol_abs, - convergence_gtol_rel=self.convergence_gtol_rel, - stopping_maxiter=self.stopping_maxiter, - stopping_max_seconds=self.stopping_max_seconds, - trustregion_initial_radius=self.trustregion_initial_radius, - trustregion_stepback_strategy=self.trustregion_stepback_strategy, - trustregion_subspace_dimension=self.trustregion_subspace_dimension, - trustregion_max_stepback_fraction=self.trustregion_max_stepback_fraction, - trustregion_decrease_threshold=self.trustregion_decrease_threshold, - trustregion_increase_threshold=self.trustregion_increase_threshold, - trustregion_decrease_factor=self.trustregion_decrease_factor, - trustregion_increase_factor=self.trustregion_increase_factor, + if not IS_FIDES_INSTALLED: + raise NotInstalledError( + "The 'fides' algorithm requires the fides package to be installed. " + 'You can install it with `pip install "fides>=0.8.2"`.' + ) + + from fides import Optimizer + + options = { + fides_name: getattr(self, optimagic_name) + for fides_name, optimagic_name in FIDES_OPTION_NAMES.items() + } + n_params = len(x0) + lower = problem.bounds.lower + upper = problem.bounds.upper + lower = np.full(n_params, -np.inf) if lower is None else lower + upper = np.full(n_params, np.inf) if upper is None else upper + + if np.isfinite(lower).any() or np.isfinite(upper).any(): + options["stepback_strategy"] = resolve_changed_default( + self.stepback_strategy, + option="stepback_strategy", + old_default="truncate", + new_default="reflect", + algo_name="fides", + changed_in="0.7.0", + ) + elif self.stepback_strategy is None: + # Without bounds the strategy is never used, so there is nothing to + # warn about. + options["stepback_strategy"] = "reflect" + + n_evals = 0 + + def fun_and_jac(x: NDArray[np.float64]) -> Any: + # fides does not count its evaluations. It always evaluates the function + # and the gradient together. + nonlocal n_evals + n_evals += 1 + return problem.fun_and_jac(x) + + opt = Optimizer( + fun=fun_and_jac, + lb=lower, + ub=upper, + verbose=logging.ERROR, + options=options, + funargs=None, + hessian_update=_create_hessian_update(self.hessian_update), + resfun=False, ) - - return res - - -def fides_internal( - fun_and_jac: Callable[[NDArray[np.float64]], NDArray[np.float64]], - x: NDArray[np.float64], - lower_bounds: NDArray[np.float64] | None, - upper_bounds: NDArray[np.float64] | None, - hessian_update_strategy: HessianUpdateStrategy, - convergence_ftol_abs: NonNegativeFloat, - convergence_ftol_rel: NonNegativeFloat, - convergence_xtol_abs: NonNegativeFloat, - convergence_gtol_abs: NonNegativeFloat, - convergence_gtol_rel: NonNegativeFloat, - stopping_maxiter: PositiveInt, - stopping_max_seconds: float, - trustregion_initial_radius: PositiveFloat, - trustregion_stepback_strategy: Literal[ - "truncate", - "reflect", - "reflect_single", - "mixed", - ], - trustregion_subspace_dimension: Literal[ - "full", - "2D", - "scg", - ], - trustregion_max_stepback_fraction: float, - trustregion_decrease_threshold: float, - trustregion_increase_threshold: float, - trustregion_decrease_factor: float, - trustregion_increase_factor: float, -) -> InternalOptimizeResult: - """Minimize a scalar function using the Fides Optimizer. - - For details see :class:`Fides`. - - """ - if not IS_FIDES_INSTALLED: - raise NotInstalledError( - "The 'fides' algorithm requires the fides package to be installed. " - 'You can install it with `pip install "fides>=0.7.4"`.' + fval, x, grad, hess = opt.minimize(x0) + + return InternalOptimizeResult( + x=x, + fun=fval, + jac=grad, + hess=hess, + success=opt.converged, + message=FIDES_EXIT_MESSAGES.get(opt.exitflag.name), + status=int(opt.exitflag.value), + n_fun_evals=n_evals, + n_jac_evals=n_evals, + n_iterations=opt.iteration, ) - from fides import Optimizer - - fides_options = { - "delta_init": trustregion_initial_radius, - "eta": trustregion_increase_threshold, - "fatol": convergence_ftol_abs, - "frtol": convergence_ftol_rel, - "gamma1": trustregion_decrease_factor, - "gamma2": trustregion_increase_factor, - "gatol": convergence_gtol_abs, - "grtol": convergence_gtol_rel, - "maxiter": stopping_maxiter, - "maxtime": stopping_max_seconds, - "mu": trustregion_decrease_threshold, - "stepback_strategy": trustregion_stepback_strategy, - "subspace_solver": trustregion_subspace_dimension, - "theta_max": trustregion_max_stepback_fraction, - "xtol": convergence_xtol_abs, - } - - hessian_instance = _create_hessian_updater_from_user_input(hessian_update_strategy) - - lower_bounds = np.full(len(x), -np.inf) if lower_bounds is None else lower_bounds - upper_bounds = np.full(len(x), np.inf) if upper_bounds is None else upper_bounds - - opt = Optimizer( - fun=fun_and_jac, - lb=lower_bounds, - ub=upper_bounds, - verbose=logging.ERROR, - options=fides_options, - funargs=None, - hessian_update=hessian_instance, - resfun=False, - ) - raw_res = opt.minimize(x) - res = _process_fides_res(raw_res, opt) - out = InternalOptimizeResult( - x=res["solution_x"], - fun=res["solution_criterion"], - jac=res["solution_derivative"], - hess=res["solution_hessian"], - success=res["success"], - message=res["message"], - n_iterations=res["n_iterations"], - ) - - return out +FIDES_EXIT_MESSAGES = { + "DID_NOT_RUN": "The optimizer did not run.", + "MAXITER": "Reached the maximum number of iterations.", + "MAXTIME": "The next iteration was expected to exceed the maximum runtime.", + "NOT_FINITE": "Encountered a non-finite function value or gradient.", + "EXCEEDED_BOUNDARY": "The parameters left the bounds.", + "DELTA_TOO_SMALL": "The trust-region radius became too small to proceed.", + "FTOL": "Converged: the change of the function value is below the tolerance.", + "XTOL": "Converged: the step length is below the tolerance.", + "GTOL": "Converged: the gradient norm is below the tolerance.", +} +"""The exit flags of fides and the messages optimagic reports for them.""" -def _process_fides_res(raw_res, opt): - """Create an optimagic results dictionary from the Fides output. +_HESSIAN_UPDATE_NAMES = ("bfgs", "sr1", "dfp", "bg", "bb") - Args: - raw_res (tuple): Tuple containing the Fides result - opt (fides.Optimizer): Fides Optimizer after minimize has been called on it. - """ - fval, x, grad, hess = raw_res - res = { - "solution_criterion": fval, - "solution_x": x, - "solution_derivative": grad, - "solution_hessian": hess, - "success": opt.converged, - "n_iterations": opt.iteration, - "message": _process_exitflag(opt.exitflag), - } - return res - - -def _process_exitflag(exitflag): - messages = { - "DID_NOT_RUN": "The optimizer did not run", - "MAXITER": "Reached maximum number of allowed iterations", - "MAXTIME": "Expected to reach maximum allowed time in next iteration", - "NOT_FINITE": "Encountered non-finite fval/grad/hess", - "EXCEEDED_BOUNDARY": "Exceeded specified boundaries", - "DELTA_TOO_SMALL": "Trust Region Radius too small to proceed", - "FTOL": "Converged according to fval difference", - "XTOL": "Converged according to x difference", - "GTOL": "Converged according to gradient norm", - } - - out = messages.get(exitflag.name) - - return out - - -def _create_hessian_updater_from_user_input(hessian_update_strategy): +def _create_hessian_update(hessian_update: HessianUpdate) -> HessianApproximation: + """Create the Hessian approximation of fides from the user input.""" from fides import hessian_approximation - hessians_needing_residuals = ( - hessian_approximation.FX, - hessian_approximation.SSM, - hessian_approximation.TSSM, - hessian_approximation.GNSBFGS, - ) - unsupported_hess_msg = ( - f"{hessian_update_strategy} not supported because it requires " - "residuals. Choose one of 'BB', 'BFGS', 'BG', 'DFP' or 'SR1' or pass " - "an instance of the fides.hessian_approximation.HessianApproximation " - "class." - ) - - if hessian_update_strategy in ("broyden", "Broyden", "BROYDEN"): - raise ValueError( - "You cannot use the Broyden update strategy without specifying the " - "interpolation parameter phi. Import the Broyden class from " - "`fides.hessian_approximation`, create an instance of it with your " - "desired value of phi and pass this instance instead." - ) - elif isinstance(hessian_update_strategy, str): - if hessian_update_strategy.lower() in ["fx", "ssm", "tssm", "gnsbfgs"]: - raise NotImplementedError(unsupported_hess_msg) - else: - hessian_name = hessian_update_strategy.upper() - hessian_class = getattr(hessian_approximation, hessian_name) - hessian_instance = hessian_class() - elif isinstance( - hessian_update_strategy, hessian_approximation.HessianApproximation - ): - hessian_instance = hessian_update_strategy - if isinstance(hessian_instance, hessians_needing_residuals): - raise NotImplementedError(unsupported_hess_msg) - else: + if isinstance(hessian_update, str): + name = hessian_update.lower() + if name == "broyden": + raise ValueError( + "The Broyden update cannot be selected by name because its parameter " + "phi has no default. Pass an instance instead, e.g. " + "`fides.hessian_approximation.Broyden(phi=0.5)`." + ) + if name in ("fx", "ssm", "tssm", "gnsbfgs", "hybridfixed", "hybridfraction"): + raise NotImplementedError(_unsupported_hessian_update_message(name)) + if name not in _HESSIAN_UPDATE_NAMES: + raise ValueError( + f"Invalid hessian_update: {hessian_update!r}. Choose one of " + f"{_HESSIAN_UPDATE_NAMES} or pass an instance of a class from " + "fides.hessian_approximation." + ) + return getattr(hessian_approximation, name.upper())() + + if not isinstance(hessian_update, hessian_approximation.HessianApproximation): raise TypeError( - "You must provide a hessian_update_strategy that is either a string or an " - "instance of the fides.hessian_approximation.HessianApproximation class." + "hessian_update must be a string or an instance of a class from " + f"fides.hessian_approximation, not {type(hessian_update)}." ) - return hessian_instance + + if hessian_update.requires_resfun or hessian_update.requires_hess: + name = type(hessian_update).__name__ + raise NotImplementedError(_unsupported_hessian_update_message(name)) + + return hessian_update + + +def _unsupported_hessian_update_message(name: str) -> str: + return ( + f"The Hessian approximation {name} is not supported yet because it needs " + "exact Hessians or least-squares residuals, which optimagic does not pass " + f"to fides. Choose one of {_HESSIAN_UPDATE_NAMES} or pass an instance of " + "BFGS, SR1, DFP, BG, BB or Broyden from fides.hessian_approximation." + ) diff --git a/src/optimagic/optimizers/nag_optimizers.py b/src/optimagic/optimizers/nag_optimizers.py index d26756292..6ce42c1fb 100644 --- a/src/optimagic/optimizers/nag_optimizers.py +++ b/src/optimagic/optimizers/nag_optimizers.py @@ -1,862 +1,1545 @@ """Implement algorithms by the `Numerical Algorithms Group `_. -The following arguments are not supported as ``algo_options``: +The module wraps DFO-LS (``nag_dfols``) and Py-BOBYQA (``nag_pybobyqa``). Both solvers +take a few arguments directly and a dictionary of advanced options with keys such as +``"restarts.use_restarts"``. The wrappers keep this structure: arguments and the +miscellaneous ``general.*`` options are options of the algorithm, every other group of +advanced options is one option group, e.g. ``trustregion_options``. + +Two groups belong to a feature that the solvers switch on with a separate flag: the +restart options (``restarts.use_restarts``) and the noise options (the argument +``objfun_has_noise``). For these, flag and group are one option that accepts a +boolean or the group: ``restarts`` and ``noisy``. + +The dictionaries below map optimagic options to the upstream names. They are the single +source of truth for the wrappers and their tests. An entry of an option group is +written as ``"